upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorTauwni <102470988+Tauwni@users.noreply.github.com>2026-11-26 12:19:12 +0100
committerTauwni <102470988+Tauwni@users.noreply.github.com>2026-11-26 12:19:12 +0100
commitbeffaa9a476ca1b3dfd9cfa55e39eafbb1f5eec6 (patch)
tree32877805bf4eb46d9a89d5753db6b5a2b06dc845 /runtime
parentf29ca7bacae9507f83e8c56abdb604bd4efb4cf1 (diff)
parenta73a57e1339be072baf5522351c8ec7f1482b56b (diff)
Merge main into fix/null-descriptor-generated-dir
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt241
-rw-r--r--runtime/README.md53
-rw-r--r--runtime/shims/d3d12_com.cpp275
-rw-r--r--runtime/shims/d3d12_com.h85
-rw-r--r--runtime/shims/d3d12_compile_exit.h7
-rw-r--r--runtime/shims/d3d12_compile_helper.h443
-rw-r--r--runtime/shims/d3d12_compute_input_probe.h16
-rw-r--r--runtime/shims/d3d12_geometry_views.h466
-rw-r--r--runtime/shims/d3d12_pipeline_compile.h186
-rw-r--r--runtime/shims/d3d12_precompile.h45
-rw-r--r--runtime/shims/d3d12_title_buffer_windows.h198
-rw-r--r--runtime/shims/d3d12_title_image_upload.h10
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp4155
-rw-r--r--runtime/shims/d3d12_xs_alloc_size.h52
-rw-r--r--runtime/shims/d3d12_xs_device.cpp550
-rw-r--r--runtime/shims/d3d12_xs_list_values.h4
-rw-r--r--runtime/shims/dxgi_swapchain.h20
-rw-r--r--runtime/shims/file_system.cpp147
-rw-r--r--runtime/shims/file_system.h13
-rw-r--r--runtime/shims/gameinput.cpp176
-rw-r--r--runtime/shims/keyboard_pad_connection.h67
-rw-r--r--runtime/shims/startup_trace.h116
-rw-r--r--runtime/shims/title_hud.h194
-rw-r--r--runtime/shims/xbox_bvh_builder.cpp188
-rw-r--r--runtime/shims/xg_xs.cpp10
-rw-r--r--runtime/shims/xg_xs_layout.h34
-rw-r--r--runtime/shims/xgameruntime_offline.cpp28
-rw-r--r--runtime/shims/xmem.cpp52
-rw-r--r--runtime/shims/xmem.h1
-rw-r--r--runtime/src/base_reservation.h5
-rw-r--r--runtime/src/buffer_va_index.h5
-rw-r--r--runtime/src/command_list.h5
-rw-r--r--runtime/src/console_heap_fix.comp292
-rw-r--r--runtime/src/console_heap_fix.inc3163
-rw-r--r--runtime/src/console_heap_fix_spv.h11
-rw-r--r--runtime/src/console_heap_gpu.h1058
-rw-r--r--runtime/src/console_heap_vsharp_slots.h115
-rw-r--r--runtime/src/descriptor_range_changes.h46
-rw-r--r--runtime/src/descriptor_table.h81
-rw-r--r--runtime/src/dev_overlay.h282
-rw-r--r--runtime/src/dev_status.h51
-rw-r--r--runtime/src/frame_pacer.h40
-rw-r--r--runtime/src/fsdraw_probe.h67
-rw-r--r--runtime/src/gfx10_descriptors.h29
-rw-r--r--runtime/src/indirect_clamp.comp10
-rw-r--r--runtime/src/indirect_clamp_spv.h264
-rw-r--r--runtime/src/indirect_draw_stats.h97
-rw-r--r--runtime/src/large_module_gate.h293
-rw-r--r--runtime/src/main.cpp193
-rw-r--r--runtime/src/memory_figures.h147
-rw-r--r--runtime/src/pe_loader.cpp35
-rw-r--r--runtime/src/pipeline_cache_journal.h356
-rw-r--r--runtime/src/pipeline_wait.h35
-rw-r--r--runtime/src/queue_holds.h7
-rw-r--r--runtime/src/root_signature.cpp11
-rw-r--r--runtime/src/root_signature.h8
-rw-r--r--runtime/src/shader_library.h85
-rw-r--r--runtime/src/submit_phases.h55
-rw-r--r--runtime/src/thread_sampler.h43
-rw-r--r--runtime/src/thread_stacks.cpp30
-rw-r--r--runtime/src/thread_stacks.h4
-rw-r--r--runtime/src/title_geometry_watch.h80
-rw-r--r--runtime/src/title_page_watch.h25
-rw-r--r--runtime/src/title_texture_refresh.h87
-rw-r--r--runtime/src/title_va_alias.h98
-rw-r--r--runtime/src/vulkan13_features.h8
-rw-r--r--runtime/src/vulkan_backend.h1176
-rw-r--r--runtime/src/vulkan_bindless.h192
-rw-r--r--runtime/src/vulkan_device_fault.h657
-rw-r--r--runtime/src/vulkan_device_markers.h245
-rw-r--r--runtime/src/vulkan_indirect_clamp.h92
-rw-r--r--runtime/src/vulkan_memory_budget.h46
-rw-r--r--runtime/src/vulkan_present.h91
-rw-r--r--runtime/src/vulkan_present_splash.h10
-rw-r--r--runtime/src/vulkan_replay.h679
-rw-r--r--runtime/src/vulkan_scratch.h7
-rw-r--r--runtime/test/big_compile_gate_test.cpp532
-rw-r--r--runtime/test/big_compute_module.h298
-rw-r--r--runtime/test/check_console_paths.cmake6
-rw-r--r--runtime/test/check_game_dir.cmake5
-rw-r--r--runtime/test/compile_helper_test.cpp176
-rw-r--r--runtime/test/console_heap_vsharp_slots_test.cpp259
-rw-r--r--runtime/test/d3d12_big_compute_test.cpp978
-rw-r--r--runtime/test/d3d12_compile_teardown_test.cpp31
-rw-r--r--runtime/test/d3d12_compute_journal_test.cpp153
-rw-r--r--runtime/test/d3d12_compute_test.cpp24
-rw-r--r--runtime/test/d3d12_existing_heap_test.cpp65
-rw-r--r--runtime/test/d3d12_f16_halves_test.cpp214
-rw-r--r--runtime/test/d3d12_indirect_rt_test.cpp306
-rw-r--r--runtime/test/d3d12_m4_compute_test.cpp23
-rw-r--r--runtime/test/d3d12_mesh_test.cpp68
-rw-r--r--runtime/test/d3d12_placed_depth_test.h13
-rw-r--r--runtime/test/d3d12_set_descriptor_heaps_test.cpp14
-rw-r--r--runtime/test/d3d12_texture_tiles_test.cpp70
-rw-r--r--runtime/test/d3d12_texture_uav_test.cpp95
-rw-r--r--runtime/test/d3d12_title_va_test.cpp22
-rw-r--r--runtime/test/d3d12_uav_clear_test.cpp323
-rw-r--r--runtime/test/d3d12_unbound_tsharp_rules_test.cpp394
-rw-r--r--runtime/test/d3d12_unmapped_vsharp_test.cpp1
-rw-r--r--runtime/test/d3d12_vram_budget_test.cpp103
-rw-r--r--runtime/test/d3d12_vulkan_device_test.cpp11
-rw-r--r--runtime/test/descriptor_table_test.cpp44
-rw-r--r--runtime/test/dev_overlay_test.cpp166
-rw-r--r--runtime/test/dxgi_swapchain_count_test.cpp4
-rw-r--r--runtime/test/file_system_test.cpp321
-rw-r--r--runtime/test/fixtures/tiny_game.cpp1
-rw-r--r--runtime/test/frame_pacer_test.cpp143
-rw-r--r--runtime/test/gameinput_test.cpp9
-rw-r--r--runtime/test/geometry_views_test.cpp355
-rw-r--r--runtime/test/gfx10_descriptors_test.cpp19
-rw-r--r--runtime/test/glsl/cs_indirect_dispatch_count.comp5
-rw-r--r--runtime/test/indirect_clamp_safety_test.cpp419
-rw-r--r--runtime/test/indirect_topology_and_stats_test.cpp409
-rw-r--r--runtime/test/int3_skip_test.cpp210
-rw-r--r--runtime/test/keyboard_pad_retry_test.cpp137
-rw-r--r--runtime/test/large_module_gate.h181
-rw-r--r--runtime/test/loader_test.cpp88
-rw-r--r--runtime/test/pipeline_cache_journal_test.cpp337
-rw-r--r--runtime/test/replay_pipeline_compile_unlock_test.cpp291
-rw-r--r--runtime/test/replay_pipeline_compiles_test.cpp380
-rw-r--r--runtime/test/replay_query_predication_test.cpp102
-rw-r--r--runtime/test/replay_uav_clear_offset_test.cpp264
-rw-r--r--runtime/test/root_sig_public_flags_test.cpp443
-rw-r--r--runtime/test/root_signature_test.cpp65
-rw-r--r--runtime/test/shader_library_test.cpp74
-rw-r--r--runtime/test/shaders/build.py4
-rw-r--r--runtime/test/shaders/check.py13
-rw-r--r--runtime/test/shaders/cs_w32_wrxchg2_ext.asm91
-rw-r--r--runtime/test/shaders/cs_w32_wrxchg2st64.asm93
-rw-r--r--runtime/test/shaders/cs_w64x_partial_swizzle.asm78
-rw-r--r--runtime/test/shaders/w64_graphics.py11
-rw-r--r--runtime/test/spirv_f16_halves_test.cpp19
-rw-r--r--runtime/test/startup_trace_test.cpp100
-rw-r--r--runtime/test/submit_mutex_test.cpp209
-rw-r--r--runtime/test/title_hud_test.cpp190
-rw-r--r--runtime/test/title_va_alias_test.cpp38
-rw-r--r--runtime/test/vk_bindless_test.cpp306
-rw-r--r--runtime/test/vk_console_heap_gpu_test.cpp584
-rw-r--r--runtime/test/vk_descriptor_bench.cpp3
-rw-r--r--runtime/test/vk_device_markers_test.cpp142
-rw-r--r--runtime/test/vk_harness.cpp3
-rw-r--r--runtime/test/vk_host_texture_order_test.cpp36
-rw-r--r--runtime/test/vk_image_fuzz.cpp2
-rw-r--r--runtime/test/vk_pipeline_check.cpp35
-rw-r--r--runtime/test/vk_presenter_sparse_capture.h192
-rw-r--r--runtime/test/vk_presenter_sync_test.cpp18
-rw-r--r--runtime/test/vk_sampler_test.cpp5
-rw-r--r--runtime/test/vk_sandbox.cpp3
-rw-r--r--runtime/test/vk_semaphore_lifetime_test.cpp261
-rw-r--r--runtime/test/vk_store_test.cpp15
-rw-r--r--runtime/test/vk_test_device.h9
-rw-r--r--runtime/test/vk_texture_test.cpp5
-rw-r--r--runtime/test/vulkan_device_markers_test.cpp300
-rw-r--r--runtime/test/xbox_bvh_builder_test.cpp128
-rw-r--r--runtime/test/xbox_depth_storage_test.cpp311
-rw-r--r--runtime/test/xbox_present_test.cpp5
-rw-r--r--runtime/test/xg_xs_test.cpp144
-rw-r--r--runtime/test/xs_proxy_mock_test.cpp350
158 files changed, 28819 insertions, 1783 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 49cb714b4..4e2511715 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -250,6 +250,20 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
250 target_compile_options(root_sig_test PRIVATE /W4 /permissive- /utf-8) 250 target_compile_options(root_sig_test PRIVATE /W4 /permissive- /utf-8)
251 target_link_options(root_sig_test PRIVATE /OPT:NOREF) 251 target_link_options(root_sig_test PRIVATE /OPT:NOREF)
252 252
253 # The flag mask keeps every public root-signature flag: helpers over [0, 0xFFFF], the shims against the host
254 # serializer and deserializer (old upstream PR 7140).
255 add_executable(root_sig_public_flags_test
256 test/root_sig_public_flags_test.cpp
257 shims/registry.cpp
258 shims/d3d12_xs.cpp
259 shims/d3d12_xs_device.cpp
260 shims/d3d12_xs_pso_stream.cpp
261 )
262 target_link_libraries(root_sig_public_flags_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY})
263 target_compile_definitions(root_sig_public_flags_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
264 target_compile_options(root_sig_public_flags_test PRIVATE /W4 /permissive- /utf-8)
265 target_link_options(root_sig_public_flags_test PRIVATE /OPT:NOREF)
266
253 # RTS0 parser oracle: synthetic descriptors only, serialized by the real PC 267 # RTS0 parser oracle: synthetic descriptors only, serialized by the real PC
254 # d3d12.dll and parsed back by rt::rootsig::parse_rts0. A layout mismatch 268 # d3d12.dll and parsed back by rt::rootsig::parse_rts0. A layout mismatch
255 # fails here with the blob bytes, never silently in a draw. 269 # fails here with the blob bytes, never silently in a draw.
@@ -439,7 +453,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
439 target_link_options(file_system_test PRIVATE /OPT:NOREF) 453 target_link_options(file_system_test PRIVATE /OPT:NOREF)
440 target_link_libraries(file_system_test PRIVATE advapi32) # the ACL calls of the unlistable-marker-folder check 454 target_link_libraries(file_system_test PRIVATE advapi32) # the ACL calls of the unlistable-marker-folder check
441 455
442 # LEONIDA_SKIP_INT3 (shims/startup_trace.h): its own executable, the variable is read once per process. 456 # LEONIDA_SKIP_INT3 (shims/startup_trace.h): each case runs in a child process with its own environment.
443 add_executable(int3_skip_test 457 add_executable(int3_skip_test
444 test/int3_skip_test.cpp 458 test/int3_skip_test.cpp
445 shims/registry.cpp 459 shims/registry.cpp
@@ -765,8 +779,28 @@ if(BUILD_TESTING)
765 endif() 779 endif()
766 target_link_libraries(title_window_test PRIVATE user32) 780 target_link_libraries(title_window_test PRIVATE user32)
767 add_test(NAME title_window COMMAND title_window_test) 781 add_test(NAME title_window COMMAND title_window_test)
782
783 # LEONIDA_TITLE_HUD's counters in the title bar of another thread's window (shims/title_hud.h): user32 and DXGI.
784 add_executable(title_hud_test test/title_hud_test.cpp)
785 target_include_directories(title_hud_test PRIVATE shims)
786 target_compile_definitions(title_hud_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
787 if(MSVC)
788 target_compile_options(title_hud_test PRIVATE /W4 /permissive- /utf-8)
789 endif()
790 target_link_libraries(title_hud_test PRIVATE Vulkan::Headers user32 psapi)
791 add_test(NAME title_hud COMMAND title_hud_test)
768 endif() 792 endif()
769 793
794 # LEONIDA_DEV_OVERLAY's text and the phase bookkeeping behind it (src/dev_overlay.h): no window, GPU or game file.
795 find_package(Threads REQUIRED)
796 add_executable(dev_overlay_test test/dev_overlay_test.cpp)
797 target_include_directories(dev_overlay_test PRIVATE src)
798 target_link_libraries(dev_overlay_test PRIVATE Threads::Threads)
799 if(WIN32)
800 target_link_libraries(dev_overlay_test PRIVATE user32 gdi32 psapi)
801 endif()
802 add_test(NAME dev_overlay COMMAND dev_overlay_test)
803
770 add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp) 804 add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp)
771 add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test) 805 add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test)
772 # The pool that compiles a submission's pipelines (runtime/src/pipeline_workers.h): pure stdlib. 806 # The pool that compiles a submission's pipelines (runtime/src/pipeline_workers.h): pure stdlib.
@@ -780,9 +814,26 @@ if(BUILD_TESTING)
780 add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) 814 add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp)
781 add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test) 815 add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test)
782 816
817 # The per-pipeline journal files compute pipelines are kept in: naming, header check, atomic replacement.
818 add_executable(pipeline_cache_journal_test test/pipeline_cache_journal_test.cpp)
819 add_test(NAME pipeline_cache_journal COMMAND pipeline_cache_journal_test)
820
821 # The compile helper's request files and building markers (shims/d3d12_compile_helper.h): Win32 file calls only.
822 if(WIN32)
823 add_executable(compile_helper_test test/compile_helper_test.cpp)
824 target_compile_definitions(compile_helper_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
825 add_test(NAME compile_helper COMMAND compile_helper_test)
826 endif()
827
783 add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) 828 add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp)
784 add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) 829 add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test)
785 830
831 # The gate of large_module_gate.h as the runtime uses it for large pipelines (LEONIDA_BIG_COMPILE_BUDGET_MB): pure
832 # stdlib.
833 add_executable(big_compile_gate_test test/big_compile_gate_test.cpp)
834 target_link_libraries(big_compile_gate_test PRIVATE Threads::Threads)
835 add_test(NAME big_compile_gate COMMAND big_compile_gate_test)
836 set_tests_properties(big_compile_gate PROPERTIES TIMEOUT 120)
786 # vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device. 837 # vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device.
787 add_executable(large_module_gate_test test/large_module_gate_test.cpp) 838 add_executable(large_module_gate_test test/large_module_gate_test.cpp)
788 find_package(Threads REQUIRED) 839 find_package(Threads REQUIRED)
@@ -1375,6 +1426,9 @@ if(BUILD_TESTING)
1375 if(TARGET root_sig_test) 1426 if(TARGET root_sig_test)
1376 add_test(NAME root_sig COMMAND root_sig_test) 1427 add_test(NAME root_sig COMMAND root_sig_test)
1377 endif() 1428 endif()
1429 if(TARGET root_sig_public_flags_test)
1430 add_test(NAME root_sig_public_flags COMMAND root_sig_public_flags_test)
1431 endif()
1378 add_executable(command_list_test test/command_list_test.cpp) 1432 add_executable(command_list_test test/command_list_test.cpp)
1379 add_test(NAME command_list COMMAND command_list_test) 1433 add_test(NAME command_list COMMAND command_list_test)
1380 # Which SPIR-V modules declare a storage image or buffer they may write (src/spirv_stores.h), on hand-built words. 1434 # Which SPIR-V modules declare a storage image or buffer they may write (src/spirv_stores.h), on hand-built words.
@@ -1645,6 +1699,7 @@ if(BUILD_TESTING)
1645 endif() 1699 endif()
1646 if(WIN32 AND TARGET dstorage_test) 1700 if(WIN32 AND TARGET dstorage_test)
1647 add_test(NAME dstorage COMMAND dstorage_test) 1701 add_test(NAME dstorage COMMAND dstorage_test)
1702 set_tests_properties(dstorage PROPERTIES TIMEOUT 120)
1648 endif() 1703 endif()
1649 if(WIN32 AND TARGET xgameruntime_test) 1704 if(WIN32 AND TARGET xgameruntime_test)
1650 add_test(NAME xgameruntime COMMAND xgameruntime_test) 1705 add_test(NAME xgameruntime COMMAND xgameruntime_test)
@@ -1667,6 +1722,12 @@ if(BUILD_TESTING)
1667 target_compile_options(active_input_test PRIVATE /W4 /permissive- /utf-8) 1722 target_compile_options(active_input_test PRIVATE /W4 /permissive- /utf-8)
1668 endif() 1723 endif()
1669 add_test(NAME active_input COMMAND active_input_test) 1724 add_test(NAME active_input COMMAND active_input_test)
1725 # The same keyboard connection lifecycle as the shim, with a fake clock and virtual-device backend only.
1726 add_executable(keyboard_pad_retry_test test/keyboard_pad_retry_test.cpp)
1727 if(MSVC)
1728 target_compile_options(keyboard_pad_retry_test PRIVATE /W4 /permissive- /utf-8)
1729 endif()
1730 add_test(NAME keyboard_pad_retry COMMAND keyboard_pad_retry_test)
1670 if(WIN32 AND TARGET gameinput_no_sdl_test) 1731 if(WIN32 AND TARGET gameinput_no_sdl_test)
1671 add_test(NAME gameinput_no_sdl COMMAND gameinput_no_sdl_test) 1732 add_test(NAME gameinput_no_sdl COMMAND gameinput_no_sdl_test)
1672 # LEONIDA_INPUT_SCRIPT without SDL3: the scripted pad, its device callbacks and its readings on a fake clock. 1733 # LEONIDA_INPUT_SCRIPT without SDL3: the scripted pad, its device callbacks and its readings on a fake clock.
@@ -1720,7 +1781,7 @@ if(BUILD_TESTING)
1720 # game's exact exit code comes back through the relaunch. 1781 # game's exact exit code comes back through the relaunch.
1721 add_test(NAME run_tiny_first_run_ui COMMAND gta6rt --first-run-ui $<TARGET_FILE:tiny_game> -- hello 42 first-run-ui) 1782 add_test(NAME run_tiny_first_run_ui COMMAND gta6rt --first-run-ui $<TARGET_FILE:tiny_game> -- hello 42 first-run-ui)
1722 set_tests_properties(run_tiny_first_run_ui PROPERTIES 1783 set_tests_properties(run_tiny_first_run_ui PROPERTIES
1723 ENVIRONMENT "LEONIDA_ARENA_MB=768;LEONIDA_D3D12=;LEONIDA_PIPELINE_COMPILE=" 1784 ENVIRONMENT "LEONIDA_ARENA_MB=768;LEONIDA_D3D12=;LEONIDA_PIPELINE_COMPILE=;LEONIDA_KEYBOARD_PAD="
1724 PASS_REGULAR_EXPRESSION "tiny_game: PASS first-run UI caller override" 1785 PASS_REGULAR_EXPRESSION "tiny_game: PASS first-run UI caller override"
1725 FAIL_REGULAR_EXPRESSION "tiny_game: FAIL") 1786 FAIL_REGULAR_EXPRESSION "tiny_game: FAIL")
1726 add_test(NAME run_tiny_game_fixed COMMAND gta6rt --run $<TARGET_FILE:tiny_game_fixed> -- hello 42) 1787 add_test(NAME run_tiny_game_fixed COMMAND gta6rt --run $<TARGET_FILE:tiny_game_fixed> -- hello 42)
@@ -1835,10 +1896,25 @@ if(TARGET Vulkan::Headers)
1835 add_executable(vulkan_device_fault_test test/vulkan_device_fault_test.cpp) 1896 add_executable(vulkan_device_fault_test test/vulkan_device_fault_test.cpp)
1836 target_link_libraries(vulkan_device_fault_test PRIVATE Vulkan::Headers) 1897 target_link_libraries(vulkan_device_fault_test PRIVATE Vulkan::Headers)
1837 add_test(NAME vulkan_device_fault COMMAND vulkan_device_fault_test) 1898 add_test(NAME vulkan_device_fault COMMAND vulkan_device_fault_test)
1899 # The AMD breadcrumbs (LEONIDA_DEVICE_MARKERS): seq numbering, marker writes and the likely-hang verdict, on the CPU.
1900 add_executable(vulkan_device_markers_test test/vulkan_device_markers_test.cpp)
1901 target_link_libraries(vulkan_device_markers_test PRIVATE Vulkan::Headers)
1902 add_test(NAME vulkan_device_markers COMMAND vulkan_device_markers_test)
1903 # The submit lock's owner tracking, waiter count, submit handoff and compile gate (SubmitMutex), on the CPU.
1904 if(WIN32)
1905 add_executable(submit_mutex_test test/submit_mutex_test.cpp)
1906 target_link_libraries(submit_mutex_test PRIVATE Vulkan::Headers)
1907 target_compile_definitions(submit_mutex_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
1908 if(MSVC)
1909 target_compile_options(submit_mutex_test PRIVATE /W4 /permissive- /utf-8)
1910 endif()
1911 add_test(NAME submit_mutex COMMAND submit_mutex_test)
1912 set_tests_properties(submit_mutex PROPERTIES TIMEOUT 60)
1913 endif()
1838 1914
1839 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 1915 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
1840 vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test 1916 vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test
1841 vk_xdxr_build_test vk_queue_test vk_sandbox) 1917 vk_xdxr_build_test vk_queue_test vk_sandbox vk_console_heap_gpu_test)
1842 add_executable(${tool} test/${tool}.cpp) 1918 add_executable(${tool} test/${tool}.cpp)
1843 target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) 1919 target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
1844 if(WIN32) 1920 if(WIN32)
@@ -1926,7 +2002,7 @@ if(TARGET Vulkan::Headers)
1926 # Self-checking Vulkan tests with no shaders or game data; each exits 77 without a Vulkan device (TEST-514). 2002 # Self-checking Vulkan tests with no shaders or game data; each exits 77 without a Vulkan device (TEST-514).
1927 # indirect_clamp is registered next to its own add_executable above, where tests/test_ctest_registration.py 2003 # indirect_clamp is registered next to its own add_executable above, where tests/test_ctest_registration.py
1928 # can see it. 2004 # can see it.
1929 foreach(test vk_command_replay vk_predicated_copy vk_predicate_capture vk_queue) 2005 foreach(test vk_command_replay vk_predicated_copy vk_predicate_capture vk_queue vk_console_heap_gpu)
1930 add_test(NAME ${test} COMMAND ${test}_test) 2006 add_test(NAME ${test} COMMAND ${test}_test)
1931 set_tests_properties(${test} PROPERTIES SKIP_RETURN_CODE 77) 2007 set_tests_properties(${test} PROPERTIES SKIP_RETURN_CODE 77)
1932 endforeach() 2008 endforeach()
@@ -1959,6 +2035,37 @@ if(TARGET Vulkan::Headers)
1959 add_test(NAME vk_queue_query_sync COMMAND vk_queue_query_sync_test) 2035 add_test(NAME vk_queue_query_sync COMMAND vk_queue_query_sync_test)
1960 set_tests_properties(vk_queue_query_sync PROPERTIES SKIP_RETURN_CODE 77) 2036 set_tests_properties(vk_queue_query_sync PROPERTIES SKIP_RETURN_CODE 77)
1961 endif() 2037 endif()
2038 # Fence and queue teardown with submissions pending: a fence released after an unheld Signal, the bindless upload
2039 # queue destroyed before another queue submits, the device-fault submit ring forgetting destroyed semaphores.
2040 add_executable(vk_semaphore_lifetime_test test/vk_semaphore_lifetime_test.cpp)
2041 target_link_libraries(vk_semaphore_lifetime_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
2042 if(WIN32)
2043 target_compile_definitions(vk_semaphore_lifetime_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2044 else()
2045 find_package(Threads REQUIRED)
2046 target_link_libraries(vk_semaphore_lifetime_test PRIVATE Threads::Threads)
2047 endif()
2048 if(MSVC)
2049 target_compile_options(vk_semaphore_lifetime_test PRIVATE /W4 /permissive- /utf-8)
2050 endif()
2051 if(BUILD_TESTING)
2052 add_test(NAME vk_semaphore_lifetime COMMAND vk_semaphore_lifetime_test)
2053 set_tests_properties(vk_semaphore_lifetime PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
2054 endif()
2055 # The AMD breadcrumbs (LEONIDA_DEVICE_MARKERS) on a real device: after a few dispatches and a wait, the queue's
2056 # started and finished markers hold the last dispatch's seq. SKIP without VK_AMD_buffer_marker.
2057 add_executable(vk_device_markers_test test/vk_device_markers_test.cpp)
2058 target_link_libraries(vk_device_markers_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
2059 if(WIN32)
2060 target_compile_definitions(vk_device_markers_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2061 endif()
2062 if(MSVC)
2063 target_compile_options(vk_device_markers_test PRIVATE /W4 /permissive- /utf-8)
2064 endif()
2065 if(BUILD_TESTING)
2066 add_test(NAME vk_device_markers COMMAND vk_device_markers_test)
2067 set_tests_properties(vk_device_markers PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
2068 endif()
1962 # With LEONIDA_VK_VALIDATION=1: synchronization validation reports a missing barrier (and not a present one), so 2069 # With LEONIDA_VK_VALIDATION=1: synchronization validation reports a missing barrier (and not a present one), so
1963 # the other GPU tests' "0 validation errors" was checked by an active layer. 77 without validation or a device. 2070 # the other GPU tests' "0 validation errors" was checked by an active layer. 77 without validation or a device.
1964 add_executable(vk_sync_validation_selftest test/vk_sync_validation_selftest.cpp) 2071 add_executable(vk_sync_validation_selftest test/vk_sync_validation_selftest.cpp)
@@ -2184,13 +2291,14 @@ if(TARGET Vulkan::Headers)
2184 ENVIRONMENT "LEONIDA_VK_VALIDATION=1;VK_VALIDATE_SYNC=1") 2291 ENVIRONMENT "LEONIDA_VK_VALIDATION=1;VK_VALIDATE_SYNC=1")
2185 # VulkanPresenter tracker lock / failed-submit rollback and capture-buffer WAW synchronization. 2292 # VulkanPresenter tracker lock / failed-submit rollback and capture-buffer WAW synchronization.
2186 add_executable(vk_presenter_sync_test test/vk_presenter_sync_test.cpp) 2293 add_executable(vk_presenter_sync_test test/vk_presenter_sync_test.cpp)
2187 target_link_libraries(vk_presenter_sync_test PRIVATE Vulkan::Headers user32) 2294 target_link_libraries(vk_presenter_sync_test PRIVATE Vulkan::Headers user32 advapi32)
2188 target_compile_definitions(vk_presenter_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 2295 target_compile_definitions(vk_presenter_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2189 if(MSVC) 2296 if(MSVC)
2190 target_compile_options(vk_presenter_sync_test PRIVATE /W4 /permissive- /utf-8) 2297 target_compile_options(vk_presenter_sync_test PRIVATE /W4 /permissive- /utf-8)
2191 endif() 2298 endif()
2192 add_test(NAME vk_presenter_sync COMMAND vk_presenter_sync_test) 2299 add_test(NAME vk_presenter_sync COMMAND vk_presenter_sync_test)
2193 set_tests_properties(vk_presenter_sync PROPERTIES SKIP_RETURN_CODE 77) 2300 add_test(NAME vk_presenter_sparse_capture COMMAND vk_presenter_sync_test --sparse-capture)
2301 set_tests_properties(vk_presenter_sync vk_presenter_sparse_capture PROPERTIES SKIP_RETURN_CODE 77)
2194 set(conformance_src ${CMAKE_CURRENT_SOURCE_DIR}/../tools/conformance/native/src) 2302 set(conformance_src ${CMAKE_CURRENT_SOURCE_DIR}/../tools/conformance/native/src)
2195 add_executable(vk_present_dump_test test/vk_present_dump_test.cpp 2303 add_executable(vk_present_dump_test test/vk_present_dump_test.cpp
2196 ${conformance_src}/png_io.cpp ${conformance_src}/diagnostics.cpp) 2304 ${conformance_src}/png_io.cpp ${conformance_src}/diagnostics.cpp)
@@ -2378,8 +2486,38 @@ if(TARGET Vulkan::Headers)
2378 add_test(NAME d3d12_pipeline_workers_eager COMMAND d3d12_pipeline_workers_test) 2486 add_test(NAME d3d12_pipeline_workers_eager COMMAND d3d12_pipeline_workers_test)
2379 set_tests_properties(d3d12_pipeline_workers d3d12_pipeline_workers_eager PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180 2487 set_tests_properties(d3d12_pipeline_workers d3d12_pipeline_workers_eager PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180
2380 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") 2488 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
2489 # One large pipeline after another: the jobs of the pool are then known (d3d12_big_compute has the budget).
2490 set_tests_properties(d3d12_pipeline_workers PROPERTIES ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=1")
2381 set_tests_properties(d3d12_pipeline_workers_eager PROPERTIES 2491 set_tests_properties(d3d12_pipeline_workers_eager PROPERTIES
2382 ENVIRONMENT "LEONIDA_LAZY_PIPELINES=0;LEONIDA_LAZY_COMPUTE=0") 2492 ENVIRONMENT "LEONIDA_LAZY_PIPELINES=0;LEONIDA_LAZY_COMPUTE=0;LEONIDA_SERIAL_BIG_COMPILES=1")
2493 # Large pipelines compiled within a memory budget, with real large compute modules: the same values for each setting
2494 # (read once for each process). 260 MiB holds three of the modules, 1 MiB none. The modules' compile runs on the test's
2495 # threads, so they get the loader's stack (docs/pipeline_check.md, "Stack reserve").
2496 add_executable(d3d12_big_compute_test test/d3d12_big_compute_test.cpp)
2497 target_link_libraries(d3d12_big_compute_test PRIVATE gta6rt_d3d12_com)
2498 target_compile_definitions(d3d12_big_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2499 target_compile_options(d3d12_big_compute_test PRIVATE /W4 /permissive- /utf-8)
2500 target_link_options(d3d12_big_compute_test PRIVATE /STACK:${GTA6RT_STACK})
2501 add_test(NAME d3d12_big_compute COMMAND d3d12_big_compute_test)
2502 add_test(NAME d3d12_big_compute_budget COMMAND d3d12_big_compute_test)
2503 add_test(NAME d3d12_big_compute_tight COMMAND d3d12_big_compute_test)
2504 add_test(NAME d3d12_big_compute_serial COMMAND d3d12_big_compute_test)
2505 add_test(NAME d3d12_big_compute_unlimited COMMAND d3d12_big_compute_test)
2506 add_test(NAME d3d12_big_compute_warmup COMMAND d3d12_big_compute_test warmup)
2507 add_test(NAME d3d12_big_compute_eager COMMAND d3d12_big_compute_test eager)
2508 set_tests_properties(d3d12_big_compute d3d12_big_compute_budget d3d12_big_compute_tight d3d12_big_compute_serial
2509 d3d12_big_compute_unlimited d3d12_big_compute_warmup d3d12_big_compute_eager
2510 PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600
2511 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
2512 set_tests_properties(d3d12_big_compute_budget PROPERTIES ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=260")
2513 set_tests_properties(d3d12_big_compute_tight d3d12_big_compute_warmup PROPERTIES
2514 ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1")
2515 set_tests_properties(d3d12_big_compute_eager PROPERTIES
2516 ENVIRONMENT "LEONIDA_BIG_COMPILE_BUDGET_MB=1;LEONIDA_LAZY_COMPUTE=0")
2517 set_tests_properties(d3d12_big_compute_serial PROPERTIES # neither of these two has a budget
2518 ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=1;LEONIDA_BIG_COMPILE_BUDGET_MB=4096")
2519 set_tests_properties(d3d12_big_compute_unlimited PROPERTIES
2520 ENVIRONMENT "LEONIDA_SERIAL_BIG_COMPILES=0;LEONIDA_BIG_COMPILE_BUDGET_MB=1")
2383 # ExecuteCommandLists refuses a list whose type isn't the queue's (debug-layer message 836). 2521 # ExecuteCommandLists refuses a list whose type isn't the queue's (debug-layer message 836).
2384 add_executable(d3d12_queue_list_type_test test/d3d12_queue_list_type_test.cpp) 2522 add_executable(d3d12_queue_list_type_test test/d3d12_queue_list_type_test.cpp)
2385 target_link_libraries(d3d12_queue_list_type_test PRIVATE gta6rt_d3d12_com) 2523 target_link_libraries(d3d12_queue_list_type_test PRIVATE gta6rt_d3d12_com)
@@ -2458,7 +2596,8 @@ if(TARGET Vulkan::Headers)
2458 set(LEONIDA_XBOX_BVH_BUILDER_OUT "${CMAKE_CURRENT_BINARY_DIR}/xbox_bvh_builder_cases") 2596 set(LEONIDA_XBOX_BVH_BUILDER_OUT "${CMAKE_CURRENT_BINARY_DIR}/xbox_bvh_builder_cases")
2459 add_executable(xbox_bvh_builder_test test/xbox_bvh_builder_test.cpp shims/xbox_bvh_builder.cpp shims/registry.cpp) 2597 add_executable(xbox_bvh_builder_test test/xbox_bvh_builder_test.cpp shims/xbox_bvh_builder.cpp shims/registry.cpp)
2460 target_link_libraries(xbox_bvh_builder_test PRIVATE gta6rt_d3d12_com) 2598 target_link_libraries(xbox_bvh_builder_test PRIVATE gta6rt_d3d12_com)
2461 target_compile_definitions(xbox_bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 2599 # LEONIDA_VULKAN_DEVICE: the shim hands its rehydration scratch to the layer's list, as in gta6rt.
2600 target_compile_definitions(xbox_bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE)
2462 target_compile_options(xbox_bvh_builder_test PRIVATE /W4 /permissive- /utf-8) 2601 target_compile_options(xbox_bvh_builder_test PRIVATE /W4 /permissive- /utf-8)
2463 target_link_options(xbox_bvh_builder_test PRIVATE /OPT:NOREF) 2602 target_link_options(xbox_bvh_builder_test PRIVATE /OPT:NOREF)
2464 add_test(NAME xbox_bvh_builder COMMAND xbox_bvh_builder_test "${LEONIDA_XBOX_BVH_BUILDER_OUT}") 2603 add_test(NAME xbox_bvh_builder COMMAND xbox_bvh_builder_test "${LEONIDA_XBOX_BVH_BUILDER_OUT}")
@@ -2572,7 +2711,7 @@ if(TARGET Vulkan::Headers)
2572 2711
2573 # ClearUnorderedAccessViewUint/Float on buffers and textures, read back through D3D12. 2712 # ClearUnorderedAccessViewUint/Float on buffers and textures, read back through D3D12.
2574 add_executable(d3d12_uav_clear_test test/d3d12_uav_clear_test.cpp) 2713 add_executable(d3d12_uav_clear_test test/d3d12_uav_clear_test.cpp)
2575 target_link_libraries(d3d12_uav_clear_test PRIVATE gta6rt_d3d12_com) 2714 target_link_libraries(d3d12_uav_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
2576 target_compile_definitions(d3d12_uav_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 2715 target_compile_definitions(d3d12_uav_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2577 target_compile_options(d3d12_uav_clear_test PRIVATE /W4 /permissive- /utf-8) 2716 target_compile_options(d3d12_uav_clear_test PRIVATE /W4 /permissive- /utf-8)
2578 add_test(NAME d3d12_uav_clear COMMAND d3d12_uav_clear_test) 2717 add_test(NAME d3d12_uav_clear COMMAND d3d12_uav_clear_test)
@@ -2652,6 +2791,9 @@ if(TARGET Vulkan::Headers)
2652 add_test(NAME d3d12_host_prefix COMMAND d3d12_existing_heap_test --host-prefix-only) 2791 add_test(NAME d3d12_host_prefix COMMAND d3d12_existing_heap_test --host-prefix-only)
2653 set_tests_properties(d3d12_host_prefix PROPERTIES SKIP_RETURN_CODE 77) 2792 set_tests_properties(d3d12_host_prefix PROPERTIES SKIP_RETURN_CODE 77)
2654 set_tests_properties(d3d12_existing_heap PROPERTIES SKIP_RETURN_CODE 77) 2793 set_tests_properties(d3d12_existing_heap PROPERTIES SKIP_RETURN_CODE 77)
2794 # LEONIDA_TEXTURE_REFRESH_ASYNC=1 (set by the test itself): a mapped plane's first submission reads its bytes.
2795 add_test(NAME d3d12_mapped_plane_async COMMAND d3d12_existing_heap_test --mapped-plane-async)
2796 set_tests_properties(d3d12_mapped_plane_async PROPERTIES SKIP_RETURN_CODE 77)
2655 # The same with write watching off: the guarded cases only, the concurrent writers among them. 2797 # The same with write watching off: the guarded cases only, the concurrent writers among them.
2656 add_test(NAME d3d12_existing_heap_no_write_watch COMMAND d3d12_existing_heap_test) 2798 add_test(NAME d3d12_existing_heap_no_write_watch COMMAND d3d12_existing_heap_test)
2657 set_tests_properties(d3d12_existing_heap_no_write_watch PROPERTIES SKIP_RETURN_CODE 77 2799 set_tests_properties(d3d12_existing_heap_no_write_watch PROPERTIES SKIP_RETURN_CODE 77
@@ -2772,6 +2914,14 @@ if(TARGET Vulkan::Headers)
2772 target_compile_options(d3d12_descriptor_test PRIVATE /W4 /permissive- /utf-8) 2914 target_compile_options(d3d12_descriptor_test PRIVATE /W4 /permissive- /utf-8)
2773 add_test(NAME d3d12_descriptor COMMAND d3d12_descriptor_test) 2915 add_test(NAME d3d12_descriptor COMMAND d3d12_descriptor_test)
2774 set_tests_properties(d3d12_descriptor PROPERTIES SKIP_RETURN_CODE 77) 2916 set_tests_properties(d3d12_descriptor PROPERTIES SKIP_RETURN_CODE 77)
2917
2918 # Console descriptor heap T# binding rules and per-reason refusal tracking (RT-UNBOUND-TSHARP-REASONS).
2919 add_executable(d3d12_unbound_tsharp_rules_test test/d3d12_unbound_tsharp_rules_test.cpp)
2920 target_link_libraries(d3d12_unbound_tsharp_rules_test PRIVATE gta6rt_d3d12_com)
2921 target_compile_definitions(d3d12_unbound_tsharp_rules_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
2922 target_compile_options(d3d12_unbound_tsharp_rules_test PRIVATE /W4 /permissive- /utf-8)
2923 add_test(NAME d3d12_unbound_tsharp_rules COMMAND d3d12_unbound_tsharp_rules_test)
2924 set_tests_properties(d3d12_unbound_tsharp_rules PROPERTIES SKIP_RETURN_CODE 77)
2775 if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) 2925 if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE)
2776 function(descriptor_test_shader shader definition) 2926 function(descriptor_test_shader shader definition)
2777 set(source ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader}) 2927 set(source ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader})
@@ -2820,6 +2970,26 @@ if(TARGET Vulkan::Headers)
2820 set_tests_properties(d3d12_indirect_group_budget PROPERTIES SKIP_RETURN_CODE 77 2970 set_tests_properties(d3d12_indirect_group_budget PROPERTIES SKIP_RETURN_CODE 77
2821 ENVIRONMENT "LEONIDA_INDIRECT_GROUP_BUDGET=2") 2971 ENVIRONMENT "LEONIDA_INDIRECT_GROUP_BUDGET=2")
2822 set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77) 2972 set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77)
2973
2974 # A single ordinary compute PSO and direct dispatch for cold/warm production journal comparisons;
2975 # only the authored two-counter shader is shared with the indirect test.
2976 set(_journal_second_spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_compute_journal_v2.spv)
2977 add_custom_command(OUTPUT ${_journal_second_spv}
2978 COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 -DTEST_COUNTER_TERM=2u
2979 -o ${_journal_second_spv} ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp
2980 DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp
2981 COMMENT "Compiling the second authored compute journal control" VERBATIM)
2982 # The first shader comes from gta6rt_indirect_count_shader: naming its output here too would give Make a second
2983 # rule for the same file, and the two glslangValidator runs raced ("Failed to open file").
2984 add_custom_target(gta6rt_compute_journal_shader DEPENDS ${_journal_second_spv})
2985 add_executable(d3d12_compute_journal_test test/d3d12_compute_journal_test.cpp)
2986 add_dependencies(d3d12_compute_journal_test gta6rt_indirect_count_shader gta6rt_compute_journal_shader)
2987 target_link_libraries(d3d12_compute_journal_test PRIVATE gta6rt_d3d12_com)
2988 target_compile_definitions(d3d12_compute_journal_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX
2989 LEONIDA_TEST_COUNTER_SPV="${_indirect_count_spv}" LEONIDA_TEST_COUNTER_V2_SPV="${_journal_second_spv}")
2990 target_compile_options(d3d12_compute_journal_test PRIVATE /W4 /permissive- /utf-8)
2991 add_test(NAME d3d12_compute_journal COMMAND d3d12_compute_journal_test)
2992 set_tests_properties(d3d12_compute_journal PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
2823 endif() 2993 endif()
2824 2994
2825 # The cache vk_pipeline_check saves has to hit on the runtime's device (docs/pipeline_check.md): the test 2995 # The cache vk_pipeline_check saves has to hit on the runtime's device (docs/pipeline_check.md): the test
@@ -3059,6 +3229,13 @@ if(TARGET Vulkan::Headers)
3059 target_compile_options(d3d12_heap_properties_test PRIVATE /W4 /permissive- /utf-8) 3229 target_compile_options(d3d12_heap_properties_test PRIVATE /W4 /permissive- /utf-8)
3060 add_test(NAME d3d12_heap_properties COMMAND d3d12_heap_properties_test) 3230 add_test(NAME d3d12_heap_properties COMMAND d3d12_heap_properties_test)
3061 set_tests_properties(d3d12_heap_properties PROPERTIES SKIP_RETURN_CODE 77) 3231 set_tests_properties(d3d12_heap_properties PROPERTIES SKIP_RETURN_CODE 77)
3232 # The title HUD's VRAM figure from VK_EXT_memory_budget (rt::d3d12::vulkan_vram_budget) on a real device.
3233 add_executable(d3d12_vram_budget_test test/d3d12_vram_budget_test.cpp)
3234 target_link_libraries(d3d12_vram_budget_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
3235 target_compile_definitions(d3d12_vram_budget_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
3236 target_compile_options(d3d12_vram_budget_test PRIVATE /W4 /permissive- /utf-8)
3237 add_test(NAME d3d12_vram_budget COMMAND d3d12_vram_budget_test)
3238 set_tests_properties(d3d12_vram_budget PROPERTIES SKIP_RETURN_CODE 77)
3062 3239
3063 # CreatePipelineLibrary and ID3D12PipelineLibrary1 arguments, compared with the host runtime. 3240 # CreatePipelineLibrary and ID3D12PipelineLibrary1 arguments, compared with the host runtime.
3064 add_executable(d3d12_pipeline_library_host_test test/d3d12_pipeline_library_host_test.cpp) 3241 add_executable(d3d12_pipeline_library_host_test test/d3d12_pipeline_library_host_test.cpp)
@@ -3087,11 +3264,11 @@ if(TARGET Vulkan::Headers)
3087 set_tests_properties(xbox_d16s8_storage PROPERTIES 3264 set_tests_properties(xbox_d16s8_storage PROPERTIES
3088 ENVIRONMENT "LEONIDA_TEST_D16S8_UAV=1;LEONIDA_CONSOLE_D16S8=native" SKIP_RETURN_CODE 77 TIMEOUT 30) 3265 ENVIRONMENT "LEONIDA_TEST_D16S8_UAV=1;LEONIDA_CONSOLE_D16S8=native" SKIP_RETURN_CODE 77 TIMEOUT 30)
3089 set_tests_properties(xbox_depth_storage PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) 3266 set_tests_properties(xbox_depth_storage PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30)
3090 # Made as D24S8, a D16S8 depth-stencil texture with unordered access is refused by the depth provider; slots 76 3267 # Made as D24S8 (the default on GPUs with D24S8 attachments, e.g. NVIDIA), a D16S8 depth-stencil texture keeps
3091 # and 133 make it without unordered access instead (d24 forces what a GPU with D24S8 attachments chooses). 3268 # its UAVs through the widened R16_TYPELESS + R8_UINT planes and Depth24Converter.
3092 add_test(NAME xbox_d16s8_refused_uav COMMAND xbox_depth_storage_test) 3269 add_test(NAME xbox_d16s8_d24_storage COMMAND xbox_depth_storage_test)
3093 set_tests_properties(xbox_d16s8_refused_uav PROPERTIES 3270 set_tests_properties(xbox_d16s8_d24_storage PROPERTIES
3094 ENVIRONMENT "LEONIDA_TEST_D16S8_REFUSED_UAV=1;LEONIDA_CONSOLE_D16S8=d24" SKIP_RETURN_CODE 77 TIMEOUT 30) 3271 ENVIRONMENT "LEONIDA_TEST_D16S8_UAV=1;LEONIDA_CONSOLE_D16S8=d24" SKIP_RETURN_CODE 77 TIMEOUT 30)
3095 add_executable(xbox_d16s8_surface_test test/xbox_d16s8_surface_test.cpp) 3272 add_executable(xbox_d16s8_surface_test test/xbox_d16s8_surface_test.cpp)
3096 target_link_libraries(xbox_d16s8_surface_test PRIVATE gta6rt_d3d12_com) 3273 target_link_libraries(xbox_d16s8_surface_test PRIVATE gta6rt_d3d12_com)
3097 target_compile_definitions(xbox_d16s8_surface_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 3274 target_compile_definitions(xbox_d16s8_surface_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
@@ -3479,7 +3656,7 @@ if(TARGET Vulkan::Headers)
3479 target_compile_definitions(d3d12_unmapped_vsharp_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) 3656 target_compile_definitions(d3d12_unmapped_vsharp_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE)
3480 target_compile_options(d3d12_unmapped_vsharp_test PRIVATE /W4 /permissive- /utf-8) 3657 target_compile_options(d3d12_unmapped_vsharp_test PRIVATE /W4 /permissive- /utf-8)
3481 add_test(NAME d3d12_unmapped_vsharp COMMAND d3d12_unmapped_vsharp_test) 3658 add_test(NAME d3d12_unmapped_vsharp COMMAND d3d12_unmapped_vsharp_test)
3482 set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77) 3659 set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_CONSOLE_FIX_US=0")
3483 add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp) 3660 add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp)
3484 target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) 3661 target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
3485 target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 3662 target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
@@ -3538,7 +3715,7 @@ if(TARGET Vulkan::Headers)
3538 target_compile_definitions(dxgi_host_parity_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 3715 target_compile_definitions(dxgi_host_parity_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
3539 target_compile_options(dxgi_host_parity_test PRIVATE /W4 /permissive- /utf-8) 3716 target_compile_options(dxgi_host_parity_test PRIVATE /W4 /permissive- /utf-8)
3540 add_test(NAME dxgi_host_parity COMMAND dxgi_host_parity_test) 3717 add_test(NAME dxgi_host_parity COMMAND dxgi_host_parity_test)
3541 set_tests_properties(dxgi_host_parity PROPERTIES SKIP_RETURN_CODE 77) 3718 set_tests_properties(dxgi_host_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120)
3542 3719
3543 # Host-parity test for DXGI waitable swap chain frame-latency semaphore behavior. 3720 # Host-parity test for DXGI waitable swap chain frame-latency semaphore behavior.
3544 add_executable(dxgi_waitable_latency_test test/dxgi_waitable_latency_test.cpp) 3721 add_executable(dxgi_waitable_latency_test test/dxgi_waitable_latency_test.cpp)
@@ -3547,7 +3724,7 @@ if(TARGET Vulkan::Headers)
3547 target_compile_options(dxgi_waitable_latency_test PRIVATE /W4 /permissive- /utf-8) 3724 target_compile_options(dxgi_waitable_latency_test PRIVATE /W4 /permissive- /utf-8)
3548 add_test(NAME dxgi_waitable_latency COMMAND dxgi_waitable_latency_test) 3725 add_test(NAME dxgi_waitable_latency COMMAND dxgi_waitable_latency_test)
3549 set_tests_properties(dxgi_waitable_latency PROPERTIES 3726 set_tests_properties(dxgi_waitable_latency PROPERTIES
3550 SKIP_RETURN_CODE 77 3727 SKIP_RETURN_CODE 77 TIMEOUT 120
3551 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") 3728 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
3552 3729
3553 # Synthetic (no GPU): VulkanSwapchain's DXGI BufferCount contract when Vulkan returns more images than the 3730 # Synthetic (no GPU): VulkanSwapchain's DXGI BufferCount contract when Vulkan returns more images than the
@@ -4259,6 +4436,16 @@ if(TARGET Vulkan::Headers)
4259 add_test(NAME replay_pipeline_compiles COMMAND replay_pipeline_compiles_test) 4436 add_test(NAME replay_pipeline_compiles COMMAND replay_pipeline_compiles_test)
4260 add_test(NAME replay_pipeline_compiles_strict COMMAND replay_pipeline_compiles_test) 4437 add_test(NAME replay_pipeline_compiles_strict COMMAND replay_pipeline_compiles_test)
4261 set_tests_properties(replay_pipeline_compiles_strict PROPERTIES ENVIRONMENT "LEONIDA_STRICT_REPLAY=1") 4438 set_tests_properties(replay_pipeline_compiles_strict PROPERTIES ENVIRONMENT "LEONIDA_STRICT_REPLAY=1")
4439 # Compiling unbuilt pipelines releases resource_mutex_ and tracker_mutex_ while keeping pipeline_mutex_ (no GPU).
4440 add_executable(replay_pipeline_compile_unlock_test test/replay_pipeline_compile_unlock_test.cpp)
4441 target_link_libraries(replay_pipeline_compile_unlock_test PRIVATE Vulkan::Headers Threads::Threads)
4442 if(WIN32)
4443 target_compile_definitions(replay_pipeline_compile_unlock_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
4444 endif()
4445 if(MSVC)
4446 target_compile_options(replay_pipeline_compile_unlock_test PRIVATE /W4 /permissive- /utf-8)
4447 endif()
4448 add_test(NAME replay_pipeline_compile_unlock COMMAND replay_pipeline_compile_unlock_test)
4262 add_executable(replay_quad_list_test test/replay_quad_list_test.cpp) 4449 add_executable(replay_quad_list_test test/replay_quad_list_test.cpp)
4263 target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers) 4450 target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers)
4264 if(WIN32) 4451 if(WIN32)
@@ -4320,6 +4507,13 @@ if(TARGET Vulkan::Headers)
4320 target_compile_definitions(indirect_dispatch_count_alloc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 4507 target_compile_definitions(indirect_dispatch_count_alloc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
4321 endif() 4508 endif()
4322 add_test(NAME indirect_dispatch_count_alloc COMMAND indirect_dispatch_count_alloc_test) 4509 add_test(NAME indirect_dispatch_count_alloc COMMAND indirect_dispatch_count_alloc_test)
4510 # IndirectArgumentClamp queue-family sharing, bind-retry cleanup, slot zeroing, offset alignment, and concurrency (no GPU).
4511 add_executable(indirect_clamp_safety_test test/indirect_clamp_safety_test.cpp)
4512 target_link_libraries(indirect_clamp_safety_test PRIVATE Vulkan::Headers Threads::Threads)
4513 if(WIN32)
4514 target_compile_definitions(indirect_clamp_safety_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
4515 endif()
4516 add_test(NAME indirect_clamp_safety COMMAND indirect_clamp_safety_test)
4323 # A buffer UAV clear writes where its resource starts in a shared VkBuffer (no GPU). 4517 # A buffer UAV clear writes where its resource starts in a shared VkBuffer (no GPU).
4324 add_executable(replay_uav_clear_offset_test test/replay_uav_clear_offset_test.cpp) 4518 add_executable(replay_uav_clear_offset_test test/replay_uav_clear_offset_test.cpp)
4325 target_link_libraries(replay_uav_clear_offset_test PRIVATE Vulkan::Headers) 4519 target_link_libraries(replay_uav_clear_offset_test PRIVATE Vulkan::Headers)
@@ -4338,6 +4532,13 @@ if(TARGET Vulkan::Headers)
4338 target_compile_definitions(replay_query_edges_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 4532 target_compile_definitions(replay_query_edges_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
4339 endif() 4533 endif()
4340 add_test(NAME replay_query_edges COMMAND replay_query_edges_test) 4534 add_test(NAME replay_query_edges COMMAND replay_query_edges_test)
4535 # Stateful indirect draw topology coverage and per-reason indirect_stats counters (no GPU or game data).
4536 add_executable(indirect_topology_and_stats_test test/indirect_topology_and_stats_test.cpp)
4537 target_link_libraries(indirect_topology_and_stats_test PRIVATE Vulkan::Headers)
4538 if(WIN32)
4539 target_compile_definitions(indirect_topology_and_stats_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
4540 endif()
4541 add_test(NAME indirect_topology_and_stats COMMAND indirect_topology_and_stats_test)
4341 # GFX10 T#/S#/V# descriptor encoding and its Vulkan mappings (src/gfx10_descriptors.h). 4542 # GFX10 T#/S#/V# descriptor encoding and its Vulkan mappings (src/gfx10_descriptors.h).
4342 add_executable(gfx10_descriptors_test test/gfx10_descriptors_test.cpp) 4543 add_executable(gfx10_descriptors_test test/gfx10_descriptors_test.cpp)
4343 target_link_libraries(gfx10_descriptors_test PRIVATE Vulkan::Headers) 4544 target_link_libraries(gfx10_descriptors_test PRIVATE Vulkan::Headers)
@@ -4384,6 +4585,12 @@ if(TARGET Vulkan::Headers)
4384 target_compile_options(title_window_plan_bounds_test PRIVATE /W4 /permissive- /utf-8) 4585 target_compile_options(title_window_plan_bounds_test PRIVATE /W4 /permissive- /utf-8)
4385 endif() 4586 endif()
4386 add_test(NAME title_window_plan_bounds COMMAND title_window_plan_bounds_test) 4587 add_test(NAME title_window_plan_bounds COMMAND title_window_plan_bounds_test)
4588 # Host-RAM bitset of live console resource-heap V# slots (src/console_heap_vsharp_slots.h).
4589 add_executable(console_heap_vsharp_slots_test test/console_heap_vsharp_slots_test.cpp)
4590 if(WIN32 AND MSVC)
4591 target_compile_options(console_heap_vsharp_slots_test PRIVATE /W4 /permissive- /utf-8)
4592 endif()
4593 add_test(NAME console_heap_vsharp_slots COMMAND console_heap_vsharp_slots_test)
4387 # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. 4594 # Queue construction cleans its Vulkan handles if holder registration runs out of host memory.
4388 add_executable(vk_host_texture_order_test test/vk_host_texture_order_test.cpp) 4595 add_executable(vk_host_texture_order_test test/vk_host_texture_order_test.cpp)
4389 target_link_libraries(vk_host_texture_order_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) 4596 target_link_libraries(vk_host_texture_order_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
diff --git a/runtime/README.md b/runtime/README.md
index b89a82a71..23a7811ab 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -133,7 +133,14 @@ with the seed on stderr; a seed of 0 uses a fixed non-zero state. Unset, the hos
133## PE loader 133## PE loader
134 134
135`src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when 135`src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when
136that base is taken, copies headers and sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds 136that base is taken. An image with a relocation table is moved and fixed up whatever `IMAGE_FILE_RELOCS_STRIPPED`
137says; without one, the flag refuses the move, and an image with the flag clear is moved with nothing fixed up (the
138loader logs that). The Windows 11 (build 26200) loader does the same in these three cases, as Zombins2 measured
139with synthetic DLLs in a review of old pull request 8847 of the original repository, which is no longer readable.
140Open question from the same measurement: Windows also refused flag-set DLLs without a relocation directory at a free
141preferred base (error 487, linker-built `/FIXED` DLLs included), and why is not known; the loader still maps those
142at their base, as before. It copies headers and sections, applies `IMAGE_REL_BASED_DIR64` and `HIGHLOW` relocations
143(rejecting the other types, such as `HIGH`, `LOW` and `HIGHADJ`, which no x64 MSVC image contains), binds
137imports by name or ordinal, parses the export table, sets section protections, and registers the 144imports by name or ordinal, parses the export table, sets section protections, and registers the
138image's x64 unwind table (`.pdata`) with `RtlAddFunctionTable`, so exceptions raised in or passing 145image's x64 unwind table (`.pdata`) with `RtlAddFunctionTable`, so exceptions raised in or passing
139through a mapped image are dispatched and stack walks can step over its frames. The table is validated 146through a mapped image are dispatched and stack walks can step over its frames. The table is validated
@@ -321,7 +328,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
321| `LEONIDA_LAZY_PIPELINES` | on | Graphics pipelines are built at their first draw. `0` builds each at `CreatePipelineState`, as before; the title creates far more pipelines at startup than it draws with. | 328| `LEONIDA_LAZY_PIPELINES` | on | Graphics pipelines are built at their first draw. `0` builds each at `CreatePipelineState`, as before; the title creates far more pipelines at startup than it draws with. |
322| `LEONIDA_LAZY_COMPUTE` | on | Compute pipelines are built at the first dispatch that names them, or earlier by the warm-up thread. `0` builds each at `CreateComputePipelineState`. | 329| `LEONIDA_LAZY_COMPUTE` | on | Compute pipelines are built at the first dispatch that names them, or earlier by the warm-up thread. `0` builds each at `CreateComputePipelineState`. |
323| `LEONIDA_COMPUTE_WARMUP_MAX_BYTES` | `1048576` | The largest SPIR-V module, in bytes, the background warm-up thread (`LEONIDA_COMPUTE_WARMUP`) builds ahead of its first dispatch. Larger modules wait for that dispatch. | 330| `LEONIDA_COMPUTE_WARMUP_MAX_BYTES` | `1048576` | The largest SPIR-V module, in bytes, the background warm-up thread (`LEONIDA_COMPUTE_WARMUP`) builds ahead of its first dispatch. Larger modules wait for that dispatch. |
324| `LEONIDA_SERIAL_BIG_COMPILES` | on | Compute modules over 128 KiB of SPIR-V compile one at a time, because the driver's compiler needs hundreds of MiB for each. `0` lets them compile side by side. | 331| `LEONIDA_SERIAL_BIG_COMPILES` | unset | Large pipelines (compute modules over 128 KiB of SPIR-V, graphics pipelines of 1 MiB or more) compile side by side while their estimates, 512 bytes of memory for each byte of SPIR-V, fit a budget (`LEONIDA_BIG_COMPILE_BUDGET_MB`): one always does, what a submission waits for goes before the warm-up, and the warm-up takes a quarter of the budget at most. `1` compiles the compute ones one at a time, and the graphics ones of a submission one after another, as before there was a budget. `0` lets all of them compile side by side. |
332| `LEONIDA_BIG_COMPILE_BUDGET_MB` | unset | The budget, in MiB: a fixed number (`0`: one large pipeline at a time) instead of three quarters of the memory that is free at the moment, which is the smaller of the free RAM and the room under the commit limit, read again for each pipeline. Text that is not a number is ignored. |
325| `LEONIDA_CONSOLE_FORMATS` | on | Texture descriptions the console accepts and a PC GPU may not (an R9G9B9E5 render target, an sRGB RGBA8 or BGRA8 texture with unordered access) get a host format that can do the job. `0` refuses them, as a PC D3D12 runtime does. | 333| `LEONIDA_CONSOLE_FORMATS` | on | Texture descriptions the console accepts and a PC GPU may not (an R9G9B9E5 render target, an sRGB RGBA8 or BGRA8 texture with unordered access) get a host format that can do the job. `0` refuses them, as a PC D3D12 runtime does. |
326| `LEONIDA_CONSOLE_HEAP_SHADOW` | on | A console descriptor heap has a copy in the descriptor arena that the shaders read. `0` keeps its bytes in the title's memory only (the comparison for a run that misbehaves with the copy). | 334| `LEONIDA_CONSOLE_HEAP_SHADOW` | on | A console descriptor heap has a copy in the descriptor arena that the shaders read. `0` keeps its bytes in the title's memory only (the comparison for a run that misbehaves with the copy). |
327| `LEONIDA_IMPORT_BELOW_ARENA` | unset | `1` keeps a host-memory import that the driver put below the GPU address arena. By default such an import is not used and the shadow buffer in the arena answers, because a V# cannot name an address below the arena. | 335| `LEONIDA_IMPORT_BELOW_ARENA` | unset | `1` keeps a host-memory import that the driver put below the GPU address arena. By default such an import is not used and the shadow buffer in the arena answers, because a V# cannot name an address below the arena. |
@@ -340,7 +348,10 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
340| `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh, as before unchanged generations were skipped. | 348| `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh, as before unchanged generations were skipped. |
341| `LEONIDA_STRICT_REPLAY` | unset | *Diagnostic.* `1` makes a draw or dispatch with an unresolvable resource fail its command list (`src/vulkan_replay.h`); by default it is dropped and logged. | 349| `LEONIDA_STRICT_REPLAY` | unset | *Diagnostic.* `1` makes a draw or dispatch with an unresolvable resource fail its command list (`src/vulkan_replay.h`); by default it is dropped and logged. |
342| `LEONIDA_VOLUME_MIPS` | on | The XG layout of a 3D texture with mips or a block format is computed (`shims/xg_xs_layout.h`). `0` refuses it. | 350| `LEONIDA_VOLUME_MIPS` | on | The XG layout of a 3D texture with mips or a block format is computed (`shims/xg_xs_layout.h`). `0` refuses it. |
343| `LEONIDA_TITLE_WATCHDOG` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `0` makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`), and only in the build the watchdog was measured in. | 351| `LEONIDA_TITLE_WATCHDOG` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `0` makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`). **Since RT-BOOT-COMBINED `0` also needs `LEONIDA_TITLE_WATCHDOG_KICK`**: the watchdog's addresses are no longer built in. With `0` and no `LEONIDA_TITLE_WATCHDOG_KICK`, the loader says once that the watchdog stays armed. |
352| `LEONIDA_TITLE_WATCHDOG_KICK` | unset | `<trap RVA>,<kick RVA>` (hex, measured locally and not kept in the repository): where the watchdog's trap instruction is and the byte the game's main loop sets. Used only with `LEONIDA_TITLE_WATCHDOG=0`, and only when the watchdog's trap instruction is at the first RVA; set without `LEONIDA_TITLE_WATCHDOG=0`, the watchdog stays armed and the loader says so once. |
353| `LEONIDA_POOL_DIAG_AT` | unset | *Diagnostic.* `<module>+0x<offset>` of the title's transient-pool assert, as the trace prints it (measured locally): the trace dumps the pool's resource list when that int3 is hit (`shims/startup_trace.h`). |
354| `LEONIDA_PEEK` | unset | *Diagnostic.* `<rva>[:n],<rva>,...` (hex): a thread prints the 8-byte values at these RVAs of the title's image (`:n` = n consecutive values) every `LEONIDA_PEEK_SECONDS` (`src/main.cpp`). The RVAs are measured locally and not kept in the repository. `scripts/windows-boot/boot.ps1` no longer sets the game-state and session-state RVAs by default: it sets `LEONIDA_PEEK` only from `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA`, and without them its RESULT states read `?` ([scripts/windows-boot/README.md](../scripts/windows-boot/README.md)). |
344| `LEONIDA_PEEK_SECONDS` | `10` | *Diagnostic.* The period of the `LEONIDA_PEEK` thread (`src/main.cpp`), which prints 8-byte values of the title's image. | 355| `LEONIDA_PEEK_SECONDS` | `10` | *Diagnostic.* The period of the `LEONIDA_PEEK` thread (`src/main.cpp`), which prints 8-byte values of the title's image. |
345| `LEONIDA_INPUT_SCRIPT` | unset | Timed pad presses, `button@seconds` separated by commas (`a@70,a@85,start@120`), each held 300 ms; the clock starts with the shim. Works with and without SDL3: with SDL3 it drives the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), without SDL3 one scripted pad that is the only device. Controllers and the keyboard pad still need SDL3. Format and buttons in [docs/gameinput.md](../docs/gameinput.md#environment-variables). | 356| `LEONIDA_INPUT_SCRIPT` | unset | Timed pad presses, `button@seconds` separated by commas (`a@70,a@85,start@120`), each held 300 ms; the clock starts with the shim. Works with and without SDL3: with SDL3 it drives the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), without SDL3 one scripted pad that is the only device. Controllers and the keyboard pad still need SDL3. Format and buttons in [docs/gameinput.md](../docs/gameinput.md#environment-variables). |
346| `LEONIDA_INPUT_LOG` | on | The GameInput shim logs every press in `LEONIDA_INPUT_SCRIPT`'s form (`name@seconds`), so a session played by hand can be replayed. `0` turns the lines off. | 357| `LEONIDA_INPUT_LOG` | on | The GameInput shim logs every press in `LEONIDA_INPUT_SCRIPT`'s form (`name@seconds`), so a session played by hand can be replayed. `0` turns the lines off. |
@@ -373,6 +384,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
373| `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. | 384| `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. |
374| `LEONIDA_TITLE_FILL_ASYNC` | unset | Trades correctness for speed. `1` stops device slot 70 views from hashing and filling the texture they name on the title's thread: a texture never filled or known stale is queued for a worker thread that fills one texture at a time. Until then a shader samples the image as it is, empty or a frame behind. | 385| `LEONIDA_TITLE_FILL_ASYNC` | unset | Trades correctness for speed. `1` stops device slot 70 views from hashing and filling the texture they name on the title's thread: a texture never filled or known stale is queued for a worker thread that fills one texture at a time. Until then a shader samples the image as it is, empty or a frame behind. |
375| `LEONIDA_TITLE_VIEW_REFRESH_MS` | `0` | The shortest time, in milliseconds, between two checks of a title texture's bytes when a device slot 70 view of it is written. `0` checks at every view. The periodic pass still checks the texture on its own period, and a texture known stale is checked at once. Has no effect with `LEONIDA_TITLE_FILL_ASYNC=1`. | 386| `LEONIDA_TITLE_VIEW_REFRESH_MS` | `0` | The shortest time, in milliseconds, between two checks of a title texture's bytes when a device slot 70 view of it is written. `0` checks at every view. The periodic pass still checks the texture on its own period, and a texture known stale is checked at once. Has no effect with `LEONIDA_TITLE_FILL_ASYNC=1`. |
387| `LEONIDA_TITLE_EVERY_BUDGET_US` | `0` | Microseconds one pass over the textures filled from the title's memory may spend on the textures it visits every pass (mapped by the title, or known stale), resuming where the last pass stopped; the texture that crosses the limit is finished. A mapped texture never filled yet is visited first whatever the limit. `0` visits all of them every pass. It limits the synchronous pass only: with `LEONIDA_TEXTURE_REFRESH_ASYNC=1` the pass runs on the refresh worker, and the limit does not apply. |
376| `LEONIDA_TITLE_TEXTURE_FILL_MS` | `8` | Milliseconds one pass over the textures filled from the title's memory may spend filling; a texture already started is finished. `0` removes the time limit and leaves `LEONIDA_TITLE_TEXTURE_FILL_MB` to bound the pass. | 388| `LEONIDA_TITLE_TEXTURE_FILL_MS` | `8` | Milliseconds one pass over the textures filled from the title's memory may spend filling; a texture already started is finished. `0` removes the time limit and leaves `LEONIDA_TITLE_TEXTURE_FILL_MB` to bound the pass. |
377| `LEONIDA_MAP_READBACK` | unset | `1` writes the GPU's texels of a small render or unordered-access target the title placed into the title's pages when the title maps it, so a CPU read of the target sees what the GPU rendered (the title reads its exposure statistics that way). Only a single-row, single-mip, single-layer, single-sample 2D target of at most 4 KiB a row; the copy waits for the GPU's work already submitted, and a page that is not writable is left as it is. Unset, the title reads its own pages, which the GPU never writes. | 389| `LEONIDA_MAP_READBACK` | unset | `1` writes the GPU's texels of a small render or unordered-access target the title placed into the title's pages when the title maps it, so a CPU read of the target sees what the GPU rendered (the title reads its exposure statistics that way). Only a single-row, single-mip, single-layer, single-sample 2D target of at most 4 KiB a row; the copy waits for the GPU's work already submitted, and a page that is not writable is left as it is. Unset, the title reads its own pages, which the GPU never writes. |
378| `LEONIDA_SLOT133_IMPORT` | on | *Diagnostic.* `0` imports no title-placed buffer (device slot 133) as host memory: each takes the shadow-buffer fallback, so no GPU store can reach the title's memory through an import. | 390| `LEONIDA_SLOT133_IMPORT` | on | *Diagnostic.* `0` imports no title-placed buffer (device slot 133) as host memory: each takes the shadow-buffer fallback, so no GPU store can reach the title's memory through an import. |
@@ -386,10 +398,12 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
386| `LEONIDA_TITLE_HEAP` | unset | `1` makes the title's `XMemAlloc` blocks come from a Win32 heap of their own instead of the CRT heap (`shims/xmem.cpp`), so a GPU store through a slot-133 import past a buffer's end, or into a freed block, cannot corrupt the runtime's own objects on the same page. | 398| `LEONIDA_TITLE_HEAP` | unset | `1` makes the title's `XMemAlloc` blocks come from a Win32 heap of their own instead of the CRT heap (`shims/xmem.cpp`), so a GPU store through a slot-133 import past a buffer's end, or into a freed block, cannot corrupt the runtime's own objects on the same page. |
387| `LEONIDA_XMEM_SEC_COMMIT` | on under Wine | XMem's physical-page sections are committed whole under Wine; `0` reserves them and commits each page at its first touch, as on Windows, where the variable has no effect (`shims/xmem.cpp`). | 399| `LEONIDA_XMEM_SEC_COMMIT` | on under Wine | XMem's physical-page sections are committed whole under Wine; `0` reserves them and commits each page at its first touch, as on Windows, where the variable has no effect (`shims/xmem.cpp`). |
388| `LEONIDA_HANG_EXIT_S` | `0` | `s` seconds with work pending on the queues and no submission retired counts as a GPU hang the driver may recover from without reporting the device lost: the stall is reported (with checkpoints under `LEONIDA_STALL_CHECKPOINTS=1`) and the process ends with exit code `0x47` (`src/vulkan_backend.h`), so a boot does not sit until its time limit. `0` or unset never ends the process. | 400| `LEONIDA_HANG_EXIT_S` | `0` | `s` seconds with work pending on the queues and no submission retired counts as a GPU hang the driver may recover from without reporting the device lost: the stall is reported (with checkpoints under `LEONIDA_STALL_CHECKPOINTS=1`) and the process ends with exit code `0x47` (`src/vulkan_backend.h`), so a boot does not sit until its time limit. `0` or unset never ends the process. |
401| `LEONIDA_DEVICE_MARKERS` | unset | *Diagnostic.* `1`, with `LEONIDA_DEVICE_FAULT=1` or `2`, on a device with `VK_AMD_buffer_marker` (RADV, AMD's drivers): every dispatch the device-fault report numbers writes its `seq` into a small host-visible buffer at top of pipe (started) and bottom of pipe (finished), one slot per queue (`src/vulkan_device_markers.h`). A loss or stall report then prints each queue's last finished and started `seq` and marks the oldest started, unfinished dispatch as the likely hang, the AMD counterpart of NVIDIA's checkpoints; the values are best-effort after a loss. Two marker writes per dispatch while on; nothing when unset. Without the extension it logs one line saying the markers are unavailable ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md) section 4.11). |
389| `LEONIDA_STALL_CHECKPOINTS` | unset | *Diagnostic.* `1` makes a device-stall report also collect the NVIDIA checkpoints of every queue (`src/vulkan_device_fault.h`), which name the programs in flight. The extension only promises them for a lost device, so outside that state the call is outside its contract. | 402| `LEONIDA_STALL_CHECKPOINTS` | unset | *Diagnostic.* `1` makes a device-stall report also collect the NVIDIA checkpoints of every queue (`src/vulkan_device_fault.h`), which name the programs in flight. The extension only promises them for a lost device, so outside that state the call is outside its contract. |
390| `LEONIDA_PASS_TRACE` | unset | *Diagnostic.* `n`, with `LEONIDA_DEVICE_FAULT=1`: in the frame after every `n`-th present, each submission logs its compute programs in order, repeats folded (`src/vulkan_backend.h`), for the frame's pass order. | 403| `LEONIDA_PASS_TRACE` | unset | *Diagnostic.* `n`, with `LEONIDA_DEVICE_FAULT=1`: in the frame after every `n`-th present, each submission logs its compute programs in order, repeats folded (`src/vulkan_backend.h`), for the frame's pass order. |
391| `LEONIDA_GPU_LATENCY` | unset | *Diagnostic.* `1` logs, every 10 s for each queue kind, how long the GPU took from a submission's `vkQueueSubmit` to it being seen done, and the share of the wall time the queue had work (`src/vulkan_backend.h`). | 404| `LEONIDA_GPU_LATENCY` | unset | *Diagnostic.* `1` logs, every 10 s for each queue kind, how long the GPU took from a submission's `vkQueueSubmit` to it being seen done, and the share of the wall time the queue had work (`src/vulkan_backend.h`). |
392| `LEONIDA_SUBMIT_PHASES_SECONDS` | `5` | *Diagnostic.* The period, in seconds, of the always-on line that says how many submissions there were and where their CPU time went, phase by phase (`src/submit_phases.h`). `0` turns the line off. | 405| `LEONIDA_SUBMIT_PHASES_SECONDS` | `5` | *Diagnostic.* The period, in seconds, of the always-on line that says how many submissions there were and where their CPU time went, phase by phase (`src/submit_phases.h`). `0` turns the line off. |
406| `LEONIDA_DEV_OVERLAY` | unset | *Diagnostic, Windows.* `1` draws what the runtime is doing over the top left corner of the title's window (`src/dev_overlay.h`): frame and submission rate, a submission's CPU time by phase, the phase running now, pipeline builds, indirect draws, cores, free RAM, and the private memory and GPU memory (`src/memory_figures.h`, shared with `LEONIDA_TITLE_HUD`; the GPU figure is the device's `VK_EXT_memory_budget`, `VRAM n/a` without it). |
393| `LEONIDA_SAMPLE_MS` | unset | *Diagnostic.* `ms` starts the thread sampler (`src/thread_sampler.h`): every `ms` milliseconds each thread of the process that used CPU since the last look is suspended just long enough to copy its context, its stack is unwound afterwards, and a periodic report lists the busiest threads and their most frequent call chains (eight frames, innermost first). | 407| `LEONIDA_SAMPLE_MS` | unset | *Diagnostic.* `ms` starts the thread sampler (`src/thread_sampler.h`): every `ms` milliseconds each thread of the process that used CPU since the last look is suspended just long enough to copy its context, its stack is unwound afterwards, and a periodic report lists the busiest threads and their most frequent call chains (eight frames, innermost first). |
394| `LEONIDA_SAMPLE_REPORT_S` | `10` | *Diagnostic.* Seconds between two reports of the thread sampler (`LEONIDA_SAMPLE_MS`). | 408| `LEONIDA_SAMPLE_REPORT_S` | `10` | *Diagnostic.* Seconds between two reports of the thread sampler (`LEONIDA_SAMPLE_MS`). |
395| `LEONIDA_SAMPLE_WAITS` | unset | *Diagnostic.* `1` makes the thread sampler sample waiting threads too, not only those that used CPU, and list each thread's most frequent chain, so a thread that waits shows where. | 409| `LEONIDA_SAMPLE_WAITS` | unset | *Diagnostic.* `1` makes the thread sampler sample waiting threads too, not only those that used CPU, and list each thread's most frequent chain, so a thread that waits shows where. |
@@ -398,6 +412,36 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
398| `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. | 412| `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. |
399| `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 `<LEONIDA_SHADERS>/<name>.spv` back when its hash matches the module's. The runtime's own modules are always kept. | 413| `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 `<LEONIDA_SHADERS>/<name>.spv` back when its hash matches the module's. The runtime's own modules are always kept. |
400| `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). | 414| `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). |
415| `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. |
416| `LEONIDA_SUBMIT_ASYNC` | `0` | `<n>`: 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. |
417| `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES` | unset | `<n>`: 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. |
418| `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. |
419| `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. |
420| `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. |
421| `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. |
422| `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. |
423| `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. |
424| `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. |
425| `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. |
426| `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. |
427| `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. |
428| `LEONIDA_SHADOW_GPU_MB` | `1024` | With `LEONIDA_SHADOW_GPU=1`, the MiB of title memory imported for those copies at most. |
429| `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. |
430| `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. |
431| `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. |
432| `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. |
433| `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. |
434| `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. |
435| `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. |
436| `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. |
437| `LEONIDA_FSDRAW_SLOTS` | `4` | *Diagnostic.* With `LEONIDA_FSDRAW_PROBE=1`, how many slots of a descriptor table are shown. |
438| `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. |
439| `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). |
440| `LEONIDA_TRACE_TEXTURE` | unset | *Diagnostic.* `<address>[,<address>...]` (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. |
441| `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`). |
442| `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`). |
443| `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`). |
444| `LEONIDA_SAMPLE_FIND` | unset | *Diagnostic.* `<rva>[,<rva>...]` (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`). |
401 445
402The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the 446The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the
403shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own 447shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own
@@ -601,10 +645,11 @@ from the ANSI code page.
601| `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` | 645| `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` |
602| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` | 646| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` |
603| `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) | 647| `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) |
648| `delay_import_unimplemented` | at load, for each delay import that binds to an unimplemented thunk (Windows would raise `0xC06D007E`/`0xC06D007F` at its first call; [runtime_imports.md](../docs/runtime_imports.md#delay-imports-and-thread-events-where-the-loader-differs-from-windows)) | `module`, `import` (`dll!name`) |
604| `xmem_attributes` | the first `XMemAlloc`, `XMemFree`, `XMemAllocDefault`, `XMemFreeDefault` and `XMemVirtualAlloc` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (not for the frees), `caller` (module+RVA) | 649| `xmem_attributes` | the first `XMemAlloc`, `XMemFree`, `XMemAllocDefault`, `XMemFreeDefault` and `XMemVirtualAlloc` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (not for the frees), `caller` (module+RVA) |
605| `xmem_physical_pages` | the first `XMemAllocatePhysicalPages` for each distinct attribute word | `api`, `attributes`, `pages`, `caller` | 650| `xmem_physical_pages` | the first `XMemAllocatePhysicalPages` for each distinct attribute word | `api`, `attributes`, `pages`, `caller` |
606| `file_open_failed` | a guest `CreateFileW`/`CreateFile2` that fails (at most 256 events) | `api`, `path` (as the title passed it), `error` (Win32), `caller` (module+RVA) | 651| `file_open_failed` | a guest `CreateFileW`/`CreateFile2` that fails (at most 256 events) | `api`, `path` (as the title passed it), `error` (Win32), `caller` (module+RVA) |
607| `int3_skipped` | with `LEONIDA_SKIP_INT3` set: first int3 at each address, which is then stepped over | `at` (module+RVA) | 652| `int3_skipped` | with `LEONIDA_SKIP_INT3` set when the trace opens: first int3 at each address, which is then stepped over (after 4096 distinct addresses, a new one is logged each time it is hit) | `at` (module+RVA) |
608| `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` | 653| `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` |
609| `exception` | any exception, before handlers run | `code`, `at`, `access`/`address` for access violations, `cpp` for C++ throws, `stack` (up to 16 frames) | 654| `exception` | any exception, before handlers run | `code`, `at`, `access`/`address` for access violations, `cpp` for C++ throws, `stack` (up to 16 frames) |
610| `exit` / `error` | `--run` returns, or the loader throws | `code` / `what` | 655| `exit` / `error` | `--run` returns, or the loader throws | `code` / `what` |
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index 6dee464a8..4a61ffadb 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -222,8 +222,11 @@ public:
222 const leonida::CommandList& commands() const { return list_; } 222 const leonida::CommandList& commands() const { return list_; }
223 // The descriptor tables this recording binds (console VAs), for the scan before a submission. 223 // The descriptor tables this recording binds (console VAs), for the scan before a submission.
224 const std::vector<std::pair<std::uint64_t, std::uint32_t>>& tables() const { return tables_; } 224 const std::vector<std::pair<std::uint64_t, std::uint32_t>>& tables() const { return tables_; }
225 // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). 225 // The pipeline states and root signatures the recording names (it holds a reference to each until Reset), and
226 // the objects a shim handed it with hold_until_reset.
226 const std::vector<IUnknown*>& pinned() const { return held_; } 227 const std::vector<IUnknown*>& pinned() const { return held_; }
228 // rt::d3d12::hold_until_reset: an object the recording uses that its caller does not keep (a shim's own scratch).
229 void hold_for_recording(IUnknown* object) { hold(object); }
227 bool needs_all_sampled_views() const { 230 bool needs_all_sampled_views() const {
228 if (directly_indexed_) return true; 231 if (directly_indexed_) return true;
229 for (const auto& command : list_.commands()) { 232 for (const auto& command : list_.commands()) {
@@ -512,6 +515,15 @@ public:
512 blend_factor_ = value; 515 blend_factor_ = value;
513 } 516 }
514 517
518 // ID3D12GraphicsCommandList1: the depth-bounds test's range for the draws after it, read by pipelines that enable
519 // the test (DEPTH_STENCIL1/2). D3D12's default is [0, 1].
520 void STDMETHODCALLTYPE OMSetDepthBounds(FLOAT min, FLOAT max) override {
521 if (list_.closed()) return;
522 const std::array<float, 2> value{min, max};
523 if (defer([=](GraphicsCommandList& l) { l.depth_bounds_ = value; })) return;
524 depth_bounds_ = value;
525 }
526
515 void STDMETHODCALLTYPE OMSetStencilRef(UINT reference) override { 527 void STDMETHODCALLTYPE OMSetStencilRef(UINT reference) override {
516 if (list_.closed()) return; 528 if (list_.closed()) return;
517 if (defer([=](GraphicsCommandList& l) { l.front_stencil_ref_ = l.back_stencil_ref_ = reference; })) return; 529 if (defer([=](GraphicsCommandList& l) { l.front_stencil_ref_ = l.back_stencil_ref_ = reference; })) return;
@@ -569,6 +581,8 @@ public:
569 note_direct_heap_indexing(graphics_.layout); 581 note_direct_heap_indexing(graphics_.layout);
570 draw.mesh = true; 582 draw.mesh = true;
571 draw.viewports = draw_viewports(); 583 draw.viewports = draw_viewports();
584 draw.depth_bounds = depth_bounds_;
585 request_draw_pipeline();
572 check(list_.draw(std::move(draw))); 586 check(list_.draw(std::move(draw)));
573 } 587 }
574 588
@@ -837,8 +851,7 @@ public:
837 d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); 851 d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView");
838 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); 852 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false);
839 if (!view.ptr || !color) return check(false); 853 if (!view.ptr || !color) return check(false);
840 // LOCAL DIAGNOSTIC: what the title clears, and with which colour 854 if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: what the title clears, and with which colour
841 if (leonida::local_diagnostics()) {
842 static std::atomic<std::uint64_t> clears{0}; 855 static std::atomic<std::uint64_t> clears{0};
843 const std::uint64_t n = ++clears; 856 const std::uint64_t n = ++clears;
844 if (n <= 6 || n % 600 == 0) { 857 if (n <= 6 || n % 600 == 0) {
@@ -1014,10 +1027,11 @@ public:
1014 if (!leonida::indirect_records_fit(arg_desc.Width, argument_buffer_offset, max_command_count, 1027 if (!leonida::indirect_records_fit(arg_desc.Width, argument_buffer_offset, max_command_count,
1015 stride, sig->packed_size())) 1028 stride, sig->packed_size()))
1016 return check(false); 1029 return check(false);
1017 if (kind == leonida::IndirectKind::dispatch_mesh) { 1030 if (kind == leonida::IndirectKind::dispatch_mesh && !terminal_only) {
1018 // Not replayed yet (#3777 replays it as vkCmdDrawMeshTasksIndirectEXT): nothing is recorded, and the 1031 // A DISPATCH_MESH signature with root arguments before it is not replayed: nothing is recorded, and the
1019 // first such call says so. The list stays valid. 1032 // first such call says so. The list stays valid. A terminal-only one is recorded below as a mesh draw
1020 leonida::indirect_stats::skip(leonida::indirect_stats::Event::record_skip, leonida::indirect_stats::mesh); 1033 // (vkCmdDrawMeshTasksIndirect(Count)EXT).
1034 leonida::indirect_stats::skip(leonida::indirect_stats::Event::record_skip, leonida::indirect_stats::compound);
1021 return; 1035 return;
1022 } 1036 }
1023 if (!terminal_only && (kind == leonida::IndirectKind::draw || kind == leonida::IndirectKind::draw_indexed)) { 1037 if (!terminal_only && (kind == leonida::IndirectKind::draw || kind == leonida::IndirectKind::draw_indexed)) {
@@ -1352,7 +1366,8 @@ private:
1352 1366
1353 void clear_unordered_access(D3D12_CPU_DESCRIPTOR_HANDLE view, ID3D12Resource* resource, bool is_float, 1367 void clear_unordered_access(D3D12_CPU_DESCRIPTOR_HANDLE view, ID3D12Resource* resource, bool is_float,
1354 const std::array<std::uint32_t, 4>& values, UINT count, const D3D12_RECT* rects) { 1368 const std::array<std::uint32_t, 4>& values, UINT count, const D3D12_RECT* rects) {
1355 if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); // no clear is allowed in a bundle 1369 if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT && type_ != D3D12_COMMAND_LIST_TYPE_COMPUTE)
1370 return check(false);
1356 leonida::UavView target{}; 1371 leonida::UavView target{};
1357 if (!view.ptr || !resource || !unordered_access_view(view, resource, target)) return check(false); 1372 if (!view.ptr || !resource || !unordered_access_view(view, resource, target)) return check(false);
1358 check(list_.clear_unordered_access(target, is_float, values, to_rects(count, rects))); 1373 check(list_.clear_unordered_access(target, is_float, values, to_rects(count, rects)));
@@ -1384,17 +1399,26 @@ private:
1384 const bool volume = image.type == g::ImageType::image_3d; 1399 const bool volume = image.type == g::ImageType::image_3d;
1385 const auto pair = xbox_depth_storage(resource); 1400 const auto pair = xbox_depth_storage(resource);
1386 if (pair.colour) out.resource = pair.colour; 1401 if (pair.colour) out.resource = pair.colour;
1387 if (g::partial_volume_uav(words, image)) {
1388 // Transfer clears operate on a whole 3D mip, not a storage image view. Refuse instead of
1389 // overwriting slices outside the UAV; a sliced clear needs a separate replay path.
1390 stub("ClearUnorderedAccessView of a partial 3D mip");
1391 return false;
1392 }
1393 out.buffer = false; 1402 out.buffer = false;
1394 out.format = std::uint32_t(descriptor_format(image.format, image.swizzle)); 1403 out.format = std::uint32_t(descriptor_format(image.format, image.swizzle));
1395 out.mip = image.first_mip; 1404 out.mip = image.first_mip;
1396 out.first_layer = volume ? 0 : image.first_layer; // a 3D view clears every slice of its mip 1405 if (volume) {
1397 out.layer_count = volume ? 1 : image.layer_count; 1406 g::VolumeUavRange slices{};
1407 if (g::volume_uav_range(words, image, slices)) {
1408 out.first_layer = slices.first_w;
1409 out.layer_count = slices.w_size;
1410 } else {
1411 // Untagged T#s select the entire resource mip, even if DEPTH describes a smaller or larger view.
1412 const auto desc = resource->GetDesc();
1413 const auto depth = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D
1414 ? std::uint32_t(desc.DepthOrArraySize) : image.depth;
1415 out.first_layer = 0;
1416 out.layer_count = std::max(1u, depth >> image.first_mip);
1417 }
1418 } else {
1419 out.first_layer = image.first_layer;
1420 out.layer_count = image.layer_count;
1421 }
1398 out.exact_clear_format = volume || image.type == g::ImageType::image_1d || 1422 out.exact_clear_format = volume || image.type == g::ImageType::image_1d ||
1399 image.type == g::ImageType::image_1d_array; 1423 image.type == g::ImageType::image_1d_array;
1400 return out.format != VK_FORMAT_UNDEFINED; 1424 return out.format != VK_FORMAT_UNDEFINED;
@@ -1533,8 +1557,10 @@ private:
1533 // No copy for the title's memory: the root view is 0, so the shader reads the arena's zero page instead 1557 // No copy for the title's memory: the root view is 0, so the shader reads the arena's zero page instead
1534 // of storing at heap_base + a raw title address. 1558 // of storing at heap_base + a raw title address.
1535 if (!va && raw) leonida::note_unbacked_view("root view", raw, kRootViewBytes); 1559 if (!va && raw) leonida::note_unbacked_view("root view", raw, kRootViewBytes);
1536 } else 1560 } else {
1561 if (descriptor_ring_diagnostics()) note_table_slots(va, p->table_descriptors);
1537 va = console_descriptor_table_va(va); 1562 va = console_descriptor_table_va(va);
1563 }
1538 if (type != rt::rootsig::ParamType::Descriptor && va && p->table_descriptors) 1564 if (type != rt::rootsig::ParamType::Descriptor && va && p->table_descriptors)
1539 remember_table(va, p->table_descriptors); 1565 remember_table(va, p->table_descriptors);
1540 const std::uint32_t first = first_dword(state, *p); 1566 const std::uint32_t first = first_dword(state, *p);
@@ -1561,6 +1587,9 @@ private:
1561 ID3D12DescriptorHeap* sampler_heap_ = nullptr; 1587 ID3D12DescriptorHeap* sampler_heap_ = nullptr;
1562 D3D12_GPU_VIRTUAL_ADDRESS cbv_srv_uav_base_ = 0; 1588 D3D12_GPU_VIRTUAL_ADDRESS cbv_srv_uav_base_ = 0;
1563 D3D12_GPU_VIRTUAL_ADDRESS sampler_base_ = 0; 1589 D3D12_GPU_VIRTUAL_ADDRESS sampler_base_ = 0;
1590 UINT heap_slots_[2]{}; // NumDescriptors of the bound view and sampler heaps
1591 std::uint64_t table_high_[3]{}; // this list's descriptor-ring marks: view, sampler, console heap (note_table_slots)
1592 std::uint64_t console_high_base_ = 0; // the console heap table_high_[2] is for
1564 std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED 1593 std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED
1565 std::array<leonida::VertexBufferView, D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> vertex_buffers_{}; 1594 std::array<leonida::VertexBufferView, D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT> vertex_buffers_{};
1566 leonida::IndexBufferView index_{}; 1595 leonida::IndexBufferView index_{};
@@ -1585,6 +1614,7 @@ private:
1585 bool draw_views_stale_ = true; 1614 bool draw_views_stale_ = true;
1586 leonida::TargetView depth_{}; 1615 leonida::TargetView depth_{};
1587 std::array<float, 4> blend_factor_{1, 1, 1, 1}; 1616 std::array<float, 4> blend_factor_{1, 1, 1, 1};
1617 std::array<float, 2> depth_bounds_{0, 1};
1588 1618
1589 // The root signatures and pipeline states this recording uses. D3D12 lets an application release them right 1619 // The root signatures and pipeline states this recording uses. D3D12 lets an application release them right
1590 // after Set*RootSignature / SetPipelineState; the list keeps them until Reset or its own release, so the root 1620 // after Set*RootSignature / SetPipelineState; the list keeps them until Reset or its own release, so the root
@@ -1632,6 +1662,7 @@ private:
1632 hold(state); 1662 hold(state);
1633 compute_pipeline_ = compute_pipeline_id(state); 1663 compute_pipeline_ = compute_pipeline_id(state);
1634 graphics_pipeline_ = graphics_pipeline_id(state); 1664 graphics_pipeline_ = graphics_pipeline_id(state);
1665 if (compute_pipeline_) request_pipeline_build(compute_pipeline_, 0, false); // starts its build, if asynchronous
1635 // A pipeline this device never registered: a LEONIDA_STUB_PIPELINES stub (its translated shader is missing), 1666 // A pipeline this device never registered: a LEONIDA_STUB_PIPELINES stub (its translated shader is missing),
1636 // or one from another device. Its draws resolve to nothing in replay; its dispatches are no-ops too 1667 // or one from another device. Its draws resolve to nothing in replay; its dispatches are no-ops too
1637 // (record_dispatch), so the list still closes. 1668 // (record_dispatch), so the list still closes.
@@ -1646,6 +1677,81 @@ private:
1646 cbv_srv_uav_base_ = cbv_base; 1677 cbv_srv_uav_base_ = cbv_base;
1647 sampler_heap_ = smp; 1678 sampler_heap_ = smp;
1648 sampler_base_ = smp_base; 1679 sampler_base_ = smp_base;
1680 if (!descriptor_ring_diagnostics()) return;
1681 for (int h = 0; h < 2; ++h) {
1682 D3D12_DESCRIPTOR_HEAP_DESC desc{};
1683 D3D12_GPU_VIRTUAL_ADDRESS base = 0;
1684 heap_slots_[h] = descriptor_heap_info(h ? smp : cbv, desc, base) ? desc.NumDescriptors : 0;
1685 table_high_[h] = 0;
1686 }
1687 }
1688
1689 // note_table_slots runs on every descriptor-table bind of the title's recording threads, and takes a global lock
1690 // whenever a list's mark rises (almost every bind of a ring): only with LEONIDA_DEVICE_FAULT=1 or
1691 // LEONIDA_DESCRIPTOR_RING=1.
1692 static bool descriptor_ring_diagnostics() {
1693 static const bool on = [] {
1694 char v[2]{};
1695 return (GetEnvironmentVariableA("LEONIDA_DEVICE_FAULT", v, 2) == 1 && (v[0] == '1' || v[0] == '2')) ||
1696 (GetEnvironmentVariableA("LEONIDA_DESCRIPTOR_RING", v, 2) == 1 && v[0] == '1');
1697 }();
1698 return on;
1699 }
1700
1701 // LOCAL DIAGNOSTIC (early device loss; VIctory 3827767, a title table ring past the slots the layer backs hung
1702 // NVIDIA ~45 s in): the highest slot a descriptor table reaches in each bound heap, against the heap's slots. Logged
1703 // when a heap's high-water mark passes another eighth of the heap, every new mark past its end, and the first
1704 // tables that lie in no bound heap. A list only takes the shared lock when its own mark rises.
1705 void note_table_slots(std::uint64_t va, std::uint32_t declared) {
1706 if (!va) return;
1707 D3D12_GPU_VIRTUAL_ADDRESS bases[3]{cbv_srv_uav_base_, sampler_base_, 0};
1708 std::uint64_t counts[3]{heap_slots_[0], heap_slots_[1], 0};
1709 int heap = -1;
1710 for (int h = 0; h < 2; ++h)
1711 if (bases[h] && counts[h] && va >= bases[h] && va < bases[h] + counts[h] * descriptor_size)
1712 heap = h;
1713 std::uint64_t console_bytes = 0;
1714 if (heap < 0 && console_descriptor_heap_range(va, bases[2], console_bytes)) {
1715 heap = 2; // a console descriptor heap (Xbox slot 14) in title memory, read from its arena copy
1716 counts[2] = console_bytes / descriptor_size;
1717 }
1718 if (heap < 0) {
1719 static std::atomic<int> outside{0};
1720 if (outside.fetch_add(1) < 8)
1721 std::fprintf(stderr, "[rt] descriptor-ring: table 0x%llx in no bound heap (view heap 0x%llx, %u slots; "
1722 "sampler heap 0x%llx, %u slots)\n",
1723 (unsigned long long)va, (unsigned long long)bases[0], heap_slots_[0],
1724 (unsigned long long)bases[1], heap_slots_[1]);
1725 return;
1726 }
1727 const std::uint64_t first = (va - bases[heap]) / descriptor_size;
1728 const std::uint64_t end = first + (declared ? declared : 1);
1729 if (heap == 2 && console_high_base_ != bases[2]) {
1730 console_high_base_ = bases[2];
1731 table_high_[2] = 0;
1732 }
1733 if (end <= table_high_[heap]) return;
1734 table_high_[heap] = end;
1735 struct Mark {
1736 std::uint64_t high = 0;
1737 std::uint64_t logged = 0;
1738 };
1739 static std::mutex mutex;
1740 static std::map<std::uint64_t, Mark> marks; // by heap base
1741 std::lock_guard lock(mutex);
1742 Mark& mark = marks[bases[heap]];
1743 if (end <= mark.high) return;
1744 mark.high = end;
1745 const std::uint64_t slots = counts[heap];
1746 const std::uint64_t step = (std::max)(slots / 8, std::uint64_t{1});
1747 if (end > slots || end >= mark.logged + step) {
1748 mark.logged = end;
1749 std::fprintf(stderr, "[rt] descriptor-ring: %s heap 0x%llx: highest slot %llu (table at %llu, %u declared) "
1750 "of %llu backed%s\n",
1751 heap == 2 ? "console" : heap ? "sampler" : "view", (unsigned long long)bases[heap], (unsigned long long)(end - 1),
1752 (unsigned long long)first, declared, (unsigned long long)slots,
1753 end > slots ? " -- PAST THE HEAP" : "");
1754 }
1649 } 1755 }
1650 1756
1651 // D3D12 bundle rule: every non-null heap bound by a bundle's SetDescriptorHeaps must match the parent list's 1757 // D3D12 bundle rule: every non-null heap bound by a bundle's SetDescriptorHeaps must match the parent list's
@@ -1663,19 +1769,26 @@ private:
1663 1769
1664 void note_direct_heap_indexing(const RootArgumentLayout* layout) { 1770 void note_direct_heap_indexing(const RootArgumentLayout* layout) {
1665 if (!layout) return; 1771 if (!layout) return;
1772 // Called at every draw and dispatch: each note has its own flag, so after its first time a site skips
1773 // note_once's process-wide mutex, std::string and set lookup.
1774 static std::atomic<bool> told[4];
1775 const auto once = [](int site, const char* what) {
1776 if (!told[site].load(std::memory_order_relaxed) && !told[site].exchange(true)) note_once(what);
1777 };
1666 if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) { 1778 if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) {
1667 if (!cbv_srv_uav_heap_) 1779 if (!cbv_srv_uav_heap_)
1668 note_once("draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound"); 1780 once(0, "draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound");
1669 else { 1781 else {
1670 remember_table(cbv_srv_uav_base_, cbv_srv_uav_heap_->GetDesc().NumDescriptors); 1782 const auto shader_va = console_descriptor_table_va(cbv_srv_uav_base_);
1671 note_once("CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list"); 1783 remember_table(shader_va, cbv_srv_uav_heap_->GetDesc().NumDescriptors);
1784 once(1, "CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list");
1672 } 1785 }
1673 } 1786 }
1674 if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { 1787 if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) {
1675 if (!sampler_heap_) 1788 if (!sampler_heap_)
1676 note_once("draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound"); 1789 once(2, "draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound");
1677 else 1790 else
1678 note_once("SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list"); 1791 once(3, "SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list");
1679 } 1792 }
1680 } 1793 }
1681 1794
@@ -1703,6 +1816,7 @@ private:
1703 draw_views_stale_ = true; 1816 draw_views_stale_ = true;
1704 depth_ = {}; 1817 depth_ = {};
1705 blend_factor_ = {1, 1, 1, 1}; 1818 blend_factor_ = {1, 1, 1, 1};
1819 depth_bounds_ = {0, 1};
1706 set_pipeline(state); 1820 set_pipeline(state);
1707 } 1821 }
1708 1822
@@ -1771,10 +1885,14 @@ private:
1771 void write_direct_heaps(const RootState& state, std::uint32_t slot, 1885 void write_direct_heaps(const RootState& state, std::uint32_t slot,
1772 std::array<std::uint32_t, rt::rootsig::kMaxUserSgprs>& data) const { 1886 std::array<std::uint32_t, rt::rootsig::kMaxUserSgprs>& data) const {
1773 const auto flags = state.layout->flags; 1887 const auto flags = state.layout->flags;
1774 if ((flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) && slot < data.size()) 1888 if ((flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) && slot < data.size()) {
1775 data[slot++] = static_cast<std::uint32_t>(cbv_srv_uav_base_); 1889 const D3D12_GPU_VIRTUAL_ADDRESS va = console_descriptor_table_va(cbv_srv_uav_base_);
1776 if ((flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) && slot < data.size()) 1890 data[slot++] = static_cast<std::uint32_t>(va);
1777 data[slot] = static_cast<std::uint32_t>(sampler_base_); 1891 }
1892 if ((flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) && slot < data.size()) {
1893 const D3D12_GPU_VIRTUAL_ADDRESS va = console_descriptor_table_va(sampler_base_);
1894 data[slot] = static_cast<std::uint32_t>(va);
1895 }
1778 } 1896 }
1779 1897
1780 std::array<std::uint32_t, rt::rootsig::kMaxUserSgprs> with_direct_heaps(const RootState& state, 1898 std::array<std::uint32_t, rt::rootsig::kMaxUserSgprs> with_direct_heaps(const RootState& state,
@@ -1830,9 +1948,12 @@ private:
1830 } 1948 }
1831 const std::uint32_t end = layout.graphics_arguments_end; 1949 const std::uint32_t end = layout.graphics_arguments_end;
1832 if (end >= rt::rootsig::kMaxUserSgprs) { 1950 if (end >= rt::rootsig::kMaxUserSgprs) {
1833 note_once(layout.graphics_console 1951 static std::atomic<bool> told[2]; // per draw: the site's own flag before note_once's mutex
1834 ? "graphics direct heaps: not supplied, the explicit arguments fill s8..s31" 1952 const int site = layout.graphics_console ? 0 : 1;
1835 : "graphics direct heaps: not supplied, the signature keeps the s0 graphics layout"); 1953 if (!told[site].load(std::memory_order_relaxed) && !told[site].exchange(true))
1954 note_once(layout.graphics_console
1955 ? "graphics direct heaps: not supplied, the explicit arguments fill s8..s31"
1956 : "graphics direct heaps: not supplied, the signature keeps the s0 graphics layout");
1836 return graphics_.data; 1957 return graphics_.data;
1837 } 1958 }
1838 static std::atomic<bool> logged{false}; 1959 static std::atomic<bool> logged{false};
@@ -1840,13 +1961,17 @@ private:
1840 const bool resource = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; 1961 const bool resource = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED;
1841 const bool sampler = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; 1962 const bool sampler = layout.flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED;
1842 char resource_at[48] = "none", sampler_at[48] = "none"; 1963 char resource_at[48] = "none", sampler_at[48] = "none";
1843 if (resource) 1964 if (resource) {
1965 const auto va = console_descriptor_table_va(cbv_srv_uav_base_);
1844 std::snprintf(resource_at, sizeof resource_at, "0x%llx at s%u", 1966 std::snprintf(resource_at, sizeof resource_at, "0x%llx at s%u",
1845 static_cast<unsigned long long>(std::uint32_t(cbv_srv_uav_base_)), end); 1967 static_cast<unsigned long long>(std::uint32_t(va)), end);
1846 if (sampler && end + (resource ? 1u : 0u) < rt::rootsig::kMaxUserSgprs) 1968 }
1969 if (sampler && end + (resource ? 1u : 0u) < rt::rootsig::kMaxUserSgprs) {
1970 const auto va = console_descriptor_table_va(sampler_base_);
1847 std::snprintf(sampler_at, sizeof sampler_at, "0x%llx at s%u", 1971 std::snprintf(sampler_at, sizeof sampler_at, "0x%llx at s%u",
1848 static_cast<unsigned long long>(std::uint32_t(sampler_base_)), 1972 static_cast<unsigned long long>(std::uint32_t(va)),
1849 end + (resource ? 1u : 0u)); 1973 end + (resource ? 1u : 0u));
1974 }
1850 std::fprintf(stderr, 1975 std::fprintf(stderr,
1851 "[rt] d3d12: graphics direct heaps: resource heap %s, sampler heap %s, after %u dwords of " 1976 "[rt] d3d12: graphics direct heaps: resource heap %s, sampler heap %s, after %u dwords of "
1852 "explicit arguments from s8 (first draw; LEONIDA_GRAPHICS_DIRECT_HEAPS=0 " 1977 "explicit arguments from s8 (first draw; LEONIDA_GRAPHICS_DIRECT_HEAPS=0 "
@@ -1912,7 +2037,41 @@ private:
1912 return draw_viewports_; 2037 return draw_viewports_;
1913 } 2038 }
1914 2039
2040 // LEONIDA_ASYNC_PIPELINES=1: the variant this draw needs (by the targets it binds) starts building on the compile
2041 // worker now, before the list is submitted (request_pipeline_build).
2042 void request_draw_pipeline() const {
2043 std::uint32_t bound = 0;
2044 for (UINT slot = 0; slot < render_target_count_ && slot < render_targets_.size(); ++slot)
2045 if (render_targets_[slot].resource) bound |= 1u << slot;
2046 request_pipeline_build(graphics_pipeline_, bound, depth_.resource != 0);
2047 }
2048
2049 // One recorder for both entry points: the direct ExecuteIndirect call and a bundle call deferred into its
2050 // parent list. A simple DRAW or DRAW_INDEXED signature becomes a stateful Draw (IndirectRasterDraw) carrying the
2051 // graphics state frozen at the call; anything else stays a legacy ExecuteIndirect command.
1915 void record_indirect(leonida::IndirectKind kind, bool terminal_only, const leonida::IndirectDrawArgs& args) { 2052 void record_indirect(leonida::IndirectKind kind, bool terminal_only, const leonida::IndirectDrawArgs& args) {
2053 if (kind == leonida::IndirectKind::dispatch_mesh) {
2054 // As DispatchMesh, with the group counts in the argument buffer: the replay draws the records with
2055 // vkCmdDrawMeshTasksIndirect(Count)EXT after its clamp pass bounds them.
2056 if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false);
2057 if (!args.max_count) return;
2058 namespace stats = leonida::indirect_stats;
2059 const auto skip = [](stats::Reason reason) { stats::skip(stats::Event::record_skip, reason); };
2060 if (indirect_draws_disabled()) return skip(stats::disabled);
2061 if (!terminal_only) return skip(stats::compound);
2062 if (!graphics_pipeline_) return skip(stats::pipeline);
2063 if (!graphics_.layout) return skip(stats::root_layout);
2064 if (!(viewport_.width > 0) || !(viewport_.height > 0)) return skip(stats::viewport);
2065 leonida::Draw draw{graphics_pipeline_, graphics_user_data(), draw_views(), depth_, {}, 0, viewport_,
2066 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, 0, 0, 0, 0, 0};
2067 note_direct_heap_indexing(graphics_.layout);
2068 draw.mesh = true;
2069 draw.depth_bounds = depth_bounds_;
2070 request_draw_pipeline();
2071 const bool recorded = list_.draw_indirect(std::move(draw), args);
2072 if (recorded) stats::note(stats::Event::recorded);
2073 return check(recorded);
2074 }
1916 if (kind == leonida::IndirectKind::draw || kind == leonida::IndirectKind::draw_indexed) { 2075 if (kind == leonida::IndirectKind::draw || kind == leonida::IndirectKind::draw_indexed) {
1917 if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false); 2076 if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false);
1918 // A valid zero-count call records nothing, even if graphics state has not been set. 2077 // A valid zero-count call records nothing, even if graphics state has not been set.
@@ -1931,11 +2090,11 @@ private:
1931 if (!terminal_only) return skip(stats::compound); 2090 if (!terminal_only) return skip(stats::compound);
1932 if (!graphics_pipeline_) return skip(stats::pipeline); 2091 if (!graphics_pipeline_) return skip(stats::pipeline);
1933 if (!graphics_.layout) return skip(stats::root_layout); 2092 if (!graphics_.layout) return skip(stats::root_layout);
1934 if (topology_ != D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST) return skip(stats::topology); 2093 if (!stats::topology_supported(topology_)) return skip(stats::topology);
1935 if (indexed && (!index_.va || !index_.size || 2094 if (indexed && (!index_.va || !index_.size ||
1936 (index_.format != DXGI_FORMAT_R16_UINT && index_.format != DXGI_FORMAT_R32_UINT))) 2095 (index_.format != DXGI_FORMAT_R16_UINT && index_.format != DXGI_FORMAT_R32_UINT)))
1937 return skip(stats::index_view); 2096 return skip(stats::index_view);
1938 if (!(viewport_.width > 0) || !(viewport_.height > 0)) return skip(stats::viewport); 2097 if (!any_nonempty_viewport()) return skip(stats::viewport);
1939 note_direct_heap_indexing(graphics_.layout); 2098 note_direct_heap_indexing(graphics_.layout);
1940 record_raster_draw(indexed, 0, 0, 0, 0, 0, &args); 2099 record_raster_draw(indexed, 0, 0, 0, 0, 0, &args);
1941 return; 2100 return;
@@ -1963,8 +2122,12 @@ private:
1963 note_direct_heap_indexing(graphics_.layout); 2122 note_direct_heap_indexing(graphics_.layout);
1964 // No viewport (never set, or unbound with RSSetViewports(0)) or every bound viewport empty: D3D12 rasterizes 2123 // No viewport (never set, or unbound with RSSetViewports(0)) or every bound viewport empty: D3D12 rasterizes
1965 // nothing, and Vulkan forbids a 0x0 viewport, so the draw is not recorded. 2124 // nothing, and Vulkan forbids a 0x0 viewport, so the draw is not recorded.
1966 // LOCAL DIAGNOSTIC: the state each draw is recorded with 2125 static const bool draw_diag = [] {
1967 if (leonida::local_diagnostics()) { 2126 const char* value = std::getenv("LEONIDA_DRAW_DIAG");
2127 if (value) return std::strcmp(value, "0") != 0;
2128 return leonida::local_diagnostics() || leonida::fsdraw::enabled();
2129 }();
2130 if (draw_diag) {
1968 static std::atomic<std::uint64_t> draws{0}, skipped{0}; 2131 static std::atomic<std::uint64_t> draws{0}, skipped{0};
1969 const bool skip = !any_nonempty_viewport(); 2132 const bool skip = !any_nonempty_viewport();
1970 const std::uint64_t n = ++draws, k = skip ? ++skipped : skipped.load(); 2133 const std::uint64_t n = ++draws, k = skip ? ++skipped : skipped.load();
@@ -1978,16 +2141,18 @@ private:
1978 scissor_.left, scissor_.top, scissor_.right, scissor_.bottom, count, instances); 2141 scissor_.left, scissor_.top, scissor_.right, scissor_.bottom, count, instances);
1979 // LOCAL DIAGNOSTIC (fsdraw): the first draw of each pipeline, and one frame's draws every ~300 frames, 2142 // LOCAL DIAGNOSTIC (fsdraw): the first draw of each pipeline, and one frame's draws every ~300 frames,
1980 // with the pipeline's description, the root data and what the bound descriptor tables hold. 2143 // with the pipeline's description, the root data and what the bound descriptor tables hold.
2144 // Only with LEONIDA_FSDRAW_PROBE=1.
1981 static std::mutex seen_mutex; 2145 static std::mutex seen_mutex;
1982 static std::set<std::uintptr_t> seen; 2146 static std::set<std::uintptr_t> seen;
1983 bool first_seen; 2147 const bool fsdraw = leonida::fsdraw::enabled();
1984 { 2148 bool first_seen = false;
2149 if (fsdraw) {
1985 std::lock_guard lock(seen_mutex); 2150 std::lock_guard lock(seen_mutex);
1986 first_seen = seen.insert(graphics_pipeline_).second; 2151 first_seen = seen.insert(graphics_pipeline_).second;
1987 } 2152 }
1988 const bool fullscreen = render_target_count_ >= 1 && count == 3 && viewport_.width >= 1000; 2153 const bool fullscreen = render_target_count_ >= 1 && count == 3 && viewport_.width >= 1000;
1989 if (fullscreen) leonida::fsdraw::note_target(render_targets_[0].resource); 2154 if (fullscreen) leonida::fsdraw::note_target(render_targets_[0].resource);
1990 if (first_seen || (n - 1) % 600 < 2 || (n > 2 && n < 9)) { 2155 if (fsdraw && (first_seen || (n - 1) % 600 < 2 || (n > 2 && n < 9))) {
1991 std::fprintf(stderr, "[rt] fsdraw: draw #%llu pso %p%s rt0 0x%llx rts %u depth 0x%llx count %u x%u: %s\n", 2156 std::fprintf(stderr, "[rt] fsdraw: draw #%llu pso %p%s rt0 0x%llx rts %u depth 0x%llx count %u x%u: %s\n",
1992 static_cast<unsigned long long>(n), reinterpret_cast<const void*>(graphics_pipeline_), 2157 static_cast<unsigned long long>(n), reinterpret_cast<const void*>(graphics_pipeline_),
1993 first_seen ? " (first use)" : "", static_cast<unsigned long long>(render_targets_[0].resource), 2158 first_seen ? " (first use)" : "", static_cast<unsigned long long>(render_targets_[0].resource),
@@ -2055,6 +2220,8 @@ private:
2055 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, 2220 scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances,
2056 first, base_vertex, first_instance}; 2221 first, base_vertex, first_instance};
2057 draw.viewports = draw_viewports(); 2222 draw.viewports = draw_viewports();
2223 draw.depth_bounds = depth_bounds_;
2224 request_draw_pipeline();
2058 const bool recorded = indirect ? list_.draw_indirect(std::move(draw), *indirect) : list_.draw(std::move(draw)); 2225 const bool recorded = indirect ? list_.draw_indirect(std::move(draw), *indirect) : list_.draw(std::move(draw));
2059 if (indirect && recorded) leonida::indirect_stats::note(leonida::indirect_stats::Event::recorded); 2226 if (indirect && recorded) leonida::indirect_stats::note(leonida::indirect_stats::Event::recorded);
2060 check(recorded); 2227 check(recorded);
@@ -2137,6 +2304,11 @@ public:
2137 return S_OK; 2304 return S_OK;
2138 } 2305 }
2139 2306
2307 // `fn` on the dispatcher's thread once the fence reaches `value` (rt::d3d12::fence_callback_at).
2308 void callback_at(UINT64 value, std::function<void()> fn) {
2309 context_.enqueue_fence_callback(fence_.semaphore(), value, std::move(fn));
2310 }
2311
2140 // Counts `waiter` down once this fence reaches `value`: now if it has, else via the centralized dispatcher. 2312 // Counts `waiter` down once this fence reaches `value`: now if it has, else via the centralized dispatcher.
2141 void notify(UINT64 value, std::shared_ptr<FenceWaiter> waiter) { 2313 void notify(UINT64 value, std::shared_ptr<FenceWaiter> waiter) {
2142 if (context_.is_device_lost() || fence_.completed() >= value) { 2314 if (context_.is_device_lost() || fence_.completed() >= value) {
@@ -2178,7 +2350,8 @@ public:
2178 2350
2179 // What a held batch (queue_holds.h) keeps alive until it has run: the pipeline states and root signatures its 2351 // What a held batch (queue_holds.h) keeps alive until it has run: the pipeline states and root signatures its
2180 // lists name, which the application may release and Reset away as soon as ExecuteCommandLists returns. Resources 2352 // lists name, which the application may release and Reset away as soon as ExecuteCommandLists returns. Resources
2181 // are not held (a D3D12 application keeps them until the fence it signals; the docs, section 4.4, list this). 2353 // are not held (a D3D12 application keeps them until the fence it signals; the docs, section 4.4, list this),
2354 // except a shim's own the recording uses (hold_until_reset), which are pinned with them.
2182 static std::shared_ptr<void> pin_lists(const std::vector<const GraphicsCommandList*>& lists) { 2355 static std::shared_ptr<void> pin_lists(const std::vector<const GraphicsCommandList*>& lists) {
2183 auto objects = std::shared_ptr<std::vector<IUnknown*>>(new std::vector<IUnknown*>, [](auto* held) { 2356 auto objects = std::shared_ptr<std::vector<IUnknown*>>(new std::vector<IUnknown*>, [](auto* held) {
2184 for (IUnknown* object : *held) object->Release(); 2357 for (IUnknown* object : *held) object->Release();
@@ -2309,7 +2482,7 @@ public:
2309 // LOCAL DIAGNOSTIC (fsdraw): what the bound tables hold when the lists are submitted 2482 // LOCAL DIAGNOSTIC (fsdraw): what the bound tables hold when the lists are submitted
2310 if (leonida::local_diagnostics()) { 2483 if (leonida::local_diagnostics()) {
2311 static std::atomic<std::uint64_t> submits{0}; 2484 static std::atomic<std::uint64_t> submits{0};
2312 const std::uint64_t n = tables.empty() ? 0 : ++submits; 2485 const std::uint64_t n = tables.empty() || !leonida::fsdraw::enabled() ? 0 : ++submits;
2313 if (n && (n <= 6 || n % 300 == 0)) { 2486 if (n && (n <= 6 || n % 300 == 0)) {
2314 char tag[48]; 2487 char tag[48];
2315 std::snprintf(tag, sizeof tag, "submit #%llu", static_cast<unsigned long long>(n)); 2488 std::snprintf(tag, sizeof tag, "submit #%llu", static_cast<unsigned long long>(n));
@@ -2367,6 +2540,10 @@ public:
2367 if (last_result_ != leonida::ReplayResult::success) 2540 if (last_result_ != leonida::ReplayResult::success)
2368 std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists failed: %s; nothing was submitted\n", 2541 std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists failed: %s; nothing was submitted\n",
2369 name(last_result_)); 2542 name(last_result_));
2543 // A batch or Signal that failed after its call returned (held, or on the queue's worker with
2544 // LEONIDA_SUBMIT_ASYNC; reported on stderr there) is this call's result, one call late.
2545 if (last_result_ == leonida::ReplayResult::success)
2546 if (const auto held = queue_.take_held_failure(); held != leonida::ReplayResult::success) last_result_ = held;
2370 } 2547 }
2371 2548
2372 // A copy list's timestamps go to COPY_QUEUE_TIMESTAMP heaps and every other list's to TIMESTAMP heaps. 2549 // A copy list's timestamps go to COPY_QUEUE_TIMESTAMP heaps and every other list's to TIMESTAMP heaps.
@@ -2793,6 +2970,13 @@ bool command_signature_info(ID3D12CommandSignature* signature, leonida::Indirect
2793 return true; 2970 return true;
2794} 2971}
2795 2972
2973bool fence_callback_at(ID3D12Fence* fence, std::uint64_t value, std::function<void()> fn) {
2974 Fence* f = Fence::from(fence);
2975 if (!f) return false;
2976 f->callback_at(value, std::move(fn));
2977 return true;
2978}
2979
2796leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue) { 2980leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue) {
2797 if (ID3D12CommandQueue* real = d3d12_xs::queue_proxy_real_queue(queue)) queue = real; // the Xbox-ABI proxy 2981 if (ID3D12CommandQueue* real = d3d12_xs::queue_proxy_real_queue(queue)) queue = real; // the Xbox-ABI proxy
2798 CommandQueue* q = CommandQueue::from(queue); 2982 CommandQueue* q = CommandQueue::from(queue);
@@ -2807,6 +2991,13 @@ bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT&
2807 return true; 2991 return true;
2808} 2992}
2809 2993
2994bool hold_until_reset(ID3D12GraphicsCommandList* list, IUnknown* object) {
2995 GraphicsCommandList* l = GraphicsCommandList::from(list);
2996 if (!l || !object) return false;
2997 l->hold_for_recording(object);
2998 return true;
2999}
3000
2810bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector<leonida::Command>& commands) { 3001bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector<leonida::Command>& commands) {
2811 const GraphicsCommandList* l = GraphicsCommandList::from(list); 3002 const GraphicsCommandList* l = GraphicsCommandList::from(list);
2812 if (!l) return false; 3003 if (!l) return false;
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index 849791a26..ca2b02789 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -14,6 +14,8 @@
14 14
15#include <windows.h> 15#include <windows.h>
16#include <d3d12.h> 16#include <d3d12.h>
17#include <array>
18#include <map>
17#include <memory> 19#include <memory>
18#include <vector> 20#include <vector>
19 21
@@ -30,6 +32,7 @@
30 32
31#include "../src/root_signature.h" 33#include "../src/root_signature.h"
32#include "../src/subgroup_size.h" 34#include "../src/subgroup_size.h"
35#include "../src/vulkan_memory_budget.h"
33 36
34namespace leonida { 37namespace leonida {
35class VulkanPresenter; 38class VulkanPresenter;
@@ -101,14 +104,20 @@ struct VulkanDeviceInfo {
101 std::vector<VkQueue> compute_queues; 104 std::vector<VkQueue> compute_queues;
102 std::vector<VkQueue> copy_queues; 105 std::vector<VkQueue> copy_queues;
103 bool pipeline_creation_feedback = false; 106 bool pipeline_creation_feedback = false;
107 // Vulkan 1.3 pipelineCreationCacheControl, enabled: FAIL_ON_PIPELINE_COMPILE_REQUIRED asks a cache without a compile.
108 // Implies core VkPipelineCreationFeedback, which then needs no extension.
109 bool pipeline_cache_control = false;
104 bool device_fault_diagnostics = false; 110 bool device_fault_diagnostics = false;
105 bool device_fault_info = false; 111 bool device_fault_info = false;
106 bool device_checkpoints = false; 112 bool device_checkpoints = false;
107 bool device_diagnostics_config = false; 113 bool device_diagnostics_config = false;
114 bool device_markers = false; // VK_AMD_buffer_marker enabled for LEONIDA_DEVICE_MARKERS=1
108 bool separate_depth_stencil_layouts = true; 115 bool separate_depth_stencil_layouts = true;
109 bool depth_range_unrestricted = false; // VK_EXT_depth_range_unrestricted enabled on this device. 116 bool depth_range_unrestricted = false; // VK_EXT_depth_range_unrestricted enabled on this device.
110 std::uint32_t max_push_constants_size = 0; 117 std::uint32_t max_push_constants_size = 0;
111 bool push_constants_need_fallback = false; 118 bool push_constants_need_fallback = false;
119 // Top location for relocated f16 halves (0: read from device limits; non-zero: override for testing low-limit devices).
120 std::uint32_t f16_half_top_location = 0;
112 // maxBufferSize and maxMemoryAllocationSize, which cap the GPU address arena (src/arena_size.h). 0: read from 121 // maxBufferSize and maxMemoryAllocationSize, which cap the GPU address arena (src/arena_size.h). 0: read from
113 // the physical device when the D3D12 device is created; a test sets smaller ones to simulate a device. 122 // the physical device when the D3D12 device is created; a test sets smaller ones to simulate a device.
114 VkDeviceSize max_buffer_size = 0; 123 VkDeviceSize max_buffer_size = 0;
@@ -215,6 +224,20 @@ struct VulkanDeviceInfo {
215 // VK_EXT_mesh_shader's meshShaderQueries feature is enabled on `device`, so the clipping invocations of a mesh 224 // VK_EXT_mesh_shader's meshShaderQueries feature is enabled on `device`, so the clipping invocations of a mesh
216 // segment come from a mesh-primitives query (D3D-MESH-CLIPPING-COUNTER). Without it they read 0. 225 // segment come from a mesh-primitives query (D3D-MESH-CLIPPING-COUNTER). Without it they read 0.
217 bool mesh_shader_queries = false; 226 bool mesh_shader_queries = false;
227 // VK_EXT_transform_feedback with its transformFeedback feature is enabled on `device` (D3D-302): an
228 // SO_STATISTICS heap is a real VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool, begun and ended indexed on the
229 // stream. StreamOutput PSOs are still refused and SOSetTargets is still not implemented.
230 bool transform_feedback = false;
231 // VK_EXT_transform_feedback's geometryStreams feature is offered by the device. The device-enable chain requests
232 // it when present so the pipeline cache key matches vk_pipeline_check; nothing rasterizes a stream other than 0.
233 bool transform_feedback_geometry_streams = false;
234 // VK_EXT_transform_feedback's transformFeedbackQueries property (D3D-302): the device can begin/end a
235 // VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT query. Without it an SO_STATISTICS heap is made without a pool and
236 // every SO_STATISTICS query resolves zero, even when the transformFeedback feature is enabled.
237 bool transform_feedback_queries = false;
238 // The device's maxTransformFeedbackStreams property: an SO_STATISTICS_STREAMn query runs only for n below it.
239 // Streams from this count up (to the D3D12 maximum of four) run nothing and resolve zero.
240 std::uint32_t max_transform_feedback_streams = 0;
218 // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, 241 // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid,
219 // depthBiasClamp or dualSrcBlend are refused unless it is set here. 242 // depthBiasClamp or dualSrcBlend are refused unless it is set here.
220 VkPhysicalDeviceFeatures features{}; 243 VkPhysicalDeviceFeatures features{};
@@ -239,6 +262,9 @@ struct VulkanDeviceInfo {
239 bool draw_indirect_count_enabled = false; 262 bool draw_indirect_count_enabled = false;
240 // Both VK_KHR_maintenance5 and robustBufferAccess2 (with core robustBufferAccess) are enabled. 263 // Both VK_KHR_maintenance5 and robustBufferAccess2 (with core robustBufferAccess) are enabled.
241 bool robust_index_view = false; 264 bool robust_index_view = false;
265 // VK_EXT_memory_budget is enabled on `device`: vulkan_vram_budget reads the GPU memory in use and the budget
266 // from it (the title HUD's VRAM figure). Without it that figure is not available.
267 bool memory_budget = false;
242 std::uint32_t max_draw_indirect_count = 1; 268 std::uint32_t max_draw_indirect_count = 1;
243}; 269};
244 270
@@ -276,6 +302,11 @@ HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIP
276 D3D12_GPU_VIRTUAL_ADDRESS console_address, std::uint64_t console_size, 302 D3D12_GPU_VIRTUAL_ADDRESS console_address, std::uint64_t console_size,
277 REFIID riid, void** out); 303 REFIID riid, void** out);
278 304
305// Calls `fn` on the device's fence-wait thread once `fence` (a fence of such a device) reaches `value` (at once on that
306// thread if it has). Released or device lost, `fn` still runs once: it must not use the fence then. False for a fence
307// of another kind. For the console fence's slot-12 mirror (d3d12_xs_device.cpp).
308bool fence_callback_at(ID3D12Fence* fence, std::uint64_t value, std::function<void()> fn);
309
279// The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain. 310// The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain.
280VkImage vulkan_image(ID3D12Resource* resource); 311VkImage vulkan_image(ID3D12Resource* resource);
281// Resolves the resource that a UAV clear writes. Xbox depth/stencil UAVs name one of two color images by T#. 312// Resolves the resource that a UAV clear writes. Xbox depth/stencil UAVs name one of two color images by T#.
@@ -284,6 +315,10 @@ leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t a
284VkBuffer vulkan_buffer(ID3D12Resource* resource); 315VkBuffer vulkan_buffer(ID3D12Resource* resource);
285// What a device from create_vulkan_device* was created with (enabled features included), or null. For tests. 316// What a device from create_vulkan_device* was created with (enabled features included), or null. For tests.
286const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device); 317const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device);
318// The GPU memory a device from create_vulkan_device* (or its Xbox-ABI proxy) uses and may use, from
319// VK_EXT_memory_budget, read now (src/vulkan_memory_budget.h). Not available without the extension or the device.
320// Any thread: the title HUD calls it from its own, at most once per refresh.
321leonida::VramBudget vulkan_vram_budget(ID3D12Device* device);
287// The device's pipeline workers (src/pipeline_workers.h) and what they have compiled; zeros without any. For tests. 322// The device's pipeline workers (src/pipeline_workers.h) and what they have compiled; zeros without any. For tests.
288leonida::PipelineWorkers::Stats pipeline_worker_stats(ID3D12Device* device); 323leonida::PipelineWorkers::Stats pipeline_worker_stats(ID3D12Device* device);
289// True when a slot-133 buffer is a shadow copied from the title's pages, false when they were imported. For tests. 324// True when a slot-133 buffer is a shadow copied from the title's pages, false when they were imported. For tests.
@@ -387,6 +422,38 @@ struct BindlessRoom {
387 std::uint32_t samplers = 0; 422 std::uint32_t samplers = 0;
388}; 423};
389BindlessRoom bindless_room(ID3D12Device* device); 424BindlessRoom bindless_room(ID3D12Device* device);
425
426// What a T# the title wrote itself into a console descriptor heap came to (bind_title_image).
427enum class TitleImage { known, bound, unknown, refused, not_tsharp };
428
429// Statistics on unbound T# descriptors refused during console descriptor heap binding.
430struct UnboundTsharpReasonStats {
431 std::size_t distinct_slots = 0;
432 std::uint64_t total_refusals = 0;
433};
434
435struct UnboundTsharpStats {
436 std::map<std::string, UnboundTsharpReasonStats> by_reason;
437 std::size_t total_distinct_slots = 0;
438 std::uint64_t total_refusals = 0;
439};
440
441// Returns statistics on unbound T# descriptor refusals across console descriptor heaps.
442UnboundTsharpStats unbound_tsharp_stats();
443// Resets unbound T# refusal statistics (for testing).
444void reset_unbound_tsharp_stats();
445// Records an unbound T# refusal (for testing).
446void note_refused_tsharp_for_test(std::uint64_t heap_va, std::size_t offset,
447 const std::array<std::uint32_t, 8>& words, const char* why);
448
449// Simulates console descriptor heap T# binding for a synthetic descriptor against registered resources.
450// Returns TitleImage::bound on success, TitleImage::refused on rule violation (with *why set to the refusal string),
451// or TitleImage::unknown / TitleImage::not_tsharp.
452TitleImage test_bind_title_image(ID3D12Device* device, const std::array<std::uint32_t, 8>& words,
453 const char** why = nullptr);
454
455// Returns the internal image address registered for a resource in the device's image table.
456std::uint64_t resource_image_address(ID3D12Resource* resource);
390// Gives each S# a sampler in that set and a key in its hash table, as CreateSampler does, without a heap slot: for 457// Gives each S# a sampler in that set and a key in its hash table, as CreateSampler does, without a heap slot: for
391// the literal S#s a shader builds from immediates (`literal_samplers` in the shader index). An S# that has them 458// the literal S#s a shader builds from immediates (`literal_samplers` in the shader index). An S# that has them
392// already is left as it is. E_INVALIDARG when `device` is not such a device; E_FAIL when one of them could not be 459// already is left as it is. E_INVALIDARG when `device` is not such a device; E_FAIL when one of them could not be
@@ -518,8 +585,16 @@ struct RootArgumentLayout {
518const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature); 585const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature);
519std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline); 586std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline);
520std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline); 587std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline);
588// Record time, for LEONIDA_ASYNC_PIPELINES=1: starts the pipeline's build on the compile worker before the list is
589// submitted, without waiting (PipelineState::queue_build). `id` is what compute_pipeline_id or graphics_pipeline_id gave (0:
590// nothing). Compute: at SetPipelineState; graphics: at each draw, with the render-target slots it binds (bit per slot)
591// and whether it binds a depth buffer.
592void request_pipeline_build(std::uintptr_t id, std::uint32_t bound_targets, bool depth_bound);
521// What each stage of a Vulkan device's PSO asked for (src/subgroup_size.h), in creation order; null for another PSO. 593// What each stage of a Vulkan device's PSO asked for (src/subgroup_size.h), in creation order; null for another PSO.
522const std::vector<leonida::SubgroupRequest>* pipeline_subgroup_requests(ID3D12PipelineState* pipeline); 594const std::vector<leonida::SubgroupRequest>* pipeline_subgroup_requests(ID3D12PipelineState* pipeline);
595// The linked SPIR-V stage modules for a lazy pipeline (in recipe stages order); false when not a lazy pipeline.
596bool pipeline_stage_words(ID3D12PipelineState* pipeline, std::vector<std::vector<std::uint32_t>>& words,
597 std::string& why);
523// PSOs of any Vulkan device not yet deleted, counting one whose deletion waits for its running build (tests). 598// PSOs of any Vulkan device not yet deleted, counting one whose deletion waits for its running build (tests).
524long live_pipeline_states(); 599long live_pipeline_states();
525 600
@@ -545,6 +620,8 @@ bool write_placed_texture_view(ID3D12Device* device, bool unordered, const std::
545// The VA shaders read a descriptor table at: for one inside a console descriptor heap (Xbox slot 14) whose arena copy 620// The VA shaders read a descriptor table at: for one inside a console descriptor heap (Xbox slot 14) whose arena copy
546// lies elsewhere, the matching VA in that copy; any other VA unchanged. 621// lies elsewhere, the matching VA in that copy; any other VA unchanged.
547D3D12_GPU_VIRTUAL_ADDRESS console_descriptor_table_va(D3D12_GPU_VIRTUAL_ADDRESS va); 622D3D12_GPU_VIRTUAL_ADDRESS console_descriptor_table_va(D3D12_GPU_VIRTUAL_ADDRESS va);
623// The console descriptor heap holding `va` (its console VA and bytes); false when none with a copy holds it.
624bool console_descriptor_heap_range(D3D12_GPU_VIRTUAL_ADDRESS va, std::uint64_t& console_va, std::uint64_t& bytes);
548 625
549// XDXR acceleration-structure commands (docs/d3d12_vulkan.md 4.8) of a list of `device`: every address the command 626// XDXR acceleration-structure commands (docs/d3d12_vulkan.md 4.8) of a list of `device`: every address the command
550// writes or reads, as the title named it, becomes the VA shaders reach that memory by (src/title_va_alias.h: a 627// writes or reads, as the title named it, becomes the VA shaders reach that memory by (src/title_va_alias.h: a
@@ -578,6 +655,14 @@ void set_global_realtime_privilege_override_for_test(int state);
578// not one of this module's command lists. 655// not one of this module's command lists.
579bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& back); 656bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& back);
580 657
658// Makes `list` hold a reference to `object` until its next Reset or its release, as it holds the pipeline states it
659// names: for an object only the recording uses, such as a shim's own scratch buffer. A list is Reset once it has
660// been executed (or a held batch, src/queue_holds.h, keeps it pinned until it has run), and a resource released
661// after its submission is destroyed through the device's deferred queue once that submission has retired, so the
662// object outlives every GPU use the recording makes of it. False when `list` is not one of this module's command
663// lists or `object` is null.
664bool hold_until_reset(ID3D12GraphicsCommandList* list, IUnknown* object);
665
581// A copy of the commands `list` has recorded so far, for tests of what a bundle puts into its parent. False when 666// A copy of the commands `list` has recorded so far, for tests of what a bundle puts into its parent. False when
582// `list` is not one of this module's command lists. 667// `list` is not one of this module's command lists.
583bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector<leonida::Command>& commands); 668bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector<leonida::Command>& commands);
diff --git a/runtime/shims/d3d12_compile_exit.h b/runtime/shims/d3d12_compile_exit.h
index 181049b8f..6c1172994 100644
--- a/runtime/shims/d3d12_compile_exit.h
+++ b/runtime/shims/d3d12_compile_exit.h
@@ -10,4 +10,11 @@ namespace rt::d3d12 {
10// False when one was still running at the deadline. Defined with the Vulkan device (d3d12_vulkan_device.cpp). 10// False when one was still running at the deadline. Defined with the Vulkan device (d3d12_vulkan_device.cpp).
11bool stop_pipeline_compiles(unsigned wait_ms); 11bool stop_pipeline_compiles(unsigned wait_ms);
12 12
13// Writes each live device's session pipeline cache (pipeline_cache.session.bin), as ~Device does, for a process that
14// ends with its devices alive: after stop_pipeline_compiles, so the compiler's own builds are done. A build still
15// running on another thread is given `wait_ms`, then the cache is written without it (the pipelines finished so far);
16// the write itself is given 3 s before the process goes on ending. Runs once per process; true when a cache write
17// finished.
18bool save_pipeline_caches_at_exit(unsigned wait_ms);
19
13} // namespace rt::d3d12 20} // namespace rt::d3d12
diff --git a/runtime/shims/d3d12_compile_helper.h b/runtime/shims/d3d12_compile_helper.h
new file mode 100644
index 000000000..59c6f4d7b
--- /dev/null
+++ b/runtime/shims/d3d12_compile_helper.h
@@ -0,0 +1,443 @@
1// Out-of-process compute pipeline compiles: the compile helper (gta6rt --compile-server).
2//
3// A first build of a large compute module keeps the driver busy for tens of seconds to minutes, and on NVIDIA 630.20 a
4// vkQueueSubmit of the same process waits for the lock that build holds (the compile gate makes it wait in our code
5// instead, which still stops the title's frames). The driver's locks are per process. So with LEONIDA_COMPILE_HELPER=1
6// a build whose pipeline is in no journal file asks a helper process to make that file, and creates the pipeline from
7// it once it is there: a cache hit of a few milliseconds. With asynchronous builds (LEONIDA_ASYNC_PIPELINES=1, the
8// intended mode) nothing waits: the dispatch is skipped until the file is there. Without them a warm-up still only
9// asks (so the helper's threads work ahead), and a dispatch waits for the file, holding nothing of the driver's.
10//
11// The helper is the same executable with the same environment, so it creates the same device and computes the same
12// journal name; the file it writes is the one the game then reads. The protocol is files beside the journal:
13//
14// <journal>/requests/<stem>.req asked: "<library entry name>\t<priority>" (0: a dispatch waits for it; a
15// warm-up asks with its module size), written whole
16// <journal>/requests/<stem>.failed the helper could not: why, one line
17// <journal>/requests/<stem>.building a lock file a process holds for the whole build (ownership is the open handle,
18// which the OS closes when the process ends, killed or not; its contents name
19// the process): precompile and helper runs skip an entry its holder is building
20// <journal>/<stem>.bin done: the journal file itself
21//
22// The game starts the helper at its device's first pipeline (`--compile-server --parent <pid>`), and the helper ends
23// with the game. With nothing asked it fills the rest of the library at idle priority. A request whose
24// file appears another way (a precompile run) is answered the same way, so nothing has to agree on who builds what.
25#pragma once
26
27#include <windows.h>
28
29#include <algorithm>
30#include <atomic>
31#include <chrono>
32#include <cstdint>
33#include <cstdio>
34#include <cstdlib>
35#include <cstring>
36#include <filesystem>
37#include <fstream>
38#include <map>
39#include <mutex>
40#include <set>
41#include <string>
42#include <system_error>
43#include <thread>
44#include <vector>
45
46#include "../src/cached_pso.h"
47#include "../src/pipeline_cache_journal.h"
48
49namespace rt::d3d12::compile_helper {
50
51inline std::filesystem::path requests_dir(const std::filesystem::path& journal_dir) { return journal_dir / "requests"; }
52
53inline std::filesystem::path sidecar(const std::filesystem::path& journal_file, const char* extension) {
54 return requests_dir(journal_file.parent_path()) / (journal_file.stem().string() + extension);
55}
56inline std::filesystem::path request_path(const std::filesystem::path& journal_file) {
57 return sidecar(journal_file, ".req");
58}
59inline std::filesystem::path failed_path(const std::filesystem::path& journal_file) {
60 return sidecar(journal_file, ".failed");
61}
62inline std::filesystem::path building_path(const std::filesystem::path& journal_file) {
63 return sidecar(journal_file, ".building");
64}
65
66// Whether another process (or thread) holds the entry's lock file: a build of it is running now. An open that asks to
67// read conflicts with the holder's share mode 0; a leftover no one holds opens and is closed again at once.
68inline bool building_held(const std::filesystem::path& journal_file) {
69 const std::filesystem::path marker = building_path(journal_file);
70 const HANDLE file = CreateFileW(marker.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
71 nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
72 if (file != INVALID_HANDLE_VALUE) {
73 CloseHandle(file);
74 return false;
75 }
76 return GetLastError() == ERROR_SHARING_VIOLATION;
77}
78
79inline std::string read_line(const std::filesystem::path& path) {
80 std::ifstream file(path, std::ios::binary);
81 std::string line;
82 std::getline(file, line);
83 while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) line.pop_back();
84 return line;
85}
86
87inline std::error_code write_line(const std::filesystem::path& path, const std::string& text) {
88 const std::string line = text + "\n";
89 return leonida::pipeline_journal::write_entry(path, line.data(), line.size());
90}
91
92// A request's line: "<name>\t<priority>"; a bare name (an older writer) is priority 0.
93struct RequestLine {
94 std::string name;
95 std::uint64_t priority = 0;
96};
97inline RequestLine parse_request(const std::string& line) {
98 RequestLine out;
99 const auto tab = line.rfind('\t');
100 if (tab == std::string::npos) {
101 out.name = line;
102 return out;
103 }
104 out.name = line.substr(0, tab);
105 out.priority = std::strtoull(line.c_str() + tab + 1, nullptr, 10);
106 return out;
107}
108inline std::string format_request(const std::string& name, std::uint64_t priority) {
109 return name + "\t" + std::to_string(priority);
110}
111
112// This process builds for others (--compile-server, --precompile-pipelines): it never asks a helper or starts one,
113// and its device keeps no session cache.
114inline std::atomic<bool> build_host{false};
115
116// LEONIDA_COMPILE_HELPER=1: modules of at least LEONIDA_COMPILE_HELPER_MIN_BYTES of SPIR-V (default 128 KiB).
117inline std::size_t min_bytes() {
118 static const std::size_t bytes = [] {
119 char text[32]{};
120 const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPILE_HELPER", text, sizeof(text));
121 if (!(n == 1 && text[0] == '1')) return SIZE_MAX;
122 const DWORD m = GetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_MIN_BYTES", text, sizeof(text));
123 const unsigned long long v = (m > 0 && m < sizeof(text)) ? std::strtoull(text, nullptr, 10) : 0;
124 return v ? static_cast<std::size_t>(v) : std::size_t{128} << 10;
125 }();
126 return bytes;
127}
128inline bool enabled() { return min_bytes() != SIZE_MAX && !build_host.load(); }
129inline bool wanted(std::size_t spirv_bytes) { return enabled() && spirv_bytes >= min_bytes(); }
130
131// LOCAL FIX (compile helper: a killed helper's marker outlived a reused process id): the marker is a lock file, not a
132// note naming its owner. It is created with no sharing and DELETE_ON_CLOSE, and the handle is held for the whole build:
133// the OS closes it when the process ends, even on TerminateProcess, so a marker no process holds is one to take over
134// and a leftover can never block a later run that happens to be given the same process id. The stems this process
135// holds are kept here instead, which is what "another thread of this process has it" means.
136inline std::mutex& markers_mutex() {
137 static std::mutex mutex;
138 return mutex;
139}
140inline std::map<std::string, HANDLE>& held_markers() { // stem -> the handle that keeps its lock file
141 static std::map<std::string, HANDLE> handles;
142 return handles;
143}
144
145// Claims the entry for this process's build: false when this process or another one holds its lock file.
146inline bool mark_building(const std::filesystem::path& journal_file) {
147 const auto marker = building_path(journal_file);
148 const std::string stem = journal_file.stem().string();
149 std::error_code ec;
150 std::filesystem::create_directories(marker.parent_path(), ec);
151 {
152 std::lock_guard lock(markers_mutex());
153 if (held_markers().count(stem)) return false; // another thread of this process is building it
154 }
155 // CREATE_NEW cannot say whether an existing file is held, so a create that finds it is followed by an open with
156 // no sharing: that succeeds on a leftover and fails with ERROR_SHARING_VIOLATION on a live build.
157 for (int attempt = 0; attempt < 2; ++attempt) {
158 HANDLE file = CreateFileW(marker.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW,
159 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, nullptr);
160 if (file == INVALID_HANDLE_VALUE) {
161 if (GetLastError() != ERROR_FILE_EXISTS) return true; // no marker can be kept: build anyway
162 file = CreateFileW(marker.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING,
163 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, nullptr);
164 if (file == INVALID_HANDLE_VALUE) {
165 if (GetLastError() == ERROR_SHARING_VIOLATION) return false; // a live build has it
166 continue; // it went away between the two calls: try the create once more
167 }
168 }
169 // Its contents are for a human reading the folder; nothing here reads them.
170 const std::string pid = std::to_string(GetCurrentProcessId()) + "\n";
171 DWORD written = 0;
172 WriteFile(file, pid.data(), DWORD(pid.size()), &written, nullptr);
173 std::lock_guard lock(markers_mutex());
174 held_markers()[stem] = file;
175 return true;
176 }
177 return true; // a marker that cannot be opened at all: build anyway
178}
179
180// Drops the claim: closing the handle removes the lock file (DELETE_ON_CLOSE).
181inline void unmark_building(const std::filesystem::path& journal_file) {
182 HANDLE handle = INVALID_HANDLE_VALUE;
183 {
184 std::lock_guard lock(markers_mutex());
185 auto& handles = held_markers();
186 const auto it = handles.find(journal_file.stem().string());
187 if (it == handles.end()) return;
188 handle = it->second;
189 handles.erase(it);
190 }
191 CloseHandle(handle);
192}
193
194// The game's side: one helper per process, started at the first request.
195class Client {
196public:
197 enum class State { ready, pending, failed, gone };
198
199 static Client& instance() {
200 static auto* client = new Client; // never destroyed: builds may still be asking at exit
201 return *client;
202 }
203
204 // Asks for `journal_file` (the entry `name`) at `priority` without waiting; true when asked (or already there).
205 // A request is written again only for a more urgent priority.
206 bool request(const std::filesystem::path& journal_file, const std::string& name, std::uint64_t priority,
207 const leonida::cached_pso::Identity& identity, std::string* why) {
208 if (leonida::pipeline_journal::entry_usable(journal_file, identity)) return true;
209 if (!start(why)) return false;
210 const std::string stem = journal_file.stem().string();
211 bool fresh = false;
212 {
213 std::lock_guard lock(mutex_);
214 const auto it = asked_.find(stem);
215 if (it != asked_.end() && it->second <= priority) return true;
216 fresh = it == asked_.end();
217 asked_[stem] = priority;
218 }
219 // LOCAL FIX (compile helper: a failure of a request this session already wrote): only a fresh request drops an
220 // older failure, so asking again can retry. Bumping the priority of a request keeps it, since .failed is the
221 // answer to that same request and dropping it would put the caller back to waiting for a file nobody builds.
222 if (fresh) {
223 std::error_code ec;
224 std::filesystem::remove(failed_path(journal_file), ec); // an older failure: ask again
225 }
226 if (const std::error_code error = write_line(request_path(journal_file), format_request(name, priority))) {
227 if (why) *why = "could not write the request: " + error.message();
228 std::lock_guard lock(mutex_);
229 asked_.erase(stem);
230 return false;
231 }
232 return true;
233 }
234
235 // Where a request stands: its file is there, the helper gave up (*why), the helper is gone, or still pending.
236 State state(const std::filesystem::path& journal_file, const leonida::cached_pso::Identity& identity,
237 std::string* why) {
238 if (leonida::pipeline_journal::entry_usable(journal_file, identity)) return State::ready;
239 std::error_code ec;
240 const auto failed = failed_path(journal_file);
241 if (std::filesystem::exists(failed, ec)) {
242 if (why) *why = "the helper could not build it: " + read_line(failed);
243 forget(journal_file);
244 return State::failed;
245 }
246 const std::string stem = journal_file.stem().string();
247 std::lock_guard lock(mutex_);
248 if (!process_ || WaitForSingleObject(process_, 0) == WAIT_OBJECT_0) {
249 drop(stem);
250 if (why) *why = "the helper exited";
251 return State::gone;
252 }
253 // The helper takes .req away when it starts a build and holds the .building lock file until the journal file
254 // is written: an entry being built is pending however long the build takes (the title's big programs take
255 // minutes), and that time does not count against the pending bound below.
256 const auto now = std::chrono::steady_clock::now();
257 if (building_held(journal_file)) {
258 pending_since_[stem] = now;
259 return State::pending;
260 }
261 // LOCAL FIX (compile helper: nothing bounded pending): the helper removes .req before it writes .failed and
262 // before the build that writes the journal file, so a request of ours that is neither listed nor being built
263 // has been answered another way or lost. Waiting would last as long as the helper lives, so answer failed here
264 // and the game builds the pipeline itself. (The journal file is checked once more: the build may have ended
265 // between the first check and the lock file's.)
266 if (!std::filesystem::exists(request_path(journal_file), ec)) {
267 if (leonida::pipeline_journal::entry_usable(journal_file, identity)) {
268 drop(stem);
269 return State::ready;
270 }
271 drop(stem);
272 if (why) *why = "its request is gone and its journal file is not usable";
273 return State::failed;
274 }
275 // The helper is alive but may never build it (a module it cannot, a request it lost): the same bound as a
276 // failed request, so a skipped dispatch becomes a build here rather than a title that never dispatches.
277 const auto first = pending_since_.emplace(stem, now).first;
278 const unsigned long long limit = pending_ms();
279 if (limit && now - first->second >= std::chrono::milliseconds(limit)) {
280 drop(stem);
281 if (why) *why = "the helper did not build it within " + std::to_string(limit) + " ms";
282 return State::failed;
283 }
284 return State::pending;
285 }
286
287 // Starts the helper now, so its device is up before the title's load needs it: made while the title fills video
288 // memory, the helper's device took 110 s in one boot. Called at the device's first pipeline.
289 void prestart() {
290 std::string why;
291 if (!start(&why)) std::fprintf(stderr, "[rt] d3d12: compile helper: %s\n", why.c_str());
292 }
293
294 // Asks and waits until the file is usable, the helper gives up or is gone, or LEONIDA_COMPILE_HELPER_WAIT_MS
295 // passes (default 120 s; 0: no limit). True when the file is there.
296 bool build(const std::filesystem::path& journal_file, const std::string& name,
297 const leonida::cached_pso::Identity& identity, std::string* why) {
298 if (!request(journal_file, name, 0, identity, why)) return false;
299 auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(wait_ms());
300 for (;;) {
301 switch (state(journal_file, identity, why)) {
302 case State::ready: return true;
303 case State::failed:
304 case State::gone: return false;
305 case State::pending: break;
306 }
307 // A build in progress is waited for to its end: giving up would only start the same build here.
308 if (building_held(journal_file))
309 deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(wait_ms());
310 if (wait_ms() && std::chrono::steady_clock::now() >= deadline) {
311 if (why) *why = "timed out waiting for the helper";
312 return false;
313 }
314 std::this_thread::sleep_for(std::chrono::milliseconds(50));
315 }
316 }
317
318 // The helper is running for a test: state() and request() then answer for it without starting one (the test's own
319 // process handle stays alive, so the helper reads as running).
320 void pretend_helper_running_for_test() {
321 std::lock_guard lock(mutex_);
322 process_ = GetCurrentProcess();
323 tried_ = true;
324 }
325
326private:
327 // Under mutex_ (or before it is taken): this process's bookkeeping for a request that is answered.
328 void drop(const std::string& stem) {
329 asked_.erase(stem);
330 pending_since_.erase(stem);
331 }
332
333 void forget(const std::filesystem::path& journal_file) {
334 std::lock_guard lock(mutex_);
335 drop(journal_file.stem().string());
336 }
337
338 // How long a dispatch waits for the helper's file: LEONIDA_COMPILE_HELPER_WAIT_MS, default 120 s so a helper that
339 // cannot build a module never holds a dispatch for the whole boot; 0 keeps the old no-limit wait.
340 static unsigned long long wait_ms() {
341 static const unsigned long long ms = [] {
342 char text[32]{};
343 const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_WAIT_MS", text, sizeof(text));
344 if (n == 0 || n >= sizeof(text)) return 120000ull;
345 return std::strtoull(text, nullptr, 10);
346 }();
347 return ms;
348 }
349
350 // How long a pending request may stay pending with the helper alive (LEONIDA_COMPILE_HELPER_PENDING_MS, default
351 // 120 s; 0: no limit). Read on each call so a test can set a short one.
352 static unsigned long long pending_ms() {
353 char text[32]{};
354 const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", text, sizeof(text));
355 if (n == 0 || n >= sizeof(text)) return 120000ull;
356 return std::strtoull(text, nullptr, 10);
357 }
358
359 // The helper's process handle, started once; null (and *why) when it could not be or has exited.
360 HANDLE start(std::string* why) {
361 std::lock_guard lock(mutex_);
362 if (process_ && WaitForSingleObject(process_, 0) != WAIT_OBJECT_0) return process_;
363 if (tried_) {
364 if (why) *why = process_ ? "the helper exited" : "the helper could not be started";
365 return nullptr;
366 }
367 tried_ = true;
368 std::wstring exe(32768, L'\0');
369 const DWORD length = GetModuleFileNameW(nullptr, exe.data(), DWORD(exe.size()));
370 if (!length || length >= exe.size()) {
371 if (why) *why = "no executable path";
372 return nullptr;
373 }
374 exe.resize(length);
375 // LEONIDA_COMPILE_HELPER_THREADS (default 2): requests built at once, ~3.5 GB of host memory each for a module
376 // over 3 MB. LEONIDA_COMPILE_HELPER_IDLE_THREADS (default 1, at most THREADS - 1 so one is always free for a
377 // request): of those, how many fill the rest of the library at idle priority when nothing is asked.
378 const auto number = [](const char* variable, unsigned fallback) {
379 char text[16]{};
380 const DWORD n = GetEnvironmentVariableA(variable, text, sizeof(text));
381 return (n > 0 && n < sizeof(text)) ? unsigned(std::strtoul(text, nullptr, 10)) : fallback;
382 };
383 const unsigned threads = (std::max)(1u, number("LEONIDA_COMPILE_HELPER_THREADS", 2));
384 const unsigned idle = number("LEONIDA_COMPILE_HELPER_IDLE_THREADS", 1);
385 std::wstring command = L"\"" + exe + L"\" --compile-server --parent " + std::to_wstring(GetCurrentProcessId()) +
386 L" --threads " + std::to_wstring(threads) + L" --idle-threads " + std::to_wstring(idle);
387 STARTUPINFOW startup{sizeof(startup)};
388 startup.dwFlags = STARTF_USESTDHANDLES; // its log lines go where the game's do
389 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
390 startup.hStdOutput = GetStdHandle(STD_ERROR_HANDLE);
391 startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
392 PROCESS_INFORMATION info{};
393 // Normal priority: its requests are what the title's skipped dispatches wait for (at below normal a busy title
394 // starved its start for minutes). Only its library filling runs at idle priority.
395 if (!CreateProcessW(exe.c_str(), command.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW, nullptr, nullptr,
396 &startup, &info)) {
397 if (why) *why = "CreateProcess failed (" + std::to_string(GetLastError()) + ")";
398 return nullptr;
399 }
400 CloseHandle(info.hThread);
401 process_ = info.hProcess;
402 std::fprintf(stderr, "[rt] d3d12: compile helper started (process %lu, %u thread(s), %u filling the library "
403 "when idle)\n", info.dwProcessId, threads, idle);
404 return process_;
405 }
406
407 std::mutex mutex_;
408 HANDLE process_ = nullptr;
409 bool tried_ = false;
410 std::map<std::string, std::uint64_t> asked_; // stem -> priority of the request written
411 std::map<std::string, std::chrono::steady_clock::time_point> pending_since_; // stem -> first seen pending
412};
413
414// One pending request, as the helper lists them.
415struct Request {
416 std::string stem; // the journal file's stem: cs-<16 hex digits>
417 std::string name; // the library entry
418 std::uint64_t priority = 0;
419 std::filesystem::file_time_type asked{};
420};
421
422// The requests in `dir`, most urgent first (priority, then age).
423inline std::vector<Request> list_requests(const std::filesystem::path& dir) {
424 std::vector<Request> out;
425 std::error_code ec;
426 for (std::filesystem::directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec)) {
427 if (it->path().extension() != ".req") continue;
428 std::error_code stat;
429 const auto asked = it->last_write_time(stat);
430 if (stat) continue;
431 RequestLine line = parse_request(read_line(it->path()));
432 if (line.name.empty()) continue;
433 out.push_back({it->path().stem().string(), std::move(line.name), line.priority, asked});
434 }
435 std::sort(out.begin(), out.end(), [](const Request& a, const Request& b) {
436 // The priority first, then the oldest: a stale request left by a killed session (a warm-up, so a high
437 // priority) cannot get ahead of this session's dispatches, which ask at 0 (LOCAL FIX, review).
438 return a.priority != b.priority ? a.priority < b.priority : a.asked < b.asked;
439 });
440 return out;
441}
442
443} // namespace rt::d3d12::compile_helper
diff --git a/runtime/shims/d3d12_compute_input_probe.h b/runtime/shims/d3d12_compute_input_probe.h
index 34042ebc1..70ac61e52 100644
--- a/runtime/shims/d3d12_compute_input_probe.h
+++ b/runtime/shims/d3d12_compute_input_probe.h
@@ -7,6 +7,7 @@
7#include "xmem.h" 7#include "xmem.h"
8#include <windows.h> 8#include <windows.h>
9#include <algorithm> 9#include <algorithm>
10#include <atomic>
10#include <array> 11#include <array>
11#include <charconv> 12#include <charconv>
12#include <cstdio> 13#include <cstdio>
@@ -251,11 +252,12 @@ void recheck(State& state) {
251 if (heap->copy) scan("console", heap->shader_va, heap->copy, heap->bytes); 252 if (heap->copy) scan("console", heap->shader_va, heap->copy, heap->bytes);
252 } 253 }
253 { 254 {
254 std::unique_lock lock(state.cbv_heap_mutex, std::try_to_lock); 255 std::unique_lock lock(state.visible_heap_mutex, std::try_to_lock);
255 if (!lock.owns_lock()) std::fputs("[rt] compute-input: after loss, arena heaps locked\n", stderr); 256 if (!lock.owns_lock()) std::fputs("[rt] compute-input: after loss, arena heaps locked\n", stderr);
256 else 257 else
257 for (const auto& [offset, end] : state.cbv_heaps) 258 for (const auto& [offset, heap] : state.visible_heaps)
258 if (end <= state.arena.size) scan("arena", offset, state.arena.mapped + offset, end - offset); 259 if (heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && heap.end <= state.arena.size)
260 scan("arena", offset, state.arena.mapped + offset, heap.end - offset);
259 } 261 }
260} 262}
261 263
@@ -526,6 +528,14 @@ void inspect(State& state, std::span<const leonida::CommandList* const> lists, s
526 if (!d && (!ind || ind->kind != leonida::IndirectKind::dispatch)) continue; 528 if (!d && (!ind || ind->kind != leonida::IndirectKind::dispatch)) continue;
527 const char* name = state.context->diagnostic_compute_name(d ? d->pipeline : ind->pipeline); 529 const char* name = state.context->diagnostic_compute_name(d ? d->pipeline : ind->pipeline);
528 if (!matches(name)) continue; 530 if (!matches(name)) continue;
531 // LEONIDA_COMPUTE_INPUT_LIMIT=<n>: the first n matching dispatches in full, then one in 1,000 (a culling
532 // program runs several times a submission; 0 or unset: every one, as before).
533 static const unsigned limit = [] {
534 const char* v = std::getenv("LEONIDA_COMPUTE_INPUT_LIMIT");
535 return v ? unsigned(std::strtoul(v, nullptr, 10)) : 0u;
536 }();
537 static std::atomic<unsigned> matched{0};
538 if (const unsigned n = ++matched; limit && n > limit && n % 1000) continue;
529 const auto& roots = d ? d->user_data : ind->user_data; 539 const auto& roots = d ? d->user_data : ind->user_data;
530 std::fprintf(stderr, "[rt] compute-input: execute=%llu list=%zu cmd=%zu queue=%s name=%s pso=%p %s groups=%u,%u,%u " 540 std::fprintf(stderr, "[rt] compute-input: execute=%llu list=%zu cmd=%zu queue=%s name=%s pso=%p %s groups=%u,%u,%u "
531 "heap-base=0x%llx roots=[%s]\n", (unsigned long long)seq, l, i, queue, name, reinterpret_cast<void*>(d ? d->pipeline : ind->pipeline), 541 "heap-base=0x%llx roots=[%s]\n", (unsigned long long)seq, l, i, queue, name, reinterpret_cast<void*>(d ? d->pipeline : ind->pipeline),
diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h
index a9299d38c..feb4ff52e 100644
--- a/runtime/shims/d3d12_geometry_views.h
+++ b/runtime/shims/d3d12_geometry_views.h
@@ -2,30 +2,41 @@
2 2
3#include "d3d12_title_buffer_windows.h" 3#include "d3d12_title_buffer_windows.h"
4#include "../src/title_geometry_watch.h" 4#include "../src/title_geometry_watch.h"
5#include <atomic>
5#include <chrono> 6#include <chrono>
7#include <cstring>
6#include <map> 8#include <map>
7#include <mutex> 9#include <mutex>
8#include <set> 10#include <set>
9#include <shared_mutex> 11#include <shared_mutex>
10#include <cstring>
11#include <unordered_map> 12#include <unordered_map>
13#include <utility>
14#include <vector>
12 15
13namespace rt::d3d12 { 16namespace rt::d3d12 {
14 17
15// One persistent device-local copy for each geometry extent. The console heap retains its original indices. 18// One persistent device-local copy for each geometry extent. The console heap retains its original indices.
16// Every CPU mapping of a source tile is watched; a physical remap changes which aliases must be watched. 19// Every CPU mapping of a source tile is watched; a physical remap changes which aliases must be watched.
20// Views whose title range is released are retired immediately and their backing storage is reclaimed once
21// in-flight GPU submissions up to their retire ticket have completed; previously cap-refused ranges retry
22// once budget has been freed.
17enum class GeometryCopy { copied, unreadable, interrupted }; 23enum class GeometryCopy { copied, unreadable, interrupted };
18 24
19class GeometryViews { 25class GeometryViews {
20 using Address = std::uintptr_t; 26 using Address = std::uintptr_t;
27 using Key = std::pair<Address, std::size_t>;
21 static constexpr auto tile_size = leonida::geometry_writes::tile_size; 28 static constexpr auto tile_size = leonida::geometry_writes::tile_size;
22 using Cell = leonida::geometry_writes::Cell; 29 using Cell = leonida::geometry_writes::Cell;
30 struct NoopRetire {
31 void operator()(Address, std::size_t, VkDeviceSize) const noexcept {}
32 };
23 struct View { 33 struct View {
24 Address source; 34 Address source{};
25 std::size_t size; 35 std::size_t size{};
26 std::uint8_t* dst; 36 std::uint8_t* dst{};
27 VkDeviceSize va; 37 VkDeviceSize va{};
28 bool ready{}, zeroed{}; 38 VkDeviceAddress bda{};
39 bool ready{}, zeroed{}, alive{};
29 }; 40 };
30 struct Tile { 41 struct Tile {
31 Cell* primary{}; 42 Cell* primary{};
@@ -34,49 +45,88 @@ class GeometryViews {
34 std::vector<std::size_t> views; 45 std::vector<std::size_t> views;
35 bool retry = false; 46 bool retry = false;
36 }; 47 };
48 struct FastEntry {
49 VkDeviceSize va{};
50 std::uint64_t refused_at{}; // free_generation_ when refused (only meaningful when va == 0)
51 };
52 struct Retired {
53 VkDeviceSize va{};
54 std::size_t size{};
55 std::uint64_t ticket{}; // kAfterExecutes until execute_end() stamps it
56 std::uint64_t epoch{}; // the last execute begun when it was retired (kAfterExecutes only)
57 };
58 std::uint64_t cap_override_{};
37 mutable std::mutex mutex_; 59 mutable std::mutex mutex_;
38 std::mutex refresh_mutex_; // refresh() only, held for its whole run, before mutex_ 60 std::mutex refresh_mutex_; // refresh() only, held for its whole run, before mutex_
39 TitleBufferWindows pool_; 61 TitleBufferWindows pool_;
40 std::map<std::pair<Address, std::size_t>, std::size_t> keys_; 62 std::map<Key, std::size_t> keys_; // live views only
41 // What resolve() and find() answer for a key already in keys_ (0 when refused), readable without mutex_: refresh() 63 // What resolve() and find() answer for a key already seen (va == 0 when refused), readable without mutex_:
42 // holds mutex_ for its whole pass over the watched tiles (up to tens of milliseconds a submission), and the title's 64 // refresh() holds mutex_ for its whole pass over the watched tiles (up to tens of milliseconds a submission),
43 // Subrender workers resolve their root views while they record (SetGraphicsRoot*View), so they waited for it 65 // and the title's Subrender workers resolve their root views while they record (SetGraphicsRoot*View), so they
44 // (speed-26). Written under mutex_ and then fast_mutex_ (in that order), read under fast_mutex_ alone. 66 // waited for it (speed-26). Written under mutex_ and then fast_mutex_ (in that order), read under fast_mutex_
67 // alone. A refused entry records free_generation_ at refusal so resolve() short-circuits while nothing has been
68 // freed and retries automatically after reap() returns budget.
45 struct KeyHash { 69 struct KeyHash {
46 std::size_t operator()(const std::pair<Address, std::size_t>& k) const { 70 std::size_t operator()(const Key& k) const {
47 return std::hash<std::uint64_t>{}(std::uint64_t(k.first) * 0x9E3779B97F4A7C15ull ^ k.second); 71 return std::hash<std::uint64_t>{}(std::uint64_t(k.first) * 0x9E3779B97F4A7C15ull ^ k.second);
48 } 72 }
49 }; 73 };
50 // keys_, views_ (the vector itself, and each view's source, size, dst and va) and by_address_ change only in 74 std::map<Key, std::uint64_t> refused_; // key -> free_generation_ at refusal (under mutex_)
51 // resolve(), under mutex_ and then structure_mutex_ exclusively. lookup() and find() read them under 75 std::size_t max_view_bytes_{}; // largest size of any view ever created (under mutex_)
76 std::size_t max_refused_bytes_{}; // largest size of any refused key (under mutex_)
77 // keys_, views_ (the vector itself, and each live view's source, size, dst, va, bda and alive) and by_address_
78 // change only under mutex_ and then structure_mutex_ exclusively. lookup() and find() read them under
52 // structure_mutex_ shared, so they do not wait for a refresh() in progress (which holds mutex_ and changes only a 79 // structure_mutex_ shared, so they do not wait for a refresh() in progress (which holds mutex_ and changes only a
53 // view's ready/zeroed flags and its bytes), on the submit thread's heaps refresh among others. 80 // view's ready/zeroed flags and its bytes), on the submit thread's heaps refresh among others.
54 mutable std::shared_mutex structure_mutex_; 81 mutable std::shared_mutex structure_mutex_;
55 mutable std::shared_mutex fast_mutex_; 82 mutable std::shared_mutex fast_mutex_;
56 std::unordered_map<std::pair<Address, std::size_t>, VkDeviceSize, KeyHash> fast_; 83 std::unordered_map<Key, FastEntry, KeyHash> fast_;
57 void publish(const std::pair<Address, std::size_t>& key, VkDeviceSize va) { // mutex_ held 84 void publish(const Key& key, VkDeviceSize va, std::uint64_t refused_at = 0) { // mutex_ held
58 std::unique_lock lock(fast_mutex_); 85 std::unique_lock lock(fast_mutex_);
59 fast_[key] = va; 86 fast_[key] = {va, refused_at};
87 }
88 bool fast_find(const Key& key, VkDeviceSize& va) const {
89 std::shared_lock lock(fast_mutex_);
90 const auto it = fast_.find(key);
91 if (it == fast_.end()) return false;
92 va = it->second.va;
93 return true;
60 } 94 }
61 bool fast_find(const std::pair<Address, std::size_t>& key, VkDeviceSize& va) const { 95 bool fast_find_resolve(const Key& key, VkDeviceSize& va) const {
62 std::shared_lock lock(fast_mutex_); 96 std::shared_lock lock(fast_mutex_);
63 const auto it = fast_.find(key); 97 const auto it = fast_.find(key);
64 if (it == fast_.end()) return false; 98 if (it == fast_.end()) return false;
65 va = it->second; 99 if (it->second.va == 0 && it->second.refused_at != free_generation_.load(std::memory_order_acquire))
100 return false;
101 va = it->second.va;
66 return true; 102 return true;
67 } 103 }
68 std::vector<View> views_; 104 std::vector<View> views_;
105 std::vector<std::size_t> free_ids_;
106 std::size_t live_views_{};
107 bool refreshing_{};
69 std::map<VkDeviceAddress, std::size_t> by_address_; 108 std::map<VkDeviceAddress, std::size_t> by_address_;
70 std::map<Address, Tile> tiles_; 109 std::map<Address, Tile> tiles_;
71 static constexpr auto refused = SIZE_MAX; 110 std::vector<Retired> retired_;
111 std::atomic<std::size_t> retired_count_{0};
112 // The ExecuteCommandLists replays in progress (execute_begin/execute_end), by the serial each began with. A view
113 // retired at kAfterExecutes may be named by any of them: by a list recorded before the retirement, or by a console
114 // heap slot their before_execute_ translated. It gets its retire ticket only once all of them have recorded their
115 // submissions, so a ticket read then covers them, however many tickets a replay records and on whichever queue.
116 std::mutex execute_mutex_; // a leaf lock
117 std::uint64_t execute_serial_{};
118 std::vector<std::uint64_t> executing_;
119 std::atomic<bool> unstamped_{false};
120 leonida::geometry_writes::ReleaseQueue releases_;
121 std::atomic<std::uint64_t> free_generation_{0};
72 std::uint64_t serial_{}, bytes_{}, cap_refusals_{}, allocation_failures_{}, ready_{}, uploads_{}, uploaded_{}; 122 std::uint64_t serial_{}, bytes_{}, cap_refusals_{}, allocation_failures_{}, ready_{}, uploads_{}, uploaded_{};
73 std::uint64_t submissions_{}, dirty_refreshes_{}, refilled_{}, tile_fills_{}; 123 std::uint64_t submissions_{}, dirty_refreshes_{}, refilled_{}, tile_fills_{};
124 std::uint64_t evicted_{}, reaped_{}, retries_succeeded_{};
74 std::unordered_map<Address, std::size_t> tile_reads_; // refresh(): offset in tile_scratch_, SIZE_MAX unreadable 125 std::unordered_map<Address, std::size_t> tile_reads_; // refresh(): offset in tile_scratch_, SIZE_MAX unreadable
75 // refresh() scratch: per view, whether it waits on a tile (pinned), is filled whole, was touched, was counted; 126 // refresh() scratch: per view, whether it waits on a tile (pinned), is filled whole, was touched, was counted;
76 // and the tiles found written, in address order. 127 // and the tiles found written, in address order.
77 enum : std::uint8_t { kPinned = 1, kWhole = 2, kTouched = 4, kCounted = 8 }; 128 enum : std::uint8_t { kPinned = 1, kWhole = 2, kTouched = 4, kCounted = 8 };
78 std::vector<std::uint8_t> marks_; 129 std::vector<std::uint8_t> marks_;
79 std::vector<const Tile*> written_;
80 std::vector<Address> written_vas_; 130 std::vector<Address> written_vas_;
81 std::vector<std::uint8_t> tile_scratch_; 131 std::vector<std::uint8_t> tile_scratch_;
82 std::chrono::steady_clock::duration refresh_time_{}; 132 std::chrono::steady_clock::duration refresh_time_{};
@@ -88,6 +138,19 @@ class GeometryViews {
88 std::uint64_t cleared_{}; 138 std::uint64_t cleared_{};
89 bool retry_{}; 139 bool retry_{};
90 140
141 void detach_tiles_locked(std::size_t id, Address source, std::size_t size) { // mutex_ held
142 for (auto p = source & ~(tile_size - 1); p < source + size; p += tile_size) {
143 const auto it = tiles_.find(p);
144 if (it == tiles_.end()) continue;
145 std::erase(it->second.views, id);
146 if (it->second.views.empty()) {
147 for (auto [peer, cell] : it->second.peers) leonida::geometry_writes::release(peer);
148 if (it->second.primary) leonida::geometry_writes::release(p);
149 tiles_.erase(it);
150 }
151 }
152 }
153
91 bool update(Address va, Tile& t) { 154 bool update(Address va, Tile& t) {
92 namespace watch = leonida::geometry_writes; 155 namespace watch = leonida::geometry_writes;
93 if (!t.primary) t.primary = watch::acquire(va); 156 if (!t.primary) t.primary = watch::acquire(va);
@@ -149,6 +212,15 @@ class GeometryViews {
149 } 212 }
150 213
151public: 214public:
215 explicit GeometryViews(std::uint64_t cap_override = 0) : cap_override_(cap_override) {
216 leonida::geometry_writes::subscribe(releases_);
217 }
218 ~GeometryViews() { leonida::geometry_writes::unsubscribe(releases_); }
219 GeometryViews(const GeometryViews&) = delete;
220 GeometryViews& operator=(const GeometryViews&) = delete;
221 GeometryViews(GeometryViews&&) = delete;
222 GeometryViews& operator=(GeometryViews&&) = delete;
223
152 static std::uint64_t cap() { 224 static std::uint64_t cap() {
153 static const std::uint64_t value = []() -> std::uint64_t { 225 static const std::uint64_t value = []() -> std::uint64_t {
154 const char* opt = std::getenv("LEONIDA_GEOMETRY_MB"); 226 const char* opt = std::getenv("LEONIDA_GEOMETRY_MB");
@@ -157,34 +229,83 @@ public:
157 return value; 229 return value;
158 } 230 }
159 231
232 std::uint64_t effective_cap() const { return cap_override_ ? cap_override_ : cap(); }
233
234 bool has_released() const { return leonida::geometry_writes::has_released(releases_); }
235 bool has_retired() const { return retired_count_.load(std::memory_order_acquire) != 0; }
236 bool has_pending_reclaim() const { return has_released() || has_retired(); }
237 leonida::geometry_writes::ReleaseQueue& release_queue() { return releases_; }
238
239 std::uint64_t bytes() const {
240 std::lock_guard lock(mutex_);
241 return bytes_;
242 }
243 std::uint64_t reserved() const {
244 std::lock_guard lock(mutex_);
245 return pool_.reserved();
246 }
247 std::size_t live_views() const {
248 std::lock_guard lock(mutex_);
249 return live_views_;
250 }
251 std::size_t retired_count() const { return retired_count_.load(std::memory_order_acquire); }
252 std::uint64_t free_generation() const { return free_generation_.load(std::memory_order_acquire); }
253 std::uint64_t cap_refusals() const {
254 std::lock_guard lock(mutex_);
255 return cap_refusals_;
256 }
257 std::uint64_t evicted() const {
258 std::lock_guard lock(mutex_);
259 return evicted_;
260 }
261 std::uint64_t reaped() const {
262 std::lock_guard lock(mutex_);
263 return reaped_;
264 }
265 std::size_t block_count() const {
266 std::lock_guard lock(mutex_);
267 return pool_.block_count();
268 }
269 std::size_t empty_blocks() const {
270 std::lock_guard lock(mutex_);
271 return pool_.empty_blocks();
272 }
273
160 std::uint64_t find(Address cpu, std::size_t bytes) const { 274 std::uint64_t find(Address cpu, std::size_t bytes) const {
161 if (VkDeviceSize va = 0; fast_find({cpu, bytes}, va)) return va; 275 if (VkDeviceSize va = 0; fast_find({cpu, bytes}, va)) return va;
162 std::shared_lock lock(structure_mutex_); 276 std::shared_lock lock(structure_mutex_);
163 const auto it = keys_.find({cpu, bytes}); 277 const auto it = keys_.find({cpu, bytes});
164 return it == keys_.end() || it->second == refused ? 0 : views_[it->second].va; 278 return it == keys_.end() || !views_[it->second].alive ? 0 : views_[it->second].va;
165 } 279 }
166 280
167 template<class Device, class Copy> 281 template<class Device, class Copy>
168 std::uint64_t resolve(Device& device, Address cpu, std::size_t bytes, Copy copy) { 282 std::uint64_t resolve(Device& device, Address cpu, std::size_t bytes, Copy copy) {
169 if (!bytes || bytes > UINTPTR_MAX - cpu) return 0; 283 if (!bytes || bytes > UINTPTR_MAX - cpu) return 0;
170 const auto key = std::make_pair(cpu, bytes); 284 const std::uint64_t limit = effective_cap();
171 if (VkDeviceSize known = 0; fast_find(key, known)) return known; 285 if (!limit) return 0;
286 const Key key = std::make_pair(cpu, bytes);
287 if (VkDeviceSize known = 0; fast_find_resolve(key, known)) return known;
172 std::lock_guard lock(mutex_); 288 std::lock_guard lock(mutex_);
173 if (const auto it = keys_.find(key); it != keys_.end()) { 289 if (const auto it = keys_.find(key); it != keys_.end()) {
174 const VkDeviceSize known = it->second == refused ? 0 : views_[it->second].va; 290 const VkDeviceSize known = views_[it->second].va;
175 publish(key, known); 291 publish(key, known, 0);
176 return known; 292 return known;
177 } 293 }
294 const std::uint64_t gen = free_generation_.load(std::memory_order_acquire);
295 const auto refused_it = refused_.find(key);
296 if (refused_it != refused_.end() && refused_it->second == gen) {
297 publish(key, 0, gen);
298 return 0;
299 }
178 std::uint8_t* mapped{}; 300 std::uint8_t* mapped{};
179 VkDeviceSize va{}; 301 VkDeviceSize va{};
180 bool at_cap = false; 302 bool at_cap = false;
181 if (bytes > cap() - bytes_ || !pool_.allocate(device, bytes, va, mapped, true, cap(), &at_cap)) { 303 const bool over_bytes = bytes_ >= limit || bytes > limit - bytes_;
182 if (at_cap || bytes > cap() - bytes_) { 304 if (over_bytes || !pool_.allocate(device, bytes, va, mapped, true, limit, &at_cap)) {
183 { 305 if (at_cap || over_bytes) {
184 std::unique_lock structure(structure_mutex_); 306 refused_[key] = gen;
185 keys_.emplace(key, refused); 307 if (bytes > max_refused_bytes_) max_refused_bytes_ = bytes;
186 } 308 publish(key, 0, gen);
187 publish(key, 0);
188 if (++cap_refusals_ <= 4) 309 if (++cap_refusals_ <= 4)
189 std::fprintf(stderr, "[rt] geometry buffer cap refused %zu bytes, %llu bytes already reserved\n", 310 std::fprintf(stderr, "[rt] geometry buffer cap refused %zu bytes, %llu bytes already reserved\n",
190 bytes, static_cast<unsigned long long>(pool_.reserved())); 311 bytes, static_cast<unsigned long long>(pool_.reserved()));
@@ -193,13 +314,27 @@ public:
193 } 314 }
194 return 0; 315 return 0;
195 } 316 }
196 auto id = views_.size(); 317 if (refused_it != refused_.end()) {
318 refused_.erase(refused_it);
319 ++retries_succeeded_;
320 }
321 const VkDeviceAddress bda = device.arena.address + va;
322 std::size_t id{};
197 { 323 {
198 std::unique_lock structure(structure_mutex_); 324 std::unique_lock structure(structure_mutex_);
325 if (!refreshing_ && !free_ids_.empty()) {
326 id = free_ids_.back();
327 free_ids_.pop_back();
328 views_[id] = View{cpu, bytes, mapped, va, bda, false, false, true};
329 } else {
330 id = views_.size();
331 views_.push_back(View{cpu, bytes, mapped, va, bda, false, false, true});
332 }
199 keys_[key] = id; 333 keys_[key] = id;
200 by_address_.emplace(device.arena.address + va, id); 334 by_address_.emplace(bda, id);
201 views_.push_back({cpu, bytes, mapped, va});
202 } 335 }
336 if (bytes > max_view_bytes_) max_view_bytes_ = bytes;
337 ++live_views_;
203 bytes_ += bytes; 338 bytes_ += bytes;
204 bool ready = true; 339 bool ready = true;
205 for (auto p = cpu & ~(tile_size - 1); p < cpu + bytes; p += tile_size) { 340 for (auto p = cpu & ~(tile_size - 1); p < cpu + bytes; p += tile_size) {
@@ -209,19 +344,180 @@ public:
209 tile.views.push_back(id); 344 tile.views.push_back(id);
210 ready &= !tile.retry; 345 ready &= !tile.retry;
211 } 346 }
212 if (ready) fill(views_.back(), copy); 347 if (ready) fill(views_[id], copy);
213 else { 348 else {
214 std::memset(mapped, 0, bytes); 349 std::memset(mapped, 0, bytes);
215 cleared_ += bytes; 350 cleared_ += bytes;
216 views_.back().zeroed = true; 351 views_[id].zeroed = true;
217 } 352 }
218 publish(key, va); 353 publish(key, va, 0);
219 return va; 354 return va;
220 } 355 }
221 356
357 // retire_range's ticket for a view that work already in flight may name: the ticket is taken by execute_end()
358 // once every ExecuteCommandLists replay begun by then has recorded its submissions.
359 static constexpr std::uint64_t kAfterExecutes = UINT64_MAX;
360
361 // An ExecuteCommandLists replay starts (before its before_execute_ work): its serial, for execute_end().
362 std::uint64_t execute_begin() {
363 std::lock_guard lock(execute_mutex_);
364 executing_.push_back(++execute_serial_);
365 return execute_serial_;
366 }
367 // The replay that began with `serial` has recorded its submissions. Views retired while only replays now finished
368 // were in progress get submitted() (the context's submitted_retire_ticket(), read here, after those replays
369 // recorded theirs) as their retire ticket. Lock order: mutex_ -> execute_mutex_, as in retire_range.
370 template<class Submitted>
371 void execute_end(std::uint64_t serial, Submitted&& submitted) {
372 {
373 std::lock_guard lock(execute_mutex_);
374 std::erase(executing_, serial);
375 }
376 if (!unstamped_.load(std::memory_order_acquire)) return;
377 std::lock_guard lock(mutex_);
378 std::uint64_t oldest = kAfterExecutes;
379 {
380 std::lock_guard execute(execute_mutex_);
381 for (const auto s : executing_) oldest = (std::min)(oldest, s);
382 }
383 const std::uint64_t ticket = submitted();
384 bool left = false;
385 for (auto& r : retired_) {
386 if (r.ticket != kAfterExecutes) continue;
387 if (r.epoch < oldest) r.ticket = ticket;
388 else left = true;
389 }
390 unstamped_.store(left, std::memory_order_release);
391 }
392
393 // Retires every live view overlapping [begin, end), unlinking it from lookup/refresh/watch immediately and
394 // deferring its backing storage reclamation until GPU submissions through `retire_ticket` have completed
395 // (kAfterExecutes: through the submissions of every replay in progress now, see execute_end).
396 template<class OnRetire = NoopRetire>
397 std::size_t retire_range(Address begin, Address end, std::uint64_t retire_ticket = 0,
398 OnRetire&& on_retire = {}) {
399 if (end <= begin) return 0;
400 struct CallbackItem {
401 Address source;
402 std::size_t size;
403 VkDeviceSize va;
404 };
405 std::vector<CallbackItem> callbacks;
406 {
407 std::lock_guard lock(mutex_);
408 std::vector<std::size_t> ids;
409 const Key key_start{begin > max_view_bytes_ ? begin - max_view_bytes_ : Address(0), 0};
410 for (auto it = keys_.lower_bound(key_start); it != keys_.end(); ++it) {
411 const auto& [key, id] = *it;
412 if (key.first >= end) break;
413 if (begin < key.first + key.second) ids.push_back(id);
414 }
415 std::vector<Key> stale_refused;
416 const Key refused_start{begin > max_refused_bytes_ ? begin - max_refused_bytes_ : Address(0), 0};
417 for (auto it = refused_.lower_bound(refused_start); it != refused_.end(); ++it) {
418 const auto& key = it->first;
419 if (key.first >= end) break;
420 if (begin < key.first + key.second) stale_refused.push_back(key);
421 }
422 if (ids.empty() && stale_refused.empty()) return 0;
423 if (retire_ticket == kAfterExecutes && !ids.empty()) unstamped_.store(true, std::memory_order_release);
424 callbacks.reserve(ids.size());
425 const std::size_t first_retired = retired_.size();
426 for (const auto id : ids) {
427 View& v = views_[id];
428 detach_tiles_locked(id, v.source, v.size);
429 if (v.ready) {
430 --ready_;
431 v.ready = false;
432 }
433 callbacks.push_back({v.source, v.size, v.va});
434 retired_.push_back({v.va, v.size, retire_ticket, 0});
435 }
436 if (!ids.empty()) {
437 std::unique_lock structure(structure_mutex_);
438 for (const auto id : ids) {
439 View& v = views_[id];
440 keys_.erase({v.source, v.size});
441 by_address_.erase(v.bda);
442 v.alive = false;
443 }
444 }
445 {
446 std::unique_lock fast(fast_mutex_);
447 for (const auto id : ids) fast_.erase({views_[id].source, views_[id].size});
448 for (const auto& k : stale_refused) fast_.erase(k);
449 }
450 // No resolve() or find() answers these views from here on, so a replay that begins now cannot name them:
451 // they wait only for the replays begun so far.
452 if (retire_ticket == kAfterExecutes && !ids.empty()) {
453 std::uint64_t epoch = 0;
454 {
455 std::lock_guard execute(execute_mutex_);
456 epoch = execute_serial_;
457 }
458 for (std::size_t i = first_retired; i < retired_.size(); ++i) retired_[i].epoch = epoch;
459 }
460 for (const auto& k : stale_refused) refused_.erase(k);
461 for (const auto id : ids) {
462 free_ids_.push_back(id);
463 --live_views_;
464 ++evicted_;
465 }
466 retired_count_.store(retired_.size(), std::memory_order_release);
467 }
468 for (const auto& item : callbacks) on_retire(item.source, item.size, item.va);
469 return callbacks.size();
470 }
471
472 // Frees backing storage for retired views whose GPU retire_ticket <= completed_ticket, returning their budget
473 // and bumping free_generation_ so previously refused ranges retry on the next resolve().
474 template<class Device>
475 std::size_t reap(Device& device, std::uint64_t completed_ticket = UINT64_MAX) {
476 if (!has_retired()) return 0;
477 std::lock_guard lock(mutex_);
478 std::size_t freed = 0;
479 std::size_t keep = 0;
480 for (std::size_t i = 0; i < retired_.size(); ++i) {
481 const Retired& r = retired_[i];
482 if (r.ticket != kAfterExecutes && r.ticket <= completed_ticket) {
483 pool_.free(device, r.va, r.size);
484 bytes_ -= r.size;
485 ++reaped_;
486 ++freed;
487 } else {
488 if (keep != i) retired_[keep] = r;
489 ++keep;
490 }
491 }
492 retired_.resize(keep);
493 retired_count_.store(retired_.size(), std::memory_order_release);
494 if (freed) free_generation_.fetch_add(1, std::memory_order_release);
495 return freed;
496 }
497
498 // Drains released title ranges recorded by xmem (retiring matching views at `retire_ticket`) and reaps retired
499 // views whose GPU work completed by `completed_ticket`.
500 template<class Device, class OnRetire = NoopRetire>
501 void drain_released(Device& device, std::uint64_t retire_ticket, std::uint64_t completed_ticket,
502 OnRetire&& on_retire = {}) {
503 std::vector<std::pair<Address, Address>> ranges;
504 leonida::geometry_writes::take_released(releases_, ranges);
505 for (const auto& [begin, end] : ranges) {
506 retire_range(begin, end, retire_ticket, on_retire);
507 leonida::title_gpu_views::Range pair{};
508 if (end > begin && leonida::title_gpu_views::view_at(begin, 1, pair) &&
509 begin >= pair.gpu && begin - pair.gpu < pair.size) {
510 const Address offset = begin - pair.gpu;
511 const Address span = (std::min)(end - begin, pair.size - offset);
512 retire_range(pair.cpu + offset, pair.cpu + offset + span, retire_ticket, on_retire);
513 }
514 }
515 reap(device, completed_ticket);
516 }
517
222 template<class Copy> 518 template<class Copy>
223 void refresh(Copy copy) { 519 void refresh(Copy copy) {
224 if (!cap()) return; 520 if (!effective_cap()) return;
225 // One refresh at a time (its scratch members, and mutex_ is let go during the walk below); taken before mutex_. 521 // One refresh at a time (its scratch members, and mutex_ is let go during the walk below); taken before mutex_.
226 std::lock_guard serial(refresh_mutex_); 522 std::lock_guard serial(refresh_mutex_);
227 std::unique_lock lock(mutex_); 523 std::unique_lock lock(mutex_);
@@ -232,6 +528,11 @@ public:
232 const auto before = uploaded_; 528 const auto before = uploaded_;
233 serial_ = now; 529 serial_ = now;
234 retry_ = false; 530 retry_ = false;
531 refreshing_ = true;
532 struct RefreshGuard {
533 bool& flag;
534 ~RefreshGuard() { flag = false; }
535 } guard{refreshing_};
235 // The views over each tile written since, with those tiles (in address order, as tiles_ is): a ready view 536 // The views over each tile written since, with those tiles (in address order, as tiles_ is): a ready view
236 // copies only them, 64 KiB each, not the whole view again (LEONIDA_GEOMETRY_WHOLE_VIEWS=1: whole views). 537 // copies only them, 64 KiB each, not the whole view again (LEONIDA_GEOMETRY_WHOLE_VIEWS=1: whole views).
237 static const bool whole = [] { 538 static const bool whole = [] {
@@ -243,41 +544,48 @@ public:
243 // 30-80 ms). A view over a tile that cannot be guarded yet (retry) is left as it is this time; a view not 544 // 30-80 ms). A view over a tile that cannot be guarded yet (retry) is left as it is this time; a view not
244 // filled yet is filled whole, once. 545 // filled yet is filled whole, once.
245 marks_.assign(views_.size(), 0); 546 marks_.assign(views_.size(), 0);
246 written_.clear(); 547 written_vas_.clear();
247 // The pass over the watched tiles makes a VirtualQuery and a VirtualProtect for each written one (tens of 548 // The pass over the watched tiles makes a VirtualQuery and a VirtualProtect for each written one (tens of
248 // milliseconds to a few hundred under Wine). resolve() waits for mutex_, and a new V# resolved while a 549 // milliseconds to a few hundred under Wine). resolve() waits for mutex_, and a new V# resolved while a
249 // submission fixes its console heap slots then waited for the whole pass (speed-35: 116 ms of fixing a 550 // submission fixes its console heap slots then waited for the whole pass (speed-35: 116 ms of fixing a
250 // submission with indirect draws on). So the lock is let go every 64 tiles. A view resolved meanwhile is 551 // submission with indirect draws on). So the lock is let go every 64 tiles. Walking by key (lower_bound)
251 // filled whole by resolve() and has no mark here; tiles_ is a std::map, so the walk survives its inserts. 552 // survives both inserts from resolve() and erasures from retire_range() while unlocked.
553 Address cursor = 0;
554 bool have_cursor = true;
252 std::size_t walked = 0; 555 std::size_t walked = 0;
253 for (auto& [va, tile] : tiles_) { 556 while (have_cursor) {
254 if (!(++walked & 63)) { 557 auto it = tiles_.lower_bound(cursor);
255 lock.unlock(); 558 if (it == tiles_.end()) break;
256 lock.lock(); 559 const Address va = it->first;
257 } 560 Tile& tile = it->second;
258 const bool written = update(va, tile); 561 const bool written = update(va, tile);
259 if (tile.retry) 562 if (tile.retry)
260 for (auto id : tile.views) 563 for (auto id : tile.views)
261 if (id < marks_.size()) marks_[id] |= kPinned; 564 if (id < marks_.size() && views_[id].alive) marks_[id] |= kPinned;
262 if (written) { 565 if (written) written_vas_.push_back(va);
263 written_.push_back(&tile); 566 if (va > UINTPTR_MAX - tile_size) have_cursor = false;
264 written_vas_.push_back(va); 567 else cursor = va + tile_size;
568 if (!(++walked & 63)) {
569 lock.unlock();
570 lock.lock();
265 } 571 }
266 } 572 }
267 const std::size_t changed_tiles = written_vas_.size(); 573 const std::size_t changed_tiles = written_vas_.size();
268 tile_reads_.clear(); 574 tile_reads_.clear();
269 tile_scratch_.clear(); 575 tile_scratch_.clear();
270 std::size_t changed_views = 0; 576 std::size_t changed_views = 0;
271 for (std::size_t w = 0; w < written_vas_.size(); ++w) { 577 for (const Address va : written_vas_) {
272 const Address va = written_vas_[w]; 578 const auto tile_it = tiles_.find(va);
273 const Tile& tile = *written_[w]; 579 if (tile_it == tiles_.end()) continue;
580 const Tile& tile = tile_it->second;
274 const std::uint8_t* read = nullptr; 581 const std::uint8_t* read = nullptr;
275 bool read_done = false; 582 bool read_done = false;
276 for (const auto id : tile.views) { 583 for (const auto id : tile.views) {
277 if (id >= marks_.size()) continue; // made by resolve() during the walk above: filled whole there 584 if (id >= marks_.size()) continue; // made by resolve() during the walk above: filled whole there
585 View& v = views_[id];
586 if (!v.alive) continue;
278 std::uint8_t& mark = marks_[id]; 587 std::uint8_t& mark = marks_[id];
279 if (mark & (kPinned | kWhole)) continue; 588 if (mark & (kPinned | kWhole)) continue;
280 View& v = views_[id];
281 if (!(mark & kTouched)) { 589 if (!(mark & kTouched)) {
282 mark |= kTouched; 590 mark |= kTouched;
283 ++changed_views; 591 ++changed_views;
@@ -308,8 +616,7 @@ public:
308 } 616 }
309 } 617 }
310 for (std::size_t id = 0; id < marks_.size(); ++id) 618 for (std::size_t id = 0; id < marks_.size(); ++id)
311 if ((marks_[id] & (kWhole | kPinned)) == kWhole) fill(views_[id], copy); 619 if ((marks_[id] & (kWhole | kPinned)) == kWhole && views_[id].alive) fill(views_[id], copy);
312 written_.clear();
313 written_vas_.clear(); 620 written_vas_.clear();
314 if (uploaded_ != before) ++dirty_refreshes_; 621 if (uploaded_ != before) ++dirty_refreshes_;
315 refilled_ += uploaded_ - before; 622 refilled_ += uploaded_ - before;
@@ -331,12 +638,15 @@ public:
331 double(window_.views) / double(window_.refreshes), 638 double(window_.views) / double(window_.refreshes),
332 double(window_.bytes) / 1024.0 / double(window_.refreshes), 639 double(window_.bytes) / 1024.0 / double(window_.refreshes),
333 std::chrono::duration<double, std::milli>(window_.time).count() / double(window_.refreshes), 640 std::chrono::duration<double, std::milli>(window_.time).count() / double(window_.refreshes),
334 tiles_.size(), views_.size()); 641 tiles_.size(), live_views_);
335 window_ = {}; 642 window_ = {};
336 window_.since = end; 643 window_.since = end;
337 } 644 }
338 } 645 }
339 646
647 // The blocks the copies live in (TitleBufferWindows::for_each_block), without the views' locks.
648 const TitleBufferWindows& pool() const { return pool_; }
649
340 bool lookup(VkDeviceAddress bda, std::uint64_t& host, std::uint64_t& bytes, std::uint64_t* source = nullptr, 650 bool lookup(VkDeviceAddress bda, std::uint64_t& host, std::uint64_t& bytes, std::uint64_t* source = nullptr,
341 bool* populated = nullptr) const { 651 bool* populated = nullptr) const {
342 std::shared_lock lock(structure_mutex_); 652 std::shared_lock lock(structure_mutex_);
@@ -345,7 +655,7 @@ public:
345 --it; 655 --it;
346 const auto offset = bda - it->first; 656 const auto offset = bda - it->first;
347 const auto& v = views_[it->second]; 657 const auto& v = views_[it->second];
348 if (offset >= v.size) return false; 658 if (!v.alive || offset >= v.size) return false;
349 bytes = v.size - offset; 659 bytes = v.size - offset;
350 host = reinterpret_cast<Address>(v.dst) + offset; 660 host = reinterpret_cast<Address>(v.dst) + offset;
351 if (source) *source = v.source + offset; 661 if (source) *source = v.source + offset;
@@ -353,13 +663,16 @@ public:
353 return true; 663 return true;
354 } 664 }
355 void report() const { 665 void report() const {
356 if (!cap()) return; 666 if (!effective_cap()) return;
357 std::lock_guard lock(mutex_); 667 std::lock_guard lock(mutex_);
358 std::fprintf(stderr, "[rt] geometry buffers: seen %zu, backed %zu (%llu bytes), populated %llu, cap %llu MiB, " 668 std::fprintf(stderr, "[rt] geometry buffers: seen %zu, backed %zu (%llu bytes), populated %llu, cap %llu MiB, "
359 "cap refused %llu, allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, reserved %llu bytes\n", 669 "cap refused %llu, retried ok %llu, evicted %llu (reaped %llu, retired %zu), "
360 keys_.size(), views_.size(), (unsigned long long)bytes_, (unsigned long long)ready_, 670 "allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, reserved %llu bytes\n",
361 (unsigned long long)(cap() >> 20), (unsigned long long)cap_refusals_, (unsigned long long)allocation_failures_, (unsigned long long)uploads_, 671 keys_.size() + refused_.size(), live_views_, (unsigned long long)bytes_, (unsigned long long)ready_,
362 (unsigned long long)uploaded_, tiles_.size(), 672 (unsigned long long)(effective_cap() >> 20), (unsigned long long)cap_refusals_,
673 (unsigned long long)retries_succeeded_, (unsigned long long)evicted_,
674 (unsigned long long)reaped_, retired_.size(), (unsigned long long)allocation_failures_,
675 (unsigned long long)uploads_, (unsigned long long)uploaded_, tiles_.size(),
363 static_cast<unsigned long long>(pool_.reserved())); 676 static_cast<unsigned long long>(pool_.reserved()));
364 std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes (%llu views by " 677 std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes (%llu views by "
365 "their written tiles only); %.3f s checking and refreshing sources, %llu bytes cleared\n", 678 "their written tiles only); %.3f s checking and refreshing sources, %llu bytes cleared\n",
@@ -369,11 +682,32 @@ public:
369 } 682 }
370 template<class Device> 683 template<class Device>
371 void release(Device& d) { 684 void release(Device& d) {
685 std::lock_guard lock(mutex_);
372 for (auto& [va, tile] : tiles_) { 686 for (auto& [va, tile] : tiles_) {
373 for (auto [peer, cell] : tile.peers) leonida::geometry_writes::release(peer); 687 for (auto [peer, cell] : tile.peers) leonida::geometry_writes::release(peer);
374 leonida::geometry_writes::release(va); 688 if (tile.primary) leonida::geometry_writes::release(va);
375 } 689 }
376 tiles_.clear(); 690 tiles_.clear();
691 {
692 std::unique_lock structure(structure_mutex_);
693 keys_.clear();
694 by_address_.clear();
695 views_.clear();
696 }
697 {
698 std::unique_lock fast(fast_mutex_);
699 fast_.clear();
700 }
701 refused_.clear();
702 max_view_bytes_ = 0;
703 max_refused_bytes_ = 0;
704 free_ids_.clear();
705 retired_.clear();
706 retired_count_.store(0, std::memory_order_release);
707 unstamped_.store(false, std::memory_order_release);
708 live_views_ = 0;
709 bytes_ = 0;
710 ready_ = 0;
377 pool_.release(d); 711 pool_.release(d);
378 } 712 }
379}; 713};
diff --git a/runtime/shims/d3d12_pipeline_compile.h b/runtime/shims/d3d12_pipeline_compile.h
index 3a5e04584..2889d7fd3 100644
--- a/runtime/shims/d3d12_pipeline_compile.h
+++ b/runtime/shims/d3d12_pipeline_compile.h
@@ -1,17 +1,21 @@
1// Timing and scheduling for Vulkan pipeline creation on the D3D12 device. 1// Timing and scheduling for Vulkan pipeline creation on the D3D12 device.
2#pragma once 2#pragma once
3 3
4#include "../src/vulkan_device_fault.h"
4#include "../src/vulkan_replay.h" 5#include "../src/vulkan_replay.h"
5#include <windows.h> 6#include <windows.h>
6#include <algorithm> 7#include <algorithm>
8#include <atomic>
7#include <chrono> 9#include <chrono>
8#include <condition_variable> 10#include <condition_variable>
9#include <cstdio> 11#include <cstdio>
10#include <functional> 12#include <functional>
11#include <map> 13#include <map>
12#include <mutex> 14#include <mutex>
15#include <optional>
13#include <thread> 16#include <thread>
14#include <string> 17#include <string>
18#include <cstring>
15#include <vector> 19#include <vector>
16 20
17namespace rt::d3d12 { 21namespace rt::d3d12 {
@@ -31,6 +35,30 @@ inline bool async_replay_compile() {
31 return on && !leonida::strict_replay(); 35 return on && !leonida::strict_replay();
32} 36}
33 37
38// LOCAL FIX (post-load stalls): LEONIDA_FAST_PIPELINES=graphics, compute, or all (1 = all) creates those pipelines with
39// VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT. After the story load, graphics creates measured about 4.5 s each, and
40// every submission waits at the compile gate while one is in the driver (frames stopped for 130 s); the title's large
41// compute programs take 30-220 s each. Slower shaders, much shorter builds: the trade for reaching the world before
42// it looks right. The flag is part of the compute journal key, so optimized and fast builds keep separate files.
43inline VkPipelineCreateFlags fast_pipeline_flags(bool compute) {
44 static const unsigned mask = [] {
45 wchar_t v[16]{};
46 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_FAST_PIPELINES", v, 16);
47 unsigned m = 0;
48 if (n > 0 && n < 16) {
49 if (!wcscmp(v, L"1") || !_wcsicmp(v, L"all")) m = 3;
50 else if (!_wcsicmp(v, L"graphics")) m = 1;
51 else if (!_wcsicmp(v, L"compute")) m = 2;
52 else std::fprintf(stderr, "[rt] d3d12: LEONIDA_FAST_PIPELINES: unknown value, ignored (graphics, compute, all)\n");
53 }
54 if (m)
55 std::fprintf(stderr, "[rt] d3d12: LEONIDA_FAST_PIPELINES: %s pipelines are built without driver optimization\n",
56 m == 3 ? "graphics and compute" : m == 1 ? "graphics" : "compute");
57 return m;
58 }();
59 return (mask & (compute ? 2u : 1u)) ? VkPipelineCreateFlags(VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT) : 0;
60}
61
34// Absolute monotonic timestamps let trace readers distinguish time in the ICD from time queued for the worker. 62// Absolute monotonic timestamps let trace readers distinguish time in the ICD from time queued for the worker.
35using CompileClock = std::chrono::steady_clock; 63using CompileClock = std::chrono::steady_clock;
36inline long long compile_us() { 64inline long long compile_us() {
@@ -59,31 +87,108 @@ struct CompileTrace {
59 nullptr, &feedback, 0, nullptr}; 87 nullptr, &feedback, 0, nullptr};
60 long long started = 0; 88 long long started = 0;
61 const char* key = "-"; 89 const char* key = "-";
90 bool linked = false; // chain is in a create info's pNext chain
62 91
63 template<class Info> void begin(Info& info, bool supported, const char* trigger, const char* shaders, 92 template<class Info> void begin(Info& info, bool supported, const char* trigger, const char* shaders,
64 std::uint32_t variant, std::size_t bytes, const std::string& description_key) { 93 std::uint32_t variant, std::size_t bytes, const std::string& description_key) {
65 if (!trace_pipeline_compile()) return; 94 if (!trace_pipeline_compile()) return;
66 if (!description_key.empty()) key = description_key.c_str(); 95 if (!description_key.empty()) key = description_key.c_str();
67 if (supported) { 96 if (supported) request_feedback(info);
68 chain.pNext = info.pNext;
69 info.pNext = &chain;
70 }
71 std::fprintf(stderr, "[rt] pipeline-compile-begin trigger=%s tid=%lu bytes=%zu variant=%u begin_ms=%lld key=%s shaders=%s\n", 97 std::fprintf(stderr, "[rt] pipeline-compile-begin trigger=%s tid=%lu bytes=%zu variant=%u begin_ms=%lld key=%s shaders=%s\n",
72 trigger, GetCurrentThreadId(), bytes, variant, compile_wall_ms(), key, shaders); 98 trigger, GetCurrentThreadId(), bytes, variant, compile_wall_ms(), key, shaders);
73 started = compile_us(); 99 started = compile_us();
74 } 100 }
75 101
102 // Chains the feedback struct ahead of info.pNext, once. begin() does when tracing; the pipeline journal does on a
103 // Vulkan 1.3 device (feedback is core there) to learn whether a pipeline came out of its cache.
104 template<class Info> void request_feedback(Info& info) {
105 if (linked) return;
106 chain.pNext = info.pNext;
107 info.pNext = &chain;
108 linked = true;
109 }
110
111 // 1 when the driver reports the pipeline was found in the application's VkPipelineCache, 0 when it reports it was
112 // not, -1 when it reported nothing (no feedback chained, or not VALID).
113 int hit() const {
114 return !(feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) ? -1 :
115 int((feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) != 0);
116 }
117
76 void end(const char* trigger, const char* shaders, std::uint32_t variant, std::size_t bytes, VkResult result) const { 118 void end(const char* trigger, const char* shaders, std::uint32_t variant, std::size_t bytes, VkResult result) const {
77 if (!started) return; 119 if (!started) return;
78 const auto ended = compile_us(); 120 const auto ended = compile_us();
79 const int hit = !(feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) ? -1 : 121 const int hit = this->hit();
80 int((feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) != 0);
81 std::fprintf(stderr, "[rt] pipeline-compile trigger=%s tid=%lu start_us=%lld us=%lld hit=%d bytes=%zu " 122 std::fprintf(stderr, "[rt] pipeline-compile trigger=%s tid=%lu start_us=%lld us=%lld hit=%d bytes=%zu "
82 "variant=%u result=%d end_ms=%lld key=%s shaders=%s\n", trigger, GetCurrentThreadId(), started, 123 "variant=%u result=%d end_ms=%lld key=%s shaders=%s\n", trigger, GetCurrentThreadId(), started,
83 ended - started, hit, bytes, variant, int(result), compile_wall_ms(), key, shaders); 124 ended - started, hit, bytes, variant, int(result), compile_wall_ms(), key, shaders);
84 } 125 }
85}; 126};
86 127
128// The triggers of builds on the compile worker (PipelineCompiler): "warmup", "dispatch-worker", "draw-worker".
129inline bool compile_worker_trigger(const char* trigger) {
130 if (!trigger) return false;
131 const std::size_t n = std::strlen(trigger);
132 return !std::strcmp(trigger, "warmup") || (n > 7 && !std::strcmp(trigger + n - 7, "-worker"));
133}
134
135// LOCAL FIX (early device loss): one driver call that builds or drops shader code, kept out of the way of queue
136// submissions (leonida::SubmitMutex). Before the call:
137// - let_submit_finish: a submit in progress finishes first. The compile worker also lets the submitters queued
138// behind it go first, and does so before its vkCreateShaderModule and vkDestroyShaderModule too; a title thread
139// waits only for the holder, and only before a pipeline create (it may wait out a vkDeviceWaitIdle or a present:
140// waits of 50 ms or more are logged).
141// - a pipeline create passes the compile gate (SubmitMutex::CompileTurn) for the length of the call.
142// - the compile worker, which runs below normal priority, runs the call at normal priority, so a preempted worker
143// does not sit on a driver lock a submit waits for.
144class DriverTurn {
145public:
146 DriverTurn(leonida::SubmitMutex& submits, const char* trigger, const char* call, bool pipeline,
147 const char* name = nullptr)
148 : worker_(compile_worker_trigger(trigger)) {
149 // Normal priority first: a below-normal worker that waits its turn at normal priority cannot keep losing the
150 // race to the next submit, and holds the gate (below) only at normal priority.
151 if (worker_) {
152 const HANDLE self = GetCurrentThread();
153 const int priority = GetThreadPriority(self);
154 if (priority != THREAD_PRIORITY_ERROR_RETURN && priority < THREAD_PRIORITY_NORMAL &&
155 SetThreadPriority(self, THREAD_PRIORITY_NORMAL))
156 restore_ = priority;
157 }
158 if (worker_ || pipeline) {
159 const std::int64_t waited = submits.let_submit_finish(worker_);
160 if (waited >= 50) note("waited for the submit lock", trigger, call, name, waited);
161 }
162 if (pipeline) {
163 gate_.emplace(submits);
164 if (gate_->waited_ms() >= 50) note("waited at the compile gate", trigger, call, name, gate_->waited_ms());
165 }
166 }
167 ~DriverTurn() {
168 // Leave the gate before dropping back to below normal: a worker preempted while still counted in the gate
169 // would hold every submitter waiting there (each with the submit lock held) until the scheduler's starvation
170 // boost runs it again.
171 gate_.reset();
172 if (restore_ != THREAD_PRIORITY_ERROR_RETURN) SetThreadPriority(GetCurrentThread(), restore_);
173 }
174 DriverTurn(const DriverTurn&) = delete;
175 DriverTurn& operator=(const DriverTurn&) = delete;
176
177private:
178 // Every wait of a second or more, and the first 32 of 50 ms or more.
179 static void note(const char* what, const char* trigger, const char* call, const char* name, std::int64_t ms) {
180 static std::atomic<unsigned> logged{0};
181 if (ms < 1000 && logged.fetch_add(1, std::memory_order_relaxed) >= 32) return;
182 std::fprintf(stderr, "[rt] submit-handoff: %s (%s, %s) on thread %lu %s %lld ms at t=%.3f s\n", call,
183 trigger ? trigger : "-", name ? name : "-", GetCurrentThreadId(), what, static_cast<long long>(ms),
184 double(leonida::diagnostic_ms()) / 1000.0);
185 }
186
187 bool worker_;
188 std::optional<leonida::SubmitMutex::CompileTurn> gate_;
189 int restore_ = THREAD_PRIORITY_ERROR_RETURN;
190};
191
87 192
88// Demanded work has priority zero, speculative work is ordered by module size, and 193// Demanded work has priority zero, speculative work is ordered by module size, and
89// an idle checkpoint runs last. No Vulkan call runs with the queue lock held. 194// an idle checkpoint runs last. No Vulkan call runs with the queue lock held.
@@ -116,27 +221,32 @@ public:
116 std::uint64_t deferred = 0; // after_running calls that left something to run after a running job 221 std::uint64_t deferred = 0; // after_running calls that left something to run after a running job
117 }; 222 };
118 223
119 // False, with nothing queued, after stop_for_exit. 224 // False, with nothing queued, after stop_for_exit. A `graphics` job (a graphics pipeline build) may also run on a
120 bool submit(const void* owner, const void* device, std::size_t priority, std::function<void()> work) { 225 // second worker that takes only graphics jobs, so a compute build the driver takes minutes over does not hold
226 // up later graphics pipelines. LEONIDA_GRAPHICS_COMPILE_WORKER=0 uses one shared worker.
227 bool submit(const void* owner, const void* device, std::size_t priority, std::function<void()> work,
228 bool graphics = false) {
121 std::lock_guard lock(mutex_); 229 std::lock_guard lock(mutex_);
122 if (closed_) { 230 if (closed_) {
123 ++stats_.refused; 231 ++stats_.refused;
124 return false; 232 return false;
125 } 233 }
126 if (!worker_.joinable()) { 234 if (!worker_.joinable()) {
127 const std::uint64_t generation = ++generation_; 235 const std::uint64_t generation = generation_;
128 worker_ = std::thread([this, generation] { run(generation); }); 236 worker_ = std::thread([this, generation] { run(generation, false); });
237 }
238 if (graphics && graphics_worker_enabled() && !graphics_worker_.joinable()) {
239 const std::uint64_t generation = generation_;
240 graphics_worker_ = std::thread([this, generation] { run(generation, true); });
129 } 241 }
130 jobs_.emplace(priority, Job{owner, device, std::move(work)}); 242 jobs_.emplace(priority, Job{owner, device, std::move(work), graphics});
131 ++stats_.submitted; 243 ++stats_.submitted;
132 wake_.notify_one(); 244 wake_.notify_all();
133 return true; 245 return true;
134 } 246 }
135 247
136 bool closed() { 248 // Lock-free: replay asks at every draw and dispatch whose pipeline is not built yet.
137 std::lock_guard lock(mutex_); 249 bool closed() const { return closed_flag_.load(std::memory_order_acquire); }
138 return closed_;
139 }
140 250
141 bool has_compile_waiter() { 251 bool has_compile_waiter() {
142 std::lock_guard lock(mutex_); 252 std::lock_guard lock(mutex_);
@@ -206,7 +316,7 @@ public:
206 } 316 }
207 void release() { 317 void release() {
208 std::vector<Job> dropped; 318 std::vector<Job> dropped;
209 std::thread worker; 319 Workers worker;
210 { 320 {
211 std::lock_guard lock(mutex_); 321 std::lock_guard lock(mutex_);
212 if (users_ && --users_) return; 322 if (users_ && --users_) return;
@@ -219,11 +329,12 @@ public:
219 // one, so ExitProcess does not end the worker inside the driver. False when a job was still running. 329 // one, so ExitProcess does not end the worker inside the driver. False when a job was still running.
220 bool stop_for_exit(std::chrono::milliseconds wait) { 330 bool stop_for_exit(std::chrono::milliseconds wait) {
221 std::vector<Job> dropped; 331 std::vector<Job> dropped;
222 std::thread worker; 332 Workers worker;
223 bool idle = true; 333 bool idle = true;
224 { 334 {
225 std::unique_lock lock(mutex_); 335 std::unique_lock lock(mutex_);
226 closed_ = true; 336 closed_ = true;
337 closed_flag_.store(true, std::memory_order_release);
227 worker = stop_locked(dropped); 338 worker = stop_locked(dropped);
228 const auto me = std::this_thread::get_id(); 339 const auto me = std::this_thread::get_id();
229 idle = done_.wait_for(lock, wait, [&] { 340 idle = done_.wait_for(lock, wait, [&] {
@@ -240,7 +351,7 @@ public:
240 } 351 }
241 bool worker_running() { 352 bool worker_running() {
242 std::lock_guard lock(mutex_); 353 std::lock_guard lock(mutex_);
243 return worker_.joinable(); 354 return worker_.joinable() || graphics_worker_.joinable();
244 } 355 }
245 // Tests: called on the worker with each job's owner, once the job counts as running and before its work. 356 // Tests: called on the worker with each job's owner, once the job counts as running and before its work.
246 void set_job_probe(std::function<void(const void* owner)> probe) { 357 void set_job_probe(std::function<void(const void* owner)> probe) {
@@ -253,6 +364,18 @@ private:
253 const void* owner = nullptr; 364 const void* owner = nullptr;
254 const void* device = nullptr; 365 const void* device = nullptr;
255 std::function<void()> work; 366 std::function<void()> work;
367 bool graphics = false; // a graphics pipeline build: the graphics worker may take it too
368 };
369 static bool graphics_worker_enabled() {
370 static const bool on = [] {
371 wchar_t v[2]{};
372 return !(GetEnvironmentVariableW(L"LEONIDA_GRAPHICS_COMPILE_WORKER", v, 2) == 1 && v[0] == L'0');
373 }();
374 return on;
375 }
376 // Both workers: the general one, and the graphics one when it was started.
377 struct Workers {
378 std::thread general, graphics;
256 }; 379 };
257 struct Running { 380 struct Running {
258 const void* owner; 381 const void* owner;
@@ -274,11 +397,11 @@ private:
274 } 397 }
275 } 398 }
276 399
277 std::thread stop_locked(std::vector<Job>& dropped) { 400 Workers stop_locked(std::vector<Job>& dropped) {
278 drop_locked(dropped, [](const Job&) { return true; }); 401 drop_locked(dropped, [](const Job&) { return true; });
279 ++generation_; // the worker returns when it next looks: after the job it is running, if any 402 ++generation_; // the workers return when they next look: after the job each is running, if any
280 wake_.notify_all(); 403 wake_.notify_all();
281 return std::move(worker_); 404 return {std::move(worker_), std::move(graphics_worker_)};
282 } 405 }
283 406
284 static void finish(std::thread worker, bool join) { 407 static void finish(std::thread worker, bool join) {
@@ -286,19 +409,30 @@ private:
286 if (join && worker.get_id() != std::this_thread::get_id()) worker.join(); 409 if (join && worker.get_id() != std::this_thread::get_id()) worker.join();
287 else worker.detach(); 410 else worker.detach();
288 } 411 }
412 static void finish(Workers workers, bool join) {
413 finish(std::move(workers.general), join);
414 finish(std::move(workers.graphics), join);
415 }
289 416
290 Running& mine(std::thread::id me) { 417 Running& mine(std::thread::id me) {
291 return *std::find_if(running_.begin(), running_.end(), [me](const Running& r) { return r.thread == me; }); 418 return *std::find_if(running_.begin(), running_.end(), [me](const Running& r) { return r.thread == me; });
292 } 419 }
293 420
294 void run(std::uint64_t generation) { 421 // The first job this worker may take, most urgent first: any job for the general worker, a graphics job for the
422 // graphics one.
423 std::multimap<std::size_t, Job>::iterator next_locked(bool graphics_only) {
424 if (!graphics_only) return jobs_.begin();
425 return std::find_if(jobs_.begin(), jobs_.end(), [](const auto& entry) { return entry.second.graphics; });
426 }
427
428 void run(std::uint64_t generation, bool graphics_only) {
295 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); 429 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
296 const auto me = std::this_thread::get_id(); 430 const auto me = std::this_thread::get_id();
297 std::unique_lock lock(mutex_); 431 std::unique_lock lock(mutex_);
298 for (;;) { 432 for (;;) {
299 wake_.wait(lock, [&] { return generation_ != generation || !jobs_.empty(); }); 433 wake_.wait(lock, [&] { return generation_ != generation || next_locked(graphics_only) != jobs_.end(); });
300 if (generation_ != generation) return; 434 if (generation_ != generation) return;
301 auto first = jobs_.begin(); 435 auto first = next_locked(graphics_only);
302 Job job = std::move(first->second); 436 Job job = std::move(first->second);
303 jobs_.erase(first); 437 jobs_.erase(first);
304 running_.push_back({job.owner, job.device, me}); 438 running_.push_back({job.owner, job.device, me});
@@ -338,9 +472,11 @@ private:
338 std::multimap<std::size_t, Job> jobs_; 472 std::multimap<std::size_t, Job> jobs_;
339 std::vector<Running> running_; // one per worker; a stopped worker may still be finishing one 473 std::vector<Running> running_; // one per worker; a stopped worker may still be finishing one
340 std::thread worker_; 474 std::thread worker_;
475 std::thread graphics_worker_; // graphics jobs only (submit's `graphics`), started at the first one
341 std::uint64_t generation_ = 0; // a worker runs while this is the value it started with 476 std::uint64_t generation_ = 0; // a worker runs while this is the value it started with
342 unsigned users_ = 0; // live devices (retain/release) 477 unsigned users_ = 0; // live devices (retain/release)
343 bool closed_ = false; // stop_for_exit: nothing more is queued 478 bool closed_ = false; // stop_for_exit: nothing more is queued
479 std::atomic<bool> closed_flag_{false}; // closed_, for closed()
344 Stats stats_; 480 Stats stats_;
345 std::function<void(const void*)> probe_; 481 std::function<void(const void*)> probe_;
346}; 482};
diff --git a/runtime/shims/d3d12_precompile.h b/runtime/shims/d3d12_precompile.h
new file mode 100644
index 000000000..447c4db4e
--- /dev/null
+++ b/runtime/shims/d3d12_precompile.h
@@ -0,0 +1,45 @@
1// gta6rt --precompile-pipelines: builds the compute pipelines of the whole translated shader library ahead of play.
2//
3// 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
4// on NVIDIA 630.20), and a title that dispatches one stalls its submissions behind it. Run with no game, this creates
5// the Vulkan device exactly as `gta6rt --run` does (the same environment: LEONIDA_SHADERS, LEONIDA_PIPELINE_CACHE_DIR,
6// LEONIDA_DEVICE_FAULT/LEONIDA_AFTERMATH, which change the pipelines) and builds every compute entry through the
7// same path as a dispatch (build_compute_pipeline), so each lands in the pipeline journal
8// (src/pipeline_cache_journal.h) under the name the game looks it up by, and in the driver's own disk cache, which
9// NVIDIA keys by the executable's name. Entries whose journal file is there are skipped, so a run can be stopped at
10// any time and started again.
11#pragma once
12
13#include <cstddef>
14#include <string>
15#include <vector>
16
17namespace rt::d3d12 {
18
19struct PrecompileOptions {
20 unsigned threads = 4; // worker threads, below normal priority
21 unsigned big_threads = 0; // of those, how many may build a module over big_bytes at once (0: threads)
22 std::size_t big_bytes = std::size_t{2} << 20;
23 bool rebuild = false; // --all: build entries whose journal file exists too
24 bool smallest_first = false; // default: the largest modules first (the ones that stall a title longest)
25 std::size_t limit = 0; // at most this many entries (0: all)
26 std::size_t min_bytes = 0, max_bytes = 0; // SPIR-V size bounds (0: none)
27 std::vector<std::string> filters; // only entries whose name contains one of these
28 bool dry_run = false; // --list: print the plan, build nothing
29 bool via_helper = false; // --via-helper: as a title does with LEONIDA_COMPILE_HELPER=1 (a test)
30};
31
32// gta6rt --compile-server (d3d12_compile_helper.h).
33struct CompileServerOptions {
34 unsigned long parent_pid = 0; // --parent: ends when that process does
35 unsigned threads = 2; // --threads
36 unsigned idle_threads = 1; // --idle-threads: of `threads`, how many fill the library when nothing is asked
37 unsigned idle_exit_s = 0; // --idle-exit: ends after this long with nothing asked (0: never)
38};
39int compile_server(const CompileServerOptions& options);
40
41// Returns 0 when every selected entry was built or already journaled, 2 when some could not be built, 1 when the
42// device or the library could not be had.
43int precompile_compute_pipelines(const PrecompileOptions& options);
44
45} // namespace rt::d3d12
diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h
index c940d6138..06927cb4b 100644
--- a/runtime/shims/d3d12_title_buffer_windows.h
+++ b/runtime/shims/d3d12_title_buffer_windows.h
@@ -1,23 +1,32 @@
1#pragma once 1#pragma once
2 2
3#include <algorithm> 3#include <algorithm>
4#include <array>
5#include <atomic>
6#include <utility>
4#include <chrono> 7#include <chrono>
5#include <cstdint> 8#include <cstdint>
6#include <cstdio> 9#include <cstdio>
10#include <iterator>
11#include <map>
7#include <vector> 12#include <vector>
8#include <vulkan/vulkan.h> 13#include <vulkan/vulkan.h>
9 14
10namespace rt::d3d12 { 15namespace rt::d3d12 {
11 16
12// Storage for shader-addressed mirrors when the main arena has no usable offset. 17// Storage for shader-addressed mirrors when the main arena has no usable offset.
13// A window lasts for the lifetime of the device, so these blocks only grow. 18// Sub-ranges freed via free() are coalesced for reuse; one empty standard 4 MiB block is kept as a spare and any
19// other empty block releases its Vulkan buffer and memory.
14class TitleBufferWindows { 20class TitleBufferWindows {
21 static constexpr VkDeviceSize kBlockSize = 4ull << 20;
15 struct Block { 22 struct Block {
16 VkBuffer buffer{}; 23 VkBuffer buffer{};
17 VkDeviceMemory memory{}; 24 VkDeviceMemory memory{};
18 VkDeviceAddress address{}; 25 VkDeviceAddress address{};
19 VkDeviceSize capacity{}, used{}; 26 VkDeviceSize capacity{}, used{}, reserved_bytes{};
20 std::uint8_t* mapped{}; 27 std::uint8_t* mapped{};
28 std::size_t live{};
29 std::map<VkDeviceSize, VkDeviceSize> free_ranges; // offset -> size, coalesced
21 }; 30 };
22 std::vector<Block> blocks_; 31 std::vector<Block> blocks_;
23 VkDeviceSize reserved_{}; 32 VkDeviceSize reserved_{};
@@ -30,26 +39,101 @@ class TitleBufferWindows {
30 bool failed_ = false; 39 bool failed_ = false;
31 bool local_refused_ = false; // device-local blocks refused once: host memory from then on 40 bool local_refused_ = false; // device-local blocks refused once: host memory from then on
32 std::uint64_t quick_refusals_ = 0; 41 std::uint64_t quick_refusals_ = 0;
42 // The blocks' (device address, capacity), readable without the owner's lock: published in order, a slot never
43 // reused before release(). A destroyed block's slot keeps its other fields and only its address goes to 0 (the
44 // readers skip it), so a reader never sees a slot half rewritten. Blocks are destroyed only once their last
45 // range was freed, which GeometryViews does after the GPU work that used them completed.
46 static constexpr std::size_t kPublished = 4096;
47 struct Published {
48 std::atomic<VkDeviceAddress> address{0};
49 VkDeviceSize capacity{};
50 std::uint8_t* mapped{};
51 VkBuffer buffer{};
52 };
53 std::array<Published, kPublished> published_{};
54 std::atomic<std::size_t> published_count_{0};
55 std::atomic<std::uint64_t> layout_generation_{0}; // bumped by every block made or destroyed
56
57 template<class Device>
58 void destroy_block(Device& d, std::vector<Block>::iterator it) {
59 // Unpublished first, so no lock-free reader picks it up again; then the owner is told, so tables built from
60 // for_each_block (the console heap pass's backed table) cut it before the next submission.
61 for (std::size_t i = 0, n = published_count_.load(std::memory_order_relaxed); i < n; ++i)
62 if (published_[i].buffer == it->buffer && published_[i].address.load(std::memory_order_relaxed)) {
63 published_[i].address.store(0, std::memory_order_release);
64 break;
65 }
66 layout_generation_.fetch_add(1, std::memory_order_release);
67 if constexpr (requires { d.title_block_gone(VkDeviceAddress{}, VkDeviceSize{}); })
68 d.title_block_gone(it->address, it->capacity);
69 d.context->vk.vkUnmapMemory(d.info.device, it->memory);
70 d.context->vk.vkDestroyBuffer(d.info.device, it->buffer, nullptr);
71 d.context->vk.vkFreeMemory(d.info.device, it->memory, nullptr);
72 reserved_ -= it->reserved_bytes;
73 blocks_.erase(it);
74 }
33 75
34public: 76public:
35 VkDeviceSize reserved() const { return reserved_; } 77 VkDeviceSize reserved() const { return reserved_; }
78 // f(device address, capacity) for each live block; from any thread.
79 template <class F>
80 void for_each_block(F&& f) const {
81 const std::size_t n = published_count_.load(std::memory_order_acquire);
82 for (std::size_t i = 0; i < n; ++i)
83 if (const VkDeviceAddress address = published_[i].address.load(std::memory_order_acquire))
84 f(address, published_[i].capacity);
85 }
86 // Changes whenever a block is made or destroyed; from any thread.
87 std::uint64_t layout_generation() const { return layout_generation_.load(std::memory_order_acquire); }
88 // The block whose mapping holds [p, p + bytes): its buffer and the offset of p in it. From any thread.
89 bool find_mapped(const std::uint8_t* p, std::size_t bytes, VkBuffer& buffer, VkDeviceSize& offset) const {
90 const std::size_t n = published_count_.load(std::memory_order_acquire);
91 for (std::size_t i = 0; i < n; ++i) {
92 const Published& b = published_[i];
93 if (!b.address.load(std::memory_order_acquire)) continue;
94 if (p >= b.mapped && p - b.mapped < std::ptrdiff_t(b.capacity) &&
95 bytes <= std::size_t(b.capacity) - std::size_t(p - b.mapped)) {
96 buffer = b.buffer;
97 offset = VkDeviceSize(p - b.mapped);
98 return true;
99 }
100 }
101 return false;
102 }
103 std::size_t block_count() const { return blocks_.size(); }
104 std::size_t empty_blocks() const {
105 std::size_t count = 0;
106 for (const auto& b : blocks_)
107 if (b.live == 0) ++count;
108 return count;
109 }
36 110
37 template<class Device> 111 template<class Device>
38 bool allocate(Device& d, VkDeviceSize bytes, VkDeviceSize& offset, std::uint8_t*& mapped, 112 bool allocate(Device& d, VkDeviceSize bytes, VkDeviceSize& offset, std::uint8_t*& mapped,
39 bool device_local = false, VkDeviceSize cap = UINT64_MAX, bool* at_cap = nullptr) { 113 bool device_local = false, VkDeviceSize cap = UINT64_MAX, bool* at_cap = nullptr) {
114 if (!bytes) return false;
40 const VkDeviceSize alignment = device_local ? 16 : 65536; 115 const VkDeviceSize alignment = device_local ? 16 : 65536;
41 constexpr VkDeviceSize block_size = 4ull << 20;
42 auto take = [&](Block& b) { 116 auto take = [&](Block& b) {
43 const auto start = (b.used + alignment - 1) & ~(alignment - 1); 117 for (auto it = b.free_ranges.begin(); it != b.free_ranges.end(); ++it) {
44 if (start > b.capacity || bytes > b.capacity - start) return false; 118 const VkDeviceSize range_start = it->first;
45 mapped = b.mapped + start; 119 const VkDeviceSize range_end = range_start + it->second;
46 offset = b.address - d.arena.address + start; 120 const VkDeviceSize start = (range_start + alignment - 1) & ~(alignment - 1);
47 b.used = start + bytes; 121 if (start < range_start || start > range_end || bytes > range_end - start) continue;
48 return true; 122 b.free_ranges.erase(it);
123 if (start > range_start) b.free_ranges.emplace(range_start, start - range_start);
124 const VkDeviceSize end = start + bytes;
125 if (end < range_end) b.free_ranges.emplace(end, range_end - end);
126 if (end > b.used) b.used = end;
127 ++b.live;
128 mapped = b.mapped + start;
129 offset = b.address - d.arena.address + start;
130 return true;
131 }
132 return false;
49 }; 133 };
50 if (!blocks_.empty() && take(blocks_.back())) return true; 134 if (!blocks_.empty() && take(blocks_.back())) return true;
51 // A large view may start a new slab while smaller views still fit earlier tails. 135 // A large view may start a new slab while smaller views still fit earlier tails or freed holes.
52 // Use those tails even after the budget can no longer accommodate another slab. 136 // Use those even after the budget can no longer accommodate another slab.
53 if (device_local && blocks_.size() > 1) 137 if (device_local && blocks_.size() > 1)
54 for (std::size_t i = blocks_.size() - 1; i != 0; --i) 138 for (std::size_t i = blocks_.size() - 1; i != 0; --i)
55 if (take(blocks_[i - 1])) return true; 139 if (take(blocks_[i - 1])) return true;
@@ -64,12 +148,25 @@ public:
64 failed_at_ = std::chrono::steady_clock::now(); 148 failed_at_ = std::chrono::steady_clock::now();
65 return false; 149 return false;
66 }; 150 };
67 Block b{}; 151 auto drop_unfitting_spare = [&] {
68 b.capacity = std::max(bytes, block_size); 152 for (auto it = blocks_.begin(); it != blocks_.end(); ++it) {
69 if (b.capacity > cap - reserved_) { 153 if (it->live == 0 && bytes > it->capacity) {
70 if (at_cap) *at_cap = true; 154 destroy_block(d, it);
155 return true;
156 }
157 }
71 return false; 158 return false;
159 };
160 VkDeviceSize remaining_cap = reserved_ < cap ? cap - reserved_ : 0;
161 if (bytes > remaining_cap) {
162 if (drop_unfitting_spare()) remaining_cap = reserved_ < cap ? cap - reserved_ : 0;
163 if (bytes > remaining_cap) {
164 if (at_cap) *at_cap = true;
165 return false;
166 }
72 } 167 }
168 Block b{};
169 b.capacity = std::max(bytes, std::min(kBlockSize, remaining_cap));
73 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 170 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
74 info.size = b.capacity; 171 info.size = b.capacity;
75 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; 172 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
@@ -77,10 +174,13 @@ public:
77 if (vk.vkCreateBuffer(d.info.device, &info, nullptr, &b.buffer) != VK_SUCCESS) return failed(); 174 if (vk.vkCreateBuffer(d.info.device, &info, nullptr, &b.buffer) != VK_SUCCESS) return failed();
78 VkMemoryRequirements req{}; 175 VkMemoryRequirements req{};
79 vk.vkGetBufferMemoryRequirements(d.info.device, b.buffer, &req); 176 vk.vkGetBufferMemoryRequirements(d.info.device, b.buffer, &req);
80 if (req.size > cap - reserved_) { 177 if (req.size > remaining_cap) {
81 if (at_cap) *at_cap = true; 178 if (drop_unfitting_spare()) remaining_cap = reserved_ < cap ? cap - reserved_ : 0;
82 vk.vkDestroyBuffer(d.info.device, b.buffer, nullptr); 179 if (req.size > remaining_cap) {
83 return false; 180 if (at_cap) *at_cap = true;
181 vk.vkDestroyBuffer(d.info.device, b.buffer, nullptr);
182 return false;
183 }
84 } 184 }
85 // Device-local (Resizable BAR) when asked and while the driver gives it; host memory otherwise. After the 185 // Device-local (Resizable BAR) when asked and while the driver gives it; host memory otherwise. After the
86 // story load the driver refused every 4 MiB device-local, host-visible block with a device address 186 // story load the driver refused every 4 MiB device-local, host-visible block with a device address
@@ -106,12 +206,22 @@ public:
106 // A positive 47-bit offset works with both generations of the translated V# decoder. 206 // A positive 47-bit offset works with both generations of the translated V# decoder.
107 if (b.address && biased < (1ull << 47) && b.capacity <= (1ull << 47) - biased) { 207 if (b.address && biased < (1ull << 47) && b.capacity <= (1ull << 47) - biased) {
108 b.mapped = static_cast<std::uint8_t*>(host); 208 b.mapped = static_cast<std::uint8_t*>(host);
109 blocks_.push_back(b); 209 b.reserved_bytes = req.size;
210 b.free_ranges.emplace(0, b.capacity);
211 if (const std::size_t n = published_count_.load(std::memory_order_relaxed); n < kPublished) {
212 published_[n].capacity = b.capacity;
213 published_[n].mapped = b.mapped;
214 published_[n].buffer = b.buffer;
215 published_[n].address.store(b.address, std::memory_order_relaxed);
216 published_count_.store(n + 1, std::memory_order_release);
217 }
218 layout_generation_.fetch_add(1, std::memory_order_release);
219 blocks_.push_back(std::move(b));
110 reserved_ += req.size; 220 reserved_ += req.size;
111 if (blocks_.size() == 1 || !(blocks_.size() & (blocks_.size() - 1))) 221 if (blocks_.size() == 1 || !(blocks_.size() & (blocks_.size() - 1)))
112 std::fprintf(stderr, "[rt] d3d12: title buffer shadows outside the arena: %zu blocks, " 222 std::fprintf(stderr, "[rt] d3d12: title buffer shadows outside the arena: %zu blocks, "
113 "new block %llu KiB at shader VA 0x%llx\n", blocks_.size(), 223 "new block %llu KiB at shader VA 0x%llx\n", blocks_.size(),
114 static_cast<unsigned long long>(b.capacity >> 10), 224 static_cast<unsigned long long>(blocks_.back().capacity >> 10),
115 static_cast<unsigned long long>(biased)); 225 static_cast<unsigned long long>(biased));
116 return take(blocks_.back()); 226 return take(blocks_.back());
117 } 227 }
@@ -121,6 +231,48 @@ public:
121 if (b.memory) vk.vkFreeMemory(d.info.device, b.memory, nullptr); 231 if (b.memory) vk.vkFreeMemory(d.info.device, b.memory, nullptr);
122 return failed(); 232 return failed();
123 } 233 }
234
235 // Returns [offset, offset + bytes) to its block for reuse; keeps one empty 4 MiB block as a spare and destroys
236 // any other empty block. Caller must guarantee no in-flight GPU work references this range.
237 template<class Device>
238 bool free(Device& d, VkDeviceSize offset, VkDeviceSize bytes) {
239 if (!bytes) return false;
240 const VkDeviceAddress bda = d.arena.address + offset;
241 for (auto it = blocks_.begin(); it != blocks_.end(); ++it) {
242 Block& b = *it;
243 if (bda < b.address || bda - b.address >= b.capacity) continue;
244 const VkDeviceSize start = bda - b.address;
245 if (bytes > b.capacity - start) return false;
246 VkDeviceSize merged_begin = start;
247 VkDeviceSize merged_end = start + bytes;
248 auto next = b.free_ranges.lower_bound(start);
249 if (next != b.free_ranges.begin()) {
250 auto prev = std::prev(next);
251 if (prev->first + prev->second >= merged_begin) {
252 merged_begin = prev->first;
253 merged_end = std::max(merged_end, prev->first + prev->second);
254 next = b.free_ranges.erase(prev);
255 }
256 }
257 while (next != b.free_ranges.end() && next->first <= merged_end) {
258 merged_end = std::max(merged_end, next->first + next->second);
259 next = b.free_ranges.erase(next);
260 }
261 b.free_ranges.emplace(merged_begin, merged_end - merged_begin);
262 if (b.live > 0) --b.live;
263 if (b.live == 0) {
264 if (b.capacity == kBlockSize && empty_blocks() == 1) {
265 b.free_ranges.clear();
266 b.free_ranges.emplace(0, b.capacity);
267 b.used = 0;
268 } else {
269 destroy_block(d, it);
270 }
271 }
272 return true;
273 }
274 return false;
275 }
124 // Allocations refused at once because a new block failed less than kRetryAfter ago. 276 // Allocations refused at once because a new block failed less than kRetryAfter ago.
125 std::uint64_t quick_refusals() const { return quick_refusals_; } 277 std::uint64_t quick_refusals() const { return quick_refusals_; }
126 278
@@ -145,6 +297,10 @@ public:
145 d.context->vk.vkFreeMemory(d.info.device, b.memory, nullptr); 297 d.context->vk.vkFreeMemory(d.info.device, b.memory, nullptr);
146 } 298 }
147 blocks_.clear(); 299 blocks_.clear();
300 for (std::size_t i = 0, n = published_count_.load(std::memory_order_relaxed); i < n; ++i)
301 published_[i].address.store(0, std::memory_order_relaxed);
302 published_count_.store(0, std::memory_order_release);
303 layout_generation_.fetch_add(1, std::memory_order_release);
148 reserved_ = 0; 304 reserved_ = 0;
149 } 305 }
150}; 306};
diff --git a/runtime/shims/d3d12_title_image_upload.h b/runtime/shims/d3d12_title_image_upload.h
index 2bb092f99..a0be8360d 100644
--- a/runtime/shims/d3d12_title_image_upload.h
+++ b/runtime/shims/d3d12_title_image_upload.h
@@ -219,11 +219,15 @@ private:
219 transfer.pCommandBuffers = &slot.command; 219 transfer.pCommandBuffers = &slot.command;
220 transfer.signalSemaphoreCount = 1; 220 transfer.signalSemaphoreCount = 1;
221 transfer.pSignalSemaphores = &ready_; 221 transfer.pSignalSemaphores = &ready_;
222 auto r = vk.vkQueueSubmit(d.info.queue, 1, &transfer, VK_NULL_HANDLE); 222 // Through the compile gate, as every other submission: it waits here, not in the driver, while a pipeline
223 // create holds it, and the caller observes a device loss from it.
224 auto r = d.context->queue_submit(d.info.queue, 1, &transfer, VK_NULL_HANDLE);
223 if (r != VK_SUCCESS) { 225 if (r != VK_SUCCESS) {
224 --value_; 226 --value_; // nothing signalled it
225 return r; 227 return r;
226 } 228 }
229 // No CPU wait: the slot's buffer is reused only after this value (wait_slot), the image's later reads are
230 // ordered behind the transfer on the GPU, and a retired image is destroyed through the deferred queue.
227 slot.value = value_; 231 slot.value = value_;
228 // GPU writes become visible to later submissions on every other queue. The primary queue has the image barrier. 232 // GPU writes become visible to later submissions on every other queue. The primary queue has the image barrier.
229 VkTimelineSemaphoreSubmitInfo acquire{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; 233 VkTimelineSemaphoreSubmitInfo acquire{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO};
@@ -235,7 +239,7 @@ private:
235 wait.pWaitSemaphores = &ready_; 239 wait.pWaitSemaphores = &ready_;
236 wait.pWaitDstStageMask = &stages; 240 wait.pWaitDstStageMask = &stages;
237 for (auto q : consumers_) 241 for (auto q : consumers_)
238 if ((r = vk.vkQueueSubmit(q, 1, &wait, VK_NULL_HANDLE)) != VK_SUCCESS) return r; 242 if ((r = d.context->queue_submit(q, 1, &wait, VK_NULL_HANDLE)) != VK_SUCCESS) return r;
239 return VK_SUCCESS; 243 return VK_SUCCESS;
240 } 244 }
241 245
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index c5f72eb27..1fb36401e 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -12,6 +12,8 @@
12#include "d3d12_com.h" 12#include "d3d12_com.h"
13#include "d3d12_compile_exit.h" 13#include "d3d12_compile_exit.h"
14#include "d3d12_pipeline_compile.h" 14#include "d3d12_pipeline_compile.h"
15#include "d3d12_precompile.h"
16#include "d3d12_compile_helper.h"
15#include "d3d12_pipeline_checkpoint.h" 17#include "d3d12_pipeline_checkpoint.h"
16#include "d3d12_feature_compat.h" 18#include "d3d12_feature_compat.h"
17 19
@@ -46,6 +48,9 @@
46#include "../src/pipeline_profile.h" 48#include "../src/pipeline_profile.h"
47#include "../src/submit_phases.h" 49#include "../src/submit_phases.h"
48#include "../src/pipeline_cache_store.h" 50#include "../src/pipeline_cache_store.h"
51#include "../src/pipeline_cache_journal.h"
52#include "../src/large_module_gate.h"
53#include "../src/dev_status.h"
49#include "../src/conservative_raster.h" 54#include "../src/conservative_raster.h"
50#include "../src/resource_detile.h" 55#include "../src/resource_detile.h"
51#include "../src/console_texture_layout.h" 56#include "../src/console_texture_layout.h"
@@ -60,6 +65,7 @@
60#include "../src/spirv_f16_halves.h" 65#include "../src/spirv_f16_halves.h"
61#include "../src/spirv_stores.h" 66#include "../src/spirv_stores.h"
62#include "../src/title_va_alias.h" 67#include "../src/title_va_alias.h"
68#include "../src/console_heap_vsharp_slots.h"
63#include "../src/title_window_plan.h" 69#include "../src/title_window_plan.h"
64#include "../src/vulkan_present.h" 70#include "../src/vulkan_present.h"
65#include "../src/vulkan_device_filter.h" 71#include "../src/vulkan_device_filter.h"
@@ -70,6 +76,7 @@
70#include "../src/local_diagnostics.h" 76#include "../src/local_diagnostics.h"
71#include "../src/mem_probe.h" // LOCAL DIAGNOSTIC 77#include "../src/mem_probe.h" // LOCAL DIAGNOSTIC
72#include "../src/vulkan_aftermath.h" 78#include "../src/vulkan_aftermath.h"
79#include "../src/console_heap_gpu.h"
73 80
74#include <vulkan/vulkan_win32.h> 81#include <vulkan/vulkan_win32.h>
75#ifdef _MSC_VER 82#ifdef _MSC_VER
@@ -89,6 +96,7 @@
89#include <fstream> 96#include <fstream>
90#include <iterator> 97#include <iterator>
91#include <map> 98#include <map>
99#include <unordered_map>
92#include <cstring> 100#include <cstring>
93#include <memory> 101#include <memory>
94#include <mutex> 102#include <mutex>
@@ -97,11 +105,13 @@
97#include <optional> 105#include <optional>
98#include <set> 106#include <set>
99#include <deque> 107#include <deque>
108#include <unordered_map>
100#include <unordered_set> 109#include <unordered_set>
101#include <shared_mutex> 110#include <shared_mutex>
102#include <string> 111#include <string>
103#include <type_traits> 112#include <type_traits>
104#include <cwchar> 113#include <cwchar>
114#include <intrin.h>
105#include <smmintrin.h> 115#include <smmintrin.h>
106#include <vector> 116#include <vector>
107 117
@@ -252,6 +262,13 @@ inline std::uint64_t hashed_bytes(std::uint64_t bytes, bool every_byte = false)
252 return bytes <= (256u << 10) || every_byte ? bytes : bytes / 32 + 64; 262 return bytes <= (256u << 10) || every_byte ? bytes : bytes / 32 + 64;
253} 263}
254 264
265bool async_texture_refresh() {
266 static const bool enabled = [] {
267 const char* v = std::getenv("LEONIDA_TEXTURE_REFRESH_ASYNC");
268 return v && std::strcmp(v, "1") == 0;
269 }();
270 return enabled;
271}
255// Set while this thread is inside the title-texture registry (it holds title_texture_mutex): a staged copy it makes 272// Set while this thread is inside the title-texture registry (it holds title_texture_mutex): a staged copy it makes
256// submits through a queue, whose before-submission refresh must then not take the registry again. 273// submits through a queue, whose before-submission refresh must then not take the registry again.
257thread_local bool t_in_title_textures = false; 274thread_local bool t_in_title_textures = false;
@@ -324,6 +341,13 @@ class ShadowPages {
324public: 341public:
325 static constexpr std::uintptr_t kPage = 0x1000; 342 static constexpr std::uintptr_t kPage = 0x1000;
326 static constexpr std::uintptr_t kBlock = 0x10000; // what one write fault makes writable again 343 static constexpr std::uintptr_t kBlock = 0x10000; // what one write fault makes writable again
344 // LEONIDA_SHADOW_GPU (DeviceState::gpu_copy_shadow): takes a copy of [from, from + bytes) to `to` for the GPU, or
345 // returns false and the CPU copies it. Set once by the device.
346 using GpuCopy = bool (*)(void* context, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes);
347 static inline GpuCopy gpu_copy = nullptr;
348 static inline void* gpu_copy_context = nullptr;
349 // Bytes this tracker's refreshes handed to gpu_copy so far.
350 std::uint64_t gpu_bytes() const { return gpu_bytes_; }
327 351
328 ShadowPages(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size, bool watch) : watch_(watch) { 352 ShadowPages(const std::uint8_t* pages, std::uint8_t* shadow, std::size_t size, bool watch) : watch_(watch) {
329 begin_ = reinterpret_cast<std::uintptr_t>(pages); 353 begin_ = reinterpret_cast<std::uintptr_t>(pages);
@@ -384,6 +408,8 @@ public:
384 // Brings every target up to date with the pages. Returns the bytes copied into them. With copy_aliased false, pages 408 // Brings every target up to date with the pages. Returns the bytes copied into them. With copy_aliased false, pages
385 // xmem maps at another address too are left as they are this time (DeviceState::refresh_shadows throttles them). 409 // xmem maps at another address too are left as they are this time (DeviceState::refresh_shadows throttles them).
386 std::size_t refresh(bool copy_aliased = true) { 410 std::size_t refresh(bool copy_aliased = true) {
411 const auto walk_start = std::chrono::steady_clock::now();
412 pieces_ = {};
387 copy_aliased_ = copy_aliased; 413 copy_aliased_ = copy_aliased;
388 jobs_.clear(); 414 jobs_.clear();
389 zeroed_.clear(); 415 zeroed_.clear();
@@ -524,11 +550,15 @@ public:
524 switch (how) { 550 switch (how) {
525 case Watch::clean: break; // write-watched, not written since it was copied 551 case Watch::clean: break; // write-watched, not written since it was copied
526 case Watch::written: // write-watched: written since, or not known yet 552 case Watch::written: // write-watched: written since, or not known yet
553 // A page this tracker made read-only is opened first: dropping kProtected alone left it
554 // read-only with no owner, so the next write could fault.
555 unguard_ours(i, j);
527 for (std::size_t k = i; k < j; ++k) 556 for (std::size_t k = i; k < j; ++k)
528 state_[k] = std::uint8_t((state_[k] & ~(kZero | kProtected)) | kClean); 557 state_[k] = std::uint8_t((state_[k] & ~(kZero | kProtected)) | kClean);
529 add_job(i, j, streaming, Copy::write_watched); 558 add_job(i, j, streaming, Copy::write_watched);
530 break; 559 break;
531 case Watch::open: // write-watched, but pinned for a kernel write: copied until the pin ends 560 case Watch::open: // write-watched, but pinned for a kernel write: copied until the pin ends
561 unguard_ours(i, j);
532 for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected | kClean); 562 for (std::size_t k = i; k < j; ++k) state_[k] &= ~(kZero | kProtected | kClean);
533 add_job(i, j, streaming, Copy::write_watched); 563 add_job(i, j, streaming, Copy::write_watched);
534 break; 564 break;
@@ -543,6 +573,7 @@ public:
543 } 573 }
544 break; 574 break;
545 case Kind::unwatched: 575 case Kind::unwatched:
576 unguard_ours(i0, i1); // as above: never drop kProtected over a page still read-only for us
546 for (std::size_t i = i0; i < i1; ++i) state_[i] &= kAliased | kPinned | kWatched; 577 for (std::size_t i = i0; i < i1; ++i) state_[i] &= kAliased | kPinned | kWatched;
547 add_job(i0, i1, streaming, Copy::copy_on_write); 578 add_job(i0, i1, streaming, Copy::copy_on_write);
548 break; 579 break;
@@ -558,15 +589,55 @@ public:
558 log_once("slot-133 shadow: VirtualProtect refused to watch the title's pages for writes, so they are " 589 log_once("slot-133 shadow: VirtualProtect refused to watch the title's pages for writes, so they are "
559 "copied at every submission; error", 590 "copied at every submission; error",
560 int(protect_error)); 591 int(protect_error));
561 // The copies run without the lock: a write that faults meanwhile is let through and copied next time. 592 // The copies run without the lock: a write that faults meanwhile is let through and copied next time. Pages
593 // copied because they are aliased go to the GPU when LEONIDA_SHADOW_GPU set gpu_copy and it takes them.
594 // LEONIDA_SHADOW_JOIN=1: pieces of one job that go on where the one before ended, in the pages and in the copy
595 // both, are one copy (one GPU region, one gpu_copy call); one the GPU refuses is copied by the CPU whole.
596 static const bool join = [] {
597 char value[4] = {};
598 return GetEnvironmentVariableA("LEONIDA_SHADOW_JOIN", value, sizeof(value)) == 1 && value[0] == '1';
599 }();
600 const auto copy_start = std::chrono::steady_clock::now();
601 pieces_.walk_ms = std::chrono::duration<double, std::milli>(copy_start - walk_start).count();
562 std::size_t copied = 0; 602 std::size_t copied = 0;
563 for (const Job& job : jobs_) 603 for (const Job& job : jobs_) {
604 std::uint8_t* run_dst = nullptr;
605 const std::uint8_t* run_src = nullptr;
606 std::size_t run_bytes = 0;
607 const auto flush = [&] {
608 if (!run_bytes) return;
609 ++pieces_.calls;
610 if (job.aliased && gpu_copy) ++pieces_.gpu_calls;
611 if (job.aliased && gpu_copy && gpu_copy(gpu_copy_context, run_dst, run_src, run_bytes))
612 gpu_bytes_ += run_bytes;
613 else
614 copy_run(run_dst, run_src, run_bytes, job.streaming);
615 run_bytes = 0;
616 };
564 for_each_target(begin_ + job.offset, begin_ + job.offset + job.bytes, 617 for_each_target(begin_ + job.offset, begin_ + job.offset + job.bytes,
565 [&](const Target& t, std::uintptr_t from, std::uintptr_t to) { 618 [&](const Target& t, std::uintptr_t from, std::uintptr_t to) {
566 copy_run(t.shadow + (from - t.begin), reinterpret_cast<const std::uint8_t*>(from), 619 std::uint8_t* dst = t.shadow + (from - t.begin);
567 to - from, job.streaming); 620 const auto* src = reinterpret_cast<const std::uint8_t*>(from);
568 copied += to - from; 621 const std::size_t n = to - from;
622 ++pieces_.pieces;
623 pieces_.short_pieces += n < kPage;
624 const bool follows = run_bytes && run_dst + run_bytes == dst && run_src + run_bytes == src;
625 pieces_.joinable += follows;
626 if (join && follows) {
627 run_bytes += n;
628 } else {
629 flush();
630 run_dst = dst;
631 run_src = src;
632 run_bytes = n;
633 if (!join) flush();
634 }
635 copied += n;
569 }); 636 });
637 flush();
638 }
639 pieces_.copy_ms =
640 std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - copy_start).count();
570 refresh_queries_ = queries; 641 refresh_queries_ = queries;
571 return copied; 642 return copied;
572 } 643 }
@@ -761,6 +832,15 @@ public:
761 // read-only pages that are not this tracker's, copy-on-write pages, write-watched pages found written. 832 // read-only pages that are not this tracker's, copy-on-write pages, write-watched pages found written.
762 enum class Copy { guarded, unguarded, aliased, pinned, read_only, copy_on_write, write_watched, count }; 833 enum class Copy { guarded, unguarded, aliased, pinned, read_only, copy_on_write, write_watched, count };
763 const std::array<std::uint64_t, unsigned(Copy::count)>& copy_bytes() const { return copy_bytes_; } 834 const std::array<std::uint64_t, unsigned(Copy::count)>& copy_bytes() const { return copy_bytes_; }
835 // The last refresh()'s copies as pieces (one per job and target: a slot-133 buffer is a few KiB, so a run of
836 // pages over many of them is many pieces), those under 4 KiB, those that go on where the one before ended in both
837 // the title's pages and the copy (VItoriaBr's JOIN_COPIES case), the copy calls made after LEONIDA_SHADOW_JOIN
838 // joined those, and the milliseconds of the walk (queries, guards, under the lock) and of the copies.
839 struct Pieces {
840 std::uint64_t pieces = 0, short_pieces = 0, joinable = 0, calls = 0, gpu_calls = 0;
841 double walk_ms = 0, copy_ms = 0;
842 };
843 const Pieces& pieces() const { return pieces_; }
764 844
765private: 845private:
766 // How a committed, readable page is watched: by the kernel (clean, written or, pinned or aliased, open) or by 846 // How a committed, readable page is watched: by the kernel (clean, written or, pinned or aliased, open) or by
@@ -905,6 +985,7 @@ private:
905 struct Job { 985 struct Job {
906 std::size_t offset, bytes; // from begin_ 986 std::size_t offset, bytes; // from begin_
907 bool streaming; 987 bool streaming;
988 bool aliased; // copied because xmem maps the pages elsewhere too (Copy::aliased)
908 }; 989 };
909 struct Target { 990 struct Target {
910 std::uintptr_t begin, end; // the title's bytes 991 std::uintptr_t begin, end; // the title's bytes
@@ -933,12 +1014,13 @@ private:
933 void add_job(std::size_t i, std::size_t j, bool streaming, Copy why) { 1014 void add_job(std::size_t i, std::size_t j, bool streaming, Copy why) {
934 const auto [offset, bytes] = span_of(i, j); 1015 const auto [offset, bytes] = span_of(i, j);
935 copy_bytes_[unsigned(why)] += bytes; 1016 copy_bytes_[unsigned(why)] += bytes;
936 if (!jobs_.empty() && jobs_.back().streaming == streaming && 1017 const bool aliased = why == Copy::aliased;
1018 if (!jobs_.empty() && jobs_.back().streaming == streaming && jobs_.back().aliased == aliased &&
937 jobs_.back().offset + jobs_.back().bytes == offset) { 1019 jobs_.back().offset + jobs_.back().bytes == offset) {
938 jobs_.back().bytes += bytes; 1020 jobs_.back().bytes += bytes;
939 return; 1021 return;
940 } 1022 }
941 jobs_.push_back({offset, bytes, streaming}); 1023 jobs_.push_back({offset, bytes, streaming, aliased});
942 } 1024 }
943 1025
944 // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the 1026 // The targets sorted by start, the bytes they hold, and reach_[k], the furthest end among targets_[0..k]: the
@@ -989,6 +1071,18 @@ private:
989 ++refresh_protects_; 1071 ++refresh_protects_;
990 } 1072 }
991 1073
1074 // With the lock held: before pages [i, j) stop counting as ours (kProtected), the ones this tracker made read-only
1075 // are given back their write access, so no page stays read-only with no guard to answer its writes.
1076 void unguard_ours(std::size_t i, std::size_t j) {
1077 for (std::size_t k = i; k < j; ++k)
1078 if (state_[k] & kProtected) {
1079 ++unguarded_on_drop_;
1080 reopen_locked(first_ + i * kPage, first_ + j * kPage);
1081 return;
1082 }
1083 }
1084 std::uint64_t unguarded_on_drop_ = 0; // times unguard_ours found pages of ours to reopen (diagnostic)
1085
992 // With the lock held: the pages in [from, to) this tracker made read-only are read-write again. 1086 // With the lock held: the pages in [from, to) this tracker made read-only are read-write again.
993 void reopen_locked(std::uintptr_t from, std::uintptr_t to) { 1087 void reopen_locked(std::uintptr_t from, std::uintptr_t to) {
994 for (std::uintptr_t at = from; at < to;) { 1088 for (std::uintptr_t at = from; at < to;) {
@@ -1042,6 +1136,8 @@ private:
1042 DWORD protect_error_ = 0; // a VirtualProtect refusal of this refresh(), logged after it 1136 DWORD protect_error_ = 0; // a VirtualProtect refusal of this refresh(), logged after it
1043 std::array<std::uint64_t, unsigned(Copy::count)> copy_bytes_{}; // refresh() only, likewise 1137 std::array<std::uint64_t, unsigned(Copy::count)> copy_bytes_{}; // refresh() only, likewise
1044 bool copy_aliased_ = true; // likewise 1138 bool copy_aliased_ = true; // likewise
1139 std::uint64_t gpu_bytes_ = 0;
1140 Pieces pieces_; // refresh() only, likewise
1045 std::uint64_t refresh_queries_ = 0; 1141 std::uint64_t refresh_queries_ = 0;
1046 std::uint64_t refresh_protects_ = 0; // VirtualProtect calls of the last refresh() 1142 std::uint64_t refresh_protects_ = 0; // VirtualProtect calls of the last refresh()
1047 bool refresh_walked_all_ = false; // the last refresh() queried every page (the title memory map changed) 1143 bool refresh_walked_all_ = false; // the last refresh() queried every page (the title memory map changed)
@@ -1075,6 +1171,49 @@ leonida::host_heap::vector<ShadowPages*>& shadow_pages_list() {
1075// pages at every submission (title_page_aliases), so the guard to look for is the faulting address's own. When none 1171// pages at every submission (title_page_aliases), so the guard to look for is the faulting address's own. When none
1076// answers for it (each guard reopens only what it protected), xmem makes the page writable again if its window is 1172// answers for it (each guard reopens only what it protected), xmem makes the page writable again if its window is
1077// (kernel_writes' unguarder): a read-only page nobody reopens would fault that write, and every later one, for good. 1173// (kernel_writes' unguarder): a read-only page nobody reopens would fault that write, and every later one, for good.
1174// A title write into a committed, private, read-only page of title memory that no guard owns (the geometry watch,
1175// the slot-133 shadows and the kernel-write unguarder all declined it): a guard of ours left behind, since the title
1176// never writes memory it made read-only itself on the console. Said for the first 32 pages, with whether a shadow's
1177// range still covers the page (its bookkeeping then calls the page unguarded). LEONIDA_STRAY_RO_HEAL=1: the page is
1178// made writable again and the write retried, so the title goes on (a shadow may then miss that page's next writes:
1179// the GPU copy may be stale for one frame).
1180bool stray_read_only(EXCEPTION_POINTERS* info, std::uintptr_t address) {
1181 MEMORY_BASIC_INFORMATION m{};
1182 if (!VirtualQuery(reinterpret_cast<const void*>(address), &m, sizeof m)) return false;
1183 if (m.State != MEM_COMMIT || m.Type != MEM_PRIVATE || (m.Protect & 0xff) != PAGE_READONLY) return false;
1184 std::uint64_t lo = 0, hi = 0;
1185 if (!leonida::title_va_aliases().title_memory(address, lo, hi)) return false;
1186 static const bool heal = [] {
1187 const char* v = std::getenv("LEONIDA_STRAY_RO_HEAL");
1188 return v && *v == '1';
1189 }();
1190 unsigned covering = 0;
1191 AcquireSRWLockShared(&g_shadow_pages_lock);
1192 for (ShadowPages* pages : shadow_pages_list()) covering += pages->contains(address);
1193 ReleaseSRWLockShared(&g_shadow_pages_lock);
1194 static std::atomic<unsigned> told{0}, healed{0};
1195 const std::uintptr_t page = address & ~std::uintptr_t(0xfff);
1196 bool ok = false;
1197 if (heal) {
1198 DWORD old = 0;
1199 ok = VirtualProtect(reinterpret_cast<void*>(page), 0x1000, (m.Protect & ~DWORD(0xff)) | PAGE_READWRITE, &old) != 0;
1200 if (ok) healed.fetch_add(1, std::memory_order_relaxed);
1201 }
1202 if (told.fetch_add(1, std::memory_order_relaxed) < 32) {
1203 const auto rip = info && info->ContextRecord ? info->ContextRecord->Rip : 0;
1204 std::fprintf(stderr, "[rt] d3d12: stray read-only title page 0x%llx (write to 0x%llx from rip 0x%llx; "
1205 "allocation 0x%llx, protect 0x%lx): no guard owns it, %u shadow range(s) cover it; %s "
1206 "(%u healed so far)\n",
1207 static_cast<unsigned long long>(page), static_cast<unsigned long long>(address),
1208 static_cast<unsigned long long>(rip), static_cast<unsigned long long>(
1209 reinterpret_cast<std::uintptr_t>(m.AllocationBase)),
1210 static_cast<unsigned long>(m.Protect), covering,
1211 !heal ? "left to fault (LEONIDA_STRAY_RO_HEAL=1 makes it writable)" : ok ? "made writable" : "could not be made writable",
1212 healed.load(std::memory_order_relaxed));
1213 }
1214 return ok;
1215}
1216
1078LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) { 1217LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) {
1079 const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; 1218 const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr;
1080 if (!record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2 || 1219 if (!record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2 ||
@@ -1097,6 +1236,7 @@ LONG CALLBACK shadow_write_fault(EXCEPTION_POINTERS* info) {
1097 if (!retry) 1236 if (!retry)
1098 if (const auto unguard = leonida::kernel_writes::state().unguarder.load(std::memory_order_acquire)) 1237 if (const auto unguard = leonida::kernel_writes::state().unguarder.load(std::memory_order_acquire))
1099 retry = unguard(address, address + 1); 1238 retry = unguard(address, address + 1);
1239 if (!retry) retry = stray_read_only(info, address);
1100 return retry ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH; 1240 return retry ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH;
1101} 1241}
1102 1242
@@ -1114,6 +1254,15 @@ void open_shadow_pages(std::uintptr_t from, std::uintptr_t to) {
1114 ReleaseSRWLockShared(&g_shadow_pages_lock); 1254 ReleaseSRWLockShared(&g_shadow_pages_lock);
1115} 1255}
1116 1256
1257// fsdraw's backing hook: whether a slot-133 shadow keeps the GPU copy of a title VA (LEONIDA_FSDRAW_PROBE only).
1258const char* fsdraw_backing(std::uint64_t title_va) {
1259 unsigned covering = 0;
1260 AcquireSRWLockShared(&g_shadow_pages_lock);
1261 for (ShadowPages* pages : shadow_pages_list()) covering += pages->contains(std::uintptr_t(title_va));
1262 ReleaseSRWLockShared(&g_shadow_pages_lock);
1263 return covering ? "a slot-133 shadow" : "an alias with no slot-133 shadow (window, geometry view or import)";
1264}
1265
1117// Installs the handler once. false: it couldn't be, and shadows copy every page at every submission. 1266// Installs the handler once. false: it couldn't be, and shadows copy every page at every submission.
1118bool watch_shadow_writes() { 1267bool watch_shadow_writes() {
1119 static const bool installed = [] { 1268 static const bool installed = [] {
@@ -1238,6 +1387,36 @@ std::filesystem::path pipeline_cache_session_path() {
1238 return path; 1387 return path;
1239} 1388}
1240 1389
1390std::size_t pipeline_cache_save_limit();
1391
1392// LOCAL FIX (pipeline journal, pipeline_cache_journal.h): where each compute pipeline's own cache file goes, beside
1393// the session file (so LEONIDA_PIPELINE_CACHE_DIR moves it too). Empty, and no journal, with LEONIDA_PIPELINE_JOURNAL=0
1394// or LEONIDA_PIPELINE_CACHE_BYTES=0.
1395const leonida::pipeline_journal::Roots& pipeline_journal_roots() {
1396 static const auto roots = []() -> leonida::pipeline_journal::Roots {
1397 wchar_t value[2]{};
1398 if (GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL", value, 2) == 1 && value[0] == L'0')
1399 return {};
1400 if (!pipeline_cache_save_limit()) return {};
1401 std::filesystem::path path = pipeline_cache_path();
1402 if (!path.empty()) path.replace_filename(L"pipeline_cache.d");
1403 std::wstring seed(32768, L'\0');
1404 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL_SEED_DIR", seed.data(),
1405 static_cast<DWORD>(seed.size()));
1406 if (n >= seed.size()) return {};
1407 seed.resize(n);
1408 auto result = leonida::pipeline_journal::resolve_roots(path, seed);
1409 if (!seed.empty() && result.writable.empty())
1410 std::fprintf(stderr, "[rt] d3d12: invalid or overlapping compute journal directories; journal disabled\n");
1411 return result;
1412 }();
1413 return roots;
1414}
1415
1416const std::filesystem::path& pipeline_journal_dir() {
1417 return pipeline_journal_roots().writable;
1418}
1419
1241// LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. 1420// LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number.
1242std::size_t pipeline_cache_save_limit() { 1421std::size_t pipeline_cache_save_limit() {
1243 char text[32] = {}; 1422 char text[32] = {};
@@ -1320,16 +1499,16 @@ VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_ca
1320// and the session file cannot be handed over as one VkPipelineCacheCreateInfo -- Vulkan reads a single blob -- so the 1499// and the session file cannot be handed over as one VkPipelineCacheCreateInfo -- Vulkan reads a single blob -- so the
1321// session cache is created on its own and merged in. A missing, foreign or corrupt session file leaves the cache as 1500// session cache is created on its own and merged in. A missing, foreign or corrupt session file leaves the cache as
1322// it was, and so does a driver that does not expose vkMergePipelineCaches. 1501// it was, and so does a driver that does not expose vkMergePipelineCaches.
1323void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, 1502bool merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache,
1324 const leonida::cached_pso::Identity& identity) { 1503 const leonida::cached_pso::Identity& identity) {
1325 if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return; 1504 if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return false;
1326 if (!pipeline_cache_save_limit()) return; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off 1505 if (!pipeline_cache_save_limit()) return false; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off
1327 const auto start = compile_us(); 1506 const auto start = compile_us();
1328 const PipelineCacheSeed seed(pipeline_cache_session_path()); 1507 const PipelineCacheSeed seed(pipeline_cache_session_path());
1329 if (!seed.data()) return; 1508 if (!seed.data()) return false;
1330 if (!seed.compatible(identity)) { 1509 if (!seed.compatible(identity)) {
1331 std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin does not match this Vulkan device\n"); 1510 std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin does not match this Vulkan device\n");
1332 return; 1511 return false;
1333 } 1512 }
1334 const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), 1513 const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(),
1335 seed.data()}; 1514 seed.data()};
@@ -1337,7 +1516,7 @@ void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDe
1337 VkPipelineCache session = VK_NULL_HANDLE; 1516 VkPipelineCache session = VK_NULL_HANDLE;
1338 if (vk.vkCreatePipelineCache(device, &create, nullptr, &session) != VK_SUCCESS) { 1517 if (vk.vkCreatePipelineCache(device, &create, nullptr, &session) != VK_SUCCESS) {
1339 std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.session.bin\n"); 1518 std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.session.bin\n");
1340 return; 1519 return false;
1341 } 1520 }
1342 const auto created = compile_us(); 1521 const auto created = compile_us();
1343 const VkResult result = vk.vkMergePipelineCaches(device, cache, 1, &session); 1522 const VkResult result = vk.vkMergePipelineCaches(device, cache, 1, &session);
@@ -1351,6 +1530,7 @@ void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDe
1351 else 1530 else
1352 std::fprintf(stderr, "[rt] d3d12: vkMergePipelineCaches on pipeline_cache.session.bin returned %d; ignored\n", 1531 std::fprintf(stderr, "[rt] d3d12: vkMergePipelineCaches on pipeline_cache.session.bin returned %d; ignored\n",
1353 static_cast<int>(result)); 1532 static_cast<int>(result));
1533 return result == VK_SUCCESS;
1354} 1534}
1355 1535
1356// LEONIDA_SKIP_COMPUTE=<part of a name>[,<part>...]: compute programs whose library name contains one of the parts are 1536// LEONIDA_SKIP_COMPUTE=<part of a name>[,<part>...]: compute programs whose library name contains one of the parts are
@@ -1402,14 +1582,39 @@ bool console_format_stand_ins() {
1402 return on; 1582 return on;
1403} 1583}
1404 1584
1405// A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Compute modules 1585// A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Large are
1406// over 128 KiB compile one at a time (LEONIDA_SERIAL_BIG_COMPILES=0: as many as are asked for). 1586// compute modules over 128 KiB and graphics pipelines of PipelineCompiles::large_spirv_bytes or more. They compile side by
1407bool serial_big_compile(std::size_t spirv_bytes) { 1587// side while their estimates fit the memory that is free (big_compile_gate). LEONIDA_SERIAL_BIG_COMPILES=1: one at a time,
1408 static const bool serial = [] { 1588// as before there was a budget (graphics: one after another in each submission). 0: as many as are asked for.
1589enum class BigCompiles { budget, serial, unlimited };
1590BigCompiles big_compiles() {
1591 static const BigCompiles mode = [] {
1409 wchar_t v[2]{}; 1592 wchar_t v[2]{};
1410 return !(GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2) == 1 && v[0] == L'0'); 1593 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2);
1594 if (n == 0) return BigCompiles::budget;
1595 return n == 1 && v[0] == L'0' ? BigCompiles::unlimited : BigCompiles::serial;
1596 }();
1597 return mode;
1598}
1599bool big_compute(std::size_t spirv_bytes) { return spirv_bytes > 128 * 1024; }
1600
1601// Where large compiles wait for memory: one for the process, as the memory is the machine's. Never destroyed: static
1602// destruction must not race the compile worker.
1603leonida::LargeModuleGate& big_compile_gate() {
1604 static auto* const gate = [] {
1605 char text[32]{};
1606 std::size_t length = 0;
1607 const bool present = getenv_s(&length, text, "LEONIDA_BIG_COMPILE_BUDGET_MB") == 0 && length > 1;
1608 const auto setting = leonida::large_compile_budget(present ? text : "");
1609 if (!setting.valid)
1610 std::fprintf(stderr, "[rt] d3d12: LEONIDA_BIG_COMPILE_BUDGET_MB=%s is not a number; not used\n", text);
1611 auto budget = [fixed = setting.fixed] { return fixed ? *fixed : leonida::large_compile_budget_bytes(); };
1612 std::fprintf(stderr, "[rt] d3d12: large pipelines compile side by side within %llu MiB (%s)\n",
1613 static_cast<unsigned long long>(budget() >> 20),
1614 setting.fixed ? "LEONIDA_BIG_COMPILE_BUDGET_MB" : "3/4 of the memory free now");
1615 return new leonida::LargeModuleGate(std::move(budget));
1411 }(); 1616 }();
1412 return serial && spirv_bytes > 128 * 1024; 1617 return *gate;
1413} 1618}
1414 1619
1415bool startup_cache_checkpoints_enabled() { 1620bool startup_cache_checkpoints_enabled() {
@@ -1422,7 +1627,7 @@ bool startup_cache_checkpoints_enabled() {
1422 1627
1423// Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write. 1628// Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write.
1424void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, 1629void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache,
1425 bool checkpoint = false) { 1630 bool checkpoint = false, const char* op = nullptr) {
1426 if (!cache || !vk.vkGetPipelineCacheData) return; 1631 if (!cache || !vk.vkGetPipelineCacheData) return;
1427 auto limit = pipeline_cache_save_limit(); 1632 auto limit = pipeline_cache_save_limit();
1428 // The output is an opaque Vulkan blob. A prefix is not an incremental cache. 1633 // The output is an opaque Vulkan blob. A prefix is not an incremental cache.
@@ -1453,7 +1658,7 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev
1453 written <= size && staging.publish(path, written); 1658 written <= size && staging.publish(path, written);
1454 if (trace_pipeline_compile()) 1659 if (trace_pipeline_compile())
1455 std::fprintf(stderr, "[rt] pipeline-cache op=%s bytes=%zu query_us=%lld fill_us=%lld publish_us=%lld ok=%d result=%d\n", 1660 std::fprintf(stderr, "[rt] pipeline-cache op=%s bytes=%zu query_us=%lld fill_us=%lld publish_us=%lld ok=%d result=%d\n",
1456 checkpoint ? "checkpoint" : "teardown", written, queried-start, filled-queried, 1661 op ? op : checkpoint ? "checkpoint" : "teardown", written, queried-start, filled-queried,
1457 compile_us()-filled, int(ok), int(result)); 1662 compile_us()-filled, int(ok), int(result));
1458 if (ok) std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written); 1663 if (ok) std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written);
1459 else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); 1664 else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result));
@@ -1875,6 +2080,18 @@ public:
1875 if (va >= r.console_va && va - r.console_va < r.bytes) return r.shader_va + (va - r.console_va); 2080 if (va >= r.console_va && va - r.console_va < r.bytes) return r.shader_va + (va - r.console_va);
1876 return va; 2081 return va;
1877 } 2082 }
2083 // The console heap holding `va`: its console VA and size. False when no console heap with a copy holds it.
2084 bool range_of(std::uint64_t va, std::uint64_t& console_va, std::uint64_t& bytes) const {
2085 if (!count_.load(std::memory_order_acquire)) return false;
2086 std::shared_lock lock(mutex_);
2087 for (const Range& r : ranges_)
2088 if (va >= r.console_va && va - r.console_va < r.bytes) {
2089 console_va = r.console_va;
2090 bytes = r.bytes;
2091 return true;
2092 }
2093 return false;
2094 }
1878 2095
1879private: 2096private:
1880 struct Range { 2097 struct Range {
@@ -1904,13 +2121,69 @@ bool console_heap_shadow_enabled() {
1904// What a T# the title wrote itself into a console descriptor heap came to (bind_title_image, after Resource). 2121// What a T# the title wrote itself into a console descriptor heap came to (bind_title_image, after Resource).
1905// not_tsharp: words with an image TYPE that do not decode as a T#: data, not a descriptor (the retail heap's last 2122// not_tsharp: words with an image TYPE that do not decode as a T#: data, not a descriptor (the retail heap's last
1906// 27 MiB are also the slot-133 pool, whose buffers sit there; T14 in ref/GAP-ANALYSIS-2.md). 2123// 27 MiB are also the slot-133 pool, whose buffers sit there; T14 in ref/GAP-ANALYSIS-2.md).
1907enum class TitleImage { known, bound, unknown, refused, not_tsharp }; 2124// TitleImage is defined in d3d12_com.h.
1908class Resource; 2125class Resource;
1909struct DeviceState; 2126struct DeviceState;
1910// `why`, when given, says what refused a T#: the first refusals are logged with their words (scan_console_slots). 2127// `why`, when given, says what refused a T#: the first refusals are logged with their words (scan_console_slots).
1911TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why = nullptr); 2128TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why = nullptr);
1912struct TitleTexture; // a texture the title keeps in its own memory (TitleTexture, after Resource) 2129struct TitleTexture; // a texture the title keeps in its own memory (TitleTexture, after Resource)
1913 2130
2131// The first refused T#s of each reason, with where they sit in the heap and their words, and counts of the
2132// distinct slots refused overall and per reason (a slot is scanned again every pass over the heap).
2133struct UnboundTsharpTracker {
2134 std::mutex mutex;
2135 std::set<std::size_t> total_slots;
2136 std::map<std::string, std::set<std::size_t>> slots_by_reason;
2137 std::map<std::string, std::uint64_t> counts_by_reason;
2138 std::map<std::string, unsigned> logged;
2139 std::uint64_t total_refusals = 0;
2140
2141 void note(std::uint64_t heap_va, std::size_t offset, const leonida::gfx10::ImageWords& words, const char* why) {
2142 std::lock_guard lock(mutex);
2143 const std::string reason = why ? why : "?";
2144 ++total_refusals;
2145 ++counts_by_reason[reason];
2146 if (total_slots.size() >= 262144) return; // enough to say how many
2147 const bool fresh_overall = total_slots.insert(offset).second;
2148 const bool fresh_reason = slots_by_reason[reason].insert(offset).second;
2149 unsigned& n = logged[reason];
2150 if ((!fresh_overall && !fresh_reason) || n >= 6) return;
2151 ++n;
2152 std::fprintf(stderr,
2153 "[rt] d3d12: unbound T# in console heap 0x%llx at +0x%zx (%zu distinct slots so far, %zu for '%s'): %s: "
2154 "%08x %08x %08x %08x %08x %08x %08x %08x\n",
2155 static_cast<unsigned long long>(heap_va), offset, total_slots.size(),
2156 slots_by_reason[reason].size(), reason.c_str(), reason.c_str(), words[0],
2157 words[1], words[2], words[3], words[4], words[5], words[6], words[7]);
2158 }
2159
2160 UnboundTsharpStats stats() {
2161 std::lock_guard lock(mutex);
2162 UnboundTsharpStats s;
2163 s.total_distinct_slots = total_slots.size();
2164 s.total_refusals = total_refusals;
2165 for (const auto& [reason, slots] : slots_by_reason) {
2166 s.by_reason[reason].distinct_slots = slots.size();
2167 s.by_reason[reason].total_refusals = counts_by_reason[reason];
2168 }
2169 return s;
2170 }
2171
2172 void reset() {
2173 std::lock_guard lock(mutex);
2174 total_slots.clear();
2175 slots_by_reason.clear();
2176 counts_by_reason.clear();
2177 logged.clear();
2178 total_refusals = 0;
2179 }
2180};
2181
2182UnboundTsharpTracker& unbound_tsharp_tracker() {
2183 static UnboundTsharpTracker tracker;
2184 return tracker;
2185}
2186
1914// What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. 2187// What a device's children need from it, kept apart from the COM class so children can hold a plain pointer.
1915class Resource; 2188class Resource;
1916struct DeviceState { 2189struct DeviceState {
@@ -1962,6 +2235,18 @@ struct DeviceState {
1962 leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against 2235 leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against
1963 std::once_flag pipeline_cache_once; 2236 std::once_flag pipeline_cache_once;
1964 VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; 2237 VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE;
2238 // The shared cache started from a file (the offline seed or an earlier session): a compute pipeline the journal
2239 // has no file for may still be in it (build_compute asks it first, when it can ask without a compile).
2240 bool pipeline_cache_seeded = false;
2241 std::atomic<unsigned> journal_hits{0}, journal_writes{0}, journal_shared_hits{0};
2242 std::atomic<std::uint64_t> journal_bytes{0}; // on disk: counted at the cache's creation, then added to
2243 std::uint64_t journal_budget = leonida::pipeline_journal::default_budget;
2244 // Ask the shared cache first, with FAIL_ON_PIPELINE_COMPILE_REQUIRED, while the driver honours it.
2245 // LEONIDA_PIPELINE_JOURNAL_ASK_SHARED=0: never.
2246 std::atomic<bool> journal_ask_shared{[] {
2247 wchar_t value[2]{};
2248 return !(GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL_ASK_SHARED", value, 2) == 1 && value[0] == L'0');
2249 }()};
1965 std::atomic<ULONGLONG> next_checkpoint{GetTickCount64() + 120000}; 2250 std::atomic<ULONGLONG> next_checkpoint{GetTickCount64() + 120000};
1966 std::atomic<unsigned> active_compiles{0}; 2251 std::atomic<unsigned> active_compiles{0};
1967 2252
@@ -1970,20 +2255,45 @@ struct DeviceState {
1970 const auto& vk = context->vk; 2255 const auto& vk = context->vk;
1971 if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; 2256 if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return;
1972 if (pipeline_cache_save_limit()) clean_stale_cache_files(pipeline_cache_session_path()); 2257 if (pipeline_cache_save_limit()) clean_stale_cache_files(pipeline_cache_session_path());
1973 pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); 2258 // A build host (precompile, compile helper) journals every pipeline: no seed, no session file.
2259 if (!compile_helper::build_host)
2260 pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity);
1974 if (pipeline_cache_handle) { 2261 if (pipeline_cache_handle) {
2262 pipeline_cache_seeded = true;
1975 merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); 2263 merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity);
1976 } else if (pipeline_cache_save_limit() && direct_session_cache()) { 2264 } else if (pipeline_cache_save_limit() && direct_session_cache() && !compile_helper::build_host) {
1977 // With no offline seed the session file can initialize the actual cache directly. 2265 // With no offline seed the session file can initialize the actual cache directly.
1978 pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity, true); 2266 pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity, true);
2267 pipeline_cache_seeded = pipeline_cache_handle != VK_NULL_HANDLE;
1979 } 2268 }
1980 if (!pipeline_cache_handle) { 2269 if (!pipeline_cache_handle) {
1981 const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; 2270 const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO};
1982 if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) 2271 if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS)
1983 pipeline_cache_handle = VK_NULL_HANDLE; 2272 pipeline_cache_handle = VK_NULL_HANDLE;
1984 else if (!direct_session_cache()) 2273 else if (!direct_session_cache() && !compile_helper::build_host)
1985 merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); 2274 pipeline_cache_seeded = merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity);
1986 } 2275 }
2276 if (!pipeline_journal_dir().empty()) {
2277 char text[32] = {};
2278 size_t length = 0;
2279 if (getenv_s(&length, text, "LEONIDA_PIPELINE_JOURNAL_BYTES") == 0 && length > 1) {
2280 const auto budget = leonida::pipeline_cache_store::parse_save_limit(text);
2281 if (budget.valid) journal_budget = budget.bytes;
2282 }
2283 // Old staging files out, and the least recently used files when over the budget: translator
2284 // regenerations leave files no build names any more.
2285 const auto tidy = leonida::pipeline_journal::tidy(pipeline_journal_dir(), journal_budget);
2286 journal_bytes = tidy.bytes;
2287 if (tidy.evicted || tidy.swept)
2288 std::fprintf(stderr, "[rt] d3d12: pipeline journal: removed %zu least recently used file(s) over "
2289 "the %llu-byte budget and %zu stale staging file(s); %zu file(s), %llu bytes "
2290 "left\n", tidy.evicted, static_cast<unsigned long long>(journal_budget),
2291 tidy.swept, tidy.entries, static_cast<unsigned long long>(tidy.bytes));
2292 }
2293 if (!pipeline_journal_dir().empty())
2294 std::fprintf(stderr, "[rt] d3d12: compute pipelines are journaled one file each in %ls\n",
2295 pipeline_journal_dir().c_str());
2296 if (compile_helper::enabled() && !pipeline_journal_dir().empty()) compile_helper::Client::instance().prestart();
1987 }); 2297 });
1988 // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. 2298 // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache.
1989 return pipeline_cache_handle; 2299 return pipeline_cache_handle;
@@ -2059,6 +2369,7 @@ struct DeviceState {
2059 std::uint64_t shadow_asks = 0; // GetWriteWatch calls, likewise 2369 std::uint64_t shadow_asks = 0; // GetWriteWatch calls, likewise
2060 std::uint64_t shadow_written = 0; // write-watched pages they found written, likewise 2370 std::uint64_t shadow_written = 0; // write-watched pages they found written, likewise
2061 std::array<std::uint64_t, unsigned(ShadowPages::Copy::count)> shadow_copy_bytes{}; // by cause, likewise 2371 std::array<std::uint64_t, unsigned(ShadowPages::Copy::count)> shadow_copy_bytes{}; // by cause, likewise
2372 ShadowPages::Pieces shadow_pieces; // summed over the refreshes since the last log line
2062 std::chrono::steady_clock::time_point shadow_alias_time{}; // the last refresh that copied aliased pages 2373 std::chrono::steady_clock::time_point shadow_alias_time{}; // the last refresh that copied aliased pages
2063 double shadow_ms = 0; // spent since the last log line 2374 double shadow_ms = 0; // spent since the last log line
2064 double shadow_max_ms = 0; // the longest refresh since the last log line 2375 double shadow_max_ms = 0; // the longest refresh since the last log line
@@ -2146,6 +2457,14 @@ struct DeviceState {
2146 shadow_asks += s->refresh_asks(); 2457 shadow_asks += s->refresh_asks();
2147 shadow_written += s->refresh_written(); 2458 shadow_written += s->refresh_written();
2148 for (unsigned k = 0; k < shadow_copy_bytes.size(); ++k) shadow_copy_bytes[k] += s->copy_bytes()[k]; 2459 for (unsigned k = 0; k < shadow_copy_bytes.size(); ++k) shadow_copy_bytes[k] += s->copy_bytes()[k];
2460 const ShadowPages::Pieces& p = s->pieces();
2461 shadow_pieces.pieces += p.pieces;
2462 shadow_pieces.short_pieces += p.short_pieces;
2463 shadow_pieces.joinable += p.joinable;
2464 shadow_pieces.calls += p.calls;
2465 shadow_pieces.gpu_calls += p.gpu_calls;
2466 shadow_pieces.walk_ms += p.walk_ms;
2467 shadow_pieces.copy_ms += p.copy_ms;
2149 } 2468 }
2150 const auto now = clock::now(); 2469 const auto now = clock::now();
2151 const double ms = std::chrono::duration<double, std::milli>(now - start).count(); 2470 const double ms = std::chrono::duration<double, std::milli>(now - start).count();
@@ -2181,6 +2500,15 @@ struct DeviceState {
2181 kib(ShadowPages::Copy::guarded), kib(ShadowPages::Copy::unguarded), kib(ShadowPages::Copy::aliased), 2500 kib(ShadowPages::Copy::guarded), kib(ShadowPages::Copy::unguarded), kib(ShadowPages::Copy::aliased),
2182 kib(ShadowPages::Copy::pinned), kib(ShadowPages::Copy::read_only), 2501 kib(ShadowPages::Copy::pinned), kib(ShadowPages::Copy::read_only),
2183 kib(ShadowPages::Copy::copy_on_write), kib(ShadowPages::Copy::write_watched)); 2502 kib(ShadowPages::Copy::copy_on_write), kib(ShadowPages::Copy::write_watched));
2503 std::fprintf(stderr,
2504 "[rt] d3d12: slot-133 shadow copies as pieces, a refresh: %.1f pieces (%.1f under 4 KiB, %.1f going on "
2505 "where the one before ended), %.1f copy calls (%.1f offered to the GPU); walk %.3f ms, copies %.3f "
2506 "ms\n",
2507 double(shadow_pieces.pieces) / count, double(shadow_pieces.short_pieces) / count,
2508 double(shadow_pieces.joinable) / count, double(shadow_pieces.calls) / count,
2509 double(shadow_pieces.gpu_calls) / count, shadow_pieces.walk_ms / count,
2510 shadow_pieces.copy_ms / count);
2511 shadow_pieces = {};
2184 shadow_copy_bytes = {}; 2512 shadow_copy_bytes = {};
2185 shadow_logged = shadow_submissions; 2513 shadow_logged = shadow_submissions;
2186 shadow_log_time = now; 2514 shadow_log_time = now;
@@ -2196,6 +2524,9 @@ struct DeviceState {
2196 // defined after TitleTexture. 2524 // defined after TitleTexture.
2197 std::mutex title_texture_mutex; 2525 std::mutex title_texture_mutex;
2198 std::map<std::uint64_t, std::shared_ptr<TitleTexture>> title_textures; 2526 std::map<std::uint64_t, std::shared_ptr<TitleTexture>> title_textures;
2527 leonida::TitleTextureRangeIndex texture_ranges;
2528 std::map<std::uint64_t, std::shared_ptr<TitleTexture>> mapped_title_textures;
2529 void index_texture(const TitleTexture& t);
2199 void title_texture_mapped(const void* resource, std::uint64_t address); 2530 void title_texture_mapped(const void* resource, std::uint64_t address);
2200 void title_texture_unmapped(const void* resource, std::uint64_t address); // the title wrote texels 2531 void title_texture_unmapped(const void* resource, std::uint64_t address); // the title wrote texels
2201 void title_texture_gone(const void* resource, std::uint64_t address); 2532 void title_texture_gone(const void* resource, std::uint64_t address);
@@ -2226,6 +2557,7 @@ struct DeviceState {
2226 static constexpr std::uint64_t kPoolExtentMax = 1ull << 20; 2557 static constexpr std::uint64_t kPoolExtentMax = 1ull << 20;
2227 std::mutex title_window_mutex; // taken before shadow_mutex, never under it 2558 std::mutex title_window_mutex; // taken before shadow_mutex, never under it
2228 rt::d3d12::TitleBufferWindows external_windows; 2559 rt::d3d12::TitleBufferWindows external_windows;
2560 std::atomic<bool> external_window_made{false}; // a window lies outside the arena: device_reachable looks there
2229 std::vector<TitleWindow> title_windows; 2561 std::vector<TitleWindow> title_windows;
2230 std::atomic<std::size_t> title_window_count{0}; // title_windows.size(), read without the mutex 2562 std::atomic<std::size_t> title_window_count{0}; // title_windows.size(), read without the mutex
2231 std::uint64_t title_window_bytes = 0; 2563 std::uint64_t title_window_bytes = 0;
@@ -2245,6 +2577,45 @@ struct DeviceState {
2245 std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views) 2577 std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views)
2246 2578
2247 rt::d3d12::GeometryViews geometry; 2579 rt::d3d12::GeometryViews geometry;
2580 // A retired geometry view: its alias ranges go, and so does every answer made through it without one
2581 // (vsharp_address and placed views take geometry_va() directly), by its CPU and its GPU-twin address.
2582 static void forget_geometry_alias(std::uintptr_t source, std::size_t size, VkDeviceSize va) {
2583 auto& aliases = leonida::title_va_aliases();
2584 aliases.remove(source, va);
2585 aliases.forget_copy(source, size, va);
2586 if (const auto twin = leonida::title_gpu_views::other_view(source)) {
2587 aliases.remove(twin, va);
2588 aliases.forget_copy(twin, size, va);
2589 }
2590 }
2591 // Before the submission's console heap slots are translated (refresh_shadows): a view retired here is answered
2592 // by nothing from now on. It is freed only after every replay in progress has recorded its submissions and those
2593 // have completed (GeometryViews::kAfterExecutes, execute_end): this submission's own lists, recorded before, and
2594 // another queue's replay that translated its slots before this retirement may still name it. A ticket read here
2595 // would be one short of this submission, which records its own only after before_execute_ (and with an idle GPU
2596 // the view would be reaped in this very call).
2597 void drain_geometry_releases() {
2598 if (!context || !geometry.has_pending_reclaim()) return;
2599 const std::uint64_t completed_ticket = geometry.has_retired() ? context->completed_retire_ticket() : 0;
2600 geometry.drain_released(*this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket,
2601 forget_geometry_alias);
2602 }
2603 // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases).
2604 static std::vector<std::uint64_t>& geometry_execute_serials() {
2605 thread_local std::vector<std::uint64_t> serials;
2606 return serials;
2607 }
2608 void geometry_execute_begin() {
2609 if (!geometry.cap()) return;
2610 geometry_execute_serials().push_back(geometry.execute_begin());
2611 }
2612 void geometry_execute_end() {
2613 auto& serials = geometry_execute_serials();
2614 if (!geometry.cap() || serials.empty()) return;
2615 const std::uint64_t serial = serials.back();
2616 serials.pop_back();
2617 geometry.execute_end(serial, [this] { return context->submitted_retire_ticket(); });
2618 }
2248 static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { 2619 static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) {
2249 using Result = rt::d3d12::GeometryCopy; 2620 using Result = rt::d3d12::GeometryCopy;
2250 if (!leonida::texture_memory_readable(reinterpret_cast<std::uintptr_t>(from), size)) return Result::unreadable; 2621 if (!leonida::texture_memory_readable(reinterpret_cast<std::uintptr_t>(from), size)) return Result::unreadable;
@@ -2334,7 +2705,9 @@ struct DeviceState {
2334 std::uint8_t* mapped{}; 2705 std::uint8_t* mapped{};
2335 if (arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) { 2706 if (arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) {
2336 mapped = arena.mapped + offset; 2707 mapped = arena.mapped + offset;
2337 } else if (!stream_windows() || !external_windows.allocate(*this, size, offset, mapped)) { 2708 } else if (stream_windows() && external_windows.allocate(*this, size, offset, mapped)) {
2709 external_window_made.store(true, std::memory_order_release);
2710 } else {
2338 ++title_window_refusals; 2711 ++title_window_refusals;
2339 log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory has no window; window KiB:", 2712 log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory has no window; window KiB:",
2340 int(std::min<std::uint64_t>(size >> 10, INT_MAX))); 2713 int(std::min<std::uint64_t>(size >> 10, INT_MAX)));
@@ -2411,8 +2784,10 @@ struct DeviceState {
2411 if (aliases.shader_va(extent.start) == extent.start) aliases.add(extent.start, extent.size, shader); 2784 if (aliases.shader_va(extent.start) == extent.start) aliases.add(extent.start, extent.size, shader);
2412 } else { 2785 } else {
2413 bool geometry_copy = false; 2786 bool geometry_copy = false;
2414 if (geometry.cap() && watch_shadow_writes() && !context->knows_buffer_va(extent.start, extent.size)) 2787 if (geometry.cap() && watch_shadow_writes() && !context->knows_buffer_va(extent.start, extent.size)) {
2415 shader = geometry.resolve(*this, extent.start, extent.size, copy_geometry), geometry_copy = shader != 0; 2788 shader = geometry.resolve(*this, extent.start, extent.size, copy_geometry);
2789 geometry_copy = shader != 0;
2790 }
2416 if (!shader) shader = make_title_window(extent.start, extent.size); 2791 if (!shader) shader = make_title_window(extent.start, extent.size);
2417 if (!shader) { 2792 if (!shader) {
2418 out = 0; 2793 out = 0;
@@ -2437,8 +2812,52 @@ struct DeviceState {
2437 return true; 2812 return true;
2438 } 2813 }
2439 2814
2815 // Whether a shader that forms heap_base + `va` reaches memory of the device's: the arena, a registered buffer (an
2816 // upload or readback heap, an import, by its VA), a geometry copy, a title window outside the arena, or the copy
2817 // of any title range (an address the layer already wrote for the title). A raw title address is none of these.
2818 // A V#'s base is 48 bits and translated shaders sign-extend it (Gen.host_addr), so a wrapped one is also tried
2819 // with its upper bits set. `buffers_checked`: the caller already asked the buffer index about `va` itself (the
2820 // resolver does). Cheapest first; title_window_mutex only once a window outside the arena exists, and never
2821 // called with it held.
2822 bool device_reachable(std::uint64_t va, bool buffers_checked = false) {
2823 if (va < arena.size) return true;
2824 const bool wrapped = va < (1ull << 48) && (va >> 47);
2825 const std::uint64_t candidates[2] = {va, wrapped ? va | ~((1ull << 48) - 1) : va};
2826 auto& aliases = leonida::title_va_aliases();
2827 for (int i = 0; i < (wrapped ? 2 : 1); ++i) {
2828 const std::uint64_t at = candidates[i];
2829 if (aliases.shader_side(at)) return true;
2830 std::uint64_t host = 0, room = 0;
2831 if (geometry.cap() && geometry.lookup(arena.address + at, host, room)) return true;
2832 if (external_window_made.load(std::memory_order_acquire)) {
2833 std::lock_guard lock(title_window_mutex);
2834 if (external_windows.lookup(arena.address + at, host, room)) return true;
2835 }
2836 if (context && !(i == 0 && buffers_checked) && context->knows_buffer_va(at)) return true;
2837 }
2838 return false;
2839 }
2840
2841 // One line per kind (and then at 2, 4, 8... of it): an address outside the title's memory that names nothing of
2842 // the device's, written as a zero-size view (a V#) or 0 (a root view) instead of a raw address.
2843 void note_unmapped(std::uint64_t va, std::uint64_t bytes) {
2844 static std::atomic<std::uint64_t> seen{0};
2845 const std::uint64_t n = seen.fetch_add(1, std::memory_order_relaxed) + 1;
2846 if (n != 1 && (n & (n - 1))) return;
2847 std::fprintf(stderr,
2848 "[rt] d3d12: address 0x%llx (%llu bytes) is neither the title's memory nor any allocation of the "
2849 "device's: the view is written with no base and no records (loads 0, stores dropped); %llu so "
2850 "far\n",
2851 static_cast<unsigned long long>(va), static_cast<unsigned long long>(bytes),
2852 static_cast<unsigned long long>(n));
2853 }
2854
2440 // Called through title_va_aliases().resolve for an address with no copy yet. False: not the title's memory. 2855 // Called through title_va_aliases().resolve for an address with no copy yet. False: not the title's memory.
2441 // True: it is, and `out` is its shader VA, 0 when no backing could be made (never the raw address). 2856 // True: it is, and `out` is its shader VA, 0 when no backing could be made (never the raw address). An address
2857 // past the arena that is not the title's memory either gets 0 too when nothing of the device's is there
2858 // (device_reachable): heap_base + such an address is no allocation, and a shader that reads or writes through it
2859 // takes an MMU fault (measured with Aftermath at world start: compute reads ~4 GiB and ~10 GiB above anything
2860 // allocated).
2442 bool resolve_title_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { 2861 bool resolve_title_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) {
2443 out = va; 2862 out = va;
2444 if (!arena.mapped || !context) return false; 2863 if (!arena.mapped || !context) return false;
@@ -2781,10 +3200,6 @@ struct DeviceState {
2781 --it; 3200 --it;
2782 return addr < it->second && (addr-it->first) % kDescriptorSize == 0; 3201 return addr < it->second && (addr-it->first) % kDescriptorSize == 0;
2783 } 3202 }
2784 // The shader-visible CBV/SRV/UAV heaps (arena offset -> end), for the scan of bound tables before a submission.
2785 std::mutex cbv_heap_mutex;
2786 std::map<VkDeviceSize, VkDeviceSize> cbv_heaps;
2787
2788 // 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, 3203 // 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,
2789 // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and 3204 // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and
2790 // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. 3205 // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time.
@@ -2807,20 +3222,99 @@ struct DeviceState {
2807 // Slots the title wrote in its own backing of this heap, if it gave the heap one. 3222 // Slots the title wrote in its own backing of this heap, if it gave the heap one.
2808 aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va)); 3223 aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va));
2809 if (sampler) return; // S# words describe sampling state. They have no buffer address to translate. 3224 if (sampler) return; // S# words describe sampling state. They have no buffer address to translate.
2810 // Each slot's V# and the counter V# in its second half, as a console heap's GPU copy (fix_vsharp): a base in 3225 for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) {
2811 // the title's memory is rebased, one nothing backs becomes zero-size instead of a GPU fault at heap_base plus 3226 auto* words = reinterpret_cast<std::uint32_t*>(arena.mapped + at);
2812 // that address. 3227 if (words[3] >> 30) continue;
2813 for (VkDeviceSize at = table_va; at + kDescriptorSize <= end; at += kDescriptorSize) { 3228 if (retry_nulled_table_slot(at, words, aliases)) continue;
2814 auto* const w = reinterpret_cast<std::uint32_t*>(arena.mapped + at); 3229 const std::uint32_t original[3] = {words[0], words[1], words[2]};
2815 fix_vsharp(w, VsharpPath::table); 3230 bool unbacked = false;
2816 fix_vsharp(w + 4, VsharpPath::table); 3231 if (!rebase_title_vsharp(words, aliases, true, &unbacked) && unbacked) {
2817 } 3232 // Title memory no window or geometry copy could back, or an address nothing backs: no base and no
3233 // records, so a shader's load returns 0 and its store is dropped rather than written at heap_base +
3234 // the raw address. The words are kept to look at again (retry_nulled_table_slot). The null form is the
3235 // one a zero-size view has (base 0, no records): base 0 is the arena's zero page, which reads 0.
3236 words[0] = 0;
3237 words[1] &= 0xFFFF0000u;
3238 words[2] = 0;
3239 note_nulled_table_slot(at, original, words[3]);
3240 }
3241 // The slot's second V# is a UAV counter (raw, 4 bytes, in the descriptor's upper 16 bytes): a store to it
3242 // at heap_base + a raw title address loses the device just as one through the buffer V# does. Nothing
3243 // retries it - a counter whose backing arrives later stays with no records until the title rewrites it.
3244 if (at + kDescriptorSize <= end) fix_vsharp(words + 4, VsharpPath::table);
3245 }
3246 }
3247
3248 // The table slots scan_title_table wrote null in place (the layer's heaps have no separate GPU copy), by arena
3249 // offset, with the words the title gave them: at each later scan that still finds the null form there, the
3250 // original is tried again, kNulledTableTries times at most, so a V# whose buffer or copy comes after the
3251 // descriptor gets its base back. A slot the title rewrote meanwhile is forgotten and scanned as new. At most
3252 // kNulledTableSlots are kept (past that a nulled slot stays null until rewritten). The null form is base 0 with no
3253 // records, as a zero-size view has; a slot holding it is recognised by the rest of the words the title gave it,
3254 // so a view Create*View wrote (also base 0) is only retried when its other words match a nulled slot's exactly.
3255 struct NulledTableSlot {
3256 std::uint32_t words[4];
3257 std::uint32_t tries;
3258 };
3259 static constexpr std::size_t kNulledTableSlots = 65536;
3260 static constexpr std::uint32_t kNulledTableTries = 16;
3261 std::mutex nulled_table_mutex;
3262 std::unordered_map<VkDeviceSize, NulledTableSlot> nulled_table_slots;
3263 std::atomic<std::size_t> nulled_table_count{0};
3264
3265 void note_nulled_table_slot(VkDeviceSize at, const std::uint32_t (&original)[3], std::uint32_t word3) {
3266 std::lock_guard lock(nulled_table_mutex);
3267 if (nulled_table_slots.size() >= kNulledTableSlots) return;
3268 nulled_table_slots[at] = {{original[0], original[1], original[2], word3}, 0};
3269 nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed);
3270 }
3271
3272 // A heap's arena range is released: what was noted in it is no longer anybody's slot.
3273 void forget_nulled_table_slots(VkDeviceSize offset, VkDeviceSize bytes) {
3274 if (!nulled_table_count.load(std::memory_order_relaxed)) return;
3275 std::lock_guard lock(nulled_table_mutex);
3276 std::erase_if(nulled_table_slots, [&](const auto& e) { return e.first - offset < bytes; });
3277 nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed);
3278 }
3279
3280 // True when `at` is a slot this scan nulled earlier and still holds that null form: tried again (and restored
3281 // when its address is backed now), so the caller moves on.
3282 bool retry_nulled_table_slot(VkDeviceSize at, std::uint32_t* words, leonida::TitleVaAliases& aliases) {
3283 if (!nulled_table_count.load(std::memory_order_relaxed)) return false;
3284 NulledTableSlot entry{};
3285 {
3286 std::lock_guard lock(nulled_table_mutex);
3287 const auto it = nulled_table_slots.find(at);
3288 if (it == nulled_table_slots.end()) return false;
3289 entry = it->second;
3290 // entry.words[2] != 0: a view the title wrote with zero records is not one this scan nulled.
3291 const bool still_null = words[0] == 0 && words[2] == 0 && entry.words[2] != 0 &&
3292 words[3] == entry.words[3] && words[1] == (entry.words[1] & 0xFFFF0000u);
3293 if (!still_null || ++it->second.tries > kNulledTableTries) {
3294 nulled_table_slots.erase(it);
3295 nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed);
3296 return still_null; // rewritten by the title: scanned as new; out of tries: left null
3297 }
3298 }
3299 std::uint32_t retry[4] = {entry.words[0], entry.words[1], entry.words[2], words[3]};
3300 bool unbacked = false;
3301 const bool rebased = rebase_title_vsharp(retry, aliases, true, &unbacked);
3302 if (!rebased && unbacked) return true; // still nothing behind it: stays null, looked at again next scan
3303 words[0] = retry[0];
3304 words[1] = retry[1];
3305 words[2] = retry[2];
3306 std::lock_guard lock(nulled_table_mutex);
3307 nulled_table_slots.erase(at);
3308 nulled_table_count.store(nulled_table_slots.size(), std::memory_order_relaxed);
3309 return true;
2818 } 3310 }
2819 3311
2820 // 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 3312 // 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
2821 // copy of that memory, in place. False for anything else: a null slot, an image, a V# already in the arena, or 3313 // copy of that memory, in place. False for anything else: a null slot, an image, a V# already in the arena, or
2822 // memory no copy could be made of. 3314 // memory no copy could be made of. `unbacked` (when given) is set for the last case: title memory with neither a
2823 bool rebase_title_vsharp(std::uint32_t* w, leonida::TitleVaAliases& aliases, bool make_window = true) { 3315 // window nor a geometry copy behind it, which the caller writes as a zero-size range.
3316 bool rebase_title_vsharp(std::uint32_t* w, leonida::TitleVaAliases& aliases, bool make_window = true,
3317 bool* unbacked = nullptr) {
2824 const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; 3318 const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3];
2825 if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) return false; // null, or not a buffer V# (TYPE, dword 3 bits 30-31) 3319 if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) return false; // null, or not a buffer V# (TYPE, dword 3 bits 30-31)
2826 const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32); 3320 const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32);
@@ -2828,6 +3322,14 @@ struct DeviceState {
2828 if (base < arena.size || (geometry.cap() && geometry.lookup(arena.address + base, host, remaining))) return false; 3322 if (base < arena.size || (geometry.cap() && geometry.lookup(arena.address + base, host, remaining))) return false;
2829 const std::uint32_t stride = (w1 >> 16) & 0x3FFFu; 3323 const std::uint32_t stride = (w1 >> 16) & 0x3FFFu;
2830 const std::uint64_t span = std::uint64_t(w2) * (stride ? stride : 1); 3324 const std::uint64_t span = std::uint64_t(w2) * (stride ? stride : 1);
3325 // A V# the layer wrote for one of its own buffers that the driver put below the arena (an upload buffer in
3326 // ReBAR memory, say): the low 48 bits of a negative offset, which the shaders read sign-extended
3327 // (vsharp_address). Not the title's memory: left as it is, never nulled.
3328 if (base & (1ull << 47)) {
3329 std::lock_guard lock(backing_mutex);
3330 if (gpu_backings.covers(arena.address + (base | ~((1ull << 48) - 1)), std::max<std::uint64_t>(span, 1)))
3331 return false;
3332 }
2831 std::uint64_t to{}; 3333 std::uint64_t to{};
2832 if (geometry.cap()) { 3334 if (geometry.cap()) {
2833 const leonida::gfx10::BufferWords words{w0, w1, w2, w3}; 3335 const leonida::gfx10::BufferWords words{w0, w1, w2, w3};
@@ -2851,22 +3353,57 @@ struct DeviceState {
2851 if (!to) to = make_window ? aliases.resolve(base, span, leonida::TitleVaAliases::table_view) 3353 if (!to) to = make_window ? aliases.resolve(base, span, leonida::TitleVaAliases::table_view)
2852 : aliases.shader_va(base, span); 3354 : aliases.shader_va(base, span);
2853 3355
2854 if (to == base || (to >> 48)) return false; 3356 // to == 0: the title's memory, and neither a window nor a geometry copy could back it, or an address that is
3357 // nobody's (resolve_title_memory). to == base: no copy was asked for (a heap scan only looks existing ones up)
3358 // or the address is left as it is; that holds only when the device can reach it (a raw title address, or one
3359 // past every allocation, cannot be). A copy whose VA does not fit the V#'s 48 bits (an import below heap_base,
3360 // off by default) cannot be named here either, and the raw base is no better. False in each case, and
3361 // `unbacked` tells the caller to write it with no records instead of leaving a base a shader would add
3362 // heap_base to.
3363 if (!to || to == base || (to >> 48)) {
3364 // The resolver (make_window) answers 0 for an address the device cannot reach, so a base it left as it
3365 // is needs no second look; a heap scan only looked existing copies up and asks here.
3366 if (unbacked) *unbacked = !to || (to >> 48) || (!make_window && !device_reachable(base));
3367 return false;
3368 }
2855 w[0] = std::uint32_t(to); 3369 w[0] = std::uint32_t(to);
2856 w[1] = (w1 & 0xFFFF0000u) | std::uint32_t((to >> 32) & 0xFFFFu); 3370 w[1] = (w1 & 0xFFFF0000u) | std::uint32_t((to >> 32) & 0xFFFFu);
2857 return true; 3371 return true;
2858 } 3372 }
2859 3373
2860 // Indexed by actual Vulkan address, never by a placed buffer's CPU address. 3374 // Indexed by actual Vulkan address, never by a placed buffer's CPU address.
3375 static bool filter_heap_releases() {
3376 static const bool on = [] {
3377 const auto* v = std::getenv("LEONIDA_CONSOLE_RELEASE_FILTER");
3378 return v && std::strcmp(v, "1") == 0;
3379 }();
3380 return on;
3381 }
3382 leonida::DescriptorRangeChanges backing_changes;
2861 std::atomic<uint64_t> released_backings{}; 3383 std::atomic<uint64_t> released_backings{};
3384 std::atomic<uint64_t> backing_generation{}; // every add and release
2862 std::mutex backing_mutex; 3385 std::mutex backing_mutex;
2863 leonida::BufferVaIndex<uint64_t> gpu_backings; 3386 leonida::BufferVaIndex<uint64_t> gpu_backings;
3387 // A title-window or geometry-copy block was destroyed (TitleBufferWindows::destroy_block; its GPU work completed):
3388 // as for a released backing, the backed table cuts it and the key entries and heap slots answering into it go at
3389 // the next refresh, so no table names the freed memory.
3390 void title_block_gone(VkDeviceAddress address, VkDeviceSize bytes) {
3391 std::lock_guard lock(backing_mutex);
3392 if (filter_heap_releases()) backing_changes.record(address, bytes);
3393 backing_generation.fetch_add(1, std::memory_order_relaxed);
3394 released_backings.fetch_add(1, std::memory_order_release);
3395 if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes);
3396 }
2864 void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) { 3397 void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) {
2865 std::lock_guard lock(backing_mutex); 3398 std::lock_guard lock(backing_mutex);
3399 if (filter_heap_releases()) backing_changes.record(address, bytes);
3400 backing_generation.fetch_add(1, std::memory_order_relaxed);
2866 if (add) gpu_backings.insert(address, bytes, id); 3401 if (add) gpu_backings.insert(address, bytes, id);
2867 else { 3402 else {
2868 gpu_backings.erase(address, id); 3403 gpu_backings.erase(address, id);
2869 released_backings.fetch_add(1, std::memory_order_release); 3404 released_backings.fetch_add(1, std::memory_order_release);
3405 // LEONIDA_CONSOLE_HEAP_GPU: the key entries answering into it go at the next refresh.
3406 if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes);
2870 } 3407 }
2871 } 3408 }
2872 3409
@@ -2898,30 +3435,35 @@ struct DeviceState {
2898 uint64_t host{}, room{}; 3435 uint64_t host{}, room{};
2899 return geometry.cap() && geometry.lookup(bda, host, room) && room >= bytes; 3436 return geometry.cap() && geometry.lookup(bda, host, room) && room >= bytes;
2900 }; 3437 };
3438 const auto path = [this](unsigned p) { vsharp_paths[p].fetch_add(1, std::memory_order_relaxed); };
2901 uint64_t to{}, room{}; 3439 uint64_t to{}, room{};
2902 if (aliases.range_of(base, to, room)) { 3440 if (aliases.range_of(base, to, room)) {
2903 if (!to || room < bytes || !backed(to)) return 0; 3441 if (!to || room < bytes || !backed(to)) return path(1), 0;
2904 aliases.note_translation(kind); 3442 aliases.note_translation(kind);
2905 return to; 3443 return path(0), to;
2906 } 3444 }
2907 // An already rewritten descriptor carries only the low 48 bits. 3445 // An already rewritten descriptor carries only the low 48 bits.
2908 uint64_t offset = base; 3446 uint64_t offset = base;
2909 if (signed_vsharp_offsets() && base <= mask && (base & (1ull << 47))) offset |= ~mask; 3447 if (signed_vsharp_offsets() && base <= mask && (base & (1ull << 47))) offset |= ~mask;
2910 if (backed(offset)) return offset; 3448 if (backed(offset)) return path(2), offset;
2911 // Read the other way: bit 47 as a sign, for a below-arena buffer's V# the layer wrote itself. 3449 // Read the other way: bit 47 as a sign, for a below-arena buffer's V# the layer wrote itself.
2912 if (offset == base && base <= mask && (base & (1ull << 47)) && backed(base | ~mask)) return base | ~mask; 3450 if (offset == base && base <= mask && (base & (1ull << 47)) && backed(base | ~mask)) return base | ~mask;
2913 if (try_geometry) { 3451 if (try_geometry) {
2914 to = geometry_va(base, bytes, false); 3452 to = geometry_va(base, bytes, false);
2915 if (to && encodable(to)) return to; 3453 if (to && encodable(to)) return path(3), to;
2916 } 3454 }
2917 uint64_t lo{}, hi{}; 3455 uint64_t lo{}, hi{};
2918 if (make_window && aliases.title_memory(base, lo, hi) && bytes <= hi - base) { 3456 if (make_window && aliases.title_memory(base, lo, hi) && bytes <= hi - base) {
2919 to = aliases.resolve(base, bytes, kind); 3457 to = aliases.resolve(base, bytes, kind);
2920 uint64_t mapped{}; 3458 uint64_t mapped{};
2921 if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to)) return to; 3459 if (to && aliases.range_of(base, mapped, room) && mapped == to && room >= bytes && backed(to))
3460 return path(4), to;
2922 } 3461 }
2923 return 0; 3462 return path(5), 0;
2924 } 3463 }
3464 // vsharp_address's outcomes (diagnostics): alias hit, alias refused, arena VA, geometry copy, window, none.
3465 static constexpr unsigned kVsharpPathCount = 6;
3466 std::array<std::atomic<std::uint64_t>, kVsharpPathCount> vsharp_paths{};
2925 3467
2926 VsharpResult fix_vsharp(uint32_t* w, VsharpPath path) { 3468 VsharpResult fix_vsharp(uint32_t* w, VsharpPath path) {
2927 if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer 3469 if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer
@@ -3086,6 +3628,7 @@ struct DeviceState {
3086 static_cast<unsigned long long>(arena.blocks.free_bytes() >> 10)); 3628 static_cast<unsigned long long>(arena.blocks.free_bytes() >> 10));
3087 return false; 3629 return false;
3088 } 3630 }
3631 // The V# writers look this range up by device address (vsharp_address): an allocation registers its backing.
3089 backing(arena.address + out, bytes, out, true); 3632 backing(arena.address + out, bytes, out, true);
3090 ++arena.allocations; 3633 ++arena.allocations;
3091 arena.in_use += bytes; 3634 arena.in_use += bytes;
@@ -3107,21 +3650,29 @@ struct DeviceState {
3107 (unsigned long long)va, (unsigned long long)bytes); 3650 (unsigned long long)va, (unsigned long long)bytes);
3108 } 3651 }
3109 3652
3110 // Printed once at device release, so a run reports the size the arena needs. 3653 // Printed once at device release, so a run reports the size the arena needs; the arena line also about once a
3654 // minute with a console heap's log (report_arena_peak), since a run cut short never releases its device.
3111 void report_arena() { 3655 void report_arena() {
3656 report_arena_peak();
3657 report_title_memory();
3658 }
3659 void report_arena_peak() {
3112 std::lock_guard lock(arena.mutex); 3660 std::lock_guard lock(arena.mutex);
3113 if (!arena.size) return; 3661 if (!arena.size) return;
3114 const double mib = 1.0 / (1 << 20); 3662 const double mib = 1.0 / (1 << 20);
3115 std::fprintf(stderr, 3663 std::fprintf(stderr,
3116 "[rt] d3d12: GPU address arena: peak end %.1f of %.1f MiB (%.1f%%), peak live %.1f MiB " 3664 "[rt] d3d12: GPU address arena: peak end %.1f of %.1f MiB (%.1f%%), peak live %.1f MiB "
3117 "(buffers %.1f, descriptor heaps %.1f, shaders %.1f, heaps %.1f), %llu allocations, %llu refused; " 3665 "(buffers %.1f, descriptor heaps %.1f of which null guards %.1f now, shaders %.1f, heaps %.1f), %llu "
3118 "%zu free blocks (largest %.1f MiB, %.1f MiB free)\n", 3666 "allocations, %llu refused; %zu free blocks (largest %.1f MiB, %.1f MiB free)\n",
3119 arena.peak_end * mib, arena.size * mib, 100.0 * double(arena.peak_end) / double(arena.size), 3667 arena.peak_end * mib, arena.size * mib, 100.0 * double(arena.peak_end) / double(arena.size),
3120 arena.peak_in_use * mib, arena.use_peak[arena_buffer] * mib, 3668 arena.peak_in_use * mib, arena.use_peak[arena_buffer] * mib,
3121 arena.use_peak[arena_descriptor_heap] * mib, arena.use_peak[arena_shader] * mib, 3669 arena.use_peak[arena_descriptor_heap] * mib,
3670 double(arena_guard_bytes.load(std::memory_order_relaxed)) * mib, arena.use_peak[arena_shader] * mib,
3122 arena.use_peak[arena_heap] * mib, 3671 arena.use_peak[arena_heap] * mib,
3123 (unsigned long long)arena.allocations, (unsigned long long)arena.failures, arena.blocks.count(), 3672 (unsigned long long)arena.allocations, (unsigned long long)arena.failures, arena.blocks.count(),
3124 arena.blocks.largest().size * mib, arena.blocks.free_bytes() * mib); 3673 arena.blocks.largest().size * mib, arena.blocks.free_bytes() * mib);
3674 }
3675 void report_title_memory() {
3125 { 3676 {
3126 std::lock_guard windows(title_window_mutex); 3677 std::lock_guard windows(title_window_mutex);
3127 const auto geometry_spans = std::count_if(pool_spans.begin(), pool_spans.end(), 3678 const auto geometry_spans = std::count_if(pool_spans.begin(), pool_spans.end(),
@@ -3149,6 +3700,8 @@ struct DeviceState {
3149 backing(arena.address + offset, bytes, offset, false); 3700 backing(arena.address + offset, bytes, offset, false);
3150 arena.in_use -= bytes; 3701 arena.in_use -= bytes;
3151 arena.use_in_use[use] -= bytes; 3702 arena.use_in_use[use] -= bytes;
3703 // A heap copy re-fixes its slots when a backing has gone (released_backings): the range is no view's.
3704 backing(arena.address + offset, bytes, offset, false);
3152 } 3705 }
3153 if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) { 3706 if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) {
3154 std::fprintf(stderr, 3707 std::fprintf(stderr,
@@ -3160,6 +3713,7 @@ struct DeviceState {
3160 static_cast<unsigned long long>(arena.blocks.free_bytes() >> 10), 3713 static_cast<unsigned long long>(arena.blocks.free_bytes() >> 10),
3161 static_cast<unsigned long long>(arena.blocks.faults())); 3714 static_cast<unsigned long long>(arena.blocks.faults()));
3162 arena_report_suppressed("arena releases"); 3715 arena_report_suppressed("arena releases");
3716
3163 } 3717 }
3164 check_arena("a release"); 3718 check_arena("a release");
3165 } 3719 }
@@ -3195,8 +3749,8 @@ struct DeviceState {
3195 std::uint64_t console_va = 0; 3749 std::uint64_t console_va = 0;
3196 VkDeviceSize bytes = 0; 3750 VkDeviceSize bytes = 0;
3197 std::uint64_t shader_va = 0; // where shaders read it 3751 std::uint64_t shader_va = 0; // where shaders read it
3198 VkDeviceSize guard = 0; 3752 VkDeviceSize guard = 0; // null bytes after the GPU copy (heap_guard_bytes/heap_guard_for), its allocation
3199 bool resource_heap = false; 3753 bool resource_heap = false; // a CBV/SRV/UAV heap; a sampler heap's S#s are copied as written
3200 bool imported = false; 3754 bool imported = false;
3201 std::uint8_t* copy = nullptr; // writable GPU mirror of the console heap 3755 std::uint8_t* copy = nullptr; // writable GPU mirror of the console heap
3202 // Keep large scratch allocations out of the low addresses the title can use for its heap. 3756 // Keep large scratch allocations out of the low addresses the title can use for its heap.
@@ -3208,17 +3762,25 @@ struct DeviceState {
3208 VkDeviceMemory memory = VK_NULL_HANDLE; 3762 VkDeviceMemory memory = VK_NULL_HANDLE;
3209 std::uint64_t pin = 0; // the imported pages' leonida::kernel_writes pin while `memory` lives 3763 std::uint64_t pin = 0; // the imported pages' leonida::kernel_writes pin while `memory` lives
3210 std::size_t scan_at = 0; // the next slot the T# scan reads 3764 std::size_t scan_at = 0; // the next slot the T# scan reads
3211 uint64_t checked_generation{}, alias_generation{}; 3765 uint64_t checked_generation{}, alias_generation{}, backing_cursor{}, alias_cursor{};
3766 uint64_t release_sweeps{}, release_candidates{}, release_fixes{}, release_rebases{}, release_full{};
3212 // copy 3767 // copy
3213 bool identity = false; 3768 bool identity = false;
3214 ShadowPagesPtr pages; 3769 ShadowPagesPtr pages;
3215 std::vector<std::uint8_t> mirror; // the title's bytes as the tracker last copied them 3770 std::vector<std::uint8_t> mirror; // the title's bytes as the tracker last copied them
3216 std::vector<std::uint8_t> made; // the title's bytes each arena slot was last made from 3771 std::vector<std::uint8_t> made; // the title's bytes each arena slot was last made from
3217 std::vector<std::uint8_t> retry; // per slot: not settled yet (fix_console_slot), in `retries` 3772 std::vector<std::uint8_t> retry; // per slot: not settled yet (fix_console_slot), in `retries`
3773 leonida::ConsoleHeapVsharpSlots live_vsharps; // slots whose GPU copy holds a live buffer V#
3218 std::vector<std::uint32_t> retries; 3774 std::vector<std::uint32_t> retries;
3219 std::set<std::uint32_t> empty_slots; 3775 std::set<std::uint32_t> empty_slots;
3220 std::uint32_t next_empty = 0; 3776 std::uint32_t next_empty = 0;
3221 std::size_t retry_at = 0; // where retry_console_slots goes on 3777 std::size_t retry_at = 0; // where retry_console_slots goes on
3778 // V#s naming an address nothing backs that is not the title's memory: null in the copy, and looked at again a
3779 // few times (kUnmappedTries, at most kUnmappedRetrySlots a submission) in case their buffer is made after the
3780 // descriptor.
3781 std::vector<std::uint8_t> unmapped_tries; // per slot: 0, or the looks so far (it is in `unmapped`)
3782 std::vector<std::uint32_t> unmapped;
3783 std::size_t unmapped_at = 0;
3222 // fix_console_slots' budget, for the current refresh, and the slots it nulled since the last log line 3784 // fix_console_slots' budget, for the current refresh, and the slots it nulled since the last log line
3223 std::chrono::steady_clock::time_point fix_start{}; 3785 std::chrono::steady_clock::time_point fix_start{};
3224 bool fix_over = false; 3786 bool fix_over = false;
@@ -3229,11 +3791,52 @@ struct DeviceState {
3229 // Since the last log line. 3791 // Since the last log line.
3230 std::uint64_t copied = 0, vsharps = 0, unbacked = 0, retried = 0; 3792 std::uint64_t copied = 0, vsharps = 0, unbacked = 0, retried = 0;
3231 std::uint64_t images[5] = {}; // by TitleImage 3793 std::uint64_t images[5] = {}; // by TitleImage
3794 std::map<std::string, std::uint64_t> refused_reasons;
3232 double ms = 0, pages_ms = 0, fix_ms = 0, retry_ms = 0; // ms: all; the others its parts 3795 double ms = 0, pages_ms = 0, fix_ms = 0, retry_ms = 0; // ms: all; the others its parts
3796 // Changed slots by class (before the fix budget), since the last log line: all-zero, V# pair, T#, other
3797 // words; V# halves whose 16 bytes were seen before (a direct-mapped memo of 65536 keys, so a lower bound of
3798 // how often an exact-key translation would be found again); rescans after a backing release and their cost.
3799 std::uint64_t changed[4] = {}, vsharp_halves = 0, vsharp_repeats = 0;
3800 std::uint64_t rescans = 0, rescanned = 0;
3801 double rescan_ms = 0;
3802 std::vector<std::array<std::uint32_t, 4>> seen_keys;
3803 // LEONIDA_CONSOLE_HEAP_GPU (DeviceState::attach_console_heap_gpu): the translation pass's index of this heap
3804 // (-1: fixed on the CPU), the import of `input` the pass reads, the slots holding a V# pair (translated again
3805 // when a backing goes), and the slots queued for the pass since the last log line.
3806 int gpu = -1;
3807 VkBuffer input_buffer = VK_NULL_HANDLE;
3808 VkDeviceMemory input_memory = VK_NULL_HANDLE;
3809 std::vector<std::uint64_t> vsharp_bits;
3810 std::uint64_t gpu_queued = 0;
3811 std::uint32_t gpu_high = 0; // one past the highest slot the title has written (a rescan's range)
3233 }; 3812 };
3234 std::mutex console_heap_mutex; // taken before title_window_mutex, shadow_mutex and descriptor_mutex 3813 std::mutex console_heap_mutex; // taken before title_window_mutex, shadow_mutex and descriptor_mutex
3235 std::vector<std::unique_ptr<ConsoleHeap>> console_heaps; 3814 std::vector<std::unique_ptr<ConsoleHeap>> console_heaps;
3236 3815
3816 // Null slots after a shader-visible resource heap's GPU copy. A directly indexed heap is read at
3817 // heap VA + index * 32 with the index from data (docs/d3d12_vulkan.md section 3.4), and nothing bounds it: an
3818 // index past the heap read whatever the arena held after it, and a buffer V# made of those bytes sent loads and
3819 // stores to heap_base + garbage (GPU MMU faults at world start). With the guard such an index reads a null
3820 // descriptor instead (loads 0, stores dropped). As VIctory does for its host heaps (crates/victory-shader/src/emit
3821 // "Heap indices": at least 2^21 slots, those past the title's own null).
3822 // Two shapes: `heap_guard_bytes` is the fixed reach a directly indexed heap is given (2^21 slots, bounded so the
3823 // heap and its guard stay inside a 32-bit shader offset, LEONIDA_HEAP_GUARD_MB overrides), and `heap_guard_for`
3824 // is the per-heap guard a console heap's copy takes - as large as the heap, at least 1 MiB, at most
3825 // `heap_guard_cap()` (64 MiB by default, 0: no guard). Either comes out of the arena every default-heap buffer is
3826 // placed in; a heap the arena has no room for with its guard is made without one (logged).
3827 static constexpr VkDeviceSize kHeapGuardFloor = VkDeviceSize(1) << 20;
3828 static VkDeviceSize heap_guard_cap() {
3829 static const VkDeviceSize bytes = [] {
3830 constexpr VkDeviceSize fallback = VkDeviceSize(64) << 20;
3831 char text[16] = {};
3832 const DWORD n = GetEnvironmentVariableA("LEONIDA_HEAP_GUARD_MB", text, sizeof(text));
3833 if (n == 0 || n >= sizeof(text)) return fallback;
3834 for (DWORD i = 0; i < n; ++i)
3835 if (text[i] < '0' || text[i] > '9') return fallback; // "-1" and the like: the default
3836 return VkDeviceSize(std::min<unsigned long long>(std::strtoull(text, nullptr, 10), 1024)) << 20;
3837 }();
3838 return bytes;
3839 }
3237 static constexpr VkDeviceSize kHeapIndexReach = VkDeviceSize(1) << 26; // 2^21 slots of 32 bytes 3840 static constexpr VkDeviceSize kHeapIndexReach = VkDeviceSize(1) << 26; // 2^21 slots of 32 bytes
3238 static VkDeviceSize heap_guard_bytes() { 3841 static VkDeviceSize heap_guard_bytes() {
3239 static const VkDeviceSize bytes = [] { 3842 static const VkDeviceSize bytes = [] {
@@ -3244,6 +3847,17 @@ struct DeviceState {
3244 }(); 3847 }();
3245 return bytes; 3848 return bytes;
3246 } 3849 }
3850 // The null bytes after a heap of `bytes`: as many as the heap, at least `floor`, at most heap_guard_cap(); grown so
3851 // heap and guard together end on a multiple of `align`. 0 with no cap.
3852 static VkDeviceSize heap_guard_for(VkDeviceSize bytes, VkDeviceSize floor, VkDeviceSize align) {
3853 const VkDeviceSize cap = heap_guard_cap();
3854 if (!cap || !bytes) return 0;
3855 VkDeviceSize guard = std::min(std::max(bytes, floor), cap);
3856 if (align > 1) guard = (bytes + guard + align - 1) / align * align - bytes;
3857 return guard;
3858 }
3859 std::atomic<std::uint64_t> arena_guard_bytes{0}; // the heap guards in the arena now (report_arena)
3860
3247 3861
3248 // [start, start + bytes) of the arena, exactly. False when any of it is taken or past the arena. 3862 // [start, start + bytes) of the arena, exactly. False when any of it is taken or past the arena.
3249 bool arena_allocate_at(VkDeviceSize start, VkDeviceSize bytes, ArenaUse use) { 3863 bool arena_allocate_at(VkDeviceSize start, VkDeviceSize bytes, ArenaUse use) {
@@ -3261,17 +3875,34 @@ struct DeviceState {
3261 } 3875 }
3262 3876
3263 // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above. True when it is settled: not a 3877 // Slot `slot` of a heap copy, as the title wrote it, fixed up as described above. True when it is settled: not a
3264 // T# whose texture is still to come, nor a V# into the title's memory that got no copy. 3878 // T# whose texture is still to come, nor a V# into the title's memory that got no copy. `unmapped` (when given) is
3265 bool fix_console_slot(ConsoleHeap& heap, std::size_t slot) { 3879 // set for a V# written null because its base is neither the title's memory nor anything of the device's: settled,
3880 // but its buffer may still be made (the round-robin probe in refresh_console_heap). A sampler heap holds S#s:
3881 // copied as written.
3882 bool fix_console_slot(ConsoleHeap& heap, std::size_t slot, bool* unmapped = nullptr) {
3266 std::uint32_t w[kDescriptorSize / 4]; 3883 std::uint32_t w[kDescriptorSize / 4];
3267 std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize); 3884 std::memcpy(w, heap.previous + slot * kDescriptorSize, kDescriptorSize);
3268 bool settled = true, empty = false; 3885 bool settled = true, empty = false;
3269 if (!(w[3] >> 30)) { 3886 if (unmapped) *unmapped = false;
3270 const auto path = heap.scratch ? VsharpPath::scratch : VsharpPath::shadow; 3887 const VsharpPath path = heap.scratch ? VsharpPath::scratch : VsharpPath::shadow;
3271 const auto result = fix_vsharp(w, path); 3888 if (!heap.resource_heap || !(w[0] | w[1] | w[2] | w[3])) {
3272 const auto counter = fix_vsharp(w + 4, path); 3889 // A sampler heap holds S#s (copied as written); an all-zero slot stays null.
3890 } else if (!(w[3] >> 30)) {
3891 // A buffer V#: rewritten to the address its bytes are backed at (fix_vsharp: the console shadow, or the
3892 // console scratch an imported heap rewrites). A base nothing backs is written with no base and no records,
3893 // settled, and left for the bounded round-robin probe in refresh_console_heap in case its buffer is made
3894 // after the descriptor.
3895 const VsharpResult result = fix_vsharp(w, path);
3273 if (result == VsharpResult::rebased) ++heap.vsharps; 3896 if (result == VsharpResult::rebased) ++heap.vsharps;
3274 if (result == VsharpResult::empty || counter == VsharpResult::empty) { 3897 if (result == VsharpResult::empty) {
3898 // Only the GPU copy changes; the title's bytes (heap.previous) stay as written.
3899 ++heap.unbacked;
3900 empty = true;
3901 }
3902 // The slot's second V# is a UAV counter (raw, 4 bytes, in the descriptor's upper 16 bytes): a store to it at
3903 // heap_base + a raw title address loses the device just as one through the buffer V# does. A counter with
3904 // no backing is nulled and left to retry_console_slots.
3905 if (fix_vsharp(w + 4, path) == VsharpResult::empty) {
3275 ++heap.unbacked; 3906 ++heap.unbacked;
3276 empty = true; 3907 empty = true;
3277 } 3908 }
@@ -3281,12 +3912,19 @@ struct DeviceState {
3281 if (leonida::gfx10::is_image(words)) { 3912 if (leonida::gfx10::is_image(words)) {
3282 const char* why = nullptr; 3913 const char* why = nullptr;
3283 const TitleImage result = bind_title_image(*this, words, &why); 3914 const TitleImage result = bind_title_image(*this, words, &why);
3284 if (result == TitleImage::unknown || result == TitleImage::refused) 3915 if (result == TitleImage::unknown || result == TitleImage::refused) {
3285 note_refused_tsharp(heap, slot * kDescriptorSize, words, why); 3916 note_refused_tsharp(heap, slot * kDescriptorSize, words, why);
3917 if (result == TitleImage::refused)
3918 ++heap.refused_reasons[why ? why : "?"];
3919 }
3286 ++heap.images[unsigned(result)]; 3920 ++heap.images[unsigned(result)];
3287 settled = result != TitleImage::unknown && result != TitleImage::refused; 3921 settled = result != TitleImage::unknown && result != TitleImage::refused;
3288 if (result == TitleImage::not_tsharp) std::memset(w, 0, 16); 3922 if (result == TitleImage::not_tsharp) std::memset(w, 0, 16);
3289 } else { 3923 } else {
3924 // Neither a buffer V# (TYPE is not 0) nor a T# the layer can decode: data the title keeps in the slot.
3925 // No image is found by these words (the bindless lookup misses, as for a null T#), but a shader that
3926 // takes the slot as a V# (an index from data, or one past what the title filled) adds heap_base to
3927 // words that name nothing: in the GPU copy the slot is null, and left to retry_console_slots.
3290 ++heap.images[unsigned(TitleImage::not_tsharp)]; 3928 ++heap.images[unsigned(TitleImage::not_tsharp)];
3291 std::memset(w, 0, 16); 3929 std::memset(w, 0, 16);
3292 } 3930 }
@@ -3294,9 +3932,38 @@ struct DeviceState {
3294 if (empty) heap.empty_slots.insert(std::uint32_t(slot)); 3932 if (empty) heap.empty_slots.insert(std::uint32_t(slot));
3295 else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot)); 3933 else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot));
3296 std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize); 3934 std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize);
3935 heap.live_vsharps.set(slot, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w));
3297 return settled; 3936 return settled;
3298 } 3937 }
3299 3938
3939 // Diagnostics only: the class of a changed slot, and whether its V# halves were seen before (ConsoleHeap::changed).
3940 static void note_changed_slot(ConsoleHeap& heap, const std::uint8_t* bytes) {
3941 std::uint32_t w[8];
3942 std::memcpy(w, bytes, sizeof(w));
3943 if (!(w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7])) {
3944 ++heap.changed[0];
3945 return;
3946 }
3947 if (w[3] >> 30) {
3948 leonida::gfx10::ImageWords words;
3949 std::memcpy(words.data(), w, sizeof(words));
3950 ++heap.changed[leonida::gfx10::is_image(words) ? 2 : 3];
3951 return;
3952 }
3953 ++heap.changed[1];
3954 if (heap.seen_keys.empty()) heap.seen_keys.resize(65536);
3955 for (int half = 0; half < 2; ++half) {
3956 const std::uint32_t* k = w + 4 * half;
3957 if (!k[2]) continue; // no records: nothing to translate
3958 ++heap.vsharp_halves;
3959 std::uint32_t h = 2166136261u;
3960 for (int i = 0; i < 4; ++i) h = (h ^ k[i]) * 16777619u;
3961 auto& entry = heap.seen_keys[h & 0xffffu];
3962 if (entry[0] == k[0] && entry[1] == k[1] && entry[2] == k[2] && entry[3] == k[3]) ++heap.vsharp_repeats;
3963 else entry = {k[0], k[1], k[2], k[3]};
3964 }
3965 }
3966
3300 // The slots on [offset, offset + bytes) of a heap copy's mirror, just brought up to date: each that differs from 3967 // The slots on [offset, offset + bytes) of a heap copy's mirror, just brought up to date: each that differs from
3301 // what its arena slot was made from is written there and fixed up. 3968 // what its arena slot was made from is written there and fixed up.
3302 // LEONIDA_CONSOLE_FIX_US limits the fixing in one submission (0, the default: no limit). Past it a changed slot is 3969 // LEONIDA_CONSOLE_FIX_US limits the fixing in one submission (0, the default: no limit). Past it a changed slot is
@@ -3320,11 +3987,14 @@ struct DeviceState {
3320 const std::size_t slot = at / kDescriptorSize; 3987 const std::size_t slot = at / kDescriptorSize;
3321 if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue; 3988 if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue;
3322 std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize); 3989 std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize);
3990 if (heap.unmapped_tries[slot]) heap.unmapped_tries[slot] = 1; // new words: their looks start over
3991 note_changed_slot(heap, heap.previous + at);
3323 if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) && 3992 if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) &&
3324 std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) 3993 std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us))
3325 heap.fix_over = true; 3994 heap.fix_over = true;
3326 if (heap.fix_over) { 3995 if (heap.fix_over) {
3327 std::memset(heap.copy + at, 0, kDescriptorSize); 3996 std::memset(heap.copy + at, 0, kDescriptorSize);
3997 heap.live_vsharps.clear(slot);
3328 ++heap.deferred_fixes; 3998 ++heap.deferred_fixes;
3329 if (!heap.retry[slot]) { 3999 if (!heap.retry[slot]) {
3330 heap.retry[slot] = 1; 4000 heap.retry[slot] = 1;
@@ -3332,13 +4002,49 @@ struct DeviceState {
3332 } 4002 }
3333 continue; 4003 continue;
3334 } 4004 }
3335 if (fix_console_slot(heap, slot)) { 4005 bool unmapped = false;
4006 if (fix_console_slot(heap, slot, &unmapped)) {
3336 heap.retry[slot] = 0; 4007 heap.retry[slot] = 0;
3337 } else if (!heap.retry[slot]) { 4008 } else if (!heap.retry[slot]) {
3338 heap.retry[slot] = 1; 4009 heap.retry[slot] = 1;
3339 heap.retries.push_back(std::uint32_t(slot)); 4010 heap.retries.push_back(std::uint32_t(slot));
3340 } 4011 }
4012 if (unmapped && !heap.unmapped_tries[slot]) {
4013 heap.unmapped_tries[slot] = 1;
4014 heap.unmapped.push_back(std::uint32_t(slot));
4015 }
4016 }
4017 }
4018
4019 // The V#s fix_console_slot wrote null because nothing backs their base: looked at again, round robin, at most
4020 // kUnmappedRetrySlots a submission, each kUnmappedTries times at most. A descriptor the title wrote before making
4021 // its buffer (or a buffer another thread registers just after) then gets its base back; one that stays unmapped
4022 // drops out of the list, so data the title keeps in its heap does not cost a lookup at every submission.
4023 static constexpr std::size_t kUnmappedRetrySlots = 2048;
4024 static constexpr std::uint8_t kUnmappedTries = 4;
4025 void retry_unmapped_slots(ConsoleHeap& heap) {
4026 std::size_t i = heap.unmapped_at;
4027 // Each entry once a submission at most: the looks are a submission apart.
4028 const std::size_t visits = std::min(kUnmappedRetrySlots, heap.unmapped.size());
4029 for (std::size_t visited = 0; visited < visits && !heap.unmapped.empty(); ++visited) {
4030 if (i >= heap.unmapped.size()) i = 0;
4031 const std::uint32_t slot = heap.unmapped[i];
4032 // Zeroed since (unmapped_tries reset), reachable now, or out of looks: out of the list.
4033 bool done = !heap.unmapped_tries[slot];
4034 if (!done) {
4035 bool unmapped = false;
4036 fix_console_slot(heap, slot, &unmapped);
4037 done = !unmapped || ++heap.unmapped_tries[slot] > kUnmappedTries;
4038 }
4039 if (done) {
4040 heap.unmapped_tries[slot] = 0;
4041 heap.unmapped[i] = heap.unmapped.back();
4042 heap.unmapped.pop_back();
4043 } else {
4044 ++i;
4045 }
3341 } 4046 }
4047 heap.unmapped_at = i;
3342 } 4048 }
3343 4049
3344 // The slots of a heap copy not settled yet: fixed again, and kept while they are still not. Round robin, for at 4050 // The slots of a heap copy not settled yet: fixed again, and kept while they are still not. Round robin, for at
@@ -3375,28 +4081,14 @@ struct DeviceState {
3375 heap.retried += visited; 4081 heap.retried += visited;
3376 } 4082 }
3377 4083
3378 // The first refused T#s of each reason, with where they sit in the heap and their words, and a count of the
3379 // distinct slots refused (a slot is scanned again every pass over the heap).
3380 void note_refused_tsharp(ConsoleHeap& heap, std::size_t offset, const leonida::gfx10::ImageWords& words, 4084 void note_refused_tsharp(ConsoleHeap& heap, std::size_t offset, const leonida::gfx10::ImageWords& words,
3381 const char* why) { 4085 const char* why) {
3382 static std::mutex mutex; 4086 unbound_tsharp_tracker().note(heap.console_va, offset, words, why);
3383 static std::map<std::string, unsigned> logged;
3384 static std::set<std::size_t> slots;
3385 std::lock_guard lock(mutex);
3386 if (slots.size() >= 262144) return; // enough to say how many
3387 const bool fresh = slots.insert(offset).second;
3388 unsigned& n = logged[why ? why : "?"];
3389 if (!fresh || n >= 6) return;
3390 ++n;
3391 std::fprintf(stderr,
3392 "[rt] d3d12: unbound T# in console heap 0x%llx at +0x%zx (%zu distinct slots so far): %s: "
3393 "%08x %08x %08x %08x %08x %08x %08x %08x\n",
3394 static_cast<unsigned long long>(heap.console_va), offset, slots.size(), why ? why : "?", words[0],
3395 words[1], words[2], words[3], words[4], words[5], words[6], words[7]);
3396 } 4087 }
3397 4088
3398 void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held 4089 void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held
3399 if (heap.imported) return; // directly imported sampler heap 4090 if (heap.imported) return; // directly imported sampler heap
4091 if (heap.gpu >= 0) return refresh_console_heap_gpu(heap);
3400 using clock = std::chrono::steady_clock; 4092 using clock = std::chrono::steady_clock;
3401 const auto ms = [](clock::time_point a, clock::time_point b) { 4093 const auto ms = [](clock::time_point a, clock::time_point b) {
3402 return std::chrono::duration<double, std::milli>(b - a).count(); 4094 return std::chrono::duration<double, std::milli>(b - a).count();
@@ -3409,7 +4101,11 @@ struct DeviceState {
3409 const auto first = std::uint32_t(offset / kDescriptorSize); 4101 const auto first = std::uint32_t(offset / kDescriptorSize);
3410 const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); 4102 const auto end = std::uint32_t((offset + bytes) / kDescriptorSize);
3411 heap.empty_slots.erase(heap.empty_slots.lower_bound(first), heap.empty_slots.lower_bound(end)); 4103 heap.empty_slots.erase(heap.empty_slots.lower_bound(first), heap.empty_slots.lower_bound(end));
3412 for (auto slot = first; slot < end; ++slot) heap.retry[slot] = 0; 4104 for (auto slot = first; slot < end; ++slot) {
4105 heap.retry[slot] = 0;
4106 heap.unmapped_tries[slot] = 0;
4107 }
4108 heap.live_vsharps.clear_range(first, end);
3413 }); 4109 });
3414 const auto t1 = clock::now(); 4110 const auto t1 = clock::now();
3415 heap.fix_start = t1; 4111 heap.fix_start = t1;
@@ -3421,17 +4117,54 @@ struct DeviceState {
3421 if (heap.resource_heap && (generation != heap.checked_generation || alias_generation != heap.alias_generation)) { 4117 if (heap.resource_heap && (generation != heap.checked_generation || alias_generation != heap.alias_generation)) {
3422 heap.alias_generation = alias_generation; 4118 heap.alias_generation = alias_generation;
3423 heap.checked_generation = generation; 4119 heap.checked_generation = generation;
4120 leonida::DescriptorRanges backing, aliases;
4121 bool filtered = filter_heap_releases();
4122 if (filtered) {
4123 {
4124 std::lock_guard lock(backing_mutex);
4125 filtered = backing_changes.read(heap.backing_cursor, backing);
4126 }
4127 filtered &= leonida::title_va_aliases().changed_ranges(heap.alias_cursor, aliases);
4128 backing.merge();
4129 aliases.merge();
4130 }
4131 ++heap.release_sweeps;
4132 heap.release_full += !filtered;
4133 const auto bda = [&](uint64_t base) {
4134 if (signed_vsharp_offsets() && (base & (1ull << 47))) base |= ~((1ull << 48)-1);
4135 return arena.address + base;
4136 };
4137 const auto affected = [&](const uint32_t* src, const uint32_t* dst) {
4138 if ((src[3] >> 30) || !src[2]) return false;
4139 const uint64_t base = uint64_t(src[0]) | (uint64_t(src[1] & 0xffff) << 32);
4140 const uint64_t fixed = uint64_t(dst[0]) | (uint64_t(dst[1] & 0xffff) << 32);
4141 const auto stride = (src[1] >> 16) & 0x3fff;
4142 const uint64_t bytes = uint64_t(src[2]) * (stride ? stride : 1);
4143 return aliases.overlaps(base, 1) || backing.overlaps(bda(base), bytes) ||
4144 (dst[2] && backing.overlaps(bda(fixed), bytes));
4145 };
4146 const auto before = heap.vsharps;
4147 ++heap.rescans;
4148 const auto rescan_start = clock::now();
3424 // Even an unchanged title slot may name a buffer released since the last submission. 4149 // Even an unchanged title slot may name a buffer released since the last submission.
3425 for (size_t at = 0; at + kDescriptorSize <= heap.bytes; at += kDescriptorSize) { 4150 // Walk the host-RAM V# bitset instead of reading every slot of `heap.copy` (which may be uncached WC VRAM).
3426 auto* w = reinterpret_cast<uint32_t*>(heap.copy + at); 4151 heap.live_vsharps.for_each([&](std::size_t slot) {
3427 if (!(w[3] >> 30) && (w[2] || w[6])) { 4152 ++heap.release_candidates;
3428 const auto slot = at / kDescriptorSize; 4153 if (filtered) {
3429 if (!fix_console_slot(heap, slot) && !heap.retry[slot]) { 4154 const auto at = slot * kDescriptorSize;
3430 heap.retry[slot] = 1; 4155 const auto* src = reinterpret_cast<const uint32_t*>(heap.previous + at);
3431 heap.retries.push_back(uint32_t(slot)); 4156 const auto* dst = reinterpret_cast<const uint32_t*>(heap.copy + at);
3432 } 4157 if (!affected(src, dst) && !affected(src + 4, dst + 4)) return;
3433 } 4158 }
3434 } 4159 ++heap.release_fixes;
4160 ++heap.rescanned;
4161 if (!fix_console_slot(heap, slot) && !heap.retry[slot]) {
4162 heap.retry[slot] = 1;
4163 heap.retries.push_back(uint32_t(slot));
4164 }
4165 });
4166 heap.release_rebases += heap.vsharps - before;
4167 heap.rescan_ms += ms(rescan_start, clock::now());
3435 } 4168 }
3436 const auto t2 = clock::now(); 4169 const auto t2 = clock::now();
3437 // A settled zero can acquire GPU backing without a CPU map event. Probe at most eight in 4170 // A settled zero can acquire GPU backing without a CPU map event. Probe at most eight in
@@ -3450,6 +4183,7 @@ struct DeviceState {
3450 } 4183 }
3451 } 4184 }
3452 if (!heap.retries.empty()) retry_console_slots(heap); 4185 if (!heap.retries.empty()) retry_console_slots(heap);
4186 if (!heap.unmapped.empty()) retry_unmapped_slots(heap);
3453 const auto t3 = clock::now(); 4187 const auto t3 = clock::now();
3454 heap.pages_ms += ms(t0, t1); 4188 heap.pages_ms += ms(t0, t1);
3455 heap.fix_ms += ms(t1, t2); 4189 heap.fix_ms += ms(t1, t2);
@@ -3459,6 +4193,16 @@ struct DeviceState {
3459 // Before every submission, ahead of the slot-133 shadows. 4193 // Before every submission, ahead of the slot-133 shadows.
3460 void refresh_console_heaps() { 4194 void refresh_console_heaps() {
3461 std::lock_guard lock(console_heap_mutex); 4195 std::lock_guard lock(console_heap_mutex);
4196 const bool heap_pass = heap_gpu && console_heap_gpu_enabled();
4197 if (heap_pass) console_heap_gpu_begin();
4198 else if (heap_gpu) heap_gpu->drain(context->completed_retire_ticket(), [](int, std::uint32_t, std::uint32_t) {}, [](int) {});
4199 struct GpuEnd { // after every heap's slots are queued, however the loop ends
4200 DeviceState& state;
4201 bool on;
4202 ~GpuEnd() {
4203 if (on) state.console_heap_gpu_end();
4204 }
4205 } gpu_end{*this, heap_pass};
3462 for (const auto& heap : console_heaps) { 4206 for (const auto& heap : console_heaps) {
3463 const auto start = std::chrono::steady_clock::now(); 4207 const auto start = std::chrono::steady_clock::now();
3464 refresh_console_heap(*heap); 4208 refresh_console_heap(*heap);
@@ -3476,8 +4220,8 @@ struct DeviceState {
3476 "in %.3f ms on average (pages %.3f, fixing copied slots %.3f, %llu left to retries past the " 4220 "in %.3f ms on average (pages %.3f, fixing copied slots %.3f, %llu left to retries past the "
3477 "budget, retrying %.3f: %.1f slots a " 4221 "budget, retrying %.3f: %.1f slots a "
3478 "submission, %zu waiting), %llu write faults; %llu title V#s rebased, %llu with no copy given " 4222 "submission, %zu waiting), %llu write faults; %llu title V#s rebased, %llu with no copy given "
3479 "no records, T#s %llu known, %llu bound, %llu naming no texture, %llu refused, %llu words " 4223 "no records (%zu naming nothing waiting for another look), T#s %llu known, %llu bound, %llu "
3480 "that are no T# (data)\n", 4224 "naming no texture, %llu refused, %llu words that are no V# or T# (data, null in the copy)\n",
3481 static_cast<unsigned long long>(heap->console_va), heap->imported ? "imported" : "copy", 4225 static_cast<unsigned long long>(heap->console_va), heap->imported ? "imported" : "copy",
3482 static_cast<unsigned long long>(heap->refreshes), "copied", 4226 static_cast<unsigned long long>(heap->refreshes), "copied",
3483 double(heap->copied) / 1024.0 / count, 4227 double(heap->copied) / 1024.0 / count,
@@ -3486,17 +4230,60 @@ struct DeviceState {
3486 double(heap->retried) / count, heap->retries.size(), 4230 double(heap->retried) / count, heap->retries.size(),
3487 static_cast<unsigned long long>(heap->pages ? heap->pages->faults() : 0), 4231 static_cast<unsigned long long>(heap->pages ? heap->pages->faults() : 0),
3488 static_cast<unsigned long long>(heap->vsharps), 4232 static_cast<unsigned long long>(heap->vsharps),
3489 static_cast<unsigned long long>(heap->unbacked), 4233 static_cast<unsigned long long>(heap->unbacked), heap->empty_slots.size(),
3490 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::known)]), 4234 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::known)]),
3491 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::bound)]), 4235 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::bound)]),
3492 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::unknown)]), 4236 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::unknown)]),
3493 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::refused)]), 4237 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::refused)]),
3494 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::not_tsharp)])); 4238 static_cast<unsigned long long>(heap->images[unsigned(TitleImage::not_tsharp)]));
4239 if (heap->release_sweeps && filter_heap_releases())
4240 std::fprintf(stderr, "[rt] CPU release filter: %llu sweeps, %llu live slots, %llu fixes, %llu rebases, %llu full fallbacks\n",
4241 (unsigned long long)heap->release_sweeps, (unsigned long long)heap->release_candidates,
4242 (unsigned long long)heap->release_fixes, (unsigned long long)heap->release_rebases,
4243 (unsigned long long)heap->release_full);
4244 heap->release_sweeps = heap->release_candidates = heap->release_fixes = heap->release_rebases = heap->release_full = 0;
4245 if (heap->resource_heap) {
4246 std::uint64_t paths[kVsharpPathCount];
4247 for (unsigned i = 0; i < kVsharpPathCount; ++i)
4248 paths[i] = vsharp_paths[i].exchange(0, std::memory_order_relaxed);
4249 std::fprintf(stderr,
4250 "[rt] d3d12: console descriptor heap 0x%llx changed slots per submission: %.1f zero, %.1f "
4251 "V# pairs, %.1f T#s, %.1f other; V# halves %.1f, %.1f%% seen before; rescans %llu (%.1f "
4252 "V# slots and %.3f ms each); V# resolutions since the last line: alias %llu, alias "
4253 "refused %llu, arena %llu, geometry %llu, window %llu, none %llu\n",
4254 static_cast<unsigned long long>(heap->console_va), double(heap->changed[0]) / count,
4255 double(heap->changed[1]) / count, double(heap->changed[2]) / count,
4256 double(heap->changed[3]) / count, double(heap->vsharp_halves) / count,
4257 heap->vsharp_halves ? 100.0 * double(heap->vsharp_repeats) / double(heap->vsharp_halves)
4258 : 0.0,
4259 static_cast<unsigned long long>(heap->rescans),
4260 heap->rescans ? double(heap->rescanned) / double(heap->rescans) : 0.0,
4261 heap->rescans ? heap->rescan_ms / double(heap->rescans) : 0.0,
4262 static_cast<unsigned long long>(paths[0]), static_cast<unsigned long long>(paths[1]),
4263 static_cast<unsigned long long>(paths[2]), static_cast<unsigned long long>(paths[3]),
4264 static_cast<unsigned long long>(paths[4]), static_cast<unsigned long long>(paths[5]));
4265 for (auto& n : heap->changed) n = 0;
4266 heap->vsharp_halves = heap->vsharp_repeats = heap->rescans = heap->rescanned = 0;
4267 heap->rescan_ms = 0;
4268 }
4269 if (heap->gpu >= 0) log_console_heap_gpu(*heap, count);
4270 std::string refused_breakdown;
4271 for (const auto& [reason, count] : heap->refused_reasons)
4272 refused_breakdown += (refused_breakdown.empty() ? "" : "; ") + reason + " " + std::to_string(count);
4273 if (!refused_breakdown.empty())
4274 std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx unbound T#s by reason: %s\n",
4275 static_cast<unsigned long long>(heap->console_va), refused_breakdown.c_str());
4276 heap->refused_reasons.clear();
3495 heap->copied = heap->vsharps = heap->unbacked = heap->retried = heap->deferred_fixes = 0; 4277 heap->copied = heap->vsharps = heap->unbacked = heap->retried = heap->deferred_fixes = 0;
3496 for (auto& n : heap->images) n = 0; 4278 for (auto& n : heap->images) n = 0;
3497 heap->ms = heap->pages_ms = heap->fix_ms = heap->retry_ms = 0; 4279 heap->ms = heap->pages_ms = heap->fix_ms = heap->retry_ms = 0;
4280 if (start - arena_log_time >= std::chrono::seconds(60)) {
4281 arena_log_time = start;
4282 report_arena_peak();
4283 }
3498 } 4284 }
3499 } 4285 }
4286 std::chrono::steady_clock::time_point arena_log_time{}; // console_heap_mutex held
3500 4287
3501 // The heap's pages imported as host memory (see above): true with `heap` filled in, false when they cannot be 4288 // The heap's pages imported as host memory (see above): true with `heap` filled in, false when they cannot be
3502 // (no VK_EXT_external_memory_host, a page not committed or write-combined, a driver refusal, or a device address 4289 // (no VK_EXT_external_memory_host, a page not committed or write-combined, a driver refusal, or a device address
@@ -3588,13 +4375,46 @@ struct DeviceState {
3588 heap->bytes = bytes; 4375 heap->bytes = bytes;
3589 // Self-written V#s must be rebased without changing the title's descriptor bytes. 4376 // Self-written V#s must be rebased without changing the title's descriptor bytes.
3590 // A directly indexed heap can lie outside the main arena and still fit in a 32-bit shader offset. 4377 // A directly indexed heap can lie outside the main arena and still fit in a 32-bit shader offset.
4378 // A resource heap's copy is followed by null slots (heap_guard_bytes), rounded so the whole stays 64 KiB
4379 // aligned for an import.
3591 heap->resource_heap = resource_heap; 4380 heap->resource_heap = resource_heap;
3592 // Round the guarded import up to Wine's allocation granularity. 4381 // Round the guarded import up to Wine's allocation granularity.
3593 if (bytes > (1ull << 32)) return false; 4382 if (bytes > (1ull << 32)) return false;
3594 const VkDeviceSize requested = resource_heap ? heap_guard_bytes() : 0; 4383 const VkDeviceSize requested = resource_heap ? heap_guard_bytes() : 0;
3595 const VkDeviceSize guard = requested && bytes + requested <= (1ull << 32) 4384 const VkDeviceSize guard = requested && bytes + requested <= (1ull << 32)
3596 ? ((bytes + requested + 65535) & ~VkDeviceSize(65535)) - bytes : 0; 4385 ? ((bytes + requested + 65535) & ~VkDeviceSize(65535)) - bytes : 0;
3597 if (resource_heap && geometry.cap()) { 4386 // LEONIDA_CONSOLE_HEAP_ARENA=1 (with LEONIDA_CONSOLE_HEAP_GPU): the copy and its guard in the arena, which is
4387 // device-local where the device has it (ReBAR), not in an import of host memory: every draw's descriptor
4388 // fetch and the pass's writes stay on the card. The CPU never writes the copy then (the pass does); [input |
4389 // previous] stay in host memory. No room in the arena: the import, as without the switch.
4390 bool in_arena = false;
4391 if (resource_heap && geometry.cap() && heap_gpu && console_heap_gpu_enabled() && console_heap_arena_enabled() &&
4392 bytes <= SIZE_MAX / 2) {
4393 VkDeviceSize offset = 0;
4394 const VkDeviceSize size = bytes + guard;
4395 if (arena_allocate(size, 65536, offset, arena_descriptor_heap)) {
4396 heap->scratch.reset(static_cast<std::uint8_t*>(
4397 VirtualAlloc(nullptr, bytes * 2, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)));
4398 if (heap->scratch) {
4399 heap->input = heap->scratch.get();
4400 heap->previous = heap->scratch.get() + bytes;
4401 heap->shader_va = offset;
4402 heap->copy = arena.mapped + offset;
4403 heap->guard = guard;
4404 heap->imported = false;
4405 in_arena = true;
4406 std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_ARENA: console descriptor heap 0x%llx's "
4407 "copy and %llu MiB guard in the arena at 0x%llx (memory type %u)\n",
4408 static_cast<unsigned long long>(console_va),
4409 static_cast<unsigned long long>(guard >> 20),
4410 static_cast<unsigned long long>(offset), unsigned(arena.memory_type));
4411 } else {
4412 arena_release(offset, size, arena_descriptor_heap);
4413 }
4414 }
4415 }
4416 if (in_arena) {
4417 } else if (resource_heap && geometry.cap()) {
3598 if (bytes > (SIZE_MAX - guard) / 3) return false; 4418 if (bytes > (SIZE_MAX - guard) / 3) return false;
3599 // [copy | guard | input | previous]: the import covers the copy and its guard. 4419 // [copy | guard | input | previous]: the import covers the copy and its guard.
3600 heap->scratch.reset(static_cast<std::uint8_t*>(VirtualAlloc(nullptr, bytes * 3 + guard, MEM_TOP_DOWN | 4420 heap->scratch.reset(static_cast<std::uint8_t*>(VirtualAlloc(nullptr, bytes * 3 + guard, MEM_TOP_DOWN |
@@ -3649,6 +4469,8 @@ struct DeviceState {
3649 heap->previous = heap->made.data(); 4469 heap->previous = heap->made.data();
3650 } 4470 }
3651 heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0); 4471 heap->retry.assign(std::size_t(bytes / kDescriptorSize), 0);
4472 heap->live_vsharps.reset(std::size_t(bytes / kDescriptorSize));
4473 heap->unmapped_tries.assign(std::size_t(bytes / kDescriptorSize), 0);
3652 heap->pages = make_shadow_pages(reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(console_va)), 4474 heap->pages = make_shadow_pages(reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(console_va)),
3653 heap->input, std::size_t(bytes)); 4475 heap->input, std::size_t(bytes));
3654 } 4476 }
@@ -3656,8 +4478,12 @@ struct DeviceState {
3656 if (shader_va != console_va) console_heap_ranges().add(console_va, bytes, shader_va); 4478 if (shader_va != console_va) console_heap_ranges().add(console_va, bytes, shader_va);
3657 const bool imported = heap->imported; 4479 const bool imported = heap->imported;
3658 const VkDeviceSize guarded = heap->guard; 4480 const VkDeviceSize guarded = heap->guard;
4481 arena_guard_bytes.fetch_add(guarded, std::memory_order_relaxed);
4482 if (heap_gpu && console_heap_gpu_enabled() && heap->scratch && resource_heap && !imported)
4483 attach_console_heap_gpu(*heap);
3659 { 4484 {
3660 std::lock_guard lock(console_heap_mutex); 4485 std::lock_guard lock(console_heap_mutex);
4486 if (heap->gpu >= 0) gpu_heaps[std::size_t(heap->gpu)] = heap.get();
3661 if (!imported) refresh_console_heap(*heap); 4487 if (!imported) refresh_console_heap(*heap);
3662 if (heap->copy) { 4488 if (heap->copy) {
3663 std::unique_lock ranges(console_copy_ranges_mutex); 4489 std::unique_lock ranges(console_copy_ranges_mutex);
@@ -3666,13 +4492,14 @@ struct DeviceState {
3666 console_heaps.push_back(std::move(heap)); 4492 console_heaps.push_back(std::move(heap));
3667 } 4493 }
3668 std::fprintf(stderr, 4494 std::fprintf(stderr,
3669 "[rt] d3d12: console descriptor heap 0x%llx (%llu KiB): shaders read it at heap_base + 0x%llx, %s; " 4495 "[rt] d3d12: console %s descriptor heap 0x%llx (%llu KiB): shaders read it at heap_base + 0x%llx, "
3670 "%llu KiB of null slots after it\n", 4496 "%s; %llu KiB of null slots after it%s\n",
3671 static_cast<unsigned long long>(console_va), static_cast<unsigned long long>(bytes >> 10), 4497 resource_heap ? "CBV/SRV/UAV" : "sampler", static_cast<unsigned long long>(console_va),
3672 static_cast<unsigned long long>(shader_va), 4498 static_cast<unsigned long long>(bytes >> 10), static_cast<unsigned long long>(shader_va),
3673 imported ? "the title's pages imported as host memory" 4499 imported ? "the title's pages imported as host memory"
3674 : "a descriptor copy brought up to date before every submission", 4500 : "a descriptor copy brought up to date before every submission",
3675 static_cast<unsigned long long>(guarded >> 10)); 4501 static_cast<unsigned long long>(guarded >> 10),
4502 imported && resource_heap ? " (imported pages have no guard)" : "");
3676 return true; 4503 return true;
3677 } 4504 }
3678 4505
@@ -3699,9 +4526,21 @@ struct DeviceState {
3699 console_heaps.erase(it); 4526 console_heaps.erase(it);
3700 std::unique_lock ranges(console_copy_ranges_mutex); 4527 std::unique_lock ranges(console_copy_ranges_mutex);
3701 std::erase_if(console_copy_ranges, [console_va](const auto& r) { return r.first == console_va; }); 4528 std::erase_if(console_copy_ranges, [console_va](const auto& r) { return r.first == console_va; });
4529 if (heap->gpu >= 0) {
4530 heap_gpu->remove_heap(heap->gpu);
4531 gpu_heaps[std::size_t(heap->gpu)] = nullptr;
4532 }
3702 } 4533 }
3703 console_heap_ranges().remove(console_va); 4534 console_heap_ranges().remove(console_va);
3704 heap->pages.reset(); 4535 heap->pages.reset();
4536 if (heap->gpu >= 0) {
4537 // A pass recorded before remove_heap may still be on its way to the queue, and then reads `input` and
4538 // writes the copy: wait for it to be submitted, then for everything submitted.
4539 while (heap_gpu->uncommitted()) Sleep(0);
4540 context->wait_retire_ticket(context->submitted_retire_ticket());
4541 if (heap->input_buffer) context->vk.vkDestroyBuffer(info.device, heap->input_buffer, nullptr);
4542 if (heap->input_memory) context->vk.vkFreeMemory(info.device, heap->input_memory, nullptr);
4543 }
3705 if (heap->buffer) { 4544 if (heap->buffer) {
3706 // As for an imported slot-133 buffer: the title may free its pages right after, so the memory goes once 4545 // As for an imported slot-133 buffer: the title may free its pages right after, so the memory goes once
3707 // what was submitted retires, not through the deferred queue. 4546 // what was submitted retires, not through the deferred queue.
@@ -3712,6 +4551,1110 @@ struct DeviceState {
3712 } else { 4551 } else {
3713 arena_release(heap->shader_va, heap->bytes + heap->guard, arena_descriptor_heap); 4552 arena_release(heap->shader_va, heap->bytes + heap->guard, arena_descriptor_heap);
3714 } 4553 }
4554 arena_guard_bytes.fetch_sub(heap->guard, std::memory_order_relaxed);
4555 }
4556
4557 // ---- LEONIDA_CONSOLE_HEAP_GPU=1: the console heaps' V#s rebased by a compute pass (src/console_heap_gpu.h) ----
4558 // Before every submission the CPU still finds the changed slots (the heap's ShadowPages, then a compare with the
4559 // bytes each slot was last made from) and registers the T#s, as fix_console_slot does; every changed slot is then
4560 // queued for the pass, which writes it into the copy at the start of the submission (the context's prelude). A
4561 // V# half the pass's tables cannot answer is written with no records and comes back as a miss once its submission
4562 // is done: resolved here with vsharp_address (which may make a geometry copy) within LEONIDA_CONSOLE_GPU_RESOLVE_US
4563 // a refresh (2000 by default), its answer entered in the key table and its slots queued again. Words that got no
4564 // backing are asked again every LEONIDA_CONSOLE_GPU_RETRY_MS (500), on a timer to bound the per-submission cost.
4565 // When a backing or an alias range goes, the key entries that answered into it are dropped and every V# slot of
4566 // the heap is translated again (on the GPU: a list of slot indices).
4567 std::unique_ptr<leonida::ConsoleHeapGpu> heap_gpu;
4568 std::array<ConsoleHeap*, leonida::ConsoleHeapGpu::kMaxHeaps> gpu_heaps{}; // console_heap_mutex
4569 std::vector<std::pair<std::uint64_t, std::uint64_t>> released_ranges; // (shader VA, bytes); backing_mutex
4570 struct GpuKeyHash {
4571 std::size_t operator()(const leonida::ConsoleHeapKeys::Key& k) const {
4572 return leonida::ConsoleHeapKeys::hash(k);
4573 }
4574 };
4575 // The rest: console_heap_mutex. Unresolved words with the slots that missed on them (heap << 28 | slot), and
4576 // whether the resolver has them.
4577 struct GpuUnresolved {
4578 std::vector<std::uint32_t> slots;
4579 bool asked = false;
4580 };
4581 std::unordered_map<leonida::ConsoleHeapKeys::Key, GpuUnresolved, GpuKeyHash> gpu_unresolved;
4582 // The resolver: a thread of ours that answers missed words with vsharp_address, off the submitting thread (one
4583 // answer can wait milliseconds for the geometry worker's lock).
4584 // Requests and answers pass under its own mutex; the refresh hands words over and takes answers, never waits.
4585 struct GpuAnswer {
4586 leonida::ConsoleHeapKeys::Key key;
4587 std::uint64_t to, span;
4588 bool retry;
4589 };
4590 struct GpuResolver {
4591 std::mutex mutex;
4592 std::condition_variable wake;
4593 bool stop = false;
4594 std::vector<std::pair<leonida::ConsoleHeapKeys::Key, bool>> requests; // (words, a retry of no backing)
4595 std::vector<GpuAnswer> answers;
4596 // T#s to register (bind_title_image), the slot's words: the refresh only decodes them. Resolver-only state:
4597 // the words registered recently (not asked again) and those whose texture is still to come (asked again).
4598 std::vector<leonida::gfx10::ImageWords> tsharps;
4599 std::unordered_set<std::uint64_t> registered;
4600 std::deque<std::pair<std::chrono::steady_clock::time_point, leonida::gfx10::ImageWords>> waiting;
4601 std::thread thread;
4602 ~GpuResolver() { halt(); }
4603 void halt() {
4604 {
4605 std::lock_guard lock(mutex);
4606 stop = true;
4607 }
4608 wake.notify_all();
4609 if (thread.joinable()) thread.join();
4610 }
4611 };
4612 std::unique_ptr<GpuResolver> gpu_resolver;
4613 std::array<std::atomic<std::uint64_t>, 5> gpu_tsharps{}; // the resolver's T# registrations, by TitleImage
4614 std::size_t gpu_asked = 0; // requests handed over and not answered yet
4615 struct GpuUnbacked {
4616 std::chrono::steady_clock::time_point at; // when it may be asked again
4617 leonida::ConsoleHeapKeys::Key key;
4618 std::uint32_t tries = 0; // asked again so far: the wait doubles each time, up to 64x retry_ms
4619 };
4620 std::deque<GpuUnbacked> gpu_unbacked; // words answered "no backing", by when they may be asked again (roughly)
4621 std::unordered_map<leonida::ConsoleHeapKeys::Key, std::uint32_t, GpuKeyHash> gpu_unbacked_tries; // being asked
4622 std::uint64_t gpu_alias_generation = ~0ull;
4623 std::chrono::steady_clock::time_point gpu_ranges_at{};
4624 std::vector<leonida::ConsoleHeapRange> gpu_ranges;
4625 leonida::ConsoleHeapSpans gpu_backed, gpu_ask;
4626 std::uint64_t gpu_backed_generation = ~0ull, gpu_ask_generation = ~0ull;
4627 std::uint64_t gpu_backed_blocks = ~0ull; // the title-window blocks' layout generations at the last rebuild
4628 std::chrono::steady_clock::time_point gpu_backed_at{};
4629 std::vector<std::uint32_t> gpu_queue_scratch;
4630 bool gpu_rescan = false, gpu_rescan_after_resolve = false;
4631 std::chrono::steady_clock::time_point gpu_rescan_asked{};
4632 // LEONIDA_CONSOLE_GPU_FILTER=1 (default: LEONIDA_CONSOLE_RELEASE_FILTER's value): a release, an alias range that
4633 // went or a word answered since asks for a rescan of the slots it touches (the release filter's interval rule,
4634 // 8a22e92c8) instead of every V# slot: the GPU passes over the rest on its device-local metadata.
4635 // gpu_filter_shader: shader-VA spans (released backings, alias copies that went); gpu_filter_title: title VAs
4636 // (words backed since). Overflows and key resets still rescan everything.
4637 static bool gpu_filter_enabled() {
4638 static const bool on = [] {
4639 char text[8] = {};
4640 if (GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_FILTER", text, sizeof(text)) && text[0])
4641 return text[0] == '1';
4642 return GetEnvironmentVariableA("LEONIDA_CONSOLE_RELEASE_FILTER", text, sizeof(text)) && text[0] == '1';
4643 }();
4644 return on;
4645 }
4646 bool gpu_rescan_filtered = false;
4647 leonida::ConsoleHeapSpans gpu_filter_shader, gpu_filter_title;
4648 void request_rescan_after_resolve() {
4649 if (!gpu_rescan_after_resolve) gpu_rescan_asked = std::chrono::steady_clock::now();
4650 gpu_rescan_after_resolve = true;
4651 }
4652 struct GpuMiss {
4653 leonida::ConsoleHeapKeys::Key key;
4654 std::uint32_t code; // heap << 28 | slot; UINT32_MAX once handled
4655 };
4656 std::vector<GpuMiss> gpu_miss_scratch;
4657 struct GpuCounts {
4658 std::uint64_t misses = 0, resolved = 0, none = 0, flips = 0, rescans = 0, dropped = 0, released = 0;
4659 std::uint64_t known_misses = 0, put_failed = 0, backed_rebuilds = 0, backed_cuts = 0, key_resets = 0;
4660 std::uint64_t retried = 0, filtered_rescans = 0;
4661 double backed_ms = 0;
4662 double resolve_ms = 0, begin_ms = 0;
4663 double part_ms[5] = {}; // before: alias probes, drain + releases, range table, backed table, ask table
4664 } gpu_counts;
4665
4666 // LEONIDA_SHADOW_GPU=1 copies aliased shadow pages on the GPU at the start of the submission.
4667 // The source uses VK_EXT_external_memory_host to import the mapped title section. An import is
4668 // made per 2 MiB-aligned window of the view, kept while xmem's map journal shows no change over it, and lives until
4669 // the last pass that copies from it retires. Destinations outside the arena, and pages that will not import, are
4670 // copied by the CPU as before.
4671 static bool shadow_gpu_enabled() {
4672 static const bool on = [] {
4673 char value[4] = {};
4674 return GetEnvironmentVariableA("LEONIDA_SHADOW_GPU", value, sizeof(value)) == 1 && value[0] == '1';
4675 }();
4676 return on;
4677 }
4678 struct ShadowImport {
4679 DeviceState* device = nullptr;
4680 std::uintptr_t base = 0;
4681 std::size_t bytes = 0;
4682 VkBuffer buffer = VK_NULL_HANDLE;
4683 VkDeviceMemory memory = VK_NULL_HANDLE;
4684 std::uint64_t generation = 0; // title_memory_map's, when last found unchanged
4685 ~ShadowImport() {
4686 if (buffer) device->context->vk.vkDestroyBuffer(device->info.device, buffer, nullptr);
4687 if (memory) device->context->vk.vkFreeMemory(device->info.device, memory, nullptr);
4688 }
4689 };
4690 std::mutex shadow_import_mutex;
4691 std::map<std::uintptr_t, std::shared_ptr<ShadowImport>> shadow_imports; // by base
4692 std::uint64_t shadow_import_bytes = 0;
4693 struct ShadowGpuCounts {
4694 std::uint64_t copies = 0, bytes = 0, imports = 0, imported = 0, dropped = 0, refused = 0, outside = 0;
4695 } shadow_gpu_counts; // shadow_import_mutex
4696
4697 static bool shadow_gpu_copy(void* context, std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) {
4698 return static_cast<DeviceState*>(context)->gpu_copy_shadow(to, from, bytes);
4699 }
4700 // Shadows with memory of their own (no room in the arena): their mapping and buffer, for gpu_copy_shadow.
4701 struct CopyTarget {
4702 std::size_t bytes;
4703 VkBuffer buffer;
4704 };
4705 std::map<const std::uint8_t*, CopyTarget> copy_targets; // shadow_import_mutex
4706 void add_copy_target(const std::uint8_t* mapped, std::size_t bytes, VkBuffer buffer) {
4707 if (!shadow_gpu_enabled() || !mapped || !buffer) return;
4708 std::lock_guard lock(shadow_import_mutex);
4709 copy_targets[mapped] = {bytes, buffer};
4710 }
4711 // Before the buffer goes: no copy into it is recorded after this (one already recorded runs before it is freed:
4712 // the buffer goes to the deferred queue, behind the submission that recorded it).
4713 void remove_copy_target(const std::uint8_t* mapped) {
4714 if (!shadow_gpu_enabled() || !mapped) return;
4715 VkBuffer buffer = VK_NULL_HANDLE;
4716 {
4717 std::lock_guard lock(shadow_import_mutex);
4718 const auto it = copy_targets.find(mapped);
4719 if (it == copy_targets.end()) return;
4720 buffer = it->second.buffer;
4721 copy_targets.erase(it);
4722 }
4723 if (heap_gpu) heap_gpu->drop_copies_to(buffer);
4724 }
4725 // Where [to, to + n) is on the GPU: the arena, a title-window block outside it, or a shadow's own buffer.
4726 bool copy_destination(const std::uint8_t* to, std::size_t n, VkBuffer& buffer, VkDeviceSize& offset) {
4727 if (arena.mapped && to >= arena.mapped && to + n <= arena.mapped + arena.size) {
4728 buffer = arena.buffer;
4729 offset = VkDeviceSize(to - arena.mapped);
4730 return true;
4731 }
4732 if (external_windows.find_mapped(to, n, buffer, offset)) return true;
4733 auto it = copy_targets.upper_bound(to); // shadow_import_mutex held
4734 if (it == copy_targets.begin()) return false;
4735 --it;
4736 if (to < it->first || n > it->second.bytes || std::size_t(to - it->first) > it->second.bytes - n) return false;
4737 buffer = it->second.buffer;
4738 offset = VkDeviceSize(to - it->first);
4739 return true;
4740 }
4741 bool gpu_copy_shadow(std::uint8_t* to, const std::uint8_t* from, std::size_t n) {
4742 if (!heap_gpu || !n) return false;
4743 std::lock_guard lock(shadow_import_mutex);
4744 VkBuffer dst_buffer = VK_NULL_HANDLE;
4745 VkDeviceSize dst_offset = 0;
4746 if (!copy_destination(to, n, dst_buffer, dst_offset)) {
4747 ++shadow_gpu_counts.outside;
4748 return false;
4749 }
4750 const auto src = reinterpret_cast<std::uintptr_t>(from);
4751 std::shared_ptr<ShadowImport> found;
4752 auto it = shadow_imports.upper_bound(src);
4753 if (it != shadow_imports.begin()) {
4754 --it;
4755 ShadowImport& cand = *it->second;
4756 if (src >= cand.base && src + n <= cand.base + cand.bytes) {
4757 std::uint64_t now = 0;
4758 bool moved = false;
4759 if (!leonida::title_memory_map::changes_since(cand.generation, now, cand.base, cand.base + cand.bytes,
4760 [&](std::uintptr_t, std::uintptr_t) { moved = true; }))
4761 moved = true;
4762 if (moved) {
4763 shadow_import_bytes -= cand.bytes;
4764 shadow_imports.erase(it);
4765 ++shadow_gpu_counts.dropped;
4766 } else {
4767 cand.generation = now;
4768 found = it->second;
4769 }
4770 }
4771 }
4772 if (!found && !(found = make_shadow_import(src, n))) {
4773 ++shadow_gpu_counts.refused;
4774 return false;
4775 }
4776 heap_gpu->queue_copy(found->buffer, src - found->base, dst_buffer, dst_offset, n, found);
4777 ++shadow_gpu_counts.copies;
4778 shadow_gpu_counts.bytes += n;
4779 return true;
4780 }
4781 // An import of the committed, readable view region around [src, src + n): its 2 MiB-aligned window, inside the
4782 // region. Null when it does not hold all of it, the budget (LEONIDA_SHADOW_GPU_MB, 1024) is spent, or the driver
4783 // refuses. shadow_import_mutex held.
4784 std::shared_ptr<ShadowImport> make_shadow_import(std::uintptr_t src, std::size_t n) {
4785 static const std::uint64_t budget = [] {
4786 char text[16] = {};
4787 const DWORD c = GetEnvironmentVariableA("LEONIDA_SHADOW_GPU_MB", text, sizeof(text));
4788 return (c > 0 && c < sizeof(text) ? std::strtoull(text, nullptr, 10) : 1024ull) << 20;
4789 }();
4790 const std::uint64_t generation = leonida::title_memory_map::generation();
4791 MEMORY_BASIC_INFORMATION region{};
4792 const auto refuse = [&](const char* why) -> std::shared_ptr<ShadowImport> {
4793 static std::atomic<int> logged{0};
4794 if (logged.fetch_add(1, std::memory_order_relaxed) < 8)
4795 std::fprintf(stderr, "[rt] d3d12: LEONIDA_SHADOW_GPU: no import of 0x%llx (+%zu; state 0x%lx protect 0x%lx "
4796 "type 0x%lx): %s; copied by the CPU\n",
4797 static_cast<unsigned long long>(src), n, static_cast<unsigned long>(region.State),
4798 static_cast<unsigned long>(region.Protect), static_cast<unsigned long>(region.Type), why);
4799 return nullptr;
4800 };
4801 if (!VirtualQuery(reinterpret_cast<const void*>(src), &region, sizeof(region))) return refuse("no region");
4802 if (region.State != MEM_COMMIT || !region.Protect ||
4803 (region.Protect & (PAGE_NOACCESS | PAGE_GUARD | PAGE_WRITECOMBINE | PAGE_NOCACHE)))
4804 return refuse("not committed and readable");
4805 // This import path supports mapped section views.
4806 if (region.Type != MEM_MAPPED) return refuse("not a section view");
4807 constexpr std::uintptr_t kWindow = 2u << 20;
4808 const auto region_base = reinterpret_cast<std::uintptr_t>(region.BaseAddress);
4809 const std::uintptr_t region_end = region_base + region.RegionSize;
4810 const std::uintptr_t base = std::max(region_base, src & ~(kWindow - 1));
4811 const std::uintptr_t end = std::min(region_end, (src + n + kWindow - 1) & ~(kWindow - 1));
4812 if (src + n > end) return refuse("the run crosses the view's end");
4813 if (shadow_import_bytes + (end - base) > budget) return refuse("LEONIDA_SHADOW_GPU_MB spent");
4814 auto imp = std::make_shared<ShadowImport>();
4815 imp->device = this;
4816 imp->base = base;
4817 imp->bytes = end - base;
4818 imp->generation = generation;
4819 VkDeviceAddress address = 0;
4820 if (!import_host_range(reinterpret_cast<void*>(base), imp->bytes, imp->buffer, imp->memory, address))
4821 return refuse("the driver refused the import");
4822 // Older imports over these pages are stale or redundant.
4823 for (auto it = shadow_imports.lower_bound(base > (64ull << 20) ? base - (64ull << 20) : 0);
4824 it != shadow_imports.end() && it->first < end;) {
4825 if (it->first + it->second->bytes > base) {
4826 shadow_import_bytes -= it->second->bytes;
4827 it = shadow_imports.erase(it);
4828 } else {
4829 ++it;
4830 }
4831 }
4832 shadow_imports[base] = imp;
4833 shadow_import_bytes += imp->bytes;
4834 ++shadow_gpu_counts.imports;
4835 shadow_gpu_counts.imported += imp->bytes;
4836 return imp;
4837 }
4838
4839 static bool console_heap_gpu_enabled() {
4840 static const bool on = [] {
4841 char value[4] = {};
4842 return GetEnvironmentVariableA("LEONIDA_CONSOLE_HEAP_GPU", value, sizeof(value)) == 1 && value[0] == '1';
4843 }();
4844 return on;
4845 }
4846 static bool console_heap_arena_enabled() {
4847 static const bool on = [] {
4848 char value[4] = {};
4849 return GetEnvironmentVariableA("LEONIDA_CONSOLE_HEAP_ARENA", value, sizeof(value)) == 1 && value[0] == '1';
4850 }();
4851 return on;
4852 }
4853
4854 void setup_console_heap_gpu(PFN_vkGetDeviceProcAddr get_device) {
4855 if ((!console_heap_gpu_enabled() && !shadow_gpu_enabled()) || !context || !get_device) return;
4856 auto gpu = std::make_unique<leonida::ConsoleHeapGpu>(get_device, info.device, memory);
4857 if (!gpu->init()) {
4858 std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: the translation pass could not be made; the "
4859 "console heaps are fixed on the CPU\n");
4860 return;
4861 }
4862 heap_gpu = std::move(gpu);
4863 heap_gpu->set_signed_offsets(signed_vsharp_offsets());
4864 leonida::title_va_aliases().record_removals(true);
4865 context->set_prelude([this](VkCommandBuffer cb) { return heap_gpu->record(cb); },
4866 [this](bool submitted, std::uint64_t ticket) { heap_gpu->commit(submitted, ticket); });
4867 gpu_resolver = std::make_unique<GpuResolver>();
4868 gpu_resolver->thread = std::thread([this, r = gpu_resolver.get()] {
4869 SetThreadDescription(GetCurrentThread(), L"leonida console heap resolver");
4870 const auto words_hash = [](const leonida::gfx10::ImageWords& w) {
4871 std::uint64_t h = 1469598103934665603ull;
4872 for (const std::uint32_t x : w) h = (h ^ x) * 1099511628211ull;
4873 return h;
4874 };
4875 const auto bind = [&](const leonida::gfx10::ImageWords& w) {
4876 const TitleImage result = bind_title_image(*this, w);
4877 gpu_tsharps[unsigned(result)].fetch_add(1, std::memory_order_relaxed);
4878 if (result == TitleImage::unknown || result == TitleImage::refused) {
4879 if (r->waiting.size() < 65536) r->waiting.emplace_back(std::chrono::steady_clock::now(), w);
4880 } else {
4881 if (r->registered.size() > (1u << 20)) r->registered.clear();
4882 r->registered.insert(words_hash(w));
4883 }
4884 };
4885 for (;;) {
4886 std::vector<std::pair<leonida::ConsoleHeapKeys::Key, bool>> batch;
4887 std::vector<leonida::gfx10::ImageWords> tsharps;
4888 {
4889 std::unique_lock lock(r->mutex);
4890 // Woken for work, or every 100 ms for the T#s whose texture is still to come.
4891 r->wake.wait_for(lock, std::chrono::milliseconds(100),
4892 [r] { return r->stop || !r->requests.empty() || !r->tsharps.empty(); });
4893 if (r->stop) return;
4894 batch.swap(r->requests);
4895 tsharps.swap(r->tsharps);
4896 }
4897 for (const auto& w : tsharps)
4898 if (!r->registered.count(words_hash(w))) bind(w);
4899 // Those still waiting for a texture, again every 500 ms, at most 256 a round.
4900 const auto now = std::chrono::steady_clock::now();
4901 for (int n = 0; n < 256 && !r->waiting.empty() &&
4902 now - r->waiting.front().first >= std::chrono::milliseconds(500);
4903 ++n) {
4904 const auto w = r->waiting.front().second;
4905 r->waiting.pop_front();
4906 bind(w);
4907 }
4908 for (const auto& [key, retry] : batch) {
4909 std::uint64_t span = 0;
4910 const std::uint64_t to = resolve_vsharp_words(key, span);
4911 std::lock_guard lock(r->mutex);
4912 if (r->stop) return;
4913 r->answers.push_back({key, to, span, retry});
4914 }
4915 }
4916 });
4917 if (shadow_gpu_enabled()) {
4918 ShadowPages::gpu_copy_context = this;
4919 ShadowPages::gpu_copy = &shadow_gpu_copy;
4920 std::fprintf(stderr, "[rt] d3d12: LEONIDA_SHADOW_GPU=1: slot-133 shadows' aliased pages are copied by the "
4921 "GPU from imports of the title's pages\n");
4922 }
4923 if (console_heap_gpu_enabled())
4924 std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU=1: console heap V#s are rebased by a compute pass "
4925 "at the start of each submission\n");
4926 }
4927
4928 // `bytes` of host memory at `host` as a buffer the GPU reads by its device address. False: not importable.
4929 bool import_host_range(void* host, VkDeviceSize bytes, VkBuffer& buffer, VkDeviceMemory& out,
4930 VkDeviceAddress& address) {
4931 auto& vk = context->vk;
4932 const VkDeviceSize alignment = info.host_pointer_alignment;
4933 if (!get_host_pointer_properties || !alignment || (reinterpret_cast<std::uintptr_t>(host) % alignment) ||
4934 (bytes % alignment))
4935 return false;
4936 VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO};
4937 external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
4938 VkBufferCreateInfo create{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external};
4939 create.size = bytes;
4940 create.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
4941 VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
4942 share(create);
4943 buffer = VK_NULL_HANDLE;
4944 out = VK_NULL_HANDLE;
4945 if (vk.vkCreateBuffer(info.device, &create, nullptr, &buffer) != VK_SUCCESS) return false;
4946 const auto fail = [&] {
4947 if (buffer) vk.vkDestroyBuffer(info.device, buffer, nullptr);
4948 if (out) vk.vkFreeMemory(info.device, out, nullptr);
4949 buffer = VK_NULL_HANDLE;
4950 out = VK_NULL_HANDLE;
4951 return false;
4952 };
4953 VkMemoryRequirements requirements{};
4954 vk.vkGetBufferMemoryRequirements(info.device, buffer, &requirements);
4955 VkMemoryHostPointerPropertiesEXT pointer{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT};
4956 if (get_host_pointer_properties(info.device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, host,
4957 &pointer) != VK_SUCCESS)
4958 return fail();
4959 const std::uint32_t types = pointer.memoryTypeBits & requirements.memoryTypeBits;
4960 if (!types || bytes < requirements.size) return fail();
4961 VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT};
4962 import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
4963 import.pHostPointer = host;
4964 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import};
4965 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
4966 for (const VkMemoryPropertyFlags want :
4967 {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
4968 VkMemoryPropertyFlags(0)}) {
4969 for (std::uint32_t i = 0; i < memory.memoryTypeCount && !out; ++i) {
4970 if (!(types & (1u << i)) || (memory.memoryTypes[i].propertyFlags & want) != want) continue;
4971 VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags};
4972 allocate.allocationSize = bytes;
4973 allocate.memoryTypeIndex = i;
4974 if (vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) != VK_SUCCESS) out = VK_NULL_HANDLE;
4975 }
4976 if (out) break;
4977 }
4978 if (!out || vk.vkBindBufferMemory(info.device, buffer, out, 0) != VK_SUCCESS) return fail();
4979 VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
4980 bda.buffer = buffer;
4981 address = vk.vkGetBufferDeviceAddress(info.device, &bda);
4982 if (!address) return fail();
4983 return true;
4984 }
4985
4986 // A resource heap with its 3x scratch (copy, input, previous) goes to the pass: `input` imported, the copy
4987 // written by the pass where shaders read it (arena.address + shader_va: the scratch import or the arena range).
4988 void attach_console_heap_gpu(ConsoleHeap& heap) {
4989 VkDeviceAddress input = 0;
4990 if (!import_host_range(heap.input, heap.bytes, heap.input_buffer, heap.input_memory, input)) {
4991 std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx: its mirror "
4992 "could not be imported; fixed on the CPU\n",
4993 static_cast<unsigned long long>(heap.console_va));
4994 return;
4995 }
4996 const int index = heap_gpu->add_heap(input, arena.address + heap.shader_va,
4997 std::uint32_t(heap.bytes / kDescriptorSize));
4998 if (index < 0) {
4999 context->vk.vkDestroyBuffer(info.device, heap.input_buffer, nullptr);
5000 context->vk.vkFreeMemory(info.device, heap.input_memory, nullptr);
5001 heap.input_buffer = VK_NULL_HANDLE;
5002 heap.input_memory = VK_NULL_HANDLE;
5003 return;
5004 }
5005 heap.gpu = index;
5006 heap.vsharp_bits.assign((heap.bytes / kDescriptorSize + 63) / 64, 0);
5007 std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx (%llu slots) is "
5008 "translated by the pass (heap %d)\n",
5009 static_cast<unsigned long long>(heap.console_va),
5010 static_cast<unsigned long long>(heap.bytes / kDescriptorSize), index);
5011 }
5012
5013 static void set_vsharp_bit(ConsoleHeap& heap, std::size_t slot, bool on) {
5014 const std::uint64_t bit = 1ull << (slot & 63);
5015 auto& word = heap.vsharp_bits[slot >> 6];
5016 word = on ? word | bit : word & ~bit;
5017 }
5018
5019 // The T# in a slot's title bytes, registered as fix_console_slot does (no write: the pass copies it). 0: not
5020 // settled (a T# whose texture is still to come); 1: settled; 2: settled, and the slot holds words that are no
5021 // buffer pair and no T# that decodes, whose dwords 0-3 the pass writes as zeros, as fix_console_slot does.
5022 int console_tsharp_check(ConsoleHeap& heap, std::size_t slot) {
5023 leonida::gfx10::ImageWords words;
5024 std::memcpy(words.data(), heap.previous + slot * kDescriptorSize, sizeof(words));
5025 if (!(words[3] >> 30)) return 1;
5026 if (!leonida::gfx10::is_image(words)) {
5027 ++heap.images[unsigned(TitleImage::not_tsharp)];
5028 return 2;
5029 }
5030 const char* why = nullptr;
5031 const TitleImage result = bind_title_image(*this, words, &why);
5032 if (result == TitleImage::unknown || result == TitleImage::refused) {
5033 note_refused_tsharp(heap, slot * kDescriptorSize, words, why);
5034 if (result == TitleImage::refused) ++heap.refused_reasons[why ? why : "?"];
5035 }
5036 ++heap.images[unsigned(result)];
5037 if (result == TitleImage::not_tsharp) return 2;
5038 return result != TitleImage::unknown && result != TitleImage::refused ? 1 : 0;
5039 }
5040
5041 // LEONIDA_CONSOLE_GPU_TSHARPS=0 keeps T# registration on the submitting thread (fix_console_slot's way, under the
5042 // fix budget); by default the resolver does it and the refresh only decodes.
5043 static bool tsharps_off_thread_enabled() {
5044 static const bool on = [] {
5045 char value[4] = {};
5046 return !(GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_TSHARPS", value, sizeof(value)) == 1 && value[0] == '0');
5047 }();
5048 return on;
5049 }
5050 std::vector<leonida::gfx10::ImageWords> tsharp_jobs; // console_heap_mutex
5051 void refresh_console_heap_gpu(ConsoleHeap& heap) { // console_heap_mutex held
5052 const bool tsharps_off_thread = tsharps_off_thread_enabled() && gpu_resolver;
5053 static const std::uint64_t budget_us = [] {
5054 char text[16] = {};
5055 const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_FIX_US", text, sizeof(text));
5056 return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 4000ull;
5057 }();
5058 using clock = std::chrono::steady_clock;
5059 const auto ms = [](clock::time_point a, clock::time_point b) {
5060 return std::chrono::duration<double, std::milli>(b - a).count();
5061 };
5062 const auto t0 = clock::now();
5063 heap.copied += heap.pages->refresh();
5064 auto& queued = gpu_queue_scratch;
5065 queued.clear();
5066 // The tracker zeroed these in `input` too: the pass copies the zeros.
5067 heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) {
5068 std::memset(heap.previous + offset, 0, bytes);
5069 for (std::size_t slot = offset / kDescriptorSize;
5070 slot * kDescriptorSize < offset + bytes && slot < heap.retry.size(); ++slot) {
5071 heap.retry[slot] = 0;
5072 set_vsharp_bit(heap, slot, false);
5073 queued.push_back(std::uint32_t(slot));
5074 }
5075 });
5076 const auto t1 = clock::now();
5077 std::uint32_t binds = 0;
5078 bool over = false;
5079 heap.pages->for_each_copied([&](std::size_t offset, std::size_t bytes) {
5080 const std::size_t end = std::min<std::size_t>(offset + bytes, std::size_t(heap.bytes));
5081 for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end;
5082 at += kDescriptorSize) {
5083 if (!std::memcmp(heap.previous + at, heap.input + at, kDescriptorSize)) continue;
5084 std::memcpy(heap.previous + at, heap.input + at, kDescriptorSize);
5085 note_changed_slot(heap, heap.previous + at);
5086 const std::size_t slot = at / kDescriptorSize;
5087 heap.gpu_high = std::max(heap.gpu_high, std::uint32_t(slot + 1));
5088 const auto* w = reinterpret_cast<const std::uint32_t*>(heap.previous + at);
5089 if (!(w[3] >> 30)) {
5090 queued.push_back(std::uint32_t(slot));
5091 set_vsharp_bit(heap, slot, w[2] || w[6]);
5092 heap.retry[slot] = 0;
5093 continue;
5094 }
5095 set_vsharp_bit(heap, slot, false);
5096 if (tsharps_off_thread) {
5097 // Only decoded here: words that are no T# are zeroed by the pass; a T# goes to the resolver to
5098 // be registered (shaders find it by its words; until then they get the fallback).
5099 leonida::gfx10::ImageWords words;
5100 std::memcpy(words.data(), w, sizeof(words));
5101 leonida::gfx10::Image image{};
5102 const bool tsharp = leonida::gfx10::is_image(words) && leonida::gfx10::decode(words, image);
5103 queued.push_back(std::uint32_t(slot) | (tsharp ? 0u : leonida::ConsoleHeapGpu::kZeroFirst));
5104 if (tsharp) tsharp_jobs.push_back(words);
5105 else ++heap.images[unsigned(TitleImage::not_tsharp)];
5106 heap.retry[slot] = 0;
5107 continue;
5108 }
5109 // Past LEONIDA_CONSOLE_FIX_US of registering T#s, the rest wait for retry_console_tsharps (copied as
5110 // they are meanwhile).
5111 if (budget_us && !over && !(++binds & 15) &&
5112 clock::now() - t1 >= std::chrono::microseconds(budget_us))
5113 over = true;
5114 const int check = over ? 0 : console_tsharp_check(heap, slot);
5115 queued.push_back(std::uint32_t(slot) | (check == 2 ? leonida::ConsoleHeapGpu::kZeroFirst : 0u));
5116 if (check) {
5117 heap.retry[slot] = 0;
5118 } else {
5119 if (over) ++heap.deferred_fixes;
5120 if (!heap.retry[slot]) {
5121 heap.retry[slot] = 1;
5122 heap.retries.push_back(std::uint32_t(slot));
5123 }
5124 }
5125 }
5126 });
5127 heap_gpu->queue(heap.gpu, queued.begin(), queued.end());
5128 heap.gpu_queued += queued.size();
5129 if (!tsharp_jobs.empty()) {
5130 {
5131 std::lock_guard lock(gpu_resolver->mutex);
5132 gpu_resolver->tsharps.insert(gpu_resolver->tsharps.end(), tsharp_jobs.begin(), tsharp_jobs.end());
5133 }
5134 gpu_resolver->wake.notify_one();
5135 tsharp_jobs.clear();
5136 }
5137 const auto t2 = clock::now();
5138 if (!heap.retries.empty()) retry_console_tsharps(heap);
5139 const auto t3 = clock::now();
5140 heap.pages_ms += ms(t0, t1);
5141 heap.fix_ms += ms(t1, t2);
5142 heap.retry_ms += ms(t2, t3);
5143 }
5144
5145 // retry_console_slots for the GPU mode: only T#s wait there, and nothing is written.
5146 void retry_console_tsharps(ConsoleHeap& heap) {
5147 static const std::uint64_t budget_us = [] {
5148 char text[16] = {};
5149 const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_RETRY_US", text, sizeof(text));
5150 return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 500ull;
5151 }();
5152 const auto start = std::chrono::steady_clock::now();
5153 std::size_t i = heap.retry_at, visited = 0;
5154 const std::size_t total = heap.retries.size();
5155 while (visited < total && !heap.retries.empty()) {
5156 if (i >= heap.retries.size()) i = 0;
5157 const std::uint32_t slot = heap.retries[i];
5158 ++visited;
5159 const int check = heap.retry[slot] ? console_tsharp_check(heap, slot) : 1;
5160 if (check == 2) heap_gpu->queue(heap.gpu, slot | leonida::ConsoleHeapGpu::kZeroFirst);
5161 if (check) {
5162 heap.retry[slot] = 0;
5163 heap.retries[i] = heap.retries.back();
5164 heap.retries.pop_back();
5165 } else {
5166 ++i;
5167 }
5168 if (budget_us && !(visited & 31) &&
5169 std::chrono::steady_clock::now() - start >= std::chrono::microseconds(budget_us))
5170 break;
5171 }
5172 heap.retry_at = i;
5173 heap.retried += visited;
5174 }
5175
5176 // What fix_vsharp's console path (VsharpPath::scratch) answers for the four words of a V# half: the shader VA, or 0
5177 // (no backing). `span` gets the V#'s span.
5178 std::uint64_t resolve_vsharp_words(const leonida::ConsoleHeapKeys::Key& k, std::uint64_t& span) {
5179 const std::uint64_t base = std::uint64_t(k[0]) | (std::uint64_t(k[1] & 0xffff) << 32);
5180 const std::uint32_t stride = (k[1] >> 16) & 0x3fffu;
5181 span = std::uint64_t(k[2]) * (stride ? stride : 1);
5182 const leonida::gfx10::BufferWords words{k[0], k[1], k[2], k[3]};
5183 leonida::gfx10::Buffer desc{};
5184 const bool copy_geometry = leonida::gfx10::decode(words, desc) &&
5185 (span <= kTitleWindowMax || (desc.format && leonida::gfx10::encode(desc) == words));
5186 return vsharp_address(base, span, leonida::TitleVaAliases::table_view, false, copy_geometry);
5187 }
5188
5189 // vsharp_address's backed(): [offset, offset + bytes) of the shader VAs is a live allocation or geometry copy.
5190 bool shader_range_backed(std::uint64_t offset, std::uint64_t bytes) {
5191 constexpr std::uint64_t mask = (1ull << 48) - 1;
5192 if (!bytes) return false;
5193 const std::uint64_t limit = signed_vsharp_offsets() ? mask / 2 : mask;
5194 const bool encodable = offset <= limit ? bytes - 1 <= limit - offset
5195 : signed_vsharp_offsets() && offset >= UINT64_MAX - limit &&
5196 bytes - 1 <= limit - offset;
5197 if (!encodable) return false;
5198 const auto bda = arena.address + offset;
5199 {
5200 std::lock_guard lock(backing_mutex);
5201 if (gpu_backings.covers(bda, bytes)) return true;
5202 }
5203 std::uint64_t host{}, room{};
5204 return geometry.cap() && geometry.lookup(bda, host, room) && room >= bytes;
5205 }
5206
5207 // The range table from the alias table: a range keeps its check while it and its backing stay; `gone` (shader
5208 // VA ranges released since the last one) clears it. True when a checked range lost its backing.
5209 bool rebuild_gpu_ranges(const std::vector<std::pair<std::uint64_t, std::uint64_t>>& gone) {
5210 std::vector<leonida::TitleVaAliases::Mapping> mappings;
5211 leonida::title_va_aliases().mappings(mappings);
5212 const auto overlaps_gone = [&](std::uint64_t start, std::uint64_t end) {
5213 for (const auto& [s, n] : gone)
5214 if (s < end && start < s + n) return true;
5215 return false;
5216 };
5217 bool lost = false;
5218 std::vector<leonida::ConsoleHeapRange> ranges;
5219 ranges.reserve(mappings.size());
5220 for (const auto& m : mappings) {
5221 const std::uint64_t bytes = m.end - m.title_va;
5222 const bool released = !gone.empty() && overlaps_gone(m.shader_va, m.shader_va + bytes);
5223 auto it = std::lower_bound(gpu_ranges.begin(), gpu_ranges.end(), m.title_va,
5224 [](const leonida::ConsoleHeapRange& r, std::uint64_t va) { return r.title_va < va; });
5225 bool checked;
5226 if (it != gpu_ranges.end() && it->title_va == m.title_va && it->end == m.end &&
5227 it->shader_va == m.shader_va && !released) {
5228 checked = it->checked;
5229 } else {
5230 checked = shader_range_backed(m.shader_va, bytes);
5231 if (released && it != gpu_ranges.end() && it->title_va == m.title_va && it->checked) lost = true;
5232 }
5233 ranges.push_back({m.title_va, m.end, m.shader_va, checked});
5234 }
5235 // A checked range that is gone from the table altogether had its slots answered from it.
5236 if (!lost) {
5237 for (const auto& r : gpu_ranges) {
5238 if (!r.checked) continue;
5239 auto it = std::lower_bound(ranges.begin(), ranges.end(), r.title_va,
5240 [](const leonida::ConsoleHeapRange& a, std::uint64_t va) { return a.title_va < va; });
5241 if (it == ranges.end() || it->title_va != r.title_va || it->shader_va != r.shader_va || !it->checked) {
5242 lost = true;
5243 break;
5244 }
5245 }
5246 }
5247 gpu_ranges = ranges;
5248 heap_gpu->set_ranges(std::move(ranges));
5249 return lost;
5250 }
5251
5252 // The backed table (src/console_heap_gpu.h): every live allocation's shader VAs and the geometry copies' blocks,
5253 // merged, and clipped to what a V# can name. Rebuilt from gpu_backings when allocations changed, at most every
5254 // 100 ms (one made since is a miss the CPU answers meanwhile); a release in between is cut out of it at once, so
5255 // the pass never leaves a V# on memory that is going (an overlapping allocation that stays is then a miss too
5256 // until the next rebuild).
5257 void update_gpu_backed(const std::vector<std::pair<std::uint64_t, std::uint64_t>>& gone) {
5258 const auto start = std::chrono::steady_clock::now();
5259 const std::uint64_t generation = backing_generation.load(std::memory_order_relaxed);
5260 const std::uint64_t blocks = geometry.pool().layout_generation() + external_windows.layout_generation();
5261 const bool changed = generation != gpu_backed_generation || blocks != gpu_backed_blocks;
5262 if (changed && (gpu_backed_generation == ~0ull || start - gpu_backed_at >= std::chrono::milliseconds(100))) {
5263 gpu_backed_generation = generation;
5264 gpu_backed_blocks = blocks;
5265 gpu_backed_at = start;
5266 gpu_backed.clear();
5267 {
5268 std::lock_guard lock(backing_mutex);
5269 gpu_backings.for_each([&](std::uint64_t va, std::uint64_t bytes) {
5270 const std::uint64_t offset = va - arena.address;
5271 if (bytes && offset <= UINT64_MAX - bytes) gpu_backed.emplace_back(offset, offset + bytes);
5272 });
5273 }
5274 const auto block = [&](VkDeviceAddress address, VkDeviceSize bytes) {
5275 const std::uint64_t offset = address - arena.address;
5276 if (address && bytes && offset <= UINT64_MAX - bytes) gpu_backed.emplace_back(offset, offset + bytes);
5277 };
5278 geometry.pool().for_each_block(block);
5279 external_windows.for_each_block(block);
5280 leonida::merge_console_heap_spans(gpu_backed);
5281 // What a V# can name: 48 bits, or +-2^47 around heap_base with signed offsets.
5282 constexpr std::uint64_t k47 = 1ull << 47, k48 = 1ull << 48;
5283 leonida::ConsoleHeapSpans clipped;
5284 for (const auto& [a, b] : gpu_backed) {
5285 if (signed_vsharp_offsets()) {
5286 if (a < k47) clipped.emplace_back(a, std::min(b, k47));
5287 else if (a >= 0ull - k47) clipped.emplace_back(a, b);
5288 } else if (a < k48) {
5289 clipped.emplace_back(a, std::min(b, k48));
5290 }
5291 }
5292 gpu_backed.swap(clipped);
5293 heap_gpu->set_spans(leonida::ConsoleHeapGpu::backed_table, gpu_backed);
5294 ++gpu_counts.backed_rebuilds;
5295 } else if (!gone.empty() && !gpu_backed.empty()) {
5296 leonida::ConsoleHeapSpans out;
5297 for (const auto& [s0, bytes] : gone) {
5298 const std::uint64_t e0 = bytes > UINT64_MAX - s0 ? UINT64_MAX : s0 + bytes;
5299 out.clear();
5300 for (const auto& [a, b] : gpu_backed) {
5301 if (b <= s0 || a >= e0) {
5302 out.emplace_back(a, b);
5303 continue;
5304 }
5305 if (a < s0) out.emplace_back(a, s0);
5306 if (b > e0) out.emplace_back(e0, b);
5307 }
5308 gpu_backed.swap(out);
5309 }
5310 heap_gpu->set_spans(leonida::ConsoleHeapGpu::backed_table, gpu_backed);
5311 ++gpu_counts.backed_cuts;
5312 }
5313 gpu_counts.backed_ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
5314 }
5315
5316 // The ask table: the title's memory and both addresses of its GPU-window pairs. A V# base outside them that the
5317 // other tables do not answer is one vsharp_address could only answer 0 for.
5318 void update_gpu_ask() {
5319 auto& aliases = leonida::title_va_aliases();
5320 const std::uint64_t generation =
5321 aliases.memory_generation() * 1000003ull + std::uint64_t(leonida::title_gpu_views::count());
5322 if (generation == gpu_ask_generation) return;
5323 gpu_ask_generation = generation;
5324 gpu_ask = aliases.title_memory_ranges();
5325 leonida::ConsoleHeapSpans views;
5326 leonida::title_gpu_views::spans(views);
5327 gpu_ask.insert(gpu_ask.end(), views.begin(), views.end());
5328 leonida::merge_console_heap_spans(gpu_ask);
5329 heap_gpu->set_spans(leonida::ConsoleHeapGpu::ask_table, gpu_ask);
5330 }
5331
5332 // Once, when xmem's aliased pages are many: can they be imported as host memory (VK_EXT_external_memory_host)?
5333 // A successful import lets the GPU copy the section. Release the diagnostic import after the check.
5334 void probe_alias_imports() {
5335 static bool probed = false;
5336 if (probed) return;
5337 std::vector<std::uintptr_t> pages;
5338 const std::size_t total = leonida::title_page_aliases::sample(pages, 8);
5339 if (total < 256) return;
5340 probed = true;
5341 int ok = 0;
5342 for (const std::uintptr_t va : pages) {
5343 VkBuffer buffer = VK_NULL_HANDLE;
5344 VkDeviceMemory imported = VK_NULL_HANDLE;
5345 VkDeviceAddress address = 0;
5346 MEMORY_BASIC_INFORMATION region{};
5347 VirtualQuery(reinterpret_cast<const void*>(va), &region, sizeof(region));
5348 const bool done = import_host_range(reinterpret_cast<void*>(va), leonida::title_page_aliases::kPageSize,
5349 buffer, imported, address);
5350 ok += done;
5351 std::fprintf(stderr,
5352 "[rt] d3d12: alias import probe: page 0x%llx (state 0x%lx protect 0x%lx type 0x%lx): %s, "
5353 "device address 0x%llx\n",
5354 static_cast<unsigned long long>(va), static_cast<unsigned long>(region.State),
5355 static_cast<unsigned long>(region.Protect), static_cast<unsigned long>(region.Type),
5356 done ? "imported" : "refused", static_cast<unsigned long long>(address));
5357 if (buffer) context->vk.vkDestroyBuffer(info.device, buffer, nullptr);
5358 if (imported) context->vk.vkFreeMemory(info.device, imported, nullptr);
5359 }
5360 std::fprintf(stderr, "[rt] d3d12: alias import probe: %d of %zu sampled pages imported (%zu aliased pages)\n", ok,
5361 pages.size(), total);
5362 }
5363
5364 // Before the heaps of a refresh: the misses of the passes that are done, the backings and alias ranges gone, the
5365 // range table. console_heap_mutex held.
5366 void console_heap_gpu_begin() {
5367 const auto start = std::chrono::steady_clock::now();
5368 auto lap = [last = start](double& to) mutable {
5369 const auto now = std::chrono::steady_clock::now();
5370 to += std::chrono::duration<double, std::milli>(now - last).count();
5371 last = now;
5372 };
5373 probe_alias_imports();
5374 lap(gpu_counts.part_ms[0]);
5375 auto& misses = gpu_miss_scratch;
5376 misses.clear();
5377 heap_gpu->drain(
5378 context->completed_retire_ticket(),
5379 [&](int h, std::uint32_t slot, std::uint32_t half) {
5380 ConsoleHeap* heap = h >= 0 && unsigned(h) < gpu_heaps.size() ? gpu_heaps[std::size_t(h)] : nullptr;
5381 ++gpu_counts.misses;
5382 if (!heap || slot >= heap->retry.size()) return;
5383 const auto* k = reinterpret_cast<const std::uint32_t*>(heap->previous + slot * kDescriptorSize) + 4 * half;
5384 if ((k[3] >> 30) || !k[2]) return; // rewritten since: queued by its change
5385 misses.push_back({{k[0], k[1], k[2], k[3]}, (std::uint32_t(h) << 28) | slot});
5386 },
5387 // A list that ran over: every V# slot again once what it did hold is resolved (at once would only
5388 // overflow it again with the same words).
5389 [&](int) { request_rescan_after_resolve(); });
5390 if (!misses.empty()) {
5391 // Words the table has now (entered after that pass was recorded): only the slot again. The rest wait to
5392 // be resolved.
5393 std::vector<std::uint32_t> again;
5394 heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) {
5395 for (auto& m : misses)
5396 if (keys.find(m.key) >= 0) again.push_back(m.code), m.code = UINT32_MAX;
5397 return 0;
5398 });
5399 for (const std::uint32_t code : again)
5400 if (gpu_heaps[code >> 28]) heap_gpu->queue(int(code >> 28), code & ((1u << 28) - 1));
5401 gpu_counts.known_misses += again.size();
5402 for (const auto& m : misses) {
5403 if (m.code == UINT32_MAX) continue;
5404 auto& slots = gpu_unresolved[m.key].slots;
5405 // Words shared by very many slots: the rest are found by the rescan after the answer.
5406 if (slots.size() < 4096) slots.push_back(m.code);
5407 else request_rescan_after_resolve();
5408 }
5409 }
5410 std::vector<std::pair<std::uint64_t, std::uint64_t>> gone, removed;
5411 {
5412 std::lock_guard lock(backing_mutex);
5413 gone.swap(released_ranges);
5414 }
5415 auto& aliases = leonida::title_va_aliases();
5416 aliases.take_removed(removed);
5417 gpu_counts.released += gone.size() + removed.size();
5418 std::size_t dropped = 0;
5419 if (!gone.empty() || !removed.empty())
5420 dropped = heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) {
5421 std::size_t n = 0;
5422 for (const auto& [s, bytes] : gone) n += keys.erase_overlapping(s, s + bytes);
5423 for (const auto& [s, bytes] : removed) n += keys.erase_overlapping(s, s + bytes);
5424 return n;
5425 });
5426 gpu_counts.dropped += dropped;
5427 lap(gpu_counts.part_ms[1]);
5428 bool lost = false;
5429 const std::uint64_t generation = aliases.generation();
5430 // At once when something went (the pass must not answer from it), else at most every 50 ms: a range added
5431 // since is a miss the resolver answers meanwhile (the alias table changes at most submissions).
5432 if ((generation != gpu_alias_generation &&
5433 (!removed.empty() || start - gpu_ranges_at >= std::chrono::milliseconds(50))) ||
5434 !gone.empty()) {
5435 gpu_alias_generation = generation;
5436 gpu_ranges_at = start;
5437 lost = rebuild_gpu_ranges(gone);
5438 }
5439 lap(gpu_counts.part_ms[2]);
5440 if (dropped || lost) {
5441 if (gpu_filter_enabled()) {
5442 gpu_rescan_filtered = true;
5443 for (const auto& [s, bytes] : gone) gpu_filter_shader.emplace_back(s, s + bytes);
5444 for (const auto& [s, bytes] : removed) gpu_filter_shader.emplace_back(s, s + bytes);
5445 } else {
5446 gpu_rescan = true;
5447 }
5448 }
5449 update_gpu_backed(gone);
5450 lap(gpu_counts.part_ms[3]);
5451 update_gpu_ask();
5452 lap(gpu_counts.part_ms[4]);
5453 gpu_counts.begin_ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
5454 }
5455
5456 // After the heaps: hand the missed words to the resolver, take its answers (entered in the key table, their slots
5457 // queued again), ask again for words that got no backing, and translate every V# slot again when something they
5458 // were answered from went. Nothing here waits for an answer.
5459 void console_heap_gpu_end() {
5460 static const std::uint64_t retry_ms = [] {
5461 char text[16] = {};
5462 const DWORD n = GetEnvironmentVariableA("LEONIDA_CONSOLE_GPU_RETRY_MS", text, sizeof(text));
5463 return n > 0 && n < sizeof(text) ? std::strtoull(text, nullptr, 10) : 2000ull;
5464 }();
5465 using clock = std::chrono::steady_clock;
5466 const auto start = clock::now();
5467 std::vector<GpuAnswer> answers;
5468 std::vector<std::pair<leonida::ConsoleHeapKeys::Key, bool>> requests;
5469 for (auto& [key, u] : gpu_unresolved)
5470 if (!u.asked) {
5471 u.asked = true;
5472 requests.emplace_back(key, false);
5473 }
5474 // Words with no backing, asked again once retry_ms old: at most 256 a refresh, and while the resolver has
5475 // fewer than 4096 waiting.
5476 const auto now = clock::now();
5477 for (int n = 0; n < 256 && !gpu_unbacked.empty() && gpu_asked + requests.size() < 4096 &&
5478 now >= gpu_unbacked.front().at;
5479 ++n) {
5480 requests.emplace_back(gpu_unbacked.front().key, true);
5481 gpu_unbacked_tries[gpu_unbacked.front().key] = gpu_unbacked.front().tries + 1;
5482 gpu_unbacked.pop_front();
5483 ++gpu_counts.retried;
5484 }
5485 {
5486 std::lock_guard lock(gpu_resolver->mutex);
5487 answers.swap(gpu_resolver->answers);
5488 gpu_resolver->requests.insert(gpu_resolver->requests.end(), requests.begin(), requests.end());
5489 }
5490 if (!requests.empty()) gpu_resolver->wake.notify_one();
5491 gpu_asked += requests.size();
5492 gpu_asked -= std::min(gpu_asked, answers.size());
5493 const auto queue_slots = [&](const std::vector<std::uint32_t>& slots) {
5494 for (const std::uint32_t code : slots) {
5495 const std::uint32_t h = code >> 28;
5496 if (h < gpu_heaps.size() && gpu_heaps[h]) heap_gpu->queue(int(h), code & ((1u << 28) - 1));
5497 }
5498 };
5499 for (const GpuAnswer& a : answers) {
5500 if (a.retry) {
5501 if (!a.to) {
5502 // Still no backing: asked again after twice the wait, at most 64x retry_ms.
5503 const auto t = gpu_unbacked_tries.find(a.key);
5504 const std::uint32_t tries = t == gpu_unbacked_tries.end() ? 1 : t->second;
5505 if (t != gpu_unbacked_tries.end()) gpu_unbacked_tries.erase(t);
5506 const auto wait = std::chrono::milliseconds(retry_ms << std::min<std::uint32_t>(tries, 6));
5507 gpu_unbacked.push_back({clock::now() + wait, a.key, tries});
5508 continue;
5509 }
5510 gpu_unbacked_tries.erase(a.key);
5511 // Backed now: every slot that read "no backing" for these words, once all are in.
5512 const bool entered = heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) {
5513 std::uint64_t to = 0;
5514 bool none = false;
5515 return keys.lookup(a.key, to, none) && none && keys.put(a.key, a.to, a.span, false);
5516 });
5517 if (entered) {
5518 ++gpu_counts.flips;
5519 if (gpu_filter_enabled()) {
5520 // The slots that read "no backing" for these words: those with this title base.
5521 const std::uint64_t base = a.key[0] | (std::uint64_t(a.key[1] & 0xffff) << 32);
5522 gpu_filter_title.emplace_back(base, base + 1);
5523 gpu_rescan_filtered = true;
5524 } else {
5525 gpu_rescan = true;
5526 }
5527 }
5528 continue;
5529 }
5530 ++gpu_counts.resolved;
5531 const auto it = gpu_unresolved.find(a.key);
5532 if (!heap_gpu->with_keys([&](leonida::ConsoleHeapKeys& keys) { return keys.put(a.key, a.to, a.span, !a.to); }))
5533 ++gpu_counts.put_failed; // every probe slot holds other words: these slots stay without records
5534 else if (it != gpu_unresolved.end())
5535 queue_slots(it->second.slots);
5536 if (it != gpu_unresolved.end()) gpu_unresolved.erase(it);
5537 if (!a.to) {
5538 ++gpu_counts.none;
5539 gpu_unbacked.push_back({clock::now() + std::chrono::milliseconds(retry_ms), a.key, 0});
5540 }
5541 }
5542 while (gpu_unbacked.size() > 65536) gpu_unbacked.pop_front(); // those stay "no backing" until a rescan
5543 // A key table past 60 % full: emptied at once (the next pass clears the GPU's), and every V# slot again.
5544 const auto [key_count, key_capacity] = heap_gpu->with_keys(
5545 [](leonida::ConsoleHeapKeys& k) { return std::pair<std::size_t, std::size_t>(k.size(), k.capacity()); });
5546 if (key_count * 10 > key_capacity * 6) {
5547 heap_gpu->reset_keys();
5548 gpu_unbacked.clear();
5549 gpu_unresolved.clear();
5550 ++gpu_counts.key_resets;
5551 gpu_rescan = true;
5552 }
5553 // Asked for after an overflow: once the misses are resolved, or a second later if new ones keep coming.
5554 if (gpu_rescan_after_resolve &&
5555 (gpu_unresolved.empty() || clock::now() - gpu_rescan_asked >= std::chrono::seconds(1))) {
5556 gpu_rescan_after_resolve = false;
5557 gpu_rescan = true;
5558 }
5559 if (gpu_rescan) {
5560 gpu_rescan = false;
5561 ++gpu_counts.rescans;
5562 // On the GPU: one dispatch over the slots the title has written, pairs only (ConsoleHeapGpu::rescan).
5563 for (unsigned h = 0; h < gpu_heaps.size(); ++h)
5564 if (ConsoleHeap* heap = gpu_heaps[h]) heap_gpu->rescan(int(h), heap->gpu_high);
5565 gpu_rescan_filtered = false; // the full one covers it
5566 gpu_filter_shader.clear();
5567 gpu_filter_title.clear();
5568 } else if (gpu_rescan_filtered) {
5569 gpu_rescan_filtered = false;
5570 ++gpu_counts.filtered_rescans;
5571 // The spans go to the pass once (its change tables serve every heap).
5572 bool first = true;
5573 const leonida::ConsoleHeapSpans none;
5574 for (unsigned h = 0; h < gpu_heaps.size(); ++h)
5575 if (ConsoleHeap* heap = gpu_heaps[h]) {
5576 heap_gpu->rescan_filtered(int(h), heap->gpu_high, first ? gpu_filter_shader : none,
5577 first ? gpu_filter_title : none);
5578 first = false;
5579 }
5580 gpu_filter_shader.clear();
5581 gpu_filter_title.clear();
5582 }
5583 gpu_counts.resolve_ms += std::chrono::duration<double, std::milli>(clock::now() - start).count();
5584 }
5585
5586 void log_console_heap_gpu(ConsoleHeap& heap, double count) {
5587 const auto stats = heap_gpu->take_stats();
5588 const std::size_t keys = heap_gpu->with_keys([](leonida::ConsoleHeapKeys& k) { return k.size(); });
5589 std::size_t checked = 0;
5590 for (const auto& r : gpu_ranges) checked += r.checked;
5591 std::fprintf(stderr,
5592 "[rt] d3d12: console descriptor heap 0x%llx on the GPU: %.1f slots queued a submission; passes "
5593 "%llu (%llu slots, %llu key updates, %llu misses, %llu overflowed, %llu not submitted); resolved "
5594 "%llu words (%llu with no backing, %llu asked again, %llu answered later, %llu not entered), %llu "
5595 "misses already "
5596 "entered, %zu waiting (%zu with the resolver), %zu unbacked; %llu rescans (%llu slots), "
5597 "%llu filtered rescans (%llu slots looked at), %llu key entries dropped for %llu releases; %zu keys (%llu resets), %zu ranges (%zu checked), %zu "
5598 "backed spans (%llu rebuilds, %llu cuts, %.3f ms a submission), %zu ask spans; %.3f ms before "
5599 "and %.3f ms resolving a submission\n",
5600 static_cast<unsigned long long>(heap.console_va), double(heap.gpu_queued) / count,
5601 static_cast<unsigned long long>(stats.passes), static_cast<unsigned long long>(stats.slots),
5602 static_cast<unsigned long long>(stats.updates), static_cast<unsigned long long>(stats.misses),
5603 static_cast<unsigned long long>(stats.overflows), static_cast<unsigned long long>(stats.failed),
5604 static_cast<unsigned long long>(gpu_counts.resolved),
5605 static_cast<unsigned long long>(gpu_counts.none),
5606 static_cast<unsigned long long>(gpu_counts.retried),
5607 static_cast<unsigned long long>(gpu_counts.flips),
5608 static_cast<unsigned long long>(gpu_counts.put_failed),
5609 static_cast<unsigned long long>(gpu_counts.known_misses), gpu_unresolved.size(), gpu_asked,
5610 gpu_unbacked.size(), static_cast<unsigned long long>(gpu_counts.rescans),
5611 static_cast<unsigned long long>(stats.rescanned),
5612 static_cast<unsigned long long>(gpu_counts.filtered_rescans),
5613 static_cast<unsigned long long>(stats.filtered),
5614 static_cast<unsigned long long>(gpu_counts.dropped),
5615 static_cast<unsigned long long>(gpu_counts.released), keys,
5616 static_cast<unsigned long long>(gpu_counts.key_resets), gpu_ranges.size(), checked,
5617 gpu_backed.size(), static_cast<unsigned long long>(gpu_counts.backed_rebuilds),
5618 static_cast<unsigned long long>(gpu_counts.backed_cuts), gpu_counts.backed_ms / count,
5619 gpu_ask.size(),
5620 gpu_counts.begin_ms / count, gpu_counts.resolve_ms / count);
5621 std::fprintf(stderr,
5622 "[rt] d3d12: console heap pass, before the heaps, ms a submission: alias probes %.3f, misses and "
5623 "releases %.3f, range table %.3f, backed table %.3f, ask table %.3f\n",
5624 gpu_counts.part_ms[0] / count, gpu_counts.part_ms[1] / count, gpu_counts.part_ms[2] / count,
5625 gpu_counts.part_ms[3] / count, gpu_counts.part_ms[4] / count);
5626 if (tsharps_off_thread_enabled()) {
5627 std::uint64_t t[5];
5628 for (unsigned i = 0; i < 5; ++i) t[i] = gpu_tsharps[i].exchange(0, std::memory_order_relaxed);
5629 std::fprintf(stderr,
5630 "[rt] d3d12: console heap T#s registered by the resolver: %llu known, %llu bound, %llu naming no "
5631 "texture, %llu refused\n",
5632 static_cast<unsigned long long>(t[0]), static_cast<unsigned long long>(t[1]),
5633 static_cast<unsigned long long>(t[2]), static_cast<unsigned long long>(t[3]));
5634 }
5635 if (shadow_gpu_enabled()) {
5636 ShadowGpuCounts c;
5637 std::size_t imports = 0;
5638 std::uint64_t imported_bytes = 0;
5639 {
5640 std::lock_guard lock(shadow_import_mutex);
5641 c = std::exchange(shadow_gpu_counts, ShadowGpuCounts{});
5642 imports = shadow_imports.size();
5643 imported_bytes = shadow_import_bytes;
5644 }
5645 std::fprintf(stderr,
5646 "[rt] d3d12: slot-133 shadows on the GPU: %llu copies (%.1f KiB a submission), %llu imports made "
5647 "(%llu MiB), %llu dropped after a map change, %llu refused, %llu with no GPU destination; %zu imports "
5648 "live (%llu MiB); passes copied %llu regions\n",
5649 static_cast<unsigned long long>(c.copies), double(c.bytes) / 1024.0 / count,
5650 static_cast<unsigned long long>(c.imports), static_cast<unsigned long long>(c.imported >> 20),
5651 static_cast<unsigned long long>(c.dropped), static_cast<unsigned long long>(c.refused),
5652 static_cast<unsigned long long>(c.outside), imports,
5653 static_cast<unsigned long long>(imported_bytes >> 20),
5654 static_cast<unsigned long long>(stats.copies));
5655 }
5656 heap.gpu_queued = 0;
5657 gpu_counts = {};
3715 } 5658 }
3716 5659
3717 // LOCAL DIAGNOSTIC (desc-probe): which console-heap slots our API wrote and which the title wrote itself, what 5660 // LOCAL DIAGNOSTIC (desc-probe): which console-heap slots our API wrote and which the title wrote itself, what
@@ -3733,6 +5676,16 @@ struct DeviceState {
3733 unsigned recent_count = 0; 5676 unsigned recent_count = 0;
3734 }; 5677 };
3735 std::mutex probe_mutex; // never under console_heap_mutex' callees; takes descriptor_mutex inside 5678 std::mutex probe_mutex; // never under console_heap_mutex' callees; takes descriptor_mutex inside
5679 // LEONIDA_DESC_PROBE=1 turns the diagnostic on (so does the compute input probe, which reads these records). Off
5680 // by default: at every submission it hashes each slot of every bound table, and formats a line under
5681 // descriptor_mutex for each slot the title wrote itself.
5682 static bool probe_enabled() {
5683 static const bool on = [] {
5684 const char* v = std::getenv("LEONIDA_DESC_PROBE");
5685 return (v && *v == '1') || rt::compute_probe::enabled();
5686 }();
5687 return on;
5688 }
3736 std::vector<std::unique_ptr<HeapProbe>> probes; 5689 std::vector<std::unique_ptr<HeapProbe>> probes;
3737 std::uint64_t probe_submissions = 0; 5690 std::uint64_t probe_submissions = 0;
3738 static constexpr const char* kProbeKinds[8] = {"V# in arena", "V# title memory", "V# other", "T# key known", 5691 static constexpr const char* kProbeKinds[8] = {"V# in arena", "V# title memory", "V# other", "T# key known",
@@ -3741,7 +5694,7 @@ struct DeviceState {
3741 std::atomic<int> probe_view_logs{0}; 5694 std::atomic<int> probe_view_logs{0};
3742 // Where a Create*View / CopyDescriptors* write landed, for the first ones. 5695 // Where a Create*View / CopyDescriptors* write landed, for the first ones.
3743 void probe_view(const char* what, SIZE_T ptr, UINT count) { 5696 void probe_view(const char* what, SIZE_T ptr, UINT count) {
3744 if (!leonida::local_diagnostics() || probe_view_logs.fetch_add(1) >= 48) return; 5697 if (!probe_enabled() || probe_view_logs.fetch_add(1) >= 48) return;
3745 std::lock_guard lock(probe_mutex); 5698 std::lock_guard lock(probe_mutex);
3746 for (const auto& p : probes) 5699 for (const auto& p : probes)
3747 if (ptr >= p->console_va && ptr < p->console_va + p->slots * kDescriptorSize) { 5700 if (ptr >= p->console_va && ptr < p->console_va + p->slots * kDescriptorSize) {
@@ -3766,8 +5719,7 @@ struct DeviceState {
3766 return !(q[0] | q[1] | q[2] | q[3]); 5719 return !(q[0] | q[1] | q[2] | q[3]);
3767 } 5720 }
3768 void probe_add(std::uint64_t console_va, std::uint64_t shader_va, std::size_t slots, bool shadowed) { 5721 void probe_add(std::uint64_t console_va, std::uint64_t shader_va, std::size_t slots, bool shadowed) {
3769 // Nothing reads a probe unless one of the two diagnostics is on; without probes the other probe_* are no-ops. 5722 if (!probe_enabled() && !rt::compute_probe::enabled()) return;
3770 if (!leonida::local_diagnostics() && !rt::compute_probe::enabled()) return;
3771 auto probe = std::make_unique<HeapProbe>(); 5723 auto probe = std::make_unique<HeapProbe>();
3772 probe->console_va = console_va; 5724 probe->console_va = console_va;
3773 probe->shader_va = shader_va; 5725 probe->shader_va = shader_va;
@@ -3787,11 +5739,12 @@ struct DeviceState {
3787 shader_va + slots * kDescriptorSize <= arena.size ? "inside" : "PAST"); 5739 shader_va + slots * kDescriptorSize <= arena.size ? "inside" : "PAST");
3788 } 5740 }
3789 void probe_remove(std::uint64_t console_va) { 5741 void probe_remove(std::uint64_t console_va) {
5742 if (!probe_enabled()) return;
3790 std::lock_guard lock(probe_mutex); 5743 std::lock_guard lock(probe_mutex);
3791 std::erase_if(probes, [console_va](const std::unique_ptr<HeapProbe>& p) { return p->console_va == console_va; }); 5744 std::erase_if(probes, [console_va](const std::unique_ptr<HeapProbe>& p) { return p->console_va == console_va; });
3792 } 5745 }
3793 void probe_api(SIZE_T ptr, UINT count, const char* what = "CopyDescriptors") { 5746 void probe_api(SIZE_T ptr, UINT count, const char* what = "CopyDescriptors") {
3794 if (!ptr || !count) return; 5747 if (!ptr || !count || !probe_enabled()) return;
3795 std::lock_guard lock(probe_mutex); 5748 std::lock_guard lock(probe_mutex);
3796 for (const auto& p : probes) { 5749 for (const auto& p : probes) {
3797 if (ptr < p->console_va || ptr >= p->console_va + p->slots * kDescriptorSize) continue; 5750 if (ptr < p->console_va || ptr >= p->console_va + p->slots * kDescriptorSize) continue;
@@ -3863,6 +5816,7 @@ struct DeviceState {
3863 } 5816 }
3864 // At a descriptor-table scan (ExecuteCommandLists): the slots a bound table in a console heap declares. 5817 // At a descriptor-table scan (ExecuteCommandLists): the slots a bound table in a console heap declares.
3865 void probe_table(std::uint64_t table_va, std::uint32_t descriptors) { 5818 void probe_table(std::uint64_t table_va, std::uint32_t descriptors) {
5819 if (!probe_enabled()) return;
3866 std::lock_guard lock(probe_mutex); 5820 std::lock_guard lock(probe_mutex);
3867 for (const auto& p : probes) { 5821 for (const auto& p : probes) {
3868 const std::uint64_t span = p->slots * kDescriptorSize; 5822 const std::uint64_t span = p->slots * kDescriptorSize;
@@ -3921,7 +5875,7 @@ struct DeviceState {
3921 } 5875 }
3922 // Before a submission, after the console heaps' copies are refreshed: the whole heap, now and then. 5876 // Before a submission, after the console heaps' copies are refreshed: the whole heap, now and then.
3923 void probe_census() { 5877 void probe_census() {
3924 if (!leonida::local_diagnostics()) return; 5878 if (!probe_enabled()) return;
3925 const std::uint64_t n = ++probe_submissions; 5879 const std::uint64_t n = ++probe_submissions;
3926 if (n != 1 && n != 64 && n != 512 && n != 2048 && n % 4096) return; 5880 if (n != 1 && n != 64 && n != 512 && n != 2048 && n % 4096) return;
3927 std::lock_guard lock(probe_mutex); 5881 std::lock_guard lock(probe_mutex);
@@ -4376,8 +6330,14 @@ struct DeviceState {
4376 VkImageView sampled; 6330 VkImageView sampled;
4377 VkImageView storage; // the same range without a component mapping, for the storage bindings; or null 6331 VkImageView storage; // the same range without a component mapping, for the storage bindings; or null
4378 std::uint64_t address; 6332 std::uint64_t address;
6333 // A 2D view of the first layer in the 2D arrays (a 2D-array image's slice 0, BindlessSet::MirrorViews); or null
6334 VkImageView mirror_sampled = VK_NULL_HANDLE;
6335 VkImageView mirror_storage = VK_NULL_HANDLE;
4379 }; 6336 };
4380 std::unique_ptr<leonida::BindlessSet> bindless; 6337 std::unique_ptr<leonida::BindlessSet> bindless;
6338 // True when the loaded library's modules read the table's kind word (create_bindless, descriptor_table.h): the
6339 // image inserts then record which arrays each index is bound in.
6340 bool descriptor_table_tagged = false;
4381 std::mutex descriptor_mutex; // the set and the containers below 6341 std::mutex descriptor_mutex; // the set and the containers below
4382 // vkDeviceWaitIdle calls made for the bindless set (none, unless LEONIDA_BINDLESS_IDLE_WAIT restores the old wait). 6342 // vkDeviceWaitIdle calls made for the bindless set (none, unless LEONIDA_BINDLESS_IDLE_WAIT restores the old wait).
4383 std::atomic<std::uint64_t> bindless_idle_waits{0}; 6343 std::atomic<std::uint64_t> bindless_idle_waits{0};
@@ -4464,6 +6424,10 @@ struct DeviceState {
4464 context->defer_destroy(leonida::DeferredDeletionQueue::Kind::bindless_slot, slot_handle); 6424 context->defer_destroy(leonida::DeferredDeletionQueue::Kind::bindless_slot, slot_handle);
4465 if (entry.sampled) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); 6425 if (entry.sampled) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled);
4466 if (entry.storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage); 6426 if (entry.storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage);
6427 if (entry.mirror_sampled)
6428 context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.mirror_sampled);
6429 if (entry.mirror_storage)
6430 context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.mirror_storage);
4467 } 6431 }
4468 6432
4469 struct PendingSample { 6433 struct PendingSample {
@@ -4641,12 +6605,10 @@ struct DeviceState {
4641 } 6605 }
4642 } 6606 }
4643 view_info.components = g::vulkan_swizzle(swizzle, channels_format); 6607 view_info.components = g::vulkan_swizzle(swizzle, channels_format);
4644 // The cast: MSVC's enums are ints, and it rejects int to VkImageAspectFlags in braces as narrowing. 6608 view_info.subresourceRange = g::vulkan_subresource_range(
4645 view_info.subresourceRange = { 6609 image, stencil ? VK_IMAGE_ASPECT_STENCIL_BIT
4646 VkImageAspectFlags(stencil ? VK_IMAGE_ASPECT_STENCIL_BIT 6610 : (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT
4647 : (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT 6611 : VK_IMAGE_ASPECT_COLOR_BIT);
4648 : VK_IMAGE_ASPECT_COLOR_BIT),
4649 image.first_mip, image.mip_count, image.first_layer, image.layer_count};
4650 ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address}; 6612 ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address};
4651 if (sampled) { 6613 if (sampled) {
4652 const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled); 6614 const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled);
@@ -4656,13 +6618,19 @@ struct DeviceState {
4656 } 6618 }
4657 } 6619 }
4658 leonida::StorageViews views{}; 6620 leonida::StorageViews views{};
6621 VkImageViewCreateInfo storage_info{};
6622 bool storage_info_valid = false;
6623 // storage_info's pNext chain: declared out here, since the 2D mirror below copies storage_info with its chain
6624 // after this block. Declared inside it, the chain dangled and the driver followed it into stale stack (the
6625 // 120 s hangs of d3d12_existing_heap, d3d12_r9g9b9e5_uav and the depth-storage tests).
6626 VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO};
6627 VkImageViewSlicedCreateInfoEXT sliced{VK_STRUCTURE_TYPE_IMAGE_VIEW_SLICED_CREATE_INFO_EXT};
4659 if (storage) { 6628 if (storage) {
4660 VkImageViewCreateInfo storage_info = view_info; 6629 storage_info = view_info;
6630 storage_info_valid = true;
4661 storage_info.components = {}; 6631 storage_info.components = {};
4662 storage_info.format = storage_format; 6632 storage_info.format = storage_format;
4663 VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO};
4664 storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; 6633 storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT;
4665 VkImageViewSlicedCreateInfoEXT sliced{VK_STRUCTURE_TYPE_IMAGE_VIEW_SLICED_CREATE_INFO_EXT};
4666 if (slices.count) { 6634 if (slices.count) {
4667 sliced.sliceOffset = slices.first; 6635 sliced.sliceOffset = slices.first;
4668 sliced.sliceCount = slices.count; 6636 sliced.sliceCount = slices.count;
@@ -4679,9 +6647,42 @@ struct DeviceState {
4679 (numeric == 1 ? views.as_uint : numeric == 2 ? views.as_sint : views.as_float) = entry.storage; 6647 (numeric == 1 ? views.as_uint : numeric == 2 ? views.as_sint : views.as_float) = entry.storage;
4680 if (storage_format == VK_FORMAT_R32_UINT) views.r32ui = entry.storage; 6648 if (storage_format == VK_FORMAT_R32_UINT) views.r32ui = entry.storage;
4681 } 6649 }
6650 // A 2D-array or cube image also gets a 2D view of its first layer, which the bindless set binds at the same
6651 // index in the 2D arrays: a 2D instruction reading this T# addresses slice 0 (BindlessSet::MirrorViews).
6652 leonida::BindlessSet::MirrorViews mirror{};
6653 if (dimension == leonida::ImageDimension::dim_2d_array) {
6654 const auto make_mirror = [&](const VkImageViewCreateInfo& base, VkImageView* out) {
6655 VkImageViewCreateInfo layer = base;
6656 layer.viewType = VK_IMAGE_VIEW_TYPE_2D;
6657 layer.subresourceRange.baseArrayLayer = image.first_layer;
6658 layer.subresourceRange.layerCount = 1;
6659 return vk.vkCreateImageView(info.device, &layer, nullptr, out) == VK_SUCCESS;
6660 };
6661 if (make_mirror(view_info, &entry.mirror_sampled)) {
6662 mirror.sampled = entry.mirror_sampled;
6663 mirror.sampled_layout = VK_IMAGE_LAYOUT_GENERAL;
6664 if (storage_info_valid && make_mirror(storage_info, &entry.mirror_storage)) {
6665 const int numeric = numeric_class(storage_info.format);
6666 (numeric == 1 ? mirror.storage.as_uint : numeric == 2 ? mirror.storage.as_sint
6667 : mirror.storage.as_float) = entry.mirror_storage;
6668 if (storage_info.format == VK_FORMAT_R32_UINT) mirror.storage.r32ui = entry.mirror_storage;
6669 }
6670 } else {
6671 log_once("no 2D view of this image's first layer; a 2D instruction reading its T# reads the fallback",
6672 int(image.type));
6673 }
6674 }
4682 // Every state a shader can read or write the texture in is GENERAL (ResourceBinding::sampled_in_general). 6675 // Every state a shader can read or write the texture in is GENERAL (ResourceBinding::sampled_in_general).
4683 entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class); 6676 // `kind` says which arrays the index is bound in; a tagged module reads it from the table (insert_key).
6677 entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class,
6678 mirror.sampled ? &mirror : nullptr);
4684 if (!entry.index) { 6679 if (!entry.index) {
6680 vk.vkDestroyImageView(info.device, entry.mirror_sampled, nullptr);
6681 entry.mirror_sampled = VK_NULL_HANDLE;
6682 if (entry.mirror_storage) {
6683 vk.vkDestroyImageView(info.device, entry.mirror_storage, nullptr);
6684 entry.mirror_storage = VK_NULL_HANDLE;
6685 }
4685 if (first_diagnostic("a bindless image array is full; dimension", int(dimension))) { 6686 if (first_diagnostic("a bindless image array is full; dimension", int(dimension))) {
4686 // Whether the array holds live textures or stale views: the T#s it holds, the textures they name, 6687 // Whether the array holds live textures or stale views: the T#s it holds, the textures they name,
4687 // and the most T#s of one texture (a texture whose T#s keep changing, a streamed mip clamp say, 6688 // and the most T#s of one texture (a texture whose T#s keep changing, a streamed mip clamp say,
@@ -4712,7 +6713,10 @@ struct DeviceState {
4712 image_entries.emplace(words, entry); 6713 image_entries.emplace(words, entry);
4713 image_keys.emplace(image.address, words); 6714 image_keys.emplace(image.address, words);
4714 } 6715 }
4715 bindless->insert_key(words, entry.index); 6716 // The set derives the entry's kind from what it bound at this index (BindlessSet::image_kind_at); a plain
6717 // library's modules do not read it, so they get 0 as before.
6718 bindless->insert_key(words, entry.index,
6719 descriptor_table_tagged ? bindless->image_kind_at(dimension, entry.index) : 0u);
4716 leonida::fsdraw::note_tsharp(words.data()); // LOCAL DIAGNOSTIC 6720 leonida::fsdraw::note_tsharp(words.data()); // LOCAL DIAGNOSTIC
4717 return true; 6721 return true;
4718 } 6722 }
@@ -4726,6 +6730,26 @@ struct DeviceState {
4726 std::lock_guard lock(descriptor_mutex); 6730 std::lock_guard lock(descriptor_mutex);
4727 images_by_address[address] = resource; 6731 images_by_address[address] = resource;
4728 } 6732 }
6733 // LEONIDA_TRACE_TEXTURE=<address>[,<address>...] (hex, the base a T# names): the resource id of an image registered
6734 // at that address, so a draw's T# can be followed to the passes that write it (fsdraw rt0, UAV views, copies).
6735 static void trace_image(std::uint64_t address, leonida::ResourceId id, const char* where) {
6736 static const std::vector<std::uint64_t> traced = [] {
6737 std::vector<std::uint64_t> out;
6738 const char* v = std::getenv("LEONIDA_TRACE_TEXTURE");
6739 for (const char* p = v; p && *p;) {
6740 char* end = nullptr;
6741 const std::uint64_t a = std::strtoull(p, &end, 16);
6742 if (end == p) break;
6743 out.push_back(a);
6744 p = *end == ',' ? end + 1 : end;
6745 }
6746 return out;
6747 }();
6748 if (traced.empty() || std::find(traced.begin(), traced.end(), address) == traced.end()) return;
6749 std::fprintf(stderr, "[rt] trace-texture: address 0x%llx is resource 0x%llx (%s)\n",
6750 static_cast<unsigned long long>(address), static_cast<unsigned long long>(id), where);
6751 leonida::fsdraw::note_target(id); // read back with the captures (numbers: mean, nonzero texels)
6752 }
4729 // The texture registered at `address` (a title-placed texture's address can be taken over by a later one). 6753 // The texture registered at `address` (a title-placed texture's address can be taken over by a later one).
4730 const void* image_owner(std::uint64_t address) { 6754 const void* image_owner(std::uint64_t address) {
4731 std::lock_guard lock(descriptor_mutex); 6755 std::lock_guard lock(descriptor_mutex);
@@ -4968,7 +6992,8 @@ Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc
4968// no-op. An A8 render target's VK_FORMAT_A8_UNORM_KHR image (Format::a8_as_alpha) is in a class of its own: no 6992// no-op. An A8 render target's VK_FORMAT_A8_UNORM_KHR image (Format::a8_as_alpha) is in a class of its own: no
4969// other format can be a view format of it, so any other castable format is refused here, before Vulkan. 6993// other format can be a view format of it, so any other castable format is refused here, before Vulkan.
4970HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, UINT32 count, 6994HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, UINT32 count,
4971 const DXGI_FORMAT* castable, std::vector<VkFormat>& out, bool depth_uav_planes = false) { 6995 const DXGI_FORMAT* castable, std::vector<VkFormat>& out, bool depth_uav_planes = false,
6996 bool console_d16s8 = false) {
4972 if (!count || !castable) return S_OK; 6997 if (!count || !castable) return S_OK;
4973 const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; 6998 const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0;
4974 const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects); 6999 const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects);
@@ -4985,6 +7010,13 @@ HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format,
4985 const bool valid = format.format == VK_FORMAT_D16_UNORM 7010 const bool valid = format.format == VK_FORMAT_D16_UNORM
4986 ? view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_D16_UNORM || 7011 ? view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_D16_UNORM ||
4987 view == DXGI_FORMAT_R16_UNORM || view == DXGI_FORMAT_R16_UINT 7012 view == DXGI_FORMAT_R16_UNORM || view == DXGI_FORMAT_R16_UINT
7013 : (format.xbox_depth16_stencil8 || console_d16s8)
7014 ? view == xbox_d16s8 || view == xbox_d16_plane || view == xbox_s8_plane ||
7015 (format.d24 && (view == DXGI_FORMAT_D24_UNORM_S8_UINT ||
7016 view == DXGI_FORMAT_R24_UNORM_X8_TYPELESS ||
7017 view == DXGI_FORMAT_X24_TYPELESS_G8_UINT)) ||
7018 view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_R16_UNORM ||
7019 view == DXGI_FORMAT_R16_UINT || view == DXGI_FORMAT_R8_UINT
4988 : view == DXGI_FORMAT_R32G8X24_TYPELESS || view == DXGI_FORMAT_D32_FLOAT_S8X24_UINT || 7020 : view == DXGI_FORMAT_R32G8X24_TYPELESS || view == DXGI_FORMAT_D32_FLOAT_S8X24_UINT ||
4989 view == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS || view == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT || 7021 view == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS || view == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT ||
4990 view == DXGI_FORMAT_R32_FLOAT || view == DXGI_FORMAT_R8_UINT; 7022 view == DXGI_FORMAT_R32_FLOAT || view == DXGI_FORMAT_R8_UINT;
@@ -5324,9 +7356,10 @@ public:
5324 desc_.NumDescriptors >= 65536 7356 desc_.NumDescriptors >= 65536
5325 ? DeviceState::heap_guard_bytes() 7357 ? DeviceState::heap_guard_bytes()
5326 : 0; 7358 : 0;
5327 if (guard && device.arena_allocate(bytes + guard, 256, arena_offset_, DeviceState::arena_descriptor_heap)) 7359 if (guard && device.arena_allocate(bytes + guard, 256, arena_offset_, DeviceState::arena_descriptor_heap)) {
5328 guard_ = guard; 7360 guard_ = guard;
5329 else if (!device.arena_allocate(bytes, 256, arena_offset_, DeviceState::arena_descriptor_heap)) { 7361 device.arena_guard_bytes.fetch_add(guard, std::memory_order_relaxed);
7362 } else if (!device.arena_allocate(bytes, 256, arena_offset_, DeviceState::arena_descriptor_heap)) {
5330 log_once("GPU address arena full (raise LEONIDA_ARENA_MB); shader-visible heap size in KiB:", 7363 log_once("GPU address arena full (raise LEONIDA_ARENA_MB); shader-visible heap size in KiB:",
5331 int(std::min<VkDeviceSize>(bytes / 1024, INT_MAX))); 7364 int(std::min<VkDeviceSize>(bytes / 1024, INT_MAX)));
5332 return; 7365 return;
@@ -5338,10 +7371,6 @@ public:
5338 std::lock_guard lock(device.visible_heap_mutex); 7371 std::lock_guard lock(device.visible_heap_mutex);
5339 device.visible_heaps[arena_offset_] = {arena_offset_ + bytes, desc.Type}; 7372 device.visible_heaps[arena_offset_] = {arena_offset_ + bytes, desc.Type};
5340 } 7373 }
5341 if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) {
5342 std::lock_guard lock(device.cbv_heap_mutex);
5343 device.cbv_heaps[arena_offset_] = arena_offset_ + bytes;
5344 }
5345 } else { 7374 } else {
5346 storage_.reset(new std::byte[std::size_t(bytes)]()); 7375 storage_.reset(new std::byte[std::size_t(bytes)]());
5347 cpu_ = reinterpret_cast<std::uint8_t*>(storage_.get()); 7376 cpu_ = reinterpret_cast<std::uint8_t*>(storage_.get());
@@ -5365,9 +7394,13 @@ public:
5365 std::lock_guard lock(device_.visible_heap_mutex); 7394 std::lock_guard lock(device_.visible_heap_mutex);
5366 device_.visible_heaps.erase(arena_offset_); 7395 device_.visible_heaps.erase(arena_offset_);
5367 } 7396 }
7397 if (in_arena_ && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) {
7398 device_.forget_nulled_table_slots(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize);
7399 }
5368 if (in_arena_) device_.arena_release(arena_offset_, 7400 if (in_arena_) device_.arena_release(arena_offset_,
5369 VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize + guard_, 7401 VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize + guard_,
5370 DeviceState::arena_descriptor_heap); 7402 DeviceState::arena_descriptor_heap);
7403 if (guard_) device_.arena_guard_bytes.fetch_sub(guard_, std::memory_order_relaxed);
5371 } 7404 }
5372 7405
5373 bool ok() const { return cpu_ != nullptr; } 7406 bool ok() const { return cpu_ != nullptr; }
@@ -5495,6 +7528,7 @@ public:
5495 device_.context->remove_resource(id()); 7528 device_.context->remove_resource(id());
5496 // Before the memory goes to the deferred queue: no submission copies into it after this. 7529 // Before the memory goes to the deferred queue: no submission copies into it after this.
5497 if (shadow_) device_.remove_shadow(shadow_); 7530 if (shadow_) device_.remove_shadow(shadow_);
7531 if (shadow_ && !in_arena_) device_.remove_copy_target(shadow_);
5498 if (host_import_) { 7532 if (host_import_) {
5499 // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole 7533 // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole
5500 // lifetime, and a title may free them right after releasing the resource. So the memory is not left to 7534 // lifetime, and a title may free them right after releasing the resource. So the memory is not left to
@@ -5619,13 +7653,12 @@ public:
5619 const bool host = cpu_visible(); 7653 const bool host = cpu_visible();
5620 leonida::ResourceBinding binding{}; // a buffer: no image 7654 leonida::ResourceBinding binding{}; // a buffer: no image
5621 binding.size = desc_.Width; 7655 binding.size = desc_.Width;
5622 if (!host && device_.arena.mapped) { 7656 const bool use_arena = !host && device_.arena.mapped;
5623 if (!device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, arena_offset_, 7657 if (use_arena && desc_.Width > device_.arena.size) return E_OUTOFMEMORY;
5624 DeviceState::arena_buffer)) { 7658 // An otherwise valid committed buffer can outgrow the largest free slice. Give it its own
5625 log_once("GPU address arena full (raise LEONIDA_ARENA_MB); buffer size in KiB:", 7659 // addressable VkBuffer below, so the title can still use its arena-relative GPU VA.
5626 int(desc_.Width / 1024)); 7660 if (use_arena && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT,
5627 return E_OUTOFMEMORY; 7661 arena_offset_, DeviceState::arena_buffer)) {
5628 }
5629 in_arena_ = true; 7662 in_arena_ = true;
5630 std::memset(device_.arena.mapped + arena_offset_, 0, std::size_t(desc_.Width)); 7663 std::memset(device_.arena.mapped + arena_offset_, 0, std::size_t(desc_.Width));
5631 va_ = arena_offset_; 7664 va_ = arena_offset_;
@@ -5636,8 +7669,8 @@ public:
5636 // No host pointer: this is DEFAULT-heap arena memory the GPU may write, so its mapped bytes can be 7669 // No host pointer: this is DEFAULT-heap arena memory the GPU may write, so its mapped bytes can be
5637 // stale. host_at() must not treat it as a CPU-written instance pointer list. 7670 // stale. host_at() must not treat it as a CPU-written instance pointer list.
5638 // A default-heap AS resource is one of these ranges: a GENERIC acceleration structure covers it where 7671 // A default-heap AS resource is one of these ranges: a GENERIC acceleration structure covers it where
5639 // it sits. It is named by its real device address (heap base + offset), as instance descriptors and 7672 // it sits. It is named by its device address (heap base + offset, as the driver reports it), as instance
5640 // BuildRaytracingAccelerationStructure hand that address to the driver, not a console VA. 7673 // descriptors and BuildRaytracingAccelerationStructure hand that address to the driver, not a console VA.
5641 if (device_.info.ray_tracing && 7674 if (device_.info.ray_tracing &&
5642 initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE && 7675 initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE &&
5643 vk.vkCreateAccelerationStructureKHR) { 7676 vk.vkCreateAccelerationStructureKHR) {
@@ -5648,12 +7681,34 @@ public:
5648 asci.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; 7681 asci.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR;
5649 if (vk.vkCreateAccelerationStructureKHR(device_.info.device, &asci, nullptr, &accel_) == VK_SUCCESS) { 7682 if (vk.vkCreateAccelerationStructureKHR(device_.info.device, &asci, nullptr, &accel_) == VK_SUCCESS) {
5650 gpu_va_ = device_.arena.address + va_; 7683 gpu_va_ = device_.arena.address + va_;
7684 // An instance names its BLAS by a value obtained from vkGetAccelerationStructureDeviceAddressKHR
7685 // (VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-12281), so ask for it, as the committed path
7686 // below does. For GENERIC the spec only promises that these addresses keep the offsets between
7687 // the structures of one buffer; drivers return buffer address + offset (vkd3d-proton checks the
7688 // same). If one ever does not, the driver's address is the one instances must hold.
7689 if (vk.vkGetAccelerationStructureDeviceAddressKHR) {
7690 VkAccelerationStructureDeviceAddressInfoKHR dai{
7691 VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR};
7692 dai.accelerationStructure = accel_;
7693 const std::uint64_t as_va =
7694 vk.vkGetAccelerationStructureDeviceAddressKHR(device_.info.device, &dai);
7695 if (as_va && as_va != gpu_va_) {
7696 log_once("GENERIC acceleration structure address is not its buffer address + offset; "
7697 "arena offset in KiB:", int(arena_offset_ / 1024));
7698 buffer_va_ = gpu_va_;
7699 gpu_va_ = as_va;
7700 }
7701 }
5651 device_.context->register_acceleration_structure(gpu_va_, accel_); 7702 device_.context->register_acceleration_structure(gpu_va_, accel_);
7703 if (buffer_va_ && buffer_va_ != gpu_va_)
7704 device_.context->register_acceleration_structure(buffer_va_, accel_);
5652 } 7705 }
5653 } 7706 }
5654 device_.context->add_resource(id(), binding); 7707 device_.context->add_resource(id(), binding);
5655 return S_OK; 7708 return S_OK;
5656 } 7709 }
7710 if (use_arena)
7711 log_once("GPU address arena full; using a dedicated default buffer, size in KiB:", int(desc_.Width / 1024));
5657 const bool addressable = device_.arena.buffer != VK_NULL_HANDLE; 7712 const bool addressable = device_.arena.buffer != VK_NULL_HANDLE;
5658 const bool need_bda = device_.info.buffer_device_address || device_.info.ray_tracing; 7713 const bool need_bda = device_.info.buffer_device_address || device_.info.ray_tracing;
5659 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 7714 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
@@ -5691,8 +7746,8 @@ public:
5691 VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; 7746 VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
5692 address.buffer = buffer_; 7747 address.buffer = buffer_;
5693 va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address; 7748 va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address;
5694 device_.log_va(heap_.Type == D3D12_HEAP_TYPE_READBACK ? "readback buffer" : "upload buffer", va_, 7749 const char* name = heap_.Type == D3D12_HEAP_TYPE_READBACK ? "readback buffer" : "upload buffer";
5695 desc_.Width); 7750 device_.log_va(host ? name : "default buffer", va_, desc_.Width);
5696 } 7751 }
5697 if (host) { 7752 if (host) {
5698 if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) 7753 if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS)
@@ -6007,6 +8062,7 @@ public:
6007 vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) 8062 vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS)
6008 return E_OUTOFMEMORY; 8063 return E_OUTOFMEMORY;
6009 shadow_ = static_cast<std::uint8_t*>(shadow); 8064 shadow_ = static_cast<std::uint8_t*>(shadow);
8065 device_.add_copy_target(shadow_, std::size_t(desc_.Width), buffer_); // LEONIDA_SHADOW_GPU
6010 device_.add_shadow(pages, shadow_, std::size_t(desc_.Width)); 8066 device_.add_shadow(pages, shadow_, std::size_t(desc_.Width));
6011 // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be 8067 // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be
6012 // overwritten by the next copy. 8068 // overwritten by the next copy.
@@ -6105,6 +8161,7 @@ public:
6105 aspects_ = format.aspects; 8161 aspects_ = format.aspects;
6106 image_address_ = device_.next_image_address.fetch_add(256); 8162 image_address_ = device_.next_image_address.fetch_add(256);
6107 device_.note_image_address(image_address_, this); 8163 device_.note_image_address(image_address_, this);
8164 DeviceState::trace_image(image_address_, id(), "registered");
6108 binding_.image = image_; 8165 binding_.image = image_;
6109 binding_.format = format_; 8166 binding_.format = format_;
6110 binding_.aspects = aspects_; 8167 binding_.aspects = aspects_;
@@ -6450,6 +8507,7 @@ public:
6450 aspects_ = format.aspects; 8507 aspects_ = format.aspects;
6451 image_address_ = device_.next_image_address.fetch_add(256); 8508 image_address_ = device_.next_image_address.fetch_add(256);
6452 device_.note_image_address(image_address_, this); 8509 device_.note_image_address(image_address_, this);
8510 DeviceState::trace_image(image_address_, id(), "registered");
6453 binding.deferred_memory = deferred_attachment_.get(); 8511 binding.deferred_memory = deferred_attachment_.get();
6454 if (origin == TitleImageOrigin::placed && leonida::mem_probe::interval_seconds()) 8512 if (origin == TitleImageOrigin::placed && leonida::mem_probe::interval_seconds())
6455 binding.replay_seen = &replay_seen_; 8513 binding.replay_seen = &replay_seen_;
@@ -6570,10 +8628,13 @@ private:
6570 } 8628 }
6571 8629
6572public: 8630public:
8631 void mark_console_d16s8() { console_d16s8_ = true; }
8632 bool console_d16s8() const { return console_d16s8_; }
8633
6573 // The Xbox proxy calls this before publishing an allocated depth texture. Each storage plane owns a 8634 // The Xbox proxy calls this before publishing an allocated depth texture. Each storage plane owns a
6574 // regular color image with its own GFX10 address, so a UAV cannot replace the original SRV in set 0. 8635 // regular color image with its own GFX10 address, so a UAV cannot replace the original SRV in set 0.
6575 HRESULT enable_depth_stencil_uav(D3D12_HEAP_FLAGS storage_heap_flags) { 8636 HRESULT enable_depth_stencil_uav(D3D12_HEAP_FLAGS storage_heap_flags) {
6576 const bool narrow_stencil = desc_.Format == xbox_d16s8; 8637 const bool narrow_stencil = desc_.Format == xbox_d16s8 || console_d16s8_;
6577 const bool depth16 = desc_.Format == DXGI_FORMAT_R16_TYPELESS || narrow_stencil; 8638 const bool depth16 = desc_.Format == DXGI_FORMAT_R16_TYPELESS || narrow_stencil;
6578 if (!image_ || (!depth16 && desc_.Format != DXGI_FORMAT_R32G8X24_TYPELESS) || 8639 if (!image_ || (!depth16 && desc_.Format != DXGI_FORMAT_R32G8X24_TYPELESS) ||
6579 !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || 8640 !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) ||
@@ -6590,7 +8651,10 @@ public:
6590 std::unique_ptr<Resource> conversion; 8651 std::unique_ptr<Resource> conversion;
6591 if (widened) { 8652 if (widened) {
6592 const auto blit = VK_FORMAT_FEATURE_2_BLIT_SRC_BIT | VK_FORMAT_FEATURE_2_BLIT_DST_BIT; 8653 const auto blit = VK_FORMAT_FEATURE_2_BLIT_SRC_BIT | VK_FORMAT_FEATURE_2_BLIT_DST_BIT;
6593 if (format_ != VK_FORMAT_D32_SFLOAT_S8_UINT || (device_.optimal_features(VK_FORMAT_R16_UNORM) & blit) != blit || 8654 const bool d24_backing = format_ == VK_FORMAT_D24_UNORM_S8_UINT;
8655 if ((format_ != VK_FORMAT_D32_SFLOAT_S8_UINT && !d24_backing) ||
8656 (d24_backing && !device_.context->has_depth24()) ||
8657 (device_.optimal_features(VK_FORMAT_R16_UNORM) & blit) != blit ||
6594 (device_.optimal_features(VK_FORMAT_R32_SFLOAT) & blit) != blit) return E_NOTIMPL; 8658 (device_.optimal_features(VK_FORMAT_R32_SFLOAT) & blit) != blit) return E_NOTIMPL;
6595 auto intermediate = plane_desc; 8659 auto intermediate = plane_desc;
6596 intermediate.Format = DXGI_FORMAT_R32_FLOAT; 8660 intermediate.Format = DXGI_FORMAT_R32_FLOAT;
@@ -6673,6 +8737,7 @@ public:
6673 device_.forget_image(va); // an earlier texture placed at this address, still alive: its views are stale 8737 device_.forget_image(va); // an earlier texture placed at this address, still alive: its views are stale
6674 image_address_ = va; 8738 image_address_ = va;
6675 device_.note_image_address(image_address_, this); 8739 device_.note_image_address(image_address_, this);
8740 DeviceState::trace_image(image_address_, id(), "registered");
6676 } 8741 }
6677 // The title's own address for a texture Xbox slot 133 placed. The image is still the committed fallback, so its 8742 // The title's own address for a texture Xbox slot 133 placed. The image is still the committed fallback, so its
6678 // pixels do not alias the title's pages yet; the address is what GetGPUVirtualAddress answers (XCL PR #168's 8743 // pixels do not alias the title's pages yet; the address is what GetGPUVirtualAddress answers (XCL PR #168's
@@ -6744,6 +8809,27 @@ public:
6744 // no pointer to give (its layout is the driver's), so D3D12 only lets it be mapped with a null pointer, before 8809 // no pointer to give (its layout is the driver's), so D3D12 only lets it be mapped with a null pointer, before
6745 // WriteToSubresource/ReadFromSubresource. 8810 // WriteToSubresource/ReadFromSubresource.
6746 HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override { 8811 HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override {
8812 // LOCAL DIAGNOSTIC: LEONIDA_LOCK_TRACE=1 logs the first 256 texture Maps with a read range: the title's
8813 // texture lock passes the subresource's byte range there, computed from its XG computer's
8814 // layout, and adds the range's start to the pointer this answers.
8815 static const bool lock_trace = [] {
8816 char value[2]{};
8817 return GetEnvironmentVariableA("LEONIDA_LOCK_TRACE", value, sizeof(value)) == 1 && value[0] == '1';
8818 }();
8819 if (lock_trace && read && image_) {
8820 static std::atomic<int> logged{0};
8821 if (logged.fetch_add(1, std::memory_order_relaxed) < 256) {
8822 const auto caller = reinterpret_cast<std::uintptr_t>(_ReturnAddress());
8823 std::fprintf(stderr,
8824 "[rt] d3d12: LOCAL DIAGNOSTIC: Map sub %u range 0x%llx..0x%llx of texture %llux%ux%u "
8825 "fmt %d flags 0x%x at 0x%llx, caller 0x%llx\n",
8826 subresource, static_cast<unsigned long long>(read->Begin),
8827 static_cast<unsigned long long>(read->End), static_cast<unsigned long long>(desc_.Width),
8828 desc_.Height, unsigned(desc_.DepthOrArraySize), int(desc_.Format), unsigned(desc_.Flags),
8829 static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(title_address_)),
8830 static_cast<unsigned long long>(caller));
8831 }
8832 }
6747 // A texture whose lease says its title memory is linear (title_linear_) and that also has a placement 8833 // A texture whose lease says its title memory is linear (title_linear_) and that also has a placement
6748 // address (slot 133; the video planes among them) has two answers. The placement address, with the title 8834 // address (slot 133; the video planes among them) has two answers. The placement address, with the title
6749 // texture registry filling the image, is the one the retail boot ran through the intro movie and the story 8835 // texture registry filling the image, is the one the retail boot ran through the intro movie and the story
@@ -7134,6 +9220,7 @@ private:
7134 if (!device_.staging_queue) { 9220 if (!device_.staging_queue) {
7135 device_.staging_queue = std::make_unique<leonida::VulkanQueue>(*device_.context, device_.info.queue, 9221 device_.staging_queue = std::make_unique<leonida::VulkanQueue>(*device_.context, device_.info.queue,
7136 device_.info.queue_family); 9222 device_.info.queue_family);
9223 device_.staging_queue->make_synchronous(); // waited for at once (idle below)
7137 } 9224 }
7138 if (device_.staging_queue->ok()) { 9225 if (device_.staging_queue->ok()) {
7139 const leonida::CommandList* lists[] = {&list}; 9226 const leonida::CommandList* lists[] = {&list};
@@ -7206,6 +9293,7 @@ private:
7206 leonida::ResourceBinding binding_{}; // a texture's, as registered with the context 9293 leonida::ResourceBinding binding_{}; // a texture's, as registered with the context
7207 std::unique_ptr<Resource> depth_conversion_; 9294 std::unique_ptr<Resource> depth_conversion_;
7208 std::array<std::unique_ptr<Resource>, 2> storage_planes_; // Xbox depth/stencil UAV, by plane 9295 std::array<std::unique_ptr<Resource>, 2> storage_planes_; // Xbox depth/stencil UAV, by plane
9296 bool console_d16s8_ = false; // created from Xbox format 118 (even when pc_format made it D24S8)
7209 VkImage shared_zero_ = VK_NULL_HANDLE; // owned by the device 9297 VkImage shared_zero_ = VK_NULL_HANDLE; // owned by the device
7210 std::unique_ptr<leonida::DeferredImageBinding> deferred_attachment_; 9298 std::unique_ptr<leonida::DeferredImageBinding> deferred_attachment_;
7211 std::atomic<bool> replay_seen_{false}; 9299 std::atomic<bool> replay_seen_{false};
@@ -7808,6 +9896,7 @@ struct PipelineStream {
7808 D3D12_SHADER_BYTECODE as{}; 9896 D3D12_SHADER_BYTECODE as{};
7809 bool has_cs = false; 9897 bool has_cs = false;
7810 bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS 9898 bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS
9899 bool depth_bounds = false; // DEPTH_STENCIL1/2 DepthBoundsTestEnable (not in the plain graphics desc)
7811}; 9900};
7812 9901
7813// Console stream retry adapted from Kokonotcu, ubiquitarianism/leonida #496 (GPL-3.0). 9902// Console stream retry adapted from Kokonotcu, ubiquitarianism/leonida #496 (GPL-3.0).
@@ -7946,9 +10035,7 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe
7946 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: { 10035 case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: {
7947 D3D12_DEPTH_STENCIL_DESC1 d{}; 10036 D3D12_DEPTH_STENCIL_DESC1 d{};
7948 take(d); 10037 take(d);
7949 if (ok && d.DepthBoundsTestEnable) { 10038 if (ok) out.depth_bounds = d.DepthBoundsTestEnable != FALSE;
7950 return stream_unsupported("depth-bounds tests are not supported yet; stream subobject", int(type));
7951 }
7952 g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, d.StencilReadMask, 10039 g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, d.StencilReadMask,
7953 d.StencilWriteMask, d.FrontFace, d.BackFace}; 10040 d.StencilWriteMask, d.FrontFace, d.BackFace};
7954 break; 10041 break;
@@ -7957,9 +10044,7 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe
7957 D3D12_DEPTH_STENCIL_DESC2 d{}; 10044 D3D12_DEPTH_STENCIL_DESC2 d{};
7958 take(d); 10045 take(d);
7959 if (!ok) break; 10046 if (!ok) break;
7960 if (d.DepthBoundsTestEnable) { 10047 out.depth_bounds = d.DepthBoundsTestEnable != FALSE;
7961 return stream_unsupported("depth-bounds tests are not supported yet; stream subobject", int(type));
7962 }
7963 // Each face has its own read and write mask (OPTIONS14.IndependentFrontAndBackStencilRefMaskSupported): 10048 // Each face has its own read and write mask (OPTIONS14.IndependentFrontAndBackStencilRefMaskSupported):
7964 // the description takes the front face's, back_stencil the back face's. 10049 // the description takes the front face's, back_stencil the back face's.
7965 out.back_masks = true; 10050 out.back_masks = true;
@@ -8018,6 +10103,410 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe
8018// its FSSM program in the translator's index, and the FSSM blob is copied into the arena as the shader's code base. 10103// its FSSM program in the translator's index, and the FSSM blob is copied into the arena as the shader's code base.
8019std::atomic<long> live_pipeline_state_count{0}; // live_pipeline_states() 10104std::atomic<long> live_pipeline_state_count{0}; // live_pipeline_states()
8020 10105
10106// What the bindless set layout was made from, for a compute pipeline's journal name: a pipeline built against another
10107// layout is another pipeline. Field by field, so padding never reaches the hash.
10108void hash_bindless_layout(leonida::pipeline_journal::Hasher& hash, const leonida::BindlessFeatures& features) {
10109 for (const std::uint32_t count : features.counts) hash.value(count);
10110 hash.value(std::uint8_t(features.update_after_bind));
10111 hash.value(std::uint8_t(features.partially_bound));
10112 hash.value(std::uint8_t(features.null_descriptor));
10113 for (const VkSampleCountFlagBits samples : features.ms_samples) hash.value(std::uint32_t(samples));
10114}
10115
10116// Opt in on this branch. Async workers normally compile while other queues submit.
10117std::unique_lock<leonida::SubmitMutex> compute_driver_turn(DeviceState& device) {
10118 static const bool enabled = [] {
10119 wchar_t value[2]{};
10120 return GetEnvironmentVariableW(L"LEONIDA_COMPILE_GATE", value, 2) == 1 && value[0] == L'1';
10121 }();
10122 std::unique_lock turn(device.context->submit_mutex(), std::defer_lock);
10123 if (enabled) turn.lock();
10124 return turn;
10125}
10126
10127// LOCAL FIX (pipeline journal, pipeline_cache_journal.h): one compute pipeline's own VkPipelineCache for the length
10128// of its build. load() reads the journal file, before any driver call. In the build's one compile-gate turn,
10129// create() makes the cache from the file's contents (seeded) or empty, and finish() takes the cache's data when the
10130// pipeline had to be compiled and destroys the cache. publish(), after the turn, writes the file, or refreshes its
10131// last use after a hit: no file I/O in the turn. Nothing else uses the cache, so it needs no synchronization beyond
10132// the build's own.
10133class JournalCache {
10134public:
10135 VkPipelineCache cache = VK_NULL_HANDLE;
10136 bool seeded = false; // made from the file's contents
10137
10138 JournalCache(DeviceState& device, leonida::SubmitMutex& submits, const char* trigger, const char* name)
10139 : device_(device), submits_(&submits), trigger_(trigger), name_(name) {}
10140 // A build outside the submit lock's owners (the async compile workers' own turn helper): compute_driver_turn.
10141 JournalCache(DeviceState& device, const char* name) : device_(device), name_(name) {}
10142 JournalCache(const JournalCache&) = delete;
10143 JournalCache& operator=(const JournalCache&) = delete;
10144 ~JournalCache() {
10145 if (!cache) return; // finish() always destroys it; this is only for a build that left early
10146 if (submits_) {
10147 const DriverTurn turn(*submits_, trigger_, "vkDestroyPipelineCache", true, name_);
10148 device_.context->vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr);
10149 } else {
10150 const auto turn = compute_driver_turn(device_);
10151 device_.context->vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr);
10152 }
10153 }
10154
10155 bool enabled() const { return enabled_; }
10156 bool has_file_data() const { return !file_.data.empty(); }
10157 bool found() const { return enabled_ && built_ && !write_; } // the pipeline came out of the journal file
10158 bool written() const { return written_; } // publish() wrote the file
10159
10160 void load(std::filesystem::path path) {
10161 const auto& vk = device_.context->vk;
10162 if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkGetPipelineCacheData) return;
10163 enabled_ = true;
10164 path_ = std::move(path);
10165 namespace journal = leonida::pipeline_journal;
10166 const auto role = compile_helper::build_host.load() ? journal::ReadRole::materialize_local : journal::ReadRole::runtime;
10167 file_ = journal::read_with_seed(path_, pipeline_journal_roots().seed, device_.pso_identity, role);
10168 }
10169
10170 // In the build's driver turn.
10171 void create() {
10172 if (!enabled_) return;
10173 const auto& vk = device_.context->vk;
10174 VkPipelineCacheCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, file_.data.size(),
10175 file_.data.empty() ? nullptr : file_.data.data()};
10176 if (!file_.data.empty() && vk.vkCreatePipelineCache(device_.info.device, &info, nullptr, &cache) == VK_SUCCESS) {
10177 seeded = true;
10178 } else {
10179 cache = VK_NULL_HANDLE; // no file, or one the driver declined: start empty, and the build rewrites it
10180 info.initialDataSize = 0;
10181 info.pInitialData = nullptr;
10182 if (vk.vkCreatePipelineCache(device_.info.device, &info, nullptr, &cache) != VK_SUCCESS) cache = VK_NULL_HANDLE;
10183 }
10184 std::vector<char>().swap(file_.data); // the driver has its own copy
10185 }
10186
10187 // In the build's driver turn, after the create against `cache`. `built`: that create made the pipeline; `hit`:
10188 // its creation feedback; `driver_ms`: the vkCreateComputePipelines call alone.
10189 void finish(bool built, int hit, std::uint64_t driver_ms) {
10190 if (!cache) return;
10191 const auto& vk = device_.context->vk;
10192 built_ = built;
10193 write_ = built && leonida::pipeline_journal::should_write(seeded, hit, driver_ms);
10194 if (write_) {
10195 std::size_t size = 0;
10196 result_ = vk.vkGetPipelineCacheData(device_.info.device, cache, &size, nullptr);
10197 if (result_ == VK_SUCCESS && size > leonida::pipeline_cache_store::header_bytes &&
10198 size <= leonida::pipeline_journal::entry_read_limit) {
10199 blob_.resize(size);
10200 result_ = vk.vkGetPipelineCacheData(device_.info.device, cache, &size, blob_.data());
10201 blob_.resize(result_ == VK_SUCCESS ? size : 0);
10202 }
10203 data_size_ = size;
10204 }
10205 vk.vkDestroyPipelineCache(device_.info.device, cache, nullptr);
10206 cache = VK_NULL_HANDLE;
10207 }
10208
10209 // The shared cache had the pipeline (FAIL_ON_PIPELINE_COMPILE_REQUIRED gave it, as a hit or quickly).
10210 void found_in_shared() { report(device_.journal_shared_hits.fetch_add(1) + 1, "found in the shared cache"); }
10211
10212 // After the driver turn.
10213 void publish() {
10214 namespace journal = leonida::pipeline_journal;
10215 if (!enabled_ || !built_) return;
10216 if (!write_) {
10217 report(device_.journal_hits.fetch_add(1) + 1, "found in their journal file");
10218 journal::touch_local_hit(path_, file_, std::filesystem::file_time_type::clock::now());
10219 return;
10220 }
10221 if (blob_.size() <= leonida::pipeline_cache_store::header_bytes) {
10222 std::fprintf(stderr, "[rt] d3d12: pipeline journal: no cache data for %s (VkResult %d, %zu bytes)\n",
10223 name_, int(result_), data_size_);
10224 return;
10225 }
10226 // A rewrite replaces the file's old size. Two builds of one name at once may both count: the next boot's
10227 // tidy counts again.
10228 if (journal::replace_bytes(device_.journal_bytes.load(), file_.bytes, blob_.size()) > device_.journal_budget) {
10229 static std::atomic<bool> said{false};
10230 if (!said.exchange(true))
10231 std::fprintf(stderr, "[rt] d3d12: pipeline journal: %llu bytes on disk, the %llu-byte budget "
10232 "(LEONIDA_PIPELINE_JOURNAL_BYTES) is spent; nothing more is written this boot\n",
10233 static_cast<unsigned long long>(device_.journal_bytes.load()),
10234 static_cast<unsigned long long>(device_.journal_budget));
10235 return;
10236 }
10237 if (const std::error_code error = journal::write_entry(path_, blob_.data(), blob_.size())) {
10238 static std::atomic<bool> said{false};
10239 if (!said.exchange(true))
10240 std::fprintf(stderr, "[rt] d3d12: pipeline journal: could not write %ls: %s\n", path_.c_str(),
10241 error.message().c_str());
10242 return;
10243 }
10244 auto total = device_.journal_bytes.load();
10245 while (!device_.journal_bytes.compare_exchange_weak(total, journal::replace_bytes(total, file_.bytes, blob_.size()))) {
10246 }
10247 written_ = true;
10248 report(device_.journal_writes.fetch_add(1) + 1, "compiled and written to their journal file");
10249 }
10250
10251private:
10252 // The first of each kind, then every 100th, with all three counts.
10253 void report(unsigned count, const char* what) const {
10254 if (count != 1 && count % 100) return;
10255 std::fprintf(stderr, "[rt] d3d12: pipeline journal: %u compute pipeline(s) %s (so far: %u from journal files, "
10256 "%u written, %u from the shared cache)\n", count, what,
10257 device_.journal_hits.load(), device_.journal_writes.load(), device_.journal_shared_hits.load());
10258 }
10259
10260 DeviceState& device_;
10261 leonida::SubmitMutex* submits_ = nullptr; // null: compute_driver_turn, for a build outside the submit lock
10262 const char* trigger_ = "";
10263 const char* name_;
10264 bool enabled_ = false;
10265 bool built_ = false;
10266 bool write_ = false;
10267 bool written_ = false;
10268 std::filesystem::path path_;
10269 leonida::pipeline_journal::EntryFile file_;
10270 std::vector<char> blob_;
10271 std::size_t data_size_ = 0;
10272 VkResult result_ = VK_SUCCESS;
10273};
10274
10275// What one compute pipeline build did (build_compute_pipeline).
10276struct ComputeBuild {
10277 VkPipeline pipeline = VK_NULL_HANDLE; // the caller's from here on
10278 VkResult result = VK_ERROR_UNKNOWN;
10279 std::size_t bytes = 0; // SPIR-V
10280 ULONGLONG ms = 0; // the whole build
10281 std::filesystem::path journal_path; // its journal file's name (empty with the journal off)
10282 bool skipped = false; // ComputeBuildOptions::skip_journaled and the journal file was there: nothing built
10283 bool busy = false; // ComputeBuildOptions::mark_building and another process is building it: nothing built
10284 bool deferred = false; // asked of the compile helper without waiting: nothing built yet
10285 bool journal_hit = false; // found in its journal file
10286 bool journaled = false; // compiled and written to its journal file
10287 bool from_shared = false; // found in the shared cache
10288};
10289
10290struct ComputeBuildOptions {
10291 const char* trigger = "dispatch"; // what asked: dispatch, warmup, dispatch-worker, precompile...
10292 const std::string* cache_key = nullptr; // the title's PSO description key, for the compile trace
10293 bool serialize_big = true; // LEONIDA_SERIAL_BIG_COMPILES=1: modules over 128 KiB one at a time
10294 bool skip_journaled = false; // precompile: leave a pipeline whose journal file exists alone
10295 bool use_helper = true; // LEONIDA_COMPILE_HELPER: a missing journal file comes from the helper
10296 bool helper_wait = true; // wait for the helper's file (false: ask, and answer deferred)
10297 std::uint64_t helper_priority = 0; // the request's urgency: 0 a dispatch, else the warm-up's module size
10298 bool mark_building = false; // precompile, helper: claim the entry, skip it when another process has it
10299 bool key_only = false; // only name the journal file (journal_path), build nothing
10300};
10301
10302// A compute pipeline from a library entry: what a PSO's first dispatch, the warm-up worker and gta6rt
10303// --precompile-pipelines all build, so their journal names and the driver's keys are the same. `layout` is the push
10304// range of leonida::ShaderUserData, with the device's bindless set 0 when the entry declares bindings; `subgroup` is
10305// leonida::decide_subgroup_size's answer for the entry.
10306ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEntry& compute_entry,
10307 VkPipelineLayout layout, const leonida::SubgroupRequest& subgroup,
10308 const ComputeBuildOptions& options) {
10309 ComputeBuild out;
10310 CompileActivity activity(device.active_compiles);
10311 const char* const trigger = options.trigger;
10312 std::filesystem::path marked; // mark_building: released on the way out
10313 struct Unmark {
10314 std::filesystem::path& path;
10315 ~Unmark() {
10316 if (!path.empty()) compile_helper::unmark_building(path);
10317 }
10318 } unmark{marked};
10319 static const std::string no_key;
10320 auto& vk = device.context->vk;
10321 const VkDevice dev = device.info.device;
10322 const leonida::ShaderLibrary* library = device.library();
10323 const leonida::ShaderEntry* entry = &compute_entry;
10324 if (!library) return out;
10325 // The driver's compiler needs hundreds of MiB per very large module; several at once exhausted host memory. By
10326 // default large modules share a memory budget (big_compile_gate, taken by the caller before any PSO lock: see
10327 // PipelineState::enter_build); LEONIDA_SERIAL_BIG_COMPILES=1 compiles them one at a time here instead.
10328 static std::mutex big_compile;
10329 std::unique_lock<std::mutex> big_lock(big_compile, std::defer_lock); // taken below, only for a compile here
10330 auto words = library->spirv(*entry);
10331 if (words.empty()) {
10332 std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str());
10333 return out;
10334 }
10335 const std::size_t bytes = words.size() * sizeof(std::uint32_t);
10336 out.bytes = bytes;
10337 VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
10338 pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
10339 pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
10340 pipeline_info.stage.pName = "main";
10341 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{};
10342 leonida::apply_subgroup_request(subgroup, required_size, pipeline_info.stage);
10343 pipeline_info.layout = layout;
10344 pipeline_info.flags |= fast_pipeline_flags(true); // before the journal key, which hashes the flags
10345 const VkPipelineCache shared = device.pipeline_cache();
10346 auto& submits = device.context->submit_mutex();
10347
10348 // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): the pipeline is created against its own cache, made
10349 // from its journal file or empty and written back after a compile, so a boot killed or crashed later keeps it.
10350 // The file is named by what the pipeline is made of and read here, before the driver turn. Without a file
10351 // the shared cache (seeded from the offline corpus or the last session) is asked first, without a compile.
10352 JournalCache journal(device, submits, trigger, entry->name.c_str());
10353 if (const std::filesystem::path& journal_dir = pipeline_journal_dir(); !journal_dir.empty()) {
10354 leonida::pipeline_journal::Hasher key;
10355 key.text("cs");
10356 key.value(std::uint64_t(words.size()));
10357 key.bytes(words.data(), bytes);
10358 key.text(pipeline_info.stage.pName);
10359 key.value(std::uint32_t(pipeline_info.flags));
10360 key.value(std::uint32_t(pipeline_info.stage.flags));
10361 key.value(std::uint32_t(pipeline_info.stage.pNext == &required_size ? required_size.requiredSubgroupSize : 0));
10362 key.value(std::uint32_t(sizeof(leonida::ShaderUserData)));
10363 key.value(std::uint32_t(entry->binding_count != 0));
10364 // NVIDIA's diagnostics config (LEONIDA_DEVICE_FAULT=1, Aftermath) compiles with shader debug info: other
10365 // pipelines, kept apart so switching it on and off does not rewrite every file. Absent when off, so the
10366 // names of ordinary boots stay as they were.
10367 if (device.info.device_diagnostics_config) {
10368 key.text("nv-diagnostics-config");
10369 key.value(std::uint32_t(leonida::aftermath::extra_config_flags()));
10370 }
10371 if (entry->binding_count) hash_bindless_layout(key, device.bindless->features());
10372 const auto path = leonida::pipeline_journal::entry_path(journal_dir, "cs", key.digest());
10373 out.journal_path = path;
10374 if (options.key_only) return out;
10375 // Precompile: a usable file is there already, so the pipeline is not built (only its header is read).
10376 if (options.skip_journaled && leonida::pipeline_journal::entry_usable(path, device.pso_identity)) {
10377 out.skipped = true;
10378 return out;
10379 }
10380 journal.load(path);
10381 // LOCAL FIX (compile helper, d3d12_compile_helper.h): no file, so this would be a compile in this process,
10382 // where the driver's lock it holds stops the title's submissions. The helper process compiles it into the file
10383 // instead, and the create below is a hit. Asked without waiting, the build answers deferred and is asked
10384 // again at the pipeline's next use; waited for, nothing of ours is in the driver meanwhile.
10385 if (!journal.has_file_data() && options.use_helper && compile_helper::wanted(bytes)) {
10386 auto& helper = compile_helper::Client::instance();
10387 std::string why;
10388 if (!options.helper_wait) {
10389 if (helper.request(path, entry->name, options.helper_priority, device.pso_identity, &why)) {
10390 out.deferred = true;
10391 return out;
10392 }
10393 std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s; built here\n", why.c_str(),
10394 entry->name.c_str());
10395 } else {
10396 const ULONGLONG asked = GetTickCount64();
10397 if (helper.build(path, entry->name, device.pso_identity, &why)) {
10398 journal.load(path);
10399 std::fprintf(stderr, "[rt] d3d12: compile helper built %s in %.1f s (%zu B SPIR-V, %s)\n",
10400 entry->name.c_str(), double(GetTickCount64() - asked) / 1000.0, bytes, trigger);
10401 } else {
10402 std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s after %.1f s; built here\n",
10403 why.c_str(), entry->name.c_str(), double(GetTickCount64() - asked) / 1000.0);
10404 }
10405 }
10406 }
10407 // Precompile and helper: another process compiling this entry is left to it.
10408 if (options.mark_building && !journal.has_file_data()) {
10409 if (!compile_helper::mark_building(path)) {
10410 out.busy = true;
10411 return out;
10412 }
10413 marked = path;
10414 }
10415 }
10416 // Only a compile here is serialized: a pipeline from its journal file takes milliseconds.
10417 if (!journal.has_file_data() && options.serialize_big && big_compiles() == BigCompiles::serial && big_compute(bytes))
10418 big_lock.lock();
10419 const bool ask_shared = journal.enabled() && !journal.has_file_data() && shared && device.pipeline_cache_seeded &&
10420 device.info.pipeline_cache_control && device.journal_ask_shared.load();
10421
10422 VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
10423 module_info.codeSize = bytes;
10424 module_info.pCode = words.data();
10425 VkShaderModule module = VK_NULL_HANDLE;
10426 const ULONGLONG started = GetTickCount64();
10427 VkPipeline built = VK_NULL_HANDLE;
10428 CompileTrace trace;
10429 trace.begin(pipeline_info, device.info.pipeline_creation_feedback, trigger, entry->name.c_str(), 0, bytes, options.cache_key ? *options.cache_key : no_key);
10430 // Was it in the cache? Core feedback on a Vulkan 1.3 device; pipeline_cache_control implies one.
10431 if (journal.enabled() && device.info.pipeline_cache_control) trace.request_feedback(pipeline_info);
10432 const leonida::dev_status::Build dev_build(entry->name.c_str());
10433 const leonida::pipeline_profile::DriverCall profile("cs", trigger, entry->name.c_str());
10434 // LOCAL DIAGNOSTIC (early device loss): a vkQueueSubmit was measured blocking 10 s and losing the device
10435 // while another thread sat in this call. Name what is building (once past the gate: in the driver), and log
10436 // the start of big ones.
10437 auto& compiling = leonida::driver_compile;
10438 VkResult created = VK_ERROR_UNKNOWN;
10439 bool from_shared = false, probe_compiled = false;
10440 ULONGLONG probe_ms = 0, driver_ms = 0;
10441 {
10442 // Every driver call of the build (shader module, journal cache, pipeline) in one turn through the compile
10443 // gate: from the journal a build takes milliseconds and the warm-up worker makes them back to back, and
10444 // three warm boots lost the device in a vkQueueSubmit (no GPU fault, no TDR) while only the create was
10445 // gated. No file I/O in here.
10446 const DriverTurn turn(submits, trigger, "vkCreateComputePipelines", true, entry->name.c_str());
10447 {
10448 const leonida::aftermath::ShaderName named(entry->name);
10449 if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return out;
10450 }
10451 pipeline_info.stage.module = module;
10452 journal.create();
10453 const VkPipelineCache cache = journal.cache ? journal.cache : shared;
10454 compiling.bytes.store(bytes, std::memory_order_relaxed);
10455 compiling.trigger.store(trigger, std::memory_order_relaxed);
10456 compiling.since_ms.store(leonida::diagnostic_ms(), std::memory_order_relaxed);
10457 compiling.name.store(entry->name.c_str(), std::memory_order_release);
10458 if (bytes >= 128 * 1024)
10459 std::fprintf(stderr, "[rt] d3d12: compute pipeline %s (%zu B SPIR-V, %s) build starts at t=%.3f s\n",
10460 entry->name.c_str(), bytes, trigger, double(leonida::diagnostic_ms()) / 1000.0);
10461 if (ask_shared) {
10462 // VK_PIPELINE_COMPILE_REQUIRED (a success code, no pipeline) when the shared cache does not have it.
10463 pipeline_info.flags |= VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT;
10464 const ULONGLONG asked = GetTickCount64();
10465 created = vk.vkCreateComputePipelines(dev, shared, 1, &pipeline_info, nullptr, &built);
10466 probe_ms = GetTickCount64() - asked;
10467 pipeline_info.flags &= ~VkPipelineCreateFlags(VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT);
10468 from_shared = created == VK_SUCCESS && built;
10469 if (from_shared && leonida::pipeline_journal::probe_compiled(trace.hit(), probe_ms)) {
10470 // NVIDIA 630.20 compiled it instead of answering VK_PIPELINE_COMPILE_REQUIRED, into the shared
10471 // cache. Built once more against the journal cache below, so it is journaled; asking stops.
10472 vk.vkDestroyPipeline(dev, built, nullptr);
10473 from_shared = false;
10474 probe_compiled = true;
10475 }
10476 if (!from_shared) built = VK_NULL_HANDLE;
10477 }
10478 if (!from_shared) {
10479 const ULONGLONG at = GetTickCount64();
10480 created = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &built);
10481 driver_ms = GetTickCount64() - at;
10482 }
10483 compiling.name.store(nullptr, std::memory_order_release);
10484 vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists
10485 journal.finish(!from_shared && created == VK_SUCCESS && built, trace.hit(), driver_ms);
10486 }
10487 std::vector<std::uint32_t>().swap(words);
10488 profile.finish(int(created));
10489 trace.end(trigger, entry->name.c_str(), 0, bytes, created);
10490 if (big_lock.owns_lock()) big_lock.unlock();
10491 if (probe_compiled && device.journal_ask_shared.exchange(false))
10492 std::fprintf(stderr, "[rt] d3d12: pipeline journal: the driver compiled %s for "
10493 "FAIL_ON_PIPELINE_COMPILE_REQUIRED (%llu ms, no cache hit); built again for its journal "
10494 "file, and the shared cache is no longer asked first\n", entry->name.c_str(),
10495 static_cast<unsigned long long>(probe_ms));
10496 if (from_shared) journal.found_in_shared();
10497 journal.publish();
10498 out.pipeline = built;
10499 out.result = created;
10500 out.from_shared = from_shared;
10501 out.journal_hit = journal.found();
10502 out.journaled = journal.written();
10503 out.ms = GetTickCount64() - started;
10504 if (created == VK_SUCCESS && built && out.ms >= 2000)
10505 std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %.1f s to build (%zu B SPIR-V)\n",
10506 entry->name.c_str(), double(out.ms) / 1000.0, bytes);
10507 return out;
10508}
10509
8021class PipelineState final 10510class PipelineState final
8022 : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, 10511 : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable,
8023 ID3D12PipelineState> { 10512 ID3D12PipelineState> {
@@ -8082,6 +10571,16 @@ public:
8082 // Asks for the subgroup size the shader was translated for, where the device allows (src/subgroup_size.h): the 10571 // Asks for the subgroup size the shader was translated for, where the device allows (src/subgroup_size.h): the
8083 // stage gets VkPipelineShaderStageRequiredSubgroupSizeCreateInfo in `storage` (which must outlive pipeline 10572 // stage gets VkPipelineShaderStageRequiredSubgroupSizeCreateInfo in `storage` (which must outlive pipeline
8084 // creation) and, for compute, REQUIRE_FULL_SUBGROUPS. A size the device cannot give is reported, not hidden. 10573 // creation) and, for compute, REQUIRE_FULL_SUBGROUPS. A size the device cannot give is reported, not hidden.
10574 // decide_subgroup_size's answer for a compute entry, reported and recorded as subgroup_size_for does; the build
10575 // applies it (build_compute_pipeline).
10576 leonida::SubgroupRequest subgroup_request_for(const leonida::ShaderEntry& entry) {
10577 const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup);
10578 if (request.outcome == leonida::SubgroupOutcome::unavailable)
10579 report_subgroup_unavailable(entry, request, device_.info.subgroup);
10580 subgroup_requests_.push_back(request);
10581 return request;
10582 }
10583
8085 void subgroup_size_for(const leonida::ShaderEntry& entry, VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage, 10584 void subgroup_size_for(const leonida::ShaderEntry& entry, VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage,
8086 VkPipelineShaderStageCreateInfo& stage) { 10585 VkPipelineShaderStageCreateInfo& stage) {
8087 const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup); 10586 const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup);
@@ -8218,7 +10717,7 @@ public:
8218 if (seen.insert(line).second) std::fprintf(stderr, "%s\n", line); 10717 if (seen.insert(line).second) std::fprintf(stderr, "%s\n", line);
8219 } 10718 }
8220 HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr, 10719 HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr,
8221 const D3D12_SHADER_BYTECODE* as = nullptr, const StencilFaceMasks* back_masks = nullptr) { 10720 const D3D12_SHADER_BYTECODE* as = nullptr, const StencilFaceMasks* back_masks = nullptr, bool depth_bounds = false) {
8222 auto& vk = device_.context->vk; 10721 auto& vk = device_.context->vk;
8223 const VkDevice dev = device_.info.device; 10722 const VkDevice dev = device_.info.device;
8224 const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength; 10723 const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength;
@@ -8488,8 +10987,8 @@ public:
8488 if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && 10987 if (vs_stage.entry && ps_stage.entry && !gs_stage.entry &&
8489 (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) { 10988 (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) {
8490 std::string link_error; 10989 std::string link_error;
8491 if (!leonida::link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, 10990 if (!link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry,
8492 &link_error, device_.f16_half_top_location)) { 10991 &link_error)) {
8493 std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str()); 10992 std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str());
8494 return E_FAIL; 10993 return E_FAIL;
8495 } 10994 }
@@ -8727,6 +11226,10 @@ public:
8727 depth.front = stencil_face(ds.FrontFace, ds.StencilReadMask, ds.StencilWriteMask); 11226 depth.front = stencil_face(ds.FrontFace, ds.StencilReadMask, ds.StencilWriteMask);
8728 depth.back = back_masks ? stencil_face(ds.BackFace, back_masks->read, back_masks->write) 11227 depth.back = back_masks ? stencil_face(ds.BackFace, back_masks->read, back_masks->write)
8729 : stencil_face(ds.BackFace, ds.StencilReadMask, ds.StencilWriteMask); 11228 : stencil_face(ds.BackFace, ds.StencilReadMask, ds.StencilWriteMask);
11229 // The depth-bounds test (DEPTH_STENCIL1/2): the bounds are dynamic, set from OMSetDepthBounds at each draw.
11230 depth.depthBoundsTestEnable = depth_bounds ? VK_TRUE : VK_FALSE;
11231 depth.minDepthBounds = 0.0f;
11232 depth.maxDepthBounds = 1.0f;
8730 11233
8731 std::vector<VkPipelineColorBlendAttachmentState> blends(desc.NumRenderTargets); 11234 std::vector<VkPipelineColorBlendAttachmentState> blends(desc.NumRenderTargets);
8732 for (UINT i = 0; i < desc.NumRenderTargets; ++i) { 11235 for (UINT i = 0; i < desc.NumRenderTargets; ++i) {
@@ -8770,6 +11273,13 @@ public:
8770 // State that needs a Vulkan feature the device did not enable (VulkanDeviceInfo::features) is refused, rather 11273 // State that needs a Vulkan feature the device did not enable (VulkanDeviceInfo::features) is refused, rather
8771 // than handed to the driver against the spec. 11274 // than handed to the driver against the spec.
8772 const VkPhysicalDeviceFeatures& features = device_.info.features; 11275 const VkPhysicalDeviceFeatures& features = device_.info.features;
11276 if (depth_bounds && !features.depthBounds)
11277 return stream_unsupported("depth-bounds tests need depthBounds, which the device lacks; stream subobject", 21);
11278 if (depth_bounds) { // how many PSOs use the test (they were all refused before)
11279 static std::atomic<unsigned> made{0};
11280 const unsigned n = ++made;
11281 if ((n & (n - 1)) == 0) std::fprintf(stderr, "[rt] d3d12: depth-bounds PSO #%u\n", n);
11282 }
8773 11283
8774 if (raster.polygonMode != VK_POLYGON_MODE_FILL && !features.fillModeNonSolid) 11284 if (raster.polygonMode != VK_POLYGON_MODE_FILL && !features.fillModeNonSolid)
8775 return stream_unsupported("wireframe fill needs fillModeNonSolid, which the device lacks; fill mode", r.FillMode); 11285 return stream_unsupported("wireframe fill needs fillModeNonSolid, which the device lacks; fill mode", r.FillMode);
@@ -8893,6 +11403,7 @@ public:
8893 11403
8894 // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. 11404 // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined.
8895 graphics_.mesh = mesh; 11405 graphics_.mesh = mesh;
11406 graphics_.depth_bounds = depth_bounds;
8896 recipe_.mesh = mesh; 11407 recipe_.mesh = mesh;
8897 recipe_.stages = std::move(stage_infos); 11408 recipe_.stages = std::move(stage_infos);
8898 recipe_.attributes = std::move(attributes); 11409 recipe_.attributes = std::move(attributes);
@@ -8928,7 +11439,9 @@ public:
8928 const auto it = variants_.find(unbound); 11439 const auto it = variants_.find(unbound);
8929 return it == variants_.end() ? VkPipeline(VK_NULL_HANDLE) : it->second; 11440 return it == variants_.end() ? VkPipeline(VK_NULL_HANDLE) : it->second;
8930 }; 11441 };
8931 graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes; 11442 graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes &&
11443 big_compiles() != BigCompiles::unlimited;
11444 graphics_.estimate = leonida::large_module_estimate(spirv_bytes);
8932 11445
8933 if (code_stage) { 11446 if (code_stage) {
8934 VkDeviceSize offset = 0; 11447 VkDeviceSize offset = 0;
@@ -8938,8 +11451,7 @@ public:
8938 code_base_ = offset; 11451 code_base_ = offset;
8939 graphics_.code_base = offset; 11452 graphics_.code_base = offset;
8940 } 11453 }
8941 // LOCAL DIAGNOSTIC: what this pipeline is, for the fsdraw probe's draw lines 11454 if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: what this pipeline is, for the fsdraw probe's draw lines
8942 if (leonida::local_diagnostics()) {
8943 const auto& rt0 = desc.BlendState.RenderTarget[0]; 11455 const auto& rt0 = desc.BlendState.RenderTarget[0];
8944 char text[640]; 11456 char text[640];
8945 std::snprintf(text, sizeof text, 11457 std::snprintf(text, sizeof text,
@@ -9058,6 +11570,7 @@ public:
9058 if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; 11570 if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL;
9059 compute_entry_ = entry; 11571 compute_entry_ = entry;
9060 stage_bytes_ = spirv_bytes; 11572 stage_bytes_ = spirv_bytes;
11573 pipeline_.estimate = leonida::large_module_estimate(spirv_bytes);
9061 // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks 11574 // The title creates hundreds of compute pipelines from job threads during startup and one of its init tasks
9062 // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver 11575 // waits for all of them; some modules (wave64-emulated ray-tracing resolves, 4 MiB of SPIR-V) take the driver
9063 // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names 11576 // minutes each. So the Vulkan pipeline is built on first use (build_compute): at the first dispatch that names
@@ -9093,7 +11606,7 @@ public:
9093 std::unique_lock lock(pso->variants_mutex_, std::try_to_lock); // held: another thread is compiling it 11606 std::unique_lock lock(pso->variants_mutex_, std::try_to_lock); // held: another thread is compiling it
9094 return lock.owns_lock() ? pso->pipeline_.pipeline : VkPipeline(VK_NULL_HANDLE); 11607 return lock.owns_lock() ? pso->pipeline_.pipeline : VkPipeline(VK_NULL_HANDLE);
9095 }; 11608 };
9096 pipeline_.large = serial_big_compile(spirv_bytes); 11609 pipeline_.large = big_compute(spirv_bytes) && big_compiles() != BigCompiles::unlimited;
9097 } else if (!build_compute("compute-create")) { 11610 } else if (!build_compute("compute-create")) {
9098 return E_FAIL; 11611 return E_FAIL;
9099 } 11612 }
@@ -9114,70 +11627,89 @@ public:
9114 } 11627 }
9115 11628
9116private: 11629private:
11630 using Work = leonida::LargeModuleGate::Work;
11631
11632 // Locks the PSO (`lock`, on variants_mutex_) for a build and, with an `estimate`, takes the build's place at the gate. A
11633 // thread that waits for its place holds no PSO's lock, and one that has its place waits for none: another thread may be
11634 // building that PSO, with a place of its own. Returns without a place when the PSO is `built` already.
11635 template<typename Built>
11636 leonida::LargeModuleGate::Ticket enter_build(std::unique_lock<std::mutex>& lock, std::uint64_t estimate, Work work,
11637 Built&& built) {
11638 for (;;) {
11639 lock.lock();
11640 if (!estimate || built()) return {};
11641 lock.unlock();
11642 leonida::LargeModuleGate::Ticket place(big_compile_gate(), estimate, work);
11643 if (lock.try_lock()) return place;
11644 }
11645 }
11646
9117 // The compute pipeline, built once: by create_compute (LEONIDA_LAZY_COMPUTE=0), by the first dispatch that names 11647 // The compute pipeline, built once: by create_compute (LEONIDA_LAZY_COMPUTE=0), by the first dispatch that names
9118 // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the 11648 // it (the replay layer calls ComputePipeline::build) or by the warm-up thread. Null when it cannot be built; the
9119 // failure is logged and not retried. 11649 // failure is logged and not retried.
9120 VkPipeline build_compute(const char* trigger) { 11650 VkPipeline build_compute(const char* trigger, Work work = Work::demand) {
9121 CompileActivity activity(device_.active_compiles); 11651 // A large module's place at the compile gate is taken before the PSO's lock (enter_build): a thread that waits
9122 std::lock_guard lock(variants_mutex_); 11652 // for memory holds no PSO lock.
11653 std::unique_lock lock(variants_mutex_, std::defer_lock);
11654 const bool budgeted = big_compute(stage_bytes_) && big_compiles() == BigCompiles::budget;
11655 auto place = enter_build(lock, budgeted ? pipeline_.estimate : 0, work,
11656 [this] { return pipeline_.pipeline || compute_failed_; });
9123 if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline; 11657 if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline;
9124 compute_failed_ = true; // until the pipeline exists
9125 auto& vk = device_.context->vk;
9126 const VkDevice dev = device_.info.device;
9127 const leonida::ShaderLibrary* library = device_.library();
9128 const leonida::ShaderEntry* entry = compute_entry_; 11658 const leonida::ShaderEntry* entry = compute_entry_;
9129 if (!library || !entry) return VK_NULL_HANDLE; 11659 if (!device_.library() || !entry) {
9130 static std::mutex big_compile; 11660 compute_failed_ = true;
9131 std::unique_lock<std::mutex> big_lock(big_compile, std::defer_lock);
9132 if (serial_big_compile(stage_bytes_)) big_lock.lock();
9133 auto words = library->spirv(*entry);
9134 if (words.empty()) {
9135 std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str());
9136 return VK_NULL_HANDLE; 11661 return VK_NULL_HANDLE;
9137 } 11662 }
9138 VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; 11663 // LOCAL FIX (compile helper, d3d12_compile_helper.h): asynchronous builds and warm-ups only ask the helper and
9139 module_info.codeSize = words.size() * 4; 11664 // are deferred (queue_build publishes nothing for them, so their next use asks again). While the helper is
9140 module_info.pCode = words.data(); 11665 // still making the file this answers at once, without reading the module; a use asks with replay's priority.
9141 VkShaderModule module = VK_NULL_HANDLE; 11666 // Only replay's own and the warm-up's triggers may answer deferred: compute-create (LEONIDA_LAZY_COMPUTE=0) is
9142 { 11667 // a create whose caller needs a pipeline now, so it waits for the file as a dispatch does in a strict replay
9143 const leonida::aftermath::ShaderName named(entry->name); 11668 // (LOCAL FIX, review: with LEONIDA_ASYNC_PIPELINES=1 it was deferred and returned E_FAIL).
9144 if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return VK_NULL_HANDLE; 11669 const bool warmup = !std::strcmp(trigger, "warmup");
11670 const bool replay_trigger = !std::strcmp(trigger, "dispatch") || !std::strcmp(trigger, "dispatch-worker");
11671 const bool helper_nowait = warmup || (replay_trigger && async_replay_compile());
11672 if (!helper_file_.empty()) {
11673 auto& helper = compile_helper::Client::instance();
11674 std::string why;
11675 const auto state = helper.state(helper_file_, device_.pso_identity, &why);
11676 if (state == compile_helper::Client::State::pending) {
11677 if (!warmup) helper.request(helper_file_, entry->name, 0, device_.pso_identity, nullptr);
11678 if (helper_nowait) {
11679 helper_deferred_ = true;
11680 return VK_NULL_HANDLE;
11681 }
11682 } else if (state != compile_helper::Client::State::ready) {
11683 std::fprintf(stderr, "[rt] d3d12: compile helper: %s for %s; built here\n", why.c_str(),
11684 entry->name.c_str());
11685 helper_refused_ = true;
11686 }
11687 helper_file_.clear();
9145 } 11688 }
9146 const auto bytes = module_info.codeSize; 11689 compute_failed_ = true; // until the pipeline exists
9147 std::vector<std::uint32_t>().swap(words); // vkCreateShaderModule consumed pCode 11690 ComputeBuildOptions options;
9148 VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; 11691 options.trigger = trigger;
9149 pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; 11692 options.cache_key = &cache_key_;
9150 pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; 11693 options.use_helper = !helper_refused_;
9151 pipeline_info.stage.module = module; 11694 options.helper_wait = !helper_nowait;
9152 pipeline_info.stage.pName = "main"; 11695 options.helper_priority = warmup ? stage_bytes_ : 0;
9153 VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; 11696 const ComputeBuild build = build_compute_pipeline(device_, *entry, pipeline_.layout, subgroup_request_for(*entry),
9154 subgroup_size_for(*entry, required_size, pipeline_info.stage); 11697 options);
9155 pipeline_info.layout = pipeline_.layout; 11698 if (build.deferred) {
9156 const VkPipelineCache cache = device_.pipeline_cache(); 11699 compute_failed_ = false;
9157 11700 helper_file_ = build.journal_path;
9158 const ULONGLONG started = GetTickCount64(); 11701 helper_deferred_ = true;
9159 VkPipeline built = VK_NULL_HANDLE; 11702 return VK_NULL_HANDLE;
9160 CompileTrace trace; 11703 }
9161 trace.begin(pipeline_info, device_.info.pipeline_creation_feedback, trigger, entry->name.c_str(), 0, bytes, cache_key_); 11704 if (build.result != VK_SUCCESS || !build.pipeline) {
9162 const leonida::pipeline_profile::DriverCall profile("cs", trigger, entry->name.c_str());
9163 const VkResult created = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &built);
9164 profile.finish(int(created));
9165 trace.end(trigger, entry->name.c_str(), 0, bytes, created);
9166 if (big_lock.owns_lock()) big_lock.unlock();
9167 vk.vkDestroyShaderModule(dev, module, nullptr); // Vulkan lets a module go once the pipeline exists
9168 const ULONGLONG took = GetTickCount64() - started;
9169 if (created != VK_SUCCESS || !built) {
9170 std::fprintf(stderr, "[rt] d3d12: compute pipeline %s could not be built (VkResult %d); its dispatches are " 11705 std::fprintf(stderr, "[rt] d3d12: compute pipeline %s could not be built (VkResult %d); its dispatches are "
9171 "dropped\n", entry->name.c_str(), int(created)); 11706 "dropped\n", entry->name.c_str(), int(build.result));
9172 return VK_NULL_HANDLE; 11707 return VK_NULL_HANDLE;
9173 } 11708 }
9174 if (took >= 2000) 11709 maybe_checkpoint(device_.pipeline_cache());
9175 std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %.1f s to build (%zu B SPIR-V)\n", 11710 pipeline_.pipeline = build.pipeline;
9176 entry->name.c_str(), double(took) / 1000.0, bytes);
9177 maybe_checkpoint(cache);
9178 pipeline_.pipeline = built;
9179 compute_failed_ = false; 11711 compute_failed_ = false;
9180 return built; 11712 return build.pipeline;
9181 } 11713 }
9182 11714
9183 // Lazy compute pipelines are also built in the background, smallest module first, so most exist before their 11715 // Lazy compute pipelines are also built in the background, smallest module first, so most exist before their
@@ -9207,37 +11739,53 @@ private:
9207 if (!queued) device_.next_checkpoint.store(now + 120000); // refused after an exit stop, or out of memory 11739 if (!queued) device_.next_checkpoint.store(now + 120000); // refused after an exit stop, or out of memory
9208 } 11740 }
9209 11741
9210 VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0) { 11742 // Asynchronous builds (LEONIDA_ASYNC_PIPELINES=1): replay asks here at prepare, with the resource lock held. The
11743 // handle once built; otherwise a compile-worker job is queued (once) and null answered, so the draw or dispatch is
11744 // skipped and a later submission uses the pipeline. `warm_bytes`: a warm-up, queued by module size. `count_skip`:
11745 // false for a request made at record time (request_early), which skips nothing.
11746 VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0, bool count_skip = true) {
9211 static std::mutex publication; // ready handles only; no compiler call holds this lock 11747 static std::mutex publication; // ready handles only; no compiler call holds this lock
9212 const bool warm = warm_bytes != 0; 11748 const bool warm = warm_bytes != 0;
9213 // After an exit stop (stop_pipeline_compiles) nothing is queued: a warm-up is skipped, and a draw or dispatch 11749 // After an exit stop (stop_pipeline_compiles) nothing is queued: a warm-up or an early request is skipped,
9214 // builds in place, as without LEONIDA_ASYNC_PIPELINES, rather than waiting for a build that never comes. 11750 // and a draw or dispatch builds in place, as without LEONIDA_ASYNC_PIPELINES, rather than waiting for a build
11751 // that never comes.
9215 if (PipelineCompiler::instance().closed()) { 11752 if (PipelineCompiler::instance().closed()) {
9216 if (warm) return VK_NULL_HANDLE; 11753 if (warm || !count_skip) return VK_NULL_HANDLE;
9217 return compute ? build_compute("dispatch") : variant(unbound, "draw"); 11754 return compute ? build_compute("dispatch") : variant(unbound, "draw");
9218 } 11755 }
9219 std::lock_guard lock(publication); 11756 std::lock_guard lock(publication);
9220 if (!warm) { 11757 if (!warm) {
9221 if (!requested_) requested_ = std::make_unique<Requests>(); 11758 if (!requested_) requested_ = std::make_unique<Requests>();
9222 auto [it, inserted] = requested_->try_emplace(unbound); 11759 auto [it, inserted] = requested_->try_emplace(unbound);
9223 if (!it->second.handle) ++it->second.skips; 11760 if (!it->second.handle && count_skip) ++it->second.skips;
9224 if (!inserted) return it->second.handle; 11761 if (!inserted) return it->second.handle;
9225 } 11762 }
9226 bool queued = false; 11763 bool queued = false;
9227 try { 11764 try {
9228 queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes, [this, compute, warm, unbound] { 11765 queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes,
11766 [this, compute, warm, unbound, warm_bytes] {
11767 // A big warm-up while the title submits is left to the pipeline's first use (warmup_waits_for_quiet).
11768 if (warm && warmup_waits_for_quiet(warm_bytes)) return;
9229 VkPipeline built{}; 11769 VkPipeline built{};
9230 try { 11770 try {
9231 built = compute ? build_compute(warm ? "warmup" : "dispatch-worker") 11771 built = compute ? build_compute(warm ? "warmup" : "dispatch-worker",
11772 warm ? Work::speculative : Work::demand)
9232 : variant(unbound, "draw-worker"); 11773 : variant(unbound, "draw-worker");
11774 // The compile helper is still making the journal file (build_compute): not built, so nothing is
11775 // published and the next use asks again.
11776 const bool deferred = compute && helper_deferred_.exchange(false);
9233 if (async_replay_compile()) { 11777 if (async_replay_compile()) {
9234 unsigned long long skipped = 0; 11778 unsigned long long skipped = 0;
9235 { 11779 {
9236 std::lock_guard publish(publication); 11780 std::lock_guard publish(publication);
9237 if (!requested_) requested_ = std::make_unique<Requests>(); 11781 if (!requested_) requested_ = std::make_unique<Requests>();
9238 auto& entry = (*requested_)[unbound]; 11782 if (deferred) {
9239 if (!entry.handle) skipped = entry.skips; 11783 if (!warm) requested_->erase(unbound);
9240 entry.handle = built; 11784 } else {
11785 auto& entry = (*requested_)[unbound];
11786 if (!entry.handle) skipped = entry.skips;
11787 entry.handle = built;
11788 }
9241 } 11789 }
9242 if (skipped && trace_pipeline_compile()) 11790 if (skipped && trace_pipeline_compile())
9243 std::fprintf(stderr, "[rt] pipeline-deferred type=%s skipped=%llu ready=%d\n", 11791 std::fprintf(stderr, "[rt] pipeline-deferred type=%s skipped=%llu ready=%d\n",
@@ -9246,7 +11794,7 @@ private:
9246 } catch (const std::exception& e) { 11794 } catch (const std::exception& e) {
9247 std::fprintf(stderr, "[rt] pipeline compile worker failed: %s\n", e.what()); 11795 std::fprintf(stderr, "[rt] pipeline compile worker failed: %s\n", e.what());
9248 } 11796 }
9249 }); 11797 }, !compute); // a graphics build may also take the graphics worker
9250 } catch (...) { 11798 } catch (...) {
9251 } 11799 }
9252 // Not queued (refused by a stop that came after the check above, or out of memory): no request stays 11800 // Not queued (refused by a stop that came after the check above, or out of memory): no request stays
@@ -9255,6 +11803,53 @@ private:
9255 return VK_NULL_HANDLE; 11803 return VK_NULL_HANDLE;
9256 } 11804 }
9257 11805
11806public:
11807 // Record time (SetPipelineState for compute, a draw for graphics, with the render-target slots it binds and
11808 // whether it binds a depth buffer): asynchronous builds start on the compile worker before the list is submitted.
11809 // Never waits; nothing to do when the variant is the last one asked for here.
11810 void request_early(std::uint32_t bound_targets, bool depth_bound) {
11811 if (!async_replay_compile() || !registered_) return;
11812 std::uint32_t unbound = 0;
11813 if (is_graphics_) {
11814 for (std::size_t slot = 0; slot < graphics_.color_formats.size() && slot < 8; ++slot)
11815 if (graphics_.color_formats[slot] != VK_FORMAT_UNDEFINED && !(bound_targets & (1u << slot)))
11816 unbound |= 1u << slot;
11817 if (graphics_.depth_format != VK_FORMAT_UNDEFINED && !depth_bound)
11818 unbound |= leonida::GraphicsPipeline::unbound_depth;
11819 if (!unbound && graphics_.pipeline) return;
11820 } else if (!pipeline_.build || pipeline_.skipped) {
11821 return; // an eager pipeline has no build
11822 }
11823 if (early_.exchange(unbound + 1, std::memory_order_relaxed) == unbound + 1) return;
11824 queue_build(!is_graphics_, unbound, 0, false);
11825 }
11826
11827private:
11828 // LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES=<n> (opt-in; unset or 0: no limit, the warm-up builds every module as on
11829 // main): a warm-up of a module over n bytes of SPIR-V is not started while the title submits (a submission in the
11830 // last second); it is left to the pipeline's first use. A create holds the compile gate (SubmitMutex::CompileTurn)
11831 // for its whole length and every submission waits behind it; on NVIDIA 630.20 the modules over 640 KiB take 4-25 s
11832 // each. Measured in a native boot past the story load (with 131072): 694 warm-ups of modules over 128 KiB against
11833 // 25 such builds a dispatch asked for, and one run's submissions waited 140 s in all at the gate behind warm-ups.
11834 static bool warmup_waits_for_quiet(std::size_t bytes) {
11835 static const std::size_t limit = [] {
11836 char text[32]{};
11837 const DWORD n = GetEnvironmentVariableA("LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES", text, sizeof(text));
11838 return (n > 0 && n < sizeof(text)) ? static_cast<std::size_t>(std::strtoull(text, nullptr, 10))
11839 : std::size_t{0};
11840 }();
11841 if (!limit || bytes <= limit || !leonida::pipeline_wait::title_submitting()) return false;
11842 if (compile_helper::wanted(bytes)) return false; // the helper compiles it, in its own process
11843 if (leonida::pipeline_wait::warmups_left().fetch_add(1, std::memory_order_relaxed) == 0) {
11844 static std::atomic<bool> logged{false};
11845 if (!logged.exchange(true))
11846 std::fprintf(stderr, "[rt] d3d12: compute warm-ups over %zu KiB are left to their first use while the "
11847 "title submits (LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES), from t=%.3f s\n",
11848 limit >> 10, double(leonida::diagnostic_ms()) / 1000.0);
11849 }
11850 return true;
11851 }
11852
9258 static void warmup_enqueue(PipelineState* pso, std::size_t bytes) { 11853 static void warmup_enqueue(PipelineState* pso, std::size_t bytes) {
9259 static const std::size_t max_bytes = [] { 11854 static const std::size_t max_bytes = [] {
9260 char text[32]{}; 11855 char text[32]{};
@@ -9352,6 +11947,7 @@ private:
9352 dyn_list[dyn_count++] = VK_DYNAMIC_STATE_STENCIL_REFERENCE; 11947 dyn_list[dyn_count++] = VK_DYNAMIC_STATE_STENCIL_REFERENCE;
9353 dyn_list[dyn_count++] = VK_DYNAMIC_STATE_BLEND_CONSTANTS; 11948 dyn_list[dyn_count++] = VK_DYNAMIC_STATE_BLEND_CONSTANTS;
9354 if (!r.mesh && !r.bindings.empty()) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE; 11949 if (!r.mesh && !r.bindings.empty()) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE;
11950 if (r.depth.depthBoundsTestEnable) dyn_list[dyn_count++] = VK_DYNAMIC_STATE_DEPTH_BOUNDS;
9355 VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; 11951 VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
9356 dynamic.dynamicStateCount = dyn_count; 11952 dynamic.dynamicStateCount = dyn_count;
9357 dynamic.pDynamicStates = dyn_list; 11953 dynamic.pDynamicStates = dyn_list;
@@ -9456,6 +12052,7 @@ private:
9456 info.pDynamicState = &dynamic; 12052 info.pDynamicState = &dynamic;
9457 info.flags=flags; 12053 info.flags=flags;
9458 info.layout = graphics_.layout; 12054 info.layout = graphics_.layout;
12055 info.flags |= fast_pipeline_flags(false);
9459 VkPipeline pipeline = VK_NULL_HANDLE; 12056 VkPipeline pipeline = VK_NULL_HANDLE;
9460 const auto cache = device_.pipeline_cache(); 12057 const auto cache = device_.pipeline_cache();
9461 const char* program = "-", *fragment = "-"; 12058 const char* program = "-", *fragment = "-";
@@ -9468,6 +12065,7 @@ private:
9468 } 12065 }
9469 CompileTrace trace; 12066 CompileTrace trace;
9470 trace.begin(info, device_.info.pipeline_creation_feedback, trigger, profile_shaders_.c_str(), unbound, bytes, cache_key_); 12067 trace.begin(info, device_.info.pipeline_creation_feedback, trigger, profile_shaders_.c_str(), unbound, bytes, cache_key_);
12068 const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline");
9471 const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", 12069 const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager",
9472 program, fragment, unbound); 12070 program, fragment, unbound);
9473 const auto result = device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &info, nullptr, &pipeline); 12071 const auto result = device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &info, nullptr, &pipeline);
@@ -9502,12 +12100,24 @@ private:
9502 return true; 12100 return true;
9503 } 12101 }
9504 12102
12103 bool link_f16_halves(std::vector<std::uint32_t>& vs_words, const leonida::ShaderEntry& vs_entry,
12104 std::vector<std::uint32_t>& ps_words, const leonida::ShaderEntry& ps_entry,
12105 std::string* error) const {
12106 return leonida::link_f16_halves(vs_words, vs_entry, ps_words, ps_entry, error,
12107 device_.f16_half_top_location);
12108 }
12109
12110public:
9505 bool stage_words(std::vector<std::vector<std::uint32_t>>& words, std::string& why) const { 12111 bool stage_words(std::vector<std::vector<std::uint32_t>>& words, std::string& why) const {
9506 const leonida::ShaderLibrary* library = device_.library(); 12112 const leonida::ShaderLibrary* library = device_.library();
9507 if (!library) { 12113 if (!library) {
9508 why = "no shader library"; 12114 why = "no shader library";
9509 return false; 12115 return false;
9510 } 12116 }
12117 if (sources_.empty()) {
12118 why = "not a lazy pipeline";
12119 return false;
12120 }
9511 words.assign(sources_.size(), {}); 12121 words.assign(sources_.size(), {});
9512 std::size_t vs = SIZE_MAX, ps = SIZE_MAX; 12122 std::size_t vs = SIZE_MAX, ps = SIZE_MAX;
9513 for (std::size_t i = 0; i < sources_.size(); ++i) { 12123 for (std::size_t i = 0; i < sources_.size(); ++i) {
@@ -9527,7 +12137,7 @@ private:
9527 } 12137 }
9528 if (f16_linked_) { 12138 if (f16_linked_) {
9529 if (vs == SIZE_MAX || ps == SIZE_MAX || 12139 if (vs == SIZE_MAX || ps == SIZE_MAX ||
9530 !leonida::link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why)) 12140 !link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why))
9531 return false; 12141 return false;
9532 } 12142 }
9533 for (std::size_t i = 0; i < sources_.size(); ++i) { 12143 for (std::size_t i = 0; i < sources_.size(); ++i) {
@@ -9550,9 +12160,13 @@ private:
9550 return true; 12160 return true;
9551 } 12161 }
9552 12162
12163private:
9553 // Built on first use and kept until the PSO is released (replay may call this from any queue). 12164 // Built on first use and kept until the PSO is released (replay may call this from any queue).
9554 VkPipeline variant(std::uint32_t unbound, const char* trigger) { 12165 VkPipeline variant(std::uint32_t unbound, const char* trigger) {
9555 std::lock_guard lock(variants_mutex_); 12166 std::unique_lock lock(variants_mutex_, std::defer_lock);
12167 const bool budgeted = graphics_.large && big_compiles() == BigCompiles::budget;
12168 const auto place = enter_build(lock, budgeted ? graphics_.estimate : 0, Work::demand,
12169 [&] { return variants_.contains(unbound); });
9556 if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; 12170 if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second;
9557 const VkPipeline pipeline = build(unbound, trigger); 12171 const VkPipeline pipeline = build(unbound, trigger);
9558 if (!pipeline) { 12172 if (!pipeline) {
@@ -9589,6 +12203,12 @@ private:
9589 struct Request { VkPipeline handle{}; unsigned long long skips = 0; }; 12203 struct Request { VkPipeline handle{}; unsigned long long skips = 0; };
9590 using Requests = std::map<std::uint32_t, Request>; 12204 using Requests = std::map<std::uint32_t, Request>;
9591 std::unique_ptr<Requests> requested_; 12205 std::unique_ptr<Requests> requested_;
12206 // Compile helper (build_compute, under variants_mutex_): the journal file asked for and not there yet; whether
12207 // the helper gave up on this pipeline (it is then built here); a build just deferred (read by queue_build).
12208 std::filesystem::path helper_file_;
12209 bool helper_refused_ = false;
12210 std::atomic<bool> helper_deferred_{false};
12211 std::atomic<std::uint32_t> early_{0}; // request_early: the last mask asked for, plus one
9592 std::string profile_shaders_; // populated only with compile tracing enabled 12212 std::string profile_shaders_; // populated only with compile tracing enabled
9593 std::size_t stage_bytes_ = 0; 12213 std::size_t stage_bytes_ = 0;
9594 std::mutex variants_mutex_; 12214 std::mutex variants_mutex_;
@@ -10134,7 +12754,7 @@ struct TitleTexture {
10134 // misses. Video planes, rewritten whole every frame, are caught by the sampled one first. 12754 // misses. Video planes, rewritten whole every frame, are caught by the sampled one first.
10135 std::uint64_t full_hash = 0; 12755 std::uint64_t full_hash = 0;
10136 bool full_hashed = false; 12756 bool full_hashed = false;
10137 bool every_byte() const { return mapped && layout.layout.size <= (4u << 20); } 12757 bool every_byte() const { return mapped && (async_texture_refresh() || layout.layout.size <= (4u << 20)); }
10138 std::uint64_t fills = 0; 12758 std::uint64_t fills = 0;
10139}; 12759};
10140 12760
@@ -10165,12 +12785,18 @@ bool title_xg_layout(const Resource& r, rt::xg_xs::Texture& out, std::array<std:
10165 return true; 12785 return true;
10166} 12786}
10167 12787
12788void DeviceState::index_texture(const TitleTexture& t) {
12789 if (async_texture_refresh())
12790 texture_ranges.set(t.address, t.cpu, t.layout_known && !t.gpu_written ? t.layout.layout.size : 0);
12791}
12792
10168void DeviceState::title_texture_mapped(const void* resource, std::uint64_t address) { 12793void DeviceState::title_texture_mapped(const void* resource, std::uint64_t address) {
10169 std::lock_guard lock(title_texture_mutex); 12794 std::lock_guard lock(title_texture_mutex);
10170 const auto it = title_textures.find(address); 12795 const auto it = title_textures.find(address);
10171 if (it == title_textures.end() || it->second->resource != resource) return; 12796 if (it == title_textures.end() || it->second->resource != resource) return;
10172 TitleTexture& t = *it->second; 12797 TitleTexture& t = *it->second;
10173 t.mapped = true; 12798 t.mapped = true;
12799 if (async_texture_refresh() && !t.gpu_written) mapped_title_textures[address] = it->second;
10174 t.memory.retry(); 12800 t.memory.retry();
10175 // The title computes the layout of what it writes right before it maps: take it when no view gave one. 12801 // The title computes the layout of what it writes right before it maps: take it when no view gave one.
10176 if (!t.gpu_written && (t.layout_guessed || !t.layout_known) && 12802 if (!t.gpu_written && (t.layout_guessed || !t.layout_known) &&
@@ -10178,6 +12804,7 @@ void DeviceState::title_texture_mapped(const void* resource, std::uint64_t addre
10178 t.layout_known = true; 12804 t.layout_known = true;
10179 t.layout_guessed = false; 12805 t.layout_guessed = false;
10180 t.layout_from_xg = true; 12806 t.layout_from_xg = true;
12807 index_texture(t);
10181 t.hashed = false; 12808 t.hashed = false;
10182 } 12809 }
10183 static std::atomic<int> logged{0}; 12810 static std::atomic<int> logged{0};
@@ -10229,7 +12856,12 @@ void DeviceState::title_texture_gone(const void* resource, std::uint64_t address
10229 gpu_placements.remove(address, resource); 12856 gpu_placements.remove(address, resource);
10230 } 12857 }
10231 const auto it = title_textures.find(address); 12858 const auto it = title_textures.find(address);
10232 if (it != title_textures.end() && it->second->resource == resource) title_textures.erase(it); 12859 if (it != title_textures.end() && it->second->resource == resource) {
12860 texture_ranges.erase(address);
12861 mapped_title_textures.erase(address);
12862 it->second->resource = nullptr;
12863 title_textures.erase(it);
12864 }
10233} 12865}
10234 12866
10235void DeviceState::drain_titles_gone() { 12867void DeviceState::drain_titles_gone() {
@@ -10268,6 +12900,8 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord
10268 std::lock_guard lock(device.descriptor_mutex); 12900 std::lock_guard lock(device.descriptor_mutex);
10269 if (!device.bindless) return refuse("no bindless set"); 12901 if (!device.bindless) return refuse("no bindless set");
10270 if (device.image_entries.count(words)) return TitleImage::known; 12902 if (device.image_entries.count(words)) return TitleImage::known;
12903 if (g::has_hardware_volume_uav_slice_offset(words, image))
12904 return refuse("a title-written 3D UAV with a slice offset is not supported");
10271 auto found = device.images_by_address.find(image.address); 12905 auto found = device.images_by_address.find(image.address);
10272 // Memory of the texture stream pool has two addresses, the CPU view's and the GPU-only alias the title hands 12906 // Memory of the texture stream pool has two addresses, the CPU view's and the GPU-only alias the title hands
10273 // to the GPU (title_gpu_views): a T# naming either finds a texture registered under the other. 12907 // to the GPU (title_gpu_views): a T# naming either finds a texture registered under the other.
@@ -10281,7 +12915,10 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord
10281 const auto alias = leonida::title_gpu_views::other_view(image.address); 12915 const auto alias = leonida::title_gpu_views::other_view(image.address);
10282 if (auto* candidate = device.gpu_placements.find(image.address, alias, matches)) owner = candidate; 12916 if (auto* candidate = device.gpu_placements.find(image.address, alias, matches)) owner = candidate;
10283 } 12917 }
10284 if (!owner) return TitleImage::unknown; 12918 if (!owner) {
12919 if (why) *why = "no texture at T# address";
12920 return TitleImage::unknown;
12921 }
10285 const Resource& r = *owner; 12922 const Resource& r = *owner;
10286 image.address = r.image_address(); // release this key with its actual owner 12923 image.address = r.image_address(); // release this key with its actual owner
10287 const D3D12_RESOURCE_DESC& d = r.desc(); 12924 const D3D12_RESOURCE_DESC& d = r.desc();
@@ -10297,10 +12934,10 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord
10297 if (!r.descriptor_image()) return refuse("the texture has no image"); 12934 if (!r.descriptor_image()) return refuse("the texture has no image");
10298 if (!type_fits) return refuse("T# type or samples do not fit the texture"); 12935 if (!type_fits) return refuse("T# type or samples do not fit the texture");
10299 if (!msaa && image.first_mip + image.mip_count > d.MipLevels) return refuse("T# names mips the texture lacks"); 12936 if (!msaa && image.first_mip + image.mip_count > d.MipLevels) return refuse("T# names mips the texture lacks");
12937 if (image.type == g::ImageType::cube && !(r.format() && layers >= 6))
12938 return refuse("cube T# on fewer than six layers");
10300 if (!volume && image.first_layer + image.layer_count > layers) 12939 if (!volume && image.first_layer + image.layer_count > layers)
10301 return refuse("T# names layers the texture lacks"); 12940 return refuse("T# names layers the texture lacks");
10302 if (image.type == g::ImageType::cube && !(r.format() && image.layer_count >= 6))
10303 return refuse("cube T# on fewer than six layers");
10304 const bool storage = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !msaa && 12941 const bool storage = (d.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !msaa &&
10305 r.aspects() == VK_IMAGE_ASPECT_COLOR_BIT; 12942 r.aspects() == VK_IMAGE_ASPECT_COLOR_BIT;
10306 if (!device.bind_image_locked(words, image, r.descriptor_image(), r.format(), r.aspects(), storage, 12943 if (!device.bind_image_locked(words, image, r.descriptor_image(), r.format(), r.aspects(), storage,
@@ -10647,11 +13284,17 @@ public:
10647 break; 13284 break;
10648 } 13285 }
10649 case h::so_statistics: 13286 case h::so_statistics:
10650 // The layer has no stream output: a graphics PSO with StreamOutput entries is refused (E_NOTIMPL) and 13287 // D3D-302: with VK_EXT_transform_feedback enabled, an SO_STATISTICS heap is a real transform-feedback
10651 // SOSetTargets is not implemented, so no primitive ever reaches a stream and every query of this heap 13288 // pool whose queries begin/end on a stream (vkCmdBeginQueryIndexedEXT); a resolve copies 16 bytes per
10652 // counts 0 written and 0 needed. That needs no Vulkan pool: Begin/EndQuery run nothing and a resolve fills zeros. When stream 13289 // query (NumPrimitivesWritten, PrimitivesStorageNeeded), in the same order. StreamOutput PSOs are still
10653 // output lands, this becomes a VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool (D3D-302). 13290 // refused and SOSetTargets is still not implemented, so no primitive reaches a stream yet and every
10654 return register_pool(desc); 13291 // query counts 0. The pool needs the transformFeedbackQueries property and at least one stream; without
13292 // them (or without the feature) the heap is made without a pool and every query resolves to zero.
13293 if (!device_.info.transform_feedback || !device_.info.transform_feedback_queries ||
13294 !device_.info.max_transform_feedback_streams)
13295 return register_pool(desc);
13296 info.queryType = VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT;
13297 break;
10655 case h::pipeline_statistics: 13298 case h::pipeline_statistics:
10656 if (!device_.info.pipeline_statistics_query) { 13299 if (!device_.info.pipeline_statistics_query) {
10657 log_once("pipeline-statistics query heap: pipelineStatisticsQuery not enabled; type", desc.Type); 13300 log_once("pipeline-statistics query heap: pipelineStatisticsQuery not enabled; type", desc.Type);
@@ -10680,6 +13323,9 @@ private:
10680 pool.count = desc.Count; 13323 pool.count = desc.Count;
10681 pool.precise = device_.info.occlusion_query_precise; 13324 pool.precise = device_.info.occlusion_query_precise;
10682 pool.ended.assign(desc.Count, false); 13325 pool.ended.assign(desc.Count, false);
13326 // D3D-302: a real transform-feedback pool queries streams below maxTransformFeedbackStreams; D3D12 has four.
13327 if (pool_ && desc.Type == leonida::d3d12_query_heap::so_statistics)
13328 pool.streams = std::min<std::uint32_t>(4, device_.info.max_transform_feedback_streams);
10683 device_.context->add_query_pool(id(), pool); 13329 device_.context->add_query_pool(id(), pool);
10684 registered_ = true; 13330 registered_ = true;
10685 return S_OK; 13331 return S_OK;
@@ -10696,6 +13342,23 @@ private:
10696 bool registered_ = false; // added to the context, so removed from it on destruction 13342 bool registered_ = false; // added to the context, so removed from it on destruction
10697}; 13343};
10698 13344
13345// The live devices whose session pipeline cache an ending process writes (save_pipeline_caches_at_exit). A title
13346// never releases its device, so ~Device, the only other writer, does not run in a real boot: without this, a run that
13347// ends (normally, at a console close or in a crash) keeps none of what it compiled. Timed, so a crash handler that
13348// finds it held gives up instead of hanging the process.
13349std::timed_mutex exit_cache_mutex;
13350std::vector<DeviceState*> exit_cache_devices;
13351std::atomic<bool> exit_cache_saved{false};
13352
13353// VK_EXT_memory_budget read from a device's info: the reader a device publishes for the title HUD and the dev overlay
13354// (src/memory_figures.h), and vulkan_vram_budget. Not available without the extension.
13355leonida::VramBudget read_vram_budget(const VulkanDeviceInfo& info) {
13356 if (!info.memory_budget || !info.get_instance_proc || !info.instance) return {};
13357 const auto get = reinterpret_cast<PFN_vkGetPhysicalDeviceMemoryProperties2>(
13358 info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMemoryProperties2"));
13359 return leonida::query_vram_budget(get, info.physical);
13360}
13361
10699// The Vulkan objects create_vulkan_device_standalone made, destroyed with the device. 13362// The Vulkan objects create_vulkan_device_standalone made, destroyed with the device.
10700struct OwnedRuntime { 13363struct OwnedRuntime {
10701 PFN_vkDestroyDevice destroy_device = nullptr; 13364 PFN_vkDestroyDevice destroy_device = nullptr;
@@ -10722,6 +13385,15 @@ public:
10722 // worker still has a warm-up to run is one too high. The proxy's count waits for the pool. 13385 // worker still has a warm-up to run is one too high. The proxy's count waits for the pool.
10723 rt::d3d12_xs::set_reference_settler([] { PipelineCompiler::instance().wait_idle(); }); 13386 rt::d3d12_xs::set_reference_settler([] { PipelineCompiler::instance().wait_idle(); });
10724 state_.info = info; 13387 state_.info = info;
13388 {
13389 std::lock_guard lock(exit_cache_mutex);
13390 exit_cache_devices.push_back(&state_);
13391 }
13392 // The GPU memory figure of the title HUD and the dev overlay: the newest device with VK_EXT_memory_budget.
13393 if (info.memory_budget)
13394 leonida::memory_figures::publish_vram_reader(
13395 [](const void* context) { return read_vram_budget(static_cast<const DeviceState*>(context)->info); },
13396 &state_);
10725 queue_users_.resize(info.command_queues.size(), 0); 13397 queue_users_.resize(info.command_queues.size(), 0);
10726 compute_users_.resize(info.compute_queues.size(), 0); 13398 compute_users_.resize(info.compute_queues.size(), 0);
10727 copy_users_.resize(info.copy_queues.size(), 0); 13399 copy_users_.resize(info.copy_queues.size(), 0);
@@ -10831,8 +13503,10 @@ public:
10831 VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_16_BIT; 13503 VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_16_BIT;
10832 state_.no_output_sample_counts = 13504 state_.no_output_sample_counts =
10833 static_cast<UINT>(props.limits.framebufferNoAttachmentsSampleCounts & kD3D12SampleCounts); 13505 static_cast<UINT>(props.limits.framebufferNoAttachmentsSampleCounts & kD3D12SampleCounts);
10834 state_.f16_half_top_location = leonida::f16_half_top_location( 13506 state_.f16_half_top_location = info.f16_half_top_location != 0
10835 props.limits.maxVertexOutputComponents, props.limits.maxFragmentInputComponents); 13507 ? info.f16_half_top_location
13508 : leonida::f16_half_top_location(
13509 props.limits.maxVertexOutputComponents, props.limits.maxFragmentInputComponents);
10836 } 13510 }
10837 if (const auto get_props2 = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>( 13511 if (const auto get_props2 = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
10838 info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2"))) { 13512 info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2"))) {
@@ -10869,7 +13543,8 @@ public:
10869 indirect); 13543 indirect);
10870 if (info.device_fault_diagnostics) { 13544 if (info.device_fault_diagnostics) {
10871 state_.context->configure_device_fault(get_device, 13545 state_.context->configure_device_fault(get_device,
10872 {info.device_fault_info, info.device_checkpoints, info.device_diagnostics_config}); 13546 {info.device_fault_info, info.device_checkpoints, info.device_diagnostics_config, info.device_markers},
13547 &state_.memory);
10873 state_.context->add_diagnostic_queue(info.queue); 13548 state_.context->add_diagnostic_queue(info.queue);
10874 for (auto queue : info.command_queues) state_.context->add_diagnostic_queue(queue); 13549 for (auto queue : info.command_queues) state_.context->add_diagnostic_queue(queue);
10875 for (auto queue : info.compute_queues) state_.context->add_diagnostic_queue(queue); 13550 for (auto queue : info.compute_queues) state_.context->add_diagnostic_queue(queue);
@@ -10883,6 +13558,9 @@ public:
10883 if (auto* fault = state_.context->device_fault()) 13558 if (auto* fault = state_.context->device_fault())
10884 fault->set_lost_hook([this] { rt::compute_probe::recheck(state_); }); 13559 fault->set_lost_hook([this] { rt::compute_probe::recheck(state_); });
10885 } 13560 }
13561 if (async_texture_refresh()) start_title_filler();
13562 state_.setup_console_heap_gpu(get_device); // LEONIDA_CONSOLE_HEAP_GPU: the context's prelude
13563 state_.context->set_after_execute([this] { state_.geometry_execute_end(); });
10886 state_.context->set_before_execute([this] { 13564 state_.context->set_before_execute([this] {
10887 namespace phases = leonida::submit_phases; 13565 namespace phases = leonida::submit_phases;
10888 // LEONIDA_REFRESH_PER_FRAME (for runs that only need the title to go on): 1 = the slot-133 shadows, title 13566 // LEONIDA_REFRESH_PER_FRAME (for runs that only need the title to go on): 1 = the slot-133 shadows, title
@@ -10895,11 +13573,13 @@ public:
10895 const char* v = std::getenv("LEONIDA_REFRESH_PER_FRAME"); 13573 const char* v = std::getenv("LEONIDA_REFRESH_PER_FRAME");
10896 return v && *v ? std::atoi(v) : 0; 13574 return v && *v ? std::atoi(v) : 0;
10897 }(); 13575 }();
13576 state_.geometry_execute_begin();
10898 bool full = true; 13577 bool full = true;
10899 if (per_frame) { 13578 if (per_frame) {
10900 const std::uint64_t serial = phases::totals().present_serial.load(std::memory_order_relaxed); 13579 const std::uint64_t serial = phases::totals().present_serial.load(std::memory_order_relaxed);
10901 full = refreshed_present_.exchange(serial, std::memory_order_relaxed) != serial; 13580 full = refreshed_present_.exchange(serial, std::memory_order_relaxed) != serial;
10902 } 13581 }
13582 state_.drain_geometry_releases();
10903 state_.refresh_shadows(full || per_frame < 2, full); 13583 state_.refresh_shadows(full || per_frame < 2, full);
10904 // LEONIDA_GEOMETRY_ASYNC=1 (for runs that only need the title to go on): the geometry copies are brought 13584 // LEONIDA_GEOMETRY_ASYNC=1 (for runs that only need the title to go on): the geometry copies are brought
10905 // up to date on a worker of ours, started here and not waited for, instead of on the title's GPU submit 13585 // up to date on a worker of ours, started here and not waited for, instead of on the title's GPU submit
@@ -10916,7 +13596,14 @@ public:
10916 state_.geometry.refresh(DeviceState::copy_geometry); 13596 state_.geometry.refresh(DeviceState::copy_geometry);
10917 } 13597 }
10918 const phases::Scope timed(phases::textures); 13598 const phases::Scope timed(phases::textures);
10919 refresh_title_textures(); 13599 if (async_texture_refresh()) {
13600 if (!t_in_title_textures) {
13601 fill_first_mapped_textures();
13602 request_title_refresh();
13603 }
13604 } else {
13605 refresh_title_textures();
13606 }
10920 }); 13607 });
10921 { 13608 {
10922 char text[16] = {}; 13609 char text[16] = {};
@@ -10937,6 +13624,10 @@ public:
10937 threads.count); 13624 threads.count);
10938 if (threads.count) 13625 if (threads.count)
10939 state_.context->set_pipeline_workers(std::make_unique<leonida::PipelineWorkers>(threads.count)); 13626 state_.context->set_pipeline_workers(std::make_unique<leonida::PipelineWorkers>(threads.count));
13627 if (big_compiles() == BigCompiles::budget)
13628 state_.context->set_large_compiles(
13629 [] { return big_compile_gate().budget(); },
13630 [] { return std::make_shared<leonida::LargeModuleGate::Demand>(big_compile_gate()); });
10940 } 13631 }
10941 leonida::title_va_aliases().set_hooks( 13632 leonida::title_va_aliases().set_hooks(
10942 &state_, 13633 &state_,
@@ -11085,12 +13776,15 @@ public:
11085 // device addresses the same scratch holds the triangle indices of indexed quad lists (quad_index_expand.h): 13776 // device addresses the same scratch holds the triangle indices of indexed quad lists (quad_index_expand.h):
11086 // a compute pass writes them through the chunk's address and the draw binds the chunk as its index buffer. 13777 // a compute pass writes them through the chunk's address and the draw binds the chunk as its index buffer.
11087 const bool index_scratch = info.buffer_device_address; 13778 const bool index_scratch = info.buffer_device_address;
13779 const VkBufferUsageFlags scratch_extra =
13780 VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
13781 (index_scratch ? VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0);
11088 state_.context->enable_copy_scratch( 13782 state_.context->enable_copy_scratch(
11089 get_device, 13783 get_device,
11090 [this, index_scratch](const VkMemoryRequirements& requirements) { 13784 [this, index_scratch](const VkMemoryRequirements& requirements) {
11091 return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch); 13785 return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch);
11092 }, 13786 },
11093 index_scratch ? VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0, state_.families); 13787 scratch_extra, state_.families);
11094 if (info.buffer_device_address && info.physical && info.get_instance_proc) { 13788 if (info.buffer_device_address && info.physical && info.get_instance_proc) {
11095 if (const auto get_props = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>( 13789 if (const auto get_props = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>(
11096 info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { 13790 info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) {
@@ -11105,7 +13799,8 @@ public:
11105 return state_.allocate(requirements, 0, 13799 return state_.allocate(requirements, 0,
11106 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 13800 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
11107 nullptr, /*device_address=*/true); 13801 nullptr, /*device_address=*/true);
11108 }); 13802 },
13803 state_.families);
11109 } 13804 }
11110 } 13805 }
11111 // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of 13806 // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of
@@ -11237,6 +13932,41 @@ public:
11237 std::fprintf(stderr, "[rt] d3d12: descriptor hash: %s (all %zu modules)\n", 13932 std::fprintf(stderr, "[rt] d3d12: descriptor hash: %s (all %zu modules)\n",
11238 leonida::descriptor_hash_kind_name(descriptor_hash), hash_modules.total()); 13933 leonida::descriptor_hash_kind_name(descriptor_hash), hash_modules.total());
11239 } 13934 }
13935 // Which entry layout the loaded modules read (descriptor_table.h): a tagged module reads the kind word next to
13936 // 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
13937 // image), and the inserts below fill it. A plain library reads only the index, exactly as before. The kind
13938 // word is additive, so one tagged module needs the tagged layout whatever the plain count (the library's
13939 // vote); chosen once here, like the hash kind, and LEONIDA_DESCRIPTOR_TABLE overrides.
13940 leonida::DescriptorTableCensus table_modules{};
13941 leonida::DescriptorTableLayout descriptor_table = leonida::DescriptorTableLayout::plain;
13942 if (const leonida::ShaderLibrary* library = state_.library()) {
13943 table_modules = library->descriptor_table_census();
13944 descriptor_table = library->descriptor_table_layout();
13945 }
13946 leonida::DescriptorTableLayout override_table = descriptor_table;
13947 if (leonida::descriptor_table_layout_from_env(std::getenv("LEONIDA_DESCRIPTOR_TABLE"), &override_table)) {
13948 std::fprintf(stderr,
13949 "[rt] d3d12: descriptor table: %s (LEONIDA_DESCRIPTOR_TABLE; %zu tagged / %zu plain modules)\n",
13950 leonida::descriptor_table_layout_name(override_table), table_modules.tagged,
13951 table_modules.plain);
13952 descriptor_table = override_table;
13953 // Under a plain table a tagged module reads no kind at all, so every image an instruction reads through
13954 // another dimension's array takes that array's fallback. That is what the override asks for; say so.
13955 if (override_table == leonida::DescriptorTableLayout::plain && table_modules.tagged)
13956 std::fprintf(stderr,
13957 "[rt] d3d12: LEONIDA_DESCRIPTOR_TABLE forces the plain descriptor table while %zu "
13958 "module(s) read the kind word; their image lookups through another dimension's array "
13959 "take the fallback\n",
13960 table_modules.tagged);
13961 } else if (table_modules.tagged && table_modules.plain) {
13962 std::fprintf(stderr, "[rt] d3d12: descriptor table: %zu tagged / %zu plain modules; using %s\n",
13963 table_modules.tagged, table_modules.plain,
13964 leonida::descriptor_table_layout_name(descriptor_table));
13965 } else {
13966 std::fprintf(stderr, "[rt] d3d12: descriptor table: %s (all %zu modules)\n",
13967 leonida::descriptor_table_layout_name(descriptor_table), table_modules.total());
13968 }
13969 state_.descriptor_table_tagged = descriptor_table == leonida::DescriptorTableLayout::tagged;
11240 const auto get_properties = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>( 13970 const auto get_properties = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
11241 state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); 13971 state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2"));
11242 if (get_properties) { 13972 if (get_properties) {
@@ -11311,6 +14041,7 @@ public:
11311 // after it, so the generations flush() retires are free at once. 14041 // after it, so the generations flush() retires are free at once.
11312 { 14042 {
11313 std::lock_guard submit(context.submit_mutex()); 14043 std::lock_guard submit(context.submit_mutex());
14044 const leonida::SubmitMutex::SubmitTurn turn(context.submit_mutex()); // the compile gate
11314 context.observe_result(context.vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); 14045 context.observe_result(context.vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle");
11315 } 14046 }
11316 state_.bindless_idle_waits.fetch_add(1, std::memory_order_relaxed); 14047 state_.bindless_idle_waits.fetch_add(1, std::memory_order_relaxed);
@@ -11400,7 +14131,14 @@ public:
11400 if (!vk.vkGetBufferDeviceAddress) return false; 14131 if (!vk.vkGetBufferDeviceAddress) return false;
11401 char text[16] = {}; 14132 char text[16] = {};
11402 size_t length = 0; 14133 size_t length = 0;
11403 const bool set = getenv_s(&length, text, "LEONIDA_ARENA_MB") == 0 && length > 1; 14134 bool set = getenv_s(&length, text, "LEONIDA_ARENA_MB") == 0 && length > 1;
14135 // A value the CRT's copy of the environment does not give (or one past this buffer): asked of Windows too,
14136 // then report the size applied to the arena.
14137 if (!set) {
14138 const DWORD n = GetEnvironmentVariableA("LEONIDA_ARENA_MB", text, sizeof(text));
14139 set = n > 0 && n < sizeof(text);
14140 if (set) std::fprintf(stderr, "[rt] d3d12: LEONIDA_ARENA_MB was read from the process environment, not the CRT's\n");
14141 }
11404 const leonida::ArenaLimits limits{state_.info.max_buffer_size, state_.info.max_memory_allocation_size}; 14142 const leonida::ArenaLimits limits{state_.info.max_buffer_size, state_.info.max_memory_allocation_size};
11405 leonida::ArenaSize size = leonida::decide_arena_size(set ? text : nullptr, limits); 14143 leonida::ArenaSize size = leonida::decide_arena_size(set ? text : nullptr, limits);
11406 auto& arena = state_.arena; 14144 auto& arena = state_.arena;
@@ -11485,6 +14223,8 @@ public:
11485 return false; 14223 return false;
11486 } 14224 }
11487 arena.mapped = static_cast<std::uint8_t*>(mapped); 14225 arena.mapped = static_cast<std::uint8_t*>(mapped);
14226 std::fprintf(stderr, "[rt] d3d12: GPU address arena: %llu MiB (LEONIDA_ARENA_MB %s)\n",
14227 static_cast<unsigned long long>(info.size >> 20), set ? text : "unset");
11488 // LEONIDA_ARENA_NULL_MB=<n> (for compute-on boots): the first n MiB of the arena, at heap_base + 0, are zeroed 14228 // LEONIDA_ARENA_NULL_MB=<n> (for compute-on boots): the first n MiB of the arena, at heap_base + 0, are zeroed
11489 // and never handed out, and the zero page and the quad indices move above them. A translated shader whose 14229 // and never handed out, and the zero page and the quad indices move above them. A translated shader whose
11490 // address arithmetic starts from a null base (a scalar or flat load the translator does not bounds-check) 14230 // address arithmetic starts from a null base (a scalar or flat load the translator does not bounds-check)
@@ -11536,6 +14276,7 @@ public:
11536 arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; 14276 arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0';
11537 state_.context->set_heap_base(arena.address, arena.size); 14277 state_.context->set_heap_base(arena.address, arena.size);
11538 leonida::fsdraw::note_arena(arena.mapped, arena.size); // LOCAL DIAGNOSTIC 14278 leonida::fsdraw::note_arena(arena.mapped, arena.size); // LOCAL DIAGNOSTIC
14279 leonida::fsdraw::backing_hook().store(&fsdraw_backing, std::memory_order_release);
11539 state_.context->set_zero_page(arena.buffer, null_bytes, kZeroPage); 14280 state_.context->set_zero_page(arena.buffer, null_bytes, kZeroPage);
11540 state_.context->set_quad_indices(arena.buffer, null_bytes + kZeroPage, kQuadIndexCount); 14281 state_.context->set_quad_indices(arena.buffer, null_bytes + kZeroPage, kQuadIndexCount);
11541 // Copy only registered title data. Each immutable upload stays alive in the queue command slot 14282 // Copy only registered title data. Each immutable upload stays alive in the queue command slot
@@ -11572,6 +14313,12 @@ public:
11572 } 14313 }
11573 14314
11574 ~Device() override { 14315 ~Device() override {
14316 leonida::memory_figures::withdraw_vram_reader(&state_); // waits for a read of this device in progress
14317 {
14318 // Before anything goes: an exit save in progress finishes with this device first.
14319 std::lock_guard lock(exit_cache_mutex);
14320 std::erase(exit_cache_devices, &state_);
14321 }
11575 leonida::value_sink::clear_arena(&state_); // first: it waits for a value write into the arena in progress 14322 leonida::value_sink::clear_arena(&state_); // first: it waits for a value write into the arena in progress
11576 raw_images_.clear(); 14323 raw_images_.clear();
11577 geometry_refresher_.reset(); // its refresh uses state_.geometry 14324 geometry_refresher_.reset(); // its refresh uses state_.geometry
@@ -11603,6 +14350,7 @@ public:
11603 if (state_.context) { 14350 if (state_.context) {
11604 { 14351 {
11605 std::lock_guard lock(state_.context->submit_mutex()); 14352 std::lock_guard lock(state_.context->submit_mutex());
14353 const leonida::SubmitMutex::SubmitTurn turn(state_.context->submit_mutex()); // the compile gate
11606 state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device), 14354 state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device),
11607 "vkDeviceWaitIdle"); 14355 "vkDeviceWaitIdle");
11608 } 14356 }
@@ -11612,6 +14360,8 @@ public:
11612 state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below 14360 state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below
11613 } 14361 }
11614 if (state_.context) { 14362 if (state_.context) {
14363 if (state_.gpu_resolver) state_.gpu_resolver->halt(); // it calls into the geometry copies
14364 ShadowPages::gpu_copy = nullptr;
11615 state_.geometry.release(state_); 14365 state_.geometry.release(state_);
11616 state_.external_windows.release(state_); 14366 state_.external_windows.release(state_);
11617 std::lock_guard upload(state_.title_upload_mutex); 14367 std::lock_guard upload(state_.title_upload_mutex);
@@ -11639,7 +14389,7 @@ public:
11639 if (const unsigned building = state_.active_compiles.load()) 14389 if (const unsigned building = state_.active_compiles.load())
11640 std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at device teardown; " 14390 std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at device teardown; "
11641 "pipeline_cache.session.bin not written\n", building); 14391 "pipeline_cache.session.bin not written\n", building);
11642 else 14392 else if (!compile_helper::build_host)
11643 save_session_pipeline_cache(state_.context->vk, state_.info.device, state_.pipeline_cache_handle); 14393 save_session_pipeline_cache(state_.context->vk, state_.info.device, state_.pipeline_cache_handle);
11644 state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); 14394 state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr);
11645 } 14395 }
@@ -11650,6 +14400,8 @@ public:
11650 } 14400 }
11651 14401
11652 bool ok() const { return state_.context && state_.context->loaded(); } 14402 bool ok() const { return state_.context && state_.context->loaded(); }
14403 // gta6rt --precompile-pipelines builds against the device's own state (precompile_compute_pipelines).
14404 DeviceState& build_state() { return state_; }
11653 const VulkanDeviceInfo& info() const { return state_.info; } 14405 const VulkanDeviceInfo& info() const { return state_.info; }
11654 // Acceleration-structure resources work: KHR builds, or the XDXR records (which need the GPU address arena). 14406 // Acceleration-structure resources work: KHR builds, or the XDXR records (which need the GPU address arena).
11655 bool acceleration_structures() const { 14407 bool acceleration_structures() const {
@@ -11658,6 +14410,7 @@ public:
11658 bool upload_in_vram() const { return state_.upload_in_vram; } 14410 bool upload_in_vram() const { return state_.upload_in_vram; }
11659 leonida::VulkanContext& context() { return *state_.context; } 14411 leonida::VulkanContext& context() { return *state_.context; }
11660 const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } 14412 const leonida::BindlessSet* bindless() const { return state_.bindless.get(); }
14413 DeviceState& state() { return state_; }
11661 const DeviceState& state() const { return state_; } 14414 const DeviceState& state() const { return state_; }
11662 HRESULT create_native_graphics(const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) { 14415 HRESULT create_native_graphics(const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) {
11663 const auto* shaders = state_.library(); 14416 const auto* shaders = state_.library();
@@ -11826,7 +14579,8 @@ public:
11826 d.height, unsigned(d.depth_or_array), d.format, unsigned(srv.Format), unsigned(d.mips), unsigned(written)); 14579 d.height, unsigned(d.depth_or_array), d.format, unsigned(srv.Format), unsigned(d.mips), unsigned(written));
11827 if (!written && stats.refusals == refusals) refuse_title_view("no reason recorded", d, address); 14580 if (!written && stats.refusals == refusals) refuse_title_view("no reason recorded", d, address);
11828 if (!written) ++stats.null_views; 14581 if (!written) ++stats.null_views;
11829 if (stats.views == 64 || !(stats.views % 2048)) log_title_census("slot-70 texture views"); 14582 if (leonida::fsdraw::enabled() && (stats.views == 64 || !(stats.views % 2048)))
14583 log_title_census("slot-70 texture views");
11830 } 14584 }
11831 state_.drain_titles_gone(); 14585 state_.drain_titles_gone();
11832 return written; 14586 return written;
@@ -11923,6 +14677,8 @@ public:
11923 } 14677 }
11924 auto& slot = state_.title_textures[address]; 14678 auto& slot = state_.title_textures[address];
11925 if (slot && slot->owned) retire_title_texture(*slot); 14679 if (slot && slot->owned) retire_title_texture(*slot);
14680 state_.mapped_title_textures.erase(address);
14681 state_.index_texture(*entry);
11926 slot = std::move(entry); 14682 slot = std::move(entry);
11927 ++title_stats_.registered; 14683 ++title_stats_.registered;
11928 } 14684 }
@@ -11969,7 +14725,11 @@ public:
11969 // title_texture_gone while this thread holds the registry mutex: the entry stops naming the resource and is 14725 // title_texture_gone while this thread holds the registry mutex: the entry stops naming the resource and is
11970 // erased by drain_titles_gone after the pass. Every walk below visits a snapshot, never an iterator into the 14726 // erased by drain_titles_gone after the pass. Every walk below visits a snapshot, never an iterator into the
11971 // registry, and skips an entry without a resource. 14727 // registry, and skips an entry without a resource.
11972 const auto entries = leonida::title_texture_snapshot(state_.title_textures); 14728 // The worker gives journal hits priority. Rotate a small slice for direct writes with no notification.
14729 const bool async = async_texture_refresh();
14730 const auto entries = async ? leonida::title_texture_snapshot(state_.title_textures, title_slice_, 128)
14731 : leonida::title_texture_snapshot(state_.title_textures);
14732 if (async) title_slice_ = entries.size() == 128 ? entries.back().first + 1 : 0;
11973 title_pass_ = true; 14733 title_pass_ = true;
11974 std::uint64_t checked = 0, filled = 0, fill_pass_ns = 0; 14734 std::uint64_t checked = 0, filled = 0, fill_pass_ns = 0;
11975 const auto visit = [&](TitleTexture& t) { 14735 const auto visit = [&](TitleTexture& t) {
@@ -11991,7 +14751,8 @@ public:
11991 } 14751 }
11992 std::uint64_t hash = 0; 14752 std::uint64_t hash = 0;
11993 if (!title_texture_readable(t)) return; 14753 if (!title_texture_readable(t)) return;
11994 checked += hashed_bytes(span); 14754 const bool full_mapped = async && always;
14755 checked += full_mapped ? span : hashed_bytes(span);
11995 ++stats.checked; 14756 ++stats.checked;
11996 const auto* bytes = reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(t.cpu)); 14757 const auto* bytes = reinterpret_cast<const std::uint8_t*>(static_cast<std::uintptr_t>(t.cpu));
11997 const auto timed_hash = [&](std::uint64_t& out, bool all = false) { 14758 const auto timed_hash = [&](std::uint64_t& out, bool all = false) {
@@ -12000,11 +14761,33 @@ public:
12000 stats.hash_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - start).count(); 14761 stats.hash_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - start).count();
12001 return ok; 14762 return ok;
12002 }; 14763 };
12003 if (!timed_hash(hash)) { 14764 if (full_mapped) {
14765 // Direct writes through a persistent Map have no journal entry. Check every byte on the
14766 // worker. A large mapped plane must not hold up view creation while its hash is computed.
14767 const auto address = t.address, fills = t.fills;
14768 const auto start = clock::now();
14769 title_pass_ = false;
14770 lock.unlock();
14771 const bool ok = hash_guarded(bytes, std::size_t(span), hash, true);
14772 lock.lock();
14773 title_pass_ = true;
14774 stats.hash_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - start).count();
14775 const auto it = state_.title_textures.find(address);
14776 if (it == state_.title_textures.end() || it->second.get() != &t || !t.resource ||
14777 !t.layout_known || t.layout.layout.size != span || t.fills != fills) return;
14778 ++stats.mapped_checks;
14779 if (!ok) {
14780 t.memory.defer();
14781 t.stale = true;
14782 return;
14783 }
14784 if (t.hashed && t.full_hashed && t.full_hash == hash && !t.stale) return;
14785 ++stats.mapped_changed;
14786 } else if (!timed_hash(hash)) {
12004 t.memory.defer(); 14787 t.memory.defer();
12005 return; 14788 return;
12006 } 14789 }
12007 if (t.hashed && hash == t.hash && !t.stale) { 14790 if (!full_mapped && t.hashed && hash == t.hash && !t.stale) {
12008 if (!t.every_byte() || stats.passes % 6) return; 14791 if (!t.every_byte() || stats.passes % 6) return;
12009 std::uint64_t full = 0; 14792 std::uint64_t full = 0;
12010 checked += span; 14793 checked += span;
@@ -12021,7 +14804,10 @@ public:
12021 return; 14804 return;
12022 } 14805 }
12023 const auto fill_start = clock::now(); 14806 const auto fill_start = clock::now();
12024 filled += fill_title_texture(t, false); 14807 const auto uploaded = fill_title_texture(t, false);
14808 filled += uploaded;
14809 if (full_mapped && uploaded) ++stats.mapped_fills;
14810 if (async && t.stale) queue_title_fill(t.address); // generic staging needs an outer fill
12025 const std::uint64_t fill_ns = 14811 const std::uint64_t fill_ns =
12026 std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - fill_start).count(); 14812 std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - fill_start).count();
12027 stats.fill_ns += fill_ns; 14813 stats.fill_ns += fill_ns;
@@ -12047,34 +14833,93 @@ public:
12047 if (!written.empty() || overflow || map_all || !title_map_changes_.empty()) { 14833 if (!written.empty() || overflow || map_all || !title_map_changes_.empty()) {
12048 stats.written_ranges += written.size(); 14834 stats.written_ranges += written.size();
12049 leonida::merge_title_writes(written); 14835 leonida::merge_title_writes(written);
12050 for (const auto& entry : entries) { 14836 const auto invalidate = [&](TitleTexture& t, bool write) {
12051 TitleTexture& t = *entry.second; 14837 if (t.gpu_written || !t.layout_known) return;
12052 if (t.gpu_written || !t.layout_known) continue; 14838 t.memory.retry();
12053 const std::uint64_t begin = t.cpu, end = t.cpu + t.layout.layout.size; 14839 if (write) t.stale = true;
12054 if (map_all || leonida::title_write_overlaps(title_map_changes_, begin, end)) t.memory.retry(); 14840 if (overflow) t.hashed = false;
12055 if (leonida::title_write_overlaps(written, begin, end)) { 14841 };
12056 t.memory.retry(); 14842 if (!async || overflow || map_all) {
12057 t.stale = true; 14843 // No fills or callbacks during invalidation; registry iterators stay valid.
12058 } 14844 for (const auto& [key, ptr] : state_.title_textures) {
12059 if (overflow) { 14845 auto& t = *ptr;
12060 t.memory.retry(); 14846 const auto end = t.cpu + t.layout.layout.size;
12061 t.hashed = false; 14847 const bool write = leonida::title_write_overlaps(written, t.cpu, end);
14848 if (write || map_all || overflow || leonida::title_write_overlaps(title_map_changes_, t.cpu, end))
14849 invalidate(t, write);
12062 } 14850 }
14851 } else {
14852 const auto apply = [&](const auto& ranges, bool write) {
14853 for (const auto& [from, to] : ranges)
14854 state_.texture_ranges.overlapping(from, to, [&](auto key) {
14855 auto& t = *state_.title_textures.at(key);
14856 invalidate(t, write);
14857 if (t.stale) queue_title_fill(key);
14858 });
14859 };
14860 apply(title_map_changes_, false);
14861 apply(written, true);
12063 } 14862 }
12064 } 14863 }
12065 const auto every_start = clock::now(); 14864 const auto every_start = clock::now();
12066 stats.written_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(every_start - now).count(); 14865 stats.written_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(every_start - now).count();
12067 for (const auto& entry : entries) 14866 // LEONIDA_TITLE_EVERY_BUDGET_US (0, the default: no limit, as before) limits the synchronous pass, the one that
12068 if (entry.second->mapped || entry.second->stale) { 14867 // runs before a submission on the title's submitting thread: the mapped and stale textures are visited for at
14868 // most this long a pass, in address order from where the last pass stopped, instead of all of them every pass
14869 // (thousands during a streaming burst on retail, 30-75 ms a pass). The texture that crosses the limit is
14870 // finished; one not reached keeps its mark and waits for a later pass. With LEONIDA_TEXTURE_REFRESH_ASYNC the
14871 // pass runs on the refresh worker, and the limit does not apply.
14872 static const std::uint64_t every_budget_us = setting("LEONIDA_TITLE_EVERY_BUDGET_US", 0);
14873 if (async) {
14874 // Poll every persistent mapping each pass, independently of the bounded stale sweep.
14875 const auto mapped = leonida::title_texture_snapshot(state_.mapped_title_textures);
14876 for (const auto& [address, entry] : mapped) {
14877 if (!entry->resource) continue;
14878 const auto it = state_.title_textures.find(address);
14879 if (it == state_.title_textures.end() || it->second != entry) continue;
12069 ++stats.every_pass_visits; 14880 ++stats.every_pass_visits;
12070 visit(*entry.second); 14881 visit(*entry);
12071 } 14882 }
14883 for (const auto& entry : entries)
14884 if (!entry.second->mapped && entry.second->stale) {
14885 const auto it = state_.title_textures.find(entry.first);
14886 if (it == state_.title_textures.end() || it->second != entry.second) continue;
14887 ++stats.every_pass_visits;
14888 visit(*entry.second);
14889 }
14890 } else if (!every_budget_us) {
14891 for (const auto& entry : entries)
14892 if (entry.second->mapped || entry.second->stale) {
14893 ++stats.every_pass_visits;
14894 visit(*entry.second);
14895 }
14896 } else {
14897 leonida::visit_marked_title_textures(
14898 entries, title_every_cursor_,
14899 [&](TitleTexture& t) {
14900 ++stats.every_pass_visits;
14901 visit(t);
14902 },
14903 // A mapped texture never filled yet does not wait for its turn: the title has written it and the GPU
14904 // has nothing of it (a video plane of #1827 would show frozen until its turn came).
14905 [](const TitleTexture& t) { return t.mapped && !t.fills; },
14906 [&] { return clock::now() - every_start >= std::chrono::microseconds(every_budget_us); });
14907 }
12072 stats.every_pass_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - every_start).count(); 14908 stats.every_pass_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - every_start).count();
12073 // The budget is the round robin's: mapped and stale textures above are checked every pass whatever it is. 14909 // The budget is the round robin's: mapped and stale textures above are checked every pass whatever it is
14910 // (unless LEONIDA_TITLE_EVERY_BUDGET_US limits them).
12074 const auto first_bytes = checked, first_hash_ns = stats.hash_ns; 14911 const auto first_bytes = checked, first_hash_ns = stats.hash_ns;
12075 if (check_budget) { 14912 if (check_budget) {
12076 const auto sweep_start = clock::now(); 14913 const auto sweep_start = clock::now();
12077 leonida::poll_title_textures(entries, title_refresh_cursor_, visit, [&] { 14914 // The normal hash sweep has its own cursor: a byte/time cutoff in a slice must not
14915 // skip the remainder next time just because the stale-texture sweep moved ahead.
14916 decltype(leonida::title_texture_snapshot(state_.title_textures)) background;
14917 if (async) {
14918 if (!state_.title_textures.empty() && title_refresh_cursor_ > state_.title_textures.rbegin()->first)
14919 title_refresh_cursor_ = 0;
14920 background = leonida::title_texture_snapshot(state_.title_textures, title_refresh_cursor_, 128);
14921 }
14922 leonida::poll_title_textures(async ? background : entries, title_refresh_cursor_, visit, [&] {
12078 if (checked - first_bytes >= check_budget || 14923 if (checked - first_bytes >= check_budget ||
12079 (hash_budget_us && (stats.hash_ns - first_hash_ns) / 1000 >= hash_budget_us)) return true; 14924 (hash_budget_us && (stats.hash_ns - first_hash_ns) / 1000 >= hash_budget_us)) return true;
12080 if (!sweep_budget_us) return false; 14925 if (!sweep_budget_us) return false;
@@ -12098,7 +14943,14 @@ public:
12098 stats.max_refresh_ns = std::max(stats.max_refresh_ns, pass_ns); 14943 stats.max_refresh_ns = std::max(stats.max_refresh_ns, pass_ns);
12099 if (now - stats.last_log >= std::chrono::seconds(10)) { 14944 if (now - stats.last_log >= std::chrono::seconds(10)) {
12100 stats.last_log = now; 14945 stats.last_log = now;
12101 log_title_census("refresh"); 14946 if (async) {
14947 std::fprintf(stderr, "[rt] async texture refresh: %llu mapped checks, %llu changed or stale, %llu uploaded in pass\n",
14948 static_cast<unsigned long long>(stats.mapped_checks),
14949 static_cast<unsigned long long>(stats.mapped_changed),
14950 static_cast<unsigned long long>(stats.mapped_fills));
14951 stats.mapped_checks = stats.mapped_changed = stats.mapped_fills = 0;
14952 }
14953 if (leonida::fsdraw::enabled()) log_title_census("refresh");
12102 } 14954 }
12103 inside.reset(); 14955 inside.reset();
12104 lock.unlock(); 14956 lock.unlock();
@@ -12108,6 +14960,7 @@ public:
12108 14960
12109private: 14961private:
12110 struct TitleTextureStats { 14962 struct TitleTextureStats {
14963 std::uint64_t mapped_checks = 0, mapped_changed = 0, mapped_fills = 0;
12111 // (format, Layout word, dimension, mips) of the slot-70 texture views -> views 14964 // (format, Layout word, dimension, mips) of the slot-70 texture views -> views
12112 std::map<std::array<std::uint32_t, 4>, std::uint64_t> asked; 14965 std::map<std::array<std::uint32_t, 4>, std::uint64_t> asked;
12113 std::map<std::string, std::uint64_t> refused; // why a view is a null view -> views 14966 std::map<std::string, std::uint64_t> refused; // why a view is a null view -> views
@@ -12149,7 +15002,7 @@ private:
12149 std::condition_variable wake; 15002 std::condition_variable wake;
12150 std::deque<std::uint64_t> queue; // texture addresses 15003 std::deque<std::uint64_t> queue; // texture addresses
12151 std::unordered_set<std::uint64_t> queued; 15004 std::unordered_set<std::uint64_t> queued;
12152 bool stop = false; 15005 bool stop = false, refresh = false;
12153 std::thread thread; 15006 std::thread thread;
12154 std::uint64_t filled = 0, skipped = 0; 15007 std::uint64_t filled = 0, skipped = 0;
12155 std::vector<std::uint8_t> tiled; // the worker's own snapshot of a texture's bytes (fill_unlocked) 15008 std::vector<std::uint8_t> tiled; // the worker's own snapshot of a texture's bytes (fill_unlocked)
@@ -12165,12 +15018,49 @@ private:
12165 }; 15018 };
12166 std::unique_ptr<TitleFiller> title_filler_; 15019 std::unique_ptr<TitleFiller> title_filler_;
12167 std::once_flag title_filler_once_; 15020 std::once_flag title_filler_once_;
12168 void queue_title_fill(std::uint64_t address) { 15021 void start_title_filler() {
12169 std::call_once(title_filler_once_, [this] { 15022 std::call_once(title_filler_once_, [this] {
12170 title_filler_ = std::make_unique<TitleFiller>(); 15023 title_filler_ = std::make_unique<TitleFiller>();
12171 TitleFiller* f = title_filler_.get(); 15024 TitleFiller* f = title_filler_.get();
12172 f->thread = std::thread([this, f] { run_title_filler(*f); }); 15025 f->thread = std::thread([this, f] { run_title_filler(*f); });
12173 }); 15026 });
15027 }
15028 // LEONIDA_TEXTURE_REFRESH_ASYNC=1, before a submission: a mapped texture that has never been filled (a video plane
15029 // the title maps, writes and draws right away) is filled here, on the submitting thread, so its first draw does not
15030 // sample an empty image while the worker has not come to it yet. Everything else stays on the worker. Only when
15031 // the registry is free: the worker may hold it for a fill that needs this queue, so waiting here could deadlock.
15032 void fill_first_mapped_textures() {
15033 std::unique_lock lock(state_.title_texture_mutex, std::try_to_lock);
15034 if (!lock.owns_lock()) return;
15035 std::vector<std::shared_ptr<TitleTexture>> first;
15036 for (const auto& [address, t] : state_.mapped_title_textures)
15037 if (t->resource && !t->fills && !t->gpu_written && t->layout_known) first.push_back(t);
15038 if (first.empty()) return;
15039 {
15040 const InTitleTextures inside;
15041 for (const auto& t : first) {
15042 // A fill can submit and retire an image (title_texture_gone): look each one up again.
15043 const auto it = state_.title_textures.find(t->address);
15044 if (it == state_.title_textures.end() || it->second != t || !t->resource || t->fills) continue;
15045 fill_title_texture(*t, false);
15046 if (t->stale) queue_title_fill(t->address); // generic staging needs an outer fill (the worker's)
15047 }
15048 }
15049 lock.unlock();
15050 state_.drain_titles_gone();
15051 }
15052
15053 void request_title_refresh() {
15054 {
15055 // A busy queue can take the next submission's request. Dirty entries stay on the worker.
15056 std::unique_lock lock(title_filler_->mutex, std::try_to_lock);
15057 if (!lock.owns_lock() || title_filler_->refresh) return;
15058 title_filler_->refresh = true;
15059 }
15060 title_filler_->wake.notify_one();
15061 }
15062 void queue_title_fill(std::uint64_t address) {
15063 start_title_filler();
12174 { 15064 {
12175 std::lock_guard lock(title_filler_->mutex); 15065 std::lock_guard lock(title_filler_->mutex);
12176 if (!title_filler_->queued.insert(address).second) return; 15066 if (!title_filler_->queued.insert(address).second) return;
@@ -12183,14 +15073,21 @@ private:
12183 auto since = clock::now(); 15073 auto since = clock::now();
12184 for (;;) { 15074 for (;;) {
12185 std::uint64_t address = 0; 15075 std::uint64_t address = 0;
15076 bool refresh = false, fill = false;
12186 { 15077 {
12187 std::unique_lock lock(f.mutex); 15078 std::unique_lock lock(f.mutex);
12188 f.wake.wait(lock, [&] { return f.stop || !f.queue.empty(); }); 15079 f.wake.wait(lock, [&] { return f.stop || f.refresh || !f.queue.empty(); });
12189 if (f.stop) return; 15080 if (f.stop) return;
12190 address = f.queue.front(); 15081 refresh = std::exchange(f.refresh, false);
12191 f.queue.pop_front(); 15082 fill = !f.queue.empty();
12192 f.queued.erase(address); 15083 if (fill) {
15084 address = f.queue.front();
15085 f.queue.pop_front();
15086 f.queued.erase(address);
15087 }
12193 } 15088 }
15089 if (refresh) refresh_title_textures();
15090 if (!fill) continue;
12194 bool filled = false; 15091 bool filled = false;
12195 // A staged texture is filled without the registry lock (the title's threads creating views wait for 15092 // A staged texture is filled without the registry lock (the title's threads creating views wait for
12196 // it: speed-31, 12 % of the main thread): its bytes, layout and resource are taken under the lock, the 15093 // it: speed-31, 12 % of the main thread): its bytes, layout and resource are taken under the lock, the
@@ -12218,6 +15115,7 @@ private:
12218 every_byte = t.every_byte(); 15115 every_byte = t.every_byte();
12219 } else { 15116 } else {
12220 filled = fill_title_texture(t, true) != 0; 15117 filled = fill_title_texture(t, true) != 0;
15118 if (!filled) t.stale = true;
12221 } 15119 }
12222 } 15120 }
12223 } 15121 }
@@ -12332,7 +15230,9 @@ private:
12332 } 15230 }
12333 geometry_refresher_->wake.notify_one(); 15231 geometry_refresher_->wake.notify_one();
12334 } 15232 }
15233 std::uint64_t title_slice_ = 0; // next registry slice on the async worker
12335 std::uint64_t title_refresh_cursor_ = 0; // under title_texture_mutex 15234 std::uint64_t title_refresh_cursor_ = 0; // under title_texture_mutex
15235 std::uint64_t title_every_cursor_ = 0; // likewise: LEONIDA_TITLE_EVERY_BUDGET_US's resume point
12336 std::uint64_t title_map_generation_ = 0; // likewise: the map changes the passes have seen 15236 std::uint64_t title_map_generation_ = 0; // likewise: the map changes the passes have seen
12337 std::chrono::steady_clock::time_point title_retry_all_{}; // likewise 15237 std::chrono::steady_clock::time_point title_retry_all_{}; // likewise
12338 leonida::TitleWriteRanges title_map_changes_; // likewise, scratch 15238 leonida::TitleWriteRanges title_map_changes_; // likewise, scratch
@@ -12428,6 +15328,7 @@ private:
12428 t->layout = layout; 15328 t->layout = layout;
12429 t->desc = words; 15329 t->desc = words;
12430 t->layout_known = true; 15330 t->layout_known = true;
15331 state_.index_texture(*t);
12431 t->layout_guessed = t->layout_from_xg = false; 15332 t->layout_guessed = t->layout_from_xg = false;
12432 t->hashed = false; 15333 t->hashed = false;
12433 } else { 15334 } else {
@@ -12446,6 +15347,7 @@ private:
12446 rt::xg_xs::format_info(t->desc[8]).side == rt::xg_xs::format_info(words[8]).side; 15347 rt::xg_xs::format_info(t->desc[8]).side == rt::xg_xs::format_info(words[8]).side;
12447 }(); 15348 }();
12448 retire_title_texture(*t); 15349 retire_title_texture(*t);
15350 state_.texture_ranges.erase(address);
12449 textures.erase(address); 15351 textures.erase(address);
12450 t = make_title_texture(d, words, srv, address, same_shape ? formats : std::vector<DXGI_FORMAT>{}); 15352 t = make_title_texture(d, words, srv, address, same_shape ? formats : std::vector<DXGI_FORMAT>{});
12451 } else if (t) { 15353 } else if (t) {
@@ -12545,6 +15447,7 @@ private:
12545 } 15447 }
12546 ++title_stats_.made; 15448 ++title_stats_.made;
12547 TitleTexture* t = entry.get(); 15449 TitleTexture* t = entry.get();
15450 state_.index_texture(*entry);
12548 state_.title_textures[address] = std::move(entry); 15451 state_.title_textures[address] = std::move(entry);
12549 if (title_fill_async() && !t->memory.pending()) queue_title_fill(address); 15452 if (title_fill_async() && !t->memory.pending()) queue_title_fill(address);
12550 return t; 15453 return t;
@@ -13788,7 +16691,7 @@ public:
13788 pipeline->attach_device(identity()); 16691 pipeline->attach_device(identity());
13789 const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute) 16692 const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute)
13790 : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as, 16693 : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as,
13791 stream.back_masks ? &stream.back_stencil : nullptr); 16694 stream.back_masks ? &stream.back_stencil : nullptr, stream.depth_bounds);
13792 if (FAILED(hr)) { 16695 if (FAILED(hr)) {
13793 pipeline->Release(); 16696 pipeline->Release();
13794 return finish(hr); 16697 return finish(hr);
@@ -14066,8 +16969,7 @@ public:
14066 words[3] = 0x0002403Cu; 16969 words[3] = 0x0002403Cu;
14067 } 16970 }
14068 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words)); 16971 std::memcpy(reinterpret_cast<void*>(destination.ptr), words.data(), sizeof(words));
14069 // LOCAL DIAGNOSTIC: the CBVs the title makes, where they go and what V# they get 16972 if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: the CBVs the title makes, where they go and what V# they get
14070 if (leonida::local_diagnostics()) {
14071 static std::atomic<std::uint64_t> made{0}; 16973 static std::atomic<std::uint64_t> made{0};
14072 const std::uint64_t n = ++made; 16974 const std::uint64_t n = ++made;
14073 if (n <= 8 || n % 600 == 0 || n % 600 == 1) 16975 if (n <= 8 || n % 600 == 0 || n % 600 == 1)
@@ -14272,8 +17174,7 @@ public:
14272 } 17174 }
14273 } 17175 }
14274 write_image_descriptor(*r, view, destination, ImageViewUse::sampled); 17176 write_image_descriptor(*r, view, destination, ImageViewUse::sampled);
14275 // LOCAL DIAGNOSTIC: the texture SRVs the title makes, where they go and the T# they get 17177 if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC: the texture SRVs the title makes, where they go and the T# they get
14276 if (leonida::local_diagnostics()) {
14277 static std::atomic<std::uint64_t> made{0}; 17178 static std::atomic<std::uint64_t> made{0};
14278 const std::uint64_t n = ++made; 17179 const std::uint64_t n = ++made;
14279 if (n <= 8 || n % 600 == 0 || n % 600 == 1) { 17180 if (n <= 8 || n % 600 == 0 || n % 600 == 1) {
@@ -14483,7 +17384,7 @@ public:
14483 return; 17384 return;
14484 } 17385 }
14485 const Resource* storage = r->depth_stencil_uav(view.plane); 17386 const Resource* storage = r->depth_stencil_uav(view.plane);
14486 const bool raw_narrow = storage && r->desc().Format == xbox_d16s8 && view.plane == 0 && 17387 const bool raw_narrow = storage && (r->desc().Format == xbox_d16s8 || r->console_d16s8()) && view.plane == 0 &&
14487 (view.format == DXGI_FORMAT_R16_UINT || 17388 (view.format == DXGI_FORMAT_R16_UINT ||
14488 (storage->desc().Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM)); 17389 (storage->desc().Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM));
14489 if (!storage || (!raw_narrow && view.format != storage->desc().Format)) { 17390 if (!storage || (!raw_narrow && view.format != storage->desc().Format)) {
@@ -15219,9 +18120,17 @@ public:
15219 if (out) *out = nullptr; 18120 if (out) *out = nullptr;
15220 auto* heap = Heap::from<Heap>(heap_interface); 18121 auto* heap = Heap::from<Heap>(heap_interface);
15221 if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG); 18122 if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG);
18123 const bool from_xbox_d16s8 = desc->Format == xbox_d16s8;
15222 D3D12_RESOURCE_DESC canonical = *desc; 18124 D3D12_RESOURCE_DESC canonical = *desc;
15223 canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 18125 canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8
15224 desc = &canonical; 18126 desc = &canonical;
18127 // Its clear value too, or the clear format's family (118) would not match the resource's (D24S8) below.
18128 D3D12_CLEAR_VALUE canonical_clear{};
18129 if (clear) {
18130 canonical_clear = *clear;
18131 canonical_clear.Format = pc_format(canonical_clear.Format);
18132 clear = &canonical_clear;
18133 }
15225 if (heap->host_address()) { 18134 if (heap->host_address()) {
15226 // An existing heap is not an arena range, and the placed path addresses resources by arena offset. 18135 // An existing heap is not an arena range, and the placed path addresses resources by arena offset.
15227 log_once("a placed resource in an existing heap (OpenExistingHeapFromAddress) is not supported yet; " 18136 log_once("a placed resource in an existing heap (OpenExistingHeapFromAddress) is not supported yet; "
@@ -15309,6 +18218,7 @@ public:
15309 // create_texture makes for 1D, 2D and 3D alike (arrays and mips included), as for a committed texture. 18218 // create_texture makes for 1D, 2D and 3D alike (arrays and mips included), as for a committed texture.
15310 const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0; 18219 const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0;
15311 auto* resource = new Resource(state_, *desc, heap->properties(), heap->flags(), placed_va); 18220 auto* resource = new Resource(state_, *desc, heap->properties(), heap->flags(), placed_va);
18221 if (from_xbox_d16s8) resource->mark_console_d16s8();
15312 resource->attach_device(identity()); 18222 resource->attach_device(identity());
15313 HRESULT hr = E_NOTIMPL; 18223 HRESULT hr = E_NOTIMPL;
15314 if (buffer) { 18224 if (buffer) {
@@ -15320,7 +18230,8 @@ public:
15320 hr = E_INVALIDARG; 18230 hr = E_INVALIDARG;
15321 } else { 18231 } else {
15322 std::vector<VkFormat> cast_formats; 18232 std::vector<VkFormat> cast_formats;
15323 hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats); 18233 hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats, false,
18234 from_xbox_d16s8);
15324 if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); 18235 if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats);
15325 if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); 18236 if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable);
15326 } 18237 }
@@ -15580,7 +18491,7 @@ public:
15580 if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS2)) return d3d12_trace::result(method, E_INVALIDARG); 18491 if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS2)) return d3d12_trace::result(method, E_INVALIDARG);
15581 auto* opts = static_cast<D3D12_FEATURE_DATA_D3D12_OPTIONS2*>(data); 18492 auto* opts = static_cast<D3D12_FEATURE_DATA_D3D12_OPTIONS2*>(data);
15582 *opts = {}; 18493 *opts = {};
15583 opts->DepthBoundsTestSupported = FALSE; 18494 opts->DepthBoundsTestSupported = state_.info.features.depthBounds ? TRUE : FALSE;
15584 opts->ProgrammableSamplePositionsTier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; 18495 opts->ProgrammableSamplePositionsTier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED;
15585 return d3d12_trace::result(method, S_OK); 18496 return d3d12_trace::result(method, S_OK);
15586 } 18497 }
@@ -16588,6 +19499,7 @@ private:
16588 TitleImageOrigin origin = TitleImageOrigin::ordinary) { 19499 TitleImageOrigin origin = TitleImageOrigin::ordinary) {
16589 if (out) *out = nullptr; 19500 if (out) *out = nullptr;
16590 if (!heap || !desc) return E_INVALIDARG; 19501 if (!heap || !desc) return E_INVALIDARG;
19502 const bool from_xbox_d16s8 = desc->Format == xbox_d16s8;
16591 D3D12_RESOURCE_DESC canonical = *desc; 19503 D3D12_RESOURCE_DESC canonical = *desc;
16592 canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8 19504 canonical.Format = pc_format(canonical.Format); // the console's D16S8 family as D24S8
16593 desc = &canonical; 19505 desc = &canonical;
@@ -16596,6 +19508,7 @@ private:
16596 return E_INVALIDARG; 19508 return E_INVALIDARG;
16597 } 19509 }
16598 auto* resource = new Resource(state_, *desc, *heap, heap_flags); 19510 auto* resource = new Resource(state_, *desc, *heap, heap_flags);
19511 if (from_xbox_d16s8) resource->mark_console_d16s8();
16599 resource->attach_device(identity()); 19512 resource->attach_device(identity());
16600 HRESULT hr = E_NOTIMPL; 19513 HRESULT hr = E_NOTIMPL;
16601 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { 19514 if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) {
@@ -16632,7 +19545,8 @@ private:
16632 hr = E_INVALIDARG; 19545 hr = E_INVALIDARG;
16633 } else { 19546 } else {
16634 std::vector<VkFormat> cast_formats; 19547 std::vector<VkFormat> cast_formats;
16635 hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats, storage_heap_flags.has_value()); 19548 hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats,
19549 storage_heap_flags.has_value(), from_xbox_d16s8);
16636 if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats, origin); 19550 if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats, origin);
16637 if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); 19551 if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable);
16638 if (SUCCEEDED(hr) && storage_heap_flags) hr = resource->enable_depth_stencil_uav(*storage_heap_flags); 19552 if (SUCCEEDED(hr) && storage_heap_flags) hr = resource->enable_depth_stencil_uav(*storage_heap_flags);
@@ -16906,6 +19820,60 @@ bool stop_pipeline_compiles(unsigned wait_ms) {
16906 return idle; 19820 return idle;
16907} 19821}
16908 19822
19823// How long an exit save waits for the write itself (save_session_pipeline_cache): a 77 MiB cache was measured at about
19824// 36 ms (fill and publish), so this only bounds a driver that blocks the read.
19825constexpr unsigned kExitCacheWriteMs = 3000;
19826
19827bool save_pipeline_caches_at_exit(unsigned wait_ms) {
19828 if (exit_cache_saved.exchange(true)) return false; // once: a crash during the normal exit's save does not redo it
19829 std::unique_lock lock(exit_cache_mutex, std::defer_lock);
19830 if (!lock.try_lock_for(std::chrono::milliseconds(wait_ms))) {
19831 std::fprintf(stderr, "[rt] d3d12: device list busy for %u ms at exit; pipeline_cache.session.bin not written\n",
19832 wait_ms);
19833 return false;
19834 }
19835 bool wrote = false;
19836 const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(wait_ms);
19837 for (DeviceState* d : exit_cache_devices) {
19838 if (!d->context || !d->pipeline_cache_handle) continue;
19839 // A build still running (a large one takes minutes; at a crash the faulting thread may be inside one) is
19840 // given until the deadline, then the cache is written without it. Unlike at teardown, the previous file is
19841 // not kept instead: the process is ending, so waiting longer is not possible and keeping the old file throws
19842 // away everything this run compiled (measured: a 1,308 s boot that ended in a title fault with 2 builds
19843 // running). The cache is not created EXTERNALLY_SYNCHRONIZED, so reading it during a build is valid; the
19844 // snapshot holds the pipelines finished so far.
19845 while (d->active_compiles.load() && std::chrono::steady_clock::now() < deadline)
19846 std::this_thread::sleep_for(std::chrono::milliseconds(5));
19847 if (const unsigned building = d->active_compiles.load())
19848 std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at exit; writing the pipelines "
19849 "finished so far\n", building);
19850 // On a thread of its own: a driver that holds the cache until a build ends would otherwise hold the ending
19851 // process too. Past the deadline the process goes on ending; the file is published by a rename
19852 // (CacheStagingFile), so a write cut off there leaves the previous file whole.
19853 struct Write {
19854 std::mutex mutex;
19855 std::condition_variable done_cv;
19856 bool done = false;
19857 };
19858 auto write = std::make_shared<Write>();
19859 std::thread([write, d] {
19860 save_session_pipeline_cache(d->context->vk, d->info.device, d->pipeline_cache_handle, false, "exit");
19861 std::lock_guard done_lock(write->mutex);
19862 write->done = true;
19863 write->done_cv.notify_all();
19864 }).detach();
19865 std::unique_lock write_lock(write->mutex);
19866 if (!write->done_cv.wait_for(write_lock, std::chrono::milliseconds(kExitCacheWriteMs),
19867 [&] { return write->done; })) {
19868 std::fprintf(stderr, "[rt] d3d12: pipeline cache still being written after %u ms at exit; the process "
19869 "ends without waiting for it\n", kExitCacheWriteMs);
19870 return wrote; // the device list stays as it is: the write still uses this device
19871 }
19872 wrote = true;
19873 }
19874 return wrote;
19875}
19876
16909HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) { 19877HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) {
16910 if (!out) return E_POINTER; 19878 if (!out) return E_POINTER;
16911 *out = nullptr; 19879 *out = nullptr;
@@ -17042,11 +20010,28 @@ std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline) {
17042 return p && p->resolve_type(true) ? p->id() : 0; 20010 return p && p->resolve_type(true) ? p->id() : 0;
17043} 20011}
17044 20012
20013void request_pipeline_build(std::uintptr_t id, std::uint32_t bound_targets, bool depth_bound) {
20014 if (!id || !async_replay_compile()) return;
20015 // The id is the PSO's own ID3D12PipelineState pointer (PipelineState::id), which the list keeps a reference to.
20016 auto* pso = static_cast<PipelineState*>(reinterpret_cast<ID3D12PipelineState*>(id));
20017 pso->request_early(bound_targets, depth_bound);
20018}
20019
17045const std::vector<leonida::SubgroupRequest>* pipeline_subgroup_requests(ID3D12PipelineState* pipeline) { 20020const std::vector<leonida::SubgroupRequest>* pipeline_subgroup_requests(ID3D12PipelineState* pipeline) {
17046 const PipelineState* p = PipelineState::from<PipelineState>(pipeline); 20021 const PipelineState* p = PipelineState::from<PipelineState>(pipeline);
17047 return p && (p->compute() || p->graphics()) ? &p->subgroup_requests() : nullptr; 20022 return p && (p->compute() || p->graphics()) ? &p->subgroup_requests() : nullptr;
17048} 20023}
17049 20024
20025bool pipeline_stage_words(ID3D12PipelineState* pipeline, std::vector<std::vector<std::uint32_t>>& words,
20026 std::string& why) {
20027 const PipelineState* p = PipelineState::from<PipelineState>(pipeline);
20028 if (!p) {
20029 why = "not a PipelineState";
20030 return false;
20031 }
20032 return p->stage_words(words, why);
20033}
20034
17050long live_pipeline_states() { return live_pipeline_state_count.load(); } 20035long live_pipeline_states() { return live_pipeline_state_count.load(); }
17051 20036
17052bool write_placed_buffer_view(ID3D12Device* device, bool unordered, const void* view, std::uint64_t address, 20037bool write_placed_buffer_view(ID3D12Device* device, bool unordered, const void* view, std::uint64_t address,
@@ -17069,6 +20054,10 @@ D3D12_GPU_VIRTUAL_ADDRESS console_descriptor_table_va(D3D12_GPU_VIRTUAL_ADDRESS
17069 return console_heap_ranges().shader_va(va); 20054 return console_heap_ranges().shader_va(va);
17070} 20055}
17071 20056
20057bool console_descriptor_heap_range(D3D12_GPU_VIRTUAL_ADDRESS va, std::uint64_t& console_va, std::uint64_t& bytes) {
20058 return console_heap_ranges().range_of(va, console_va, bytes);
20059}
20060
17072// The device a command list of this module belongs to: its attached device is the d3d12_xs proxy when the title made 20061// The device a command list of this module belongs to: its attached device is the d3d12_xs proxy when the title made
17073// the list through one (Device::identity), which does not answer Device's tag itself. 20062// the list through one (Device::identity), which does not answer Device's tag itself.
17074Device* list_device(IUnknown* device) { 20063Device* list_device(IUnknown* device) {
@@ -17158,6 +20147,11 @@ const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) {
17158 return nullptr; 20147 return nullptr;
17159} 20148}
17160 20149
20150leonida::VramBudget vulkan_vram_budget(ID3D12Device* device) {
20151 const VulkanDeviceInfo* info = vulkan_device_info(device);
20152 return info ? read_vram_budget(*info) : leonida::VramBudget{};
20153}
20154
17161std::uint64_t title_shadow_refresh_queries(ID3D12Device* device) { 20155std::uint64_t title_shadow_refresh_queries(ID3D12Device* device) {
17162 auto* d = Device::from<Device>(device); 20156 auto* d = Device::from<Device>(device);
17163 if (!d) return 0; 20157 if (!d) return 0;
@@ -17794,6 +20788,10 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
17794 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; 20788 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR};
17795 VkPhysicalDeviceRayQueryFeaturesKHR rq_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; 20789 VkPhysicalDeviceRayQueryFeaturesKHR rq_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR};
17796 VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; 20790 VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
20791 VkPhysicalDeviceTransformFeedbackFeaturesEXT transform_feedback_features{
20792 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT};
20793 VkPhysicalDeviceTransformFeedbackPropertiesEXT transform_feedback_properties{
20794 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT};
17797 { 20795 {
17798 std::uint32_t extension_count = 0; 20796 std::uint32_t extension_count = 0;
17799 vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); 20797 vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr);
@@ -17818,10 +20816,28 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
17818 vkGetPhysicalDeviceFeatures2(info.physical, &features); 20816 vkGetPhysicalDeviceFeatures2(info.physical, &features);
17819 info.mesh_shader = mesh_features.meshShader == VK_TRUE; 20817 info.mesh_shader = mesh_features.meshShader == VK_TRUE;
17820 info.mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE; 20818 info.mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE;
20819 } else if (!std::strcmp(e.extensionName, VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME)) {
20820 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,
20821 &transform_feedback_features};
20822 vkGetPhysicalDeviceFeatures2(info.physical, &features);
20823 info.transform_feedback = transform_feedback_features.transformFeedback == VK_TRUE;
20824 info.transform_feedback_geometry_streams = transform_feedback_features.geometryStreams == VK_TRUE;
20825 // D3D-302: the queries and the stream count are properties, not features.
20826 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,
20827 &transform_feedback_properties};
20828 vkGetPhysicalDeviceProperties2(info.physical, &properties);
20829 info.transform_feedback_queries = transform_feedback_properties.transformFeedbackQueries == VK_TRUE;
20830 info.max_transform_feedback_streams = transform_feedback_properties.maxTransformFeedbackStreams;
17821 } 20831 }
17822 } 20832 }
17823 if (!info.mesh_shader) 20833 if (!info.mesh_shader)
17824 std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n"); 20834 std::fprintf(stderr, "[rt] d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n");
20835 if (!info.transform_feedback)
20836 std::fprintf(stderr,
20837 "[rt] d3d12: the GPU has no VK_EXT_transform_feedback: SO_STATISTICS query pools read zero\n");
20838 else if (!info.transform_feedback_queries || !info.max_transform_feedback_streams)
20839 std::fprintf(stderr, "[rt] d3d12: the GPU has no transform-feedback queries (transformFeedbackQueries, "
20840 "maxTransformFeedbackStreams): SO_STATISTICS query pools read zero\n");
17825 if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) { 20841 if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) {
17826 as_features.pNext = &rq_features; 20842 as_features.pNext = &rq_features;
17827 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features}; 20843 VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features};
@@ -17857,11 +20873,22 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
17857 // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER). 20873 // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER).
17858 enable_mesh.meshShaderQueries = info.mesh_shader_queries ? VK_TRUE : VK_FALSE; 20874 enable_mesh.meshShaderQueries = info.mesh_shader_queries ? VK_TRUE : VK_FALSE;
17859 20875
20876 // D3D-302: real SO_STATISTICS queries need transformFeedback; geometryStreams is only requested when the device
20877 // already offers it, so the enable chain matches vk_pipeline_check's (a driver keys the pipeline cache on it).
20878 VkPhysicalDeviceTransformFeedbackFeaturesEXT enable_transform_feedback{
20879 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT};
20880 enable_transform_feedback.transformFeedback = VK_TRUE;
20881 enable_transform_feedback.geometryStreams = info.transform_feedback_geometry_streams ? VK_TRUE : VK_FALSE;
20882
17860 void* ext_chain = nullptr; 20883 void* ext_chain = nullptr;
17861 if (info.mesh_shader) { 20884 if (info.mesh_shader) {
17862 enable_mesh.pNext = ext_chain; 20885 enable_mesh.pNext = ext_chain;
17863 ext_chain = &enable_mesh; 20886 ext_chain = &enable_mesh;
17864 } 20887 }
20888 if (info.transform_feedback) {
20889 enable_transform_feedback.pNext = ext_chain;
20890 ext_chain = &enable_transform_feedback;
20891 }
17865 if (info.ray_tracing) { 20892 if (info.ray_tracing) {
17866 enable_rq.pNext = ext_chain; 20893 enable_rq.pNext = ext_chain;
17867 enable_as.pNext = &enable_rq; 20894 enable_as.pNext = &enable_rq;
@@ -18192,6 +21219,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
18192 enable.logicOp = chosen_features.logicOp; 21219 enable.logicOp = chosen_features.logicOp;
18193 enable.depthClamp = chosen_features.depthClamp; 21220 enable.depthClamp = chosen_features.depthClamp;
18194 enable.multiViewport = chosen_features.multiViewport; 21221 enable.multiViewport = chosen_features.multiViewport;
21222 enable.depthBounds = chosen_features.depthBounds; // DEPTH_STENCIL1/2 DepthBoundsTestEnable, OMSetDepthBounds
18195 enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) 21223 enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus)
18196 // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of 21224 // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of
18197 // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, formatless image 21225 // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, formatless image
@@ -18332,6 +21360,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
18332 v13.add_extensions(device_extensions); 21360 v13.add_extensions(device_extensions);
18333 if (info.depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); 21361 if (info.depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME);
18334 info.pipeline_creation_feedback = v13.core || has_device_extension(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); 21362 info.pipeline_creation_feedback = v13.core || has_device_extension(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME);
21363 info.pipeline_cache_control = v13.core && v13.pipeline_creation_cache_control;
18335 if (trace_pipeline_compile() && !v13.core && info.pipeline_creation_feedback) 21364 if (trace_pipeline_compile() && !v13.core && info.pipeline_creation_feedback)
18336 device_extensions.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); 21365 device_extensions.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME);
18337 if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); 21366 if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME);
@@ -18364,6 +21393,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
18364 if (has_swapchain && instance_has_surface) device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); 21393 if (has_swapchain && instance_has_surface) device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
18365 if (swapchain_m1_name) device_extensions.push_back(swapchain_m1_name); 21394 if (swapchain_m1_name) device_extensions.push_back(swapchain_m1_name);
18366 if (info.mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); 21395 if (info.mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME);
21396 if (info.transform_feedback) device_extensions.push_back(VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME);
18367 if (info.ray_tracing) { 21397 if (info.ray_tracing) {
18368 device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); 21398 device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME);
18369 device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); 21399 device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME);
@@ -18374,18 +21404,28 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
18374 if (info.custom_border_color) device_extensions.push_back(custom_border_name); 21404 if (info.custom_border_color) device_extensions.push_back(custom_border_name);
18375 if (info.null_descriptor || info.robust_index_view) device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME); 21405 if (info.null_descriptor || info.robust_index_view) device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME);
18376 if (info.host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); 21406 if (info.host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME);
21407 // Optional: VK_EXT_memory_budget gives the GPU memory in use and the budget (vulkan_vram_budget, the title HUD).
21408 info.memory_budget = has_device_extension(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME);
21409 if (info.memory_budget) device_extensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME);
18377 leonida::DeviceFaultFeatures fault_features; 21410 leonida::DeviceFaultFeatures fault_features;
18378 const bool aftermath = leonida::aftermath::enable(); // already on, before the instance: see above 21411 const bool aftermath = leonida::aftermath::enable(); // already on, before the instance: see above
18379 char device_fault[2]{}; 21412 char device_fault[2]{};
21413 // LEONIDA_DEVICE_FAULT=1: fault info, checkpoints and NVIDIA's diagnostics config. =2: fault info and checkpoints
21414 // only — the diagnostics config compiles pipelines with debug info under other cache keys, so =2 keeps the warmed
21415 // pipeline journal usable for a boot that only wants the fault report.
18380 if (GetEnvironmentVariableA("LEONIDA_DEVICE_FAULT", device_fault, sizeof(device_fault)) == 1 && 21416 if (GetEnvironmentVariableA("LEONIDA_DEVICE_FAULT", device_fault, sizeof(device_fault)) == 1 &&
18381 device_fault[0] == '1') { 21417 (device_fault[0] == '1' || device_fault[0] == '2')) {
18382 info.device_fault_diagnostics = true; 21418 info.device_fault_diagnostics = true;
21419 const bool with_config = device_fault[0] == '1';
21420 // LEONIDA_DEVICE_MARKERS=1: also VK_AMD_buffer_marker, for the AMD breadcrumbs (vulkan_device_markers.h).
18383 const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, 21421 const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions,
18384 device_extensions, device_info, 21422 device_extensions, device_info,
18385 {true, true, leonida::aftermath::extra_config_flags()}); 21423 {true, with_config, leonida::aftermath::extra_config_flags(),
21424 leonida::device_markers_requested()});
18386 info.device_fault_info = fault.fault; 21425 info.device_fault_info = fault.fault;
18387 info.device_checkpoints = fault.checkpoints; 21426 info.device_checkpoints = fault.checkpoints;
18388 info.device_diagnostics_config = fault.diagnostics_config; 21427 info.device_diagnostics_config = fault.diagnostics_config;
21428 info.device_markers = fault.markers;
18389 } else if (aftermath) { 21429 } else if (aftermath) {
18390 // The diagnostics config alone: shader debug info, resource tracking and automatic checkpoints in the dump. 21430 // The diagnostics config alone: shader debug info, resource tracking and automatic checkpoints in the dump.
18391 const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions, 21431 const auto fault = fault_features.enable(info.physical, vkGetPhysicalDeviceFeatures2, extensions,
@@ -18393,6 +21433,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
18393 {false, true, leonida::aftermath::extra_config_flags()}); 21433 {false, true, leonida::aftermath::extra_config_flags()});
18394 info.device_diagnostics_config = fault.diagnostics_config; 21434 info.device_diagnostics_config = fault.diagnostics_config;
18395 } 21435 }
21436 if (leonida::device_markers_requested() && !info.device_fault_diagnostics)
21437 std::fprintf(stderr, "[rt] device-markers: unavailable: LEONIDA_DEVICE_MARKERS=1 needs LEONIDA_DEVICE_FAULT=1 "
21438 "or 2\n");
18396 if (aftermath && !info.device_diagnostics_config) 21439 if (aftermath && !info.device_diagnostics_config)
18397 std::fprintf(stderr, "[rt] aftermath: VK_NV_device_diagnostics_config unavailable; the dump has no shader " 21440 std::fprintf(stderr, "[rt] aftermath: VK_NV_device_diagnostics_config unavailable; the dump has no shader "
18398 "debug info, resource tracking or checkpoints\n"); 21441 "debug info, resource tracking or checkpoints\n");
@@ -18449,6 +21492,532 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
18449 return hand_out(device, riid, out); 21492 return hand_out(device, riid, out);
18450} 21493}
18451 21494
21495// A Vulkan device made as `gta6rt --run` makes it, for building the library's compute pipelines with no title
21496// (--precompile-pipelines, --compile-server), with the two layouts create_compute makes.
21497class BuildHost {
21498public:
21499 explicit BuildHost(const char* tag) : tag_(tag) {}
21500 BuildHost(const BuildHost&) = delete;
21501 BuildHost& operator=(const BuildHost&) = delete;
21502 ~BuildHost() {
21503 if (!d3d_) return;
21504 if (device_) {
21505 auto& vk = device_->context->vk;
21506 if (plain_) vk.vkDestroyPipelineLayout(device_->info.device, plain_, nullptr);
21507 if (with_set0_) vk.vkDestroyPipelineLayout(device_->info.device, with_set0_, nullptr);
21508 }
21509 d3d_->Release();
21510 }
21511
21512 bool open() {
21513 // The GPU address arena holds nothing here and does not change a pipeline: 64 MB, not a title's 2 GB.
21514 _putenv_s("LEONIDA_ARENA_MB", "64");
21515 compile_helper::build_host = true;
21516 if (FAILED(create_vulkan_device_standalone(__uuidof(ID3D12Device), reinterpret_cast<void**>(&d3d_),
21517 QueueTestSettings::ignore)) || !d3d_) {
21518 d3d_ = nullptr;
21519 std::fprintf(stderr, "%s the Vulkan device could not be created\n", tag_);
21520 return false;
21521 }
21522 Device* device = Device::from<Device>(d3d_);
21523 if (!device) return false;
21524 device_ = &device->build_state();
21525 DeviceState& state = *device_;
21526 library_ = state.library();
21527 if (!library_) {
21528 std::fprintf(stderr, "%s no translated shader library (LEONIDA_SHADERS)\n", tag_);
21529 return false;
21530 }
21531 if (pipeline_journal_dir().empty())
21532 std::fprintf(stderr, "%s the pipeline journal is off (LEONIDA_PIPELINE_JOURNAL=0 or "
21533 "LEONIDA_PIPELINE_CACHE_BYTES=0): only the driver's own cache is filled\n", tag_);
21534 state.pipeline_cache(); // the shared cache and the journal's upkeep, as at a title's first pipeline
21535 // Every pipeline goes into a journal file: one found in the shared cache would not be.
21536 state.journal_ask_shared = false;
21537 auto& vk = state.context->vk;
21538 const VkDevice dev = state.info.device;
21539 if (state.info.max_push_constants_size && state.info.max_push_constants_size < sizeof(leonida::ShaderUserData)) {
21540 std::fprintf(stderr, "%s maxPushConstantsSize %u is under the shaders' %zu bytes: the runtime builds no "
21541 "compute pipeline on this device\n",
21542 tag_, state.info.max_push_constants_size, sizeof(leonida::ShaderUserData));
21543 return false;
21544 }
21545 const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)};
21546 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
21547 layout_info.pushConstantRangeCount = 1;
21548 layout_info.pPushConstantRanges = &push;
21549 if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &plain_) != VK_SUCCESS) return false;
21550 if (state.bindless) {
21551 const VkDescriptorSetLayout set0 = state.bindless->layout();
21552 layout_info.setLayoutCount = 1;
21553 layout_info.pSetLayouts = &set0;
21554 if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &with_set0_) != VK_SUCCESS)
21555 with_set0_ = VK_NULL_HANDLE;
21556 }
21557 if (const auto get_props = reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>(
21558 state.info.get_instance_proc
21559 ? state.info.get_instance_proc(state.info.instance, "vkGetPhysicalDeviceProperties")
21560 : nullptr)) {
21561 VkPhysicalDeviceProperties props{};
21562 get_props(state.info.physical, &props);
21563 max_shared_ = props.limits.maxComputeSharedMemorySize;
21564 }
21565 return true;
21566 }
21567
21568 DeviceState& state() { return *device_; }
21569 const leonida::ShaderLibrary* library() const { return library_; }
21570
21571 // Why create_compute would refuse the entry, or null.
21572 const char* unbuildable(const leonida::ShaderEntry& entry, std::size_t bytes) const {
21573 if (!bytes) return "no .spv";
21574 if (skip_compute(entry.name)) return "LEONIDA_SKIP_COMPUTE";
21575 if (entry.binding_count && !with_set0_) return "set-0 bindings and no bindless set";
21576 if (entry.lds_bytes && max_shared_ && entry.lds_bytes > max_shared_) return "workgroup memory over the limit";
21577 return nullptr;
21578 }
21579
21580 ComputeBuild build(const leonida::ShaderEntry& entry, const ComputeBuildOptions& options) {
21581 const leonida::SubgroupRequest subgroup = leonida::decide_subgroup_size(entry, device_->info.subgroup);
21582 return build_compute_pipeline(*device_, entry, entry.binding_count ? with_set0_ : plain_, subgroup, options);
21583 }
21584
21585 void destroy(VkPipeline pipeline) {
21586 if (pipeline) device_->context->vk.vkDestroyPipeline(device_->info.device, pipeline, nullptr);
21587 }
21588
21589private:
21590 const char* tag_;
21591 ID3D12Device* d3d_ = nullptr;
21592 DeviceState* device_ = nullptr;
21593 const leonida::ShaderLibrary* library_ = nullptr;
21594 VkPipelineLayout plain_ = VK_NULL_HANDLE, with_set0_ = VK_NULL_HANDLE;
21595 std::uint32_t max_shared_ = 0;
21596};
21597
21598// gta6rt --precompile-pipelines (d3d12_precompile.h).
21599int precompile_compute_pipelines(const PrecompileOptions& options) {
21600 using Clock = std::chrono::steady_clock;
21601 const auto began = Clock::now();
21602 BuildHost host("[precompile]");
21603 if (!host.open()) return 1;
21604 const leonida::ShaderLibrary* library = host.library();
21605
21606 // What to build: every compute entry the runtime could create a pipeline for.
21607 struct Job {
21608 const leonida::ShaderEntry* entry;
21609 std::size_t bytes;
21610 };
21611 std::vector<Job> jobs;
21612 std::size_t not_buildable = 0, filtered = 0;
21613 for (const leonida::ShaderEntry* entry : library->stage_entries("cs")) {
21614 if (!options.filters.empty() &&
21615 std::none_of(options.filters.begin(), options.filters.end(),
21616 [&](const std::string& part) { return entry->name.find(part) != std::string::npos; })) {
21617 ++filtered;
21618 continue;
21619 }
21620 const std::size_t bytes = library->spirv_bytes(*entry);
21621 if ((options.min_bytes && bytes < options.min_bytes) || (options.max_bytes && bytes > options.max_bytes)) {
21622 ++filtered;
21623 continue;
21624 }
21625 if (const char* why = host.unbuildable(*entry, bytes)) {
21626 ++not_buildable;
21627 std::fprintf(stderr, "[precompile] %s: not built (%s)\n", entry->name.c_str(), why);
21628 continue;
21629 }
21630 jobs.push_back({entry, bytes});
21631 }
21632 std::stable_sort(jobs.begin(), jobs.end(), [&](const Job& a, const Job& b) {
21633 return options.smallest_first ? a.bytes < b.bytes : a.bytes > b.bytes;
21634 });
21635 if (options.limit && jobs.size() > options.limit) jobs.resize(options.limit);
21636 std::uint64_t total_bytes = 0;
21637 for (const Job& job : jobs) total_bytes += job.bytes;
21638 const unsigned threads = (std::max)(1u, options.threads);
21639 const unsigned big_threads = options.big_threads ? (std::min)(options.big_threads, threads) : threads;
21640 std::fprintf(stderr, "[precompile] %zu compute entries to build (%.1f MB of SPIR-V; %zu filtered out, %zu not "
21641 "buildable), %s first, %u thread(s), at most %u on modules over %zu bytes; journal %ls\n",
21642 jobs.size(), double(total_bytes) / 1e6, filtered, not_buildable,
21643 options.smallest_first ? "smallest" : "largest", threads, big_threads, options.big_bytes,
21644 pipeline_journal_dir().c_str());
21645 if (options.dry_run) {
21646 for (const Job& job : jobs) std::printf("%zu %s\n", job.bytes, job.entry->name.c_str());
21647 return 0;
21648 }
21649
21650 std::atomic<std::size_t> next{0};
21651 std::mutex progress_mutex;
21652 std::size_t done = 0, compiled = 0, skipped = 0, hits = 0, failed = 0;
21653 std::uint64_t done_bytes = 0;
21654 std::mutex big_mutex;
21655 std::condition_variable big_free;
21656 unsigned big_running = 0;
21657 auto worker = [&] {
21658 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
21659 for (;;) {
21660 const std::size_t i = next.fetch_add(1);
21661 if (i >= jobs.size()) return;
21662 const Job& job = jobs[i];
21663 const bool big = job.bytes > options.big_bytes;
21664 if (big) {
21665 std::unique_lock lock(big_mutex);
21666 big_free.wait(lock, [&] { return big_running < big_threads; });
21667 ++big_running;
21668 }
21669 ComputeBuildOptions build_options;
21670 build_options.trigger = "precompile";
21671 build_options.serialize_big = false; // nothing else is building; big_threads bounds them instead
21672 build_options.skip_journaled = !options.rebuild;
21673 build_options.use_helper = options.via_helper;
21674 build_options.mark_building = !options.via_helper; // an entry another process is compiling is left to it
21675 ComputeBuild build;
21676 try {
21677 build = host.build(*job.entry, build_options);
21678 } catch (const std::exception& e) {
21679 std::fprintf(stderr, "[precompile] %s: %s\n", job.entry->name.c_str(), e.what());
21680 }
21681 host.destroy(build.pipeline);
21682 if (big) {
21683 std::lock_guard lock(big_mutex);
21684 --big_running;
21685 big_free.notify_one();
21686 }
21687 std::lock_guard lock(progress_mutex);
21688 ++done;
21689 done_bytes += job.bytes;
21690 const char* what = "failed";
21691 if (build.skipped) ++skipped, what = "journaled already";
21692 else if (build.busy) ++skipped, what = "being built by another process";
21693 else if (build.result != VK_SUCCESS || (!build.pipeline && !build.skipped)) ++failed;
21694 else if (build.journal_hit || build.from_shared) ++hits, what = "found in a cache";
21695 else ++compiled, what = build.journaled ? "compiled and journaled" : "compiled (not journaled)";
21696 const double elapsed = std::chrono::duration<double>(Clock::now() - began).count();
21697 const double eta = done_bytes ? elapsed / double(done_bytes) * double(total_bytes - done_bytes) : 0.0;
21698 // Skips are not logged one by one (a resumed run skips thousands); every 100th is, with the counts.
21699 if (!build.skipped || done % 100 == 0 || done == jobs.size())
21700 std::fprintf(stderr, "[precompile] %zu/%zu %s (%zu B): %s in %.1f s (VkResult %d) | %zu compiled, %zu "
21701 "from a cache, %zu skipped, %zu failed; %.0f s elapsed, ~%.0f s left by size\n",
21702 done, jobs.size(), job.entry->name.c_str(), job.bytes, what, double(build.ms) / 1000.0,
21703 int(build.result), compiled, hits, skipped, failed, elapsed, eta);
21704 }
21705 };
21706 std::vector<std::thread> pool;
21707 for (unsigned t = 0; t < threads; ++t) pool.emplace_back(worker);
21708 for (std::thread& t : pool) t.join();
21709 std::fprintf(stderr, "[precompile] done: %zu compiled, %zu from a cache, %zu journaled already, %zu failed, %zu "
21710 "not buildable, in %.0f s\n", compiled, hits, skipped, failed, not_buildable,
21711 std::chrono::duration<double>(Clock::now() - began).count());
21712 return failed ? 2 : 0;
21713}
21714
21715// What a compute pipeline's journal name depends on besides its module: a name remembered for a module is good for
21716// another run while this is unchanged (compile_server's index).
21717std::uint64_t journal_name_context(DeviceState& state) {
21718 leonida::pipeline_journal::Hasher hash;
21719 hash.text("journal-name-context");
21720 hash.value(std::uint32_t(sizeof(leonida::ShaderUserData)));
21721 const leonida::SubgroupSizeCaps& sub = state.info.subgroup;
21722 hash.value(std::uint32_t(sub.subgroup_size_control));
21723 hash.value(std::uint32_t(sub.compute_full_subgroups));
21724 hash.value(sub.min_size);
21725 hash.value(sub.max_size);
21726 hash.value(sub.default_size);
21727 hash.value(std::uint32_t(sub.required_stages));
21728 hash.value(std::uint32_t(state.info.device_diagnostics_config));
21729 if (state.info.device_diagnostics_config) hash.value(std::uint32_t(leonida::aftermath::extra_config_flags()));
21730 if (state.bindless) hash_bindless_layout(hash, state.bindless->features());
21731 return hash.digest();
21732}
21733
21734// gta6rt --compile-server (d3d12_compile_helper.h): builds what the games using this journal ask for, most urgent
21735// first, and with nothing asked fills the rest of the library, smallest module first, at idle priority.
21736int compile_server(const CompileServerOptions& options) {
21737 namespace helper = compile_helper;
21738 namespace journal = leonida::pipeline_journal;
21739 const std::filesystem::path& dir = pipeline_journal_dir();
21740 if (dir.empty()) {
21741 std::fprintf(stderr, "[compile-server] the pipeline journal is off: nothing to serve\n");
21742 return 1;
21743 }
21744 const auto requests = helper::requests_dir(dir);
21745 std::error_code ec;
21746 std::filesystem::create_directories(requests, ec);
21747 // One helper per journal: a second (two games, or one started by hand) leaves the requests to the first.
21748 journal::Hasher dir_hash;
21749 dir_hash.text(dir.string().c_str());
21750 const std::wstring mutex_name = L"Local\\leonida-compile-server-" + std::to_wstring(dir_hash.digest());
21751 const HANDLE single = CreateMutexW(nullptr, TRUE, mutex_name.c_str());
21752 if (!single || GetLastError() == ERROR_ALREADY_EXISTS) {
21753 std::fprintf(stderr, "[compile-server] another helper serves %ls\n", dir.c_str());
21754 return 0;
21755 }
21756 // It ends with the game that started it, at once: whatever it was building is in no file yet, and a file is
21757 // written whole or not at all. A .building marker it leaves names a dead process and is taken over.
21758 if (options.parent_pid) {
21759 const HANDLE parent = OpenProcess(SYNCHRONIZE, FALSE, options.parent_pid);
21760 if (!parent) {
21761 std::fprintf(stderr, "[compile-server] process %lu is gone\n", options.parent_pid);
21762 return 0;
21763 }
21764 std::thread([parent] {
21765 WaitForSingleObject(parent, INFINITE);
21766 TerminateProcess(GetCurrentProcess(), 0);
21767 }).detach();
21768 }
21769 BuildHost host("[compile-server]");
21770 if (!host.open()) return 1;
21771 const leonida::ShaderLibrary* library = host.library();
21772 const std::vector<const leonida::ShaderEntry*> entries = library->stage_entries("cs");
21773 std::map<std::string, const leonida::ShaderEntry*> by_name;
21774 for (const leonida::ShaderEntry* entry : entries) by_name.emplace(entry->name, entry);
21775 const unsigned threads = (std::max)(1u, options.threads);
21776 const unsigned idle_threads = (std::min)(options.idle_threads, threads - 1); // one is always free for a request
21777 std::fprintf(stderr, "[compile-server] serving %ls: %u thread(s) for requests, %u of them filling the library "
21778 "when nothing is asked, %zu compute entries\n", requests.c_str(), threads, idle_threads,
21779 entries.size());
21780
21781 std::mutex mutex;
21782 std::condition_variable wake;
21783 std::vector<helper::Request> pending; // the last listing, most urgent first
21784 std::set<std::string> busy; // stems being built here
21785 std::map<std::string, std::chrono::steady_clock::time_point> elsewhere; // stems another process is building
21786 bool stop = false;
21787 std::atomic<unsigned> requests_done{0}, filled{0};
21788
21789 // A request this helper can take: listed, not being built here, not one another process was building a moment ago.
21790 auto take_locked = [&](helper::Request& out) {
21791 const auto now = std::chrono::steady_clock::now();
21792 for (const helper::Request& request : pending) {
21793 if (busy.count(request.stem)) continue;
21794 if (const auto it = elsewhere.find(request.stem); it != elsewhere.end() && now - it->second < std::chrono::seconds(5))
21795 continue;
21796 busy.insert(request.stem);
21797 out = request;
21798 return true;
21799 }
21800 return false;
21801 };
21802 auto build_entry = [&](const leonida::ShaderEntry& entry, const char* trigger) {
21803 ComputeBuildOptions build_options;
21804 build_options.trigger = trigger;
21805 build_options.serialize_big = false;
21806 build_options.skip_journaled = true;
21807 build_options.use_helper = false;
21808 build_options.mark_building = true;
21809 ComputeBuild build = host.build(entry, build_options);
21810 host.destroy(build.pipeline);
21811 build.pipeline = VK_NULL_HANDLE;
21812 return build;
21813 };
21814 auto serve = [&] { // normal priority: a title waits for these
21815 for (;;) {
21816 helper::Request request;
21817 {
21818 std::unique_lock lock(mutex);
21819 wake.wait_for(lock, std::chrono::milliseconds(100), [&] { return stop || take_locked(request); });
21820 if (stop) return;
21821 if (request.stem.empty()) continue;
21822 }
21823 std::string failure;
21824 bool leave = false; // another process is building it: its file answers the request
21825 const auto it = by_name.find(request.name);
21826 const leonida::ShaderEntry* entry = it == by_name.end() ? nullptr : it->second;
21827 const std::size_t bytes = entry ? library->spirv_bytes(*entry) : 0;
21828 if (!entry) failure = "no compute entry of that name in this library";
21829 else if (const char* why = host.unbuildable(*entry, bytes)) failure = why;
21830 // LOCAL FIX (compile helper: the journal name was checked after the build): the name is hashed from the
21831 // module and this device's environment, which costs no driver call. A request from a game whose environment
21832 // differs is answered before a compile is spent on a file that game never reads; the build below would only
21833 // have found the same mismatch.
21834 if (failure.empty()) {
21835 ComputeBuildOptions key_options;
21836 key_options.trigger = "compile-server";
21837 key_options.key_only = true;
21838 key_options.use_helper = false;
21839 const std::filesystem::path key_path = host.build(*entry, key_options).journal_path;
21840 if (!key_path.empty() && key_path.stem().string() != request.stem)
21841 failure = "its journal name here is " + key_path.stem().string() +
21842 ": the helper's environment differs from the game's";
21843 }
21844 if (failure.empty()) {
21845 ComputeBuild build;
21846 try {
21847 build = build_entry(*entry, "compile-server");
21848 } catch (const std::exception& e) {
21849 failure = e.what();
21850 }
21851 if (failure.empty()) {
21852 if (build.busy)
21853 leave = true;
21854 else if (!build.skipped && (build.result != VK_SUCCESS || !(build.journaled || build.journal_hit)))
21855 failure = "not built or not journaled (VkResult " + std::to_string(int(build.result)) + ")";
21856 else if (!leonida::pipeline_journal::entry_usable(build.journal_path, host.state().pso_identity))
21857 failure = "requested writable journal file is missing or incompatible";
21858 else
21859 std::fprintf(stderr, "[compile-server] %s (%zu B, priority %llu): %s in %.1f s\n",
21860 request.name.c_str(), bytes, static_cast<unsigned long long>(request.priority),
21861 build.skipped ? "journaled already" : "built and journaled",
21862 double(build.ms) / 1000.0);
21863 }
21864 }
21865 std::error_code ignored;
21866 // LOCAL FIX (compile helper: a .failed left with its .request listed): the .req goes first. A request with
21867 // no .req and no .failed is one the game reads as answered, so it builds the pipeline itself instead of
21868 // waiting for a file that is not coming (Client::state).
21869 if (!leave) std::filesystem::remove(requests / (request.stem + ".req"), ignored);
21870 if (!failure.empty()) {
21871 helper::write_line(requests / (request.stem + ".failed"), failure);
21872 std::fprintf(stderr, "[compile-server] %s: %s\n", request.name.c_str(), failure.c_str());
21873 }
21874 if (!leave) ++requests_done;
21875 std::lock_guard lock(mutex);
21876 busy.erase(request.stem);
21877 if (leave) elsewhere[request.stem] = std::chrono::steady_clock::now();
21878 }
21879 };
21880
21881 // The rest of the library, smallest module first, while nothing is asked. The journal names of modules looked at
21882 // before are kept in requests/names.idx (with each module's size and time, and what the names depend on), so a
21883 // later helper finds what is missing without reading every module again.
21884 struct Indexed {
21885 std::uint64_t size = 0;
21886 long long mtime = 0;
21887 std::string stem;
21888 };
21889 std::map<std::string, Indexed> index;
21890 std::mutex index_mutex;
21891 const auto index_file = requests / "names.idx";
21892 const std::string signature = "v1 " + std::to_string(journal_name_context(host.state()));
21893 {
21894 std::ifstream in(index_file, std::ios::binary);
21895 std::string line;
21896 if (std::getline(in, line) && line == signature) {
21897 while (std::getline(in, line)) {
21898 const auto t1 = line.find('\t'), t2 = line.find('\t', t1 + 1), t3 = line.find('\t', t2 + 1);
21899 if (t3 == std::string::npos) continue;
21900 index[line.substr(0, t1)] = {std::strtoull(line.c_str() + t1 + 1, nullptr, 10),
21901 std::strtoll(line.c_str() + t2 + 1, nullptr, 10), line.substr(t3 + 1)};
21902 }
21903 }
21904 }
21905 auto save_index = [&] {
21906 std::string text = signature + "\n";
21907 std::lock_guard lock(index_mutex);
21908 for (const auto& [name, item] : index)
21909 text += name + "\t" + std::to_string(item.size) + "\t" + std::to_string(item.mtime) + "\t" + item.stem + "\n";
21910 journal::write_entry(index_file, text.data(), text.size());
21911 };
21912 std::vector<const leonida::ShaderEntry*> fill_order = entries;
21913 std::vector<std::size_t> fill_bytes(fill_order.size());
21914 {
21915 std::vector<std::pair<std::size_t, const leonida::ShaderEntry*>> sized;
21916 for (const leonida::ShaderEntry* entry : entries) sized.emplace_back(library->spirv_bytes(*entry), entry);
21917 std::stable_sort(sized.begin(), sized.end(), [](const auto& x, const auto& y) { return x.first < y.first; });
21918 for (std::size_t i = 0; i < sized.size(); ++i) {
21919 fill_order[i] = sized[i].second;
21920 fill_bytes[i] = sized[i].first;
21921 }
21922 }
21923 std::atomic<std::size_t> fill_next{0};
21924 std::atomic<unsigned> fill_unsaved{0};
21925 auto fill = [&] {
21926 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE);
21927 for (;;) {
21928 {
21929 // Requests first: wait while one is listed that this helper could take.
21930 std::unique_lock lock(mutex);
21931 wake.wait_for(lock, std::chrono::milliseconds(200), [&] {
21932 if (stop) return true;
21933 for (const helper::Request& request : pending)
21934 if (!busy.count(request.stem)) return false;
21935 return true;
21936 });
21937 if (stop) return;
21938 bool asked = false;
21939 for (const helper::Request& request : pending)
21940 if (!busy.count(request.stem)) asked = true;
21941 if (asked) continue;
21942 }
21943 const std::size_t i = fill_next.fetch_add(1);
21944 if (i >= fill_order.size()) {
21945 if (i == fill_order.size()) {
21946 save_index();
21947 std::fprintf(stderr, "[compile-server] the library is in the journal (%u built while idle)\n",
21948 filled.load());
21949 }
21950 return;
21951 }
21952 const leonida::ShaderEntry& entry = *fill_order[i];
21953 if (host.unbuildable(entry, fill_bytes[i])) continue;
21954 std::error_code stat;
21955 const auto spv = library->spirv_file(entry);
21956 const long long mtime = static_cast<long long>(std::filesystem::last_write_time(spv, stat).time_since_epoch().count());
21957 std::filesystem::path path;
21958 {
21959 std::lock_guard lock(index_mutex);
21960 const auto it = index.find(entry.name);
21961 if (it != index.end() && it->second.size == fill_bytes[i] && it->second.mtime == mtime)
21962 path = dir / (it->second.stem + ".bin");
21963 }
21964 if (path.empty()) {
21965 ComputeBuildOptions key_options;
21966 key_options.key_only = true;
21967 key_options.use_helper = false;
21968 path = host.build(entry, key_options).journal_path;
21969 if (path.empty()) continue;
21970 {
21971 std::lock_guard lock(index_mutex);
21972 index[entry.name] = {fill_bytes[i], mtime, path.stem().string()};
21973 }
21974 if (++fill_unsaved % 200 == 0) save_index();
21975 }
21976 if (journal::entry_usable(path, host.state().pso_identity)) continue;
21977 ComputeBuild build;
21978 try {
21979 build = build_entry(entry, "idle-fill");
21980 } catch (const std::exception& e) {
21981 std::fprintf(stderr, "[compile-server] %s: %s\n", entry.name.c_str(), e.what());
21982 continue;
21983 }
21984 if (!build.skipped && !build.busy && build.result == VK_SUCCESS && build.journaled) {
21985 ++filled;
21986 std::fprintf(stderr, "[compile-server] idle: %s (%zu B) built and journaled in %.1f s (%zu/%zu)\n",
21987 entry.name.c_str(), fill_bytes[i], double(build.ms) / 1000.0, i + 1, fill_order.size());
21988 }
21989 }
21990 };
21991
21992 std::vector<std::thread> pool;
21993 for (unsigned t = 0; t < threads - idle_threads; ++t) pool.emplace_back(serve);
21994 for (unsigned t = 0; t < idle_threads; ++t) pool.emplace_back(fill);
21995 auto quiet_since = std::chrono::steady_clock::now();
21996 for (;;) {
21997 auto listing = helper::list_requests(requests);
21998 {
21999 std::lock_guard lock(mutex);
22000 pending = std::move(listing);
22001 if (!pending.empty() || !busy.empty()) quiet_since = std::chrono::steady_clock::now();
22002 }
22003 wake.notify_all();
22004 if (options.idle_exit_s &&
22005 std::chrono::steady_clock::now() - quiet_since > std::chrono::seconds(options.idle_exit_s))
22006 break;
22007 std::this_thread::sleep_for(std::chrono::milliseconds(50));
22008 }
22009 {
22010 std::lock_guard lock(mutex);
22011 stop = true;
22012 }
22013 wake.notify_all();
22014 for (std::thread& t : pool) t.join();
22015 save_index();
22016 std::fprintf(stderr, "[compile-server] nothing asked for %u s: done (%u requests, %u built while idle)\n",
22017 options.idle_exit_s, requests_done.load(), filled.load());
22018 return 0;
22019}
22020
18452bool has_global_realtime_privilege() { 22021bool has_global_realtime_privilege() {
18453 const int override_state = g_global_realtime_privilege_override.load(std::memory_order_relaxed); 22022 const int override_state = g_global_realtime_privilege_override.load(std::memory_order_relaxed);
18454 if (override_state >= 0) return override_state != 0; 22023 if (override_state >= 0) return override_state != 0;
@@ -18496,6 +22065,38 @@ HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIP
18496 return d->create_console_descriptor_heap(desc, console_address, console_size, riid, out); 22065 return d->create_console_descriptor_heap(desc, console_address, console_size, riid, out);
18497} 22066}
18498 22067
22068UnboundTsharpStats unbound_tsharp_stats() {
22069 return unbound_tsharp_tracker().stats();
22070}
22071
22072void reset_unbound_tsharp_stats() {
22073 unbound_tsharp_tracker().reset();
22074}
22075
22076void note_refused_tsharp_for_test(std::uint64_t heap_va, std::size_t offset,
22077 const std::array<std::uint32_t, 8>& words, const char* why) {
22078 leonida::gfx10::ImageWords w;
22079 std::memcpy(w.data(), words.data(), sizeof(w));
22080 unbound_tsharp_tracker().note(heap_va, offset, w, why);
22081}
22082
22083TitleImage test_bind_title_image(ID3D12Device* device, const std::array<std::uint32_t, 8>& words,
22084 const char** why) {
22085 if (!device) return TitleImage::not_tsharp;
22086 ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device);
22087 Device* d = Device::from<Device>(real ? real : device);
22088 if (!d) return TitleImage::not_tsharp;
22089 leonida::gfx10::ImageWords w;
22090 std::memcpy(w.data(), words.data(), sizeof(w));
22091 return bind_title_image(d->state(), w, why);
22092}
22093
22094std::uint64_t resource_image_address(ID3D12Resource* resource) {
22095 if (!resource) return 0;
22096 const Resource* r = Resource::from<Resource>(resource);
22097 return r ? r->image_address() : 0;
22098}
22099
18499std::filesystem::path configured_shader_directory(std::string* error, const std::filesystem::path& config) { 22100std::filesystem::path configured_shader_directory(std::string* error, const std::filesystem::path& config) {
18500 return leonida::shader_paths::configured(error, config); 22101 return leonida::shader_paths::configured(error, config);
18501} 22102}
diff --git a/runtime/shims/d3d12_xs_alloc_size.h b/runtime/shims/d3d12_xs_alloc_size.h
index 7f1948ecc..6ad3d02f8 100644
--- a/runtime/shims/d3d12_xs_alloc_size.h
+++ b/runtime/shims/d3d12_xs_alloc_size.h
@@ -175,7 +175,7 @@ inline UINT64 console_depth_stencil_size(const D3D12_RESOURCE_DESC& desc) {
175// 175//
176// Why exact: the title keeps this size in its streaming tables and reads exactly that many bytes of the texture 176// Why exact: the title keeps this size in its streaming tables and reads exactly that many bytes of the texture
177// from its archives through DirectStorage; a compressed chunk must be read whole, and the title stops on an int3 177// from its archives through DirectStorage; a compressed chunk must be read whole, and the title stops on an int3
178// (game+0x4ffd879) when the size it was given is smaller than the chunk. Measured with a debugger at that int3: a 178// when the size it was given is smaller than the chunk. Measured with a debugger at that int3: a
179// request of 0x2000 bytes for a chunk that spans 0x4000, the PC answer for the texture being half the console's. 179// request of 0x2000 bytes for a chunk that spans 0x4000, the PC answer for the texture being half the console's.
180inline bool console_texture_layout(const D3D12_RESOURCE_DESC& desc, UINT64& size, UINT64& alignment) { 180inline bool console_texture_layout(const D3D12_RESOURCE_DESC& desc, UINT64& size, UINT64& alignment) {
181 constexpr UINT gpu_written = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | 181 constexpr UINT gpu_written = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
@@ -199,6 +199,40 @@ inline bool console_texture_layout(const D3D12_RESOURCE_DESC& desc, UINT64& size
199 return true; 199 return true;
200} 200}
201 201
202// The console's size of a texture the GPU writes through unordered access (no render-target or depth-stencil flag,
203// which have their own rules above) whose layout word names its swizzle mode: row-major (1), or 0x100 | mode. That
204// is XG's layout of it; 0 when the rule does not apply (any other description, or a mode XG's model lacks).
205// `title_layout` is the layout word as the title wrote it: the PC form of the description (pc_resource_desc) has
206// lost it.
207//
208// Why: the title also writes such a texture with the CPU, through its texture lock, at the offsets
209// and over the bytes XG's layout gives. Measured: a 32x32x36 R32_UINT 3D texture with layout 0x100 (linear) is
210// 0x48000 bytes on the console (256-byte rows, 36 slices of 8 KiB), the PC device sizes it 0x30000, the title placed
211// the next resource 0x30000 after it, and its lock clears all 0x48000 bytes - 0x18000 of them in the neighbour.
212// Like the render-target rule this only ever makes a size larger than the PC device's own answer, never smaller
213// (console_placement).
214inline UINT64 console_unordered_access_size(const D3D12_RESOURCE_DESC& desc, UINT title_layout) {
215 if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D &&
216 desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D)
217 return 0;
218 constexpr UINT targets = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
219 if (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || (desc.Flags & targets) ||
220 desc.SampleDesc.Count != 1)
221 return 0;
222 if (title_layout != 1 && (title_layout & ~0x1fu) != rt::xg_xs::kSwizzled) return 0; // XG picks the mode
223 static_assert(sizeof(rt::xg_xs::ResourceDesc) == sizeof(D3D12_RESOURCE_DESC));
224 rt::xg_xs::ResourceDesc xg{};
225 std::memcpy(&xg, &desc, sizeof(xg));
226 xg.alignment = 0;
227 xg.quality = 0;
228 xg.flags = 0;
229 xg.layout = title_layout;
230 static thread_local rt::xg_xs::Texture texture; // 7 KiB: not on a title thread's stack
231 texture = {};
232 if (!rt::xg_xs::build_texture(xg, texture) || !texture.layout.size) return 0;
233 return texture.layout.size;
234}
235
202// Rounds up to a multiple of `to`, stopping at the last multiple below 2^64 instead of wrapping (as the PC device's 236// Rounds up to a multiple of `to`, stopping at the last multiple below 2^64 instead of wrapping (as the PC device's
203// totals do). 237// totals do).
204inline UINT64 align_up_saturating(UINT64 value, UINT64 to) { 238inline UINT64 align_up_saturating(UINT64 value, UINT64 to) {
@@ -214,15 +248,22 @@ inline UINT64 align_up_saturating(UINT64 value, UINT64 to) {
214// Returns false, and writes nothing, when no description is a console render target that grows, or when the PC 248// Returns false, and writes nothing, when no description is a console render target that grows, or when the PC
215// device refuses one: the PC answer then stands. A true answer is never below what the PC device gave for the same 249// device refuses one: the PC answer then stands. A true answer is never below what the PC device gave for the same
216// descriptions laid out in that way. 250// descriptions laid out in that way.
251//
252// `title_descs` is the title's own array when `descs` is its PC form, for the layout words the PC form drops
253// (console_unordered_access_size); null when `descs` is the title's array.
217template <class PcOne> 254template <class PcOne>
218bool console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, PcOne pc_one, 255bool console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, PcOne pc_one,
219 D3D12_RESOURCE_ALLOCATION_INFO& total, D3D12_RESOURCE_ALLOCATION_INFO1* each) { 256 D3D12_RESOURCE_ALLOCATION_INFO& total, D3D12_RESOURCE_ALLOCATION_INFO1* each,
257 const D3D12_RESOURCE_DESC* title_descs = nullptr) {
220 if (!descs) return false; 258 if (!descs) return false;
259 const auto unordered_access = [&](UINT i) {
260 return console_unordered_access_size(descs[i], static_cast<UINT>((title_descs ? title_descs : descs)[i].Layout));
261 };
221 bool any_target = false; 262 bool any_target = false;
222 for (UINT i = 0; i < count && !any_target; ++i) { 263 for (UINT i = 0; i < count && !any_target; ++i) {
223 UINT64 xg_size = 0, xg_alignment = 0; 264 UINT64 xg_size = 0, xg_alignment = 0;
224 any_target = console_render_target_size(descs[i]) != 0 || console_depth_stencil_size(descs[i]) != 0 || 265 any_target = console_render_target_size(descs[i]) != 0 || console_depth_stencil_size(descs[i]) != 0 ||
225 console_texture_layout(descs[i], xg_size, xg_alignment); 266 console_texture_layout(descs[i], xg_size, xg_alignment) || unordered_access(i) != 0;
226 } 267 }
227 if (!any_target) return false; 268 if (!any_target) return false;
228 // Two passes when `each` is wanted: the first decides, the second writes, so a refusal or a list that does not 269 // 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
246 size = align_up_saturating(console, one.Alignment); 287 size = align_up_saturating(console, one.Alignment);
247 grows = true; 288 grows = true;
248 } 289 }
290 // A texture the title also locks and writes with the CPU takes its console layout when that is larger.
291 if (const UINT64 written = unordered_access(i); written > size) {
292 size = align_up_saturating(written, one.Alignment);
293 grows = true;
294 }
249 // A depth-stencil target takes its console size whichever way it differs (console_depth_stencil_size). 295 // A depth-stencil target takes its console size whichever way it differs (console_depth_stencil_size).
250 if (const UINT64 depth = console_depth_stencil_size(descs[i])) { 296 if (const UINT64 depth = console_depth_stencil_size(descs[i])) {
251 const UINT64 planes = align_up_saturating(depth, one.Alignment); 297 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 90dcc6113..87cc26dd3 100644
--- a/runtime/shims/d3d12_xs_device.cpp
+++ b/runtime/shims/d3d12_xs_device.cpp
@@ -32,6 +32,7 @@
32#endif 32#endif
33#include "d3d12_xs_placed_depth.h" 33#include "d3d12_xs_placed_depth.h"
34#include "d3d12_trace.h" 34#include "d3d12_trace.h"
35#include "../src/fsdraw_probe.h" // LEONIDA_FSDRAW_PROBE gates the fsdraw lines here
35#include "../src/native_pso.h" 36#include "../src/native_pso.h"
36#include "xmem.h" // rt::xmem::copy_page_mappings_fn for queue slot 31 37#include "xmem.h" // rt::xmem::copy_page_mappings_fn for queue slot 31
37#include "d3d12_xs_alloc_size.h" 38#include "d3d12_xs_alloc_size.h"
@@ -49,6 +50,7 @@
49// WindowPresenter. Other builds of this file (mock and COM tests) keep the refused-slot behaviour. 50// WindowPresenter. Other builds of this file (mock and COM tests) keep the refused-slot behaviour.
50#include "xbox_present.h" 51#include "xbox_present.h"
51#include "title_window.h" 52#include "title_window.h"
53#include "title_hud.h"
52#include "package_splash.h" 54#include "package_splash.h"
53#include "startup_trace.h" 55#include "startup_trace.h"
54#endif 56#endif
@@ -124,6 +126,14 @@ struct DeviceProxy {
124 // The console runtime layout this title was built against (docs/d3d12_xs_console_abi.md §4): the queue proxy 126 // The console runtime layout this title was built against (docs/d3d12_xs_console_abi.md §4): the queue proxy
125 // writes it on detection and every object shares it — the queue/list slot tails shift +2 under the newer one. 127 // writes it on detection and every object shares it — the queue/list slot tails shift +2 under the newer one.
126 std::atomic<unsigned char> console_layout{0}; // 0 unknown, 1 older, 2 newer 128 std::atomic<unsigned char> console_layout{0}; // 0 unknown, 1 older, 2 newer
129 // The real (translated) CPU handles that hold a render-target view the title created with no resource (device
130 // slot 20 with a null resource), for console list slot 52: on the console, clearing such a view does nothing.
131 // The real device's descriptor cannot tell (the Vulkan layer writes the same empty record for a view it could not
132 // make, and the PC runtime's handles are opaque), so the proxy keeps the mark itself. A view made there with a
133 // resource, or a descriptor copy over it, removes it.
134 std::mutex null_rtv_lock;
135 std::set<SIZE_T> null_rtvs;
136 std::atomic<std::size_t> null_rtv_count{0}; // null_rtvs.size(), read without the lock on the clear path
127 // Set by create_device_proxy: false hands real (PC-shaped) lists back from CreateCommandList for callers 137 // Set by create_device_proxy: false hands real (PC-shaped) lists back from CreateCommandList for callers
128 // compiled against the PC headers. 138 // compiled against the PC headers.
129 bool console_lists = true; 139 bool console_lists = true;
@@ -193,6 +203,10 @@ struct HeapProxy {
193 SIZE_T custom_byte_size; 203 SIZE_T custom_byte_size;
194 SIZE_T real_cpu_start; 204 SIZE_T real_cpu_start;
195 DescriptorHeapBackingFree custom_free; 205 DescriptorHeapBackingFree custom_free;
206 // An RTV heap's real CPU range, [rtv_real_start, +rtv_real_bytes): the null-view marks in it
207 // (DeviceProxy::null_rtvs) are dropped when the heap goes, so a later heap at the same address starts unmarked.
208 SIZE_T rtv_real_start = 0;
209 SIZE_T rtv_real_bytes = 0;
196}; 210};
197 211
198struct DescriptorRange { 212struct DescriptorRange {
@@ -385,6 +399,81 @@ void local_mirror_table(const DeviceProxy* device, std::uint64_t gpu_handle) {
385 } 399 }
386} 400}
387 401
402// ---- Render-target views made with no resource (DeviceProxy::null_rtvs) ----
403
404// Device slot 20 wrote an RTV at the real handle `ptr`: marked when the title passed no resource, unmarked otherwise.
405void mark_null_rtv(DeviceProxy* device, SIZE_T ptr, bool no_resource) {
406 if (!ptr || (!no_resource && device->null_rtv_count.load(std::memory_order_acquire) == 0)) return;
407 std::lock_guard lock(device->null_rtv_lock);
408 try {
409 if (no_resource)
410 device->null_rtvs.insert(ptr);
411 else
412 device->null_rtvs.erase(ptr);
413 } catch (const std::bad_alloc&) {
414 // The mark is lost: a clear of this view keeps the PC list's answer, as before the mark existed.
415 }
416 device->null_rtv_count.store(device->null_rtvs.size(), std::memory_order_release);
417}
418
419bool is_null_rtv(DeviceProxy* device, SIZE_T ptr) {
420 if (!ptr || device->null_rtv_count.load(std::memory_order_acquire) == 0) return false;
421 std::lock_guard lock(device->null_rtv_lock);
422 return device->null_rtvs.count(ptr) != 0;
423}
424
425// A descriptor copy moves the marks with the descriptors: `count` RTV descriptors from the real handle `src` to
426// `dest`, `increment` bytes apart. Caller holds null_rtv_lock.
427void copy_null_rtv_marks_locked(DeviceProxy* device, SIZE_T dest, SIZE_T src, UINT count, UINT increment) {
428 for (UINT i = 0; i < count; ++i) {
429 const SIZE_T to = dest + static_cast<SIZE_T>(i) * increment;
430 if (device->null_rtvs.count(src + static_cast<SIZE_T>(i) * increment))
431 device->null_rtvs.insert(to);
432 else
433 device->null_rtvs.erase(to);
434 }
435}
436
437// CopyDescriptors / CopyDescriptorsSimple of RTVs, after the copy, with the handles the real device got. A null
438// size array means ranges of one descriptor, as in D3D12. Nothing to do while no view is marked: a copy can only
439// move a mark, never make one.
440void copy_null_rtv_marks(DeviceProxy* device, UINT num_dest, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
441 const UINT* dest_sizes, UINT num_src, const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts,
442 const UINT* src_sizes, D3D12_DESCRIPTOR_HEAP_TYPE type) {
443 if (type != D3D12_DESCRIPTOR_HEAP_TYPE_RTV || device->null_rtv_count.load(std::memory_order_acquire) == 0) return;
444 if (!dest_starts || !src_starts) return;
445 const UINT increment = device->real->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
446 if (!increment) return;
447 std::lock_guard lock(device->null_rtv_lock);
448 try {
449 UINT d = 0, s = 0, d_used = 0, s_used = 0;
450 while (d < num_dest && s < num_src) {
451 const UINT d_size = dest_sizes ? dest_sizes[d] : 1;
452 const UINT s_size = src_sizes ? src_sizes[s] : 1;
453 if (d_used == d_size) { ++d; d_used = 0; continue; }
454 if (s_used == s_size) { ++s; s_used = 0; continue; }
455 const UINT d_left = d_size - d_used, s_left = s_size - s_used;
456 const UINT run = d_left < s_left ? d_left : s_left;
457 copy_null_rtv_marks_locked(device, dest_starts[d].ptr + static_cast<SIZE_T>(d_used) * increment,
458 src_starts[s].ptr + static_cast<SIZE_T>(s_used) * increment, run, increment);
459 d_used += run;
460 s_used += run;
461 }
462 } catch (const std::bad_alloc&) {
463 }
464 device->null_rtv_count.store(device->null_rtvs.size(), std::memory_order_release);
465}
466
467// An RTV heap was released: its real handles can name another heap's views from now on, so no mark may outlive it.
468void drop_null_rtv_marks(DeviceProxy* device, SIZE_T start, SIZE_T bytes) {
469 if (!device || !start || !bytes || device->null_rtv_count.load(std::memory_order_acquire) == 0) return;
470 const SIZE_T end = start > (std::numeric_limits<SIZE_T>::max)() - bytes ? (std::numeric_limits<SIZE_T>::max)()
471 : start + bytes;
472 std::lock_guard lock(device->null_rtv_lock);
473 device->null_rtvs.erase(device->null_rtvs.lower_bound(start), device->null_rtvs.lower_bound(end));
474 device->null_rtv_count.store(device->null_rtvs.size(), std::memory_order_release);
475}
476
388std::atomic<std::uint64_t> g_hits[kMaxSlots]; 477std::atomic<std::uint64_t> g_hits[kMaxSlots];
389std::atomic<bool> g_first[kMaxSlots]; 478std::atomic<bool> g_first[kMaxSlots];
390std::atomic<bool> g_beyond_warned[kMaxSlots]; 479std::atomic<bool> g_beyond_warned[kMaxSlots];
@@ -823,6 +912,7 @@ unsigned long heap_release(HeapProxy* self) {
823 const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; 912 const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1;
824 if (refs == 0) { 913 if (refs == 0) {
825 if (self->custom_cpu_start != 0) unregister_descriptor_range(self); 914 if (self->custom_cpu_start != 0) unregister_descriptor_range(self);
915 drop_null_rtv_marks(self->device, self->rtv_real_start, self->rtv_real_bytes);
826 void* const backing = reinterpret_cast<void*>(self->custom_cpu_start); 916 void* const backing = reinterpret_cast<void*>(self->custom_cpu_start);
827 const DescriptorHeapBackingFree free_fn = self->custom_free; 917 const DescriptorHeapBackingFree free_fn = self->custom_free;
828 ID3D12DescriptorHeap* real = self->real; 918 ID3D12DescriptorHeap* real = self->real;
@@ -1069,9 +1159,9 @@ struct FenceMirror;
1069// Queue slots that take queue_order: the ones that may put work on the queue or change page mappings. Not the debug 1159// Queue slots that take queue_order: the ones that may put work on the queue or change page mappings. Not the debug
1070// markers (SetMarker, BeginEvent, EndEvent: 11-13 in both layouts) and not slot 18, a getter in both layouts (the 1160// markers (SetMarker, BeginEvent, EndEvent: 11-13 in both layouts) and not slot 18, a getter in both layouts (the
1071// older layout's GetDesc, the newer one's GetTimestampFrequency). The title's render thread calls slot 18 every frame 1161// older layout's GetDesc, the newer one's GetTimestampFrequency). The title's render thread calls slot 18 every frame
1072// (t+0x2484180, vtable +0x90, then 1/frequency), and under queue_order it waited for whole submissions on the submit 1162// and a queued frequency query can wait for whole submissions. Slots 16-17 and 19-20 keep the lock here:
1073// 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 1163// which of them are getters depends on the layout (16-17 are Signal/Wait in the newer one). The caller drops the lock
1074// them are getters depends on the layout (16-17 are Signal/Wait in the newer one). 1164// for a 16/17 call that passes no fence: that is the older layout's frequency/calibration getter, not Signal/Wait.
1075constexpr bool queue_slot_orders_work(unsigned slot) { 1165constexpr bool queue_slot_orders_work(unsigned slot) {
1076 if (slot < 8 || slot > kQueueExecuteCommandListsX) return false; 1166 if (slot < 8 || slot > kQueueExecuteCommandListsX) return false;
1077 if (slot >= 11 && slot <= 13) return false; // SetMarker, BeginEvent, EndEvent 1167 if (slot >= 11 && slot <= 13) return false; // SetMarker, BeginEvent, EndEvent
@@ -1095,7 +1185,7 @@ struct ChildProxy {
1095 std::mutex queue_order; // serializes queue work across a host-side page remap 1185 std::mutex queue_order; // serializes queue work across a host-side page remap
1096 // Queue slot 31's fence, made at its first call and signalled with a rising value at each (under queue_order); 1186 // Queue slot 31's fence, made at its first call and signalled with a rising value at each (under queue_order);
1097 // kept for the queue's life. It was a new fence a call: a Vulkan timeline semaphore made and destroyed per batch. 1187 // kept for the queue's life. It was a new fence a call: a Vulkan timeline semaphore made and destroyed per batch.
1098 Microsoft::WRL::ComPtr<ID3D12Fence> map_fence; 1188 ID3D12Fence* map_fence = nullptr;
1099 std::uint64_t map_fence_value = 0; 1189 std::uint64_t map_fence_value = 0;
1100 std::atomic<unsigned char> queue_layout{kQueueLayoutUnknown}; 1190 std::atomic<unsigned char> queue_layout{kQueueLayoutUnknown};
1101 // Allocators only: callback and context recorded by console slot 9 (SetAllocatorCallbackX). 1191 // Allocators only: callback and context recorded by console slot 9 (SetAllocatorCallbackX).
@@ -1212,8 +1302,30 @@ void reset_child_stats() {
1212// 1302//
1213// The descriptor's code pointer is not called: the measured run goes on without it, and its contract (when it runs, 1303// The descriptor's code pointer is not called: the measured run goes on without it, and its contract (when it runs,
1214// on which thread, with what) is not known. The first call is logged with its arguments. 1304// on which thread, with what) is not known. The first call is logged with its arguments.
1305// LEONIDA_MIRROR_LAG=1: how late the mirror shows a value the GPU has reached. Each mirror also has the device's
1306// fence-wait thread call back the moment the timeline reaches the next value (it only notes when); the refresh that
1307// then writes that value adds now - that moment to the stats. LEONIDA_MIRROR_EXACT=1: that callback writes the
1308// mirror itself and asks for the next value, so the title sees a completion as soon as our dispatcher does (the
1309// thread-pool wait stays as the backstop for rewinds).
1310struct FenceMirror;
1311struct MirrorLink { // shared with the fence-wait callbacks; destroy_child clears `mirror` before the fence goes
1312 SRWLOCK lock = SRWLOCK_INIT;
1313 FenceMirror* mirror = nullptr; // under lock
1314 std::atomic<std::uint64_t> reached_value{0}; // the value the callback saw, 0: none outstanding
1315 std::atomic<std::int64_t> reached_at{0}; // QueryPerformanceCounter when it saw it
1316};
1317bool mirror_lag_enabled() {
1318 static const bool on = [] { const char* v = std::getenv("LEONIDA_MIRROR_LAG"); return v && *v == '1'; }();
1319 return on;
1320}
1321bool mirror_exact_enabled() {
1322 static const bool on = [] { const char* v = std::getenv("LEONIDA_MIRROR_EXACT"); return v && *v == '1'; }();
1323 return on;
1324}
1325
1215struct FenceMirror { 1326struct FenceMirror {
1216 alignas(8) volatile std::uint64_t completed = 0; // what the title reads through slot 12's pointer 1327 alignas(8) volatile std::uint64_t completed = 0; // what the title reads through slot 12's pointer
1328 std::shared_ptr<MirrorLink> link; // LEONIDA_MIRROR_LAG / LEONIDA_MIRROR_EXACT only
1217 ID3D12Fence* fence = nullptr; // the real fence; the proxy holds the reference 1329 ID3D12Fence* fence = nullptr; // the real fence; the proxy holds the reference
1218 SRWLOCK lock = SRWLOCK_INIT; // orders refreshes 1330 SRWLOCK lock = SRWLOCK_INIT; // orders refreshes
1219 HANDLE event = nullptr; // auto-reset; the real fence sets it at the armed value 1331 HANDLE event = nullptr; // auto-reset; the real fence sets it at the armed value
@@ -1222,14 +1334,89 @@ struct FenceMirror {
1222 std::atomic<bool> arm_failed{false}; 1334 std::atomic<bool> arm_failed{false};
1223}; 1335};
1224 1336
1225std::uint64_t refresh_mirror(FenceMirror* m) { 1337void note_mirror_lag(std::int64_t ticks, bool exact);
1338
1339std::uint64_t refresh_mirror(FenceMirror* m, bool exact = false) {
1226 AcquireSRWLockExclusive(&m->lock); 1340 AcquireSRWLockExclusive(&m->lock);
1227 const std::uint64_t value = m->fence->GetCompletedValue(); 1341 const std::uint64_t value = m->fence->GetCompletedValue();
1228 if (m->completed != value) m->completed = value; 1342 const bool advanced = m->completed != value;
1343 if (advanced) m->completed = value;
1229 ReleaseSRWLockExclusive(&m->lock); 1344 ReleaseSRWLockExclusive(&m->lock);
1345 if (advanced && m->link && value != ~std::uint64_t{0}) {
1346 std::uint64_t reached = m->link->reached_value.load(std::memory_order_acquire);
1347 if (reached && reached <= value && m->link->reached_value.compare_exchange_strong(reached, 0)) {
1348 LARGE_INTEGER now;
1349 QueryPerformanceCounter(&now);
1350 note_mirror_lag(now.QuadPart - m->link->reached_at.load(std::memory_order_acquire), exact);
1351 }
1352 }
1230 return value; 1353 return value;
1231} 1354}
1232 1355
1356// Every 10 s with LEONIDA_MIRROR_LAG: from our dispatcher seeing a fence reach a value to the mirror showing it.
1357void note_mirror_lag(std::int64_t ticks, bool exact) {
1358 static LARGE_INTEGER frequency = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }();
1359 static std::atomic<std::uint64_t> count{0}, total_us{0}, max_us{0}, over_1ms{0}, exact_count{0};
1360 static std::atomic<ULONGLONG> last{0};
1361 const std::uint64_t us = ticks > 0 ? std::uint64_t(ticks) * 1000000 / std::uint64_t(frequency.QuadPart) : 0;
1362 count.fetch_add(1, std::memory_order_relaxed);
1363 exact_count.fetch_add(exact, std::memory_order_relaxed);
1364 total_us.fetch_add(us, std::memory_order_relaxed);
1365 over_1ms.fetch_add(us > 1000, std::memory_order_relaxed);
1366 for (std::uint64_t m = max_us.load(); us > m && !max_us.compare_exchange_weak(m, us);) {
1367 }
1368 const ULONGLONG now = GetTickCount64();
1369 ULONGLONG was = last.load(std::memory_order_relaxed);
1370 if (!was) {
1371 last.compare_exchange_strong(was, now);
1372 return;
1373 }
1374 if (now - was < 10000 || !last.compare_exchange_strong(was, now)) return;
1375 const std::uint64_t n = count.exchange(0);
1376 std::fprintf(stderr, "[rt] d3d12_xs: fence slot 12 mirror lag (dispatcher saw the value -> mirror shows it): %llu "
1377 "updates in %.0f s (%llu written by the exact callback), avg %.0f us, max %llu us, %llu over 1 ms\n",
1378 static_cast<unsigned long long>(n), double(now - was) / 1000.0,
1379 static_cast<unsigned long long>(exact_count.exchange(0)),
1380 n ? double(total_us.exchange(0)) / double(n) : 0.0,
1381 static_cast<unsigned long long>(max_us.exchange(0)), static_cast<unsigned long long>(over_1ms.exchange(0)));
1382}
1383
1384// Asks the fence-wait thread for a callback when the fence reaches `value`. Once per call chain: the dispatcher runs a
1385// callback at once when it is stopping or the device is lost, which would otherwise ask again without end.
1386thread_local int t_mirror_arming = 0; // this thread is inside arm_mirror_callback
1387
1388void arm_mirror_callback(const std::shared_ptr<MirrorLink>& link, ID3D12Fence* fence, std::uint64_t value) {
1389#ifndef LEONIDA_VULKAN_DEVICE
1390 (void)link, (void)fence, (void)value; // no fence-wait thread to ask: the thread-pool wait alone
1391#else
1392 if (t_mirror_arming) return;
1393 ++t_mirror_arming;
1394 rt::d3d12::fence_callback_at(fence, value, [link] {
1395 // Run at once inside the arming call (dispatcher stopping): this thread may hold link->lock already.
1396 if (t_mirror_arming) return;
1397 LARGE_INTEGER now;
1398 QueryPerformanceCounter(&now);
1399 AcquireSRWLockExclusive(&link->lock);
1400 FenceMirror* m = link->mirror;
1401 if (m) {
1402 const std::uint64_t seen = m->fence->GetCompletedValue();
1403 if (seen != ~std::uint64_t{0}) {
1404 // Only a value the mirror does not show yet: one another path (slot 12, a CPU Signal) already wrote
1405 // would otherwise stay outstanding until the next advance and count that wait as lag.
1406 if (!link->reached_value.load(std::memory_order_acquire) && m->completed < seen) {
1407 link->reached_at.store(now.QuadPart, std::memory_order_release);
1408 link->reached_value.store(seen, std::memory_order_release);
1409 }
1410 if (mirror_exact_enabled()) refresh_mirror(m, true);
1411 arm_mirror_callback(link, m->fence, seen + 1);
1412 }
1413 }
1414 ReleaseSRWLockExclusive(&link->lock);
1415 });
1416 --t_mirror_arming;
1417#endif
1418}
1419
1233void wait_for_fence_progress(FenceMirror* mirror) { 1420void wait_for_fence_progress(FenceMirror* mirror) {
1234 constexpr LONGLONG kRewindPollInterval = -10 * 10'000; // 10 ms in relative 100 ns units 1421 constexpr LONGLONG kRewindPollInterval = -10 * 10'000; // 10 ms in relative 100 ns units
1235 ULARGE_INTEGER due{}; 1422 ULARGE_INTEGER due{};
@@ -1286,6 +1473,11 @@ FenceMirror* fence_mirror(ChildProxy* self) {
1286 if (!m && (m = new (std::nothrow) FenceMirror)) { 1473 if (!m && (m = new (std::nothrow) FenceMirror)) {
1287 m->fence = reinterpret_cast<ID3D12Fence*>(self->real); 1474 m->fence = reinterpret_cast<ID3D12Fence*>(self->real);
1288 refresh_mirror(m); 1475 refresh_mirror(m);
1476 if (mirror_lag_enabled() || mirror_exact_enabled()) {
1477 m->link = std::make_shared<MirrorLink>();
1478 m->link->mirror = m;
1479 arm_mirror_callback(m->link, m->fence, m->completed + 1);
1480 }
1289 m->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); 1481 m->event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1290 if (m->event) m->wait = CreateThreadpoolWait(on_fence_progress, m, nullptr); 1482 if (m->event) m->wait = CreateThreadpoolWait(on_fence_progress, m, nullptr);
1291 if (m->wait) { 1483 if (m->wait) {
@@ -1343,7 +1535,14 @@ void destroy_child(ChildProxy* self) {
1343 CloseThreadpoolWait(mirror->wait); 1535 CloseThreadpoolWait(mirror->wait);
1344 g_mirrors_live.fetch_sub(1, std::memory_order_relaxed); 1536 g_mirrors_live.fetch_sub(1, std::memory_order_relaxed);
1345 } 1537 }
1538 if (mirror && mirror->link) { // a fence-wait callback still pending (or running) no longer reaches the mirror
1539 AcquireSRWLockExclusive(&mirror->link->lock);
1540 mirror->link->mirror = nullptr;
1541 ReleaseSRWLockExclusive(&mirror->link->lock);
1542 }
1543 ID3D12Fence* const map_fence = self->map_fence; // queue slot 31's; an async mapping in flight holds its own
1346 delete self; 1544 delete self;
1545 if (map_fence) map_fence->Release();
1347 const unsigned long left = real ? real->Release() : 0; 1546 const unsigned long left = real ? real->Release() : 0;
1348 if (mirror) { 1547 if (mirror) {
1349 if (mirror->event && left == 0) CloseHandle(mirror->event); 1548 if (mirror->event && left == 0) CloseHandle(mirror->event);
@@ -1569,6 +1768,7 @@ struct PresentState {
1569 } 1768 }
1570 HWND window = nullptr; // the runtime's own fallback window, when the title has no window to present in 1769 HWND window = nullptr; // the runtime's own fallback window, when the title has no window to present in
1571 std::unique_ptr<rt::d3d12::XboxPresentation> xbox; 1770 std::unique_ptr<rt::d3d12::XboxPresentation> xbox;
1771 std::unique_ptr<TitleHud> hud; // LEONIDA_TITLE_HUD: counters in the window's title bar (title_hud.h)
1572}; 1772};
1573 1773
1574void destroy_present_state(void* present_state) { 1774void destroy_present_state(void* present_state) {
@@ -1739,6 +1939,7 @@ PresentState* present_state_for(DeviceProxy* device, bool splash_only = false) {
1739 std::fprintf(stderr, "[rt] d3d12_xs: frame interval %u us replayed (0x%08lx), origin event (0x%08lx)\n", 1939 std::fprintf(stderr, "[rt] d3d12_xs: frame interval %u us replayed (0x%08lx), origin event (0x%08lx)\n",
1740 interval, static_cast<unsigned long>(set), static_cast<unsigned long>(armed)); 1940 interval, static_cast<unsigned long>(set), static_cast<unsigned long>(armed));
1741 } 1941 }
1942 if (TitleHud::enabled()) state->hud = std::make_unique<TitleHud>(target);
1742 if (splash_only) device->present_state = pending.release(); 1943 if (splash_only) device->present_state = pending.release();
1743 std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p: %s, client area %ldx%ld)\n", 1944 std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p: %s, client area %ldx%ld)\n",
1744 static_cast<void*>(target), 1945 static_cast<void*>(target),
@@ -1758,10 +1959,11 @@ std::uint64_t queue_present_x(ChildProxy* self, std::uint64_t plane_count, std::
1758 std::uint64_t params) { 1959 std::uint64_t params) {
1759 PresentState* state = self->device ? present_state_for(self->device) : nullptr; 1960 PresentState* state = self->device ? present_state_for(self->device) : nullptr;
1760 if (!state || !state->xbox) return hr_to_u64(S_OK); // a title still runs with nothing presented 1961 if (!state || !state->xbox) return hr_to_u64(S_OK); // a title still runs with nothing presented
1761 return hr_to_u64(state->xbox->PresentX( 1962 const HRESULT result = state->xbox->PresentX(
1762 static_cast<UINT>(plane_count), 1963 static_cast<UINT>(plane_count), reinterpret_cast<const rt::d3d12::XboxPresentPlaneParameters*>(planes),
1763 reinterpret_cast<const rt::d3d12::XboxPresentPlaneParameters*>(planes), 1964 reinterpret_cast<const rt::d3d12::XboxPresentParameters*>(params));
1764 reinterpret_cast<const rt::d3d12::XboxPresentParameters*>(params))); 1965 if (SUCCEEDED(result) && state->hud) state->hud->note_present();
1966 return hr_to_u64(result);
1765} 1967}
1766 1968
1767#else // !LEONIDA_VULKAN_DEVICE: this translation unit stands alone (mock and COM tests) 1969#else // !LEONIDA_VULKAN_DEVICE: this translation unit stands alone (mock and COM tests)
@@ -1924,8 +2126,8 @@ bool slot31_async() {
1924 2126
1925struct AsyncMapping { 2127struct AsyncMapping {
1926 CopyPageMappingsHook map; 2128 CopyPageMappingsHook map;
1927 Microsoft::WRL::ComPtr<ID3D12Fence> fence; 2129 ID3D12Fence* fence = nullptr;
1928 std::uint64_t value; 2130 std::uint64_t value = 0;
1929 std::vector<xmem::PageBatch> batches; 2131 std::vector<xmem::PageBatch> batches;
1930 std::vector<std::vector<xmem::PageRange>> ranges; 2132 std::vector<std::vector<xmem::PageRange>> ranges;
1931 std::uintptr_t pool; 2133 std::uintptr_t pool;
@@ -1953,6 +2155,7 @@ struct AsyncMapper {
1953 } 2155 }
1954 const auto t0 = clock::now(); 2156 const auto t0 = clock::now();
1955 HRESULT hr = job.fence->SetEventOnCompletion(job.value, nullptr); 2157 HRESULT hr = job.fence->SetEventOnCompletion(job.value, nullptr);
2158 job.fence->Release(); // the reference the call took for this job: the queue may be gone by now
1956 const auto t1 = clock::now(); 2159 const auto t1 = clock::now();
1957 bool ok = SUCCEEDED(hr) && 2160 bool ok = SUCCEEDED(hr) &&
1958 job.map(std::uint32_t(job.batches.size()), job.batches.data(), job.pool, job.pages, job.flags); 2161 job.map(std::uint32_t(job.batches.size()), job.batches.data(), job.pool, job.pages, job.flags);
@@ -2077,6 +2280,9 @@ bool copy_page_mappings_default(std::uint32_t count, const xmem::PageBatch* batc
2077// call return before the remap, as on the console; an error is logged and counted then, not returned. 2280// call return before the remap, as on the console; an error is logged and counted then, not returned.
2078// With LEONIDA_LIST_VALUES=0 (no gates), without the value fences or the list-value threads, or when the queue's Wait 2281// With LEONIDA_LIST_VALUES=0 (no gates), without the value fences or the list-value threads, or when the queue's Wait
2079// for the remap cannot be submitted, the call waits for the earlier work, however long, as it did before. 2282// for the remap cannot be submitted, the call waits for the earlier work, however long, as it did before.
2283// With LEONIDA_SLOT31_ASYNC=1 neither: the call signals the queue map fence and returns, and the async worker
2284// maps once the GPU passes it (slot31_async), in call order. The remap runs xmem's copy_page_mappings
2285// (g_copy_page_mappings) on every path, deferred or not.
2080HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageBatch* batches, 2286HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageBatch* batches,
2081 std::uintptr_t pool, UINT pages, UINT flags) { 2287 std::uintptr_t pool, UINT pages, UINT flags) {
2082 auto map = g_copy_page_mappings.load(std::memory_order_acquire); 2288 auto map = g_copy_page_mappings.load(std::memory_order_acquire);
@@ -2084,13 +2290,19 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB
2084 if (!map || !count) return S_OK; 2290 if (!map || !count) return S_OK;
2085 if (!batches || flags) return E_INVALIDARG; 2291 if (!batches || flags) return E_INVALIDARG;
2086 auto* queue = reinterpret_cast<ID3D12CommandQueue*>(self->real); 2292 auto* queue = reinterpret_cast<ID3D12CommandQueue*>(self->real);
2087 if (list_values::enabled() && !self->values) 2293 using clock = std::chrono::steady_clock;
2294 const auto t0 = clock::now();
2295 HRESULT hr = S_OK;
2296 bool deferred = false; // the remap is the list-value releaser's now: nothing is mapped here
2297 // LEONIDA_SLOT31_ASYNC=1 asks for the async worker below instead of the bounded wait and the gate.
2298 const bool gated = list_values::enabled() && !slot31_async();
2299 if (gated && !self->values)
2088 self->values = list_values::QueueValues::create(self->device->real, queue); 2300 self->values = list_values::QueueValues::create(self->device->real, queue);
2089 if (list_values::QueueValues* values = list_values::enabled() ? self->values.get() : nullptr) { 2301 if (list_values::QueueValues* values = gated ? self->values.get() : nullptr) {
2090 auto& counters = list_values::counters(); 2302 auto& counters = list_values::counters();
2091 list_values::Pump& pump = list_values::Pump::get(); 2303 list_values::Pump& pump = list_values::Pump::get();
2092 const std::uint64_t point = ++values->written_value; 2304 const std::uint64_t point = ++values->written_value;
2093 HRESULT hr = queue->Signal(values->written, point); 2305 hr = queue->Signal(values->written, point);
2094 if (FAILED(hr)) return hr; 2306 if (FAILED(hr)) return hr;
2095 // The bound is kept with a high-resolution timer: a plain timed wait rounds to the system tick (15.6 ms), 2307 // The bound is kept with a high-resolution timer: a plain timed wait rounds to the system tick (15.6 ms),
2096 // which would defer at once or hold queue_order for two ticks. Neither handle is ever closed: a fence may still 2308 // which would defer at once or hold queue_order for two ticks. Neither handle is ever closed: a fence may still
@@ -2098,14 +2310,12 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB
2098 static thread_local const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); 2310 static thread_local const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
2099 static thread_local const HANDLE timer = 2311 static thread_local const HANDLE timer =
2100 CreateWaitableTimerExW(nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); 2312 CreateWaitableTimerExW(nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS);
2101 using Clock = std::chrono::steady_clock; 2313 const auto deadline = t0 + std::chrono::milliseconds(kPageMappingWaitMs);
2102 const auto started = Clock::now();
2103 const auto deadline = started + std::chrono::milliseconds(kPageMappingWaitMs);
2104 bool reached = values->written->GetCompletedValue() >= point; 2314 bool reached = values->written->GetCompletedValue() >= point;
2105 if (!reached && event && SUCCEEDED(values->written->SetEventOnCompletion(point, event))) { 2315 if (!reached && event && SUCCEEDED(values->written->SetEventOnCompletion(point, event))) {
2106 for (;;) { 2316 for (;;) {
2107 reached = values->written->GetCompletedValue() >= point; 2317 reached = values->written->GetCompletedValue() >= point;
2108 const auto now = Clock::now(); 2318 const auto now = clock::now();
2109 if (reached || now >= deadline) break; 2319 if (reached || now >= deadline) break;
2110 const auto left = std::chrono::duration_cast<std::chrono::nanoseconds>(deadline - now).count(); 2320 const auto left = std::chrono::duration_cast<std::chrono::nanoseconds>(deadline - now).count();
2111 LARGE_INTEGER due{}; 2321 LARGE_INTEGER due{};
@@ -2120,7 +2330,7 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB
2120 } 2330 }
2121 list_values::raise_to(counters.remap_wait_us_max, 2331 list_values::raise_to(counters.remap_wait_us_max,
2122 static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>( 2332 static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(
2123 Clock::now() - started) 2333 clock::now() - t0)
2124 .count())); 2334 .count()));
2125 // After stop_list_values (the process is ending) the queue's gates are not signalled any more and its earlier 2335 // After stop_list_values (the process is ending) the queue's gates are not signalled any more and its earlier
2126 // work may never run: the remap is done now rather than holding queue_order until ExitProcess. 2336 // work may never run: the remap is done now rather than holding queue_order until ExitProcess.
@@ -2149,55 +2359,51 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB
2149 error, copy->batches.size(), reinterpret_cast<void*>(copy->pool), 2359 error, copy->batches.size(), reinterpret_cast<void*>(copy->pool),
2150 copy->pages); 2360 copy->pages);
2151 })) { 2361 })) {
2152 const std::uint64_t deferred = 2362 const std::uint64_t so_far =
2153 counters.remaps_deferred.fetch_add(1, std::memory_order_relaxed) + 1; 2363 counters.remaps_deferred.fetch_add(1, std::memory_order_relaxed) + 1;
2154 if (deferred == 1 || (deferred & (deferred - 1)) == 0) 2364 if (so_far == 1 || (so_far & (so_far - 1)) == 0)
2155 std::fprintf(stderr, "[rt] d3d12_xs: CopyPageMappingsBatchX waits behind held queue work: " 2365 std::fprintf(stderr, "[rt] d3d12_xs: CopyPageMappingsBatchX waits behind held queue work: "
2156 "the remap runs when the queue gets there (%llu deferred so far)\n", 2366 "the remap runs when the queue gets there (%llu deferred so far)\n",
2157 static_cast<unsigned long long>(deferred)); 2367 static_cast<unsigned long long>(so_far));
2158 return S_OK; 2368 deferred = true;
2159 } 2369 }
2160 // stop_list_values came in between: nothing opens the gate any more; the remap is done now. 2370 // Otherwise stop_list_values came in between: nothing opens the gate any more; the remap is done now.
2161 } else { 2371 } else {
2162 hr = values->written->SetEventOnCompletion(point, nullptr); // not deferred: wait, as before 2372 hr = values->written->SetEventOnCompletion(point, nullptr); // not deferred: wait, as before
2163 if (FAILED(hr)) return hr; 2373 if (FAILED(hr)) return hr;
2164 } 2374 }
2165 } 2375 }
2166 if (values->written->GetCompletedValue() == UINT64_MAX) return DXGI_ERROR_DEVICE_REMOVED; 2376 if (!deferred) {
2167 list_values::bump(counters.remaps_now); 2377 if (values->written->GetCompletedValue() == UINT64_MAX) hr = DXGI_ERROR_DEVICE_REMOVED;
2168 if (!map(count, batches, pool, pages, flags)) { 2378 else list_values::bump(counters.remaps_now);
2169 const DWORD error = GetLastError();
2170 return error ? HRESULT_FROM_WIN32(error) : E_FAIL;
2171 } 2379 }
2172 return S_OK; 2380 } else {
2173 } 2381 if (!self->map_fence) {
2174 HRESULT hr = S_OK; 2382 hr = self->device->real->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&self->map_fence));
2175 if (!self->map_fence) { 2383 if (FAILED(hr)) return hr;
2176 hr = self->device->real->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(self->map_fence.GetAddressOf())); 2384 if (!self->map_fence) return E_FAIL;
2177 if (FAILED(hr)) return hr;
2178 if (!self->map_fence) return E_FAIL;
2179 }
2180 ID3D12Fence* const fence = self->map_fence.Get();
2181 const std::uint64_t value = ++self->map_fence_value;
2182 using clock = std::chrono::steady_clock;
2183 const auto t0 = clock::now();
2184 hr = queue->Signal(fence, value);
2185 if (SUCCEEDED(hr) && slot31_async()) {
2186 AsyncMapping job{map, self->map_fence, value, {}, {}, pool, pages, flags};
2187 job.batches.assign(batches, batches + count);
2188 job.ranges.resize(count);
2189 for (UINT b = 0; b < count; ++b) {
2190 if (batches[b].count && batches[b].ranges)
2191 job.ranges[b].assign(batches[b].ranges, batches[b].ranges + batches[b].count);
2192 job.batches[b].ranges = job.ranges[b].data();
2193 } 2385 }
2194 async_mapper().push(std::move(job)); 2386 ID3D12Fence* const fence = self->map_fence;
2195 return S_OK; 2387 const std::uint64_t value = ++self->map_fence_value;
2388 hr = queue->Signal(fence, value);
2389 if (SUCCEEDED(hr) && slot31_async()) {
2390 AsyncMapping job{map, fence, value, {}, {}, pool, pages, flags};
2391 job.batches.assign(batches, batches + count);
2392 job.ranges.resize(count);
2393 for (UINT b = 0; b < count; ++b) {
2394 if (batches[b].count && batches[b].ranges)
2395 job.ranges[b].assign(batches[b].ranges, batches[b].ranges + batches[b].count);
2396 job.batches[b].ranges = job.ranges[b].data();
2397 }
2398 fence->AddRef(); // the worker releases it: destroy_child releases the queue's own reference
2399 async_mapper().push(std::move(job));
2400 return S_OK;
2401 }
2402 if (SUCCEEDED(hr)) hr = fence->SetEventOnCompletion(value, nullptr);
2403 if (SUCCEEDED(hr) && fence->GetCompletedValue() == UINT64_MAX) hr = DXGI_ERROR_DEVICE_REMOVED;
2196 } 2404 }
2197 if (SUCCEEDED(hr)) hr = fence->SetEventOnCompletion(value, nullptr);
2198 if (SUCCEEDED(hr) && fence->GetCompletedValue() == UINT64_MAX) hr = DXGI_ERROR_DEVICE_REMOVED;
2199 const auto t1 = clock::now(); 2405 const auto t1 = clock::now();
2200 if (SUCCEEDED(hr) && !map(count, batches, pool, pages, flags)) { 2406 if (SUCCEEDED(hr) && !deferred && !map(count, batches, pool, pages, flags)) {
2201 const DWORD error = GetLastError(); 2407 const DWORD error = GetLastError();
2202 hr = error ? HRESULT_FROM_WIN32(error) : E_FAIL; 2408 hr = error ? HRESULT_FROM_WIN32(error) : E_FAIL;
2203 } 2409 }
@@ -2256,8 +2462,28 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_
2256 } else { 2462 } else {
2257 note_child_slot<K>(Slot); 2463 note_child_slot<K>(Slot);
2258 std::unique_lock<std::mutex> queue_order; 2464 std::unique_lock<std::mutex> queue_order;
2259 if constexpr (K == ChildKind::queue && queue_slot_orders_work(Slot)) 2465 // Both queue-order fixes: only work that orders on the queue takes queue_order. The markers do not, and
2260 queue_order = std::unique_lock(self->queue_order); 2466 // neither does slot 18 - an ExecuteCommandListsX holds it for its whole replay, which can include building a
2467 // pipeline for minutes, while the title's render thread asks the timestamp frequency every frame (a frozen
2468 // frame loop, measured). 16/17 keep the lock when a fence comes with them (the newer layout's Signal/Wait);
2469 // without one they are the older layout's frequency/calibration getter. 19/20 are the newer layout's
2470 // GetClockCalibration and GetDesc (PC 17/18 shifted by two): getters there, so no lock once that layout is
2471 // known (the title uses it natively); in the older layout they keep it. Queues only: for other proxy kinds
2472 // a1 is not an object pointer and must not be read.
2473 if constexpr (K == ChildKind::queue) {
2474 bool orders = queue_slot_orders_work(Slot);
2475 if (orders && (Slot == 16 || Slot == 17))
2476 orders = proxy_real_object(reinterpret_cast<const void*>(a1)) != nullptr;
2477 if (orders && (Slot == 19 || Slot == 20)) {
2478 const unsigned char own = self->queue_layout.load(std::memory_order_relaxed);
2479 const bool newer = own == ChildProxy::kQueueLayoutNewer ||
2480 (own == ChildProxy::kQueueLayoutUnknown &&
2481 self->device->console_layout.load(std::memory_order_relaxed) ==
2482 ChildProxy::kQueueLayoutNewer);
2483 if (newer) orders = false;
2484 }
2485 if (orders) queue_order = std::unique_lock(self->queue_order);
2486 }
2261 // CopyPageMappingsBatchX when something can remap: a hook (set_copy_page_mappings_hook) or xmem. Without 2487 // CopyPageMappingsBatchX when something can remap: a hook (set_copy_page_mappings_hook) or xmem. Without
2262 // either (a proxy compiled without xmem) the slot keeps the answer every unmodelled queue slot past the 2488 // either (a proxy compiled without xmem) the slot keeps the answer every unmodelled queue slot past the
2263 // public chain gets below: console-only S_OK, or E_NOTIMPL on a queue whose presentation is managed outside. 2489 // public chain gets below: console-only S_OK, or E_NOTIMPL on a queue whose presentation is managed outside.
@@ -3174,6 +3400,101 @@ void note_bundle_value_op(ConsoleValueOp op) {
3174 op == ConsoleValueOp::write32 || op == ConsoleValueOp::write64 ? "write" : "wait"); 3400 op == ConsoleValueOp::write32 || op == ConsoleValueOp::write64 ? "write" : "wait");
3175} 3401}
3176 3402
3403// ---- Console list slot 146: Barrier(NumBarrierGroups, pBarrierGroups) -> GCL7 Barrier (PC 80) ----
3404//
3405// The title records texture barriers with no resource, which the console takes as a global memory and execution
3406// barrier. A PC texture barrier needs a resource (the Vulkan layer's list goes into its error state, so Close fails
3407// and the submission is dropped), so each such barrier becomes a D3D12_GLOBAL_BARRIER with the same sync and access;
3408// its layouts, subresource range and flags have nothing to apply to. A texture group with both kinds is split into
3409// runs in their order: texture runs point into the title's array, global runs into the call's own storage. A call
3410// with nothing to convert is forwarded with the title's own pointer.
3411constexpr UINT32 kMaxConsoleBarrierGroups = 1024; // the measured calls pass one group
3412constexpr UINT32 kMaxConsoleBarriersPerGroup = 65536;
3413
3414struct ConsoleBarrierStorage { // lives for one call, on the recording thread's stack
3415 std::vector<D3D12_BARRIER_GROUP> groups;
3416 std::vector<D3D12_GLOBAL_BARRIER> globals;
3417};
3418
3419// The groups to forward: `in` when nothing needs converting, `storage.groups` when something does, null with
3420// `reason` set when the array cannot be read safely and the call is refused. `out_count` is the group count to pass.
3421const D3D12_BARRIER_GROUP* console_barrier_groups(UINT32 count, const D3D12_BARRIER_GROUP* in,
3422 ConsoleBarrierStorage& storage, UINT32& out_count,
3423 const char*& reason) {
3424 const auto refuse = [&reason](const char* why) -> const D3D12_BARRIER_GROUP* {
3425 reason = why;
3426 return nullptr;
3427 };
3428 out_count = count;
3429 if (count == 0) return in; // nothing to read: the PC call is a no-op either way
3430 if (!in) return refuse("null group array with a nonzero count");
3431 if (count > kMaxConsoleBarrierGroups) return refuse("group count over the limit");
3432 std::size_t null_textures = 0, texture_barriers = 0;
3433 for (UINT32 g = 0; g < count; ++g) {
3434 const D3D12_BARRIER_GROUP& group = in[g];
3435 if (group.Type != D3D12_BARRIER_TYPE_GLOBAL && group.Type != D3D12_BARRIER_TYPE_TEXTURE &&
3436 group.Type != D3D12_BARRIER_TYPE_BUFFER)
3437 return refuse("unknown barrier group type");
3438 if (group.NumBarriers > kMaxConsoleBarriersPerGroup) return refuse("barrier count over the limit");
3439 if (group.NumBarriers && !group.pGlobalBarriers) // the union's pointer, whichever member the type names
3440 return refuse("null barrier array with a nonzero count");
3441 if (group.Type != D3D12_BARRIER_TYPE_TEXTURE) continue;
3442 texture_barriers += group.NumBarriers;
3443 for (UINT32 i = 0; i < group.NumBarriers; ++i)
3444 if (!group.pTextureBarriers[i].pResource) ++null_textures;
3445 }
3446 if (null_textures == 0) return in;
3447 try {
3448 storage.globals.reserve(null_textures); // exact: the groups point into it, so it never reallocates
3449 storage.groups.reserve(count + texture_barriers);
3450 for (UINT32 g = 0; g < count; ++g) {
3451 const D3D12_BARRIER_GROUP& group = in[g];
3452 if (group.Type != D3D12_BARRIER_TYPE_TEXTURE) {
3453 storage.groups.push_back(group);
3454 continue;
3455 }
3456 const D3D12_TEXTURE_BARRIER* barriers = group.pTextureBarriers;
3457 for (UINT32 i = 0; i < group.NumBarriers;) {
3458 const UINT32 start = i;
3459 const bool no_resource = !barriers[i].pResource;
3460 while (i < group.NumBarriers && !barriers[i].pResource == no_resource) ++i;
3461 D3D12_BARRIER_GROUP run{};
3462 run.NumBarriers = i - start;
3463 if (no_resource) {
3464 run.Type = D3D12_BARRIER_TYPE_GLOBAL;
3465 run.pGlobalBarriers = storage.globals.data() + storage.globals.size();
3466 for (UINT32 k = start; k < i; ++k)
3467 storage.globals.push_back(D3D12_GLOBAL_BARRIER{barriers[k].SyncBefore, barriers[k].SyncAfter,
3468 barriers[k].AccessBefore,
3469 barriers[k].AccessAfter});
3470 } else {
3471 run.Type = D3D12_BARRIER_TYPE_TEXTURE;
3472 run.pTextureBarriers = barriers + start;
3473 }
3474 storage.groups.push_back(run);
3475 }
3476 }
3477 } catch (const std::bad_alloc&) {
3478 return refuse("out of memory converting the groups");
3479 }
3480 out_count = static_cast<UINT32>(storage.groups.size());
3481 return storage.groups.data();
3482}
3483
3484// Logged once per reason. The call is dropped whole: nothing of it reaches the PC list.
3485void log_refused_barrier(const char* reason, UINT32 count, const void* groups) {
3486 static std::mutex lock;
3487 static std::set<const char*> seen; // the reasons are string literals
3488 std::lock_guard guard(lock);
3489 try {
3490 if (!seen.insert(reason).second) return;
3491 } catch (const std::bad_alloc&) {
3492 return;
3493 }
3494 std::fprintf(stderr, "[rt] d3d12_xs: list slot 146 (Barrier) refused, nothing recorded: %s (%u groups at %p)\n",
3495 reason, count, groups);
3496}
3497
3177template <unsigned Slot> 3498template <unsigned Slot>
3178std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, 3499std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3,
3179 std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, 3500 std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7,
@@ -3394,6 +3715,36 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t
3394 // ClearRenderTargetView(RenderTargetView, ColorRGBA, NumRects, pRects): translate the RTV handle. 3715 // ClearRenderTargetView(RenderTargetView, ColorRGBA, NumRects, pRects): translate the RTV handle.
3395 a1 = static_cast<std::uint64_t>( 3716 a1 = static_cast<std::uint64_t>(
3396 translate_cpu_handle(self->device, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast<SIZE_T>(a1)}).ptr); 3717 translate_cpu_handle(self->device, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast<SIZE_T>(a1)}).ptr);
3718 // A view the title made with no resource: the console clear does nothing, and the PC list would
3719 // take the view as invalid and fail its Close. Any other view goes to the PC list as before.
3720 if (is_null_rtv(self->device, static_cast<SIZE_T>(a1))) {
3721 static std::atomic<bool> logged{false};
3722 if (first_call(logged))
3723 std::fprintf(stderr, "[rt] d3d12_xs: list slot 52 (ClearRenderTargetView) of a view made with "
3724 "no resource skipped, as on the console (handle 0x%llx)\n",
3725 static_cast<unsigned long long>(a1));
3726 return 0;
3727 }
3728 } else if constexpr (Slot == kConsoleBarrier) {
3729 // Barrier(NumBarrierGroups, pBarrierGroups): console_barrier_groups above.
3730 ConsoleBarrierStorage storage;
3731 UINT32 count = 0;
3732 const char* reason = nullptr;
3733 const D3D12_BARRIER_GROUP* groups = console_barrier_groups(
3734 static_cast<UINT32>(a1), reinterpret_cast<const D3D12_BARRIER_GROUP*>(a2), storage, count, reason);
3735 if (reason) {
3736 log_refused_barrier(reason, static_cast<UINT32>(a1), reinterpret_cast<const void*>(a2));
3737 return 0;
3738 }
3739 if (groups && groups == storage.groups.data()) {
3740 static std::atomic<bool> logged{false};
3741 if (first_call(logged))
3742 std::fprintf(stderr, "[rt] d3d12_xs: list slot 146 (Barrier): texture barriers with no "
3743 "resource recorded as global barriers, as on the console\n");
3744 }
3745 return reinterpret_cast<ForwardFn>(real_vtable[pc])(self->real, count,
3746 reinterpret_cast<std::uint64_t>(groups), a3, a4,
3747 a5, a6, a7, a8, a9, a10, a11, a12, a13, a14);
3397 } else if constexpr (Slot == kConsoleClearUavUint || Slot == kConsoleClearUavFloat) { 3748 } else if constexpr (Slot == kConsoleClearUavUint || Slot == kConsoleClearUavFloat) {
3398 // ClearUnorderedAccessViewUint/Float(ViewGPUHandle, ViewCPUHandle, pResource, Values, NumRects, 3749 // ClearUnorderedAccessViewUint/Float(ViewGPUHandle, ViewCPUHandle, pResource, Values, NumRects,
3399 // pRects): keep GPU handle, translate CPU handle. 3750 // pRects): keep GPU handle, translate CPU handle.
@@ -3438,10 +3789,38 @@ void WINAPI list_clear_depth_stencil_view(ListProxy* self, D3D12_CPU_DESCRIPTOR_
3438 reinterpret_cast<ClearDsvFn>(real_vtable[pc])(self->real, translated, flags, depth, stencil, num_rects, rects); 3789 reinterpret_cast<ClearDsvFn>(real_vtable[pc])(self->real, translated, flags, depth, stencil, num_rects, rects);
3439} 3790}
3440 3791
3792// OMSetDepthBoundsX (console slot 70 in the newer layout, this package's) -> ID3D12GraphicsCommandList1::
3793// OMSetDepthBounds (PC slot 62). Its FLOAT arguments arrive in XMM1 and XMM2, which list_slot's integer thunk would
3794// lose, so it has a typed thunk too. In the older layout slot 70 is a memory write (console_value_op), which this
3795// thunk cannot see: LEONIDA_DEPTH_BOUNDS_SLOT70=0 keeps the generic thunk for such a title.
3796constexpr unsigned kConsoleOMSetDepthBounds = 70, kPcOMSetDepthBounds = 62;
3797void WINAPI list_om_set_depth_bounds(ListProxy* self, FLOAT min, FLOAT max) {
3798 std::uint32_t lo = 0, hi = 0;
3799 std::memcpy(&lo, &min, sizeof lo);
3800 std::memcpy(&hi, &max, sizeof hi);
3801 const unsigned char layout = self->device->console_layout.load(std::memory_order_relaxed);
3802 note_list_slot(kConsoleOMSetDepthBounds, lo, hi, 0, 0, layout);
3803 if (layout == kConsoleLayoutOlder) {
3804 static std::atomic<bool> warned{false};
3805 if (!warned.exchange(true, std::memory_order_relaxed))
3806 std::fprintf(stderr, "[rt] d3d12_xs: list slot 70 in the older layout is a memory write the depth-bounds "
3807 "thunk drops; run with LEONIDA_DEPTH_BOUNDS_SLOT70=0\n");
3808 return;
3809 }
3810 if (kPcOMSetDepthBounds >= self->pc_slot_count) return;
3811 using Fn = void(WINAPI*)(IUnknown*, FLOAT, FLOAT);
3812 auto** const real_vtable = *reinterpret_cast<void***>(self->real);
3813 reinterpret_cast<Fn>(real_vtable[kPcOMSetDepthBounds])(self->real, min, max);
3814}
3815
3441template <std::size_t... I> 3816template <std::size_t... I>
3442void fill_list_vtable(void** vtable, std::index_sequence<I...>) { 3817void fill_list_vtable(void** vtable, std::index_sequence<I...>) {
3443 ((vtable[I] = reinterpret_cast<void*>(&list_slot<static_cast<unsigned>(I)>) ), ...); 3818 ((vtable[I] = reinterpret_cast<void*>(&list_slot<static_cast<unsigned>(I)>) ), ...);
3444 vtable[kConsoleClearDepthStencilView] = reinterpret_cast<void*>(&list_clear_depth_stencil_view); 3819 vtable[kConsoleClearDepthStencilView] = reinterpret_cast<void*>(&list_clear_depth_stencil_view);
3820 wchar_t v[4]{};
3821 const DWORD n = GetEnvironmentVariableW(L"LEONIDA_DEPTH_BOUNDS_SLOT70", v, 4);
3822 if (!(n == 1 && v[0] == L'0'))
3823 vtable[kConsoleOMSetDepthBounds] = reinterpret_cast<void*>(&list_om_set_depth_bounds);
3445} 3824}
3446 3825
3447void** get_list_vtable() { 3826void** get_list_vtable() {
@@ -4350,8 +4729,16 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H
4350 4729
4351 hr = create_heap_proxy(heap, self, *riid, out, custom_cpu_start, custom_byte_size, real_cpu_start, 4730 hr = create_heap_proxy(heap, self, *riid, out, custom_cpu_start, custom_byte_size, real_cpu_start,
4352 custom_cpu_start ? free_fn : nullptr, stride); 4731 custom_cpu_start ? free_fn : nullptr, stride);
4353 // LOCAL DIAGNOSTIC (fsdraw): which CPU start the title gets for this heap 4732 if (SUCCEEDED(hr) && desc && desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_RTV && is_heap_proxy(*out)) {
4354 if (leonida::local_diagnostics()) { 4733 // The null-view marks are kept by real handle (mark_null_rtv); heap_release drops those in this range.
4734 const UINT inc = self->real->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
4735 auto* proxy = static_cast<HeapProxy*>(*out);
4736 proxy->rtv_real_start =
4737 real_cpu_start ? real_cpu_start : raw_heap_get_cpu_handle(heap, *reinterpret_cast<void***>(heap)).ptr;
4738 if (inc && desc->NumDescriptors <= (std::numeric_limits<SIZE_T>::max)() / inc)
4739 proxy->rtv_real_bytes = static_cast<SIZE_T>(desc->NumDescriptors) * inc;
4740 }
4741 if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC (fsdraw): which CPU start the title gets for this heap
4355 static std::atomic<int> logged{0}; 4742 static std::atomic<int> logged{0};
4356 if (logged.fetch_add(1) < 32) 4743 if (logged.fetch_add(1) < 32)
4357 std::fprintf(stderr, "[rt] fsdraw: heap type %d num %u flags 0x%x console %d: title CPU start 0x%llx (custom " 4744 std::fprintf(stderr, "[rt] fsdraw: heap type %d num %u flags 0x%x console %d: title CPU start 0x%llx (custom "
@@ -4401,7 +4788,9 @@ void proxy_create_uav(DeviceProxy* self, ID3D12Resource* resource, ID3D12Resourc
4401void proxy_create_rtv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc, 4788void proxy_create_rtv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc,
4402 D3D12_CPU_DESCRIPTOR_HANDLE dest) { 4789 D3D12_CPU_DESCRIPTOR_HANDLE dest) {
4403 note_slot(20); 4790 note_slot(20);
4404 self->real->CreateRenderTargetView(resource, desc, translate_cpu_handle(self, dest)); 4791 const D3D12_CPU_DESCRIPTOR_HANDLE real_dest = translate_cpu_handle(self, dest);
4792 self->real->CreateRenderTargetView(resource, desc, real_dest);
4793 mark_null_rtv(self, real_dest.ptr, resource == nullptr); // for console list slot 52 (DeviceProxy::null_rtvs)
4405} 4794}
4406 4795
4407void proxy_create_dsv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_DEPTH_STENCIL_VIEW_DESC* desc, 4796void proxy_create_dsv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_DEPTH_STENCIL_VIEW_DESC* desc,
@@ -4422,6 +4811,7 @@ void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DE
4422 note_slot(23); 4811 note_slot(23);
4423 if (g_custom_range_count.load(std::memory_order_acquire) == 0) { 4812 if (g_custom_range_count.load(std::memory_order_acquire) == 0) {
4424 self->real->CopyDescriptors(num_dest, dest_starts, dest_sizes, num_src, src_starts, src_sizes, type); 4813 self->real->CopyDescriptors(num_dest, dest_starts, dest_sizes, num_src, src_starts, src_sizes, type);
4814 copy_null_rtv_marks(self, num_dest, dest_starts, dest_sizes, num_src, src_starts, src_sizes, type);
4425 return; 4815 return;
4426 } 4816 }
4427 constexpr UINT kInline = 32; 4817 constexpr UINT kInline = 32;
@@ -4456,6 +4846,7 @@ void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DE
4456 self->real->CopyDescriptors(num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type); 4846 self->real->CopyDescriptors(num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type);
4457 for (UINT i = 0; dest_starts && i < num_dest; ++i) 4847 for (UINT i = 0; dest_starts && i < num_dest; ++i)
4458 local_write_through(self, dest_starts[i], dest_sizes ? dest_sizes[i] : 1); 4848 local_write_through(self, dest_starts[i], dest_sizes ? dest_sizes[i] : 1);
4849 copy_null_rtv_marks(self, num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type);
4459} 4850}
4460 4851
4461void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D12_CPU_DESCRIPTOR_HANDLE dest_start, 4852void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D12_CPU_DESCRIPTOR_HANDLE dest_start,
@@ -4465,8 +4856,8 @@ void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D1
4465 const D3D12_CPU_DESCRIPTOR_HANDLE src = translate_cpu_handle(self, src_start); 4856 const D3D12_CPU_DESCRIPTOR_HANDLE src = translate_cpu_handle(self, src_start);
4466 self->real->CopyDescriptorsSimple(num_descriptors, dest, src, type); 4857 self->real->CopyDescriptorsSimple(num_descriptors, dest, src, type);
4467 local_write_through(self, dest_start, num_descriptors); 4858 local_write_through(self, dest_start, num_descriptors);
4468 // LOCAL DIAGNOSTIC (fsdraw): where the title copies its descriptors, and what lands there 4859 copy_null_rtv_marks(self, 1, &dest, &num_descriptors, 1, &src, &num_descriptors, type);
4469 if (leonida::local_diagnostics()) { 4860 if (leonida::fsdraw::enabled()) { // LOCAL DIAGNOSTIC (fsdraw): where the title copies its descriptors, and what lands there
4470 static std::atomic<std::uint64_t> copies{0}; 4861 static std::atomic<std::uint64_t> copies{0};
4471 const std::uint64_t n = ++copies; 4862 const std::uint64_t n = ++copies;
4472 if (n <= 24 || n % 600 == 0 || n % 600 == 1) { 4863 if (n <= 24 || n % 600 == 0 || n % 600 == 1) {
@@ -5736,7 +6127,8 @@ HRESULT proxy_create_state_object(DeviceProxy* self, const D3D12_STATE_OBJECT_DE
5736// D3D12_RESOURCE_FLAGS are normalized on the copy before the PC call. 6127// D3D12_RESOURCE_FLAGS are normalized on the copy before the PC call.
5737void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12_RESOURCE_ALLOCATION_INFO& info, 6128void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12_RESOURCE_ALLOCATION_INFO& info,
5738 D3D12_RESOURCE_ALLOCATION_INFO1* each, 6129 D3D12_RESOURCE_ALLOCATION_INFO1* each,
5739 const std::function<D3D12_RESOURCE_ALLOCATION_INFO(UINT)>& pc_one, unsigned slot); 6130 const std::function<D3D12_RESOURCE_ALLOCATION_INFO(UINT)>& pc_one, unsigned slot,
6131 const D3D12_RESOURCE_DESC* title_descs);
5740 6132
5741std::uint64_t proxy_get_resource_allocation_info2(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2, 6133std::uint64_t proxy_get_resource_allocation_info2(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2,
5742 std::uint64_t a3, std::uint64_t a4, std::uint64_t a5) { 6134 std::uint64_t a3, std::uint64_t a4, std::uint64_t a5) {
@@ -5811,7 +6203,7 @@ std::uint64_t proxy_get_resource_allocation_info2(DeviceProxy* self, std::uint64
5811 if (info1 && !pc.empty()) 6203 if (info1 && !pc.empty())
5812 apply_console_placement(pc.data(), count, *ret, info1, [&](UINT i) { 6204 apply_console_placement(pc.data(), count, *ret, info1, [&](UINT i) {
5813 return D3D12_RESOURCE_ALLOCATION_INFO{info1[i].SizeInBytes, info1[i].Alignment}; 6205 return D3D12_RESOURCE_ALLOCATION_INFO{info1[i].SizeInBytes, info1[i].Alignment};
5814 }, 108); 6206 }, 108, raw_descs);
5815 return reinterpret_cast<std::uint64_t>(ret); 6207 return reinterpret_cast<std::uint64_t>(ret);
5816} 6208}
5817 6209
@@ -6099,13 +6491,15 @@ StructReturnCall struct_return_call(std::uint64_t a0, std::uint64_t a1) {
6099 6491
6100// The console size of a list of descriptions (d3d12_xs_alloc_size.h): the PC device's answer with every console render 6492// The console size of a list of descriptions (d3d12_xs_alloc_size.h): the PC device's answer with every console render
6101// target laid out at its console size, each at its own alignment. `info` is the PC answer and is replaced only when 6493// target laid out at its console size, each at its own alignment. `info` is the PC answer and is replaced only when
6102// the console layout is larger. `each` is the per-description array of slot 56, or null. 6494// the console layout is larger. `each` is the per-description array of slot 56, or null. `title_descs` is the
6495// title's own array when `descs` is its PC form (the layout words the PC form drops), else null.
6103void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12_RESOURCE_ALLOCATION_INFO& info, 6496void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12_RESOURCE_ALLOCATION_INFO& info,
6104 D3D12_RESOURCE_ALLOCATION_INFO1* each, 6497 D3D12_RESOURCE_ALLOCATION_INFO1* each,
6105 const std::function<D3D12_RESOURCE_ALLOCATION_INFO(UINT)>& pc_one, unsigned slot) { 6498 const std::function<D3D12_RESOURCE_ALLOCATION_INFO(UINT)>& pc_one, unsigned slot,
6499 const D3D12_RESOURCE_DESC* title_descs) {
6106 if (info.SizeInBytes == UINT64_MAX) return; 6500 if (info.SizeInBytes == UINT64_MAX) return;
6107 D3D12_RESOURCE_ALLOCATION_INFO console{}; 6501 D3D12_RESOURCE_ALLOCATION_INFO console{};
6108 if (!console_placement(descs, count, pc_one, console, each)) return; 6502 if (!console_placement(descs, count, pc_one, console, each, title_descs)) return;
6109 static std::atomic<bool> logged{false}; 6503 static std::atomic<bool> logged{false};
6110 if (!logged.exchange(true, std::memory_order_relaxed)) 6504 if (!logged.exchange(true, std::memory_order_relaxed))
6111 std::fprintf(stderr, 6505 std::fprintf(stderr,
@@ -6113,6 +6507,22 @@ void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12
6113 "description(s)\n", 6507 "description(s)\n",
6114 slot, static_cast<unsigned long long>(console.SizeInBytes), 6508 slot, static_cast<unsigned long long>(console.SizeInBytes),
6115 static_cast<unsigned long long>(info.SizeInBytes), static_cast<unsigned>(count)); 6509 static_cast<unsigned long long>(info.SizeInBytes), static_cast<unsigned>(count));
6510 // The first few textures the title writes with the CPU through its lock that took their console layout's size
6511 // (console_unordered_access_size).
6512 static std::atomic<int> uav_logged{0};
6513 for (UINT i = 0; descs && i < count && uav_logged.load(std::memory_order_relaxed) < 8; ++i) {
6514 const D3D12_RESOURCE_DESC& d = descs[i];
6515 const UINT layout = static_cast<UINT>((title_descs ? title_descs : descs)[i].Layout);
6516 const UINT64 written = console_unordered_access_size(d, layout);
6517 if (!written || uav_logged.fetch_add(1, std::memory_order_relaxed) >= 8) continue;
6518 std::fprintf(stderr,
6519 "[rt] d3d12_xs: slot %u: unordered-access texture dimension %d %llux%ux%u mips %u format %d "
6520 "layout 0x%x takes its console layout's %llu B (list %llu B, PC %llu B)\n",
6521 slot, static_cast<int>(d.Dimension), static_cast<unsigned long long>(d.Width), d.Height,
6522 unsigned(d.DepthOrArraySize), unsigned(d.MipLevels), static_cast<int>(d.Format), layout,
6523 static_cast<unsigned long long>(written), static_cast<unsigned long long>(console.SizeInBytes),
6524 static_cast<unsigned long long>(info.SizeInBytes));
6525 }
6116 // A list with a depth-stencil target may come out smaller than the PC answer (console_depth_stencil_size). 6526 // A list with a depth-stencil target may come out smaller than the PC answer (console_depth_stencil_size).
6117 bool depth = false; 6527 bool depth = false;
6118 for (UINT i = 0; descs && i < count && !depth; ++i) { 6528 for (UINT i = 0; descs && i < count && !depth; ++i) {
@@ -6181,7 +6591,7 @@ void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t
6181 // own code and tests, which compare with the PC device) gets the PC device's answer unchanged. 6591 // own code and tests, which compare with the PC device) gets the PC device's answer unchanged.
6182 if (call.console_abi) 6592 if (call.console_abi)
6183 apply_console_placement(descs, desc_count, info, nullptr, 6593 apply_console_placement(descs, desc_count, info, nullptr,
6184 [&](UINT i) { return real->GetResourceAllocationInfo(mask, 1, &descs[i]); }, 25); 6594 [&](UINT i) { return real->GetResourceAllocationInfo(mask, 1, &descs[i]); }, 25, title_descs);
6185 // LEONIDA_LOG_ALLOCINFO=1: every call, with the calling thread (the title sums a batch of these against a fixed 6595 // LEONIDA_LOG_ALLOCINFO=1: every call, with the calling thread (the title sums a batch of these against a fixed
6186 // pool and asserts when the batch does not fit). 6596 // pool and asserts when the batch does not fit).
6187 static const bool log_all = [] { 6597 static const bool log_all = [] {
@@ -6234,7 +6644,7 @@ void* WINAPI proxy_get_resource_allocation_info1(std::uint64_t a0, std::uint64_t
6234 auto& info = *static_cast<D3D12_RESOURCE_ALLOCATION_INFO*>(call.ret); 6644 auto& info = *static_cast<D3D12_RESOURCE_ALLOCATION_INFO*>(call.ret);
6235 apply_console_placement(descs, n, info, each, [&](UINT i) { 6645 apply_console_placement(descs, n, info, each, [&](UINT i) {
6236 return D3D12_RESOURCE_ALLOCATION_INFO{each[i].SizeInBytes, each[i].Alignment}; 6646 return D3D12_RESOURCE_ALLOCATION_INFO{each[i].SizeInBytes, each[i].Alignment};
6237 }, 56); 6647 }, 56, nullptr);
6238 } 6648 }
6239 return returned; 6649 return returned;
6240} 6650}
diff --git a/runtime/shims/d3d12_xs_list_values.h b/runtime/shims/d3d12_xs_list_values.h
index 2a30b4b96..e49eefa98 100644
--- a/runtime/shims/d3d12_xs_list_values.h
+++ b/runtime/shims/d3d12_xs_list_values.h
@@ -602,7 +602,9 @@ private:
602 stall_logged_ = false; 602 stall_logged_ = false;
603 return; 603 return;
604 } 604 }
605 const std::uint64_t ms = GetTickCount64() - since; 605 // `since` is the start tick with its low bit set (never 0 while inside), so it can be one past now.
606 const std::uint64_t now = GetTickCount64();
607 const std::uint64_t ms = now > since ? now - since : 0;
606 if (ms < kStallMs || stall_logged_) return; 608 if (ms < kStallMs || stall_logged_) return;
607 stall_logged_ = true; 609 stall_logged_ = true;
608 bump(counters().release_stalls); 610 bump(counters().release_stalls);
diff --git a/runtime/shims/dxgi_swapchain.h b/runtime/shims/dxgi_swapchain.h
index ebe3bc027..477bc29b2 100644
--- a/runtime/shims/dxgi_swapchain.h
+++ b/runtime/shims/dxgi_swapchain.h
@@ -111,7 +111,7 @@ class VulkanSwapchain {
111public: 111public:
112 VulkanSwapchain(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, VkPhysicalDevice physical, 112 VulkanSwapchain(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, VkPhysicalDevice physical,
113 PFN_vkGetDeviceProcAddr gdpa, VkDevice device, VkQueue queue, std::uint32_t queue_family, 113 PFN_vkGetDeviceProcAddr gdpa, VkDevice device, VkQueue queue, std::uint32_t queue_family,
114 std::mutex& submit_mutex, DeviceFaultDiagnostics* diagnostics) 114 SubmitMutex& submit_mutex, DeviceFaultDiagnostics* diagnostics)
115 : instance_(instance), physical_(physical), device_(device), queue_(queue), queue_family_(queue_family), 115 : instance_(instance), physical_(physical), device_(device), queue_(queue), queue_family_(queue_family),
116 submit_mutex_(submit_mutex), diagnostics_(diagnostics) { 116 submit_mutex_(submit_mutex), diagnostics_(diagnostics) {
117 loaded_ = fn_.load(gipa, instance, gdpa, device); 117 loaded_ = fn_.load(gipa, instance, gdpa, device);
@@ -220,6 +220,7 @@ public:
220 pi.pSwapchains = &swapchain_; 220 pi.pSwapchains = &swapchain_;
221 pi.pImageIndices = &image_index; 221 pi.pImageIndices = &image_index;
222 std::lock_guard lock(submit_mutex_); 222 std::lock_guard lock(submit_mutex_);
223 const SubmitMutex::SubmitTurn turn(submit_mutex_); // a queue operation: the compile gate
223 const VkResult r = observe(fn_.queue_present(queue_, &pi), "vkQueuePresentKHR (DXGI)"); 224 const VkResult r = observe(fn_.queue_present(queue_, &pi), "vkQueuePresentKHR (DXGI)");
224 return r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR; 225 return r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR;
225 } 226 }
@@ -400,8 +401,12 @@ private:
400 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; 401 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO};
401 si.commandBufferCount = 1; 402 si.commandBufferCount = 1;
402 si.pCommandBuffers = &blit_cmd_; 403 si.pCommandBuffers = &blit_cmd_;
403 if (fn_.queue_submit(queue_, 1, &si, blit_fence_) != VK_SUCCESS || 404 bool submitted = false;
404 fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX) != VK_SUCCESS) { 405 {
406 const SubmitMutex::SubmitTurn turn(submit_mutex_); // a queue operation: the compile gate
407 submitted = fn_.queue_submit(queue_, 1, &si, blit_fence_) == VK_SUCCESS;
408 }
409 if (!submitted || fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX) != VK_SUCCESS) {
405 destroy_offscreen(); 410 destroy_offscreen();
406 return false; 411 return false;
407 } 412 }
@@ -486,7 +491,12 @@ private:
486 } 491 }
487 492
488 bool submit_blit_and_wait(const VkSubmitInfo& submit) { 493 bool submit_blit_and_wait(const VkSubmitInfo& submit) {
489 return observe(fn_.queue_submit(queue_, 1, &submit, blit_fence_), "vkQueueSubmit (DXGI)") == VK_SUCCESS && 494 VkResult submitted;
495 {
496 const SubmitMutex::SubmitTurn turn(submit_mutex_); // the compile gate (VulkanContext::queue_submit)
497 submitted = fn_.queue_submit(queue_, 1, &submit, blit_fence_);
498 }
499 return observe(submitted, "vkQueueSubmit (DXGI)") == VK_SUCCESS &&
490 observe(fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX), 500 observe(fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX),
491 "vkWaitForFences (DXGI blit)") == VK_SUCCESS; 501 "vkWaitForFences (DXGI blit)") == VK_SUCCESS;
492 } 502 }
@@ -595,7 +605,7 @@ private:
595 VkDevice device_ = VK_NULL_HANDLE; 605 VkDevice device_ = VK_NULL_HANDLE;
596 VkQueue queue_ = VK_NULL_HANDLE; 606 VkQueue queue_ = VK_NULL_HANDLE;
597 std::uint32_t queue_family_ = 0; 607 std::uint32_t queue_family_ = 0;
598 std::mutex& submit_mutex_; 608 SubmitMutex& submit_mutex_;
599 DeviceFaultDiagnostics* diagnostics_; 609 DeviceFaultDiagnostics* diagnostics_;
600 VkSurfaceKHR surface_ = VK_NULL_HANDLE; 610 VkSurfaceKHR surface_ = VK_NULL_HANDLE;
601 VkSwapchainKHR swapchain_ = VK_NULL_HANDLE; 611 VkSwapchainKHR swapchain_ = VK_NULL_HANDLE;
diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp
index dad6f37a8..8a20b21e9 100644
--- a/runtime/shims/file_system.cpp
+++ b/runtime/shims/file_system.cpp
@@ -6,7 +6,8 @@
6// here (docs/runtime_imports.md, "Console paths and the write overlay"; the prefixes come from ivall/xcl, 6// here (docs/runtime_imports.md, "Console paths and the write overlay"; the prefixes come from ivall/xcl,
7// GPL-2.0-only, as facts). The rules: 7// GPL-2.0-only, as facts). The rules:
8// - "GAME:" (any case, "\\" or "/") maps under --game-dir, "G:\\" is the same folder and "T:\\" a scratch folder in 8// - "GAME:" (any case, "\\" or "/") maps under --game-dir, "G:\\" is the same folder and "T:\\" a scratch folder in
9// the overlay (RT-218); any other path is a host path and goes to the host; 9// the overlay (RT-218), <overlay>\\.gta6rt-temp\\<run>, a new one reserved by every process; any other path is a
10// host path and goes to the host;
10// - an open that can write, and DeleteFile, go to the overlay (--overlay, default <game-dir>\\overlay), so the 11// - an open that can write, and DeleteFile, go to the overlay (--overlay, default <game-dir>\\overlay), so the
11// package stays exactly as installed. A write-open of a package file copies it into the overlay first, so 12// package stays exactly as installed. A write-open of a package file copies it into the overlay first, so
12// OPEN_EXISTING keeps its bytes; a delete of a package file leaves an empty marker under 13// OPEN_EXISTING keeps its bytes; a delete of a package file leaves an empty marker under
@@ -26,6 +27,7 @@
26#include <intrin.h> 27#include <intrin.h>
27 28
28#include <atomic> 29#include <atomic>
30#include <cstdio>
29#include <cstring> 31#include <cstring>
30#include <cwchar> 32#include <cwchar>
31#include <cwctype> 33#include <cwctype>
@@ -49,7 +51,7 @@ namespace {
49constexpr wchar_t kGamePrefix[] = L"game:"; 51constexpr wchar_t kGamePrefix[] = L"game:";
50constexpr size_t kGamePrefixLength = 5; 52constexpr size_t kGamePrefixLength = 5;
51constexpr wchar_t kDeletedDir[] = L".gta6rt-deleted"; 53constexpr wchar_t kDeletedDir[] = L".gta6rt-deleted";
52constexpr wchar_t kScratchDir[] = L".gta6rt-temp"; // what "T:\" names, inside the overlay 54constexpr wchar_t kScratchDir[] = L".gta6rt-temp"; // holds one folder per process; "T:\" names this process's
53// A removed package folder is marked by this file inside its marker folder: the marker folder itself can already 55// A removed package folder is marked by this file inside its marker folder: the marker folder itself can already
54// exist because files below it were deleted, and that alone does not hide the folder. 56// exist because files below it were deleted, and that alone does not hide the folder.
55constexpr wchar_t kRemovedDirMarker[] = L".gta6rt-dir"; 57constexpr wchar_t kRemovedDirMarker[] = L".gta6rt-dir";
@@ -167,9 +169,68 @@ std::filesystem::path win32_find_path(const std::filesystem::path& path, const s
167// other console layers map those two drives (RT-218). Only the executable can say which spelling the title uses, so 169// other console layers map those two drives (RT-218). Only the executable can say which spelling the title uses, so
168// a host drive of the same letter must keep working: a path under --game-dir or the overlay (a package on drive G:, 170// a host drive of the same letter must keep working: a path under --game-dir or the overlay (a package on drive G:,
169// or a path GetModuleFileName handed back) stays a host path, and so does every G:/T: path while no roots are 171// or a path GetModuleFileName handed back) stays a host path, and so does every G:/T: path while no roots are
170// configured. The scratch folder lives in the overlay, as `.gta6rt-temp`. 172// configured. The scratch folder lives in the overlay, as `.gta6rt-temp\<run>`, one per process (scratch_folder()).
171enum class Drive { None, Game, Scratch }; 173enum class Drive { None, Game, Scratch };
172 174
175// The stem of this process's T: folder below `.gta6rt-temp`: the process's start time (UTC, to the millisecond) and
176// its id, e.g. "20261123-181502-123-pid4242". On the console T: is the title's own temporary drive, empty at launch
177// and shared with nothing; one folder that every run shared kept the files earlier runs left, so a title that makes a
178// file there with CREATE_NEW (its crash dump and crash log, measured under Wine) got ERROR_FILE_EXISTS. The stem only
179// makes the folder easy to find: a reused process id in the same millisecond gives the same stem, so the folder is
180// reserved by reserve_unique_dir, which never hands out one that already existed.
181const std::wstring& scratch_run() {
182 static const std::wstring name = [] {
183 const DWORD last_error = ::GetLastError();
184 FILETIME created{}, exited{}, kernel{}, user{};
185 SYSTEMTIME t{};
186 if (!::GetProcessTimes(::GetCurrentProcess(), &created, &exited, &kernel, &user) ||
187 !::FileTimeToSystemTime(&created, &t))
188 ::GetSystemTime(&t);
189 wchar_t buffer[64];
190 const unsigned long pid = ::GetCurrentProcessId();
191 std::swprintf(buffer, sizeof(buffer) / sizeof(buffer[0]), L"%04u%02u%02u-%02u%02u%02u-%03u-pid%lu",
192 unsigned{t.wYear}, unsigned{t.wMonth}, unsigned{t.wDay}, unsigned{t.wHour}, unsigned{t.wMinute},
193 unsigned{t.wSecond}, unsigned{t.wMilliseconds}, pid);
194 ::SetLastError(last_error);
195 return std::wstring(buffer);
196 }();
197 return name;
198}
199
200// The T: folder this process reserved in each overlay it was given (configure() may name several, as the test does),
201// or the error that stopped the reservation. Decided once per overlay, under the mutex, so concurrent first T: calls
202// get the same folder.
203struct ScratchFolder {
204 std::wstring name; // empty: the reservation failed with `error`
205 DWORD error = 0;
206};
207std::mutex g_scratch_mutex;
208std::map<std::wstring, ScratchFolder> g_scratch_folders; // keyed by the overlay path, lowercased
209
210// The name of this process's folder below <overlay>\.gta6rt-temp, reserved on the first call for that overlay; empty
211// when it could not be reserved (logged once). With no overlay configured nothing is made and the stem is the name.
212std::wstring scratch_folder(const std::filesystem::path& overlay) {
213 if (overlay.empty()) return scratch_run();
214 std::lock_guard lock(g_scratch_mutex);
215 ScratchFolder& folder = g_scratch_folders[lower(overlay.native())];
216 if (folder.name.empty() && folder.error == 0) {
217 const DWORD last_error = ::GetLastError();
218 DWORD error = 0;
219 const std::filesystem::path reserved = reserve_unique_dir(overlay / kScratchDir, scratch_run(), error);
220 if (reserved.empty()) {
221 folder.error = error ? error : ERROR_CANNOT_MAKE;
222 std::fprintf(stderr,
223 "[rt] file_system: no T: folder could be reserved below %ls (Win32 error %lu); T: paths "
224 "fail with ERROR_INVALID_NAME\n",
225 (overlay / kScratchDir).c_str(), static_cast<unsigned long>(folder.error));
226 } else {
227 folder.name = reserved.filename().native();
228 }
229 ::SetLastError(last_error);
230 }
231 return folder.name;
232}
233
173Drive console_drive(const std::wstring& path, size_t& prefix_length) { 234Drive console_drive(const std::wstring& path, size_t& prefix_length) {
174 if (path.size() >= kGamePrefixLength && lower(path.substr(0, kGamePrefixLength)) == kGamePrefix) { 235 if (path.size() >= kGamePrefixLength && lower(path.substr(0, kGamePrefixLength)) == kGamePrefix) {
175 prefix_length = kGamePrefixLength; 236 prefix_length = kGamePrefixLength;
@@ -191,11 +252,15 @@ Parsed parse_console(const std::wstring& path, std::vector<std::wstring>& parts)
191 if (drive == Drive::None) return Parsed::Host; 252 if (drive == Drive::None) return Parsed::Host;
192 parts.clear(); 253 parts.clear();
193 if (drive == Drive::Scratch) { 254 if (drive == Drive::Scratch) {
194 parts.push_back(kScratchDir);
195 const std::filesystem::path overlay = roots().overlay; 255 const std::filesystem::path overlay = roots().overlay;
256 const std::wstring folder = scratch_folder(overlay);
257 if (folder.empty()) return Parsed::Refused;
258 parts.push_back(kScratchDir);
259 parts.push_back(folder);
260 // The folder is this process's from its reservation on; made again if something removed it since.
196 const DWORD last_error = ::GetLastError(); 261 const DWORD last_error = ::GetLastError();
197 std::error_code ec; 262 std::error_code ec;
198 if (!overlay.empty()) std::filesystem::create_directories(win32_io_path(overlay / kScratchDir), ec); 263 if (!overlay.empty()) std::filesystem::create_directories(win32_io_path(overlay / kScratchDir / folder), ec);
199 ::SetLastError(last_error); 264 ::SetLastError(last_error);
200 } 265 }
201 const size_t floor = parts.size(); // ".." may not climb out of the drive's own root 266 const size_t floor = parts.size(); // ".." may not climb out of the drive's own root
@@ -227,7 +292,7 @@ Parsed parse_console(const std::wstring& path, std::vector<std::wstring>& parts)
227 if (!flush()) return Parsed::Refused; 292 if (!flush()) return Parsed::Refused;
228 // The overlay's own folders are not part of the title's GAME: tree: hidden from its listings (internal_dir) and 293 // The overlay's own folders are not part of the title's GAME: tree: hidden from its listings (internal_dir) and
229 // refused as an explicit path too, in every spelling the loop above normalises (case, slashes, "." and ".."). 294 // refused as an explicit path too, in every spelling the loop above normalises (case, slashes, "." and "..").
230 // T: still names the scratch folder: its first part is pushed above, not parsed from the title's path. 295 // T: still names the scratch folder: its first two parts are pushed above, not parsed from the title's path.
231 if (drive == Drive::Game && !parts.empty() && internal_dir(parts.front().c_str())) return Parsed::Refused; 296 if (drive == Drive::Game && !parts.empty() && internal_dir(parts.front().c_str())) return Parsed::Refused;
232 return Parsed::Console; 297 return Parsed::Console;
233} 298}
@@ -244,12 +309,44 @@ std::filesystem::path disk_path(const std::filesystem::path& root, const std::ve
244 309
245bool drive_root(const std::wstring& path, const std::vector<std::wstring>& parts) { 310bool drive_root(const std::wstring& path, const std::vector<std::wstring>& parts) {
246 size_t prefix_length = 0; 311 size_t prefix_length = 0;
247 return parts.empty() || (parts.size() == 1 && console_drive(path, prefix_length) == Drive::Scratch); 312 return parts.empty() || (parts.size() == 2 && console_drive(path, prefix_length) == Drive::Scratch);
313}
314
315// A folder's entries change one step at a time, as on the host: RemoveDirectory holds the folder's lock from its
316// emptiness check to its marker, and a GAME: write-open or CreateDirectory holds the lock of the folder it creates in
317// from its "does the folder exist" check, through mirroring that folder into the overlay, to the host call that makes
318// the entry. One of the two goes first: the create fails with ERROR_PATH_NOT_FOUND, or the remove with
319// ERROR_DIR_NOT_EMPTY. Without it both succeeded and the removed folder was back, the new entry in it. The locks are
320// striped by the folder's name, so calls in different folders rarely wait on each other; reads never take one.
321// Namespace scope, not function-local statics: these run on the title's threads. Taken after roots(); nothing holding
322// one takes another of them or calls back into the title (a copy-up's lock may be taken inside one, never around one).
323constexpr size_t kFolderLocks = 64;
324std::mutex g_folder_locks[kFolderLocks];
325
326std::mutex& folder_lock(const std::vector<std::wstring>& folder) {
327 // FNV-1a over the upper-cased components: names compare without case, so every spelling of a folder gets its lock.
328 uint64_t hash = 14695981039346656037ull;
329 const auto mix = [&hash](wchar_t c) {
330 hash ^= static_cast<uint64_t>(c);
331 hash *= 1099511628211ull;
332 };
333 for (const auto& part : folder) {
334 std::wstring upper(part.size(), L'\0');
335 if (part.empty() || LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_UPPERCASE, part.data(),
336 static_cast<int>(part.size()), upper.data(), static_cast<int>(upper.size()),
337 nullptr, nullptr, 0) != static_cast<int>(part.size()))
338 upper = part;
339 for (const wchar_t c : upper) mix(c);
340 mix(L'\\');
341 }
342 return g_folder_locks[hash % kFolderLocks];
248} 343}
249 344
250struct Target { 345struct Target {
251 std::filesystem::path path; 346 std::filesystem::path path;
252 DWORD error = 0; // non-zero: the caller fails with this error and does not touch the host 347 DWORD error = 0; // non-zero: the caller fails with this error and does not touch the host
348 // A write-open's hold on the folder it opens in, until the Target goes after the host open (g_folder_locks).
349 std::unique_lock<std::mutex> folder;
253}; 350};
254 351
255Target fail(DWORD error) { 352Target fail(DWORD error) {
@@ -438,10 +535,14 @@ Target write_target(const std::wstring& path, bool copy_up) {
438 // below a package file (which then read as a folder) and inside a folder the title had removed. The overlay may 535 // below a package file (which then read as a folder) and inside a folder the title had removed. The overlay may
439 // still lack a folder only the package has, so it is mirrored here, which the title cannot see. 536 // still lack a folder only the package has, so it is mirrored here, which the title cannot see.
440 // T:'s scratch folder is the exception: it creates its parent folders, as merged with RT-218. 537 // T:'s scratch folder is the exception: it creates its parent folders, as merged with RT-218.
538 // The folder's lock is held from this check to the caller's host open, so a RemoveDirectory of the folder comes
539 // wholly before or after (g_folder_locks).
540 std::unique_lock folder(folder_lock(parent_of(parts)));
441 const bool scratch = !parts.empty() && same_name(parts.front().c_str(), kScratchDir); 541 const bool scratch = !parts.empty() && same_name(parts.front().c_str(), kScratchDir);
442 if (!scratch && !is_folder(r, parent_of(parts))) return fail(ERROR_PATH_NOT_FOUND); 542 if (!scratch && !is_folder(r, parent_of(parts))) return fail(ERROR_PATH_NOT_FOUND);
443 543
444 Target t; 544 Target t;
545 t.folder = std::move(folder);
445 t.path = disk_path(r.overlay, parts); 546 t.path = disk_path(r.overlay, parts);
446 547
447 std::error_code ec; 548 std::error_code ec;
@@ -687,6 +788,34 @@ std::filesystem::path overlay_dir() {
687 return g_overlay_dir; 788 return g_overlay_dir;
688} 789}
689 790
791std::filesystem::path scratch_dir() {
792 const std::filesystem::path overlay = overlay_dir();
793 if (overlay.empty()) return {};
794 const std::wstring folder = scratch_folder(overlay);
795 return folder.empty() ? std::filesystem::path() : overlay / kScratchDir / folder;
796}
797
798std::wstring scratch_stem() { return scratch_run(); }
799
800std::filesystem::path reserve_unique_dir(const std::filesystem::path& base, const std::wstring& stem, DWORD& error,
801 unsigned max_tries) {
802 error = 0;
803 std::error_code ec;
804 std::filesystem::create_directories(win32_io_path(base), ec);
805 for (unsigned n = 1; n <= max_tries; ++n) {
806 const std::filesystem::path candidate = base / (n == 1 ? stem : stem + L"-" + std::to_wstring(n));
807 // Create-only: success means no other process or run had this name, so the folder is new and ours. Through
808 // win32_io_path, as every other create here, so a long overlay root keeps working.
809 if (::CreateDirectoryW(win32_io_path(candidate).c_str(), nullptr)) {
810 error = 0;
811 return candidate;
812 }
813 error = ::GetLastError();
814 if (error != ERROR_ALREADY_EXISTS) return {}; // another name will not get past this error
815 }
816 return {};
817}
818
690// gta6rt --trace FILE: a failed open of a guest path goes to the startup trace as a "file_open_failed" event (the 819// gta6rt --trace FILE: a failed open of a guest path goes to the startup trace as a "file_open_failed" event (the
691// path the title passed, the Win32 error, the caller as module+RVA), so a boot that stops on a missing or refused 820// path the title passed, the Win32 error, the caller as module+RVA), so a boot that stops on a missing or refused
692// file names it. Failures only, and at most 256 of them, so a title probing many optional files can't fill the file. 821// file names it. Failures only, and at most 256 of them, so a title probing many optional files can't fill the file.
@@ -1071,6 +1200,8 @@ BOOL create_directory(LPCWSTR template_name, LPCWSTR name, LPSECURITY_ATTRIBUTES
1071 const Roots r = roots(); 1200 const Roots r = roots();
1072 if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND); 1201 if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND);
1073 if (view(r, parts).kind != Kind::None) return fail_bool(ERROR_ALREADY_EXISTS); // "GAME:" included 1202 if (view(r, parts).kind != Kind::None) return fail_bool(ERROR_ALREADY_EXISTS); // "GAME:" included
1203 // From the parent's check to the new folder: a RemoveDirectory of the parent comes wholly before or after.
1204 std::lock_guard folder(folder_lock(parent_of(parts)));
1074 if (!is_folder(r, parent_of(parts))) return fail_bool(ERROR_PATH_NOT_FOUND); 1205 if (!is_folder(r, parent_of(parts))) return fail_bool(ERROR_PATH_NOT_FOUND);
1075 1206
1076 const std::filesystem::path target = disk_path(r.overlay, parts); 1207 const std::filesystem::path target = disk_path(r.overlay, parts);
@@ -1124,6 +1255,8 @@ BOOL WINAPI remove_directory_w(LPCWSTR name) {
1124 const Roots r = roots(); 1255 const Roots r = roots();
1125 if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND); 1256 if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND);
1126 if (drive_root(name, parts)) return fail_bool(ERROR_ACCESS_DENIED); // "GAME:" and "T:" themselves stay 1257 if (drive_root(name, parts)) return fail_bool(ERROR_ACCESS_DENIED); // "GAME:" and "T:" themselves stay
1258 // From the emptiness check to the marker: a create in the folder comes wholly before or after (g_folder_locks).
1259 std::lock_guard folder(folder_lock(parts));
1127 const View v = view(r, parts); 1260 const View v = view(r, parts);
1128 if (v.kind == Kind::None) return fail_bool(missing_error(r, parts)); 1261 if (v.kind == Kind::None) return fail_bool(missing_error(r, parts));
1129 if (v.kind == Kind::File) return fail_bool(ERROR_DIRECTORY); 1262 if (v.kind == Kind::File) return fail_bool(ERROR_DIRECTORY);
diff --git a/runtime/shims/file_system.h b/runtime/shims/file_system.h
index d252bb1ce..420430e13 100644
--- a/runtime/shims/file_system.h
+++ b/runtime/shims/file_system.h
@@ -28,6 +28,19 @@ void configure(const std::filesystem::path& game_dir, const std::filesystem::pat
28 28
29std::filesystem::path game_dir(); 29std::filesystem::path game_dir();
30std::filesystem::path overlay_dir(); 30std::filesystem::path overlay_dir();
31// The folder "T:\" names in this process: <overlay dir>\.gta6rt-temp\<stem>, or <stem>-2, -3, ... when that name was
32// taken (scratch_stem(), reserve_unique_dir). Reserved on the first T: call or the first call of this function for the
33// overlay and kept for the rest of the process; empty while no overlay is configured or when no folder could be made.
34std::filesystem::path scratch_dir();
35// The first name tried for that folder: the process's start time (UTC) and id, "YYYYMMDD-HHMMSS-mmm-pid<id>".
36std::wstring scratch_stem();
37
38// Makes a new folder base\stem, or base\stem-2 ... base\stem-<max_tries> when the names before it exist, each with a
39// create-only CreateDirectoryW, so the folder returned did not exist before and no other process got it. Makes `base`
40// first. Returns an empty path, with the Win32 error in `error`, when every name was taken (ERROR_ALREADY_EXISTS) or
41// a create failed for another reason.
42std::filesystem::path reserve_unique_dir(const std::filesystem::path& base, const std::wstring& stem,
43 unsigned long& error, unsigned max_tries = 1000);
31 44
32// For tests: true makes the CopyFile2 shim use its CopyFileExW fallback even where the host has CopyFile2, so the 45// For tests: true makes the CopyFile2 shim use its CopyFileExW fallback even where the host has CopyFile2, so the
33// path Wine 9 takes can be checked on Windows. Off by default; main.cpp never sets it. 46// path Wine 9 takes can be checked on Windows. Off by default; main.cpp never sets it.
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index 47e9aa941..fa5889d6a 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -45,6 +45,7 @@
45#include <cstring> 45#include <cstring>
46#include <deque> 46#include <deque>
47#include <mutex> 47#include <mutex>
48#include <map>
48#include <string> 49#include <string>
49#include <thread> 50#include <thread>
50#include <utility> 51#include <utility>
@@ -53,6 +54,7 @@
53#include "gameinput.h" 54#include "gameinput.h"
54#include "gameinput_abi.h" 55#include "gameinput_abi.h"
55#include "gameinput_script.h" 56#include "gameinput_script.h"
57#include "keyboard_pad_connection.h"
56#include "shims.h" 58#include "shims.h"
57 59
58using namespace gi; 60using namespace gi;
@@ -1004,6 +1006,9 @@ leonida::InputFamily family_of(SDL_JoystickID jid, SDL_Gamepad* p) {
1004// in bits 0-7, forced in bit 8, the generation from bit 16. 1006// in bits 0-7, forced in bit 8, the generation from bit 16.
1005leonida::ActiveInputTracker g_tracker; 1007leonida::ActiveInputTracker g_tracker;
1006std::atomic<uint64_t> g_active{0}; 1008std::atomic<uint64_t> g_active{0};
1009// GetCurrentReading calls so far, any device: a scripted press is held until the title has read the pads a few
1010// times since it began (update_keyboard_pad).
1011std::atomic<uint64_t> g_reading_calls{0};
1007 1012
1008void publish_active() { 1013void publish_active() {
1009 g_active.store(static_cast<uint64_t>(g_tracker.active()) | (g_tracker.forced() ? 1ull << 8 : 0) | 1014 g_active.store(static_cast<uint64_t>(g_tracker.active()) | (g_tracker.forced() ? 1ull << 8 : 0) |
@@ -1766,10 +1771,7 @@ std::atomic<rt::gameinput::KeyDownFn> g_key_down{async_key_down};
1766std::atomic<rt::gameinput::HasFocusFn> g_has_focus{foreground_is_ours}; 1771std::atomic<rt::gameinput::HasFocusFn> g_has_focus{foreground_is_ours};
1767std::atomic<rt::gameinput::CursorPosFn> g_cursor_pos{system_cursor_pos}; 1772std::atomic<rt::gameinput::CursorPosFn> g_cursor_pos{system_cursor_pos};
1768 1773
1769struct KeyboardPad { 1774struct KeyboardPad : rt::gameinput::detail::KeyboardPadConnection<SDL_JoystickID, SDL_Joystick*> {
1770 SDL_JoystickID id = 0;
1771 SDL_Joystick* js = nullptr;
1772 bool failed = false; // attaching failed once; not retried every 2 ms
1773 int right_x = 0, right_y = 0; // the mouse's right stick, SDL axis units (+Y down) 1775 int right_x = 0, right_y = 0; // the mouse's right stick, SDL axis units (+Y down)
1774 int cursor_x = 0, cursor_y = 0; // the cursor at the last poll 1776 int cursor_x = 0, cursor_y = 0; // the cursor at the last poll
1775 bool have_cursor = false; // cursor_x/y are valid; false after focus loss, so the first poll moves nothing 1777 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;
1778 1780
1779bool is_keyboard_pad(SDL_JoystickID jid) { return jid != 0 && jid == g_keyboard.id; } 1781bool is_keyboard_pad(SDL_JoystickID jid) { return jid != 0 && jid == g_keyboard.id; }
1780 1782
1781void detach_keyboard_pad() {
1782 if (g_keyboard.js) SDL_CloseJoystick(g_keyboard.js);
1783 if (g_keyboard.id) SDL_DetachVirtualJoystick(g_keyboard.id);
1784 if (g_keyboard.id) std::fprintf(stderr, "[rt] gameinput: keyboard pad removed\n");
1785 g_keyboard = {};
1786}
1787
1788// Keeps the cursor inside the game window while it has focus, so a click cannot land on another window, and releases 1783// Keeps the cursor inside the game window while it has focus, so a click cannot land on another window, and releases
1789// it on focus loss. Only with raw input (a clipped plain cursor would stop the stick at the window edge) and only for 1784// it on focus loss. Only with raw input (a clipped plain cursor would stop the stick at the window edge) and only for
1790// a real foreground window of this process: not KeyboardPadMode::Always over a terminal, nor a test's fake focus. 1785// 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) {
1812 } 1807 }
1813} 1808}
1814 1809
1815bool attach_keyboard_pad() { 1810struct KeyboardPadBackend {
1816 SDL_VirtualJoystickDesc d; 1811 static uint64_t now() { return now_us(); }
1817 SDL_INIT_INTERFACE(&d); 1812 static SDL_JoystickID attach() {
1818 d.type = SDL_JOYSTICK_TYPE_GAMEPAD; 1813 SDL_VirtualJoystickDesc d;
1819 d.naxes = SDL_GAMEPAD_AXIS_COUNT; 1814 SDL_INIT_INTERFACE(&d);
1820 d.nbuttons = SDL_GAMEPAD_BUTTON_COUNT; 1815 d.type = SDL_JOYSTICK_TYPE_GAMEPAD;
1821 d.button_mask = (1u << SDL_GAMEPAD_BUTTON_COUNT) - 1; 1816 d.naxes = SDL_GAMEPAD_AXIS_COUNT;
1822 d.axis_mask = (1u << SDL_GAMEPAD_AXIS_COUNT) - 1; 1817 d.nbuttons = SDL_GAMEPAD_BUTTON_COUNT;
1823 d.name = "Keyboard pad (Leonida)"; 1818 d.button_mask = (1u << SDL_GAMEPAD_BUTTON_COUNT) - 1;
1824 g_keyboard.id = SDL_AttachVirtualJoystick(&d); 1819 d.axis_mask = (1u << SDL_GAMEPAD_AXIS_COUNT) - 1;
1825 g_keyboard.js = g_keyboard.id ? SDL_OpenJoystick(g_keyboard.id) : nullptr; 1820 d.name = "Keyboard pad (Leonida)";
1826 if (!g_keyboard.js) { 1821 return SDL_AttachVirtualJoystick(&d);
1822 }
1823 static SDL_Joystick* open(SDL_JoystickID id) { return SDL_OpenJoystick(id); }
1824 static void close(SDL_Joystick* js) { SDL_CloseJoystick(js); }
1825 static bool detach(SDL_JoystickID id) { return SDL_DetachVirtualJoystick(id); }
1826 static bool is_virtual(SDL_JoystickID id) { return SDL_IsJoystickVirtual(id); }
1827 static void removed() { std::fprintf(stderr, "[rt] gameinput: keyboard pad removed\n"); }
1828 static void failed() {
1827 std::fprintf(stderr, "[rt] gameinput: cannot attach the keyboard pad: %s\n", SDL_GetError()); 1829 std::fprintf(stderr, "[rt] gameinput: cannot attach the keyboard pad: %s\n", SDL_GetError());
1828 detach_keyboard_pad();
1829 g_keyboard.failed = true;
1830 return false;
1831 } 1830 }
1832 std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, " 1831 static void attached() {
1833 "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left " 1832 std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, "
1834 "button LT/RT)\n"); 1833 "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left "
1835 start_raw_mouse(); 1834 "button LT/RT)\n");
1836 return true; 1835 start_raw_mouse();
1837} 1836 }
1837};
1838 1838
1839// Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading. 1839// Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading.
1840void update_keyboard_pad() { 1840void update_keyboard_pad() {
@@ -1845,13 +1845,14 @@ void update_keyboard_pad() {
1845 mode = g().config.keyboard_pad; 1845 mode = g().config.keyboard_pad;
1846 sens = g().config.mouse_sensitivity; 1846 sens = g().config.mouse_sensitivity;
1847 } 1847 }
1848 if (mode == rt::gameinput::KeyboardPadMode::Off) { 1848 KeyboardPadBackend backend;
1849 const bool enabled = mode != rt::gameinput::KeyboardPadMode::Off;
1850 if (!enabled) {
1849 clip_cursor(false); 1851 clip_cursor(false);
1850 if (g_keyboard.id) detach_keyboard_pad(); 1852 g_keyboard.right_x = g_keyboard.right_y = 0;
1851 g_keyboard.failed = false; 1853 g_keyboard.have_cursor = false;
1852 return;
1853 } 1854 }
1854 if (!g_keyboard.js && (g_keyboard.failed || !attach_keyboard_pad())) return; 1855 if (!g_keyboard.update(enabled, backend)) return;
1855 1856
1856 bool down[SDL_GAMEPAD_BUTTON_COUNT] = {}; 1857 bool down[SDL_GAMEPAD_BUTTON_COUNT] = {};
1857 int lx = 0, ly = 0; 1858 int lx = 0, ly = 0;
@@ -1901,7 +1902,26 @@ void update_keyboard_pad() {
1901 if (!scripted.empty()) { 1902 if (!scripted.empty()) {
1902 static const ULONGLONG origin = GetTickCount64(); 1903 static const ULONGLONG origin = GetTickCount64();
1903 const double now = (GetTickCount64() - origin) / 1000.0; 1904 const double now = (GetTickCount64() - origin) / 1000.0;
1904 const script::Held held = script::held_at(scripted, now); 1905 script::Held held{};
1906 static constexpr uint64_t kReads = 6;
1907 static constexpr double kMaxHold = 5.0;
1908 static std::vector<uint64_t> began(scripted.presses.size(), 0);
1909 static std::vector<char> started(scripted.presses.size(), 0);
1910 const uint64_t calls = g_reading_calls.load(std::memory_order_relaxed);
1911 for (std::size_t i = 0; i < scripted.presses.size(); ++i) {
1912 const auto& press = scripted.presses[i];
1913 bool active = false;
1914 if (now >= press.at && now < press.at + kMaxHold) {
1915 if (!started[i]) {
1916 started[i] = 1;
1917 began[i] = calls;
1918 }
1919 active = now < press.at + 0.3 || calls - began[i] < kReads;
1920 }
1921 if (!active) continue;
1922 if (press.stick) held.stick = press.stick;
1923 else held.buttons |= press.button;
1924 }
1905 if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down 1925 if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down
1906 for (const script::Button& b : script::kButtons) { 1926 for (const script::Button& b : script::kButtons) {
1907 if (!(scripted.named & b.bit)) continue; 1927 if (!(scripted.named & b.bit)) continue;
@@ -1959,6 +1979,10 @@ void poll_once() {
1959 SDL_JoystickID* ids = SDL_GetGamepads(&count); 1979 SDL_JoystickID* ids = SDL_GetGamepads(&count);
1960 std::vector<SDL_JoystickID> present(ids, ids + (ids ? count : 0)); 1980 std::vector<SDL_JoystickID> present(ids, ids + (ids ? count : 0));
1961 SDL_free(ids); 1981 SDL_free(ids);
1982 // An unopened virtual device may still be waiting for SDL to finish detaching it.
1983 // Do not advertise it to the title until it has a working keyboard handle.
1984 if (g_keyboard.id && !g_keyboard.js)
1985 present.erase(std::remove(present.begin(), present.end(), g_keyboard.id), present.end());
1962 1986
1963 std::vector<Device*> connected; 1987 std::vector<Device*> connected;
1964 { 1988 {
@@ -2411,7 +2435,75 @@ public:
2411 2435
2412 uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); } 2436 uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); }
2413 2437
2438 // LEONIDA_INPUT_STATS=1 (diagnostic): every 10 s, how the title asked for readings (by method and device
2439 // argument) and what it got (by the reading's device, and whether a gamepad button was down in it).
2440 static void note_reading(int method, IGameInputDevice* asked, HRESULT hr, IGameInputReading* got) {
2441 static const bool on = env("LEONIDA_INPUT_STATS") == "1";
2442 if (!on) return;
2443 struct Stats {
2444 std::mutex mu;
2445 uint64_t calls[3][3] = {}; // method x (null, aggregate, a device)
2446 uint64_t found[3] = {}, pressed[3] = {};
2447 std::map<std::string, std::pair<uint64_t, uint64_t>> by_device; // name -> (readings, with buttons)
2448 uint64_t since = 0;
2449 };
2450 static Stats st;
2451 std::string name;
2452 bool buttons = false;
2453 if (SUCCEEDED(hr) && got) {
2454 IGameInputDevice* d = nullptr;
2455 got->GetDevice(&d);
2456 if (d) {
2457 name = as_device(d)->name;
2458 d->Release();
2459 }
2460 GameInputGamepadState g{};
2461 if (got->GetGamepadState(&g)) buttons = g.buttons != 0;
2462 }
2463 const int arg = !asked ? 0 : as_device(asked)->info.deviceFamily == GameInputFamilyAggregate ? 1 : 2;
2464 std::lock_guard lock(st.mu);
2465 ++st.calls[method][arg];
2466 if (SUCCEEDED(hr) && got) {
2467 ++st.found[method];
2468 st.pressed[method] += buttons;
2469 auto& e = st.by_device[name];
2470 ++e.first;
2471 e.second += buttons;
2472 }
2473 const uint64_t now = now_us();
2474 if (!st.since) st.since = now;
2475 if (now - st.since < 10'000'000) return;
2476 static const char* methods[] = {"GetCurrentReading", "GetNextReading", "GetPreviousReading"};
2477 std::string line;
2478 for (int m = 0; m < 3; ++m) {
2479 char t[200];
2480 std::snprintf(t, sizeof(t), " %s %llu/%llu/%llu found %llu pressed %llu;", methods[m],
2481 (unsigned long long)st.calls[m][0], (unsigned long long)st.calls[m][1],
2482 (unsigned long long)st.calls[m][2], (unsigned long long)st.found[m],
2483 (unsigned long long)st.pressed[m]);
2484 line += t;
2485 }
2486 for (const auto& [n, c] : st.by_device) {
2487 char t[160];
2488 std::snprintf(t, sizeof(t), " [%s: %llu readings, %llu with buttons]", n.c_str(), (unsigned long long)c.first,
2489 (unsigned long long)c.second);
2490 line += t;
2491 }
2492 std::fprintf(stderr, "[rt] gameinput stats (calls null/aggregate/device): %s\n", line.c_str());
2493 std::memset(st.calls, 0, sizeof(st.calls));
2494 std::memset(st.found, 0, sizeof(st.found));
2495 std::memset(st.pressed, 0, sizeof(st.pressed));
2496 st.by_device.clear();
2497 st.since = now;
2498 }
2499
2414 HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override { 2500 HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override {
2501 g_reading_calls.fetch_add(1, std::memory_order_relaxed);
2502 const HRESULT hr = current_reading(kind, device, out);
2503 note_reading(0, device, hr, out ? *out : nullptr);
2504 return hr;
2505 }
2506 HRESULT current_reading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) {
2415 if (!out) return E_POINTER; 2507 if (!out) return E_POINTER;
2416 *out = nullptr; 2508 *out = nullptr;
2417 if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND; 2509 if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND;
@@ -2445,11 +2537,15 @@ public:
2445 2537
2446 HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, 2538 HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device,
2447 IGameInputReading** out) override { 2539 IGameInputReading** out) override {
2448 return find_reading(ref, kind, device, out, true); 2540 const HRESULT hr = find_reading(ref, kind, device, out, true);
2541 note_reading(1, device, hr, out ? *out : nullptr);
2542 return hr;
2449 } 2543 }
2450 HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, 2544 HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device,
2451 IGameInputReading** out) override { 2545 IGameInputReading** out) override {
2452 return find_reading(ref, kind, device, out, false); 2546 const HRESULT hr = find_reading(ref, kind, device, out, false);
2547 note_reading(2, device, hr, out ? *out : nullptr);
2548 return hr;
2453 } 2549 }
2454 // E_NOTIMPL is GameInput v0's own answer: Microsoft's reference page says the method "was never implemented in 2550 // E_NOTIMPL is GameInput v0's own answer: Microsoft's reference page says the method "was never implemented in
2455 // v0" and returns E_NOTIMPL, and v1 removed it. A history lookup here would give a title what no GameInput does. 2551 // 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 000000000..fff655f2a
--- /dev/null
+++ b/runtime/shims/keyboard_pad_connection.h
@@ -0,0 +1,67 @@
1#pragma once
2
3#include <cstdint>
4
5namespace rt::gameinput::detail {
6
7// Owned by the poll lock. Keep the virtual device ID until SDL confirms detachment;
8// a successful attach followed by a failed open still leaves a device to release.
9template <class Id, class Handle>
10struct KeyboardPadConnection {
11 Id id{};
12 Handle js{};
13
14 template <class Backend>
15 bool update(bool enabled, Backend& b) {
16 if (enabled != enabled_) {
17 enabled_ = enabled;
18 waiting_ = warned_ = false; // changing mode never waits for the previous mode's retry
19 }
20 if (enabled && js) return true;
21 if (!enabled && !id) return false;
22 if (waiting_ && b.now() - failed_at_ < 1'000'000) return false;
23
24 if (js) { // switching off a connected pad
25 b.close(js);
26 js = {};
27 }
28 if (id) { // switching off, or cleanup was incomplete on the previous poll
29 if (!release(b)) return wait(b);
30 if (announced_) b.removed();
31 announced_ = false;
32 }
33 if (!enabled) return false;
34
35 id = b.attach();
36 if (id) js = b.open(id);
37 if (!js) {
38 if (!warned_) b.failed(); // preserve the attach/open error before cleanup
39 warned_ = true;
40 if (id) release(b);
41 return wait(b);
42 }
43 waiting_ = warned_ = false;
44 announced_ = true;
45 b.attached();
46 return true;
47 }
48
49private:
50 template <class Backend>
51 bool release(Backend& b) {
52 // An already-removed ID also fails SDL_DetachVirtualJoystick. Retain only a still-live virtual device.
53 if (!b.detach(id) && b.is_virtual(id)) return false;
54 id = {};
55 return true;
56 }
57 template <class Backend>
58 bool wait(Backend& b) {
59 failed_at_ = b.now(); // measure from completion, not from the start of a slow attempt
60 waiting_ = true;
61 return false;
62 }
63 std::uint64_t failed_at_ = 0;
64 bool enabled_ = false, waiting_ = false, warned_ = false, announced_ = false;
65};
66
67} // namespace rt::gameinput::detail
diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h
index 6be16118b..9a5598129 100644
--- a/runtime/shims/startup_trace.h
+++ b/runtime/shims/startup_trace.h
@@ -7,12 +7,13 @@
7// {"seq":3,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false} 7// {"seq":3,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false}
8// {"seq":4,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1} 8// {"seq":4,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1}
9// {"seq":5,"t":0.002,"kind":"dllmain","module":"a.dll","result":1} 9// {"seq":5,"t":0.002,"kind":"dllmain","module":"a.dll","result":1}
10// {"seq":6,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only) 10// {"seq":6,"t":0.002,"kind":"delay_import_unimplemented","module":"a.dll","import":"x.dll!Bar"} (at load)
11// {"seq":7,"t":0.011,"kind":"debug_string","text":"..."} 11// {"seq":7,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only)
12// {"seq":8,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0", 12// {"seq":8,"t":0.011,"kind":"debug_string","text":"..."}
13// {"seq":9,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0",
13// "region":{"base":"0x0","allocation_base":"0x0","size":"0x7ffe0000","state":"0x10000","protect":"0x1", 14// "region":{"base":"0x0","allocation_base":"0x0","size":"0x7ffe0000","state":"0x10000","protect":"0x1",
14// "type":"0x0"},"regs":{...},"stack":["a.dll+0x4a00","a.dll+0x2210"]} 15// "type":"0x0"},"regs":{...},"stack":["a.dll+0x4a00","a.dll+0x2210"]}
15// {"seq":9,"t":0.030,"kind":"exit","code":0} 16// {"seq":10,"t":0.030,"kind":"exit","code":0}
16// 17//
17// The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process 18// The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process
18// does (except LEONIDA_SKIP_INT3, below). 19// does (except LEONIDA_SKIP_INT3, below).
@@ -23,7 +24,6 @@
23#pragma once 24#pragma once
24 25
25#include <windows.h> 26#include <windows.h>
26#include <set>
27 27
28#include <atomic> 28#include <atomic>
29#include <cerrno> 29#include <cerrno>
@@ -31,6 +31,7 @@
31#include <cstdint> 31#include <cstdint>
32#include <cstdio> 32#include <cstdio>
33#include <cstdlib> 33#include <cstdlib>
34#include <initializer_list>
34#include <mutex> 35#include <mutex>
35#include <string> 36#include <string>
36 37
@@ -39,13 +40,25 @@
39namespace rt::startup_trace { 40namespace rt::startup_trace {
40 41
41namespace detail { 42namespace detail {
42inline std::atomic<bool> on{false}; 43// What the exception handler touches lives at namespace scope and is constant-initialized: it exists before any code
43// Intentionally immortal: vectored exception handlers or late teardown paths can still run after normal statics would 44// runs, on every thread, and is never destroyed. A block-scope static is initialized on its first use, and that can be
44// have been destroyed. 45// on a title thread, where under Wine the MSVC thread-safe-static guard has been seen to pass while the object was
45inline std::mutex& mutex() { 46// still zero (old upstream 7599): LEONIDA_SKIP_INT3 stayed off and the int3 set and the trace lock were never
46 static auto* m = new std::mutex; 47// constructed.
47 return *m; 48inline constinit std::atomic<bool> on{false};
48} 49
50// The trace lock. An SRW lock needs no constructor or destructor, so vectored exception handlers and late teardown
51// paths can take it at any time, also after normal statics have been destroyed.
52class Lock {
53public:
54 void lock() noexcept { AcquireSRWLockExclusive(&srw_); }
55 void unlock() noexcept { ReleaseSRWLockExclusive(&srw_); }
56
57private:
58 SRWLOCK srw_ = SRWLOCK_INIT;
59};
60inline constinit Lock trace_lock{};
61inline Lock& mutex() noexcept { return trace_lock; }
49inline FILE* file = nullptr; 62inline FILE* file = nullptr;
50inline unsigned long long seq = 0; 63inline unsigned long long seq = 0;
51inline std::chrono::steady_clock::time_point start; 64inline std::chrono::steady_clock::time_point start;
@@ -165,8 +178,10 @@ inline std::string debug_text(const EXCEPTION_RECORD& r) {
165 return utf8_from_ansi(a, static_cast<int>(n ? n - 1 : strlen(a))); 178 return utf8_from_ansi(a, static_cast<int>(n ? n - 1 : strlen(a)));
166} 179}
167 180
168// LOCAL DIAGNOSTIC for one of the title's asserts (docs/re/answers.md, "transient pool"): at the int3 at 181// LOCAL DIAGNOSTIC for one of the title's asserts (docs/re/answers.md, "transient pool"): at that assert's int3
169// game+0x2473e88 the title has just computed the peak of a list of resources with lifetimes against a fixed pool. 182// the title has just computed the peak of a list of resources with lifetimes against a fixed pool. The int3's
183// location is measured locally and not kept here: LEONIDA_POOL_DIAG_AT names it as the trace prints it
184// (`<module>+0x<offset>`), and the dump is off without it.
170// rdi = the list (24-byte records: entry pointer, u32 size rounded to 64 KiB), r13 = the count, rax = the peak, 185// rdi = the list (24-byte records: entry pointer, u32 size rounded to 64 KiB), r13 = the count, rax = the peak,
171// rcx = the pool size. An entry is {record pointer, ..., u32 first pass at +16, u32 last pass at +20}; a record has 186// rcx = the pool size. An entry is {record pointer, ..., u32 first pass at +16, u32 last pass at +20}; a record has
172// its usage word at +14, kind word at +16 and, for a texture, width/height/depth words at +56/+58/+60, the dimension 187// its usage word at +14, kind word at +16 and, for a texture, width/height/depth words at +56/+58/+60, the dimension
@@ -202,8 +217,13 @@ inline void dump_transient_pool(const CONTEXT& c) {
202inline void log_exception(const EXCEPTION_POINTERS& info) { 217inline void log_exception(const EXCEPTION_POINTERS& info) {
203 const EXCEPTION_RECORD& r = *info.ExceptionRecord; 218 const EXCEPTION_RECORD& r = *info.ExceptionRecord;
204 try { 219 try {
205 if (r.ExceptionCode == EXCEPTION_BREAKPOINT && info.ContextRecord && 220 static const std::string pool_diag_at = [] {
206 where(reinterpret_cast<uint64_t>(r.ExceptionAddress)).ends_with("master.exe+0x2473e88")) 221 char at[128]{};
222 const DWORD n = GetEnvironmentVariableA("LEONIDA_POOL_DIAG_AT", at, sizeof(at));
223 return n && n < sizeof(at) ? std::string(at, n) : std::string();
224 }();
225 if (r.ExceptionCode == EXCEPTION_BREAKPOINT && info.ContextRecord && !pool_diag_at.empty() &&
226 where(reinterpret_cast<uint64_t>(r.ExceptionAddress)).ends_with(pool_diag_at))
207 dump_transient_pool(*info.ContextRecord); 227 dump_transient_pool(*info.ContextRecord);
208 if (r.ExceptionCode == kDbgPrint || r.ExceptionCode == kDbgPrintWide) { 228 if (r.ExceptionCode == kDbgPrint || r.ExceptionCode == kDbgPrintWide) {
209 const ULONG_PTR fallback = wide_fallback; 229 const ULONG_PTR fallback = wide_fallback;
@@ -269,20 +289,57 @@ inline void log_exception(const EXCEPTION_POINTERS& info) {
269// LEONIDA_SKIP_INT3 (diagnostic, with --trace): an int3 in guest code is logged once per address and stepped over, 289// LEONIDA_SKIP_INT3 (diagnostic, with --trace): an int3 in guest code is logged once per address and stepped over,
270// so a boot can be followed past the title's soft asserts (an int3 followed by code that carries on). Off by default: 290// so a boot can be followed past the title's soft asserts (an int3 followed by code that carries on). Off by default:
271// a console title never reaches one in a correct run, so each skipped address is a finding, not a fix. 291// a console title never reaches one in a correct run, so each skipped address is a finding, not a fix.
272inline bool skip_int3(EXCEPTION_POINTERS* info) { 292//
273 static const bool skip = GetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr, 0) != 0; 293// open() reads the variable, on the thread that opens the trace and before any guest code runs.
274 if (!skip || info->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT || !info->ContextRecord) return false; 294inline constinit std::atomic<bool> skip_int3_on{false};
275 const auto* at = static_cast<const unsigned char*>(info->ExceptionRecord->ExceptionAddress); 295inline bool skip_int3_requested() { return GetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr, 0) != 0; }
276 if (!at || *at != 0xCC || info->ContextRecord->Rip != reinterpret_cast<DWORD64>(at)) return false; 296
277 static std::mutex m; 297// The addresses already logged: an open-addressing table of atomics, so the handler needs no constructor, lock or
278 static std::set<const void*> seen; 298// allocation for it. When it is full, a site is logged again rather than lost.
279 bool first = false; 299constexpr size_t kInt3Sites = 4096; // a power of two: 12 bits of the hash below
280 { 300inline constinit std::atomic<const void*> int3_sites[kInt3Sites]{};
281 const std::lock_guard lock(m); 301
282 first = seen.insert(at).second; 302inline bool first_int3_at(const void* at) {
303 const auto key = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(at));
304 size_t i = static_cast<size_t>((key * 0x9E3779B97F4A7C15ull) >> 52);
305 for (size_t probe = 0; probe < kInt3Sites; ++probe, i = (i + 1) & (kInt3Sites - 1)) {
306 const void* seen = int3_sites[i].load(std::memory_order_acquire);
307 if (!seen && int3_sites[i].compare_exchange_strong(seen, at, std::memory_order_acq_rel)) return true;
308 if (seen == at) return false; // also when another thread has just claimed this slot for the same site
283 } 309 }
284 if (first) event("int3_skipped", "\"at\":" + quote(where(reinterpret_cast<uint64_t>(at)))); 310 return true;
285 info->ContextRecord->Rip += 1; 311}
312
313inline bool readable_byte(const unsigned char* p) {
314 MEMORY_BASIC_INFORMATION m{};
315 if (!p || VirtualQuery(p, &m, sizeof m) != sizeof m || m.State != MEM_COMMIT) return false;
316 return (m.Protect & (PAGE_NOACCESS | PAGE_GUARD)) == 0;
317}
318
319// The int3 (0xCC) a breakpoint stopped at, or null. Windows reports Rip and ExceptionAddress on the 0xCC byte, and so
320// did Wine 11.22 (Staging) in a probe here; Spacecer2's Wine 11.22 boot reported both one byte past it (old upstream
321// 7599). The candidate taken is the one ExceptionAddress agrees with (on it, or one byte before it), the byte at Rip
322// first, so the Windows form is handled as before. With Rip one past the 0xCC and ExceptionAddress on it, a run of
323// 0xCC bytes still gives the int3 ExceptionAddress names, not the one at Rip. When both name the byte after the int3
324// (the second form) and that byte is another 0xCC, the next int3 is taken, and stepped over with this one.
325inline const unsigned char* int3_from(const EXCEPTION_RECORD& r, const CONTEXT& c) {
326 const auto* rip = reinterpret_cast<const unsigned char*>(c.Rip);
327 const auto* address = static_cast<const unsigned char*>(r.ExceptionAddress);
328 if (!rip) return nullptr;
329 for (const unsigned char* at : {rip, rip - 1})
330 if ((address == at || address == at + 1) && readable_byte(at) && *at == 0xCC) return at;
331 return nullptr;
332}
333
334// With LEONIDA_SKIP_INT3, steps over an int3: Rip ends one byte past the 0xCC in either form.
335inline bool skip_int3(EXCEPTION_POINTERS* info) {
336 if (!skip_int3_on.load(std::memory_order_relaxed)) return false;
337 if (!info || !info->ExceptionRecord || !info->ContextRecord) return false;
338 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT) return false;
339 const unsigned char* at = int3_from(*info->ExceptionRecord, *info->ContextRecord);
340 if (!at) return false;
341 if (first_int3_at(at)) event("int3_skipped", "\"at\":" + quote(where(reinterpret_cast<uint64_t>(at))));
342 info->ContextRecord->Rip = reinterpret_cast<DWORD64>(at) + 1;
286 return true; 343 return true;
287} 344}
288 345
@@ -325,6 +382,7 @@ inline bool open(const wchar_t* path, int* error = nullptr) {
325 } 382 }
326 detail::start = std::chrono::steady_clock::now(); 383 detail::start = std::chrono::steady_clock::now();
327 detail::seq = 0; 384 detail::seq = 0;
385 detail::skip_int3_on.store(detail::skip_int3_requested(), std::memory_order_relaxed);
328 static const int atexit_registered = std::atexit(&close); 386 static const int atexit_registered = std::atexit(&close);
329 (void)atexit_registered; 387 (void)atexit_registered;
330 } 388 }
diff --git a/runtime/shims/title_hud.h b/runtime/shims/title_hud.h
new file mode 100644
index 000000000..160d769c4
--- /dev/null
+++ b/runtime/shims/title_hud.h
@@ -0,0 +1,194 @@
1#pragma once
2// LEONIDA_TITLE_HUD=1 shows live counters in the title bar of the window the title presents in:
3// frame rate and frame time from PresentX (average and worst frame of the last half second), or how long
4// since the last frame when there was none;
5// the process's private memory (its commit charge) and working set;
6// its GPU memory: in use and the budget over the device-local heaps, and in use in the other heaps, from the
7// device's VK_EXT_memory_budget; without it, DXGI's QueryVideoMemoryInfo (local and non-local segments), which
8// Wine leaves at 0; "n/a" when neither has a figure. Both memory figures and their text come from
9// src/memory_figures.h, which the dev overlay (src/dev_overlay.h) shows as well;
10// graphics and compute pipelines created, and the seconds spent in vkCreate*Pipelines in the last interval,
11// which is where an inline compile shows up as a hitch (needs LEONIDA_MEM_PROBE, src/mem_probe.h; else "-");
12// time since the first present.
13// The text is set from a thread of its own with SendMessageTimeout, so a busy or hung window thread never holds
14// the present path.
15
16#include <windows.h>
17#include <dxgi1_4.h>
18#include <psapi.h>
19#include <wrl/client.h>
20
21#include <algorithm>
22#include <atomic>
23#include <cstdint>
24#include <cstdio>
25#include <cstdlib>
26#include <cwchar>
27#include <functional>
28#include <string>
29#include <thread>
30#include <utility>
31
32#include "../src/mem_probe.h"
33#include "../src/memory_figures.h"
34
35namespace rt::d3d12_xs {
36
37class TitleHud {
38public:
39 static bool enabled() {
40 static const bool on = [] {
41 char v[2] = {};
42 return GetEnvironmentVariableA("LEONIDA_TITLE_HUD", v, sizeof v) == 1 && v[0] != '0';
43 }();
44 return on;
45 }
46
47 // The VRAM figure's source, called once per refresh on the HUD's thread. Empty: the figure the device publishes
48 // (memory_figures::latest_vram). A budget that is not available: DXGI's figures, else "n/a". Tests pass their own.
49 using VramSource = std::function<leonida::VramBudget()>;
50
51 explicit TitleHud(HWND window, VramSource vram = {}) : window_(window), vram_(std::move(vram)) {
52 QueryPerformanceFrequency(&frequency_);
53 stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
54 if (stop_) thread_ = std::thread([this] { run(); });
55 }
56 TitleHud(const TitleHud&) = delete;
57 TitleHud& operator=(const TitleHud&) = delete;
58 ~TitleHud() {
59 if (stop_) SetEvent(stop_);
60 if (thread_.joinable()) thread_.join();
61 if (stop_) CloseHandle(stop_);
62 }
63
64 // On every successful PresentX.
65 void note_present() {
66 LARGE_INTEGER now;
67 QueryPerformanceCounter(&now);
68 const std::int64_t previous = last_present_.exchange(now.QuadPart, std::memory_order_relaxed);
69 if (previous) {
70 const std::int64_t gap = now.QuadPart - previous;
71 std::int64_t worst = worst_gap_.load(std::memory_order_relaxed);
72 while (gap > worst && !worst_gap_.compare_exchange_weak(worst, gap, std::memory_order_relaxed)) {}
73 } else {
74 first_present_.store(now.QuadPart, std::memory_order_relaxed);
75 }
76 presents_.fetch_add(1, std::memory_order_relaxed);
77 }
78
79 // DXGI's figures as a budget. A local segment with no usage or no budget is how Wine's stub answers (a process
80 // that presents through a GPU always has some memory there), so that is not available rather than a 0.
81 static leonida::VramBudget dxgi_budget(const DXGI_QUERY_VIDEO_MEMORY_INFO& local,
82 const DXGI_QUERY_VIDEO_MEMORY_INFO& non_local) {
83 leonida::VramBudget out;
84 out.local_usage = local.CurrentUsage;
85 out.local_budget = local.Budget;
86 out.shared_usage = non_local.CurrentUsage;
87 out.available = local.CurrentUsage != 0 && local.Budget != 0;
88 return out;
89 }
90
91private:
92 static constexpr DWORD interval_ms = 500;
93
94 void run() {
95 Microsoft::WRL::ComPtr<IDXGIAdapter3> adapter = gpu_adapter();
96 std::uint64_t last_presents = 0, last_compile_ns = 0;
97 LARGE_INTEGER last;
98 QueryPerformanceCounter(&last);
99 while (WaitForSingleObject(stop_, interval_ms) == WAIT_TIMEOUT) {
100 if (!IsWindow(window_)) return;
101 LARGE_INTEGER now;
102 QueryPerformanceCounter(&now);
103 const double seconds = double(now.QuadPart - last.QuadPart) / double(frequency_.QuadPart);
104 last = now;
105 const std::uint64_t presents = presents_.load(std::memory_order_relaxed);
106 const std::uint64_t frames = presents - last_presents;
107 last_presents = presents;
108 const double worst_ms =
109 double(worst_gap_.exchange(0, std::memory_order_relaxed)) * 1000.0 / double(frequency_.QuadPart);
110 const double fps = seconds > 0 ? double(frames) / seconds : 0.0;
111 const double frame_ms = frames ? seconds * 1000.0 / double(frames) : 0.0;
112
113 namespace mf = leonida::memory_figures;
114 const std::wstring memory = widen(mf::ram_text(mf::process_memory()));
115 leonida::VramBudget vram = vram_ ? vram_() : mf::latest_vram();
116 DXGI_QUERY_VIDEO_MEMORY_INFO local{}, shared{};
117 if (!vram.available && adapter &&
118 SUCCEEDED(adapter->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &local)) &&
119 SUCCEEDED(adapter->QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &shared)))
120 vram = dxgi_budget(local, shared);
121 const std::wstring video = widen(mf::vram_text(vram));
122
123 wchar_t pipelines[128] = L"PSO -";
124 auto& probe = leonida::mem_probe::state();
125 if (probe.installed) {
126 std::uint64_t graphics, compute, ns;
127 {
128 std::lock_guard lock(probe.mutex);
129 graphics = probe.graphics_made;
130 compute = probe.compute_made;
131 ns = probe.graphics_ns + probe.compute_ns;
132 }
133 const double compiling = double(ns - last_compile_ns) / 1e9;
134 last_compile_ns = ns;
135 std::swprintf(pipelines, 128, L"PSO %llug %lluc, compiling %.1f s", (unsigned long long)graphics,
136 (unsigned long long)compute, compiling);
137 }
138
139 const std::int64_t first = first_present_.load(std::memory_order_relaxed);
140 const unsigned up = first ? unsigned((now.QuadPart - first) / frequency_.QuadPart) : 0;
141
142 // No present in this interval: how long since the last one, which tells a hang from a slow frame.
143 wchar_t frame[96];
144 const std::int64_t last_present = last_present_.load(std::memory_order_relaxed);
145 if (frames || !last_present)
146 std::swprintf(frame, 96, L"%.0f fps %.1f ms (worst %.0f)", fps, frame_ms, worst_ms);
147 else
148 std::swprintf(frame, 96, L"0 fps, no frame for %.1f s",
149 double(now.QuadPart - last_present) / double(frequency_.QuadPart));
150 wchar_t text[512];
151 std::swprintf(text, 512, L"Leonida | %ls | %ls | %ls | %ls | %u:%02u", frame, memory.c_str(),
152 video.c_str(), pipelines, up / 60, up % 60);
153 DWORD_PTR ignored = 0;
154 SendMessageTimeoutW(window_, WM_SETTEXT, 0, reinterpret_cast<LPARAM>(text), SMTO_ABORTIFHUNG,
155 interval_ms, &ignored);
156 }
157 }
158
159 // memory_figures' text is ASCII.
160 static std::wstring widen(const std::string& text) { return std::wstring(text.begin(), text.end()); }
161
162 // The hardware adapter with the most dedicated memory: the one LEONIDA_VK_DEVICE picks on a machine with a
163 // discrete GPU. The host's own dxgi.dll, not the title's shim.
164 static Microsoft::WRL::ComPtr<IDXGIAdapter3> gpu_adapter() {
165 using Create = HRESULT(WINAPI*)(REFIID, void**);
166 HMODULE dxgi = LoadLibraryW(L"dxgi.dll");
167 auto create = dxgi ? reinterpret_cast<Create>(GetProcAddress(dxgi, "CreateDXGIFactory1")) : nullptr;
168 Microsoft::WRL::ComPtr<IDXGIFactory1> factory;
169 Microsoft::WRL::ComPtr<IDXGIAdapter3> best;
170 if (!create || FAILED(create(IID_PPV_ARGS(&factory)))) return best;
171 SIZE_T most = 0;
172 Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter;
173 for (UINT i = 0; factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) {
174 DXGI_ADAPTER_DESC1 desc{};
175 if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue;
176 Microsoft::WRL::ComPtr<IDXGIAdapter3> three;
177 if (desc.DedicatedVideoMemory > most && SUCCEEDED(adapter.As(&three))) {
178 most = desc.DedicatedVideoMemory;
179 best = three;
180 }
181 }
182 return best;
183 }
184
185 HWND window_;
186 VramSource vram_;
187 HANDLE stop_ = nullptr;
188 std::thread thread_;
189 LARGE_INTEGER frequency_{};
190 std::atomic<std::int64_t> last_present_{0}, first_present_{0}, worst_gap_{0};
191 std::atomic<std::uint64_t> presents_{0};
192};
193
194} // namespace rt::d3d12_xs
diff --git a/runtime/shims/xbox_bvh_builder.cpp b/runtime/shims/xbox_bvh_builder.cpp
index 8c80419e2..ad6d6810a 100644
--- a/runtime/shims/xbox_bvh_builder.cpp
+++ b/runtime/shims/xbox_bvh_builder.cpp
@@ -28,8 +28,13 @@
28// - The DLL throws its validation errors as C++ exceptions (docs/xdxr.md, "Errors are thrown, not returned"). A 28// - The DLL throws its validation errors as C++ exceptions (docs/xdxr.md, "Errors are thrown, not returned"). A
29// shim must not throw into the title, so an element the DLL would reject is logged and skipped instead. The one 29// shim must not throw into the title, so an element the DLL would reject is logged and skipped instead. The one
30// rule a correct title meets every time is kept: the offline-statistics postbuild type (0x10) is never written. 30// rule a correct title meets every time is kept: the offline-statistics postbuild type (0x10) is never written.
31// - Rehydration is not implemented yet: RehydrateRaytracingAccelerationStructureBatched2X logs once and returns 31// - Rehydration: RehydrateRaytracingAccelerationStructureBatched2X rebuilds each structure from the source
32// E_NOTIMPL. (Planned: rebuild each structure from the source geometry its description carries.) 32// geometry its description carries (BuildRaytracingAccelerationStructure) (docs/bvh.md §4a). The leaf frame
33// compressionParams gives is not applied yet: the leaves are built from the geometry as the description has it.
34// The GPU cannot read offline dehydrated console streams directly (docs/bvh.md §4/§4a),
35// so source-only streams without geometry are refused with E_NOTIMPL. The title passes Scratch = 0, so the shim
36// supplies scratch: one buffer per call, sized via GetRaytracingAccelerationStructurePrebuildInfo, in which each
37// element has a region of its own (rehydrate_scratch).
33// 38//
34// The builder object belongs to the title, which allocates it with a size this file doesn't know, so nothing is 39// The builder object belongs to the title, which allocates it with a size this file doesn't know, so nothing is
35// written into it: what the shim keeps (the device, the Morton option) lives in a table keyed by its address. 40// written into it: what the shim keeps (the device, the Morton option) lives in a table keyed by its address.
@@ -47,7 +52,11 @@
47#include <cstring> 52#include <cstring>
48#include <mutex> 53#include <mutex>
49#include <unordered_map> 54#include <unordered_map>
55#include <vector>
50 56
57#ifdef LEONIDA_VULKAN_DEVICE
58#include "d3d12_com.h" // rt::d3d12::hold_until_reset
59#endif
51#include "d3d12_xs_device.h" 60#include "d3d12_xs_device.h"
52#include "shims.h" 61#include "shims.h"
53#include "../src/xdxr_descs.h" 62#include "../src/xdxr_descs.h"
@@ -59,8 +68,18 @@ namespace xdxr = leonida::xdxr;
59struct BuilderState { 68struct BuilderState {
60 ID3D12Device5* device = nullptr; // a reference held for the builder's lifetime; null if it has no DXR methods 69 ID3D12Device5* device = nullptr; // a reference held for the builder's lifetime; null if it has no DXR methods
61 bool morton64 = false; 70 bool morton64 = false;
71 // Rehydration scratch made for a list that cannot hold it (not the layer's own, rehydrate_scratch): kept until the
72 // builder is destroyed, since the shim never learns when the GPU is done with it.
73 std::vector<ID3D12Resource*> kept;
62}; 74};
63 75
76void release_state(BuilderState& state) {
77 for (ID3D12Resource* scratch : state.kept) scratch->Release();
78 state.kept.clear();
79 if (state.device) state.device->Release();
80 state.device = nullptr;
81}
82
64std::mutex g_mutex; 83std::mutex g_mutex;
65std::unordered_map<const void*, BuilderState> g_builders; 84std::unordered_map<const void*, BuilderState> g_builders;
66 85
@@ -107,8 +126,8 @@ void* builder_construct(void* self, void* device, bool) {
107 } 126 }
108 std::lock_guard<std::mutex> lock(g_mutex); 127 std::lock_guard<std::mutex> lock(g_mutex);
109 BuilderState& state = g_builders[self]; 128 BuilderState& state = g_builders[self];
110 if (state.device) state.device->Release(); // the same storage constructed twice without a destructor 129 release_state(state); // the same storage constructed twice without a destructor
111 state = BuilderState{device5, false}; 130 state = BuilderState{device5, false, {}};
112 return self; 131 return self;
113} 132}
114 133
@@ -117,7 +136,7 @@ void builder_destruct(void* self) {
117 std::lock_guard<std::mutex> lock(g_mutex); 136 std::lock_guard<std::mutex> lock(g_mutex);
118 auto it = g_builders.find(self); 137 auto it = g_builders.find(self);
119 if (it == g_builders.end()) return; 138 if (it == g_builders.end()) return;
120 if (it->second.device) it->second.device->Release(); 139 release_state(it->second);
121 g_builders.erase(it); 140 g_builders.erase(it);
122} 141}
123 142
@@ -138,6 +157,63 @@ ID3D12Device5* builder_device(void* self) {
138 return it->second.device; 157 return it->second.device;
139} 158}
140 159
160// Scratch for one RehydrateRaytracingAccelerationStructureBatched2X call, where the title passes
161// ScratchAccelerationStructureData = 0 (measured on the retail title): a new buffer of `bytes`, in which each element
162// that needs scratch has a region of its own. It is never shared with another call: two calls on one list (the title
163// puts no barrier between them for scratch it does not know of) or lists recorded on several threads never write the
164// same bytes. The list holds the buffer until it is Reset or released (rt::d3d12::hold_until_reset), and the layer
165// destroys it after the submission that used it has retired; a list that cannot hold it leaves it to the builder,
166// which keeps it until its destruction. Returns the buffer's GPU address, 0 when it could not be made.
167UINT64 rehydrate_scratch(void* self, ID3D12Device5* device, ID3D12GraphicsCommandList4* list, UINT64 bytes) {
168 if (!device || !bytes) return 0;
169 D3D12_HEAP_PROPERTIES heap_props{};
170 heap_props.Type = D3D12_HEAP_TYPE_DEFAULT;
171 D3D12_RESOURCE_DESC res_desc{};
172 res_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
173 res_desc.Alignment = 0;
174 res_desc.Width = bytes;
175 res_desc.Height = 1;
176 res_desc.DepthOrArraySize = 1;
177 res_desc.MipLevels = 1;
178 res_desc.Format = DXGI_FORMAT_UNKNOWN;
179 res_desc.SampleDesc.Count = 1;
180 res_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
181 res_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
182
183 ID3D12Resource* res = nullptr;
184 HRESULT hr = device->CreateCommittedResource(
185 &heap_props, D3D12_HEAP_FLAG_NONE, &res_desc,
186 D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
187 IID_PPV_ARGS(&res));
188 if (FAILED(hr) || !res) return 0;
189 const UINT64 va = res->GetGPUVirtualAddress();
190 bool held = false;
191#ifdef LEONIDA_VULKAN_DEVICE
192 held = rt::d3d12::hold_until_reset(list, res);
193#else
194 (void)list;
195#endif
196 if (held) {
197 res->Release(); // the list's reference keeps it from here
198 return va;
199 }
200 static std::atomic<bool> s_logged{false};
201 log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X: the list cannot hold its scratch; the "
202 "builder keeps it until it is destroyed");
203 std::lock_guard<std::mutex> lock(g_mutex);
204 auto it = g_builders.find(self);
205 if (it == g_builders.end()) { // destroyed during the call: nothing is recorded with this scratch
206 res->Release();
207 return 0;
208 }
209 it->second.kept.push_back(res);
210 return va;
211}
212
213bool has_geometry(const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS& inputs) {
214 return inputs.NumDescs > 0 && (inputs.pGeometryDescs || inputs.InstanceDescs);
215}
216
141void note_stream(const xdxr::StreamDesc& stream) { 217void note_stream(const xdxr::StreamDesc& stream) {
142 if (stream.size_in_bytes == 0 || !stream.stream) return; 218 if (stream.size_in_bytes == 0 || !stream.stream) return;
143 static std::atomic<bool> s_logged{false}; 219 static std::atomic<bool> s_logged{false};
@@ -227,12 +303,102 @@ void builder_copy(void*, void* list, UINT64 dest, UINT64 source, D3D12_RAYTRACIN
227} 303}
228 304
229// ?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_ 305// ?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_
230// BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z -> HRESULT. Not implemented yet (see the header comment). 306// BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z -> HRESULT.
231HRESULT builder_rehydrate_batched2x(void*, void*, UINT, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*, 307// Rebuilds each acceleration structure from geometry on the command list.
232 const UINT64*) { 308HRESULT builder_rehydrate_batched2x(void* self, void* list, UINT count,
233 static std::atomic<bool> s_logged{false}; 309 const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* descs,
234 log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X is not implemented yet; E_NOTIMPL"); 310 const UINT64* source_data) {
235 return E_NOTIMPL; 311 if (count == 0) return S_OK;
312 if (!descs) return E_INVALIDARG;
313 if (!list) return E_INVALIDARG;
314 ID3D12GraphicsCommandList4* list4 = list4_of(list);
315 if (!list4) {
316 static std::atomic<bool> s_logged{false};
317 log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X: the list has no ID3D12GraphicsCommandList4");
318 return E_NOINTERFACE;
319 }
320 ID3D12Device5* device = builder_device(self);
321 // First pass: the descriptions as they are recorded, and for each element that builds without scratch of the
322 // title's a region of its own in one scratch buffer for the batch, at D3D12's acceleration-structure alignment
323 // (256 bytes, which the layer checks scratch addresses against). The XDXR recorder leaves the dependency between
324 // builds to the caller's barrier (src/xdxr_build.h, dispatch()) and the title puts none between the elements of
325 // a batch, so elements must not share scratch bytes. The first source-only element ends the batch (below).
326 constexpr UINT64 kAlign = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT;
327 constexpr UINT64 kNoRegion = ~0ull;
328 std::vector<D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC> builds;
329 std::vector<UINT64> regions;
330 builds.reserve(count);
331 regions.reserve(count);
332 UINT64 scratch_bytes = 0;
333 bool source_only = false;
334 for (UINT i = 0; i < count; ++i) {
335 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC build = descs[i];
336 const UINT64 src = source_data ? source_data[i] : build.SourceAccelerationStructureData;
337 // A rehydrate is a fresh build from geometry. The title sets SourceAccelerationStructureData to the
338 // dehydrated stream (measured on the retail title), and the layer reads that address for an update
339 // (d3d12_com.cpp, BuildRaytracingAccelerationStructure), so with PERFORM_UPDATE kept it would refit from
340 // the stream's bytes. Both are cleared.
341 if (build.Inputs.Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE) {
342 static std::atomic<bool> s_update_logged{false};
343 log_once(s_update_logged,
344 "RehydrateRaytracingAccelerationStructureBatched2X: an element asks for PERFORM_UPDATE; it is "
345 "built afresh from its geometry instead (the source is the dehydrated stream)");
346 build.Inputs.Flags &= ~D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE;
347 }
348 build.SourceAccelerationStructureData = 0;
349 UINT64 region = kNoRegion;
350 if (has_geometry(build.Inputs)) {
351 if (!build.ScratchAccelerationStructureData && device) {
352 D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO prebuild{};
353 device->GetRaytracingAccelerationStructurePrebuildInfo(&build.Inputs, &prebuild);
354 const UINT64 size = prebuild.ScratchDataSizeInBytes ? prebuild.ScratchDataSizeInBytes : 1;
355 region = scratch_bytes;
356 scratch_bytes += (size + kAlign - 1) / kAlign * kAlign;
357 }
358 } else if (src) {
359 source_only = true;
360 break;
361 }
362 builds.push_back(build);
363 regions.push_back(region);
364 }
365 const UINT64 scratch = scratch_bytes ? rehydrate_scratch(self, device, list4, scratch_bytes) : 0;
366
367 for (std::size_t i = 0; i < builds.size(); ++i) {
368 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC& build = builds[i];
369 if (has_geometry(build.Inputs)) {
370 // The title passes ScratchAccelerationStructureData = 0 (measured on the retail title).
371 // Supply a scratch region to prevent d3d12_com.cpp from poisoning the command list.
372 if (regions[i] != kNoRegion && scratch) build.ScratchAccelerationStructureData = scratch + regions[i];
373 if (!build.ScratchAccelerationStructureData) {
374 static std::atomic<bool> s_scratch_logged{false};
375 log_once(s_scratch_logged,
376 "RehydrateRaytracingAccelerationStructureBatched2X: ScratchAccelerationStructureData is 0 "
377 "and could not be allocated; skipping build to avoid command list rejection");
378 continue;
379 }
380 list4->BuildRaytracingAccelerationStructure(&build, 0, nullptr);
381 } else {
382 static std::atomic<bool> s_empty_logged{false};
383 log_once(s_empty_logged,
384 "RehydrateRaytracingAccelerationStructureBatched2X: element has NumDescs == 0 with no geometry; "
385 "skipping empty structure");
386 }
387 }
388 if (source_only) {
389 // docs/bvh.md §4/§4a: the rehydrate source is a dehydrated console stream (element chunks,
390 // level table, box overrides), not a D3D12 serialized blob. On the XDXR path, a DESERIALIZE
391 // copy is replayed as a byte clone, so the destination would hold dehydrated bytes the GPU
392 // traversal shaders cannot read. Rehydration requires geometry reconstruction (docs/bvh.md §4a).
393 // Refusing source-only rehydration without geometry.
394 static std::atomic<bool> s_source_only_logged{false};
395 log_once(s_source_only_logged,
396 "RehydrateRaytracingAccelerationStructureBatched2X: source-only dehydrated stream without "
397 "geometry cannot be deserialized as a D3D12 BLAS (docs/bvh.md §4/§4a); refusing element");
398 }
399 if (device) device->Release();
400 list4->Release();
401 return source_only ? E_NOTIMPL : S_OK;
236} 402}
237 403
238constexpr const char kDll[] = "xboxbvhbuilder.dll"; 404constexpr const char kDll[] = "xboxbvhbuilder.dll";
diff --git a/runtime/shims/xg_xs.cpp b/runtime/shims/xg_xs.cpp
index 7a9066d5d..891ba0ec9 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) {
747 } 747 }
748 } 748 }
749 trace_desc(calls, "create", _ReturnAddress(), desc ? &d : nullptr, out, 0, hr, t.mode, t.layout.size); 749 trace_desc(calls, "create", _ReturnAddress(), desc ? &d : nullptr, out, 0, hr, t.mode, t.layout.size);
750 // A refused computer is not harmless: the title's texture lock reads the layout it would have written
751 // without checking, so say which descriptions are refused (at most 32 lines).
752 static std::atomic<unsigned> refused{0};
753 if (desc && FAILED(hr) && refused.fetch_add(1, std::memory_order_relaxed) < 32)
754 std::fprintf(stderr,
755 "[rt] xg_xs: XGCreateTextureComputer refuses dim=%u %llux%ux%u mips=%u fmt=%u samples=%u "
756 "layout=%#x flags=%#x (hr 0x%08x), caller %s\n",
757 d.dimension, static_cast<unsigned long long>(d.width), d.height, unsigned(d.depth_or_array),
758 unsigned(d.mips), d.format, d.samples, d.layout, d.flags, uint32_t(hr),
759 rt::shims::module_offset(reinterpret_cast<uint64_t>(_ReturnAddress())).c_str());
750 // LOCAL DIAGNOSTIC: LEONIDA_XG_TRACE_FORMAT=<DXGI format> logs the first 256 computers of that format whatever 760 // LOCAL DIAGNOSTIC: LEONIDA_XG_TRACE_FORMAT=<DXGI format> logs the first 256 computers of that format whatever
751 // LEONIDA_XG_TRACE's cap, with the layout the title asked for (which tiling its CPU writes use). 761 // LEONIDA_XG_TRACE's cap, with the layout the title asked for (which tiling its CPU writes use).
752 static const uint32_t only = [] { 762 static const uint32_t only = [] {
diff --git a/runtime/shims/xg_xs_layout.h b/runtime/shims/xg_xs_layout.h
index 36d6c0db3..939c9e892 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) {
114// contracts by floor division, while physical pitch/height use ShiftCeil on 114// contracts by floor division, while physical pitch/height use ShiftCeil on
115// the base extent in elements. A slice stores the tail block, then its 115// the base extent in elements. A slice stores the tail block, then its
116// unpacked mips from smallest to largest. 116// unpacked mips from smallest to largest.
117//
118// A render-target or depth-stencil flag only matters when the layout word
119// leaves the mode to XG (select_mode then picks a Z/R mode this model lacks);
120// with an explicit mode the layout is that mode's, as on the console.
121//
122// A linear 3D texture is thin (addrlib's HwlComputeSurfaceInfoLinear): every
123// depth slice holds the whole mip chain, rows aligned to 256 bytes, so the
124// slices are plane.slice_bytes apart and a mip's size spans all its slices.
117inline bool build_texture(const ResourceDesc& desc, Texture& texture) { 125inline bool build_texture(const ResourceDesc& desc, Texture& texture) {
118 // Exposure readback uses the explicit linear Series layout, including the 126 // Exposure readback uses the explicit linear Series layout, including the
119 // console flag set by its render-target descriptor builder. 127 // console flag set by its render-target descriptor builder.
@@ -145,8 +153,12 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) {
145 default: return false; 153 default: return false;
146 } 154 }
147 const bool volume = desc.dimension == kTexture3D; 155 const bool volume = desc.dimension == kTexture3D;
148 if (volume && mode != k4kbS) return false; 156 if (volume && mode != k4kbS && mode != kLinear) return false;
149 if (volume && (mips != 1 || format.side != 1)) { 157 // Linear 3D is measured with one mip only (256-byte rows, slice after slice). Whether a linear 3D chain is laid
158 // out slice-major or mip-major is not measured, and the two put mips 1+ at different offsets: refused, as before.
159 if (volume && mode == kLinear && mips > 1) return false;
160 const bool thick = volume && mode != kLinear; // GFX10 3D S modes: blocks span tile_depth slices
161 if (thick && (mips != 1 || format.side != 1)) {
150 static const bool enabled = [] { 162 static const bool enabled = [] {
151 const char* value = std::getenv("LEONIDA_VOLUME_MIPS"); 163 const char* value = std::getenv("LEONIDA_VOLUME_MIPS");
152 return !value || std::strcmp(value, "0") != 0; 164 return !value || std::strcmp(value, "0") != 0;
@@ -169,7 +181,7 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) {
169 texture.tile_width = tw; 181 texture.tile_width = tw;
170 texture.tile_height = th; 182 texture.tile_height = th;
171 texture.array = volume ? 1u : desc.depth_or_array; 183 texture.array = volume ? 1u : desc.depth_or_array;
172 if (volume) { 184 if (thick) {
173 // Dimensions in elements (4x4 blocks for BC formats). 185 // Dimensions in elements (4x4 blocks for BC formats).
174 constexpr uint32_t blocks[5][3] = {{16, 16, 16}, {8, 16, 16}, {8, 16, 8}, {8, 8, 8}, {4, 8, 8}}; 186 constexpr uint32_t blocks[5][3] = {{16, 16, 16}, {8, 16, 16}, {8, 16, 8}, {8, 8, 8}, {4, 8, 8}};
175 texture.tile_width = tw = blocks[element_bits][0]; 187 texture.tile_width = tw = blocks[element_bits][0];
@@ -189,11 +201,11 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) {
189 plane.standard_mips = mips; 201 plane.standard_mips = mips;
190 // AMD addrlib Gfx10Lib::ComputeSurfaceInfoMacroTiled and Lib::GetMipTailDim. 202 // AMD addrlib Gfx10Lib::ComputeSurfaceInfoMacroTiled and Lib::GetMipTailDim.
191 // A 4 KiB thick block has five tail levels and halves height. BC extents are in blocks. 203 // A 4 KiB thick block has five tail levels and halves height. BC extents are in blocks.
192 const unsigned max_tail = volume ? 5u : tile_bits - 4; 204 const unsigned max_tail = thick ? 5u : tile_bits - 4;
193 uint32_t tail_w = volume ? tw : tw / 2, tail_h = volume ? th / 2 : th; 205 uint32_t tail_w = thick ? tw : tw / 2, tail_h = thick ? th / 2 : th;
194 constexpr uint32_t micro3d[5][3] = {{8,4,8}, {4,4,8}, {4,4,4}, {4,2,4}, {2,2,4}}; 206 constexpr uint32_t micro3d[5][3] = {{8,4,8}, {4,4,8}, {4,4,4}, {4,2,4}, {2,2,4}};
195 const uint32_t micro_w = volume ? micro3d[element_bits][0] : 1u << ((8 - element_bits + 1) / 2); 207 const uint32_t micro_w = thick ? micro3d[element_bits][0] : 1u << ((8 - element_bits + 1) / 2);
196 const uint32_t micro_h = volume ? micro3d[element_bits][1] : 256 / (format.bytes * micro_w); 208 const uint32_t micro_h = thick ? micro3d[element_bits][1] : 256 / (format.bytes * micro_w);
197 uint32_t tail_depth = 0; 209 uint32_t tail_depth = 0;
198 210
199 uint64_t chain_bytes = 0; 211 uint64_t chain_bytes = 0;
@@ -222,7 +234,7 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) {
222 if (mip.in_tail) { 234 if (mip.in_tail) {
223 const unsigned index = max_tail - 1 - (i - plane.standard_mips); 235 const unsigned index = max_tail - 1 - (i - plane.standard_mips);
224 mip.offset = index > 6 ? 16u << index : index * 256u; 236 mip.offset = index > 6 ? 16u << index : index * 256u;
225 if (volume) { 237 if (thick) {
226 texture.volume_mips[i].tail_x = ((index >> 1) & 1u) * micro_w; 238 texture.volume_mips[i].tail_x = ((index >> 1) & 1u) * micro_w;
227 texture.volume_mips[i].tail_y = ((index & 1u) | ((index >> 1) & 2u)) * micro_h; 239 texture.volume_mips[i].tail_y = ((index & 1u) | ((index >> 1) & 2u)) * micro_h;
228 mip.offset *= align_up(tail_depth, micro3d[element_bits][2]) / micro3d[element_bits][2]; 240 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) {
244 mip.slice_bytes = uint64_t(mip.pitch_bytes) * mip.padded_height; 256 mip.slice_bytes = uint64_t(mip.pitch_bytes) * mip.padded_height;
245 mip.size = mip.slice_bytes * (volume ? mip.padded_depth : 1u); 257 mip.size = mip.slice_bytes * (volume ? mip.padded_depth : 1u);
246 } 258 }
247 if (volume) { 259 if (thick) {
248 uint64_t macro = chain_bytes; 260 uint64_t macro = chain_bytes;
249 chain_bytes *= align_up(tail_depth, texture.tile_depth) / texture.tile_depth; 261 chain_bytes *= align_up(tail_depth, texture.tile_depth) / texture.tile_depth;
250 for (unsigned i = plane.standard_mips; i > 0; --i) { 262 for (unsigned i = plane.standard_mips; i > 0; --i) {
@@ -262,10 +274,10 @@ inline bool build_texture(const ResourceDesc& desc, Texture& texture) {
262 for (unsigned i = plane.standard_mips; i > 0; --i) { 274 for (unsigned i = plane.standard_mips; i > 0; --i) {
263 auto& mip = plane.mips[i - 1]; 275 auto& mip = plane.mips[i - 1];
264 mip.offset = chain_bytes; 276 mip.offset = chain_bytes;
265 chain_bytes += mip.size; 277 chain_bytes += mip.slice_bytes; // one slice's share: a linear 3D mip's size spans every depth slice
266 } 278 }
267 plane.slice_bytes = chain_bytes; 279 plane.slice_bytes = chain_bytes;
268 plane.size = layout.size = chain_bytes * texture.array; 280 plane.size = layout.size = chain_bytes * (volume ? desc.depth_or_array : texture.array);
269 return true; 281 return true;
270} 282}
271 283
diff --git a/runtime/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp
index 3a5be5520..1a59d4212 100644
--- a/runtime/shims/xgameruntime_offline.cpp
+++ b/runtime/shims/xgameruntime_offline.cpp
@@ -107,15 +107,23 @@ constexpr char kEventName[] = "XGameEventImpl";
107constexpr GUID kEventClass = {0xbbfbdcc7, 0xbfe7, 0x409b, {0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d}}; 107constexpr GUID kEventClass = {0xbbfbdcc7, 0xbfe7, 0x409b, {0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d}};
108std::atomic<long> g_events{0}; 108std::atomic<long> g_events{0};
109 109
110bool log_every_event() { 110// "=1" exactly. Read on the first call, which is on a title thread: the answer is kept in a namespace-scope atomic, not
111 static const bool on = [] { 111// a block-scope static, whose guard has been seen to skip the initializer on such a thread under Wine (old upstream
112// 7599).
113bool env_is_one(const char* name, std::atomic<int>& cached) {
114 int on = cached.load(std::memory_order_relaxed);
115 if (on < 0) {
112 char value[4] = {}; 116 char value[4] = {};
113 size_t length = 0; 117 size_t length = 0;
114 return getenv_s(&length, value, "LEONIDA_LOG_GAME_EVENTS") == 0 && length == 2 && value[0] == '1'; 118 on = getenv_s(&length, value, name) == 0 && length == 2 && value[0] == '1';
115 }(); 119 cached.store(on, std::memory_order_relaxed);
116 return on; 120 }
121 return on != 0;
117} 122}
118 123
124std::atomic<int> g_log_every_event{-1};
125bool log_every_event() { return env_is_one("LEONIDA_LOG_GAME_EVENTS", g_log_every_event); }
126
119// 3: HRESULT XGameEventWrite(XUserHandle user, const char* serviceConfigId, const char* playSessionId, 127// 3: HRESULT XGameEventWrite(XUserHandle user, const char* serviceConfigId, const char* playSessionId,
120// const char* eventName, const char* dimensionsJson, const char* measurementsJson) 128// const char* eventName, const char* dimensionsJson, const char* measurementsJson)
121HRESULT STDMETHODCALLTYPE event_write(void*, XUserHandle, const char*, const char*, const char* name, 129HRESULT STDMETHODCALLTYPE event_write(void*, XUserHandle, const char*, const char*, const char* name,
@@ -399,14 +407,8 @@ struct XDisplayHdrModeInfo {
399 float maxFullFrameToneMapLuminance; 407 float maxFullFrameToneMapLuminance;
400}; 408};
401 409
402bool hdr_requested() { 410std::atomic<int> g_hdr_requested{-1};
403 static const bool on = [] { 411bool hdr_requested() { return env_is_one("LEONIDA_HDR", g_hdr_requested); }
404 char value[4] = {};
405 size_t length = 0;
406 return getenv_s(&length, value, "LEONIDA_HDR") == 0 && length == 2 && value[0] == '1';
407 }();
408 return on;
409}
410 412
411// 4: XDisplayHdrModeResult XDisplayTryEnableHdrMode(XDisplayHdrModePreference preference, XDisplayHdrModeInfo* info) 413// 4: XDisplayHdrModeResult XDisplayTryEnableHdrMode(XDisplayHdrModePreference preference, XDisplayHdrModeInfo* info)
412// The host swapchain is SDR, so HDR stays off unless LEONIDA_HDR=1; then it is "enabled" with the documented 414// The host swapchain is SDR, so HDR stays off unless LEONIDA_HDR=1; then it is "enabled" with the documented
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index 40bc28f2a..384f7bd27 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
78 rt::startup_trace::event("xmem_attributes", fields); 78 rt::startup_trace::event("xmem_attributes", fields);
79} 79}
80 80
81// LEONIDA_TITLE_HEAP=1: the title's XMemAlloc blocks come from a heap of their own instead of the CRT heap. Slot-133 81// The title's XMemAlloc blocks come from a heap of their own instead of the CRT heap (LEONIDA_TITLE_HEAP=0: not). Slot-133
82// imports pin title memory page by page for the GPU, and on the CRT heap a pinned page also holds the runtime's own 82// imports pin title memory page by page for the GPU, and on the CRT heap a pinned page also holds the runtime's own
83// objects (g_pages' nodes among them): a GPU store past a buffer's end, or into a block freed while its import still 83// objects (g_pages' nodes among them): a GPU store past a buffer's end, or into a block freed while its import still
84// lived, then corrupted the runtime (speed-30/41/49-52: g_pages found corrupt under g_phys_mutex). Each block keeps its 84// 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 {
89}; 89};
90HANDLE title_heap() { 90HANDLE title_heap() {
91 static const HANDLE heap = [] { 91 static const HANDLE heap = [] {
92 // Set LEONIDA_TITLE_HEAP=0 to use the CRT heap.
92 const char* v = std::getenv("LEONIDA_TITLE_HEAP"); 93 const char* v = std::getenv("LEONIDA_TITLE_HEAP");
93 if (!v || std::strcmp(v, "1") != 0) return HANDLE(nullptr); 94 if (v && std::strcmp(v, "0") == 0) return HANDLE(nullptr);
94 const HANDLE h = HeapCreate(0, 0, 0); 95 const HANDLE h = HeapCreate(0, 0, 0);
95 std::fprintf(stderr, "[rt] xmem: XMemAlloc blocks come from a heap of their own (%p)\n", h); 96 std::fprintf(stderr, "[rt] xmem: XMemAlloc blocks come from a heap of their own (%p)\n", h);
96 return h; 97 return h;
@@ -145,7 +146,12 @@ void free_title_block(void* p) {
145 if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast<uintptr_t>(p)); 146 if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast<uintptr_t>(p));
146 const size_t size = block_size(p); 147 const size_t size = block_size(p);
147 free_block(p); 148 free_block(p);
148 if (p) leonida::title_memory_map::changed(p, size ? size : 1); 149 if (p) {
150 const auto from = reinterpret_cast<uintptr_t>(p);
151 const size_t bytes = size ? size : 1;
152 leonida::title_memory_map::changed(p, bytes);
153 leonida::geometry_writes::note_released(from, from + bytes);
154 }
149} 155}
150 156
151void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { 157void* __stdcall XMemAlloc(size_t size, uint64_t attributes) {
@@ -391,7 +397,7 @@ uintptr_t stream_cpu, stream_gpu, stream_size;
391bool mirror_stream; 397bool mirror_stream;
392leonida::host_heap::map<uintptr_t, Window> stream_offsets; 398leonida::host_heap::map<uintptr_t, Window> stream_offsets;
393std::mutex g_phys_mutex; 399std::mutex g_phys_mutex;
394std::map<uintptr_t, Window> g_windows; // base -> window 400leonida::host_heap::map<uintptr_t, Window> g_windows; // base -> window (host_heap: see g_pages)
395// The same table for the fault handler, which may not wait for g_phys_mutex: a holder of that mutex allocates 401// The same table for the fault handler, which may not wait for g_phys_mutex: a holder of that mutex allocates
396// (g_mapped, g_windows) and the faulting title thread can hold the process heap's lock (see g_fault_lock). Host heap, 402// (g_mapped, g_windows) and the faulting title thread can hold the process heap's lock (see g_fault_lock). Host heap,
397// read and written under g_fault_lock. 403// read and written under g_fault_lock.
@@ -400,7 +406,10 @@ leonida::host_heap::map<uintptr_t, Window> g_fault_windows;
400// until the title releases them (TitleVirtualFree). With the windows these are the title's reserved memory: the only 406// until the title releases them (TitleVirtualFree). With the windows these are the title's reserved memory: the only
401// place the fault handler commits a mapped section page it has no view of (commit_title_section_page). 407// place the fault handler commits a mapped section page it has no view of (commit_title_section_page).
402leonida::host_heap::map<uintptr_t, Window> g_title_placeholders; 408leonida::host_heap::map<uintptr_t, Window> g_title_placeholders;
403std::unordered_map<uint64_t, PhysicalPage> g_pages; // page number -> backing 409// Keep page table nodes on the runtime heap alongside the window table.
410std::unordered_map<uint64_t, PhysicalPage, std::hash<uint64_t>, std::equal_to<uint64_t>,
411 leonida::host_heap::Allocator<std::pair<const uint64_t, PhysicalPage>>>
412 g_pages; // page number -> backing
404std::vector<uint64_t> g_free_slots; 413std::vector<uint64_t> g_free_slots;
405uint64_t g_next_slot = 1; 414uint64_t g_next_slot = 1;
406// A mapped run: `count` pages of one section at consecutive offsets, mapped as one view at its base. One view per run 415// A mapped run: `count` pages of one section at consecutive offsets, mapped as one view at its base. One view per run
@@ -797,10 +806,15 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type,
797 const DWORD host_type = allocation_type & kXmemHostAllocationTypeMask; 806 const DWORD host_type = allocation_type & kXmemHostAllocationTypeMask;
798 if (result && host_type && !(host_type & MEM_COMMIT)) { 807 if (result && host_type && !(host_type & MEM_COMMIT)) {
799 const bool gpu_only = (protect & kPageGraphicsMask) && host_protect(protect) == PAGE_NOACCESS; 808 const bool gpu_only = (protect & kPageGraphicsMask) && host_protect(protect) == PAGE_NOACCESS;
800 if (leonida::title_gpu_views::note_reservation(reinterpret_cast<uintptr_t>(result), size, gpu_only)) 809 const auto base = reinterpret_cast<uintptr_t>(result);
801 std::fprintf(stderr, "[rt] xmem: GPU-only view %p (%llu MiB, protect 0x%lx) reads at the CPU view %p\n", 810 const bool stream_queue_view = allocation_type == 0x20402000 && gpu_only &&
811 reinterpret_cast<uintptr_t>(_ReturnAddress()) - kTitleImage == 0x1e1d03e &&
812 rt::xmem::slot31_runs() && rt::xmem::queue_page_mappings_enabled();
813 if (leonida::title_gpu_views::note_reservation(base, size, gpu_only, stream_queue_view))
814 std::fprintf(stderr, "[rt] xmem: GPU-only view %p (%llu MiB, protect 0x%lx) paired with CPU view %p (%s)\n",
802 result, static_cast<unsigned long long>(size >> 20), static_cast<unsigned long>(protect), 815 result, static_cast<unsigned long long>(size >> 20), static_cast<unsigned long>(protect),
803 reinterpret_cast<void*>(leonida::title_gpu_views::to_cpu(reinterpret_cast<uintptr_t>(result)))); 816 reinterpret_cast<void*>(leonida::title_gpu_views::other_view(base)),
817 stream_queue_view ? "separate queue mappings" : "CPU backing");
804 else if (gpu_only && size >= (64u << 20)) 818 else if (gpu_only && size >= (64u << 20))
805 std::fprintf(stderr, "[rt] xmem: GPU-only reservation %p (%llu MiB, protect 0x%lx) has no CPU view\n", result, 819 std::fprintf(stderr, "[rt] xmem: GPU-only reservation %p (%llu MiB, protect 0x%lx) has no CPU view\n", result,
806 static_cast<unsigned long long>(size >> 20), static_cast<unsigned long>(protect)); 820 static_cast<unsigned long long>(size >> 20), static_cast<unsigned long>(protect));
@@ -1823,8 +1837,13 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint
1823 const uintptr_t end = start + page_count * kPhysicalPageSize; 1837 const uintptr_t end = start + page_count * kPhysicalPageSize;
1824 const UnmapCause cause(page_array ? "XMemMapPhysicalPages (remap)" : "XMemMapPhysicalPages (unmap)"); 1838 const UnmapCause cause(page_array ? "XMemMapPhysicalPages (remap)" : "XMemMapPhysicalPages (unmap)");
1825 if (!page_array) { 1839 if (!page_array) {
1826 const FaultLockExclusive view_lock; 1840 bool ok = false;
1827 return unmap_range_locked(start, end) ? address : nullptr; 1841 {
1842 const FaultLockExclusive view_lock;
1843 ok = unmap_range_locked(start, end);
1844 }
1845 if (ok) leonida::geometry_writes::note_released(start, end);
1846 return ok ? address : nullptr;
1828 } 1847 }
1829 const Window* const window = find_window(start, page_count * kPhysicalPageSize); 1848 const Window* const window = find_window(start, page_count * kPhysicalPageSize);
1830 if (!window) { 1849 if (!window) {
@@ -2196,6 +2215,14 @@ BOOL title_release(void* address, SIZE_T size, DWORD free_type, const void* call
2196BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) { 2215BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) {
2197 drain_fault_notes(); 2216 drain_fault_notes();
2198 const bool releases = (free_type & MEM_RELEASE) && !(free_type & (MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS)); 2217 const bool releases = (free_type & MEM_RELEASE) && !(free_type & (MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS));
2218 const uintptr_t start = reinterpret_cast<uintptr_t>(address);
2219 uintptr_t release_end = 0;
2220 if (releases && address) allocation_extent(address, release_end);
2221 uintptr_t decommit_end = 0;
2222 if ((free_type & MEM_DECOMMIT) && address) {
2223 decommit_end = size ? start + size : leonida::title_write_watch::end_of(start);
2224 if (decommit_end <= start) allocation_extent(address, decommit_end);
2225 }
2199 BOOL result; 2226 BOOL result;
2200 if (releases) { 2227 if (releases) {
2201 result = title_release(address, size, free_type, _ReturnAddress()); 2228 result = title_release(address, size, free_type, _ReturnAddress());
@@ -2213,6 +2240,10 @@ BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) {
2213 if (result && (free_type & MEM_DECOMMIT)) note_unwatched_change(address, size, 0, true); 2240 if (result && (free_type & MEM_DECOMMIT)) note_unwatched_change(address, size, 0, true);
2214 if (result && (free_type & MEM_RELEASE) && !(free_type & MEM_PRESERVE_PLACEHOLDER)) 2241 if (result && (free_type & MEM_RELEASE) && !(free_type & MEM_PRESERVE_PLACEHOLDER))
2215 leonida::title_write_watch::remove(reinterpret_cast<uintptr_t>(address)); 2242 leonida::title_write_watch::remove(reinterpret_cast<uintptr_t>(address));
2243 if (result && releases && release_end > start)
2244 leonida::geometry_writes::note_released(start, release_end);
2245 if (result && (free_type & MEM_DECOMMIT) && decommit_end > start)
2246 leonida::geometry_writes::note_released(start, decommit_end);
2216 return result; 2247 return result;
2217} 2248}
2218 2249
@@ -2434,6 +2465,7 @@ bool copy_page_mappings(std::uint32_t count, const PageBatch* batches, std::uint
2434 if (!mirror && r.spec.kind == 2) { 2465 if (!mirror && r.spec.kind == 2) {
2435 const UnmapCause cause("CopyPageMappingsBatchX (unmap range)"); 2466 const UnmapCause cause("CopyPageMappingsBatchX (unmap range)");
2436 ok = unmap_range(r.at, r.at + bytes); 2467 ok = unmap_range(r.at, r.at + bytes);
2468 if (ok) leonida::geometry_writes::note_released(r.at, r.at + bytes);
2437 } else if (!mirror && !slot31_runs()) { 2469 } else if (!mirror && !slot31_runs()) {
2438 for (uint32_t j = 0; j < r.spec.count; ++j) { 2470 for (uint32_t j = 0; j < r.spec.count; ++j) {
2439 const auto at = r.at + uint64_t(j) * kPhysicalPageSize; 2471 const auto at = r.at + uint64_t(j) * kPhysicalPageSize;
diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h
index 9a7df46c5..96fb89e7e 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
24// Record the two measured stream-pool reservation return sites; other callers are ignored. 24// Record the two measured stream-pool reservation return sites; other callers are ignored.
25void note_stream_reservation(std::uintptr_t base, std::size_t size, std::uintptr_t caller_rva); 25void note_stream_reservation(std::uintptr_t base, std::size_t size, std::uintptr_t caller_rva);
26bool queue_page_mappings_enabled(); 26bool queue_page_mappings_enabled();
27bool slot31_runs();
27bool copy_page_mappings(std::uint32_t count, const PageBatch* batches, std::uintptr_t pool, 28bool copy_page_mappings(std::uint32_t count, const PageBatch* batches, std::uintptr_t pool,
28 std::uint32_t pool_pages, std::uint32_t flags); 29 std::uint32_t pool_pages, std::uint32_t flags);
29 30
diff --git a/runtime/src/base_reservation.h b/runtime/src/base_reservation.h
index b76c28c70..5ccfe1aaa 100644
--- a/runtime/src/base_reservation.h
+++ b/runtime/src/base_reservation.h
@@ -63,7 +63,10 @@ inline void* commit_reserved(std::uint64_t base, std::uint64_t size) {
63} 63}
64 64
65// The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt 65// The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt
66// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). 66// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). Without a
67// relocation directory the loader refuses to move an image that has IMAGE_FILE_RELOCS_STRIPPED, and moves one with
68// the flag clear with nothing fixed up: that is right only for an image with no absolute addresses in it, so its
69// range is kept free either way. An image with a relocation table is moved and fixed up whatever the flag says.
67inline std::optional<Range> needed(const std::filesystem::path& image) { 70inline std::optional<Range> needed(const std::filesystem::path& image) {
68 std::ifstream file(image, std::ios::binary); 71 std::ifstream file(image, std::ios::binary);
69 IMAGE_DOS_HEADER dos{}; 72 IMAGE_DOS_HEADER dos{};
diff --git a/runtime/src/buffer_va_index.h b/runtime/src/buffer_va_index.h
index 6fbba5b05..3ab8edf82 100644
--- a/runtime/src/buffer_va_index.h
+++ b/runtime/src/buffer_va_index.h
@@ -91,6 +91,11 @@ public:
91 91
92 std::size_t size() const { return ranges_.size(); } 92 std::size_t size() const { return ranges_.size(); }
93 std::uint64_t longest() const { return longest_; } 93 std::uint64_t longest() const { return longest_; }
94 // f(first VA, bytes) for every range, in VA order.
95 template <class F>
96 void for_each(F&& f) const {
97 for (const auto& [key, bytes] : ranges_) f(key.first, bytes);
98 }
94 99
95private: 100private:
96 static constexpr Id max_id() { return ~Id(0); } 101 static constexpr Id max_id() { return ~Id(0); }
diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h
index 3d7ed093b..d7d739640 100644
--- a/runtime/src/command_list.h
+++ b/runtime/src/command_list.h
@@ -462,6 +462,7 @@ struct Draw {
462 std::uint32_t first_instance = 0; 462 std::uint32_t first_instance = 0;
463 bool mesh = false; 463 bool mesh = false;
464 std::shared_ptr<const DrawViewports> viewports; // non-null when >1 viewport or >1 scissor was bound 464 std::shared_ptr<const DrawViewports> viewports; // non-null when >1 viewport or >1 scissor was bound
465 std::array<float, 2> depth_bounds{0, 1}; // OMSetDepthBounds (min, max); used by depth-bounds pipelines only
465}; 466};
466 467
467// Only indirect draws allocate this extra payload. Copies of the IR share both its 468// Only indirect draws allocate this extra payload. Copies of the IR share both its
@@ -545,8 +546,8 @@ struct UavView {
545 std::uint64_t size; // buffer: bytes in the view 546 std::uint64_t size; // buffer: bytes in the view
546 std::uint32_t element_size; // buffer: bytes an element (rects count elements), 4 for a raw view 547 std::uint32_t element_size; // buffer: bytes an element (rects count elements), 4 for a raw view
547 std::uint32_t mip; // texture 548 std::uint32_t mip; // texture
548 std::uint32_t first_layer; 549 std::uint32_t first_layer; // 1D/2D array: first slice; 3D volume: FirstWSlice
549 std::uint32_t layer_count; 550 std::uint32_t layer_count; // 1D/2D array: slice count; 3D volume: WSize
550 bool exact_clear_format = false; // newly exposed 1D/3D UAVs: do not clear via a different backing format 551 bool exact_clear_format = false; // newly exposed 1D/3D UAVs: do not clear via a different backing format
551}; 552};
552 553
diff --git a/runtime/src/console_heap_fix.comp b/runtime/src/console_heap_fix.comp
new file mode 100644
index 000000000..85b5d1787
--- /dev/null
+++ b/runtime/src/console_heap_fix.comp
@@ -0,0 +1,292 @@
1// Console descriptor heap translation on the GPU (LEONIDA_CONSOLE_HEAP_GPU=1, shims/d3d12_console_heap_gpu.h).
2// The title writes 32-byte RDNA2 records into its console descriptor heap; shaders read a copy in which every buffer
3// V# whose base is the title's own memory names the GPU copy of that memory instead (DeviceState::fix_vsharp). This
4// pass makes that copy: for each listed slot it reads the title's bytes (a host mirror of the heap's pages), rewrites
5// the V# halves, and writes the record where shaders read it. T#s and other words are copied as they are (T#s are
6// found by their exact words in the bindless table; the CPU registers them).
7// console_heap_fix_spv.h is this file compiled with `glslc --target-env=vulkan1.2 -O -mfmt=c` (see the header);
8// keep them together. runtime/test/vk_console_heap_gpu_test.cpp checks it against the CPU reference
9// (console_heap_gpu_reference in d3d12_console_heap_gpu.h).
10//
11// A V# half (dwords 0-3, and 4-7 when dword 3 says the slot is a buffer pair) is translated like fix_vsharp:
12// - skipped when its TYPE bits (dword 3, bits 30-31) are set or it has no records (dword 2 zero);
13// - base 0: written with no records;
14// - base inside a range of the range table (the alias table: slot-133 buffers, title windows, pool extents), sorted
15// by title VA: rebased to the range's shader VA when the range was checked backed on the CPU and holds the V#'s
16// whole span; written with no records when it does not hold it (vsharp_address answers 0 there too). An
17// unchecked range falls through;
18// - the base as a shader VA (sign-extended from bit 47 with FLAG_SIGNED) with its whole span inside a span of the
19// backed table (live allocations, geometry blocks): left as it is, as vsharp_address's backed() leaves it;
20// - otherwise its exact 16 bytes are looked up in the key table (an open-addressed table the CPU fills with what
21// vsharp_address answered for those words: a shader VA, or "no backing"); found: rebased, or written with no
22// records;
23// - not found: written with no records; when the base is in the ask table (the title's memory and GPU windows, with
24// FLAG_ASK), or there is no ask table, the half is recorded in the miss list, which the CPU reads once the
25// submission is done, resolves (making the copy if it can) and enters in the key table.
26// "No records" is what fix_vsharp writes: dwords 0, 1 and 2 zero, so loads return 0 and stores are dropped, and no
27// shader adds heap_base to a raw title address.
28//
29// MODE_UPDATE writes the key table entries the CPU changed (one thread each) before MODE_TRANSLATE runs, so the
30// table only ever changes in GPU order, between passes.
31//
32// Addresses are 64-bit buffer device addresses passed as uvec2 (GL_EXT_buffer_reference_uvec2): only the
33// bufferDeviceAddress feature is needed, no shaderInt64.
34#version 460
35#extension GL_EXT_buffer_reference : require
36#extension GL_EXT_buffer_reference_uvec2 : require
37
38layout(local_size_x = 64) in;
39
40layout(buffer_reference, std430, buffer_reference_align = 16) buffer Slots {
41 uvec4 v[];
42};
43layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words {
44 uint w[];
45};
46
47const uint MODE_TRANSLATE = 0u;
48const uint MODE_UPDATE = 1u;
49
50const uint RANGE_WORDS = 8u; // title_va (2), end (2), shader_va (2), flags, pad
51const uint RANGE_CHECKED = 1u; // the CPU found the whole range backed
52const uint KEY_WORDS = 8u; // key (4), to.x, to.y | flags << 16, pad (2)
53const uint KEY_USED = 1u;
54const uint KEY_NONE = 2u; // vsharp_address answered 0: no records
55const uint KEY_PROBES = 16u;
56const uint UPDATE_WORDS = 12u; // index, pad (3), entry (8)
57const uint MISS_HEADER = 4u; // count, capacity, overflowed, pad
58const uint SPAN_WORDS = 4u; // start (2), end (2)
59const uint FLAG_SIGNED = 1u;
60const uint FLAG_ASK = 2u;
61const uint FLAG_RANGE = 4u; // MODE_TRANSLATE over slots pc.work.x + i, not a list: a rescan, V# pairs only
62const uint FLAG_FILTER = 8u; // with FLAG_RANGE: only slots whose metadata meets a change span (below)
63
64layout(push_constant) uniform Params {
65 uvec2 input_slots; // the title's bytes of the heap (its host mirror)
66 uvec2 copy_slots; // the heap where shaders read it
67 uvec2 work; // slot indices (MODE_TRANSLATE)
68 uvec2 ranges; // range table
69 uvec2 keys; // key table
70 uvec2 misses; // miss list
71 uvec2 backed; // backed spans
72 uvec2 ask; // ask spans
73 uvec2 meta; // per slot and half, device-local: what the pass last made of it (meta_of); 0: none
74 uvec2 cshader; // a filtered rescan's change spans in shader VAs (backings and alias copies that went)
75 uvec2 ctitle; // and in title VAs (alias ranges that went, words answered since)
76 uint count; // work items or updates
77 uint range_count;
78 uint key_mask; // key table entries - 1 (a power of two)
79 uint mode;
80 uint heap; // the heap's index (< 8), kept in each miss
81 uint backed_count;
82 uint ask_count;
83 uint flags;
84 uint cshader_count;
85 uint ctitle_count;
86} pc;
87// MODE_UPDATE reads its records at pc.work (the push constants hold 128 bytes).
88
89uvec2 add64(uvec2 a, uvec2 b) {
90 uint carry;
91 uint lo = uaddCarry(a.x, b.x, carry);
92 return uvec2(lo, a.y + b.y + carry);
93}
94uvec2 sub64(uvec2 a, uvec2 b) {
95 uint borrow;
96 uint lo = usubBorrow(a.x, b.x, borrow);
97 return uvec2(lo, a.y - b.y - borrow);
98}
99bool less64(uvec2 a, uvec2 b) { return a.y < b.y || (a.y == b.y && a.x < b.x); }
100uvec2 offset(uvec2 base, uint word) {
101 uint carry;
102 uint lo = uaddCarry(base.x, word * 4u, carry);
103 return uvec2(lo, base.y + carry);
104}
105uint load(uvec2 base, uint word) { return Words(offset(base, word)).w[0]; }
106uvec2 load2(uvec2 base, uint word) { return uvec2(load(base, word), load(base, word + 1u)); }
107
108// FNV-1a over the four dwords, then MurmurHash3's fmix32: without the finalizer the low bits (the table index) depend
109// only on the low bits of each dword, and V#s whose bases differ only above bit 20 all fell into one probe chain.
110uint key_hash(uvec4 k) {
111 uint h = 2166136261u;
112 h = (h ^ k.x) * 16777619u;
113 h = (h ^ k.y) * 16777619u;
114 h = (h ^ k.z) * 16777619u;
115 h = (h ^ k.w) * 16777619u;
116 h ^= h >> 16;
117 h *= 0x85EBCA6Bu;
118 h ^= h >> 13;
119 h *= 0xC2B2AE35u;
120 h ^= h >> 16;
121 return h;
122}
123
124// [v, v + n) inside one of `count` sorted, disjoint spans at `spans`.
125bool spans_hold(uvec2 spans, uint count, uvec2 v, uvec2 n) {
126 uint lo = 0u, hi = count;
127 while (lo < hi) {
128 const uint mid = (lo + hi) >> 1u;
129 if (less64(v, load2(spans, SPAN_WORDS * mid))) hi = mid;
130 else lo = mid + 1u;
131 }
132 if (lo == 0u) return false;
133 const uvec2 end = load2(spans, SPAN_WORDS * (lo - 1u) + 2u);
134 return less64(v, end) && !less64(sub64(end, v), n);
135}
136
137// Some span of `count` sorted, disjoint spans at `spans` overlaps [v, v + n).
138bool spans_meet(uvec2 spans, uint count, uvec2 v, uvec2 n) {
139 const uvec2 last = add64(v, n); // spans starting below it
140 uint lo = 0u, hi = count;
141 while (lo < hi) {
142 const uint mid = (lo + hi) >> 1u;
143 if (less64(load2(spans, SPAN_WORDS * mid), last)) lo = mid + 1u;
144 else hi = mid;
145 }
146 if (lo == 0u) return false;
147 return less64(v, load2(spans, SPAN_WORDS * (lo - 1u) + 2u));
148}
149
150// A 48-bit V# base as the shader VA it names: sign-extended from bit 47 with FLAG_SIGNED.
151uvec2 shader_va(uvec2 base48) {
152 uvec2 v = uvec2(base48.x, base48.y & 0xffffu);
153 if ((pc.flags & FLAG_SIGNED) != 0u && (v.y & 0x8000u) != 0u) v.y |= 0xffff0000u;
154 return v;
155}
156
157// Metadata of one V# half: its title base and span before the pass, and the base it got (0: no records).
158// x = title base low, y = title base bits 32-47 | result bits 32-47 << 16, z = result low, w = span (saturated).
159uvec4 meta_of(uvec4 before, uvec4 after) {
160 if ((before.w >> 30) != 0u || before.z == 0u) return uvec4(0u);
161 const uint stride = (before.y >> 16) & 0x3fffu;
162 uvec2 span;
163 umulExtended(before.z, stride == 0u ? 1u : stride, span.y, span.x);
164 const uvec2 to = after.z == 0u ? uvec2(0u) : uvec2(after.x, after.y & 0xffffu);
165 return uvec4(before.x, (before.y & 0xffffu) | (to.y << 16), to.x, span.y != 0u ? 0xffffffffu : span.x);
166}
167
168// The half's metadata meets a change span: its title base in a title span, or its base or result (with its span) in
169// a shader span. What DeviceState's CPU release filter asks of a slot (LEONIDA_CONSOLE_RELEASE_FILTER).
170bool affected(uvec4 m) {
171 if (m.x == 0u && m.y == 0u && m.z == 0u) return false;
172 const uvec2 base = uvec2(m.x, m.y & 0xffffu);
173 const uvec2 span = uvec2(m.w, 0u);
174 if (pc.ctitle_count != 0u && spans_meet(pc.ctitle, pc.ctitle_count, base, uvec2(1u, 0u))) return true;
175 if (pc.cshader_count == 0u) return false;
176 if (spans_meet(pc.cshader, pc.cshader_count, shader_va(base), span)) return true;
177 const uvec2 to = uvec2(m.z, m.y >> 16);
178 return !(to.x == 0u && to.y == 0u) && spans_meet(pc.cshader, pc.cshader_count, shader_va(to), span);
179}
180
181void rebase(inout uvec4 k, uvec2 to) {
182 k.x = to.x;
183 k.y = (k.y & 0xffff0000u) | (to.y & 0xffffu);
184}
185void no_records(inout uvec4 k) {
186 k.x = 0u;
187 k.y = 0u;
188 k.z = 0u;
189}
190
191// 0: left as it is, 1: rebased or written with no records by a table, 2: missed (written with no records).
192uint translate(inout uvec4 k) {
193 if ((k.w >> 30) != 0u || k.z == 0u) return 0u;
194 const uvec2 base = uvec2(k.x, k.y & 0xffffu);
195 if (base.x == 0u && base.y == 0u) {
196 no_records(k);
197 return 1u;
198 }
199 const uint stride = (k.y >> 16) & 0x3fffu;
200 uvec2 span;
201 umulExtended(k.z, stride == 0u ? 1u : stride, span.y, span.x);
202 // The last range that starts at or below base.
203 uint lo = 0u, hi = pc.range_count;
204 while (lo < hi) {
205 const uint mid = (lo + hi) >> 1u;
206 if (less64(base, load2(pc.ranges, RANGE_WORDS * mid))) hi = mid;
207 else lo = mid + 1u;
208 }
209 if (lo > 0u) {
210 const uint e = RANGE_WORDS * (lo - 1u);
211 const uvec2 end = load2(pc.ranges, e + 2u);
212 if (less64(base, end) && (load(pc.ranges, e + 6u) & RANGE_CHECKED) != 0u) {
213 if (less64(sub64(end, base), span)) {
214 no_records(k);
215 } else {
216 const uvec2 start = load2(pc.ranges, e);
217 rebase(k, add64(load2(pc.ranges, e + 4u), sub64(base, start)));
218 }
219 return 1u;
220 }
221 }
222 uvec2 shader = base;
223 if ((pc.flags & FLAG_SIGNED) != 0u && (base.y & 0x8000u) != 0u) shader.y |= 0xffff0000u;
224 if (pc.backed_count != 0u && spans_hold(pc.backed, pc.backed_count, shader, span.x == 0u && span.y == 0u ? uvec2(1u, 0u) : span))
225 return 1u;
226 const uint h = key_hash(k);
227 for (uint p = 0u; p < KEY_PROBES; ++p) {
228 const uint at = KEY_WORDS * ((h + p) & pc.key_mask);
229 const uint flags = load(pc.keys, at + 5u) >> 16;
230 if ((flags & KEY_USED) == 0u) continue;
231 if (load(pc.keys, at) != k.x || load(pc.keys, at + 1u) != k.y || load(pc.keys, at + 2u) != k.z ||
232 load(pc.keys, at + 3u) != k.w)
233 continue;
234 if ((flags & KEY_NONE) != 0u) no_records(k);
235 else rebase(k, uvec2(load(pc.keys, at + 4u), load(pc.keys, at + 5u) & 0xffffu));
236 return 1u;
237 }
238 no_records(k);
239 if ((pc.flags & FLAG_ASK) != 0u && !spans_hold(pc.ask, pc.ask_count, base, uvec2(1u, 0u))) return 1u;
240 return 2u;
241}
242
243void miss(uint code) {
244 Words m = Words(pc.misses);
245 const uint at = atomicAdd(m.w[0], 1u);
246 if (at < m.w[1]) m.w[MISS_HEADER + at] = code;
247 else m.w[2] = 1u;
248}
249
250void main() {
251 const uint i = gl_GlobalInvocationID.x;
252 if (i >= pc.count) return;
253 if (pc.mode == MODE_UPDATE) {
254 const uvec2 record = offset(pc.work, UPDATE_WORDS * i);
255 const uint index = Words(record).w[0];
256 Words table = Words(offset(pc.keys, KEY_WORDS * index));
257 for (uint j = 0u; j < KEY_WORDS; ++j) table.w[j] = Words(record).w[4u + j];
258 return;
259 }
260 // 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
261 // dwords 0-3 are written as zeros (fix_console_slot's rule: such words must not reach a shader as a descriptor).
262 const bool range = (pc.flags & FLAG_RANGE) != 0u;
263 const uint item = range ? pc.work.x + i : Words(pc.work).w[i];
264 const uint slot = item & 0x7fffffffu;
265 const bool has_meta = !(pc.meta.x == 0u && pc.meta.y == 0u);
266 // A filtered rescan reads only the device-local metadata of a slot it leaves alone, not the title's bytes.
267 if (range && (pc.flags & FLAG_FILTER) != 0u && has_meta) {
268 Slots m = Slots(pc.meta);
269 if (!affected(m.v[2u * slot]) && !affected(m.v[2u * slot + 1u])) return;
270 }
271 Slots source = Slots(pc.input_slots);
272 uvec4 a = source.v[2u * slot];
273 uvec4 b = source.v[2u * slot + 1u];
274 // A rescan rewrites buffer pairs only: every other slot keeps what its last listed pass wrote.
275 if (range && (a.w >> 30) != 0u) return;
276 if ((item >> 31) != 0u && (a.w >> 30) != 0u) a = uvec4(0u);
277 const uvec4 a0 = a, b0 = b;
278 if ((a.w >> 30) == 0u) {
279 // A miss is (heap << 29) | (slot << 1) | half: up to eight heaps of 2^28 slots.
280 if (translate(a) == 2u) miss((pc.heap << 29) | (slot << 1u));
281 if (translate(b) == 2u) miss((pc.heap << 29) | (slot << 1u) | 1u);
282 }
283 Slots target = Slots(pc.copy_slots);
284 target.v[2u * slot] = a;
285 target.v[2u * slot + 1u] = b;
286 if (has_meta) {
287 Slots m = Slots(pc.meta);
288 const bool pair = (a0.w >> 30) == 0u;
289 m.v[2u * slot] = pair ? meta_of(a0, a) : uvec4(0u);
290 m.v[2u * slot + 1u] = pair ? meta_of(b0, b) : uvec4(0u);
291 }
292}
diff --git a/runtime/src/console_heap_fix.inc b/runtime/src/console_heap_fix.inc
new file mode 100644
index 000000000..2e2882f6d
--- /dev/null
+++ b/runtime/src/console_heap_fix.inc
@@ -0,0 +1,3163 @@
1{0x07230203,0x00010500,0x000d000b,0x000021a5,
20x00000000,0x00020011,0x00000001,0x00020011,
30x000014e3,0x0006000b,0x00000001,0x4c534c47,
40x6474732e,0x3035342e,0x00000000,0x0003000e,
50x000014e4,0x00000001,0x0007000f,0x00000005,
60x00000004,0x6e69616d,0x00000000,0x00000180,
70x000003f8,0x00060010,0x00000004,0x00000011,
80x00000040,0x00000001,0x00000001,0x00040047,
90x000000b2,0x00000006,0x00000004,0x00030047,
100x000000b3,0x00000002,0x00050048,0x000000b3,
110x00000000,0x00000023,0x00000000,0x00030047,
120x0000017e,0x00000002,0x00050048,0x0000017e,
130x00000000,0x00000023,0x00000000,0x00050048,
140x0000017e,0x00000001,0x00000023,0x00000008,
150x00050048,0x0000017e,0x00000002,0x00000023,
160x00000010,0x00050048,0x0000017e,0x00000003,
170x00000023,0x00000018,0x00050048,0x0000017e,
180x00000004,0x00000023,0x00000020,0x00050048,
190x0000017e,0x00000005,0x00000023,0x00000028,
200x00050048,0x0000017e,0x00000006,0x00000023,
210x00000030,0x00050048,0x0000017e,0x00000007,
220x00000023,0x00000038,0x00050048,0x0000017e,
230x00000008,0x00000023,0x00000040,0x00050048,
240x0000017e,0x00000009,0x00000023,0x00000048,
250x00050048,0x0000017e,0x0000000a,0x00000023,
260x00000050,0x00050048,0x0000017e,0x0000000b,
270x00000023,0x00000058,0x00050048,0x0000017e,
280x0000000c,0x00000023,0x0000005c,0x00050048,
290x0000017e,0x0000000d,0x00000023,0x00000060,
300x00050048,0x0000017e,0x0000000e,0x00000023,
310x00000064,0x00050048,0x0000017e,0x0000000f,
320x00000023,0x00000068,0x00050048,0x0000017e,
330x00000010,0x00000023,0x0000006c,0x00050048,
340x0000017e,0x00000011,0x00000023,0x00000070,
350x00050048,0x0000017e,0x00000012,0x00000023,
360x00000074,0x00050048,0x0000017e,0x00000013,
370x00000023,0x00000078,0x00050048,0x0000017e,
380x00000014,0x00000023,0x0000007c,0x00040047,
390x000003f8,0x0000000b,0x0000001c,0x00040047,
400x00000469,0x00000006,0x00000010,0x00030047,
410x0000046a,0x00000002,0x00050048,0x0000046a,
420x00000000,0x00000023,0x00000000,0x00040047,
430x00000517,0x0000000b,0x00000019,0x00020013,
440x00000002,0x00030021,0x00000003,0x00000002,
450x00040015,0x00000006,0x00000020,0x00000000,
460x00040017,0x00000007,0x00000006,0x00000002,
470x00020014,0x00000012,0x00040017,0x00000027,
480x00000006,0x00000004,0x0004002b,0x00000006,
490x00000058,0x00000000,0x0004001e,0x0000005e,
500x00000006,0x00000006,0x0004002b,0x00000006,
510x00000063,0x00000001,0x0004002b,0x00000006,
520x0000009e,0x00000004,0x00030027,0x000000b1,
530x000014e5,0x0003001d,0x000000b2,0x00000006,
540x0003001e,0x000000b3,0x000000b2,0x00040020,
550x000000b1,0x000014e5,0x000000b3,0x00040015,
560x000000b5,0x00000020,0x00000001,0x0004002b,
570x000000b5,0x000000b6,0x00000000,0x00040020,
580x000000b7,0x000014e5,0x00000006,0x0004002b,
590x00000006,0x000000cb,0x811c9dc5,0x0004002b,
600x00000006,0x000000d0,0x01000193,0x0004002b,
610x00000006,0x000000d8,0x00000002,0x0004002b,
620x00000006,0x000000de,0x00000003,0x0004002b,
630x000000b5,0x000000e4,0x00000010,0x0004002b,
640x00000006,0x000000e8,0x85ebca6b,0x0004002b,
650x000000b5,0x000000ec,0x0000000d,0x0004002b,
660x00000006,0x000000f0,0xc2b2ae35,0x0003002a,
670x00000012,0x0000011e,0x0004002b,0x00000006,
680x0000017b,0x0000ffff,0x0017001e,0x0000017e,
690x00000007,0x00000007,0x00000007,0x00000007,
700x00000007,0x00000007,0x00000007,0x00000007,
710x00000007,0x00000007,0x00000007,0x00000006,
720x00000006,0x00000006,0x00000006,0x00000006,
730x00000006,0x00000006,0x00000006,0x00000006,
740x00000006,0x00040020,0x0000017f,0x00000009,
750x0000017e,0x0004003b,0x0000017f,0x00000180,
760x00000009,0x0004002b,0x000000b5,0x00000181,
770x00000012,0x00040020,0x00000182,0x00000009,
780x00000006,0x0004002b,0x00000006,0x0000018b,
790x00008000,0x0004002b,0x00000006,0x00000191,
800xffff0000,0x0004002b,0x000000b5,0x0000019b,
810x0000001e,0x0007002c,0x00000027,0x000001a7,
820x00000058,0x00000058,0x00000058,0x00000058,
830x0004002b,0x00000006,0x000001ad,0x00003fff,
840x0005002c,0x00000007,0x000001c2,0x00000058,
850x00000058,0x0004002b,0x00000006,0x000001dc,
860xffffffff,0x0004002b,0x000000b5,0x00000201,
870x00000014,0x0004002b,0x000000b5,0x00000207,
880x0000000a,0x0005002c,0x00000007,0x00000208,
890x00000063,0x00000058,0x00040020,0x0000020a,
900x00000009,0x00000007,0x00030029,0x00000012,
910x00000217,0x0004002b,0x000000b5,0x00000219,
920x00000013,0x0004002b,0x000000b5,0x00000220,
930x00000009,0x0004002b,0x000000b5,0x0000029a,
940x0000000c,0x0004002b,0x000000b5,0x000002aa,
950x00000003,0x0004002b,0x00000006,0x000002ab,
960x00000008,0x0004002b,0x00000006,0x000002d5,
970x00000006,0x0004002b,0x000000b5,0x00000325,
980x00000006,0x0004002b,0x00000006,0x0000034a,
990x00000010,0x0004002b,0x000000b5,0x00000355,
1000x00000004,0x0004002b,0x00000006,0x00000357,
1010x00000005,0x0004002b,0x000000b5,0x000003bc,
1020x00000001,0x0004002b,0x000000b5,0x000003c8,
1030x00000007,0x0004002b,0x000000b5,0x000003c9,
1040x00000011,0x0004002b,0x000000b5,0x000003dd,
1050x00000005,0x0004002b,0x000000b5,0x000003f3,
1060x00000002,0x00040017,0x000003f6,0x00000006,
1070x00000003,0x00040020,0x000003f7,0x00000001,
1080x000003f6,0x0004003b,0x000003f7,0x000003f8,
1090x00000001,0x00040020,0x000003f9,0x00000001,
1100x00000006,0x0004002b,0x000000b5,0x000003fd,
1110x0000000b,0x0004002b,0x000000b5,0x00000404,
1120x0000000e,0x0004002b,0x00000006,0x0000044e,
1130x7fffffff,0x0004002b,0x000000b5,0x00000451,
1140x00000008,0x00030027,0x00000468,0x000014e5,
1150x0003001d,0x00000469,0x00000027,0x0003001e,
1160x0000046a,0x00000469,0x00040020,0x00000468,
1170x000014e5,0x0000046a,0x00040020,0x00000474,
1180x000014e5,0x00000027,0x0004002b,0x000000b5,
1190x000004a5,0x0000001f,0x0004002b,0x000000b5,
1200x000004c2,0x0000000f,0x0004002b,0x000000b5,
1210x000004c5,0x0000001d,0x0004002b,0x00000006,
1220x00000516,0x00000040,0x0006002c,0x000003f6,
1230x00000517,0x00000516,0x00000063,0x00000063,
1240x00030001,0x00000006,0x00001da1,0x0004002b,
1250x00000006,0x0000218f,0x00000020,0x0004002b,
1260x00000006,0x00002193,0x00000030,0x00040017,
1270x0000219a,0x00000012,0x00000004,0x00050036,
1280x00000002,0x00000004,0x00000000,0x00000003,
1290x000200f8,0x00000005,0x000300f7,0x00000518,
1300x00000000,0x000300fb,0x00000058,0x00000519,
1310x000200f8,0x00000519,0x00050041,0x000003f9,
1320x000003fa,0x000003f8,0x00000058,0x0004003d,
1330x00000006,0x000003fb,0x000003fa,0x00050041,
1340x00000182,0x000003fe,0x00000180,0x000003fd,
1350x0004003d,0x00000006,0x000003ff,0x000003fe,
1360x000500ae,0x00000012,0x00000400,0x000003fb,
1370x000003ff,0x000300f7,0x00000402,0x00000000,
1380x000400fa,0x00000400,0x00000401,0x00000402,
1390x000200f8,0x00000401,0x000200f9,0x00000518,
1400x000200f8,0x00000402,0x00050041,0x00000182,
1410x00000405,0x00000180,0x00000404,0x0004003d,
1420x00000006,0x00000406,0x00000405,0x000500aa,
1430x00000012,0x00000407,0x00000406,0x00000063,
1440x000300f7,0x00000409,0x00000000,0x000400fa,
1450x00000407,0x00000408,0x00000409,0x000200f8,
1460x00000408,0x00050041,0x0000020a,0x0000040f,
1470x00000180,0x000003f3,0x0004003d,0x00000007,
1480x00000410,0x0000040f,0x00050051,0x00000006,
1490x0000053b,0x00000410,0x00000000,0x00050084,
1500x00000006,0x0000053d,0x000003fb,0x00002193,
1510x00050095,0x0000005e,0x0000053e,0x0000053b,
1520x0000053d,0x00050051,0x00000006,0x0000053f,
1530x0000053e,0x00000001,0x00050051,0x00000006,
1540x00000540,0x0000053e,0x00000000,0x00050051,
1550x00000006,0x00000543,0x00000410,0x00000001,
1560x00050080,0x00000006,0x00000545,0x00000543,
1570x0000053f,0x00050050,0x00000007,0x00000546,
1580x00000540,0x00000545,0x0004007c,0x000000b1,
1590x00000415,0x00000546,0x00060041,0x000000b7,
1600x00000416,0x00000415,0x000000b6,0x000000b6,
1610x0006003d,0x00000006,0x00000417,0x00000416,
1620x00000002,0x00000004,0x00050041,0x0000020a,
1630x0000041c,0x00000180,0x00000355,0x0004003d,
1640x00000007,0x0000041d,0x0000041c,0x00050051,
1650x00000006,0x0000054c,0x0000041d,0x00000000,
1660x00050084,0x00000006,0x0000054e,0x00000417,
1670x0000218f,0x00050095,0x0000005e,0x0000054f,
1680x0000054c,0x0000054e,0x00050051,0x00000006,
1690x00000550,0x0000054f,0x00000001,0x00050051,
1700x00000006,0x00000551,0x0000054f,0x00000000,
1710x00050051,0x00000006,0x00000554,0x0000041d,
1720x00000001,0x00050080,0x00000006,0x00000556,
1730x00000554,0x00000550,0x00050050,0x00000007,
1740x00000557,0x00000551,0x00000556,0x0004007c,
1750x000000b1,0x00000420,0x00000557,0x000200f9,
1760x00000422,0x000200f8,0x00000422,0x000700f5,
1770x00000006,0x00002123,0x00000058,0x00000408,
1780x00000433,0x00000423,0x000500b0,0x00000012,
1790x00000428,0x00002123,0x000002ab,0x000400f6,
1800x00000424,0x00000423,0x00000000,0x000400fa,
1810x00000428,0x00000423,0x00000424,0x000200f8,
1820x00000423,0x00050080,0x00000006,0x0000042e,
1830x0000009e,0x00002123,0x00060041,0x000000b7,
1840x0000042f,0x00000415,0x000000b6,0x0000042e,
1850x0006003d,0x00000006,0x00000430,0x0000042f,
1860x00000002,0x00000004,0x00060041,0x000000b7,
1870x00000431,0x00000420,0x000000b6,0x00002123,
1880x0005003e,0x00000431,0x00000430,0x00000002,
1890x00000004,0x00050080,0x00000006,0x00000433,
1900x00002123,0x000003bc,0x000200f9,0x00000422,
1910x000200f8,0x00000424,0x000200f9,0x00000518,
1920x000200f8,0x00000409,0x00050041,0x00000182,
1930x00000437,0x00000180,0x00000181,0x0004003d,
1940x00000006,0x00000438,0x00000437,0x000500c7,
1950x00000006,0x00000439,0x00000438,0x0000009e,
1960x000500ab,0x00000012,0x0000043a,0x00000439,
1970x00000058,0x000300f7,0x0000043f,0x00000000,
1980x000400fa,0x0000043a,0x0000043e,0x00000444,
1990x000200f8,0x00000444,0x00050041,0x0000020a,
2000x00000445,0x00000180,0x000003f3,0x0004003d,
2010x00000007,0x00000446,0x00000445,0x0004007c,
2020x000000b1,0x00000447,0x00000446,0x00060041,
2030x000000b7,0x00000449,0x00000447,0x000000b6,
2040x000003fb,0x0006003d,0x00000006,0x0000044a,
2050x00000449,0x00000002,0x00000004,0x000200f9,
2060x0000043f,0x000200f8,0x0000043e,0x00060041,
2070x00000182,0x00000440,0x00000180,0x000003f3,
2080x00000058,0x0004003d,0x00000006,0x00000441,
2090x00000440,0x00050080,0x00000006,0x00000443,
2100x00000441,0x000003fb,0x000200f9,0x0000043f,
2110x000200f8,0x0000043f,0x000700f5,0x00000006,
2120x00001ce6,0x00000443,0x0000043e,0x0000044a,
2130x00000444,0x000500c7,0x00000006,0x0000044f,
2140x00001ce6,0x0000044e,0x00060041,0x00000182,
2150x00000452,0x00000180,0x00000451,0x00000058,
2160x0004003d,0x00000006,0x00000453,0x00000452,
2170x000500aa,0x00000012,0x00000454,0x00000453,
2180x00000058,0x000300f7,0x00000456,0x00000000,
2190x000400fa,0x00000454,0x00000455,0x00000456,
2200x000200f8,0x00000455,0x00060041,0x00000182,
2210x00000457,0x00000180,0x00000451,0x00000063,
2220x0004003d,0x00000006,0x00000458,0x00000457,
2230x000500aa,0x00000012,0x00000459,0x00000458,
2240x00000058,0x000200f9,0x00000456,0x000200f8,
2250x00000456,0x000700f5,0x00000012,0x0000045a,
2260x00000454,0x0000043f,0x00000459,0x00000455,
2270x000400a8,0x00000012,0x0000045b,0x0000045a,
2280x000300f7,0x0000045e,0x00000000,0x000400fa,
2290x0000043a,0x0000045d,0x0000045e,0x000200f8,
2300x0000045d,0x000500c7,0x00000006,0x00000461,
2310x00000438,0x000002ab,0x000500ab,0x00000012,
2320x00000462,0x00000461,0x00000058,0x000200f9,
2330x0000045e,0x000200f8,0x0000045e,0x000700f5,
2340x00000012,0x00000463,0x0000043a,0x00000456,
2350x00000462,0x0000045d,0x000500a7,0x00000012,
2360x00000465,0x00000463,0x0000045b,0x000300f7,
2370x00000467,0x00000000,0x000400fa,0x00000465,
2380x00000466,0x00000467,0x000200f8,0x00000466,
2390x00050041,0x0000020a,0x0000046d,0x00000180,
2400x00000451,0x0004003d,0x00000007,0x0000046e,
2410x0000046d,0x0004007c,0x00000468,0x0000046f,
2420x0000046e,0x00050084,0x00000006,0x00000472,
2430x000000d8,0x0000044f,0x00060041,0x00000474,
2440x00000475,0x0000046f,0x000000b6,0x00000472,
2450x0006003d,0x00000027,0x00000476,0x00000475,
2460x00000002,0x00000010,0x000300f7,0x000005c0,
2470x00000000,0x000300fb,0x00000058,0x0000056d,
2480x000200f8,0x0000056d,0x00050051,0x00000006,
2490x0000056f,0x00000476,0x00000000,0x000500aa,
2500x00000012,0x00000570,0x0000056f,0x00000058,
2510x000300f7,0x00000575,0x00000000,0x000400fa,
2520x00000570,0x00000571,0x00000575,0x000200f8,
2530x00000571,0x00050051,0x00000006,0x00000573,
2540x00000476,0x00000001,0x000500aa,0x00000012,
2550x00000574,0x00000573,0x00000058,0x000200f9,
2560x00000575,0x000200f8,0x00000575,0x000700f5,
2570x00000012,0x00000576,0x00000570,0x0000056d,
2580x00000574,0x00000571,0x000300f7,0x0000057b,
2590x00000000,0x000400fa,0x00000576,0x00000577,
2600x0000057b,0x000200f8,0x00000577,0x00050051,
2610x00000006,0x00000579,0x00000476,0x00000002,
2620x000500aa,0x00000012,0x0000057a,0x00000579,
2630x00000058,0x000200f9,0x0000057b,0x000200f8,
2640x0000057b,0x000700f5,0x00000012,0x0000057c,
2650x00000576,0x00000575,0x0000057a,0x00000577,
2660x000300f7,0x0000057e,0x00000000,0x000400fa,
2670x0000057c,0x0000057d,0x0000057e,0x000200f8,
2680x0000057d,0x000200f9,0x000005c0,0x000200f8,
2690x0000057e,0x00050051,0x00000006,0x00000582,
2700x00000476,0x00000001,0x000500c7,0x00000006,
2710x00000583,0x00000582,0x0000017b,0x00050051,
2720x00000006,0x00000586,0x00000476,0x00000003,
2730x00050041,0x00000182,0x00000588,0x00000180,
2740x00000201,0x0004003d,0x00000006,0x00000589,
2750x00000588,0x000500ab,0x00000012,0x0000058a,
2760x00000589,0x00000058,0x000300f7,0x00000592,
2770x00000000,0x000400fa,0x0000058a,0x0000058b,
2780x00000592,0x000200f8,0x0000058b,0x00050041,
2790x0000020a,0x0000058c,0x00000180,0x00000207,
2800x0004003d,0x00000007,0x0000058d,0x0000058c,
2810x000300f7,0x000005fd,0x00000000,0x000300fb,
2820x00000058,0x000005d4,0x000200f8,0x000005d4,
2830x00050095,0x0000005e,0x00000607,0x0000056f,
2840x00000063,0x00050051,0x00000006,0x00000608,
2850x00000607,0x00000001,0x00050051,0x00000006,
2860x00000609,0x00000607,0x00000000,0x00050080,
2870x00000006,0x00000611,0x00000583,0x00000608,
2880x000200f9,0x000005d9,0x000200f8,0x000005d9,
2890x000700f5,0x00000006,0x00001ce8,0x00000589,
2900x000005d4,0x00002194,0x000005ef,0x000700f5,
2910x00000006,0x00001ce7,0x00000058,0x000005d4,
2920x00002124,0x000005ef,0x000500b0,0x00000012,
2930x000005dd,0x00001ce7,0x00001ce8,0x000400f6,
2940x000005f0,0x000005ef,0x00000000,0x000400fa,
2950x000005dd,0x000005de,0x000005f0,0x000200f8,
2960x000005de,0x00050080,0x00000006,0x000005e1,
2970x00001ce7,0x00001ce8,0x000500c2,0x00000006,
2980x000005e2,0x000005e1,0x00000063,0x00050084,
2990x00000006,0x000005e4,0x0000009e,0x000005e2,
3000x00050051,0x00000006,0x00000630,0x0000058d,
3010x00000000,0x00050084,0x00000006,0x00000632,
3020x000005e2,0x0000034a,0x00050095,0x0000005e,
3030x00000633,0x00000630,0x00000632,0x00050051,
3040x00000006,0x00000634,0x00000633,0x00000001,
3050x00050051,0x00000006,0x00000635,0x00000633,
3060x00000000,0x00050051,0x00000006,0x00000638,
3070x0000058d,0x00000001,0x00050080,0x00000006,
3080x0000063a,0x00000638,0x00000634,0x00050050,
3090x00000007,0x0000063b,0x00000635,0x0000063a,
3100x0004007c,0x000000b1,0x00000628,0x0000063b,
3110x00060041,0x000000b7,0x00000629,0x00000628,
3120x000000b6,0x000000b6,0x0006003d,0x00000006,
3130x0000062a,0x00000629,0x00000002,0x00000004,
3140x00050080,0x00000006,0x0000061d,0x000005e4,
3150x00000063,0x00050084,0x00000006,0x0000064d,
3160x0000061d,0x0000009e,0x00050095,0x0000005e,
3170x0000064e,0x00000630,0x0000064d,0x00050051,
3180x00000006,0x0000064f,0x0000064e,0x00000001,
3190x00050051,0x00000006,0x00000650,0x0000064e,
3200x00000000,0x00050080,0x00000006,0x00000655,
3210x00000638,0x0000064f,0x00050050,0x00000007,
3220x00000656,0x00000650,0x00000655,0x0004007c,
3230x000000b1,0x00000643,0x00000656,0x00060041,
3240x000000b7,0x00000644,0x00000643,0x000000b6,
3250x000000b6,0x0006003d,0x00000006,0x00000645,
3260x00000644,0x00000002,0x00000004,0x000500b0,
3270x00000012,0x0000065d,0x00000645,0x00000611,
3280x000400a8,0x00000012,0x0000065e,0x0000065d,
3290x000300f7,0x0000066d,0x00000000,0x000400fa,
3300x0000065e,0x0000065f,0x0000066d,0x000200f8,
3310x0000065f,0x000500aa,0x00000012,0x00000664,
3320x00000645,0x00000611,0x000300f7,0x0000066b,
3330x00000000,0x000400fa,0x00000664,0x00000665,
3340x0000066b,0x000200f8,0x00000665,0x000500b0,
3350x00000012,0x0000066a,0x0000062a,0x00000609,
3360x000200f9,0x0000066b,0x000200f8,0x0000066b,
3370x000700f5,0x00000012,0x0000066c,0x00000664,
3380x0000065f,0x0000066a,0x00000665,0x000200f9,
3390x0000066d,0x000200f8,0x0000066d,0x000700f5,
3400x00000012,0x0000066e,0x0000065d,0x000005de,
3410x0000066c,0x0000066b,0x000300f7,0x000005ee,
3420x00000000,0x000400fa,0x0000066e,0x000005e9,
3430x000005ec,0x000200f8,0x000005ec,0x000200f9,
3440x000005ee,0x000200f8,0x000005e9,0x00050080,
3450x00000006,0x000005eb,0x000005e2,0x00000063,
3460x000200f9,0x000005ee,0x000200f8,0x000005ee,
3470x000700f5,0x00000006,0x00002124,0x000005eb,
3480x000005e9,0x00001ce7,0x000005ec,0x000600a9,
3490x00000006,0x00002194,0x0000066e,0x00001ce8,
3500x000005e2,0x000200f9,0x000005ef,0x000200f8,
3510x000005ef,0x000200f9,0x000005d9,0x000200f8,
3520x000005f0,0x000500aa,0x00000012,0x000005f2,
3530x00001ce7,0x00000058,0x000300f7,0x000005f4,
3540x00000000,0x000400fa,0x000005f2,0x000005f3,
3550x000005f4,0x000200f8,0x000005f3,0x000200f9,
3560x000005fd,0x000200f8,0x000005f4,0x00050082,
3570x00000006,0x000005f6,0x00001ce7,0x00000063,
3580x00050084,0x00000006,0x000005f7,0x0000009e,
3590x000005f6,0x00050080,0x00000006,0x000005f8,
3600x000005f7,0x000000d8,0x00050051,0x00000006,
3610x0000068c,0x0000058d,0x00000000,0x00050084,
3620x00000006,0x0000068e,0x000005f8,0x0000009e,
3630x00050095,0x0000005e,0x0000068f,0x0000068c,
3640x0000068e,0x00050051,0x00000006,0x00000690,
3650x0000068f,0x00000001,0x00050051,0x00000006,
3660x00000691,0x0000068f,0x00000000,0x00050051,
3670x00000006,0x00000694,0x0000058d,0x00000001,
3680x00050080,0x00000006,0x00000696,0x00000694,
3690x00000690,0x00050050,0x00000007,0x00000697,
3700x00000691,0x00000696,0x0004007c,0x000000b1,
3710x00000684,0x00000697,0x00060041,0x000000b7,
3720x00000685,0x00000684,0x000000b6,0x000000b6,
3730x0006003d,0x00000006,0x00000686,0x00000685,
3740x00000002,0x00000004,0x00050080,0x00000006,
3750x00000679,0x000005f7,0x000000de,0x00050084,
3760x00000006,0x000006a9,0x00000679,0x0000009e,
3770x00050095,0x0000005e,0x000006aa,0x0000068c,
3780x000006a9,0x00050051,0x00000006,0x000006ab,
3790x000006aa,0x00000001,0x00050051,0x00000006,
3800x000006ac,0x000006aa,0x00000000,0x00050080,
3810x00000006,0x000006b1,0x00000694,0x000006ab,
3820x00050050,0x00000007,0x000006b2,0x000006ac,
3830x000006b1,0x0004007c,0x000000b1,0x0000069f,
3840x000006b2,0x00060041,0x000000b7,0x000006a0,
3850x0000069f,0x000000b6,0x000000b6,0x0006003d,
3860x00000006,0x000006a1,0x000006a0,0x00000002,
3870x00000004,0x000500b0,0x00000012,0x000006b9,
3880x00000583,0x000006a1,0x000400a8,0x00000012,
3890x000006ba,0x000006b9,0x000300f7,0x000006c9,
3900x00000000,0x000400fa,0x000006ba,0x000006bb,
3910x000006c9,0x000200f8,0x000006bb,0x000500aa,
3920x00000012,0x000006c0,0x00000583,0x000006a1,
3930x000300f7,0x000006c7,0x00000000,0x000400fa,
3940x000006c0,0x000006c1,0x000006c7,0x000200f8,
3950x000006c1,0x000500b0,0x00000012,0x000006c6,
3960x0000056f,0x00000686,0x000200f9,0x000006c7,
3970x000200f8,0x000006c7,0x000700f5,0x00000012,
3980x000006c8,0x000006c0,0x000006bb,0x000006c6,
3990x000006c1,0x000200f9,0x000006c9,0x000200f8,
4000x000006c9,0x000700f5,0x00000012,0x000006ca,
4010x000006b9,0x000005f4,0x000006c8,0x000006c7,
4020x000200f9,0x000005fd,0x000200f8,0x000005fd,
4030x000700f5,0x00000012,0x00001ce9,0x0000011e,
4040x000005f3,0x000006ca,0x000006c9,0x000200f9,
4050x00000592,0x000200f8,0x00000592,0x000700f5,
4060x00000012,0x00000593,0x0000058a,0x0000057e,
4070x00001ce9,0x000005fd,0x000300f7,0x00000595,
4080x00000000,0x000400fa,0x00000593,0x00000594,
4090x00000595,0x000200f8,0x00000594,0x000200f9,
4100x000005c0,0x000200f8,0x00000595,0x00050041,
4110x00000182,0x00000596,0x00000180,0x00000219,
4120x0004003d,0x00000006,0x00000597,0x00000596,
4130x000500aa,0x00000012,0x00000598,0x00000597,
4140x00000058,0x000300f7,0x0000059a,0x00000000,
4150x000400fa,0x00000598,0x00000599,0x0000059a,
4160x000200f8,0x00000599,0x000200f9,0x000005c0,
4170x000200f8,0x0000059a,0x00050050,0x00000007,
4180x000006d3,0x0000056f,0x00000583,0x000500c7,
4190x00000006,0x000006d6,0x00000438,0x00000063,
4200x000500ab,0x00000012,0x000006d7,0x000006d6,
4210x00000058,0x000300f7,0x000006dd,0x00000000,
4220x000400fa,0x000006d7,0x000006d8,0x000006dd,
4230x000200f8,0x000006d8,0x000500c7,0x00000006,
4240x000006db,0x00000582,0x0000018b,0x000500ab,
4250x00000012,0x000006dc,0x000006db,0x00000058,
4260x000200f9,0x000006dd,0x000200f8,0x000006dd,
4270x000700f5,0x00000012,0x000006de,0x000006d7,
4280x0000059a,0x000006dc,0x000006d8,0x000300f7,
4290x000006e4,0x00000000,0x000400fa,0x000006de,
4300x000006df,0x000006e4,0x000200f8,0x000006df,
4310x000500c5,0x00000006,0x000006e2,0x00000583,
4320x00000191,0x00060052,0x00000007,0x00001ab3,
4330x000006e2,0x000006d3,0x00000001,0x000200f9,
4340x000006e4,0x000200f8,0x000006e4,0x000700f5,
4350x00000007,0x00001ceb,0x000006d3,0x000006dd,
4360x00001ab3,0x000006df,0x00050041,0x0000020a,
4370x0000059d,0x00000180,0x00000220,0x0004003d,
4380x00000007,0x0000059e,0x0000059d,0x000300f7,
4390x00000721,0x00000000,0x000300fb,0x00000058,
4400x000006f8,0x000200f8,0x000006f8,0x00050051,
4410x00000006,0x00000728,0x00001ceb,0x00000000,
4420x00050095,0x0000005e,0x0000072b,0x00000728,
4430x00000586,0x00050051,0x00000006,0x0000072c,
4440x0000072b,0x00000001,0x00050051,0x00000006,
4450x0000072d,0x0000072b,0x00000000,0x00050051,
4460x00000006,0x00000730,0x00001ceb,0x00000001,
4470x00050080,0x00000006,0x00000735,0x00000730,
4480x0000072c,0x000200f9,0x000006fd,0x000200f8,
4490x000006fd,0x000700f5,0x00000006,0x00001ced,
4500x00000597,0x000006f8,0x00002195,0x00000713,
4510x000700f5,0x00000006,0x00001cec,0x00000058,
4520x000006f8,0x0000212a,0x00000713,0x000500b0,
4530x00000012,0x00000701,0x00001cec,0x00001ced,
4540x000400f6,0x00000714,0x00000713,0x00000000,
4550x000400fa,0x00000701,0x00000702,0x00000714,
4560x000200f8,0x00000702,0x00050080,0x00000006,
4570x00000705,0x00001cec,0x00001ced,0x000500c2,
4580x00000006,0x00000706,0x00000705,0x00000063,
4590x00050084,0x00000006,0x00000708,0x0000009e,
4600x00000706,0x00050051,0x00000006,0x00000754,
4610x0000059e,0x00000000,0x00050084,0x00000006,
4620x00000756,0x00000706,0x0000034a,0x00050095,
4630x0000005e,0x00000757,0x00000754,0x00000756,
4640x00050051,0x00000006,0x00000758,0x00000757,
4650x00000001,0x00050051,0x00000006,0x00000759,
4660x00000757,0x00000000,0x00050051,0x00000006,
4670x0000075c,0x0000059e,0x00000001,0x00050080,
4680x00000006,0x0000075e,0x0000075c,0x00000758,
4690x00050050,0x00000007,0x0000075f,0x00000759,
4700x0000075e,0x0004007c,0x000000b1,0x0000074c,
4710x0000075f,0x00060041,0x000000b7,0x0000074d,
4720x0000074c,0x000000b6,0x000000b6,0x0006003d,
4730x00000006,0x0000074e,0x0000074d,0x00000002,
4740x00000004,0x00050080,0x00000006,0x00000741,
4750x00000708,0x00000063,0x00050084,0x00000006,
4760x00000771,0x00000741,0x0000009e,0x00050095,
4770x0000005e,0x00000772,0x00000754,0x00000771,
4780x00050051,0x00000006,0x00000773,0x00000772,
4790x00000001,0x00050051,0x00000006,0x00000774,
4800x00000772,0x00000000,0x00050080,0x00000006,
4810x00000779,0x0000075c,0x00000773,0x00050050,
4820x00000007,0x0000077a,0x00000774,0x00000779,
4830x0004007c,0x000000b1,0x00000767,0x0000077a,
4840x00060041,0x000000b7,0x00000768,0x00000767,
4850x000000b6,0x000000b6,0x0006003d,0x00000006,
4860x00000769,0x00000768,0x00000002,0x00000004,
4870x000500b0,0x00000012,0x00000781,0x00000769,
4880x00000735,0x000400a8,0x00000012,0x00000782,
4890x00000781,0x000300f7,0x00000791,0x00000000,
4900x000400fa,0x00000782,0x00000783,0x00000791,
4910x000200f8,0x00000783,0x000500aa,0x00000012,
4920x00000788,0x00000769,0x00000735,0x000300f7,
4930x0000078f,0x00000000,0x000400fa,0x00000788,
4940x00000789,0x0000078f,0x000200f8,0x00000789,
4950x000500b0,0x00000012,0x0000078e,0x0000074e,
4960x0000072d,0x000200f9,0x0000078f,0x000200f8,
4970x0000078f,0x000700f5,0x00000012,0x00000790,
4980x00000788,0x00000783,0x0000078e,0x00000789,
4990x000200f9,0x00000791,0x000200f8,0x00000791,
5000x000700f5,0x00000012,0x00000792,0x00000781,
5010x00000702,0x00000790,0x0000078f,0x000300f7,
5020x00000712,0x00000000,0x000400fa,0x00000792,
5030x0000070d,0x00000710,0x000200f8,0x00000710,
5040x000200f9,0x00000712,0x000200f8,0x0000070d,
5050x00050080,0x00000006,0x0000070f,0x00000706,
5060x00000063,0x000200f9,0x00000712,0x000200f8,
5070x00000712,0x000700f5,0x00000006,0x0000212a,
5080x0000070f,0x0000070d,0x00001cec,0x00000710,
5090x000600a9,0x00000006,0x00002195,0x00000792,
5100x00001ced,0x00000706,0x000200f9,0x00000713,
5110x000200f8,0x00000713,0x000200f9,0x000006fd,
5120x000200f8,0x00000714,0x000500aa,0x00000012,
5130x00000716,0x00001cec,0x00000058,0x000300f7,
5140x00000718,0x00000000,0x000400fa,0x00000716,
5150x00000717,0x00000718,0x000200f8,0x00000717,
5160x000200f9,0x00000721,0x000200f8,0x00000718,
5170x00050082,0x00000006,0x0000071a,0x00001cec,
5180x00000063,0x00050084,0x00000006,0x0000071b,
5190x0000009e,0x0000071a,0x00050080,0x00000006,
5200x0000071c,0x0000071b,0x000000d8,0x00050051,
5210x00000006,0x000007b0,0x0000059e,0x00000000,
5220x00050084,0x00000006,0x000007b2,0x0000071c,
5230x0000009e,0x00050095,0x0000005e,0x000007b3,
5240x000007b0,0x000007b2,0x00050051,0x00000006,
5250x000007b4,0x000007b3,0x00000001,0x00050051,
5260x00000006,0x000007b5,0x000007b3,0x00000000,
5270x00050051,0x00000006,0x000007b8,0x0000059e,
5280x00000001,0x00050080,0x00000006,0x000007ba,
5290x000007b8,0x000007b4,0x00050050,0x00000007,
5300x000007bb,0x000007b5,0x000007ba,0x0004007c,
5310x000000b1,0x000007a8,0x000007bb,0x00060041,
5320x000000b7,0x000007a9,0x000007a8,0x000000b6,
5330x000000b6,0x0006003d,0x00000006,0x000007aa,
5340x000007a9,0x00000002,0x00000004,0x00050080,
5350x00000006,0x0000079d,0x0000071b,0x000000de,
5360x00050084,0x00000006,0x000007cd,0x0000079d,
5370x0000009e,0x00050095,0x0000005e,0x000007ce,
5380x000007b0,0x000007cd,0x00050051,0x00000006,
5390x000007cf,0x000007ce,0x00000001,0x00050051,
5400x00000006,0x000007d0,0x000007ce,0x00000000,
5410x00050080,0x00000006,0x000007d5,0x000007b8,
5420x000007cf,0x00050050,0x00000007,0x000007d6,
5430x000007d0,0x000007d5,0x0004007c,0x000000b1,
5440x000007c3,0x000007d6,0x00060041,0x000000b7,
5450x000007c4,0x000007c3,0x000000b6,0x000000b6,
5460x0006003d,0x00000006,0x000007c5,0x000007c4,
5470x00000002,0x00000004,0x000500b0,0x00000012,
5480x000007dd,0x00000730,0x000007c5,0x000400a8,
5490x00000012,0x000007de,0x000007dd,0x000300f7,
5500x000007ed,0x00000000,0x000400fa,0x000007de,
5510x000007df,0x000007ed,0x000200f8,0x000007df,
5520x000500aa,0x00000012,0x000007e4,0x00000730,
5530x000007c5,0x000300f7,0x000007eb,0x00000000,
5540x000400fa,0x000007e4,0x000007e5,0x000007eb,
5550x000200f8,0x000007e5,0x000500b0,0x00000012,
5560x000007ea,0x00000728,0x000007aa,0x000200f9,
5570x000007eb,0x000200f8,0x000007eb,0x000700f5,
5580x00000012,0x000007ec,0x000007e4,0x000007df,
5590x000007ea,0x000007e5,0x000200f9,0x000007ed,
5600x000200f8,0x000007ed,0x000700f5,0x00000012,
5610x000007ee,0x000007dd,0x00000718,0x000007ec,
5620x000007eb,0x000200f9,0x00000721,0x000200f8,
5630x00000721,0x000700f5,0x00000012,0x00001cee,
5640x0000011e,0x00000717,0x000007ee,0x000007ed,
5650x000300f7,0x000005a4,0x00000000,0x000400fa,
5660x00001cee,0x000005a3,0x000005a4,0x000200f8,
5670x000005a3,0x000200f9,0x000005c0,0x000200f8,
5680x000005a4,0x00050051,0x00000006,0x000005a6,
5690x00000476,0x00000002,0x000500c2,0x00000006,
5700x000005a9,0x00000582,0x000000e4,0x000500aa,
5710x00000012,0x000005ad,0x000005a6,0x00000058,
5720x000300f7,0x000005b2,0x00000000,0x000400fa,
5730x000005ad,0x000005ae,0x000005b2,0x000200f8,
5740x000005ae,0x000500aa,0x00000012,0x000005b1,
5750x000005a9,0x00000058,0x000200f9,0x000005b2,
5760x000200f8,0x000005b2,0x000700f5,0x00000012,
5770x000005b3,0x000005ad,0x000005a4,0x000005b1,
5780x000005ae,0x000400a8,0x00000012,0x000005b4,
5790x000005b3,0x000300f7,0x000005be,0x00000000,
5800x000400fa,0x000005b4,0x000005b5,0x000005be,
5810x000200f8,0x000005b5,0x000500c7,0x00000006,
5820x000007f6,0x000005a9,0x0000017b,0x00050050,
5830x00000007,0x000007f7,0x000005a6,0x000007f6,
5840x000300f7,0x00000801,0x00000000,0x000400fa,
5850x000006d7,0x000007fc,0x00000801,0x000200f8,
5860x000007fc,0x000500c7,0x00000006,0x000007ff,
5870x000005a9,0x0000018b,0x000500ab,0x00000012,
5880x00000800,0x000007ff,0x00000058,0x000200f9,
5890x00000801,0x000200f8,0x00000801,0x000700f5,
5900x00000012,0x00000802,0x000006d7,0x000005b5,
5910x00000800,0x000007fc,0x000300f7,0x00000808,
5920x00000000,0x000400fa,0x00000802,0x00000803,
5930x00000808,0x000200f8,0x00000803,0x000500c5,
5940x00000006,0x00000806,0x000007f6,0x00000191,
5950x00060052,0x00000007,0x00001ad5,0x00000806,
5960x000007f7,0x00000001,0x000200f9,0x00000808,
5970x000200f8,0x00000808,0x000700f5,0x00000007,
5980x00001cf0,0x000007f7,0x00000801,0x00001ad5,
5990x00000803,0x000300f7,0x00000845,0x00000000,
6000x000300fb,0x00000058,0x0000081c,0x000200f8,
6010x0000081c,0x00050051,0x00000006,0x0000084c,
6020x00001cf0,0x00000000,0x00050095,0x0000005e,
6030x0000084f,0x0000084c,0x00000586,0x00050051,
6040x00000006,0x00000850,0x0000084f,0x00000001,
6050x00050051,0x00000006,0x00000851,0x0000084f,
6060x00000000,0x00050051,0x00000006,0x00000854,
6070x00001cf0,0x00000001,0x00050080,0x00000006,
6080x00000859,0x00000854,0x00000850,0x000200f9,
6090x00000821,0x000200f8,0x00000821,0x000700f5,
6100x00000006,0x00001cf2,0x00000597,0x0000081c,
6110x00002196,0x00000837,0x000700f5,0x00000006,
6120x00001cf1,0x00000058,0x0000081c,0x00002130,
6130x00000837,0x000500b0,0x00000012,0x00000825,
6140x00001cf1,0x00001cf2,0x000400f6,0x00000838,
6150x00000837,0x00000000,0x000400fa,0x00000825,
6160x00000826,0x00000838,0x000200f8,0x00000826,
6170x00050080,0x00000006,0x00000829,0x00001cf1,
6180x00001cf2,0x000500c2,0x00000006,0x0000082a,
6190x00000829,0x00000063,0x00050084,0x00000006,
6200x0000082c,0x0000009e,0x0000082a,0x00050051,
6210x00000006,0x00000878,0x0000059e,0x00000000,
6220x00050084,0x00000006,0x0000087a,0x0000082a,
6230x0000034a,0x00050095,0x0000005e,0x0000087b,
6240x00000878,0x0000087a,0x00050051,0x00000006,
6250x0000087c,0x0000087b,0x00000001,0x00050051,
6260x00000006,0x0000087d,0x0000087b,0x00000000,
6270x00050051,0x00000006,0x00000880,0x0000059e,
6280x00000001,0x00050080,0x00000006,0x00000882,
6290x00000880,0x0000087c,0x00050050,0x00000007,
6300x00000883,0x0000087d,0x00000882,0x0004007c,
6310x000000b1,0x00000870,0x00000883,0x00060041,
6320x000000b7,0x00000871,0x00000870,0x000000b6,
6330x000000b6,0x0006003d,0x00000006,0x00000872,
6340x00000871,0x00000002,0x00000004,0x00050080,
6350x00000006,0x00000865,0x0000082c,0x00000063,
6360x00050084,0x00000006,0x00000895,0x00000865,
6370x0000009e,0x00050095,0x0000005e,0x00000896,
6380x00000878,0x00000895,0x00050051,0x00000006,
6390x00000897,0x00000896,0x00000001,0x00050051,
6400x00000006,0x00000898,0x00000896,0x00000000,
6410x00050080,0x00000006,0x0000089d,0x00000880,
6420x00000897,0x00050050,0x00000007,0x0000089e,
6430x00000898,0x0000089d,0x0004007c,0x000000b1,
6440x0000088b,0x0000089e,0x00060041,0x000000b7,
6450x0000088c,0x0000088b,0x000000b6,0x000000b6,
6460x0006003d,0x00000006,0x0000088d,0x0000088c,
6470x00000002,0x00000004,0x000500b0,0x00000012,
6480x000008a5,0x0000088d,0x00000859,0x000400a8,
6490x00000012,0x000008a6,0x000008a5,0x000300f7,
6500x000008b5,0x00000000,0x000400fa,0x000008a6,
6510x000008a7,0x000008b5,0x000200f8,0x000008a7,
6520x000500aa,0x00000012,0x000008ac,0x0000088d,
6530x00000859,0x000300f7,0x000008b3,0x00000000,
6540x000400fa,0x000008ac,0x000008ad,0x000008b3,
6550x000200f8,0x000008ad,0x000500b0,0x00000012,
6560x000008b2,0x00000872,0x00000851,0x000200f9,
6570x000008b3,0x000200f8,0x000008b3,0x000700f5,
6580x00000012,0x000008b4,0x000008ac,0x000008a7,
6590x000008b2,0x000008ad,0x000200f9,0x000008b5,
6600x000200f8,0x000008b5,0x000700f5,0x00000012,
6610x000008b6,0x000008a5,0x00000826,0x000008b4,
6620x000008b3,0x000300f7,0x00000836,0x00000000,
6630x000400fa,0x000008b6,0x00000831,0x00000834,
6640x000200f8,0x00000834,0x000200f9,0x00000836,
6650x000200f8,0x00000831,0x00050080,0x00000006,
6660x00000833,0x0000082a,0x00000063,0x000200f9,
6670x00000836,0x000200f8,0x00000836,0x000700f5,
6680x00000006,0x00002130,0x00000833,0x00000831,
6690x00001cf1,0x00000834,0x000600a9,0x00000006,
6700x00002196,0x000008b6,0x00001cf2,0x0000082a,
6710x000200f9,0x00000837,0x000200f8,0x00000837,
6720x000200f9,0x00000821,0x000200f8,0x00000838,
6730x000500aa,0x00000012,0x0000083a,0x00001cf1,
6740x00000058,0x000300f7,0x0000083c,0x00000000,
6750x000400fa,0x0000083a,0x0000083b,0x0000083c,
6760x000200f8,0x0000083b,0x000200f9,0x00000845,
6770x000200f8,0x0000083c,0x00050082,0x00000006,
6780x0000083e,0x00001cf1,0x00000063,0x00050084,
6790x00000006,0x0000083f,0x0000009e,0x0000083e,
6800x00050080,0x00000006,0x00000840,0x0000083f,
6810x000000d8,0x00050051,0x00000006,0x000008d4,
6820x0000059e,0x00000000,0x00050084,0x00000006,
6830x000008d6,0x00000840,0x0000009e,0x00050095,
6840x0000005e,0x000008d7,0x000008d4,0x000008d6,
6850x00050051,0x00000006,0x000008d8,0x000008d7,
6860x00000001,0x00050051,0x00000006,0x000008d9,
6870x000008d7,0x00000000,0x00050051,0x00000006,
6880x000008dc,0x0000059e,0x00000001,0x00050080,
6890x00000006,0x000008de,0x000008dc,0x000008d8,
6900x00050050,0x00000007,0x000008df,0x000008d9,
6910x000008de,0x0004007c,0x000000b1,0x000008cc,
6920x000008df,0x00060041,0x000000b7,0x000008cd,
6930x000008cc,0x000000b6,0x000000b6,0x0006003d,
6940x00000006,0x000008ce,0x000008cd,0x00000002,
6950x00000004,0x00050080,0x00000006,0x000008c1,
6960x0000083f,0x000000de,0x00050084,0x00000006,
6970x000008f1,0x000008c1,0x0000009e,0x00050095,
6980x0000005e,0x000008f2,0x000008d4,0x000008f1,
6990x00050051,0x00000006,0x000008f3,0x000008f2,
7000x00000001,0x00050051,0x00000006,0x000008f4,
7010x000008f2,0x00000000,0x00050080,0x00000006,
7020x000008f9,0x000008dc,0x000008f3,0x00050050,
7030x00000007,0x000008fa,0x000008f4,0x000008f9,
7040x0004007c,0x000000b1,0x000008e7,0x000008fa,
7050x00060041,0x000000b7,0x000008e8,0x000008e7,
7060x000000b6,0x000000b6,0x0006003d,0x00000006,
7070x000008e9,0x000008e8,0x00000002,0x00000004,
7080x000500b0,0x00000012,0x00000901,0x00000854,
7090x000008e9,0x000400a8,0x00000012,0x00000902,
7100x00000901,0x000300f7,0x00000911,0x00000000,
7110x000400fa,0x00000902,0x00000903,0x00000911,
7120x000200f8,0x00000903,0x000500aa,0x00000012,
7130x00000908,0x00000854,0x000008e9,0x000300f7,
7140x0000090f,0x00000000,0x000400fa,0x00000908,
7150x00000909,0x0000090f,0x000200f8,0x00000909,
7160x000500b0,0x00000012,0x0000090e,0x0000084c,
7170x000008ce,0x000200f9,0x0000090f,0x000200f8,
7180x0000090f,0x000700f5,0x00000012,0x00000910,
7190x00000908,0x00000903,0x0000090e,0x00000909,
7200x000200f9,0x00000911,0x000200f8,0x00000911,
7210x000700f5,0x00000012,0x00000912,0x00000901,
7220x0000083c,0x00000910,0x0000090f,0x000200f9,
7230x00000845,0x000200f8,0x00000845,0x000700f5,
7240x00000012,0x00001cf3,0x0000011e,0x0000083b,
7250x00000912,0x00000911,0x000200f9,0x000005be,
7260x000200f8,0x000005be,0x000700f5,0x00000012,
7270x000005bf,0x000005b4,0x000005b2,0x00001cf3,
7280x00000845,0x000200f9,0x000005c0,0x000200f8,
7290x000005c0,0x000d00f5,0x00000012,0x00001cf4,
7300x0000011e,0x0000057d,0x00000217,0x00000594,
7310x0000011e,0x00000599,0x00000217,0x000005a3,
7320x000005bf,0x000005be,0x000400a8,0x00000012,
7330x00000478,0x00001cf4,0x000300f7,0x0000047a,
7340x00000000,0x000400fa,0x00000478,0x00000479,
7350x0000047a,0x000200f8,0x00000479,0x00050080,
7360x00000006,0x0000047e,0x00000472,0x00000063,
7370x00060041,0x00000474,0x00000480,0x0000046f,
7380x000000b6,0x0000047e,0x0006003d,0x00000027,
7390x00000481,0x00000480,0x00000002,0x00000010,
7400x000300f7,0x0000097b,0x00000000,0x000300fb,
7410x00000058,0x00000928,0x000200f8,0x00000928,
7420x00050051,0x00000006,0x0000092a,0x00000481,
7430x00000000,0x000500aa,0x00000012,0x0000092b,
7440x0000092a,0x00000058,0x000300f7,0x00000930,
7450x00000000,0x000400fa,0x0000092b,0x0000092c,
7460x00000930,0x000200f8,0x0000092c,0x00050051,
7470x00000006,0x0000092e,0x00000481,0x00000001,
7480x000500aa,0x00000012,0x0000092f,0x0000092e,
7490x00000058,0x000200f9,0x00000930,0x000200f8,
7500x00000930,0x000700f5,0x00000012,0x00000931,
7510x0000092b,0x00000928,0x0000092f,0x0000092c,
7520x000300f7,0x00000936,0x00000000,0x000400fa,
7530x00000931,0x00000932,0x00000936,0x000200f8,
7540x00000932,0x00050051,0x00000006,0x00000934,
7550x00000481,0x00000002,0x000500aa,0x00000012,
7560x00000935,0x00000934,0x00000058,0x000200f9,
7570x00000936,0x000200f8,0x00000936,0x000700f5,
7580x00000012,0x00000937,0x00000931,0x00000930,
7590x00000935,0x00000932,0x000300f7,0x00000939,
7600x00000000,0x000400fa,0x00000937,0x00000938,
7610x00000939,0x000200f8,0x00000938,0x000200f9,
7620x0000097b,0x000200f8,0x00000939,0x00050051,
7630x00000006,0x0000093d,0x00000481,0x00000001,
7640x000500c7,0x00000006,0x0000093e,0x0000093d,
7650x0000017b,0x00050051,0x00000006,0x00000941,
7660x00000481,0x00000003,0x00050041,0x00000182,
7670x00000943,0x00000180,0x00000201,0x0004003d,
7680x00000006,0x00000944,0x00000943,0x000500ab,
7690x00000012,0x00000945,0x00000944,0x00000058,
7700x000300f7,0x0000094d,0x00000000,0x000400fa,
7710x00000945,0x00000946,0x0000094d,0x000200f8,
7720x00000946,0x00050041,0x0000020a,0x00000947,
7730x00000180,0x00000207,0x0004003d,0x00000007,
7740x00000948,0x00000947,0x000300f7,0x000009b8,
7750x00000000,0x000300fb,0x00000058,0x0000098f,
7760x000200f8,0x0000098f,0x00050095,0x0000005e,
7770x000009c2,0x0000092a,0x00000063,0x00050051,
7780x00000006,0x000009c3,0x000009c2,0x00000001,
7790x00050051,0x00000006,0x000009c4,0x000009c2,
7800x00000000,0x00050080,0x00000006,0x000009cc,
7810x0000093e,0x000009c3,0x000200f9,0x00000994,
7820x000200f8,0x00000994,0x000700f5,0x00000006,
7830x00001cf6,0x00000944,0x0000098f,0x00002197,
7840x000009aa,0x000700f5,0x00000006,0x00001cf5,
7850x00000058,0x0000098f,0x00002136,0x000009aa,
7860x000500b0,0x00000012,0x00000998,0x00001cf5,
7870x00001cf6,0x000400f6,0x000009ab,0x000009aa,
7880x00000000,0x000400fa,0x00000998,0x00000999,
7890x000009ab,0x000200f8,0x00000999,0x00050080,
7900x00000006,0x0000099c,0x00001cf5,0x00001cf6,
7910x000500c2,0x00000006,0x0000099d,0x0000099c,
7920x00000063,0x00050084,0x00000006,0x0000099f,
7930x0000009e,0x0000099d,0x00050051,0x00000006,
7940x000009eb,0x00000948,0x00000000,0x00050084,
7950x00000006,0x000009ed,0x0000099d,0x0000034a,
7960x00050095,0x0000005e,0x000009ee,0x000009eb,
7970x000009ed,0x00050051,0x00000006,0x000009ef,
7980x000009ee,0x00000001,0x00050051,0x00000006,
7990x000009f0,0x000009ee,0x00000000,0x00050051,
8000x00000006,0x000009f3,0x00000948,0x00000001,
8010x00050080,0x00000006,0x000009f5,0x000009f3,
8020x000009ef,0x00050050,0x00000007,0x000009f6,
8030x000009f0,0x000009f5,0x0004007c,0x000000b1,
8040x000009e3,0x000009f6,0x00060041,0x000000b7,
8050x000009e4,0x000009e3,0x000000b6,0x000000b6,
8060x0006003d,0x00000006,0x000009e5,0x000009e4,
8070x00000002,0x00000004,0x00050080,0x00000006,
8080x000009d8,0x0000099f,0x00000063,0x00050084,
8090x00000006,0x00000a08,0x000009d8,0x0000009e,
8100x00050095,0x0000005e,0x00000a09,0x000009eb,
8110x00000a08,0x00050051,0x00000006,0x00000a0a,
8120x00000a09,0x00000001,0x00050051,0x00000006,
8130x00000a0b,0x00000a09,0x00000000,0x00050080,
8140x00000006,0x00000a10,0x000009f3,0x00000a0a,
8150x00050050,0x00000007,0x00000a11,0x00000a0b,
8160x00000a10,0x0004007c,0x000000b1,0x000009fe,
8170x00000a11,0x00060041,0x000000b7,0x000009ff,
8180x000009fe,0x000000b6,0x000000b6,0x0006003d,
8190x00000006,0x00000a00,0x000009ff,0x00000002,
8200x00000004,0x000500b0,0x00000012,0x00000a18,
8210x00000a00,0x000009cc,0x000400a8,0x00000012,
8220x00000a19,0x00000a18,0x000300f7,0x00000a28,
8230x00000000,0x000400fa,0x00000a19,0x00000a1a,
8240x00000a28,0x000200f8,0x00000a1a,0x000500aa,
8250x00000012,0x00000a1f,0x00000a00,0x000009cc,
8260x000300f7,0x00000a26,0x00000000,0x000400fa,
8270x00000a1f,0x00000a20,0x00000a26,0x000200f8,
8280x00000a20,0x000500b0,0x00000012,0x00000a25,
8290x000009e5,0x000009c4,0x000200f9,0x00000a26,
8300x000200f8,0x00000a26,0x000700f5,0x00000012,
8310x00000a27,0x00000a1f,0x00000a1a,0x00000a25,
8320x00000a20,0x000200f9,0x00000a28,0x000200f8,
8330x00000a28,0x000700f5,0x00000012,0x00000a29,
8340x00000a18,0x00000999,0x00000a27,0x00000a26,
8350x000300f7,0x000009a9,0x00000000,0x000400fa,
8360x00000a29,0x000009a4,0x000009a7,0x000200f8,
8370x000009a7,0x000200f9,0x000009a9,0x000200f8,
8380x000009a4,0x00050080,0x00000006,0x000009a6,
8390x0000099d,0x00000063,0x000200f9,0x000009a9,
8400x000200f8,0x000009a9,0x000700f5,0x00000006,
8410x00002136,0x000009a6,0x000009a4,0x00001cf5,
8420x000009a7,0x000600a9,0x00000006,0x00002197,
8430x00000a29,0x00001cf6,0x0000099d,0x000200f9,
8440x000009aa,0x000200f8,0x000009aa,0x000200f9,
8450x00000994,0x000200f8,0x000009ab,0x000500aa,
8460x00000012,0x000009ad,0x00001cf5,0x00000058,
8470x000300f7,0x000009af,0x00000000,0x000400fa,
8480x000009ad,0x000009ae,0x000009af,0x000200f8,
8490x000009ae,0x000200f9,0x000009b8,0x000200f8,
8500x000009af,0x00050082,0x00000006,0x000009b1,
8510x00001cf5,0x00000063,0x00050084,0x00000006,
8520x000009b2,0x0000009e,0x000009b1,0x00050080,
8530x00000006,0x000009b3,0x000009b2,0x000000d8,
8540x00050051,0x00000006,0x00000a47,0x00000948,
8550x00000000,0x00050084,0x00000006,0x00000a49,
8560x000009b3,0x0000009e,0x00050095,0x0000005e,
8570x00000a4a,0x00000a47,0x00000a49,0x00050051,
8580x00000006,0x00000a4b,0x00000a4a,0x00000001,
8590x00050051,0x00000006,0x00000a4c,0x00000a4a,
8600x00000000,0x00050051,0x00000006,0x00000a4f,
8610x00000948,0x00000001,0x00050080,0x00000006,
8620x00000a51,0x00000a4f,0x00000a4b,0x00050050,
8630x00000007,0x00000a52,0x00000a4c,0x00000a51,
8640x0004007c,0x000000b1,0x00000a3f,0x00000a52,
8650x00060041,0x000000b7,0x00000a40,0x00000a3f,
8660x000000b6,0x000000b6,0x0006003d,0x00000006,
8670x00000a41,0x00000a40,0x00000002,0x00000004,
8680x00050080,0x00000006,0x00000a34,0x000009b2,
8690x000000de,0x00050084,0x00000006,0x00000a64,
8700x00000a34,0x0000009e,0x00050095,0x0000005e,
8710x00000a65,0x00000a47,0x00000a64,0x00050051,
8720x00000006,0x00000a66,0x00000a65,0x00000001,
8730x00050051,0x00000006,0x00000a67,0x00000a65,
8740x00000000,0x00050080,0x00000006,0x00000a6c,
8750x00000a4f,0x00000a66,0x00050050,0x00000007,
8760x00000a6d,0x00000a67,0x00000a6c,0x0004007c,
8770x000000b1,0x00000a5a,0x00000a6d,0x00060041,
8780x000000b7,0x00000a5b,0x00000a5a,0x000000b6,
8790x000000b6,0x0006003d,0x00000006,0x00000a5c,
8800x00000a5b,0x00000002,0x00000004,0x000500b0,
8810x00000012,0x00000a74,0x0000093e,0x00000a5c,
8820x000400a8,0x00000012,0x00000a75,0x00000a74,
8830x000300f7,0x00000a84,0x00000000,0x000400fa,
8840x00000a75,0x00000a76,0x00000a84,0x000200f8,
8850x00000a76,0x000500aa,0x00000012,0x00000a7b,
8860x0000093e,0x00000a5c,0x000300f7,0x00000a82,
8870x00000000,0x000400fa,0x00000a7b,0x00000a7c,
8880x00000a82,0x000200f8,0x00000a7c,0x000500b0,
8890x00000012,0x00000a81,0x0000092a,0x00000a41,
8900x000200f9,0x00000a82,0x000200f8,0x00000a82,
8910x000700f5,0x00000012,0x00000a83,0x00000a7b,
8920x00000a76,0x00000a81,0x00000a7c,0x000200f9,
8930x00000a84,0x000200f8,0x00000a84,0x000700f5,
8940x00000012,0x00000a85,0x00000a74,0x000009af,
8950x00000a83,0x00000a82,0x000200f9,0x000009b8,
8960x000200f8,0x000009b8,0x000700f5,0x00000012,
8970x00001cf7,0x0000011e,0x000009ae,0x00000a85,
8980x00000a84,0x000200f9,0x0000094d,0x000200f8,
8990x0000094d,0x000700f5,0x00000012,0x0000094e,
9000x00000945,0x00000939,0x00001cf7,0x000009b8,
9010x000300f7,0x00000950,0x00000000,0x000400fa,
9020x0000094e,0x0000094f,0x00000950,0x000200f8,
9030x0000094f,0x000200f9,0x0000097b,0x000200f8,
9040x00000950,0x00050041,0x00000182,0x00000951,
9050x00000180,0x00000219,0x0004003d,0x00000006,
9060x00000952,0x00000951,0x000500aa,0x00000012,
9070x00000953,0x00000952,0x00000058,0x000300f7,
9080x00000955,0x00000000,0x000400fa,0x00000953,
9090x00000954,0x00000955,0x000200f8,0x00000954,
9100x000200f9,0x0000097b,0x000200f8,0x00000955,
9110x00050050,0x00000007,0x00000a8e,0x0000092a,
9120x0000093e,0x000500c7,0x00000006,0x00000a91,
9130x00000438,0x00000063,0x000500ab,0x00000012,
9140x00000a92,0x00000a91,0x00000058,0x000300f7,
9150x00000a98,0x00000000,0x000400fa,0x00000a92,
9160x00000a93,0x00000a98,0x000200f8,0x00000a93,
9170x000500c7,0x00000006,0x00000a96,0x0000093d,
9180x0000018b,0x000500ab,0x00000012,0x00000a97,
9190x00000a96,0x00000058,0x000200f9,0x00000a98,
9200x000200f8,0x00000a98,0x000700f5,0x00000012,
9210x00000a99,0x00000a92,0x00000955,0x00000a97,
9220x00000a93,0x000300f7,0x00000a9f,0x00000000,
9230x000400fa,0x00000a99,0x00000a9a,0x00000a9f,
9240x000200f8,0x00000a9a,0x000500c5,0x00000006,
9250x00000a9d,0x0000093e,0x00000191,0x00060052,
9260x00000007,0x00001b11,0x00000a9d,0x00000a8e,
9270x00000001,0x000200f9,0x00000a9f,0x000200f8,
9280x00000a9f,0x000700f5,0x00000007,0x00001cf9,
9290x00000a8e,0x00000a98,0x00001b11,0x00000a9a,
9300x00050041,0x0000020a,0x00000958,0x00000180,
9310x00000220,0x0004003d,0x00000007,0x00000959,
9320x00000958,0x000300f7,0x00000adc,0x00000000,
9330x000300fb,0x00000058,0x00000ab3,0x000200f8,
9340x00000ab3,0x00050051,0x00000006,0x00000ae3,
9350x00001cf9,0x00000000,0x00050095,0x0000005e,
9360x00000ae6,0x00000ae3,0x00000941,0x00050051,
9370x00000006,0x00000ae7,0x00000ae6,0x00000001,
9380x00050051,0x00000006,0x00000ae8,0x00000ae6,
9390x00000000,0x00050051,0x00000006,0x00000aeb,
9400x00001cf9,0x00000001,0x00050080,0x00000006,
9410x00000af0,0x00000aeb,0x00000ae7,0x000200f9,
9420x00000ab8,0x000200f8,0x00000ab8,0x000700f5,
9430x00000006,0x00001cfb,0x00000952,0x00000ab3,
9440x00002198,0x00000ace,0x000700f5,0x00000006,
9450x00001cfa,0x00000058,0x00000ab3,0x0000213c,
9460x00000ace,0x000500b0,0x00000012,0x00000abc,
9470x00001cfa,0x00001cfb,0x000400f6,0x00000acf,
9480x00000ace,0x00000000,0x000400fa,0x00000abc,
9490x00000abd,0x00000acf,0x000200f8,0x00000abd,
9500x00050080,0x00000006,0x00000ac0,0x00001cfa,
9510x00001cfb,0x000500c2,0x00000006,0x00000ac1,
9520x00000ac0,0x00000063,0x00050084,0x00000006,
9530x00000ac3,0x0000009e,0x00000ac1,0x00050051,
9540x00000006,0x00000b0f,0x00000959,0x00000000,
9550x00050084,0x00000006,0x00000b11,0x00000ac1,
9560x0000034a,0x00050095,0x0000005e,0x00000b12,
9570x00000b0f,0x00000b11,0x00050051,0x00000006,
9580x00000b13,0x00000b12,0x00000001,0x00050051,
9590x00000006,0x00000b14,0x00000b12,0x00000000,
9600x00050051,0x00000006,0x00000b17,0x00000959,
9610x00000001,0x00050080,0x00000006,0x00000b19,
9620x00000b17,0x00000b13,0x00050050,0x00000007,
9630x00000b1a,0x00000b14,0x00000b19,0x0004007c,
9640x000000b1,0x00000b07,0x00000b1a,0x00060041,
9650x000000b7,0x00000b08,0x00000b07,0x000000b6,
9660x000000b6,0x0006003d,0x00000006,0x00000b09,
9670x00000b08,0x00000002,0x00000004,0x00050080,
9680x00000006,0x00000afc,0x00000ac3,0x00000063,
9690x00050084,0x00000006,0x00000b2c,0x00000afc,
9700x0000009e,0x00050095,0x0000005e,0x00000b2d,
9710x00000b0f,0x00000b2c,0x00050051,0x00000006,
9720x00000b2e,0x00000b2d,0x00000001,0x00050051,
9730x00000006,0x00000b2f,0x00000b2d,0x00000000,
9740x00050080,0x00000006,0x00000b34,0x00000b17,
9750x00000b2e,0x00050050,0x00000007,0x00000b35,
9760x00000b2f,0x00000b34,0x0004007c,0x000000b1,
9770x00000b22,0x00000b35,0x00060041,0x000000b7,
9780x00000b23,0x00000b22,0x000000b6,0x000000b6,
9790x0006003d,0x00000006,0x00000b24,0x00000b23,
9800x00000002,0x00000004,0x000500b0,0x00000012,
9810x00000b3c,0x00000b24,0x00000af0,0x000400a8,
9820x00000012,0x00000b3d,0x00000b3c,0x000300f7,
9830x00000b4c,0x00000000,0x000400fa,0x00000b3d,
9840x00000b3e,0x00000b4c,0x000200f8,0x00000b3e,
9850x000500aa,0x00000012,0x00000b43,0x00000b24,
9860x00000af0,0x000300f7,0x00000b4a,0x00000000,
9870x000400fa,0x00000b43,0x00000b44,0x00000b4a,
9880x000200f8,0x00000b44,0x000500b0,0x00000012,
9890x00000b49,0x00000b09,0x00000ae8,0x000200f9,
9900x00000b4a,0x000200f8,0x00000b4a,0x000700f5,
9910x00000012,0x00000b4b,0x00000b43,0x00000b3e,
9920x00000b49,0x00000b44,0x000200f9,0x00000b4c,
9930x000200f8,0x00000b4c,0x000700f5,0x00000012,
9940x00000b4d,0x00000b3c,0x00000abd,0x00000b4b,
9950x00000b4a,0x000300f7,0x00000acd,0x00000000,
9960x000400fa,0x00000b4d,0x00000ac8,0x00000acb,
9970x000200f8,0x00000acb,0x000200f9,0x00000acd,
9980x000200f8,0x00000ac8,0x00050080,0x00000006,
9990x00000aca,0x00000ac1,0x00000063,0x000200f9,
10000x00000acd,0x000200f8,0x00000acd,0x000700f5,
10010x00000006,0x0000213c,0x00000aca,0x00000ac8,
10020x00001cfa,0x00000acb,0x000600a9,0x00000006,
10030x00002198,0x00000b4d,0x00001cfb,0x00000ac1,
10040x000200f9,0x00000ace,0x000200f8,0x00000ace,
10050x000200f9,0x00000ab8,0x000200f8,0x00000acf,
10060x000500aa,0x00000012,0x00000ad1,0x00001cfa,
10070x00000058,0x000300f7,0x00000ad3,0x00000000,
10080x000400fa,0x00000ad1,0x00000ad2,0x00000ad3,
10090x000200f8,0x00000ad2,0x000200f9,0x00000adc,
10100x000200f8,0x00000ad3,0x00050082,0x00000006,
10110x00000ad5,0x00001cfa,0x00000063,0x00050084,
10120x00000006,0x00000ad6,0x0000009e,0x00000ad5,
10130x00050080,0x00000006,0x00000ad7,0x00000ad6,
10140x000000d8,0x00050051,0x00000006,0x00000b6b,
10150x00000959,0x00000000,0x00050084,0x00000006,
10160x00000b6d,0x00000ad7,0x0000009e,0x00050095,
10170x0000005e,0x00000b6e,0x00000b6b,0x00000b6d,
10180x00050051,0x00000006,0x00000b6f,0x00000b6e,
10190x00000001,0x00050051,0x00000006,0x00000b70,
10200x00000b6e,0x00000000,0x00050051,0x00000006,
10210x00000b73,0x00000959,0x00000001,0x00050080,
10220x00000006,0x00000b75,0x00000b73,0x00000b6f,
10230x00050050,0x00000007,0x00000b76,0x00000b70,
10240x00000b75,0x0004007c,0x000000b1,0x00000b63,
10250x00000b76,0x00060041,0x000000b7,0x00000b64,
10260x00000b63,0x000000b6,0x000000b6,0x0006003d,
10270x00000006,0x00000b65,0x00000b64,0x00000002,
10280x00000004,0x00050080,0x00000006,0x00000b58,
10290x00000ad6,0x000000de,0x00050084,0x00000006,
10300x00000b88,0x00000b58,0x0000009e,0x00050095,
10310x0000005e,0x00000b89,0x00000b6b,0x00000b88,
10320x00050051,0x00000006,0x00000b8a,0x00000b89,
10330x00000001,0x00050051,0x00000006,0x00000b8b,
10340x00000b89,0x00000000,0x00050080,0x00000006,
10350x00000b90,0x00000b73,0x00000b8a,0x00050050,
10360x00000007,0x00000b91,0x00000b8b,0x00000b90,
10370x0004007c,0x000000b1,0x00000b7e,0x00000b91,
10380x00060041,0x000000b7,0x00000b7f,0x00000b7e,
10390x000000b6,0x000000b6,0x0006003d,0x00000006,
10400x00000b80,0x00000b7f,0x00000002,0x00000004,
10410x000500b0,0x00000012,0x00000b98,0x00000aeb,
10420x00000b80,0x000400a8,0x00000012,0x00000b99,
10430x00000b98,0x000300f7,0x00000ba8,0x00000000,
10440x000400fa,0x00000b99,0x00000b9a,0x00000ba8,
10450x000200f8,0x00000b9a,0x000500aa,0x00000012,
10460x00000b9f,0x00000aeb,0x00000b80,0x000300f7,
10470x00000ba6,0x00000000,0x000400fa,0x00000b9f,
10480x00000ba0,0x00000ba6,0x000200f8,0x00000ba0,
10490x000500b0,0x00000012,0x00000ba5,0x00000ae3,
10500x00000b65,0x000200f9,0x00000ba6,0x000200f8,
10510x00000ba6,0x000700f5,0x00000012,0x00000ba7,
10520x00000b9f,0x00000b9a,0x00000ba5,0x00000ba0,
10530x000200f9,0x00000ba8,0x000200f8,0x00000ba8,
10540x000700f5,0x00000012,0x00000ba9,0x00000b98,
10550x00000ad3,0x00000ba7,0x00000ba6,0x000200f9,
10560x00000adc,0x000200f8,0x00000adc,0x000700f5,
10570x00000012,0x00001cfc,0x0000011e,0x00000ad2,
10580x00000ba9,0x00000ba8,0x000300f7,0x0000095f,
10590x00000000,0x000400fa,0x00001cfc,0x0000095e,
10600x0000095f,0x000200f8,0x0000095e,0x000200f9,
10610x0000097b,0x000200f8,0x0000095f,0x00050051,
10620x00000006,0x00000961,0x00000481,0x00000002,
10630x000500c2,0x00000006,0x00000964,0x0000093d,
10640x000000e4,0x000500aa,0x00000012,0x00000968,
10650x00000961,0x00000058,0x000300f7,0x0000096d,
10660x00000000,0x000400fa,0x00000968,0x00000969,
10670x0000096d,0x000200f8,0x00000969,0x000500aa,
10680x00000012,0x0000096c,0x00000964,0x00000058,
10690x000200f9,0x0000096d,0x000200f8,0x0000096d,
10700x000700f5,0x00000012,0x0000096e,0x00000968,
10710x0000095f,0x0000096c,0x00000969,0x000400a8,
10720x00000012,0x0000096f,0x0000096e,0x000300f7,
10730x00000979,0x00000000,0x000400fa,0x0000096f,
10740x00000970,0x00000979,0x000200f8,0x00000970,
10750x000500c7,0x00000006,0x00000bb1,0x00000964,
10760x0000017b,0x00050050,0x00000007,0x00000bb2,
10770x00000961,0x00000bb1,0x000300f7,0x00000bbc,
10780x00000000,0x000400fa,0x00000a92,0x00000bb7,
10790x00000bbc,0x000200f8,0x00000bb7,0x000500c7,
10800x00000006,0x00000bba,0x00000964,0x0000018b,
10810x000500ab,0x00000012,0x00000bbb,0x00000bba,
10820x00000058,0x000200f9,0x00000bbc,0x000200f8,
10830x00000bbc,0x000700f5,0x00000012,0x00000bbd,
10840x00000a92,0x00000970,0x00000bbb,0x00000bb7,
10850x000300f7,0x00000bc3,0x00000000,0x000400fa,
10860x00000bbd,0x00000bbe,0x00000bc3,0x000200f8,
10870x00000bbe,0x000500c5,0x00000006,0x00000bc1,
10880x00000bb1,0x00000191,0x00060052,0x00000007,
10890x00001b33,0x00000bc1,0x00000bb2,0x00000001,
10900x000200f9,0x00000bc3,0x000200f8,0x00000bc3,
10910x000700f5,0x00000007,0x00001cfe,0x00000bb2,
10920x00000bbc,0x00001b33,0x00000bbe,0x000300f7,
10930x00000c00,0x00000000,0x000300fb,0x00000058,
10940x00000bd7,0x000200f8,0x00000bd7,0x00050051,
10950x00000006,0x00000c07,0x00001cfe,0x00000000,
10960x00050095,0x0000005e,0x00000c0a,0x00000c07,
10970x00000941,0x00050051,0x00000006,0x00000c0b,
10980x00000c0a,0x00000001,0x00050051,0x00000006,
10990x00000c0c,0x00000c0a,0x00000000,0x00050051,
11000x00000006,0x00000c0f,0x00001cfe,0x00000001,
11010x00050080,0x00000006,0x00000c14,0x00000c0f,
11020x00000c0b,0x000200f9,0x00000bdc,0x000200f8,
11030x00000bdc,0x000700f5,0x00000006,0x00001d00,
11040x00000952,0x00000bd7,0x00002199,0x00000bf2,
11050x000700f5,0x00000006,0x00001cff,0x00000058,
11060x00000bd7,0x00002142,0x00000bf2,0x000500b0,
11070x00000012,0x00000be0,0x00001cff,0x00001d00,
11080x000400f6,0x00000bf3,0x00000bf2,0x00000000,
11090x000400fa,0x00000be0,0x00000be1,0x00000bf3,
11100x000200f8,0x00000be1,0x00050080,0x00000006,
11110x00000be4,0x00001cff,0x00001d00,0x000500c2,
11120x00000006,0x00000be5,0x00000be4,0x00000063,
11130x00050084,0x00000006,0x00000be7,0x0000009e,
11140x00000be5,0x00050051,0x00000006,0x00000c33,
11150x00000959,0x00000000,0x00050084,0x00000006,
11160x00000c35,0x00000be5,0x0000034a,0x00050095,
11170x0000005e,0x00000c36,0x00000c33,0x00000c35,
11180x00050051,0x00000006,0x00000c37,0x00000c36,
11190x00000001,0x00050051,0x00000006,0x00000c38,
11200x00000c36,0x00000000,0x00050051,0x00000006,
11210x00000c3b,0x00000959,0x00000001,0x00050080,
11220x00000006,0x00000c3d,0x00000c3b,0x00000c37,
11230x00050050,0x00000007,0x00000c3e,0x00000c38,
11240x00000c3d,0x0004007c,0x000000b1,0x00000c2b,
11250x00000c3e,0x00060041,0x000000b7,0x00000c2c,
11260x00000c2b,0x000000b6,0x000000b6,0x0006003d,
11270x00000006,0x00000c2d,0x00000c2c,0x00000002,
11280x00000004,0x00050080,0x00000006,0x00000c20,
11290x00000be7,0x00000063,0x00050084,0x00000006,
11300x00000c50,0x00000c20,0x0000009e,0x00050095,
11310x0000005e,0x00000c51,0x00000c33,0x00000c50,
11320x00050051,0x00000006,0x00000c52,0x00000c51,
11330x00000001,0x00050051,0x00000006,0x00000c53,
11340x00000c51,0x00000000,0x00050080,0x00000006,
11350x00000c58,0x00000c3b,0x00000c52,0x00050050,
11360x00000007,0x00000c59,0x00000c53,0x00000c58,
11370x0004007c,0x000000b1,0x00000c46,0x00000c59,
11380x00060041,0x000000b7,0x00000c47,0x00000c46,
11390x000000b6,0x000000b6,0x0006003d,0x00000006,
11400x00000c48,0x00000c47,0x00000002,0x00000004,
11410x000500b0,0x00000012,0x00000c60,0x00000c48,
11420x00000c14,0x000400a8,0x00000012,0x00000c61,
11430x00000c60,0x000300f7,0x00000c70,0x00000000,
11440x000400fa,0x00000c61,0x00000c62,0x00000c70,
11450x000200f8,0x00000c62,0x000500aa,0x00000012,
11460x00000c67,0x00000c48,0x00000c14,0x000300f7,
11470x00000c6e,0x00000000,0x000400fa,0x00000c67,
11480x00000c68,0x00000c6e,0x000200f8,0x00000c68,
11490x000500b0,0x00000012,0x00000c6d,0x00000c2d,
11500x00000c0c,0x000200f9,0x00000c6e,0x000200f8,
11510x00000c6e,0x000700f5,0x00000012,0x00000c6f,
11520x00000c67,0x00000c62,0x00000c6d,0x00000c68,
11530x000200f9,0x00000c70,0x000200f8,0x00000c70,
11540x000700f5,0x00000012,0x00000c71,0x00000c60,
11550x00000be1,0x00000c6f,0x00000c6e,0x000300f7,
11560x00000bf1,0x00000000,0x000400fa,0x00000c71,
11570x00000bec,0x00000bef,0x000200f8,0x00000bef,
11580x000200f9,0x00000bf1,0x000200f8,0x00000bec,
11590x00050080,0x00000006,0x00000bee,0x00000be5,
11600x00000063,0x000200f9,0x00000bf1,0x000200f8,
11610x00000bf1,0x000700f5,0x00000006,0x00002142,
11620x00000bee,0x00000bec,0x00001cff,0x00000bef,
11630x000600a9,0x00000006,0x00002199,0x00000c71,
11640x00001d00,0x00000be5,0x000200f9,0x00000bf2,
11650x000200f8,0x00000bf2,0x000200f9,0x00000bdc,
11660x000200f8,0x00000bf3,0x000500aa,0x00000012,
11670x00000bf5,0x00001cff,0x00000058,0x000300f7,
11680x00000bf7,0x00000000,0x000400fa,0x00000bf5,
11690x00000bf6,0x00000bf7,0x000200f8,0x00000bf6,
11700x000200f9,0x00000c00,0x000200f8,0x00000bf7,
11710x00050082,0x00000006,0x00000bf9,0x00001cff,
11720x00000063,0x00050084,0x00000006,0x00000bfa,
11730x0000009e,0x00000bf9,0x00050080,0x00000006,
11740x00000bfb,0x00000bfa,0x000000d8,0x00050051,
11750x00000006,0x00000c8f,0x00000959,0x00000000,
11760x00050084,0x00000006,0x00000c91,0x00000bfb,
11770x0000009e,0x00050095,0x0000005e,0x00000c92,
11780x00000c8f,0x00000c91,0x00050051,0x00000006,
11790x00000c93,0x00000c92,0x00000001,0x00050051,
11800x00000006,0x00000c94,0x00000c92,0x00000000,
11810x00050051,0x00000006,0x00000c97,0x00000959,
11820x00000001,0x00050080,0x00000006,0x00000c99,
11830x00000c97,0x00000c93,0x00050050,0x00000007,
11840x00000c9a,0x00000c94,0x00000c99,0x0004007c,
11850x000000b1,0x00000c87,0x00000c9a,0x00060041,
11860x000000b7,0x00000c88,0x00000c87,0x000000b6,
11870x000000b6,0x0006003d,0x00000006,0x00000c89,
11880x00000c88,0x00000002,0x00000004,0x00050080,
11890x00000006,0x00000c7c,0x00000bfa,0x000000de,
11900x00050084,0x00000006,0x00000cac,0x00000c7c,
11910x0000009e,0x00050095,0x0000005e,0x00000cad,
11920x00000c8f,0x00000cac,0x00050051,0x00000006,
11930x00000cae,0x00000cad,0x00000001,0x00050051,
11940x00000006,0x00000caf,0x00000cad,0x00000000,
11950x00050080,0x00000006,0x00000cb4,0x00000c97,
11960x00000cae,0x00050050,0x00000007,0x00000cb5,
11970x00000caf,0x00000cb4,0x0004007c,0x000000b1,
11980x00000ca2,0x00000cb5,0x00060041,0x000000b7,
11990x00000ca3,0x00000ca2,0x000000b6,0x000000b6,
12000x0006003d,0x00000006,0x00000ca4,0x00000ca3,
12010x00000002,0x00000004,0x000500b0,0x00000012,
12020x00000cbc,0x00000c0f,0x00000ca4,0x000400a8,
12030x00000012,0x00000cbd,0x00000cbc,0x000300f7,
12040x00000ccc,0x00000000,0x000400fa,0x00000cbd,
12050x00000cbe,0x00000ccc,0x000200f8,0x00000cbe,
12060x000500aa,0x00000012,0x00000cc3,0x00000c0f,
12070x00000ca4,0x000300f7,0x00000cca,0x00000000,
12080x000400fa,0x00000cc3,0x00000cc4,0x00000cca,
12090x000200f8,0x00000cc4,0x000500b0,0x00000012,
12100x00000cc9,0x00000c07,0x00000c89,0x000200f9,
12110x00000cca,0x000200f8,0x00000cca,0x000700f5,
12120x00000012,0x00000ccb,0x00000cc3,0x00000cbe,
12130x00000cc9,0x00000cc4,0x000200f9,0x00000ccc,
12140x000200f8,0x00000ccc,0x000700f5,0x00000012,
12150x00000ccd,0x00000cbc,0x00000bf7,0x00000ccb,
12160x00000cca,0x000200f9,0x00000c00,0x000200f8,
12170x00000c00,0x000700f5,0x00000012,0x00001d01,
12180x0000011e,0x00000bf6,0x00000ccd,0x00000ccc,
12190x000200f9,0x00000979,0x000200f8,0x00000979,
12200x000700f5,0x00000012,0x0000097a,0x0000096f,
12210x0000096d,0x00001d01,0x00000c00,0x000200f9,
12220x0000097b,0x000200f8,0x0000097b,0x000d00f5,
12230x00000012,0x00001d02,0x0000011e,0x00000938,
12240x00000217,0x0000094f,0x0000011e,0x00000954,
12250x00000217,0x0000095e,0x0000097a,0x00000979,
12260x000400a8,0x00000012,0x00000483,0x00001d02,
12270x000200f9,0x0000047a,0x000200f8,0x0000047a,
12280x000700f5,0x00000012,0x00000484,0x00000478,
12290x000005c0,0x00000483,0x0000097b,0x000300f7,
12300x00000486,0x00000000,0x000400fa,0x00000484,
12310x00000485,0x00000486,0x000200f8,0x00000485,
12320x000200f9,0x00000518,0x000200f8,0x00000486,
12330x000200f9,0x00000467,0x000200f8,0x00000467,
12340x00050041,0x0000020a,0x00000489,0x00000180,
12350x000000b6,0x0004003d,0x00000007,0x0000048a,
12360x00000489,0x0004007c,0x00000468,0x0000048b,
12370x0000048a,0x00050084,0x00000006,0x0000048f,
12380x000000d8,0x0000044f,0x00060041,0x00000474,
12390x00000490,0x0000048b,0x000000b6,0x0000048f,
12400x0006003d,0x00000027,0x00000491,0x00000490,
12410x00000002,0x00000010,0x00050080,0x00000006,
12420x00000496,0x0000048f,0x00000063,0x00060041,
12430x00000474,0x00000497,0x0000048b,0x000000b6,
12440x00000496,0x0006003d,0x00000027,0x00000498,
12450x00000497,0x00000002,0x00000010,0x000300f7,
12460x0000049b,0x00000000,0x000400fa,0x0000043a,
12470x0000049a,0x0000049b,0x000200f8,0x0000049a,
12480x00050051,0x00000006,0x0000049d,0x00000491,
12490x00000003,0x000500c2,0x00000006,0x0000049e,
12500x0000049d,0x0000019b,0x000500ab,0x00000012,
12510x0000049f,0x0000049e,0x00000058,0x000200f9,
12520x0000049b,0x000200f8,0x0000049b,0x000700f5,
12530x00000012,0x000004a0,0x0000043a,0x00000467,
12540x0000049f,0x0000049a,0x000300f7,0x000004a2,
12550x00000000,0x000400fa,0x000004a0,0x000004a1,
12560x000004a2,0x000200f8,0x000004a1,0x000200f9,
12570x00000518,0x000200f8,0x000004a2,0x000500c2,
12580x00000006,0x000004a6,0x00001ce6,0x000004a5,
12590x000500ab,0x00000012,0x000004a7,0x000004a6,
12600x00000058,0x000300f7,0x000004a9,0x00000000,
12610x000400fa,0x000004a7,0x000004a8,0x000004a9,
12620x000200f8,0x000004a8,0x00050051,0x00000006,
12630x000004ab,0x00000491,0x00000003,0x000500c2,
12640x00000006,0x000004ac,0x000004ab,0x0000019b,
12650x000500ab,0x00000012,0x000004ad,0x000004ac,
12660x00000058,0x000200f9,0x000004a9,0x000200f8,
12670x000004a9,0x000700f5,0x00000012,0x000004ae,
12680x000004a7,0x000004a2,0x000004ad,0x000004a8,
12690x00070050,0x0000219a,0x0000219b,0x000004ae,
12700x000004ae,0x000004ae,0x000004ae,0x000600a9,
12710x00000027,0x0000219c,0x0000219b,0x000001a7,
12720x00000491,0x00050051,0x00000006,0x000004b6,
12730x0000219c,0x00000003,0x000500c2,0x00000006,
12740x000004b7,0x000004b6,0x0000019b,0x000500aa,
12750x00000012,0x000004b8,0x000004b7,0x00000058,
12760x000300f7,0x000004ba,0x00000000,0x000400fa,
12770x000004b8,0x000004b9,0x000004ba,0x000200f8,
12780x000004b9,0x000300f7,0x00000e39,0x00000000,
12790x000300fb,0x00000058,0x00000d15,0x000200f8,
12800x00000d15,0x000500ab,0x00000012,0x00000d19,
12810x000004b7,0x00000058,0x000400a8,0x00000012,
12820x00000d1a,0x00000d19,0x000300f7,0x00000d1f,
12830x00000000,0x000400fa,0x00000d1a,0x00000d1b,
12840x00000d1f,0x000200f8,0x00000d1b,0x00050051,
12850x00000006,0x00000d1d,0x0000219c,0x00000002,
12860x000500aa,0x00000012,0x00000d1e,0x00000d1d,
12870x00000058,0x000200f9,0x00000d1f,0x000200f8,
12880x00000d1f,0x000700f5,0x00000012,0x00000d20,
12890x00000d19,0x00000d15,0x00000d1e,0x00000d1b,
12900x000300f7,0x00000d22,0x00000000,0x000400fa,
12910x00000d20,0x00000d21,0x00000d22,0x000200f8,
12920x00000d21,0x000200f9,0x00000e39,0x000200f8,
12930x00000d22,0x00050051,0x00000006,0x00000d24,
12940x0000219c,0x00000000,0x00050051,0x00000006,
12950x00000d26,0x0000219c,0x00000001,0x000500c7,
12960x00000006,0x00000d27,0x00000d26,0x0000017b,
12970x00050050,0x00000007,0x00000d28,0x00000d24,
12980x00000d27,0x000500aa,0x00000012,0x00000d2b,
12990x00000d24,0x00000058,0x000300f7,0x00000d30,
13000x00000000,0x000400fa,0x00000d2b,0x00000d2c,
13010x00000d30,0x000200f8,0x00000d2c,0x000500aa,
13020x00000012,0x00000d2f,0x00000d27,0x00000058,
13030x000200f9,0x00000d30,0x000200f8,0x00000d30,
13040x000700f5,0x00000012,0x00000d31,0x00000d2b,
13050x00000d22,0x00000d2f,0x00000d2c,0x000300f7,
13060x00000d36,0x00000000,0x000400fa,0x00000d31,
13070x00000d32,0x00000d36,0x000200f8,0x00000d32,
13080x00060052,0x00000027,0x00001b56,0x00000058,
13090x0000219c,0x00000000,0x00060052,0x00000027,
13100x00001b58,0x00000058,0x00001b56,0x00000001,
13110x00060052,0x00000027,0x00001b5a,0x00000058,
13120x00001b58,0x00000002,0x000200f9,0x00000e39,
13130x000200f8,0x00000d36,0x000500c2,0x00000006,
13140x00000d39,0x00000d26,0x000000e4,0x000500c7,
13150x00000006,0x00000d3a,0x00000d39,0x000001ad,
13160x00050051,0x00000006,0x00000d3c,0x0000219c,
13170x00000002,0x000500aa,0x00000012,0x00000d3e,
13180x00000d3a,0x00000058,0x000600a9,0x00000006,
13190x00000d40,0x00000d3e,0x00000063,0x00000d3a,
13200x00050097,0x0000005e,0x00000d43,0x00000d3c,
13210x00000d40,0x00050051,0x00000006,0x00000d44,
13220x00000d43,0x00000000,0x00050051,0x00000006,
13230x00000d45,0x00000d43,0x00000001,0x00050050,
13240x00000007,0x0000218e,0x00000d44,0x00000d45,
13250x00050041,0x00000182,0x00000d46,0x00000180,
13260x0000029a,0x0004003d,0x00000006,0x00000d47,
13270x00000d46,0x000200f9,0x00000d48,0x000200f8,
13280x00000d48,0x000700f5,0x00000006,0x00001d55,
13290x00000d47,0x00000d36,0x0000219d,0x00000d5f,
13300x000700f5,0x00000006,0x00001d54,0x00000058,
13310x00000d36,0x00002148,0x00000d5f,0x000500b0,
13320x00000012,0x00000d4c,0x00001d54,0x00001d55,
13330x000400f6,0x00000d60,0x00000d5f,0x00000000,
13340x000400fa,0x00000d4c,0x00000d4d,0x00000d60,
13350x000200f8,0x00000d4d,0x00050080,0x00000006,
13360x00000d50,0x00001d54,0x00001d55,0x000500c2,
13370x00000006,0x00000d51,0x00000d50,0x00000063,
13380x00050084,0x00000006,0x00000d53,0x000002ab,
13390x00000d51,0x00050041,0x0000020a,0x00000d54,
13400x00000180,0x000002aa,0x0004003d,0x00000007,
13410x00000d55,0x00000d54,0x00050051,0x00000006,
13420x00000e5c,0x00000d55,0x00000000,0x00050084,
13430x00000006,0x00000e5e,0x00000d51,0x0000218f,
13440x00050095,0x0000005e,0x00000e5f,0x00000e5c,
13450x00000e5e,0x00050051,0x00000006,0x00000e60,
13460x00000e5f,0x00000001,0x00050051,0x00000006,
13470x00000e61,0x00000e5f,0x00000000,0x00050051,
13480x00000006,0x00000e64,0x00000d55,0x00000001,
13490x00050080,0x00000006,0x00000e66,0x00000e64,
13500x00000e60,0x00050050,0x00000007,0x00000e67,
13510x00000e61,0x00000e66,0x0004007c,0x000000b1,
13520x00000e54,0x00000e67,0x00060041,0x000000b7,
13530x00000e55,0x00000e54,0x000000b6,0x000000b6,
13540x0006003d,0x00000006,0x00000e56,0x00000e55,
13550x00000002,0x00000004,0x00050080,0x00000006,
13560x00000e49,0x00000d53,0x00000063,0x00050084,
13570x00000006,0x00000e79,0x00000e49,0x0000009e,
13580x00050095,0x0000005e,0x00000e7a,0x00000e5c,
13590x00000e79,0x00050051,0x00000006,0x00000e7b,
13600x00000e7a,0x00000001,0x00050051,0x00000006,
13610x00000e7c,0x00000e7a,0x00000000,0x00050080,
13620x00000006,0x00000e81,0x00000e64,0x00000e7b,
13630x00050050,0x00000007,0x00000e82,0x00000e7c,
13640x00000e81,0x0004007c,0x000000b1,0x00000e6f,
13650x00000e82,0x00060041,0x000000b7,0x00000e70,
13660x00000e6f,0x000000b6,0x000000b6,0x0006003d,
13670x00000006,0x00000e71,0x00000e70,0x00000002,
13680x00000004,0x000500b0,0x00000012,0x00000e89,
13690x00000d27,0x00000e71,0x000400a8,0x00000012,
13700x00000e8a,0x00000e89,0x000300f7,0x00000e99,
13710x00000000,0x000400fa,0x00000e8a,0x00000e8b,
13720x00000e99,0x000200f8,0x00000e8b,0x000500aa,
13730x00000012,0x00000e90,0x00000d27,0x00000e71,
13740x000300f7,0x00000e97,0x00000000,0x000400fa,
13750x00000e90,0x00000e91,0x00000e97,0x000200f8,
13760x00000e91,0x000500b0,0x00000012,0x00000e96,
13770x00000d24,0x00000e56,0x000200f9,0x00000e97,
13780x000200f8,0x00000e97,0x000700f5,0x00000012,
13790x00000e98,0x00000e90,0x00000e8b,0x00000e96,
13800x00000e91,0x000200f9,0x00000e99,0x000200f8,
13810x00000e99,0x000700f5,0x00000012,0x00000e9a,
13820x00000e89,0x00000d4d,0x00000e98,0x00000e97,
13830x000300f7,0x00000d5e,0x00000000,0x000400fa,
13840x00000e9a,0x00000d59,0x00000d5b,0x000200f8,
13850x00000d5b,0x00050080,0x00000006,0x00000d5d,
13860x00000d51,0x00000063,0x000200f9,0x00000d5e,
13870x000200f8,0x00000d59,0x000200f9,0x00000d5e,
13880x000200f8,0x00000d5e,0x000700f5,0x00000006,
13890x00002148,0x00001d54,0x00000d59,0x00000d5d,
13900x00000d5b,0x000600a9,0x00000006,0x0000219d,
13910x00000e9a,0x00000d51,0x00001d55,0x000200f9,
13920x00000d5f,0x000200f8,0x00000d5f,0x000200f9,
13930x00000d48,0x000200f8,0x00000d60,0x000500ac,
13940x00000012,0x00000d62,0x00001d54,0x00000058,
13950x000300f7,0x00000d96,0x00000000,0x000400fa,
13960x00000d62,0x00000d63,0x00000d96,0x000200f8,
13970x00000d63,0x00050082,0x00000006,0x00000d65,
13980x00001d54,0x00000063,0x00050084,0x00000006,
13990x00000d66,0x000002ab,0x00000d65,0x00050080,
14000x00000006,0x00000d68,0x00000d66,0x000000d8,
14010x00050041,0x0000020a,0x00000d69,0x00000180,
14020x000002aa,0x0004003d,0x00000007,0x00000d6a,
14030x00000d69,0x00050051,0x00000006,0x00000eb8,
14040x00000d6a,0x00000000,0x00050084,0x00000006,
14050x00000eba,0x00000d68,0x0000009e,0x00050095,
14060x0000005e,0x00000ebb,0x00000eb8,0x00000eba,
14070x00050051,0x00000006,0x00000ebc,0x00000ebb,
14080x00000001,0x00050051,0x00000006,0x00000ebd,
14090x00000ebb,0x00000000,0x00050051,0x00000006,
14100x00000ec0,0x00000d6a,0x00000001,0x00050080,
14110x00000006,0x00000ec2,0x00000ec0,0x00000ebc,
14120x00050050,0x00000007,0x00000ec3,0x00000ebd,
14130x00000ec2,0x0004007c,0x000000b1,0x00000eb0,
14140x00000ec3,0x00060041,0x000000b7,0x00000eb1,
14150x00000eb0,0x000000b6,0x000000b6,0x0006003d,
14160x00000006,0x00000eb2,0x00000eb1,0x00000002,
14170x00000004,0x00050080,0x00000006,0x00000ea5,
14180x00000d66,0x000000de,0x00050084,0x00000006,
14190x00000ed5,0x00000ea5,0x0000009e,0x00050095,
14200x0000005e,0x00000ed6,0x00000eb8,0x00000ed5,
14210x00050051,0x00000006,0x00000ed7,0x00000ed6,
14220x00000001,0x00050051,0x00000006,0x00000ed8,
14230x00000ed6,0x00000000,0x00050080,0x00000006,
14240x00000edd,0x00000ec0,0x00000ed7,0x00050050,
14250x00000007,0x00000ede,0x00000ed8,0x00000edd,
14260x0004007c,0x000000b1,0x00000ecb,0x00000ede,
14270x00060041,0x000000b7,0x00000ecc,0x00000ecb,
14280x000000b6,0x000000b6,0x0006003d,0x00000006,
14290x00000ecd,0x00000ecc,0x00000002,0x00000004,
14300x000500b0,0x00000012,0x00000ee5,0x00000d27,
14310x00000ecd,0x000400a8,0x00000012,0x00000ee6,
14320x00000ee5,0x000300f7,0x00000ef5,0x00000000,
14330x000400fa,0x00000ee6,0x00000ee7,0x00000ef5,
14340x000200f8,0x00000ee7,0x000500aa,0x00000012,
14350x00000eec,0x00000d27,0x00000ecd,0x000300f7,
14360x00000ef3,0x00000000,0x000400fa,0x00000eec,
14370x00000eed,0x00000ef3,0x000200f8,0x00000eed,
14380x000500b0,0x00000012,0x00000ef2,0x00000d24,
14390x00000eb2,0x000200f9,0x00000ef3,0x000200f8,
14400x00000ef3,0x000700f5,0x00000012,0x00000ef4,
14410x00000eec,0x00000ee7,0x00000ef2,0x00000eed,
14420x000200f9,0x00000ef5,0x000200f8,0x00000ef5,
14430x000700f5,0x00000012,0x00000ef6,0x00000ee5,
14440x00000d63,0x00000ef4,0x00000ef3,0x000300f7,
14450x00000d77,0x00000000,0x000400fa,0x00000ef6,
14460x00000d6f,0x00000d77,0x000200f8,0x00000d6f,
14470x00050080,0x00000006,0x00000d71,0x00000d66,
14480x000002d5,0x00050084,0x00000006,0x00000f08,
14490x00000d71,0x0000009e,0x00050095,0x0000005e,
14500x00000f09,0x00000eb8,0x00000f08,0x00050051,
14510x00000006,0x00000f0a,0x00000f09,0x00000001,
14520x00050051,0x00000006,0x00000f0b,0x00000f09,
14530x00000000,0x00050080,0x00000006,0x00000f10,
14540x00000ec0,0x00000f0a,0x00050050,0x00000007,
14550x00000f11,0x00000f0b,0x00000f10,0x0004007c,
14560x000000b1,0x00000efe,0x00000f11,0x00060041,
14570x000000b7,0x00000eff,0x00000efe,0x000000b6,
14580x000000b6,0x0006003d,0x00000006,0x00000f00,
14590x00000eff,0x00000002,0x00000004,0x000500c7,
14600x00000006,0x00000d75,0x00000f00,0x00000063,
14610x000500ab,0x00000012,0x00000d76,0x00000d75,
14620x00000058,0x000200f9,0x00000d77,0x000200f8,
14630x00000d77,0x000700f5,0x00000012,0x00000d78,
14640x00000ef6,0x00000ef5,0x00000d76,0x00000d6f,
14650x000300f7,0x00000d95,0x00000000,0x000400fa,
14660x00000d78,0x00000d79,0x00000d95,0x000200f8,
14670x00000d79,0x00050096,0x0000005e,0x00000f1a,
14680x00000eb2,0x00000d24,0x00050051,0x00000006,
14690x00000f1b,0x00000f1a,0x00000001,0x00050051,
14700x00000006,0x00000f1c,0x00000f1a,0x00000000,
14710x00050082,0x00000006,0x00000f22,0x00000ecd,
14720x00000d27,0x00050082,0x00000006,0x00000f24,
14730x00000f22,0x00000f1b,0x000500b0,0x00000012,
14740x00000f2c,0x00000f24,0x00000d45,0x000400a8,
14750x00000012,0x00000f2d,0x00000f2c,0x000300f7,
14760x00000f3c,0x00000000,0x000400fa,0x00000f2d,
14770x00000f2e,0x00000f3c,0x000200f8,0x00000f2e,
14780x000500aa,0x00000012,0x00000f33,0x00000f24,
14790x00000d45,0x000300f7,0x00000f3a,0x00000000,
14800x000400fa,0x00000f33,0x00000f34,0x00000f3a,
14810x000200f8,0x00000f34,0x000500b0,0x00000012,
14820x00000f39,0x00000f1c,0x00000d44,0x000200f9,
14830x00000f3a,0x000200f8,0x00000f3a,0x000700f5,
14840x00000012,0x00000f3b,0x00000f33,0x00000f2e,
14850x00000f39,0x00000f34,0x000200f9,0x00000f3c,
14860x000200f8,0x00000f3c,0x000700f5,0x00000012,
14870x00000f3d,0x00000f2c,0x00000d79,0x00000f3b,
14880x00000f3a,0x000300f7,0x00000d94,0x00000000,
14890x000400fa,0x00000f3d,0x00000d7f,0x00000d83,
14900x000200f8,0x00000d83,0x00050084,0x00000006,
14910x00000f61,0x00000d65,0x0000218f,0x00050095,
14920x0000005e,0x00000f62,0x00000eb8,0x00000f61,
14930x00050051,0x00000006,0x00000f63,0x00000f62,
14940x00000001,0x00050051,0x00000006,0x00000f64,
14950x00000f62,0x00000000,0x00050080,0x00000006,
14960x00000f69,0x00000ec0,0x00000f63,0x00050050,
14970x00000007,0x00000f6a,0x00000f64,0x00000f69,
14980x0004007c,0x000000b1,0x00000f57,0x00000f6a,
14990x00060041,0x000000b7,0x00000f58,0x00000f57,
15000x000000b6,0x000000b6,0x0006003d,0x00000006,
15010x00000f59,0x00000f58,0x00000002,0x00000004,
15020x00050080,0x00000006,0x00000f4c,0x00000d66,
15030x00000063,0x00050084,0x00000006,0x00000f7c,
15040x00000f4c,0x0000009e,0x00050095,0x0000005e,
15050x00000f7d,0x00000eb8,0x00000f7c,0x00050051,
15060x00000006,0x00000f7e,0x00000f7d,0x00000001,
15070x00050051,0x00000006,0x00000f7f,0x00000f7d,
15080x00000000,0x00050080,0x00000006,0x00000f84,
15090x00000ec0,0x00000f7e,0x00050050,0x00000007,
15100x00000f85,0x00000f7f,0x00000f84,0x0004007c,
15110x000000b1,0x00000f72,0x00000f85,0x00060041,
15120x000000b7,0x00000f73,0x00000f72,0x000000b6,
15130x000000b6,0x0006003d,0x00000006,0x00000f74,
15140x00000f73,0x00000002,0x00000004,0x00050080,
15150x00000006,0x00000d89,0x00000d66,0x0000009e,
15160x00050084,0x00000006,0x00000fa5,0x00000d89,
15170x0000009e,0x00050095,0x0000005e,0x00000fa6,
15180x00000eb8,0x00000fa5,0x00050051,0x00000006,
15190x00000fa7,0x00000fa6,0x00000001,0x00050051,
15200x00000006,0x00000fa8,0x00000fa6,0x00000000,
15210x00050080,0x00000006,0x00000fad,0x00000ec0,
15220x00000fa7,0x00050050,0x00000007,0x00000fae,
15230x00000fa8,0x00000fad,0x0004007c,0x000000b1,
15240x00000f9b,0x00000fae,0x00060041,0x000000b7,
15250x00000f9c,0x00000f9b,0x000000b6,0x000000b6,
15260x0006003d,0x00000006,0x00000f9d,0x00000f9c,
15270x00000002,0x00000004,0x00050080,0x00000006,
15280x00000f90,0x00000d66,0x00000357,0x00050084,
15290x00000006,0x00000fc0,0x00000f90,0x0000009e,
15300x00050095,0x0000005e,0x00000fc1,0x00000eb8,
15310x00000fc0,0x00050051,0x00000006,0x00000fc2,
15320x00000fc1,0x00000001,0x00050051,0x00000006,
15330x00000fc3,0x00000fc1,0x00000000,0x00050080,
15340x00000006,0x00000fc8,0x00000ec0,0x00000fc2,
15350x00050050,0x00000007,0x00000fc9,0x00000fc3,
15360x00000fc8,0x0004007c,0x000000b1,0x00000fb6,
15370x00000fc9,0x00060041,0x000000b7,0x00000fb7,
15380x00000fb6,0x000000b6,0x000000b6,0x0006003d,
15390x00000006,0x00000fb8,0x00000fb7,0x00000002,
15400x00000004,0x00050096,0x0000005e,0x00000fd2,
15410x00000d24,0x00000f59,0x00050051,0x00000006,
15420x00000fd3,0x00000fd2,0x00000001,0x00050051,
15430x00000006,0x00000fd4,0x00000fd2,0x00000000,
15440x00050082,0x00000006,0x00000fda,0x00000d27,
15450x00000f74,0x00050082,0x00000006,0x00000fdc,
15460x00000fda,0x00000fd3,0x00050095,0x0000005e,
15470x00000fe6,0x00000f9d,0x00000fd4,0x00050051,
15480x00000006,0x00000fe7,0x00000fe6,0x00000001,
15490x00050051,0x00000006,0x00000fe8,0x00000fe6,
15500x00000000,0x00050080,0x00000006,0x00000fee,
15510x00000fb8,0x00000fdc,0x00050080,0x00000006,
15520x00000ff0,0x00000fee,0x00000fe7,0x00060052,
15530x00000027,0x00001b99,0x00000fe8,0x0000219c,
15540x00000000,0x000500c7,0x00000006,0x00000ff8,
15550x00000d26,0x00000191,0x000500c7,0x00000006,
15560x00000ffb,0x00000ff0,0x0000017b,0x000500c5,
15570x00000006,0x00000ffc,0x00000ff8,0x00000ffb,
15580x00060052,0x00000027,0x00001b9d,0x00000ffc,
15590x00001b99,0x00000001,0x000200f9,0x00000d94,
15600x000200f8,0x00000d7f,0x00060052,0x00000027,
15610x00001b82,0x00000058,0x0000219c,0x00000000,
15620x00060052,0x00000027,0x00001b84,0x00000058,
15630x00001b82,0x00000001,0x00060052,0x00000027,
15640x00001b86,0x00000058,0x00001b84,0x00000002,
15650x000200f9,0x00000d94,0x000200f8,0x00000d94,
15660x000700f5,0x00000027,0x00001df7,0x00001b86,
15670x00000d7f,0x00001b9d,0x00000d83,0x000200f9,
15680x00000e39,0x000200f8,0x00000d95,0x000200f9,
15690x00000d96,0x000200f8,0x00000d96,0x000500c7,
15700x00000006,0x00000d9a,0x00000438,0x00000063,
15710x000500ab,0x00000012,0x00000d9b,0x00000d9a,
15720x00000058,0x000300f7,0x00000da1,0x00000000,
15730x000400fa,0x00000d9b,0x00000d9c,0x00000da1,
15740x000200f8,0x00000d9c,0x000500c7,0x00000006,
15750x00000d9f,0x00000d26,0x0000018b,0x000500ab,
15760x00000012,0x00000da0,0x00000d9f,0x00000058,
15770x000200f9,0x00000da1,0x000200f8,0x00000da1,
15780x000700f5,0x00000012,0x00000da2,0x00000d9b,
15790x00000d96,0x00000da0,0x00000d9c,0x000300f7,
15800x00000da8,0x00000000,0x000400fa,0x00000da2,
15810x00000da3,0x00000da8,0x000200f8,0x00000da3,
15820x000500c5,0x00000006,0x00000da6,0x00000d27,
15830x00000191,0x00060052,0x00000007,0x00001ba1,
15840x00000da6,0x00000d28,0x00000001,0x000200f9,
15850x00000da8,0x000200f8,0x00000da8,0x000700f5,
15860x00000007,0x00001d58,0x00000d28,0x00000da1,
15870x00001ba1,0x00000da3,0x00050041,0x00000182,
15880x00000da9,0x00000180,0x000000e4,0x0004003d,
15890x00000006,0x00000daa,0x00000da9,0x000500ab,
15900x00000012,0x00000dab,0x00000daa,0x00000058,
15910x000300f7,0x00000dbe,0x00000000,0x000400fa,
15920x00000dab,0x00000dac,0x00000dbe,0x000200f8,
15930x00000dac,0x000500aa,0x00000012,0x00000daf,
15940x00000d44,0x00000058,0x000300f7,0x00000db4,
15950x00000000,0x000400fa,0x00000daf,0x00000db0,
15960x00000db4,0x000200f8,0x00000db0,0x000500aa,
15970x00000012,0x00000db3,0x00000d45,0x00000058,
15980x000200f9,0x00000db4,0x000200f8,0x00000db4,
15990x000700f5,0x00000012,0x00000db5,0x00000daf,
16000x00000dac,0x00000db3,0x00000db0,0x000600a9,
16010x00000007,0x00000db7,0x00000db5,0x00000208,
16020x0000218e,0x00050041,0x0000020a,0x00000db8,
16030x00000180,0x00000325,0x0004003d,0x00000007,
16040x00000db9,0x00000db8,0x000300f7,0x00001042,
16050x00000000,0x000300fb,0x00000058,0x00001012,
16060x000200f8,0x00001012,0x000200f9,0x00001014,
16070x000200f8,0x00001014,0x000700f5,0x00000006,
16080x00001d5a,0x00000daa,0x00001012,0x0000219e,
16090x0000102a,0x000700f5,0x00000006,0x00001d59,
16100x00000058,0x00001012,0x0000214e,0x0000102a,
16110x000500b0,0x00000012,0x00001018,0x00001d59,
16120x00001d5a,0x000400f6,0x0000102b,0x0000102a,
16130x00000000,0x000400fa,0x00001018,0x00001019,
16140x0000102b,0x000200f8,0x00001019,0x00050080,
16150x00000006,0x0000101c,0x00001d59,0x00001d5a,
16160x000500c2,0x00000006,0x0000101d,0x0000101c,
16170x00000063,0x00050084,0x00000006,0x0000101f,
16180x0000009e,0x0000101d,0x00050051,0x00000006,
16190x00001061,0x00000db9,0x00000000,0x00050084,
16200x00000006,0x00001063,0x0000101d,0x0000034a,
16210x00050095,0x0000005e,0x00001064,0x00001061,
16220x00001063,0x00050051,0x00000006,0x00001065,
16230x00001064,0x00000001,0x00050051,0x00000006,
16240x00001066,0x00001064,0x00000000,0x00050051,
16250x00000006,0x00001069,0x00000db9,0x00000001,
16260x00050080,0x00000006,0x0000106b,0x00001069,
16270x00001065,0x00050050,0x00000007,0x0000106c,
16280x00001066,0x0000106b,0x0004007c,0x000000b1,
16290x00001059,0x0000106c,0x00060041,0x000000b7,
16300x0000105a,0x00001059,0x000000b6,0x000000b6,
16310x0006003d,0x00000006,0x0000105b,0x0000105a,
16320x00000002,0x00000004,0x00050080,0x00000006,
16330x0000104e,0x0000101f,0x00000063,0x00050084,
16340x00000006,0x0000107e,0x0000104e,0x0000009e,
16350x00050095,0x0000005e,0x0000107f,0x00001061,
16360x0000107e,0x00050051,0x00000006,0x00001080,
16370x0000107f,0x00000001,0x00050051,0x00000006,
16380x00001081,0x0000107f,0x00000000,0x00050080,
16390x00000006,0x00001086,0x00001069,0x00001080,
16400x00050050,0x00000007,0x00001087,0x00001081,
16410x00001086,0x0004007c,0x000000b1,0x00001074,
16420x00001087,0x00060041,0x000000b7,0x00001075,
16430x00001074,0x000000b6,0x000000b6,0x0006003d,
16440x00000006,0x00001076,0x00001075,0x00000002,
16450x00000004,0x00050051,0x00000006,0x0000108b,
16460x00001d58,0x00000001,0x000500b0,0x00000012,
16470x0000108e,0x0000108b,0x00001076,0x000400a8,
16480x00000012,0x0000108f,0x0000108e,0x000300f7,
16490x0000109e,0x00000000,0x000400fa,0x0000108f,
16500x00001090,0x0000109e,0x000200f8,0x00001090,
16510x000500aa,0x00000012,0x00001095,0x0000108b,
16520x00001076,0x000300f7,0x0000109c,0x00000000,
16530x000400fa,0x00001095,0x00001096,0x0000109c,
16540x000200f8,0x00001096,0x00050051,0x00000006,
16550x00001098,0x00001d58,0x00000000,0x000500b0,
16560x00000012,0x0000109b,0x00001098,0x0000105b,
16570x000200f9,0x0000109c,0x000200f8,0x0000109c,
16580x000700f5,0x00000012,0x0000109d,0x00001095,
16590x00001090,0x0000109b,0x00001096,0x000200f9,
16600x0000109e,0x000200f8,0x0000109e,0x000700f5,
16610x00000012,0x0000109f,0x0000108e,0x00001019,
16620x0000109d,0x0000109c,0x000300f7,0x00001029,
16630x00000000,0x000400fa,0x0000109f,0x00001024,
16640x00001026,0x000200f8,0x00001026,0x00050080,
16650x00000006,0x00001028,0x0000101d,0x00000063,
16660x000200f9,0x00001029,0x000200f8,0x00001024,
16670x000200f9,0x00001029,0x000200f8,0x00001029,
16680x000700f5,0x00000006,0x0000214e,0x00001d59,
16690x00001024,0x00001028,0x00001026,0x000600a9,
16700x00000006,0x0000219e,0x0000109f,0x0000101d,
16710x00001d5a,0x000200f9,0x0000102a,0x000200f8,
16720x0000102a,0x000200f9,0x00001014,0x000200f8,
16730x0000102b,0x000500aa,0x00000012,0x0000102d,
16740x00001d59,0x00000058,0x000300f7,0x0000102f,
16750x00000000,0x000400fa,0x0000102d,0x0000102e,
16760x0000102f,0x000200f8,0x0000102e,0x000200f9,
16770x00001042,0x000200f8,0x0000102f,0x00050082,
16780x00000006,0x00001031,0x00001d59,0x00000063,
16790x00050084,0x00000006,0x00001032,0x0000009e,
16800x00001031,0x00050080,0x00000006,0x00001033,
16810x00001032,0x000000d8,0x00050051,0x00000006,
16820x000010bd,0x00000db9,0x00000000,0x00050084,
16830x00000006,0x000010bf,0x00001033,0x0000009e,
16840x00050095,0x0000005e,0x000010c0,0x000010bd,
16850x000010bf,0x00050051,0x00000006,0x000010c1,
16860x000010c0,0x00000001,0x00050051,0x00000006,
16870x000010c2,0x000010c0,0x00000000,0x00050051,
16880x00000006,0x000010c5,0x00000db9,0x00000001,
16890x00050080,0x00000006,0x000010c7,0x000010c5,
16900x000010c1,0x00050050,0x00000007,0x000010c8,
16910x000010c2,0x000010c7,0x0004007c,0x000000b1,
16920x000010b5,0x000010c8,0x00060041,0x000000b7,
16930x000010b6,0x000010b5,0x000000b6,0x000000b6,
16940x0006003d,0x00000006,0x000010b7,0x000010b6,
16950x00000002,0x00000004,0x00050080,0x00000006,
16960x000010aa,0x00001032,0x000000de,0x00050084,
16970x00000006,0x000010da,0x000010aa,0x0000009e,
16980x00050095,0x0000005e,0x000010db,0x000010bd,
16990x000010da,0x00050051,0x00000006,0x000010dc,
17000x000010db,0x00000001,0x00050051,0x00000006,
17010x000010dd,0x000010db,0x00000000,0x00050080,
17020x00000006,0x000010e2,0x000010c5,0x000010dc,
17030x00050050,0x00000007,0x000010e3,0x000010dd,
17040x000010e2,0x0004007c,0x000000b1,0x000010d0,
17050x000010e3,0x00060041,0x000000b7,0x000010d1,
17060x000010d0,0x000000b6,0x000000b6,0x0006003d,
17070x00000006,0x000010d2,0x000010d1,0x00000002,
17080x00000004,0x00050051,0x00000006,0x000010e7,
17090x00001d58,0x00000001,0x000500b0,0x00000012,
17100x000010ea,0x000010e7,0x000010d2,0x000400a8,
17110x00000012,0x000010eb,0x000010ea,0x000300f7,
17120x000010fa,0x00000000,0x000400fa,0x000010eb,
17130x000010ec,0x000010fa,0x000200f8,0x000010ec,
17140x000500aa,0x00000012,0x000010f1,0x000010e7,
17150x000010d2,0x000300f7,0x000010f8,0x00000000,
17160x000400fa,0x000010f1,0x000010f2,0x000010f8,
17170x000200f8,0x000010f2,0x00050051,0x00000006,
17180x000010f4,0x00001d58,0x00000000,0x000500b0,
17190x00000012,0x000010f7,0x000010f4,0x000010b7,
17200x000200f9,0x000010f8,0x000200f8,0x000010f8,
17210x000700f5,0x00000012,0x000010f9,0x000010f1,
17220x000010ec,0x000010f7,0x000010f2,0x000200f9,
17230x000010fa,0x000200f8,0x000010fa,0x000700f5,
17240x00000012,0x000010fb,0x000010ea,0x0000102f,
17250x000010f9,0x000010f8,0x000300f7,0x00001040,
17260x00000000,0x000400fa,0x000010fb,0x00001039,
17270x00001040,0x000200f8,0x00001039,0x00050051,
17280x00000006,0x00001103,0x00001d58,0x00000000,
17290x00050096,0x0000005e,0x00001104,0x000010b7,
17300x00001103,0x00050051,0x00000006,0x00001105,
17310x00001104,0x00000001,0x00050051,0x00000006,
17320x00001106,0x00001104,0x00000000,0x00050082,
17330x00000006,0x0000110c,0x000010d2,0x000010e7,
17340x00050082,0x00000006,0x0000110e,0x0000110c,
17350x00001105,0x00050051,0x00000006,0x00001115,
17360x00000db7,0x00000001,0x000500b0,0x00000012,
17370x00001116,0x0000110e,0x00001115,0x000400a8,
17380x00000012,0x00001117,0x00001116,0x000300f7,
17390x00001126,0x00000000,0x000400fa,0x00001117,
17400x00001118,0x00001126,0x000200f8,0x00001118,
17410x000500aa,0x00000012,0x0000111d,0x0000110e,
17420x00001115,0x000300f7,0x00001124,0x00000000,
17430x000400fa,0x0000111d,0x0000111e,0x00001124,
17440x000200f8,0x0000111e,0x00050051,0x00000006,
17450x00001122,0x00000db7,0x00000000,0x000500b0,
17460x00000012,0x00001123,0x00001106,0x00001122,
17470x000200f9,0x00001124,0x000200f8,0x00001124,
17480x000700f5,0x00000012,0x00001125,0x0000111d,
17490x00001118,0x00001123,0x0000111e,0x000200f9,
17500x00001126,0x000200f8,0x00001126,0x000700f5,
17510x00000012,0x00001127,0x00001116,0x00001039,
17520x00001125,0x00001124,0x000400a8,0x00000012,
17530x0000103f,0x00001127,0x000200f9,0x00001040,
17540x000200f8,0x00001040,0x000700f5,0x00000012,
17550x00001041,0x000010fb,0x000010fa,0x0000103f,
17560x00001126,0x000200f9,0x00001042,0x000200f8,
17570x00001042,0x000700f5,0x00000012,0x00001d5b,
17580x0000011e,0x0000102e,0x00001041,0x00001040,
17590x000200f9,0x00000dbe,0x000200f8,0x00000dbe,
17600x000700f5,0x00000012,0x00000dbf,0x00000dab,
17610x00000da8,0x00001d5b,0x00001042,0x000300f7,
17620x00000dc1,0x00000000,0x000400fa,0x00000dbf,
17630x00000dc0,0x00000dc1,0x000200f8,0x00000dc0,
17640x000200f9,0x00000e39,0x000200f8,0x00000dc1,
17650x000500c6,0x00000006,0x0000112e,0x000000cb,
17660x00000d24,0x00050084,0x00000006,0x0000112f,
17670x0000112e,0x000000d0,0x000500c6,0x00000006,
17680x00001133,0x0000112f,0x00000d26,0x00050084,
17690x00000006,0x00001134,0x00001133,0x000000d0,
17700x000500c6,0x00000006,0x00001138,0x00001134,
17710x00000d3c,0x00050084,0x00000006,0x00001139,
17720x00001138,0x000000d0,0x000500c6,0x00000006,
17730x0000113d,0x00001139,0x000004b6,0x00050084,
17740x00000006,0x0000113e,0x0000113d,0x000000d0,
17750x000500c2,0x00000006,0x00001140,0x0000113e,
17760x000000e4,0x000500c6,0x00000006,0x00001142,
17770x0000113e,0x00001140,0x00050084,0x00000006,
17780x00001144,0x00001142,0x000000e8,0x000500c2,
17790x00000006,0x00001146,0x00001144,0x000000ec,
17800x000500c6,0x00000006,0x00001148,0x00001144,
17810x00001146,0x00050084,0x00000006,0x0000114a,
17820x00001148,0x000000f0,0x000500c2,0x00000006,
17830x0000114c,0x0000114a,0x000000e4,0x000500c6,
17840x00000006,0x0000114e,0x0000114a,0x0000114c,
17850x000200f9,0x00000dc4,0x000200f8,0x00000dc4,
17860x000700f5,0x00000006,0x00001d6c,0x00000058,
17870x00000dc1,0x00000e22,0x00000e20,0x000500b0,
17880x00000012,0x00000dc7,0x00001d6c,0x0000034a,
17890x000400f6,0x00000e23,0x00000e20,0x00000000,
17900x000400fa,0x00000dc7,0x00000dc8,0x00000e23,
17910x000200f8,0x00000dc8,0x00050080,0x00000006,
17920x00000dcb,0x0000114e,0x00001d6c,0x00050041,
17930x00000182,0x00000dcc,0x00000180,0x000000ec,
17940x0004003d,0x00000006,0x00000dcd,0x00000dcc,
17950x000500c7,0x00000006,0x00000dce,0x00000dcb,
17960x00000dcd,0x00050084,0x00000006,0x00000dcf,
17970x000002ab,0x00000dce,0x00050080,0x00000006,
17980x00000dd1,0x00000dcf,0x00000357,0x00050041,
17990x0000020a,0x00000dd2,0x00000180,0x00000355,
18000x0004003d,0x00000007,0x00000dd3,0x00000dd2,
18010x00050051,0x00000006,0x0000115f,0x00000dd3,
18020x00000000,0x00050084,0x00000006,0x00001161,
18030x00000dd1,0x0000009e,0x00050095,0x0000005e,
18040x00001162,0x0000115f,0x00001161,0x00050051,
18050x00000006,0x00001163,0x00001162,0x00000001,
18060x00050051,0x00000006,0x00001164,0x00001162,
18070x00000000,0x00050051,0x00000006,0x00001167,
18080x00000dd3,0x00000001,0x00050080,0x00000006,
18090x00001169,0x00001167,0x00001163,0x00050050,
18100x00000007,0x0000116a,0x00001164,0x00001169,
18110x0004007c,0x000000b1,0x00001157,0x0000116a,
18120x00060041,0x000000b7,0x00001158,0x00001157,
18130x000000b6,0x000000b6,0x0006003d,0x00000006,
18140x00001159,0x00001158,0x00000002,0x00000004,
18150x000500c2,0x00000006,0x00000dd5,0x00001159,
18160x000000e4,0x000500c7,0x00000006,0x00000dd7,
18170x00000dd5,0x00000063,0x000500aa,0x00000012,
18180x00000dd8,0x00000dd7,0x00000058,0x000300f7,
18190x00000dda,0x00000000,0x000400fa,0x00000dd8,
18200x00000dd9,0x00000dda,0x000200f8,0x00000dd9,
18210x000200f9,0x00000e20,0x000200f8,0x00000dda,
18220x00050084,0x00000006,0x0000117c,0x00000dce,
18230x0000218f,0x00050095,0x0000005e,0x0000117d,
18240x0000115f,0x0000117c,0x00050051,0x00000006,
18250x0000117e,0x0000117d,0x00000001,0x00050051,
18260x00000006,0x0000117f,0x0000117d,0x00000000,
18270x00050080,0x00000006,0x00001184,0x00001167,
18280x0000117e,0x00050050,0x00000007,0x00001185,
18290x0000117f,0x00001184,0x0004007c,0x000000b1,
18300x00001172,0x00001185,0x00060041,0x000000b7,
18310x00001173,0x00001172,0x000000b6,0x000000b6,
18320x0006003d,0x00000006,0x00001174,0x00001173,
18330x00000002,0x00000004,0x000500ab,0x00000012,
18340x00000de1,0x00001174,0x00000d24,0x000400a8,
18350x00000012,0x00000de2,0x00000de1,0x000300f7,
18360x00000dec,0x00000000,0x000400fa,0x00000de2,
18370x00000de3,0x00000dec,0x000200f8,0x00000de3,
18380x00050080,0x00000006,0x00000de5,0x00000dcf,
18390x00000063,0x00050084,0x00000006,0x00001197,
18400x00000de5,0x0000009e,0x00050095,0x0000005e,
18410x00001198,0x0000115f,0x00001197,0x00050051,
18420x00000006,0x00001199,0x00001198,0x00000001,
18430x00050051,0x00000006,0x0000119a,0x00001198,
18440x00000000,0x00050080,0x00000006,0x0000119f,
18450x00001167,0x00001199,0x00050050,0x00000007,
18460x000011a0,0x0000119a,0x0000119f,0x0004007c,
18470x000000b1,0x0000118d,0x000011a0,0x00060041,
18480x000000b7,0x0000118e,0x0000118d,0x000000b6,
18490x000000b6,0x0006003d,0x00000006,0x0000118f,
18500x0000118e,0x00000002,0x00000004,0x000500ab,
18510x00000012,0x00000deb,0x0000118f,0x00000d26,
18520x000200f9,0x00000dec,0x000200f8,0x00000dec,
18530x000700f5,0x00000012,0x00000ded,0x00000de1,
18540x00000dda,0x00000deb,0x00000de3,0x000400a8,
18550x00000012,0x00000dee,0x00000ded,0x000300f7,
18560x00000df8,0x00000000,0x000400fa,0x00000dee,
18570x00000def,0x00000df8,0x000200f8,0x00000def,
18580x00050080,0x00000006,0x00000df1,0x00000dcf,
18590x000000d8,0x00050084,0x00000006,0x000011b2,
18600x00000df1,0x0000009e,0x00050095,0x0000005e,
18610x000011b3,0x0000115f,0x000011b2,0x00050051,
18620x00000006,0x000011b4,0x000011b3,0x00000001,
18630x00050051,0x00000006,0x000011b5,0x000011b3,
18640x00000000,0x00050080,0x00000006,0x000011ba,
18650x00001167,0x000011b4,0x00050050,0x00000007,
18660x000011bb,0x000011b5,0x000011ba,0x0004007c,
18670x000000b1,0x000011a8,0x000011bb,0x00060041,
18680x000000b7,0x000011a9,0x000011a8,0x000000b6,
18690x000000b6,0x0006003d,0x00000006,0x000011aa,
18700x000011a9,0x00000002,0x00000004,0x000500ab,
18710x00000012,0x00000df7,0x000011aa,0x00000d3c,
18720x000200f9,0x00000df8,0x000200f8,0x00000df8,
18730x000700f5,0x00000012,0x00000df9,0x00000ded,
18740x00000dec,0x00000df7,0x00000def,0x000400a8,
18750x00000012,0x00000dfa,0x00000df9,0x000300f7,
18760x00000e04,0x00000000,0x000400fa,0x00000dfa,
18770x00000dfb,0x00000e04,0x000200f8,0x00000dfb,
18780x00050080,0x00000006,0x00000dfd,0x00000dcf,
18790x000000de,0x00050084,0x00000006,0x000011cd,
18800x00000dfd,0x0000009e,0x00050095,0x0000005e,
18810x000011ce,0x0000115f,0x000011cd,0x00050051,
18820x00000006,0x000011cf,0x000011ce,0x00000001,
18830x00050051,0x00000006,0x000011d0,0x000011ce,
18840x00000000,0x00050080,0x00000006,0x000011d5,
18850x00001167,0x000011cf,0x00050050,0x00000007,
18860x000011d6,0x000011d0,0x000011d5,0x0004007c,
18870x000000b1,0x000011c3,0x000011d6,0x00060041,
18880x000000b7,0x000011c4,0x000011c3,0x000000b6,
18890x000000b6,0x0006003d,0x00000006,0x000011c5,
18900x000011c4,0x00000002,0x00000004,0x000500ab,
18910x00000012,0x00000e03,0x000011c5,0x000004b6,
18920x000200f9,0x00000e04,0x000200f8,0x00000e04,
18930x000700f5,0x00000012,0x00000e05,0x00000df9,
18940x00000df8,0x00000e03,0x00000dfb,0x000300f7,
18950x00000e07,0x00000000,0x000400fa,0x00000e05,
18960x00000e06,0x00000e07,0x000200f8,0x00000e06,
18970x000200f9,0x00000e20,0x000200f8,0x00000e07,
18980x000500c7,0x00000006,0x00000e09,0x00000dd5,
18990x000000d8,0x000500ab,0x00000012,0x00000e0a,
19000x00000e09,0x00000058,0x000300f7,0x00000e1f,
19010x00000000,0x000400fa,0x00000e0a,0x00000e0b,
19020x00000e0f,0x000200f8,0x00000e0f,0x00050080,
19030x00000006,0x00000e11,0x00000dcf,0x0000009e,
19040x00050084,0x00000006,0x000011ec,0x00000e11,
19050x0000009e,0x00050095,0x0000005e,0x000011ed,
19060x0000115f,0x000011ec,0x00050051,0x00000006,
19070x000011ee,0x000011ed,0x00000001,0x00050051,
19080x00000006,0x000011ef,0x000011ed,0x00000000,
19090x00050080,0x00000006,0x000011f4,0x00001167,
19100x000011ee,0x00050050,0x00000007,0x000011f5,
19110x000011ef,0x000011f4,0x0004007c,0x000000b1,
19120x000011e2,0x000011f5,0x00060041,0x000000b7,
19130x000011e3,0x000011e2,0x000000b6,0x000000b6,
19140x0006003d,0x00000006,0x000011e4,0x000011e3,
19150x00000002,0x00000004,0x0006003d,0x00000006,
19160x000011ff,0x00001158,0x00000002,0x00000004,
19170x00060052,0x00000027,0x00001be0,0x000011e4,
19180x0000219c,0x00000000,0x000500c7,0x00000006,
19190x00001217,0x00000d26,0x00000191,0x000500c7,
19200x00000006,0x0000121a,0x000011ff,0x0000017b,
19210x000500c5,0x00000006,0x0000121b,0x00001217,
19220x0000121a,0x00060052,0x00000027,0x00001be4,
19230x0000121b,0x00001be0,0x00000001,0x000200f9,
19240x00000e1f,0x000200f8,0x00000e0b,0x00060052,
19250x00000027,0x00001bd5,0x00000058,0x0000219c,
19260x00000000,0x00060052,0x00000027,0x00001bd7,
19270x00000058,0x00001bd5,0x00000001,0x00060052,
19280x00000027,0x00001bd9,0x00000058,0x00001bd7,
19290x00000002,0x000200f9,0x00000e1f,0x000200f8,
19300x00000e1f,0x000700f5,0x00000027,0x00001d86,
19310x00001bd9,0x00000e0b,0x00001be4,0x00000e0f,
19320x000200f9,0x00000e23,0x000200f8,0x00000e20,
19330x00050080,0x00000006,0x00000e22,0x00001d6c,
19340x000003bc,0x000200f9,0x00000dc4,0x000200f8,
19350x00000e23,0x000700f5,0x00000006,0x00001d91,
19360x00001da1,0x00000dc4,0x00000063,0x00000e1f,
19370x000700f5,0x00000027,0x00001d85,0x0000219c,
19380x00000dc4,0x00001d86,0x00000e1f,0x000700f5,
19390x00000012,0x00001d71,0x0000011e,0x00000dc4,
19400x00000217,0x00000e1f,0x000300f7,0x00000e25,
19410x00000000,0x000400fa,0x00001d71,0x00000e39,
19420x00000e25,0x000200f8,0x00000e25,0x00060052,
19430x00000027,0x00001be6,0x00000058,0x00001d85,
19440x00000000,0x00060052,0x00000027,0x00001be8,
19450x00000058,0x00001be6,0x00000001,0x00060052,
19460x00000027,0x00001bea,0x00000058,0x00001be8,
19470x00000002,0x000500c7,0x00000006,0x00000e2b,
19480x00000438,0x000000d8,0x000500ab,0x00000012,
19490x00000e2c,0x00000e2b,0x00000058,0x000300f7,
19500x00000e35,0x00000000,0x000400fa,0x00000e2c,
19510x00000e2d,0x00000e35,0x000200f8,0x00000e2d,
19520x00050041,0x0000020a,0x00000e2e,0x00000180,
19530x000003c8,0x0004003d,0x00000007,0x00000e2f,
19540x00000e2e,0x00050041,0x00000182,0x00000e30,
19550x00000180,0x000003c9,0x0004003d,0x00000006,
19560x00000e31,0x00000e30,0x000300f7,0x00001265,
19570x00000000,0x000300fb,0x00000058,0x00001235,
19580x000200f8,0x00001235,0x000200f9,0x00001237,
19590x000200f8,0x00001237,0x000700f5,0x00000006,
19600x00001d88,0x00000e31,0x00001235,0x0000219f,
19610x0000124d,0x000700f5,0x00000006,0x00001d87,
19620x00000058,0x00001235,0x00002165,0x0000124d,
19630x000500b0,0x00000012,0x0000123b,0x00001d87,
19640x00001d88,0x000400f6,0x0000124e,0x0000124d,
19650x00000000,0x000400fa,0x0000123b,0x0000123c,
19660x0000124e,0x000200f8,0x0000123c,0x00050080,
19670x00000006,0x0000123f,0x00001d87,0x00001d88,
19680x000500c2,0x00000006,0x00001240,0x0000123f,
19690x00000063,0x00050084,0x00000006,0x00001242,
19700x0000009e,0x00001240,0x00050051,0x00000006,
19710x00001284,0x00000e2f,0x00000000,0x00050084,
19720x00000006,0x00001286,0x00001240,0x0000034a,
19730x00050095,0x0000005e,0x00001287,0x00001284,
19740x00001286,0x00050051,0x00000006,0x00001288,
19750x00001287,0x00000001,0x00050051,0x00000006,
19760x00001289,0x00001287,0x00000000,0x00050051,
19770x00000006,0x0000128c,0x00000e2f,0x00000001,
19780x00050080,0x00000006,0x0000128e,0x0000128c,
19790x00001288,0x00050050,0x00000007,0x0000128f,
19800x00001289,0x0000128e,0x0004007c,0x000000b1,
19810x0000127c,0x0000128f,0x00060041,0x000000b7,
19820x0000127d,0x0000127c,0x000000b6,0x000000b6,
19830x0006003d,0x00000006,0x0000127e,0x0000127d,
19840x00000002,0x00000004,0x00050080,0x00000006,
19850x00001271,0x00001242,0x00000063,0x00050084,
19860x00000006,0x000012a1,0x00001271,0x0000009e,
19870x00050095,0x0000005e,0x000012a2,0x00001284,
19880x000012a1,0x00050051,0x00000006,0x000012a3,
19890x000012a2,0x00000001,0x00050051,0x00000006,
19900x000012a4,0x000012a2,0x00000000,0x00050080,
19910x00000006,0x000012a9,0x0000128c,0x000012a3,
19920x00050050,0x00000007,0x000012aa,0x000012a4,
19930x000012a9,0x0004007c,0x000000b1,0x00001297,
19940x000012aa,0x00060041,0x000000b7,0x00001298,
19950x00001297,0x000000b6,0x000000b6,0x0006003d,
19960x00000006,0x00001299,0x00001298,0x00000002,
19970x00000004,0x000500b0,0x00000012,0x000012b1,
19980x00000d27,0x00001299,0x000400a8,0x00000012,
19990x000012b2,0x000012b1,0x000300f7,0x000012c1,
20000x00000000,0x000400fa,0x000012b2,0x000012b3,
20010x000012c1,0x000200f8,0x000012b3,0x000500aa,
20020x00000012,0x000012b8,0x00000d27,0x00001299,
20030x000300f7,0x000012bf,0x00000000,0x000400fa,
20040x000012b8,0x000012b9,0x000012bf,0x000200f8,
20050x000012b9,0x000500b0,0x00000012,0x000012be,
20060x00000d24,0x0000127e,0x000200f9,0x000012bf,
20070x000200f8,0x000012bf,0x000700f5,0x00000012,
20080x000012c0,0x000012b8,0x000012b3,0x000012be,
20090x000012b9,0x000200f9,0x000012c1,0x000200f8,
20100x000012c1,0x000700f5,0x00000012,0x000012c2,
20110x000012b1,0x0000123c,0x000012c0,0x000012bf,
20120x000300f7,0x0000124c,0x00000000,0x000400fa,
20130x000012c2,0x00001247,0x00001249,0x000200f8,
20140x00001249,0x00050080,0x00000006,0x0000124b,
20150x00001240,0x00000063,0x000200f9,0x0000124c,
20160x000200f8,0x00001247,0x000200f9,0x0000124c,
20170x000200f8,0x0000124c,0x000700f5,0x00000006,
20180x00002165,0x00001d87,0x00001247,0x0000124b,
20190x00001249,0x000600a9,0x00000006,0x0000219f,
20200x000012c2,0x00001240,0x00001d88,0x000200f9,
20210x0000124d,0x000200f8,0x0000124d,0x000200f9,
20220x00001237,0x000200f8,0x0000124e,0x000500aa,
20230x00000012,0x00001250,0x00001d87,0x00000058,
20240x000300f7,0x00001252,0x00000000,0x000400fa,
20250x00001250,0x00001251,0x00001252,0x000200f8,
20260x00001251,0x000200f9,0x00001265,0x000200f8,
20270x00001252,0x00050082,0x00000006,0x00001254,
20280x00001d87,0x00000063,0x00050084,0x00000006,
20290x00001255,0x0000009e,0x00001254,0x00050080,
20300x00000006,0x00001256,0x00001255,0x000000d8,
20310x00050051,0x00000006,0x000012e0,0x00000e2f,
20320x00000000,0x00050084,0x00000006,0x000012e2,
20330x00001256,0x0000009e,0x00050095,0x0000005e,
20340x000012e3,0x000012e0,0x000012e2,0x00050051,
20350x00000006,0x000012e4,0x000012e3,0x00000001,
20360x00050051,0x00000006,0x000012e5,0x000012e3,
20370x00000000,0x00050051,0x00000006,0x000012e8,
20380x00000e2f,0x00000001,0x00050080,0x00000006,
20390x000012ea,0x000012e8,0x000012e4,0x00050050,
20400x00000007,0x000012eb,0x000012e5,0x000012ea,
20410x0004007c,0x000000b1,0x000012d8,0x000012eb,
20420x00060041,0x000000b7,0x000012d9,0x000012d8,
20430x000000b6,0x000000b6,0x0006003d,0x00000006,
20440x000012da,0x000012d9,0x00000002,0x00000004,
20450x00050080,0x00000006,0x000012cd,0x00001255,
20460x000000de,0x00050084,0x00000006,0x000012fd,
20470x000012cd,0x0000009e,0x00050095,0x0000005e,
20480x000012fe,0x000012e0,0x000012fd,0x00050051,
20490x00000006,0x000012ff,0x000012fe,0x00000001,
20500x00050051,0x00000006,0x00001300,0x000012fe,
20510x00000000,0x00050080,0x00000006,0x00001305,
20520x000012e8,0x000012ff,0x00050050,0x00000007,
20530x00001306,0x00001300,0x00001305,0x0004007c,
20540x000000b1,0x000012f3,0x00001306,0x00060041,
20550x000000b7,0x000012f4,0x000012f3,0x000000b6,
20560x000000b6,0x0006003d,0x00000006,0x000012f5,
20570x000012f4,0x00000002,0x00000004,0x000500b0,
20580x00000012,0x0000130d,0x00000d27,0x000012f5,
20590x000400a8,0x00000012,0x0000130e,0x0000130d,
20600x000300f7,0x0000131d,0x00000000,0x000400fa,
20610x0000130e,0x0000130f,0x0000131d,0x000200f8,
20620x0000130f,0x000500aa,0x00000012,0x00001314,
20630x00000d27,0x000012f5,0x000300f7,0x0000131b,
20640x00000000,0x000400fa,0x00001314,0x00001315,
20650x0000131b,0x000200f8,0x00001315,0x000500b0,
20660x00000012,0x0000131a,0x00000d24,0x000012da,
20670x000200f9,0x0000131b,0x000200f8,0x0000131b,
20680x000700f5,0x00000012,0x0000131c,0x00001314,
20690x0000130f,0x0000131a,0x00001315,0x000200f9,
20700x0000131d,0x000200f8,0x0000131d,0x000700f5,
20710x00000012,0x0000131e,0x0000130d,0x00001252,
20720x0000131c,0x0000131b,0x000300f7,0x00001263,
20730x00000000,0x000400fa,0x0000131e,0x0000125c,
20740x00001263,0x000200f8,0x0000125c,0x00050096,
20750x0000005e,0x00001327,0x000012da,0x00000d24,
20760x00050051,0x00000006,0x00001328,0x00001327,
20770x00000001,0x00050051,0x00000006,0x00001329,
20780x00001327,0x00000000,0x00050082,0x00000006,
20790x0000132f,0x000012f5,0x00000d27,0x00050082,
20800x00000006,0x00001331,0x0000132f,0x00001328,
20810x000500aa,0x00000012,0x00001340,0x00001331,
20820x00000058,0x000300f7,0x00001347,0x00000000,
20830x000400fa,0x00001340,0x00001341,0x00001347,
20840x000200f8,0x00001341,0x000500b0,0x00000012,
20850x00001346,0x00001329,0x00000063,0x000200f9,
20860x00001347,0x000200f8,0x00001347,0x000700f5,
20870x00000012,0x00001348,0x00001340,0x0000125c,
20880x00001346,0x00001341,0x000400a8,0x00000012,
20890x00001262,0x00001348,0x000200f9,0x00001263,
20900x000200f8,0x00001263,0x000700f5,0x00000012,
20910x00001264,0x0000131e,0x0000131d,0x00001262,
20920x00001347,0x000200f9,0x00001265,0x000200f8,
20930x00001265,0x000700f5,0x00000012,0x00001d89,
20940x0000011e,0x00001251,0x00001264,0x00001263,
20950x000400a8,0x00000012,0x00000e34,0x00001d89,
20960x000200f9,0x00000e35,0x000200f8,0x00000e35,
20970x000700f5,0x00000012,0x00000e36,0x00000e2c,
20980x00000e25,0x00000e34,0x00001265,0x000300f7,
20990x00000e38,0x00000000,0x000400fa,0x00000e36,
21000x00000e37,0x00000e38,0x000200f8,0x00000e37,
21010x000200f9,0x00000e39,0x000200f8,0x00000e38,
21020x000200f9,0x00000e39,0x000200f8,0x00000e39,
21030x001100f5,0x00000027,0x00001df6,0x0000219c,
21040x00000d21,0x00001b5a,0x00000d32,0x00001df7,
21050x00000d94,0x0000219c,0x00000dc0,0x00001d85,
21060x00000e23,0x00001bea,0x00000e37,0x00001bea,
21070x00000e38,0x001100f5,0x00000006,0x00001d90,
21080x00000058,0x00000d21,0x00000063,0x00000d32,
21090x00000063,0x00000d94,0x00000063,0x00000dc0,
21100x00001d91,0x00000e23,0x00000063,0x00000e37,
21110x000000d8,0x00000e38,0x000500aa,0x00000012,
21120x000004bf,0x00001d90,0x000000d8,0x000300f7,
21130x000004c1,0x00000000,0x000400fa,0x000004bf,
21140x000004c0,0x000004c1,0x000200f8,0x000004c0,
21150x00050041,0x00000182,0x000004c3,0x00000180,
21160x000004c2,0x0004003d,0x00000006,0x000004c4,
21170x000004c3,0x000500c4,0x00000006,0x000004c6,
21180x000004c4,0x000004c5,0x000500c4,0x00000006,
21190x000004c8,0x0000044f,0x00000063,0x000500c5,
21200x00000006,0x000004c9,0x000004c6,0x000004c8,
21210x00050041,0x0000020a,0x0000134e,0x00000180,
21220x000003dd,0x0004003d,0x00000007,0x0000134f,
21230x0000134e,0x0004007c,0x000000b1,0x00001350,
21240x0000134f,0x00060041,0x000000b7,0x00001352,
21250x00001350,0x000000b6,0x000000b6,0x000700ea,
21260x00000006,0x00001353,0x00001352,0x00000063,
21270x00000058,0x00000063,0x00060041,0x000000b7,
21280x00001356,0x00001350,0x000000b6,0x000003bc,
21290x0006003d,0x00000006,0x00001357,0x00001356,
21300x00000002,0x00000004,0x000500b0,0x00000012,
21310x00001358,0x00001353,0x00001357,0x000300f7,
21320x00001362,0x00000000,0x000400fa,0x00001358,
21330x00001359,0x0000135f,0x000200f8,0x0000135f,
21340x00060041,0x000000b7,0x00001361,0x00001350,
21350x000000b6,0x000003f3,0x0005003e,0x00001361,
21360x00000063,0x00000002,0x00000004,0x000200f9,
21370x00001362,0x000200f8,0x00001359,0x00050080,
21380x00000006,0x0000135c,0x0000009e,0x00001353,
21390x00060041,0x000000b7,0x0000135e,0x00001350,
21400x000000b6,0x0000135c,0x0005003e,0x0000135e,
21410x000004c9,0x00000002,0x00000004,0x000200f9,
21420x00001362,0x000200f8,0x00001362,0x000200f9,
21430x000004c1,0x000200f8,0x000004c1,0x000300f7,
21440x000014ce,0x00000000,0x000300fb,0x00000058,
21450x000013aa,0x000200f8,0x000013aa,0x00050051,
21460x00000006,0x000013ac,0x00000498,0x00000003,
21470x000500c2,0x00000006,0x000013ad,0x000013ac,
21480x0000019b,0x000500ab,0x00000012,0x000013ae,
21490x000013ad,0x00000058,0x000400a8,0x00000012,
21500x000013af,0x000013ae,0x000300f7,0x000013b4,
21510x00000000,0x000400fa,0x000013af,0x000013b0,
21520x000013b4,0x000200f8,0x000013b0,0x00050051,
21530x00000006,0x000013b2,0x00000498,0x00000002,
21540x000500aa,0x00000012,0x000013b3,0x000013b2,
21550x00000058,0x000200f9,0x000013b4,0x000200f8,
21560x000013b4,0x000700f5,0x00000012,0x000013b5,
21570x000013ae,0x000013aa,0x000013b3,0x000013b0,
21580x000300f7,0x000013b7,0x00000000,0x000400fa,
21590x000013b5,0x000013b6,0x000013b7,0x000200f8,
21600x000013b6,0x000200f9,0x000014ce,0x000200f8,
21610x000013b7,0x00050051,0x00000006,0x000013b9,
21620x00000498,0x00000000,0x00050051,0x00000006,
21630x000013bb,0x00000498,0x00000001,0x000500c7,
21640x00000006,0x000013bc,0x000013bb,0x0000017b,
21650x00050050,0x00000007,0x000013bd,0x000013b9,
21660x000013bc,0x000500aa,0x00000012,0x000013c0,
21670x000013b9,0x00000058,0x000300f7,0x000013c5,
21680x00000000,0x000400fa,0x000013c0,0x000013c1,
21690x000013c5,0x000200f8,0x000013c1,0x000500aa,
21700x00000012,0x000013c4,0x000013bc,0x00000058,
21710x000200f9,0x000013c5,0x000200f8,0x000013c5,
21720x000700f5,0x00000012,0x000013c6,0x000013c0,
21730x000013b7,0x000013c4,0x000013c1,0x000300f7,
21740x000013cb,0x00000000,0x000400fa,0x000013c6,
21750x000013c7,0x000013cb,0x000200f8,0x000013c7,
21760x00060052,0x00000027,0x00001c10,0x00000058,
21770x00000498,0x00000000,0x00060052,0x00000027,
21780x00001c12,0x00000058,0x00001c10,0x00000001,
21790x00060052,0x00000027,0x00001c14,0x00000058,
21800x00001c12,0x00000002,0x000200f9,0x000014ce,
21810x000200f8,0x000013cb,0x000500c2,0x00000006,
21820x000013ce,0x000013bb,0x000000e4,0x000500c7,
21830x00000006,0x000013cf,0x000013ce,0x000001ad,
21840x00050051,0x00000006,0x000013d1,0x00000498,
21850x00000002,0x000500aa,0x00000012,0x000013d3,
21860x000013cf,0x00000058,0x000600a9,0x00000006,
21870x000013d5,0x000013d3,0x00000063,0x000013cf,
21880x00050097,0x0000005e,0x000013d8,0x000013d1,
21890x000013d5,0x00050051,0x00000006,0x000013d9,
21900x000013d8,0x00000000,0x00050051,0x00000006,
21910x000013da,0x000013d8,0x00000001,0x00050050,
21920x00000007,0x00002190,0x000013d9,0x000013da,
21930x00050041,0x00000182,0x000013db,0x00000180,
21940x0000029a,0x0004003d,0x00000006,0x000013dc,
21950x000013db,0x000200f9,0x000013dd,0x000200f8,
21960x000013dd,0x000700f5,0x00000006,0x00001eae,
21970x000013dc,0x000013cb,0x000021a0,0x000013f4,
21980x000700f5,0x00000006,0x00001ead,0x00000058,
21990x000013cb,0x0000216b,0x000013f4,0x000500b0,
22000x00000012,0x000013e1,0x00001ead,0x00001eae,
22010x000400f6,0x000013f5,0x000013f4,0x00000000,
22020x000400fa,0x000013e1,0x000013e2,0x000013f5,
22030x000200f8,0x000013e2,0x00050080,0x00000006,
22040x000013e5,0x00001ead,0x00001eae,0x000500c2,
22050x00000006,0x000013e6,0x000013e5,0x00000063,
22060x00050084,0x00000006,0x000013e8,0x000002ab,
22070x000013e6,0x00050041,0x0000020a,0x000013e9,
22080x00000180,0x000002aa,0x0004003d,0x00000007,
22090x000013ea,0x000013e9,0x00050051,0x00000006,
22100x000014f1,0x000013ea,0x00000000,0x00050084,
22110x00000006,0x000014f3,0x000013e6,0x0000218f,
22120x00050095,0x0000005e,0x000014f4,0x000014f1,
22130x000014f3,0x00050051,0x00000006,0x000014f5,
22140x000014f4,0x00000001,0x00050051,0x00000006,
22150x000014f6,0x000014f4,0x00000000,0x00050051,
22160x00000006,0x000014f9,0x000013ea,0x00000001,
22170x00050080,0x00000006,0x000014fb,0x000014f9,
22180x000014f5,0x00050050,0x00000007,0x000014fc,
22190x000014f6,0x000014fb,0x0004007c,0x000000b1,
22200x000014e9,0x000014fc,0x00060041,0x000000b7,
22210x000014ea,0x000014e9,0x000000b6,0x000000b6,
22220x0006003d,0x00000006,0x000014eb,0x000014ea,
22230x00000002,0x00000004,0x00050080,0x00000006,
22240x000014de,0x000013e8,0x00000063,0x00050084,
22250x00000006,0x0000150e,0x000014de,0x0000009e,
22260x00050095,0x0000005e,0x0000150f,0x000014f1,
22270x0000150e,0x00050051,0x00000006,0x00001510,
22280x0000150f,0x00000001,0x00050051,0x00000006,
22290x00001511,0x0000150f,0x00000000,0x00050080,
22300x00000006,0x00001516,0x000014f9,0x00001510,
22310x00050050,0x00000007,0x00001517,0x00001511,
22320x00001516,0x0004007c,0x000000b1,0x00001504,
22330x00001517,0x00060041,0x000000b7,0x00001505,
22340x00001504,0x000000b6,0x000000b6,0x0006003d,
22350x00000006,0x00001506,0x00001505,0x00000002,
22360x00000004,0x000500b0,0x00000012,0x0000151e,
22370x000013bc,0x00001506,0x000400a8,0x00000012,
22380x0000151f,0x0000151e,0x000300f7,0x0000152e,
22390x00000000,0x000400fa,0x0000151f,0x00001520,
22400x0000152e,0x000200f8,0x00001520,0x000500aa,
22410x00000012,0x00001525,0x000013bc,0x00001506,
22420x000300f7,0x0000152c,0x00000000,0x000400fa,
22430x00001525,0x00001526,0x0000152c,0x000200f8,
22440x00001526,0x000500b0,0x00000012,0x0000152b,
22450x000013b9,0x000014eb,0x000200f9,0x0000152c,
22460x000200f8,0x0000152c,0x000700f5,0x00000012,
22470x0000152d,0x00001525,0x00001520,0x0000152b,
22480x00001526,0x000200f9,0x0000152e,0x000200f8,
22490x0000152e,0x000700f5,0x00000012,0x0000152f,
22500x0000151e,0x000013e2,0x0000152d,0x0000152c,
22510x000300f7,0x000013f3,0x00000000,0x000400fa,
22520x0000152f,0x000013ee,0x000013f0,0x000200f8,
22530x000013f0,0x00050080,0x00000006,0x000013f2,
22540x000013e6,0x00000063,0x000200f9,0x000013f3,
22550x000200f8,0x000013ee,0x000200f9,0x000013f3,
22560x000200f8,0x000013f3,0x000700f5,0x00000006,
22570x0000216b,0x00001ead,0x000013ee,0x000013f2,
22580x000013f0,0x000600a9,0x00000006,0x000021a0,
22590x0000152f,0x000013e6,0x00001eae,0x000200f9,
22600x000013f4,0x000200f8,0x000013f4,0x000200f9,
22610x000013dd,0x000200f8,0x000013f5,0x000500ac,
22620x00000012,0x000013f7,0x00001ead,0x00000058,
22630x000300f7,0x0000142b,0x00000000,0x000400fa,
22640x000013f7,0x000013f8,0x0000142b,0x000200f8,
22650x000013f8,0x00050082,0x00000006,0x000013fa,
22660x00001ead,0x00000063,0x00050084,0x00000006,
22670x000013fb,0x000002ab,0x000013fa,0x00050080,
22680x00000006,0x000013fd,0x000013fb,0x000000d8,
22690x00050041,0x0000020a,0x000013fe,0x00000180,
22700x000002aa,0x0004003d,0x00000007,0x000013ff,
22710x000013fe,0x00050051,0x00000006,0x0000154d,
22720x000013ff,0x00000000,0x00050084,0x00000006,
22730x0000154f,0x000013fd,0x0000009e,0x00050095,
22740x0000005e,0x00001550,0x0000154d,0x0000154f,
22750x00050051,0x00000006,0x00001551,0x00001550,
22760x00000001,0x00050051,0x00000006,0x00001552,
22770x00001550,0x00000000,0x00050051,0x00000006,
22780x00001555,0x000013ff,0x00000001,0x00050080,
22790x00000006,0x00001557,0x00001555,0x00001551,
22800x00050050,0x00000007,0x00001558,0x00001552,
22810x00001557,0x0004007c,0x000000b1,0x00001545,
22820x00001558,0x00060041,0x000000b7,0x00001546,
22830x00001545,0x000000b6,0x000000b6,0x0006003d,
22840x00000006,0x00001547,0x00001546,0x00000002,
22850x00000004,0x00050080,0x00000006,0x0000153a,
22860x000013fb,0x000000de,0x00050084,0x00000006,
22870x0000156a,0x0000153a,0x0000009e,0x00050095,
22880x0000005e,0x0000156b,0x0000154d,0x0000156a,
22890x00050051,0x00000006,0x0000156c,0x0000156b,
22900x00000001,0x00050051,0x00000006,0x0000156d,
22910x0000156b,0x00000000,0x00050080,0x00000006,
22920x00001572,0x00001555,0x0000156c,0x00050050,
22930x00000007,0x00001573,0x0000156d,0x00001572,
22940x0004007c,0x000000b1,0x00001560,0x00001573,
22950x00060041,0x000000b7,0x00001561,0x00001560,
22960x000000b6,0x000000b6,0x0006003d,0x00000006,
22970x00001562,0x00001561,0x00000002,0x00000004,
22980x000500b0,0x00000012,0x0000157a,0x000013bc,
22990x00001562,0x000400a8,0x00000012,0x0000157b,
23000x0000157a,0x000300f7,0x0000158a,0x00000000,
23010x000400fa,0x0000157b,0x0000157c,0x0000158a,
23020x000200f8,0x0000157c,0x000500aa,0x00000012,
23030x00001581,0x000013bc,0x00001562,0x000300f7,
23040x00001588,0x00000000,0x000400fa,0x00001581,
23050x00001582,0x00001588,0x000200f8,0x00001582,
23060x000500b0,0x00000012,0x00001587,0x000013b9,
23070x00001547,0x000200f9,0x00001588,0x000200f8,
23080x00001588,0x000700f5,0x00000012,0x00001589,
23090x00001581,0x0000157c,0x00001587,0x00001582,
23100x000200f9,0x0000158a,0x000200f8,0x0000158a,
23110x000700f5,0x00000012,0x0000158b,0x0000157a,
23120x000013f8,0x00001589,0x00001588,0x000300f7,
23130x0000140c,0x00000000,0x000400fa,0x0000158b,
23140x00001404,0x0000140c,0x000200f8,0x00001404,
23150x00050080,0x00000006,0x00001406,0x000013fb,
23160x000002d5,0x00050084,0x00000006,0x0000159d,
23170x00001406,0x0000009e,0x00050095,0x0000005e,
23180x0000159e,0x0000154d,0x0000159d,0x00050051,
23190x00000006,0x0000159f,0x0000159e,0x00000001,
23200x00050051,0x00000006,0x000015a0,0x0000159e,
23210x00000000,0x00050080,0x00000006,0x000015a5,
23220x00001555,0x0000159f,0x00050050,0x00000007,
23230x000015a6,0x000015a0,0x000015a5,0x0004007c,
23240x000000b1,0x00001593,0x000015a6,0x00060041,
23250x000000b7,0x00001594,0x00001593,0x000000b6,
23260x000000b6,0x0006003d,0x00000006,0x00001595,
23270x00001594,0x00000002,0x00000004,0x000500c7,
23280x00000006,0x0000140a,0x00001595,0x00000063,
23290x000500ab,0x00000012,0x0000140b,0x0000140a,
23300x00000058,0x000200f9,0x0000140c,0x000200f8,
23310x0000140c,0x000700f5,0x00000012,0x0000140d,
23320x0000158b,0x0000158a,0x0000140b,0x00001404,
23330x000300f7,0x0000142a,0x00000000,0x000400fa,
23340x0000140d,0x0000140e,0x0000142a,0x000200f8,
23350x0000140e,0x00050096,0x0000005e,0x000015af,
23360x00001547,0x000013b9,0x00050051,0x00000006,
23370x000015b0,0x000015af,0x00000001,0x00050051,
23380x00000006,0x000015b1,0x000015af,0x00000000,
23390x00050082,0x00000006,0x000015b7,0x00001562,
23400x000013bc,0x00050082,0x00000006,0x000015b9,
23410x000015b7,0x000015b0,0x000500b0,0x00000012,
23420x000015c1,0x000015b9,0x000013da,0x000400a8,
23430x00000012,0x000015c2,0x000015c1,0x000300f7,
23440x000015d1,0x00000000,0x000400fa,0x000015c2,
23450x000015c3,0x000015d1,0x000200f8,0x000015c3,
23460x000500aa,0x00000012,0x000015c8,0x000015b9,
23470x000013da,0x000300f7,0x000015cf,0x00000000,
23480x000400fa,0x000015c8,0x000015c9,0x000015cf,
23490x000200f8,0x000015c9,0x000500b0,0x00000012,
23500x000015ce,0x000015b1,0x000013d9,0x000200f9,
23510x000015cf,0x000200f8,0x000015cf,0x000700f5,
23520x00000012,0x000015d0,0x000015c8,0x000015c3,
23530x000015ce,0x000015c9,0x000200f9,0x000015d1,
23540x000200f8,0x000015d1,0x000700f5,0x00000012,
23550x000015d2,0x000015c1,0x0000140e,0x000015d0,
23560x000015cf,0x000300f7,0x00001429,0x00000000,
23570x000400fa,0x000015d2,0x00001414,0x00001418,
23580x000200f8,0x00001418,0x00050084,0x00000006,
23590x000015f6,0x000013fa,0x0000218f,0x00050095,
23600x0000005e,0x000015f7,0x0000154d,0x000015f6,
23610x00050051,0x00000006,0x000015f8,0x000015f7,
23620x00000001,0x00050051,0x00000006,0x000015f9,
23630x000015f7,0x00000000,0x00050080,0x00000006,
23640x000015fe,0x00001555,0x000015f8,0x00050050,
23650x00000007,0x000015ff,0x000015f9,0x000015fe,
23660x0004007c,0x000000b1,0x000015ec,0x000015ff,
23670x00060041,0x000000b7,0x000015ed,0x000015ec,
23680x000000b6,0x000000b6,0x0006003d,0x00000006,
23690x000015ee,0x000015ed,0x00000002,0x00000004,
23700x00050080,0x00000006,0x000015e1,0x000013fb,
23710x00000063,0x00050084,0x00000006,0x00001611,
23720x000015e1,0x0000009e,0x00050095,0x0000005e,
23730x00001612,0x0000154d,0x00001611,0x00050051,
23740x00000006,0x00001613,0x00001612,0x00000001,
23750x00050051,0x00000006,0x00001614,0x00001612,
23760x00000000,0x00050080,0x00000006,0x00001619,
23770x00001555,0x00001613,0x00050050,0x00000007,
23780x0000161a,0x00001614,0x00001619,0x0004007c,
23790x000000b1,0x00001607,0x0000161a,0x00060041,
23800x000000b7,0x00001608,0x00001607,0x000000b6,
23810x000000b6,0x0006003d,0x00000006,0x00001609,
23820x00001608,0x00000002,0x00000004,0x00050080,
23830x00000006,0x0000141e,0x000013fb,0x0000009e,
23840x00050084,0x00000006,0x0000163a,0x0000141e,
23850x0000009e,0x00050095,0x0000005e,0x0000163b,
23860x0000154d,0x0000163a,0x00050051,0x00000006,
23870x0000163c,0x0000163b,0x00000001,0x00050051,
23880x00000006,0x0000163d,0x0000163b,0x00000000,
23890x00050080,0x00000006,0x00001642,0x00001555,
23900x0000163c,0x00050050,0x00000007,0x00001643,
23910x0000163d,0x00001642,0x0004007c,0x000000b1,
23920x00001630,0x00001643,0x00060041,0x000000b7,
23930x00001631,0x00001630,0x000000b6,0x000000b6,
23940x0006003d,0x00000006,0x00001632,0x00001631,
23950x00000002,0x00000004,0x00050080,0x00000006,
23960x00001625,0x000013fb,0x00000357,0x00050084,
23970x00000006,0x00001655,0x00001625,0x0000009e,
23980x00050095,0x0000005e,0x00001656,0x0000154d,
23990x00001655,0x00050051,0x00000006,0x00001657,
24000x00001656,0x00000001,0x00050051,0x00000006,
24010x00001658,0x00001656,0x00000000,0x00050080,
24020x00000006,0x0000165d,0x00001555,0x00001657,
24030x00050050,0x00000007,0x0000165e,0x00001658,
24040x0000165d,0x0004007c,0x000000b1,0x0000164b,
24050x0000165e,0x00060041,0x000000b7,0x0000164c,
24060x0000164b,0x000000b6,0x000000b6,0x0006003d,
24070x00000006,0x0000164d,0x0000164c,0x00000002,
24080x00000004,0x00050096,0x0000005e,0x00001667,
24090x000013b9,0x000015ee,0x00050051,0x00000006,
24100x00001668,0x00001667,0x00000001,0x00050051,
24110x00000006,0x00001669,0x00001667,0x00000000,
24120x00050082,0x00000006,0x0000166f,0x000013bc,
24130x00001609,0x00050082,0x00000006,0x00001671,
24140x0000166f,0x00001668,0x00050095,0x0000005e,
24150x0000167b,0x00001632,0x00001669,0x00050051,
24160x00000006,0x0000167c,0x0000167b,0x00000001,
24170x00050051,0x00000006,0x0000167d,0x0000167b,
24180x00000000,0x00050080,0x00000006,0x00001683,
24190x0000164d,0x00001671,0x00050080,0x00000006,
24200x00001685,0x00001683,0x0000167c,0x00060052,
24210x00000027,0x00001c53,0x0000167d,0x00000498,
24220x00000000,0x000500c7,0x00000006,0x0000168d,
24230x000013bb,0x00000191,0x000500c7,0x00000006,
24240x00001690,0x00001685,0x0000017b,0x000500c5,
24250x00000006,0x00001691,0x0000168d,0x00001690,
24260x00060052,0x00000027,0x00001c57,0x00001691,
24270x00001c53,0x00000001,0x000200f9,0x00001429,
24280x000200f8,0x00001414,0x00060052,0x00000027,
24290x00001c3c,0x00000058,0x00000498,0x00000000,
24300x00060052,0x00000027,0x00001c3e,0x00000058,
24310x00001c3c,0x00000001,0x00060052,0x00000027,
24320x00001c40,0x00000058,0x00001c3e,0x00000002,
24330x000200f9,0x00001429,0x000200f8,0x00001429,
24340x000700f5,0x00000027,0x00001f7f,0x00001c40,
24350x00001414,0x00001c57,0x00001418,0x000200f9,
24360x000014ce,0x000200f8,0x0000142a,0x000200f9,
24370x0000142b,0x000200f8,0x0000142b,0x000500c7,
24380x00000006,0x0000142f,0x00000438,0x00000063,
24390x000500ab,0x00000012,0x00001430,0x0000142f,
24400x00000058,0x000300f7,0x00001436,0x00000000,
24410x000400fa,0x00001430,0x00001431,0x00001436,
24420x000200f8,0x00001431,0x000500c7,0x00000006,
24430x00001434,0x000013bb,0x0000018b,0x000500ab,
24440x00000012,0x00001435,0x00001434,0x00000058,
24450x000200f9,0x00001436,0x000200f8,0x00001436,
24460x000700f5,0x00000012,0x00001437,0x00001430,
24470x0000142b,0x00001435,0x00001431,0x000300f7,
24480x0000143d,0x00000000,0x000400fa,0x00001437,
24490x00001438,0x0000143d,0x000200f8,0x00001438,
24500x000500c5,0x00000006,0x0000143b,0x000013bc,
24510x00000191,0x00060052,0x00000007,0x00001c5b,
24520x0000143b,0x000013bd,0x00000001,0x000200f9,
24530x0000143d,0x000200f8,0x0000143d,0x000700f5,
24540x00000007,0x00001eb1,0x000013bd,0x00001436,
24550x00001c5b,0x00001438,0x00050041,0x00000182,
24560x0000143e,0x00000180,0x000000e4,0x0004003d,
24570x00000006,0x0000143f,0x0000143e,0x000500ab,
24580x00000012,0x00001440,0x0000143f,0x00000058,
24590x000300f7,0x00001453,0x00000000,0x000400fa,
24600x00001440,0x00001441,0x00001453,0x000200f8,
24610x00001441,0x000500aa,0x00000012,0x00001444,
24620x000013d9,0x00000058,0x000300f7,0x00001449,
24630x00000000,0x000400fa,0x00001444,0x00001445,
24640x00001449,0x000200f8,0x00001445,0x000500aa,
24650x00000012,0x00001448,0x000013da,0x00000058,
24660x000200f9,0x00001449,0x000200f8,0x00001449,
24670x000700f5,0x00000012,0x0000144a,0x00001444,
24680x00001441,0x00001448,0x00001445,0x000600a9,
24690x00000007,0x0000144c,0x0000144a,0x00000208,
24700x00002190,0x00050041,0x0000020a,0x0000144d,
24710x00000180,0x00000325,0x0004003d,0x00000007,
24720x0000144e,0x0000144d,0x000300f7,0x000016d7,
24730x00000000,0x000300fb,0x00000058,0x000016a7,
24740x000200f8,0x000016a7,0x000200f9,0x000016a9,
24750x000200f8,0x000016a9,0x000700f5,0x00000006,
24760x00001eb3,0x0000143f,0x000016a7,0x000021a1,
24770x000016bf,0x000700f5,0x00000006,0x00001eb2,
24780x00000058,0x000016a7,0x00002171,0x000016bf,
24790x000500b0,0x00000012,0x000016ad,0x00001eb2,
24800x00001eb3,0x000400f6,0x000016c0,0x000016bf,
24810x00000000,0x000400fa,0x000016ad,0x000016ae,
24820x000016c0,0x000200f8,0x000016ae,0x00050080,
24830x00000006,0x000016b1,0x00001eb2,0x00001eb3,
24840x000500c2,0x00000006,0x000016b2,0x000016b1,
24850x00000063,0x00050084,0x00000006,0x000016b4,
24860x0000009e,0x000016b2,0x00050051,0x00000006,
24870x000016f6,0x0000144e,0x00000000,0x00050084,
24880x00000006,0x000016f8,0x000016b2,0x0000034a,
24890x00050095,0x0000005e,0x000016f9,0x000016f6,
24900x000016f8,0x00050051,0x00000006,0x000016fa,
24910x000016f9,0x00000001,0x00050051,0x00000006,
24920x000016fb,0x000016f9,0x00000000,0x00050051,
24930x00000006,0x000016fe,0x0000144e,0x00000001,
24940x00050080,0x00000006,0x00001700,0x000016fe,
24950x000016fa,0x00050050,0x00000007,0x00001701,
24960x000016fb,0x00001700,0x0004007c,0x000000b1,
24970x000016ee,0x00001701,0x00060041,0x000000b7,
24980x000016ef,0x000016ee,0x000000b6,0x000000b6,
24990x0006003d,0x00000006,0x000016f0,0x000016ef,
25000x00000002,0x00000004,0x00050080,0x00000006,
25010x000016e3,0x000016b4,0x00000063,0x00050084,
25020x00000006,0x00001713,0x000016e3,0x0000009e,
25030x00050095,0x0000005e,0x00001714,0x000016f6,
25040x00001713,0x00050051,0x00000006,0x00001715,
25050x00001714,0x00000001,0x00050051,0x00000006,
25060x00001716,0x00001714,0x00000000,0x00050080,
25070x00000006,0x0000171b,0x000016fe,0x00001715,
25080x00050050,0x00000007,0x0000171c,0x00001716,
25090x0000171b,0x0004007c,0x000000b1,0x00001709,
25100x0000171c,0x00060041,0x000000b7,0x0000170a,
25110x00001709,0x000000b6,0x000000b6,0x0006003d,
25120x00000006,0x0000170b,0x0000170a,0x00000002,
25130x00000004,0x00050051,0x00000006,0x00001720,
25140x00001eb1,0x00000001,0x000500b0,0x00000012,
25150x00001723,0x00001720,0x0000170b,0x000400a8,
25160x00000012,0x00001724,0x00001723,0x000300f7,
25170x00001733,0x00000000,0x000400fa,0x00001724,
25180x00001725,0x00001733,0x000200f8,0x00001725,
25190x000500aa,0x00000012,0x0000172a,0x00001720,
25200x0000170b,0x000300f7,0x00001731,0x00000000,
25210x000400fa,0x0000172a,0x0000172b,0x00001731,
25220x000200f8,0x0000172b,0x00050051,0x00000006,
25230x0000172d,0x00001eb1,0x00000000,0x000500b0,
25240x00000012,0x00001730,0x0000172d,0x000016f0,
25250x000200f9,0x00001731,0x000200f8,0x00001731,
25260x000700f5,0x00000012,0x00001732,0x0000172a,
25270x00001725,0x00001730,0x0000172b,0x000200f9,
25280x00001733,0x000200f8,0x00001733,0x000700f5,
25290x00000012,0x00001734,0x00001723,0x000016ae,
25300x00001732,0x00001731,0x000300f7,0x000016be,
25310x00000000,0x000400fa,0x00001734,0x000016b9,
25320x000016bb,0x000200f8,0x000016bb,0x00050080,
25330x00000006,0x000016bd,0x000016b2,0x00000063,
25340x000200f9,0x000016be,0x000200f8,0x000016b9,
25350x000200f9,0x000016be,0x000200f8,0x000016be,
25360x000700f5,0x00000006,0x00002171,0x00001eb2,
25370x000016b9,0x000016bd,0x000016bb,0x000600a9,
25380x00000006,0x000021a1,0x00001734,0x000016b2,
25390x00001eb3,0x000200f9,0x000016bf,0x000200f8,
25400x000016bf,0x000200f9,0x000016a9,0x000200f8,
25410x000016c0,0x000500aa,0x00000012,0x000016c2,
25420x00001eb2,0x00000058,0x000300f7,0x000016c4,
25430x00000000,0x000400fa,0x000016c2,0x000016c3,
25440x000016c4,0x000200f8,0x000016c3,0x000200f9,
25450x000016d7,0x000200f8,0x000016c4,0x00050082,
25460x00000006,0x000016c6,0x00001eb2,0x00000063,
25470x00050084,0x00000006,0x000016c7,0x0000009e,
25480x000016c6,0x00050080,0x00000006,0x000016c8,
25490x000016c7,0x000000d8,0x00050051,0x00000006,
25500x00001752,0x0000144e,0x00000000,0x00050084,
25510x00000006,0x00001754,0x000016c8,0x0000009e,
25520x00050095,0x0000005e,0x00001755,0x00001752,
25530x00001754,0x00050051,0x00000006,0x00001756,
25540x00001755,0x00000001,0x00050051,0x00000006,
25550x00001757,0x00001755,0x00000000,0x00050051,
25560x00000006,0x0000175a,0x0000144e,0x00000001,
25570x00050080,0x00000006,0x0000175c,0x0000175a,
25580x00001756,0x00050050,0x00000007,0x0000175d,
25590x00001757,0x0000175c,0x0004007c,0x000000b1,
25600x0000174a,0x0000175d,0x00060041,0x000000b7,
25610x0000174b,0x0000174a,0x000000b6,0x000000b6,
25620x0006003d,0x00000006,0x0000174c,0x0000174b,
25630x00000002,0x00000004,0x00050080,0x00000006,
25640x0000173f,0x000016c7,0x000000de,0x00050084,
25650x00000006,0x0000176f,0x0000173f,0x0000009e,
25660x00050095,0x0000005e,0x00001770,0x00001752,
25670x0000176f,0x00050051,0x00000006,0x00001771,
25680x00001770,0x00000001,0x00050051,0x00000006,
25690x00001772,0x00001770,0x00000000,0x00050080,
25700x00000006,0x00001777,0x0000175a,0x00001771,
25710x00050050,0x00000007,0x00001778,0x00001772,
25720x00001777,0x0004007c,0x000000b1,0x00001765,
25730x00001778,0x00060041,0x000000b7,0x00001766,
25740x00001765,0x000000b6,0x000000b6,0x0006003d,
25750x00000006,0x00001767,0x00001766,0x00000002,
25760x00000004,0x00050051,0x00000006,0x0000177c,
25770x00001eb1,0x00000001,0x000500b0,0x00000012,
25780x0000177f,0x0000177c,0x00001767,0x000400a8,
25790x00000012,0x00001780,0x0000177f,0x000300f7,
25800x0000178f,0x00000000,0x000400fa,0x00001780,
25810x00001781,0x0000178f,0x000200f8,0x00001781,
25820x000500aa,0x00000012,0x00001786,0x0000177c,
25830x00001767,0x000300f7,0x0000178d,0x00000000,
25840x000400fa,0x00001786,0x00001787,0x0000178d,
25850x000200f8,0x00001787,0x00050051,0x00000006,
25860x00001789,0x00001eb1,0x00000000,0x000500b0,
25870x00000012,0x0000178c,0x00001789,0x0000174c,
25880x000200f9,0x0000178d,0x000200f8,0x0000178d,
25890x000700f5,0x00000012,0x0000178e,0x00001786,
25900x00001781,0x0000178c,0x00001787,0x000200f9,
25910x0000178f,0x000200f8,0x0000178f,0x000700f5,
25920x00000012,0x00001790,0x0000177f,0x000016c4,
25930x0000178e,0x0000178d,0x000300f7,0x000016d5,
25940x00000000,0x000400fa,0x00001790,0x000016ce,
25950x000016d5,0x000200f8,0x000016ce,0x00050051,
25960x00000006,0x00001798,0x00001eb1,0x00000000,
25970x00050096,0x0000005e,0x00001799,0x0000174c,
25980x00001798,0x00050051,0x00000006,0x0000179a,
25990x00001799,0x00000001,0x00050051,0x00000006,
26000x0000179b,0x00001799,0x00000000,0x00050082,
26010x00000006,0x000017a1,0x00001767,0x0000177c,
26020x00050082,0x00000006,0x000017a3,0x000017a1,
26030x0000179a,0x00050051,0x00000006,0x000017aa,
26040x0000144c,0x00000001,0x000500b0,0x00000012,
26050x000017ab,0x000017a3,0x000017aa,0x000400a8,
26060x00000012,0x000017ac,0x000017ab,0x000300f7,
26070x000017bb,0x00000000,0x000400fa,0x000017ac,
26080x000017ad,0x000017bb,0x000200f8,0x000017ad,
26090x000500aa,0x00000012,0x000017b2,0x000017a3,
26100x000017aa,0x000300f7,0x000017b9,0x00000000,
26110x000400fa,0x000017b2,0x000017b3,0x000017b9,
26120x000200f8,0x000017b3,0x00050051,0x00000006,
26130x000017b7,0x0000144c,0x00000000,0x000500b0,
26140x00000012,0x000017b8,0x0000179b,0x000017b7,
26150x000200f9,0x000017b9,0x000200f8,0x000017b9,
26160x000700f5,0x00000012,0x000017ba,0x000017b2,
26170x000017ad,0x000017b8,0x000017b3,0x000200f9,
26180x000017bb,0x000200f8,0x000017bb,0x000700f5,
26190x00000012,0x000017bc,0x000017ab,0x000016ce,
26200x000017ba,0x000017b9,0x000400a8,0x00000012,
26210x000016d4,0x000017bc,0x000200f9,0x000016d5,
26220x000200f8,0x000016d5,0x000700f5,0x00000012,
26230x000016d6,0x00001790,0x0000178f,0x000016d4,
26240x000017bb,0x000200f9,0x000016d7,0x000200f8,
26250x000016d7,0x000700f5,0x00000012,0x00001eb4,
26260x0000011e,0x000016c3,0x000016d6,0x000016d5,
26270x000200f9,0x00001453,0x000200f8,0x00001453,
26280x000700f5,0x00000012,0x00001454,0x00001440,
26290x0000143d,0x00001eb4,0x000016d7,0x000300f7,
26300x00001456,0x00000000,0x000400fa,0x00001454,
26310x00001455,0x00001456,0x000200f8,0x00001455,
26320x000200f9,0x000014ce,0x000200f8,0x00001456,
26330x000500c6,0x00000006,0x000017c3,0x000000cb,
26340x000013b9,0x00050084,0x00000006,0x000017c4,
26350x000017c3,0x000000d0,0x000500c6,0x00000006,
26360x000017c8,0x000017c4,0x000013bb,0x00050084,
26370x00000006,0x000017c9,0x000017c8,0x000000d0,
26380x000500c6,0x00000006,0x000017cd,0x000017c9,
26390x000013d1,0x00050084,0x00000006,0x000017ce,
26400x000017cd,0x000000d0,0x000500c6,0x00000006,
26410x000017d2,0x000017ce,0x000013ac,0x00050084,
26420x00000006,0x000017d3,0x000017d2,0x000000d0,
26430x000500c2,0x00000006,0x000017d5,0x000017d3,
26440x000000e4,0x000500c6,0x00000006,0x000017d7,
26450x000017d3,0x000017d5,0x00050084,0x00000006,
26460x000017d9,0x000017d7,0x000000e8,0x000500c2,
26470x00000006,0x000017db,0x000017d9,0x000000ec,
26480x000500c6,0x00000006,0x000017dd,0x000017d9,
26490x000017db,0x00050084,0x00000006,0x000017df,
26500x000017dd,0x000000f0,0x000500c2,0x00000006,
26510x000017e1,0x000017df,0x000000e4,0x000500c6,
26520x00000006,0x000017e3,0x000017df,0x000017e1,
26530x000200f9,0x00001459,0x000200f8,0x00001459,
26540x000700f5,0x00000006,0x00001ec5,0x00000058,
26550x00001456,0x000014b7,0x000014b5,0x000500b0,
26560x00000012,0x0000145c,0x00001ec5,0x0000034a,
26570x000400f6,0x000014b8,0x000014b5,0x00000000,
26580x000400fa,0x0000145c,0x0000145d,0x000014b8,
26590x000200f8,0x0000145d,0x00050080,0x00000006,
26600x00001460,0x000017e3,0x00001ec5,0x00050041,
26610x00000182,0x00001461,0x00000180,0x000000ec,
26620x0004003d,0x00000006,0x00001462,0x00001461,
26630x000500c7,0x00000006,0x00001463,0x00001460,
26640x00001462,0x00050084,0x00000006,0x00001464,
26650x000002ab,0x00001463,0x00050080,0x00000006,
26660x00001466,0x00001464,0x00000357,0x00050041,
26670x0000020a,0x00001467,0x00000180,0x00000355,
26680x0004003d,0x00000007,0x00001468,0x00001467,
26690x00050051,0x00000006,0x000017f4,0x00001468,
26700x00000000,0x00050084,0x00000006,0x000017f6,
26710x00001466,0x0000009e,0x00050095,0x0000005e,
26720x000017f7,0x000017f4,0x000017f6,0x00050051,
26730x00000006,0x000017f8,0x000017f7,0x00000001,
26740x00050051,0x00000006,0x000017f9,0x000017f7,
26750x00000000,0x00050051,0x00000006,0x000017fc,
26760x00001468,0x00000001,0x00050080,0x00000006,
26770x000017fe,0x000017fc,0x000017f8,0x00050050,
26780x00000007,0x000017ff,0x000017f9,0x000017fe,
26790x0004007c,0x000000b1,0x000017ec,0x000017ff,
26800x00060041,0x000000b7,0x000017ed,0x000017ec,
26810x000000b6,0x000000b6,0x0006003d,0x00000006,
26820x000017ee,0x000017ed,0x00000002,0x00000004,
26830x000500c2,0x00000006,0x0000146a,0x000017ee,
26840x000000e4,0x000500c7,0x00000006,0x0000146c,
26850x0000146a,0x00000063,0x000500aa,0x00000012,
26860x0000146d,0x0000146c,0x00000058,0x000300f7,
26870x0000146f,0x00000000,0x000400fa,0x0000146d,
26880x0000146e,0x0000146f,0x000200f8,0x0000146e,
26890x000200f9,0x000014b5,0x000200f8,0x0000146f,
26900x00050084,0x00000006,0x00001811,0x00001463,
26910x0000218f,0x00050095,0x0000005e,0x00001812,
26920x000017f4,0x00001811,0x00050051,0x00000006,
26930x00001813,0x00001812,0x00000001,0x00050051,
26940x00000006,0x00001814,0x00001812,0x00000000,
26950x00050080,0x00000006,0x00001819,0x000017fc,
26960x00001813,0x00050050,0x00000007,0x0000181a,
26970x00001814,0x00001819,0x0004007c,0x000000b1,
26980x00001807,0x0000181a,0x00060041,0x000000b7,
26990x00001808,0x00001807,0x000000b6,0x000000b6,
27000x0006003d,0x00000006,0x00001809,0x00001808,
27010x00000002,0x00000004,0x000500ab,0x00000012,
27020x00001476,0x00001809,0x000013b9,0x000400a8,
27030x00000012,0x00001477,0x00001476,0x000300f7,
27040x00001481,0x00000000,0x000400fa,0x00001477,
27050x00001478,0x00001481,0x000200f8,0x00001478,
27060x00050080,0x00000006,0x0000147a,0x00001464,
27070x00000063,0x00050084,0x00000006,0x0000182c,
27080x0000147a,0x0000009e,0x00050095,0x0000005e,
27090x0000182d,0x000017f4,0x0000182c,0x00050051,
27100x00000006,0x0000182e,0x0000182d,0x00000001,
27110x00050051,0x00000006,0x0000182f,0x0000182d,
27120x00000000,0x00050080,0x00000006,0x00001834,
27130x000017fc,0x0000182e,0x00050050,0x00000007,
27140x00001835,0x0000182f,0x00001834,0x0004007c,
27150x000000b1,0x00001822,0x00001835,0x00060041,
27160x000000b7,0x00001823,0x00001822,0x000000b6,
27170x000000b6,0x0006003d,0x00000006,0x00001824,
27180x00001823,0x00000002,0x00000004,0x000500ab,
27190x00000012,0x00001480,0x00001824,0x000013bb,
27200x000200f9,0x00001481,0x000200f8,0x00001481,
27210x000700f5,0x00000012,0x00001482,0x00001476,
27220x0000146f,0x00001480,0x00001478,0x000400a8,
27230x00000012,0x00001483,0x00001482,0x000300f7,
27240x0000148d,0x00000000,0x000400fa,0x00001483,
27250x00001484,0x0000148d,0x000200f8,0x00001484,
27260x00050080,0x00000006,0x00001486,0x00001464,
27270x000000d8,0x00050084,0x00000006,0x00001847,
27280x00001486,0x0000009e,0x00050095,0x0000005e,
27290x00001848,0x000017f4,0x00001847,0x00050051,
27300x00000006,0x00001849,0x00001848,0x00000001,
27310x00050051,0x00000006,0x0000184a,0x00001848,
27320x00000000,0x00050080,0x00000006,0x0000184f,
27330x000017fc,0x00001849,0x00050050,0x00000007,
27340x00001850,0x0000184a,0x0000184f,0x0004007c,
27350x000000b1,0x0000183d,0x00001850,0x00060041,
27360x000000b7,0x0000183e,0x0000183d,0x000000b6,
27370x000000b6,0x0006003d,0x00000006,0x0000183f,
27380x0000183e,0x00000002,0x00000004,0x000500ab,
27390x00000012,0x0000148c,0x0000183f,0x000013d1,
27400x000200f9,0x0000148d,0x000200f8,0x0000148d,
27410x000700f5,0x00000012,0x0000148e,0x00001482,
27420x00001481,0x0000148c,0x00001484,0x000400a8,
27430x00000012,0x0000148f,0x0000148e,0x000300f7,
27440x00001499,0x00000000,0x000400fa,0x0000148f,
27450x00001490,0x00001499,0x000200f8,0x00001490,
27460x00050080,0x00000006,0x00001492,0x00001464,
27470x000000de,0x00050084,0x00000006,0x00001862,
27480x00001492,0x0000009e,0x00050095,0x0000005e,
27490x00001863,0x000017f4,0x00001862,0x00050051,
27500x00000006,0x00001864,0x00001863,0x00000001,
27510x00050051,0x00000006,0x00001865,0x00001863,
27520x00000000,0x00050080,0x00000006,0x0000186a,
27530x000017fc,0x00001864,0x00050050,0x00000007,
27540x0000186b,0x00001865,0x0000186a,0x0004007c,
27550x000000b1,0x00001858,0x0000186b,0x00060041,
27560x000000b7,0x00001859,0x00001858,0x000000b6,
27570x000000b6,0x0006003d,0x00000006,0x0000185a,
27580x00001859,0x00000002,0x00000004,0x000500ab,
27590x00000012,0x00001498,0x0000185a,0x000013ac,
27600x000200f9,0x00001499,0x000200f8,0x00001499,
27610x000700f5,0x00000012,0x0000149a,0x0000148e,
27620x0000148d,0x00001498,0x00001490,0x000300f7,
27630x0000149c,0x00000000,0x000400fa,0x0000149a,
27640x0000149b,0x0000149c,0x000200f8,0x0000149b,
27650x000200f9,0x000014b5,0x000200f8,0x0000149c,
27660x000500c7,0x00000006,0x0000149e,0x0000146a,
27670x000000d8,0x000500ab,0x00000012,0x0000149f,
27680x0000149e,0x00000058,0x000300f7,0x000014b4,
27690x00000000,0x000400fa,0x0000149f,0x000014a0,
27700x000014a4,0x000200f8,0x000014a4,0x00050080,
27710x00000006,0x000014a6,0x00001464,0x0000009e,
27720x00050084,0x00000006,0x00001881,0x000014a6,
27730x0000009e,0x00050095,0x0000005e,0x00001882,
27740x000017f4,0x00001881,0x00050051,0x00000006,
27750x00001883,0x00001882,0x00000001,0x00050051,
27760x00000006,0x00001884,0x00001882,0x00000000,
27770x00050080,0x00000006,0x00001889,0x000017fc,
27780x00001883,0x00050050,0x00000007,0x0000188a,
27790x00001884,0x00001889,0x0004007c,0x000000b1,
27800x00001877,0x0000188a,0x00060041,0x000000b7,
27810x00001878,0x00001877,0x000000b6,0x000000b6,
27820x0006003d,0x00000006,0x00001879,0x00001878,
27830x00000002,0x00000004,0x0006003d,0x00000006,
27840x00001894,0x000017ed,0x00000002,0x00000004,
27850x00060052,0x00000027,0x00001c9a,0x00001879,
27860x00000498,0x00000000,0x000500c7,0x00000006,
27870x000018ac,0x000013bb,0x00000191,0x000500c7,
27880x00000006,0x000018af,0x00001894,0x0000017b,
27890x000500c5,0x00000006,0x000018b0,0x000018ac,
27900x000018af,0x00060052,0x00000027,0x00001c9e,
27910x000018b0,0x00001c9a,0x00000001,0x000200f9,
27920x000014b4,0x000200f8,0x000014a0,0x00060052,
27930x00000027,0x00001c8f,0x00000058,0x00000498,
27940x00000000,0x00060052,0x00000027,0x00001c91,
27950x00000058,0x00001c8f,0x00000001,0x00060052,
27960x00000027,0x00001c93,0x00000058,0x00001c91,
27970x00000002,0x000200f9,0x000014b4,0x000200f8,
27980x000014b4,0x000700f5,0x00000027,0x00001edf,
27990x00001c93,0x000014a0,0x00001c9e,0x000014a4,
28000x000200f9,0x000014b8,0x000200f8,0x000014b5,
28010x00050080,0x00000006,0x000014b7,0x00001ec5,
28020x000003bc,0x000200f9,0x00001459,0x000200f8,
28030x000014b8,0x000700f5,0x00000006,0x00001eea,
28040x00001da1,0x00001459,0x00000063,0x000014b4,
28050x000700f5,0x00000027,0x00001ede,0x00000498,
28060x00001459,0x00001edf,0x000014b4,0x000700f5,
28070x00000012,0x00001eca,0x0000011e,0x00001459,
28080x00000217,0x000014b4,0x000300f7,0x000014ba,
28090x00000000,0x000400fa,0x00001eca,0x000014ce,
28100x000014ba,0x000200f8,0x000014ba,0x00060052,
28110x00000027,0x00001ca0,0x00000058,0x00001ede,
28120x00000000,0x00060052,0x00000027,0x00001ca2,
28130x00000058,0x00001ca0,0x00000001,0x00060052,
28140x00000027,0x00001ca4,0x00000058,0x00001ca2,
28150x00000002,0x000500c7,0x00000006,0x000014c0,
28160x00000438,0x000000d8,0x000500ab,0x00000012,
28170x000014c1,0x000014c0,0x00000058,0x000300f7,
28180x000014ca,0x00000000,0x000400fa,0x000014c1,
28190x000014c2,0x000014ca,0x000200f8,0x000014c2,
28200x00050041,0x0000020a,0x000014c3,0x00000180,
28210x000003c8,0x0004003d,0x00000007,0x000014c4,
28220x000014c3,0x00050041,0x00000182,0x000014c5,
28230x00000180,0x000003c9,0x0004003d,0x00000006,
28240x000014c6,0x000014c5,0x000300f7,0x000018fa,
28250x00000000,0x000300fb,0x00000058,0x000018ca,
28260x000200f8,0x000018ca,0x000200f9,0x000018cc,
28270x000200f8,0x000018cc,0x000700f5,0x00000006,
28280x00001ee1,0x000014c6,0x000018ca,0x000021a2,
28290x000018e2,0x000700f5,0x00000006,0x00001ee0,
28300x00000058,0x000018ca,0x00002188,0x000018e2,
28310x000500b0,0x00000012,0x000018d0,0x00001ee0,
28320x00001ee1,0x000400f6,0x000018e3,0x000018e2,
28330x00000000,0x000400fa,0x000018d0,0x000018d1,
28340x000018e3,0x000200f8,0x000018d1,0x00050080,
28350x00000006,0x000018d4,0x00001ee0,0x00001ee1,
28360x000500c2,0x00000006,0x000018d5,0x000018d4,
28370x00000063,0x00050084,0x00000006,0x000018d7,
28380x0000009e,0x000018d5,0x00050051,0x00000006,
28390x00001919,0x000014c4,0x00000000,0x00050084,
28400x00000006,0x0000191b,0x000018d5,0x0000034a,
28410x00050095,0x0000005e,0x0000191c,0x00001919,
28420x0000191b,0x00050051,0x00000006,0x0000191d,
28430x0000191c,0x00000001,0x00050051,0x00000006,
28440x0000191e,0x0000191c,0x00000000,0x00050051,
28450x00000006,0x00001921,0x000014c4,0x00000001,
28460x00050080,0x00000006,0x00001923,0x00001921,
28470x0000191d,0x00050050,0x00000007,0x00001924,
28480x0000191e,0x00001923,0x0004007c,0x000000b1,
28490x00001911,0x00001924,0x00060041,0x000000b7,
28500x00001912,0x00001911,0x000000b6,0x000000b6,
28510x0006003d,0x00000006,0x00001913,0x00001912,
28520x00000002,0x00000004,0x00050080,0x00000006,
28530x00001906,0x000018d7,0x00000063,0x00050084,
28540x00000006,0x00001936,0x00001906,0x0000009e,
28550x00050095,0x0000005e,0x00001937,0x00001919,
28560x00001936,0x00050051,0x00000006,0x00001938,
28570x00001937,0x00000001,0x00050051,0x00000006,
28580x00001939,0x00001937,0x00000000,0x00050080,
28590x00000006,0x0000193e,0x00001921,0x00001938,
28600x00050050,0x00000007,0x0000193f,0x00001939,
28610x0000193e,0x0004007c,0x000000b1,0x0000192c,
28620x0000193f,0x00060041,0x000000b7,0x0000192d,
28630x0000192c,0x000000b6,0x000000b6,0x0006003d,
28640x00000006,0x0000192e,0x0000192d,0x00000002,
28650x00000004,0x000500b0,0x00000012,0x00001946,
28660x000013bc,0x0000192e,0x000400a8,0x00000012,
28670x00001947,0x00001946,0x000300f7,0x00001956,
28680x00000000,0x000400fa,0x00001947,0x00001948,
28690x00001956,0x000200f8,0x00001948,0x000500aa,
28700x00000012,0x0000194d,0x000013bc,0x0000192e,
28710x000300f7,0x00001954,0x00000000,0x000400fa,
28720x0000194d,0x0000194e,0x00001954,0x000200f8,
28730x0000194e,0x000500b0,0x00000012,0x00001953,
28740x000013b9,0x00001913,0x000200f9,0x00001954,
28750x000200f8,0x00001954,0x000700f5,0x00000012,
28760x00001955,0x0000194d,0x00001948,0x00001953,
28770x0000194e,0x000200f9,0x00001956,0x000200f8,
28780x00001956,0x000700f5,0x00000012,0x00001957,
28790x00001946,0x000018d1,0x00001955,0x00001954,
28800x000300f7,0x000018e1,0x00000000,0x000400fa,
28810x00001957,0x000018dc,0x000018de,0x000200f8,
28820x000018de,0x00050080,0x00000006,0x000018e0,
28830x000018d5,0x00000063,0x000200f9,0x000018e1,
28840x000200f8,0x000018dc,0x000200f9,0x000018e1,
28850x000200f8,0x000018e1,0x000700f5,0x00000006,
28860x00002188,0x00001ee0,0x000018dc,0x000018e0,
28870x000018de,0x000600a9,0x00000006,0x000021a2,
28880x00001957,0x000018d5,0x00001ee1,0x000200f9,
28890x000018e2,0x000200f8,0x000018e2,0x000200f9,
28900x000018cc,0x000200f8,0x000018e3,0x000500aa,
28910x00000012,0x000018e5,0x00001ee0,0x00000058,
28920x000300f7,0x000018e7,0x00000000,0x000400fa,
28930x000018e5,0x000018e6,0x000018e7,0x000200f8,
28940x000018e6,0x000200f9,0x000018fa,0x000200f8,
28950x000018e7,0x00050082,0x00000006,0x000018e9,
28960x00001ee0,0x00000063,0x00050084,0x00000006,
28970x000018ea,0x0000009e,0x000018e9,0x00050080,
28980x00000006,0x000018eb,0x000018ea,0x000000d8,
28990x00050051,0x00000006,0x00001975,0x000014c4,
29000x00000000,0x00050084,0x00000006,0x00001977,
29010x000018eb,0x0000009e,0x00050095,0x0000005e,
29020x00001978,0x00001975,0x00001977,0x00050051,
29030x00000006,0x00001979,0x00001978,0x00000001,
29040x00050051,0x00000006,0x0000197a,0x00001978,
29050x00000000,0x00050051,0x00000006,0x0000197d,
29060x000014c4,0x00000001,0x00050080,0x00000006,
29070x0000197f,0x0000197d,0x00001979,0x00050050,
29080x00000007,0x00001980,0x0000197a,0x0000197f,
29090x0004007c,0x000000b1,0x0000196d,0x00001980,
29100x00060041,0x000000b7,0x0000196e,0x0000196d,
29110x000000b6,0x000000b6,0x0006003d,0x00000006,
29120x0000196f,0x0000196e,0x00000002,0x00000004,
29130x00050080,0x00000006,0x00001962,0x000018ea,
29140x000000de,0x00050084,0x00000006,0x00001992,
29150x00001962,0x0000009e,0x00050095,0x0000005e,
29160x00001993,0x00001975,0x00001992,0x00050051,
29170x00000006,0x00001994,0x00001993,0x00000001,
29180x00050051,0x00000006,0x00001995,0x00001993,
29190x00000000,0x00050080,0x00000006,0x0000199a,
29200x0000197d,0x00001994,0x00050050,0x00000007,
29210x0000199b,0x00001995,0x0000199a,0x0004007c,
29220x000000b1,0x00001988,0x0000199b,0x00060041,
29230x000000b7,0x00001989,0x00001988,0x000000b6,
29240x000000b6,0x0006003d,0x00000006,0x0000198a,
29250x00001989,0x00000002,0x00000004,0x000500b0,
29260x00000012,0x000019a2,0x000013bc,0x0000198a,
29270x000400a8,0x00000012,0x000019a3,0x000019a2,
29280x000300f7,0x000019b2,0x00000000,0x000400fa,
29290x000019a3,0x000019a4,0x000019b2,0x000200f8,
29300x000019a4,0x000500aa,0x00000012,0x000019a9,
29310x000013bc,0x0000198a,0x000300f7,0x000019b0,
29320x00000000,0x000400fa,0x000019a9,0x000019aa,
29330x000019b0,0x000200f8,0x000019aa,0x000500b0,
29340x00000012,0x000019af,0x000013b9,0x0000196f,
29350x000200f9,0x000019b0,0x000200f8,0x000019b0,
29360x000700f5,0x00000012,0x000019b1,0x000019a9,
29370x000019a4,0x000019af,0x000019aa,0x000200f9,
29380x000019b2,0x000200f8,0x000019b2,0x000700f5,
29390x00000012,0x000019b3,0x000019a2,0x000018e7,
29400x000019b1,0x000019b0,0x000300f7,0x000018f8,
29410x00000000,0x000400fa,0x000019b3,0x000018f1,
29420x000018f8,0x000200f8,0x000018f1,0x00050096,
29430x0000005e,0x000019bc,0x0000196f,0x000013b9,
29440x00050051,0x00000006,0x000019bd,0x000019bc,
29450x00000001,0x00050051,0x00000006,0x000019be,
29460x000019bc,0x00000000,0x00050082,0x00000006,
29470x000019c4,0x0000198a,0x000013bc,0x00050082,
29480x00000006,0x000019c6,0x000019c4,0x000019bd,
29490x000500aa,0x00000012,0x000019d5,0x000019c6,
29500x00000058,0x000300f7,0x000019dc,0x00000000,
29510x000400fa,0x000019d5,0x000019d6,0x000019dc,
29520x000200f8,0x000019d6,0x000500b0,0x00000012,
29530x000019db,0x000019be,0x00000063,0x000200f9,
29540x000019dc,0x000200f8,0x000019dc,0x000700f5,
29550x00000012,0x000019dd,0x000019d5,0x000018f1,
29560x000019db,0x000019d6,0x000400a8,0x00000012,
29570x000018f7,0x000019dd,0x000200f9,0x000018f8,
29580x000200f8,0x000018f8,0x000700f5,0x00000012,
29590x000018f9,0x000019b3,0x000019b2,0x000018f7,
29600x000019dc,0x000200f9,0x000018fa,0x000200f8,
29610x000018fa,0x000700f5,0x00000012,0x00001ee2,
29620x0000011e,0x000018e6,0x000018f9,0x000018f8,
29630x000400a8,0x00000012,0x000014c9,0x00001ee2,
29640x000200f9,0x000014ca,0x000200f8,0x000014ca,
29650x000700f5,0x00000012,0x000014cb,0x000014c1,
29660x000014ba,0x000014c9,0x000018fa,0x000300f7,
29670x000014cd,0x00000000,0x000400fa,0x000014cb,
29680x000014cc,0x000014cd,0x000200f8,0x000014cc,
29690x000200f9,0x000014ce,0x000200f8,0x000014cd,
29700x000200f9,0x000014ce,0x000200f8,0x000014ce,
29710x001100f5,0x00000027,0x00001f7e,0x00000498,
29720x000013b6,0x00001c14,0x000013c7,0x00001f7f,
29730x00001429,0x00000498,0x00001455,0x00001ede,
29740x000014b8,0x00001ca4,0x000014cc,0x00001ca4,
29750x000014cd,0x001100f5,0x00000006,0x00001ee9,
29760x00000058,0x000013b6,0x00000063,0x000013c7,
29770x00000063,0x00001429,0x00000063,0x00001455,
29780x00001eea,0x000014b8,0x00000063,0x000014cc,
29790x000000d8,0x000014cd,0x000500aa,0x00000012,
29800x000004d0,0x00001ee9,0x000000d8,0x000300f7,
29810x000004d2,0x00000000,0x000400fa,0x000004d0,
29820x000004d1,0x000004d2,0x000200f8,0x000004d1,
29830x00050041,0x00000182,0x000004d3,0x00000180,
29840x000004c2,0x0004003d,0x00000006,0x000004d4,
29850x000004d3,0x000500c4,0x00000006,0x000004d5,
29860x000004d4,0x000004c5,0x000500c4,0x00000006,
29870x000004d7,0x0000044f,0x00000063,0x000500c5,
29880x00000006,0x000004d8,0x000004d5,0x000004d7,
29890x000500c5,0x00000006,0x000004d9,0x000004d8,
29900x00000063,0x00050041,0x0000020a,0x000019e3,
29910x00000180,0x000003dd,0x0004003d,0x00000007,
29920x000019e4,0x000019e3,0x0004007c,0x000000b1,
29930x000019e5,0x000019e4,0x00060041,0x000000b7,
29940x000019e7,0x000019e5,0x000000b6,0x000000b6,
29950x000700ea,0x00000006,0x000019e8,0x000019e7,
29960x00000063,0x00000058,0x00000063,0x00060041,
29970x000000b7,0x000019eb,0x000019e5,0x000000b6,
29980x000003bc,0x0006003d,0x00000006,0x000019ec,
29990x000019eb,0x00000002,0x00000004,0x000500b0,
30000x00000012,0x000019ed,0x000019e8,0x000019ec,
30010x000300f7,0x000019f7,0x00000000,0x000400fa,
30020x000019ed,0x000019ee,0x000019f4,0x000200f8,
30030x000019f4,0x00060041,0x000000b7,0x000019f6,
30040x000019e5,0x000000b6,0x000003f3,0x0005003e,
30050x000019f6,0x00000063,0x00000002,0x00000004,
30060x000200f9,0x000019f7,0x000200f8,0x000019ee,
30070x00050080,0x00000006,0x000019f1,0x0000009e,
30080x000019e8,0x00060041,0x000000b7,0x000019f3,
30090x000019e5,0x000000b6,0x000019f1,0x0005003e,
30100x000019f3,0x000004d9,0x00000002,0x00000004,
30110x000200f9,0x000019f7,0x000200f8,0x000019f7,
30120x000200f9,0x000004d2,0x000200f8,0x000004d2,
30130x000200f9,0x000004ba,0x000200f8,0x000004ba,
30140x000700f5,0x00000027,0x00001fbe,0x00000498,
30150x000004a9,0x00001f7e,0x000004d2,0x000700f5,
30160x00000027,0x00001f8b,0x0000219c,0x000004a9,
30170x00001df6,0x000004d2,0x00050041,0x0000020a,
30180x000004dd,0x00000180,0x000003bc,0x0004003d,
30190x00000007,0x000004de,0x000004dd,0x0004007c,
30200x00000468,0x000004df,0x000004de,0x00060041,
30210x00000474,0x000004e4,0x000004df,0x000000b6,
30220x0000048f,0x0005003e,0x000004e4,0x00001f8b,
30230x00000002,0x00000010,0x00060041,0x00000474,
30240x000004ea,0x000004df,0x000000b6,0x00000496,
30250x0005003e,0x000004ea,0x00001fbe,0x00000002,
30260x00000010,0x000300f7,0x000004ed,0x00000000,
30270x000400fa,0x0000045b,0x000004ec,0x000004ed,
30280x000200f8,0x000004ec,0x00050041,0x0000020a,
30290x000004ef,0x00000180,0x00000451,0x0004003d,
30300x00000007,0x000004f0,0x000004ef,0x0004007c,
30310x00000468,0x000004f1,0x000004f0,0x000300f7,
30320x000004fd,0x00000000,0x000400fa,0x000004b8,
30330x000004fc,0x00000503,0x000200f8,0x00000503,
30340x000200f9,0x000004fd,0x000200f8,0x000004fc,
30350x000300f7,0x00001a40,0x00000000,0x000300fb,
30360x00000058,0x00001a01,0x000200f8,0x00001a01,
30370x000500ab,0x00000012,0x00001a05,0x000004b7,
30380x00000058,0x000400a8,0x00000012,0x00001a06,
30390x00001a05,0x000300f7,0x00001a0b,0x00000000,
30400x000400fa,0x00001a06,0x00001a07,0x00001a0b,
30410x000200f8,0x00001a07,0x00050051,0x00000006,
30420x00001a09,0x0000219c,0x00000002,0x000500aa,
30430x00000012,0x00001a0a,0x00001a09,0x00000058,
30440x000200f9,0x00001a0b,0x000200f8,0x00001a0b,
30450x000700f5,0x00000012,0x00001a0c,0x00001a05,
30460x00001a01,0x00001a0a,0x00001a07,0x000300f7,
30470x00001a0e,0x00000000,0x000400fa,0x00001a0c,
30480x00001a0d,0x00001a0e,0x000200f8,0x00001a0d,
30490x000200f9,0x00001a40,0x000200f8,0x00001a0e,
30500x00050051,0x00000006,0x00001a10,0x0000219c,
30510x00000001,0x000500c2,0x00000006,0x00001a11,
30520x00001a10,0x000000e4,0x000500c7,0x00000006,
30530x00001a12,0x00001a11,0x000001ad,0x00050051,
30540x00000006,0x00001a14,0x0000219c,0x00000002,
30550x000500aa,0x00000012,0x00001a16,0x00001a12,
30560x00000058,0x000600a9,0x00000006,0x00001a18,
30570x00001a16,0x00000063,0x00001a12,0x00050097,
30580x0000005e,0x00001a1b,0x00001a14,0x00001a18,
30590x00050051,0x00000006,0x00001a1c,0x00001a1b,
30600x00000000,0x00050051,0x00000006,0x00001a1d,
30610x00001a1b,0x00000001,0x00050051,0x00000006,
30620x00001a1f,0x00001f8b,0x00000002,0x000500aa,
30630x00000012,0x00001a20,0x00001a1f,0x00000058,
30640x000300f7,0x00001a29,0x00000000,0x000400fa,
30650x00001a20,0x00001a21,0x00001a22,0x000200f8,
30660x00001a22,0x00050051,0x00000006,0x00001a24,
30670x00001f8b,0x00000000,0x00050051,0x00000006,
30680x00001a26,0x00001f8b,0x00000001,0x000500c7,
30690x00000006,0x00001a27,0x00001a26,0x0000017b,
30700x00050050,0x00000007,0x00001a28,0x00001a24,
30710x00001a27,0x000200f9,0x00001a29,0x000200f8,
30720x00001a21,0x000200f9,0x00001a29,0x000200f8,
30730x00001a29,0x000700f5,0x00000007,0x00002069,
30740x000001c2,0x00001a21,0x00001a28,0x00001a22,
30750x00050051,0x00000006,0x00001a2c,0x0000219c,
30760x00000000,0x000500c7,0x00000006,0x00001a2f,
30770x00001a10,0x0000017b,0x00050051,0x00000006,
30780x00001a31,0x00002069,0x00000001,0x000500c4,
30790x00000006,0x00001a32,0x00001a31,0x000000e4,
30800x000500c5,0x00000006,0x00001a33,0x00001a2f,
30810x00001a32,0x00050051,0x00000006,0x00001a35,
30820x00002069,0x00000000,0x000500ab,0x00000012,
30830x00001a38,0x00001a1d,0x00000058,0x000600a9,
30840x00000006,0x000021a3,0x00001a38,0x000001dc,
30850x00001a1c,0x00070050,0x00000027,0x00001a3f,
30860x00001a2c,0x00001a33,0x00001a35,0x000021a3,
30870x000200f9,0x00001a40,0x000200f8,0x00001a40,
30880x000700f5,0x00000027,0x0000206b,0x000001a7,
30890x00001a0d,0x00001a3f,0x00001a29,0x000200f9,
30900x000004fd,0x000200f8,0x000004fd,0x000700f5,
30910x00000027,0x0000206c,0x0000206b,0x00001a40,
30920x000001a7,0x00000503,0x00060041,0x00000474,
30930x00000505,0x000004f1,0x000000b6,0x0000048f,
30940x0005003e,0x00000505,0x0000206c,0x00000002,
30950x00000010,0x000300f7,0x0000050d,0x00000000,
30960x000400fa,0x000004b8,0x0000050c,0x00000513,
30970x000200f8,0x00000513,0x000200f9,0x0000050d,
30980x000200f8,0x0000050c,0x000300f7,0x00001a8a,
30990x00000000,0x000300fb,0x00000058,0x00001a4b,
31000x000200f8,0x00001a4b,0x00050051,0x00000006,
31010x00001a4d,0x00000498,0x00000003,0x000500c2,
31020x00000006,0x00001a4e,0x00001a4d,0x0000019b,
31030x000500ab,0x00000012,0x00001a4f,0x00001a4e,
31040x00000058,0x000400a8,0x00000012,0x00001a50,
31050x00001a4f,0x000300f7,0x00001a55,0x00000000,
31060x000400fa,0x00001a50,0x00001a51,0x00001a55,
31070x000200f8,0x00001a51,0x00050051,0x00000006,
31080x00001a53,0x00000498,0x00000002,0x000500aa,
31090x00000012,0x00001a54,0x00001a53,0x00000058,
31100x000200f9,0x00001a55,0x000200f8,0x00001a55,
31110x000700f5,0x00000012,0x00001a56,0x00001a4f,
31120x00001a4b,0x00001a54,0x00001a51,0x000300f7,
31130x00001a58,0x00000000,0x000400fa,0x00001a56,
31140x00001a57,0x00001a58,0x000200f8,0x00001a57,
31150x000200f9,0x00001a8a,0x000200f8,0x00001a58,
31160x00050051,0x00000006,0x00001a5a,0x00000498,
31170x00000001,0x000500c2,0x00000006,0x00001a5b,
31180x00001a5a,0x000000e4,0x000500c7,0x00000006,
31190x00001a5c,0x00001a5b,0x000001ad,0x00050051,
31200x00000006,0x00001a5e,0x00000498,0x00000002,
31210x000500aa,0x00000012,0x00001a60,0x00001a5c,
31220x00000058,0x000600a9,0x00000006,0x00001a62,
31230x00001a60,0x00000063,0x00001a5c,0x00050097,
31240x0000005e,0x00001a65,0x00001a5e,0x00001a62,
31250x00050051,0x00000006,0x00001a66,0x00001a65,
31260x00000000,0x00050051,0x00000006,0x00001a67,
31270x00001a65,0x00000001,0x00050051,0x00000006,
31280x00001a69,0x00001fbe,0x00000002,0x000500aa,
31290x00000012,0x00001a6a,0x00001a69,0x00000058,
31300x000300f7,0x00001a73,0x00000000,0x000400fa,
31310x00001a6a,0x00001a6b,0x00001a6c,0x000200f8,
31320x00001a6c,0x00050051,0x00000006,0x00001a6e,
31330x00001fbe,0x00000000,0x00050051,0x00000006,
31340x00001a70,0x00001fbe,0x00000001,0x000500c7,
31350x00000006,0x00001a71,0x00001a70,0x0000017b,
31360x00050050,0x00000007,0x00001a72,0x00001a6e,
31370x00001a71,0x000200f9,0x00001a73,0x000200f8,
31380x00001a6b,0x000200f9,0x00001a73,0x000200f8,
31390x00001a73,0x000700f5,0x00000007,0x0000211f,
31400x000001c2,0x00001a6b,0x00001a72,0x00001a6c,
31410x00050051,0x00000006,0x00001a76,0x00000498,
31420x00000000,0x000500c7,0x00000006,0x00001a79,
31430x00001a5a,0x0000017b,0x00050051,0x00000006,
31440x00001a7b,0x0000211f,0x00000001,0x000500c4,
31450x00000006,0x00001a7c,0x00001a7b,0x000000e4,
31460x000500c5,0x00000006,0x00001a7d,0x00001a79,
31470x00001a7c,0x00050051,0x00000006,0x00001a7f,
31480x0000211f,0x00000000,0x000500ab,0x00000012,
31490x00001a82,0x00001a67,0x00000058,0x000600a9,
31500x00000006,0x000021a4,0x00001a82,0x000001dc,
31510x00001a66,0x00070050,0x00000027,0x00001a89,
31520x00001a76,0x00001a7d,0x00001a7f,0x000021a4,
31530x000200f9,0x00001a8a,0x000200f8,0x00001a8a,
31540x000700f5,0x00000027,0x00002121,0x000001a7,
31550x00001a57,0x00001a89,0x00001a73,0x000200f9,
31560x0000050d,0x000200f8,0x0000050d,0x000700f5,
31570x00000027,0x00002122,0x00002121,0x00001a8a,
31580x000001a7,0x00000513,0x00060041,0x00000474,
31590x00000515,0x000004f1,0x000000b6,0x00000496,
31600x0005003e,0x00000515,0x00002122,0x00000002,
31610x00000010,0x000200f9,0x000004ed,0x000200f8,
31620x000004ed,0x000200f9,0x00000518,0x000200f8,
31630x00000518,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 000000000..026f1c794
--- /dev/null
+++ b/runtime/src/console_heap_fix_spv.h
@@ -0,0 +1,11 @@
1#pragma once
2#include <cstdint>
3
4namespace leonida {
5
6// console_heap_fix.comp compiled with: glslc --target-env=vulkan1.2 -O -mfmt=c console_heap_fix.comp -o console_heap_fix.inc
7inline constexpr std::uint32_t console_heap_fix_spirv[] =
8#include "console_heap_fix.inc"
9;
10
11} // namespace leonida
diff --git a/runtime/src/console_heap_gpu.h b/runtime/src/console_heap_gpu.h
new file mode 100644
index 000000000..b3a4c0ba4
--- /dev/null
+++ b/runtime/src/console_heap_gpu.h
@@ -0,0 +1,1058 @@
1// Console descriptor heap translation on the GPU (LEONIDA_CONSOLE_HEAP_GPU=1): the buffer V#s the title writes into
2// its console descriptor heaps are rebased by a compute pass (console_heap_fix.comp) at the start of the submission
3// that reads them, instead of one by one on the submitting thread (DeviceState::fix_console_slot).
4//
5// What stays on the CPU (shims/d3d12_vulkan_device.cpp): finding the changed slots (the heap's ShadowPages and a
6// compare against the bytes each slot was last made from), registering the T#s (they are copied as they are; shaders
7// find them by their words), and every lookup that can make something: a V# the pass cannot answer is written with no
8// records and recorded in the pass's miss list; once the submission is done the CPU resolves its words with
9// vsharp_address (which may make a geometry copy), enters the answer in the key table, and queues the slot again.
10//
11// The pass answers a V# half from four tables, in vsharp_address's order:
12// - the range table: the title-VA ranges of the alias table (src/title_va_alias.h), sorted, each with the shader VA
13// of its copy and whether the CPU found that copy backed. Rebuilt when the alias table or the backings change;
14// - the backed table: the shader-VA spans of the live GPU allocations (DeviceState's gpu_backings, merged) and of
15// the geometry copies' blocks. A base already inside one (a V# our API wrote, or the title copied) is left as it
16// is, as vsharp_address's backed() leaves it. Merged neighbours make it a superset of what backed() accepts, but
17// never of memory that is not there;
18// - the key table: the exact 16 bytes of a V# half and what vsharp_address answered for them (a shader VA, or no
19// backing), open addressed with up to kProbes slots per key (FNV-1a and fmix32). The CPU keeps the
20// mirror below; its changes reach the GPU as updates the pass applies first, so the table changes in GPU order;
21// - the ask table: the title's memory and its GPU windows. A base outside them that nothing above answered gets no
22// records (vsharp_address could only answer 0); one inside them is a miss, for the CPU.
23// When a backing or an alias range goes, every key entry whose answer falls in its shader VAs is dropped and every V#
24// slot of the heap is translated again.
25//
26// ConsoleHeapKeys and console_heap_translate_slot are the CPU reference of the pass (vk_console_heap_gpu_test checks
27// the GPU against them); ConsoleHeapGpu records the pass.
28#pragma once
29#ifndef VK_NO_PROTOTYPES
30#define VK_NO_PROTOTYPES
31#endif
32#include <vulkan/vulkan.h>
33
34#include <algorithm>
35#include <array>
36#include <cstdint>
37#include <cstring>
38#include <map>
39#include <memory>
40#include <mutex>
41#include <utility>
42#include <vector>
43
44#include "console_heap_fix_spv.h"
45#include "vulkan_aftermath.h"
46#include "vulkan_memory.h"
47
48namespace leonida {
49
50struct ConsoleHeapRange {
51 std::uint64_t title_va = 0, end = 0, shader_va = 0;
52 bool checked = false; // the whole [shader_va, shader_va + end - title_va) is backed
53};
54
55// Sorted, disjoint [start, end) spans: the backed and ask tables.
56using ConsoleHeapSpans = std::vector<std::pair<std::uint64_t, std::uint64_t>>;
57
58// Sorts and merges spans (overlapping or touching ones become one); empty and wrapping ones are dropped.
59inline void merge_console_heap_spans(ConsoleHeapSpans& spans) {
60 std::erase_if(spans, [](const auto& s) { return s.second <= s.first; });
61 std::sort(spans.begin(), spans.end());
62 std::size_t out = 0;
63 for (std::size_t i = 0; i < spans.size(); ++i) {
64 if (out && spans[i].first <= spans[out - 1].second) spans[out - 1].second = std::max(spans[out - 1].second, spans[i].second);
65 else spans[out++] = spans[i];
66 }
67 spans.resize(out);
68}
69
70// [v, v + bytes) inside one span (bytes 0 counts as 1).
71inline bool console_heap_spans_hold(const ConsoleHeapSpans& spans, std::uint64_t v, std::uint64_t bytes) {
72 auto it = std::upper_bound(spans.begin(), spans.end(), v,
73 [](std::uint64_t x, const auto& s) { return x < s.first; });
74 if (it == spans.begin()) return false;
75 --it;
76 const std::uint64_t n = std::max<std::uint64_t>(bytes, 1);
77 return v < it->second && n <= it->second - v;
78}
79
80// What the reference (and the pass) answers from, besides the key table.
81struct ConsoleHeapTables {
82 std::vector<ConsoleHeapRange> ranges;
83 ConsoleHeapSpans backed;
84 ConsoleHeapSpans ask;
85 bool use_ask = false; // without it every unanswered half is a miss
86 bool signed_offsets = false; // LEONIDA_IMPORT_BELOW_ARENA: a base with bit 47 set is a negative offset
87};
88
89// 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
90// the flags in bits 16-31 of the sixth, two pad dwords.
91class ConsoleHeapKeys {
92public:
93 using Key = std::array<std::uint32_t, 4>;
94 static constexpr std::uint32_t kProbes = 16;
95 static constexpr std::uint32_t kUsed = 1, kNone = 2;
96 static constexpr std::uint32_t kEntryWords = 8, kUpdateWords = 12;
97
98 explicit ConsoleHeapKeys(std::uint32_t log2_entries = 20)
99 : mask_((1u << std::min<std::uint32_t>(log2_entries, 26)) - 1), entries_(std::size_t(mask_) + 1),
100 dirty_flag_(std::size_t(mask_) + 1, 0) {}
101
102 // FNV-1a over the four dwords, then MurmurHash3's fmix32 (console_heap_fix.comp key_hash): the finalizer makes
103 // the low bits, which index the table, depend on every bit of the key. Bare FNV-1a put every V# whose base
104 // differed only above bit 20 into one probe chain, and the 17th of them found no slot.
105 static std::uint32_t hash(const Key& k) {
106 std::uint32_t h = 2166136261u;
107 for (const std::uint32_t w : k) h = (h ^ w) * 16777619u;
108 h ^= h >> 16;
109 h *= 0x85EBCA6Bu;
110 h ^= h >> 13;
111 h *= 0xC2B2AE35u;
112 h ^= h >> 16;
113 return h;
114 }
115
116 std::uint32_t mask() const { return mask_; }
117 std::size_t size() const { return used_; }
118 std::size_t capacity() const { return entries_.size(); }
119
120 // The entry's index, or -1.
121 std::int64_t find(const Key& k) const {
122 const std::uint32_t h = hash(k);
123 for (std::uint32_t p = 0; p < kProbes; ++p) {
124 const std::uint32_t at = (h + p) & mask_;
125 if (entries_[at].flags & kUsed && entries_[at].key == k) return at;
126 }
127 return -1;
128 }
129 // True with the answer when the key is entered: `none` for no backing.
130 bool lookup(const Key& k, std::uint64_t& to, bool& none) const {
131 const std::int64_t at = find(k);
132 if (at < 0) return false;
133 to = entries_[std::size_t(at)].to;
134 none = entries_[std::size_t(at)].flags & kNone;
135 return true;
136 }
137
138 // Enters (or replaces) the answer for `k`: the shader VA `to` reaching `span` bytes, or no backing. False when all
139 // of the key's probe slots hold other keys.
140 bool put(const Key& k, std::uint64_t to, std::uint64_t span, bool none) {
141 std::int64_t at = find(k);
142 if (at < 0) {
143 const std::uint32_t h = hash(k);
144 for (std::uint32_t p = 0; p < kProbes && at < 0; ++p)
145 if (!(entries_[(h + p) & mask_].flags & kUsed)) at = (h + p) & mask_;
146 if (at < 0) return false;
147 ++used_;
148 } else {
149 unindex(std::uint32_t(at));
150 }
151 Entry& e = entries_[std::size_t(at)];
152 e.key = k;
153 e.to = to;
154 e.span = span;
155 e.flags = kUsed | (none ? kNone : 0);
156 if (!none) {
157 by_to_.emplace(to, std::uint32_t(at));
158 longest_ = std::max(longest_, span);
159 }
160 touch(std::uint32_t(at));
161 return true;
162 }
163
164 bool erase(const Key& k) {
165 const std::int64_t at = find(k);
166 if (at < 0) return false;
167 erase_at(std::uint32_t(at));
168 return true;
169 }
170
171 // Every answer reaching into [start, end) of the shader VAs: dropped. Returns how many.
172 std::size_t erase_overlapping(std::uint64_t start, std::uint64_t end) {
173 if (end <= start || by_to_.empty()) return 0;
174 const std::uint64_t from = start > longest_ ? start - longest_ : 0;
175 std::vector<std::uint32_t> gone;
176 for (auto it = by_to_.lower_bound(from); it != by_to_.end() && it->first < end; ++it) {
177 const Entry& e = entries_[it->second];
178 if (e.to + std::max<std::uint64_t>(e.span, 1) > start) gone.push_back(it->second);
179 }
180 for (const std::uint32_t at : gone) erase_at(at);
181 return gone.size();
182 }
183
184 // Every "no backing" answer, for a caller that asks again after something changed: their keys.
185 void take_none(std::vector<Key>& out, std::size_t at_most) {
186 out.clear();
187 for (std::uint32_t at = 0; at < entries_.size() && out.size() < at_most; ++at) {
188 if ((entries_[at].flags & (kUsed | kNone)) != (kUsed | kNone)) continue;
189 out.push_back(entries_[at].key);
190 erase_at(at);
191 }
192 }
193
194 void clear() {
195 for (std::uint32_t at = 0; at < entries_.size(); ++at)
196 if (entries_[at].flags & kUsed) erase_at(at);
197 by_to_.clear();
198 longest_ = 0;
199 }
200 // Everything gone with no updates: for a GPU table that is cleared as a whole (ConsoleHeapGpu::reset_keys).
201 void clear_silent() {
202 std::fill(entries_.begin(), entries_.end(), Entry{});
203 for (const std::uint32_t at : dirty_) dirty_flag_[at] = 0;
204 dirty_.clear();
205 by_to_.clear();
206 used_ = 0;
207 longest_ = 0;
208 }
209
210 void gpu_words(std::uint32_t at, std::uint32_t out[kEntryWords]) const {
211 const Entry& e = entries_[at];
212 std::memset(out, 0, kEntryWords * 4);
213 if (!(e.flags & kUsed)) return;
214 for (int i = 0; i < 4; ++i) out[i] = e.key[i];
215 out[4] = std::uint32_t(e.to);
216 out[5] = std::uint32_t((e.to >> 32) & 0xffffu) | (std::uint32_t(e.flags) << 16);
217 }
218
219 // The entries changed since the last take, as update records (index, 3 pad dwords, the entry's 8 dwords).
220 void take_updates(std::vector<std::uint32_t>& out) {
221 out.clear();
222 out.reserve(dirty_.size() * kUpdateWords);
223 for (const std::uint32_t at : dirty_) {
224 dirty_flag_[at] = 0;
225 const std::size_t base = out.size();
226 out.resize(base + kUpdateWords, 0);
227 out[base] = at;
228 gpu_words(at, out.data() + base + 4);
229 }
230 dirty_.clear();
231 }
232 bool has_updates() const { return !dirty_.empty(); }
233 // Every entry again (a new GPU table, or updates that never reached the GPU).
234 void touch_all() {
235 for (std::uint32_t at = 0; at < entries_.size(); ++at)
236 if (entries_[at].flags & kUsed) touch(at);
237 }
238 void touch(std::uint32_t at) {
239 if (!dirty_flag_[at]) {
240 dirty_flag_[at] = 1;
241 dirty_.push_back(at);
242 }
243 }
244
245private:
246 struct Entry {
247 Key key{};
248 std::uint64_t to = 0;
249 std::uint64_t span = 0;
250 std::uint32_t flags = 0;
251 };
252 void unindex(std::uint32_t at) {
253 const Entry& e = entries_[at];
254 if (!(e.flags & kUsed) || (e.flags & kNone)) return;
255 auto [lo, hi] = by_to_.equal_range(e.to);
256 for (auto it = lo; it != hi; ++it)
257 if (it->second == at) {
258 by_to_.erase(it);
259 break;
260 }
261 }
262 void erase_at(std::uint32_t at) {
263 if (!(entries_[at].flags & kUsed)) return;
264 unindex(at);
265 entries_[at] = Entry{};
266 --used_;
267 touch(at);
268 }
269
270 std::uint32_t mask_;
271 std::vector<Entry> entries_;
272 std::size_t used_ = 0;
273 std::multimap<std::uint64_t, std::uint32_t> by_to_; // positive answers by shader VA
274 std::uint64_t longest_ = 0;
275 std::vector<std::uint32_t> dirty_;
276 std::vector<std::uint8_t> dirty_flag_;
277};
278
279// What the pass does to one V# half (console_heap_fix.comp translate()): 0 left as it is, 1 answered by a table
280// (rebased, written with no records, or left as it is), 2 missed (written with no records).
281inline unsigned console_heap_translate_half(std::uint32_t k[4], const ConsoleHeapTables& t,
282 const ConsoleHeapKeys& keys) {
283 if ((k[3] >> 30) || !k[2]) return 0;
284 const auto no_records = [k] { k[0] = k[1] = k[2] = 0; };
285 const auto rebase = [k](std::uint64_t to) {
286 k[0] = std::uint32_t(to);
287 k[1] = (k[1] & 0xffff0000u) | std::uint32_t((to >> 32) & 0xffffu);
288 };
289 const std::uint64_t base = std::uint64_t(k[0]) | (std::uint64_t(k[1] & 0xffffu) << 32);
290 if (!base) return no_records(), 1;
291 const std::uint32_t stride = (k[1] >> 16) & 0x3fffu;
292 const std::uint64_t span = std::uint64_t(k[2]) * (stride ? stride : 1);
293 auto it = std::upper_bound(t.ranges.begin(), t.ranges.end(), base,
294 [](std::uint64_t va, const ConsoleHeapRange& r) { return va < r.title_va; });
295 if (it != t.ranges.begin()) {
296 const ConsoleHeapRange& r = *std::prev(it);
297 if (base < r.end && r.checked) {
298 if (r.end - base < span) no_records();
299 else rebase(r.shader_va + (base - r.title_va));
300 return 1;
301 }
302 }
303 std::uint64_t offset = base;
304 if (t.signed_offsets && (base & (1ull << 47))) offset |= ~((1ull << 48) - 1);
305 if (console_heap_spans_hold(t.backed, offset, span)) return 1;
306 const ConsoleHeapKeys::Key key{k[0], k[1], k[2], k[3]};
307 std::uint64_t to = 0;
308 bool none = false;
309 if (keys.lookup(key, to, none)) {
310 if (none) no_records();
311 else rebase(to);
312 return 1;
313 }
314 no_records();
315 if (t.use_ask && !console_heap_spans_hold(t.ask, base, 1)) return 1;
316 return 2;
317}
318
319// One 32-byte slot as the pass writes it; the bit of each half that missed (1: dwords 0-3, 2: dwords 4-7).
320// `zero_first`: the work item's bit 31 (ConsoleHeapGpu::kZeroFirst).
321inline unsigned console_heap_translate_slot(std::uint32_t w[8], const ConsoleHeapTables& t,
322 const ConsoleHeapKeys& keys, bool zero_first = false) {
323 if (w[3] >> 30) {
324 if (zero_first) w[0] = w[1] = w[2] = w[3] = 0;
325 else return 0;
326 }
327 unsigned missed = 0;
328 if (console_heap_translate_half(w, t, keys) == 2) missed |= 1;
329 if (console_heap_translate_half(w + 4, t, keys) == 2) missed |= 2;
330 return missed;
331}
332
333// The pass itself: the key table on the GPU, the range table's versions, the slots to translate per heap, and the
334// passes in flight with their miss lists. Every method takes the object's own lock (a leaf: it takes no other).
335class ConsoleHeapGpu {
336public:
337 static constexpr unsigned kMaxHeaps = 8;
338 // 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
339 // dwords 0-3 as zeros. The last queue() of a slot before a pass decides it.
340 static constexpr std::uint32_t kZeroFirst = 0x80000000u;
341 static constexpr std::uint32_t kMissCapacity = 1u << 16;
342 static constexpr std::uint32_t kMissHeader = 4;
343
344 struct Stats {
345 std::uint64_t passes = 0, slots = 0, updates = 0, misses = 0, overflows = 0, tables = 0, resets = 0;
346 std::uint64_t rescanned = 0; // slots of rescan() dispatches
347 std::uint64_t filtered = 0; // slots of rescan_filtered() dispatches
348 std::uint64_t copies = 0, copy_bytes = 0; // queue_copy()
349 std::uint64_t failed = 0; // passes whose submission did not reach the queue (their work went back)
350 };
351 enum TableKind : unsigned { range_table, backed_table, ask_table, change_shader_table, change_title_table, table_count };
352
353 ConsoleHeapGpu(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory,
354 std::uint32_t log2_keys = 20)
355 : get_(get), device_(device), memory_(memory), keys_(log2_keys) {}
356 ~ConsoleHeapGpu() {
357 std::lock_guard lock(mutex_);
358 for (auto& pass : in_flight_) free_buffer(pass.buffer);
359 for (Heap& h : heaps_) free_buffer(h.meta);
360 for (auto& b : retired_) free_buffer(b);
361 for (auto& buffer : pool_) free_buffer(buffer);
362 for (Table& t : tables_) {
363 for (auto& [version, buffer] : t.old) free_buffer(buffer);
364 for (auto& buffer : t.pool) free_buffer(buffer);
365 if (t.current) free_buffer(*t.current);
366 }
367 free_buffer(key_table_);
368 if (pipeline_) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline_, nullptr);
369 if (layout_) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout_, nullptr);
370 }
371 ConsoleHeapGpu(const ConsoleHeapGpu&) = delete;
372 ConsoleHeapGpu& operator=(const ConsoleHeapGpu&) = delete;
373
374 // The pipeline and the GPU key table (device-local, zeroed by the first pass). False: the pass cannot run.
375 bool init() {
376 std::lock_guard lock(mutex_);
377 if (pipeline_) return true;
378 if (!make_pipeline()) return false;
379 const VkDeviceSize bytes = VkDeviceSize(keys_.capacity()) * ConsoleHeapKeys::kEntryWords * 4;
380 if (!make_buffer(bytes, false, key_table_)) return false;
381 clear_keys_ = true;
382 return true;
383 }
384
385 // A heap the pass writes: its title bytes (`input`) and the copy shaders read (`copy`), `slots` 32-byte slots.
386 // -1 when there is no room.
387 // Each heap also gets device-local metadata, 32 bytes a slot (what the pass last made of each V# half), which
388 // lets a filtered rescan pass over the slots no change touches without reading their words (rescan_filtered).
389 int add_heap(VkDeviceAddress input, VkDeviceAddress copy, std::uint32_t slots) {
390 std::lock_guard lock(mutex_);
391 for (unsigned i = 0; i < kMaxHeaps; ++i) {
392 if (heaps_[i].slots) continue;
393 Heap& h = heaps_[i];
394 h = Heap{};
395 h.input = input;
396 h.copy = copy;
397 h.slots = slots;
398 h.queued.assign(slots, 0);
399 if (make_buffer(VkDeviceSize(slots) * 32, false, h.meta)) h.meta_clear = true;
400 return int(i);
401 }
402 return -1;
403 }
404 void remove_heap(int heap) {
405 std::lock_guard lock(mutex_);
406 if (heap < 0 || unsigned(heap) >= kMaxHeaps) return;
407 if (heaps_[heap].meta.buffer) retired_.push_back(heaps_[heap].meta); // a pass in flight may still write it
408 heaps_[heap] = Heap{};
409 }
410
411 void queue(int heap, std::uint32_t slot) {
412 std::lock_guard lock(mutex_);
413 queue_locked(heap, slot);
414 }
415 // A buffer copy for the start of the next pass, before the heap translation (LEONIDA_SHADOW_GPU: a slot-133 shadow's
416 // pages copied from an import of the title's pages). `keep` (the source import) lives until that pass retires.
417 void queue_copy(VkBuffer src, VkDeviceSize src_offset, VkBuffer dst, VkDeviceSize dst_offset, VkDeviceSize bytes,
418 std::shared_ptr<void> keep) {
419 std::lock_guard lock(mutex_);
420 copies_.push_back({src, dst, {src_offset, dst_offset, bytes}});
421 if (keep) keeps_.push_back(std::move(keep));
422 }
423
424 // Queued copies into `dst` dropped (its buffer is about to go); copies already recorded stay with their pass.
425 void drop_copies_to(VkBuffer dst) {
426 std::lock_guard lock(mutex_);
427 std::erase_if(copies_, [dst](const Copy& c) { return c.dst == dst; });
428 }
429
430 // Every buffer pair of slots [0, slots) translated again by the next pass: one dispatch over the range, no list
431 // (the pass reads each slot's words and leaves the slots that hold no pair as they are).
432 void rescan(int heap, std::uint32_t slots) {
433 std::lock_guard lock(mutex_);
434 if (heap < 0 || unsigned(heap) >= kMaxHeaps) return;
435 heaps_[heap].rescan = std::max(heaps_[heap].rescan, std::min(slots, heaps_[heap].slots));
436 }
437 // Like rescan(), but only the slots whose metadata meets a change span: `shader` spans of shader VAs (backings and
438 // alias copies that went: a half whose title base or result reaches into one) and `title` spans of title VAs
439 // (alias ranges that went, words answered since: a half whose title base is in one). Without metadata, every
440 // slot of the range, as rescan().
441 void rescan_filtered(int heap, std::uint32_t slots, const ConsoleHeapSpans& shader, const ConsoleHeapSpans& title) {
442 std::lock_guard lock(mutex_);
443 if (heap < 0 || unsigned(heap) >= kMaxHeaps) return;
444 heaps_[heap].rescan_filtered = std::max(heaps_[heap].rescan_filtered, std::min(slots, heaps_[heap].slots));
445 change_shader_.insert(change_shader_.end(), shader.begin(), shader.end());
446 change_title_.insert(change_title_.end(), title.begin(), title.end());
447 }
448 template <class It>
449 void queue(int heap, It first, It last) {
450 std::lock_guard lock(mutex_);
451 for (; first != last; ++first) queue_locked(heap, *first);
452 }
453
454 // A new range table for the next pass (sorted by title VA, not overlapping).
455 void set_ranges(const std::vector<ConsoleHeapRange>& ranges) {
456 std::lock_guard lock(mutex_);
457 Table& t = tables_[range_table];
458 t.words.clear();
459 for (const ConsoleHeapRange& r : ranges)
460 t.words.insert(t.words.end(), {std::uint32_t(r.title_va), std::uint32_t(r.title_va >> 32),
461 std::uint32_t(r.end), std::uint32_t(r.end >> 32),
462 std::uint32_t(r.shader_va), std::uint32_t(r.shader_va >> 32),
463 r.checked ? 1u : 0u, 0u});
464 t.count = std::uint32_t(ranges.size());
465 t.dirty = true;
466 }
467 // New backed or ask spans (merged) for the next pass.
468 void set_spans(TableKind kind, const ConsoleHeapSpans& spans) {
469 std::lock_guard lock(mutex_);
470 spans_locked(kind, spans);
471 }
472 void spans_locked(TableKind kind, const ConsoleHeapSpans& spans) {
473 Table& t = tables_[kind];
474 t.words.clear();
475 for (const auto& [start, end] : spans)
476 t.words.insert(t.words.end(), {std::uint32_t(start), std::uint32_t(start >> 32), std::uint32_t(end),
477 std::uint32_t(end >> 32)});
478 t.count = std::uint32_t(spans.size());
479 t.dirty = true;
480 if (kind == ask_table) use_ask_ = true;
481 }
482 void set_signed_offsets(bool on) {
483 std::lock_guard lock(mutex_);
484 signed_offsets_ = on;
485 }
486 // Every key entry gone at once (the GPU table is cleared by the next pass), for a table filling up.
487 void reset_keys() {
488 std::lock_guard lock(mutex_);
489 keys_.clear_silent();
490 clear_keys_ = true;
491 ++stats_.resets;
492 }
493
494 template <class F>
495 auto with_keys(F&& f) {
496 std::lock_guard lock(mutex_);
497 return f(keys_);
498 }
499
500 bool pending() {
501 std::lock_guard lock(mutex_);
502 return pending_locked();
503 }
504
505 // Records the pass into `cb`, ahead of the submission's lists: the key table updates, then each heap's queued
506 // slots, between barriers that order it after earlier work on the queue and before everything after it (and the
507 // host's read of the miss list). True when something was recorded; commit() must follow the submit.
508 bool record(VkCommandBuffer cb) {
509 std::lock_guard lock(mutex_);
510 if (!pipeline_ || !pending_locked() || in_flight_.size() >= 64) return false;
511 if (clear_keys_) keys_.touch_all();
512 std::vector<std::uint32_t> updates;
513 keys_.take_updates(updates);
514 const std::uint32_t update_count = std::uint32_t(updates.size() / ConsoleHeapKeys::kUpdateWords);
515 std::size_t work = 0;
516 for (const Heap& h : heaps_) work += h.work.size();
517 const VkDeviceSize bytes = VkDeviceSize(kMissHeader + kMissCapacity) * 4 + VkDeviceSize(work) * 4 +
518 VkDeviceSize(updates.size()) * 4 + 64;
519 Pass pass{};
520 if (!acquire_buffer(bytes, pass.buffer)) {
521 for (std::size_t i = 0; i < updates.size(); i += ConsoleHeapKeys::kUpdateWords) keys_.touch(updates[i]);
522 return false;
523 }
524 // A filtered rescan's change spans, merged, as this pass's change tables.
525 bool filtered = false;
526 for (const Heap& h : heaps_) filtered |= h.rescan_filtered && !h.rescan;
527 ConsoleHeapSpans change_shader, change_title;
528 if (filtered) {
529 change_shader = change_shader_;
530 change_title = change_title_;
531 merge_console_heap_spans(change_shader);
532 merge_console_heap_spans(change_title);
533 spans_locked(change_shader_table, change_shader);
534 spans_locked(change_title_table, change_title);
535 }
536 for (unsigned kind = 0; kind < table_count; ++kind) {
537 if (tables_[kind].dirty && !publish(tables_[kind], kind == range_table ? 32 : 16)) {
538 pool_.push_back(pass.buffer);
539 for (std::size_t i = 0; i < updates.size(); i += ConsoleHeapKeys::kUpdateWords) keys_.touch(updates[i]);
540 return false;
541 }
542 pass.versions[kind] = tables_[kind].version;
543 }
544 auto* words = static_cast<std::uint32_t*>(pass.buffer.mapped);
545 words[0] = 0;
546 words[1] = kMissCapacity;
547 words[2] = 0;
548 words[3] = 0;
549 std::size_t at = kMissHeader + kMissCapacity;
550 const VkDeviceAddress base = pass.buffer.address;
551 const VkDeviceAddress update_address = base + at * 4;
552 if (!updates.empty()) std::memcpy(words + at, updates.data(), updates.size() * 4);
553 at += updates.size();
554 const auto barrier = fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
555 const auto dispatch = fn<PFN_vkCmdDispatch>("vkCmdDispatch");
556 const auto push = fn<PFN_vkCmdPushConstants>("vkCmdPushConstants");
557 // The copies first (another kind of work in the same prelude), then what reads their destinations may run.
558 if (!copies_.empty()) {
559 std::sort(copies_.begin(), copies_.end(), [](const Copy& a, const Copy& b) {
560 return a.src != b.src ? a.src < b.src : a.dst < b.dst;
561 });
562 std::vector<VkBufferCopy> regions;
563 const auto copy = fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer");
564 for (std::size_t i = 0; i < copies_.size();) {
565 std::size_t j = i;
566 regions.clear();
567 while (j < copies_.size() && copies_[j].src == copies_[i].src && copies_[j].dst == copies_[i].dst) {
568 regions.push_back(copies_[j].region);
569 stats_.copy_bytes += copies_[j].region.size;
570 ++j;
571 }
572 copy(cb, copies_[i].src, copies_[i].dst, std::uint32_t(regions.size()), regions.data());
573 stats_.copies += regions.size();
574 i = j;
575 }
576 VkMemoryBarrier copied{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
577 copied.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
578 copied.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
579 barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &copied, 0, nullptr, 0,
580 nullptr);
581 pass.copies = std::move(copies_);
582 pass.keeps = std::move(keeps_);
583 copies_.clear();
584 keeps_.clear();
585 }
586 // No barrier against the queue's earlier work: one from ALL_COMMANDS made every submission wait for the one
587 // before it to finish.
588 // The pass may then rewrite a slot an earlier submission still reads, as the CPU path's memcpy into the copy
589 // always could.
590 fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_);
591 Push p{};
592 const auto address = [&](TableKind kind) { return tables_[kind].current ? tables_[kind].current->address : 0; };
593 p.ranges = address(range_table);
594 p.backed = address(backed_table);
595 p.ask = address(ask_table);
596 p.keys = key_table_.address;
597 p.misses = base;
598 p.range_count = tables_[range_table].current ? tables_[range_table].count : 0;
599 p.backed_count = tables_[backed_table].current ? tables_[backed_table].count : 0;
600 p.ask_count = tables_[ask_table].current ? tables_[ask_table].count : 0;
601 p.flags = (signed_offsets_ ? 1u : 0u) | (use_ask_ ? 2u : 0u);
602 p.key_mask = keys_.mask();
603 if (clear_keys_) {
604 fn<PFN_vkCmdFillBuffer>("vkCmdFillBuffer")(cb, key_table_.buffer, 0, VK_WHOLE_SIZE, 0);
605 VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
606 filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
607 filled.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
608 barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &filled, 0,
609 nullptr, 0, nullptr);
610 }
611 // New heaps' metadata starts at zero (no half known).
612 bool meta_filled = false;
613 for (Heap& h : heaps_)
614 if (h.meta_clear && h.meta.buffer) {
615 fn<PFN_vkCmdFillBuffer>("vkCmdFillBuffer")(cb, h.meta.buffer, 0, VK_WHOLE_SIZE, 0);
616 h.meta_clear = false;
617 meta_filled = true;
618 pass.filled.push_back(int(&h - heaps_.data()));
619 }
620 if (meta_filled) {
621 VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
622 filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
623 filled.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
624 barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &filled, 0,
625 nullptr, 0, nullptr);
626 }
627 if (update_count) {
628 p.work = update_address; // MODE_UPDATE's records
629 p.count = update_count;
630 p.mode = 1;
631 push(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(p), &p);
632 dispatch(cb, (update_count + 63) / 64, 1, 1);
633 VkMemoryBarrier written{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
634 written.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
635 written.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
636 barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &written, 0,
637 nullptr, 0, nullptr);
638 }
639 p.mode = 0;
640 p.cshader = filtered ? address(change_shader_table) : 0;
641 p.ctitle = filtered ? address(change_title_table) : 0;
642 p.cshader_count = filtered && tables_[change_shader_table].current ? tables_[change_shader_table].count : 0;
643 p.ctitle_count = filtered && tables_[change_title_table].current ? tables_[change_title_table].count : 0;
644 for (unsigned i = 0; i < kMaxHeaps; ++i) {
645 Heap& h = heaps_[i];
646 const bool full = h.rescan != 0;
647 const std::uint32_t slots = full ? std::max(h.rescan, h.rescan_filtered) : h.rescan_filtered;
648 if (!slots) continue;
649 // Before the listed slots, so a slot both rewritten and rescanned ends with its listed (newer) form.
650 p.input_slots = h.input;
651 p.copy_slots = h.copy;
652 p.meta = h.meta.address;
653 p.heap = i;
654 const std::uint32_t flags = p.flags;
655 p.flags |= 4u; // FLAG_RANGE
656 if (!full) p.flags |= 8u; // FLAG_FILTER
657 for (std::uint32_t first = 0; first < slots; first += 65535u * 64u) {
658 const std::uint32_t n = std::min<std::uint32_t>(slots - first, 65535u * 64u);
659 p.work = first;
660 p.count = n;
661 push(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(p), &p);
662 dispatch(cb, (n + 63) / 64, 1, 1);
663 (full ? stats_.rescanned : stats_.filtered) += n;
664 }
665 p.flags = flags;
666 pass.rescans.push_back({int(i), slots, !full});
667 h.rescan = h.rescan_filtered = 0;
668 }
669 if (filtered) {
670 pass.change_shader = std::move(change_shader);
671 pass.change_title = std::move(change_title);
672 }
673 change_shader_.clear();
674 change_title_.clear();
675 if (!pass.rescans.empty()) { // the listed slots' writes land after the rescan's
676 VkMemoryBarrier rescanned{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
677 rescanned.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
678 rescanned.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
679 barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &rescanned,
680 0, nullptr, 0, nullptr);
681 }
682 for (unsigned i = 0; i < kMaxHeaps; ++i) {
683 Heap& h = heaps_[i];
684 if (h.work.empty()) continue;
685 std::memcpy(words + at, h.work.data(), h.work.size() * 4);
686 pass.work.push_back({int(i), std::move(h.work)});
687 const auto& list = pass.work.back().second;
688 for (const std::uint32_t item : list) h.queued[item & ~kZeroFirst] = 0;
689 h.work.clear();
690 p.input_slots = h.input;
691 p.copy_slots = h.copy;
692 p.meta = h.meta.address;
693 p.heap = i;
694 // At most 65535 groups a dispatch (the guaranteed limit).
695 for (std::size_t first = 0; first < list.size(); first += 65535ull * 64) {
696 const std::uint32_t n = std::uint32_t(std::min<std::size_t>(list.size() - first, 65535ull * 64));
697 p.work = base + (at + first) * 4;
698 p.count = n;
699 push(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(p), &p);
700 dispatch(cb, (n + 63) / 64, 1, 1);
701 stats_.slots += n;
702 }
703 at += list.size();
704 }
705 VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
706 after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
707 after.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_READ_BIT;
708 barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT,
709 0, 1, &after, 0, nullptr, 0, nullptr);
710 pass.updates = std::move(updates);
711 pass.cleared = clear_keys_;
712 clear_keys_ = false;
713 stats_.updates += update_count;
714 ++stats_.passes;
715 in_flight_.push_back(std::move(pass));
716 return true;
717 }
718
719 // After the submit of the command buffer record() wrote into: `ticket` is a retire ticket at or after that
720 // submission. Not submitted: its slots and updates are queued again.
721 void commit(bool submitted, std::uint64_t ticket) {
722 std::lock_guard lock(mutex_);
723 for (auto it = in_flight_.rbegin(); it != in_flight_.rend(); ++it) {
724 if (it->committed) continue;
725 if (submitted) {
726 it->committed = true;
727 it->ticket = ticket;
728 return;
729 }
730 ++stats_.failed;
731 for (const auto& [heap, list] : it->work)
732 if (heaps_[heap].slots)
733 for (const std::uint32_t item : list) queue_locked(heap, item);
734 for (const auto& r : it->rescans) {
735 if (!heaps_[r.heap].slots) continue;
736 auto& to = r.filtered ? heaps_[r.heap].rescan_filtered : heaps_[r.heap].rescan;
737 to = std::max(to, r.slots);
738 }
739 change_shader_.insert(change_shader_.end(), it->change_shader.begin(), it->change_shader.end());
740 change_title_.insert(change_title_.end(), it->change_title.begin(), it->change_title.end());
741 for (const int heap : it->filled)
742 if (heaps_[heap].slots) heaps_[heap].meta_clear = true;
743 copies_.insert(copies_.end(), it->copies.begin(), it->copies.end());
744 keeps_.insert(keeps_.end(), it->keeps.begin(), it->keeps.end());
745 for (std::size_t i = 0; i < it->updates.size(); i += ConsoleHeapKeys::kUpdateWords)
746 keys_.touch(it->updates[i]);
747 if (it->cleared) clear_keys_ = true;
748 pool_.push_back(it->buffer);
749 in_flight_.erase(std::next(it).base());
750 return;
751 }
752 }
753
754 // The passes done by `completed` (a completed retire ticket): `miss(heap, slot, half)` for each V# half they
755 // could not answer, `overflow(heap)` for a heap whose misses ran past the list (-1: every heap).
756 template <class Miss, class Overflow>
757 void drain(std::uint64_t completed, Miss&& miss, Overflow&& overflow) {
758 std::vector<Pass> done;
759 {
760 std::lock_guard lock(mutex_);
761 for (auto it = in_flight_.begin(); it != in_flight_.end();) {
762 if (!it->committed || it->ticket > completed) {
763 ++it;
764 continue;
765 }
766 done.push_back(std::move(*it));
767 it = in_flight_.erase(it);
768 }
769 // Tables no pass in flight still reads go back to their pool.
770 for (unsigned kind = 0; kind < table_count; ++kind) {
771 Table& t = tables_[kind];
772 std::uint64_t oldest = t.version;
773 for (const Pass& pass : in_flight_) oldest = std::min(oldest, pass.versions[kind]);
774 for (auto it = t.old.begin(); it != t.old.end();) {
775 if (it->first < oldest) {
776 if (t.pool.size() < 8) t.pool.push_back(it->second);
777 else free_buffer(it->second);
778 it = t.old.erase(it);
779 } else {
780 ++it;
781 }
782 }
783 }
784 }
785 for (Pass& pass : done) {
786 const auto* words = static_cast<const std::uint32_t*>(pass.buffer.mapped);
787 const std::uint32_t count = std::min(words[0], kMissCapacity);
788 for (std::uint32_t i = 0; i < count; ++i) {
789 const std::uint32_t code = words[kMissHeader + i];
790 miss(int(code >> 29), (code >> 1) & ((1u << 28) - 1), code & 1u);
791 }
792 if (words[2]) overflow(-1);
793 std::lock_guard lock(mutex_);
794 stats_.misses += count;
795 stats_.overflows += words[2] ? 1 : 0;
796 pool_.push_back(pass.buffer);
797 }
798 }
799
800 std::size_t in_flight() {
801 std::lock_guard lock(mutex_);
802 return in_flight_.size();
803 }
804 // A pass recorded and not yet committed: its command buffer is on its way to the queue.
805 bool uncommitted() {
806 std::lock_guard lock(mutex_);
807 return std::any_of(in_flight_.begin(), in_flight_.end(), [](const Pass& p) { return !p.committed; });
808 }
809 Stats take_stats() {
810 std::lock_guard lock(mutex_);
811 return std::exchange(stats_, Stats{});
812 }
813
814private:
815 struct Buffer {
816 VkBuffer buffer = VK_NULL_HANDLE;
817 VkDeviceMemory memory = VK_NULL_HANDLE;
818 VkDeviceAddress address = 0;
819 VkDeviceSize size = 0;
820 void* mapped = nullptr;
821 };
822 struct Heap {
823 VkDeviceAddress input = 0, copy = 0;
824 std::uint32_t slots = 0;
825 std::vector<std::uint32_t> work;
826 std::vector<std::uint32_t> queued; // per slot: its position in `work` + 1, 0 when not queued
827 std::uint32_t rescan = 0; // slots [0, rescan) to translate again (rescan())
828 std::uint32_t rescan_filtered = 0; // the same, filtered by the change spans (rescan_filtered())
829 Buffer meta; // device-local, 32 bytes a slot (console_heap_fix.comp meta_of)
830 bool meta_clear = false;
831 };
832 struct Copy {
833 VkBuffer src, dst;
834 VkBufferCopy region;
835 };
836 struct Pass {
837 Buffer buffer;
838 std::array<std::uint64_t, table_count> versions{};
839 struct Rescan {
840 int heap;
841 std::uint32_t slots;
842 bool filtered;
843 };
844 std::vector<Rescan> rescans;
845 ConsoleHeapSpans change_shader, change_title;
846 std::vector<int> filled; // heaps whose metadata this pass zeroed
847 std::vector<Copy> copies;
848 std::vector<std::shared_ptr<void>> keeps;
849 std::vector<std::pair<int, std::vector<std::uint32_t>>> work;
850 std::vector<std::uint32_t> updates;
851 bool cleared = false, committed = false;
852 std::uint64_t ticket = 0;
853 };
854 struct Push {
855 VkDeviceAddress input_slots, copy_slots, work, ranges, keys, misses, backed, ask, meta, cshader, ctitle;
856 std::uint32_t count, range_count, key_mask, mode, heap, backed_count, ask_count, flags, cshader_count,
857 ctitle_count;
858 };
859 static_assert(sizeof(Push) == 128); // the guaranteed maxPushConstantsSize
860 // A table the CPU rebuilds whole (range, backed, ask): each version is its own buffer, kept until no pass in
861 // flight reads it, then reused.
862 struct Table {
863 std::vector<std::uint32_t> words;
864 std::uint32_t count = 0;
865 bool dirty = false;
866 std::unique_ptr<Buffer> current;
867 std::uint64_t version = 0;
868 std::vector<std::pair<std::uint64_t, Buffer>> old;
869 std::vector<Buffer> pool;
870 };
871
872 template <typename T>
873 T fn(const char* name) const {
874 return reinterpret_cast<T>(get_(device_, name));
875 }
876
877 void queue_locked(int heap, std::uint32_t item) {
878 if (heap < 0 || unsigned(heap) >= kMaxHeaps) return;
879 Heap& h = heaps_[heap];
880 const std::uint32_t slot = item & ~kZeroFirst;
881 if (slot >= h.slots) return;
882 if (const std::uint32_t at = h.queued[slot]) {
883 h.work[at - 1] = item;
884 return;
885 }
886 h.work.push_back(item);
887 h.queued[slot] = std::uint32_t(h.work.size());
888 }
889 bool pending_locked() const {
890 if (keys_.has_updates() || clear_keys_ || !copies_.empty()) return true;
891 for (const Heap& h : heaps_)
892 if (!h.work.empty() || h.rescan || h.rescan_filtered) return true;
893 return false;
894 }
895
896 bool publish(Table& t, std::size_t entry_bytes) {
897 Buffer table{};
898 if (t.count) {
899 // A version no pass reads any more, when one is big enough: the tables change at most submissions.
900 const VkDeviceSize bytes = VkDeviceSize(t.count) * entry_bytes;
901 for (auto it = t.pool.begin(); it != t.pool.end(); ++it)
902 if (it->size >= bytes) {
903 table = *it;
904 t.pool.erase(it);
905 break;
906 }
907 // Device-local and host-visible where there is such memory: the pass's binary searches read it a few
908 // dozen times per slot, and from system memory each step was a trip over the bus.
909 if (!table.buffer && !make_buffer(std::max<VkDeviceSize>(bytes + bytes / 2, 64 * 1024), true, table, true))
910 return false;
911 std::memcpy(table.mapped, t.words.data(), t.words.size() * 4);
912 }
913 if (t.current) t.old.emplace_back(t.version, *t.current);
914 t.current.reset();
915 if (table.buffer) t.current = std::make_unique<Buffer>(table);
916 ++t.version;
917 t.dirty = false;
918 ++stats_.tables;
919 return true;
920 }
921
922 bool acquire_buffer(VkDeviceSize bytes, Buffer& out) {
923 for (auto it = pool_.begin(); it != pool_.end(); ++it) {
924 if (it->size < bytes) continue;
925 out = *it;
926 pool_.erase(it);
927 return true;
928 }
929 // Room to grow: the next pass of about this size reuses it.
930 return make_buffer(std::max<VkDeviceSize>(bytes + bytes / 2, 1 << 20), true, out);
931 }
932
933 bool make_buffer(VkDeviceSize bytes, bool host, Buffer& out, bool host_device_local = false) {
934 out = {};
935 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
936 info.size = bytes;
937 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
938 VK_BUFFER_USAGE_TRANSFER_DST_BIT;
939 if (fn<PFN_vkCreateBuffer>("vkCreateBuffer")(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false;
940 VkMemoryRequirements requirements{};
941 fn<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(device_, out.buffer, &requirements);
942 const VkMemoryPropertyFlags required =
943 host ? VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT : 0;
944 const VkMemoryPropertyFlags preferred = host ? 0 : VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
945 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO};
946 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
947 VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags};
948 allocate.allocationSize = requirements.size;
949 // Host-visible: system memory first (not the ReBAR heap the title's windows need).
950 std::vector<std::uint32_t> order;
951 if (host && host_device_local) {
952 order = memory_type_order(memory_, requirements.memoryTypeBits, required | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
953 0, requirements.size);
954 for (const std::uint32_t t : memory_type_order(memory_, requirements.memoryTypeBits, required, 0,
955 requirements.size))
956 if (std::find(order.begin(), order.end(), t) == order.end()) order.push_back(t);
957 } else if (host) {
958 order = memory_type_order(memory_, requirements.memoryTypeBits, required | VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
959 0, requirements.size);
960 for (const std::uint32_t t : memory_type_order(memory_, requirements.memoryTypeBits, required, 0,
961 requirements.size))
962 if (std::find(order.begin(), order.end(), t) == order.end()) order.push_back(t);
963 } else {
964 order = memory_type_order(memory_, requirements.memoryTypeBits, required, preferred, requirements.size);
965 }
966 const auto allocate_memory = fn<PFN_vkAllocateMemory>("vkAllocateMemory");
967 for (const std::uint32_t type : order) {
968 allocate.memoryTypeIndex = type;
969 if (allocate_memory(device_, &allocate, nullptr, &out.memory) == VK_SUCCESS) break;
970 out.memory = VK_NULL_HANDLE;
971 }
972 if (!out.memory ||
973 fn<PFN_vkBindBufferMemory>("vkBindBufferMemory")(device_, out.buffer, out.memory, 0) != VK_SUCCESS ||
974 (host && fn<PFN_vkMapMemory>("vkMapMemory")(device_, out.memory, 0, VK_WHOLE_SIZE, 0, &out.mapped) !=
975 VK_SUCCESS)) {
976 free_buffer(out);
977 return false;
978 }
979 VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
980 address.buffer = out.buffer;
981 out.address = fn<PFN_vkGetBufferDeviceAddress>("vkGetBufferDeviceAddress")(device_, &address);
982 out.size = bytes;
983 if (!out.address) {
984 free_buffer(out);
985 return false;
986 }
987 return true;
988 }
989 void free_buffer(Buffer& b) {
990 if (b.buffer) fn<PFN_vkDestroyBuffer>("vkDestroyBuffer")(device_, b.buffer, nullptr);
991 if (b.memory) fn<PFN_vkFreeMemory>("vkFreeMemory")(device_, b.memory, nullptr); // unmaps
992 b = {};
993 }
994
995 bool make_pipeline() {
996 for (const char* name :
997 {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", "vkAllocateMemory", "vkFreeMemory",
998 "vkBindBufferMemory", "vkMapMemory", "vkGetBufferDeviceAddress", "vkCreateShaderModule",
999 "vkDestroyShaderModule", "vkCreatePipelineLayout", "vkDestroyPipelineLayout", "vkCreateComputePipelines",
1000 "vkDestroyPipeline", "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch",
1001 "vkCmdFillBuffer", "vkCmdCopyBuffer"})
1002 if (!get_(device_, name)) return false;
1003 VkShaderModule module = VK_NULL_HANDLE;
1004 VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
1005 shader.codeSize = sizeof(console_heap_fix_spirv);
1006 shader.pCode = console_heap_fix_spirv;
1007 const aftermath::ShaderName aftermath_name("(runtime) console_heap_fix");
1008 bool ok =
1009 fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS;
1010 const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push)};
1011 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
1012 layout_info.pushConstantRangeCount = 1;
1013 layout_info.pPushConstantRanges = &range;
1014 VkPipelineLayout layout = VK_NULL_HANDLE;
1015 VkPipeline pipeline = VK_NULL_HANDLE;
1016 ok = ok && fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) ==
1017 VK_SUCCESS;
1018 VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
1019 info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
1020 info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
1021 info.stage.module = module;
1022 info.stage.pName = "main";
1023 info.layout = layout;
1024 ok = ok && fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info,
1025 nullptr, &pipeline) == VK_SUCCESS;
1026 if (module) fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(device_, module, nullptr);
1027 if (!ok) {
1028 if (pipeline) fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(device_, pipeline, nullptr);
1029 if (layout) fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(device_, layout, nullptr);
1030 return false;
1031 }
1032 layout_ = layout;
1033 pipeline_ = pipeline;
1034 return true;
1035 }
1036
1037 PFN_vkGetDeviceProcAddr get_;
1038 VkDevice device_;
1039 VkPhysicalDeviceMemoryProperties memory_;
1040 std::mutex mutex_;
1041 VkPipelineLayout layout_ = VK_NULL_HANDLE;
1042 VkPipeline pipeline_ = VK_NULL_HANDLE;
1043 ConsoleHeapKeys keys_;
1044 Buffer key_table_;
1045 bool clear_keys_ = false;
1046 std::array<Heap, kMaxHeaps> heaps_{};
1047 std::array<Table, table_count> tables_{};
1048 bool use_ask_ = false, signed_offsets_ = false;
1049 std::vector<Pass> in_flight_;
1050 std::vector<Buffer> pool_;
1051 std::vector<Copy> copies_;
1052 std::vector<std::shared_ptr<void>> keeps_;
1053 ConsoleHeapSpans change_shader_, change_title_; // pending rescan_filtered() spans
1054 std::vector<Buffer> retired_; // removed heaps' metadata
1055 Stats stats_;
1056};
1057
1058} // namespace leonida
diff --git a/runtime/src/console_heap_vsharp_slots.h b/runtime/src/console_heap_vsharp_slots.h
new file mode 100644
index 000000000..0b0830053
--- /dev/null
+++ b/runtime/src/console_heap_vsharp_slots.h
@@ -0,0 +1,115 @@
1#pragma once
2// Host-RAM bitset of console resource-heap slots whose GPU copy (`heap.copy`) currently holds a live buffer V#
3// (`!(w[3] >> 30) && (w[2] || w[6])`).
4//
5// When a buffer backing or title VA alias is released, `refresh_console_heap` must re-run `fix_console_slot` on every
6// slot that might still point at the released allocation. Scanning `heap.copy` linearly reads every 32-byte slot of
7// the heap (4-5.5+ MiB): when `heap.copy` sits in `arena.mapped` (uncached write-combined GPU memory), each release
8// triggers ~180k uncached PCIe reads. Tracking the live V# slots in host RAM keeps invalidation scans strictly in CPU
9// cache (zero reads from `heap.copy`) and skips empty and T# slots 64 at a time.
10
11#include <algorithm>
12#include <bit>
13#include <cstddef>
14#include <cstdint>
15#include <vector>
16
17namespace leonida {
18
19class ConsoleHeapVsharpSlots {
20public:
21 // Matches the descriptor predicate for a non-empty buffer V# (primary or counter half) in a 32-byte slot.
22 static constexpr bool is_live_vsharp(const std::uint32_t* w) noexcept {
23 return !(w[3] >> 30) && (w[2] || w[6]);
24 }
25
26 void reset(std::size_t slot_count) {
27 slot_count_ = slot_count;
28 live_count_ = 0;
29 words_.assign((slot_count + 63) / 64, 0);
30 }
31
32 void set(std::size_t slot, bool live) noexcept {
33 if (slot >= slot_count_) return;
34 std::uint64_t& word = words_[slot >> 6];
35 const std::uint64_t mask = std::uint64_t{1} << (slot & 63);
36 const bool was = (word & mask) != 0;
37 if (live == was) return;
38 if (live) {
39 word |= mask;
40 ++live_count_;
41 } else {
42 word &= ~mask;
43 --live_count_;
44 }
45 }
46
47 void clear(std::size_t slot) noexcept { set(slot, false); }
48
49 // Clears every slot in [first, end), clamping to slot_count().
50 void clear_range(std::size_t first, std::size_t end) noexcept {
51 if (first >= end || first >= slot_count_ || live_count_ == 0) return;
52 end = (std::min)(end, slot_count_);
53 std::size_t w = first >> 6;
54 const std::size_t last_w = (end - 1) >> 6;
55 const unsigned first_bit = static_cast<unsigned>(first & 63);
56 const unsigned end_bit = static_cast<unsigned>(end & 63);
57 const std::uint64_t head_mask = ~std::uint64_t{0} << first_bit;
58 const std::uint64_t tail_mask = end_bit ? ((std::uint64_t{1} << end_bit) - 1) : ~std::uint64_t{0};
59 if (w == last_w) {
60 const std::uint64_t mask = head_mask & tail_mask;
61 const std::uint64_t cleared = words_[w] & mask;
62 if (cleared) {
63 words_[w] &= ~mask;
64 live_count_ -= static_cast<std::size_t>(std::popcount(cleared));
65 }
66 return;
67 }
68 if (const std::uint64_t cleared = words_[w] & head_mask) {
69 words_[w] &= ~head_mask;
70 live_count_ -= static_cast<std::size_t>(std::popcount(cleared));
71 }
72 for (++w; w < last_w; ++w) {
73 if (const std::uint64_t cleared = words_[w]) {
74 words_[w] = 0;
75 live_count_ -= static_cast<std::size_t>(std::popcount(cleared));
76 }
77 }
78 if (const std::uint64_t cleared = words_[last_w] & tail_mask) {
79 words_[last_w] &= ~tail_mask;
80 live_count_ -= static_cast<std::size_t>(std::popcount(cleared));
81 }
82 }
83
84 // Calls fn(slot) in ascending slot order for every set bit present when its 64-slot word is entered.
85 // Safe if fn mutates the bit for `slot` (e.g., fix_console_slot clearing an invalidated V#).
86 template <class F>
87 void for_each(F&& fn) const {
88 if (live_count_ == 0) return;
89 for (std::size_t w = 0; w < words_.size(); ++w) {
90 std::uint64_t bits = words_[w];
91 if (!bits) continue;
92 const std::size_t base = w << 6;
93 while (bits) {
94 const unsigned bit = static_cast<unsigned>(std::countr_zero(bits));
95 bits &= bits - 1;
96 fn(base + bit);
97 }
98 }
99 }
100
101 bool test(std::size_t slot) const noexcept {
102 return slot < slot_count_ && ((words_[slot >> 6] >> (slot & 63)) & 1u) != 0;
103 }
104
105 std::size_t slot_count() const noexcept { return slot_count_; }
106 std::size_t live_count() const noexcept { return live_count_; }
107 bool empty() const noexcept { return live_count_ == 0; }
108
109private:
110 std::size_t slot_count_ = 0;
111 std::size_t live_count_ = 0;
112 std::vector<std::uint64_t> words_;
113};
114
115} // namespace leonida
diff --git a/runtime/src/descriptor_range_changes.h b/runtime/src/descriptor_range_changes.h
new file mode 100644
index 000000000..5a4d7717f
--- /dev/null
+++ b/runtime/src/descriptor_range_changes.h
@@ -0,0 +1,46 @@
1#pragma once
2#include <algorithm>
3#include <array>
4#include <cstdint>
5#include <vector>
6
7namespace leonida {
8// A separate cursor per console heap. The owning backing/alias registry locks record() and read().
9struct DescriptorRanges {
10 struct Range { uint64_t first, last; }; // inclusive, including UINT64_MAX
11 std::vector<Range> ranges;
12 void merge() {
13 std::sort(ranges.begin(), ranges.end(), [](auto a, auto b) { return a.first < b.first; });
14 size_t n = 0;
15 for (auto r : ranges) {
16 if (n && r.first <= ranges[n-1].last)
17 ranges[n-1].last = (std::max)(ranges[n-1].last, r.last);
18 else ranges[n++] = r;
19 }
20 ranges.resize(n);
21 }
22 bool overlaps(uint64_t base, uint64_t bytes) const {
23 if (!bytes) return false;
24 auto it = std::lower_bound(ranges.begin(), ranges.end(), base,
25 [](auto r, uint64_t v) { return r.last < v; });
26 return it != ranges.end() && (it->first <= base || it->first - base < bytes);
27 }
28};
29class DescriptorRangeChanges {
30 std::array<DescriptorRanges::Range, 4096> ring_{};
31 uint64_t serial_{};
32public:
33 void record(uint64_t start, uint64_t bytes) {
34 if (bytes) {
35 ring_[serial_++ % ring_.size()] = {start, start + (std::min)(UINT64_MAX-start, bytes-1)};
36 }
37 }
38 bool read(uint64_t& cursor, DescriptorRanges& out) const {
39 const auto previous = cursor;
40 cursor = serial_;
41 if (serial_ - previous > ring_.size()) return false;
42 for (auto i = previous; i != serial_; ++i) out.ranges.push_back(ring_[i % ring_.size()]);
43 return true;
44 }
45};
46}
diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h
index a0d80968a..82fa19dbf 100644
--- a/runtime/src/descriptor_table.h
+++ b/runtime/src/descriptor_table.h
@@ -19,7 +19,21 @@ namespace leonida {
19inline constexpr std::uint32_t kFnvOffsetBasis = 2166136261u; 19inline constexpr std::uint32_t kFnvOffsetBasis = 2166136261u;
20inline constexpr std::uint32_t kFnvPrime = 16777619u; 20inline constexpr std::uint32_t kFnvPrime = 16777619u;
21inline constexpr std::uint32_t kDescriptorProbes = 8; 21inline constexpr std::uint32_t kDescriptorProbes = 8;
22inline constexpr std::uint32_t kSlotOccupiedMarker = 0xA11CA7EDu; 22// An entry's last dword is 0 while the slot is empty. This bit marks it occupied, and the low bits (kKindMask) say
23// what the index is good for: one bit per array the image is bound in, sampled and storage.
24inline constexpr std::uint32_t kSlotOccupiedMarker = 0x80000000u;
25inline constexpr std::uint32_t kKindMask = 0x1FFFu; // bits 0..6 sampled, 8..12 storage
26
27// What an index is bound in, for the library whose modules read it (`descriptor_table` tagged in their index.json
28// meta; tools/rdna2spirv.py reads the same bits with OpBitFieldUExtract). Bit `dimension` is that dimension's
29// sampled array (dimensions 0..6, ImageDimension in vulkan_bindless.h); bit 8 + dimension its storage arrays
30// (dimensions 0..4 have them). A table for a plain library leaves every kind bit zero.
31inline constexpr std::uint32_t kind_sampled_bit(std::uint32_t dimension) {
32 return dimension < 7 ? (1u << dimension) : 0u;
33}
34inline constexpr std::uint32_t kind_storage_bit(std::uint32_t dimension) {
35 return dimension < 5 ? (1u << (8 + dimension)) : 0u;
36}
23 37
24// Key types: 38// Key types:
25// T# key is 8 dwords. 39// T# key is 8 dwords.
@@ -93,14 +107,20 @@ inline DescriptorKey make_ssharp_key(const std::uint32_t ssharp[4]) {
93 return k; 107 return k;
94} 108}
95 109
96// Memory layout of each entry in the table: 10 uint32s = 40 bytes. 110// Memory layout of each entry in the table: 10 uint32s = 40 bytes. The last word is the kind a translated shader
111// reads next to the index, and its occupied bit; a module that does not read it never looks at it.
97struct DescriptorEntry { 112struct DescriptorEntry {
98 std::uint32_t key[8] = {}; 113 std::uint32_t key[8] = {};
99 std::uint32_t index = 0; 114 std::uint32_t index = 0;
100 std::uint32_t pad = 0; // 0 when empty, kSlotOccupiedMarker when occupied 115 std::uint32_t kind = 0; // 0 when empty, kSlotOccupiedMarker | (kKindMask bits) when occupied
101}; 116};
102static_assert(sizeof(DescriptorEntry) == 40); 117static_assert(sizeof(DescriptorEntry) == 40);
103 118
119inline constexpr bool slot_occupied(const DescriptorEntry& entry) {
120 return (entry.kind & kSlotOccupiedMarker) != 0;
121}
122inline constexpr std::uint32_t slot_kind(const DescriptorEntry& entry) { return entry.kind & kKindMask; }
123
104class DescriptorTable { 124class DescriptorTable {
105public: 125public:
106 enum class InsertResult { added, unchanged, replaced, added_with_relocation }; 126 enum class InsertResult { added, unchanged, replaced, added_with_relocation };
@@ -122,22 +142,23 @@ public:
122 // The kind this table places and finds keys with (immutable after construction). 142 // The kind this table places and finds keys with (immutable after construction).
123 DescriptorHashKind hash_kind() const { return hash_kind_; } 143 DescriptorHashKind hash_kind() const { return hash_kind_; }
124 144
125 // Inserts or updates a key -> index mapping. 145 // Inserts or updates a key -> (index, kind) mapping. If the key already exists in one of the 8 probe slots,
126 // If the key already exists in one of the 8 probe slots, its index is updated. 146 // its entry is updated. Try one bounded relocation before growing. Load never exceeds 50%. `kind` is what a
127 // Try one bounded relocation before growing. Load never exceeds 50%. 147 // shader that reads it (a `descriptor_table` tagged module) uses to tell which array the index is bound in; a
128 bool insert(const std::uint32_t key[8], std::uint32_t index) { 148 // sampler's entry has none.
129 insert_or_update(key, index); 149 bool insert(const std::uint32_t key[8], std::uint32_t index, std::uint32_t kind = 0) {
150 insert_or_update(key, index, kind);
130 return true; 151 return true;
131 } 152 }
132 153
133 // Report the change under the same lock so the GPU caller can synchronize writes to live slots. 154 // Report the change under the same lock so the GPU caller can synchronize writes to live slots.
134 InsertResult insert_or_update(const std::uint32_t key[8], std::uint32_t index) { 155 InsertResult insert_or_update(const std::uint32_t key[8], std::uint32_t index, std::uint32_t kind = 0) {
135 std::lock_guard lock(mutex_); 156 std::lock_guard lock(mutex_);
136 return insert_locked(key, index); 157 return insert_locked(key, index, kind);
137 } 158 }
138 159
139 bool insert(const DescriptorKey& key, std::uint32_t index) { 160 bool insert(const DescriptorKey& key, std::uint32_t index, std::uint32_t kind = 0) {
140 return insert(key.data(), index); 161 return insert(key.data(), index, kind);
141 } 162 }
142 163
143 // Queries the index associated with key. Returns 0 if not found. 164 // Queries the index associated with key. Returns 0 if not found.
@@ -147,7 +168,7 @@ public:
147 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { 168 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
148 const std::uint32_t slot = (h + k) & mask_; 169 const std::uint32_t slot = (h + k) & mask_;
149 const auto& entry = entries_[slot]; 170 const auto& entry = entries_[slot];
150 if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { 171 if (slot_occupied(entry) && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) {
151 return entry.index; 172 return entry.index;
152 } 173 }
153 } 174 }
@@ -164,7 +185,7 @@ public:
164 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { 185 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
165 const std::uint32_t slot = (h + k) & mask_; 186 const std::uint32_t slot = (h + k) & mask_;
166 const auto& entry = entries_[slot]; 187 const auto& entry = entries_[slot];
167 if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { 188 if (slot_occupied(entry) && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) {
168 return true; 189 return true;
169 } 190 }
170 } 191 }
@@ -222,8 +243,8 @@ public:
222 } 243 }
223 244
224 // Exports the table buffer format consumed by SPIR-V set 0, binding 2. 245 // Exports the table buffer format consumed by SPIR-V set 0, binding 2.
225 // Word 0 is mask; followed by entries[mask + 1] of 10 dwords: key[8], index, pad. 246 // Word 0 is mask; followed by entries[mask + 1] of 10 dwords: key[8], index, kind.
226 std::vector<std::uint32_t> build_gpu_buffer(bool clear_pad = false) const { 247 std::vector<std::uint32_t> build_gpu_buffer(bool clear_occupied = false) const {
227 std::lock_guard lock(mutex_); 248 std::lock_guard lock(mutex_);
228 std::vector<std::uint32_t> out(1 + entries_.size() * 10, 0); 249 std::vector<std::uint32_t> out(1 + entries_.size() * 10, 0);
229 out[0] = mask_; 250 out[0] = mask_;
@@ -231,7 +252,7 @@ public:
231 const std::size_t base = 1 + s * 10; 252 const std::size_t base = 1 + s * 10;
232 std::memcpy(&out[base], entries_[s].key, sizeof(entries_[s].key)); 253 std::memcpy(&out[base], entries_[s].key, sizeof(entries_[s].key));
233 out[base + 8] = entries_[s].index; 254 out[base + 8] = entries_[s].index;
234 out[base + 9] = clear_pad ? 0 : entries_[s].pad; 255 out[base + 9] = clear_occupied ? slot_kind(entries_[s]) : entries_[s].kind;
235 } 256 }
236 return out; 257 return out;
237 } 258 }
@@ -252,7 +273,7 @@ public:
252 return changes; 273 return changes;
253 } 274 }
254 275
255 // One slot's 10 dwords (key[8], index, pad) to `dest`; false when the slot is out of range. 276 // One slot's 10 dwords (key[8], index, kind) to `dest`; false when the slot is out of range.
256 bool read_slot(std::uint32_t slot, std::uint32_t* dest) const { return read_slots(slot, 1, dest); } 277 bool read_slot(std::uint32_t slot, std::uint32_t* dest) const { return read_slots(slot, 1, dest); }
257 278
258 // `count` consecutive slots' 10 dwords each to `dest`, under one lock; false when any is out of range. 279 // `count` consecutive slots' 10 dwords each to `dest`, under one lock; false when any is out of range.
@@ -264,13 +285,13 @@ public:
264 const DescriptorEntry& entry = entries_[first + i]; 285 const DescriptorEntry& entry = entries_[first + i];
265 std::memcpy(dest + i * 10, entry.key, sizeof(entry.key)); 286 std::memcpy(dest + i * 10, entry.key, sizeof(entry.key));
266 dest[i * 10 + 8] = entry.index; 287 dest[i * 10 + 8] = entry.index;
267 dest[i * 10 + 9] = entry.pad; 288 dest[i * 10 + 9] = entry.kind;
268 } 289 }
269 return true; 290 return true;
270 } 291 }
271 292
272 // Serializes directly into `dest` (must hold at least size_bytes()) without allocating a temporary vector. 293 // Serializes directly into `dest` (must hold at least size_bytes()) without allocating a temporary vector.
273 void write_to_buffer(void* dest, bool clear_pad = false) const { 294 void write_to_buffer(void* dest, bool clear_occupied = false) const {
274 if (!dest) return; 295 if (!dest) return;
275 std::lock_guard lock(mutex_); 296 std::lock_guard lock(mutex_);
276 auto* out = static_cast<std::uint8_t*>(dest); 297 auto* out = static_cast<std::uint8_t*>(dest);
@@ -280,7 +301,7 @@ public:
280 std::uint32_t slot[10]; 301 std::uint32_t slot[10];
281 std::memcpy(slot, entry.key, sizeof(entry.key)); 302 std::memcpy(slot, entry.key, sizeof(entry.key));
282 slot[8] = entry.index; 303 slot[8] = entry.index;
283 slot[9] = clear_pad ? 0 : entry.pad; 304 slot[9] = clear_occupied ? slot_kind(entry) : entry.kind;
284 std::memcpy(out, slot, sizeof(slot)); 305 std::memcpy(out, slot, sizeof(slot));
285 out += sizeof(slot); 306 out += sizeof(slot);
286 } 307 }
@@ -298,7 +319,7 @@ private:
298 const auto mask = static_cast<std::uint32_t>(entries.size() - 1); 319 const auto mask = static_cast<std::uint32_t>(entries.size() - 1);
299 for (auto offset = kDescriptorProbes; offset < 2 * kDescriptorProbes - 1; ++offset) { 320 for (auto offset = kDescriptorProbes; offset < 2 * kDescriptorProbes - 1; ++offset) {
300 const auto hole = (hash + offset) & mask; 321 const auto hole = (hash + offset) & mask;
301 if (entries[hole].pad == kSlotOccupiedMarker) continue; 322 if (slot_occupied(entries[hole])) continue;
302 for (auto k = kDescriptorProbes; k > 0; --k) { 323 for (auto k = kDescriptorProbes; k > 0; --k) {
303 const auto slot = (hash + k - 1) & mask; 324 const auto slot = (hash + k - 1) & mask;
304 const auto home = hash_descriptor_key(entries[slot].key, kind); 325 const auto home = hash_descriptor_key(entries[slot].key, kind);
@@ -313,7 +334,7 @@ private:
313 return -1; 334 return -1;
314 } 335 }
315 336
316 InsertResult insert_locked(const std::uint32_t key[8], std::uint32_t index) { 337 InsertResult insert_locked(const std::uint32_t key[8], std::uint32_t index, std::uint32_t kind) {
317 while (true) { 338 while (true) {
318 const std::uint32_t h = hash_descriptor_key(key, hash_kind_); 339 const std::uint32_t h = hash_descriptor_key(key, hash_kind_);
319 int empty_slot = -1; 340 int empty_slot = -1;
@@ -321,10 +342,12 @@ private:
321 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { 342 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
322 const std::uint32_t slot = (h + k) & mask_; 343 const std::uint32_t slot = (h + k) & mask_;
323 auto& entry = entries_[slot]; 344 auto& entry = entries_[slot];
324 if (entry.pad == kSlotOccupiedMarker) { 345 if (slot_occupied(entry)) {
325 if (std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { 346 if (std::memcmp(entry.key, key, sizeof(entry.key)) == 0) {
326 if (entry.index == index) return InsertResult::unchanged; 347 if (entry.index == index && slot_kind(entry) == kind) return InsertResult::unchanged;
348 // A new index or a new kind: either way the slot's copy of the entry must reach the GPU.
327 entry.index = index; 349 entry.index = index;
350 entry.kind = kSlotOccupiedMarker | (kind & kKindMask);
328 mark(slot); 351 mark(slot);
329 return InsertResult::replaced; 352 return InsertResult::replaced;
330 } 353 }
@@ -356,7 +379,7 @@ private:
356 auto& entry = entries_[empty_slot]; 379 auto& entry = entries_[empty_slot];
357 std::memcpy(entry.key, key, sizeof(entry.key)); 380 std::memcpy(entry.key, key, sizeof(entry.key));
358 entry.index = index; 381 entry.index = index;
359 entry.pad = kSlotOccupiedMarker; 382 entry.kind = kSlotOccupiedMarker | (kind & kKindMask);
360 ++occupied_count_; 383 ++occupied_count_;
361 if (relocate) mark(moved_to); 384 if (relocate) mark(moved_to);
362 mark(std::uint32_t(empty_slot)); 385 mark(std::uint32_t(empty_slot));
@@ -374,7 +397,7 @@ private:
374 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { 397 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
375 const std::uint32_t slot = (h + k) & mask_; 398 const std::uint32_t slot = (h + k) & mask_;
376 const auto& entry = entries_[slot]; 399 const auto& entry = entries_[slot];
377 if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { 400 if (slot_occupied(entry) && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) {
378 found_slot = slot; 401 found_slot = slot;
379 found = true; 402 found = true;
380 break; 403 break;
@@ -398,12 +421,12 @@ private:
398 bool rehash_ok = true; 421 bool rehash_ok = true;
399 422
400 for (const auto& old : entries_) { 423 for (const auto& old : entries_) {
401 if (old.pad != kSlotOccupiedMarker) continue; 424 if (!slot_occupied(old)) continue;
402 const std::uint32_t h = hash_descriptor_key(old.key, hash_kind_); 425 const std::uint32_t h = hash_descriptor_key(old.key, hash_kind_);
403 int slot = -1; 426 int slot = -1;
404 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { 427 for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) {
405 const std::uint32_t s = (h + k) & new_mask; 428 const std::uint32_t s = (h + k) & new_mask;
406 if (new_entries[s].pad != kSlotOccupiedMarker) { 429 if (!slot_occupied(new_entries[s])) {
407 slot = static_cast<int>(s); 430 slot = static_cast<int>(s);
408 break; 431 break;
409 } 432 }
diff --git a/runtime/src/dev_overlay.h b/runtime/src/dev_overlay.h
new file mode 100644
index 000000000..1eecfc366
--- /dev/null
+++ b/runtime/src/dev_overlay.h
@@ -0,0 +1,282 @@
1#pragma once
2// LEONIDA_DEV_OVERLAY=1 (off by default, Windows): a small click-through window over the top left corner of the title's
3// window that says how the boot is doing: frames and submissions a second, where a submission's CPU time goes and which
4// phase runs now, pipeline builds, indirect draws, CPU, memory. It is its own window with its own thread and GDI text,
5// so it keeps counting while the title shows no frames for seconds (pipeline builds, a stalled submission), it is in no
6// captured frame, and it changes nothing the GPU does. It only reads counters: submit_phases.h, indirect_draw_stats.h,
7// dev_status.h, and memory_figures.h for the private memory and the device's GPU memory, which LEONIDA_TITLE_HUD
8// (shims/title_hud.h) shows with the same text. The HUD is the other view: frame times, memory and compile time in the
9// window's title bar.
10#include "dev_status.h"
11#include "indirect_draw_stats.h"
12#include "memory_figures.h"
13#include "submit_phases.h"
14
15#ifdef _WIN32
16#ifndef NOMINMAX
17#define NOMINMAX
18#endif
19#include <windows.h>
20#include <psapi.h>
21#ifdef _MSC_VER
22#pragma comment(lib, "user32.lib")
23#pragma comment(lib, "gdi32.lib")
24#pragma comment(lib, "psapi.lib")
25#endif
26#endif
27
28#include <algorithm>
29#include <cstdint>
30#include <cstdio>
31#include <cstdlib>
32#include <string>
33#include <thread>
34#include <vector>
35
36namespace leonida::dev_overlay {
37
38// The counters between two looks. A total that went down was reset by its own log line: what it holds is the new part.
39inline std::uint64_t grown(std::uint64_t now, std::uint64_t& before) {
40 const std::uint64_t by = now >= before ? now - before : now;
41 before = now;
42 return by;
43}
44
45struct Sample {
46 double seconds = 0;
47 double frames = 0, submissions = 0; // a second
48 double phase_ms[submit_phases::kCount]{}; // a submission
49 int phase = -1; // running now
50 double phase_for = 0; // seconds it has been
51 unsigned building = 0;
52 std::uint64_t built = 0;
53 std::string build; // the last one started
54 unsigned long long drawn = 0, skipped = 0; // indirect draws so far
55 double cores = 0, free_gb = 0;
56 memory_figures::ProcessMemory ram; // private memory and working set
57 VramBudget vram; // the device's VK_EXT_memory_budget; "n/a" without it
58};
59
60// The text of one sample: pure, for the test.
61inline std::vector<std::string> lines(const Sample& s, double age) {
62 char text[160];
63 std::vector<std::string> out;
64 std::snprintf(text, sizeof text, "Leonida dev %.0f s %.1f fps %.1f submissions/s", age, s.frames, s.submissions);
65 out.emplace_back(text);
66 double total = 0;
67 for (const double ms : s.phase_ms) total += ms;
68 std::snprintf(text, sizeof text, "CPU/submission %.1f ms: descriptors %.1f, textures %.1f, copies %.1f, replay %.1f", total,
69 s.phase_ms[submit_phases::heaps], s.phase_ms[submit_phases::textures],
70 s.phase_ms[submit_phases::shadows] + s.phase_ms[submit_phases::geometry],
71 s.phase_ms[submit_phases::replay]);
72 out.emplace_back(text);
73 static const char* const now[submit_phases::kCount] = {"waiting for the GPU", "fixing descriptors", "copying title memory",
74 "copying geometry", "refreshing textures", "recording and submitting"};
75 if (s.phase >= 0 && s.phase < int(submit_phases::kCount))
76 std::snprintf(text, sizeof text, "now: %s%s", now[s.phase],
77 s.phase_for >= 1 ? (" for " + std::to_string(int(s.phase_for)) + " s").c_str() : "");
78 else
79 std::snprintf(text, sizeof text, "now: the title's own code");
80 out.emplace_back(text);
81 if (s.building)
82 std::snprintf(text, sizeof text, "pipelines: %llu built, %u building (%.50s)",
83 static_cast<unsigned long long>(s.built), s.building, s.build.c_str());
84 else
85 std::snprintf(text, sizeof text, "pipelines: %llu built", static_cast<unsigned long long>(s.built));
86 out.emplace_back(text);
87 std::snprintf(text, sizeof text, "indirect draws: %llu drawn, %llu skipped", s.drawn, s.skipped);
88 out.emplace_back(text);
89 std::snprintf(text, sizeof text, "%.1f cores, %.1f GB RAM free", s.cores, s.free_gb);
90 out.emplace_back(text);
91 out.emplace_back(memory_figures::ram_text(s.ram) + " " + memory_figures::vram_text(s.vram));
92 return out;
93}
94
95inline bool enabled() {
96 static const bool on = [] {
97#ifdef _WIN32
98 char value[3]{};
99 std::size_t length = 0;
100 return getenv_s(&length, value, sizeof value, "LEONIDA_DEV_OVERLAY") == 0 && length == 2 && value[0] == '1';
101#else
102 const char* value = std::getenv("LEONIDA_DEV_OVERLAY");
103 return value && value[0] == '1' && !value[1];
104#endif
105 }();
106 return on;
107}
108
109#ifdef _WIN32
110class Overlay {
111public:
112 void run() {
113 WNDCLASSW type{};
114 type.lpfnWndProc = &Overlay::procedure;
115 type.hInstance = GetModuleHandleW(nullptr);
116 type.lpszClassName = L"LeonidaDevOverlay";
117 if (!RegisterClassW(&type)) return;
118 window_ = CreateWindowExW(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE | WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
119 type.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, type.hInstance, this);
120 if (!window_) return;
121 SetWindowLongPtrW(window_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
122 SetLayeredWindowAttributes(window_, 0, 205, LWA_ALPHA);
123 font_ = CreateFontW(-14, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
124 CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, FIXED_PITCH | FF_MODERN, L"Consolas");
125 look();
126 SetTimer(window_, 1, 500, nullptr);
127 MSG message;
128 while (GetMessageW(&message, nullptr, 0, 0) > 0) DispatchMessageW(&message);
129 }
130
131private:
132 static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM w, LPARAM l) {
133 auto* self = reinterpret_cast<Overlay*>(GetWindowLongPtrW(window, GWLP_USERDATA));
134 if (self && message == WM_TIMER) {
135 self->look();
136 return 0;
137 }
138 if (self && message == WM_PAINT) {
139 self->paint();
140 return 0;
141 }
142 if (message == WM_NCHITTEST) return HTTRANSPARENT;
143 return DefWindowProcW(window, message, w, l);
144 }
145
146 // The process's largest visible top-level window is the title's.
147 struct Search {
148 HWND own, found;
149 std::int64_t area;
150 };
151 static BOOL CALLBACK consider(HWND window, LPARAM parameter) {
152 auto& search = *reinterpret_cast<Search*>(parameter);
153 DWORD process = 0;
154 GetWindowThreadProcessId(window, &process);
155 RECT r{};
156 if (process != GetCurrentProcessId() || window == search.own || !IsWindowVisible(window) || IsIconic(window) ||
157 !GetClientRect(window, &r))
158 return TRUE;
159 const std::int64_t area = std::int64_t(r.right) * r.bottom;
160 if (area > search.area) search = {search.own, window, area};
161 return TRUE;
162 }
163
164 void look() {
165 namespace sp = submit_phases;
166 sp::Totals& totals = sp::totals();
167 const std::int64_t now = sp::now_ns();
168 Sample s;
169 s.seconds = before_ ? double(now - before_) * 1e-9 : 0;
170 const std::uint64_t frames = grown(totals.present_serial.load(std::memory_order_relaxed), frames_);
171 const std::uint64_t submissions = grown(totals.all_submissions.load(std::memory_order_relaxed), submissions_);
172 std::uint64_t ns[sp::kCount];
173 for (unsigned p = 0; p < sp::kCount; ++p) ns[p] = grown(totals.ns[p].load(std::memory_order_relaxed), ns_[p]);
174 // A stall longer than a look leaves nothing to divide by: the figures then cover the last two seconds.
175 window_frames_ += frames;
176 window_submissions_ += submissions;
177 window_seconds_ += s.seconds;
178 for (unsigned p = 0; p < sp::kCount; ++p) window_ns_[p] += ns[p];
179 if (window_seconds_ >= 2 || !before_) {
180 shown_ = {};
181 if (window_seconds_ > 0) {
182 shown_.frames = double(window_frames_) / window_seconds_;
183 shown_.submissions = double(window_submissions_) / window_seconds_;
184 }
185 for (unsigned p = 0; p < sp::kCount; ++p) {
186 if (window_submissions_) shown_.phase_ms[p] = double(window_ns_[p]) * 1e-6 / double(window_submissions_);
187 window_ns_[p] = 0;
188 }
189 window_frames_ = window_submissions_ = 0;
190 window_seconds_ = 0;
191 }
192 s.frames = shown_.frames;
193 s.submissions = shown_.submissions;
194 std::copy(std::begin(shown_.phase_ms), std::end(shown_.phase_ms), std::begin(s.phase_ms));
195 before_ = now;
196
197 const sp::Running running = sp::running();
198 s.phase = running.phase;
199 if (s.phase >= 0) s.phase_for = std::max(0.0, double(now - running.since) * 1e-9);
200 dev_status::Builds& builds = dev_status::builds();
201 s.building = builds.active.load(std::memory_order_relaxed);
202 s.built = builds.done.load(std::memory_order_relaxed);
203 s.build = builds.last();
204 const auto& draws = indirect_stats::counts().values;
205 s.drawn = draws[std::size_t(indirect_stats::Event::emitted)].load(std::memory_order_relaxed);
206 s.skipped = draws[std::size_t(indirect_stats::Event::record_skip)].load(std::memory_order_relaxed) +
207 draws[std::size_t(indirect_stats::Event::replay_skip)].load(std::memory_order_relaxed);
208 FILETIME created{}, exited{}, kernel{}, user{};
209 if (GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) {
210 const auto ticks = [](const FILETIME& f) { return (std::uint64_t(f.dwHighDateTime) << 32) | f.dwLowDateTime; };
211 const std::uint64_t used = grown(ticks(kernel) + ticks(user), cpu_);
212 if (s.seconds > 0) s.cores = double(used) * 1e-7 / s.seconds;
213 }
214 s.ram = memory_figures::process_memory();
215 s.vram = memory_figures::latest_vram(); // reads the device at most once per 500 ms
216 MEMORYSTATUSEX status{sizeof status};
217 if (GlobalMemoryStatusEx(&status)) s.free_gb = double(status.ullAvailPhys) / double(1u << 30);
218 lines_ = lines(s, sp::process_age());
219 place();
220 }
221
222 void place() {
223 Search search{window_, nullptr, 0};
224 EnumWindows(&Overlay::consider, reinterpret_cast<LPARAM>(&search));
225 // Shown only over the title while it is the window in front, so the topmost text is never over anything else.
226 if (!search.found || GetForegroundWindow() != search.found) {
227 ShowWindow(window_, SW_HIDE);
228 return;
229 }
230 POINT corner{8, 8};
231 ClientToScreen(search.found, &corner);
232 std::size_t longest = 0;
233 for (const auto& line : lines_) longest = std::max(longest, line.size());
234 SetWindowPos(window_, HWND_TOPMOST, corner.x, corner.y, int(longest) * 8 + 12, int(lines_.size()) * 17 + 8,
235 SWP_NOACTIVATE | SWP_SHOWWINDOW);
236 InvalidateRect(window_, nullptr, FALSE);
237 }
238
239 void paint() {
240 PAINTSTRUCT ps;
241 HDC dc = BeginPaint(window_, &ps);
242 RECT area;
243 GetClientRect(window_, &area);
244 HDC memory = CreateCompatibleDC(dc);
245 HBITMAP bitmap = CreateCompatibleBitmap(dc, area.right, area.bottom);
246 HGDIOBJ old_bitmap = SelectObject(memory, bitmap), old_font = SelectObject(memory, font_);
247 FillRect(memory, &area, static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
248 SetBkMode(memory, TRANSPARENT);
249 int y = 4;
250 for (std::size_t i = 0; i < lines_.size(); ++i, y += 17) {
251 SetTextColor(memory, i == 0 ? RGB(120, 255, 140) : RGB(235, 235, 235));
252 TextOutA(memory, 6, y, lines_[i].data(), int(lines_[i].size()));
253 }
254 BitBlt(dc, 0, 0, area.right, area.bottom, memory, 0, 0, SRCCOPY);
255 SelectObject(memory, old_bitmap);
256 SelectObject(memory, old_font);
257 DeleteObject(bitmap);
258 DeleteDC(memory);
259 EndPaint(window_, &ps);
260 }
261
262 HWND window_ = nullptr;
263 HFONT font_ = nullptr;
264 std::vector<std::string> lines_;
265 std::int64_t before_ = 0;
266 std::uint64_t frames_ = 0, submissions_ = 0, cpu_ = 0, ns_[submit_phases::kCount]{};
267 std::uint64_t window_frames_ = 0, window_submissions_ = 0, window_ns_[submit_phases::kCount]{};
268 double window_seconds_ = 0;
269 Sample shown_;
270};
271#endif
272
273// Once per process; nothing without LEONIDA_DEV_OVERLAY=1.
274inline void start() {
275#ifdef _WIN32
276 if (!enabled()) return;
277 std::fprintf(stderr, "[rt] dev overlay on (LEONIDA_DEV_OVERLAY=1)\n");
278 std::thread([] { static Overlay overlay; overlay.run(); }).detach();
279#endif
280}
281
282} // namespace leonida::dev_overlay
diff --git a/runtime/src/dev_status.h b/runtime/src/dev_status.h
new file mode 100644
index 000000000..3efc9bf4f
--- /dev/null
+++ b/runtime/src/dev_status.h
@@ -0,0 +1,51 @@
1#pragma once
2// What the runtime is building now, for the dev overlay (dev_overlay.h). Always on: two relaxed atomics a build, and a
3// short copy under a lock for the name.
4#include <algorithm>
5#include <atomic>
6#include <cstdint>
7#include <cstring>
8#include <mutex>
9#include <string>
10
11namespace leonida::dev_status {
12
13struct Builds {
14 std::atomic<unsigned> active{0};
15 std::atomic<std::uint64_t> done{0};
16
17 std::string last() {
18 std::lock_guard lock(mutex_);
19 return name_;
20 }
21 void name(const char* text) {
22 std::lock_guard lock(mutex_);
23 const std::size_t n = std::min(std::strlen(text), sizeof name_ - 1);
24 std::memcpy(name_, text, n);
25 name_[n] = 0;
26 }
27
28private:
29 std::mutex mutex_;
30 char name_[96]{};
31};
32inline Builds& builds() {
33 static Builds instance;
34 return instance;
35}
36
37// One pipeline build, from construction to destruction.
38struct Build {
39 explicit Build(const char* name) {
40 builds().name(name);
41 builds().active.fetch_add(1, std::memory_order_relaxed);
42 }
43 ~Build() {
44 builds().active.fetch_sub(1, std::memory_order_relaxed);
45 builds().done.fetch_add(1, std::memory_order_relaxed);
46 }
47 Build(const Build&) = delete;
48 Build& operator=(const Build&) = delete;
49};
50
51} // namespace leonida::dev_status
diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h
index 2c9f1fd7e..5588d73ea 100644
--- a/runtime/src/frame_pacer.h
+++ b/runtime/src/frame_pacer.h
@@ -19,6 +19,10 @@
19// * A frame is "in flight" from PresentX until the vblank that shows it. Frames show one per vblank, in order. 19// * A frame is "in flight" from PresentX until the vblank that shows it. Frames show one per vblank, in order.
20// WaitFrameEventX does not return while `latency` frames are in flight. A frame presented while the origin event 20// WaitFrameEventX does not return while `latency` frames are in flight. A frame presented while the origin event
21// is not armed is not paced (PresentX does not hold it for a vblank): it shows at once and is never in flight. 21// is not armed is not paced (PresentX does not hold it for a vblank): it shows at once and is never in flight.
22// * At most `latency` frames are in flight. A present into a full queue (several presents with no wait between
23// them) replaces the newest queued frame and takes its vblank, like a mailbox: the replaced frame is never shown,
24// and the older ones keep their vblanks. So the queue, and the next wait, never reach further than `latency`
25// vblanks ahead, however many presents came in between.
22// * A wait that comes late (after the next origin already passed) returns at once with the newest passed origin; 26// * A wait that comes late (after the next origin already passed) returns at once with the newest passed origin;
23// the missed origins are skipped, not queued. 27// the missed origins are skipped, not queued.
24// * Tokens are 1, 2, 3, ... (0 is the null token), one per successful wait, never reused, across suspend/resume. 28// * Tokens are 1, 2, 3, ... (0 is the null token), one per successful wait, never reused, across suspend/resume.
@@ -266,8 +270,9 @@ public:
266 270
267 // GetFrameStatisticsX(token, type_mask, &count, array). `count` is the room in `out` on entry and the number of 271 // GetFrameStatisticsX(token, type_mask, &count, array). `count` is the room in `out` on entry and the number of
268 // entries written on return. S_OK when every producible requested type was written (event, present, display), 272 // entries written on return. S_OK when every producible requested type was written (event, present, display),
269 // S_FALSE with count 0 or fewer when they are not (there yet, or the token is unknown or has aged out of the 273 // S_FALSE with count 0 or fewer when they are not (there yet, the frame was replaced in a full queue and never
270 // last 64). With a null `out`, count only receives how many entries are available. 274 // shown, or the token is unknown or has aged out of the last 64). With a null `out`, count only receives how many
275 // entries are available.
271 std::int32_t get_frame_statistics(std::uint64_t token, std::uint32_t type_mask, std::uint32_t* count, 276 std::int32_t get_frame_statistics(std::uint64_t token, std::uint32_t type_mask, std::uint32_t* count,
272 FrameStatistic* out) { 277 FrameStatistic* out) {
273 if (!count) return pacer_hr::invalid_arg; 278 if (!count) return pacer_hr::invalid_arg;
@@ -359,12 +364,10 @@ public:
359 if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } 364 if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; }
360 return; 365 return;
361 } 366 }
362 // The vblank after now, and not before the one after the previous queued frame. 367 const bool queued_before = !pending_.empty();
363 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; 368 std::uint64_t flip = queue_flip_locked(now);
364 std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_;
365 if (!pending_.empty()) flip = std::max(flip, pending_.back().flip_us + period_us_);
366 float percent = 0.0f; 369 float percent = 0.0f;
367 if (sync == PresentSync::immediate && pending_.empty()) { 370 if (sync == PresentSync::immediate && !queued_before) {
368 flip = now; 371 flip = now;
369 std::uint64_t late_us = 0; 372 std::uint64_t late_us = 0;
370 for (const Record& r : records_) 373 for (const Record& r : records_)
@@ -386,9 +389,7 @@ public:
386 record_present_timing_locked(now, 0); 389 record_present_timing_locked(now, 0);
387 if (!interval_set_ || !any_armed_locked() || uncapped_) return; 390 if (!interval_set_ || !any_armed_locked() || uncapped_) return;
388 retire_locked(now); 391 retire_locked(now);
389 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; 392 const std::uint64_t flip = queue_flip_locked(now);
390 std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_;
391 if (!pending_.empty()) flip = std::max(flip, pending_.back().flip_us + period_us_);
392 pending_.push_back(Pending{0, flip, 0.0f}); 393 pending_.push_back(Pending{0, flip, 0.0f});
393 cv_.notify_all(); 394 cv_.notify_all();
394 } 395 }
@@ -484,6 +485,25 @@ private:
484 bool presented = false, displayed = false; 485 bool presented = false, displayed = false;
485 }; 486 };
486 487
488 // The vblank a frame presented now is queued for: the vblank after now, and not before the one after the previous
489 // queued frame. At most `latency_` frames are in flight, so with the queue full the newest queued frame is
490 // replaced (dropped: never shown) and the new one takes its vblank; the older ones keep theirs. A queue longer
491 // than the latency (after SetFrameIntervalX lowered it) is cut back the same way, from the newest end.
492 std::uint64_t queue_flip_locked(std::uint64_t now) {
493 if (pending_.size() >= latency_) { // latency_ is at least 1, so the queue is not empty
494 std::uint64_t flip = 0;
495 while (pending_.size() >= latency_) {
496 flip = pending_.back().flip_us;
497 pending_.pop_back();
498 }
499 return flip;
500 }
501 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0;
502 std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_;
503 if (!pending_.empty()) flip = std::max(flip, pending_.back().flip_us + period_us_);
504 return flip;
505 }
506
487 void record_present_timing_locked(std::uint64_t now, std::uint64_t token) { 507 void record_present_timing_locked(std::uint64_t now, std::uint64_t token) {
488 ++presents_recorded_; 508 ++presents_recorded_;
489 if (has_last_present_ && now >= last_present_us_) { 509 if (has_last_present_ && now >= last_present_us_) {
diff --git a/runtime/src/fsdraw_probe.h b/runtime/src/fsdraw_probe.h
index 180b02b36..367f793cb 100644
--- a/runtime/src/fsdraw_probe.h
+++ b/runtime/src/fsdraw_probe.h
@@ -38,7 +38,26 @@ inline State& state() {
38 return s; 38 return s;
39} 39}
40 40
41// What backs a title VA on the GPU side (set by the device: "slot-133 shadow", ...), for the CB comparison below.
42inline std::atomic<const char* (*)(std::uint64_t)>& backing_hook() {
43 static std::atomic<const char* (*)(std::uint64_t)> hook{nullptr};
44 return hook;
45}
46
47// LEONIDA_FSDRAW_PROBE=1 turns the records and lines on (so does LEONIDA_COMPUTE_INPUTS, whose probe reads the T#
48// and CBV records). Off by default: they take this mutex at every T# registered, CBV made, pipeline created and
49// table submitted. The arena mapping (note_arena) is kept either way.
50inline bool enabled() {
51 static const bool on = [] {
52 const char* v = std::getenv("LEONIDA_FSDRAW_PROBE");
53 const char* inputs = std::getenv("LEONIDA_COMPUTE_INPUTS");
54 return (v && *v == '1') || (inputs && *inputs);
55 }();
56 return on;
57}
58
41inline void note_pipeline(std::uintptr_t id, std::string text) { 59inline void note_pipeline(std::uintptr_t id, std::string text) {
60 if (!enabled()) return;
42 std::lock_guard lock(state().mutex); 61 std::lock_guard lock(state().mutex);
43 state().pipelines[id] = std::move(text); 62 state().pipelines[id] = std::move(text);
44} 63}
@@ -55,6 +74,7 @@ inline std::string pipeline(std::uintptr_t id) {
55} 74}
56 75
57inline void note_tsharp(const std::uint32_t* words) { 76inline void note_tsharp(const std::uint32_t* words) {
77 if (!enabled()) return;
58 std::array<std::uint32_t, 8> key{}; 78 std::array<std::uint32_t, 8> key{};
59 std::memcpy(key.data(), words, sizeof(key)); 79 std::memcpy(key.data(), words, sizeof(key));
60 std::lock_guard lock(state().mutex); 80 std::lock_guard lock(state().mutex);
@@ -62,6 +82,7 @@ inline void note_tsharp(const std::uint32_t* words) {
62} 82}
63 83
64inline bool has_tsharp(const std::uint32_t* words) { 84inline bool has_tsharp(const std::uint32_t* words) {
85 if (!enabled()) return false;
65 std::array<std::uint32_t, 8> key{}; 86 std::array<std::uint32_t, 8> key{};
66 std::memcpy(key.data(), words, sizeof(key)); 87 std::memcpy(key.data(), words, sizeof(key));
67 std::lock_guard lock(state().mutex); 88 std::lock_guard lock(state().mutex);
@@ -84,22 +105,25 @@ inline void forget_arena(const std::uint8_t* mapped) {
84 } 105 }
85} 106}
86 107
87// A render target a fullscreen draw wrote: the present-probe reads it back with the source (at most 4 kept). 108// A render target a fullscreen draw wrote, or a traced texture (LEONIDA_TRACE_TEXTURE): the present-probe reads it back
109// with the source (at most 24 kept).
88inline void note_target(std::uint64_t id) { 110inline void note_target(std::uint64_t id) {
89 if (!id) return; 111 if (!id || !enabled()) return;
90 std::lock_guard lock(state().mutex); 112 std::lock_guard lock(state().mutex);
91 auto& r = state().readback; 113 auto& r = state().readback;
92 for (const std::uint64_t x : r) 114 for (const std::uint64_t x : r)
93 if (x == id) return; 115 if (x == id) return;
94 if (r.size() < 4) r.push_back(id); 116 if (r.size() < 24) r.push_back(id);
95} 117}
96 118
97inline std::vector<std::uint64_t> targets() { 119inline std::vector<std::uint64_t> targets() {
120 if (!enabled()) return {};
98 std::lock_guard lock(state().mutex); 121 std::lock_guard lock(state().mutex);
99 return state().readback; 122 return state().readback;
100} 123}
101 124
102inline void note_table(std::uint64_t translated, std::uint64_t original) { 125inline void note_table(std::uint64_t translated, std::uint64_t original) {
126 if (!enabled()) return;
103 std::lock_guard lock(state().mutex); 127 std::lock_guard lock(state().mutex);
104 auto& m = state().table_origin; 128 auto& m = state().table_origin;
105 if (m.size() > 8192) m.clear(); 129 if (m.size() > 8192) m.clear();
@@ -107,12 +131,14 @@ inline void note_table(std::uint64_t translated, std::uint64_t original) {
107} 131}
108 132
109inline std::uint64_t table_origin(std::uint64_t va) { 133inline std::uint64_t table_origin(std::uint64_t va) {
134 if (!enabled()) return va;
110 std::lock_guard lock(state().mutex); 135 std::lock_guard lock(state().mutex);
111 const auto it = state().table_origin.find(va); 136 const auto it = state().table_origin.find(va);
112 return it == state().table_origin.end() ? va : it->second; 137 return it == state().table_origin.end() ? va : it->second;
113} 138}
114 139
115inline void note_cbv(std::uint64_t base, std::uint64_t location, std::uint32_t size) { 140inline void note_cbv(std::uint64_t base, std::uint64_t location, std::uint32_t size) {
141 if (!enabled()) return;
116 std::lock_guard lock(state().mutex); 142 std::lock_guard lock(state().mutex);
117 auto& m = state().cbv_origin; 143 auto& m = state().cbv_origin;
118 if (m.size() > 8192) m.clear(); 144 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
120} 146}
121 147
122inline bool cbv_origin(std::uint64_t base, std::uint64_t& location) { 148inline bool cbv_origin(std::uint64_t base, std::uint64_t& location) {
149 if (!enabled()) return false;
123 std::lock_guard lock(state().mutex); 150 std::lock_guard lock(state().mutex);
124 const auto it = state().cbv_origin.find(base); 151 const auto it = state().cbv_origin.find(base);
125 if (it == state().cbv_origin.end()) return false; 152 if (it == state().cbv_origin.end()) return false;
@@ -157,7 +184,13 @@ inline std::uint64_t arena_size() {
157// arena has its first 16 dwords printed from the arena. 184// arena has its first 16 dwords printed from the arena.
158inline void describe_table(const char* tag, std::uint64_t va, std::uint32_t slots, const std::uint8_t* cpu, 185inline void describe_table(const char* tag, std::uint64_t va, std::uint32_t slots, const std::uint8_t* cpu,
159 const char* heap_kind) { 186 const char* heap_kind) {
160 const std::uint32_t shown = slots < 4 ? slots : 4; 187 // LEONIDA_FSDRAW_SLOTS=<n>: how many of a table's slots are shown (4 by default; a composite's textures sit later).
188 static const std::uint32_t limit = [] {
189 const char* v = std::getenv("LEONIDA_FSDRAW_SLOTS");
190 const unsigned long n = v ? std::strtoul(v, nullptr, 10) : 0;
191 return n ? std::uint32_t(n < 64 ? n : 64) : 4u;
192 }();
193 const std::uint32_t shown = slots < limit ? slots : limit;
161 std::fprintf(stderr, "[rt] fsdraw: %s table va 0x%llx slots %u heap %s (arena size 0x%llx)\n", tag, 194 std::fprintf(stderr, "[rt] fsdraw: %s table va 0x%llx slots %u heap %s (arena size 0x%llx)\n", tag,
162 static_cast<unsigned long long>(va), slots, heap_kind, static_cast<unsigned long long>(arena_size())); 195 static_cast<unsigned long long>(va), slots, heap_kind, static_cast<unsigned long long>(arena_size()));
163 for (std::uint32_t i = 0; i < shown; ++i) { 196 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
187 if (!all.empty() && arena_words(base, all.data(), all.size())) 220 if (!all.empty() && arena_words(base, all.data(), all.size()))
188 for (const std::uint32_t x : all) nonzero += x != 0; 221 for (const std::uint32_t x : all) nonzero += x != 0;
189 } 222 }
223 // A V# in the arena: the title bytes it was copied from, beside the arena copy the GPU reads, and what
224 // keeps that copy (a coherence gap shows as title nonzero / arena zero, repeatedly).
225 std::uint64_t source = 0, range_va = 0, range_bytes = 0;
226 if (in_arena && title_va_aliases().title_of_shader(base, source, range_va, range_bytes)) {
227 std::uint64_t lo = 0, hi = 0;
228 std::uint32_t title_words[16]{};
229 const bool title_readable =
230 title_va_aliases().title_memory(source, lo, hi) && hi - source >= sizeof title_words;
231 if (title_readable)
232 std::memcpy(title_words, reinterpret_cast<const void*>(static_cast<std::uintptr_t>(source)),
233 sizeof title_words);
234 const auto hook = backing_hook().load(std::memory_order_acquire);
235 std::fprintf(stderr, "[rt] fsdraw: %s slot %u arena 0x%llx comes from title 0x%llx (alias range 0x%llx, "
236 "%llu bytes; backing %s): title [%s]%s\n",
237 tag, i, static_cast<unsigned long long>(base), static_cast<unsigned long long>(source),
238 static_cast<unsigned long long>(range_va), static_cast<unsigned long long>(range_bytes),
239 hook ? hook(source) : "unknown",
240 title_readable ? hex_words(title_words, 16).c_str() : "not readable",
241 !title_readable ? ""
242 // Only the alias range's own bytes (at most the 64 shown): the rest is another object's.
243 : std::memcmp(title_words, data, std::size_t(std::min<std::uint64_t>(
244 sizeof data, range_va + range_bytes - source))) ? " DIFFER" : " SAME");
245 } else if (in_arena) {
246 std::fprintf(stderr, "[rt] fsdraw: %s slot %u arena 0x%llx: no title range maps to it (the layer's own memory)\n",
247 tag, i, static_cast<unsigned long long>(base));
248 }
190 std::uint64_t location = 0; 249 std::uint64_t location = 0;
191 const bool made = cbv_origin(base, location); 250 const bool made = cbv_origin(base, location);
192 std::fprintf(stderr, "[rt] fsdraw: %s slot %u V# base 0x%llx stride %u records %u -> %s [%s] nonzero dwords " 251 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/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index 9dad4ed7a..acfa590f8 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -159,11 +159,24 @@ inline constexpr std::uint32_t packed_uav_flag = 0x00400000;
159inline constexpr std::uint32_t volume_uav_word(std::uint32_t offset, std::uint32_t count) { 159inline constexpr std::uint32_t volume_uav_word(std::uint32_t offset, std::uint32_t count) {
160 return volume_uav_tag | ((count - 1) << 11) | offset; 160 return volume_uav_tag | ((count - 1) << 11) | offset;
161} 161}
162struct VolumeUavRange {
163 std::uint32_t first_w = 0;
164 std::uint32_t w_size = 0;
165};
166// The tag stores the first W slice and the slice count minus one. Bit 22 is independent packed-format metadata.
167inline constexpr bool volume_uav_range(const ImageWords& words, const Image& image, VolumeUavRange& out) {
168 if (image.type != ImageType::image_3d || !(words[4] & volume_uav_flag) ||
169 (words[7] & volume_uav_tag_mask) != volume_uav_tag)
170 return false;
171 out.first_w = words[7] & 0x7ffu;
172 out.w_size = ((words[7] >> 11) & 0x7ffu) + 1u;
173 return true;
174}
162inline constexpr bool partial_volume_uav(const ImageWords& words, const Image& image) { 175inline constexpr bool partial_volume_uav(const ImageWords& words, const Image& image) {
176 VolumeUavRange range{};
177 if (!volume_uav_range(words, image, range)) return false;
163 const auto mip_depth = image.depth >> image.first_mip; 178 const auto mip_depth = image.depth >> image.first_mip;
164 return image.type == ImageType::image_3d && (words[4] & volume_uav_flag) && 179 return range.first_w != 0 || range.w_size != (mip_depth ? mip_depth : 1u);
165 (words[7] & volume_uav_tag_mask) == volume_uav_tag &&
166 (words[7] & ~packed_uav_flag) != volume_uav_word(0, mip_depth ? mip_depth : 1u);
167} 180}
168 181
169inline constexpr float image_min_lod(const ImageWords& words) { 182inline constexpr float image_min_lod(const ImageWords& words) {
@@ -223,6 +236,16 @@ inline constexpr VkImageViewType vulkan_view_type(ImageType type) {
223 } 236 }
224} 237}
225 238
239inline constexpr VkImageSubresourceRange vulkan_subresource_range(const Image& image, VkImageAspectFlags aspects) {
240 const bool volume = image.type == ImageType::image_3d;
241 return {aspects, image.first_mip, image.mip_count, volume ? 0u : image.first_layer,
242 volume ? 1u : image.layer_count};
243}
244
245inline constexpr bool has_hardware_volume_uav_slice_offset(const ImageWords& words, const Image& image) {
246 return image.type == ImageType::image_3d && image.first_layer != 0 && detail::get(words[5], 0, 4) == 1;
247}
248
226// ---- formats ---- 249// ---- formats ----
227 250
228// One row for each Vulkan format: its GFX10_FORMAT code, and the DST_SEL that reads its channels as R, G, B, A 251// One row for each Vulkan format: its GFX10_FORMAT code, and the DST_SEL that reads its channels as R, G, B, A
diff --git a/runtime/src/indirect_clamp.comp b/runtime/src/indirect_clamp.comp
index 565a19463..3b99da59a 100644
--- a/runtime/src/indirect_clamp.comp
+++ b/runtime/src/indirect_clamp.comp
@@ -117,6 +117,16 @@ void main() {
117 const uint asked_x = p.arguments.data[src]; 117 const uint asked_x = p.arguments.data[src];
118 const uint asked_y = p.arguments.data[src + 1u]; 118 const uint asked_y = p.arguments.data[src + 1u];
119 const uint asked_z = p.arguments.data[src + 2u]; 119 const uint asked_z = p.arguments.data[src + 2u];
120 if (p.kind == 3u) {
121 // Before the clamp: how many mesh records ask for more than one group in y or z, and the largest y and z
122 // asked (stats words 8-11), which y = z = 1 below would cut.
123 atomicAdd(p.stats.data[8], 1u);
124 if (asked_y > 1u || asked_z > 1u) {
125 atomicAdd(p.stats.data[9], 1u);
126 atomicMax(p.stats.data[10], asked_y);
127 atomicMax(p.stats.data[11], asked_z);
128 }
129 }
120 uint x = min(asked_x, max_group_dimension); 130 uint x = min(asked_x, max_group_dimension);
121 uint y = min(asked_y, max_group_dimension); 131 uint y = min(asked_y, max_group_dimension);
122 uint z = min(asked_z, max_group_dimension); 132 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 50253df78..653e0543f 100644
--- a/runtime/src/indirect_clamp_spv.h
+++ b/runtime/src/indirect_clamp_spv.h
@@ -3,7 +3,7 @@
3#include <cstdint> 3#include <cstdint>
4namespace leonida { 4namespace leonida {
5inline constexpr std::uint32_t indirect_clamp_spirv[] = { 5inline constexpr std::uint32_t indirect_clamp_spirv[] = {
6 0x07230203u, 0x00010500u, 0x0008000bu, 0x000002d0u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, 6 0x07230203u, 0x00010500u, 0x0008000bu, 0x000002fau, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u,
7 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 7 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu,
8 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000026u, 8 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000026u,
9 0x0000005au, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u, 9 0x0000005au, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u,
@@ -42,7 +42,7 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = {
42 0x00000006u, 0x00000004u, 0x00030047u, 0x00000022u, 0x00000002u, 0x00050048u, 0x00000022u, 0x00000000u, 42 0x00000006u, 0x00000004u, 0x00030047u, 0x00000022u, 0x00000002u, 0x00050048u, 0x00000022u, 0x00000000u,
43 0x00000023u, 0x00000000u, 0x00040047u, 0x00000023u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000024u, 43 0x00000023u, 0x00000000u, 0x00040047u, 0x00000023u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000024u,
44 0x00000002u, 0x00050048u, 0x00000024u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x0000005au, 44 0x00000002u, 0x00050048u, 0x00000024u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x0000005au,
45 0x0000000bu, 0x0000001cu, 0x00040047u, 0x00000209u, 0x0000000bu, 0x00000019u, 0x00020013u, 0x00000002u, 45 0x0000000bu, 0x0000001cu, 0x00040047u, 0x00000227u, 0x0000000bu, 0x00000019u, 0x00020013u, 0x00000002u,
46 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000000u, 0x00040020u, 46 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000000u, 0x00040020u,
47 0x00000007u, 0x00000007u, 0x00000006u, 0x00020014u, 0x00000008u, 0x0004002bu, 0x00000006u, 0x0000000eu, 47 0x00000007u, 0x00000007u, 0x00000006u, 0x00020014u, 0x00000008u, 0x0004002bu, 0x00000006u, 0x0000000eu,
48 0x00000000u, 0x00030029u, 0x00000008u, 0x00000012u, 0x00030027u, 0x00000015u, 0x000014e5u, 0x00030027u, 48 0x00000000u, 0x00030029u, 0x00000008u, 0x00000012u, 0x00030027u, 0x00000015u, 0x000014e5u, 0x00030027u,
@@ -75,16 +75,16 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = {
75 0x00000006u, 0x00000079u, 0x00040020u, 0x00000115u, 0x00000007u, 0x00000114u, 0x0008002cu, 0x00000114u, 75 0x00000006u, 0x00000079u, 0x00040020u, 0x00000115u, 0x00000007u, 0x00000114u, 0x0008002cu, 0x00000114u,
76 0x00000117u, 0x0000000eu, 0x0000000eu, 0x0000000eu, 0x0000000eu, 0x0000000eu, 0x0004002bu, 0x00000006u, 76 0x00000117u, 0x0000000eu, 0x0000000eu, 0x0000000eu, 0x0000000eu, 0x0000000eu, 0x0004002bu, 0x00000006u,
77 0x0000012eu, 0x01000000u, 0x0004002bu, 0x00000006u, 0x00000132u, 0x04000000u, 0x0004002bu, 0x00000006u, 77 0x0000012eu, 0x01000000u, 0x0004002bu, 0x00000006u, 0x00000132u, 0x04000000u, 0x0004002bu, 0x00000006u,
78 0x0000014du, 0x00000002u, 0x0004002bu, 0x00000006u, 0x0000017cu, 0x0000ffffu, 0x0004002bu, 0x00000006u, 78 0x0000014du, 0x00000002u, 0x0004002bu, 0x00000006u, 0x0000019au, 0x0000ffffu, 0x0004002bu, 0x00000006u,
79 0x000001b0u, 0x00100000u, 0x0004002bu, 0x00000006u, 0x000001cbu, 0x00000080u, 0x0004002bu, 0x00000006u, 79 0x000001ceu, 0x00100000u, 0x0004002bu, 0x00000006u, 0x000001e9u, 0x00000080u, 0x0004002bu, 0x00000006u,
80 0x000001ccu, 0x00000040u, 0x0006002cu, 0x00000058u, 0x00000209u, 0x000001ccu, 0x0000002fu, 0x0000002fu, 80 0x000001eau, 0x00000040u, 0x0006002cu, 0x00000058u, 0x00000227u, 0x000001eau, 0x0000002fu, 0x0000002fu,
81 0x00030001u, 0x00000008u, 0x00000288u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 81 0x00030001u, 0x00000008u, 0x000002acu, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u,
82 0x000200f8u, 0x00000005u, 0x0004003bu, 0x00000115u, 0x00000116u, 0x00000007u, 0x000300f7u, 0x0000020au, 82 0x000200f8u, 0x00000005u, 0x0004003bu, 0x00000115u, 0x00000116u, 0x00000007u, 0x000300f7u, 0x00000228u,
83 0x00000000u, 0x000300fbu, 0x0000000eu, 0x0000020bu, 0x000200f8u, 0x0000020bu, 0x00050041u, 0x0000005bu, 83 0x00000000u, 0x000300fbu, 0x0000000eu, 0x00000229u, 0x000200f8u, 0x00000229u, 0x00050041u, 0x0000005bu,
84 0x0000005cu, 0x0000005au, 0x0000000eu, 0x0004003du, 0x00000006u, 0x0000005du, 0x0000005cu, 0x00050041u, 84 0x0000005cu, 0x0000005au, 0x0000000eu, 0x0004003du, 0x00000006u, 0x0000005du, 0x0000005cu, 0x00050041u,
85 0x00000060u, 0x00000061u, 0x00000026u, 0x0000005fu, 0x0004003du, 0x00000006u, 0x00000062u, 0x00000061u, 85 0x00000060u, 0x00000061u, 0x00000026u, 0x0000005fu, 0x0004003du, 0x00000006u, 0x00000062u, 0x00000061u,
86 0x000500aeu, 0x00000008u, 0x00000063u, 0x0000005du, 0x00000062u, 0x000300f7u, 0x00000065u, 0x00000000u, 86 0x000500aeu, 0x00000008u, 0x00000063u, 0x0000005du, 0x00000062u, 0x000300f7u, 0x00000065u, 0x00000000u,
87 0x000400fau, 0x00000063u, 0x00000064u, 0x00000065u, 0x000200f8u, 0x00000064u, 0x000200f9u, 0x0000020au, 87 0x000400fau, 0x00000063u, 0x00000064u, 0x00000065u, 0x000200f8u, 0x00000064u, 0x000200f9u, 0x00000228u,
88 0x000200f8u, 0x00000065u, 0x00050041u, 0x00000060u, 0x00000069u, 0x00000026u, 0x00000068u, 0x0004003du, 88 0x000200f8u, 0x00000065u, 0x00050041u, 0x00000060u, 0x00000069u, 0x00000026u, 0x00000068u, 0x0004003du,
89 0x00000006u, 0x0000006au, 0x00000069u, 0x00050080u, 0x00000006u, 0x0000006cu, 0x0000006au, 0x0000005du, 89 0x00000006u, 0x0000006au, 0x00000069u, 0x00050080u, 0x00000006u, 0x0000006cu, 0x0000006au, 0x0000005du,
90 0x00050041u, 0x00000060u, 0x0000006fu, 0x00000026u, 0x0000006eu, 0x0004003du, 0x00000006u, 0x00000070u, 90 0x00050041u, 0x00000060u, 0x0000006fu, 0x00000026u, 0x0000006eu, 0x0004003du, 0x00000006u, 0x00000070u,
@@ -92,8 +92,8 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = {
92 0x00000000u, 0x000400fau, 0x00000071u, 0x00000073u, 0x0000007bu, 0x000200f8u, 0x00000073u, 0x000500aau, 92 0x00000000u, 0x000400fau, 0x00000071u, 0x00000073u, 0x0000007bu, 0x000200f8u, 0x00000073u, 0x000500aau,
93 0x00000008u, 0x00000077u, 0x00000070u, 0x0000000eu, 0x000600a9u, 0x00000006u, 0x0000007au, 0x00000077u, 93 0x00000008u, 0x00000077u, 0x00000070u, 0x0000000eu, 0x000600a9u, 0x00000006u, 0x0000007au, 0x00000077u,
94 0x00000078u, 0x00000079u, 0x000200f9u, 0x00000074u, 0x000200f8u, 0x0000007bu, 0x000200f9u, 0x00000074u, 94 0x00000078u, 0x00000079u, 0x000200f9u, 0x00000074u, 0x000200f8u, 0x0000007bu, 0x000200f9u, 0x00000074u,
95 0x000200f8u, 0x00000074u, 0x000700f5u, 0x00000006u, 0x00000246u, 0x0000007au, 0x00000073u, 0x0000007cu, 95 0x000200f8u, 0x00000074u, 0x000700f5u, 0x00000006u, 0x00000264u, 0x0000007au, 0x00000073u, 0x0000007cu,
96 0x0000007bu, 0x00050084u, 0x00000006u, 0x00000081u, 0x0000005du, 0x00000246u, 0x00050041u, 0x00000060u, 96 0x0000007bu, 0x00050084u, 0x00000006u, 0x00000081u, 0x0000005du, 0x00000264u, 0x00050041u, 0x00000060u,
97 0x00000085u, 0x00000026u, 0x00000084u, 0x0004003du, 0x00000006u, 0x00000086u, 0x00000085u, 0x000500c7u, 97 0x00000085u, 0x00000026u, 0x00000084u, 0x0004003du, 0x00000006u, 0x00000086u, 0x00000085u, 0x000500c7u,
98 0x00000006u, 0x00000087u, 0x00000086u, 0x0000002fu, 0x000500abu, 0x00000008u, 0x00000088u, 0x00000087u, 98 0x00000006u, 0x00000087u, 0x00000086u, 0x0000002fu, 0x000500abu, 0x00000008u, 0x00000088u, 0x00000087u,
99 0x0000000eu, 0x00050041u, 0x00000060u, 0x0000008bu, 0x00000026u, 0x0000008au, 0x0004003du, 0x00000006u, 99 0x0000000eu, 0x00050041u, 0x00000060u, 0x0000008bu, 0x00000026u, 0x0000008au, 0x0004003du, 0x00000006u,
@@ -112,32 +112,32 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = {
112 0x00060041u, 0x0000002du, 0x000000acu, 0x000000abu, 0x0000002cu, 0x00000091u, 0x000700eau, 0x00000006u, 112 0x00060041u, 0x0000002du, 0x000000acu, 0x000000abu, 0x0000002cu, 0x00000091u, 0x000700eau, 0x00000006u,
113 0x000000adu, 0x000000acu, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x000200f9u, 0x000000a8u, 0x000200f8u, 113 0x000000adu, 0x000000acu, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x000200f9u, 0x000000a8u, 0x000200f8u,
114 0x000000a8u, 0x000200f9u, 0x0000009du, 0x000200f8u, 0x0000009du, 0x000200f9u, 0x0000008fu, 0x000200f8u, 114 0x000000a8u, 0x000200f9u, 0x0000009du, 0x000200f8u, 0x0000009du, 0x000200f9u, 0x0000008fu, 0x000200f8u,
115 0x0000008fu, 0x000700f5u, 0x00000006u, 0x0000024cu, 0x0000008cu, 0x00000074u, 0x00000099u, 0x0000009du, 115 0x0000008fu, 0x000700f5u, 0x00000006u, 0x0000026au, 0x0000008cu, 0x00000074u, 0x00000099u, 0x0000009du,
116 0x000500aeu, 0x00000008u, 0x000000b0u, 0x0000006cu, 0x0000024cu, 0x000300f7u, 0x000000b2u, 0x00000000u, 116 0x000500aeu, 0x00000008u, 0x000000b0u, 0x0000006cu, 0x0000026au, 0x000300f7u, 0x000000b2u, 0x00000000u,
117 0x000400fau, 0x000000b0u, 0x000000b1u, 0x000000b2u, 0x000200f8u, 0x000000b1u, 0x000200f9u, 0x000000b4u, 117 0x000400fau, 0x000000b0u, 0x000000b1u, 0x000000b2u, 0x000200f8u, 0x000000b1u, 0x000200f9u, 0x000000b4u,
118 0x000200f8u, 0x000000b4u, 0x000700f5u, 0x00000006u, 0x000002c2u, 0x0000000eu, 0x000000b1u, 0x000000c5u, 118 0x000200f8u, 0x000000b4u, 0x000700f5u, 0x00000006u, 0x000002ecu, 0x0000000eu, 0x000000b1u, 0x000000c5u,
119 0x000000b5u, 0x000500b0u, 0x00000008u, 0x000000bbu, 0x000002c2u, 0x00000246u, 0x000400f6u, 0x000000b6u, 119 0x000000b5u, 0x000500b0u, 0x00000008u, 0x000000bbu, 0x000002ecu, 0x00000264u, 0x000400f6u, 0x000000b6u,
120 0x000000b5u, 0x00000000u, 0x000400fau, 0x000000bbu, 0x000000b5u, 0x000000b6u, 0x000200f8u, 0x000000b5u, 120 0x000000b5u, 0x00000000u, 0x000400fau, 0x000000bbu, 0x000000b5u, 0x000000b6u, 0x000200f8u, 0x000000b5u,
121 0x00050041u, 0x000000bdu, 0x000000beu, 0x00000026u, 0x000000bcu, 0x0004003du, 0x00000017u, 0x000000bfu, 121 0x00050041u, 0x000000bdu, 0x000000beu, 0x00000026u, 0x000000bcu, 0x0004003du, 0x00000017u, 0x000000bfu,
122 0x000000beu, 0x00050080u, 0x00000006u, 0x000000c2u, 0x00000081u, 0x000002c2u, 0x00060041u, 0x0000002du, 122 0x000000beu, 0x00050080u, 0x00000006u, 0x000000c2u, 0x00000081u, 0x000002ecu, 0x00060041u, 0x0000002du,
123 0x000000c3u, 0x000000bfu, 0x0000002cu, 0x000000c2u, 0x0005003eu, 0x000000c3u, 0x0000000eu, 0x00000002u, 123 0x000000c3u, 0x000000bfu, 0x0000002cu, 0x000000c2u, 0x0005003eu, 0x000000c3u, 0x0000000eu, 0x00000002u,
124 0x00000004u, 0x00050080u, 0x00000006u, 0x000000c5u, 0x000002c2u, 0x00000091u, 0x000200f9u, 0x000000b4u, 124 0x00000004u, 0x00050080u, 0x00000006u, 0x000000c5u, 0x000002ecu, 0x00000091u, 0x000200f9u, 0x000000b4u,
125 0x000200f8u, 0x000000b6u, 0x000200f9u, 0x0000020au, 0x000200f8u, 0x000000b2u, 0x00050041u, 0x00000060u, 125 0x000200f8u, 0x000000b6u, 0x000200f9u, 0x00000228u, 0x000200f8u, 0x000000b2u, 0x00050041u, 0x00000060u,
126 0x000000cau, 0x00000026u, 0x000000c9u, 0x0004003du, 0x00000006u, 0x000000cbu, 0x000000cau, 0x00050084u, 126 0x000000cau, 0x00000026u, 0x000000c9u, 0x0004003du, 0x00000006u, 0x000000cbu, 0x000000cau, 0x00050084u,
127 0x00000006u, 0x000000ccu, 0x0000005du, 0x000000cbu, 0x000200f9u, 0x000000cfu, 0x000200f8u, 0x000000cfu, 127 0x00000006u, 0x000000ccu, 0x0000005du, 0x000000cbu, 0x000200f9u, 0x000000cfu, 0x000200f8u, 0x000000cfu,
128 0x000700f5u, 0x00000008u, 0x00000257u, 0x00000012u, 0x000000b2u, 0x000000e4u, 0x000000d2u, 0x000700f5u, 128 0x000700f5u, 0x00000008u, 0x00000275u, 0x00000012u, 0x000000b2u, 0x000000e4u, 0x000000d2u, 0x000700f5u,
129 0x00000006u, 0x00000252u, 0x0000000eu, 0x000000b2u, 0x000000e6u, 0x000000d2u, 0x000500b0u, 0x00000008u, 129 0x00000006u, 0x00000270u, 0x0000000eu, 0x000000b2u, 0x000000e6u, 0x000000d2u, 0x000500b0u, 0x00000008u,
130 0x000000d6u, 0x00000252u, 0x00000246u, 0x000400f6u, 0x000000d1u, 0x000000d2u, 0x00000000u, 0x000400fau, 130 0x000000d6u, 0x00000270u, 0x00000264u, 0x000400f6u, 0x000000d1u, 0x000000d2u, 0x00000000u, 0x000400fau,
131 0x000000d6u, 0x000000d0u, 0x000000d1u, 0x000200f8u, 0x000000d0u, 0x000300f7u, 0x000000d9u, 0x00000000u, 131 0x000000d6u, 0x000000d0u, 0x000000d1u, 0x000200f8u, 0x000000d0u, 0x000300f7u, 0x000000d9u, 0x00000000u,
132 0x000400fau, 0x00000257u, 0x000000d8u, 0x000000d9u, 0x000200f8u, 0x000000d8u, 0x00050041u, 0x000000dau, 132 0x000400fau, 0x00000275u, 0x000000d8u, 0x000000d9u, 0x000200f8u, 0x000000d8u, 0x00050041u, 0x000000dau,
133 0x000000dbu, 0x00000026u, 0x0000002cu, 0x0004003du, 0x00000015u, 0x000000dcu, 0x000000dbu, 0x00050080u, 133 0x000000dbu, 0x00000026u, 0x0000002cu, 0x0004003du, 0x00000015u, 0x000000dcu, 0x000000dbu, 0x00050080u,
134 0x00000006u, 0x000000dfu, 0x000000ccu, 0x00000252u, 0x00060041u, 0x0000002du, 0x000000e0u, 0x000000dcu, 134 0x00000006u, 0x000000dfu, 0x000000ccu, 0x00000270u, 0x00060041u, 0x0000002du, 0x000000e0u, 0x000000dcu,
135 0x0000002cu, 0x000000dfu, 0x0006003du, 0x00000006u, 0x000000e1u, 0x000000e0u, 0x00000002u, 0x00000004u, 135 0x0000002cu, 0x000000dfu, 0x0006003du, 0x00000006u, 0x000000e1u, 0x000000e0u, 0x00000002u, 0x00000004u,
136 0x000500aau, 0x00000008u, 0x000000e3u, 0x000000e1u, 0x000000e2u, 0x000200f9u, 0x000000d9u, 0x000200f8u, 136 0x000500aau, 0x00000008u, 0x000000e3u, 0x000000e1u, 0x000000e2u, 0x000200f9u, 0x000000d9u, 0x000200f8u,
137 0x000000d9u, 0x000700f5u, 0x00000008u, 0x000000e4u, 0x00000257u, 0x000000d0u, 0x000000e3u, 0x000000d8u, 137 0x000000d9u, 0x000700f5u, 0x00000008u, 0x000000e4u, 0x00000275u, 0x000000d0u, 0x000000e3u, 0x000000d8u,
138 0x000200f9u, 0x000000d2u, 0x000200f8u, 0x000000d2u, 0x00050080u, 0x00000006u, 0x000000e6u, 0x00000252u, 138 0x000200f9u, 0x000000d2u, 0x000200f8u, 0x000000d2u, 0x00050080u, 0x00000006u, 0x000000e6u, 0x00000270u,
139 0x00000091u, 0x000200f9u, 0x000000cfu, 0x000200f8u, 0x000000d1u, 0x000400a8u, 0x00000008u, 0x000000e8u, 139 0x00000091u, 0x000200f9u, 0x000000cfu, 0x000200f8u, 0x000000d1u, 0x000400a8u, 0x00000008u, 0x000000e8u,
140 0x00000257u, 0x000300f7u, 0x000000eau, 0x00000000u, 0x000400fau, 0x000000e8u, 0x000000e9u, 0x000000eau, 140 0x00000275u, 0x000300f7u, 0x000000eau, 0x00000000u, 0x000400fau, 0x000000e8u, 0x000000e9u, 0x000000eau,
141 0x000200f8u, 0x000000e9u, 0x000500aau, 0x00000008u, 0x000000edu, 0x00000070u, 0x0000007cu, 0x000300f7u, 141 0x000200f8u, 0x000000e9u, 0x000500aau, 0x00000008u, 0x000000edu, 0x00000070u, 0x0000007cu, 0x000300f7u,
142 0x000000efu, 0x00000000u, 0x000400fau, 0x000000edu, 0x000000eeu, 0x000000efu, 0x000200f8u, 0x000000eeu, 142 0x000000efu, 0x00000000u, 0x000400fau, 0x000000edu, 0x000000eeu, 0x000000efu, 0x000200f8u, 0x000000eeu,
143 0x00050041u, 0x000000dau, 0x000000f0u, 0x00000026u, 0x0000002cu, 0x0004003du, 0x00000015u, 0x000000f1u, 143 0x00050041u, 0x000000dau, 0x000000f0u, 0x00000026u, 0x0000002cu, 0x0004003du, 0x00000015u, 0x000000f1u,
@@ -145,21 +145,21 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = {
145 0x00000006u, 0x000000f4u, 0x000000f3u, 0x00000002u, 0x00000004u, 0x000500aau, 0x00000008u, 0x000000f5u, 145 0x00000006u, 0x000000f4u, 0x000000f3u, 0x00000002u, 0x00000004u, 0x000500aau, 0x00000008u, 0x000000f5u,
146 0x000000f4u, 0x000000e2u, 0x000200f9u, 0x000000efu, 0x000200f8u, 0x000000efu, 0x000700f5u, 0x00000008u, 146 0x000000f4u, 0x000000e2u, 0x000200f9u, 0x000000efu, 0x000200f8u, 0x000000efu, 0x000700f5u, 0x00000008u,
147 0x000000f6u, 0x000000edu, 0x000000e9u, 0x000000f5u, 0x000000eeu, 0x000200f9u, 0x000000eau, 0x000200f8u, 147 0x000000f6u, 0x000000edu, 0x000000e9u, 0x000000f5u, 0x000000eeu, 0x000200f9u, 0x000000eau, 0x000200f8u,
148 0x000000eau, 0x000700f5u, 0x00000008u, 0x000000f7u, 0x00000257u, 0x000000d1u, 0x000000f6u, 0x000000efu, 148 0x000000eau, 0x000700f5u, 0x00000008u, 0x000000f7u, 0x00000275u, 0x000000d1u, 0x000000f6u, 0x000000efu,
149 0x000300f7u, 0x000000f9u, 0x00000000u, 0x000400fau, 0x000000f7u, 0x000000f8u, 0x000000f9u, 0x000200f8u, 149 0x000300f7u, 0x000000f9u, 0x00000000u, 0x000400fau, 0x000000f7u, 0x000000f8u, 0x000000f9u, 0x000200f8u,
150 0x000000f8u, 0x000200f9u, 0x000000fbu, 0x000200f8u, 0x000000fbu, 0x000700f5u, 0x00000006u, 0x000002beu, 150 0x000000f8u, 0x000200f9u, 0x000000fbu, 0x000200f8u, 0x000000fbu, 0x000700f5u, 0x00000006u, 0x000002e8u,
151 0x0000000eu, 0x000000f8u, 0x0000010au, 0x000000fcu, 0x000500b0u, 0x00000008u, 0x00000102u, 0x000002beu, 151 0x0000000eu, 0x000000f8u, 0x0000010au, 0x000000fcu, 0x000500b0u, 0x00000008u, 0x00000102u, 0x000002e8u,
152 0x00000246u, 0x000400f6u, 0x000000fdu, 0x000000fcu, 0x00000000u, 0x000400fau, 0x00000102u, 0x000000fcu, 152 0x00000264u, 0x000400f6u, 0x000000fdu, 0x000000fcu, 0x00000000u, 0x000400fau, 0x00000102u, 0x000000fcu,
153 0x000000fdu, 0x000200f8u, 0x000000fcu, 0x00050041u, 0x000000bdu, 0x00000103u, 0x00000026u, 0x000000bcu, 153 0x000000fdu, 0x000200f8u, 0x000000fcu, 0x00050041u, 0x000000bdu, 0x00000103u, 0x00000026u, 0x000000bcu,
154 0x0004003du, 0x00000017u, 0x00000104u, 0x00000103u, 0x00050080u, 0x00000006u, 0x00000107u, 0x00000081u, 154 0x0004003du, 0x00000017u, 0x00000104u, 0x00000103u, 0x00050080u, 0x00000006u, 0x00000107u, 0x00000081u,
155 0x000002beu, 0x00060041u, 0x0000002du, 0x00000108u, 0x00000104u, 0x0000002cu, 0x00000107u, 0x0005003eu, 155 0x000002e8u, 0x00060041u, 0x0000002du, 0x00000108u, 0x00000104u, 0x0000002cu, 0x00000107u, 0x0005003eu,
156 0x00000108u, 0x0000000eu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x0000010au, 0x000002beu, 156 0x00000108u, 0x0000000eu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x0000010au, 0x000002e8u,
157 0x00000091u, 0x000200f9u, 0x000000fbu, 0x000200f8u, 0x000000fdu, 0x00050041u, 0x00000029u, 0x0000010bu, 157 0x00000091u, 0x000200f9u, 0x000000fbu, 0x000200f8u, 0x000000fdu, 0x00050041u, 0x00000029u, 0x0000010bu,
158 0x00000026u, 0x000000a9u, 0x0004003du, 0x00000019u, 0x0000010cu, 0x0000010bu, 0x00060041u, 0x0000002du, 158 0x00000026u, 0x000000a9u, 0x0004003du, 0x00000019u, 0x0000010cu, 0x0000010bu, 0x00060041u, 0x0000002du,
159 0x0000010du, 0x0000010cu, 0x0000002cu, 0x0000002cu, 0x000700eau, 0x00000006u, 0x0000010eu, 0x0000010du, 159 0x0000010du, 0x0000010cu, 0x0000002cu, 0x0000002cu, 0x000700eau, 0x00000006u, 0x0000010eu, 0x0000010du,
160 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x00060041u, 0x0000002du, 0x00000111u, 0x0000010cu, 0x0000002cu, 160 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x00060041u, 0x0000002du, 0x00000111u, 0x0000010cu, 0x0000002cu,
161 0x0000009eu, 0x000700eau, 0x00000006u, 0x00000112u, 0x00000111u, 0x0000002fu, 0x0000000eu, 0x0000002fu, 161 0x0000009eu, 0x000700eau, 0x00000006u, 0x00000112u, 0x00000111u, 0x0000002fu, 0x0000000eu, 0x0000002fu,
162 0x000200f9u, 0x0000020au, 0x000200f8u, 0x000000f9u, 0x0003003eu, 0x00000116u, 0x00000117u, 0x000300f7u, 162 0x000200f9u, 0x00000228u, 0x000200f8u, 0x000000f9u, 0x0003003eu, 0x00000116u, 0x00000117u, 0x000300f7u,
163 0x0000011eu, 0x00000000u, 0x000400fau, 0x00000071u, 0x0000011du, 0x00000165u, 0x000200f8u, 0x0000011du, 163 0x0000011eu, 0x00000000u, 0x000400fau, 0x00000071u, 0x0000011du, 0x00000165u, 0x000200f8u, 0x0000011du,
164 0x00050041u, 0x000000dau, 0x00000120u, 0x00000026u, 0x0000002cu, 0x0004003du, 0x00000015u, 0x00000121u, 164 0x00050041u, 0x000000dau, 0x00000120u, 0x00000026u, 0x0000002cu, 0x0004003du, 0x00000015u, 0x00000121u,
165 0x00000120u, 0x00060041u, 0x0000002du, 0x00000123u, 0x00000121u, 0x0000002cu, 0x000000ccu, 0x0006003du, 165 0x00000120u, 0x00060041u, 0x0000002du, 0x00000123u, 0x00000121u, 0x0000002cu, 0x000000ccu, 0x0006003du,
@@ -169,13 +169,13 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = {
169 0x0000012fu, 0x00000001u, 0x00000026u, 0x00000124u, 0x0000012eu, 0x0007000cu, 0x00000006u, 0x00000134u, 169 0x0000012fu, 0x00000001u, 0x00000026u, 0x00000124u, 0x0000012eu, 0x0007000cu, 0x00000006u, 0x00000134u,
170 0x00000001u, 0x00000029u, 0x0000012fu, 0x0000002fu, 0x00050086u, 0x00000006u, 0x00000135u, 0x00000132u, 170 0x00000001u, 0x00000029u, 0x0000012fu, 0x0000002fu, 0x00050086u, 0x00000006u, 0x00000135u, 0x00000132u,
171 0x00000134u, 0x0007000cu, 0x00000006u, 0x00000136u, 0x00000001u, 0x00000026u, 0x0000012bu, 0x00000135u, 171 0x00000134u, 0x0007000cu, 0x00000006u, 0x00000136u, 0x00000001u, 0x00000026u, 0x0000012bu, 0x00000135u,
172 0x000500aau, 0x00000008u, 0x00000138u, 0x0000012fu, 0x0000000eu, 0x000600a9u, 0x00000006u, 0x000002c9u, 172 0x000500aau, 0x00000008u, 0x00000138u, 0x0000012fu, 0x0000000eu, 0x000600a9u, 0x00000006u, 0x000002f3u,
173 0x00000138u, 0x0000000eu, 0x00000136u, 0x000500abu, 0x00000008u, 0x0000013du, 0x0000012fu, 0x00000124u, 173 0x00000138u, 0x0000000eu, 0x00000136u, 0x000500abu, 0x00000008u, 0x0000013du, 0x0000012fu, 0x00000124u,
174 0x000500abu, 0x00000008u, 0x00000140u, 0x000002c9u, 0x0000012bu, 0x000500a6u, 0x00000008u, 0x00000141u, 174 0x000500abu, 0x00000008u, 0x00000140u, 0x000002f3u, 0x0000012bu, 0x000500a6u, 0x00000008u, 0x00000141u,
175 0x0000013du, 0x00000140u, 0x000600a9u, 0x00000006u, 0x00000142u, 0x00000141u, 0x0000002fu, 0x0000000eu, 175 0x0000013du, 0x00000140u, 0x000600a9u, 0x00000006u, 0x00000142u, 0x00000141u, 0x0000002fu, 0x0000000eu,
176 0x00050084u, 0x00000006u, 0x00000145u, 0x0000012fu, 0x000002c9u, 0x00050041u, 0x00000007u, 0x00000147u, 176 0x00050084u, 0x00000006u, 0x00000145u, 0x0000012fu, 0x000002f3u, 0x00050041u, 0x00000007u, 0x00000147u,
177 0x00000116u, 0x0000002cu, 0x0003003eu, 0x00000147u, 0x0000012fu, 0x00050041u, 0x00000007u, 0x00000149u, 177 0x00000116u, 0x0000002cu, 0x0003003eu, 0x00000147u, 0x0000012fu, 0x00050041u, 0x00000007u, 0x00000149u,
178 0x00000116u, 0x00000091u, 0x0003003eu, 0x00000149u, 0x000002c9u, 0x00050080u, 0x00000006u, 0x0000014eu, 178 0x00000116u, 0x00000091u, 0x0003003eu, 0x00000149u, 0x000002f3u, 0x00050080u, 0x00000006u, 0x0000014eu,
179 0x000000ccu, 0x0000014du, 0x00060041u, 0x0000002du, 0x0000014fu, 0x00000121u, 0x0000002cu, 0x0000014eu, 179 0x000000ccu, 0x0000014du, 0x00060041u, 0x0000002du, 0x0000014fu, 0x00000121u, 0x0000002cu, 0x0000014eu,
180 0x0006003du, 0x00000006u, 0x00000150u, 0x0000014fu, 0x00000002u, 0x00000004u, 0x00050041u, 0x00000007u, 180 0x0006003du, 0x00000006u, 0x00000150u, 0x0000014fu, 0x00000002u, 0x00000004u, 0x00050041u, 0x00000007u,
181 0x00000151u, 0x00000116u, 0x000000bcu, 0x0003003eu, 0x00000151u, 0x00000150u, 0x00050080u, 0x00000006u, 181 0x00000151u, 0x00000116u, 0x000000bcu, 0x0003003eu, 0x00000151u, 0x00000150u, 0x00050080u, 0x00000006u,
@@ -194,94 +194,106 @@ inline constexpr std::uint32_t indirect_clamp_spirv[] = {
194 0x00060041u, 0x0000002du, 0x00000171u, 0x00000168u, 0x0000002cu, 0x00000170u, 0x0006003du, 0x00000006u, 194 0x00060041u, 0x0000002du, 0x00000171u, 0x00000168u, 0x0000002cu, 0x00000170u, 0x0006003du, 0x00000006u,
195 0x00000172u, 0x00000171u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x00000177u, 0x000000ccu, 195 0x00000172u, 0x00000171u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x00000177u, 0x000000ccu,
196 0x0000014du, 0x00060041u, 0x0000002du, 0x00000178u, 0x00000168u, 0x0000002cu, 0x00000177u, 0x0006003du, 196 0x0000014du, 0x00060041u, 0x0000002du, 0x00000178u, 0x00000168u, 0x0000002cu, 0x00000177u, 0x0006003du,
197 0x00000006u, 0x00000179u, 0x00000178u, 0x00000002u, 0x00000004u, 0x0007000cu, 0x00000006u, 0x0000017du, 197 0x00000006u, 0x00000179u, 0x00000178u, 0x00000002u, 0x00000004u, 0x000500aau, 0x00000008u, 0x0000017cu,
198 0x00000001u, 0x00000026u, 0x0000016bu, 0x0000017cu, 0x0007000cu, 0x00000006u, 0x00000180u, 0x00000001u, 198 0x00000070u, 0x0000007cu, 0x000300f7u, 0x0000017eu, 0x00000000u, 0x000400fau, 0x0000017cu, 0x0000017du,
199 0x00000026u, 0x00000172u, 0x0000017cu, 0x0007000cu, 0x00000006u, 0x00000183u, 0x00000001u, 0x00000026u, 199 0x0000017eu, 0x000200f8u, 0x0000017du, 0x00050041u, 0x00000029u, 0x0000017fu, 0x00000026u, 0x000000a9u,
200 0x00000179u, 0x0000017cu, 0x000500aau, 0x00000008u, 0x00000186u, 0x00000070u, 0x0000007cu, 0x000600a9u, 200 0x0004003du, 0x00000019u, 0x00000180u, 0x0000017fu, 0x00060041u, 0x0000002du, 0x00000181u, 0x00000180u,
201 0x00000006u, 0x000002cau, 0x00000186u, 0x0000002fu, 0x00000183u, 0x000600a9u, 0x00000006u, 0x000002cbu, 201 0x0000002cu, 0x0000005fu, 0x000700eau, 0x00000006u, 0x00000182u, 0x00000181u, 0x0000002fu, 0x0000000eu,
202 0x00000186u, 0x0000002fu, 0x00000180u, 0x000500c2u, 0x00000006u, 0x0000018cu, 0x00000086u, 0x0000002fu, 202 0x0000002fu, 0x000500acu, 0x00000008u, 0x00000184u, 0x00000172u, 0x0000002fu, 0x000500acu, 0x00000008u,
203 0x000500abu, 0x00000008u, 0x0000018eu, 0x0000018cu, 0x0000000eu, 0x000500abu, 0x00000008u, 0x00000190u, 203 0x00000186u, 0x00000179u, 0x0000002fu, 0x000500a6u, 0x00000008u, 0x00000187u, 0x00000184u, 0x00000186u,
204 0x0000017du, 0x0000000eu, 0x000500a7u, 0x00000008u, 0x00000191u, 0x0000018eu, 0x00000190u, 0x000500abu, 204 0x000300f7u, 0x00000189u, 0x00000000u, 0x000400fau, 0x00000187u, 0x00000188u, 0x00000189u, 0x000200f8u,
205 0x00000008u, 0x00000193u, 0x000002cbu, 0x0000000eu, 0x000500a7u, 0x00000008u, 0x00000194u, 0x00000191u, 205 0x00000188u, 0x00060041u, 0x0000002du, 0x0000018cu, 0x00000180u, 0x0000002cu, 0x00000068u, 0x000700eau,
206 0x00000193u, 0x000500abu, 0x00000008u, 0x00000196u, 0x000002cau, 0x0000000eu, 0x000500a7u, 0x00000008u, 206 0x00000006u, 0x0000018du, 0x0000018cu, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x00060041u, 0x0000002du,
207 0x00000197u, 0x00000194u, 0x00000196u, 0x000300f7u, 0x00000199u, 0x00000000u, 0x000400fau, 0x00000197u, 207 0x00000190u, 0x00000180u, 0x0000002cu, 0x0000008au, 0x000700efu, 0x00000006u, 0x00000192u, 0x00000190u,
208 0x00000198u, 0x00000199u, 0x000200f8u, 0x00000198u, 0x0007000cu, 0x00000006u, 0x0000019cu, 0x00000001u, 208 0x0000002fu, 0x0000000eu, 0x00000172u, 0x00060041u, 0x0000002du, 0x00000195u, 0x00000180u, 0x0000002cu,
209 0x00000026u, 0x0000017du, 0x0000018cu, 0x00050086u, 0x00000006u, 0x000001a0u, 0x0000018cu, 0x0000019cu, 209 0x00000084u, 0x000700efu, 0x00000006u, 0x00000197u, 0x00000195u, 0x0000002fu, 0x0000000eu, 0x00000179u,
210 0x0007000cu, 0x00000006u, 0x000001a1u, 0x00000001u, 0x00000026u, 0x000002cbu, 0x000001a0u, 0x00050086u, 210 0x000200f9u, 0x00000189u, 0x000200f8u, 0x00000189u, 0x000200f9u, 0x0000017eu, 0x000200f8u, 0x0000017eu,
211 0x00000006u, 0x000001a7u, 0x000001a0u, 0x000001a1u, 0x0007000cu, 0x00000006u, 0x000001a8u, 0x00000001u, 211 0x0007000cu, 0x00000006u, 0x0000019bu, 0x00000001u, 0x00000026u, 0x0000016bu, 0x0000019au, 0x0007000cu,
212 0x00000026u, 0x000002cau, 0x000001a7u, 0x000200f9u, 0x00000199u, 0x000200f8u, 0x00000199u, 0x000700f5u, 212 0x00000006u, 0x0000019eu, 0x00000001u, 0x00000026u, 0x00000172u, 0x0000019au, 0x0007000cu, 0x00000006u,
213 0x00000006u, 0x00000260u, 0x000002cbu, 0x00000165u, 0x000001a1u, 0x00000198u, 0x000700f5u, 0x00000006u, 213 0x000001a1u, 0x00000001u, 0x00000026u, 0x00000179u, 0x0000019au, 0x000600a9u, 0x00000006u, 0x000002f4u,
214 0x0000025fu, 0x0000017du, 0x00000165u, 0x0000019cu, 0x00000198u, 0x000700f5u, 0x00000006u, 0x0000025eu, 214 0x0000017cu, 0x0000002fu, 0x000001a1u, 0x000600a9u, 0x00000006u, 0x000002f5u, 0x0000017cu, 0x0000002fu,
215 0x000002cau, 0x00000165u, 0x000001a8u, 0x00000198u, 0x000500abu, 0x00000008u, 0x000001aau, 0x0000025eu, 215 0x0000019eu, 0x000500c2u, 0x00000006u, 0x000001aau, 0x00000086u, 0x0000002fu, 0x000500abu, 0x00000008u,
216 0x0000000eu, 0x000300f7u, 0x000001acu, 0x00000000u, 0x000400fau, 0x000001aau, 0x000001abu, 0x000001acu, 216 0x000001acu, 0x000001aau, 0x0000000eu, 0x000500abu, 0x00000008u, 0x000001aeu, 0x0000019bu, 0x0000000eu,
217 0x000200f8u, 0x000001abu, 0x00050084u, 0x00000006u, 0x000001afu, 0x0000025fu, 0x00000260u, 0x00050086u, 217 0x000500a7u, 0x00000008u, 0x000001afu, 0x000001acu, 0x000001aeu, 0x000500abu, 0x00000008u, 0x000001b1u,
218 0x00000006u, 0x000001b2u, 0x000001b0u, 0x0000025eu, 0x000500acu, 0x00000008u, 0x000001b3u, 0x000001afu, 218 0x000002f5u, 0x0000000eu, 0x000500a7u, 0x00000008u, 0x000001b2u, 0x000001afu, 0x000001b1u, 0x000500abu,
219 0x000001b2u, 0x000200f9u, 0x000001acu, 0x000200f8u, 0x000001acu, 0x000700f5u, 0x00000008u, 0x000001b4u, 219 0x00000008u, 0x000001b4u, 0x000002f4u, 0x0000000eu, 0x000500a7u, 0x00000008u, 0x000001b5u, 0x000001b2u,
220 0x000001aau, 0x00000199u, 0x000001b3u, 0x000001abu, 0x000600a9u, 0x00000006u, 0x000002ccu, 0x000001b4u, 220 0x000001b4u, 0x000300f7u, 0x000001b7u, 0x00000000u, 0x000400fau, 0x000001b5u, 0x000001b6u, 0x000001b7u,
221 0x0000000eu, 0x0000025eu, 0x000600a9u, 0x00000006u, 0x000002cdu, 0x000001b4u, 0x0000000eu, 0x00000260u, 221 0x000200f8u, 0x000001b6u, 0x0007000cu, 0x00000006u, 0x000001bau, 0x00000001u, 0x00000026u, 0x0000019bu,
222 0x000600a9u, 0x00000006u, 0x000002ceu, 0x000001b4u, 0x0000000eu, 0x0000025fu, 0x000500abu, 0x00000008u, 222 0x000001aau, 0x00050086u, 0x00000006u, 0x000001beu, 0x000001aau, 0x000001bau, 0x0007000cu, 0x00000006u,
223 0x000001b9u, 0x000002ceu, 0x0000016bu, 0x000500abu, 0x00000008u, 0x000001bcu, 0x000002cdu, 0x00000172u, 223 0x000001bfu, 0x00000001u, 0x00000026u, 0x000002f5u, 0x000001beu, 0x00050086u, 0x00000006u, 0x000001c5u,
224 0x000500a6u, 0x00000008u, 0x000001bdu, 0x000001b9u, 0x000001bcu, 0x000500abu, 0x00000008u, 0x000001c0u, 224 0x000001beu, 0x000001bfu, 0x0007000cu, 0x00000006u, 0x000001c6u, 0x00000001u, 0x00000026u, 0x000002f4u,
225 0x000002ccu, 0x00000179u, 0x000500a6u, 0x00000008u, 0x000001c1u, 0x000001bdu, 0x000001c0u, 0x000600a9u, 225 0x000001c5u, 0x000200f9u, 0x000001b7u, 0x000200f8u, 0x000001b7u, 0x000700f5u, 0x00000006u, 0x00000284u,
226 0x00000006u, 0x000001c2u, 0x000001c1u, 0x0000002fu, 0x0000000eu, 0x00050084u, 0x00000006u, 0x000001c5u, 226 0x000002f5u, 0x0000017eu, 0x000001bfu, 0x000001b6u, 0x000700f5u, 0x00000006u, 0x00000283u, 0x0000019bu,
227 0x000002ceu, 0x000002cdu, 0x00050084u, 0x00000006u, 0x000001c7u, 0x000001c5u, 0x000002ccu, 0x000600a9u, 227 0x0000017eu, 0x000001bau, 0x000001b6u, 0x000700f5u, 0x00000006u, 0x00000282u, 0x000002f4u, 0x0000017eu,
228 0x00000006u, 0x000001cdu, 0x00000186u, 0x000001cbu, 0x000001ccu, 0x00050084u, 0x00000006u, 0x000001ceu, 228 0x000001c6u, 0x000001b6u, 0x000500abu, 0x00000008u, 0x000001c8u, 0x00000282u, 0x0000000eu, 0x000300f7u,
229 0x000001c7u, 0x000001cdu, 0x00050041u, 0x00000007u, 0x000001d0u, 0x00000116u, 0x0000002cu, 0x0003003eu, 229 0x000001cau, 0x00000000u, 0x000400fau, 0x000001c8u, 0x000001c9u, 0x000001cau, 0x000200f8u, 0x000001c9u,
230 0x000001d0u, 0x000002ceu, 0x00050041u, 0x00000007u, 0x000001d2u, 0x00000116u, 0x00000091u, 0x0003003eu, 230 0x00050084u, 0x00000006u, 0x000001cdu, 0x00000283u, 0x00000284u, 0x00050086u, 0x00000006u, 0x000001d0u,
231 0x000001d2u, 0x000002cdu, 0x00050041u, 0x00000007u, 0x000001d4u, 0x00000116u, 0x000000bcu, 0x0003003eu, 231 0x000001ceu, 0x00000282u, 0x000500acu, 0x00000008u, 0x000001d1u, 0x000001cdu, 0x000001d0u, 0x000200f9u,
232 0x000001d4u, 0x000002ccu, 0x000200f9u, 0x0000011eu, 0x000200f8u, 0x0000011eu, 0x000700f5u, 0x00000006u, 232 0x000001cau, 0x000200f8u, 0x000001cau, 0x000700f5u, 0x00000008u, 0x000001d2u, 0x000001c8u, 0x000001b7u,
233 0x00000292u, 0x00000142u, 0x0000015du, 0x000001c2u, 0x000001acu, 0x000700f5u, 0x00000006u, 0x00000278u, 233 0x000001d1u, 0x000001c9u, 0x000600a9u, 0x00000006u, 0x000002f6u, 0x000001d2u, 0x0000000eu, 0x00000282u,
234 0x00000145u, 0x0000015du, 0x000001ceu, 0x000001acu, 0x000500abu, 0x00000008u, 0x000001d6u, 0x00000278u, 234 0x000600a9u, 0x00000006u, 0x000002f7u, 0x000001d2u, 0x0000000eu, 0x00000284u, 0x000600a9u, 0x00000006u,
235 0x0000000eu, 0x000300f7u, 0x000001d8u, 0x00000000u, 0x000400fau, 0x000001d6u, 0x000001d7u, 0x000001d8u, 235 0x000002f8u, 0x000001d2u, 0x0000000eu, 0x00000283u, 0x000500abu, 0x00000008u, 0x000001d7u, 0x000002f8u,
236 0x000200f8u, 0x000001d7u, 0x000300f7u, 0x00000244u, 0x00000000u, 0x000300fbu, 0x0000000eu, 0x0000021cu, 236 0x0000016bu, 0x000500abu, 0x00000008u, 0x000001dau, 0x000002f7u, 0x00000172u, 0x000500a6u, 0x00000008u,
237 0x000200f8u, 0x0000021cu, 0x000500aau, 0x00000008u, 0x0000021eu, 0x00000278u, 0x0000000eu, 0x000300f7u, 237 0x000001dbu, 0x000001d7u, 0x000001dau, 0x000500abu, 0x00000008u, 0x000001deu, 0x000002f6u, 0x00000179u,
238 0x00000220u, 0x00000000u, 0x000400fau, 0x0000021eu, 0x0000021fu, 0x00000220u, 0x000200f8u, 0x0000021fu, 238 0x000500a6u, 0x00000008u, 0x000001dfu, 0x000001dbu, 0x000001deu, 0x000600a9u, 0x00000006u, 0x000001e0u,
239 0x000200f9u, 0x00000244u, 0x000200f8u, 0x00000220u, 0x00050041u, 0x00000029u, 0x00000221u, 0x00000026u, 239 0x000001dfu, 0x0000002fu, 0x0000000eu, 0x00050084u, 0x00000006u, 0x000001e3u, 0x000002f8u, 0x000002f7u,
240 0x00000028u, 0x0004003du, 0x00000019u, 0x00000222u, 0x00000221u, 0x00060041u, 0x0000002du, 0x00000223u, 240 0x00050084u, 0x00000006u, 0x000001e5u, 0x000001e3u, 0x000002f6u, 0x000600a9u, 0x00000006u, 0x000001ebu,
241 0x00000222u, 0x0000002cu, 0x0000002cu, 0x000700eau, 0x00000006u, 0x00000224u, 0x00000223u, 0x0000002fu, 241 0x0000017cu, 0x000001e9u, 0x000001eau, 0x00050084u, 0x00000006u, 0x000001ecu, 0x000001e5u, 0x000001ebu,
242 0x0000000eu, 0x0000000eu, 0x000200f9u, 0x00000225u, 0x000200f8u, 0x00000225u, 0x000700f5u, 0x00000006u, 242 0x00050041u, 0x00000007u, 0x000001eeu, 0x00000116u, 0x0000002cu, 0x0003003eu, 0x000001eeu, 0x000002f8u,
243 0x0000027au, 0x00000224u, 0x00000220u, 0x00000239u, 0x00000240u, 0x000500b0u, 0x00000008u, 0x00000228u, 243 0x00050041u, 0x00000007u, 0x000001f0u, 0x00000116u, 0x00000091u, 0x0003003eu, 0x000001f0u, 0x000002f7u,
244 0x0000027au, 0x00000037u, 0x000400f6u, 0x00000241u, 0x00000240u, 0x00000000u, 0x000400fau, 0x00000228u, 244 0x00050041u, 0x00000007u, 0x000001f2u, 0x00000116u, 0x000000bcu, 0x0003003eu, 0x000001f2u, 0x000002f6u,
245 0x00000229u, 0x00000241u, 0x000200f8u, 0x00000229u, 0x00050082u, 0x00000006u, 0x0000022bu, 0x00000037u, 245 0x000200f9u, 0x0000011eu, 0x000200f8u, 0x0000011eu, 0x000700f5u, 0x00000006u, 0x000002b8u, 0x00000142u,
246 0x0000027au, 0x000500acu, 0x00000008u, 0x0000022eu, 0x00000278u, 0x0000022bu, 0x000300f7u, 0x00000230u, 246 0x0000015du, 0x000001e0u, 0x000001cau, 0x000700f5u, 0x00000006u, 0x0000029cu, 0x00000145u, 0x0000015du,
247 0x00000000u, 0x000400fau, 0x0000022eu, 0x0000022fu, 0x00000230u, 0x000200f8u, 0x0000022fu, 0x000200f9u, 247 0x000001ecu, 0x000001cau, 0x000500abu, 0x00000008u, 0x000001f4u, 0x0000029cu, 0x0000000eu, 0x000300f7u,
248 0x00000241u, 0x000200f8u, 0x00000230u, 0x00050080u, 0x00000006u, 0x00000233u, 0x0000027au, 0x00000278u, 248 0x000001f6u, 0x00000000u, 0x000400fau, 0x000001f4u, 0x000001f5u, 0x000001f6u, 0x000200f8u, 0x000001f5u,
249 0x000900e6u, 0x00000006u, 0x00000239u, 0x00000223u, 0x0000002fu, 0x0000000eu, 0x0000000eu, 0x00000233u, 249 0x000300f7u, 0x00000262u, 0x00000000u, 0x000300fbu, 0x0000000eu, 0x0000023au, 0x000200f8u, 0x0000023au,
250 0x0000027au, 0x000500aau, 0x00000008u, 0x0000023cu, 0x00000239u, 0x0000027au, 0x000300f7u, 0x0000023eu, 250 0x000500aau, 0x00000008u, 0x0000023cu, 0x0000029cu, 0x0000000eu, 0x000300f7u, 0x0000023eu, 0x00000000u,
251 0x00000000u, 0x000400fau, 0x0000023cu, 0x0000023du, 0x0000023eu, 0x000200f8u, 0x0000023du, 0x000200f9u, 251 0x000400fau, 0x0000023cu, 0x0000023du, 0x0000023eu, 0x000200f8u, 0x0000023du, 0x000200f9u, 0x00000262u,
252 0x00000241u, 0x000200f8u, 0x0000023eu, 0x000200f9u, 0x00000240u, 0x000200f8u, 0x00000240u, 0x000200f9u, 252 0x000200f8u, 0x0000023eu, 0x00050041u, 0x00000029u, 0x0000023fu, 0x00000026u, 0x00000028u, 0x0004003du,
253 0x00000225u, 0x000200f8u, 0x00000241u, 0x000900f5u, 0x00000008u, 0x0000027fu, 0x00000288u, 0x00000225u, 253 0x00000019u, 0x00000240u, 0x0000023fu, 0x00060041u, 0x0000002du, 0x00000241u, 0x00000240u, 0x0000002cu,
254 0x00000041u, 0x0000022fu, 0x00000012u, 0x0000023du, 0x000900f5u, 0x00000008u, 0x0000027cu, 0x00000041u, 254 0x0000002cu, 0x000700eau, 0x00000006u, 0x00000242u, 0x00000241u, 0x0000002fu, 0x0000000eu, 0x0000000eu,
255 0x00000225u, 0x00000012u, 0x0000022fu, 0x00000012u, 0x0000023du, 0x000300f7u, 0x00000243u, 0x00000000u, 255 0x000200f9u, 0x00000243u, 0x000200f8u, 0x00000243u, 0x000700f5u, 0x00000006u, 0x0000029eu, 0x00000242u,
256 0x000400fau, 0x0000027cu, 0x00000244u, 0x00000243u, 0x000200f8u, 0x00000243u, 0x000200f9u, 0x00000244u, 256 0x0000023eu, 0x00000257u, 0x0000025eu, 0x000500b0u, 0x00000008u, 0x00000246u, 0x0000029eu, 0x00000037u,
257 0x000200f8u, 0x00000244u, 0x000900f5u, 0x00000008u, 0x0000027eu, 0x00000012u, 0x0000021fu, 0x0000027fu, 257 0x000400f6u, 0x0000025fu, 0x0000025eu, 0x00000000u, 0x000400fau, 0x00000246u, 0x00000247u, 0x0000025fu,
258 0x00000241u, 0x00000041u, 0x00000243u, 0x000400a8u, 0x00000008u, 0x000001dcu, 0x0000027eu, 0x000200f9u, 258 0x000200f8u, 0x00000247u, 0x00050082u, 0x00000006u, 0x00000249u, 0x00000037u, 0x0000029eu, 0x000500acu,
259 0x000001d8u, 0x000200f8u, 0x000001d8u, 0x000700f5u, 0x00000008u, 0x000001ddu, 0x000001d6u, 0x0000011eu, 259 0x00000008u, 0x0000024cu, 0x0000029cu, 0x00000249u, 0x000300f7u, 0x0000024eu, 0x00000000u, 0x000400fau,
260 0x000001dcu, 0x00000244u, 0x000300f7u, 0x000001dfu, 0x00000000u, 0x000400fau, 0x000001ddu, 0x000001deu, 260 0x0000024cu, 0x0000024du, 0x0000024eu, 0x000200f8u, 0x0000024du, 0x000200f9u, 0x0000025fu, 0x000200f8u,
261 0x000001dfu, 0x000200f8u, 0x000001deu, 0x00050041u, 0x00000029u, 0x000001e0u, 0x00000026u, 0x000000a9u, 261 0x0000024eu, 0x00050080u, 0x00000006u, 0x00000251u, 0x0000029eu, 0x0000029cu, 0x000900e6u, 0x00000006u,
262 0x0004003du, 0x00000019u, 0x000001e1u, 0x000001e0u, 0x00060041u, 0x0000002du, 0x000001e2u, 0x000001e1u, 262 0x00000257u, 0x00000241u, 0x0000002fu, 0x0000000eu, 0x0000000eu, 0x00000251u, 0x0000029eu, 0x000500aau,
263 0x0000002cu, 0x000000bcu, 0x000700eau, 0x00000006u, 0x000001e3u, 0x000001e2u, 0x0000002fu, 0x0000000eu, 263 0x00000008u, 0x0000025au, 0x00000257u, 0x0000029eu, 0x000300f7u, 0x0000025cu, 0x00000000u, 0x000400fau,
264 0x0000002fu, 0x0003003eu, 0x00000116u, 0x00000117u, 0x000200f9u, 0x000001dfu, 0x000200f8u, 0x000001dfu, 264 0x0000025au, 0x0000025bu, 0x0000025cu, 0x000200f8u, 0x0000025bu, 0x000200f9u, 0x0000025fu, 0x000200f8u,
265 0x000600a9u, 0x00000006u, 0x000002cfu, 0x000001ddu, 0x0000002fu, 0x00000292u, 0x000500abu, 0x00000008u, 265 0x0000025cu, 0x000200f9u, 0x0000025eu, 0x000200f8u, 0x0000025eu, 0x000200f9u, 0x00000243u, 0x000200f8u,
266 0x000001e5u, 0x000002cfu, 0x0000000eu, 0x000300f7u, 0x000001e7u, 0x00000000u, 0x000400fau, 0x000001e5u, 266 0x0000025fu, 0x000900f5u, 0x00000008u, 0x000002a3u, 0x000002acu, 0x00000243u, 0x00000041u, 0x0000024du,
267 0x000001e6u, 0x000001e7u, 0x000200f8u, 0x000001e6u, 0x00050041u, 0x00000029u, 0x000001e8u, 0x00000026u, 267 0x00000012u, 0x0000025bu, 0x000900f5u, 0x00000008u, 0x000002a0u, 0x00000041u, 0x00000243u, 0x00000012u,
268 0x000000a9u, 0x0004003du, 0x00000019u, 0x000001e9u, 0x000001e8u, 0x00060041u, 0x0000002du, 0x000001eau, 268 0x0000024du, 0x00000012u, 0x0000025bu, 0x000300f7u, 0x00000261u, 0x00000000u, 0x000400fau, 0x000002a0u,
269 0x000001e9u, 0x0000002cu, 0x0000002cu, 0x000700eau, 0x00000006u, 0x000001ebu, 0x000001eau, 0x0000002fu, 269 0x00000262u, 0x00000261u, 0x000200f8u, 0x00000261u, 0x000200f9u, 0x00000262u, 0x000200f8u, 0x00000262u,
270 0x0000000eu, 0x0000002fu, 0x00050041u, 0x00000007u, 0x000001ecu, 0x00000116u, 0x0000002cu, 0x0004003du, 270 0x000900f5u, 0x00000008u, 0x000002a2u, 0x00000012u, 0x0000023du, 0x000002a3u, 0x0000025fu, 0x00000041u,
271 0x00000006u, 0x000001edu, 0x000001ecu, 0x000500aau, 0x00000008u, 0x000001eeu, 0x000001edu, 0x0000000eu, 271 0x00000261u, 0x000400a8u, 0x00000008u, 0x000001fau, 0x000002a2u, 0x000200f9u, 0x000001f6u, 0x000200f8u,
272 0x000300f7u, 0x000001f0u, 0x00000000u, 0x000400fau, 0x000001eeu, 0x000001efu, 0x000001f0u, 0x000200f8u, 272 0x000001f6u, 0x000700f5u, 0x00000008u, 0x000001fbu, 0x000001f4u, 0x0000011eu, 0x000001fau, 0x00000262u,
273 0x000001efu, 0x00060041u, 0x0000002du, 0x000001f3u, 0x000001e9u, 0x0000002cu, 0x0000009eu, 0x000700eau, 273 0x000300f7u, 0x000001fdu, 0x00000000u, 0x000400fau, 0x000001fbu, 0x000001fcu, 0x000001fdu, 0x000200f8u,
274 0x00000006u, 0x000001f4u, 0x000001f3u, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x000200f9u, 0x000001f0u, 274 0x000001fcu, 0x00050041u, 0x00000029u, 0x000001feu, 0x00000026u, 0x000000a9u, 0x0004003du, 0x00000019u,
275 0x000200f8u, 0x000001f0u, 0x000200f9u, 0x000001e7u, 0x000200f8u, 0x000001e7u, 0x000200f9u, 0x000001f6u, 275 0x000001ffu, 0x000001feu, 0x00060041u, 0x0000002du, 0x00000200u, 0x000001ffu, 0x0000002cu, 0x000000bcu,
276 0x000200f8u, 0x000001f6u, 0x000700f5u, 0x00000006u, 0x00000297u, 0x0000000eu, 0x000001e7u, 0x00000208u, 276 0x000700eau, 0x00000006u, 0x00000201u, 0x00000200u, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x0003003eu,
277 0x000001f7u, 0x000500b0u, 0x00000008u, 0x000001fdu, 0x00000297u, 0x00000246u, 0x000400f6u, 0x000001f8u, 277 0x00000116u, 0x00000117u, 0x000200f9u, 0x000001fdu, 0x000200f8u, 0x000001fdu, 0x000600a9u, 0x00000006u,
278 0x000001f7u, 0x00000000u, 0x000400fau, 0x000001fdu, 0x000001f7u, 0x000001f8u, 0x000200f8u, 0x000001f7u, 278 0x000002f9u, 0x000001fbu, 0x0000002fu, 0x000002b8u, 0x000500abu, 0x00000008u, 0x00000203u, 0x000002f9u,
279 0x00050041u, 0x000000bdu, 0x000001feu, 0x00000026u, 0x000000bcu, 0x0004003du, 0x00000017u, 0x000001ffu, 279 0x0000000eu, 0x000300f7u, 0x00000205u, 0x00000000u, 0x000400fau, 0x00000203u, 0x00000204u, 0x00000205u,
280 0x000001feu, 0x00050080u, 0x00000006u, 0x00000202u, 0x00000081u, 0x00000297u, 0x00050041u, 0x00000007u, 280 0x000200f8u, 0x00000204u, 0x00050041u, 0x00000029u, 0x00000206u, 0x00000026u, 0x000000a9u, 0x0004003du,
281 0x00000204u, 0x00000116u, 0x00000297u, 0x0004003du, 0x00000006u, 0x00000205u, 0x00000204u, 0x00060041u, 281 0x00000019u, 0x00000207u, 0x00000206u, 0x00060041u, 0x0000002du, 0x00000208u, 0x00000207u, 0x0000002cu,
282 0x0000002du, 0x00000206u, 0x000001ffu, 0x0000002cu, 0x00000202u, 0x0005003eu, 0x00000206u, 0x00000205u, 282 0x0000002cu, 0x000700eau, 0x00000006u, 0x00000209u, 0x00000208u, 0x0000002fu, 0x0000000eu, 0x0000002fu,
283 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x00000208u, 0x00000297u, 0x00000091u, 0x000200f9u, 283 0x00050041u, 0x00000007u, 0x0000020au, 0x00000116u, 0x0000002cu, 0x0004003du, 0x00000006u, 0x0000020bu,
284 0x000001f6u, 0x000200f8u, 0x000001f8u, 0x000200f9u, 0x0000020au, 0x000200f8u, 0x0000020au, 0x000100fdu, 284 0x0000020au, 0x000500aau, 0x00000008u, 0x0000020cu, 0x0000020bu, 0x0000000eu, 0x000300f7u, 0x0000020eu,
285 0x00010038u, 285 0x00000000u, 0x000400fau, 0x0000020cu, 0x0000020du, 0x0000020eu, 0x000200f8u, 0x0000020du, 0x00060041u,
286 0x0000002du, 0x00000211u, 0x00000207u, 0x0000002cu, 0x0000009eu, 0x000700eau, 0x00000006u, 0x00000212u,
287 0x00000211u, 0x0000002fu, 0x0000000eu, 0x0000002fu, 0x000200f9u, 0x0000020eu, 0x000200f8u, 0x0000020eu,
288 0x000200f9u, 0x00000205u, 0x000200f8u, 0x00000205u, 0x000200f9u, 0x00000214u, 0x000200f8u, 0x00000214u,
289 0x000700f5u, 0x00000006u, 0x000002bdu, 0x0000000eu, 0x00000205u, 0x00000226u, 0x00000215u, 0x000500b0u,
290 0x00000008u, 0x0000021bu, 0x000002bdu, 0x00000264u, 0x000400f6u, 0x00000216u, 0x00000215u, 0x00000000u,
291 0x000400fau, 0x0000021bu, 0x00000215u, 0x00000216u, 0x000200f8u, 0x00000215u, 0x00050041u, 0x000000bdu,
292 0x0000021cu, 0x00000026u, 0x000000bcu, 0x0004003du, 0x00000017u, 0x0000021du, 0x0000021cu, 0x00050080u,
293 0x00000006u, 0x00000220u, 0x00000081u, 0x000002bdu, 0x00050041u, 0x00000007u, 0x00000222u, 0x00000116u,
294 0x000002bdu, 0x0004003du, 0x00000006u, 0x00000223u, 0x00000222u, 0x00060041u, 0x0000002du, 0x00000224u,
295 0x0000021du, 0x0000002cu, 0x00000220u, 0x0005003eu, 0x00000224u, 0x00000223u, 0x00000002u, 0x00000004u,
296 0x00050080u, 0x00000006u, 0x00000226u, 0x000002bdu, 0x00000091u, 0x000200f9u, 0x00000214u, 0x000200f8u,
297 0x00000216u, 0x000200f9u, 0x00000228u, 0x000200f8u, 0x00000228u, 0x000100fdu, 0x00010038u,
286}; 298};
287} // namespace leonida 299} // namespace leonida
diff --git a/runtime/src/indirect_draw_stats.h b/runtime/src/indirect_draw_stats.h
index 39ed09b35..0413ae5d8 100644
--- a/runtime/src/indirect_draw_stats.h
+++ b/runtime/src/indirect_draw_stats.h
@@ -1,45 +1,104 @@
1// Process-wide counts of calls recorded and replay attempts. A command list can replay more than once. 1// Process-wide counts of calls recorded and replay attempts. A command list can replay more than once.
2#pragma once 2#pragma once
3#include <atomic> 3#include <atomic>
4#include <cstddef>
5#include <cstdint>
4#include <cstdio> 6#include <cstdio>
5 7
6namespace leonida::indirect_stats { 8namespace leonida::indirect_stats {
7enum class Event { recorded, emitted, record_skip, replay_skip }; 9enum class Event { recorded, emitted, record_skip, replay_skip };
10// One flag per reason, shared across resolver instantiations.
11enum Reason { compound, disabled, pipeline, root_layout, viewport, mesh, topology, first_instance, entry, robust_index,
12 count_limit, multi_draw, count_feature, raw_count_limit, argument_usage, count_usage,
13 divisor, pending_pipeline, index_view, index_range, stateless, reason_count };
14
15// D3D_PRIMITIVE_TOPOLOGY values whose Vulkan dynamic topology (or rectangle-list geometry-stage variant) needs no CPU
16// vertex/index-count expansion at prepare time: POINTLIST(1), LINELIST(2), LINESTRIP(3), TRIANGLELIST(4),
17// TRIANGLESTRIP(5), *_ADJ(10..13), and console RECTLIST(17). UNDEFINED(0), QUADLIST(19), and patch lists remain skipped.
18inline constexpr bool topology_supported(std::uint32_t value) {
19 return (value >= 1 && value <= 5) || (value >= 10 && value <= 13) || value == 17;
20}
21
22inline constexpr const char* reason_name(Reason reason) {
23 constexpr const char* names[]{"compound signature", "opt-out", "missing pipeline", "missing root signature",
24 "empty viewport", "mesh indirect", "topology", "drawIndirectFirstInstance", "missing Vulkan entry point",
25 "robust sized index binding", "maxDrawIndirectCount", "multiDrawIndirect", "drawIndirectCount",
26 "counted draw requires maxDrawIndirectCount == UINT32_MAX", "argument buffer lacks indirect creation usage",
27 "count buffer lacks indirect creation usage", "nonunit vertex divisor", "pipeline pending",
28 "invalid index view", "index view outside buffer or misaligned", "legacy command has no graphics state"};
29 static_assert(sizeof(names) / sizeof(*names) == reason_count);
30 return static_cast<unsigned>(reason) < reason_count ? names[reason] : "unknown";
31}
32
33inline constexpr const char* reason_tag(Reason reason) {
34 constexpr const char* tags[]{"compound", "disabled", "pipeline", "root_layout", "viewport", "mesh", "topology",
35 "first_instance", "entry", "robust_index", "count_limit", "multi_draw", "count_feature", "raw_count_limit",
36 "argument_usage", "count_usage", "divisor", "pending_pipeline", "index_view", "index_range", "stateless"};
37 static_assert(sizeof(tags) / sizeof(*tags) == reason_count);
38 return static_cast<unsigned>(reason) < reason_count ? tags[reason] : "unknown";
39}
40
8struct Counts { 41struct Counts {
9 std::atomic<unsigned long long> values[4]{}; 42 std::atomic<unsigned long long> values[4]{};
10 void report() const { 43 std::atomic<unsigned long long> by_reason[reason_count]{};
11 std::fprintf(stderr, "[rt] indirect graphics: recorded=%llu emitted=%llu record_skips=%llu replay_skips=%llu\n", 44 void report(std::FILE* out = stderr) const {
12 values[0].load(), values[1].load(), values[2].load(), values[3].load()); 45 char line[1280];
46 int pos = std::snprintf(
47 line, sizeof(line),
48 "[rt] indirect graphics: recorded=%llu emitted=%llu record_skips=%llu replay_skips=%llu",
49 values[0].load(std::memory_order_relaxed), values[1].load(std::memory_order_relaxed),
50 values[2].load(std::memory_order_relaxed), values[3].load(std::memory_order_relaxed));
51 if (pos < 0) return;
52 if (static_cast<std::size_t>(pos) >= sizeof(line)) pos = static_cast<int>(sizeof(line) - 1);
53 bool first_reason = true;
54 for (unsigned i = 0; i < reason_count; ++i) {
55 const auto count = by_reason[i].load(std::memory_order_relaxed);
56 if (!count) continue;
57 const int rem = static_cast<int>(sizeof(line)) - pos;
58 if (rem <= 2) break;
59 const int n = std::snprintf(line + pos, static_cast<std::size_t>(rem), "%s%s=%llu",
60 first_reason ? " [" : ", ",
61 reason_tag(static_cast<Reason>(i)), count);
62 if (n <= 0) break;
63 pos += (n < rem) ? n : (rem - 1);
64 first_reason = false;
65 }
66 if (!first_reason && static_cast<std::size_t>(pos) + 1 < sizeof(line)) line[pos++] = ']';
67 std::fprintf(out, "%.*s\n", pos, line);
13 } 68 }
14 ~Counts() { 69 ~Counts() {
15 for (const auto& value : values) { 70 for (const auto& value : values) {
16 if (value.load()) { 71 if (value.load(std::memory_order_relaxed)) {
17 report(); 72 report();
18 break; 73 break;
19 } 74 }
20 } 75 }
21 } 76 }
22}; 77};
78
79inline Counts& counts() {
80 static Counts instance;
81 return instance;
82}
83
84inline unsigned long long reason_skips(Reason reason) {
85 return static_cast<unsigned>(reason) < reason_count
86 ? counts().by_reason[reason].load(std::memory_order_relaxed)
87 : 0ull;
88}
89
23inline void note(Event event) { 90inline void note(Event event) {
24 static Counts counts; 91 auto& c = counts();
25 const auto n = 1 + counts.values[static_cast<unsigned>(event)].fetch_add(1, std::memory_order_relaxed); 92 const auto n = 1 + c.values[static_cast<unsigned>(event)].fetch_add(1, std::memory_order_relaxed);
26 if ((n & (n - 1)) == 0) counts.report(); 93 if ((n & (n - 1)) == 0) c.report();
27} 94}
28// One flag per reason, shared across resolver instantiations. 95
29enum Reason { compound, disabled, pipeline, root_layout, viewport, mesh, topology, first_instance, entry, robust_index,
30 count_limit, multi_draw, count_feature, raw_count_limit, argument_usage, count_usage,
31 divisor, pending_pipeline, index_view, index_range, stateless, reason_count };
32inline void skip(Event event, Reason reason) { 96inline void skip(Event event, Reason reason) {
33 static constexpr const char* names[]{"compound signature", "opt-out", "missing pipeline", "missing root signature", 97 if (static_cast<unsigned>(reason) >= reason_count) return;
34 "empty viewport", "mesh indirect", "topology", "drawIndirectFirstInstance", "missing Vulkan entry point",
35 "robust sized index binding", "maxDrawIndirectCount", "multiDrawIndirect", "drawIndirectCount",
36 "counted draw requires maxDrawIndirectCount == UINT32_MAX", "argument buffer lacks indirect creation usage",
37 "count buffer lacks indirect creation usage", "nonunit vertex divisor", "pipeline pending",
38 "invalid index view", "index view outside buffer or misaligned", "legacy command has no graphics state"};
39 static_assert(sizeof(names) / sizeof(*names) == reason_count);
40 static std::atomic_flag shown[reason_count]{}; 98 static std::atomic_flag shown[reason_count]{};
41 if (!shown[reason].test_and_set(std::memory_order_relaxed)) 99 if (!shown[reason].test_and_set(std::memory_order_relaxed))
42 std::fprintf(stderr, "[rt] indirect graphics skipped: %s\n", names[reason]); 100 std::fprintf(stderr, "[rt] indirect graphics skipped: %s\n", reason_name(reason));
101 counts().by_reason[reason].fetch_add(1, std::memory_order_relaxed);
43 note(event); 102 note(event);
44} 103}
45} 104}
diff --git a/runtime/src/large_module_gate.h b/runtime/src/large_module_gate.h
new file mode 100644
index 000000000..f66420bc2
--- /dev/null
+++ b/runtime/src/large_module_gate.h
@@ -0,0 +1,293 @@
1// How many large SPIR-V modules vk_pipeline_check and the runtime let into the driver at once, by a memory budget.
2//
3// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute
4// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB.
5// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6
6// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin
7// over the measurement. The NVIDIA 621.24 driver (RTX 3080) took 85 to 131 bytes per SPIR-V byte for synthetic compute
8// modules of 128 KiB to 4 MiB (docs/d3d12_vulkan.md, "Large pipelines").
9//
10// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas
11// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each
12// large module.
13#pragma once
14
15#include <algorithm>
16#include <condition_variable>
17#include <cstddef>
18#include <cstdint>
19#include <cstdio>
20#include <functional>
21#include <list>
22#include <mutex>
23#include <optional>
24#include <string>
25#include <utility>
26
27#ifdef _WIN32
28#ifndef NOMINMAX
29#define NOMINMAX
30#endif
31#include <windows.h>
32#endif
33#if defined(__GLIBC__)
34#include <malloc.h>
35#endif
36
37namespace leonida {
38
39inline constexpr uint64_t kBytesPerSpirvByte = 512;
40
41inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; }
42
43#if defined(__linux__)
44// The first unsigned number in a file ("max" and unreadable files give no value).
45inline bool read_u64_file(const std::string& path, uint64_t& value) {
46 std::FILE* f = std::fopen(path.c_str(), "r");
47 if (!f) return false;
48 unsigned long long v = 0;
49 const bool ok = std::fscanf(f, "%llu", &v) == 1;
50 std::fclose(f);
51 value = v;
52 return ok;
53}
54
55// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or
56// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests.
57inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup",
58 const std::string& cgroup_root = "/sys/fs/cgroup") {
59 std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r");
60 if (!f) return UINT64_MAX;
61 char line[4096];
62 std::string rel;
63 while (std::fgets(line, sizeof(line), f)) {
64 std::string l(line);
65 if (l.rfind("0::", 0) == 0) { // the cgroup v2 line
66 rel = l.substr(3);
67 while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back();
68 break;
69 }
70 }
71 std::fclose(f);
72 uint64_t room = UINT64_MAX;
73 for (std::string dir = rel; !dir.empty();) {
74 // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root.
75 const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir;
76 uint64_t max = 0, current = 0;
77 if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current))
78 room = std::min(room, max > current ? max - current : 0);
79 const auto slash = dir.find_last_of('/');
80 if (dir == "/" || slash == std::string::npos) break;
81 dir.resize(slash == 0 ? 1 : slash);
82 }
83 return room;
84}
85#endif
86
87// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate).
88inline uint64_t available_memory_bytes() {
89#ifdef _WIN32
90 MEMORYSTATUSEX status{};
91 status.dwLength = sizeof(status);
92 return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0;
93#elif defined(__linux__)
94 std::FILE* f = std::fopen("/proc/meminfo", "r");
95 if (!f) return 0;
96 char line[256];
97 unsigned long long kb = 0;
98 bool found = false;
99 while (std::fgets(line, sizeof(line), f))
100 if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; }
101 std::fclose(f);
102 if (!found) return 0;
103 const uint64_t room = cgroup_memory_room();
104 return std::max<uint64_t>(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown"
105#else
106 return 0;
107#endif
108}
109
110// What large compiles may use of the free RAM and of the room under the commit limit: three quarters of the smaller. (On
111// Windows an allocation that the limit has no room for fails, whatever RAM is free.)
112inline uint64_t large_compile_share(uint64_t free_ram, uint64_t commit_room) {
113 return std::min(free_ram, commit_room) / 4 * 3;
114}
115
116// The same of the memory that is free at this moment. 0 when it is unknown: then they compile one at a time.
117inline uint64_t large_compile_budget_bytes() {
118#ifdef _WIN32
119 MEMORYSTATUSEX status{};
120 status.dwLength = sizeof(status);
121 if (!GlobalMemoryStatusEx(&status)) return 0;
122 return large_compile_share(status.ullAvailPhys, status.ullAvailPageFile);
123#else
124 return large_compile_share(available_memory_bytes(), UINT64_MAX);
125#endif
126}
127
128// LEONIDA_BIG_COMPILE_BUDGET_MB: a fixed budget in MiB instead of the share of the free memory (0: one at a time). Unset
129// or empty, and text that is not a number: none. `valid` is false for the latter.
130struct LargeCompileBudget {
131 std::optional<uint64_t> fixed{};
132 bool valid = true;
133};
134
135inline LargeCompileBudget large_compile_budget(const char* text) {
136 if (!text || !*text) return {};
137 uint64_t mib = 0;
138 for (const char* c = text; *c; ++c) {
139 if (*c < '0' || *c > '9') return {std::nullopt, false};
140 mib = std::min<uint64_t>(mib * 10 + uint64_t(*c - '0'), UINT64_MAX >> 20);
141 }
142 return {mib << 20, true};
143}
144
145// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it).
146inline void release_free_memory() {
147#if defined(__GLIBC__)
148 malloc_trim(0);
149#endif
150}
151
152// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in
153// when none is, so a module bigger than the whole budget still compiles (alone among the large ones).
154//
155// The second constructor is the runtime's: the budget is read again whenever a place is given or returned, and the
156// modules get in in the order they came, those a submission waits for (demand) before the others (speculative). While the
157// first in line does not fit, the next behind it that does may pass, as long as all that have passed it would fit the
158// budget together with it. So, with the budget as it is, it waits at most for those that were in when it became the first,
159// however many come after it, and one larger than the budget is not passed. A speculative one gets in only while no demand
160// waits and no submission has a Demand, and only within a quarter of the budget, so that a demand finds the rest free. An
161// estimate counts in full until its module leaves, although the driver has allocated part of it by then and the budget is
162// that much smaller: what is in has not taken all it is going to.
163class LargeModuleGate {
164public:
165 enum class Work { demand, speculative };
166
167 LargeModuleGate(uint64_t budget, unsigned max_inflight)
168 : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {}
169 explicit LargeModuleGate(std::function<uint64_t()> budget)
170 : budget_(0), max_inflight_(UINT32_MAX), read_budget_(std::move(budget)) {}
171
172 bool admits(uint64_t estimate) const {
173 std::lock_guard<std::mutex> g(mu_);
174 return admits_locked(estimate, budget());
175 }
176 void enter(uint64_t estimate, Work work = Work::demand) {
177 std::unique_lock<std::mutex> l(mu_);
178 if (!read_budget_) {
179 cv_.wait(l, [&] { return admits_locked(estimate, limit_for(work)); });
180 } else {
181 auto& queue = waiting_[work == Work::demand ? 0 : 1];
182 const auto me = queue.insert(queue.end(), Waiter{estimate});
183 cv_.wait(l, [&] {
184 return (work == Work::demand || (waiting_[0].empty() && !demanded_)) && next_locked(work) == &*me;
185 });
186 if (me != queue.begin()) queue.front().passed += estimate;
187 queue.erase(me);
188 }
189 used_ += estimate;
190 ++inflight_;
191 if (!waiting_[0].empty() || !waiting_[1].empty()) cv_.notify_all(); // the next in the queue may fit as well
192 }
193 void leave(uint64_t estimate) {
194 {
195 std::lock_guard<std::mutex> g(mu_);
196 used_ -= estimate;
197 --inflight_;
198 }
199 cv_.notify_all();
200 }
201 unsigned inflight() const {
202 std::lock_guard<std::mutex> g(mu_);
203 return inflight_;
204 }
205 size_t waiting(Work work) const { // in order: the threads in enter(), with a budget that is read
206 std::lock_guard<std::mutex> g(mu_);
207 return waiting_[work == Work::demand ? 0 : 1].size();
208 }
209 uint64_t budget() const { return read_budget_ ? read_budget_() : budget_; }
210 unsigned max_inflight() const { return max_inflight_; }
211
212 // A submission that has large modules to build: until it ends, the places that its modules leave between one and the
213 // next are not taken by speculative ones.
214 class Demand {
215 public:
216 explicit Demand(LargeModuleGate& gate) : gate_(gate) {
217 std::lock_guard<std::mutex> g(gate_.mu_);
218 ++gate_.demanded_;
219 }
220 ~Demand() {
221 {
222 std::lock_guard<std::mutex> g(gate_.mu_);
223 --gate_.demanded_;
224 }
225 gate_.cv_.notify_all();
226 }
227 Demand(const Demand&) = delete;
228 Demand& operator=(const Demand&) = delete;
229
230 private:
231 LargeModuleGate& gate_;
232 };
233
234 // Holds a place from construction until destruction (or release()), then hands freed memory back.
235 class Ticket {
236 public:
237 Ticket() = default;
238 Ticket(LargeModuleGate& gate, uint64_t estimate, Work work = Work::demand) : gate_(&gate), estimate_(estimate) {
239 gate.enter(estimate, work);
240 }
241 Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; }
242 Ticket& operator=(Ticket&& o) noexcept {
243 if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; }
244 return *this;
245 }
246 Ticket(const Ticket&) = delete;
247 Ticket& operator=(const Ticket&) = delete;
248 ~Ticket() { release(); }
249 void release() {
250 if (!gate_) return;
251 gate_->leave(estimate_);
252 gate_ = nullptr;
253 release_free_memory();
254 }
255 private:
256 LargeModuleGate* gate_ = nullptr;
257 uint64_t estimate_ = 0;
258 };
259
260private:
261 struct Waiter {
262 uint64_t estimate;
263 uint64_t passed = 0; // the estimates of those that have passed it while it was the first in line
264 };
265
266 uint64_t limit_for(Work work) const { return work == Work::demand ? budget() : budget() / 4; }
267 bool admits_locked(uint64_t estimate, uint64_t limit) const {
268 return inflight_ == 0 || (inflight_ < max_inflight_ && used_ + estimate <= limit);
269 }
270 // The one in line that gets in now, if any: the first, or else the first that fits and may pass it.
271 const Waiter* next_locked(Work work) const {
272 const auto& queue = waiting_[work == Work::demand ? 0 : 1];
273 const uint64_t limit = limit_for(work);
274 for (const Waiter& w : queue) {
275 const Waiter& first = queue.front();
276 if (&w != &first && first.passed + w.estimate + first.estimate > limit) continue;
277 if (admits_locked(w.estimate, limit)) return &w;
278 }
279 return nullptr;
280 }
281
282 const uint64_t budget_;
283 const unsigned max_inflight_;
284 const std::function<uint64_t()> read_budget_;
285 mutable std::mutex mu_;
286 std::condition_variable cv_;
287 std::list<Waiter> waiting_[2]; // demand, speculative: one for each thread in enter(), in the order they came
288 uint64_t used_ = 0;
289 unsigned inflight_ = 0;
290 unsigned demanded_ = 0; // the Demands
291};
292
293} // namespace leonida
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index f01997775..21551e948 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -9,6 +9,13 @@
9// gta6rt --init <image> [--game-dir DIR] [--overlay DIR] 9// gta6rt --init <image> [--game-dir DIR] [--overlay DIR]
10// The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. 10// The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run.
11// 11//
12// gta6rt --precompile-pipelines [--threads N] [--big-threads N] [--big-bytes N] [--all] [--smallest-first]
13// [--limit N] [--min-bytes N] [--max-bytes N] [--filter PART]... [--list]
14// No game: creates the Vulkan device as --run does and builds every compute pipeline of the shader library
15// (LEONIDA_SHADERS) into the pipeline journal and the driver's cache, so a title's first dispatch of a large one
16// does not stall it. Resumable: entries already journaled are skipped (--all: built anyway). See
17// shims/d3d12_precompile.h.
18//
12// gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE] [-- game arguments...] 19// gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE] [-- game arguments...]
13// The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and 20// The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and
14// command line are <exe name> plus the arguments after "--"; exit/ExitProcess from the game end the run 21// command line are <exe name> plus the arguments after "--"; exit/ExitProcess from the game end the run
@@ -24,6 +31,7 @@
24#include <exception> 31#include <exception>
25#include <filesystem> 32#include <filesystem>
26#include <map> 33#include <map>
34#include <mutex>
27#include <string> 35#include <string>
28#include <system_error> 36#include <system_error>
29#include <vector> 37#include <vector>
@@ -32,24 +40,51 @@
32 40
33namespace { 41namespace {
34 42
35// The retail executable (1.0.2.1) runs a hang watchdog thread (function at RVA 0x2215a60): when the game's main loop 43// The retail title runs a hang watchdog thread: when the game's main loop has not set its "kick" byte for 30
36// has not set its "kick" byte (RVA 0x71b6331) for 30 one-second ticks, it calls a crash callback and then writes to 44// one-second ticks, it calls a crash callback and then writes to address 0 (`movl $0, 0`). Under the runtime the
37// address 0 (`movl $0, 0` at RVA 0x2215c35). Under the runtime the game thread can legitimately stall for longer than 45// game thread can legitimately stall for longer than that, e.g. while the driver compiles pipelines against a cold
38// that, e.g. while the driver compiles pipelines against a cold cache (first boot after a driver update), and the 46// cache (first boot after a driver update), and the title then kills itself. By default the watchdog stays armed, as
39// title then kills itself. By default the watchdog stays armed, as on the console. With LEONIDA_TITLE_WATCHDOG=0, and 47// on the console. LEONIDA_TITLE_WATCHDOG=0 asks to keep it from firing, as before. The two places that takes are
40// only when that exact trap instruction sits where it does in this build, a runtime thread sets the kick byte twice a 48// measured locally and not kept in the repository: LEONIDA_TITLE_WATCHDOG_KICK="<trap RVA>,<kick RVA>" (hex) names
41// second so the title's watchdog never fires. 49// them, and only with both variables, and only when that exact trap instruction sits at the first RVA, does a
42constexpr std::uint32_t kWatchdogTrapRva = 0x2215c35; 50// runtime thread set the byte at the second twice a second, so the title's watchdog never fires. Either variable
43constexpr std::uint32_t kWatchdogKickRva = 0x71b6331; 51// alone leaves the watchdog armed and says so once.
44constexpr unsigned char kWatchdogTrap[] = {0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0}; // movl $0, 0x0 52constexpr unsigned char kWatchdogTrap[] = {0xC7, 0x04, 0x25, 0, 0, 0, 0, 0, 0, 0, 0}; // movl $0, 0x0
45 53
54bool watchdog_rvas(std::uint32_t& trap_rva, std::uint32_t& kick_rva) {
55 char value[64]{};
56 const DWORD n = GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG_KICK", value, sizeof(value));
57 if (!n || n >= sizeof(value)) return false;
58 char* rest = nullptr;
59 const unsigned long long trap = std::strtoull(value, &rest, 16);
60 if (!rest || *rest != ',') return false;
61 const unsigned long long kick = std::strtoull(rest + 1, &rest, 16);
62 if (!rest || *rest || !trap || !kick || trap > 0xFFFFFFFFull || kick > 0xFFFFFFFFull) return false;
63 trap_rva = static_cast<std::uint32_t>(trap);
64 kick_rva = static_cast<std::uint32_t>(kick);
65 return true;
66}
67
46void keep_title_watchdog_kicked(std::uint8_t* base) { 68void keep_title_watchdog_kicked(std::uint8_t* base) {
47 char value[4]{}; 69 char keep[4]{};
48 if (GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", value, sizeof(value)) != 1 || value[0] != '0') return; 70 const bool disarm = GetEnvironmentVariableA("LEONIDA_TITLE_WATCHDOG", keep, sizeof(keep)) == 1 && keep[0] == '0';
71 std::uint32_t kWatchdogTrapRva = 0, kWatchdogKickRva = 0;
72 const bool named = watchdog_rvas(kWatchdogTrapRva, kWatchdogKickRva);
73 if (!disarm) {
74 if (named)
75 std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_WATCHDOG_KICK is set but LEONIDA_TITLE_WATCHDOG is not 0;"
76 " the title's hang watchdog stays armed\n");
77 return;
78 }
79 if (!named) {
80 std::fprintf(stderr, "[rt] loader: LEONIDA_TITLE_WATCHDOG=0 needs LEONIDA_TITLE_WATCHDOG_KICK=<trap RVA>,"
81 "<kick RVA> (hex); the title's hang watchdog stays armed\n");
82 return;
83 }
49 MEMORY_BASIC_INFORMATION trap{}, kick{}; 84 MEMORY_BASIC_INFORMATION trap{}, kick{};
50 if (!VirtualQuery(base + kWatchdogTrapRva, &trap, sizeof(trap)) || trap.State != MEM_COMMIT || 85 if (!VirtualQuery(base + kWatchdogTrapRva, &trap, sizeof(trap)) || trap.State != MEM_COMMIT ||
51 std::memcmp(base + kWatchdogTrapRva, kWatchdogTrap, sizeof(kWatchdogTrap)) != 0) 86 std::memcmp(base + kWatchdogTrapRva, kWatchdogTrap, sizeof(kWatchdogTrap)) != 0)
52 return; // not the build this was measured on: leave the title's watchdog alone 87 return; // not the trap the RVAs name: leave the title's watchdog alone
53 const DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; 88 const DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
54 if (!VirtualQuery(base + kWatchdogKickRva, &kick, sizeof(kick)) || kick.State != MEM_COMMIT || 89 if (!VirtualQuery(base + kWatchdogKickRva, &kick, sizeof(kick)) || kick.State != MEM_COMMIT ||
55 !(kick.Protect & writable)) 90 !(kick.Protect & writable))
@@ -71,7 +106,7 @@ void keep_title_watchdog_kicked(std::uint8_t* base) {
71 } 106 }
72} 107}
73 108
74// LEONIDA_PEEK="0x9e1dac0:3,0x7446510,0x98f828c" (diagnostic): a thread prints the 8-byte values at these RVAs of the 109// LEONIDA_PEEK="<rva>:3,<rva>,<rva>" (diagnostic): a thread prints the 8-byte values at these RVAs of the
75// title's image (":n" = n consecutive values, at most 32; "RVA>OFF" reads through the pointer stored at the RVA, at 110// title's image (":n" = n consecutive values, at most 32; "RVA>OFF" reads through the pointer stored at the RVA, at
76// pointer + OFF, both hex) every LEONIDA_PEEK_SECONDS (default 10). For answering "what does this 111// pointer + OFF, both hex) every LEONIDA_PEEK_SECONDS (default 10). For answering "what does this
77// global hold at run time" without a debugger: the reverse-engineering notes (docs/re/requests.md) ask for exactly 112// global hold at run time" without a debugger: the reverse-engineering notes (docs/re/requests.md) ask for exactly
@@ -148,6 +183,7 @@ void start_title_peek(std::uint8_t* base) {
148#include "mods.h" 183#include "mods.h"
149#include "pe_loader.h" 184#include "pe_loader.h"
150#include "thread_stacks.h" 185#include "thread_stacks.h"
186#include "dev_overlay.h"
151#include "thread_sampler.h" 187#include "thread_sampler.h"
152#include "title_page_watch.h" 188#include "title_page_watch.h"
153#include "title_geometry_watch.h" 189#include "title_geometry_watch.h"
@@ -155,7 +191,9 @@ void start_title_peek(std::uint8_t* base) {
155#include "../shims/d3d12_xs_device.h" 191#include "../shims/d3d12_xs_device.h"
156#include "../shims/file_system.h" 192#include "../shims/file_system.h"
157#ifdef LEONIDA_VULKAN_DEVICE 193#ifdef LEONIDA_VULKAN_DEVICE
194#include "vulkan_device_fault.h"
158#include "../shims/d3d12_compile_exit.h" 195#include "../shims/d3d12_compile_exit.h"
196#include "../shims/d3d12_precompile.h"
159#include "../shims/package_splash.h" 197#include "../shims/package_splash.h"
160#endif 198#endif
161#include "../shims/process_shim.h" 199#include "../shims/process_shim.h"
@@ -196,7 +234,9 @@ bool configure_first_run_ui(const std::filesystem::path& package, std::filesyste
196 {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"}, 234 {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"},
197 {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"}, 235 {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"},
198 {L"LEONIDA_FRAME_PACING", L"1"}, 236 {L"LEONIDA_FRAME_PACING", L"1"},
199 {L"LEONIDA_KEYBOARD_PAD", L"always"}, 237 // Focused, not always: keys typed into another window must not press anything on a consent page.
238 // Scripted presses (LEONIDA_INPUT_SCRIPT) still run while the window is unfocused.
239 {L"LEONIDA_KEYBOARD_PAD", L"1"},
200 }; 240 };
201 for (const auto& setting : settings) { 241 for (const auto& setting : settings) {
202 if (!set_default(setting.name, setting.value)) return false; 242 if (!set_default(setting.name, setting.value)) return false;
@@ -221,25 +261,119 @@ int usage() {
221 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" 261 "usage: gta6rt --dry-run <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n"
222 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n" 262 " gta6rt --init <image> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n"
223 " gta6rt --first-run-ui <exe> [--game-dir DIR] [--overlay DIR] [--trace FILE]\n" 263 " gta6rt --first-run-ui <exe> [--game-dir DIR] [--overlay DIR] [--trace FILE]\n"
224 " gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n"); 264 " gta6rt --run <exe> [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n"
265 " 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"
266 " gta6rt --compile-server [--parent PID] [--threads N] [--idle-threads N] [--idle-exit SECONDS]\n");
225 return 2; 267 return 2;
226} 268}
227 269
270#ifdef LEONIDA_VULKAN_DEVICE
271// gta6rt --precompile-pipelines ...: argv[1] is the mode.
272int precompile_main(int argc, wchar_t** argv) {
273 rt::d3d12::PrecompileOptions options;
274 const auto number = [&](int& i, auto& out) {
275 if (i + 1 >= argc) return false;
276 wchar_t* end = nullptr;
277 const unsigned long long v = std::wcstoull(argv[++i], &end, 10);
278 if (!end || *end) return false;
279 out = static_cast<std::remove_reference_t<decltype(out)>>(v);
280 return true;
281 };
282 for (int i = 2; i < argc; ++i) {
283 const std::wstring a = argv[i];
284 bool ok = true;
285 if (a == L"--threads") ok = number(i, options.threads);
286 else if (a == L"--big-threads") ok = number(i, options.big_threads);
287 else if (a == L"--big-bytes") ok = number(i, options.big_bytes);
288 else if (a == L"--limit") ok = number(i, options.limit);
289 else if (a == L"--min-bytes") ok = number(i, options.min_bytes);
290 else if (a == L"--max-bytes") ok = number(i, options.max_bytes);
291 else if (a == L"--all") options.rebuild = true;
292 else if (a == L"--smallest-first") options.smallest_first = true;
293 else if (a == L"--list") options.dry_run = true;
294 else if (a == L"--via-helper") options.via_helper = true;
295 else if (a == L"--filter" && i + 1 < argc) {
296 const std::wstring part = argv[++i];
297 options.filters.emplace_back(part.begin(), part.end()); // library names are ASCII
298 } else ok = false;
299 if (!ok) return usage();
300 }
301 return rt::d3d12::precompile_compute_pipelines(options);
302}
303
304// gta6rt --compile-server [--parent PID] [--threads N] [--idle-threads N] [--idle-exit SECONDS]
305// (shims/d3d12_compile_helper.h).
306int compile_server_main(int argc, wchar_t** argv) {
307 rt::d3d12::CompileServerOptions options;
308 for (int i = 2; i < argc; ++i) {
309 const std::wstring a = argv[i];
310 if (i + 1 >= argc) return usage();
311 wchar_t* end = nullptr;
312 const unsigned long long v = std::wcstoull(argv[++i], &end, 10);
313 if (!end || *end) return usage();
314 if (a == L"--parent") options.parent_pid = static_cast<unsigned long>(v);
315 else if (a == L"--threads") options.threads = static_cast<unsigned>(v);
316 else if (a == L"--idle-threads") options.idle_threads = static_cast<unsigned>(v);
317 else if (a == L"--idle-exit") options.idle_exit_s = static_cast<unsigned>(v);
318 else return usage();
319 }
320 return rt::d3d12::compile_server(options);
321}
322#endif
323
228} // namespace 324} // namespace
229 325
230#ifdef LEONIDA_VULKAN_DEVICE 326#ifdef LEONIDA_VULKAN_DEVICE
231// The run ends with the title's Vulkan device alive, so no ~Device stops the background pipeline compiler: stop it 327// The run ends with the title's Vulkan device alive, so no ~Device stops the background pipeline compiler: stop it
232// here, before ExitProcess ends its thread, maybe inside the driver's compiler (rt::d3d12::stop_pipeline_compiles). 328// here, before ExitProcess ends its thread, maybe inside the driver's compiler (rt::d3d12::stop_pipeline_compiles).
233constexpr unsigned kExitCompileWaitMs = 2000; // a console close gives the whole process 5 s 329constexpr unsigned kExitCompileWaitMs = 2000; // a console close gives the whole process 5 s
330// For a build still running on a title thread, then the session cache write (rt::d3d12::save_pipeline_caches_at_exit).
331constexpr unsigned kExitCacheWaitMs = 1000;
234 332
235static BOOL WINAPI stop_compiles_on_console_exit(DWORD event) { 333static BOOL WINAPI stop_compiles_on_console_exit(DWORD event) {
236 if (event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT || event == CTRL_CLOSE_EVENT) { 334 if (event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT || event == CTRL_CLOSE_EVENT) {
237 rt::d3d12_xs::stop_list_values(500); // as at the run's end: no list-value thread cut off inside the layer 335 rt::d3d12_xs::stop_list_values(500); // as at the run's end: no list-value thread cut off inside the layer
238 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); 336 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
337 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
239 } 338 }
240 return FALSE; // the next handler (the default one: ExitProcess) ends the process, as before 339 return FALSE; // the next handler (the default one: ExitProcess) ends the process, as before
241} 340}
242 341
342// A run that ends in an exception nothing handles (a fault in the title or one of its DLLs, the int3 after a device
343// loss) would otherwise keep none of the pipelines it compiled, and the next boot builds them all again. The device is
344// left alone apart from that write; the exception then goes on as before (the previous filter, or Windows' own
345// handling), so the exit code is the exception's. Not for a stack overflow: no stack is left to write with.
346static LPTOP_LEVEL_EXCEPTION_FILTER previous_fatal_filter = nullptr;
347// The retail title installs a filter of its own (SetUnhandledExceptionFilter from api-ms-win-core-errorhandling),
348// which replaced this one and ended the process without it (measured: a title fault at 354 s wrote nothing). Its
349// call is served here instead: this filter stays installed and hands the exception to the title's, as Windows would.
350static void* volatile title_fatal_filter = nullptr;
351
352static LPTOP_LEVEL_EXCEPTION_FILTER WINAPI title_set_unhandled_exception_filter(LPTOP_LEVEL_EXCEPTION_FILTER filter) {
353 return reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>(
354 InterlockedExchangePointer(&title_fatal_filter, reinterpret_cast<void*>(filter)));
355}
356
357static LONG WINAPI save_caches_on_fatal_exception(EXCEPTION_POINTERS* info) {
358 const DWORD code = info && info->ExceptionRecord ? info->ExceptionRecord->ExceptionCode : 0;
359 if (code != EXCEPTION_STACK_OVERFLOW) {
360 // Several title threads can fault at once (measured: eight within a second). The first writes; the others
361 // wait here for it, so none of them reaches the title's filter, which may end the process, mid-write.
362 static std::once_flag once;
363 std::call_once(once, [code] {
364 std::fprintf(stderr, "[rt] unhandled exception 0x%08lx: writing the session pipeline cache before the "
365 "process ends\n", static_cast<unsigned long>(code));
366 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
367 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
368 std::fflush(stderr);
369 });
370 }
371 if (auto* title = reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>(
372 InterlockedCompareExchangePointer(&title_fatal_filter, nullptr, nullptr)))
373 return title(info);
374 return previous_fatal_filter ? previous_fatal_filter(info) : EXCEPTION_CONTINUE_SEARCH;
375}
376
243static BOOL WINAPI show_package_window(HWND window, int command) { 377static BOOL WINAPI show_package_window(HWND window, int command) {
244 const BOOL previous = ShowWindow(window, command); 378 const BOOL previous = ShowWindow(window, command);
245 const DWORD error = GetLastError(); 379 const DWORD error = GetLastError();
@@ -251,6 +385,10 @@ static BOOL WINAPI show_package_window(HWND window, int command) {
251#endif 385#endif
252 386
253int wmain(int argc, wchar_t** argv) { 387int wmain(int argc, wchar_t** argv) {
388#ifdef LEONIDA_VULKAN_DEVICE
389 if (argc > 1 && std::wstring(argv[1]) == L"--precompile-pipelines") return precompile_main(argc, argv);
390 if (argc > 1 && std::wstring(argv[1]) == L"--compile-server") return compile_server_main(argc, argv);
391#endif
254 std::filesystem::path image, game_dir, overlay_dir, mods_dir; 392 std::filesystem::path image, game_dir, overlay_dir, mods_dir;
255 uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash 393 uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash
256 int archetype_lookup_arg = 0; 394 int archetype_lookup_arg = 0;
@@ -347,6 +485,13 @@ int wmain(int argc, wchar_t** argv) {
347 rt::fs::configure(game_dir, overlay_dir); 485 rt::fs::configure(game_dir, overlay_dir);
348#ifdef LEONIDA_VULKAN_DEVICE 486#ifdef LEONIDA_VULKAN_DEVICE
349 if (run) { 487 if (run) {
488 // Before the image is loaded, so its import binds here (save_caches_on_fatal_exception).
489 const rt::shims::Entry filter_imports[] = {
490 {"api-ms-win-core-errorhandling-l1-1-0.dll", "SetUnhandledExceptionFilter",
491 reinterpret_cast<void*>(&title_set_unhandled_exception_filter)},
492 {"kernel32.dll", "SetUnhandledExceptionFilter", reinterpret_cast<void*>(&title_set_unhandled_exception_filter)},
493 };
494 rt::shims::Table{filter_imports, std::size(filter_imports)};
350 rt::package_splash::configure(game_dir); 495 rt::package_splash::configure(game_dir);
351 if (rt::package_splash::configured()) { 496 if (rt::package_splash::configured()) {
352 const rt::shims::Entry window_imports[] = { 497 const rt::shims::Entry window_imports[] = {
@@ -388,6 +533,8 @@ int wmain(int argc, wchar_t** argv) {
388 rt::d3d12_trace::set_enabled(trace_d3d12); 533 rt::d3d12_trace::set_enabled(trace_d3d12);
389 // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. 534 // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first.
390 rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); 535 rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range);
536 if (rt::xmem::slot31_runs() && rt::xmem::queue_page_mappings_enabled())
537 rt::d3d12_xs::set_copy_page_mappings_hook(&rt::xmem::copy_page_mappings);
391 // So do the file shims' reads, whose kernel writes do not fault them in: on ERROR_NOACCESS (title_page_watch.h). 538 // So do the file shims' reads, whose kernel writes do not fault them in: on ERROR_NOACCESS (title_page_watch.h).
392 leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases); 539 leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases);
393 leonida::kernel_writes::set_committer(&rt::xmem::commit_physical_range); 540 leonida::kernel_writes::set_committer(&rt::xmem::commit_physical_range);
@@ -493,7 +640,9 @@ int wmain(int argc, wchar_t** argv) {
493 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); 640 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str());
494 return 1; 641 return 1;
495 } 642 }
496 const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " + overlay_dir.native(); 643 const std::filesystem::path scratch_dir = rt::fs::scratch_dir();
644 const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " +
645 overlay_dir.native() + L", T: -> " + scratch_dir.native();
497 const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 646 const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
498 DWORD mode; 647 DWORD mode;
499 bool printed = false; 648 bool printed = false;
@@ -506,18 +655,25 @@ int wmain(int argc, wchar_t** argv) {
506 if (!printed) { 655 if (!printed) {
507 const auto game = game_dir.u8string(); 656 const auto game = game_dir.u8string();
508 const auto overlay = overlay_dir.u8string(); 657 const auto overlay = overlay_dir.u8string();
509 std::printf("console paths: GAME: -> %s, writes -> %s\n", 658 const auto scratch = scratch_dir.u8string();
510 reinterpret_cast<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str())); 659 std::printf("console paths: GAME: -> %s, writes -> %s, T: -> %s\n",
660 reinterpret_cast<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str()),
661 reinterpret_cast<const char*>(scratch.c_str()));
511 } 662 }
512 std::printf("running %s\n", main_module.name.c_str()); 663 std::printf("running %s\n", main_module.name.c_str());
513 std::fflush(stdout); 664 std::fflush(stdout);
514 keep_title_watchdog_kicked(main_module.base); 665 keep_title_watchdog_kicked(main_module.base);
515 start_title_peek(main_module.base); 666 start_title_peek(main_module.base);
667 leonida::dev_overlay::start(); // LEONIDA_DEV_OVERLAY=1
516 leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic) 668 leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic)
517#ifdef LEONIDA_VULKAN_DEVICE 669#ifdef LEONIDA_VULKAN_DEVICE
518 SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE); 670 SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE);
671 previous_fatal_filter = SetUnhandledExceptionFilter(&save_caches_on_fatal_exception);
519#endif 672#endif
520 int code; 673 int code;
674#ifdef LEONIDA_VULKAN_DEVICE
675 leonida::thread_stack_hook.store(&rt::print_thread_stacks_now, std::memory_order_release);
676#endif
521 { 677 {
522 auto stacks = rt::start_thread_stacks(); 678 auto stacks = rt::start_thread_stacks();
523 code = rt::process::run_entry(main_module.base + main_module.entry_rva); 679 code = rt::process::run_entry(main_module.base + main_module.entry_rva);
@@ -536,6 +692,7 @@ int wmain(int argc, wchar_t** argv) {
536 rt::d3d12_xs::stop_list_values(500); 692 rt::d3d12_xs::stop_list_values(500);
537#ifdef LEONIDA_VULKAN_DEVICE 693#ifdef LEONIDA_VULKAN_DEVICE
538 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); 694 rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
695 rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
539#endif 696#endif
540 rt::cleanup_tls_clones(); 697 rt::cleanup_tls_clones();
541 ExitProcess(static_cast<UINT>(code)); 698 ExitProcess(static_cast<UINT>(code));
diff --git a/runtime/src/memory_figures.h b/runtime/src/memory_figures.h
new file mode 100644
index 000000000..8bf611553
--- /dev/null
+++ b/runtime/src/memory_figures.h
@@ -0,0 +1,147 @@
1#pragma once
2// The memory figures that the title HUD (shims/title_hud.h, LEONIDA_TITLE_HUD) and the dev overlay (dev_overlay.h,
3// LEONIDA_DEV_OVERLAY) both show, and the text for each. Both views use this header, so they show the same figures
4// and the same "n/a" where there is no figure, never a false 0:
5// GPU memory: in use and the budget over the device-local heaps, and in use in the other heaps, from the device's
6// VK_EXT_memory_budget (vulkan_memory_budget.h reads it). The device publishes a reader here (publish_vram_reader)
7// because the overlay runs outside the device, and latest_vram() calls it at most once per refresh_ms.
8// Private memory: the process's commit charge. Wine fills only PagefileUsage, which on Windows 8 and later is the
9// same figure as PrivateUsage.
10// No Vulkan here, and Win32 only under _WIN32, so the overlay's test builds on every host.
11#ifdef _WIN32
12#ifndef NOMINMAX
13#define NOMINMAX
14#endif
15#include <windows.h>
16#include <psapi.h>
17#ifdef _MSC_VER
18#pragma comment(lib, "psapi.lib")
19#endif
20#endif
21
22#include <algorithm>
23#include <chrono>
24#include <cstdint>
25#include <cstdio>
26#include <mutex>
27#include <string>
28
29namespace leonida {
30
31struct VramBudget {
32 // False when there is nothing to show: no VK_EXT_memory_budget on the device, no device, or a device that
33 // reports no budget for any DEVICE_LOCAL heap. The views show "n/a" then, not a 0.
34 bool available = false;
35 std::uint64_t local_usage = 0; // heapUsage summed over the DEVICE_LOCAL heaps
36 std::uint64_t local_budget = 0; // heapBudget summed over the DEVICE_LOCAL heaps
37 std::uint64_t shared_usage = 0; // heapUsage summed over the other heaps: system memory the GPU uses
38};
39
40namespace memory_figures {
41
42inline double gb(std::uint64_t bytes) { return double(bytes) / double(1ull << 30); }
43
44// "VRAM 3.5/16.0 GB +0.5 shared", or "VRAM n/a".
45inline std::string vram_text(const VramBudget& vram) {
46 if (!vram.available) return "VRAM n/a";
47 char text[96];
48 std::snprintf(text, sizeof text, "VRAM %.1f/%.1f GB +%.1f shared", gb(vram.local_usage), gb(vram.local_budget),
49 gb(vram.shared_usage));
50 return text;
51}
52
53struct ProcessMemory {
54 bool read = false; // GetProcessMemoryInfo answered
55 std::uint64_t private_usage = 0, pagefile_usage = 0, working_set = 0;
56};
57
58// The commit charge. PrivateUsage and PagefileUsage are the same figure on Windows 8 and later. Wine's
59// GetProcessMemoryInfo writes only the PROCESS_MEMORY_COUNTERS part, so PrivateUsage reads 0 there.
60inline std::uint64_t private_bytes(const ProcessMemory& memory) {
61 return (std::max)(memory.private_usage, memory.pagefile_usage); // parenthesised: windows.h may define max
62}
63
64// "RAM 2.5 GB (ws 1.0)". "RAM n/a (ws 1.0)" when the private bytes read 0, "RAM n/a" when nothing could be read.
65inline std::string ram_text(const ProcessMemory& memory) {
66 char text[96];
67 if (!memory.read)
68 std::snprintf(text, sizeof text, "RAM n/a");
69 else if (const std::uint64_t bytes = private_bytes(memory); !bytes)
70 std::snprintf(text, sizeof text, "RAM n/a (ws %.1f)", gb(memory.working_set));
71 else
72 std::snprintf(text, sizeof text, "RAM %.1f GB (ws %.1f)", gb(bytes), gb(memory.working_set));
73 return text;
74}
75
76#ifdef _WIN32
77// This process's figures now.
78inline ProcessMemory process_memory() {
79 PROCESS_MEMORY_COUNTERS_EX counters{};
80 counters.cb = sizeof counters;
81 ProcessMemory out;
82 if (!GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&counters),
83 sizeof counters))
84 return out;
85 out.read = true;
86 out.private_usage = counters.PrivateUsage;
87 out.pagefile_usage = counters.PagefileUsage;
88 out.working_set = counters.WorkingSetSize;
89 return out;
90}
91#endif
92
93// The device's figure, published for views outside the device. A device with VK_EXT_memory_budget publishes a reader
94// when it is created and withdraws it first thing when it goes. The views call latest_vram(), which calls the reader at
95// most once per refresh_ms and returns the last figure in between. The lock is held during a read, so withdrawing
96// waits for a read that is in progress, and a reader is never called after its device is gone.
97using VramReader = VramBudget (*)(const void* context);
98inline constexpr std::chrono::milliseconds refresh_ms{500};
99
100class VramPublisher {
101public:
102 void publish(VramReader reader, const void* context) {
103 std::lock_guard lock(mutex_);
104 reader_ = reader;
105 context_ = context;
106 last_ = {};
107 read_ = false;
108 }
109 // Only the device that published the current reader withdraws it. Another device may have published since.
110 void withdraw(const void* context) {
111 std::lock_guard lock(mutex_);
112 if (context_ != context) return;
113 reader_ = nullptr;
114 context_ = nullptr;
115 last_ = {};
116 read_ = false;
117 }
118 VramBudget latest(std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now()) {
119 std::lock_guard lock(mutex_);
120 if (!reader_) return {};
121 if (!read_ || now - at_ >= refresh_ms) {
122 last_ = reader_(context_);
123 at_ = now;
124 read_ = true;
125 }
126 return last_;
127 }
128
129private:
130 std::mutex mutex_;
131 VramReader reader_ = nullptr;
132 const void* context_ = nullptr;
133 VramBudget last_;
134 std::chrono::steady_clock::time_point at_{};
135 bool read_ = false;
136};
137
138inline VramPublisher& vram_publisher() {
139 static VramPublisher instance;
140 return instance;
141}
142inline void publish_vram_reader(VramReader reader, const void* context) { vram_publisher().publish(reader, context); }
143inline void withdraw_vram_reader(const void* context) { vram_publisher().withdraw(context); }
144inline VramBudget latest_vram() { return vram_publisher().latest(); }
145
146} // namespace memory_figures
147} // namespace leonida
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 3558cffb5..fc73f37f5 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -1721,10 +1721,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1721 if (!m->base) 1721 if (!m->base)
1722 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, 1722 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage,
1723 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 1723 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
1724 if (!m->base) { 1724 if (!m->base) { // whether the image may move is decided at the relocation step below
1725 const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
1726 if (!relocs.Size)
1727 throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations");
1728 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 1725 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
1729 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); 1726 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed");
1730 } 1727 }
@@ -1749,10 +1746,19 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1749 } 1746 }
1750 1747
1751 int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); 1748 int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase);
1752 if (delta) { 1749 // A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table,
1753 m->relocated = true; 1750 // the flag refuses the move; with the flag clear the image is moved and nothing is fixed up, so it is trusted to
1754 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); 1751 // hold no absolute addresses. The Windows 11 loader does all three (runtime/README.md); that move is logged so
1755 if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); 1752 // it shows in traces. base_reservation::needed still keeps the main image's range free when it has no
1753 // relocation directory, so a main image is moved this way only where the range could not be had.
1754 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
1755 if (delta) m->relocated = true;
1756 if (delta && !dir.Size && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED))
1757 throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped");
1758 if (delta && !dir.Size)
1759 std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n",
1760 m->name.c_str(), static_cast<unsigned long long>(oh.ImageBase), static_cast<void*>(m->base));
1761 if (delta && dir.Size) {
1756 require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); 1762 require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table");
1757 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); 1763 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress);
1758 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size; 1764 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size;
@@ -2123,7 +2129,10 @@ void Loader::bind_imports(Module& m) {
2123 const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders; 2129 const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders;
2124 2130
2125 // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. 2131 // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image.
2126 auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva) { 2132 // `delayed`: a delay import that binds to an unimplemented thunk is traced. Windows' delay-load helper would raise
2133 // 0xC06D007E (module) or 0xC06D007F (procedure) at its first call, which a title can catch for a fallback; the
2134 // thunk returns 0 instead, so the trace names each such import before any image code runs.
2135 auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva, bool delayed) {
2127 for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) { 2136 for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) {
2128 require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table"); 2137 require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table");
2129 require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table"); 2138 require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table");
@@ -2141,6 +2150,10 @@ void Loader::bind_imports(Module& m) {
2141 throw std::runtime_error(m.name + ": an import address table lands in the headers"); 2150 throw std::runtime_error(m.name + ": an import address table lands in the headers");
2142 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = 2151 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function =
2143 reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord)); 2152 reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord));
2153 if (delayed && startup_trace::enabled() && m.imports.back().binding == Binding::Unimplemented)
2154 startup_trace::event("delay_import_unimplemented",
2155 "\"module\":" + startup_trace::quote(m.name) + ",\"import\":" +
2156 startup_trace::quote(dll + "!" + m.imports.back().name));
2144 } 2157 }
2145 }; 2158 };
2146 2159
@@ -2153,7 +2166,7 @@ void Loader::bind_imports(Module& m) {
2153 if (!d->Name) break; 2166 if (!d->Name) break;
2154 std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); 2167 std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name");
2155 uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; 2168 uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk;
2156 bind_thunks(dll, lookup, d->FirstThunk); 2169 bind_thunks(dll, lookup, d->FirstThunk, false);
2157 } 2170 }
2158 } 2171 }
2159 // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. 2172 // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run.
@@ -2176,7 +2189,7 @@ void Loader::bind_imports(Module& m) {
2176 // thunk addresses as name RVAs. 2189 // thunk addresses as name RVAs.
2177 if (!d->ImportNameTableRVA) 2190 if (!d->ImportNameTableRVA)
2178 throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); 2191 throw std::runtime_error(m.name + ": a delay-import descriptor has no name table");
2179 bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA); 2192 bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA, true);
2180 } 2193 }
2181 } 2194 }
2182} 2195}
diff --git a/runtime/src/pipeline_cache_journal.h b/runtime/src/pipeline_cache_journal.h
new file mode 100644
index 000000000..6a72d07f0
--- /dev/null
+++ b/runtime/src/pipeline_cache_journal.h
@@ -0,0 +1,356 @@
1// One Vulkan pipeline cache file per compiled compute pipeline: the "pipeline journal".
2//
3// The session cache (pipeline_cache_store.h) is one blob written at device teardown or at an idle checkpoint. A boot
4// that ends by a crash, a device loss or `timeout` never tears the device down, and while the compute warm-up thread
5// has builds queued the idle checkpoint never runs, so the hundreds of large compute pipelines a boot compiles were
6// compiled again on every boot. The journal keeps each one in its own small cache file the moment it is built:
7//
8// <cache dir>/pipeline_cache.d/cs-<16 hex digits>.bin
9//
10// The name is a hash of what the pipeline is made of (the SPIR-V words, the stage's subgroup request and the layout).
11// Each file is a complete VkPipelineCache blob holding one pipeline. A build reads the file, if any, into a
12// VkPipelineCache of its own and creates the pipeline against it: the driver finds the pipeline there (a hit, a few
13// milliseconds where the compile took seconds) or compiles it and the file is written again. Files are published
14// whole (write_pipeline_cache_file: a closed staging file renamed over the target), so a process killed mid-write
15// leaves the previous file or none, and a boot that dies keeps everything it built before.
16//
17// The hash only picks the file. Whether the pipeline in it may be used is the driver's decision: it checks the blob
18// header (vendor, device, pipeline-cache UUID; checked here first too, so a driver update starts over) and its own key.
19//
20// Upkeep (tidy, at the first pipeline of a device): staging files a killed writer left behind are removed once they are
21// ten minutes old, and past LEONIDA_PIPELINE_JOURNAL_BYTES the least recently used files go until three quarters of
22// it is left. A file's modification time is its last use: written, or touched when a build found its pipeline there.
23//
24// Pure stdlib apart from pipeline_cache_file.h's Windows rename retry; tested by pipeline_cache_journal_test.
25#pragma once
26
27#include <algorithm>
28#include <chrono>
29#include <cstddef>
30#include <cstdint>
31#include <cstdio>
32#include <filesystem>
33#include <fstream>
34#include <string>
35#include <string_view>
36#include <system_error>
37#include <type_traits>
38#include <vector>
39
40#include "cached_pso.h"
41#include "pipeline_cache_store.h" // before pipeline_cache_file.h, whose <windows.h> may define max
42#include "pipeline_cache_file.h"
43
44namespace leonida::pipeline_journal {
45
46// Bumped when what goes into a key changes, so files named under the old scheme are no longer looked up.
47inline constexpr std::uint32_t key_version = 1;
48
49// A file larger than this is not read (a corrupt or foreign file; one pipeline's cache is a few MiB at most).
50inline constexpr std::size_t entry_read_limit = std::size_t{256} << 20;
51
52// 64-bit FNV-1a. Not cryptographic: it names a file, and a collision costs one compile, not a wrong pipeline.
53class Hasher {
54public:
55 Hasher() { value(key_version); }
56
57 void bytes(const void* data, std::size_t size) {
58 const auto* p = static_cast<const std::uint8_t*>(data);
59 std::uint64_t h = hash_;
60 for (std::size_t i = 0; i < size; ++i) {
61 h ^= p[i];
62 h *= 0x100000001b3ull;
63 }
64 hash_ = h;
65 }
66
67 template<class T> void value(const T& v) {
68 static_assert(std::is_trivially_copyable_v<T>);
69 bytes(&v, sizeof(v));
70 }
71
72 void text(const char* s) {
73 const std::string_view view(s ? s : "");
74 value(std::uint64_t(view.size()));
75 bytes(view.data(), view.size());
76 }
77
78 std::uint64_t digest() const { return hash_; }
79
80private:
81 std::uint64_t hash_ = 0xcbf29ce484222325ull;
82};
83
84// <dir>/<kind>-<key as 16 lowercase hex digits>.bin
85inline std::filesystem::path entry_path(const std::filesystem::path& dir, const char* kind, std::uint64_t key) {
86 char name[64];
87 std::snprintf(name, sizeof(name), "%s-%016llx.bin", kind, static_cast<unsigned long long>(key));
88 return dir / name;
89}
90
91// Resolve the two roots once, not on the compile path. With no seed keep the original single-root behavior.
92// An explicit bad/overlapping pair disables the journal rather than accidentally publishing into the seed.
93// This is a configuration check, not a substitute for a read-only mount/ACL and stable parent directories.
94struct Roots {
95 std::filesystem::path writable;
96 std::filesystem::path seed;
97};
98
99inline Roots resolve_roots(const std::filesystem::path& local, const std::filesystem::path& seed) {
100 namespace fs = std::filesystem;
101 if (seed.empty() || local.empty()) return {local, {}};
102 std::error_code ec;
103 if (!seed.is_absolute() || !fs::is_directory(seed, ec) || ec) return {};
104 const auto source = fs::canonical(seed, ec);
105 if (ec) return {};
106 const auto abs_local = fs::absolute(local, ec);
107 if (ec) return {};
108 const auto dest = fs::weakly_canonical(abs_local, ec); // The writable leaf need not exist yet.
109 if (ec) return {};
110 const bool dest_exists = fs::exists(dest, ec);
111 if (ec || (dest_exists && !fs::is_directory(dest, ec))) return {};
112 // Use directory identity, not string prefixes: NTFS aliases and case differences still identify one directory.
113 auto overlaps = [&](const fs::path& existing, fs::path path) {
114 for (;;) {
115 if (fs::exists(path, ec) && fs::equivalent(existing, path, ec)) return true;
116 if (ec) return true;
117 const auto parent = path.parent_path();
118 if (parent == path || parent.empty()) return false;
119 path = parent;
120 }
121 };
122 if (overlaps(source, dest) || (dest_exists && overlaps(dest, source))) return {};
123 return {dest, source};
124}
125
126// The selected compatible bytes plus metadata for the *writable* leaf as the build found it.
127struct EntryFile {
128 std::vector<char> data; // compatible local bytes, else compatible seed bytes; empty when neither is usable
129 bool from_seed = false; // an external hit must not refresh either the immutable seed or a stale local file
130 std::uint64_t bytes = 0; // its size on disk, whatever its contents (0: none): what a rewrite replaces
131 std::filesystem::file_time_type used{}; // its modification time: its last use
132};
133
134inline EntryFile read_entry_file(const std::filesystem::path& path, const cached_pso::Identity& identity,
135 std::size_t limit = entry_read_limit) {
136 EntryFile entry;
137 std::error_code ec;
138 const auto size = std::filesystem::file_size(path, ec);
139 if (ec) return entry;
140 entry.bytes = size;
141 entry.used = std::filesystem::last_write_time(path, ec);
142 if (ec || size < pipeline_cache_store::header_bytes || size > limit) return entry;
143 std::ifstream file(path, std::ios::binary);
144 if (!file) return entry;
145 entry.data.resize(static_cast<std::size_t>(size));
146 if (!file.read(entry.data.data(), static_cast<std::streamsize>(entry.data.size())) ||
147 !pipeline_cache_store::header_matches(entry.data.data(), entry.data.size(), identity))
148 entry.data.clear();
149 return entry;
150}
151
152// The file's bytes, or empty when it is missing, unreadable, over `limit`, or its header does not name `identity`.
153inline std::vector<char> read_entry(const std::filesystem::path& path, const cached_pso::Identity& identity,
154 std::size_t limit = entry_read_limit) {
155 return read_entry_file(path, identity, limit).data;
156}
157
158// Whether the file is there with a header naming this device and driver: only the header is read (gta6rt
159// --precompile-pipelines asks this of thousands of files of a few MiB).
160inline bool entry_usable(const std::filesystem::path& path, const cached_pso::Identity& identity,
161 std::size_t limit = entry_read_limit) {
162 // A helper-ready file must also fit the consumer's bounded read. Check metadata, not the full payload.
163 std::error_code ec;
164 const auto size = std::filesystem::file_size(path, ec);
165 if (ec || size < pipeline_cache_store::header_bytes || size > limit) return false;
166 std::ifstream file(path, std::ios::binary);
167 char header[pipeline_cache_store::header_bytes];
168 return file && file.read(header, sizeof(header)) &&
169 pipeline_cache_store::header_matches(header, sizeof(header), identity);
170}
171
172enum class ReadRole { runtime, materialize_local };
173
174// A write always replaces the local file, not the seed. Keep its size and timestamp even if its
175// data is unusable. A seed miss adds no writable bytes; the seed directory is never scanned.
176inline EntryFile read_with_seed(const std::filesystem::path& local_entry, const std::filesystem::path& seed,
177 const cached_pso::Identity& identity, ReadRole role, std::size_t limit = entry_read_limit) {
178 auto local = read_entry_file(local_entry, identity, limit);
179 // Build hosts promise a file in the writable journal. External data must not satisfy such a request.
180 if (role == ReadRole::runtime && local.data.empty() && !seed.empty()) {
181 local.data = read_entry_file(seed / local_entry.filename(), identity, limit).data;
182 local.from_seed = !local.data.empty();
183 }
184 return local;
185}
186
187// A create this long, with no feedback to say, was a compile.
188inline constexpr std::uint64_t unreported_compile_ms = 1000;
189// NVIDIA 630.20 answers FAIL_ON_PIPELINE_COMPILE_REQUIRED with a compiled pipeline (seconds) instead of
190// VK_PIPELINE_COMPILE_REQUIRED. A pipeline from its own disk cache comes back fast and without the application-cache
191// hit bit too, and is no sign of that.
192inline constexpr std::uint64_t probe_compile_ms = 250;
193
194// Whether a build writes its journal file. `seeded`: its cache was made from the file; `hit`: the creation feedback
195// (1 found in that cache, 0 not, -1 not reported); `driver_ms`: the vkCreateComputePipelines call alone.
196inline bool should_write(bool seeded, int hit, std::uint64_t driver_ms) {
197 if (!seeded) return true; // the pipeline is in no file yet
198 if (hit >= 0) return hit == 0;
199 return driver_ms >= unreported_compile_ms;
200}
201
202// Whether a pipeline the shared cache gave for FAIL_ON_PIPELINE_COMPILE_REQUIRED was compiled after all.
203inline bool probe_compiled(int hit, std::uint64_t driver_ms) { return hit == 0 && driver_ms >= probe_compile_ms; }
204
205// The journal's size after a file of `old_bytes` (0: none) is replaced by one of `new_bytes`.
206inline std::uint64_t replace_bytes(std::uint64_t total, std::uint64_t old_bytes, std::uint64_t new_bytes) {
207 return total - (std::min)(total, old_bytes) + new_bytes;
208}
209
210// A file's last use is refreshed when it is more than this old, not at every hit.
211inline constexpr std::chrono::hours touch_after{1};
212
213inline void touch(const std::filesystem::path& path, std::filesystem::file_time_type now) {
214 std::error_code ec;
215 std::filesystem::last_write_time(path, now, ec);
216}
217
218// Called only after a journal cache hit. Only the local entry that supplied the hit is eligible for LRU.
219inline void touch_local_hit(const std::filesystem::path& local_entry, const EntryFile& file,
220 std::filesystem::file_time_type now) {
221 if (!file.from_seed && file.bytes && now - file.used >= touch_after)
222 touch(local_entry, now);
223}
224
225namespace detail {
226inline bool digits(std::string_view s) {
227 return !s.empty() && s.find_first_not_of("0123456789") == std::string_view::npos;
228}
229inline bool hex(std::string_view s) {
230 return !s.empty() && s.find_first_not_of("0123456789abcdef") == std::string_view::npos;
231}
232} // namespace detail
233
234// <kind>-<16 hex digits>.bin, as entry_path names them.
235inline bool entry_name(std::string_view name) {
236 constexpr std::string_view ext = ".bin";
237 const auto dash = name.find('-');
238 if (dash == std::string_view::npos || dash == 0 || name.size() != dash + 1 + 16 + ext.size() ||
239 name.substr(name.size() - ext.size()) != ext)
240 return false;
241 return detail::hex(name.substr(dash + 1, 16));
242}
243
244// What write_pipeline_cache_file stages an entry in: <entry>.tmp.<digits>.<digits>.
245inline bool staging_name(std::string_view name) {
246 constexpr std::string_view mark = ".tmp.";
247 const auto at = name.rfind(mark);
248 if (at == std::string_view::npos || !entry_name(name.substr(0, at))) return false;
249 const auto suffix = name.substr(at + mark.size());
250 const auto dot = suffix.find('.');
251 return dot != std::string_view::npos && detail::digits(suffix.substr(0, dot)) &&
252 detail::digits(suffix.substr(dot + 1));
253}
254
255struct EntryInfo {
256 std::filesystem::path path;
257 std::uint64_t bytes = 0;
258 std::filesystem::file_time_type used{};
259};
260
261// Which entries go, least recently used first, when they hold more than `budget`: as many as leave at most `target`.
262inline std::vector<std::size_t> plan_eviction(const std::vector<EntryInfo>& entries, std::uint64_t budget,
263 std::uint64_t target) {
264 std::uint64_t total = 0;
265 for (const EntryInfo& entry : entries) total += entry.bytes;
266 std::vector<std::size_t> out;
267 if (total <= budget) return out;
268 std::vector<std::size_t> order(entries.size());
269 for (std::size_t i = 0; i < order.size(); ++i) order[i] = i;
270 std::sort(order.begin(), order.end(), [&](std::size_t a, std::size_t b) {
271 if (entries[a].used != entries[b].used) return entries[a].used < entries[b].used;
272 return entries[a].path < entries[b].path;
273 });
274 for (const std::size_t i : order) {
275 if (total <= target) break;
276 out.push_back(i);
277 total -= entries[i].bytes;
278 }
279 return out;
280}
281
282struct TidyResult {
283 std::uint64_t bytes = 0; // what the entries left take
284 std::size_t entries = 0; // how many are left
285 std::size_t evicted = 0; // entries removed for the budget
286 std::size_t swept = 0; // staging files removed
287};
288
289// Removes staging files older than `staging_age` (a writer still holding one keeps it: Windows refuses to delete an
290// open file not shared for deletion), then, past `budget`, the least recently used entries until three quarters of
291// it is left. Other files in `dir` are left alone and not counted.
292inline TidyResult tidy(const std::filesystem::path& dir, std::uint64_t budget,
293 std::chrono::seconds staging_age = std::chrono::minutes(10),
294 std::filesystem::file_time_type now = std::filesystem::file_time_type::clock::now()) {
295 TidyResult result;
296 std::vector<EntryInfo> entries;
297 std::error_code ec;
298 for (std::filesystem::directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec)) {
299 std::error_code stat;
300 if (!it->is_regular_file(stat) || stat) continue;
301 const std::string name = it->path().filename().string();
302 const auto used = it->last_write_time(stat);
303 if (stat) continue;
304 if (staging_name(name)) {
305 std::error_code removed;
306 if (now - used >= staging_age && std::filesystem::remove(it->path(), removed) && !removed) ++result.swept;
307 continue;
308 }
309 if (!entry_name(name)) continue;
310 const auto size = it->file_size(stat);
311 if (!stat) entries.push_back({it->path(), size, used});
312 }
313 std::vector<bool> gone(entries.size());
314 for (const std::size_t i : plan_eviction(entries, budget, budget / 4 * 3)) {
315 std::error_code removed;
316 if (std::filesystem::remove(entries[i].path, removed) && !removed) {
317 gone[i] = true;
318 ++result.evicted;
319 }
320 }
321 for (std::size_t i = 0; i < entries.size(); ++i) {
322 if (gone[i]) continue;
323 result.bytes += entries[i].bytes;
324 ++result.entries;
325 }
326 return result;
327}
328
329// What the journal's files take on disk now: the sizes of the regular files in `dir` (0 when it does not exist).
330inline std::uint64_t directory_bytes(const std::filesystem::path& dir) {
331 std::uint64_t total = 0;
332 std::error_code ec;
333 for (std::filesystem::directory_iterator it(dir, ec), end; !ec && it != end; it.increment(ec)) {
334 std::error_code stat;
335 if (it->is_regular_file(stat) && !stat) {
336 const auto size = it->file_size(stat);
337 if (!stat) total += size;
338 }
339 }
340 return total;
341}
342
343// LEONIDA_PIPELINE_JOURNAL_BYTES: how much the journal may hold. A compute pipeline's file is 2-5 MiB on NVIDIA: the
344// ~1700 a boot builds take ~4 GiB, the whole library's ~5400 (gta6rt --precompile-pipelines) about 15. A boot writes
345// nothing past it; the next one's tidy makes room.
346inline constexpr std::uint64_t default_budget = std::uint64_t{32} << 30;
347
348// Publishes `data` as the file at `path`, creating its directory. The previous file stays until the rename.
349inline std::error_code write_entry(const std::filesystem::path& path, const void* data, std::size_t size) {
350 std::error_code ec;
351 std::filesystem::create_directories(path.parent_path(), ec);
352 if (ec) return ec;
353 return write_pipeline_cache_file(path, static_cast<const char*>(data), size);
354}
355
356} // namespace leonida::pipeline_journal
diff --git a/runtime/src/pipeline_wait.h b/runtime/src/pipeline_wait.h
new file mode 100644
index 000000000..2d74d8581
--- /dev/null
+++ b/runtime/src/pipeline_wait.h
@@ -0,0 +1,35 @@
1#pragma once
2// When the title last submitted, for the compute warm-ups (runtime/shims/d3d12_vulkan_device.cpp,
3// LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES, opt-in): while the title submits, a warm-up of a big module is left to the
4// pipeline's first use, since a create holds the compile gate for its whole length and every submission waits behind it.
5// No windows.h here: vulkan_backend.h includes this, and translation units without NOMINMAX include that.
6#include <atomic>
7#include <chrono>
8#include <cstdint>
9
10namespace leonida::pipeline_wait {
11
12// Steady-clock nanoseconds (the clock of submit_phases::now_ns).
13inline std::int64_t now_ns() {
14 return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch())
15 .count();
16}
17
18// The last submission (VulkanQueue::execute).
19inline std::atomic<std::int64_t>& last_submission() {
20 static std::atomic<std::int64_t> value{0};
21 return value;
22}
23inline void note_submission() { last_submission().store(now_ns(), std::memory_order_relaxed); }
24inline bool title_submitting(std::int64_t within_ns = 1000000000) {
25 const std::int64_t last = last_submission().load(std::memory_order_relaxed);
26 return last && now_ns() - last < within_ns;
27}
28
29// Big warm-ups left to their first use while the title submits.
30inline std::atomic<std::uint64_t>& warmups_left() {
31 static std::atomic<std::uint64_t> value{0};
32 return value;
33}
34
35} // namespace leonida::pipeline_wait
diff --git a/runtime/src/queue_holds.h b/runtime/src/queue_holds.h
index 2839d4210..40cc33117 100644
--- a/runtime/src/queue_holds.h
+++ b/runtime/src/queue_holds.h
@@ -93,6 +93,13 @@ public:
93 return it == fences_.end() || it->second < value; 93 return it == fences_.end() || it->second < value;
94 } 94 }
95 95
96 // The highest Signal submitted for the fence (or set by the CPU); 0 for an unknown semaphore.
97 std::uint64_t submitted_value(Semaphore semaphore) const {
98 std::lock_guard lock(mutex_);
99 const auto it = fences_.find(semaphore);
100 return it == fences_.end() ? 0 : it->second;
101 }
102
96 // true when no submitted Signal reaches `value` yet. Unknown semaphores are satisfied. 103 // true when no submitted Signal reaches `value` yet. Unknown semaphores are satisfied.
97 bool pending(Semaphore semaphore, std::uint64_t value) const { 104 bool pending(Semaphore semaphore, std::uint64_t value) const {
98 std::lock_guard lock(mutex_); 105 std::lock_guard lock(mutex_);
diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp
index 10dd1e02c..41d3f6c5a 100644
--- a/runtime/src/root_signature.cpp
+++ b/runtime/src/root_signature.cpp
@@ -17,10 +17,8 @@ PackResult pack(const RootSignature& sig) {
17 out.error = "unknown root parameter type"; 17 out.error = "unknown root parameter type";
18 return out; 18 return out;
19 } 19 }
20 if (p.type == ParamType::Constants && p.num_values == 0) { 20 // A constant parameter of 0 values is valid (the host serializer warns, CreateRootSignature answers S_OK):
21 out.error = "root constant parameter needs at least 1 dword"; 21 // it takes no dwords, so it gets no provenance entry and the parameters after it pack as if it were absent.
22 return out;
23 }
24 const uint32_t dwords = p.type == ParamType::Table ? 2 22 const uint32_t dwords = p.type == ParamType::Table ? 2
25 : p.type == ParamType::Descriptor ? 2 23 : p.type == ParamType::Descriptor ? 2
26 : p.num_values; 24 : p.num_values;
@@ -71,15 +69,12 @@ StagePackResult pack_stage(const RootSignature& sig, Stage stage) {
71 out.error = "unknown root parameter type"; 69 out.error = "unknown root parameter type";
72 return out; 70 return out;
73 } 71 }
74 if (p.type == ParamType::Constants && p.num_values == 0) {
75 out.error = "root constant parameter needs at least 1 dword";
76 return out;
77 }
78 cost += param_cost(p.type, p.num_values); 72 cost += param_cost(p.type, p.num_values);
79 if (cost > kMaxD3d12Cost) { 73 if (cost > kMaxD3d12Cost) {
80 out.error = "root signature exceeds the 64-dword D3D12 cost limit"; 74 out.error = "root signature exceeds the 64-dword D3D12 cost limit";
81 return out; 75 return out;
82 } 76 }
77 // 0 for a constant parameter of 0 values, which then shares its first SGPR with the next parameter.
83 const uint64_t dwords = stage_dwords(p.type, p.num_values); 78 const uint64_t dwords = stage_dwords(p.type, p.num_values);
84 if (!spilling && next + dwords <= kMaxUserSgprs) { 79 if (!spilling && next + dwords <= kMaxUserSgprs) {
85 first.push_back(static_cast<uint32_t>(next)); 80 first.push_back(static_cast<uint32_t>(next));
diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h
index e7976fc73..559f4c54d 100644
--- a/runtime/src/root_signature.h
+++ b/runtime/src/root_signature.h
@@ -114,7 +114,8 @@ constexpr uint32_t kMaxD3d12Cost = 64;
114// Packs root parameters in order. Static samplers consume no dwords. 114// Packs root parameters in order. Static samplers consume no dwords.
115// Fails (ok == false) when the signature needs more than 32 user SGPRs 115// Fails (ok == false) when the signature needs more than 32 user SGPRs
116// (spill layout unknown: refuse, do not guess) or exceeds the 64-dword 116// (spill layout unknown: refuse, do not guess) or exceeds the 64-dword
117// D3D12 cost limit, or holds more than 64 root parameters. 117// D3D12 cost limit, or holds more than 64 root parameters. A constant
118// parameter of 0 values takes no dwords, as on the host.
118[[nodiscard]] PackResult pack(const RootSignature& sig); 119[[nodiscard]] PackResult pack(const RootSignature& sig);
119 120
120// The console layout of root arguments in a stage's user SGPRs (docs/d3d12_vulkan.md section 3.5, D3D-448). 121// The console layout of root arguments in a stage's user SGPRs (docs/d3d12_vulkan.md section 3.5, D3D-448).
@@ -183,8 +184,9 @@ struct StagePackResult {
183}; 184};
184 185
185// Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, an 186// Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, an
186// unknown parameter type, a constant parameter of 0 values, or the 64-dword cost limit. Compute spills any trailing 187// unknown parameter type or the 64-dword cost limit. Compute spills any trailing parameters from the first one
187// parameters from the first one that does not fit whole into spill_dword; non-compute stages refuse any spill. 188// that does not fit whole into spill_dword; non-compute stages refuse any spill. A constant parameter of 0 values
189// takes no SGPRs and no spill dwords.
188[[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage); 190[[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage);
189 191
190// D3D12 cost of one parameter against the 64-dword limit. 192// D3D12 cost of one parameter against the 64-dword limit.
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h
index a359287cb..7699dfbb0 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
897 return census.fnv1a_fmix32 > census.fnv1a ? DescriptorHashKind::fnv1a_fmix32 : DescriptorHashKind::fnv1a; 897 return census.fnv1a_fmix32 > census.fnv1a ? DescriptorHashKind::fnv1a_fmix32 : DescriptorHashKind::fnv1a;
898} 898}
899 899
900// Which descriptor-table entry layout the loaded modules read (descriptor_table.h, tools/rdna2spirv.py
901// --descriptor-table). A module whose meta carries `"descriptor_table": "tagged"` also reads the kind word next to
902// each index and uses it to tell which array an index belongs to; an absent key is the old plain layout, which reads
903// only the index. The runtime fills the kind word for a tagged table and leaves it alone for a plain one, so a
904// library translated before the marker (or with --descriptor-table plain) behaves exactly as it did.
905enum class DescriptorTableLayout : std::uint8_t { plain = 0, tagged = 1 };
906
907inline constexpr const char* descriptor_table_layout_name(DescriptorTableLayout layout) {
908 return layout == DescriptorTableLayout::tagged ? "tagged" : "plain";
909}
910
911struct DescriptorTableCensus {
912 std::size_t plain = 0;
913 std::size_t tagged = 0;
914 std::size_t total() const { return plain + tagged; }
915};
916
917// The tagged layout when any module reads it. The kind word is additive: a tagged module reads it and a plain
918// module ignores it (it reads the index at the same place), so one tagged module in the corpus needs the tagged
919// layout, however many plain ones there are. Counting entries would let a merged or partial index whose plain
920// modules outnumber the tagged ones hand every tagged module an all-zero kind, and every image of another
921// dimension would then fall back. No tagged module is the old plain layout.
922inline DescriptorTableLayout majority_descriptor_table_layout(const DescriptorTableCensus& census) {
923 return census.tagged > 0 ? DescriptorTableLayout::tagged : DescriptorTableLayout::plain;
924}
925
926// LEONIDA_DESCRIPTOR_TABLE=plain|tagged overrides the modules' vote. False when `value` is null, empty or not one
927// of the two layouts (an unrecognised value is ignored rather than failing startup).
928inline bool descriptor_table_layout_from_env(const char* value, DescriptorTableLayout* layout) {
929 if (!value || !*value) return false;
930 if (std::strcmp(value, "tagged") == 0) {
931 if (layout) *layout = DescriptorTableLayout::tagged;
932 return true;
933 }
934 if (std::strcmp(value, "plain") == 0) {
935 if (layout) *layout = DescriptorTableLayout::plain;
936 return true;
937 }
938 return false;
939}
940
900// LEONIDA_DESCRIPTOR_HASH=fnv1a|fnv1a_fmix32 overrides the modules' majority. False when `value` is null, empty or not 941// LEONIDA_DESCRIPTOR_HASH=fnv1a|fnv1a_fmix32 overrides the modules' majority. False when `value` is null, empty or not
901// one of the two kinds (an unrecognised value is ignored rather than failing startup). 942// one of the two kinds (an unrecognised value is ignored rather than failing startup).
902inline bool descriptor_hash_kind_from_env(const char* value, DescriptorHashKind* kind) { 943inline bool descriptor_hash_kind_from_env(const char* value, DescriptorHashKind* kind) {
@@ -973,6 +1014,7 @@ public:
973 bvh_count_ = 0; 1014 bvh_count_ = 0;
974 exe_count_ = 0; 1015 exe_count_ = 0;
975 descriptor_hash_census_ = {}; 1016 descriptor_hash_census_ = {};
1017 descriptor_table_census_ = {};
976 for (const char* folder : {"fspx", "fspx_gfx"}) { 1018 for (const char* folder : {"fspx", "fspx_gfx"}) {
977 try { 1019 try {
978 const auto ignore = [](const std::string&) { return false; }; 1020 const auto ignore = [](const std::string&) { return false; };
@@ -994,6 +1036,13 @@ public:
994 // LEONIDA_DESCRIPTOR_HASH names a kind. 1036 // LEONIDA_DESCRIPTOR_HASH names a kind.
995 const DescriptorHashCensus& descriptor_hash_census() const { return descriptor_hash_census_; } 1037 const DescriptorHashCensus& descriptor_hash_census() const { return descriptor_hash_census_; }
996 DescriptorHashKind descriptor_hash_kind() const { return majority_descriptor_hash_kind(descriptor_hash_census_); } 1038 DescriptorHashKind descriptor_hash_kind() const { return majority_descriptor_hash_kind(descriptor_hash_census_); }
1039 // The entry layouts the loaded modules read, and the layout to use: tagged as soon as one module reads the kind
1040 // word (it is additive, see majority_descriptor_table_layout), plain when none does. The device takes this once,
1041 // before its descriptor table's first insert, unless LEONIDA_DESCRIPTOR_TABLE names a layout.
1042 const DescriptorTableCensus& descriptor_table_census() const { return descriptor_table_census_; }
1043 DescriptorTableLayout descriptor_table_layout() const {
1044 return majority_descriptor_table_layout(descriptor_table_census_);
1045 }
997 // Entries loaded from <dir>/fspx/index.json and <dir>/library/index.json. A corpus of RPF containers never 1046 // Entries loaded from <dir>/fspx/index.json and <dir>/library/index.json. A corpus of RPF containers never
998 // reaches these: their programs come from FidelityFX DLLs and the pipeline library, so callers comparing reached 1047 // reaches these: their programs come from FidelityFX DLLs and the pipeline library, so callers comparing reached
999 // entries with size() must leave them out. 1048 // entries with size() must leave them out.
@@ -1069,6 +1118,19 @@ public:
1069 return all; 1118 return all;
1070 } 1119 }
1071 1120
1121 // The module's file: <dir>/<name>.spv, or the index's spv file name when that one is missing.
1122 std::filesystem::path spirv_file(const ShaderEntry& entry) const {
1123 std::error_code ec;
1124 auto path = dir_;
1125 path += "/" + entry.name + ".spv";
1126 if (!std::filesystem::exists(path, ec) && !entry.spv_file.empty()) {
1127 auto alt = dir_;
1128 alt += "/" + entry.spv_file;
1129 return alt;
1130 }
1131 return path;
1132 }
1133
1072 // The size of the module's file in bytes, or 0 when it is missing: what spirv() would read, without reading it. 1134 // The size of the module's file in bytes, or 0 when it is missing: what spirv() would read, without reading it.
1073 std::size_t spirv_bytes(const ShaderEntry& entry) const { 1135 std::size_t spirv_bytes(const ShaderEntry& entry) const {
1074 std::error_code ec; 1136 std::error_code ec;
@@ -1083,6 +1145,20 @@ public:
1083 return ec ? 0 : static_cast<std::size_t>(size); 1145 return ec ? 0 : static_cast<std::size_t>(size);
1084 } 1146 }
1085 1147
1148 // Every entry of `stage` once, in name order, from every index (an entry reachable both by its FSSM and its FSPX
1149 // hash is one entry). gta6rt --precompile-pipelines builds them all.
1150 std::vector<const ShaderEntry*> stage_entries(std::string_view stage) const {
1151 std::map<std::pair<std::string_view, std::string_view>, const ShaderEntry*> unique;
1152 for (const Entries* map : {&entries_, &fspx_entries_})
1153 for (const auto& [key, list] : *map)
1154 for (const ShaderEntry& e : list)
1155 if (e.stage == stage) unique.emplace(std::pair<std::string_view, std::string_view>{e.name, e.spv_file}, &e);
1156 std::vector<const ShaderEntry*> out;
1157 out.reserve(unique.size());
1158 for (const auto& [key, e] : unique) out.push_back(e);
1159 return out;
1160 }
1161
1086 // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V. 1162 // The module's words, or empty when <dir>/<name>.spv is missing or not SPIR-V.
1087 std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const { 1163 std::vector<std::uint32_t> spirv(const ShaderEntry& entry) const {
1088 auto path = dir_; 1164 auto path = dir_;
@@ -1146,6 +1222,7 @@ private:
1146 bvh_count_ = 0; 1222 bvh_count_ = 0;
1147 exe_count_ = 0; 1223 exe_count_ = 0;
1148 descriptor_hash_census_ = {}; 1224 descriptor_hash_census_ = {};
1225 descriptor_table_census_ = {};
1149 } 1226 }
1150 for (const auto& [name, meta] : root.object) { 1227 for (const auto& [name, meta] : root.object) {
1151 const Json* hash = meta.find("fssm_sha256"); 1228 const Json* hash = meta.find("fssm_sha256");
@@ -1241,6 +1318,13 @@ private:
1241 ++descriptor_hash_census_.fnv1a_fmix32; 1318 ++descriptor_hash_census_.fnv1a_fmix32;
1242 else 1319 else
1243 ++descriptor_hash_census_.fnv1a; 1320 ++descriptor_hash_census_.fnv1a;
1321 // Which entry layout this module reads (descriptor_table.h). Absent, or not a layout this runtime knows,
1322 // is the old plain one.
1323 if (const Json* dt = meta.find("descriptor_table");
1324 dt && dt->kind == Json::Kind::string && dt->string == "tagged")
1325 ++descriptor_table_census_.tagged;
1326 else
1327 ++descriptor_table_census_.plain;
1244 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); 1328 if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e);
1245 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); 1329 if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e));
1246 if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_; 1330 if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_;
@@ -1264,6 +1348,7 @@ private:
1264 Entries entries_; 1348 Entries entries_;
1265 Entries fspx_entries_; 1349 Entries fspx_entries_;
1266 DescriptorHashCensus descriptor_hash_census_; 1350 DescriptorHashCensus descriptor_hash_census_;
1351 DescriptorTableCensus descriptor_table_census_;
1267}; 1352};
1268 1353
1269} // namespace leonida 1354} // namespace leonida
diff --git a/runtime/src/submit_phases.h b/runtime/src/submit_phases.h
index 84ea77b02..dfaf8ce95 100644
--- a/runtime/src/submit_phases.h
+++ b/runtime/src/submit_phases.h
@@ -24,12 +24,14 @@ enum Phase : unsigned {
24 shadows, // slot-133 shadow buffers and title windows (ShadowPages::refresh) 24 shadows, // slot-133 shadow buffers and title windows (ShadowPages::refresh)
25 geometry, // GeometryViews::refresh 25 geometry, // GeometryViews::refresh
26 textures, // Device::refresh_title_textures 26 textures, // Device::refresh_title_textures
27 pipelines, // no longer timed (the pre-pass that waited for pipelines is gone); kept for the column order
27 replay, // the rest of execute_now: preparing, recording and submitting the lists 28 replay, // the rest of execute_now: preparing, recording and submitting the lists
28 kCount 29 kCount
29}; 30};
30 31
31inline const char* name(unsigned p) { 32inline const char* name(unsigned p) {
32 static const char* const names[kCount] = {"wait", "heaps", "shadows", "geometry", "textures", "replay"}; 33 static const char* const names[kCount] = {"wait", "heaps", "shadows", "geometry", "textures", "pipes",
34 "replay"};
33 return p < kCount ? names[p] : "?"; 35 return p < kCount ? names[p] : "?";
34} 36}
35 37
@@ -40,6 +42,10 @@ struct Totals {
40 std::atomic<std::int64_t> last_log{0}; 42 std::atomic<std::int64_t> last_log{0};
41 std::atomic<std::uint64_t> presents{0}; // frames the presenter showed (VulkanPresenter), since the last line 43 std::atomic<std::uint64_t> presents{0}; // frames the presenter showed (VulkanPresenter), since the last line
42 std::atomic<std::uint64_t> present_serial{0}; // the same, never reset (LEONIDA_REFRESH_PER_FRAME) 44 std::atomic<std::uint64_t> present_serial{0}; // the same, never reset (LEONIDA_REFRESH_PER_FRAME)
45 // Threads whose innermost Scope is this phase now, and when the first of them entered it (steady_clock). Counted
46 // per phase, since queues submit from several threads: one value would go stale when their scopes overlap.
47 std::atomic<unsigned> active[kCount]{};
48 std::atomic<std::int64_t> active_since[kCount]{};
43 std::atomic<std::uint32_t> thread{0}; // the thread of the last submission (the thread sampler reports it apart) 49 std::atomic<std::uint32_t> thread{0}; // the thread of the last submission (the thread sampler reports it apart)
44}; 50};
45inline Totals& totals() { 51inline Totals& totals() {
@@ -86,12 +92,48 @@ inline void add(Phase p, std::uint64_t ns) {
86struct Scope { 92struct Scope {
87 Phase phase; 93 Phase phase;
88 std::int64_t start = now_ns(); 94 std::int64_t start = now_ns();
89 explicit Scope(Phase p) : phase(p) {} 95 int outer; // the phase of this thread's Scope around this one, -1 for none
90 ~Scope() { add(phase, std::uint64_t(now_ns() - start)); } 96 explicit Scope(Phase p) : phase(p), outer(innermost()) {
97 if (outer >= 0) leave(outer);
98 enter(int(p), start);
99 innermost() = int(p);
100 }
101 ~Scope() {
102 const std::int64_t end = now_ns();
103 add(phase, std::uint64_t(end - start));
104 leave(int(phase));
105 if (outer >= 0) enter(outer, end);
106 innermost() = outer;
107 }
108 static int& innermost() {
109 thread_local int phase_of_this_thread = -1;
110 return phase_of_this_thread;
111 }
112 static void enter(int p, std::int64_t at) {
113 Totals& t = totals();
114 if (t.active[p].fetch_add(1, std::memory_order_relaxed) == 0) t.active_since[p].store(at, std::memory_order_relaxed);
115 }
116 static void leave(int p) { totals().active[p].fetch_sub(1, std::memory_order_relaxed); }
91 Scope(const Scope&) = delete; 117 Scope(const Scope&) = delete;
92 Scope& operator=(const Scope&) = delete; 118 Scope& operator=(const Scope&) = delete;
93}; 119};
94 120
121// The phase that some thread has been in longest, -1 when none is in one.
122struct Running {
123 int phase = -1;
124 std::int64_t since = 0;
125};
126inline Running running() {
127 Totals& t = totals();
128 Running r;
129 for (unsigned p = 0; p < kCount; ++p) {
130 if (!t.active[p].load(std::memory_order_relaxed)) continue;
131 const std::int64_t since = t.active_since[p].load(std::memory_order_relaxed);
132 if (r.phase < 0 || since < r.since) r = {int(p), since};
133 }
134 return r;
135}
136
95// After each submission: counts it, and prints the line when the period has passed. One thread wins the line. 137// After each submission: counts it, and prints the line when the period has passed. One thread wins the line.
96inline void submitted() { 138inline void submitted() {
97 Totals& t = totals(); 139 Totals& t = totals();
@@ -120,14 +162,15 @@ inline void submitted() {
120 all += total; 162 all += total;
121 } 163 }
122 std::fprintf(stderr, 164 std::fprintf(stderr,
123 "[rt] submit phases t=%.0fs: %llu submissions in %.1f s (%.2f/s, %llu in all), %.2f frames/s; ms per submission " 165 "[rt] submit phases t=%.0fs: %llu submissions in %.1f s (%.2f/s, %llu in all), %.2f frames/s; ms per "
124 "(max): %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f); " 166 "submission (max): %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f (%.0f) %s %.2f "
167 "(%.0f) %s %.2f (%.0f); "
125 "%.0f%% of the wall time\n", 168 "%.0f%% of the wall time\n",
126 process_age(), static_cast<unsigned long long>(n), seconds, double(n) / seconds, 169 process_age(), static_cast<unsigned long long>(n), seconds, double(n) / seconds,
127 static_cast<unsigned long long>(t.all_submissions.load(std::memory_order_relaxed)), 170 static_cast<unsigned long long>(t.all_submissions.load(std::memory_order_relaxed)),
128 double(frames) / seconds, name(0), ms[0], 171 double(frames) / seconds, name(0), ms[0],
129 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), 172 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),
130 ms[4], max_ms[4], name(5), ms[5], max_ms[5], 100.0 * all * 1e-3 / seconds); 173 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);
131} 174}
132 175
133} // namespace leonida::submit_phases 176} // namespace leonida::submit_phases
diff --git a/runtime/src/thread_sampler.h b/runtime/src/thread_sampler.h
index 282eb20dd..0c18949ce 100644
--- a/runtime/src/thread_sampler.h
+++ b/runtime/src/thread_sampler.h
@@ -44,6 +44,9 @@ struct Sampler {
44 // LEONIDA_SAMPLE_DETAIL=<id>[,<id>...]: for these threads, the 10 most frequent chains, 16 frames deep, each as a 44 // LEONIDA_SAMPLE_DETAIL=<id>[,<id>...]: for these threads, the 10 most frequent chains, 16 frames deep, each as a
45 // share of that thread's samples (thread ids are stable from boot to boot: the title's main, render and submit). 45 // share of that thread's samples (thread ids are stable from boot to boot: the title's main, render and submit).
46 std::vector<DWORD> detail; 46 std::vector<DWORD> detail;
47 // LEONIDA_SAMPLE_FIND=<rva>[,<rva>...] (title function starts): which threads have the function on their stack
48 // (48 frames deep), how often, and their most frequent chain under it, every report.
49 std::vector<std::uint64_t> find;
47}; 50};
48 51
49// Per title thread (one with a title frame in its chain): how many samples were inside our runtime, and through which 52// 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) {
151 constexpr int kDetailFrames = 16; 154 constexpr int kDetailFrames = 16;
152 using DetailChain = std::array<std::uint64_t, kDetailFrames>; 155 using DetailChain = std::array<std::uint64_t, kDetailFrames>;
153 std::map<std::pair<DWORD, DetailChain>, std::uint64_t> detail_chains; 156 std::map<std::pair<DWORD, DetailChain>, std::uint64_t> detail_chains;
157 std::map<std::pair<std::uint64_t, DWORD>, std::map<DetailChain, std::uint64_t>> found; // (rva, thread) -> chains
154 std::uint64_t total = 0; 158 std::uint64_t total = 0;
155 ULONGLONG listed = 0, reported = GetTickCount64(); 159 ULONGLONG listed = 0, reported = GetTickCount64();
156 const auto cpu_of = [](HANDLE h) { 160 const auto cpu_of = [](HANDLE h) {
@@ -205,11 +209,20 @@ inline DWORD WINAPI run(LPVOID parameter) {
205 unwind(context, deep); 209 unwind(context, deep);
206 ++detail_chains[{it->first, deep}]; 210 ++detail_chains[{it->first, deep}];
207 } 211 }
208 if (s.shims) { 212 if (s.shims || !s.find.empty()) {
209 DeepChain deep{}; 213 DeepChain deep{};
210 const int n = unwind(context, deep); 214 const int n = unwind(context, deep);
211 std::copy_n(deep.begin(), kFrames, chain.begin()); 215 std::copy_n(deep.begin(), kFrames, chain.begin());
212 count_shims(s, deep, n, moved, shim_counts[it->first]); 216 if (s.shims) count_shims(s, deep, n, moved, shim_counts[it->first]);
217 const auto title = reinterpret_cast<std::uint64_t>(s.title);
218 for (const std::uint64_t rva : s.find)
219 for (int f = 0; f < n; ++f)
220 if (deep[f] == title + rva) {
221 DetailChain inner{};
222 std::copy_n(deep.begin(), (std::min)(kDetailFrames, n), inner.begin());
223 ++found[{rva, it->first}][inner];
224 break;
225 }
213 } else { 226 } else {
214 unwind(context, chain); 227 unwind(context, chain);
215 } 228 }
@@ -299,6 +312,23 @@ inline DWORD WINAPI run(LPVOID parameter) {
299 } 312 }
300 } 313 }
301 detail_chains.clear(); 314 detail_chains.clear();
315 for (const auto& [key, chains_of] : found) {
316 std::uint64_t all = 0;
317 const DetailChain* top = nullptr;
318 std::uint64_t top_n = 0;
319 for (const auto& [c, n] : chains_of) {
320 all += n;
321 if (n > top_n) top_n = n, top = &c;
322 }
323 std::string frames;
324 for (int f = 0; top && f < kDetailFrames && (*top)[f]; ++f) frames += (f ? " < " : "") + name_of(s, (*top)[f]);
325 const auto t = threads.find(key.second);
326 std::fprintf(stderr, "[rt] sampler: find t+%llx: thread %lu %llu samples of %llu; top chain (%llu): %s\n",
327 static_cast<unsigned long long>(key.first), key.second, static_cast<unsigned long long>(all),
328 static_cast<unsigned long long>(t == threads.end() ? 0 : t->second.samples),
329 static_cast<unsigned long long>(top_n), frames.c_str());
330 }
331 found.clear();
302 if (s.shims) { 332 if (s.shims) {
303 // Title threads by their samples inside our runtime: where the title's own threads (its main, render and 333 // Title threads by their samples inside our runtime: where the title's own threads (its main, render and
304 // Subrender workers, streaming) spend time in our shims, waiting or running. 334 // 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) {
386 if (id) s.detail.push_back(DWORD(id)); 416 if (id) s.detail.push_back(DWORD(id));
387 at = *end == ',' ? end + 1 : end; 417 at = *end == ',' ? end + 1 : end;
388 } 418 }
419 char finds[256] = {};
420 if (const DWORD n = GetEnvironmentVariableA("LEONIDA_SAMPLE_FIND", finds, sizeof(finds)); n && n < sizeof(finds))
421 for (char* at = finds; *at;) {
422 char* end = nullptr;
423 const std::uint64_t rva = std::strtoull(at, &end, 16);
424 if (end == at) break;
425 if (rva) s.find.push_back(rva);
426 at = *end == ',' ? end + 1 : end;
427 }
389 char shims[4] = {}; 428 char shims[4] = {};
390 s.shims = GetEnvironmentVariableA("LEONIDA_SAMPLE_SHIMS", shims, sizeof(shims)) == 1 && shims[0] == '1'; 429 s.shims = GetEnvironmentVariableA("LEONIDA_SAMPLE_SHIMS", shims, sizeof(shims)) == 1 && shims[0] == '1';
391 if (const auto self = reinterpret_cast<const std::uint8_t*>(GetModuleHandleW(nullptr))) { 430 if (const auto self = reinterpret_cast<const std::uint8_t*>(GetModuleHandleW(nullptr))) {
diff --git a/runtime/src/thread_stacks.cpp b/runtime/src/thread_stacks.cpp
index 67188d908..38d7cc2a4 100644
--- a/runtime/src/thread_stacks.cpp
+++ b/runtime/src/thread_stacks.cpp
@@ -121,10 +121,10 @@ struct ThreadTrace {
121 size_t count = 0; 121 size_t count = 0;
122}; 122};
123 123
124void print_traces(unsigned at, const std::vector<ThreadTrace>& traces) { 124void print_traces(const std::string& tag, const std::vector<ThreadTrace>& traces) {
125 std::string out = "[rt] stacks t=" + std::to_string(at) + ": " + std::to_string(traces.size()) + " threads\n"; 125 std::string out = "[rt] stacks " + tag + ": " + std::to_string(traces.size()) + " threads\n";
126 for (auto it = traces.begin(); it != traces.end(); ++it) { 126 for (auto it = traces.begin(); it != traces.end(); ++it) {
127 out += "[rt] stacks t=" + std::to_string(at) + " thread " + std::to_string(it->tid) + " (" + it->label + "):\n"; 127 out += "[rt] stacks " + tag + " thread " + std::to_string(it->tid) + " (" + it->label + "):\n";
128 const auto same = std::find_if(traces.begin(), it, [&](const ThreadTrace& earlier) { 128 const auto same = std::find_if(traces.begin(), it, [&](const ThreadTrace& earlier) {
129 return it->count && it->count == earlier.count && 129 return it->count && it->count == earlier.count &&
130 std::equal(it->frames.begin(), it->frames.begin() + it->count, earlier.frames.begin()); 130 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<ThreadTrace>& traces) {
142 std::fflush(stderr); 142 std::fflush(stderr);
143} 143}
144 144
145void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describe, QueryThread query) { 145void snapshot_threads(const std::string& tag, StackSampler& sampler, GetDescription describe, QueryThread query,
146 DWORD only = 0) {
146 const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); 147 const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
147 if (snapshot == INVALID_HANDLE_VALUE) { 148 if (snapshot == INVALID_HANDLE_VALUE) {
148 std::fprintf(stderr, "[rt] stacks t=%u: thread list failed (error %lu)\n", at, GetLastError()); 149 std::fprintf(stderr, "[rt] stacks %s: thread list failed (error %lu)\n", tag.c_str(), GetLastError());
149 return; 150 return;
150 } 151 }
151 std::vector<ThreadTrace> traces; 152 std::vector<ThreadTrace> traces;
@@ -157,6 +158,7 @@ void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describ
157 for (BOOL ok = Thread32First(snapshot, &entry); ok; ok = Thread32Next(snapshot, &entry)) { 158 for (BOOL ok = Thread32First(snapshot, &entry); ok; ok = Thread32Next(snapshot, &entry)) {
158 entry.dwSize = sizeof(entry); 159 entry.dwSize = sizeof(entry);
159 if (entry.th32OwnerProcessID != pid || entry.th32ThreadID == self) continue; 160 if (entry.th32OwnerProcessID != pid || entry.th32ThreadID == self) continue;
161 if (only && entry.th32ThreadID != only) continue;
160 const HANDLE thread = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 162 const HANDLE thread = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
161 FALSE, entry.th32ThreadID); 163 FALSE, entry.th32ThreadID);
162 if (!thread) continue; 164 if (!thread) continue;
@@ -169,7 +171,7 @@ void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describ
169 CloseHandle(thread); 171 CloseHandle(thread);
170 } 172 }
171 CloseHandle(snapshot); 173 CloseHandle(snapshot);
172 print_traces(at, traces); 174 print_traces(tag, traces);
173} 175}
174 176
175} // namespace 177} // namespace
@@ -207,6 +209,20 @@ bool parse_stack_times(std::string_view text, std::vector<unsigned>& seconds) {
207 return true; 209 return true;
208} 210}
209 211
212void print_thread_stacks_now(std::uint32_t tid, const char* why) noexcept {
213 static std::mutex mutex;
214 try {
215 std::lock_guard lock(mutex);
216 static StackSampler sampler;
217 const auto describe = reinterpret_cast<GetDescription>(reinterpret_cast<void*>(
218 GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription")));
219 const auto query = reinterpret_cast<QueryThread>(reinterpret_cast<void*>(
220 GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread")));
221 snapshot_threads(why ? why : "now", sampler, describe, query, tid);
222 } catch (...) {
223 }
224}
225
210std::jthread start_thread_stacks() { 226std::jthread start_thread_stacks() {
211 const auto start = Clock::now(); 227 const auto start = Clock::now();
212 char spec[1024]; 228 char spec[1024];
@@ -229,7 +245,7 @@ std::jthread start_thread_stacks() {
229 for (const unsigned at : times) { 245 for (const unsigned at : times) {
230 wake.wait_until(lock, stop, start + std::chrono::seconds(at), [] { return false; }); 246 wake.wait_until(lock, stop, start + std::chrono::seconds(at), [] { return false; });
231 if (stop.stop_requested()) break; 247 if (stop.stop_requested()) break;
232 snapshot_threads(at, sampler, describe, query); 248 snapshot_threads("t=" + std::to_string(at), sampler, describe, query);
233 } 249 }
234 }); 250 });
235} 251}
diff --git a/runtime/src/thread_stacks.h b/runtime/src/thread_stacks.h
index 523c7b266..1edc1b350 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<unsigned>& seconds);
35// sampler before unmapping the title image. 35// sampler before unmapping the title image.
36std::jthread start_thread_stacks(); 36std::jthread start_thread_stacks();
37 37
38// The call chain of thread `tid` now, or of every other thread when `tid` is 0, printed as LEONIDA_STACKS does under
39// the tag `why`. One call at a time; the device-loss diagnostics call it (vulkan_device_fault.h thread_stack_hook).
40void print_thread_stacks_now(std::uint32_t tid, const char* why) noexcept;
41
38} // namespace rt 42} // namespace rt
diff --git a/runtime/src/title_geometry_watch.h b/runtime/src/title_geometry_watch.h
index d01439776..ca600fb9b 100644
--- a/runtime/src/title_geometry_watch.h
+++ b/runtime/src/title_geometry_watch.h
@@ -2,6 +2,7 @@
2 2
3#include "title_page_watch.h" 3#include "title_page_watch.h"
4#include <array> 4#include <array>
5#include <cstdint>
5#include <vector> 6#include <vector>
6 7
7namespace leonida::geometry_writes { 8namespace leonida::geometry_writes {
@@ -15,19 +16,98 @@ struct Cell {
15 std::array<DWORD, tile_size / page_size> restore{}; 16 std::array<DWORD, tile_size / page_size> restore{};
16 unsigned refs = 0; 17 unsigned refs = 0;
17}; 18};
19struct ReleaseQueue {
20 std::mutex mutex;
21 host_heap::vector<std::pair<std::uintptr_t, std::uintptr_t>> ranges;
22 std::atomic<bool> pending{false};
23};
18struct State { 24struct State {
19 std::mutex mutex; 25 std::mutex mutex;
20 host_heap::map<std::uintptr_t, Cell> cells; 26 host_heap::map<std::uintptr_t, Cell> cells;
21 std::atomic<std::uint64_t> serial{1}; 27 std::atomic<std::uint64_t> serial{1};
22 std::atomic<std::size_t> count{0}; 28 std::atomic<std::size_t> count{0};
29 // Union of every tile passed to acquire(): [watched_lo, watched_hi). Monotonic; updated under mutex.
30 std::atomic<std::uintptr_t> watched_lo{UINTPTR_MAX};
31 std::atomic<std::uintptr_t> watched_hi{0};
32 std::mutex subscribers_mutex;
33 host_heap::vector<ReleaseQueue*> subscribers;
23}; 34};
24inline State& state() { static State s; return s; } 35inline State& state() { static State s; return s; }
25 36
37inline void subscribe(ReleaseQueue& queue) {
38 auto& s = state();
39 std::lock_guard lock(s.subscribers_mutex);
40 if (std::find(s.subscribers.begin(), s.subscribers.end(), &queue) == s.subscribers.end())
41 s.subscribers.push_back(&queue);
42}
43
44inline void unsubscribe(ReleaseQueue& queue) {
45 auto& s = state();
46 std::lock_guard lock(s.subscribers_mutex);
47 std::erase(s.subscribers, &queue);
48}
49
50inline bool has_released(const ReleaseQueue& queue) {
51 return queue.pending.load(std::memory_order_acquire);
52}
53
54// Records a title address range [begin, end) that was released or unmapped so every subscribed GeometryViews can
55// evict its views. Uses host_heap and separate leaf locks so xmem does not contend with the write-fault handler.
56// Lock order: subscribers_mutex -> queue.mutex; take_released takes only queue.mutex.
57inline void note_released(std::uintptr_t begin, std::uintptr_t end) {
58 auto& s = state();
59 if (end <= begin || !s.count.load(std::memory_order_acquire)) return;
60 const std::uintptr_t lo = s.watched_lo.load(std::memory_order_acquire);
61 const std::uintptr_t hi = s.watched_hi.load(std::memory_order_acquire);
62 if (end <= lo || begin >= hi) {
63 // Views are keyed by the CPU view's address, so a GPU-only range freed by its own address counts through its
64 // CPU view (GeometryViews::drain_released maps it there).
65 leonida::title_gpu_views::Range pair{};
66 if (!leonida::title_gpu_views::view_at(begin, 1, pair) || begin < pair.gpu || begin - pair.gpu >= pair.size)
67 return;
68 const std::uintptr_t cpu = pair.cpu + (begin - pair.gpu);
69 const std::uintptr_t span = (std::min)(end - begin, pair.size - (begin - pair.gpu));
70 if (cpu + span <= lo || cpu >= hi) return;
71 }
72 std::lock_guard subscribers_lock(s.subscribers_mutex);
73 for (ReleaseQueue* q : s.subscribers) {
74 std::lock_guard lock(q->mutex);
75 if (q->ranges.size() < 65536) {
76 q->ranges.emplace_back(begin, end);
77 } else {
78 std::uintptr_t merged_lo = begin;
79 std::uintptr_t merged_hi = end;
80 for (const auto& [r_lo, r_hi] : q->ranges) {
81 if (r_lo < merged_lo) merged_lo = r_lo;
82 if (r_hi > merged_hi) merged_hi = r_hi;
83 }
84 q->ranges.clear();
85 q->ranges.emplace_back(merged_lo, merged_hi);
86 }
87 q->pending.store(true, std::memory_order_release);
88 }
89}
90
91template<class Out>
92inline void take_released(ReleaseQueue& queue, Out& out) {
93 out.clear();
94 if (!queue.pending.load(std::memory_order_acquire)) return;
95 std::lock_guard lock(queue.mutex);
96 out.assign(queue.ranges.begin(), queue.ranges.end());
97 queue.ranges.clear();
98 queue.pending.store(false, std::memory_order_release);
99}
100
26inline Cell* acquire(std::uintptr_t va) { 101inline Cell* acquire(std::uintptr_t va) {
27 auto& s = state(); 102 auto& s = state();
28 std::lock_guard lock(s.mutex); 103 std::lock_guard lock(s.mutex);
29 auto& c = s.cells[va]; 104 auto& c = s.cells[va];
30 ++c.refs; 105 ++c.refs;
106 const std::uintptr_t tile_end = va <= UINTPTR_MAX - tile_size ? va + tile_size : UINTPTR_MAX;
107 if (va < s.watched_lo.load(std::memory_order_relaxed))
108 s.watched_lo.store(va, std::memory_order_release);
109 if (tile_end > s.watched_hi.load(std::memory_order_relaxed))
110 s.watched_hi.store(tile_end, std::memory_order_release);
31 s.count.store(s.cells.size(), std::memory_order_release); 111 s.count.store(s.cells.size(), std::memory_order_release);
32 return &c; 112 return &c;
33} 113}
diff --git a/runtime/src/title_page_watch.h b/runtime/src/title_page_watch.h
index ccc085466..9d0a2ccfc 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) {
204// Bumped by every change of set(). 204// Bumped by every change of set().
205inline std::uint64_t generation() { return state().generation.load(std::memory_order_acquire); } 205inline std::uint64_t generation() { return state().generation.load(std::memory_order_acquire); }
206 206
207// Up to `n` aliased pages, and how many there are (a probe's sample; no order).
208inline std::size_t sample(std::vector<std::uintptr_t>& out, std::size_t n) {
209 State& s = state();
210 out.clear();
211 std::shared_lock lock(s.mutex);
212 for (const std::uintptr_t va : s.aliased) {
213 if (out.size() >= n) break;
214 out.push_back(va);
215 }
216 return s.aliased.size();
217}
218
207// Calls `f(va)` for each aliased 64 KiB page overlapping [begin, end). 219// Calls `f(va)` for each aliased 64 KiB page overlapping [begin, end).
208template<class F> 220template<class F>
209void for_each_in(std::uintptr_t begin, std::uintptr_t end, F&& f) { 221void 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_
258 return true; 270 return true;
259} 271}
260 272
273// Both addresses of every pair, as [start, end) ranges (LEONIDA_CONSOLE_HEAP_GPU's ask table); `count()` changes
274// with them.
275inline void spans(std::vector<std::pair<std::uint64_t, std::uint64_t>>& out) {
276 State& s = state();
277 out.clear();
278 if (!s.count.load(std::memory_order_acquire)) return;
279 std::shared_lock lock(s.mutex);
280 for (const View& v : s.views) {
281 out.emplace_back(v.gpu, v.gpu + v.size);
282 out.emplace_back(v.cpu, v.cpu + v.size);
283 }
284}
285inline std::size_t count() { return state().count.load(std::memory_order_acquire); }
261// Marks the pair whose GPU-only range starts at `gpu` as one whose GPU-only range has pages of its own (queue slot 31 286// Marks the pair whose GPU-only range starts at `gpu` as one whose GPU-only range has pages of its own (queue slot 31
262// or XMemMapPhysicalPages map them at that address, not through the CPU view): the host reads it there (to_cpu) and 287// or XMemMapPhysicalPages map them at that address, not through the CPU view): the host reads it there (to_cpu) and
263// a slot-133 buffer over it is a shadow, not an import (independently_mapped). False when no pair starts at `gpu`. 288// 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 ed7c0f2b6..feb8a0cc2 100644
--- a/runtime/src/title_texture_refresh.h
+++ b/runtime/src/title_texture_refresh.h
@@ -1,5 +1,7 @@
1#pragma once 1#pragma once
2#include <algorithm> 2#include <algorithm>
3#include <bit>
4#include <map>
3#include <cstdint> 5#include <cstdint>
4#include <utility> 6#include <utility>
5#include <vector> 7#include <vector>
@@ -8,6 +10,48 @@ namespace leonida {
8 10
9using TitleWriteRanges = std::vector<std::pair<std::uintptr_t, std::uintptr_t>>; 11using TitleWriteRanges = std::vector<std::pair<std::uintptr_t, std::uintptr_t>>;
10 12
13// Store each texture once, in the smallest aligned power-of-two page containing its CPU range.
14// A journal interval needs only the overlapping pages at each occupied size. Aliases keep distinct keys.
15class TitleTextureRangeIndex {
16 using Address = std::uint64_t;
17 struct Range { Address first, last; };
18 using PageKey = std::pair<Address, Address>; // page, registry key
19 std::map<unsigned, std::map<PageKey, Range>> pages_;
20 std::map<Address, std::pair<unsigned, Address>> location_;
21 static Address page(Address at, unsigned shift) { return shift == 64 ? 0 : at >> shift; }
22
23public:
24 void erase(Address key) {
25 const auto where = location_.find(key);
26 if (where == location_.end()) return;
27 const auto [shift, number] = where->second;
28 auto level = pages_.find(shift);
29 level->second.erase({number, key});
30 if (level->second.empty()) pages_.erase(level);
31 location_.erase(where);
32 }
33 void set(Address key, Address first, Address bytes) {
34 erase(key);
35 if (!bytes) return;
36 const Address last = first + std::min(bytes - 1, UINT64_MAX - first);
37 const unsigned shift = unsigned(std::bit_width(first ^ last));
38 const Address number = page(first, shift);
39 pages_[shift][{number, key}] = {first, last};
40 location_[key] = {shift, number};
41 }
42 template<class Visit>
43 void overlapping(Address from, Address to, Visit visit) const {
44 if (from >= to) return;
45 for (const auto& [shift, entries] : pages_) {
46 const Address last = page(to - 1, shift);
47 for (auto it = entries.lower_bound({page(from, shift), 0});
48 it != entries.end() && it->first.first <= last; ++it) {
49 if (it->second.first < to && from <= it->second.last) visit(it->first.second);
50 }
51 }
52 }
53};
54
11// Sorted, disjoint half-open intervals let each texture find its first possible writer by end address. 55// Sorted, disjoint half-open intervals let each texture find its first possible writer by end address.
12inline void merge_title_writes(TitleWriteRanges& writes) { 56inline void merge_title_writes(TitleWriteRanges& writes) {
13 std::sort(writes.begin(), writes.end()); 57 std::sort(writes.begin(), writes.end());
@@ -34,10 +78,13 @@ inline bool title_write_overlaps(const TitleWriteRanges& writes, std::uintptr_t
34// the walk would step through a freed node. The list holds a reference to each entry, so an entry erased during the 78// the walk would step through a freed node. The list holds a reference to each entry, so an entry erased during the
35// pass is still alive when its turn comes. 79// pass is still alive when its turn comes.
36template<class Registry> 80template<class Registry>
37std::vector<std::pair<std::uint64_t, typename Registry::mapped_type>> title_texture_snapshot(const Registry& textures) { 81std::vector<std::pair<std::uint64_t, typename Registry::mapped_type>> title_texture_snapshot(
82 const Registry& textures, std::uint64_t start = 0, std::size_t limit = SIZE_MAX) {
38 std::vector<std::pair<std::uint64_t, typename Registry::mapped_type>> entries; 83 std::vector<std::pair<std::uint64_t, typename Registry::mapped_type>> entries;
39 entries.reserve(textures.size()); 84 const auto count = std::min(textures.size(), limit);
40 for (const auto& [address, texture] : textures) entries.emplace_back(address, texture); 85 entries.reserve(count);
86 for (auto it = textures.lower_bound(start); it != textures.end() && entries.size() < count; ++it)
87 entries.emplace_back(it->first, it->second);
41 return entries; 88 return entries;
42} 89}
43 90
@@ -60,4 +107,38 @@ void poll_title_textures(const std::vector<Entry>& entries, std::uint64_t& curso
60 } 107 }
61} 108}
62 109
110// Visit the marked textures of a snapshot (mapped by the title, or known stale) under a time limit
111// (LEONIDA_TITLE_EVERY_BUDGET_US). Those `urgent` answers true for (a mapped texture never filled yet) are all
112// visited first, in placement order, whatever the limit. The others are visited
113// from `cursor`, as poll_title_textures does for the unmarked ones, until `exhausted()` answers true after a visit;
114// the next pass resumes at the entry after the last one visited, so every marked texture gets its turn however many
115// there are. An entry skipped as unmarked costs no check.
116template<class Entry, class Visit, class Urgent, class Exhausted>
117void visit_marked_title_textures(const std::vector<Entry>& entries, std::uint64_t& cursor, Visit visit, Urgent urgent,
118 Exhausted exhausted) {
119 if (entries.empty()) return;
120 // Which entries are urgent is decided before any visit: a visit fills the texture, and it must not come round
121 // again in the rotation of the same pass.
122 std::vector<char> was_urgent(entries.size());
123 for (std::size_t i = 0; i < entries.size(); ++i) {
124 const auto& texture = entries[i].second;
125 was_urgent[i] = (texture->mapped || texture->stale) && urgent(*texture);
126 }
127 for (std::size_t i = 0; i < entries.size(); ++i)
128 if (was_urgent[i]) visit(*entries[i].second);
129 const auto first = std::lower_bound(entries.begin(), entries.end(), cursor,
130 [](const Entry& entry, std::uint64_t at) { return entry.first < at; });
131 auto index = std::size_t(first - entries.begin());
132 if (index == entries.size()) index = 0;
133 for (auto left = entries.size(); left; --left) {
134 const auto& [address, texture] = entries[index];
135 cursor = address + 1;
136 if ((texture->mapped || texture->stale) && !was_urgent[index]) {
137 visit(*texture);
138 if (exhausted()) break;
139 }
140 index = index + 1 == entries.size() ? 0 : index + 1;
141 }
142}
143
63} // namespace leonida 144} // namespace leonida
diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h
index b3de5ce70..f3fd2b410 100644
--- a/runtime/src/title_va_alias.h
+++ b/runtime/src/title_va_alias.h
@@ -16,7 +16,10 @@
16// that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the 16// that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the
17// buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was 17// buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was
18// added to it, so it is tested without a GPU (title_va_alias_test). 18// added to it, so it is tested without a GPU (title_va_alias_test).
19#include "descriptor_range_changes.h"
19#include <algorithm> 20#include <algorithm>
21#include "buffer_va_index.h"
22
20#include <array> 23#include <array>
21#include <atomic> 24#include <atomic>
22#include <cstddef> 25#include <cstddef>
@@ -49,8 +52,11 @@ public:
49 if (!bytes || title_va > UINT64_MAX - bytes) return false; 52 if (!bytes || title_va > UINT64_MAX - bytes) return false;
50 std::unique_lock lock(mutex_); 53 std::unique_lock lock(mutex_);
51 erase_overlapping(title_va, title_va + bytes); 54 erase_overlapping(title_va, title_va + bytes);
55 changes_.record(title_va, bytes);
52 ranges_[title_va] = {title_va + bytes, shader_va}; 56 ranges_[title_va] = {title_va + bytes, shader_va};
57 by_shader_.insert(shader_va, bytes, title_va);
53 count_.store(ranges_.size(), std::memory_order_release); 58 count_.store(ranges_.size(), std::memory_order_release);
59 generation_.fetch_add(1, std::memory_order_release);
54 return true; 60 return true;
55 } 61 }
56 62
@@ -68,12 +74,29 @@ public:
68 std::unique_lock lock(mutex_); 74 std::unique_lock lock(mutex_);
69 const auto it = ranges_.find(title_va); 75 const auto it = ranges_.find(title_va);
70 if (it != ranges_.end() && it->second.shader_va == shader_va) { 76 if (it != ranges_.end() && it->second.shader_va == shader_va) {
77 changes_.record(it->first, it->second.end - it->first);
78 by_shader_.erase(shader_va, title_va);
79 note_removed(it->second.shader_va, it->second.end - it->first);
71 ranges_.erase(it); 80 ranges_.erase(it);
72 invalidations_.fetch_add(1, std::memory_order_release); 81 invalidations_.fetch_add(1, std::memory_order_release);
82 generation_.fetch_add(1, std::memory_order_release);
73 } 83 }
74 count_.store(ranges_.size(), std::memory_order_release); 84 count_.store(ranges_.size(), std::memory_order_release);
75 } 85 }
76 86
87 // A copy that answered for [title_va, title_va + bytes) at shader_va went, whether or not it had a range here (a
88 // geometry copy that vsharp_address or a placed view reached through GeometryViews directly has none): what was
89 // translated through it is stale. Recorded as a removal would be: the console heaps translate the slots in the
90 // range again (invalidations, changed_ranges), and the GPU key table drops answers into shader_va (take_removed).
91 void forget_copy(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) {
92 if (!bytes) return;
93 std::unique_lock lock(mutex_);
94 changes_.record(title_va, bytes);
95 note_removed(shader_va, bytes);
96 invalidations_.fetch_add(1, std::memory_order_release);
97 generation_.fetch_add(1, std::memory_order_release);
98 }
99
77 // The address a shader must be given for `va` from the ranges added so far: translated inside one, unchanged 100 // The address a shader must be given for `va` from the ranges added so far: translated inside one, unchanged
78 // elsewhere. No copy is made here. 101 // elsewhere. No copy is made here.
79 std::uint64_t shader_va(std::uint64_t va, std::uint64_t bytes = 1) const { 102 std::uint64_t shader_va(std::uint64_t va, std::uint64_t bytes = 1) const {
@@ -113,6 +136,16 @@ public:
113 for (const auto& [start, range] : ranges_) out.push_back({start, range.end, range.shader_va}); 136 for (const auto& [start, range] : ranges_) out.push_back({start, range.end, range.shader_va});
114 } 137 }
115 138
139 // Whether `shader_va` lies in the copy of a range added so far: an address the layer itself wrote for the title
140 // (a window, a geometry copy, a slot-133 shadow or import), which a later scan of the same descriptor sees again.
141 // A binary search over the copies' addresses (source_of_vsharp walks every range).
142 bool shader_side(std::uint64_t shader_va) const {
143 if (!count_.load(std::memory_order_acquire)) return false;
144 std::shared_lock lock(mutex_);
145 BufferVaIndex<std::uint64_t>::Hit hit{};
146 return by_shader_.find(shader_va, hit);
147 }
148
116 // Debug-only inverse lookup. V#s retain 48 bits, so an import below heap_base wraps. 149 // Debug-only inverse lookup. V#s retain 48 bits, so an import below heap_base wraps.
117 bool source_of_vsharp(std::uint64_t base, std::uint64_t& title, std::uint64_t& available) const { 150 bool source_of_vsharp(std::uint64_t base, std::uint64_t& title, std::uint64_t& available) const {
118 constexpr std::uint64_t mask = (1ull << 48) - 1; 151 constexpr std::uint64_t mask = (1ull << 48) - 1;
@@ -208,11 +241,15 @@ public:
208 it = memory_.erase(it); 241 it = memory_.erase(it);
209 } 242 }
210 memory_[begin] = end; 243 memory_[begin] = end;
244 memory_generation_.fetch_add(1, std::memory_order_release);
211 } 245 }
212 void remove_title_memory(std::uint64_t base) { 246 void remove_title_memory(std::uint64_t base) {
213 std::unique_lock lock(memory_mutex_); 247 std::unique_lock lock(memory_mutex_);
214 memory_.erase(base); 248 memory_.erase(base);
249 memory_generation_.fetch_add(1, std::memory_order_release);
215 } 250 }
251 // Bumped whenever title_memory_ranges() changes.
252 std::uint64_t memory_generation() const { return memory_generation_.load(std::memory_order_acquire); }
216 // LOCAL DIAGNOSTIC (mem probe): every title range, [begin, end), in address order. 253 // LOCAL DIAGNOSTIC (mem probe): every title range, [begin, end), in address order.
217 std::vector<std::pair<std::uint64_t, std::uint64_t>> title_memory_ranges() const { 254 std::vector<std::pair<std::uint64_t, std::uint64_t>> title_memory_ranges() const {
218 std::shared_lock lock(memory_mutex_); 255 std::shared_lock lock(memory_mutex_);
@@ -314,6 +351,34 @@ public:
314 351
315 std::size_t size() const { return count_.load(std::memory_order_acquire); } 352 std::size_t size() const { return count_.load(std::memory_order_acquire); }
316 std::uint64_t invalidations() const { return invalidations_.load(std::memory_order_acquire); } 353 std::uint64_t invalidations() const { return invalidations_.load(std::memory_order_acquire); }
354 bool changed_ranges(uint64_t& cursor, DescriptorRanges& ranges) const {
355 std::shared_lock lock(mutex_);
356 return changes_.read(cursor, ranges);
357 }
358 // Bumped by every add and every removal: a copy of mappings() is current while it has not moved.
359 std::uint64_t generation() const { return generation_.load(std::memory_order_acquire); }
360 // Diagnostics (fsdraw): the title VA a shader VA was made from, the reverse of translate; a linear scan.
361 bool title_of_shader(std::uint64_t shader_va, std::uint64_t& title_va, std::uint64_t& range_va,
362 std::uint64_t& range_bytes) const {
363 std::shared_lock lock(mutex_);
364 for (const auto& [va, r] : ranges_)
365 if (shader_va >= r.shader_va && shader_va - r.shader_va < r.end - va) {
366 title_va = va + (shader_va - r.shader_va);
367 range_va = va;
368 range_bytes = r.end - va;
369 return true;
370 }
371 return false;
372 }
373 // LEONIDA_CONSOLE_HEAP_GPU: the shader-VA ranges of the ranges removed (or replaced) since the last take, so a
374 // GPU table translated through them can drop what it derived. Nothing is kept until recording is turned on.
375 void record_removals(bool on) { record_removals_.store(on, std::memory_order_relaxed); }
376 void take_removed(std::vector<std::pair<std::uint64_t, std::uint64_t>>& out) {
377 out.clear();
378 if (!record_removals_.load(std::memory_order_relaxed)) return;
379 std::unique_lock lock(mutex_);
380 out.swap(removed_);
381 }
317 void note_translation(Kind kind) { translated_[kind].fetch_add(1, std::memory_order_relaxed); } 382 void note_translation(Kind kind) { translated_[kind].fetch_add(1, std::memory_order_relaxed); }
318 std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); } 383 std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); }
319 std::uint64_t untranslated(Kind kind) const { return untranslated_[kind].load(std::memory_order_relaxed); } 384 std::uint64_t untranslated(Kind kind) const { return untranslated_[kind].load(std::memory_order_relaxed); }
@@ -331,13 +396,28 @@ private:
331 if (previous->second.end > begin) it = previous; 396 if (previous->second.end > begin) it = previous;
332 } 397 }
333 if (it != ranges_.end() && it->first < end) invalidations_.fetch_add(1, std::memory_order_release); 398 if (it != ranges_.end() && it->first < end) invalidations_.fetch_add(1, std::memory_order_release);
334 while (it != ranges_.end() && it->first < end) it = ranges_.erase(it); 399 while (it != ranges_.end() && it->first < end) {
400 changes_.record(it->first, it->second.end - it->first);
401 by_shader_.erase(it->second.shader_va, it->first);
402 note_removed(it->second.shader_va, it->second.end - it->first);
403 it = ranges_.erase(it);
404 }
335 } 405 }
336 406
407 // mutex_ held exclusively.
408 void note_removed(std::uint64_t shader_va, std::uint64_t bytes) {
409 if (record_removals_.load(std::memory_order_relaxed)) removed_.push_back({shader_va, bytes});
410 }
411
412 DescriptorRangeChanges changes_;
337 mutable std::shared_mutex mutex_; 413 mutable std::shared_mutex mutex_;
338 std::map<std::uint64_t, Range> ranges_; // by title VA 414 std::map<std::uint64_t, Range> ranges_; // by title VA
415 BufferVaIndex<std::uint64_t> by_shader_; // the same ranges by shader VA (id: the title VA); copies may overlap
339 std::atomic<std::size_t> count_{0}; 416 std::atomic<std::size_t> count_{0};
340 std::atomic<std::uint64_t> invalidations_{}; 417 std::atomic<std::uint64_t> invalidations_{};
418 std::atomic<std::uint64_t> generation_{};
419 std::atomic<bool> record_removals_{false};
420 std::vector<std::pair<std::uint64_t, std::uint64_t>> removed_; // (shader VA, bytes), when recorded
341 std::mutex hook_mutex_; 421 std::mutex hook_mutex_;
342 void* hook_context_ = nullptr; 422 void* hook_context_ = nullptr;
343 void* maker_context_ = nullptr; 423 void* maker_context_ = nullptr;
@@ -352,6 +432,7 @@ private:
352 std::atomic<std::uint64_t> scans_{0}, scan_ns_{0}, scan_max_ns_{0}; 432 std::atomic<std::uint64_t> scans_{0}, scan_ns_{0}, scan_max_ns_{0};
353 mutable std::shared_mutex memory_mutex_; 433 mutable std::shared_mutex memory_mutex_;
354 std::map<std::uint64_t, std::uint64_t> memory_; // the title's memory: base -> end 434 std::map<std::uint64_t, std::uint64_t> memory_; // the title's memory: base -> end
435 std::atomic<std::uint64_t> memory_generation_{};
355}; 436};
356 437
357// The process's table: the device's title ranges and hooks, read by the command lists and descriptor writers. 438// The process's table: the device's title ranges and hooks, read by the command lists and descriptor writers.
@@ -360,12 +441,25 @@ inline TitleVaAliases& title_va_aliases() {
360 return aliases; 441 return aliases;
361} 442}
362 443
363// One diagnostic per descriptor-writing path. 444// One diagnostic per descriptor-writing path. Called per descriptor write on the unbacked path, so the sites already
445// told (string literals: their addresses) are looked up without the lock first.
364inline void note_unbacked_view(const char* site, std::uint64_t va, std::uint64_t bytes) { 446inline void note_unbacked_view(const char* site, std::uint64_t va, std::uint64_t bytes) {
447 static std::atomic<const char*> told[8] = {};
448 for (const auto& t : told)
449 if (t.load(std::memory_order_relaxed) == site) return;
365 static std::mutex mutex; 450 static std::mutex mutex;
366 static std::map<std::string, bool> sites; 451 static std::map<std::string, bool> sites;
367 { 452 {
368 std::lock_guard lock(mutex); 453 std::lock_guard lock(mutex);
454 for (auto& t : told) {
455 const char* none = nullptr;
456 if (t.load(std::memory_order_relaxed) == site ||
457 t.compare_exchange_strong(none, site, std::memory_order_relaxed))
458 break;
459 }
460 }
461 {
462 std::lock_guard lock(mutex);
369 if (!sites.emplace(site, true).second) return; 463 if (!sites.emplace(site, true).second) return;
370 } 464 }
371 std::fprintf(stderr, "[rt] d3d12: %s: address 0x%llx (%llu bytes) has no GPU copy; zero records\n", 465 std::fprintf(stderr, "[rt] d3d12: %s: address 0x%llx (%llu bytes) has no GPU copy; zero records\n",
diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h
index 8f2dd61f8..0cb843cef 100644
--- a/runtime/src/vulkan13_features.h
+++ b/runtime/src/vulkan13_features.h
@@ -40,6 +40,9 @@ public:
40 bool subgroup_size_control = false; 40 bool subgroup_size_control = false;
41 bool compute_full_subgroups = false; 41 bool compute_full_subgroups = false;
42 bool extended_dynamic_state = false; // core on 1.3; on 1.2 both VK_EXT_extended_dynamic_state(2) extensions 42 bool extended_dynamic_state = false; // core on 1.3; on 1.2 both VK_EXT_extended_dynamic_state(2) extensions
43 // VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT, asking a pipeline cache "do you have it?" without a
44 // compile (pipeline_cache_journal.h). Core 1.3 only; a 1.2 device goes without.
45 bool pipeline_creation_cache_control = false;
43 46
44 bool usable() const { return dynamic_rendering && synchronization2; } 47 bool usable() const { return dynamic_rendering && synchronization2; }
45 48
@@ -49,7 +52,7 @@ public:
49 core = api_version >= VK_API_VERSION_1_3; 52 core = api_version >= VK_API_VERSION_1_3;
50 pipeline_cache_control=false;enable_pipeline_cache_control=false; 53 pipeline_cache_control=false;enable_pipeline_cache_control=false;
51 dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false; 54 dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false;
52 extended_dynamic_state = false; 55 extended_dynamic_state = pipeline_creation_cache_control = false;
53 if (!features2) return; 56 if (!features2) return;
54 if (core) { 57 if (core) {
55 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; 58 VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
@@ -60,6 +63,7 @@ public:
60 synchronization2 = f13.synchronization2 == VK_TRUE; 63 synchronization2 = f13.synchronization2 == VK_TRUE;
61 subgroup_size_control = f13.subgroupSizeControl == VK_TRUE; 64 subgroup_size_control = f13.subgroupSizeControl == VK_TRUE;
62 compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE; 65 compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE;
66 pipeline_creation_cache_control = f13.pipelineCreationCacheControl == VK_TRUE;
63 extended_dynamic_state = true; // core in 1.3, no feature bit 67 extended_dynamic_state = true; // core in 1.3, no feature bit
64 return; 68 return;
65 } 69 }
@@ -108,6 +112,7 @@ public:
108 subgroup_size_control = from.subgroup_size_control; 112 subgroup_size_control = from.subgroup_size_control;
109 compute_full_subgroups = from.compute_full_subgroups; 113 compute_full_subgroups = from.compute_full_subgroups;
110 extended_dynamic_state = from.extended_dynamic_state; 114 extended_dynamic_state = from.extended_dynamic_state;
115 pipeline_creation_cache_control = from.pipeline_creation_cache_control;
111 } 116 }
112 117
113 // The structs that enable both features, ahead of `chain`; returns their head for VkPhysicalDeviceVulkan12Features' 118 // The structs that enable both features, ahead of `chain`; returns their head for VkPhysicalDeviceVulkan12Features'
@@ -120,6 +125,7 @@ public:
120 enable13_.synchronization2 = VK_TRUE; 125 enable13_.synchronization2 = VK_TRUE;
121 enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE; 126 enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE;
122 enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE; 127 enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE;
128 enable13_.pipelineCreationCacheControl = pipeline_creation_cache_control ? VK_TRUE : VK_FALSE;
123 return &enable13_; 129 return &enable13_;
124 } 130 }
125 if (subgroup_size_control) { 131 if (subgroup_size_control) {
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 145fa11ee..9fdb29640 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -30,6 +30,7 @@
30#include "resource_tiling.h" 30#include "resource_tiling.h"
31#include "pipeline_profile.h" 31#include "pipeline_profile.h"
32#include "submit_phases.h" 32#include "submit_phases.h"
33#include "pipeline_wait.h"
33#include "title_va_alias.h" 34#include "title_va_alias.h"
34#include "xdxr_build.h" 35#include "xdxr_build.h"
35 36
@@ -124,13 +125,14 @@ struct VulkanDeviceFunctions {
124 X(vkCmdPushConstants) X(vkCmdDispatch) \ 125 X(vkCmdPushConstants) X(vkCmdDispatch) \
125 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ 126 X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \
126 X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \ 127 X(vkCmdSetViewportWithCount) X(vkCmdSetScissorWithCount) \
127 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ 128 X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) X(vkCmdSetDepthBounds) \
128 X(vkCmdSetBlendConstants) X(vkCmdDraw) \ 129 X(vkCmdSetBlendConstants) X(vkCmdDraw) \
129 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ 130 X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \
130 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ 131 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \
131 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ 132 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) X(vkCmdDrawMeshTasksIndirectEXT) X(vkCmdDrawMeshTasksIndirectCountEXT) \
132 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ 133 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \
133 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) 134 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) \
135 X(vkCmdBeginQueryIndexedEXT) X(vkCmdEndQueryIndexedEXT)
134#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; 136#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr;
135 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) 137 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER)
136#undef LEONIDA_VK_MEMBER 138#undef LEONIDA_VK_MEMBER
@@ -165,6 +167,9 @@ struct VulkanDeviceFunctions {
165 return vkCmdBeginRendering && vkCmdEndRendering && vkCmdBindVertexBuffers2 && vkCmdSetPrimitiveTopology && 167 return vkCmdBeginRendering && vkCmdEndRendering && vkCmdBindVertexBuffers2 && vkCmdSetPrimitiveTopology &&
166 vkCmdSetPrimitiveRestartEnable; 168 vkCmdSetPrimitiveRestartEnable;
167 } 169 }
170 // VK_EXT_transform_feedback is enabled on the device: the indexed-query entry points are loaded, so an
171 // SO_STATISTICS heap can be a real transform-feedback pool (D3D-302).
172 bool transform_feedback = false;
168}; 173};
169 174
170// Both kinds of compute resolve use the same storage buffer, descriptor set and pipeline layout. 175// Both kinds of compute resolve use the same storage buffer, descriptor set and pipeline layout.
@@ -618,6 +623,8 @@ inline Stats& stats(int kind) {
618 static Stats s[3]; 623 static Stats s[3];
619 return s[kind < 0 || kind > 2 ? 0 : kind]; 624 return s[kind < 0 || kind > 2 ? 0 : kind];
620} 625}
626inline void held_tick(int kind); // below: the held-operations line, due on the same 10 s
627
621inline void done(int kind, std::chrono::steady_clock::time_point submitted) { 628inline void done(int kind, std::chrono::steady_clock::time_point submitted) {
622 using clock = std::chrono::steady_clock; 629 using clock = std::chrono::steady_clock;
623 const auto now = clock::now(); 630 const auto now = clock::now();
@@ -641,36 +648,66 @@ inline void done(int kind, std::chrono::steady_clock::time_point submitted) {
641 s.sum_ms = s.max_ms = s.busy_ms = 0; 648 s.sum_ms = s.max_ms = s.busy_ms = 0;
642 s.since = now; 649 s.since = now;
643 } 650 }
651 held_tick(kind);
644} 652}
645// A held queue operation (Wait before Signal), released: how long it waited on the CPU before it could run. 653// A held queue operation (Wait before Signal), released: how long it waited on the CPU before it could run.
646inline void held(int kind, int op, std::chrono::steady_clock::time_point at) { 654// A held queue operation (Wait before Signal), released: how long it waited on the CPU before it could run, and for
655// the longest one of the window the fence (semaphore handle) and value it waited for, so the slow signaller can be
656// named. The line is due every 10 s: held() prints it, and so does done() (held_tick), so a window with nothing
657// released still reports.
658struct HeldStats {
659 std::mutex mutex;
660 std::uint64_t count[3] = {};
661 double sum_ms = 0, max_ms = 0;
662 std::uint64_t max_fence = 0, max_value = 0;
663 int max_op = 0;
664 std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now();
665};
666inline HeldStats& held_stats(int kind) {
667 static HeldStats h[3];
668 return h[kind < 0 || kind > 2 ? 0 : kind];
669}
670// held_stats(kind).mutex held.
671inline void held_report_locked(int kind, HeldStats& s, std::chrono::steady_clock::time_point now) {
672 if (now - s.since < std::chrono::seconds(10)) return;
673 const std::uint64_t all = s.count[0] + s.count[1] + s.count[2];
674 std::fprintf(stderr, "[rt] gpu latency (%s): %llu held operations released in %.0f s (%llu batches, %llu "
675 "signals, %llu markers), held %.2f ms on average, %.1f ms the longest",
676 kind == 0 ? "direct" : kind == 1 ? "compute" : "copy", static_cast<unsigned long long>(all),
677 std::chrono::duration<double>(now - s.since).count(), static_cast<unsigned long long>(s.count[0]),
678 static_cast<unsigned long long>(s.count[1]), static_cast<unsigned long long>(s.count[2]),
679 all ? s.sum_ms / double(all) : 0.0, s.max_ms);
680 if (all && s.max_fence)
681 std::fprintf(stderr, " (a %s waiting for fence 0x%llx value %llu)",
682 s.max_op == 0 ? "batch" : s.max_op == 1 ? "Signal" : "marker",
683 static_cast<unsigned long long>(s.max_fence), static_cast<unsigned long long>(s.max_value));
684 std::fputc('\n', stderr);
685 s.count[0] = s.count[1] = s.count[2] = 0;
686 s.sum_ms = s.max_ms = 0;
687 s.max_fence = s.max_value = 0;
688 s.since = now;
689}
690inline void held(int kind, int op, std::chrono::steady_clock::time_point at, std::uint64_t fence = 0,
691 std::uint64_t value = 0) {
647 using clock = std::chrono::steady_clock; 692 using clock = std::chrono::steady_clock;
648 struct Held { 693 HeldStats& s = held_stats(kind);
649 std::mutex mutex;
650 std::uint64_t count[3] = {};
651 double sum_ms = 0, max_ms = 0;
652 clock::time_point since = clock::now();
653 };
654 static Held h[3];
655 Held& s = h[kind < 0 || kind > 2 ? 0 : kind];
656 const auto now = clock::now(); 694 const auto now = clock::now();
657 const double ms = std::chrono::duration<double, std::milli>(now - at).count(); 695 const double ms = std::chrono::duration<double, std::milli>(now - at).count();
658 std::lock_guard lock(s.mutex); 696 std::lock_guard lock(s.mutex);
659 ++s.count[op < 0 || op > 2 ? 0 : op]; 697 ++s.count[op < 0 || op > 2 ? 0 : op];
660 s.sum_ms += ms; 698 s.sum_ms += ms;
661 s.max_ms = (std::max)(s.max_ms, ms); 699 if (ms > s.max_ms) {
662 if (now - s.since >= std::chrono::seconds(10)) { 700 s.max_ms = ms;
663 const std::uint64_t all = s.count[0] + s.count[1] + s.count[2]; 701 s.max_fence = fence;
664 std::fprintf(stderr, "[rt] gpu latency (%s): %llu held operations released in %.0f s (%llu batches, %llu " 702 s.max_value = value;
665 "signals, %llu markers), held %.2f ms on average, %.1f ms the longest\n", 703 s.max_op = op;
666 kind == 0 ? "direct" : kind == 1 ? "compute" : "copy", static_cast<unsigned long long>(all),
667 std::chrono::duration<double>(now - s.since).count(), static_cast<unsigned long long>(s.count[0]),
668 static_cast<unsigned long long>(s.count[1]), static_cast<unsigned long long>(s.count[2]),
669 all ? s.sum_ms / double(all) : 0.0, s.max_ms);
670 s.count[0] = s.count[1] = s.count[2] = 0;
671 s.sum_ms = s.max_ms = 0;
672 s.since = now;
673 } 704 }
705 held_report_locked(kind, s, now);
706}
707inline void held_tick(int kind) {
708 HeldStats& s = held_stats(kind);
709 std::lock_guard lock(s.mutex);
710 held_report_locked(kind, s, std::chrono::steady_clock::now());
674} 711}
675} // namespace gpu_latency 712} // namespace gpu_latency
676 713
@@ -1090,6 +1127,8 @@ public:
1090 GraphicsIndirectCapabilities indirect = {}) 1127 GraphicsIndirectCapabilities indirect = {})
1091 : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) { 1128 : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) {
1092 loaded_ = vk.load(get, device); 1129 loaded_ = vk.load(get, device);
1130 // VK_EXT_transform_feedback: enabled on the device when its indexed-query entry points resolved (D3D-302).
1131 vk.transform_feedback = vk.vkCmdBeginQueryIndexedEXT && vk.vkCmdEndQueryIndexedEXT;
1093 if (loaded_ && gpu_labels_.initialize(device, get)) { 1132 if (loaded_ && gpu_labels_.initialize(device, get)) {
1094 replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); }; 1133 replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); };
1095 } 1134 }
@@ -1125,6 +1164,11 @@ public:
1125 replay_.reset_query_pool = vk.vkCmdResetQueryPool; 1164 replay_.reset_query_pool = vk.vkCmdResetQueryPool;
1126 replay_.begin_query = vk.vkCmdBeginQuery; 1165 replay_.begin_query = vk.vkCmdBeginQuery;
1127 replay_.end_query = vk.vkCmdEndQuery; 1166 replay_.end_query = vk.vkCmdEndQuery;
1167 // VK_EXT_transform_feedback (D3D-302), loaded when the device enabled it: indexed SO_STATISTICS queries.
1168 if (vk.transform_feedback) {
1169 replay_.begin_query_indexed = vk.vkCmdBeginQueryIndexedEXT;
1170 replay_.end_query_indexed = vk.vkCmdEndQueryIndexedEXT;
1171 }
1128 replay_.write_timestamp = vk.vkCmdWriteTimestamp; 1172 replay_.write_timestamp = vk.vkCmdWriteTimestamp;
1129 replay_.copy_query_pool_results = vk.vkCmdCopyQueryPoolResults; 1173 replay_.copy_query_pool_results = vk.vkCmdCopyQueryPoolResults;
1130 replay_.bind_pipeline = vk.vkCmdBindPipeline; 1174 replay_.bind_pipeline = vk.vkCmdBindPipeline;
@@ -1148,8 +1192,11 @@ public:
1148 replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; 1192 replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable;
1149 replay_.set_stencil_reference = vk.vkCmdSetStencilReference; 1193 replay_.set_stencil_reference = vk.vkCmdSetStencilReference;
1150 replay_.set_blend_constants = vk.vkCmdSetBlendConstants; 1194 replay_.set_blend_constants = vk.vkCmdSetBlendConstants;
1195 replay_.set_depth_bounds = vk.vkCmdSetDepthBounds;
1151 replay_.draw = vk.vkCmdDraw; 1196 replay_.draw = vk.vkCmdDraw;
1152 replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled 1197 replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled
1198 replay_.draw_mesh_tasks_indirect = vk.vkCmdDrawMeshTasksIndirectEXT;
1199 replay_.draw_mesh_tasks_indirect_count = vk.vkCmdDrawMeshTasksIndirectCountEXT;
1153 replay_.draw_indexed = vk.vkCmdDrawIndexed; 1200 replay_.draw_indexed = vk.vkCmdDrawIndexed;
1154 replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { 1201 replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* {
1155 const auto it = graphics_pipelines_.find(id); 1202 const auto it = graphics_pipelines_.find(id);
@@ -1278,8 +1325,12 @@ public:
1278 1325
1279 bool loaded() const { return loaded_; } 1326 bool loaded() const { return loaded_; }
1280 1327
1281 void configure_device_fault(PFN_vkGetDeviceProcAddr get, DeviceFaultExtensions enabled) { 1328 // `memory`: the physical device's memory types, for the AMD marker buffer (enabled.markers).
1282 device_fault_ = std::make_unique<DeviceFaultDiagnostics>(get, device_, enabled); 1329 void configure_device_fault(PFN_vkGetDeviceProcAddr get, DeviceFaultExtensions enabled,
1330 const VkPhysicalDeviceMemoryProperties* memory = nullptr) {
1331 device_fault_ = std::make_unique<DeviceFaultDiagnostics>(get, device_, enabled, memory,
1332 vk.vkCmdPipelineBarrier2 != nullptr);
1333 device_fault_->set_submit_lock(&submit_mutex_);
1283 if (fence_dispatcher_) fence_dispatcher_->set_device_fault(device_fault_.get()); 1334 if (fence_dispatcher_) fence_dispatcher_->set_device_fault(device_fault_.get());
1284 if (loaded_) progress_watch_ = std::jthread([this](std::stop_token stop) { watch_queue_progress(stop); }); 1335 if (loaded_) progress_watch_ = std::jthread([this](std::stop_token stop) { watch_queue_progress(stop); });
1285 } 1336 }
@@ -1326,14 +1377,19 @@ public:
1326 // device-local memory, and must set VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT. LEONIDA_INDIRECT_CLAMP=0 turns the 1377 // device-local memory, and must set VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT. LEONIDA_INDIRECT_CLAMP=0 turns the
1327 // pass off at replay time. 1378 // pass off at replay time.
1328 void enable_indirect_clamp(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, 1379 void enable_indirect_clamp(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory,
1329 const VkPhysicalDeviceLimits& limits, ScratchBuffers::Allocate allocate) { 1380 const VkPhysicalDeviceLimits& limits, ScratchBuffers::Allocate allocate,
1381 std::vector<std::uint32_t> families = {}) {
1330 std::unique_lock lock(resource_mutex_); 1382 std::unique_lock lock(resource_mutex_);
1383 // An enabled clamp is required: a call whose scratch preparation fails is refused (unsupported) instead of
1384 // reading the application's argument buffer, which may hold a record no compute pass wrote. Off, or on a
1385 // device the pass cannot run on, the replay keeps the application's buffer as before.
1331 replay_.require_indirect_clamp = indirect_clamp_enabled(); 1386 replay_.require_indirect_clamp = indirect_clamp_enabled();
1332 if (!replay_.require_indirect_clamp) return; 1387 if (!replay_.require_indirect_clamp) return;
1333 indirect_clamp_ = std::make_unique<IndirectArgumentClamp>(get, device_, memory, limits, std::move(allocate), 1388 indirect_clamp_ = std::make_unique<IndirectArgumentClamp>(get, device_, memory, limits, std::move(allocate),
1334 device_fault_.get()); 1389 device_fault_.get(), std::move(families));
1335 if (!indirect_clamp_->loaded()) { 1390 if (!indirect_clamp_->loaded()) {
1336 indirect_clamp_.reset(); 1391 indirect_clamp_.reset();
1392 replay_.require_indirect_clamp = false;
1337 return; 1393 return;
1338 } 1394 }
1339 // The preparation callback needs this submission's counter-slot batch, so it is set per ExecuteCommandLists 1395 // The preparation callback needs this submission's counter-slot batch, so it is set per ExecuteCommandLists
@@ -1545,32 +1601,42 @@ public:
1545 } 1601 }
1546 1602
1547 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. 1603 // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives.
1604 // Guarded by pipeline_mutex_ (separate from resource_mutex_) so shader compilation on one queue does not block
1605 // resource registration or destruction on the render thread.
1548 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) { 1606 void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline, const char* shader = nullptr) {
1549 std::unique_lock lock(resource_mutex_); 1607 std::unique_lock lock(pipeline_mutex_);
1550 pipelines_[id] = pipeline; 1608 pipelines_[id] = pipeline;
1551 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader}; 1609 if (shader && device_fault_) device_fault_->pipeline_names[id] = {shader};
1552 } 1610 }
1553 void remove_pipeline(std::uintptr_t id) { 1611 void remove_pipeline(std::uintptr_t id) {
1554 std::unique_lock lock(resource_mutex_); 1612 std::unique_lock lock(pipeline_mutex_);
1555 pipelines_.erase(id); 1613 pipelines_.erase(id);
1556 graphics_pipelines_.erase(id); 1614 graphics_pipelines_.erase(id);
1557 if (device_fault_) device_fault_->pipeline_names.erase(id); 1615 if (device_fault_) device_fault_->pipeline_names.erase(id);
1558 } 1616 }
1559 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline, 1617 void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline,
1560 const CheckpointShaders* shaders = nullptr) { 1618 const CheckpointShaders* shaders = nullptr) {
1561 std::unique_lock lock(resource_mutex_); 1619 std::unique_lock lock(pipeline_mutex_);
1562 graphics_pipelines_[id] = pipeline; 1620 graphics_pipelines_[id] = pipeline;
1563 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders; 1621 if (shaders && device_fault_) device_fault_->pipeline_names[id] = *shaders;
1564 } 1622 }
1565 // Workers for the pipelines a submission needs and that are not built yet. Null (the default): each is built where 1623 // Workers for the pipelines a submission needs and that are not built yet. Null (the default): compiled serially on
1566 // prepare() meets it, on the submitting thread. Replacing it waits for submissions that are compiling, and ends the 1624 // the submitting thread once resource_mutex_ is released. Replacing it waits for submissions that are compiling, and
1567 // workers it had. 1625 // ends the workers it had.
1568 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) { 1626 void set_pipeline_workers(std::unique_ptr<PipelineWorkers> workers) {
1569 std::unique_lock lock(resource_mutex_); 1627 std::unique_lock lock(pipeline_mutex_);
1570 pipeline_workers_.swap(workers); 1628 pipeline_workers_.swap(workers);
1571 } 1629 }
1630 // For the large pipelines of a submission: the memory they may use while they compile together
1631 // (PipelineCompiles::build), and what is kept while they do (LargeModuleGate::Demand). None (the default): they compile
1632 // one after another.
1633 void set_large_compiles(std::function<std::uint64_t()> budget, std::function<std::shared_ptr<void>()> demand) {
1634 std::unique_lock lock(pipeline_mutex_);
1635 large_compile_budget_ = std::move(budget);
1636 large_compile_demand_ = std::move(demand);
1637 }
1572 PipelineWorkers::Stats pipeline_worker_stats() { 1638 PipelineWorkers::Stats pipeline_worker_stats() {
1573 std::shared_lock lock(resource_mutex_); 1639 std::shared_lock lock(pipeline_mutex_);
1574 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; 1640 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{};
1575 } 1641 }
1576 // Configure before queue creation, when the selected queue family supports compute. 1642 // Configure before queue creation, when the selected queue family supports compute.
@@ -1584,6 +1650,44 @@ public:
1584 return host_texture_stats_; 1650 return host_texture_stats_;
1585 } 1651 }
1586 1652
1653 // LOCAL FIX (deadlock on the first-run pages): the texture writes below used vkDeviceWaitIdle with the submit
1654 // lock held. The device is idle only once every queue has run all it was given, and a queue whose submitted
1655 // work waits on a value a later submission signals never gets there while this thread keeps the lock: a native
1656 // boot sat 270 s in vkDeviceWaitIdle (title staging), then lost the device. Instead: wait for the queue
1657 // timelines to pass what was submitted so far, at most `timeout`; on VK_TIMEOUT the caller skips this write (the
1658 // title-texture pass tries it again) rather than freeze the title. Not covered, unlike the device wait: present
1659 // and probe submissions, which have their own fences outside the retirement timelines (a present reading the
1660 // image). The staged write is ordered behind them anyway (same queue, an ALL_COMMANDS barrier); the host copy
1661 // is not, so a presented title texture can be written while a present still reads it (a torn frame, no fault).
1662 // With submit_mutex_ held.
1663 VkResult wait_submitted_locked(std::uint64_t timeout_ns, const char* what) {
1664 if (is_device_lost()) return VK_ERROR_DEVICE_LOST; // a queue's timeline may be gone already
1665 const auto pending = retire_tickets_.pending_through(submitted_ticket_.load(std::memory_order_acquire));
1666 if (pending.empty()) return VK_SUCCESS;
1667 std::vector<VkSemaphore> semaphores;
1668 std::vector<std::uint64_t> values;
1669 for (const auto& [semaphore, value] : pending) {
1670 semaphores.push_back(semaphore);
1671 values.push_back(value);
1672 }
1673 VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO};
1674 wait.semaphoreCount = std::uint32_t(semaphores.size());
1675 wait.pSemaphores = semaphores.data();
1676 wait.pValues = values.data();
1677 const VkResult r = observe_result(vk.vkWaitSemaphores(device_, &wait, timeout_ns), what);
1678 if (r == VK_TIMEOUT) {
1679 static std::atomic<std::uint64_t> timeouts{0};
1680 const std::uint64_t n = timeouts.fetch_add(1, std::memory_order_relaxed) + 1;
1681 if (!(n & (n - 1)))
1682 std::fprintf(stderr, "[rt] vulkan: %s: submitted work not done within %llu ms (%llu time(s)); the "
1683 "write is skipped this time\n", what,
1684 static_cast<unsigned long long>(timeout_ns / 1000000), static_cast<unsigned long long>(n));
1685 }
1686 return r;
1687 }
1688 // Short: a timeout is certain when the awaited work needs this thread's lock, and the write is only skipped.
1689 static constexpr std::uint64_t kTitleWriteWaitNs = 250'000'000; // 250 ms
1690
1587 // CPU writes to a title texture have no application fence. Prevent another queue from 1691 // CPU writes to a title texture have no application fence. Prevent another queue from
1588 // claiming a new layout or submitting work between the completion check and the host copy. 1692 // claiming a new layout or submitting work between the completion check and the host copy.
1589 // An unsatisfied console Wait lives in QueueHolds, outside the Vulkan queues. 1693 // An unsatisfied console Wait lives in QueueHolds, outside the Vulkan queues.
@@ -1594,7 +1698,13 @@ public:
1594 if (tracker_.layout(id, subresource) != VK_IMAGE_LAYOUT_GENERAL) return VK_NOT_READY; 1698 if (tracker_.layout(id, subresource) != VK_IMAGE_LAYOUT_GENERAL) return VK_NOT_READY;
1595 if (image_work_pending_) { 1699 if (image_work_pending_) {
1596 ++host_texture_stats_.waits; 1700 ++host_texture_stats_.waits;
1597 const auto result = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title texture upload)"); 1701 // A device wait is a queue operation: it passes the compile gate, so it never waits in the driver behind a
1702 // long pipeline create (the starved wait that loses the device after 10 s).
1703 const SubmitMutex::SubmitTurn turn(submit_mutex_);
1704 const auto result = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title texture upload)");
1705 // Not done in time: VK_NOT_READY, so the caller takes its staged path (ordered on the queue) or tries
1706 // again later, and the skip is not counted as a failed fill.
1707 if (result == VK_TIMEOUT) return VK_NOT_READY;
1598 if (result != VK_SUCCESS) return result; 1708 if (result != VK_SUCCESS) return result;
1599 image_work_pending_ = false; 1709 image_work_pending_ = false;
1600 } 1710 }
@@ -1612,7 +1722,8 @@ public:
1612 LayoutPieces pieces; 1722 LayoutPieces pieces;
1613 if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN; 1723 if (!tracker_.pieces(id, range, pieces) || pieces.empty()) return VK_ERROR_UNKNOWN;
1614 if (image_work_pending_) { 1724 if (image_work_pending_) {
1615 const auto r = observe_result(vk.vkDeviceWaitIdle(device_), "vkDeviceWaitIdle (title staging)"); 1725 const SubmitMutex::SubmitTurn turn(submit_mutex_); // a queue operation: the compile gate (as above)
1726 const auto r = wait_submitted_locked(kTitleWriteWaitNs, "vkWaitSemaphores (title staging)");
1616 if (r != VK_SUCCESS) return r; 1727 if (r != VK_SUCCESS) return r;
1617 image_work_pending_ = false; 1728 image_work_pending_ = false;
1618 } 1729 }
@@ -1737,7 +1848,6 @@ public:
1737 // `before` is called at the start of every submission of command lists (a held batch: when it is released), 1848 // `before` is called at the start of every submission of command lists (a held batch: when it is released),
1738 // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there. 1849 // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there.
1739 // Set once, before the first queue exists. 1850 // Set once, before the first queue exists.
1740 void set_before_execute(std::function<void()> before) { before_execute_ = std::move(before); }
1741 1851
1742 // Table VAs are offsets in this device's arena. Install its scanner before creating any queues. 1852 // Table VAs are offsets in this device's arena. Install its scanner before creating any queues.
1743 // (The per-device scan is from the patch descriptor-table-refresh, part 2, of 1853 // (The per-device scan is from the patch descriptor-table-refresh, part 2, of
@@ -1774,11 +1884,25 @@ public:
1774 return true; 1884 return true;
1775 } 1885 }
1776 const char* diagnostic_compute_name(std::uintptr_t id) { 1886 const char* diagnostic_compute_name(std::uintptr_t id) {
1777 std::shared_lock lock(resource_mutex_); 1887 std::shared_lock lock(pipeline_mutex_);
1778 if (!device_fault_) return nullptr; 1888 if (!device_fault_) return nullptr;
1779 const auto it = device_fault_->pipeline_names.find(id); 1889 const auto it = device_fault_->pipeline_names.find(id);
1780 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; 1890 return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0];
1781 } 1891 }
1892 void set_before_execute(std::function<void()> before) { before_execute_ = std::move(before); }
1893 // Called at the end of every ExecuteCommandLists replay that called before_execute_, however it returns: by then
1894 // the submissions it made are recorded, so submitted_retire_ticket() covers them.
1895 void set_after_execute(std::function<void()> after) { after_execute_ = std::move(after); }
1896 // GPU work the lists of a submission depend on, recorded at the start of its command buffer by a queue that can
1897 // run compute (the console heap translation pass, src/console_heap_gpu.h): `record` returns true when it recorded
1898 // something, and `commit` follows that submit (true: it reached the queue; the ticket is a retire ticket at or
1899 // after it). Every other queue's next submission then waits for that one, as for a bindless table upload: a
1900 // queue that records nothing itself may run lists that read what the pass wrote. Called with tracker_mutex_
1901 // held, so passes and those waits follow submission order. Set once, before the first queue exists.
1902 void set_prelude(std::function<bool(VkCommandBuffer)> record, std::function<void(bool, std::uint64_t)> commit) {
1903 prelude_record_ = std::move(record);
1904 prelude_commit_ = std::move(commit);
1905 }
1782 1906
1783 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) { 1907 void set_bindless_prepare(std::function<bool(VkCommandBuffer)> prepare) {
1784 std::unique_lock lock(resource_mutex_); 1908 std::unique_lock lock(resource_mutex_);
@@ -1802,6 +1926,11 @@ public:
1802 }; 1926 };
1803 } 1927 }
1804 1928
1929 bool has_depth24() {
1930 std::shared_lock lock(resource_mutex_);
1931 return depth24_ != nullptr;
1932 }
1933
1805 // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from 1934 // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from
1806 // `allocate`. Without this such a copy is refused as unsupported. `extra_usage` is added to the chunks' transfer 1935 // `allocate`. Without this such a copy is refused as unsupported. `extra_usage` is added to the chunks' transfer
1807 // usage, for configure_quad_indices. 1936 // usage, for configure_quad_indices.
@@ -1933,7 +2062,14 @@ public:
1933 VulkanDeviceFunctions vk; 2062 VulkanDeviceFunctions vk;
1934 2063
1935 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. 2064 // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one.
1936 std::mutex& submit_mutex() { return submit_mutex_; } 2065 SubmitMutex& submit_mutex() { return submit_mutex_; }
2066
2067 // vkQueueSubmit through the compile gate (SubmitMutex::SubmitTurn): it waits here, not in the driver, while a
2068 // pipeline create is in the driver. Called with the submit lock held; the caller observes the result.
2069 VkResult queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, VkFence fence) {
2070 const SubmitMutex::SubmitTurn turn(submit_mutex_);
2071 return vk.vkQueueSubmit(queue, count, submits, fence);
2072 }
1937 2073
1938 void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept { 2074 void mark_device_lost(const char* where = "a Vulkan call returned VK_ERROR_DEVICE_LOST") noexcept {
1939 set_device_lost(device_lost_, where); 2075 set_device_lost(device_lost_, where);
@@ -2103,19 +2239,32 @@ private:
2103 using Watch = SubmissionProgressWatch; 2239 using Watch = SubmissionProgressWatch;
2104 Watch watch; 2240 Watch watch;
2105 std::uint64_t retired = 0; 2241 std::uint64_t retired = 0;
2242 std::int64_t reported_hold = -1;
2243 std::int64_t busy_since = -1;
2244 SubmitMutex::GateStats gate_logged;
2245 unsigned tick = 0;
2106 std::mutex timer_mutex; 2246 std::mutex timer_mutex;
2107 std::condition_variable_any timer; 2247 std::condition_variable_any timer;
2108 std::unique_lock timer_lock(timer_mutex); 2248 std::unique_lock timer_lock(timer_mutex);
2249 // LOCAL DIAGNOSTIC (post-load GPU hangs): with the device-fault report on, sample every 250 ms, so a loss the
2250 // driver has already reset is seen (and its checkpoints read) before a watchdog outside kills the process.
2251 const auto period = device_fault_ ? std::chrono::milliseconds(250) : std::chrono::milliseconds(1000);
2252 const unsigned per_10s = unsigned(std::chrono::seconds(10) / period);
2109 while (!stop.stop_requested()) { 2253 while (!stop.stop_requested()) {
2110 timer.wait_for(timer_lock, stop, std::chrono::seconds(1), [] { return false; }); 2254 timer.wait_for(timer_lock, stop, period, [] { return false; });
2111 if (stop.stop_requested() || is_device_lost()) break; 2255 if (stop.stop_requested() || is_device_lost()) break;
2112 auto state = Watch::State::submit_lock_busy; 2256 auto state = Watch::State::submit_lock_busy;
2113 VkResult result = VK_SUCCESS; 2257 VkResult result = VK_SUCCESS;
2114 std::uint64_t submitted; 2258 std::uint64_t submitted;
2115 { 2259 {
2116 // Keep queue timelines alive as in completed_retire_ticket(). A submit or idle wait 2260 // Keep queue timelines alive as in completed_retire_ticket(). A submit or idle wait
2117 // blocked inside the driver can hold this mutex indefinitely. 2261 // blocked inside the driver can hold this mutex indefinitely. Under heavy submission one try finds
2262 // it busy most of the time: a few more within a millisecond or two.
2118 std::unique_lock lock(submit_mutex_, std::try_to_lock); 2263 std::unique_lock lock(submit_mutex_, std::try_to_lock);
2264 for (int retry = 0; !lock.owns_lock() && retry < 20; ++retry) {
2265 std::this_thread::sleep_for(std::chrono::microseconds(100));
2266 if (lock.try_lock()) break;
2267 }
2119 submitted = submitted_retire_ticket(); 2268 submitted = submitted_retire_ticket();
2120 if (lock.owns_lock()) { 2269 if (lock.owns_lock()) {
2121 if (is_device_lost()) break; 2270 if (is_device_lost()) break;
@@ -2123,12 +2272,49 @@ private:
2123 state = retired < submitted ? Watch::State::pending : Watch::State::idle; 2272 state = retired < submitted ? Watch::State::pending : Watch::State::idle;
2124 } 2273 }
2125 } 2274 }
2275 // LOCAL DIAGNOSTIC (early device loss): a submission unfinished for 4 s dumps the recent submissions with
2276 // their semaphore counters (unreadable once the device is lost); a hold of the submit lock of 3 s names
2277 // its thread and prints its call chain, once per hold.
2278 // A vkQueueSubmit stuck in the driver (measured: 10 s, then VK_ERROR_DEVICE_LOST) also blocks
2279 // vkGetSemaphoreCounterValue, so with the lock busy the watch stays out of the driver: the holder report
2280 // samples stacks only, and the counters are read once the lock is free again.
2281 if (state == Watch::State::submit_lock_busy) {
2282 const std::uint32_t owner = submit_mutex_.owner();
2283 const std::int64_t since = submit_mutex_.since_ms();
2284 const std::int64_t held = diagnostic_ms() - since;
2285 if (owner && held >= 3000 && since != reported_hold) {
2286 reported_hold = since;
2287 device_fault_->report_submit_lock_holder(owner, held);
2288 }
2289 // Busy at every sample but changing hands: contended, not stuck. Only a hold that lasts (the same
2290 // holder since the same time) counts toward the 15 s stall report.
2291 if (since != busy_since) {
2292 busy_since = since;
2293 state = Watch::State::idle;
2294 }
2295 } else {
2296 device_fault_->check_submit_progress();
2297 }
2126 if (result == VK_ERROR_DEVICE_LOST) { 2298 if (result == VK_ERROR_DEVICE_LOST) {
2127 mark_device_lost(); 2299 mark_device_lost();
2128 break; 2300 break;
2129 } 2301 }
2130 // A failed counter query does not measure GPU progress. 2302 // A failed counter query does not measure GPU progress.
2131 if (result != VK_SUCCESS) state = Watch::State::idle; 2303 if (result != VK_SUCCESS) state = Watch::State::idle;
2304 // Every 10 s while it changes: what the compile gate has cost so far (SubmitMutex::CompileTurn).
2305 if (++tick % per_10s == 0) {
2306 const SubmitMutex::GateStats gate = submit_mutex_.gate_stats();
2307 if (gate.submits != gate_logged.submits || gate.creates != gate_logged.creates) {
2308 gate_logged = gate;
2309 std::fprintf(stderr, "[rt] compile-gate: t=%.0f s: %llu submissions waited for pipeline creates "
2310 "(%lld ms in all, longest %lld ms); %llu creates waited behind a submission "
2311 "(%lld ms in all, longest %lld ms)\n",
2312 double(diagnostic_ms()) / 1000.0, static_cast<unsigned long long>(gate.submits),
2313 static_cast<long long>(gate.submit_ms), static_cast<long long>(gate.submit_max_ms),
2314 static_cast<unsigned long long>(gate.creates), static_cast<long long>(gate.create_ms),
2315 static_cast<long long>(gate.create_max_ms));
2316 }
2317 }
2132 // LEONIDA_HANG_EXIT_S=<s> (for boots): work pending and retirement still for s seconds is a GPU hang 2318 // LEONIDA_HANG_EXIT_S=<s> (for boots): work pending and retirement still for s seconds is a GPU hang
2133 // the driver may recover from without Vulkan ever reporting the device lost (Xid 109: the title then 2319 // the driver may recover from without Vulkan ever reporting the device lost (Xid 109: the title then
2134 // waits forever, the window frozen). The stall is reported (with the checkpoints under 2320 // waits forever, the window frozen). The stall is reported (with the checkpoints under
@@ -2156,7 +2342,9 @@ private:
2156 } 2342 }
2157 if (watch.sample(state, retired, Watch::Clock::now())) 2343 if (watch.sample(state, retired, Watch::Clock::now()))
2158 device_fault_->report_stall(state == Watch::State::pending ? "queue retirement has not advanced" 2344 device_fault_->report_stall(state == Watch::State::pending ? "queue retirement has not advanced"
2159 : "could not sample the submit lock", 2345 : submit_mutex_.gate_waiter() && submit_mutex_.gate_waiter() == submit_mutex_.owner()
2346 ? "could not sample the submit lock (its holder waits at the compile gate)"
2347 : "could not sample the submit lock",
2160 submitted, retired); 2348 submitted, retired);
2161 } 2349 }
2162 } 2350 }
@@ -2166,10 +2354,17 @@ private:
2166 bool ray_tracing_ = false; 2354 bool ray_tracing_ = false;
2167 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records 2355 std::unique_ptr<XdxrBuilder> xdxr_; // set: acceleration structures are XDXR BVH4 records
2168 std::atomic<bool> device_lost_{false}; 2356 std::atomic<bool> device_lost_{false};
2357 alignas(64) std::shared_mutex pipeline_mutex_; // shared for prepare/compile/emit pipeline lookups, unique for add/remove/workers
2169 alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove 2358 alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove
2170 alignas(64) std::mutex tracker_mutex_; 2359 alignas(64) std::mutex tracker_mutex_;
2171 alignas(64) std::mutex views_mutex_; 2360 alignas(64) std::mutex views_mutex_;
2172 alignas(64) std::mutex submit_mutex_; 2361 // Lock hierarchy (see VulkanQueue::execute): resource_mutex_ -> tracker_mutex_ -> submit_mutex_. A PSO build
2362 // (shims/d3d12_vulkan_device.cpp, PipelineState::build_compute / build) holds its variants_mutex_ and the
2363 // static big_compile mutex while it waits for the submit lock (SubmitMutex::let_submit_finish) or at the compile
2364 // gate: variants_mutex_ -> big_compile -> submit_mutex_, and nothing holding submit_mutex_ takes either. The
2365 // gate's own mutex is a leaf; a submission waits at the gate with submit_mutex_ held, for creates already in the
2366 // driver only (SubmitMutex::CompileTurn).
2367 alignas(64) SubmitMutex submit_mutex_;
2173 bool image_work_pending_ = false; // under submit_mutex_ 2368 bool image_work_pending_ = false; // under submit_mutex_
2174 HostTextureStats host_texture_stats_; // under submit_mutex_ 2369 HostTextureStats host_texture_stats_; // under submit_mutex_
2175 RetireTickets<VkSemaphore> retire_tickets_; 2370 RetireTickets<VkSemaphore> retire_tickets_;
@@ -2185,6 +2380,8 @@ private:
2185 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; 2380 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_;
2186 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 2381 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
2187 std::unique_ptr<PipelineWorkers> pipeline_workers_; 2382 std::unique_ptr<PipelineWorkers> pipeline_workers_;
2383 std::function<std::uint64_t()> large_compile_budget_;
2384 std::function<std::shared_ptr<void>()> large_compile_demand_;
2188 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 2385 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
2189 LayoutTracker tracker_; 2386 LayoutTracker tracker_;
2190 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only 2387 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only
@@ -2206,6 +2403,7 @@ private:
2206 resolve_passes_; 2403 resolve_passes_;
2207 std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_; 2404 std::map<std::tuple<VkImage, VkImage, VkImageView, VkImageView, VkRenderPass>, VkFramebuffer> resolve_framebuffers_;
2208 std::function<void()> before_execute_; 2405 std::function<void()> before_execute_;
2406 std::function<void()> after_execute_;
2209 InputProbe input_probe_; 2407 InputProbe input_probe_;
2210 TableScanner table_scanner_; 2408 TableScanner table_scanner_;
2211 GeometryProvider geometry_provider_; 2409 GeometryProvider geometry_provider_;
@@ -2219,6 +2417,11 @@ private:
2219 VkSemaphore bindless_upload_semaphore_ = VK_NULL_HANDLE; 2417 VkSemaphore bindless_upload_semaphore_ = VK_NULL_HANDLE;
2220 std::uint64_t bindless_upload_value_ = 0; 2418 std::uint64_t bindless_upload_value_ = 0;
2221 std::uint64_t bindless_upload_version_ = 0; 2419 std::uint64_t bindless_upload_version_ = 0;
2420 std::function<bool(VkCommandBuffer)> prelude_record_;
2421 std::function<void(bool, std::uint64_t)> prelude_commit_;
2422 VkSemaphore prelude_semaphore_ = VK_NULL_HANDLE; // the queue whose submission recorded the last prelude
2423 std::uint64_t prelude_value_ = 0;
2424 std::uint64_t prelude_version_ = 0;
2222 std::unique_ptr<Depth24Converter> depth24_; 2425 std::unique_ptr<Depth24Converter> depth24_;
2223 std::unique_ptr<ScratchBuffers> scratch_; // copies staged through a buffer (depth <-> colour) 2426 std::unique_ptr<ScratchBuffers> scratch_; // copies staged through a buffer (depth <-> colour)
2224 std::function<void(bool)> bindless_commit_; 2427 std::function<void(bool)> bindless_commit_;
@@ -2256,7 +2459,19 @@ public:
2256 } 2459 }
2257 ~VulkanFence() { 2460 ~VulkanFence() {
2258 if (!semaphore_) return; 2461 if (!semaphore_) return;
2462 // LOCAL DIAGNOSTIC (early device loss): a fence released while a Signal the GPU has not run yet names it.
2463 if (!context_.is_device_lost()) {
2464 const std::uint64_t submitted = context_.holds().submitted_value(semaphore_);
2465 std::uint64_t reached = 0;
2466 if (submitted && context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &reached) == VK_SUCCESS &&
2467 reached < submitted)
2468 std::fprintf(stderr, "[rt] d3d12: fence semaphore %p destroyed with a Signal pending (submitted %llu, "
2469 "reached %llu) at t=%.3f s\n",
2470 static_cast<void*>(semaphore_), static_cast<unsigned long long>(submitted),
2471 static_cast<unsigned long long>(reached), double(diagnostic_ms()) / 1000.0);
2472 }
2259 context_.holds().remove_fence(semaphore_); // batches held on it can never run: dropped and reported 2473 context_.holds().remove_fence(semaphore_); // batches held on it can never run: dropped and reported
2474 if (DeviceFaultDiagnostics* ring = context_.device_fault()) ring->forget(semaphore_); // no report reads it
2260 context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr); 2475 context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr);
2261 } 2476 }
2262 VulkanFence(const VulkanFence&) = delete; 2477 VulkanFence(const VulkanFence&) = delete;
@@ -2390,16 +2605,24 @@ public:
2390 2605
2391 ~VulkanQueue() { 2606 ~VulkanQueue() {
2392 auto& vk = context_.vk; 2607 auto& vk = context_.vk;
2608 stop_async(); // LEONIDA_SUBMIT_ASYNC: what is queued runs first
2609 std::fprintf(stderr, "[rt] d3d12: queue %p (progress %p) destroyed at t=%.3f s\n", static_cast<void*>(queue_),
2610 static_cast<void*>(progress_), double(diagnostic_ms()) / 1000.0);
2393 context_.holds().detach(this); // no thread releases into this queue from here on 2611 context_.holds().detach(this); // no thread releases into this queue from here on
2394 report_held_at_teardown(); 2612 report_held_at_teardown();
2395 context_.holds().pump_ready(); // presents queued behind what was just dropped can run 2613 context_.holds().pump_ready(); // presents queued behind what was just dropped can run
2396 if (queue_) { 2614 if (queue_) {
2397 std::lock_guard lock(context_.submit_mutex()); 2615 std::lock_guard lock(context_.submit_mutex());
2616 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
2398 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); 2617 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_);
2399 const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle"); 2618 const VkResult idle_result = context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle");
2400 if (idle_result == VK_SUCCESS) { 2619 if (idle_result == VK_SUCCESS) {
2401 if (progress_) context_.retire_queue_idle_locked(progress_); 2620 if (progress_) context_.retire_queue_idle_locked(progress_);
2402 } else { 2621 } else {
2622 // Any failure here makes every fence read ~0 from now on: say so when it is not a real loss.
2623 if (idle_result != VK_ERROR_DEVICE_LOST)
2624 std::fprintf(stderr, "[rt] d3d12: vkQueueWaitIdle at queue teardown returned %d; the device is "
2625 "treated as lost\n", int(idle_result));
2403 context_.mark_device_lost(); 2626 context_.mark_device_lost();
2404 } 2627 }
2405 } 2628 }
@@ -2414,9 +2637,15 @@ public:
2414 // finished: the next submission on another queue must not wait on a semaphore that is about to go. 2637 // finished: the next submission on another queue must not wait on a semaphore that is about to go.
2415 std::lock_guard lock(context_.storage_mutex_); 2638 std::lock_guard lock(context_.storage_mutex_);
2416 if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE; 2639 if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE;
2640 // The same for the bindless table upload: a queue that had not seen its version yet would otherwise
2641 // wait on this destroyed semaphore in its next vkQueueSubmit.
2642 if (context_.bindless_upload_semaphore_ == progress_) context_.bindless_upload_semaphore_ = VK_NULL_HANDLE;
2417 } 2643 }
2418 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); 2644 if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr);
2419 if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); 2645 if (progress_) {
2646 if (DeviceFaultDiagnostics* ring = context_.device_fault()) ring->forget(progress_); // no report reads it
2647 vk.vkDestroySemaphore(context_.device(), progress_, nullptr);
2648 }
2420 destroy_khr_stages(khr_stage_pool_); 2649 destroy_khr_stages(khr_stage_pool_);
2421 destroy_khr_as_queries(khr_as_query_pool_); 2650 destroy_khr_as_queries(khr_as_query_pool_);
2422 for (auto& slot : buffers_) { 2651 for (auto& slot : buffers_) {
@@ -2431,6 +2660,8 @@ public:
2431 VulkanQueue& operator=(const VulkanQueue&) = delete; 2660 VulkanQueue& operator=(const VulkanQueue&) = delete;
2432 2661
2433 bool ok() const { return ok_; } 2662 bool ok() const { return ok_; }
2663 // A queue of the runtime's own whose caller waits for each call (a staging copy): never on a worker.
2664 void make_synchronous() { synchronous_ = true; }
2434 2665
2435 // Entries kept between executions. Execute only uses the first lists.size(); a larger count is retained storage, 2666 // Entries kept between executions. Execute only uses the first lists.size(); a larger count is retained storage,
2436 // not work the next submission will replay (vk_queue_test checks both halves of that contract). 2667 // not work the next submission will replay (vk_queue_test checks both halves of that contract).
@@ -2439,6 +2670,7 @@ public:
2439 template<typename GetHeap> 2670 template<typename GetHeap>
2440 bool update_tiles(ResourceId id, std::span<const TileRegion> regions, 2671 bool update_tiles(ResourceId id, std::span<const TileRegion> regions,
2441 std::span<const TileRange> ranges, GetHeap&& get_heap) { 2672 std::span<const TileRange> ranges, GetHeap&& get_heap) {
2673 flush_async(); // after the calls queued before it (LEONIDA_SUBMIT_ASYNC)
2442 std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads 2674 std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads
2443 std::unique_lock lock(context_.resource_mutex_); 2675 std::unique_lock lock(context_.resource_mutex_);
2444 const auto it = context_.sparse_resources_.find(id); 2676 const auto it = context_.sparse_resources_.find(id);
@@ -2486,6 +2718,7 @@ public:
2486 2718
2487 bool copy_tile_mappings(ResourceId dst, std::span<const TileRegion> dst_regions, ResourceId src, 2719 bool copy_tile_mappings(ResourceId dst, std::span<const TileRegion> dst_regions, ResourceId src,
2488 std::span<const TileRegion> src_regions) { 2720 std::span<const TileRegion> src_regions) {
2721 flush_async();
2489 std::lock_guard state(state_mutex_); 2722 std::lock_guard state(state_mutex_);
2490 std::unique_lock lock(context_.resource_mutex_); 2723 std::unique_lock lock(context_.resource_mutex_);
2491 const auto source = context_.sparse_resources_.find(src), target = context_.sparse_resources_.find(dst); 2724 const auto source = context_.sparse_resources_.find(src), target = context_.sparse_resources_.find(dst);
@@ -2518,8 +2751,23 @@ public:
2518 using PinFn = std::function<std::shared_ptr<void>()>; 2751 using PinFn = std::function<std::shared_ptr<void>()>;
2519 2752
2520 ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) { 2753 ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) {
2754 pipeline_wait::note_submission(); // big compute warm-ups are left to their first use while the title submits
2521 auto* diagnostics = context_.device_fault(); 2755 auto* diagnostics = context_.device_fault();
2522 const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0; 2756 const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0;
2757 if (async_on()) { // copied and queued: the worker replays it (a failure is reported as a held one's)
2758 Call call;
2759 call.kind = Call::Kind::execute;
2760 call.execute_call = execute_call;
2761 call.lists.reserve(lists.size());
2762 for (const CommandList* list : lists) call.lists.push_back(*list);
2763 if (pin) call.pin = pin();
2764 enqueue(std::move(call));
2765 return ReplayResult::success;
2766 }
2767 return execute_sync(lists, pin, execute_call);
2768 }
2769
2770 ReplayResult execute_sync(std::span<const CommandList* const> lists, const PinFn& pin, std::uint64_t execute_call) {
2523 ReplayResult result = ReplayResult::success; 2771 ReplayResult result = ReplayResult::success;
2524 bool held = false; 2772 bool held = false;
2525 std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released 2773 std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released
@@ -2550,6 +2798,19 @@ public:
2550 // held operations, so the fence does not run ahead of the work it follows. `pin` (called only when the Signal is 2798 // held operations, so the fence does not run ahead of the work it follows. `pin` (called only when the Signal is
2551 // held) keeps the fence object alive until it has been submitted, as D3D12 does. 2799 // held) keeps the fence object alive until it has been submitted, as D3D12 does.
2552 bool signal(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { 2800 bool signal(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) {
2801 if (async_on()) {
2802 Call call;
2803 call.kind = Call::Kind::signal;
2804 call.fence = fence;
2805 call.value = value;
2806 if (pin) call.pin = pin();
2807 enqueue(std::move(call));
2808 return true;
2809 }
2810 return signal_sync(fence, value, pin);
2811 }
2812
2813 bool signal_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin) {
2553 bool ok = true; 2814 bool ok = true;
2554 std::vector<std::shared_ptr<void>> retired; 2815 std::vector<std::shared_ptr<void>> retired;
2555 { 2816 {
@@ -2563,6 +2824,10 @@ public:
2563 hold(std::move(op)); 2824 hold(std::move(op));
2564 } else { 2825 } else {
2565 ok = submit(VK_NULL_HANDLE, fence, value); 2826 ok = submit(VK_NULL_HANDLE, fence, value);
2827 // As for a held Signal (release_held): the fence object, and so its semaphore, stays alive until the
2828 // GPU has run the signal. Destroying a semaphore a pending submission signals is undefined
2829 // (VUID-vkDestroySemaphore-semaphore-05149), and a title may release a fence right after Signal.
2830 if (ok && pin) pin_queue_.push_back({submitted_, pin()});
2566 } 2831 }
2567 drain_pins(retired); 2832 drain_pins(retired);
2568 } 2833 }
@@ -2575,6 +2840,19 @@ public:
2575 // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet). 2840 // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet).
2576 // `pin` returns what keeps the fence object alive until then (a D3D12 queue holds its fences). 2841 // `pin` returns what keeps the fence object alive until then (a D3D12 queue holds its fences).
2577 void wait(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { 2842 void wait(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) {
2843 if (async_on()) {
2844 Call call;
2845 call.kind = Call::Kind::wait;
2846 call.fence = fence;
2847 call.value = value;
2848 if (pin) call.pin = pin();
2849 enqueue(std::move(call));
2850 return;
2851 }
2852 wait_sync(fence, value, pin);
2853 }
2854
2855 void wait_sync(VkSemaphore fence, std::uint64_t value, const PinFn& pin) {
2578 std::vector<std::shared_ptr<void>> retired; // fences whose submission has completed: released unlocked 2856 std::vector<std::shared_ptr<void>> retired; // fences whose submission has completed: released unlocked
2579 { 2857 {
2580 std::lock_guard state(state_mutex_); 2858 std::lock_guard state(state_mutex_);
@@ -2595,6 +2873,18 @@ public:
2595 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end 2873 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end
2596 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension. 2874 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension.
2597 void marker(DebugMarker::Kind kind, const char* label) { 2875 void marker(DebugMarker::Kind kind, const char* label) {
2876 if (async_on()) {
2877 Call call;
2878 call.kind = Call::Kind::marker;
2879 call.marker_kind = kind;
2880 call.label = label ? label : "";
2881 enqueue(std::move(call));
2882 return;
2883 }
2884 marker_sync(kind, label);
2885 }
2886
2887 void marker_sync(DebugMarker::Kind kind, const char* label) {
2598 std::vector<std::shared_ptr<void>> retired; 2888 std::vector<std::shared_ptr<void>> retired;
2599 std::lock_guard state(state_mutex_); 2889 std::lock_guard state(state_mutex_);
2600 drain_pins(retired); // destroyed after the lock (reverse declaration order) 2890 drain_pins(retired); // destroyed after the lock (reverse declaration order)
@@ -2610,7 +2900,9 @@ public:
2610 } 2900 }
2611 2901
2612 bool idle() { 2902 bool idle() {
2903 flush_async();
2613 std::lock_guard lock(context_.submit_mutex()); 2904 std::lock_guard lock(context_.submit_mutex());
2905 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
2614 return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS; 2906 return context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle") == VK_SUCCESS;
2615 } 2907 }
2616 2908
@@ -2871,6 +3163,12 @@ private:
2871 if (context_.is_device_lost() || !wait_for_room()) return queue_unsupported(__LINE__); 3163 if (context_.is_device_lost() || !wait_for_room()) return queue_unsupported(__LINE__);
2872 } 3164 }
2873 if (context_.before_execute_) context_.before_execute_(); 3165 if (context_.before_execute_) context_.before_execute_();
3166 struct AfterExecute {
3167 VulkanContext& context;
3168 ~AfterExecute() {
3169 if (context.after_execute_) context.after_execute_();
3170 }
3171 } after_execute{context_};
2874 // The rest of this call is the replay phase; the submission is counted when it returns, however it returns. 3172 // The rest of this call is the replay phase; the submission is counted when it returns, however it returns.
2875 struct Replayed { 3173 struct Replayed {
2876 std::int64_t start = submit_phases::now_ns(); 3174 std::int64_t start = submit_phases::now_ns();
@@ -2899,11 +3197,15 @@ private:
2899 } 3197 }
2900 } khr_guard{this}; 3198 } khr_guard{this};
2901 std::function<void(bool)> bindless_commit; 3199 std::function<void(bool)> bindless_commit;
2902 // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. 3200 // Lock hierarchy: state_mutex_ -> pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ -> submit_mutex_.
2903 // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during 3201 // Shared pipeline_lock keeps registered pipelines, pipeline_names, and pipeline_workers_ alive across
2904 // prepare() only if a list actually converts a depth24_as_float copy, and otherwise right before 3202 // preparation, compilation, and emit. Shared resource_lock allows concurrent prepare() across queues and is
2905 // bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and submissions stay in order. 3203 // released while unbuilt pipelines compile so add_resource()/remove_resource() never stall behind shader
2906 std::shared_lock resource_lock(context_.resource_mutex_); 3204 // compiles; tracker_mutex_ is acquired lazily during prepare() only if a list uses a shared helper, and
3205 // otherwise right before bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and
3206 // submissions stay in order.
3207 std::shared_lock pipeline_lock(context_.pipeline_mutex_);
3208 std::shared_lock resource_lock(context_.resource_mutex_, std::defer_lock);
2907 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 3209 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
2908 // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools 3210 // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools
2909 // with ticket 0 while tracker_lock is still held. 3211 // with ticket 0 while tracker_lock is still held.
@@ -2914,7 +3216,7 @@ private:
2914 ~Depth24Guard() { 3216 ~Depth24Guard() {
2915 if (active && d24) d24->retire(progress, 0); 3217 if (active && d24) d24->retire(progress, 0);
2916 } 3218 }
2917 } depth24_guard{context_.depth24_.get(), progress_, false}; 3219 } depth24_guard{nullptr, progress_, false};
2918 struct ScratchGuard { // the same for the copy scratch 3220 struct ScratchGuard { // the same for the copy scratch
2919 ScratchBuffers* scratch = nullptr; 3221 ScratchBuffers* scratch = nullptr;
2920 VkSemaphore progress = VK_NULL_HANDLE; 3222 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2922,7 +3224,7 @@ private:
2922 ~ScratchGuard() { 3224 ~ScratchGuard() {
2923 if (active && scratch) scratch->retire(progress, 0); 3225 if (active && scratch) scratch->retire(progress, 0);
2924 } 3226 }
2925 } scratch_guard{context_.scratch_.get(), progress_, false}; 3227 } scratch_guard{nullptr, progress_, false};
2926 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch 3228 struct ClampGuard { // and for the ExecuteIndirect clamp's record scratch
2927 IndirectArgumentClamp* clamp = nullptr; 3229 IndirectArgumentClamp* clamp = nullptr;
2928 VkSemaphore progress = VK_NULL_HANDLE; 3230 VkSemaphore progress = VK_NULL_HANDLE;
@@ -2930,9 +3232,8 @@ private:
2930 ~ClampGuard() { 3232 ~ClampGuard() {
2931 if (active && clamp) clamp->retire(progress, 0); 3233 if (active && clamp) clamp->retire(progress, 0);
2932 } 3234 }
2933 } clamp_guard{context_.indirect_clamp_.get(), progress_, false}; 3235 } clamp_guard{nullptr, progress_, false};
2934 const bool transfer_only = family_ == context_.transfer_only_family_; 3236 const bool transfer_only = family_ == context_.transfer_only_family_;
2935 if (!transfer_only) bindless_commit = context_.bindless_commit_;
2936 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where 3237 // Kept between executions: prepare refills each list's entries in the storage the last execution left, where
2937 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). 3238 // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench).
2938 auto& prepared = prepared_; 3239 auto& prepared = prepared_;
@@ -2940,42 +3241,9 @@ private:
2940 // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below 3241 // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below
2941 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. 3242 // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted.
2942 if (prepared.size() < lists.size()) prepared.resize(lists.size()); 3243 if (prepared.size() < lists.size()) prepared.resize(lists.size());
2943 ReplayFunctions replay = context_.replay_; 3244 ReplayFunctions replay{};
2944 unsigned mesh_draws = 0; 3245 unsigned mesh_draws = 0;
2945 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
2946 std::vector<VulkanContext::GeometryUpload> geometry; 3246 std::vector<VulkanContext::GeometryUpload> geometry;
2947 if (context_.geometry_provider_) {
2948 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
2949 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
2950 for (const auto& upload : geometry) {
2951 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
2952 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
2953 return true;
2954 }
2955 VulkanContext::GeometryUpload upload;
2956 if (!context_.geometry_provider_(va,bytes,upload)) return false;
2957 buffer=upload.buffer;offset=upload.offset;
2958 geometry.push_back(std::move(upload));
2959 return true;
2960 };
2961 }
2962 replay.graphics_family = family_ == context_.graphics_family_;
2963 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
2964 : kind_ == QueueKind::compute ? detail::queue_stages_compute
2965 : 0;
2966 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
2967 VkDeviceAddress& address) {
2968 return stage_khr_instances(replay, build, khr_guard.stages, address);
2969 };
2970 replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) {
2971 return stage_xdxr_table(khr_guard.stages, address, count);
2972 };
2973 if (replay.write_acceleration_structures_properties) {
2974 replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool,
2975 std::uint32_t& first) {
2976 return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first);
2977 };
2978 }
2979 std::uint64_t captures = 0; 3247 std::uint64_t captures = 0;
2980 for (const auto* list : lists) 3248 for (const auto* list : lists)
2981 for (const auto& command : list->commands()) 3249 for (const auto& command : list->commands())
@@ -2984,149 +3252,239 @@ private:
2984 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch; 3252 std::unique_ptr<PredicatedBufferCopier::Batch> copy_batch;
2985 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch; 3253 std::unique_ptr<IndirectDispatchCounter::Batch> counted_batch;
2986 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch; 3254 std::unique_ptr<IndirectArgumentClamp::Batch> clamp_batch;
2987 if (captures) { 3255 const auto& occlusion_memory = context_.occlusion_resolve_memory_;
2988 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) 3256 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0;
2989 return queue_unsupported(__LINE__); 3257 const auto resolve = [this](ResourceId id) { return context_.resolve(id); };
2990 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, 3258 std::uint32_t segments = 0, statistics_segments = 0;
2991 // retaining main's resource -> tracker -> submit lock order through emit and submission. 3259 bool has_queries = false;
2992 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3260 const auto run_compiles = [this](std::size_t count, const std::function<void(std::size_t)>& job) {
2993 batch = context_.predicate_reducer_->batch(captures); 3261 context_.pipeline_workers_->run(count, job);
2994 if (!batch) return queue_unsupported(__LINE__); 3262 };
2995 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { 3263 PipelineCompiles prior_compiles;
2996 return batch->prepare(buffer, offset, out); 3264 bool has_prior_compiles = false;
3265 for (int pass = 0;; ++pass) {
3266 resource_lock.lock();
3267 bindless_commit = !transfer_only ? context_.bindless_commit_ : std::function<void(bool)>{};
3268 replay = context_.replay_;
3269 mesh_draws = 0;
3270 if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws;
3271 if (context_.geometry_provider_) {
3272 replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) {
3273 if (!va || !bytes || bytes>UINT64_MAX-va) return false;
3274 for (const auto& upload : geometry) {
3275 if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue;
3276 buffer=upload.buffer; offset=upload.offset+(va-upload.source);
3277 return true;
3278 }
3279 VulkanContext::GeometryUpload upload;
3280 if (!context_.geometry_provider_(va,bytes,upload)) return false;
3281 buffer=upload.buffer;offset=upload.offset;
3282 geometry.push_back(std::move(upload));
3283 return true;
3284 };
3285 }
3286 replay.graphics_family = family_ == context_.graphics_family_;
3287 replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy
3288 : kind_ == QueueKind::compute ? detail::queue_stages_compute
3289 : 0;
3290 replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build,
3291 VkDeviceAddress& address) {
3292 return stage_khr_instances(replay, build, khr_guard.stages, address);
2997 }; 3293 };
2998 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { 3294 replay.prepare_xdxr_table = [this, &khr_guard](VkDeviceAddress& address, std::uint32_t& count) {
2999 context_.predicate_reducer_->capture(cb, p); 3295 return stage_xdxr_table(khr_guard.stages, address, count);
3000 }; 3296 };
3001 if (context_.predicated_copier_) { 3297 if (replay.write_acceleration_structures_properties) {
3002 copy_batch = context_.predicated_copier_->batch(); 3298 replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool,
3003 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, 3299 std::uint32_t& first) {
3004 VkDeviceSize dst, VkDeviceSize size, 3300 return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first);
3005 std::vector<PredicatedCopyDispatch>& out) {
3006 return copy_batch->prepare(source, destination, src, dst, size, out);
3007 };
3008 replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) {
3009 context_.predicated_copier_->emit(cb, jobs);
3010 }; 3301 };
3011 } 3302 }
3012 } 3303 if (captures) {
3013 if (context_.scratch_) { 3304 if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_)
3014 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, 3305 return queue_unsupported(__LINE__);
3015 VkDeviceSize& offset) { 3306 // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock,
3307 // retaining pipeline -> resource -> tracker -> submit lock order through emit and submission.
3016 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3308 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3017 if (!scratch_guard.active) { 3309 batch = context_.predicate_reducer_->batch(captures);
3018 context_.scratch_->collect(); 3310 if (!batch) return queue_unsupported(__LINE__);
3019 scratch_guard.active = true; 3311 replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) {
3312 return batch->prepare(buffer, offset, out);
3313 };
3314 replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) {
3315 context_.predicate_reducer_->capture(cb, p);
3316 };
3317 if (context_.predicated_copier_) {
3318 copy_batch = context_.predicated_copier_->batch();
3319 replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src,
3320 VkDeviceSize dst, VkDeviceSize size,
3321 std::vector<PredicatedCopyDispatch>& out) {
3322 return copy_batch->prepare(source, destination, src, dst, size, out);
3323 };
3324 replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector<PredicatedCopyDispatch>& jobs) {
3325 context_.predicated_copier_->emit(cb, jobs);
3326 };
3020 } 3327 }
3021 return context_.scratch_->get(bytes, buffer, offset); 3328 }
3022 }; 3329 if (context_.scratch_) {
3023 } 3330 replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer,
3024 if (kind_ != QueueKind::copy && context_.indirect_clamp_) { 3331 VkDeviceSize& offset) {
3025 // The record scratch belongs to this submission: collected here, retired below with its ticket. The 3332 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3026 // counter slots are read back once that ticket completes (the batch's destructor). 3333 if (!scratch_guard.active) {
3027 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard]( 3334 scratch_guard.scratch = context_.scratch_.get();
3028 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, 3335 context_.scratch_->collect();
3029 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride, 3336 scratch_guard.active = true;
3030 std::uint32_t max_count, ClampedIndirect& out) { 3337 }
3031 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3338 return context_.scratch_->get(bytes, buffer, offset);
3032 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3339 };
3033 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch(); 3340 }
3034 if (!clamp_guard.active) { 3341 if (kind_ != QueueKind::copy && context_.indirect_clamp_) {
3035 context_.indirect_clamp_->collect(); 3342 // The record scratch belongs to this submission: collected here, retired below with its ticket. The
3036 clamp_guard.active = true; 3343 // counter slots are read back once that ticket completes (the batch's destructor).
3344 replay.prepare_indirect_clamp = [this, &tracker_lock, &clamp_batch, &clamp_guard](
3345 VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count,
3346 VkDeviceSize count_offset, std::uint32_t kind, std::uint32_t stride,
3347 std::uint32_t max_count, ClampedIndirect& out) {
3348 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3349 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3350 if (!clamp_batch) clamp_batch = context_.indirect_clamp_->batch();
3351 if (!clamp_guard.active) {
3352 clamp_guard.clamp = context_.indirect_clamp_.get();
3353 context_.indirect_clamp_->collect();
3354 clamp_guard.active = true;
3355 }
3356 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride,
3357 max_count, out);
3358 };
3359 }
3360 if (kind_ != QueueKind::copy && context_.counted_dispatch_) {
3361 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch](
3362 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset,
3363 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) {
3364 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3365 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3366 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch();
3367 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
3368 };
3369 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
3370 context_.counted_dispatch_->emit(cb, job);
3371 };
3372 }
3373 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
3374 replay.prepare_quad_indices = [this, &tracker_lock](
3375 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
3376 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
3377 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3378 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3379 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
3380 scratch_offset, out);
3381 };
3382 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
3383 context_.quad_indices_->emit(cb, job);
3384 };
3385 }
3386 if (context_.depth24_ && !transfer_only) {
3387 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
3388 std::vector<Depth24Job>& parts) {
3389 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3390 if (!depth24_guard.active) {
3391 depth24_guard.d24 = context_.depth24_.get();
3392 context_.depth24_->collect();
3393 depth24_guard.active = true;
3394 }
3395 return context_.depth24_->prepare(job, parts);
3396 };
3397 }
3398 if (can_resolve_occlusion) {
3399 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3400 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3401 occlusion_resolve_->sum(cb, pool, first, count, dst, offset);
3402 };
3403 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3404 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3405 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset);
3406 };
3407 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool,
3408 VkQueryPool primitives_pool, const std::uint8_t* mesh,
3409 std::uint32_t first, std::uint32_t count, VkBuffer dst,
3410 VkDeviceSize offset) {
3411 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst,
3412 offset);
3413 };
3414 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
3415 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) {
3416 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset);
3417 };
3418 }
3419 segments = 0;
3420 statistics_segments = 0;
3421 has_queries = false;
3422 // Collect unbuilt pipelines via PipelineCompiles (whether pipeline_workers_ is enabled or serial).
3423 // On pass 0, if any pipeline must be compiled, release pass-0 transient state along with tracker_lock
3424 // and resource_lock before invoking the compiler (keeping pipeline_lock so registered pipelines and
3425 // workers stay alive), then re-prepare on pass 1 against current resources.
3426 PipelineCompiles compiles;
3427 replay.compiles = &compiles;
3428 ReplayResult prepare_result = ReplayResult::success;
3429 for (std::size_t i = 0; i < lists.size(); ++i) {
3430 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
3431 if (result != ReplayResult::success) {
3432 prepare_result = result;
3433 break;
3037 } 3434 }
3038 return clamp_batch->prepare(arguments, argument_offset, count, count_offset, kind, stride, max_count, 3435 if (prepared[i].segment_count > UINT32_MAX - segments ||
3039 out); 3436 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments)
3040 }; 3437 return queue_unsupported(__LINE__);
3041 } 3438 segments += prepared[i].segment_count;
3042 if (kind_ != QueueKind::copy && context_.counted_dispatch_) { 3439 statistics_segments += prepared[i].statistics_segment_count;
3043 replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( 3440 has_queries = has_queries || !prepared[i].queries.empty();
3044 VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, 3441 }
3045 std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { 3442 if (pass == 0 && !compiles.empty()) {
3046 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. 3443 if (depth24_guard.active) {
3047 if (!tracker_lock.owns_lock()) tracker_lock.lock(); 3444 context_.depth24_->retire(progress_, 0);
3048 if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); 3445 depth24_guard.active = false;
3049 return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out);
3050 };
3051 replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) {
3052 context_.counted_dispatch_->emit(cb, job);
3053 };
3054 }
3055 if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) {
3056 replay.prepare_quad_indices = [this, &tracker_lock](
3057 VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads,
3058 VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) {
3059 // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation.
3060 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3061 return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch,
3062 scratch_offset, out);
3063 };
3064 replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) {
3065 context_.quad_indices_->emit(cb, job);
3066 };
3067 }
3068 if (context_.depth24_ && !transfer_only) {
3069 replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job,
3070 std::vector<Depth24Job>& parts) {
3071 if (!tracker_lock.owns_lock()) tracker_lock.lock();
3072 if (!depth24_guard.active) {
3073 context_.depth24_->collect();
3074 depth24_guard.active = true;
3075 } 3446 }
3076 return context_.depth24_->prepare(job, parts); 3447 if (scratch_guard.active) {
3077 }; 3448 context_.scratch_->retire(progress_, 0);
3078 } 3449 scratch_guard.active = false;
3079 const auto& occlusion_memory = context_.occlusion_resolve_memory_; 3450 }
3080 const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; 3451 if (clamp_guard.active) {
3081 if (can_resolve_occlusion) { 3452 context_.indirect_clamp_->retire(progress_, 0);
3082 replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3453 clamp_guard.active = false;
3083 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3454 }
3084 occlusion_resolve_->sum(cb, pool, first, count, dst, offset); 3455 batch.reset();
3085 }; 3456 copy_batch.reset();
3086 replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3457 counted_batch.reset();
3087 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3458 clamp_batch.reset();
3088 occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); 3459 if (tracker_lock.owns_lock()) tracker_lock.unlock();
3089 }; 3460 resource_lock.unlock();
3090 replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, 3461 recycle_khr_stages(khr_guard.stages);
3091 VkQueryPool primitives_pool, const std::uint8_t* mesh, 3462 recycle_khr_as_queries(khr_guard.as_queries);
3092 std::uint32_t first, std::uint32_t count, VkBuffer dst, 3463 geometry.clear();
3093 VkDeviceSize offset) { 3464
3094 occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, 3465 std::shared_ptr<void> demand;
3095 offset); 3466 if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_();
3096 }; 3467 if (context_.pipeline_workers_)
3097 replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, 3468 compiles.build(run_compiles, context_.large_compile_budget_);
3098 std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { 3469 else
3099 occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); 3470 compiles.build_serial();
3100 }; 3471 demand.reset();
3101 } 3472 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result);
3102 const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; 3473 if (compile_result != ReplayResult::success) return compile_result;
3103 std::uint32_t segments = 0, statistics_segments = 0; 3474 prior_compiles = std::move(compiles);
3104 bool has_queries = false; 3475 has_prior_compiles = true;
3105 // With workers, the pipelines the lists need and that are not built yet are compiled together below instead of 3476 continue;
3106 // one after another in prepare(). resource_lock is held until they are all built, which keeps the pipeline
3107 // states that own them alive (remove_pipeline takes it uniquely).
3108 PipelineCompiles compiles;
3109 if (context_.pipeline_workers_) replay.compiles = &compiles;
3110 ReplayResult prepare_result = ReplayResult::success;
3111 for (std::size_t i = 0; i < lists.size(); ++i) {
3112 const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion);
3113 if (result != ReplayResult::success) {
3114 prepare_result = result;
3115 break;
3116 } 3477 }
3117 if (prepared[i].segment_count > UINT32_MAX - segments || 3478 const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr;
3118 prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) 3479 prepare_result = context_.pipeline_workers_
3119 return queue_unsupported(__LINE__); 3480 ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result,
3120 segments += prepared[i].segment_count; 3481 run_compiles, context_.large_compile_budget_, prior)
3121 statistics_segments += prepared[i].statistics_segment_count; 3482 : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()),
3122 has_queries = has_queries || !prepared[i].queries.empty(); 3483 prepare_result, prior);
3123 } 3484 replay.compiles = nullptr;
3124 prepare_result = build_pipelines( 3485 if (prepare_result != ReplayResult::success) return prepare_result;
3125 compiles, std::span(prepared).first(lists.size()), prepare_result, 3486 break;
3126 [this](std::size_t count, const std::function<void(std::size_t)>& job) { 3487 }
3127 context_.pipeline_workers_->run(count, job);
3128 });
3129 if (prepare_result != ReplayResult::success) return prepare_result;
3130 const auto segment_pool = [this](VkQueryType type, std::uint32_t count, 3488 const auto segment_pool = [this](VkQueryType type, std::uint32_t count,
3131 std::shared_ptr<OcclusionSegmentPool>& out) { 3489 std::shared_ptr<OcclusionSegmentPool>& out) {
3132 const auto& vk = context_.vk; 3490 const auto& vk = context_.vk;
@@ -3253,6 +3611,7 @@ private:
3253 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3611 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3254 "vkEndCommandBuffer") == VK_SUCCESS; 3612 "vkEndCommandBuffer") == VK_SUCCESS;
3255 resource_lock.unlock(); 3613 resource_lock.unlock();
3614 pipeline_lock.unlock();
3256 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); 3615 const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0);
3257 if (!submitted) discard(); 3616 if (!submitted) discard();
3258 if (depth24_guard.active) { 3617 if (depth24_guard.active) {
@@ -3330,6 +3689,25 @@ private:
3330 auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED); 3689 auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED);
3331 detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker); 3690 detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker);
3332 } 3691 }
3692 // The prelude (set_prelude): recorded here, after the set's upload and before the lists, and in either case
3693 // after the last submission of another queue that recorded one (its pass writes what these lists read, and
3694 // a pass here must not overtake it).
3695 const bool prelude = !transfer_only && context_.prelude_record_ && context_.prelude_record_(command_buffer);
3696 // LEONIDA_PRELUDE_QUEUE_WAIT=0 (an experiment): no wait for another queue's pass, so the queues do not
3697 // serialise on each other's whole submissions; a list may then read what that pass has not written yet.
3698 static const bool cross_wait = [] {
3699 const char* v = std::getenv("LEONIDA_PRELUDE_QUEUE_WAIT");
3700 return !(v && v[0] == '0' && v[1] == 0);
3701 }();
3702 {
3703 std::lock_guard lock(context_.storage_mutex_);
3704 if (cross_wait && context_.prelude_semaphore_ && context_.prelude_semaphore_ != progress_ &&
3705 context_.prelude_version_ != prelude_seen_) {
3706 waits_.push_back(context_.prelude_semaphore_);
3707 wait_values_.push_back(context_.prelude_value_);
3708 }
3709 prelude_seen_ = context_.prelude_version_;
3710 }
3333 bool wrote_readback = false; 3711 bool wrote_readback = false;
3334 VkPipelineStageFlags2 readback_stages = 0; 3712 VkPipelineStageFlags2 readback_stages = 0;
3335 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists 3713 std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists
@@ -3386,7 +3764,8 @@ private:
3386 } 3764 }
3387 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), 3765 const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer),
3388 "vkEndCommandBuffer") == VK_SUCCESS; 3766 "vkEndCommandBuffer") == VK_SUCCESS;
3389 resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held 3767 resource_lock.unlock(); // release resource_mutex_ and pipeline_mutex_ before vkQueueSubmit while keeping tracker_lock held
3768 pipeline_lock.unlock();
3390 const bool wait_previous = ordered_timestamps && submitted_; 3769 const bool wait_previous = ordered_timestamps && submitted_;
3391 if (wait_previous) { 3770 if (wait_previous) {
3392 waits_.push_back(progress_); 3771 waits_.push_back(progress_);
@@ -3417,6 +3796,16 @@ private:
3417 ++context_.bindless_upload_version_; 3796 ++context_.bindless_upload_version_;
3418 bindless_upload_seen_ = context_.bindless_upload_version_; 3797 bindless_upload_seen_ = context_.bindless_upload_version_;
3419 } 3798 }
3799 if (prelude) {
3800 if (submitted) {
3801 std::lock_guard lock(context_.storage_mutex_);
3802 context_.prelude_semaphore_ = progress_;
3803 context_.prelude_value_ = submitted_;
3804 ++context_.prelude_version_;
3805 prelude_seen_ = context_.prelude_version_;
3806 }
3807 if (context_.prelude_commit_) context_.prelude_commit_(submitted, context_.submitted_retire_ticket());
3808 }
3420 if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one 3809 if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one
3421 waits_.pop_back(); 3810 waits_.pop_back();
3422 wait_values_.pop_back(); 3811 wait_values_.pop_back();
@@ -3537,7 +3926,9 @@ private:
3537 3926
3538 // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held. 3927 // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held.
3539 void hold(Deferred&& op) { 3928 void hold(Deferred&& op) {
3540 op.seq = context_.holds().next_seq(); 3929 // A call the worker runs (LEONIDA_SUBMIT_ASYNC) keeps the number it was queued with: what was registered
3930 // behind it (a Present) still waits for it.
3931 op.seq = async_seq_ ? async_seq_ : context_.holds().next_seq();
3541 if (op.kind != Deferred::Kind::marker) { 3932 if (op.kind != Deferred::Kind::marker) {
3542 op.waits = std::move(waits_); 3933 op.waits = std::move(waits_);
3543 op.wait_values = std::move(wait_values_); 3934 op.wait_values = std::move(wait_values_);
@@ -3548,6 +3939,7 @@ private:
3548 } 3939 }
3549 if (gpu_latency::enabled()) op.held_at = std::chrono::steady_clock::now(); 3940 if (gpu_latency::enabled()) op.held_at = std::chrono::steady_clock::now();
3550 held_.push_back(std::move(op)); 3941 held_.push_back(std::move(op));
3942 held_front_seq_.store(held_.front().seq, std::memory_order_release);
3551 context_.holds().held_changed(1); 3943 context_.holds().held_changed(1);
3552 } 3944 }
3553 3945
@@ -3594,7 +3986,21 @@ private:
3594 bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); } 3986 bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); }
3595 3987
3596 // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held). 3988 // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held).
3989 // With LEONIDA_SUBMIT_ASYNC another thread does not run this queue's held work: it asks the queue's worker,
3990 // which releases it and then pumps the holds itself (so a Present behind it still runs after it).
3597 bool release_ready() override { 3991 bool release_ready() override {
3992 if (async_started_.load(std::memory_order_acquire) && t_worker_of_ != this) {
3993 {
3994 std::lock_guard lock(inbox_mutex_);
3995 release_requested_ = true;
3996 }
3997 inbox_cv_.notify_one();
3998 return false;
3999 }
4000 return release_held();
4001 }
4002
4003 bool release_held() {
3598 std::vector<std::shared_ptr<void>> retired; 4004 std::vector<std::shared_ptr<void>> retired;
3599 bool released = false; 4005 bool released = false;
3600 { 4006 {
@@ -3603,8 +4009,19 @@ private:
3603 Deferred op = std::move(held_.front()); 4009 Deferred op = std::move(held_.front());
3604 held_.pop_front(); 4010 held_.pop_front();
3605 context_.holds().held_changed(-1); 4011 context_.holds().held_changed(-1);
3606 if (gpu_latency::enabled()) gpu_latency::held(int(kind_), int(op.kind), op.held_at); 4012 if (gpu_latency::enabled()) {
4013 // The wait that was pending when it was held: the fence whose Signal let it go.
4014 std::uint64_t fence = 0, value = 0;
4015 for (std::size_t i = 0; i < op.waits.size(); ++i)
4016 if (op.wait_values[i] > value) {
4017 fence = std::uint64_t(reinterpret_cast<std::uintptr_t>(op.waits[i]));
4018 value = op.wait_values[i];
4019 }
4020 gpu_latency::held(int(kind_), int(op.kind), op.held_at, fence, value);
4021 }
3607 if (!context_.is_device_lost()) run(op); 4022 if (!context_.is_device_lost()) run(op);
4023 // Only now: until it has run, the operation still counts as the oldest held one.
4024 held_front_seq_.store(held_.empty() ? 0 : held_.front().seq, std::memory_order_release);
3608 released = true; 4025 released = true;
3609 } 4026 }
3610 drain_pins(retired); 4027 drain_pins(retired);
@@ -3629,13 +4046,22 @@ private:
3629 it = held_.erase(it); 4046 it = held_.erase(it);
3630 context_.holds().held_changed(-1); 4047 context_.holds().held_changed(-1);
3631 } 4048 }
4049 held_front_seq_.store(held_.empty() ? 0 : held_.front().seq, std::memory_order_release);
3632 } 4050 }
3633 } 4051 }
3634 4052
3635 // Holder: the sequence number of the oldest held operation. 4053 // Holder: the sequence number of the oldest held operation.
3636 std::uint64_t oldest_held_seq() override { 4054 std::uint64_t oldest_held_seq() override {
3637 std::lock_guard state(state_mutex_); 4055 if (!async_on()) {
3638 return held_.empty() ? 0 : held_.front().seq; 4056 std::lock_guard state(state_mutex_);
4057 return held_.empty() ? 0 : held_.front().seq;
4058 }
4059 // Not under state_mutex_, which the worker holds while it replays: the front's number is kept apart.
4060 std::uint64_t oldest = held_front_seq_.load(std::memory_order_acquire);
4061 std::lock_guard lock(inbox_mutex_);
4062 const std::uint64_t queued = running_seq_ ? running_seq_ : inbox_.empty() ? 0 : inbox_.front().seq;
4063 if (queued && (!oldest || queued < oldest)) oldest = queued;
4064 return oldest;
3639 } 4065 }
3640 4066
3641 // A queue destroyed with held work. Reported, not waited for: nothing was submitted for it, so the VkQueue is 4067 // A queue destroyed with held work. Reported, not waited for: nothing was submitted for it, so the VkQueue is
@@ -3661,6 +4087,7 @@ private:
3661 if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence); 4087 if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence);
3662 context_.holds().held_changed(-static_cast<std::int64_t>(held_.size())); 4088 context_.holds().held_changed(-static_cast<std::int64_t>(held_.size()));
3663 dropped.swap(held_); 4089 dropped.swap(held_);
4090 held_front_seq_.store(0, std::memory_order_release);
3664 } 4091 }
3665 // The pins (fences, pipeline states) are released here, outside the lock. 4092 // The pins (fences, pipeline states) are released here, outside the lock.
3666 } 4093 }
@@ -3795,8 +4222,12 @@ private:
3795 pending_bindings_.push_back(std::move(pending)); 4222 pending_bindings_.push_back(std::move(pending));
3796 { 4223 {
3797 std::lock_guard lock(context_.submit_mutex()); 4224 std::lock_guard lock(context_.submit_mutex());
3798 const auto result = context_.observe_result(vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE), 4225 VkResult bound;
3799 "vkQueueBindSparse"); 4226 {
4227 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
4228 bound = vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE);
4229 }
4230 const auto result = context_.observe_result(bound, "vkQueueBindSparse");
3800 if (result != VK_SUCCESS) { 4231 if (result != VK_SUCCESS) {
3801 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); 4232 if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost();
3802 pending_bindings_.pop_back(); 4233 pending_bindings_.pop_back();
@@ -4020,10 +4451,32 @@ private:
4020 if (diagnostics) pass_trace(*diagnostics); 4451 if (diagnostics) pass_trace(*diagnostics);
4021 // Publish before the driver can execute a marker or a concurrent fence wait can see the loss. 4452 // Publish before the driver can execute a marker or a concurrent fence wait can see the loss.
4022 if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics)); 4453 if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics));
4023 const auto label_fence=context_.gpu_labels_.submit_fence(command_buffer); 4454 DeviceFaultDiagnostics* const ring = context_.device_fault();
4024 res = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence), 4455 std::size_t ring_at = 0;
4456 const std::int64_t submit_start = diagnostic_ms();
4457 if (ring) {
4458 SubmitRecord record;
4459 record.at_ms = submit_start;
4460 record.queue = queue_;
4461 record.kind = kind_ == QueueKind::direct ? "direct" : kind_ == QueueKind::compute ? "compute" : "copy";
4462 record.progress = progress_;
4463 record.ticket = ticket;
4464 record.buffers = submit.commandBufferCount;
4465 if (signals_fence) {
4466 record.fence = fence;
4467 record.fence_value = value;
4468 }
4469 record.waits = std::uint32_t(semaphores.size());
4470 for (std::size_t i = 0; i < semaphores.size() && i < SubmitRecord::max_waits; ++i) {
4471 record.wait_semaphores[i] = semaphores[i];
4472 record.wait_values[i] = values[i];
4473 }
4474 ring_at = ring->begin_submit(record);
4475 }
4476 res = context_.observe_result(context_.queue_submit(queue_, 1, &submit, context_.gpu_labels_.submit_fence(command_buffer)),
4025 "vkQueueSubmit"); 4477 "vkQueueSubmit");
4026 context_.gpu_labels_.submitted(command_buffer,res==VK_SUCCESS); 4478 context_.gpu_labels_.submitted(command_buffer, res == VK_SUCCESS);
4479 if (ring) ring->end_submit(ring_at, diagnostic_ms() - submit_start, res);
4027 if (res == VK_SUCCESS) { 4480 if (res == VK_SUCCESS) {
4028 context_.record_submit_locked(progress_, ticket); 4481 context_.record_submit_locked(progress_, ticket);
4029 if (signals_fence) context_.holds().signaled(fence, value); 4482 if (signals_fence) context_.holds().signaled(fence, value);
@@ -4062,6 +4515,7 @@ private:
4062 std::unique_ptr<OcclusionResolve> occlusion_resolve_; 4515 std::unique_ptr<OcclusionResolve> occlusion_resolve_;
4063 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for 4516 std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for
4064 std::uint64_t bindless_upload_seen_ = 0; // the bindless_upload_version_ this queue has waited for 4517 std::uint64_t bindless_upload_seen_ = 0; // the bindless_upload_version_ this queue has waited for
4518 std::uint64_t prelude_seen_ = 0; // the prelude_version_ this queue has waited for (or recorded)
4065 std::uint64_t last_sparse_ = 0; 4519 std::uint64_t last_sparse_ = 0;
4066 std::deque<PendingBindings> pending_bindings_; 4520 std::deque<PendingBindings> pending_bindings_;
4067 std::vector<VkSemaphore> waits_; 4521 std::vector<VkSemaphore> waits_;
@@ -4071,8 +4525,260 @@ private:
4071 std::vector<PreparedList> prepared_; 4525 std::vector<PreparedList> prepared_;
4072 std::uint32_t open_labels_ = 0; // queue labels begun and not ended 4526 std::uint32_t open_labels_ = 0; // queue labels begun and not ended
4073 bool ok_ = false; 4527 bool ok_ = false;
4074 // Wait-before-Signal. state_mutex_ is outermost (before resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and 4528 // ---- LEONIDA_SUBMIT_ASYNC=<n>: the queue's calls run on a worker of its own -----------------------------------
4075 // guards the members above that execute, signal, wait and marker touch. 4529 // ExecuteCommandLists, Signal, Wait and the markers are queued in call order and return at once; one worker per
4530 // queue runs each through the synchronous path (execute_sync & co.), so the replay, the before-submission
4531 // refreshes and vkQueueSubmit leave the caller's thread and overlap with its next frame. At most n batches wait per
4532 // queue; the caller of the next one waits for room (the in-flight bound). A queued call counts as held work
4533 // (QueueHolds), numbered when it was called, so a Present behind it still waits for it and cross-queue order is
4534 // the call order. Calls that use the queue's state at once (tile mappings, idle, the destructor) first wait for
4535 // what is queued. A batch that fails is reported as a held one is (stderr, take_held_failure()). Off (0) by
4536 // default: every call runs on the caller's thread, as before.
4537 static unsigned async_depth() {
4538 static const unsigned depth = [] {
4539 const char* v = std::getenv("LEONIDA_SUBMIT_ASYNC");
4540 const int n = v && *v ? std::atoi(v) : 0;
4541 return n > 0 ? unsigned(n) : 0u;
4542 }();
4543 return depth;
4544 }
4545
4546 bool async_on() const { return async_depth() && !synchronous_; }
4547
4548 struct Call {
4549 enum class Kind : std::uint8_t { execute, signal, wait, marker };
4550 Kind kind = Kind::execute;
4551 std::uint64_t seq = 0, execute_call = 0, value = 0;
4552 std::vector<CommandList> lists; // copies: the application may Reset its lists after the call
4553 std::shared_ptr<void> pin; // the fence, or the lists' pipeline states and root signatures
4554 VkSemaphore fence = VK_NULL_HANDLE;
4555 DebugMarker::Kind marker_kind = DebugMarker::Kind::set;
4556 std::string label;
4557 std::chrono::steady_clock::time_point queued_at{};
4558 };
4559
4560 struct AsyncStats { // under inbox_mutex_, since the last line
4561 std::uint64_t calls = 0, batches = 0, room_waits = 0, room_wait_ns = 0, run_ns = 0, lag_ns = 0, lag_max_ns = 0;
4562 std::size_t depth_max = 0;
4563 std::chrono::steady_clock::time_point since = std::chrono::steady_clock::now();
4564 };
4565
4566 void enqueue(Call&& call) {
4567 const bool batch = call.kind == Call::Kind::execute;
4568 std::unique_lock lock(inbox_mutex_);
4569 if (!worker_.joinable()) {
4570 worker_ = std::thread([this] { async_worker(); });
4571 async_started_.store(true, std::memory_order_release);
4572 }
4573 // n batches, and 4n calls of any kind (a title that signals after every small job must not queue Signals
4574 // without bound). n = 1 makes each caller wait for the batch before it: n should be 2 or more.
4575 const auto room = [this, batch] {
4576 return async_stop_ ||
4577 ((!batch || inbox_batches_ < async_depth()) && inbox_.size() < 4 * std::size_t(async_depth()));
4578 };
4579 if (!room()) {
4580 const auto start = std::chrono::steady_clock::now();
4581 room_cv_.wait(lock, room);
4582 ++async_stats_.room_waits;
4583 async_stats_.room_wait_ns += std::uint64_t(
4584 std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start).count());
4585 }
4586 if (batch) {
4587 ++inbox_batches_;
4588 ++async_stats_.batches;
4589 }
4590 ++async_stats_.calls;
4591 call.seq = context_.holds().next_seq();
4592 call.queued_at = std::chrono::steady_clock::now();
4593 context_.holds().held_changed(1);
4594 inbox_.push_back(std::move(call));
4595 async_stats_.depth_max = std::max(async_stats_.depth_max, inbox_.size());
4596 lock.unlock();
4597 inbox_cv_.notify_one();
4598 }
4599
4600 void async_worker() {
4601 t_worker_of_ = this;
4602 for (;;) {
4603 Call call;
4604 bool have = false, release = false;
4605 {
4606 std::unique_lock lock(inbox_mutex_);
4607 inbox_cv_.wait(lock, [this] { return !inbox_.empty() || release_requested_ || async_stop_; });
4608 release = std::exchange(release_requested_, false);
4609 if (!inbox_.empty()) {
4610 call = std::move(inbox_.front());
4611 inbox_.pop_front();
4612 running_seq_ = call.seq;
4613 have = true;
4614 } else if (!release) {
4615 return; // stopping, nothing queued
4616 }
4617 worker_busy_ = true;
4618 }
4619 if (release) release_held();
4620 std::uint64_t ran_ns = 0;
4621 if (have) {
4622 const auto start = std::chrono::steady_clock::now();
4623 run_call(call);
4624 const auto end = std::chrono::steady_clock::now();
4625 ran_ns = std::uint64_t(std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count());
4626 const auto lag = std::uint64_t(
4627 std::chrono::duration_cast<std::chrono::nanoseconds>(start - call.queued_at).count());
4628 std::lock_guard lock(inbox_mutex_);
4629 async_stats_.run_ns += ran_ns;
4630 async_stats_.lag_ns += lag;
4631 async_stats_.lag_max_ns = std::max(async_stats_.lag_max_ns, lag);
4632 }
4633 {
4634 std::lock_guard lock(inbox_mutex_);
4635 running_seq_ = 0;
4636 worker_busy_ = false;
4637 if (have && call.kind == Call::Kind::execute) --inbox_batches_;
4638 if (have) room_cv_.notify_all();
4639 idle_cv_.notify_all();
4640 report_async_locked();
4641 }
4642 if (have) context_.holds().held_changed(-1);
4643 call = Call{}; // the copies and pins go before the pump, outside the lock
4644 context_.holds().pump_ready();
4645 }
4646 }
4647
4648 // An exception on the worker would end the process (std::terminate) and leave the queue's callers waiting: it is
4649 // turned into a held failure and a lost device instead, as a failed submission would be, and the worker goes on
4650 // (each later call fails at once on the lost device).
4651 void run_call(Call& call) {
4652 try {
4653 run_call_unguarded(call);
4654 } catch (const std::exception& e) {
4655 worker_threw(call, e.what());
4656 } catch (...) {
4657 worker_threw(call, "not a std::exception");
4658 }
4659 async_seq_ = 0;
4660 }
4661
4662 void worker_threw(const Call& call, const char* what) {
4663 int none = static_cast<int>(ReplayResult::success);
4664 held_failure_.compare_exchange_strong(none, static_cast<int>(ReplayResult::unsupported));
4665 std::fprintf(stderr, "[rt] d3d12: the queue's worker caught an exception running a queued %s (%s); the device is "
4666 "marked lost\n",
4667 call.kind == Call::Kind::execute ? "ExecuteCommandLists"
4668 : call.kind == Call::Kind::signal ? "Signal"
4669 : call.kind == Call::Kind::wait ? "Wait"
4670 : "marker",
4671 what);
4672 context_.mark_device_lost();
4673 }
4674
4675 void run_call_unguarded(Call& call) {
4676 async_seq_ = call.seq;
4677 const PinFn pin = call.pin ? PinFn([&call] { return call.pin; }) : PinFn{};
4678 switch (call.kind) {
4679 case Call::Kind::execute: {
4680 std::vector<const CommandList*> lists;
4681 lists.reserve(call.lists.size());
4682 for (const CommandList& list : call.lists) lists.push_back(&list);
4683 const ReplayResult result = execute_sync(lists, pin, call.execute_call);
4684 if (result != ReplayResult::success) {
4685 int none = static_cast<int>(ReplayResult::success);
4686 held_failure_.compare_exchange_strong(none, static_cast<int>(result));
4687 std::fprintf(stderr, "[rt] d3d12: a queued ExecuteCommandLists failed on the queue's worker (result "
4688 "%d); nothing was submitted for it\n",
4689 static_cast<int>(result));
4690 }
4691 break;
4692 }
4693 case Call::Kind::signal:
4694 if (!signal_sync(call.fence, call.value, pin)) {
4695 int none = static_cast<int>(ReplayResult::success);
4696 held_failure_.compare_exchange_strong(none, static_cast<int>(ReplayResult::unsupported));
4697 std::fprintf(stderr, "[rt] d3d12: a queued Signal failed on the queue's worker\n");
4698 }
4699 break;
4700 case Call::Kind::wait: wait_sync(call.fence, call.value, pin); break;
4701 case Call::Kind::marker: marker_sync(call.marker_kind, call.label.c_str()); break;
4702 }
4703 if (call.pin && call.kind == Call::Kind::execute) {
4704 // The pipeline states stay alive until what was just submitted has completed (a held batch keeps its own).
4705 std::lock_guard state(state_mutex_);
4706 std::vector<std::shared_ptr<void>> pins{std::move(call.pin)};
4707 retire_pins(pins, submitted_);
4708 }
4709 }
4710
4711 // Every 10 s, per queue: what the worker did. Called with inbox_mutex_ held.
4712 void report_async_locked() {
4713 const auto now = std::chrono::steady_clock::now();
4714 const double s = std::chrono::duration<double>(now - async_stats_.since).count();
4715 if (s < 10.0) return;
4716 static constexpr const char* kinds[] = {"direct", "compute", "copy"};
4717 const AsyncStats& a = async_stats_;
4718 std::fprintf(stderr,
4719 "[rt] submit-async: %s queue %p: %.1f calls/s (%.1f batches/s), queued now %zu (max %zu), "
4720 "worker busy %.0f%%, call waited for the worker avg %.2f ms max %.2f ms, caller waited for "
4721 "room %llu times %.1f ms\n",
4722 kinds[int(kind_) < 3 ? int(kind_) : 0], static_cast<const void*>(this), double(a.calls) / s,
4723 double(a.batches) / s, inbox_.size(), a.depth_max, 100.0 * double(a.run_ns) / (s * 1e9),
4724 a.calls ? double(a.lag_ns) / double(a.calls) / 1e6 : 0.0, double(a.lag_max_ns) / 1e6,
4725 static_cast<unsigned long long>(a.room_waits), double(a.room_wait_ns) / 1e6);
4726 async_stats_ = AsyncStats{};
4727 }
4728
4729 // What was queued before this call has run (held work may stay held, as without the worker). A worker that does
4730 // not come back (a GPU hang inside wait_for_room, say) is reported every 10 s, and after 60 s the caller goes on
4731 // without it: false.
4732 bool flush_async() {
4733 if (!async_started_.load(std::memory_order_acquire) || t_worker_of_ == this) return true;
4734 std::unique_lock lock(inbox_mutex_);
4735 const auto idle = [this] { return inbox_.empty() && !worker_busy_; };
4736 for (int slice = 1; slice <= 6; ++slice) {
4737 if (idle_cv_.wait_for(lock, std::chrono::seconds(10), idle)) return true;
4738 std::fprintf(stderr, "[rt] d3d12: waited %d s for a queue's worker to finish what is queued (%zu calls, "
4739 "running call %llu)%s\n",
4740 slice * 10, inbox_.size(), static_cast<unsigned long long>(running_seq_),
4741 slice == 6 ? "; going on without it" : "");
4742 }
4743 return false;
4744 }
4745
4746 void stop_async() {
4747 if (!async_started_.load(std::memory_order_acquire)) return;
4748 const bool drained = flush_async();
4749 {
4750 std::lock_guard lock(inbox_mutex_);
4751 async_stop_ = true;
4752 }
4753 inbox_cv_.notify_all();
4754 room_cv_.notify_all();
4755 if (!worker_.joinable()) return;
4756 if (drained) {
4757 worker_.join();
4758 return;
4759 }
4760 // A worker stuck for a minute holds this queue's objects: it is left running rather than joined forever
4761 // (only at teardown; the process is ending or the device is gone).
4762 std::fprintf(stderr, "[rt] d3d12: a queue's worker did not finish; it is detached at the queue's destruction\n");
4763 worker_.detach();
4764 }
4765
4766 std::mutex inbox_mutex_;
4767 std::condition_variable inbox_cv_, room_cv_, idle_cv_;
4768 std::deque<Call> inbox_;
4769 std::size_t inbox_batches_ = 0;
4770 std::uint64_t running_seq_ = 0; // the call the worker runs now
4771 bool worker_busy_ = false, release_requested_ = false, async_stop_ = false;
4772 AsyncStats async_stats_;
4773 std::atomic<bool> async_started_{false};
4774 bool synchronous_ = false; // make_synchronous()
4775 std::thread worker_;
4776 static inline thread_local VulkanQueue* t_worker_of_ = nullptr; // the queue whose worker this thread is
4777 static inline thread_local std::uint64_t async_seq_ = 0; // the sequence number of the call being run
4778 std::atomic<std::uint64_t> held_front_seq_{0}; // held_.front().seq, 0 when empty; see release_held()
4779
4780 // Wait-before-Signal. state_mutex_ is outermost (before pipeline_mutex_ -> resource_mutex_ -> tracker_mutex_ ->
4781 // submit_mutex_) and guards the members above that execute, signal, wait and marker touch.
4076 std::mutex state_mutex_; 4782 std::mutex state_mutex_;
4077 std::deque<Deferred> held_; 4783 std::deque<Deferred> held_;
4078 std::vector<std::shared_ptr<void>> wait_pins_; // keep the fences of waits_ alive 4784 std::vector<std::shared_ptr<void>> wait_pins_; // keep the fences of waits_ alive
diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h
index e72225396..da6d680f0 100644
--- a/runtime/src/vulkan_bindless.h
+++ b/runtime/src/vulkan_bindless.h
@@ -25,6 +25,14 @@
25// and samplers it adds and keeps them alive while they are in the set; this class owns only the fallbacks and the 25// and samplers it adds and keeps them alive while they are in the set; this class owns only the fallbacks and the
26// table's buffer. 26// table's buffer.
27// 27//
28// The T#'s own type is the truth: the index was given out in ITS dimension's space, so a shader reading it through
29// another dimension's array (a 2D instruction on a 2D-array or cube T#, say) must not use it blindly. Every entry
30// therefore carries, next to the index, which arrays the index is bound in (descriptor_table.h's kind bits), and a
31// translated module of the tagged contract reads that word: it uses the index only in an array the entry names and
32// otherwise takes that array's fallback. For the one mismatch the hardware reads rather than drops - a 2D
33// instruction on a 2D-array or cube T#, which addresses slice 0 - add_image's MirrorViews bind a view of that slice
34// at the same index in the 2D arrays and name 2D in the kind, so the instruction finds it.
35//
28// The fallbacks stand for the console's null descriptors (a zero T#, a T# whose image the layer refused or never 36// The fallbacks stand for the console's null descriptors (a zero T#, a T# whose image the layer refused or never
29// saw): each is of the kind the instruction asks for, since the translator picks the binding by the instruction's 37// saw): each is of the kind the instruction asks for, since the translator picks the binding by the instruction's
30// 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 38// 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 @@
68 76
69#include <algorithm> 77#include <algorithm>
70#include <array> 78#include <array>
79#include <cassert>
71#include <cstdint> 80#include <cstdint>
72#include <cstring> 81#include <cstring>
73#include <functional> 82#include <functional>
@@ -398,6 +407,8 @@ public:
398 BindlessSet& operator=(const BindlessSet&) = delete; 407 BindlessSet& operator=(const BindlessSet&) = delete;
399 408
400 bool ok() const { return ok_; } 409 bool ok() const { return ok_; }
410 // What the set layout was made from (the pipeline journal names compute pipelines by it).
411 const BindlessFeatures& features() const { return features_; }
401 bool supports_ms_class(std::uint32_t component_class) const { 412 bool supports_ms_class(std::uint32_t component_class) const {
402 return component_class < classes && features_.ms_samples[component_class] != VK_SAMPLE_COUNT_1_BIT; 413 return component_class < classes && features_.ms_samples[component_class] != VK_SAMPLE_COUNT_1_BIT;
403 } 414 }
@@ -461,29 +472,109 @@ public:
461 &done, 0, nullptr, 0, nullptr); 472 &done, 0, nullptr, 0, nullptr);
462 } 473 }
463 474
475 // A second view of the same image in the 2D arrays: the slice a 2D instruction reads through a 2D-array or cube
476 // T# (its first layer). The hardware addresses such a read as slice 0, and the translated shader reads binding 0
477 // with the identity the table gives, so the runtime binds this copy at the image's own index and records that
478 // index as valid in the 2D array too (kind_sampled_bit), owned by this image (mirror_of): another dimension's
479 // image with the same slot number does not inherit it. The storage views follow the same rule when the image has
480 // them, so a 2D store or atomic lands on layer 0.
481 struct MirrorViews {
482 VkImageView sampled = VK_NULL_HANDLE;
483 VkImageLayout sampled_layout = VK_IMAGE_LAYOUT_GENERAL;
484 StorageViews storage{};
485 };
486
464 // Gives an image an index in its dimension's bindings: 0 when the dimension is full. `sampled` goes to the 487 // Gives an image an index in its dimension's bindings: 0 when the dimension is full. `sampled` goes to the
465 // sampled array in `sampled_layout` (the layout the image is in when shaders read it); the storage views go to 488 // sampled array in `sampled_layout` (the layout the image is in when shaders read it); the storage views go to
466 // the storage arrays in GENERAL. For MS views, sampled_class selects the float, uint or sint sampled array. 489 // the storage arrays in GENERAL. For MS views, sampled_class selects the float, uint or sint sampled array.
467 // The caller maps the T# to the index with insert_key(). Takes effect at flush(). 490 // `mirror` adds the same index in the 2D arrays (a 2D-array or cube image's slice 0): the slot must then be free
491 // in both index spaces. `kind_out`, when given, receives what the index is bound in (descriptor_table.h's kind
492 // bits), which the caller records with insert_key. The caller maps the T# to the index with insert_key(). Takes
493 // effect at flush().
468 std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout, 494 std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout,
469 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { 495 const StorageViews& storage = {}, std::uint32_t sampled_class = 0,
496 const MirrorViews* mirror = nullptr, std::uint32_t* kind_out = nullptr) {
470 const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; 497 const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui;
471 if (!stores && bindless::sampled_binding(dimension) == bindless::no_binding) return 0; 498 if (!stores && bindless::sampled_binding(dimension) == bindless::no_binding) return 0;
472 if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; 499 if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0;
473 auto& used = image_used_[std::uint32_t(dimension)]; 500 auto& used = image_used_[std::uint32_t(dimension)];
474 const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension)); 501 const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension));
475 std::uint32_t index = stores ? 0 : allocate(used, low_end, std::uint32_t(used.size())); 502 std::vector<std::uint8_t>* used_2d = nullptr; // the mirror's index space, when there is one
476 if (!index) index = allocate(used, 1, low_end); 503 if (mirror && dimension != ImageDimension::dim_2d && mirror->sampled) {
477 if (index) write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); 504 used_2d = &image_used_[std::uint32_t(ImageDimension::dim_2d)];
505 if (mirror->sampled_layout == VK_IMAGE_LAYOUT_UNDEFINED) used_2d = nullptr;
506 }
507 // A store through the array T# and one through its 2D slice both have to land on a view, so an index with
508 // storage views must be inside this dimension's storage arrays and, when the mirror has storage views too,
509 // inside the 2D arrays' (their range can be the shorter of the two).
510 const bool any_stores = stores || mirror_storage(mirror);
511 const std::uint32_t mirrored_storage_end = std::min(stores ? low_end : std::uint32_t(used.size()),
512 storage_capacity(ImageDimension::dim_2d));
513 std::uint32_t index = 0;
514 if (used_2d) {
515 index = any_stores ? allocate_pair(used, *used_2d, 1, mirrored_storage_end)
516 : allocate_pair(used, *used_2d, low_end, std::uint32_t(used.size()));
517 if (!index && !any_stores) index = allocate_pair(used, *used_2d, 1, low_end);
518 if (!index) {
519 // No shared slot: the image still gets its own dimension's slot, unmirrored (a 2D read then finds
520 // the fallback). A full array is what returns 0.
521 used_2d = nullptr;
522 }
523 }
524 if (!used_2d) {
525 index = stores ? allocate(used, 1, low_end) : allocate(used, low_end, std::uint32_t(used.size()));
526 if (!index) index = allocate(used, 1, low_end);
527 }
528 if (!index) return 0;
529 assert(!used_2d || !any_stores || index < storage_capacity(ImageDimension::dim_2d));
530 write_image(dimension, index, sampled, sampled_layout, storage, sampled_class);
531 if (index < storage_used_[std::uint32_t(dimension)].size())
532 storage_used_[std::uint32_t(dimension)][index] = stores ? 1 : 0;
533 if (used_2d) {
534 write_image(ImageDimension::dim_2d, index, mirror->sampled, mirror->sampled_layout, mirror->storage, 0);
535 used_2d->at(index) = in_use;
536 // The 2D slot is this image's mirror, and this image is its owner: the slot number alone does not say
537 // so, because every dimension's index space is dense and independent.
538 if (index < mirror_owner_.size()) {
539 mirror_owner_[index] = std::uint8_t(std::uint32_t(dimension) + 1);
540 mirror_storage_used_[index] = mirror_storage(mirror) ? 1 : 0;
541 }
542 auto& storage_2d = storage_used_[std::uint32_t(ImageDimension::dim_2d)];
543 if (index < storage_2d.size()) storage_2d[index] = mirror_storage(mirror) ? 1 : 0;
544 }
545 if (kind_out) {
546 *kind_out = kind_sampled_bit(std::uint32_t(dimension)) |
547 (stores ? kind_storage_bit(std::uint32_t(dimension)) : 0) |
548 (used_2d ? (kind_sampled_bit(std::uint32_t(ImageDimension::dim_2d)) |
549 (mirror_storage(mirror) ? kind_storage_bit(std::uint32_t(ImageDimension::dim_2d))
550 : 0))
551 : 0);
552 }
478 return index; 553 return index;
479 } 554 }
480 555
481 // New views or a new layout for an index add_image returned (a texture's state changed, say). 556 // New views or a new layout for an index add_image returned (a texture's state changed, say). `mirror` is
557 // refreshed too when the image was added with one (mirror_of says whose 2D slot it is). The slot bookkeeping
558 // follows what was written, and `kind_out`, when given, receives the index's kind word afterwards for a
559 // re-insert: the table keeps the kind it was given, so a caller that adds or drops storage views re-records it.
482 void update_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout, 560 void update_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout,
483 const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { 561 const StorageViews& storage = {}, std::uint32_t sampled_class = 0,
562 const MirrorViews* mirror = nullptr, std::uint32_t* kind_out = nullptr) {
484 const auto& used = image_used_[std::uint32_t(dimension)]; 563 const auto& used = image_used_[std::uint32_t(dimension)];
485 if (index && index < used.size() && used[index] == in_use) 564 const bool live = index && index < used.size() && used[index] == in_use;
565 if (live) {
486 write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); 566 write_image(dimension, index, sampled, sampled_layout, storage, sampled_class);
567 const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui;
568 if (index < storage_used_[std::uint32_t(dimension)].size())
569 storage_used_[std::uint32_t(dimension)][index] = stores ? 1 : 0;
570 }
571 if (live && mirror && mirror->sampled && mirror_of(dimension, index)) {
572 write_image(ImageDimension::dim_2d, index, mirror->sampled, mirror->sampled_layout, mirror->storage, 0);
573 if (index < mirror_storage_used_.size()) mirror_storage_used_[index] = mirror_storage(mirror) ? 1 : 0;
574 auto& storage_2d = storage_used_[std::uint32_t(ImageDimension::dim_2d)];
575 if (index < storage_2d.size()) storage_2d[index] = mirror_storage(mirror) ? 1 : 0;
576 }
577 if (kind_out) *kind_out = image_kind_at(dimension, index);
487 } 578 }
488 579
489 // Returns the index to the fallback and frees it. The caller removes the image's keys with erase_key() first. 580 // Returns the index to the fallback and frees it. The caller removes the image's keys with erase_key() first.
@@ -495,7 +586,22 @@ public:
495 if (!index || index >= used.size() || used[index] != in_use) return; 586 if (!index || index >= used.size() || used[index] != in_use) return;
496 write_image(dimension, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0); 587 write_image(dimension, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0);
497 used[index] = table_dirty_ ? held : 0; 588 used[index] = table_dirty_ ? held : 0;
589 if (index < storage_used_[std::uint32_t(dimension)].size())
590 storage_used_[std::uint32_t(dimension)][index] = 0;
498 if (table_dirty_) held_images_.push_back({dimension, index}); 591 if (table_dirty_) held_images_.push_back({dimension, index});
592 // Its 2D copy goes back to the fallback as well (add_image's mirror), when this image is the one that owns
593 // that slot: another dimension's image at the same slot number has its own index space and keeps its 2D
594 // descriptor (and, if it is a 2D-array image, its own mirror there).
595 if (mirror_of(dimension, index)) {
596 auto& used_2d = image_used_[std::uint32_t(ImageDimension::dim_2d)];
597 write_image(ImageDimension::dim_2d, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0);
598 used_2d[index] = table_dirty_ ? held : 0;
599 mirror_owner_[index] = 0;
600 mirror_storage_used_[index] = 0;
601 auto& storage_2d = storage_used_[std::uint32_t(ImageDimension::dim_2d)];
602 if (index < storage_2d.size()) storage_2d[index] = 0;
603 if (table_dirty_) held_images_.push_back({ImageDimension::dim_2d, index});
604 }
499 } 605 }
500 606
501 // 0 when the sampler array is full. 607 // 0 when the sampler array is full.
@@ -512,15 +618,37 @@ public:
512 if (table_dirty_) held_samplers_.push_back(index); 618 if (table_dirty_) held_samplers_.push_back(index);
513 } 619 }
514 620
515 // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). Changes reach the shaders 621 // What an index of `dimension` is bound in, from what add_image wrote: that dimension's sampled bit, its storage
516 // at flush(). 622 // bit when the slot holds storage views, and the 2D bits when this image owns the slot at the same number in the
517 bool insert_key(const DescriptorKey& key, std::uint32_t index) { 623 // 2D arrays as its mirror (mirror_of).
518 const auto result = table_.insert_or_update(key.data(), index); 624 std::uint32_t image_kind_at(ImageDimension dimension, std::uint32_t index) const {
625 const auto set = [&](const std::vector<std::uint8_t>& used) {
626 return index < used.size() && used[index] != 0;
627 };
628 const std::uint32_t d = std::uint32_t(dimension);
629 std::uint32_t kind = kind_sampled_bit(d) | (set(storage_used_[d]) ? kind_storage_bit(d) : 0);
630 if (mirror_of(dimension, index)) {
631 kind |= kind_sampled_bit(std::uint32_t(ImageDimension::dim_2d));
632 if (set(mirror_storage_used_)) kind |= kind_storage_bit(std::uint32_t(ImageDimension::dim_2d));
633 }
634 return kind;
635 }
636
637 // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). `kind` is what the index is
638 // bound in, for the modules that read it (descriptor_table.h's kind bits); a sampler's entry has none. Changes
639 // reach the shaders at flush().
640 bool insert_key(const DescriptorKey& key, std::uint32_t index, std::uint32_t kind = 0) {
641 const auto result = table_.insert_or_update(key.data(), index, kind);
519 table_dirty_ |= result != DescriptorTable::InsertResult::unchanged; 642 table_dirty_ |= result != DescriptorTable::InsertResult::unchanged;
520 existing_entries_changed_ |= result == DescriptorTable::InsertResult::replaced || 643 existing_entries_changed_ |= result == DescriptorTable::InsertResult::replaced ||
521 result == DescriptorTable::InsertResult::added_with_relocation; 644 result == DescriptorTable::InsertResult::added_with_relocation;
522 return true; 645 return true;
523 } 646 }
647 // The T#'s own dimension, whose kind the set derives from the index it gave out (image_kind_at): a caller that
648 // knows the T#'s TYPE needs to pass no bits.
649 bool insert_key(const DescriptorKey& key, std::uint32_t index, ImageDimension dimension) {
650 return insert_key(key, index, image_kind_at(dimension, index));
651 }
524 // Erasing empties only the key's own slot; no other entry moves (DescriptorTable::erase), so it needs no idle. 652 // Erasing empties only the key's own slot; no other entry moves (DescriptorTable::erase), so it needs no idle.
525 // The caller erases a key once no submitted work uses it (its texture is gone), like D3D12 requires. 653 // The caller erases a key once no submitted work uses it (its texture is gone), like D3D12 requires.
526 bool erase_key(const DescriptorKey& key) { 654 bool erase_key(const DescriptorKey& key) {
@@ -754,6 +882,34 @@ private:
754 return 0; 882 return 0;
755 } 883 }
756 884
885 // The first index in [begin, end) free in both arrays, marked used in the first; 0 when there is none. The
886 // second array's size bounds the range: a mirrored index must exist in it (its 2D slot).
887 static std::uint32_t allocate_pair(std::vector<std::uint8_t>& used, std::vector<std::uint8_t>& other,
888 std::uint32_t begin, std::uint32_t end) {
889 end = std::min(end, std::uint32_t(other.size()));
890 for (std::uint32_t i = begin; i < end; ++i) {
891 if (used[i] || other[i]) continue;
892 used[i] = 1;
893 return i;
894 }
895 return 0;
896 }
897
898 // A mirror is worth binding only when it has a view; its storage views make the 2D storage arrays valid too.
899 static bool mirror_storage(const MirrorViews* mirror) {
900 return mirror && (mirror->storage.as_float || mirror->storage.as_uint || mirror->storage.as_sint ||
901 mirror->storage.r32ui);
902 }
903
904 // True when the 2D slot at `index` is the mirror of the image whose index is `index` in `dimension` (add_image's
905 // MirrorViews). A bare per-slot flag cannot say so: every dimension's index space is dense and independent, so
906 // the Nth image of one dimension shares its slot number with the Nth 2D-array image's mirror slot in the 2D
907 // arrays. The owner is the dimension + 1 (0: no mirror).
908 bool mirror_of(ImageDimension dimension, std::uint32_t index) const {
909 if (dimension == ImageDimension::dim_2d) return false;
910 return index < mirror_owner_.size() && mirror_owner_[index] == std::uint8_t(std::uint32_t(dimension) + 1);
911 }
912
757 std::uint32_t memory_type(std::uint32_t allowed, VkMemoryPropertyFlags wanted) const { 913 std::uint32_t memory_type(std::uint32_t allowed, VkMemoryPropertyFlags wanted) const {
758 for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i) 914 for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i)
759 if ((allowed & (1u << i)) && (memory_.memoryTypes[i].propertyFlags & wanted) == wanted) return i; 915 if ((allowed & (1u << i)) && (memory_.memoryTypes[i].propertyFlags & wanted) == wanted) return i;
@@ -778,6 +934,10 @@ private:
778 image_used_[d].assign(image_capacity(ImageDimension(d)), 0); 934 image_used_[d].assign(image_capacity(ImageDimension(d)), 0);
779 image_used_[d][0] = 1; 935 image_used_[d][0] = 1;
780 } 936 }
937 for (std::uint32_t d = 0; d < dimensions; ++d)
938 storage_used_[d].assign(image_capacity(ImageDimension(d)), 0);
939 mirror_owner_.assign(image_capacity(ImageDimension::dim_2d), 0);
940 mirror_storage_used_.assign(image_capacity(ImageDimension::dim_2d), 0);
781 sampler_used_.assign(sampler_capacity(), 0); 941 sampler_used_.assign(sampler_capacity(), 0);
782 sampler_used_[0] = 1; 942 sampler_used_[0] = 1;
783 return true; 943 return true;
@@ -1282,6 +1442,14 @@ private:
1282 VkSampler fallback_sampler_ = VK_NULL_HANDLE; 1442 VkSampler fallback_sampler_ = VK_NULL_HANDLE;
1283 bool fallbacks_ready_ = false; 1443 bool fallbacks_ready_ = false;
1284 std::array<std::vector<std::uint8_t>, dimensions> image_used_; 1444 std::array<std::vector<std::uint8_t>, dimensions> image_used_;
1445 // Which of those slots also hold storage views (add_image's `storage`), and which 2D slots hold the mirror of an
1446 // image in another dimension (add_image's MirrorViews): removing that image frees the 2D slot too. insert_key
1447 // reads both to say which arrays an index is bound in. mirror_owner_ says whose mirror each of those 2D slots is
1448 // (dimension + 1, 0 for none) and mirror_storage_used_ whether it has storage views: the 2D slot numbers line up
1449 // with another dimension's indices, so the slot alone does not identify its owner.
1450 std::array<std::vector<std::uint8_t>, dimensions> storage_used_;
1451 std::vector<std::uint8_t> mirror_owner_;
1452 std::vector<std::uint8_t> mirror_storage_used_;
1285 std::vector<std::uint8_t> sampler_used_; 1453 std::vector<std::uint8_t> sampler_used_;
1286 std::vector<std::pair<ImageDimension, std::uint32_t>> held_images_; // removed, not yet free (remove_image) 1454 std::vector<std::pair<ImageDimension, std::uint32_t>> held_images_; // removed, not yet free (remove_image)
1287 std::vector<std::uint32_t> held_samplers_; 1455 std::vector<std::uint32_t> held_samplers_;
diff --git a/runtime/src/vulkan_device_fault.h b/runtime/src/vulkan_device_fault.h
index d60367491..b3af188d1 100644
--- a/runtime/src/vulkan_device_fault.h
+++ b/runtime/src/vulkan_device_fault.h
@@ -2,19 +2,25 @@
2 2
3#include <vulkan/vulkan.h> 3#include <vulkan/vulkan.h>
4 4
5#include "vulkan_device_markers.h"
6
5#include <algorithm> 7#include <algorithm>
6#include <array> 8#include <array>
7#include <atomic> 9#include <atomic>
8#include <chrono> 10#include <chrono>
11#include <condition_variable>
9#include <cinttypes> 12#include <cinttypes>
10#include <cstddef> 13#include <cstddef>
11#include <cstdint> 14#include <cstdint>
12#include <cstdio> 15#include <cstdio>
13#include <cstdlib> 16#include <cstdlib>
14#include <functional> 17#include <functional>
18#include <memory>
15#include <cstring> 19#include <cstring>
16#include <mutex> 20#include <mutex>
17#include <span> 21#include <span>
22#include <string>
23#include <thread>
18#include <unordered_map> 24#include <unordered_map>
19#include <utility> 25#include <utility>
20#include <vector> 26#include <vector>
@@ -25,6 +31,7 @@ struct DeviceFaultExtensions {
25 bool fault = false; 31 bool fault = false;
26 bool checkpoints = false; 32 bool checkpoints = false;
27 bool diagnostics_config = false; 33 bool diagnostics_config = false;
34 bool markers = false; // VK_AMD_buffer_marker (LEONIDA_DEVICE_MARKERS=1, vulkan_device_markers.h)
28}; 35};
29 36
30// What a device asks for. LEONIDA_DEVICE_FAULT=1 wants all of it; LEONIDA_AFTERMATH=1 alone (vulkan_aftermath.h) only 37// What a device asks for. LEONIDA_DEVICE_FAULT=1 wants all of it; LEONIDA_AFTERMATH=1 alone (vulkan_aftermath.h) only
@@ -33,6 +40,7 @@ struct DeviceFaultRequest {
33 bool fault = true; // VK_EXT_device_fault and VK_NV_device_diagnostic_checkpoints 40 bool fault = true; // VK_EXT_device_fault and VK_NV_device_diagnostic_checkpoints
34 bool diagnostics_config = true; // VK_NV_device_diagnostics_config 41 bool diagnostics_config = true; // VK_NV_device_diagnostics_config
35 VkDeviceDiagnosticsConfigFlagsNV extra_flags = 0; // added to the default config flags below 42 VkDeviceDiagnosticsConfigFlagsNV extra_flags = 0; // added to the default config flags below
43 bool markers = false; // VK_AMD_buffer_marker, when the device has it
36}; 44};
37 45
38// Owns the feature structures until vkCreateDevice returns. 46// Owns the feature structures until vkCreateDevice returns.
@@ -62,13 +70,15 @@ struct DeviceFaultFeatures {
62 } 70 }
63 const DeviceFaultExtensions enabled{has_fault && fault.deviceFault == VK_TRUE, 71 const DeviceFaultExtensions enabled{has_fault && fault.deviceFault == VK_TRUE,
64 request.fault && has(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME), 72 request.fault && has(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME),
65 has_config && diagnostics.diagnosticsConfig == VK_TRUE}; 73 has_config && diagnostics.diagnosticsConfig == VK_TRUE,
74 request.markers && has(VK_AMD_BUFFER_MARKER_EXTENSION_NAME)};
66 if (enabled.fault) { 75 if (enabled.fault) {
67 extensions.push_back(VK_EXT_DEVICE_FAULT_EXTENSION_NAME); 76 extensions.push_back(VK_EXT_DEVICE_FAULT_EXTENSION_NAME);
68 fault.pNext = const_cast<void*>(device.pNext); 77 fault.pNext = const_cast<void*>(device.pNext);
69 device.pNext = &fault; 78 device.pNext = &fault;
70 } 79 }
71 if (enabled.checkpoints) extensions.push_back(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME); 80 if (enabled.checkpoints) extensions.push_back(VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME);
81 if (enabled.markers) extensions.push_back(VK_AMD_BUFFER_MARKER_EXTENSION_NAME);
72 if (enabled.diagnostics_config) { 82 if (enabled.diagnostics_config) {
73 extensions.push_back(VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME); 83 extensions.push_back(VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME);
74 diagnostics.pNext = const_cast<void*>(device.pNext); 84 diagnostics.pNext = const_cast<void*>(device.pNext);
@@ -153,6 +163,7 @@ struct CheckpointDispatch {
153 std::uint32_t max_count, stride; 163 std::uint32_t max_count, stride;
154 std::array<std::uint32_t, 32> roots; 164 std::array<std::uint32_t, 32> roots;
155 bool indirect; 165 bool indirect;
166 std::uint64_t seq = 0; // the report's dispatch number, counted over every recorded dispatch (CheckpointRecorder)
156}; 167};
157 168
158struct CheckpointSubmission { 169struct CheckpointSubmission {
@@ -165,6 +176,13 @@ struct CheckpointSubmission {
165 std::vector<CheckpointDispatch> dispatches; 176 std::vector<CheckpointDispatch> dispatches;
166 std::size_t dispatch_count = 0; 177 std::size_t dispatch_count = 0;
167 static constexpr std::size_t dispatch_limit = 64; 178 static constexpr std::size_t dispatch_limit = 64;
179 // Numbers every recorded dispatch, across queues and submissions (the report's seq). Null: no numbers.
180 std::atomic<std::uint64_t>* dispatch_seq = nullptr;
181 // LEONIDA_DEVICE_MARKERS=1: this queue's marker slot, every dispatch recorded for the marker history and the seq
182 // whose finished marker is still to be written after its dispatch (CheckpointRecorder::dispatched).
183 MarkerTarget markers;
184 std::vector<MarkedDispatch> marked;
185 std::uint64_t open_marker = 0;
168 186
169 void append_dispatch(CheckpointDispatch d) { 187 void append_dispatch(CheckpointDispatch d) {
170 if (dispatches.size() < dispatch_limit) dispatches.push_back(d); 188 if (dispatches.size() < dispatch_limit) dispatches.push_back(d);
@@ -201,11 +219,26 @@ struct CheckpointRecorder {
201 std::uintptr_t count = 0, std::uint64_t count_offset = 0, 219 std::uintptr_t count = 0, std::uint64_t count_offset = 0,
202 std::uint32_t max_count = 0, std::uint32_t stride = 0) const { 220 std::uint32_t max_count = 0, std::uint32_t stride = 0) const {
203 const auto names = pipeline_names.find(id); 221 const auto names = pipeline_names.find(id);
222 const char* shader = names != pipeline_names.end() ? names->second[0] : nullptr;
223 const std::uint64_t seq =
224 submission.dispatch_seq ? submission.dispatch_seq->fetch_add(1, std::memory_order_relaxed) + 1 : 0;
204 submission.append_dispatch({submission.execute_call, submission.queue, submission.queue_kind, list, command, 225 submission.append_dispatch({submission.execute_call, submission.queue, submission.queue_kind, list, command,
205 names != pipeline_names.end() ? names->second[0] : nullptr, groups, args, count, 226 shader, groups, args, count, offset, count_offset, max_count, stride, roots, indirect, seq});
206 offset, count_offset, max_count, stride, roots, indirect}); 227 if (submission.markers) {
228 submission.marked.push_back({seq, submission.execute_call, submission.queue, submission.queue_kind,
229 static_cast<std::uint32_t>(list), static_cast<std::uint32_t>(command), shader});
230 submission.markers.started(buffer, seq);
231 submission.open_marker = seq;
232 }
207 record(buffer, command, CheckpointKind::dispatch, pipeline, id); 233 record(buffer, command, CheckpointKind::dispatch, pipeline, id);
208 } 234 }
235
236 // After the dispatch call(s) that dispatch() announced: its finished marker.
237 void dispatched(VkCommandBuffer buffer) const {
238 if (!submission.open_marker) return;
239 submission.markers.finished(buffer, submission.open_marker);
240 submission.open_marker = 0;
241 }
209}; 242};
210 243
211// A D3D fence may stay unsignalled by design. Only queue retirement tickets represent 244// A D3D fence may stay unsignalled by design. Only queue retirement tickets represent
@@ -244,9 +277,308 @@ inline void run_device_lost_hook() noexcept {
244 if (const auto hook = device_lost_hook.load(std::memory_order_acquire)) hook(); 277 if (const auto hook = device_lost_hook.load(std::memory_order_acquire)) hook();
245} 278}
246 279
280// LOCAL DIAGNOSTIC (early device loss): what the submit lock, the recent submissions and the other threads were
281// doing when a submission stalled or the device was lost.
282inline std::int64_t diagnostic_ms() {
283 static const auto start = std::chrono::steady_clock::now();
284 return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
285}
286
287#ifdef _WIN32
288extern "C" __declspec(dllimport) unsigned long __stdcall GetCurrentThreadId(void);
289inline std::uint32_t diagnostic_thread_id() { return static_cast<std::uint32_t>(GetCurrentThreadId()); }
290#else
291inline std::uint32_t diagnostic_thread_id() { return 0; }
292#endif
293
294// Set by gta6rt's main (src/thread_stacks.cpp): prints the call chain of thread `tid`, or of every other thread
295// when `tid` is 0. Unset in the tests.
296inline std::atomic<void (*)(std::uint32_t tid, const char* why) noexcept> thread_stack_hook{nullptr};
297
298inline void print_thread_stacks(std::uint32_t tid, const char* why) noexcept {
299 if (const auto hook = thread_stack_hook.load(std::memory_order_acquire)) hook(tid, why);
300}
301
302// The compute pipeline vkCreateComputePipelines is building now (one at a time is enough: the reports name the one
303// set last), for the submit-lock hold report. Names are ShaderLibrary strings, valid until device teardown.
304struct DriverCompile {
305 std::atomic<const char*> name{nullptr};
306 std::atomic<const char*> trigger{nullptr};
307 std::atomic<std::int64_t> since_ms{0};
308 std::atomic<std::size_t> bytes{0};
309};
310inline DriverCompile driver_compile;
311
312// VulkanContext's submit lock, which also remembers who holds it, since when and how many threads wait for it. A
313// submit or an idle wait blocked inside the driver holds it for as long as it blocks; the stall watchdog and the loss
314// report name that thread, and a hold of a second or more is logged when it ends.
315class SubmitMutex {
316public:
317 static constexpr std::int64_t kLongHoldMs = 1000;
318 // How long let_submit_finish(true) keeps letting queued submitters go first before the caller goes ahead anyway,
319 // so a steady stream of submits cannot hold the compile worker back for ever. Waiting out the holder itself is
320 // not capped: entering the driver while a submit is inside it is what lost the device.
321 static constexpr std::int64_t kHandoffCapMs = 250;
322
323 void lock() {
324 if (mutex_.try_lock()) {
325 taken();
326 return;
327 }
328 // Counted until this thread owns the lock (owner_ set), so let_submit_finish never sees neither.
329 waiting_.fetch_add(1, std::memory_order_relaxed);
330 mutex_.lock();
331 taken();
332 waiting_.fetch_sub(1, std::memory_order_relaxed);
333 }
334 bool try_lock() {
335 if (!mutex_.try_lock()) return false;
336 taken();
337 return true;
338 }
339 void unlock() {
340 const std::int64_t since = since_.load(std::memory_order_relaxed);
341 const std::uint32_t owner = owner_.load(std::memory_order_relaxed);
342 owner_.store(0, std::memory_order_relaxed);
343 releases_.fetch_add(1); // seq_cst with the handoff_waiters_ load: no let_submit_finish misses this release
344 mutex_.unlock();
345 if (handoff_waiters_.load()) {
346 std::lock_guard lock(handoff_mutex_);
347 released_.notify_all();
348 }
349 const std::int64_t now = diagnostic_ms();
350 if (now - since >= kLongHoldMs)
351 std::fprintf(stderr, "[rt] submit-lock: held %lld ms by thread %u, t=%.3f..%.3f s\n",
352 static_cast<long long>(now - since), owner, double(since) / 1000.0, double(now) / 1000.0);
353 }
354
355 std::uint32_t owner() const { return owner_.load(std::memory_order_relaxed); }
356 std::int64_t since_ms() const { return since_.load(std::memory_order_relaxed); }
357 // Threads blocked in lock() (try_lock never counts).
358 std::uint32_t waiting() const { return waiting_.load(std::memory_order_relaxed); }
359
360 // Called before the driver calls that build pipelines: waits for a submit in progress to finish (unless this
361 // thread is the one submitting). Measured on NVIDIA 630.20 (three early losses): back-to-back pipeline creates on
362 // the compile worker keep re-taking a driver lock that vkQueueSubmit waits for; after 10 s of that wait the driver
363 // returns VK_ERROR_DEVICE_LOST, with no GPU fault and no TDR. Not entering the driver while a submit is in it lets
364 // the submit take that lock between two creates.
365 // `queued` (the compile worker): also lets the submitters queued behind the holder go first - std::mutex is not
366 // fair, so without that the worker's next create could get in ahead of them - for at most `cap_ms`; past it the
367 // hold in progress is the last one waited for. The wait never takes the lock itself (taking it could queue behind
368 // every submitter that re-takes it), it waits for the hold it saw to end. Returns how many milliseconds it waited.
369 std::int64_t let_submit_finish(bool queued = true, std::int64_t cap_ms = kHandoffCapMs) {
370 const std::uint32_t self = diagnostic_thread_id();
371 if (owner_.load(std::memory_order_relaxed) == self) return 0; // this thread submits: nothing to let through
372 const auto queue = [&] { return queued && waiting_.load(std::memory_order_relaxed) != 0; };
373 std::uint64_t seen = releases_.load();
374 const auto held = [&] {
375 seen = releases_.load(); // read before the owner: a hold that ends after this changes it
376 return owner_.load() != 0;
377 };
378 if (!held() && !queue()) return 0;
379 const std::int64_t start = diagnostic_ms();
380 for (;;) {
381 const bool over = diagnostic_ms() - start >= cap_ms;
382 if (held()) {
383 wait_release(seen);
384 if (!queued || over) break;
385 } else if (!queue() || over) {
386 break;
387 } else {
388 std::this_thread::yield(); // a queued submitter is between its wake-up and taking the lock
389 }
390 }
391 return diagnostic_ms() - start;
392 }
393
394 // The compile gate. A queue submission never enters the driver while a pipeline create is in it: measured on
395 // NVIDIA 630.20 (wf6), a vkQueueSubmit that entered while the warm-up thread was inside one long
396 // vkCreateComputePipelines waited 10 s in the driver and returned VK_ERROR_DEVICE_LOST; let_submit_finish cannot
397 // help once the create is already running. Creates pass the gate shared, a submission exclusively, and a create
398 // that arrives while a submission waits queues behind it, so a submission waits only for the creates already in
399 // the driver. A long compile then stalls the submitting thread here, in our code, instead of in the driver.
400 // No deadlock: a create holds the gate only across its vkCreate*Pipelines and a submission only across its
401 // vkQueueSubmit, and neither driver call waits for anything of ours. LEONIDA_COMPILE_GATE=0 turns it off.
402 class CompileTurn { // around vkCreate*Pipelines
403 public:
404 explicit CompileTurn(SubmitMutex& gate) : gate_(gate), waited_(gate.enter_compile()) {}
405 ~CompileTurn() { gate_.leave_compile(); }
406 CompileTurn(const CompileTurn&) = delete;
407 CompileTurn& operator=(const CompileTurn&) = delete;
408 std::int64_t waited_ms() const { return waited_; }
409
410 private:
411 SubmitMutex& gate_;
412 std::int64_t waited_;
413 };
414 class SubmitTurn { // around vkQueueSubmit, with the submit lock held
415 public:
416 explicit SubmitTurn(SubmitMutex& gate) : gate_(gate) { gate.enter_submit(); }
417 ~SubmitTurn() { gate_.leave_submit(); }
418 SubmitTurn(const SubmitTurn&) = delete;
419 SubmitTurn& operator=(const SubmitTurn&) = delete;
420
421 private:
422 SubmitMutex& gate_;
423 };
424
425 static bool compile_gate_enabled() {
426 static const bool on = [] {
427 const char* value = std::getenv("LEONIDA_COMPILE_GATE");
428 return !(value && !std::strcmp(value, "0"));
429 }();
430 return on;
431 }
432
433 // The thread waiting in enter_submit for creates to leave the driver, or 0.
434 std::uint32_t gate_waiter() const { return gate_waiter_.load(std::memory_order_relaxed); }
435
436 struct GateStats {
437 std::uint64_t submits = 0; // submissions that had to wait for a create
438 std::int64_t submit_ms = 0, submit_max_ms = 0;
439 std::uint64_t creates = 0; // creates that waited behind a submission
440 std::int64_t create_ms = 0, create_max_ms = 0;
441 };
442 GateStats gate_stats() {
443 std::lock_guard lock(gate_mutex_);
444 return stats_;
445 }
446
447 std::int64_t enter_compile() {
448 if (!compile_gate_enabled()) return 0;
449 std::unique_lock lock(gate_mutex_);
450 std::int64_t waited = 0;
451 if (submits_) {
452 const std::int64_t start = diagnostic_ms();
453 gate_changed_.wait(lock, [&] { return submits_ == 0; });
454 waited = diagnostic_ms() - start;
455 ++stats_.creates;
456 stats_.create_ms += waited;
457 stats_.create_max_ms = (std::max)(stats_.create_max_ms, waited);
458 }
459 ++compiles_;
460 return waited;
461 }
462 void leave_compile() {
463 if (!compile_gate_enabled()) return;
464 std::lock_guard lock(gate_mutex_);
465 if (--compiles_ == 0 && submits_) gate_changed_.notify_all();
466 }
467
468 std::int64_t enter_submit() {
469 if (!compile_gate_enabled()) return 0;
470 std::unique_lock lock(gate_mutex_);
471 ++submits_;
472 if (!compiles_) return 0;
473 const std::uint32_t self = diagnostic_thread_id();
474 gate_waiter_.store(self, std::memory_order_relaxed);
475 const std::int64_t start = diagnostic_ms();
476 const GateWait what{self, compiles_, driver_compile.name.load(std::memory_order_acquire),
477 driver_compile.trigger.load(std::memory_order_relaxed),
478 driver_compile.bytes.load(std::memory_order_relaxed)};
479 std::int64_t next_note = 2000;
480 while (!gate_changed_.wait_for(lock, std::chrono::milliseconds(250), [&] { return compiles_ == 0; })) {
481 const std::int64_t waited = diagnostic_ms() - start;
482 if (waited < next_note) continue;
483 next_note = waited + 5000;
484 note_gate_wait("has waited", what, waited);
485 }
486 gate_waiter_.store(0, std::memory_order_relaxed);
487 const std::int64_t waited = diagnostic_ms() - start;
488 ++stats_.submits;
489 stats_.submit_ms += waited;
490 stats_.submit_max_ms = (std::max)(stats_.submit_max_ms, waited);
491 // Every wait of 500 ms or more, and the first 32 of 50 ms or more.
492 if (waited >= 500 || (waited >= 50 && logged_waits_ < 32)) {
493 ++logged_waits_;
494 note_gate_wait("waited", what, waited);
495 }
496 return waited;
497 }
498 void leave_submit() {
499 if (!compile_gate_enabled()) return;
500 std::lock_guard lock(gate_mutex_);
501 if (--submits_ == 0) gate_changed_.notify_all();
502 }
503
504private:
505 void taken() {
506 since_.store(diagnostic_ms(), std::memory_order_relaxed);
507 owner_.store(diagnostic_thread_id(), std::memory_order_relaxed);
508 }
509
510 // Until a hold ends after `seen` releases.
511 void wait_release(std::uint64_t seen) {
512 handoff_waiters_.fetch_add(1);
513 {
514 std::unique_lock lock(handoff_mutex_);
515 released_.wait(lock, [&] { return releases_.load() != seen; });
516 }
517 handoff_waiters_.fetch_sub(1);
518 }
519
520 // With gate_mutex_ held.
521 // The creates a submission found in the driver: how many, and the compute one named last (graphics creates are
522 // not named). Names are ShaderLibrary strings, valid until device teardown.
523 struct GateWait {
524 std::uint32_t thread;
525 std::uint32_t creates;
526 const char* name;
527 const char* trigger;
528 std::size_t bytes;
529 };
530 void note_gate_wait(const char* how, const GateWait& what, std::int64_t waited) const {
531 std::fprintf(stderr, "[rt] compile-gate: vkQueueSubmit on thread %u %s %lld ms for %u pipeline create(s) to "
532 "leave the driver (compute %s, %zu B SPIR-V, %s) at t=%.3f s; %llu such waits so far, "
533 "%lld ms in all, longest %lld ms\n",
534 what.thread, how, static_cast<long long>(waited), what.creates, what.name ? what.name : "-",
535 what.name ? what.bytes : std::size_t{0}, what.name && what.trigger ? what.trigger : "-",
536 double(diagnostic_ms()) / 1000.0, static_cast<unsigned long long>(stats_.submits),
537 static_cast<long long>(stats_.submit_ms), static_cast<long long>(stats_.submit_max_ms));
538 }
539
540 std::mutex mutex_;
541 std::atomic<std::uint32_t> owner_{0};
542 std::atomic<std::int64_t> since_{0};
543 std::atomic<std::uint32_t> waiting_{0};
544 std::atomic<std::uint64_t> releases_{0}; // unlocks so far
545 std::atomic<std::uint32_t> handoff_waiters_{0};
546 std::mutex handoff_mutex_; // leaf
547 std::condition_variable released_;
548
549 std::mutex gate_mutex_; // leaf: guards the gate counts and stats
550 std::condition_variable gate_changed_;
551 std::uint32_t compiles_ = 0; // creates in the driver
552 std::uint32_t submits_ = 0; // submissions waiting for them or in the driver
553 std::atomic<std::uint32_t> gate_waiter_{0};
554 GateStats stats_;
555 unsigned logged_waits_ = 0;
556};
557
558// One vkQueueSubmit of a VulkanQueue: its waits, its signals and how long the call took (-1: not returned yet).
559struct SubmitRecord {
560 static constexpr std::size_t max_waits = 6;
561 std::int64_t at_ms = 0;
562 std::int64_t took_ms = -1;
563 int result = 1;
564 VkQueue queue = VK_NULL_HANDLE;
565 const char* kind = "";
566 VkSemaphore progress = VK_NULL_HANDLE;
567 std::uint64_t ticket = 0;
568 VkSemaphore fence = VK_NULL_HANDLE;
569 std::uint64_t fence_value = 0;
570 std::uint32_t buffers = 0;
571 std::uint32_t waits = 0;
572 std::array<VkSemaphore, max_waits> wait_semaphores{};
573 std::array<std::uint64_t, max_waits> wait_values{};
574};
575
247class DeviceFaultDiagnostics { 576class DeviceFaultDiagnostics {
248public: 577public:
249 DeviceFaultDiagnostics(PFN_vkGetDeviceProcAddr get, VkDevice device, DeviceFaultExtensions enabled) 578 // `memory` and `synchronization2` are for the AMD markers (enabled.markers): where their buffer goes and whether
579 // vkCmdWriteBufferMarker2AMD may be used.
580 DeviceFaultDiagnostics(PFN_vkGetDeviceProcAddr get, VkDevice device, DeviceFaultExtensions enabled,
581 const VkPhysicalDeviceMemoryProperties* memory = nullptr, bool synchronization2 = false)
250 : device_(device) { 582 : device_(device) {
251#define LEONIDA_FAULT_LOAD(name) name = reinterpret_cast<PFN_##name>(get(device, #name)) 583#define LEONIDA_FAULT_LOAD(name) name = reinterpret_cast<PFN_##name>(get(device, #name))
252 if (enabled.fault) LEONIDA_FAULT_LOAD(vkGetDeviceFaultInfoEXT); 584 if (enabled.fault) LEONIDA_FAULT_LOAD(vkGetDeviceFaultInfoEXT);
@@ -254,10 +586,22 @@ public:
254 LEONIDA_FAULT_LOAD(vkCmdSetCheckpointNV); 586 LEONIDA_FAULT_LOAD(vkCmdSetCheckpointNV);
255 LEONIDA_FAULT_LOAD(vkGetQueueCheckpointDataNV); 587 LEONIDA_FAULT_LOAD(vkGetQueueCheckpointDataNV);
256 } 588 }
589 LEONIDA_FAULT_LOAD(vkGetSemaphoreCounterValue);
257#undef LEONIDA_FAULT_LOAD 590#undef LEONIDA_FAULT_LOAD
258 std::fprintf(stderr, "[rt] device-fault: enabled (fault info %s, checkpoints %s, NVIDIA diagnostics config %s)\n", 591 std::fprintf(stderr, "[rt] device-fault: enabled (fault info %s, checkpoints %s, NVIDIA diagnostics config %s)\n",
259 vkGetDeviceFaultInfoEXT ? "on" : "unavailable", checkpoint_command() ? "on" : "unavailable", 592 vkGetDeviceFaultInfoEXT ? "on" : "unavailable", checkpoint_command() ? "on" : "unavailable",
260 enabled.diagnostics_config ? "on" : "unavailable"); 593 enabled.diagnostics_config ? "on" : "unavailable");
594 if (enabled.markers) enable_markers(get, memory, synchronization2);
595 else if (device_markers_requested())
596 std::fprintf(stderr, "[rt] device-markers: unavailable: the device has no VK_AMD_buffer_marker\n");
597 }
598
599 bool markers_on() const { return markers_ != nullptr; }
600
601 // The queue's marker slot as the GPU last wrote it ({0, 0} without markers).
602 MarkerSlot marker_slot(VkQueue queue) {
603 std::lock_guard lock(mutex_);
604 return markers_ ? markers_->read(queue) : MarkerSlot{};
261 } 605 }
262 606
263 PFN_vkCmdSetCheckpointNV checkpoint_command() const { 607 PFN_vkCmdSetCheckpointNV checkpoint_command() const {
@@ -265,21 +609,166 @@ public:
265 } 609 }
266 610
267 void add_queue(VkQueue queue) { 611 void add_queue(VkQueue queue) {
268 if (!queue || !vkGetQueueCheckpointDataNV) return; 612 if (!queue) return;
269 std::lock_guard lock(mutex_); 613 std::lock_guard lock(mutex_);
614 if (markers_ && !markers_->add_queue(queue))
615 std::fprintf(stderr, "[rt] device-markers: no slot for queue %p (%u queues have one)\n",
616 static_cast<void*>(queue), DeviceMarkers::max_queues);
617 if (!vkGetQueueCheckpointDataNV) return;
270 if (std::find(queues_.begin(), queues_.end(), queue) == queues_.end()) queues_.push_back(queue); 618 if (std::find(queues_.begin(), queues_.end(), queue) == queues_.end()) queues_.push_back(queue);
271 } 619 }
272 620
273 std::uint64_t next_execute_call() { return ++execute_calls_; } 621 std::uint64_t next_execute_call() { return ++execute_calls_; }
274 622
623 void set_submit_lock(const SubmitMutex* lock) { submit_lock_ = lock; }
624
625 // Called under the submit lock, before and after the vkQueueSubmit it describes.
626 std::size_t begin_submit(const SubmitRecord& record) {
627 std::lock_guard lock(mutex_);
628 const std::size_t at = submit_count_++;
629 submits_[at % submits_.size()] = record;
630 return at;
631 }
632 void end_submit(std::size_t at, std::int64_t took_ms, VkResult result) {
633 std::lock_guard lock(mutex_);
634 if (submit_count_ - at > submits_.size()) return;
635 auto& record = submits_[at % submits_.size()];
636 record.took_ms = took_ms;
637 record.result = int(result);
638 }
639
640 // The holder of the submit lock has kept it for `held_ms`: its call chain and what was submitted last.
641 void report_submit_lock_holder(std::uint32_t owner, std::int64_t held_ms) {
642 std::fprintf(stderr, "[rt] submit-lock: thread %u has held it for %lld ms (t=%.3f s)\n", owner,
643 static_cast<long long>(held_ms), double(diagnostic_ms()) / 1000.0);
644 if (const char* name = driver_compile.name.load(std::memory_order_acquire)) {
645 const char* trigger = driver_compile.trigger.load(std::memory_order_relaxed);
646 std::fprintf(stderr, "[rt] submit-lock: vkCreateComputePipelines has been building %s (%zu B SPIR-V, %s) "
647 "for %lld ms\n",
648 name, driver_compile.bytes.load(std::memory_order_relaxed), trigger ? trigger : "?",
649 static_cast<long long>(diagnostic_ms() - driver_compile.since_ms.load(std::memory_order_relaxed)));
650 }
651 if (submit_lock_ && submit_lock_->gate_waiter() == owner) {
652 // Not in the driver: waiting at the compile gate for the create named above (SubmitMutex::CompileTurn).
653 std::fprintf(stderr, "[rt] submit-lock: thread %u is waiting at the compile gate, not in the driver\n", owner);
654 return;
655 }
656 // Every thread, the holder included: what the driver waits for may be another thread's work. No counters
657 // here (dump_submits would block in the driver behind the holder); the loss report has them. A long hold can
658 // also be a legitimate vkDeviceWaitIdle: the stacks of the first three holds, then at most one a minute.
659 const std::int64_t now = diagnostic_ms();
660 if (stack_reports_ >= 3 && now - last_stack_report_ms_ < 60000) return;
661 ++stack_reports_;
662 last_stack_report_ms_ = now;
663 print_thread_stacks(0, "submit-lock hold");
664 }
665
666 // Before `semaphore` is destroyed (~VulkanFence, ~VulkanQueue): the ring stops naming it, so no report reads the
667 // counter of a destroyed semaphore. Waits for a report that is reading counters now.
668 void forget(VkSemaphore semaphore) {
669 if (!semaphore) return;
670 std::lock_guard reading(read_mutex_);
671 if (stalled_progress_ == semaphore) stalled_progress_ = VK_NULL_HANDLE;
672 std::lock_guard lock(mutex_);
673 for (auto& r : submits_) {
674 if (r.progress == semaphore) r.progress = VK_NULL_HANDLE;
675 if (r.fence == semaphore) r.fence = VK_NULL_HANDLE;
676 for (auto& wait : r.wait_semaphores)
677 if (wait == semaphore) wait = VK_NULL_HANDLE;
678 }
679 }
680
681 // Once a second from the progress watch, without the submit lock: when the oldest submission in the ring that
682 // has not finished is 4 s old, the ring with every counter as it is now, once per such submission.
683 void check_submit_progress() {
684 std::lock_guard reading(read_mutex_); // the semaphores read below outlive this call (forget)
685 const std::vector<SubmitRecord> records = submit_records();
686 if (!vkGetSemaphoreCounterValue) return;
687 const std::int64_t now = diagnostic_ms();
688 for (const auto& r : records) {
689 if (r.took_ms < 0 || r.result != VK_SUCCESS || !r.progress) continue;
690 std::uint64_t done = 0;
691 if (vkGetSemaphoreCounterValue(device_, r.progress, &done) != VK_SUCCESS) return;
692 if (done >= r.ticket) continue;
693 // Age from when vkQueueSubmit returned: the call itself may have waited at the compile gate.
694 if (now - (r.at_ms + r.took_ms) < 4000) return; // the oldest unfinished one is young
695 if (r.progress == stalled_progress_ && r.ticket == stalled_ticket_) return;
696 stalled_progress_ = r.progress;
697 stalled_ticket_ = r.ticket;
698 std::fprintf(stderr, "[rt] gpu-stall: %s queue %p ticket %llu submitted at t=%.3f s not done after %lld ms "
699 "(progress %llu)\n",
700 r.kind, static_cast<void*>(r.queue), static_cast<unsigned long long>(r.ticket),
701 double(r.at_ms) / 1000.0, static_cast<long long>(now - r.at_ms),
702 static_cast<unsigned long long>(done));
703 dump_submits_reading();
704 return;
705 }
706 }
707
708 // The last submissions, oldest first, with every semaphore's counter now (? once the device is lost, or for a
709 // semaphore destroyed since).
710 void dump_submits() {
711 std::lock_guard reading(read_mutex_);
712 dump_submits_reading();
713 }
714
715private:
716 std::vector<SubmitRecord> submit_records() {
717 std::vector<SubmitRecord> records;
718 std::lock_guard lock(mutex_);
719 const std::size_t n = std::min(submit_count_, submits_.size());
720 records.reserve(n);
721 for (std::size_t i = submit_count_ - n; i < submit_count_; ++i) records.push_back(submits_[i % submits_.size()]);
722 return records;
723 }
724
725 // dump_submits with read_mutex_ held.
726 void dump_submits_reading() {
727 const std::vector<SubmitRecord> records = submit_records();
728 // Every semaphore the ring names is non-null when recorded: null is one destroyed since (forget).
729 const auto counter = [&](VkSemaphore semaphore) -> std::string {
730 std::uint64_t value = 0;
731 if (!semaphore) return "destroyed";
732 if (!vkGetSemaphoreCounterValue || vkGetSemaphoreCounterValue(device_, semaphore, &value) != VK_SUCCESS)
733 return "?";
734 return std::to_string(value);
735 };
736 const std::int64_t now = diagnostic_ms();
737 for (const auto& r : records) {
738 std::string line = "[rt] submit-ring: t=" + std::to_string(double(r.at_ms) / 1000.0) + " s " + r.kind +
739 " queue=" + std::to_string(reinterpret_cast<std::uintptr_t>(r.queue)) +
740 " buffers=" + std::to_string(r.buffers) + " ticket=" + std::to_string(r.ticket) +
741 " progress=" + counter(r.progress) + " took=" +
742 (r.took_ms < 0 ? "pending(" + std::to_string(now - r.at_ms) + " ms)"
743 : std::to_string(r.took_ms) + " ms") +
744 " result=" + std::to_string(r.result);
745 if (r.fence || r.fence_value)
746 line += " signal=" + std::to_string(pipeline_handle(r.fence)) + ":" + std::to_string(r.fence_value) +
747 " now " + counter(r.fence);
748 for (std::uint32_t i = 0; i < r.waits && i < SubmitRecord::max_waits; ++i)
749 line += " wait=" + std::to_string(pipeline_handle(r.wait_semaphores[i])) + ":" +
750 std::to_string(r.wait_values[i]) + " now " + counter(r.wait_semaphores[i]);
751 if (r.waits > SubmitRecord::max_waits) line += " (+" + std::to_string(r.waits - SubmitRecord::max_waits) + " waits)";
752 line += '\n';
753 std::fputs(line.c_str(), stderr);
754 }
755 }
756
757public:
275 // Accessed under the context's resource lock. Reports read the names copied into the ring instead. 758 // Accessed under the context's resource lock. Reports read the names copied into the ring instead.
276 std::unordered_map<std::uintptr_t, CheckpointShaders> pipeline_names; 759 std::unordered_map<std::uintptr_t, CheckpointShaders> pipeline_names;
277 760
278 // Called under the context's tracker lock, in replay order. 761 // Called under the context's tracker lock, in replay order.
279 CheckpointSubmission begin_submission(std::uint64_t call, VkQueue queue, const char* kind, std::size_t lists) { 762 CheckpointSubmission begin_submission(std::uint64_t call, VkQueue queue, const char* kind, std::size_t lists) {
280 if (!++sequence_) ++sequence_; // 0 is reserved for invalid markers 763 if (!++sequence_) ++sequence_; // 0 is reserved for invalid markers
281 return {sequence_, call, queue, kind, lists, 764 CheckpointSubmission submission{sequence_, call, queue, kind, lists,
282 std::vector<CheckpointList>(std::min(lists, std::size_t{CheckpointMarker::max_list} + 1))}; 765 std::vector<CheckpointList>(std::min(lists, std::size_t{CheckpointMarker::max_list} + 1))};
766 submission.dispatch_seq = &dispatch_seq_;
767 if (markers_) {
768 std::lock_guard lock(mutex_);
769 submission.markers = markers_->target(queue);
770 }
771 return submission;
283 } 772 }
284 773
285 void publish(CheckpointSubmission&& submission) { 774 void publish(CheckpointSubmission&& submission) {
@@ -287,12 +776,24 @@ public:
287 for (std::size_t i = submission.dispatch_count - submission.dispatches.size(); i < submission.dispatch_count; ++i) 776 for (std::size_t i = submission.dispatch_count - submission.dispatches.size(); i < submission.dispatch_count; ++i)
288 dispatches_[dispatch_count_++ % dispatches_.size()] = submission.dispatches[i % submission.dispatch_limit]; 777 dispatches_[dispatch_count_++ % dispatches_.size()] = submission.dispatches[i % submission.dispatch_limit];
289 submission.dispatches.clear(); 778 submission.dispatches.clear();
779 if (history_)
780 for (const auto& d : submission.marked) history_->push(d);
781 submission.marked.clear();
290 recent_[submission.sequence % recent_.size()] = std::move(submission); 782 recent_[submission.sequence % recent_.size()] = std::move(submission);
291 } 783 }
292 784
293 static VkResult observe(DeviceFaultDiagnostics* diagnostics, VkResult result, const char* operation) noexcept { 785 static VkResult observe(DeviceFaultDiagnostics* diagnostics, VkResult result, const char* operation) noexcept {
294 if (result == VK_ERROR_DEVICE_LOST) { 786 if (result == VK_ERROR_DEVICE_LOST) {
295 if (diagnostics) diagnostics->report(operation); 787 if (diagnostics) {
788 diagnostics->report(operation);
789 } else {
790 // Without LEONIDA_DEVICE_FAULT a loss was silent: the title only saw ~0 in its fence words.
791 static std::atomic<bool> logged{false};
792 if (!logged.exchange(true, std::memory_order_relaxed))
793 std::fprintf(stderr, "[rt] vulkan: VK_ERROR_DEVICE_LOST from %s at t=%.3f s on thread %u "
794 "(LEONIDA_DEVICE_FAULT=1 for the fault report)\n",
795 operation, double(diagnostic_ms()) / 1000.0, diagnostic_thread_id());
796 }
296 run_device_lost_hook(); 797 run_device_lost_hook();
297 } 798 }
298 return result; 799 return result;
@@ -301,8 +802,9 @@ public:
301 void report_stall(const char* reason, std::uint64_t submitted, std::uint64_t retired) { 802 void report_stall(const char* reason, std::uint64_t submitted, std::uint64_t retired) {
302 std::fprintf(stderr, "[rt] device-stall: %s for 15 s; submitted ticket %" PRIu64 803 std::fprintf(stderr, "[rt] device-stall: %s for 15 s; submitted ticket %" PRIu64
303 ", last observed retired ticket %" PRIu64 "\n", reason, submitted, retired); 804 ", last observed retired ticket %" PRIu64 "\n", reason, submitted, retired);
304 // NV checkpoints and EXT fault data require a lost device. The CPU ring is valid at any time. 805 // NV checkpoints and EXT fault data require a lost device. The CPU ring and the AMD markers are valid at any
305 dump_dispatches(); 806 // time.
807 dump_dispatches(report_markers(false));
306 // LEONIDA_STALL_CHECKPOINTS=1 (diagnostic): ask for the checkpoints anyway. A hang (Xid 109) the driver 808 // LEONIDA_STALL_CHECKPOINTS=1 (diagnostic): ask for the checkpoints anyway. A hang (Xid 109) the driver
307 // recovers from without losing the device otherwise names no program; outside the lost state the call is 809 // recovers from without losing the device otherwise names no program; outside the lost state the call is
308 // out of the extension's contract, which the NVIDIA driver has answered so far. 810 // out of the extension's contract, which the NVIDIA driver has answered so far.
@@ -319,14 +821,87 @@ public:
319 } 821 }
320 } 822 }
321 823
824 // LEONIDA_DEVICE_MARKERS=1: each queue's marker slot judged against the marker history, printed; returns the
825 // likely hangs (the oldest started, unfinished dispatch of each queue) for dump_dispatches to mark.
826 std::vector<std::uint64_t> report_markers(bool lost) noexcept {
827 std::vector<std::uint64_t> hangs;
828 if (!markers_) return hangs;
829 try {
830 std::lock_guard lock(mutex_);
831 std::fprintf(stderr, "[rt] device-markers: AMD buffer markers, read %s; best-effort: %s\n",
832 lost ? "after the device loss" : "while the device is still up",
833 lost ? "only what the GPU wrote before it stopped, and a reset may have lost the last writes"
834 : "the GPU may still be writing them");
835 for (VkQueue queue : markers_->queues()) {
836 const MarkerQueueReport r = judge_markers(queue, markers_->read(queue), *history_);
837 if (!r.slot.started && !r.slot.finished && !r.next_queued) continue; // never marked a dispatch
838 const char* kind = r.queue_kind ? r.queue_kind : "?";
839 if (r.idle()) {
840 std::fprintf(stderr, "[rt] device-markers: queue %p (%s) idle: finished seq=%u, nothing started "
841 "after it", static_cast<void*>(queue), kind, unsigned(r.slot.finished));
842 if (r.next_queued)
843 std::fprintf(stderr, "; next submitted seq=%" PRIu64 " not started (waiting, or behind other "
844 "work of the queue)", r.next_queued);
845 std::fputc('\n', stderr);
846 continue;
847 }
848 std::string line = "[rt] device-markers: queue " + hex(queue) + " (" + kind + ") finished seq=" +
849 std::to_string(r.slot.finished) + " started seq=" + std::to_string(r.slot.started) +
850 "; started, not finished:";
851 for (std::size_t i = 0; i < r.unfinished.size() && i < 16; ++i)
852 line += " " + std::to_string(r.unfinished[i]);
853 if (r.unfinished.size() > 16) line += " (+" + std::to_string(r.unfinished.size() - 16) + ")";
854 if (r.missing) line += " (no longer in the marker history)";
855 line += '\n';
856 std::fputs(line.c_str(), stderr);
857 if (!r.likely_hang) continue;
858 hangs.push_back(r.likely_hang);
859 history_->for_each([&](const MarkedDispatch& d) {
860 if (d.seq != r.likely_hang) return;
861 std::fprintf(stderr, "[rt] device-markers: likely hang: seq=%" PRIu64 " execute=%" PRIu64
862 " queue=%p (%s) list=%u command=%u shader=%s\n",
863 d.seq, d.execute_call, static_cast<void*>(d.queue), kind, d.list, d.command,
864 d.shader ? d.shader : "-");
865 });
866 }
867 } catch (...) {
868 std::fprintf(stderr, "[rt] device-markers: marker collection failed\n");
869 }
870 return hangs;
871 }
872
322private: 873private:
323 void dump_dispatches() { 874 void enable_markers(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties* memory,
875 bool synchronization2) {
876 auto markers = std::make_unique<DeviceMarkers>();
877 const VkResult result =
878 memory ? markers->create(get, device_, *memory, synchronization2) : VK_ERROR_INITIALIZATION_FAILED;
879 if (result != VK_SUCCESS) {
880 std::fprintf(stderr, "[rt] device-markers: unavailable: the marker buffer could not be made (%d)\n",
881 int(result));
882 return;
883 }
884 std::fprintf(stderr, "[rt] device-markers: on (VK_AMD_buffer_marker, %s): each dispatch writes its seq at top "
885 "and bottom of pipe\n",
886 markers->synchronization2() ? "vkCmdWriteBufferMarker2AMD" : "vkCmdWriteBufferMarkerAMD");
887 history_ = std::make_unique<MarkerHistory>();
888 markers_ = std::move(markers);
889 }
890
891 template<typename Handle>
892 static std::string hex(Handle handle) {
893 char text[24];
894 std::snprintf(text, sizeof(text), "%p", static_cast<void*>(handle));
895 return text;
896 }
897
898 void dump_dispatches(const std::vector<std::uint64_t>& hangs = {}) {
324 std::lock_guard lock(mutex_); 899 std::lock_guard lock(mutex_);
325 const auto n = std::min(dispatch_count_, dispatches_.size()); 900 const auto n = std::min(dispatch_count_, dispatches_.size());
326 for (std::size_t i = dispatch_count_ - n; i < dispatch_count_; ++i) { 901 for (std::size_t i = dispatch_count_ - n; i < dispatch_count_; ++i) {
327 const auto& d = dispatches_[i % dispatches_.size()]; 902 const auto& d = dispatches_[i % dispatches_.size()];
328 std::fprintf(stderr, "[rt] device-fault: submitted dispatch seq=%zu execute=%" PRIu64 903 std::fprintf(stderr, "[rt] device-fault: submitted dispatch seq=%" PRIu64 " execute=%" PRIu64
329 " queue=%p (%s) list=%zu command=%zu shader=%s ", i + 1, d.execute_call, 904 " queue=%p (%s) list=%zu command=%zu shader=%s ", d.seq, d.execute_call,
330 static_cast<void*>(d.queue), d.queue_kind, d.list, d.command, d.shader ? d.shader : "-"); 905 static_cast<void*>(d.queue), d.queue_kind, d.list, d.command, d.shader ? d.shader : "-");
331 if (d.indirect) 906 if (d.indirect)
332 std::fprintf(stderr, "indirect args=0x%" PRIxPTR "+0x%" PRIx64 " count=0x%" PRIxPTR 907 std::fprintf(stderr, "indirect args=0x%" PRIxPTR "+0x%" PRIx64 " count=0x%" PRIxPTR
@@ -337,6 +912,8 @@ private:
337 std::fputs(" roots=", stderr); 912 std::fputs(" roots=", stderr);
338 for (auto word : d.roots) std::fprintf(stderr, "%08x ", word); 913 for (auto word : d.roots) std::fprintf(stderr, "%08x ", word);
339 } 914 }
915 if (d.seq && std::find(hangs.begin(), hangs.end(), d.seq) != hangs.end())
916 std::fputs(" <- likely hang (device-markers)", stderr);
340 std::fputc('\n', stderr); 917 std::fputc('\n', stderr);
341 } 918 }
342 } 919 }
@@ -354,7 +931,17 @@ private:
354 void report(const char* operation) noexcept { 931 void report(const char* operation) noexcept {
355 if (reported_.exchange(true, std::memory_order_relaxed)) return; 932 if (reported_.exchange(true, std::memory_order_relaxed)) return;
356 std::fprintf(stderr, "[rt] device-fault: VK_ERROR_DEVICE_LOST from %s\n", operation); 933 std::fprintf(stderr, "[rt] device-fault: VK_ERROR_DEVICE_LOST from %s\n", operation);
357 dump_dispatches(); 934 try {
935 const std::int64_t now = diagnostic_ms();
936 const std::uint32_t owner = submit_lock_ ? submit_lock_->owner() : 0;
937 std::fprintf(stderr, "[rt] device-fault: t=%.3f s on thread %u; submit lock held by thread %u for %lld ms\n",
938 double(now) / 1000.0, diagnostic_thread_id(), owner,
939 owner ? static_cast<long long>(now - submit_lock_->since_ms()) : 0LL);
940 dump_submits();
941 print_thread_stacks(0, "device lost");
942 } catch (...) {
943 }
944 dump_dispatches(report_markers(true));
358 try { 945 try {
359 std::function<void()> hook; 946 std::function<void()> hook;
360 { 947 {
@@ -455,6 +1042,36 @@ private:
455 pipeline.shaders[2] ? pipeline.shaders[2] : "-"); 1042 pipeline.shaders[2] ? pipeline.shaders[2] : "-");
456 } 1043 }
457 } 1044 }
1045 // LOCAL DIAGNOSTIC (post-load GPU faults): the work in flight is between the bottom-of-pipe checkpoint (last
1046 // command finished) and the top-of-pipe one (last command started) of the same list. Every pipeline bound in
1047 // that window, so the faulting program is among them; the dispatch ring above only keeps the last 64
1048 // dispatches of all queues, and those were from another queue in the fault this was added for.
1049 for (std::uint32_t i = 0; i < count; ++i) {
1050 const auto top = CheckpointMarker::decode(reinterpret_cast<std::uintptr_t>(data[i].pCheckpointMarker));
1051 if (!top.submission || !(static_cast<std::uint64_t>(data[i].stage) & VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT))
1052 continue;
1053 std::uint32_t from = 0; // no bottom-of-pipe checkpoint in this list: from its start
1054 for (std::uint32_t j = 0; j < count; ++j) {
1055 const auto bottom = CheckpointMarker::decode(reinterpret_cast<std::uintptr_t>(data[j].pCheckpointMarker));
1056 if (bottom.submission == top.submission && bottom.list == top.list &&
1057 (static_cast<std::uint64_t>(data[j].stage) & VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT))
1058 from = bottom.command;
1059 }
1060 const auto& entry = recent_[top.submission % recent_.size()];
1061 if (entry.sequence != top.submission || entry.queue != queue || top.list >= entry.lists.size()) continue;
1062 const auto& shaders = entry.lists[top.list].shaders;
1063 // The pipeline bound when `from` ran, then every change up to the top-of-pipe command.
1064 auto it = std::upper_bound(shaders.begin(), shaders.end(), from,
1065 [](auto command, const auto& change) { return command < change.command; });
1066 if (it != shaders.begin()) --it;
1067 for (; it != shaders.end() && it->command <= top.command; ++it)
1068 std::fprintf(stderr, "[rt] device-fault: in flight (submission %u list %u, commands %u..%u): command %u "
1069 "pipeline=0x%" PRIx64 " shaders=%s %s %s\n",
1070 top.submission, top.list, from, top.command, unsigned(it->command),
1071 pipeline_handle(it->pipeline.handle), it->pipeline.shaders[0] ? it->pipeline.shaders[0] : "-",
1072 it->pipeline.shaders[1] ? it->pipeline.shaders[1] : "-",
1073 it->pipeline.shaders[2] ? it->pipeline.shaders[2] : "-");
1074 }
458 } 1075 }
459 1076
460 template<typename Handle> 1077 template<typename Handle>
@@ -467,9 +1084,20 @@ private:
467 PFN_vkGetDeviceFaultInfoEXT vkGetDeviceFaultInfoEXT = nullptr; 1084 PFN_vkGetDeviceFaultInfoEXT vkGetDeviceFaultInfoEXT = nullptr;
468 PFN_vkCmdSetCheckpointNV vkCmdSetCheckpointNV = nullptr; 1085 PFN_vkCmdSetCheckpointNV vkCmdSetCheckpointNV = nullptr;
469 PFN_vkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNV = nullptr; 1086 PFN_vkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNV = nullptr;
1087 PFN_vkGetSemaphoreCounterValue vkGetSemaphoreCounterValue = nullptr;
1088 const SubmitMutex* submit_lock_ = nullptr;
1089 std::array<SubmitRecord, 96> submits_{}; // under mutex_
1090 std::size_t submit_count_ = 0;
1091 unsigned stack_reports_ = 0; // report_submit_lock_holder: the progress watch's thread only
1092 std::int64_t last_stack_report_ms_ = 0;
1093 VkSemaphore stalled_progress_ = VK_NULL_HANDLE; // under read_mutex_
1094 std::uint64_t stalled_ticket_ = 0;
470 std::atomic<bool> reported_{false}; 1095 std::atomic<bool> reported_{false};
471 std::atomic<std::uint64_t> execute_calls_{0}; 1096 std::atomic<std::uint64_t> execute_calls_{0};
472 std::uint32_t sequence_ = 0; 1097 std::uint32_t sequence_ = 0;
1098 // Held while a report reads the counters of the semaphores in the ring, and by forget before one is destroyed.
1099 // Before mutex_; the submit path never takes it.
1100 std::mutex read_mutex_;
473 std::mutex mutex_; // leaf lock, guards queues_ and recent_ 1101 std::mutex mutex_; // leaf lock, guards queues_ and recent_
474 std::vector<VkQueue> queues_; 1102 std::vector<VkQueue> queues_;
475 const bool include_roots_ = [] { 1103 const bool include_roots_ = [] {
@@ -478,6 +1106,9 @@ private:
478 }(); 1106 }();
479 std::array<CheckpointDispatch, CheckpointSubmission::dispatch_limit> dispatches_{}; 1107 std::array<CheckpointDispatch, CheckpointSubmission::dispatch_limit> dispatches_{};
480 std::size_t dispatch_count_ = 0; 1108 std::size_t dispatch_count_ = 0;
1109 std::atomic<std::uint64_t> dispatch_seq_{0}; // the last seq handed out (CheckpointRecorder::dispatch)
1110 std::unique_ptr<DeviceMarkers> markers_; // LEONIDA_DEVICE_MARKERS=1 on a device with VK_AMD_buffer_marker
1111 std::unique_ptr<MarkerHistory> history_; // with markers_, under mutex_
481 std::array<CheckpointSubmission, 64> recent_; 1112 std::array<CheckpointSubmission, 64> recent_;
482}; 1113};
483 1114
diff --git a/runtime/src/vulkan_device_markers.h b/runtime/src/vulkan_device_markers.h
new file mode 100644
index 000000000..fea7e578b
--- /dev/null
+++ b/runtime/src/vulkan_device_markers.h
@@ -0,0 +1,245 @@
1#pragma once
2
3// LEONIDA_DEVICE_MARKERS=1 (diagnostic, with LEONIDA_DEVICE_FAULT=1 or 2): AMD breadcrumbs for the device-fault report
4// (vulkan_device_fault.h). On a device with VK_AMD_buffer_marker every dispatch the report numbers writes its `seq`
5// into its queue's slot of one small host-visible buffer twice: at top of pipe before the dispatch (started) and at
6// bottom of pipe after it (finished). A bottom-of-pipe write waits for all earlier work of the queue, so the finished
7// word is the last dispatch before which everything had completed; the dispatches after it up to the started word
8// are the ones the GPU had begun and not finished. On a loss or a stall report the slots are read back and the oldest
9// started, unfinished dispatch of a queue is reported as the likely hang. NVIDIA checkpoints do this on NVIDIA; RADV
10// has none. The buffer lives in system memory, so the last values usually survive a ring reset, but they are only
11// what the GPU wrote before it stopped: best-effort after a loss.
12
13#include <vulkan/vulkan.h>
14
15#include <array>
16#include <cstddef>
17#include <cstdint>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <span>
22#include <vector>
23
24namespace leonida {
25
26inline bool device_markers_requested() {
27 static const bool on = [] {
28 const char* value = std::getenv("LEONIDA_DEVICE_MARKERS");
29 return value && !std::strcmp(value, "1");
30 }();
31 return on;
32}
33
34// One queue's slot as the GPU writes it: the low 32 bits of the seq of the last dispatch whose top-of-pipe write ran
35// (started) and of the last whose bottom-of-pipe write ran (finished). 0 is no dispatch yet; seqs start at 1.
36struct MarkerSlot {
37 std::uint32_t started = 0;
38 std::uint32_t finished = 0;
39};
40
41// `seq` comes after the 32-bit marker value `marker` (serial-number arithmetic, so a wrap past 2^32 still orders the
42// recent dispatches the history holds).
43constexpr bool marker_after(std::uint64_t seq, std::uint32_t marker) {
44 return static_cast<std::int32_t>(static_cast<std::uint32_t>(seq) - marker) > 0;
45}
46
47// What the marker history keeps of each recorded dispatch: enough to name one that left the report's 64-entry list.
48struct MarkedDispatch {
49 std::uint64_t seq = 0;
50 std::uint64_t execute_call = 0;
51 VkQueue queue = VK_NULL_HANDLE;
52 const char* queue_kind = nullptr;
53 std::uint32_t list = 0;
54 std::uint32_t command = 0;
55 const char* shader = nullptr; // ShaderLibrary name, valid until device teardown
56};
57
58// The recent dispatches of every queue, oldest first once read. Allocated once, when the markers are on.
59class MarkerHistory {
60public:
61 static constexpr std::size_t capacity = 16384;
62
63 MarkerHistory() : entries_(capacity) {}
64
65 void push(const MarkedDispatch& d) { entries_[count_++ % capacity] = d; }
66
67 std::size_t size() const { return count_ < capacity ? count_ : capacity; }
68
69 template<typename Visit>
70 void for_each(Visit&& visit) const { // oldest first
71 for (std::size_t i = count_ - size(); i < count_; ++i) visit(entries_[i % capacity]);
72 }
73
74private:
75 std::vector<MarkedDispatch> entries_;
76 std::size_t count_ = 0;
77};
78
79// What one queue's slot says, judged against the history (MarkerHistory::for_each order).
80struct MarkerQueueReport {
81 MarkerSlot slot;
82 const char* queue_kind = nullptr; // from the history, null when it holds no dispatch of the queue
83 std::vector<std::uint64_t> unfinished; // seqs of this queue in (finished, started], oldest first
84 std::uint64_t likely_hang = 0; // the oldest of them; 0 when none was started and not finished
85 std::uint64_t next_queued = 0; // idle queue: the oldest submitted dispatch after `finished`, not started yet
86 bool missing = false; // started > finished but the history no longer holds any of them
87
88 bool idle() const { return slot.started == slot.finished; }
89};
90
91template<typename History>
92MarkerQueueReport judge_markers(VkQueue queue, MarkerSlot slot, const History& history) {
93 MarkerQueueReport report;
94 // The started word is written before the finished word of the same dispatch and both only rise, so started is
95 // never behind; a value that says otherwise (memory lost in a reset) is read as an idle queue.
96 if (slot.started != slot.finished && !marker_after(slot.started, slot.finished)) slot.started = slot.finished;
97 report.slot = slot;
98 history.for_each([&](const MarkedDispatch& d) {
99 if (d.queue != queue) return;
100 if (!report.queue_kind) report.queue_kind = d.queue_kind;
101 if (!marker_after(d.seq, slot.finished)) return;
102 if (!marker_after(d.seq, slot.started)) report.unfinished.push_back(d.seq);
103 else if (!report.next_queued) report.next_queued = d.seq;
104 });
105 if (!report.unfinished.empty()) report.likely_hang = report.unfinished.front();
106 report.missing = !report.idle() && report.unfinished.empty();
107 if (!report.idle()) report.next_queued = 0; // only said of an idle queue
108 return report;
109}
110
111// Where the recorder writes one queue's markers. Empty (no buffer) when the markers are off.
112struct MarkerTarget {
113 PFN_vkCmdWriteBufferMarkerAMD write = nullptr;
114 PFN_vkCmdWriteBufferMarker2AMD write2 = nullptr; // with synchronization2
115 VkBuffer buffer = VK_NULL_HANDLE;
116 VkDeviceSize offset = 0; // the slot: started at +0, finished at +4
117
118 explicit operator bool() const { return buffer != VK_NULL_HANDLE; }
119
120 void started(VkCommandBuffer command_buffer, std::uint64_t seq) const {
121 if (write2)
122 write2(command_buffer, VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT, buffer, offset, std::uint32_t(seq));
123 else
124 write(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, buffer, offset, std::uint32_t(seq));
125 }
126 void finished(VkCommandBuffer command_buffer, std::uint64_t seq) const {
127 if (write2)
128 write2(command_buffer, VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT, buffer, offset + 4, std::uint32_t(seq));
129 else
130 write(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, buffer, offset + 4, std::uint32_t(seq));
131 }
132};
133
134// The persistent marker buffer: one 8-byte slot per queue, in host-visible, host-coherent memory that stays mapped.
135class DeviceMarkers {
136public:
137 static constexpr std::uint32_t max_queues = 64;
138
139 DeviceMarkers() = default;
140 DeviceMarkers(const DeviceMarkers&) = delete;
141 DeviceMarkers& operator=(const DeviceMarkers&) = delete;
142 ~DeviceMarkers() {
143 if (memory_ && unmap_) unmap_(device_, memory_);
144 if (buffer_ && destroy_buffer_) destroy_buffer_(device_, buffer_, nullptr);
145 if (memory_ && free_memory_) free_memory_(device_, memory_, nullptr);
146 }
147
148 // Returns the VkResult of the step that failed, or VK_SUCCESS.
149 VkResult create(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory,
150 bool synchronization2) {
151 device_ = device;
152#define LEONIDA_MARKER_LOAD(type, name) const auto name = reinterpret_cast<type>(get(device, #name))
153 LEONIDA_MARKER_LOAD(PFN_vkCreateBuffer, vkCreateBuffer);
154 LEONIDA_MARKER_LOAD(PFN_vkGetBufferMemoryRequirements, vkGetBufferMemoryRequirements);
155 LEONIDA_MARKER_LOAD(PFN_vkAllocateMemory, vkAllocateMemory);
156 LEONIDA_MARKER_LOAD(PFN_vkBindBufferMemory, vkBindBufferMemory);
157 LEONIDA_MARKER_LOAD(PFN_vkMapMemory, vkMapMemory);
158 LEONIDA_MARKER_LOAD(PFN_vkCmdWriteBufferMarkerAMD, vkCmdWriteBufferMarkerAMD);
159 LEONIDA_MARKER_LOAD(PFN_vkCmdWriteBufferMarker2AMD, vkCmdWriteBufferMarker2AMD);
160#undef LEONIDA_MARKER_LOAD
161 destroy_buffer_ = reinterpret_cast<PFN_vkDestroyBuffer>(get(device, "vkDestroyBuffer"));
162 free_memory_ = reinterpret_cast<PFN_vkFreeMemory>(get(device, "vkFreeMemory"));
163 unmap_ = reinterpret_cast<PFN_vkUnmapMemory>(get(device, "vkUnmapMemory"));
164 if (!vkCreateBuffer || !vkGetBufferMemoryRequirements || !vkAllocateMemory || !vkBindBufferMemory ||
165 !vkMapMemory || !destroy_buffer_ || !free_memory_ || !vkCmdWriteBufferMarkerAMD)
166 return VK_ERROR_EXTENSION_NOT_PRESENT;
167 write_ = vkCmdWriteBufferMarkerAMD;
168 write2_ = synchronization2 ? vkCmdWriteBufferMarker2AMD : nullptr;
169 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
170 info.size = VkDeviceSize{8} * max_queues;
171 info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
172 info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; // written by every queue, never read on the GPU
173 VkResult result = vkCreateBuffer(device, &info, nullptr, &buffer_);
174 if (result != VK_SUCCESS) return result;
175 VkMemoryRequirements requirements{};
176 vkGetBufferMemoryRequirements(device, buffer_, &requirements);
177 const std::uint32_t type = memory_type(memory, requirements.memoryTypeBits);
178 if (type == UINT32_MAX) return VK_ERROR_OUT_OF_HOST_MEMORY;
179 VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
180 allocate.allocationSize = requirements.size;
181 allocate.memoryTypeIndex = type;
182 if ((result = vkAllocateMemory(device, &allocate, nullptr, &memory_)) != VK_SUCCESS) return result;
183 if ((result = vkBindBufferMemory(device, buffer_, memory_, 0)) != VK_SUCCESS) return result;
184 void* mapped = nullptr;
185 if ((result = vkMapMemory(device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped)) != VK_SUCCESS) return result;
186 std::memset(mapped, 0, std::size_t(info.size));
187 words_ = static_cast<volatile std::uint32_t*>(mapped);
188 return VK_SUCCESS;
189 }
190
191 bool ready() const { return words_ != nullptr; }
192 bool synchronization2() const { return write2_ != nullptr; }
193
194 // The queue's slot, assigned on first use; false past max_queues.
195 bool add_queue(VkQueue queue) {
196 if (!ready() || !queue) return false;
197 for (std::uint32_t i = 0; i < count_; ++i)
198 if (queues_[i] == queue) return true;
199 if (count_ == max_queues) return false;
200 queues_[count_++] = queue;
201 return true;
202 }
203
204 MarkerTarget target(VkQueue queue) const {
205 for (std::uint32_t i = 0; i < count_; ++i)
206 if (queues_[i] == queue) return {write_, write2_, buffer_, VkDeviceSize{8} * i};
207 return {};
208 }
209
210 std::span<const VkQueue> queues() const { return {queues_.data(), count_}; }
211
212 MarkerSlot read(VkQueue queue) const {
213 for (std::uint32_t i = 0; i < count_; ++i)
214 if (queues_[i] == queue) return {words_[2 * i], words_[2 * i + 1]};
215 return {};
216 }
217
218 // Host-visible and coherent, not device-local if there is such a type: system memory outlives a VRAM reset.
219 static std::uint32_t memory_type(const VkPhysicalDeviceMemoryProperties& memory, std::uint32_t allowed) {
220 constexpr VkMemoryPropertyFlags need = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
221 std::uint32_t fallback = UINT32_MAX;
222 for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) {
223 const VkMemoryPropertyFlags flags = memory.memoryTypes[i].propertyFlags;
224 if (!(allowed & (1u << i)) || (flags & need) != need) continue;
225 if (!(flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) return i;
226 if (fallback == UINT32_MAX) fallback = i;
227 }
228 return fallback;
229 }
230
231private:
232 VkDevice device_ = VK_NULL_HANDLE;
233 PFN_vkDestroyBuffer destroy_buffer_ = nullptr;
234 PFN_vkFreeMemory free_memory_ = nullptr;
235 PFN_vkUnmapMemory unmap_ = nullptr;
236 PFN_vkCmdWriteBufferMarkerAMD write_ = nullptr;
237 PFN_vkCmdWriteBufferMarker2AMD write2_ = nullptr;
238 VkBuffer buffer_ = VK_NULL_HANDLE;
239 VkDeviceMemory memory_ = VK_NULL_HANDLE;
240 volatile std::uint32_t* words_ = nullptr;
241 std::array<VkQueue, max_queues> queues_{};
242 std::uint32_t count_ = 0;
243};
244
245} // namespace leonida
diff --git a/runtime/src/vulkan_indirect_clamp.h b/runtime/src/vulkan_indirect_clamp.h
index e510e3b0c..1822d9614 100644
--- a/runtime/src/vulkan_indirect_clamp.h
+++ b/runtime/src/vulkan_indirect_clamp.h
@@ -37,6 +37,7 @@
37#include <algorithm> 37#include <algorithm>
38#include <cstdint> 38#include <cstdint>
39#include <cstdio> 39#include <cstdio>
40#include <chrono>
40#include <cstdlib> 41#include <cstdlib>
41#include <cstring> 42#include <cstring>
42#include <memory> 43#include <memory>
@@ -135,7 +136,8 @@ public:
135 136
136 IndirectArgumentClamp(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, 137 IndirectArgumentClamp(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory,
137 const VkPhysicalDeviceLimits& limits, Allocate allocate, 138 const VkPhysicalDeviceLimits& limits, Allocate allocate,
138 DeviceFaultDiagnostics* diagnostics = nullptr); 139 DeviceFaultDiagnostics* diagnostics = nullptr,
140 std::vector<std::uint32_t> families = {});
139 ~IndirectArgumentClamp(); 141 ~IndirectArgumentClamp();
140 IndirectArgumentClamp(const IndirectArgumentClamp&) = delete; 142 IndirectArgumentClamp(const IndirectArgumentClamp&) = delete;
141 IndirectArgumentClamp& operator=(const IndirectArgumentClamp&) = delete; 143 IndirectArgumentClamp& operator=(const IndirectArgumentClamp&) = delete;
@@ -160,6 +162,11 @@ public:
160 std::uint64_t zeroed = 0; 162 std::uint64_t zeroed = 0;
161 std::uint64_t unclamped_calls = 0; // the fallbacks: calls the pool or the limits left to the replay 163 std::uint64_t unclamped_calls = 0; // the fallbacks: calls the pool or the limits left to the replay
162 std::uint64_t uncounted_calls = 0; // clamped with no counter slot free: their counters are not read back 164 std::uint64_t uncounted_calls = 0; // clamped with no counter slot free: their counters are not read back
165 // Mesh records before the clamp: all active ones, those with y > 1 or z > 1, and the largest y and z asked.
166 std::uint64_t mesh_records = 0;
167 std::uint64_t mesh_yz_records = 0;
168 std::uint32_t mesh_max_y = 0;
169 std::uint32_t mesh_max_z = 0;
163 }; 170 };
164 171
165 // One submission's clamp state: the counter slots its calls claimed, read and released together once that 172 // One submission's clamp state: the counter slots its calls claimed, read and released together once that
@@ -189,7 +196,14 @@ public:
189 if (counted) owner_.release_one(slot); 196 if (counted) owner_.release_one(slot);
190 return false; 197 return false;
191 } 198 }
192 if (counted) slots_.push_back(slot); 199 if (counted) {
200 try {
201 slots_.push_back(slot);
202 } catch (...) {
203 owner_.release_one(slot);
204 throw;
205 }
206 }
193 return true; 207 return true;
194 } 208 }
195 209
@@ -218,7 +232,7 @@ private:
218 VkDeviceMemory memory = VK_NULL_HANDLE; 232 VkDeviceMemory memory = VK_NULL_HANDLE;
219 std::uint8_t* host = nullptr; 233 std::uint8_t* host = nullptr;
220 std::uint32_t slots = 0; 234 std::uint32_t slots = 0;
221 static constexpr std::uint32_t slot_bytes = 32; // 16 bytes of counters, 16 of padding 235 static constexpr std::uint32_t slot_bytes = 64; // 48 bytes of counters (words 4-7 unused), 16 of padding
222 }; 236 };
223 static constexpr std::uint32_t slots_per_area = 64; 237 static constexpr std::uint32_t slots_per_area = 64;
224 // 4,096 slots (128 KiB of host memory): enough for a submission's ExecuteIndirect calls after the load, and the 238 // 4,096 slots (128 KiB of host memory): enough for a submission's ExecuteIndirect calls after the load, and the
@@ -240,7 +254,7 @@ private:
240 VkDevice device_; 254 VkDevice device_;
241 VkPhysicalDeviceMemoryProperties memory_{}; 255 VkPhysicalDeviceMemoryProperties memory_{};
242 VkPhysicalDeviceLimits limits_{}; 256 VkPhysicalDeviceLimits limits_{};
243 DeviceFaultDiagnostics* diagnostics_ = nullptr; 257 std::vector<std::uint32_t> families_;
244 ScratchBuffers scratch_; 258 ScratchBuffers scratch_;
245 VkPipelineLayout layout_ = VK_NULL_HANDLE; 259 VkPipelineLayout layout_ = VK_NULL_HANDLE;
246 VkPipeline pipeline_ = VK_NULL_HANDLE; 260 VkPipeline pipeline_ = VK_NULL_HANDLE;
@@ -250,6 +264,7 @@ private:
250 std::vector<Slot> free_slots_; 264 std::vector<Slot> free_slots_;
251 Counters counters_{}; 265 Counters counters_{};
252 std::uint64_t next_report_frame_ = 0; 266 std::uint64_t next_report_frame_ = 0;
267 std::chrono::steady_clock::time_point next_mesh_report_{};
253}; 268};
254 269
255namespace detail { 270namespace detail {
@@ -281,9 +296,10 @@ inline constexpr VkBufferUsageFlags indirect_clamp_scratch_usage =
281inline IndirectArgumentClamp::IndirectArgumentClamp(PFN_vkGetDeviceProcAddr get, VkDevice device, 296inline IndirectArgumentClamp::IndirectArgumentClamp(PFN_vkGetDeviceProcAddr get, VkDevice device,
282 const VkPhysicalDeviceMemoryProperties& memory, 297 const VkPhysicalDeviceMemoryProperties& memory,
283 const VkPhysicalDeviceLimits& limits, Allocate allocate, 298 const VkPhysicalDeviceLimits& limits, Allocate allocate,
284 DeviceFaultDiagnostics* diagnostics) 299 DeviceFaultDiagnostics* diagnostics,
285 : get_(get), device_(device), memory_(memory), limits_(limits), diagnostics_(diagnostics), 300 std::vector<std::uint32_t> families)
286 scratch_(get, device, std::move(allocate), diagnostics, detail::indirect_clamp_scratch_usage) {} 301 : get_(get), device_(device), memory_(memory), limits_(limits), families_(std::move(families)),
302 scratch_(get, device, std::move(allocate), diagnostics, detail::indirect_clamp_scratch_usage, families_) {}
287 303
288inline IndirectArgumentClamp::~IndirectArgumentClamp() { 304inline IndirectArgumentClamp::~IndirectArgumentClamp() {
289 const auto destroy_pipeline = fn<PFN_vkDestroyPipeline>("vkDestroyPipeline"); 305 const auto destroy_pipeline = fn<PFN_vkDestroyPipeline>("vkDestroyPipeline");
@@ -354,7 +370,17 @@ inline bool IndirectArgumentClamp::make_area() {
354 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 370 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
355 info.size = VkDeviceSize(area.slots) * HostArea::slot_bytes; 371 info.size = VkDeviceSize(area.slots) * HostArea::slot_bytes;
356 info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; 372 info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
373 // Direct and async-compute queues copy counter slots into the same HostArea buffer concurrently.
374 share_across_queue_families(info, families_);
357 if (create_buffer(device_, &info, nullptr, &area.buffer) != VK_SUCCESS) return false; 375 if (create_buffer(device_, &info, nullptr, &area.buffer) != VK_SUCCESS) return false;
376 const auto destroy_buffer = fn<PFN_vkDestroyBuffer>("vkDestroyBuffer");
377 const auto free_memory = fn<PFN_vkFreeMemory>("vkFreeMemory");
378 const auto cleanup = [&] {
379 if (area.buffer && destroy_buffer) destroy_buffer(device_, area.buffer, nullptr);
380 if (area.memory && free_memory) free_memory(device_, area.memory, nullptr);
381 area.buffer = VK_NULL_HANDLE;
382 area.memory = VK_NULL_HANDLE;
383 };
358 VkMemoryRequirements requirements{}; 384 VkMemoryRequirements requirements{};
359 requirements_fn(device_, area.buffer, &requirements); 385 requirements_fn(device_, area.buffer, &requirements);
360 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; 386 VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
@@ -371,16 +397,23 @@ inline bool IndirectArgumentClamp::make_area() {
371 } 397 }
372 bound = bind_fn(device_, area.buffer, area.memory, 0) == VK_SUCCESS; 398 bound = bind_fn(device_, area.buffer, area.memory, 0) == VK_SUCCESS;
373 if (bound) break; 399 if (bound) break;
400 if (free_memory) free_memory(device_, area.memory, nullptr);
401 area.memory = VK_NULL_HANDLE;
374 } 402 }
375 if (!bound || map_fn(device_, area.memory, 0, info.size, 0, reinterpret_cast<void**>(&area.host)) != VK_SUCCESS) { 403 if (!bound || map_fn(device_, area.memory, 0, info.size, 0, reinterpret_cast<void**>(&area.host)) != VK_SUCCESS) {
376 const auto destroy_buffer = fn<PFN_vkDestroyBuffer>("vkDestroyBuffer"); 404 cleanup();
377 const auto free_memory = fn<PFN_vkFreeMemory>("vkFreeMemory");
378 if (area.buffer && destroy_buffer) destroy_buffer(device_, area.buffer, nullptr);
379 if (area.memory && free_memory) free_memory(device_, area.memory, nullptr);
380 return false; 405 return false;
381 } 406 }
382 std::memset(area.host, 0, size_t(info.size)); 407 std::memset(area.host, 0, size_t(info.size));
383 for (std::uint32_t i = 0; i < area.slots; ++i) free_slots_.push_back({std::uint32_t(areas_.size()), i}); 408 try {
409 free_slots_.reserve(free_slots_.size() + area.slots);
410 areas_.reserve(areas_.size() + 1);
411 } catch (...) {
412 cleanup();
413 throw;
414 }
415 const auto area_index = std::uint32_t(areas_.size());
416 for (std::uint32_t i = 0; i < area.slots; ++i) free_slots_.push_back({area_index, i});
384 areas_.push_back(area); 417 areas_.push_back(area);
385 return true; 418 return true;
386} 419}
@@ -408,12 +441,19 @@ inline void IndirectArgumentClamp::release(std::vector<Slot>& slots, bool read)
408 for (const Slot& slot : slots) { 441 for (const Slot& slot : slots) {
409 if (read && slot.area < areas_.size() && slot.index < areas_[slot.area].slots) { 442 if (read && slot.area < areas_.size() && slot.index < areas_[slot.area].slots) {
410 const HostArea& area = areas_[slot.area]; 443 const HostArea& area = areas_[slot.area];
411 const std::uint32_t* words = 444 auto* words =
412 reinterpret_cast<const std::uint32_t*>(area.host + std::size_t(slot.index) * HostArea::slot_bytes); 445 reinterpret_cast<std::uint32_t*>(area.host + std::size_t(slot.index) * HostArea::slot_bytes);
413 delta.records_clamped += words[0]; 446 delta.records_clamped += words[0];
414 delta.counts_clamped += words[1]; 447 delta.counts_clamped += words[1];
415 delta.over_budget += words[2]; 448 delta.over_budget += words[2];
416 delta.zeroed += words[3]; 449 delta.zeroed += words[3];
450 delta.mesh_records += words[8];
451 delta.mesh_yz_records += words[9];
452 delta.mesh_max_y = std::max(delta.mesh_max_y, words[10]);
453 delta.mesh_max_z = std::max(delta.mesh_max_z, words[11]);
454 // Clear after reading so a later aborted batch that reuses this slot without submitting never
455 // double-counts a previous submission's counters.
456 std::memset(words, 0, HostArea::slot_bytes);
417 } 457 }
418 free_slots_.push_back(slot); 458 free_slots_.push_back(slot);
419 } 459 }
@@ -421,6 +461,20 @@ inline void IndirectArgumentClamp::release(std::vector<Slot>& slots, bool read)
421 counters_.counts_clamped += delta.counts_clamped; 461 counters_.counts_clamped += delta.counts_clamped;
422 counters_.over_budget += delta.over_budget; 462 counters_.over_budget += delta.over_budget;
423 counters_.zeroed += delta.zeroed; 463 counters_.zeroed += delta.zeroed;
464 counters_.mesh_records += delta.mesh_records;
465 counters_.mesh_yz_records += delta.mesh_yz_records;
466 counters_.mesh_max_y = std::max(counters_.mesh_max_y, delta.mesh_max_y);
467 counters_.mesh_max_z = std::max(counters_.mesh_max_z, delta.mesh_max_z);
468 // One line every 10 s while mesh records are clamped: does the console's mesh dispatch use y or z?
469 const auto now = std::chrono::steady_clock::now();
470 if (read && counters_.mesh_records && now >= next_mesh_report_) {
471 next_mesh_report_ = now + std::chrono::seconds(10);
472 std::fprintf(stderr, "[rt] indirect clamp mesh: %llu records, %llu with y > 1 or z > 1 (forced to 1), "
473 "max y %u, max z %u\n",
474 static_cast<unsigned long long>(counters_.mesh_records),
475 static_cast<unsigned long long>(counters_.mesh_yz_records), counters_.mesh_max_y,
476 counters_.mesh_max_z);
477 }
424 const auto frame = submit_phases::totals().present_serial.load(std::memory_order_relaxed); 478 const auto frame = submit_phases::totals().present_serial.load(std::memory_order_relaxed);
425 if (read && calls && frame >= next_report_frame_) { 479 if (read && calls && frame >= next_report_frame_) {
426 next_report_frame_ = frame + 60; 480 next_report_frame_ = frame + 60;
@@ -461,8 +515,9 @@ inline bool IndirectArgumentClamp::prepare(VkBuffer arguments, VkDeviceSize argu
461 std::uint32_t max_count, Slot slot, ClampedIndirect& out) { 515 std::uint32_t max_count, Slot slot, ClampedIndirect& out) {
462 out = {}; 516 out = {};
463 const std::uint32_t record_size = indirect_clamp_record_size(kind); 517 const std::uint32_t record_size = indirect_clamp_record_size(kind);
464 if (kind > indirect_clamp_mesh || !arguments || !max_count || stride < record_size || stride % 4) { 518 if (kind > indirect_clamp_mesh || !arguments || !max_count || stride < record_size || stride % 4 ||
465 fallback("an argument stride this pass does not handle"); 519 (argument_offset % 4) != 0 || (count && (count_offset % 4) != 0)) {
520 fallback("an argument stride or offset this pass does not handle");
466 return false; 521 return false;
467 } 522 }
468 const VkDeviceSize records_bytes = VkDeviceSize(max_count) * record_size; 523 const VkDeviceSize records_bytes = VkDeviceSize(max_count) * record_size;
@@ -514,10 +569,10 @@ inline bool IndirectArgumentClamp::prepare(VkBuffer arguments, VkDeviceSize argu
514 out.stats = address + stats_scratch; 569 out.stats = address + stats_scratch;
515 out.list_budget = out.stats + 4 * sizeof(std::uint32_t); 570 out.list_budget = out.stats + 4 * sizeof(std::uint32_t);
516 out.stats_scratch_offset = offset + stats_scratch; 571 out.stats_scratch_offset = offset + stats_scratch;
517 out.stats_buffer = slot.area == no_slot ? VK_NULL_HANDLE : areas_[slot.area].buffer; // no_slot: no copy-back
518 out.stats_offset = slot.area == no_slot ? 0 : VkDeviceSize(slot.index) * HostArea::slot_bytes; 572 out.stats_offset = slot.area == no_slot ? 0 : VkDeviceSize(slot.index) * HostArea::slot_bytes;
519 { 573 {
520 std::lock_guard lock(mutex_); 574 std::lock_guard lock(mutex_);
575 out.stats_buffer = slot.area == no_slot ? VK_NULL_HANDLE : areas_[slot.area].buffer; // no_slot: no copy-back
521 ++counters_.calls; 576 ++counters_.calls;
522 counters_.records += max_count; 577 counters_.records += max_count;
523 } 578 }
@@ -532,6 +587,7 @@ inline void IndirectArgumentClamp::emit(VkCommandBuffer cb, const ClampedIndirec
532 // The counters start at zero: the budget's compare-and-swap and the record counts accumulate into them. A 587 // The counters start at zero: the budget's compare-and-swap and the record counts accumulate into them. A
533 // transfer write, ordered to the compute stage by the barrier below, like the arguments' own writes. 588 // transfer write, ordered to the compute stage by the barrier below, like the arguments' own writes.
534 fn<PFN_vkCmdFillBuffer>("vkCmdFillBuffer")(cb, job.buffer, job.stats_scratch_offset, job.list_budget == job.stats + 16 ? 20 : 16, 0); 589 fn<PFN_vkCmdFillBuffer>("vkCmdFillBuffer")(cb, job.buffer, job.stats_scratch_offset, job.list_budget == job.stats + 16 ? 20 : 16, 0);
590 fn<PFN_vkCmdFillBuffer>("vkCmdFillBuffer")(cb, job.buffer, job.stats_scratch_offset + 32, 16, 0); // mesh words 8-11
535 VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; 591 VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
536 before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; // every earlier write: the compute that wrote these arguments 592 before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; // every earlier write: the compute that wrote these arguments
537 before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; 593 before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
@@ -570,7 +626,7 @@ inline void IndirectArgumentClamp::emit(VkCommandBuffer cb, const ClampedIndirec
570 after_copy.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; 626 after_copy.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
571 barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &after_copy, 0, nullptr, 627 barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &after_copy, 0, nullptr,
572 0, nullptr); 628 0, nullptr);
573 VkBufferCopy copy{job.stats_scratch_offset, job.stats_offset, 4 * sizeof(std::uint32_t)}; 629 VkBufferCopy copy{job.stats_scratch_offset, job.stats_offset, 12 * sizeof(std::uint32_t)};
574 fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer")(cb, job.buffer, job.stats_buffer, 1, &copy); 630 fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer")(cb, job.buffer, job.stats_buffer, 1, &copy);
575 } 631 }
576 // The indirect command reads the records, and nothing else may read them while it does. 632 // The indirect command reads the records, and nothing else may read them while it does.
diff --git a/runtime/src/vulkan_memory_budget.h b/runtime/src/vulkan_memory_budget.h
new file mode 100644
index 000000000..e9bc549b1
--- /dev/null
+++ b/runtime/src/vulkan_memory_budget.h
@@ -0,0 +1,46 @@
1#pragma once
2
3// VK_EXT_memory_budget: how much GPU memory this process uses and may use, read from the Vulkan device itself. The
4// device publishes it (memory_figures.h) for the title HUD (shims/title_hud.h, LEONIDA_TITLE_HUD) and the dev overlay
5// (dev_overlay.h, LEONIDA_DEV_OVERLAY); DXGI's QueryVideoMemoryInfo, which the HUD read before, is 0 under Wine. The
6// sums depend only on the two Vulkan structures, so a test can feed them made-up heaps.
7
8#ifndef VK_NO_PROTOTYPES
9#define VK_NO_PROTOTYPES
10#endif
11#include <vulkan/vulkan.h>
12
13#include <cstdint>
14
15#include "memory_figures.h" // VramBudget
16
17namespace leonida {
18
19inline VramBudget sum_vram_budget(const VkPhysicalDeviceMemoryProperties& memory,
20 const VkPhysicalDeviceMemoryBudgetPropertiesEXT& budget) {
21 VramBudget out;
22 for (std::uint32_t i = 0; i < memory.memoryHeapCount && i < VK_MAX_MEMORY_HEAPS; ++i) {
23 if (memory.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
24 out.local_usage += budget.heapUsage[i];
25 out.local_budget += budget.heapBudget[i];
26 } else {
27 out.shared_usage += budget.heapUsage[i];
28 }
29 }
30 out.available = out.local_budget != 0;
31 return out;
32}
33
34// Reads the budget now. `physical` must have VK_EXT_memory_budget (enabled on the logical device, as the runtime's
35// device does). One vkGetPhysicalDeviceMemoryProperties2 call, which needs no external synchronization, so another
36// thread (the HUD's or the overlay's) may call it while the device is in use.
37inline VramBudget query_vram_budget(PFN_vkGetPhysicalDeviceMemoryProperties2 get_memory_properties2,
38 VkPhysicalDevice physical) {
39 if (!get_memory_properties2 || physical == VK_NULL_HANDLE) return {};
40 VkPhysicalDeviceMemoryBudgetPropertiesEXT budget{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT};
41 VkPhysicalDeviceMemoryProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2, &budget};
42 get_memory_properties2(physical, &properties);
43 return sum_vram_budget(properties.memoryProperties, budget);
44}
45
46} // namespace leonida
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index d494233d3..81f3b57e1 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -183,7 +183,7 @@ public:
183 std::error_code created; 183 std::error_code created;
184 std::filesystem::create_directories(capture_dir_, created); 184 std::filesystem::create_directories(capture_dir_, created);
185 capture_to_disk_ = true; 185 capture_to_disk_ = true;
186 capture_ = true; // the swapchain needs TRANSFER_SRC, and every frame copies into a staging buffer 186 capture_ = true; // provision TRANSFER_SRC and staging; disk-only copies follow the requested cadence
187 if (const char* every = std::getenv("LEONIDA_CAPTURE_EVERY")) capture_every_ = std::max(1, std::atoi(every)); 187 if (const char* every = std::getenv("LEONIDA_CAPTURE_EVERY")) capture_every_ = std::max(1, std::atoi(every));
188 if (const char* limit = std::getenv("LEONIDA_CAPTURE_LIMIT")) capture_limit_ = std::max(1, std::atoi(limit)); 188 if (const char* limit = std::getenv("LEONIDA_CAPTURE_LIMIT")) capture_limit_ = std::max(1, std::atoi(limit));
189 std::fprintf(stderr, "[rt] present: capture on: every %d presented frame(s), at most %d, into %s\n", 189 std::fprintf(stderr, "[rt] present: capture on: every %d presented frame(s), at most %d, into %s\n",
@@ -212,6 +212,7 @@ public:
212 const VkDevice device = context_.device(); 212 const VkDevice device = context_.device();
213 { 213 {
214 std::lock_guard lock(context_.submit_mutex()); 214 std::lock_guard lock(context_.submit_mutex());
215 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
215 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); 216 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
216 // A WSI layer may perform a device-wide idle while destroying the swapchain. 217 // A WSI layer may perform a device-wide idle while destroying the swapchain.
217 // Keep that implicit idle serialized with submits from every context queue. 218 // Keep that implicit idle serialized with submits from every context queue.
@@ -348,15 +349,9 @@ public:
348 // Call before the first present. 349 // Call before the first present.
349 bool enable_capture() { 350 bool enable_capture() {
350 std::lock_guard lock(present_mutex_); 351 std::lock_guard lock(present_mutex_);
351 if (!ok_) return false;
352 splash_capture_only_ = false; 352 splash_capture_only_ = false;
353 capture_ = true; 353 continuous_readback_ = enable_capture_storage();
354 stale_ = true; 354 return continuous_readback_;
355 if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) {
356 capture_ = false;
357 return false;
358 }
359 return true;
360 } 355 }
361 356
362 // Present the shell image immediately. Keep it on screen until the window has a non-black title frame. 357 // Present the shell image immediately. Keep it on screen until the window has a non-black title frame.
@@ -365,7 +360,7 @@ public:
365 // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order). 360 // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order).
366 // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present 361 // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present
367 // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next 362 // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next
368 // frame that is shown (the frame before it is not what the window was last asked to show), or when the wait fails. 363 // frame that is shown, on an unsampled disk-only present, or when the wait fails.
369 bool read_back(std::vector<std::uint8_t>& pixels, VkExtent2D* extent, VkFormat* format) { 364 bool read_back(std::vector<std::uint8_t>& pixels, VkExtent2D* extent, VkFormat* format) {
370 std::lock_guard lock(present_mutex_); 365 std::lock_guard lock(present_mutex_);
371 if (!capture_ || !capture_ptr_ || !captured_) return false; 366 if (!capture_ || !capture_ptr_ || !captured_) return false;
@@ -416,6 +411,19 @@ public:
416 } 411 }
417 412
418private: 413private:
414 // Called with present_mutex_ held. Reserving staging for the splash or rare disk samples
415 // is distinct from promising the caller a copy of every frame through read_back().
416 bool enable_capture_storage() {
417 if (!ok_) return false;
418 capture_ = true;
419 stale_ = true;
420 if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) {
421 capture_ = false;
422 return false;
423 }
424 return true;
425 }
426
419 bool should_abort() { 427 bool should_abort() {
420 std::function<bool()> abort; 428 std::function<bool()> abort;
421 { 429 {
@@ -507,14 +515,13 @@ private:
507 if ((binding || planes) && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT)) 515 if ((binding || planes) && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT))
508 return VK_ERROR_FORMAT_NOT_SUPPORTED; 516 return VK_ERROR_FORMAT_NOT_SUPPORTED;
509 if (planes && !prepare_compose()) return VK_ERROR_FORMAT_NOT_SUPPORTED; 517 if (planes && !prepare_compose()) return VK_ERROR_FORMAT_NOT_SUPPORTED;
510 auto& vk = context_.vk;
511 const VkDevice device = context_.device(); 518 const VkDevice device = context_.device();
512 Frame& frame = frames_[frame_index_ % frames_.size()]; 519 Frame& frame = frames_[frame_index_ % frames_.size()];
513 if (const VkResult waited = context_.observe_result( 520 if (const VkResult waited = context_.observe_result(
514 vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX), "vkWaitForFences (present)"); 521 vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX), "vkWaitForFences (present)");
515 waited != VK_SUCCESS) 522 waited != VK_SUCCESS)
516 return stop(waited); 523 return stop(waited);
517 // Every submit copies into the same mapped buffer, even if its frame is outside the disk capture stride. 524 // Drain the preceding disk sample before reusing its fence or advancing its metadata.
518 if (const VkResult r = finish_pending_capture(); r != VK_SUCCESS) return stop(r); 525 if (const VkResult r = finish_pending_capture(); r != VK_SUCCESS) return stop(r);
519 526
520 std::uint32_t image = 0; 527 std::uint32_t image = 0;
@@ -537,6 +544,15 @@ private:
537 // An out-of-date retry above may have given the swapchain another extent: the compose target follows it. 544 // An out-of-date retry above may have given the swapchain another extent: the compose target follows it.
538 if (planes && !prepare_compose()) return give_back(frame, VK_ERROR_FORMAT_NOT_SUPPORTED); 545 if (planes && !prepare_compose()) return give_back(frame, VK_ERROR_FORMAT_NOT_SUPPORTED);
539 546
547 // The ordinal counts accepted presents, not submissions or deferred requests. Decide after
548 // draining the previous disk sample and any acquire/recreate retry; an unshown attempt consumes no slot.
549 const bool disk_sample = capture_to_disk_ && capture_written_ < capture_limit_ &&
550 presented_ % std::uint64_t(capture_every_) == 0;
551 const bool inspect = splash_owner_ && capture_ptr_;
552 // Merely allocating a temporary splash buffer does not require a copy. In particular, a minimized
553 // initial splash can return before taking ownership; later ordinary frames must not become continuous.
554 const bool copy_frame = capture_buffer_ && ((capture_ && (disk_sample || continuous_readback_ || inspect)) || dump_.due(presented_));
555 captured_ = false; // never expose a stale sample after an unsampled or unshown frame
540 bool recorded = false; 556 bool recorded = false;
541 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); 557 std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock);
542 bool rollback_source = false; 558 bool rollback_source = false;
@@ -561,7 +577,8 @@ private:
561 plane_rollbacks[i].tracked = context_.tracker_.tracked(plane_rollbacks[i].id); 577 plane_rollbacks[i].tracked = context_.tracker_.tracked(plane_rollbacks[i].id);
562 if (plane_rollbacks[i].tracked) plane_rollbacks[i].layout = context_.tracker_.layout(plane_rollbacks[i].id, 0); 578 if (plane_rollbacks[i].tracked) plane_rollbacks[i].layout = context_.tracker_.layout(plane_rollbacks[i].id, 0);
563 } 579 }
564 recorded = record_planes(frame, std::uint32_t(frame_index_ % frames_.size()), current, *planes, image); 580 recorded = record_planes(frame, std::uint32_t(frame_index_ % frames_.size()), current, *planes,
581 image, copy_frame);
565 } 582 }
566 } 583 }
567 } else if (binding) { 584 } else if (binding) {
@@ -574,11 +591,11 @@ private:
574 tracker_lock.lock(); 591 tracker_lock.lock();
575 rollback_source = context_.tracker_.tracked(source); 592 rollback_source = context_.tracker_.tracked(source);
576 if (rollback_source) prev_layout = context_.tracker_.layout(source, 0); 593 if (rollback_source) prev_layout = context_.tracker_.layout(source, 0);
577 record(frame.commands, *current, source, image, source_rect); 594 record(frame.commands, *current, source, image, source_rect, copy_frame);
578 recorded = true; 595 recorded = true;
579 } 596 }
580 } else { 597 } else {
581 record_blank(frame.commands, image); 598 record_blank(frame.commands, image, copy_frame);
582 recorded = true; 599 recorded = true;
583 } 600 }
584 const auto rollback = [&] { 601 const auto rollback = [&] {
@@ -624,7 +641,6 @@ private:
624 const bool tearing = false; 641 const bool tearing = false;
625 (void)tear; 642 (void)tear;
626#endif 643#endif
627 const bool inspect = splash_owner_ && capture_ptr_;
628 bool show_title = false; 644 bool show_title = false;
629 if (inspect) { 645 if (inspect) {
630 submit_info.signalSemaphoreCount = 0; // signal ready only after choosing the image the window will show 646 submit_info.signalSemaphoreCount = 0; // signal ready only after choosing the image the window will show
@@ -633,7 +649,10 @@ private:
633 VkResult submitted, result = VK_SUCCESS; 649 VkResult submitted, result = VK_SUCCESS;
634 { 650 {
635 std::lock_guard lock(context_.submit_mutex()); 651 std::lock_guard lock(context_.submit_mutex());
636 submitted = context_.observe_result(vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done), 652 // One turn of the compile gate for the submit and the present after it: no pipeline create enters the
653 // driver between the two (queue_submit's own turn nests inside this one).
654 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
655 submitted = context_.observe_result(context_.queue_submit(queue_, 1, &submit_info, frame.done),
637 "vkQueueSubmit (present)"); 656 "vkQueueSubmit (present)");
638 if (submitted == VK_SUCCESS) context_.note_image_work_locked(); 657 if (submitted == VK_SUCCESS) context_.note_image_work_locked();
639 if (submitted != VK_SUCCESS) rollback(); 658 if (submitted != VK_SUCCESS) rollback();
@@ -674,14 +693,12 @@ private:
674 last_tore_ = true; 693 last_tore_ = true;
675 ++tear_presents_; 694 ++tear_presents_;
676 } 695 }
677 if (capture_to_disk_ && capture_ && capture_ptr_ && capture_written_ < capture_limit_ && 696 if (copy_frame && capture_ptr_) { // a temporary splash-only allocation may have just been released
678 (presented_ - 1) % std::uint64_t(capture_every_) == 0) 697 captured_ = true;
679 pending_capture_ = frame.done; 698 captured_extent_ = extent_;
680 } 699 captured_format_ = format_;
681 if (capture_ && capture_ptr_) { 700 if (disk_sample) pending_capture_ = frame.done;
682 captured_ = true; 701 }
683 captured_extent_ = extent_;
684 captured_format_ = format_;
685 } 702 }
686 if (result == VK_ERROR_SURFACE_LOST_KHR) { 703 if (result == VK_ERROR_SURFACE_LOST_KHR) {
687 // The surface was lost during the present (display disconnected, a driver reset of the window's 704 // The surface was lost during the present (display disconnected, a driver reset of the window's
@@ -913,7 +930,7 @@ private:
913 VkResult submitted; 930 VkResult submitted;
914 { 931 {
915 std::lock_guard lock(context_.submit_mutex()); 932 std::lock_guard lock(context_.submit_mutex());
916 submitted = context_.observe_result(vk.vkQueueSubmit(queue_, 1, &submit_info, probe_fence_), 933 submitted = context_.observe_result(context_.queue_submit(queue_, 1, &submit_info, probe_fence_),
917 "vkQueueSubmit (present probe)"); 934 "vkQueueSubmit (present probe)");
918 if (submitted == VK_SUCCESS) context_.note_image_work_locked(); 935 if (submitted == VK_SUCCESS) context_.note_image_work_locked();
919 } 936 }
@@ -1034,7 +1051,7 @@ private:
1034 VkResult submitted; 1051 VkResult submitted;
1035 { 1052 {
1036 std::lock_guard lock(context_.submit_mutex()); 1053 std::lock_guard lock(context_.submit_mutex());
1037 submitted = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done), 1054 submitted = context_.observe_result(context_.queue_submit(queue_, 1, &submit_info, frame.done),
1038 "vkQueueSubmit (return present image)"); 1055 "vkQueueSubmit (return present image)");
1039 } 1056 }
1040 if (submitted != VK_SUCCESS) return stop(failure); 1057 if (submitted != VK_SUCCESS) return stop(failure);
@@ -1066,6 +1083,7 @@ private:
1066 const VkDevice device = context_.device(); 1083 const VkDevice device = context_.device();
1067 { 1084 {
1068 std::lock_guard lock(context_.submit_mutex()); 1085 std::lock_guard lock(context_.submit_mutex());
1086 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
1069 // The old swapchain's images and semaphores may still be in use. 1087 // The old swapchain's images and semaphores may still be in use.
1070 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); 1088 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
1071 release(swapchain_); 1089 release(swapchain_);
@@ -1079,7 +1097,7 @@ private:
1079 } 1097 }
1080 1098
1081 void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image, 1099 void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image,
1082 const PresentRect* source_rect) { 1100 const PresentRect* source_rect, bool copy_frame) {
1083 auto& vk = context_.vk; 1101 auto& vk = context_.vk;
1084 const ReplayFunctions& fn = context_.replay_; 1102 const ReplayFunctions& fn = context_.replay_;
1085 vk.vkResetCommandBuffer(commands, 0); 1103 vk.vkResetCommandBuffer(commands, 0);
@@ -1122,7 +1140,7 @@ private:
1122 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, 1140 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit,
1123 sw == dw && sh == dh ? VK_FILTER_NEAREST : blit_filter(binding.format)); 1141 sw == dw && sh == dh ? VK_FILTER_NEAREST : blit_filter(binding.format));
1124 1142
1125 finish_image(commands, image); 1143 finish_image(commands, image, copy_frame);
1126 for (const auto& piece : pieces) 1144 for (const auto& piece : pieces)
1127 detail::image_barrier(fn, commands, binding, piece.range, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, 1145 detail::image_barrier(fn, commands, binding, piece.range, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1128 piece.layout, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, any, 1146 piece.layout, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, any,
@@ -1156,6 +1174,7 @@ private:
1156 return true; 1174 return true;
1157 { 1175 {
1158 std::lock_guard lock(context_.submit_mutex()); 1176 std::lock_guard lock(context_.submit_mutex());
1177 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
1159 // The old target may still be in use. 1178 // The old target may still be in use.
1160 context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); 1179 context_.observe_result(context_.vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
1161 } 1180 }
@@ -1166,7 +1185,7 @@ private:
1166 // Records the composition of `planes` and its copy to swapchain image `image`. False, with nothing recorded and the 1185 // Records the composition of `planes` and its copy to swapchain image `image`. False, with nothing recorded and the
1167 // tracker untouched, when a view cannot be made. The caller holds the resource and tracker locks. 1186 // tracker untouched, when a view cannot be made. The caller holds the resource and tracker locks.
1168 bool record_planes(Frame& frame, std::uint32_t slot, const std::array<ResourceBinding, 2>& current, 1187 bool record_planes(Frame& frame, std::uint32_t slot, const std::array<ResourceBinding, 2>& current,
1169 const PresentPlanes& planes, std::uint32_t image) { 1188 const PresentPlanes& planes, std::uint32_t image, bool copy_frame) {
1170 auto& vk = context_.vk; 1189 auto& vk = context_.vk;
1171 const ReplayFunctions& fn = context_.replay_; 1190 const ReplayFunctions& fn = context_.replay_;
1172 if (composer_->target() == VK_NULL_HANDLE || composer_->extent().width != extent_.width || 1191 if (composer_->target() == VK_NULL_HANDLE || composer_->extent().width != extent_.width ||
@@ -1254,7 +1273,7 @@ private:
1254 blit.dstOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1}; 1273 blit.dstOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1};
1255 vkCmdBlitImage_(commands, composer_->target(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images_[image], 1274 vkCmdBlitImage_(commands, composer_->target(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images_[image],
1256 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST); 1275 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
1257 finish_image(commands, image); 1276 finish_image(commands, image, copy_frame);
1258 for (std::uint32_t i = 0; i < planes.count; ++i) { 1277 for (std::uint32_t i = 0; i < planes.count; ++i) {
1259 if (i == 1 && same) continue; 1278 if (i == 1 && same) continue;
1260 for (const auto& piece : pieces[i]) 1279 for (const auto& piece : pieces[i])
@@ -1291,7 +1310,7 @@ private:
1291 } 1310 }
1292 1311
1293 // Clears the swapchain image to opaque black. 1312 // Clears the swapchain image to opaque black.
1294 void record_blank(VkCommandBuffer commands, std::uint32_t image) { 1313 void record_blank(VkCommandBuffer commands, std::uint32_t image, bool copy_frame) {
1295 auto& vk = context_.vk; 1314 auto& vk = context_.vk;
1296 const ReplayFunctions& fn = context_.replay_; 1315 const ReplayFunctions& fn = context_.replay_;
1297 vk.vkResetCommandBuffer(commands, 0); 1316 vk.vkResetCommandBuffer(commands, 0);
@@ -1304,18 +1323,18 @@ private:
1304 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); 1323 VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
1305 const VkClearColorValue black{{0.0f, 0.0f, 0.0f, 1.0f}}; 1324 const VkClearColorValue black{{0.0f, 0.0f, 0.0f, 1.0f}};
1306 vkCmdClearColorImage_(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, &range); 1325 vkCmdClearColorImage_(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, &range);
1307 finish_image(commands, image); 1326 finish_image(commands, image, copy_frame);
1308 vk.vkEndCommandBuffer(commands); 1327 vk.vkEndCommandBuffer(commands);
1309 } 1328 }
1310 1329
1311 // The swapchain image is written (TRANSFER_DST): optionally copy it to the capture buffer, then hand it to 1330 // The swapchain image is written (TRANSFER_DST): optionally copy it to the capture buffer, then hand it to
1312 // the presentation engine. 1331 // the presentation engine.
1313 void finish_image(VkCommandBuffer commands, std::uint32_t image) { 1332 void finish_image(VkCommandBuffer commands, std::uint32_t image, bool copy_frame) {
1314 const ReplayFunctions& fn = context_.replay_; 1333 const ReplayFunctions& fn = context_.replay_;
1315 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; 1334 const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
1316 VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; 1335 VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1317 VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT; 1336 VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT;
1318 if (capture_buffer_ && (capture_ || dump_.due(presented_))) { 1337 if (copy_frame) {
1319 // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy 1338 // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy
1320 // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC. 1339 // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC.
1321 VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; 1340 VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER};
@@ -1512,6 +1531,7 @@ private:
1512 const VkDevice device = context_.device(); 1531 const VkDevice device = context_.device();
1513 { 1532 {
1514 std::lock_guard lock(context_.submit_mutex()); 1533 std::lock_guard lock(context_.submit_mutex());
1534 const SubmitMutex::SubmitTurn turn(context_.submit_mutex()); // a queue operation: the compile gate
1515 // The old swapchain's images and semaphores may still be in use. 1535 // The old swapchain's images and semaphores may still be in use.
1516 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)"); 1536 context_.observe_result(vk.vkQueueWaitIdle(queue_), "vkQueueWaitIdle (present)");
1517 } 1537 }
@@ -1819,6 +1839,7 @@ private:
1819 bool capture_ = false; 1839 bool capture_ = false;
1820 present_dump::PresentDump dump_; 1840 present_dump::PresentDump dump_;
1821 bool dump_pq_ = false; 1841 bool dump_pq_ = false;
1842 bool continuous_readback_ = false; // explicit enable_capture(), independent of disk sampling
1822 VkBuffer capture_buffer_ = VK_NULL_HANDLE; 1843 VkBuffer capture_buffer_ = VK_NULL_HANDLE;
1823 VkDeviceMemory capture_memory_ = VK_NULL_HANDLE; 1844 VkDeviceMemory capture_memory_ = VK_NULL_HANDLE;
1824 VkDeviceSize capture_size_ = 0; 1845 VkDeviceSize capture_size_ = 0;
diff --git a/runtime/src/vulkan_present_splash.h b/runtime/src/vulkan_present_splash.h
index affc9a92b..450b06296 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_ptr<v
13 if (!binding || !binding->image) return false; 13 if (!binding || !binding->image) return false;
14 splash_binding_ = *binding; 14 splash_binding_ = *binding;
15 } 15 }
16 if (!capture_) splash_capture_only_ = enable_capture(); 16 if (!capture_) splash_capture_only_ = enable_capture_storage();
17 const auto before = presented(); 17 const auto before = presented();
18 if (present(source, true) != VK_SUCCESS || presented() == before) return false; 18 if (present(source, true) != VK_SUCCESS || presented() == before) return false;
19 const Frame& frame = frames_[(frame_index_ - 1) % frames_.size()]; 19 const Frame& frame = frames_[(frame_index_ - 1) % frames_.size()];
@@ -61,14 +61,16 @@ inline VkResult VulkanPresenter::finish_startup_frame(Frame& frame, std::uint32_
61 VkSubmitInfo ready{VK_STRUCTURE_TYPE_SUBMIT_INFO}; 61 VkSubmitInfo ready{VK_STRUCTURE_TYPE_SUBMIT_INFO};
62 ready.signalSemaphoreCount = 1; 62 ready.signalSemaphoreCount = 1;
63 ready.pSignalSemaphores = &ready_[image]; 63 ready.pSignalSemaphores = &ready_[image];
64 if (show_title) return context_.vk.vkQueueSubmit(queue_, 1, &ready, VK_NULL_HANDLE); 64 if (show_title) return context_.queue_submit(queue_, 1, &ready, VK_NULL_HANDLE);
65 // The acquire was consumed and the title commands finished. Overwrite the same image before presenting it. 65 // The acquire was consumed and the title commands finished. Overwrite the same image before presenting it.
66 record(frame.commands, splash_binding_, splash_source_, image, nullptr); 66 // The inspected copy contains the black title frame. Overwrite staging with the
67 // splash actually shown; this is the copy an active disk/readback consumer must see.
68 record(frame.commands, splash_binding_, splash_source_, image, nullptr, true);
67 result = vkResetFences_(device, 1, &frame.done); 69 result = vkResetFences_(device, 1, &frame.done);
68 if (result != VK_SUCCESS) return result; 70 if (result != VK_SUCCESS) return result;
69 ready.commandBufferCount = 1; 71 ready.commandBufferCount = 1;
70 ready.pCommandBuffers = &frame.commands; 72 ready.pCommandBuffers = &frame.commands;
71 return context_.vk.vkQueueSubmit(queue_, 1, &ready, frame.done); 73 return context_.queue_submit(queue_, 1, &ready, frame.done);
72} 74}
73 75
74} // namespace leonida 76} // namespace leonida
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index 359fabff0..8889560e9 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -60,9 +60,12 @@
60#include <limits> 60#include <limits>
61#include <map> 61#include <map>
62#include <memory> 62#include <memory>
63#include <mutex>
63#include <optional> 64#include <optional>
65#include <span>
64#include <type_traits> 66#include <type_traits>
65#include <unordered_map> 67#include <unordered_map>
68#include <unordered_set>
66#include <utility> 69#include <utility>
67#include <vector> 70#include <vector>
68 71
@@ -843,14 +846,19 @@ struct OcclusionResult {
843// A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that 846// A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that
844// was never ended writes zeros instead of waiting on it. 847// was never ended writes zeros instead of waiting on it.
845struct QueryPool { 848struct QueryPool {
846 // Null for a stream-output statistics heap: the layer has no stream output (PSOs with StreamOutput entries are 849 // Null for a stream-output statistics heap on a device without VK_EXT_transform_feedback (D3D-302): every
847 // refused), so every SO_STATISTICS_STREAMn query counts 0 written and 0 needed, and a resolve fills zeros. 850 // SO_STATISTICS_STREAMn query then counts 0 written and 0 needed, and a resolve fills zeros. With the feature
851 // it is a VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool, begun/ended indexed on the stream.
848 VkQueryPool pool = VK_NULL_HANDLE; 852 VkQueryPool pool = VK_NULL_HANDLE;
849 std::uint32_t heap_type = 0; // d3d12_query_heap 853 std::uint32_t heap_type = 0; // d3d12_query_heap
850 std::uint32_t count = 0; 854 std::uint32_t count = 0;
851 bool precise = false; // occlusionQueryPrecise: D3D12_QUERY_TYPE_OCCLUSION counts exact samples 855 bool precise = false; // occlusionQueryPrecise: D3D12_QUERY_TYPE_OCCLUSION counts exact samples
852 std::vector<bool> ended; 856 std::vector<bool> ended;
853 std::unordered_map<std::uint32_t, OcclusionResult> occlusion; 857 std::unordered_map<std::uint32_t, OcclusionResult> occlusion;
858 // Transform-feedback streams the pool can query (D3D-302): 0 when it has no pool, otherwise the device's
859 // maxTransformFeedbackStreams clamped to D3D12's four. SO_STATISTICS_STREAMn with n at or above this runs nothing
860 // and resolves zero.
861 std::uint32_t streams = 0;
854}; 862};
855 863
856// A compute pipeline as replay needs it. code_base is the console VA of the shader's FSSM blob (push-constant 864// A compute pipeline as replay needs it. code_base is the console VA of the shader's FSSM blob (push-constant
@@ -860,16 +868,18 @@ struct ComputePipeline {
860 VkPipelineLayout layout = VK_NULL_HANDLE; 868 VkPipelineLayout layout = VK_NULL_HANDLE;
861 std::uint64_t code_base = 0; 869 std::uint64_t code_base = 0;
862 VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none 870 VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none
863 // A pipeline built on first use: with `pipeline` null, `build(build_context)` returns the handle (building it if 871 // A pipeline built on first use: with `pipeline` null, `build(build_context)` returns the handle, or null when it
864 // nobody has yet), or null when it cannot be built. Null `build`: `pipeline` is final. 872 // cannot be built or (async_build) is still being built - it never waits for a build another thread runs, since
873 // prepare calls it with the resource lock held. Null `build`: `pipeline` is final.
865 VkPipeline (*build)(void*) = nullptr; 874 VkPipeline (*build)(void*) = nullptr;
866 void* build_context = nullptr; 875 void* build_context = nullptr;
867 bool async_build = false; // a null handle may be waiting for the compile worker 876 bool async_build = false; // a null handle may be waiting for the compile worker
868 // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a 877 // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a
869 // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles. 878 // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles.
870 VkPipeline (*built)(void*) = nullptr; 879 VkPipeline (*built)(void*) = nullptr;
871 bool large = false; // compiled one after another with the other large ones (PipelineCompiles) 880 bool large = false; // PipelineCompiles limits how many of these compile at once
872 bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped 881 bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped
882 std::uint64_t estimate = 0; // large: the bytes of memory its compile is expected to take
873}; 883};
874 884
875// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it 885// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it
@@ -888,6 +898,7 @@ struct GraphicsPipeline {
888 std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) 898 std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF)
889 bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only 899 bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only
890 bool viewport_with_count = false; // pipeline uses VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT 900 bool viewport_with_count = false; // pipeline uses VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT / SCISSOR_WITH_COUNT
901 bool depth_bounds = false; // depthBoundsTestEnable: the bounds are dynamic (vkCmdSetDepthBounds)
891 // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots 902 // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots
892 // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth 903 // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth
893 // and stencil. Null when it cannot be built. 904 // and stencil. Null when it cannot be built.
@@ -903,6 +914,7 @@ struct GraphicsPipeline {
903 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count 914 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count
904 bool async_build = false; 915 bool async_build = false;
905 bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation 916 bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation
917 std::uint64_t estimate = 0; // as ComputePipeline::estimate
906}; 918};
907 919
908// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. 920// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base.
@@ -988,7 +1000,7 @@ inline ReplayResult unsupported_at(int line) {
988 1000
989// The pipelines of a submission that are not built yet. prepare() adds each of them once and goes on; build_pipelines() 1001// The pipelines of a submission that are not built yet. prepare() adds each of them once and goes on; build_pipelines()
990// then compiles them all and puts them where prepare() left them out. Holds pointers to registered pipelines: valid 1002// then compiles them all and puts them where prepare() left them out. Holds pointers to registered pipelines: valid
991// while the context's resource lock is held. 1003// while the context's pipeline lock is held.
992class PipelineCompiles { 1004class PipelineCompiles {
993public: 1005public:
994 // Where a prepared command finds its pipeline: an index for `built`, plus one; 0 when it needs none. 1006 // Where a prepared command finds its pipeline: an index for `built`, plus one; 0 when it needs none.
@@ -1000,7 +1012,7 @@ public:
1000 User user; 1012 User user;
1001 }; 1013 };
1002 // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics 1014 // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics
1003 // pipelines of this much or more are `large`. 1015 // pipelines of this much or more are `large`. For compute pipelines the D3D12 layer decides.
1004 static constexpr std::uint64_t large_spirv_bytes = 1u << 20; 1016 static constexpr std::uint64_t large_spirv_bytes = 1u << 20;
1005 1017
1006 Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) { 1018 Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) {
@@ -1009,29 +1021,111 @@ public:
1009 Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); } 1021 Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); }
1010 1022
1011 bool empty() const { return jobs_.empty(); } 1023 bool empty() const { return jobs_.empty(); }
1024 bool any_large() const {
1025 return std::any_of(jobs_.begin(), jobs_.end(), [](const Job& job) { return is_large(job); });
1026 }
1012 std::size_t size() const { return jobs_.size(); } 1027 std::size_t size() const { return jobs_.size(); }
1013 VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; } 1028 VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; }
1014 const std::vector<Use>& uses() const { return uses_; } // in the order of the commands 1029 const std::vector<Use>& uses() const { return uses_; } // in the order of the commands
1015 1030
1016 // Compiles all of them through run(count, job) (PipelineWorkers::run): the large ones one after another, as without 1031 // Whether this batch already attempted (pipeline, flags); writes its outcome (built handle or VK_NULL_HANDLE) to `out`.
1017 // workers, beside the others. 1032 bool lookup(const GraphicsPipeline* graphics, const ComputePipeline* compute, std::uint32_t flags,
1033 VkPipeline& out) const {
1034 const void* const pipeline = graphics ? static_cast<const void*>(graphics) : compute;
1035 const auto it = tickets_.find({pipeline, flags});
1036 if (it == tickets_.end()) return false;
1037 out = jobs_[it->second - 1].built;
1038 return true;
1039 }
1040
1041 // Whether this batch already attempted the job named by `other`'s `ticket`.
1042 bool contains_ticket(const PipelineCompiles& other, Ticket ticket) const {
1043 VkPipeline unused = VK_NULL_HANDLE;
1044 const Job& job = other.jobs_[ticket - 1];
1045 return lookup(job.graphics, job.compute, job.flags, unused);
1046 }
1047
1048 // Compiles all of them through run(count, job) (PipelineWorkers::run). The large ones share budget() bytes of memory:
1049 // the largest first, as many at once as their estimates fit, one at least; while the next one does not fit, the
1050 // others are compiled first. No budget, or 0: the large ones one after another, as without workers, beside the others.
1018 template<typename Run> 1051 template<typename Run>
1019 void build(Run&& run) { 1052 void build(Run&& run, const std::function<std::uint64_t()>& read_budget = {},
1053 const PipelineCompiles* prior = nullptr) {
1020 std::vector<std::size_t> single, large; 1054 std::vector<std::size_t> single, large;
1021 for (std::size_t i = 0; i < jobs_.size(); ++i) (is_large(jobs_[i]) ? large : single).push_back(i); 1055 for (std::size_t i = 0; i < jobs_.size(); ++i) {
1056 if (prior && prior->lookup(jobs_[i].graphics, jobs_[i].compute, jobs_[i].flags, jobs_[i].built)) continue;
1057 (is_large(jobs_[i]) ? large : single).push_back(i);
1058 }
1059 if (single.empty() && large.empty()) return;
1060 // The first jobs of the run are lanes, which take large ones until none is left: no more of them than there are
1061 // large ones that fit the budget together (the smallest), so that no thread waits here for room in vain.
1062 std::size_t lanes = large.empty() ? 0 : 1;
1063 const std::uint64_t budget = lanes && read_budget ? read_budget() : 0;
1064 if (budget) {
1065 std::stable_sort(large.begin(), large.end(), [this](std::size_t a, std::size_t b) {
1066 return estimate(jobs_[a]) > estimate(jobs_[b]);
1067 });
1068 std::uint64_t sum = estimate(jobs_[large.back()]);
1069 while (lanes < large.size() && (sum += estimate(jobs_[large[large.size() - 1 - lanes]])) <= budget) ++lanes;
1070 }
1022 const auto compile = [this](std::size_t i) { 1071 const auto compile = [this](std::size_t i) {
1023 Job& job = jobs_[i]; 1072 Job& job = jobs_[i];
1024 job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); 1073 job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context);
1025 }; 1074 };
1026 const std::size_t chain = large.empty() ? 0 : 1; // the large ones are one unit, the first 1075 std::mutex mutex; // guards the four below
1027 run(chain + single.size(), [&](std::size_t i) { 1076 std::size_t next_single = 0, next_large = 0, compiling = 0;
1028 if (i >= chain) 1077 std::uint64_t reserved = 0; // the estimates of the large ones compiling
1029 compile(single[i - chain]); 1078 run(lanes + single.size(), [&](std::size_t i) {
1030 else 1079 std::unique_lock lock(mutex);
1031 for (const std::size_t each : large) compile(each); 1080 if (i >= lanes) {
1081 if (next_single == single.size()) return; // a lane has taken it
1082 const std::size_t index = single[next_single++];
1083 lock.unlock();
1084 compile(index);
1085 return;
1086 }
1087 while (next_large < large.size()) {
1088 const std::uint64_t need = estimate(jobs_[large[next_large]]);
1089 const bool fits = !compiling || reserved + need <= budget;
1090 if (!fits && next_single < single.size()) {
1091 const std::size_t index = single[next_single++];
1092 lock.unlock();
1093 compile(index);
1094 lock.lock();
1095 continue;
1096 }
1097 const std::size_t index = large[next_large++];
1098 ++compiling;
1099 reserved += need;
1100 lock.unlock();
1101 compile(index);
1102 lock.lock();
1103 --compiling;
1104 reserved -= need;
1105 }
1032 }); 1106 });
1033 } 1107 }
1034 1108
1109 // Compiles jobs serially in command order without workers, stopping at the first fatal refusal (a failed draw, a
1110 // failed indirect dispatch, or any failed dispatch under strict_replay()). Matches serial prepare() short-circuit
1111 // semantics while allowing the caller to compile outside resource_mutex_.
1112 void build_serial(const PipelineCompiles* prior = nullptr) {
1113 std::vector<bool> done(jobs_.size(), false);
1114 for (const Use& use : uses_) {
1115 const std::size_t i = use.ticket - 1;
1116 if (!done[i]) {
1117 done[i] = true;
1118 Job& job = jobs_[i];
1119 if (!prior || !prior->lookup(job.graphics, job.compute, job.flags, job.built)) {
1120 job.built =
1121 job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context);
1122 }
1123 }
1124 if (!jobs_[i].built && (use.user == User::draw || use.user == User::indirect_dispatch || strict_replay()))
1125 return;
1126 }
1127 }
1128
1035private: 1129private:
1036 struct Job { 1130 struct Job {
1037 const GraphicsPipeline* graphics; // one of the two 1131 const GraphicsPipeline* graphics; // one of the two
@@ -1040,6 +1134,9 @@ private:
1040 VkPipeline built = VK_NULL_HANDLE; 1134 VkPipeline built = VK_NULL_HANDLE;
1041 }; 1135 };
1042 static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; } 1136 static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; }
1137 static std::uint64_t estimate(const Job& job) {
1138 return job.graphics ? job.graphics->estimate : job.compute->estimate;
1139 }
1043 Ticket add(const Job& job, User user) { 1140 Ticket add(const Job& job, User user) {
1044 const void* const pipeline = job.graphics ? static_cast<const void*>(job.graphics) : job.compute; 1141 const void* const pipeline = job.graphics ? static_cast<const void*>(job.graphics) : job.compute;
1045 const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1)); 1142 const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1));
@@ -1087,6 +1184,10 @@ struct ReplayFunctions {
1087 PFN_vkCmdResetQueryPool reset_query_pool = nullptr; // queries, with fill_buffer for unavailable results 1184 PFN_vkCmdResetQueryPool reset_query_pool = nullptr; // queries, with fill_buffer for unavailable results
1088 PFN_vkCmdBeginQuery begin_query = nullptr; 1185 PFN_vkCmdBeginQuery begin_query = nullptr;
1089 PFN_vkCmdEndQuery end_query = nullptr; 1186 PFN_vkCmdEndQuery end_query = nullptr;
1187 // VK_EXT_transform_feedback (D3D-302): SO_STATISTICS queries begin/end indexed on a stream. Null when the device
1188 // lacks the feature.
1189 PFN_vkCmdBeginQueryIndexedEXT begin_query_indexed = nullptr;
1190 PFN_vkCmdEndQueryIndexedEXT end_query_indexed = nullptr;
1090 PFN_vkCmdWriteTimestamp write_timestamp = nullptr; 1191 PFN_vkCmdWriteTimestamp write_timestamp = nullptr;
1091 PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr; 1192 PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr;
1092 // Set only where a copy of timestamp results is not ordered after the timestamps written before it (MoltenVK on 1193 // Set only where a copy of timestamp results is not ordered after the timestamps written before it (MoltenVK on
@@ -1116,9 +1217,13 @@ struct ReplayFunctions {
1116 PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; 1217 PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr;
1117 PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; 1218 PFN_vkCmdSetStencilReference set_stencil_reference = nullptr;
1118 PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; 1219 PFN_vkCmdSetBlendConstants set_blend_constants = nullptr;
1220 PFN_vkCmdSetDepthBounds set_depth_bounds = nullptr; // for depth-bounds pipelines only
1119 PFN_vkCmdDraw draw = nullptr; 1221 PFN_vkCmdDraw draw = nullptr;
1120 unsigned* mesh_draw_count = nullptr; // opt-in count for this submission 1222 unsigned* mesh_draw_count = nullptr; // opt-in count for this submission
1121 PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported 1223 PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported
1224 // ExecuteIndirect with a DISPATCH_MESH signature. Its 12-byte record is VkDrawMeshTasksIndirectCommandEXT.
1225 PFN_vkCmdDrawMeshTasksIndirectEXT draw_mesh_tasks_indirect = nullptr;
1226 PFN_vkCmdDrawMeshTasksIndirectCountEXT draw_mesh_tasks_indirect_count = nullptr;
1122 PFN_vkCmdDrawIndexed draw_indexed = nullptr; 1227 PFN_vkCmdDrawIndexed draw_indexed = nullptr;
1123 std::function<const GraphicsPipeline*(std::uintptr_t)> graphics_pipeline; 1228 std::function<const GraphicsPipeline*(std::uintptr_t)> graphics_pipeline;
1124 // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is 1229 // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is
@@ -1192,6 +1297,7 @@ struct ReplayFunctions {
1192 std::function<bool(VkBuffer, VkDeviceSize, VkBuffer, VkDeviceSize, std::uint32_t, std::uint32_t, std::uint32_t, 1297 std::function<bool(VkBuffer, VkDeviceSize, VkBuffer, VkDeviceSize, std::uint32_t, std::uint32_t, std::uint32_t,
1193 ClampedIndirect&)> prepare_indirect_clamp; 1298 ClampedIndirect&)> prepare_indirect_clamp;
1194 std::function<void(VkCommandBuffer, const ClampedIndirect&)> emit_indirect_clamp; 1299 std::function<void(VkCommandBuffer, const ClampedIndirect&)> emit_indirect_clamp;
1300 bool external_graphics_scope = false; // Caller supplies the rendering scope, pipeline and bindings for legacy draws.
1195 bool require_indirect_clamp = false; // an enabled device refuses an indirect if scratch preparation fails 1301 bool require_indirect_clamp = false; // an enabled device refuses an indirect if scratch preparation fails
1196 // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. 1302 // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure.
1197 PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; 1303 PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr;
@@ -1296,7 +1402,7 @@ struct Prepared {
1296 PredicateCapture predicate; 1402 PredicateCapture predicate;
1297 std::vector<PredicatedCopyDispatch> predicated_copy; 1403 std::vector<PredicatedCopyDispatch> predicated_copy;
1298 CountedDispatch counted_dispatch; 1404 CountedDispatch counted_dispatch;
1299 ClampedIndirect indirect_clamp; // ExecuteIndirect: the clamped arguments the command reads, or null 1405 ClampedIndirect indirect_clamp; // an indirect command's clamped arguments it reads, or null
1300 ResourceBinding binding; 1406 ResourceBinding binding;
1301 VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only) 1407 VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only)
1302 VkImageView view = VK_NULL_HANDLE; 1408 VkImageView view = VK_NULL_HANDLE;
@@ -1327,7 +1433,7 @@ struct Prepared {
1327 // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination. 1433 // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination.
1328 VkBuffer staged = VK_NULL_HANDLE; 1434 VkBuffer staged = VK_NULL_HANDLE;
1329 std::vector<VkBufferImageCopy> staged_reads, staged_writes; 1435 std::vector<VkBufferImageCopy> staged_reads, staged_writes;
1330 VkDeviceSize clear_pattern_bytes = 0; // rectangular UAV clear on a compute-only queue 1436 VkDeviceSize clear_pattern_bytes = 0; // staged transfer UAV clear (compute-only rects or sliced/rect 3D)
1331 std::vector<VkImageSubresourceRange> discards; // DiscardResource: the subresources to discard 1437 std::vector<VkImageSubresourceRange> discards; // DiscardResource: the subresources to discard
1332 VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands 1438 VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands
1333 VkDeviceSize write_offset = 0; 1439 VkDeviceSize write_offset = 0;
@@ -1355,6 +1461,9 @@ struct DepthUavCopy {
1355 ResourceBinding conversion{}; 1461 ResourceBinding conversion{};
1356 VkBuffer scratch; 1462 VkBuffer scratch;
1357 VkDeviceSize offset; 1463 VkDeviceSize offset;
1464 VkBuffer depth24_scratch = VK_NULL_HANDLE;
1465 VkDeviceSize depth24_scratch_offset = 0;
1466 std::vector<Depth24Job> depth24_parts;
1358 bool to_storage; 1467 bool to_storage;
1359}; 1468};
1360 1469
@@ -1612,6 +1721,13 @@ inline VkExtent2D mip_extent(const ResourceBinding& resource, std::uint32_t mip)
1612 return {std::max(1u, resource.width >> mip), std::max(1u, resource.height >> mip)}; 1721 return {std::max(1u, resource.width >> mip), std::max(1u, resource.height >> mip)};
1613} 1722}
1614 1723
1724// Nonempty, clipped rectangle. The entire constant pattern fits in one vkCmdUpdateBuffer for wide texels.
1725inline VkExtent2D volume_clear_tile(VkExtent2D rect, std::uint32_t texel_bytes) {
1726 const std::uint32_t max_texels = 65536 / texel_bytes;
1727 const auto width = std::min(rect.width, max_texels);
1728 return {width, std::min(rect.height, max_texels / width)};
1729}
1730
1615// Into `out`, replacing what it held: a kept PreparedList entry reuses the vector's storage. 1731// Into `out`, replacing what it held: a kept PreparedList entry reuses the vector's storage.
1616inline void clip(std::span<const Rect> rects, VkExtent2D extent, std::uint32_t layers, std::vector<VkClearRect>& out) { 1732inline void clip(std::span<const Rect> rects, VkExtent2D extent, std::uint32_t layers, std::vector<VkClearRect>& out) {
1617 out.clear(); 1733 out.clear();
@@ -2475,10 +2591,13 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const
2475// Vulkan cannot copy a depth or stencil image aspect directly to or from a color image. The transfer 2591// Vulkan cannot copy a depth or stencil image aspect directly to or from a color image. The transfer
2476// buffer preserves the native D16, D32 or S8 bits. Only the requested layers and planes are copied, even when the device 2592// buffer preserves the native D16, D32 or S8 bits. Only the requested layers and planes are copied, even when the device
2477// requires both parent aspects to transition layouts together. A storage descriptor always names GENERAL. 2593// requires both parent aspects to transition layouts together. A storage descriptor always names GENERAL.
2594template<typename RunDepth24, typename EndStatistics, typename BeginStatistics>
2478inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const Prepared& p, const DepthUavCopy& copy, 2595inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const Prepared& p, const DepthUavCopy& copy,
2479 VkImageLayout parent_layout, LayoutTracker* tracker) { 2596 VkImageLayout parent_layout, LayoutTracker* tracker, RunDepth24&& run_depth24,
2597 EndStatistics&& end_statistics, BeginStatistics&& begin_statistics) {
2480 constexpr auto all = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; 2598 constexpr auto all = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
2481 constexpr auto transfer = VK_PIPELINE_STAGE_TRANSFER_BIT; 2599 constexpr auto transfer = VK_PIPELINE_STAGE_TRANSFER_BIT;
2600 constexpr auto compute = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
2482 constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; 2601 constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT;
2483 const auto parent_access = copy.to_storage ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_TRANSFER_WRITE_BIT; 2602 const auto parent_access = copy.to_storage ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_TRANSFER_WRITE_BIT;
2484 const auto child_access = copy.to_storage ? VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT; 2603 const auto child_access = copy.to_storage ? VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT;
@@ -2506,10 +2625,12 @@ inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const
2506 child_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; 2625 child_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2507 // Last use of this staging range was a read by CopyBufferToImage, possibly on the previous barrier. 2626 // Last use of this staging range was a read by CopyBufferToImage, possibly on the previous barrier.
2508 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_READ_BIT, transfer, VK_ACCESS_TRANSFER_WRITE_BIT, transfer); 2627 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_READ_BIT, transfer, VK_ACCESS_TRANSFER_WRITE_BIT, transfer);
2509 // A D32 depth aspect and R32_FLOAT colour carry the same bits through transfer scratch. The 2628 // A D32 depth aspect and R32_FLOAT colour carry the same bits through transfer scratch. A native D24
2510 // intermediate colour image permits a real normalized blit between R32_FLOAT and R16_UNORM; 2629 // depth aspect carries 24-bit UNORM words in copy.scratch and converts to/from floats in depth24_scratch
2511 // shaders see the latter's exact bits through an R16_UINT view. 2630 // via Depth24Converter. The intermediate R32_FLOAT colour image then permits a normalized blit to/from
2631 // R16_UNORM; shaders see the latter's exact bits through an R16_UINT (or R16_UNORM) view.
2512 const bool convert = plane == 0 && copy.conversion.image; 2632 const bool convert = plane == 0 && copy.conversion.image;
2633 const bool d24_convert = convert && !copy.depth24_parts.empty();
2513 const VkImage colour = convert ? copy.conversion.image : child.image; 2634 const VkImage colour = convert ? copy.conversion.image : child.image;
2514 VkImageBlit blit{}; 2635 VkImageBlit blit{};
2515 if (convert) { 2636 if (convert) {
@@ -2527,14 +2648,40 @@ inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const
2527 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer); 2648 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer);
2528 } 2649 }
2529 } 2650 }
2530 vk.copy_image_to_buffer(cb, copy.to_storage ? p.binding.image : colour, VK_IMAGE_LAYOUT_GENERAL, 2651 if (d24_convert) {
2531 copy.scratch, 1, copy.to_storage ? &parent_region : &child_region); 2652 child_region.bufferOffset = copy.depth24_scratch_offset;
2532 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer); 2653 if (copy.to_storage) {
2533 vk.copy_buffer_to_image(cb, copy.scratch, copy.to_storage ? colour : p.binding.image, VK_IMAGE_LAYOUT_GENERAL, 2654 vk.copy_image_to_buffer(cb, p.binding.image, VK_IMAGE_LAYOUT_GENERAL, copy.scratch, 1, &parent_region);
2534 1, copy.to_storage ? &child_region : &parent_region); 2655 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer,
2535 if (convert && copy.to_storage) { 2656 VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, compute);
2657 end_statistics();
2658 for (const auto& part : copy.depth24_parts) run_depth24(part);
2659 begin_statistics();
2660 memory_barrier(vk, cb, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, compute,
2661 VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, transfer);
2662 vk.copy_buffer_to_image(cb, copy.depth24_scratch, colour, VK_IMAGE_LAYOUT_GENERAL, 1, &child_region);
2663 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer);
2664 vk.blit_image(cb, colour, VK_IMAGE_LAYOUT_GENERAL, child.image, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST);
2665 } else {
2666 vk.copy_image_to_buffer(cb, colour, VK_IMAGE_LAYOUT_GENERAL, copy.depth24_scratch, 1, &child_region);
2667 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT,
2668 transfer | compute, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, compute);
2669 end_statistics();
2670 for (const auto& part : copy.depth24_parts) run_depth24(part);
2671 begin_statistics();
2672 memory_barrier(vk, cb, VK_ACCESS_SHADER_WRITE_BIT, compute, VK_ACCESS_TRANSFER_READ_BIT, transfer);
2673 vk.copy_buffer_to_image(cb, copy.scratch, p.binding.image, VK_IMAGE_LAYOUT_GENERAL, 1, &parent_region);
2674 }
2675 } else {
2676 vk.copy_image_to_buffer(cb, copy.to_storage ? p.binding.image : colour, VK_IMAGE_LAYOUT_GENERAL,
2677 copy.scratch, 1, copy.to_storage ? &parent_region : &child_region);
2536 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer); 2678 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer);
2537 vk.blit_image(cb, colour, VK_IMAGE_LAYOUT_GENERAL, child.image, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST); 2679 vk.copy_buffer_to_image(cb, copy.scratch, copy.to_storage ? colour : p.binding.image, VK_IMAGE_LAYOUT_GENERAL,
2680 1, copy.to_storage ? &child_region : &parent_region);
2681 if (convert && copy.to_storage) {
2682 memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer);
2683 vk.blit_image(cb, colour, VK_IMAGE_LAYOUT_GENERAL, child.image, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST);
2684 }
2538 } 2685 }
2539 image_barrier(vk, cb, child, color, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, 2686 image_barrier(vk, cb, child, color, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL,
2540 child_access, transfer, any, all); 2687 child_access, transfer, any, all);
@@ -2554,7 +2701,9 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R
2554 const ReplayFunctions& vk, PreparedDraw& p) { 2701 const ReplayFunctions& vk, PreparedDraw& p) {
2555 if (arguments) { 2702 if (arguments) {
2556 const IndirectDrawArgs& arg = *arguments; 2703 const IndirectDrawArgs& arg = *arguments;
2557 const VkDeviceSize record_size = draw.indexed ? sizeof(VkDrawIndexedIndirectCommand) : sizeof(VkDrawIndirectCommand); 2704 const VkDeviceSize record_size = draw.mesh ? sizeof(VkDrawMeshTasksIndirectCommandEXT)
2705 : draw.indexed ? sizeof(VkDrawIndexedIndirectCommand)
2706 : sizeof(VkDrawIndirectCommand);
2558 if (!arg.argument_buffer || !arg.max_count || arg.stride < record_size || 2707 if (!arg.argument_buffer || !arg.max_count || arg.stride < record_size ||
2559 (arg.stride | arg.argument_offset | arg.count_offset) % 4 || (!arg.count_buffer && arg.count_offset)) 2708 (arg.stride | arg.argument_offset | arg.count_offset) % 4 || (!arg.count_buffer && arg.count_offset))
2560 return ReplayResult::invalid_indirect_arguments; 2709 return ReplayResult::invalid_indirect_arguments;
@@ -2562,8 +2711,10 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R
2562 // independently of the supplied maxDrawCount. On a device with a smaller limit an 2711 // independently of the supplied maxDrawCount. On a device with a smaller limit an
2563 // arbitrary D3D12 count requires a GPU clamp pass; keep that case guarded for now. 2712 // arbitrary D3D12 count requires a GPU clamp pass; keep that case guarded for now.
2564 const bool counted = arg.count_buffer != 0; 2713 const bool counted = arg.count_buffer != 0;
2565 const bool entry_available = counted ? (draw.indexed ? vk.draw_indexed_indirect_count : vk.draw_indirect_count) != nullptr 2714 const bool entry_available =
2566 : (draw.indexed ? vk.draw_indexed_indirect : vk.draw_indirect) != nullptr; 2715 draw.mesh ? (counted ? vk.draw_mesh_tasks_indirect_count != nullptr : vk.draw_mesh_tasks_indirect != nullptr)
2716 : counted ? (draw.indexed ? vk.draw_indexed_indirect_count : vk.draw_indirect_count) != nullptr
2717 : (draw.indexed ? vk.draw_indexed_indirect : vk.draw_indirect) != nullptr;
2567 // The GPU supplies firstIndex/indexCount at execution (VUID-08798). A sized binding alone 2718 // The GPU supplies firstIndex/indexCount at execution (VUID-08798). A sized binding alone
2568 // does not guarantee a robust fetch, and the legacy binding covers the backing buffer's tail. 2719 // does not guarantee a robust fetch, and the legacy binding covers the backing buffer's tail.
2569 const auto skip = [&](indirect_stats::Reason reason) { 2720 const auto skip = [&](indirect_stats::Reason reason) {
@@ -2571,9 +2722,13 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R
2571 p.skipped = true; 2722 p.skipped = true;
2572 return ReplayResult::success; 2723 return ReplayResult::success;
2573 }; 2724 };
2574 if (draw.mesh) return skip(indirect_stats::mesh); 2725 // A mesh draw has no topology, first instance or index buffer; its records go through the clamp pass,
2575 if (draw.topology != 4) return skip(indirect_stats::topology); 2726 // which bounds x and sets y = z = 1 (the console's mesh dispatch is one-dimensional), or it is not drawn.
2576 if (!vk.draw_indirect_first_instance) return skip(indirect_stats::first_instance); 2727 if (draw.mesh && (!entry_available || !leonida::indirect_clamp_enabled())) return skip(indirect_stats::mesh);
2728 static_assert(indirect_stats::topology_supported(topology_rect_list) &&
2729 !indirect_stats::topology_supported(topology_quad_list));
2730 if (!draw.mesh && !indirect_stats::topology_supported(draw.topology)) return skip(indirect_stats::topology);
2731 if (!draw.mesh && !vk.draw_indirect_first_instance) return skip(indirect_stats::first_instance);
2577 if (!entry_available) return skip(indirect_stats::entry); 2732 if (!entry_available) return skip(indirect_stats::entry);
2578 if (draw.indexed && !vk.bind_robust_index_view) return skip(indirect_stats::robust_index); 2733 if (draw.indexed && !vk.bind_robust_index_view) return skip(indirect_stats::robust_index);
2579 if (arg.max_count > vk.max_draw_indirect_count) return skip(indirect_stats::count_limit); 2734 if (arg.max_count > vk.max_draw_indirect_count) return skip(indirect_stats::count_limit);
@@ -2617,6 +2772,7 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R
2617 if (draw.mesh && !vk.draw_mesh_tasks) return unsupported_at(__LINE__); 2772 if (draw.mesh && !vk.draw_mesh_tasks) return unsupported_at(__LINE__);
2618 if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count)) 2773 if (pipeline->viewport_with_count && (!vk.set_viewport_with_count || !vk.set_scissor_with_count))
2619 return unsupported_at(__LINE__); 2774 return unsupported_at(__LINE__);
2775 if (pipeline->depth_bounds && !vk.set_depth_bounds) return unsupported_at(__LINE__);
2620 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); 2776 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__);
2621 if (pipeline->color_formats.size() > max_render_targets) return unsupported_at(__LINE__); 2777 if (pipeline->color_formats.size() > max_render_targets) return unsupported_at(__LINE__);
2622 p.graphics = pipeline; 2778 p.graphics = pipeline;
@@ -2688,7 +2844,8 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R
2688 if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; 2844 if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot;
2689 if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; 2845 if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth;
2690 if (unbound || !p.pipeline) { 2846 if (unbound || !p.pipeline) {
2691 if (vk.compiles && pipeline->variant && pipeline->built && !pipeline->async_build) { 2847 const bool indirect_rect_variant = arguments && (unbound & GraphicsPipeline::rectangle_stage);
2848 if (vk.compiles && pipeline->variant && pipeline->built && !pipeline->async_build && !indirect_rect_variant) {
2692 p.pipeline = pipeline->built(unbound); 2849 p.pipeline = pipeline->built(unbound);
2693 if (!p.pipeline) p.compile = vk.compiles->add(*pipeline, unbound); 2850 if (!p.pipeline) p.compile = vk.compiles->add(*pipeline, unbound);
2694 } else { 2851 } else {
@@ -2698,6 +2855,11 @@ ReplayResult prepare_draw(const Draw& draw, const IndirectDrawArgs* arguments, R
2698 p.skipped = true; 2855 p.skipped = true;
2699 return ReplayResult::success; 2856 return ReplayResult::success;
2700 } 2857 }
2858 if (!p.pipeline && !pipeline->async_build && indirect_rect_variant) {
2859 indirect_stats::skip(indirect_stats::Event::replay_skip, indirect_stats::topology);
2860 p.skipped = true;
2861 return ReplayResult::success;
2862 }
2701 if (!p.pipeline) return unsupported_at(__LINE__); 2863 if (!p.pipeline) return unsupported_at(__LINE__);
2702 } 2864 }
2703 } 2865 }
@@ -2925,30 +3087,51 @@ public:
2925 std::vector<detail::PreparedKhrPostbuild> khr_postbuilds; 3087 std::vector<detail::PreparedKhrPostbuild> khr_postbuilds;
2926}; 3088};
2927 3089
2928// Ends the preparation of a submission whose prepare() calls used `compiles` and returned `result` (the first that 3090// Checks the outcomes of a compiled PipelineCompiles batch against `result` (the first prepare() failure, if any).
2929// failed, if any): builds the pipelines through run(count, job), puts them into `lists`, and returns what the calls would 3091// Every use in `compiles` comes from a command before the one that failed, so a pipeline that cannot be built counts
2930// have returned had they built each pipeline themselves. Every use in `compiles` comes from a command before the one that 3092// first, at the earliest command that uses it: it fails the list of a draw or an indirect dispatch, and a dispatch is
2931// failed, so a pipeline that cannot be built counts first, at the earliest command that uses it: it fails the list of a 3093// dropped as prepare() drops one. Non-strict failed dispatches already logged in `prior` are not logged twice.
2932// draw or an indirect dispatch, and a dispatch is dropped as prepare() drops one. 3094inline ReplayResult check_compiled_pipelines(const PipelineCompiles& compiles, ReplayResult result,
2933template<typename Run> 3095 const PipelineCompiles* prior = nullptr) {
2934ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result,
2935 Run&& run) {
2936 if (compiles.empty()) return result;
2937 compiles.build(run);
2938 for (const PipelineCompiles::Use& use : compiles.uses()) { 3096 for (const PipelineCompiles::Use& use : compiles.uses()) {
2939 if (compiles.built(use.ticket)) continue; 3097 if (compiles.built(use.ticket)) continue;
2940 if (use.user == PipelineCompiles::User::draw) return unsupported_at(__LINE__); 3098 if (use.user == PipelineCompiles::User::draw) return unsupported_at(__LINE__);
2941 if (use.user == PipelineCompiles::User::indirect_dispatch || strict_replay()) return unresolved_at(__LINE__); 3099 if (use.user == PipelineCompiles::User::indirect_dispatch || strict_replay()) return unresolved_at(__LINE__);
2942 unresolved_at(__LINE__); 3100 if (!prior || !prior->contains_ticket(compiles, use.ticket)) unresolved_at(__LINE__);
2943 } 3101 }
2944 if (result != ReplayResult::success) return result; 3102 return result;
3103}
3104
3105inline ReplayResult finish_compiled_pipelines(const PipelineCompiles& compiles, std::span<PreparedList> lists,
3106 ReplayResult result, const PipelineCompiles* prior = nullptr) {
3107 const ReplayResult checked = check_compiled_pipelines(compiles, result, prior);
3108 if (checked != ReplayResult::success) return checked;
2945 for (PreparedList& list : lists) { 3109 for (PreparedList& list : lists) {
2946 for (detail::Prepared& command : list.commands) 3110 for (detail::Prepared& command : list.commands)
2947 if (command.compile) command.pipeline.pipeline = compiles.built(command.compile); 3111 if (command.compile) command.pipeline.pipeline = compiles.built(command.compile);
2948 for (std::size_t i = 0; i < list.draw_count; ++i) 3112 for (std::size_t i = 0; i < list.draw_count; ++i)
2949 if (list.draws[i].compile) list.draws[i].pipeline = compiles.built(list.draws[i].compile); 3113 if (list.draws[i].compile) list.draws[i].pipeline = compiles.built(list.draws[i].compile);
2950 } 3114 }
2951 return result; 3115 return checked;
3116}
3117
3118// Ends the preparation of a submission whose prepare() calls used `compiles` and returned `result` (the first that
3119// failed, if any): builds the pipelines through run(count, job), puts them into `lists`, and returns what the calls would
3120// have returned had they built each pipeline themselves.
3121template<typename Run>
3122ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result,
3123 Run&& run, const std::function<std::uint64_t()>& budget = {},
3124 const PipelineCompiles* prior = nullptr) {
3125 if (compiles.empty()) return result;
3126 compiles.build(run, budget, prior);
3127 return finish_compiled_pipelines(compiles, lists, result, prior);
3128}
3129
3130inline ReplayResult build_pipelines_serial(PipelineCompiles& compiles, std::span<PreparedList> lists,
3131 ReplayResult result, const PipelineCompiles* prior = nullptr) {
3132 if (compiles.empty()) return result;
3133 compiles.build_serial(prior);
3134 return finish_compiled_pipelines(compiles, lists, result, prior);
2952} 3135}
2953 3136
2954inline ReplayResult plan_occlusion_segments(PreparedList& out) { 3137inline ReplayResult plan_occlusion_segments(PreparedList& out) {
@@ -2989,6 +3172,8 @@ inline bool has_helper_dispatch(const PreparedList& out, std::size_t i) {
2989 const auto& p = out.commands[i]; 3172 const auto& p = out.commands[i];
2990 if (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || p.counted_dispatch.indirect) 3173 if (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || p.counted_dispatch.indirect)
2991 return true; 3174 return true;
3175 if (p.depth_uav_copy != UINT32_MAX && !out.depth_uav_copies[p.depth_uav_copy].depth24_parts.empty())
3176 return true;
2992 return std::holds_alternative<Draw>(out.list->commands()[i]) && p.draw < out.draws.size() && 3177 return std::holds_alternative<Draw>(out.list->commands()[i]) && p.draw < out.draws.size() &&
2993 out.draws[p.draw].quad_indices.buffer; 3178 out.draws[p.draw].quad_indices.buffer;
2994} 3179}
@@ -3263,6 +3448,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3263 out.unpredicated_copies = 0; 3448 out.unpredicated_copies = 0;
3264 const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp && 3449 const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp &&
3265 vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool; 3450 vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool;
3451 // An SO_STATISTICS query on a real transform-feedback heap additionally needs the indexed begin/end (D3D-302).
3452 const bool so_queries = vk.begin_query_indexed && vk.end_query_indexed;
3266 // Vulkan allows one active query per type. Overlapping ordinary and binary occlusion share one physical 3453 // Vulkan allows one active query per type. Overlapping ordinary and binary occlusion share one physical
3267 // segment pool, and overlapping statistics split into the statistics pool (D3D-252); a physical query of a 3454 // segment pool, and overlapping statistics split into the statistics pool (D3D-252); a physical query of a
3268 // type is still open at most once at any point, because each event closes the one open slot and opens a new 3455 // type is still open at most once at any point, because each event closes the one open slot and opens a new
@@ -3270,6 +3457,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3270 VkDeviceAddress indirect_list_budget = 0; 3457 VkDeviceAddress indirect_list_budget = 0;
3271 std::size_t ordinary_active = 0, binary_active = 0, statistics_active_count = 0; 3458 std::size_t ordinary_active = 0, binary_active = 0, statistics_active_count = 0;
3272 bool overlaps = false, statistics_overlaps = false, statistics_active = false; 3459 bool overlaps = false, statistics_overlaps = false, statistics_active = false;
3460 // Streams with an active SO_STATISTICS query in this list, one bit each (D3D-302). Two active transform-feedback
3461 // queries on one stream break VUID-vkCmdBeginQueryIndexedEXT-queryPool-04753 anywhere in the command buffer,
3462 // whatever their pools, so prepare refuses a second Begin on an active stream.
3463 std::uint32_t so_active = 0;
3273 out.wrote_readback = false; 3464 out.wrote_readback = false;
3274 out.readback_src_stages = 0; 3465 out.readback_src_stages = 0;
3275 3466
@@ -3322,8 +3513,27 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3322 copy.scratch = plane_scratch; 3513 copy.scratch = plane_scratch;
3323 copy.offset = plane_offset; 3514 copy.offset = plane_offset;
3324 copy.to_storage = after; 3515 copy.to_storage = after;
3516 if (copy.conversion.image && p.binding.format == VK_FORMAT_D24_UNORM_S8_UINT) {
3517 if (!vk.depth24_prepare || !vk.depth24_run ||
3518 (vk.queue_stages && !(vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT)) ||
3519 texels > UINT32_MAX || (statistics_active && !statistics_helpers))
3520 return ReplayResult::unsupported;
3521 Depth24Job job{};
3522 job.to_float = after;
3523 job.app = plane_scratch;
3524 job.app_offset = plane_offset;
3525 job.app_size = plane_offset + bytes;
3526 job.width = p.binding.width;
3527 job.height = p.binding.height;
3528 job.slices = p.range.layerCount;
3529 job.app_row_words = job.width;
3530 job.app_slice_words = std::uint32_t(texels);
3531 if (!vk.depth24_prepare(job, copy.depth24_parts)) return ReplayResult::unsupported;
3532 copy.depth24_scratch = job.scratch;
3533 copy.depth24_scratch_offset = job.scratch_offset;
3534 }
3325 p.depth_uav_copy = static_cast<std::uint32_t>(out.depth_uav_copies.size()); 3535 p.depth_uav_copy = static_cast<std::uint32_t>(out.depth_uav_copies.size());
3326 out.depth_uav_copies.push_back(copy); 3536 out.depth_uav_copies.push_back(std::move(copy));
3327 return ReplayResult::success; 3537 return ReplayResult::success;
3328 }; 3538 };
3329 3539
@@ -3476,36 +3686,46 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3476 : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; 3686 : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32;
3477 const bool reinterpret = view_format != p.binding.format && attachment && view_attachable && !packed_rgb9e5; 3687 const bool reinterpret = view_format != p.binding.format && attachment && view_attachable && !packed_rgb9e5;
3478 if (view.exact_clear_format && view_format != p.binding.format && !packed_rgb9e5) 3688 if (view.exact_clear_format && view_format != p.binding.format && !packed_rgb9e5)
3479 return ReplayResult::unsupported; 3689 return unsupported_at(__LINE__);
3480 const VkFormat clear_format = reinterpret ? view_format : p.binding.format; 3690 const VkFormat clear_format = reinterpret ? view_format : p.binding.format;
3481 if (!uav_clear::decode(clear_format, p.element, p.clear_color)) 3691 if (!uav_clear::decode(clear_format, p.element, p.clear_color))
3482 return unsupported_at(__LINE__); 3692 return unsupported_at(__LINE__);
3483 if (reinterpret) p.clear_format = view_format; 3693 if (reinterpret) p.clear_format = view_format;
3484 // Compute list barriers have no attachment stages, and a dedicated compute queue cannot render. 3694 // A 3D transfer clear covers a whole mip and a compute-only queue cannot render rectangles.
3485 // Copy the encoded texel bits from a filled buffer. Transfers cannot implement a predicated clear. 3695 // Copy the encoded texel bits instead. These copies cannot implement a predicated clear.
3486 if ((vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) && 3696 const bool sliced = p.binding.volume && view.layer_count != std::max(1u, p.binding.depth >> view.mip);
3487 (!uav->rects.empty() || reinterpret || predicated)) { 3697 const bool stage_volume = p.binding.volume && (sliced || !uav->rects.empty());
3488 if (predicated || p.binding.volume || !vk.copy_scratch || !vk.fill_buffer || !vk.copy_buffer_to_image || 3698 const bool stage_compute = (vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) &&
3489 (p.element.size != 1 && p.element.size != 2 && p.element.size != 4)) 3699 (!uav->rects.empty() || reinterpret || predicated);
3490 return ReplayResult::unsupported; 3700 if (stage_volume || stage_compute) {
3701 if (predicated) return unsupported_at(__LINE__);
3702 if (stage_volume && view_format != p.binding.format && !packed_rgb9e5)
3703 return unsupported_at(__LINE__);
3704 if (!vk.copy_scratch || !vk.copy_buffer_to_image ||
3705 (p.element.size <= 4 ? !vk.fill_buffer : (!stage_volume || !vk.update_buffer)))
3706 return unsupported_at(__LINE__);
3491 const auto rects = uav->rects.empty() ? std::span<const Rect>(&whole_view, 1) : 3707 const auto rects = uav->rects.empty() ? std::span<const Rect>(&whole_view, 1) :
3492 std::span<const Rect>(uav->rects); 3708 std::span<const Rect>(uav->rects);
3493 detail::clip(rects, detail::mip_extent(p.binding, view.mip), view.layer_count, p.rects); 3709 detail::clip(rects, detail::mip_extent(p.binding, view.mip), p.range.layerCount, p.rects);
3494 if (p.rects.empty()) { p.skip = true; continue; } 3710 if (p.rects.empty()) { p.skip = true; continue; }
3495 for (const auto& rect : p.rects) { 3711 for (const auto& rect : p.rects) {
3496 VkBufferImageCopy region{}; 3712 VkBufferImageCopy region{};
3497 region.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, view.mip, view.first_layer, view.layer_count}; 3713 region.imageSubresource = {p.range.aspectMask, view.mip, p.range.baseArrayLayer, p.range.layerCount};
3498 region.imageOffset = {rect.rect.offset.x, rect.rect.offset.y, 0}; 3714 region.imageOffset = {rect.rect.offset.x, rect.rect.offset.y, 0};
3499 region.imageExtent = {rect.rect.extent.width, rect.rect.extent.height, 1}; 3715 region.imageExtent = {rect.rect.extent.width, rect.rect.extent.height, 1};
3500 const VkDeviceSize pixels = VkDeviceSize(region.imageExtent.width) * region.imageExtent.height; 3716 const auto tile = stage_volume ? detail::volume_clear_tile(rect.rect.extent, p.element.size)
3501 const VkDeviceSize stride = VkDeviceSize(view.layer_count) * p.element.size; 3717 : rect.rect.extent;
3502 if (pixels > (UINT64_MAX - 3) / stride) return ReplayResult::unsupported; 3718 const VkDeviceSize pixels = VkDeviceSize(tile.width) * tile.height;
3719 const VkDeviceSize stride = VkDeviceSize(p.range.layerCount) * p.element.size;
3720 if (pixels > (UINT64_MAX - 3) / stride) return unsupported_at(__LINE__);
3721 // Pad only the private pattern for vkCmdFillBuffer; copies use the exact image extent.
3503 p.clear_pattern_bytes = std::max(p.clear_pattern_bytes, (pixels * stride + 3) & ~VkDeviceSize(3)); 3722 p.clear_pattern_bytes = std::max(p.clear_pattern_bytes, (pixels * stride + 3) & ~VkDeviceSize(3));
3504 p.staged_writes.push_back(region); 3723 p.staged_writes.push_back(region);
3505 } 3724 }
3506 VkDeviceSize offset = 0; 3725 VkDeviceSize offset = 0;
3507 if (!vk.copy_scratch(p.clear_pattern_bytes, p.staged, offset) || !p.staged || offset % 4) 3726 if (!vk.copy_scratch(p.clear_pattern_bytes, p.staged, offset) || !p.staged ||
3508 return ReplayResult::unsupported; 3727 offset % std::max(4u, p.element.size) || offset > UINT64_MAX - p.clear_pattern_bytes)
3728 return unsupported_at(__LINE__);
3509 for (auto& region : p.staged_writes) region.bufferOffset = offset; 3729 for (auto& region : p.staged_writes) region.bufferOffset = offset;
3510 continue; 3730 continue;
3511 } 3731 }
@@ -3808,7 +4028,23 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3808 overlaps |= begin && (ordinary_active || binary_active); 4028 overlaps |= begin && (ordinary_active || binary_active);
3809 if (begin) ++binary_active; else --binary_active; 4029 if (begin) ++binary_active; else --binary_active;
3810 } else if (is_so_statistics(range.type)) { 4030 } else if (is_so_statistics(range.type)) {
3811 // No Vulkan query runs for it (QueryPool::pool is null), so it overlaps nothing. 4031 // A real transform-feedback heap queries on a stream (D3D-302). Stream n runs only when the
4032 // heap's pool covers it; then the indexed commands are required. Without a pool (the feature is
4033 // off or has no transformFeedbackQueries) or past maxTransformFeedbackStreams it runs nothing
4034 // and resolves zero. Two overlapping queries on one stream cannot both be active in one command
4035 // buffer, even in two heaps (VUID-vkCmdBeginQueryIndexedEXT-queryPool-04753), so a second Begin
4036 // is refused.
4037 const std::uint32_t stream = range.type - d3d12_query::so_statistics_stream0;
4038 if (heap->pool && stream < heap->streams) {
4039 if (!so_queries) return unsupported_at(__LINE__);
4040 const std::uint32_t bit = 1u << stream; // stream < heap->streams <= 4
4041 if (begin) {
4042 if (so_active & bit) return ReplayResult::invalid_query;
4043 so_active |= bit;
4044 } else {
4045 so_active &= ~bit;
4046 }
4047 }
3812 } else { 4048 } else {
3813 statistics_overlaps |= begin && statistics_active_count; 4049 statistics_overlaps |= begin && statistics_active_count;
3814 if (begin) ++statistics_active_count; else --statistics_active_count; 4050 if (begin) ++statistics_active_count; else --statistics_active_count;
@@ -3854,6 +4090,58 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3854 return ReplayResult::invalid_indirect_arguments; 4090 return ReplayResult::invalid_indirect_arguments;
3855 p.source = *cnt; 4091 p.source = *cnt;
3856 } 4092 }
4093 if (ind->kind != IndirectKind::dispatch && !vk.external_graphics_scope) continue;
4094 // The clamp pass (vulkan_indirect_clamp.h): the arguments are copied on the GPU into scratch with their
4095 // values bounded before the indirect command reads them, so a stale or garbage record left by a skipped or
4096 // mistranslated compute pass cannot run for seconds and reset the display driver. A counted call has its
4097 // count clamped to max_command_count too. It is a helper dispatch, so it needs the statistics segments of
4098 // a pipeline-statistics query. Every clamp of this list shares one work budget: a list of many calls does
4099 // not multiply the per-list limit.
4100 const bool clamp_command_available =
4101 ind->kind == IndirectKind::dispatch
4102 ? vk.dispatch_indirect != nullptr
4103 : ind->kind == IndirectKind::draw
4104 ? (ind->count_buffer ? vk.draw_indirect_count != nullptr : vk.draw_indirect != nullptr)
4105 : (ind->count_buffer ? vk.draw_indexed_indirect_count != nullptr
4106 : vk.draw_indexed_indirect != nullptr);
4107 const bool clamped =
4108 leonida::indirect_clamp_enabled() && vk.prepare_indirect_clamp && vk.emit_indirect_clamp &&
4109 clamp_command_available && !(statistics_active && !statistics_helpers) &&
4110 vk.prepare_indirect_clamp(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset,
4111 ind->count_buffer ? p.source.buffer : VK_NULL_HANDLE,
4112 ind->count_buffer ? p.source.buffer_offset + ind->count_offset : 0,
4113 static_cast<std::uint32_t>(ind->kind), ind->stride, ind->max_count,
4114 p.indirect_clamp);
4115 if (clamped) p.indirect_clamp.share_list_budget(indirect_list_budget);
4116 // A device with the pass enabled refuses an indirect call whose clamp could not be prepared: reading the
4117 // application's buffer is what the clamp exists to avoid. Otherwise the fallbacks below apply.
4118 if (!clamped && vk.require_indirect_clamp) return unsupported_at(__LINE__);
4119 // Nothing else to resolve when clamped: the clamp's scratch is the indirect buffer and its count word.
4120 if (!clamped) {
4121 if (ind->kind == IndirectKind::dispatch) {
4122 if (ind->count_buffer || indirect_group_budget()) {
4123 // Vulkan lacks vkCmdDispatchIndirectCount. Copy the GPU-visible commands to private scratch
4124 // and replace commands past min(count, max_count) with zero-group dispatches - or, with
4125 // LEONIDA_INDIRECT_GROUP_BUDGET and no count buffer, keep the whole batch inside its work
4126 // budget. `source` is the count binding, null without one.
4127 if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_counted_dispatch ||
4128 !vk.emit_counted_dispatch || (statistics_active && !statistics_helpers) ||
4129 !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset,
4130 p.source.buffer, p.source.buffer_offset + ind->count_offset,
4131 ind->stride, ind->max_count, p.counted_dispatch))
4132 return unsupported_at(__LINE__);
4133 } else if (!vk.dispatch_indirect) {
4134 return unsupported_at(__LINE__);
4135 }
4136 } else if (!clamp_command_available) {
4137 // A legacy graphics indirect draw is still emitted (a caller that opened its own rendering scope
4138 // around the replay, as the tests do); without vkCmdDrawIndirect[Count] there is nothing to emit.
4139 return unsupported_at(__LINE__);
4140 }
4141 }
4142 // Legacy graphics IR carries no graphics state of its own: the recorded, stateful graphics indirects are
4143 // Draw commands (IndirectRasterDraw) and open their own rendering scope. A legacy one is emitted as it is
4144 // - the clamp pass above is what keeps its arguments safe - and its dispatch-side work ends here.
3857 if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded 4145 if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded
3858 if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return unsupported_at(__LINE__); 4146 if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return unsupported_at(__LINE__);
3859 const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); 4147 const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline);
@@ -3865,28 +4153,6 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3865 if (!found) return unresolved_at(__LINE__); 4153 if (!found) return unresolved_at(__LINE__);
3866 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__); 4154 if (pipeline->bindless_set && !vk.bind_descriptor_sets) return unsupported_at(__LINE__);
3867 } 4155 }
3868 if (ind->kind == IndirectKind::dispatch && vk.require_indirect_clamp) {
3869 if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_indirect_clamp || !vk.emit_indirect_clamp ||
3870 (statistics_active && !statistics_helpers) ||
3871 !vk.prepare_indirect_clamp(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset,
3872 p.source.buffer, p.source.buffer_offset + ind->count_offset, indirect_clamp_dispatch,
3873 ind->stride, ind->max_count, p.indirect_clamp))
3874 return unsupported_at(__LINE__);
3875 p.indirect_clamp.share_list_budget(indirect_list_budget);
3876 } else if (ind->kind == IndirectKind::dispatch && (ind->count_buffer || indirect_group_budget())) {
3877 // Vulkan lacks vkCmdDispatchIndirectCount. Copy the GPU-visible commands to private scratch
3878 // and replace commands past min(count, max_count) with zero-group dispatches.
3879 if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_counted_dispatch ||
3880 !vk.emit_counted_dispatch || (statistics_active && !statistics_helpers) ||
3881 !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset,
3882 p.source.buffer, p.source.buffer_offset + ind->count_offset,
3883 ind->stride, ind->max_count, p.counted_dispatch))
3884 return unsupported_at(__LINE__);
3885 } else if (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect) {
3886 return unsupported_at(__LINE__);
3887 }
3888 // Legacy graphics IR carries no graphics state. Validate its resource ranges above,
3889 // but never emit it; stateful graphics indirects use Draw and its rendering scope.
3890 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) { 4156 } else if (const auto* build = std::get_if<BuildAccelerationStructure>(&command)) {
3891 p.khr_instances = 0; 4157 p.khr_instances = 0;
3892 if (vk.xdxr_check) { 4158 if (vk.xdxr_check) {
@@ -4027,19 +4293,49 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
4027 if (const auto r = detail::prepare_quad_indices(*draw.state, vk, prepared_draw); r != ReplayResult::success) 4293 if (const auto r = detail::prepare_quad_indices(*draw.state, vk, prepared_draw); r != ReplayResult::success)
4028 return r; 4294 return r;
4029 } 4295 }
4030 if (draw.arguments && !prepared_draw.skipped && vk.require_indirect_clamp) { 4296 // A stateful indirect draw takes the same clamp pass (vulkan_indirect_clamp.h) as a legacy ExecuteIndirect:
4031 const auto& arg = *draw.arguments; 4297 // the arguments it reads are copied and bounded on the GPU before its rendering scope opens, and the draw
4032 if (!vk.prepare_indirect_clamp || !vk.emit_indirect_clamp || (statistics_active && !statistics_helpers) || 4298 // then reads that scratch. Recorded in this command's Prepared so the emit phase records the pass before
4033 !vk.prepare_indirect_clamp(prepared_draw.indirect_buffer, prepared_draw.indirect_offset, 4299 // vkCmdBeginRendering - outside the scope and outside a pipeline-statistics query. A draw that was already
4034 prepared_draw.indirect_count_buffer, prepared_draw.indirect_count_offset, 4300 // dropped, or whose indirect entry point or scratch is missing, keeps the application's argument buffer.
4035 draw.state->indexed ? indirect_clamp_draw_indexed : indirect_clamp_draw, 4301 if (draw.arguments && !prepared_draw.skipped) {
4036 arg.stride, arg.max_count, p.indirect_clamp)) 4302 const IndirectDrawArgs& arg = *draw.arguments;
4303 const ResourceBinding* args_of = resolve(arg.argument_buffer);
4304 const ResourceBinding* count = arg.count_buffer ? resolve(arg.count_buffer) : nullptr;
4305 const bool indexed = draw.state->indexed;
4306 const bool mesh = draw.state->mesh;
4307 const bool clamp_command_available =
4308 mesh ? (arg.count_buffer ? vk.draw_mesh_tasks_indirect_count != nullptr
4309 : vk.draw_mesh_tasks_indirect != nullptr)
4310 : arg.count_buffer
4311 ? (indexed ? vk.draw_indexed_indirect_count != nullptr : vk.draw_indirect_count != nullptr)
4312 : (indexed ? vk.draw_indexed_indirect != nullptr : vk.draw_indirect != nullptr);
4313 const bool clamped =
4314 args_of && args_of->buffer && clamp_command_available && leonida::indirect_clamp_enabled() &&
4315 vk.prepare_indirect_clamp && vk.emit_indirect_clamp && !(statistics_active && !statistics_helpers) &&
4316 vk.prepare_indirect_clamp(args_of->buffer, args_of->buffer_offset + arg.argument_offset,
4317 count ? count->buffer : VK_NULL_HANDLE,
4318 count ? count->buffer_offset + arg.count_offset : 0,
4319 static_cast<std::uint32_t>(mesh ? IndirectKind::dispatch_mesh
4320 : indexed ? IndirectKind::draw_indexed
4321 : IndirectKind::draw),
4322 arg.stride, arg.max_count, p.indirect_clamp);
4323 if (clamped) {
4324 // Clamped: p.indirect_clamp names the scratch this draw reads; nothing else to resolve. Its budget
4325 // is the list's (one per command list, shared with the legacy ExecuteIndirect clamps above), and
4326 // the prepared draw carries the clamped arguments too.
4327 p.indirect_clamp.share_list_budget(indirect_list_budget);
4328 prepared_draw.indirect_buffer = p.indirect_clamp.buffer;
4329 prepared_draw.indirect_offset = p.indirect_clamp.offset;
4330 prepared_draw.indirect_count_buffer = p.indirect_clamp.count_buffer;
4331 prepared_draw.indirect_count_offset = p.indirect_clamp.count_offset;
4332 } else if (mesh) {
4333 // Unclamped, a mesh record's y and z are whatever the title left there: not drawn.
4334 indirect_stats::skip(indirect_stats::Event::replay_skip, indirect_stats::mesh);
4335 prepared_draw.skipped = true;
4336 } else if (vk.require_indirect_clamp) {
4037 return unsupported_at(__LINE__); 4337 return unsupported_at(__LINE__);
4038 p.indirect_clamp.share_list_budget(indirect_list_budget); 4338 }
4039 prepared_draw.indirect_buffer = p.indirect_clamp.buffer;
4040 prepared_draw.indirect_offset = p.indirect_clamp.offset;
4041 prepared_draw.indirect_count_buffer = p.indirect_clamp.count_buffer;
4042 prepared_draw.indirect_count_offset = p.indirect_clamp.count_offset;
4043 } 4339 }
4044 } 4340 }
4045 } 4341 }
@@ -4122,12 +4418,16 @@ public:
4122 query.statistics_end != detail::PreparedQuery::no_segment; 4418 query.statistics_end != detail::PreparedQuery::no_segment;
4123 const std::uint32_t size = query_result_size(resolve.type); 4419 const std::uint32_t size = query_result_size(resolve.type);
4124 const auto offset = list.commands[query.command].binding.buffer_offset + resolve.offset; 4420 const auto offset = list.commands[query.command].binding.buffer_offset + resolve.offset;
4421 // A stream past the pool's maxTransformFeedbackStreams ran nothing (D3D-302): its resolve is zeros.
4422 const std::uint32_t so_stream =
4423 is_so_statistics(resolve.type) ? resolve.type - d3d12_query::so_statistics_stream0 : 0;
4424 const bool so_runs = !is_so_statistics(resolve.type) || so_stream < query.heap->streams;
4125 for (std::uint32_t i = 0; i < resolve.count; ++i) { 4425 for (std::uint32_t i = 0; i < resolve.count; ++i) {
4126 const auto index = resolve.first + i; 4426 const auto index = resolve.first + i;
4127 const auto value = lookup(*query.heap, index); 4427 const auto value = lookup(*query.heap, index);
4128 if (binary && value.ended && !uncounted) return unsupported_at(__LINE__); 4428 if (binary && value.ended && !uncounted) return unsupported_at(__LINE__);
4129 needs_binary |= binary && value.ended; 4429 needs_binary |= binary && value.ended;
4130 detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE, 4430 detail::QueryResolveRun run{value.ended && so_runs ? query.heap->pool : VK_NULL_HANDLE,
4131 index, 1, offset + VkDeviceSize(i) * size}; 4431 index, 1, offset + VkDeviceSize(i) * size};
4132 if (value.occlusion.segments) { 4432 if (value.occlusion.segments) {
4133 if (resolve.type != d3d12_query::occlusion && !binary && !statistics) 4433 if (resolve.type != d3d12_query::occlusion && !binary && !statistics)
@@ -4251,17 +4551,34 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
4251 begin_statistics(); 4551 begin_statistics();
4252 return; 4552 return;
4253 } 4553 }
4254 // A heap without a Vulkan pool (stream-output statistics: the layer has no stream output) runs nothing for 4554 // A heap without a Vulkan pool (stream-output statistics on a device without VK_EXT_transform_feedback) runs
4255 // BeginQuery and EndQuery; its resolves were planned as zero fills. 4555 // nothing for BeginQuery and EndQuery; its resolves were planned as zero fills.
4256 if (!heap.pool && !std::holds_alternative<ResolveQueries>(command)) return; 4556 if (!heap.pool && !std::holds_alternative<ResolveQueries>(command)) return;
4557 // An SO_STATISTICS_STREAMn query begins/ends indexed on that stream (D3D-302): the query type's stream index is
4558 // the `index` argument of vkCmdBeginQueryIndexedEXT / vkCmdEndQueryIndexedEXT. A stream past the pool's
4559 // maxTransformFeedbackStreams runs nothing, like a heap without a pool: its resolves were planned as zero fills.
4560 const auto so_stream = [](std::uint32_t type) -> std::uint32_t {
4561 return is_so_statistics(type) ? type - d3d12_query::so_statistics_stream0 : 0;
4562 };
4563 const auto so_runs = [&](std::uint32_t type) {
4564 return !is_so_statistics(type) || so_stream(type) < heap.streams;
4565 };
4257 if (const auto* begin = std::get_if<BeginQuery>(&command)) { 4566 if (const auto* begin = std::get_if<BeginQuery>(&command)) {
4567 if (!so_runs(begin->type)) return;
4258 vk.reset_query_pool(cb, heap.pool, begin->index, 1); 4568 vk.reset_query_pool(cb, heap.pool, begin->index, 1);
4259 const bool precise = begin->type == d3d12_query::occlusion && heap.precise; 4569 if (is_so_statistics(begin->type)) {
4260 vk.begin_query(cb, heap.pool, begin->index, precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0); 4570 vk.begin_query_indexed(cb, heap.pool, begin->index, so_stream(begin->type), 0);
4571 } else {
4572 const bool precise = begin->type == d3d12_query::occlusion && heap.precise;
4573 vk.begin_query(cb, heap.pool, begin->index, precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0);
4574 }
4261 } else if (const auto* end = std::get_if<EndQuery>(&command)) { 4575 } else if (const auto* end = std::get_if<EndQuery>(&command)) {
4576 if (!so_runs(end->type)) return;
4262 if (end->type == d3d12_query::timestamp) { 4577 if (end->type == d3d12_query::timestamp) {
4263 vk.reset_query_pool(cb, heap.pool, end->index, 1); 4578 vk.reset_query_pool(cb, heap.pool, end->index, 1);
4264 vk.write_timestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, heap.pool, end->index); 4579 vk.write_timestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, heap.pool, end->index);
4580 } else if (is_so_statistics(end->type)) {
4581 vk.end_query_indexed(cb, heap.pool, end->index, so_stream(end->type));
4265 } else { 4582 } else {
4266 vk.end_query(cb, heap.pool, end->index); 4583 vk.end_query(cb, heap.pool, end->index);
4267 } 4584 }
@@ -4330,9 +4647,11 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_
4330 vk.depth24_run(command_buffer, job); 4647 vk.depth24_run(command_buffer, job);
4331 if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); 4648 if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate);
4332 }; 4649 };
4333 const auto finish_depth_uav_barrier = [&](const detail::Prepared& p, VkImageLayout layout) { 4650 const auto finish_depth_uav_barrier = [&](const detail::Prepared& p, VkImageLayout layout,
4651 auto&& end_statistics, auto&& begin_statistics) {
4334 if (p.depth_uav_copy != UINT32_MAX) { 4652 if (p.depth_uav_copy != UINT32_MAX) {
4335 detail::copy_depth_uav(vk, command_buffer, p, prepared.depth_uav_copies[p.depth_uav_copy], layout, tracker); 4653 detail::copy_depth_uav(vk, command_buffer, p, prepared.depth_uav_copies[p.depth_uav_copy], layout, tracker,
4654 run_depth24, end_statistics, begin_statistics);
4336 } else if (p.order_depth_uav) { 4655 } else if (p.order_depth_uav) {
4337 // A UAV-to-UAV texture barrier names the parent, but the actual shader accesses target its children. 4656 // A UAV-to-UAV texture barrier names the parent, but the actual shader accesses target its children.
4338 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 4657 detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
@@ -4362,13 +4681,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_
4362 // draw's own rendering scope begins. The index expansion of an indexed quad list runs here too: outside the 4681 // draw's own rendering scope begins. The index expansion of an indexed quad list runs here too: outside the
4363 // rendering scope, and between the segments so that no query counts its dispatch (D3D-162). It stays inside 4682 // rendering scope, and between the segments so that no query counts its dispatch (D3D-162). It stays inside
4364 // the predicate, which skips it together with its draw. 4683 // the predicate, which skips it together with its draw.
4365 if (p.indirect_clamp.buffer) { 4684 if (!p.indirect_clamp.buffer && !p.counted_dispatch.indirect &&
4366 end_statistics(); 4685 (raster.state || std::holds_alternative<ExecuteIndirect>(command))) {
4367 if (predicate.buffer) vk.end_conditional_rendering(command_buffer);
4368 vk.emit_indirect_clamp(command_buffer, p.indirect_clamp);
4369 if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate);
4370 begin_statistics();
4371 } else if (!p.counted_dispatch.indirect && (raster.state || std::holds_alternative<ExecuteIndirect>(command))) {
4372 end_statistics(); 4686 end_statistics();
4373 if (raster.state && prepared.draws[p.draw].quad_indices.buffer) 4687 if (raster.state && prepared.draws[p.draw].quad_indices.buffer)
4374 vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices); 4688 vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices);
@@ -4420,7 +4734,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_
4420 detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout, 4734 detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout,
4421 from.access, from.stages, to.access, to.stages); 4735 from.access, from.stages, to.access, to.stages);
4422 if (tracker) tracker->set(id, range, new_layout); 4736 if (tracker) tracker->set(id, range, new_layout);
4423 finish_depth_uav_barrier(p, new_layout); 4737 finish_depth_uav_barrier(p, new_layout, end_statistics, begin_statistics);
4424 } else if (std::holds_alternative<UavBarrier>(command)) { 4738 } else if (std::holds_alternative<UavBarrier>(command)) {
4425 const VulkanAccess uav = vulkan_access(d3d12_state::unordered_access, false); 4739 const VulkanAccess uav = vulkan_access(d3d12_state::unordered_access, false);
4426 VkAccessFlags src_access = VK_ACCESS_SHADER_WRITE_BIT; 4740 VkAccessFlags src_access = VK_ACCESS_SHADER_WRITE_BIT;
@@ -4520,7 +4834,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_
4520 vk.pipeline_barrier2(command_buffer, &dependency); 4834 vk.pipeline_barrier2(command_buffer, &dependency);
4521 } 4835 }
4522 if (tracker && !release) tracker->set(id, range, new_layout); 4836 if (tracker && !release) tracker->set(id, range, new_layout);
4523 if (!release) finish_depth_uav_barrier(p, new_layout); 4837 if (!release) finish_depth_uav_barrier(p, new_layout, end_statistics, begin_statistics);
4524 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) { 4838 } else if (const auto* color_clear = std::get_if<ClearRenderTarget>(&command)) {
4525 if (p.skip) continue; 4839 if (p.skip) continue;
4526 if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); 4840 if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear);
@@ -4638,7 +4952,27 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_
4638 detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 4952 detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
4639 VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, 4953 VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT,
4640 VK_PIPELINE_STAGE_TRANSFER_BIT); 4954 VK_PIPELINE_STAGE_TRANSFER_BIT);
4641 vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, 1, &region); 4955 if (!p.binding.volume) {
4956 vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, 1, &region);
4957 continue;
4958 }
4959 // Tiles within this rectangle are disjoint. Reuse the same scratch texels for every
4960 // tile and W slice; keep only one region per clipped rectangle in the prepared list.
4961 const auto tile = detail::volume_clear_tile({region.imageExtent.width, region.imageExtent.height},
4962 p.element.size);
4963 auto piece = region;
4964 for (std::uint32_t z = 0; z < uav->view.layer_count; ++z) {
4965 piece.imageOffset.z = std::int32_t(uav->view.first_layer + z);
4966 for (std::uint32_t y = 0; y < region.imageExtent.height; y += tile.height) {
4967 piece.imageOffset.y = region.imageOffset.y + std::int32_t(y);
4968 piece.imageExtent.height = std::min(tile.height, region.imageExtent.height - y);
4969 for (std::uint32_t x = 0; x < region.imageExtent.width; x += tile.width) {
4970 piece.imageOffset.x = region.imageOffset.x + std::int32_t(x);
4971 piece.imageExtent.width = std::min(tile.width, region.imageExtent.width - x);
4972 vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, 1, &piece);
4973 }
4974 }
4975 }
4642 } 4976 }
4643 }); 4977 });
4644 continue; 4978 continue;
@@ -4953,17 +5287,64 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_
4953 VK_PIPELINE_STAGE_TRANSFER_BIT); 5287 VK_PIPELINE_STAGE_TRANSFER_BIT);
4954 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); 5288 vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data());
4955 } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) { 5289 } else if (const auto* ind = std::get_if<ExecuteIndirect>(&command)) {
4956 if (ind->kind != IndirectKind::dispatch) { 5290 if (ind->kind != IndirectKind::dispatch && !vk.external_graphics_scope) {
4957 indirect_stats::skip(indirect_stats::Event::replay_skip, indirect_stats::stateless); 5291 indirect_stats::skip(indirect_stats::Event::replay_skip, indirect_stats::stateless);
4958 continue; 5292 continue;
4959 } 5293 }
5294 // The clamp pass (vulkan_indirect_clamp.h) runs before anything reads the indirect arguments, and before
5295 // the drawing scope an indirect draw opens around itself. It is a helper dispatch: a pipeline-statistics
5296 // query must not count it, and it runs even under a false predicate (the draw it feeds may be the one
5297 // the predicate discards, and a later command may read the same scratch).
5298 const bool clamped = p.indirect_clamp.buffer != VK_NULL_HANDLE;
5299 if (clamped) {
5300 end_statistics();
5301 if (predicate.buffer) vk.end_conditional_rendering(command_buffer);
5302 vk.emit_indirect_clamp(command_buffer, p.indirect_clamp);
5303 if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate);
5304 begin_statistics();
5305 }
5306 // What the indirect command reads: the clamped scratch, the application's own buffer, or for a counted
5307 // DISPATCH (Vulkan has no vkCmdDispatchIndirectCount, and LEONIDA_INDIRECT_GROUP_BUDGET packs a batch
5308 // without one too) the zero-filled copy the replay made.
5309 const bool counted_dispatch = !clamped && p.counted_dispatch.indirect;
5310 const VkBuffer indirect_buffer = clamped ? p.indirect_clamp.buffer
5311 : counted_dispatch ? p.counted_dispatch.indirect
5312 : p.binding.buffer;
5313 const VkDeviceSize arguments = clamped ? p.indirect_clamp.offset
5314 : counted_dispatch ? p.counted_dispatch.offset
5315 : p.binding.buffer_offset + ind->argument_offset;
5316 const VkBuffer count_buffer = clamped ? p.indirect_clamp.count_buffer : p.source.buffer;
5317 const VkDeviceSize count_offset = clamped ? p.indirect_clamp.count_offset : p.source.buffer_offset + ind->count_offset;
5318 const std::uint32_t records = clamped ? p.indirect_clamp.records : ind->max_count;
5319 const std::uint32_t stride = clamped ? p.indirect_clamp.stride
5320 : counted_dispatch ? std::uint32_t(sizeof(VkDispatchIndirectCommand))
5321 : ind->stride;
5322 // A legacy graphics indirect draw opens no rendering scope of its own: the caller has one open around the
5323 // replay (the tests do), and the recorded, stateful graphics indirects are Draw commands instead.
5324 if (ind->kind != IndirectKind::dispatch) {
5325 if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::draw);
5326 if (ind->count_buffer) {
5327 if (ind->kind == IndirectKind::draw)
5328 vk.draw_indirect_count(command_buffer, indirect_buffer, arguments, count_buffer, count_offset,
5329 records, stride);
5330 else
5331 vk.draw_indexed_indirect_count(command_buffer, indirect_buffer, arguments, count_buffer,
5332 count_offset, records, stride);
5333 } else if (ind->kind == IndirectKind::draw) {
5334 vk.draw_indirect(command_buffer, indirect_buffer, arguments, records, stride);
5335 } else {
5336 vk.draw_indexed_indirect(command_buffer, indirect_buffer, arguments, records, stride);
5337 }
5338 continue;
5339 }
4960 if (ind->pipeline && !p.pipeline.pipeline && (p.pipeline.async_build || p.pipeline.skipped)) continue; 5340 if (ind->pipeline && !p.pipeline.pipeline && (p.pipeline.async_build || p.pipeline.skipped)) continue;
4961 if constexpr (Checkpoints) 5341 if constexpr (Checkpoints)
4962 checkpoints->dispatch(command_buffer, i, p.pipeline.pipeline, ind->pipeline, ind->user_data, {}, true, 5342 checkpoints->dispatch(command_buffer, i, p.pipeline.pipeline, ind->pipeline, ind->user_data, {}, true,
4963 ind->argument_buffer, ind->argument_offset, ind->count_buffer, 5343 reinterpret_cast<std::uintptr_t>(indirect_buffer),
4964 ind->count_offset, ind->max_count, ind->stride); 5344 clamped || counted_dispatch ? arguments : ind->argument_offset,
4965 const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; 5345 ind->count_buffer ? reinterpret_cast<std::uintptr_t>(count_buffer) : 0,
4966 if (p.counted_dispatch.indirect) { 5346 clamped ? count_offset : ind->count_offset, records, stride);
5347 if (counted_dispatch) {
4967 // No D3D12 query must count this internal compute pass as an application dispatch. 5348 // No D3D12 query must count this internal compute pass as an application dispatch.
4968 end_statistics(); 5349 end_statistics();
4969 vk.emit_counted_dispatch(command_buffer, p.counted_dispatch); 5350 vk.emit_counted_dispatch(command_buffer, p.counted_dispatch);
@@ -4983,14 +5364,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_
4983 vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), 5364 vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data),
4984 &data); 5365 &data);
4985 } 5366 }
4986 for (std::uint32_t k = 0; k < ind->max_count; ++k) { 5367 for (std::uint32_t k = 0; k < records; ++k) {
4987 vk.dispatch_indirect(command_buffer, 5368 vk.dispatch_indirect(command_buffer, indirect_buffer, arguments + VkDeviceSize(k) * stride);
4988 p.indirect_clamp.buffer ? p.indirect_clamp.buffer :
4989 p.counted_dispatch.indirect ? p.counted_dispatch.indirect : p.binding.buffer,
4990 (p.indirect_clamp.buffer ? p.indirect_clamp.offset + VkDeviceSize(k) * p.indirect_clamp.stride
4991 : p.counted_dispatch.indirect ? p.counted_dispatch.offset + VkDeviceSize(k) * 12
4992 : arguments + VkDeviceSize(k) * ind->stride));
4993 } 5369 }
5370 if constexpr (Checkpoints) checkpoints->dispatched(command_buffer);
4994 } else if (const auto* xdxr_build = std::get_if<BuildAccelerationStructure>(&command); 5371 } else if (const auto* xdxr_build = std::get_if<BuildAccelerationStructure>(&command);
4995 xdxr_build && vk.xdxr_record) { 5372 xdxr_build && vk.xdxr_record) {
4996 vk.xdxr_record(command_buffer, *xdxr_build, p.xdxr_blases); 5373 vk.xdxr_record(command_buffer, *xdxr_build, p.xdxr_blases);
@@ -5107,10 +5484,21 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_
5107 } 5484 }
5108 vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), &data); 5485 vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), &data);
5109 vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z); 5486 vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z);
5487 if constexpr (Checkpoints) checkpoints->dispatched(command_buffer);
5110 } else if (raster.state) { 5488 } else if (raster.state) {
5111 const Draw* draw = raster.state; 5489 const Draw* draw = raster.state;
5112 const detail::PreparedDraw& d = prepared.draws[p.draw]; 5490 const detail::PreparedDraw& d = prepared.draws[p.draw];
5113 if (d.skipped) continue; // could not be resolved in prepare: dropped 5491 if (d.skipped) continue; // could not be resolved in prepare: dropped
5492 // The clamp pass for a stateful indirect draw (vulkan_indirect_clamp.h) runs before vkCmdBeginRendering,
5493 // because its copy and transfer barrier are not allowed inside a dynamic-rendering scope. It is a helper
5494 // dispatch, so a pipeline-statistics query must not count it, and it runs even under a false predicate.
5495 if (p.indirect_clamp.buffer != VK_NULL_HANDLE) {
5496 end_statistics();
5497 if (predicate.buffer) vk.end_conditional_rendering(command_buffer);
5498 vk.emit_indirect_clamp(command_buffer, p.indirect_clamp);
5499 if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate);
5500 begin_statistics();
5501 }
5114 if constexpr (Checkpoints) 5502 if constexpr (Checkpoints)
5115 checkpoints->record(command_buffer, i, CheckpointKind::draw, 5503 checkpoints->record(command_buffer, i, CheckpointKind::draw,
5116 d.pipeline, draw->pipeline); 5504 d.pipeline, draw->pipeline);
@@ -5220,6 +5608,12 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_
5220 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); 5608 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front);
5221 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); 5609 vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back);
5222 vk.set_blend_constants(command_buffer, draw->blend_factor.data()); 5610 vk.set_blend_constants(command_buffer, draw->blend_factor.data());
5611 if (graphics.depth_bounds) {
5612 // Vulkan takes bounds in [0, 1] only (without VK_EXT_depth_range_unrestricted), as D3D12 does.
5613 const float lo = std::clamp(draw->depth_bounds[0], 0.0f, 1.0f);
5614 const float hi = std::clamp(draw->depth_bounds[1], 0.0f, 1.0f);
5615 vk.set_depth_bounds(command_buffer, lo, hi);
5616 }
5223 for (std::uint32_t slot = 0; slot < d.vertex_buffers.size(); ++slot) { 5617 for (std::uint32_t slot = 0; slot < d.vertex_buffers.size(); ++slot) {
5224 if (!d.vertex_buffers[slot]) continue; 5618 if (!d.vertex_buffers[slot]) continue;
5225 vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot], 5619 vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot],
@@ -5234,14 +5628,29 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_
5234 const VkDeviceSize bytes = draw->index.size - draw->index.size % width; 5628 const VkDeviceSize bytes = draw->index.size - draw->index.size % width;
5235 vk.bind_robust_index_view(command_buffer, d.index_buffer, d.index_offset, bytes, d.index_type); 5629 vk.bind_robust_index_view(command_buffer, d.index_buffer, d.index_offset, bytes, d.index_type);
5236 } 5630 }
5237 const auto stride = p.indirect_clamp.buffer ? p.indirect_clamp.stride : arg.stride; 5631 // What the draw reads: the clamp pass's scratch (and its clamped count) when it ran, else the
5238 if (arg.count_buffer) { 5632 // application's own buffer. Its records and stride are the clamp's then, not the signature's.
5633 const bool clamped = p.indirect_clamp.buffer != VK_NULL_HANDLE;
5634 const VkBuffer arguments_buffer = clamped ? p.indirect_clamp.buffer : d.indirect_buffer;
5635 const VkDeviceSize arguments_offset = clamped ? p.indirect_clamp.offset : d.indirect_offset;
5636 const VkBuffer count_buffer = clamped ? p.indirect_clamp.count_buffer : d.indirect_count_buffer;
5637 const VkDeviceSize count_offset = clamped ? p.indirect_clamp.count_offset : d.indirect_count_offset;
5638 const std::uint32_t records = clamped ? p.indirect_clamp.records : arg.max_count;
5639 const std::uint32_t stride = clamped ? p.indirect_clamp.stride : arg.stride;
5640 if (draw->mesh) {
5641 if (arg.count_buffer)
5642 vk.draw_mesh_tasks_indirect_count(command_buffer, arguments_buffer, arguments_offset, count_buffer,
5643 count_offset, records, stride);
5644 else
5645 vk.draw_mesh_tasks_indirect(command_buffer, arguments_buffer, arguments_offset, records, stride);
5646 if (vk.mesh_draw_count) ++*vk.mesh_draw_count;
5647 } else if (arg.count_buffer) {
5239 const auto emit_counted = draw->indexed ? vk.draw_indexed_indirect_count : vk.draw_indirect_count; 5648 const auto emit_counted = draw->indexed ? vk.draw_indexed_indirect_count : vk.draw_indirect_count;
5240 emit_counted(command_buffer, d.indirect_buffer, d.indirect_offset, d.indirect_count_buffer, 5649 emit_counted(command_buffer, arguments_buffer, arguments_offset, count_buffer, count_offset,
5241 d.indirect_count_offset, arg.max_count, stride); 5650 records, stride);
5242 } else { 5651 } else {
5243 const auto emit_fixed = draw->indexed ? vk.draw_indexed_indirect : vk.draw_indirect; 5652 const auto emit_fixed = draw->indexed ? vk.draw_indexed_indirect : vk.draw_indirect;
5244 emit_fixed(command_buffer, d.indirect_buffer, d.indirect_offset, arg.max_count, stride); 5653 emit_fixed(command_buffer, arguments_buffer, arguments_offset, records, stride);
5245 } 5654 }
5246 } else if (draw->mesh) { 5655 } else if (draw->mesh) {
5247 vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); 5656 vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first);
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h
index 3e6a8eab8..958f27ca5 100644
--- a/runtime/src/vulkan_scratch.h
+++ b/runtime/src/vulkan_scratch.h
@@ -44,10 +44,13 @@ public:
44 44
45 // `usage` is what the chunks are created with. A chunk that declares VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT 45 // `usage` is what the chunks are created with. A chunk that declares VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT
46 // gets its device address from get() as well, and its memory must have been allocated with 46 // gets its device address from get() as well, and its memory must have been allocated with
47 // VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT (the allocate callback's job). 47 // VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT (the allocate callback's job). `families` keeps retired chunks shareable
48 // across queue families (graphics + async compute).
48 ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, 49 ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate,
49 DeviceFaultDiagnostics* diagnostics, VkBufferUsageFlags usage) 50 DeviceFaultDiagnostics* diagnostics, VkBufferUsageFlags usage,
51 std::vector<std::uint32_t> families = {})
50 : device_(device), diagnostics_(diagnostics), allocate_(std::move(allocate)), usage_(usage), 52 : device_(device), diagnostics_(diagnostics), allocate_(std::move(allocate)), usage_(usage),
53 families_(std::move(families)),
51 addressable_((usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0) { 54 addressable_((usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) != 0) {
52 loaded_ = vk_.load(get, device, addressable_); 55 loaded_ = vk_.load(get, device, addressable_);
53 } 56 }
diff --git a/runtime/test/big_compile_gate_test.cpp b/runtime/test/big_compile_gate_test.cpp
new file mode 100644
index 000000000..a012ac9f9
--- /dev/null
+++ b/runtime/test/big_compile_gate_test.cpp
@@ -0,0 +1,532 @@
1// LargeModuleGate with a budget that is read (runtime/src/large_module_gate.h): who gets in, in which order and when, and
2// the settings. The threads that wait for a place are real; every check that waits for one gives up after 10 s, so a
3// missing wake-up fails the test and does not hang it. Fixed budgets (vk_pipeline_check's) are large_module_gate_test.cpp's.
4// No Vulkan.
5#include "../src/large_module_gate.h"
6
7#include <atomic>
8#include <chrono>
9#include <condition_variable>
10#include <cstdint>
11#include <cstdio>
12#include <cstdlib>
13#include <functional>
14#include <memory>
15#include <mutex>
16#include <thread>
17#include <vector>
18
19namespace {
20
21using namespace std::chrono_literals;
22using leonida::LargeModuleGate;
23using Work = LargeModuleGate::Work;
24
25// Ends the process: the threads that the failed check left waiting would keep the rest from ending.
26#define CHECK(condition) do { \
27 if (!(condition)) { \
28 std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \
29 std::fflush(stderr); \
30 std::_Exit(1); \
31 } \
32} while (0)
33
34bool eventually(const std::function<bool()>& what) {
35 const auto end = std::chrono::steady_clock::now() + 10s;
36 while (!what()) {
37 if (std::chrono::steady_clock::now() > end) return false;
38 std::this_thread::sleep_for(1ms);
39 }
40 return true;
41}
42
43// A thread in enter() for one estimate, which keeps its place until leave() is called.
44class Entrant {
45public:
46 Entrant(LargeModuleGate& gate, std::uint64_t estimate, Work work = Work::demand) {
47 thread_ = std::thread([&gate, estimate, work, this] {
48 LargeModuleGate::Ticket place(gate, estimate, work);
49 in_ = true;
50 std::unique_lock lock(mutex_);
51 go_.wait(lock, [this] { return leave_; });
52 lock.unlock();
53 });
54 }
55 ~Entrant() {
56 if (thread_.joinable()) {
57 leave();
58 join();
59 }
60 }
61 Entrant(const Entrant&) = delete;
62 Entrant& operator=(const Entrant&) = delete;
63 bool in() const { return in_; }
64 void leave() {
65 std::lock_guard lock(mutex_);
66 leave_ = true;
67 go_.notify_all();
68 }
69 void join() { thread_.join(); }
70
71private:
72 std::atomic<bool> in_{false};
73 std::mutex mutex_;
74 std::condition_variable go_;
75 bool leave_ = false;
76 std::thread thread_;
77};
78
79bool waiting(LargeModuleGate& gate, Work work, std::size_t count) {
80 return eventually([&] { return gate.waiting(work) == count; });
81}
82bool in(const Entrant& e) { return eventually([&] { return e.in(); }); }
83// The time a wrong admission would need to happen.
84bool stays_out(const Entrant& e) {
85 std::this_thread::sleep_for(50ms);
86 return !e.in();
87}
88
89LargeModuleGate fixed(std::uint64_t budget) {
90 return LargeModuleGate([budget] { return budget; });
91}
92
93void bound_and_one_always() {
94 auto gate = fixed(10);
95 Entrant big(gate, 25); // more than the whole budget: it compiles alone
96 CHECK(in(big));
97 Entrant first(gate, 6), second(gate, 4);
98 CHECK(stays_out(first) && stays_out(second));
99 big.leave();
100 big.join();
101 CHECK(in(first) && in(second)); // 10 fits exactly
102 Entrant third(gate, 1);
103 CHECK(waiting(gate, Work::demand, 1) && stays_out(third));
104 first.leave();
105 CHECK(in(third));
106 CHECK(gate.inflight() == 2);
107 second.leave();
108 third.leave();
109 second.join();
110 third.join();
111 first.join();
112 CHECK(eventually([&] { return gate.inflight() == 0; }));
113}
114
115// Whatever the sizes, what is in fits, or is one alone; everything gets in, once.
116void many_threads() {
117 for (const std::uint64_t budget : {0u, 1u, 10u, 40u}) {
118 auto gate = fixed(budget);
119 std::atomic<std::uint64_t> used{0};
120 std::atomic<unsigned> inside{0}, most{0};
121 std::atomic<int> over{0}, done{0};
122 std::vector<std::thread> threads;
123 for (unsigned t = 0; t < 8; ++t)
124 threads.emplace_back([&, t] {
125 for (unsigned i = 0; i < 150; ++i) {
126 const std::uint64_t estimate = 1 + (t * 7 + i) % 13;
127 const LargeModuleGate::Ticket place(gate, estimate,
128 (t + i) % 3 ? Work::demand : Work::speculative);
129 const std::uint64_t sum = used += estimate;
130 const unsigned n = ++inside;
131 if (sum > budget && n > 1) ++over;
132 unsigned m = most;
133 while (n > m && !most.compare_exchange_weak(m, n)) {}
134 for (int spin = 0; spin < 20; ++spin) std::this_thread::yield();
135 --inside;
136 used -= estimate;
137 ++done;
138 }
139 });
140 for (auto& t : threads) t.join();
141 CHECK(over == 0);
142 CHECK(done == 8 * 150);
143 CHECK(gate.inflight() == 0);
144 CHECK(budget < 40 || most > 1); // and where there is room, several are in
145 }
146}
147
148// Those that wait get in in the order they came, but for what fits now and also beside the first in line: that one finds
149// its room when those that were in before it leave, whatever passed it.
150void order() {
151 auto gate = fixed(10);
152 Entrant first(gate, 8);
153 CHECK(in(first));
154 Entrant big(gate, 9);
155 CHECK(waiting(gate, Work::demand, 1));
156 Entrant in_the_way(gate, 2); // it fits beside the first, and not beside the big one
157 CHECK(waiting(gate, Work::demand, 2));
158 Entrant little(gate, 1);
159 CHECK(in(little));
160 Entrant next(gate, 1); // beside the big one there is room for one of these
161 CHECK(waiting(gate, Work::demand, 3));
162 CHECK(stays_out(big) && stays_out(in_the_way) && stays_out(next));
163 little.leave();
164 little.join();
165 CHECK(stays_out(big) && stays_out(in_the_way) && stays_out(next)); // nor when the one that passed has left
166 first.leave();
167 CHECK(in(big));
168 CHECK(in(next)); // the first in line is now in_the_way, which it can pass
169 CHECK(stays_out(in_the_way));
170 big.leave();
171 CHECK(in(in_the_way));
172 in_the_way.leave();
173 next.leave();
174}
175
176// What passes the first in line is bounded: a stream of small ones does not keep it out.
177void a_stream_of_small_ones_does_not_keep_out() {
178 auto gate = fixed(100);
179 Entrant first(gate, 50);
180 CHECK(in(first));
181 Entrant big(gate, 70);
182 CHECK(waiting(gate, Work::demand, 1));
183 std::vector<std::unique_ptr<Entrant>> stream;
184 for (int i = 0; i < 3; ++i) { // 30 beside the big one's 70, one after another
185 stream.push_back(std::make_unique<Entrant>(gate, 10));
186 CHECK(in(*stream.back()));
187 if (i < 2) { // one of them stays in
188 stream.back()->leave();
189 stream.back()->join();
190 }
191 }
192 Entrant more(gate, 10);
193 CHECK(waiting(gate, Work::demand, 2));
194 CHECK(stays_out(more)); // it fits (70 of 100 with the rest), but the first in line has been passed enough
195 first.leave();
196 CHECK(in(big)); // 10 of the stream and 70
197 CHECK(in(more));
198 big.leave();
199 more.leave();
200 stream.back()->leave();
201}
202
203// Of those that can pass, the one that came first does.
204void those_that_pass_keep_their_order() {
205 for (int round = 0; round < 10; ++round) {
206 auto gate = fixed(20);
207 Entrant first(gate, 15), other(gate, 5);
208 CHECK(in(first) && in(other));
209 Entrant big(gate, 12);
210 CHECK(waiting(gate, Work::demand, 1));
211 Entrant a(gate, 4);
212 CHECK(waiting(gate, Work::demand, 2));
213 Entrant b(gate, 4);
214 CHECK(waiting(gate, Work::demand, 3));
215 other.leave();
216 CHECK(in(a));
217 CHECK(stays_out(b) && stays_out(big)); // 19 of 20
218 first.leave();
219 CHECK(in(big) && in(b));
220 big.leave();
221 a.leave();
222 b.leave();
223 }
224}
225
226// One that needs the machine for itself is not passed: what got in beside it would keep it out.
227void larger_than_the_budget_is_not_passed() {
228 auto gate = fixed(10);
229 Entrant first(gate, 5);
230 CHECK(in(first));
231 Entrant alone(gate, 25);
232 CHECK(waiting(gate, Work::demand, 1));
233 Entrant little(gate, 1);
234 CHECK(waiting(gate, Work::demand, 2));
235 CHECK(stays_out(little));
236 first.leave();
237 CHECK(in(alone));
238 CHECK(stays_out(little));
239 alone.leave();
240 CHECK(in(little));
241 little.leave();
242}
243
244// The same for the speculative ones, within their quarter.
245void speculative_ones_pass_each_other() {
246 auto gate = fixed(100);
247 Entrant first(gate, 20, Work::speculative);
248 CHECK(in(first));
249 Entrant big(gate, 18, Work::speculative);
250 CHECK(waiting(gate, Work::speculative, 1));
251 Entrant little(gate, 5, Work::speculative);
252 CHECK(in(little)); // 25 of 25, and 23 with the big one
253 Entrant next(gate, 1, Work::speculative);
254 CHECK(waiting(gate, Work::speculative, 2));
255 little.leave();
256 little.join();
257 CHECK(in(next)); // 21 of 25, and 24 of what may pass
258 Entrant over(gate, 2, Work::speculative);
259 CHECK(waiting(gate, Work::speculative, 2));
260 CHECK(stays_out(over) && stays_out(big)); // it would be 26
261 first.leave();
262 CHECK(in(big) && in(over));
263 big.leave();
264 next.leave();
265 over.leave();
266}
267
268// The first in the queue leaves it, and the next one, which fits as well, gets in at once and not when something leaves.
269void one_admission_wakes_the_next() {
270 auto gate = fixed(10);
271 Entrant first(gate, 10);
272 CHECK(in(first));
273 Entrant a(gate, 4), b(gate, 4), c(gate, 2);
274 CHECK(waiting(gate, Work::demand, 3));
275 first.leave();
276 CHECK(in(a) && in(b) && in(c));
277 CHECK(gate.inflight() == 3);
278 a.leave();
279 b.leave();
280 c.leave();
281}
282
283void leaving_wakes_all_that_fit() {
284 auto gate = fixed(10);
285 Entrant a(gate, 5), b(gate, 5);
286 CHECK(in(a) && in(b));
287 Entrant c(gate, 3), d(gate, 2);
288 CHECK(waiting(gate, Work::demand, 2) && stays_out(c));
289 a.leave();
290 CHECK(in(c) && in(d));
291 b.leave();
292 c.leave();
293 d.leave();
294}
295
296// What a submission waits for goes first, whenever it came.
297void demand_before_speculative() {
298 auto gate = fixed(10);
299 Entrant first(gate, 10);
300 CHECK(in(first));
301 Entrant speculative(gate, 1, Work::speculative);
302 CHECK(waiting(gate, Work::speculative, 1));
303 Entrant demand(gate, 9);
304 CHECK(waiting(gate, Work::demand, 1));
305 first.leave();
306 CHECK(in(demand)); // the speculative one came first and would have fitted
307 CHECK(stays_out(speculative));
308 demand.leave();
309 CHECK(in(speculative));
310 speculative.leave();
311}
312
313// Waiting demand keeps out speculative work that fits, also the one that is first in line.
314void waiting_demand_keeps_speculative_out() {
315 auto gate = fixed(100);
316 Entrant first(gate, 40, Work::demand);
317 CHECK(in(first));
318 Entrant blocked(gate, 100); // waits for the first
319 CHECK(waiting(gate, Work::demand, 1));
320 Entrant speculative(gate, 5, Work::speculative); // a quarter holds it
321 CHECK(waiting(gate, Work::speculative, 1));
322 CHECK(stays_out(speculative));
323 first.leave();
324 CHECK(in(blocked));
325 CHECK(stays_out(speculative));
326 blocked.leave();
327 CHECK(in(speculative));
328 speculative.leave();
329}
330
331// While a submission has more to build, the room between two of its modules is not a speculative one's.
332void a_demand_keeps_speculative_out() {
333 auto gate = fixed(100);
334 auto one = std::make_unique<LargeModuleGate::Demand>(gate), other = std::make_unique<LargeModuleGate::Demand>(gate);
335 Entrant speculative(gate, 10, Work::speculative);
336 CHECK(waiting(gate, Work::speculative, 1));
337 CHECK(stays_out(speculative)); // it fits, and nothing is in
338 for (int i = 0; i < 2; ++i) {
339 Entrant built(gate, 10);
340 CHECK(in(built));
341 built.leave();
342 built.join();
343 CHECK(stays_out(speculative)); // between two of the submission's modules
344 }
345 one.reset();
346 CHECK(stays_out(speculative)); // another submission has some
347 other.reset();
348 CHECK(in(speculative)); // the end of the last one wakes it
349 speculative.leave();
350}
351
352// A speculative one gets in within a quarter of the budget, and what is free of it is there for a demand.
353void speculative_share() {
354 auto gate = fixed(100);
355 Entrant demand(gate, 30);
356 CHECK(in(demand));
357 Entrant over(gate, 26, Work::speculative); // 56 of 100, but more than 25 with the rest
358 CHECK(waiting(gate, Work::speculative, 1));
359 CHECK(stays_out(over));
360 demand.leave();
361 CHECK(in(over)); // alone, whatever its size
362 Entrant quick(gate, 70);
363 CHECK(in(quick)); // 96 of 100: the speculative one does not count against it
364 quick.leave();
365 over.leave();
366 quick.join();
367 over.join();
368 CHECK(eventually([&] { return gate.inflight() == 0; }));
369 Entrant share(gate, 25, Work::speculative);
370 CHECK(in(share));
371 Entrant second(gate, 1, Work::speculative);
372 CHECK(waiting(gate, Work::speculative, 1)); // one more byte is past the quarter
373 CHECK(stays_out(second));
374 Entrant next(gate, 75);
375 CHECK(in(next)); // the whole rest
376 CHECK(stays_out(second));
377 next.leave();
378 share.leave();
379 CHECK(in(second));
380 second.leave();
381}
382
383// Speculative ones get in in the order they came, and alone when nothing is in.
384void speculative_order_and_alone() {
385 auto gate = fixed(0); // unknown memory: one at a time
386 Entrant a(gate, 5, Work::speculative);
387 CHECK(in(a));
388 Entrant b(gate, 5, Work::speculative);
389 CHECK(waiting(gate, Work::speculative, 1));
390 Entrant c(gate, 5, Work::demand);
391 CHECK(waiting(gate, Work::demand, 1));
392 CHECK(stays_out(b) && stays_out(c));
393 a.leave();
394 CHECK(in(c));
395 CHECK(stays_out(b));
396 c.leave();
397 CHECK(in(b));
398 b.leave();
399}
400
401// The budget is read when a place is asked for and when one is given back, not once.
402void budget_follows_the_moment() {
403 std::atomic<std::uint64_t> free{100};
404 LargeModuleGate gate([&] { return free.load(); });
405 CHECK(gate.budget() == 100);
406 Entrant a(gate, 30), b(gate, 10);
407 CHECK(in(a) && in(b));
408 free = 35;
409 Entrant c(gate, 20); // 60 of 100 a moment ago
410 CHECK(waiting(gate, Work::demand, 1));
411 CHECK(stays_out(c));
412 free = 100;
413 b.leave();
414 CHECK(in(c)); // 50 of 100 now; it would not be within 35
415 CHECK(gate.inflight() == 2);
416 a.leave();
417 c.leave();
418 a.join();
419 c.join();
420 // A budget that shrinks while a module is in does not throw it out, and holds the next.
421 Entrant d(gate, 100);
422 CHECK(in(d));
423 free = 1;
424 Entrant e(gate, 1);
425 CHECK(waiting(gate, Work::demand, 1));
426 CHECK(stays_out(e));
427 CHECK(gate.inflight() == 1);
428 d.leave();
429 CHECK(in(e));
430}
431
432// An estimate counts for as long as its module is in, whatever the driver has taken of it already.
433void estimates_stay_reserved() {
434 auto gate = fixed(100); // the driver has taken nothing yet: the memory is all there
435 Entrant a(gate, 60);
436 CHECK(in(a));
437 Entrant b(gate, 60);
438 CHECK(waiting(gate, Work::demand, 1));
439 CHECK(stays_out(b));
440 a.leave();
441 CHECK(in(b));
442 b.leave();
443}
444
445// A ticket gives its place back once, however it ends.
446void tickets() {
447 auto gate = fixed(10);
448 {
449 LargeModuleGate::Ticket a(gate, 6, Work::speculative);
450 LargeModuleGate::Ticket moved = std::move(a);
451 CHECK(gate.inflight() == 1);
452 LargeModuleGate::Ticket b;
453 b = LargeModuleGate::Ticket(gate, 3);
454 CHECK(gate.inflight() == 2);
455 b.release();
456 b.release();
457 CHECK(gate.inflight() == 1);
458 }
459 CHECK(gate.inflight() == 0);
460}
461
462// The memory budget's setting: what it says, and nothing else.
463void settings() {
464 using leonida::large_compile_budget;
465 const auto check = [](const char* text, bool valid, bool has, std::uint64_t mib) {
466 const auto s = large_compile_budget(text);
467 CHECK(s.valid == valid);
468 CHECK(s.fixed.has_value() == has);
469 if (has) CHECK(*s.fixed == mib << 20);
470 };
471 check(nullptr, true, false, 0);
472 check("", true, false, 0);
473 check("0", true, true, 0);
474 check("1", true, true, 1);
475 check("512", true, true, 512);
476 check("0512", true, true, 512);
477 check("12a", false, false, 0);
478 check(" 5", false, false, 0);
479 check("-1", false, false, 0);
480 check("1.5", false, false, 0);
481 check("99999999999999999999999", true, true, UINT64_MAX >> 20); // saturates: no limit, not a small number
482 CHECK(*large_compile_budget("99999999999999999999999").fixed >= (UINT64_MAX >> 20) << 20);
483}
484
485// The share of the memory, and what the machine gives now: nothing unknown on Windows and Linux, and no more than three
486// quarters of either limit.
487void machine() {
488 using leonida::large_compile_share;
489 CHECK(large_compile_share(1000, 4000) == 750);
490 CHECK(large_compile_share(4000, 1000) == 750); // the commit limit has less room than the RAM
491 CHECK(large_compile_share(0, 4000) == 0);
492 const std::uint64_t budget = leonida::large_compile_budget_bytes();
493#if defined(_WIN32) || defined(__linux__)
494 CHECK(budget > 0);
495#endif
496 // Read a moment apart on a running machine: the budget may not exceed either limit by more than that moment.
497 const std::uint64_t slack = std::uint64_t(256) << 20;
498 CHECK(budget <= leonida::available_memory_bytes() / 4 * 3 + slack);
499 CHECK(leonida::large_module_estimate(1 << 20) == (std::uint64_t(1) << 20) * leonida::kBytesPerSpirvByte);
500#ifdef _WIN32
501 MEMORYSTATUSEX status{};
502 status.dwLength = sizeof(status);
503 CHECK(GlobalMemoryStatusEx(&status) != 0);
504 CHECK(budget <= status.ullAvailPageFile / 4 * 3 + slack);
505#endif
506}
507
508} // namespace
509
510int main() {
511 bound_and_one_always();
512 many_threads();
513 order();
514 a_stream_of_small_ones_does_not_keep_out();
515 those_that_pass_keep_their_order();
516 larger_than_the_budget_is_not_passed();
517 speculative_ones_pass_each_other();
518 one_admission_wakes_the_next();
519 leaving_wakes_all_that_fit();
520 demand_before_speculative();
521 waiting_demand_keeps_speculative_out();
522 a_demand_keeps_speculative_out();
523 speculative_share();
524 speculative_order_and_alone();
525 budget_follows_the_moment();
526 estimates_stay_reserved();
527 tickets();
528 settings();
529 machine();
530 std::puts("big_compile_gate: ok");
531 return 0;
532}
diff --git a/runtime/test/big_compute_module.h b/runtime/test/big_compute_module.h
new file mode 100644
index 000000000..28dde996f
--- /dev/null
+++ b/runtime/test/big_compute_module.h
@@ -0,0 +1,298 @@
1// Large compute modules that are work for a driver's compiler, not padding: a register file in a Function array that every
2// instruction loads from and stores to (as the translator's modules have it), integer instructions, selections, nested
3// conditionals and loops, and loads from memory the compiler knows nothing about. The same instructions run on the CPU, so
4// the value that a dispatch stores is known. Made from a seed; no game data.
5#pragma once
6
7#include <cstddef>
8#include <cstdint>
9#include <initializer_list>
10#include <random>
11#include <utility>
12#include <vector>
13
14namespace bigmodule {
15
16using Words = std::vector<std::uint32_t>;
17
18inline void op(Words& out, std::uint16_t code, std::initializer_list<std::uint32_t> operands) {
19 out.push_back((std::uint32_t(operands.size() + 1) << 16) | code);
20 out.insert(out.end(), operands.begin(), operands.end());
21}
22
23enum class Kind : std::uint8_t { add, sub, mul, xor_, and_, or_, shl, shr, select, load, if_, end_if, loop, end_loop };
24
25struct Instruction {
26 Kind kind;
27 std::uint8_t d = 0, a = 0, b = 0, c = 0; // registers; c is a shift count or a loop count for those kinds
28};
29
30constexpr unsigned kRegisters = 48, kConstants = 64, kDepth = 3;
31constexpr unsigned kLoadBase = 256, kLoadWords = 64; // the words of the buffer the loads read (the CPU takes them as 0)
32
33struct Program {
34 std::vector<Instruction> code;
35 std::uint32_t constants[kConstants];
36
37 // What the module stores for the dispatch with this root constant.
38 std::uint32_t run(std::uint32_t root_constant) const {
39 std::uint32_t v[kRegisters];
40 for (unsigned i = 0; i < kRegisters; ++i) v[i] = constants[i % kConstants] ^ (root_constant + i);
41 walk(0, v);
42 std::uint32_t out = 0;
43 for (unsigned i = 0; i < kRegisters; ++i) out ^= v[i];
44 return out;
45 }
46
47private:
48 // Runs from `at` to the end marker of its block and returns the index after it.
49 std::size_t walk(std::size_t at, std::uint32_t* v) const {
50 for (; at < code.size();) {
51 const Instruction& i = code[at];
52 const std::uint32_t k = constants[i.c % kConstants];
53 switch (i.kind) {
54 case Kind::add: v[i.d] = v[i.a] + v[i.b] + k; break;
55 case Kind::sub: v[i.d] = v[i.a] - v[i.b] - k; break;
56 case Kind::mul: v[i.d] = v[i.a] * v[i.b] * k; break;
57 case Kind::xor_: v[i.d] = v[i.a] ^ v[i.b] ^ k; break;
58 case Kind::and_: v[i.d] = v[i.a] & (v[i.b] | k); break;
59 case Kind::or_: v[i.d] = v[i.a] | (v[i.b] & k); break;
60 case Kind::shl: v[i.d] = (v[i.a] << (i.c & 31)) ^ v[i.b]; break;
61 case Kind::shr: v[i.d] = (v[i.a] >> (i.c & 31)) ^ v[i.b]; break;
62 case Kind::select: v[i.d] = v[i.a] < v[i.b] ? v[i.c % kRegisters] : v[i.a]; break;
63 case Kind::load: v[i.d] = v[i.b]; break; // + the loaded word, which is 0
64 case Kind::if_: {
65 std::size_t after = at + 1;
66 if (v[i.a] < v[i.b])
67 after = walk(at + 1, v);
68 else
69 after = skip(at + 1);
70 at = after;
71 continue;
72 }
73 case Kind::loop: {
74 std::size_t after = at + 1;
75 for (unsigned n = 0; n < i.c; ++n) after = walk(at + 1, v);
76 at = after;
77 continue;
78 }
79 case Kind::end_if:
80 case Kind::end_loop: return at + 1;
81 }
82 ++at;
83 }
84 return at;
85 }
86 std::size_t skip(std::size_t at) const {
87 for (int depth = 1; at < code.size(); ++at) {
88 const Kind k = code[at].kind;
89 if (k == Kind::if_ || k == Kind::loop) ++depth;
90 if ((k == Kind::end_if || k == Kind::end_loop) && !--depth) return at + 1;
91 }
92 return at;
93 }
94};
95
96// A module of about `bytes` bytes of SPIR-V (a few KiB more), and the program it runs. `seed` decides everything. It has the
97// translator's push-constant block: s[4]:s[5] is the console VA of a root UAV, s[6] a root constant. A dispatch stores
98// Program::run(s[6]) at the UAV's word s[6], and reads its words kLoadBase to kLoadBase + kLoadWords - 1, which have to
99// be 0.
100inline Words make(std::size_t bytes, std::uint64_t seed, Program* out = nullptr) {
101 std::mt19937_64 random(seed);
102 Program program;
103 for (auto& c : program.constants) c = std::uint32_t(random());
104 // Ids.
105 enum : std::uint32_t {
106 id_void = 1, id_fn, id_main, id_uint, id_ulong, id_bool, id_block, id_sarr, id_c32, id_ptr_push_block,
107 id_push, id_ptr_push_uint, id_ptr_push_ulong, id_data, id_ptr_data, id_ptr_phys_uint, id_regs, id_cregs,
108 id_ptr_regs, id_ptr_fn_uint, id_vregs, id_entry, id_c64_32, id_c64_2, id_mask, id_base,
109 id_index0 = 40, // uint constants 0..127
110 id_const0 = id_index0 + 128, // the program's constants
111 id_counter0 = id_const0 + kConstants, // loop counters by depth
112 id_first = id_counter0 + kDepth + 1,
113 };
114 std::uint32_t next = id_first;
115 Words w = {0x07230203u, 0x00010500u, 0u, 0u, 0u};
116 op(w, 17, {1}); // Shader
117 op(w, 17, {11}); // Int64
118 op(w, 17, {5347}); // PhysicalStorageBufferAddresses
119 op(w, 14, {5348, 1});
120 op(w, 15, {5, id_main, 0x6e69616du, 0u, id_push});
121 op(w, 16, {id_main, 17, 1, 1, 1});
122 op(w, 71, {id_sarr, 6, 4});
123 op(w, 71, {id_block, 2});
124 op(w, 72, {id_block, 0, 35, 0});
125 op(w, 72, {id_block, 1, 35, 128});
126 op(w, 72, {id_block, 2, 35, 136});
127 op(w, 71, {id_data, 2});
128 op(w, 72, {id_data, 0, 35, 0});
129 op(w, 19, {id_void});
130 op(w, 33, {id_fn, id_void});
131 op(w, 21, {id_uint, 32, 0});
132 op(w, 21, {id_ulong, 64, 0});
133 op(w, 20, {id_bool});
134 op(w, 43, {id_uint, id_c32, 32});
135 op(w, 28, {id_sarr, id_uint, id_c32});
136 op(w, 30, {id_block, id_sarr, id_ulong, id_ulong});
137 op(w, 32, {id_ptr_push_block, 9, id_block});
138 op(w, 59, {id_ptr_push_block, id_push, 9});
139 op(w, 32, {id_ptr_push_uint, 9, id_uint});
140 op(w, 32, {id_ptr_push_ulong, 9, id_ulong});
141 op(w, 30, {id_data, id_uint});
142 op(w, 32, {id_ptr_data, 5349, id_data});
143 op(w, 32, {id_ptr_phys_uint, 5349, id_uint});
144 op(w, 43, {id_uint, id_cregs, kRegisters});
145 op(w, 28, {id_regs, id_uint, id_cregs});
146 op(w, 32, {id_ptr_regs, 7, id_regs});
147 op(w, 32, {id_ptr_fn_uint, 7, id_uint});
148 op(w, 43, {id_ulong, id_c64_32, 32, 0});
149 op(w, 43, {id_ulong, id_c64_2, 2, 0});
150 op(w, 43, {id_uint, id_mask, kLoadWords - 1});
151 op(w, 43, {id_uint, id_base, kLoadBase});
152 for (std::uint32_t i = 0; i < 128; ++i) op(w, 43, {id_uint, id_index0 + i, i});
153 for (std::uint32_t i = 0; i < kConstants; ++i) op(w, 43, {id_uint, id_const0 + i, program.constants[i]});
154 op(w, 54, {id_void, id_main, 0, id_fn});
155 op(w, 248, {id_entry});
156 op(w, 59, {id_ptr_regs, id_vregs, 7});
157 for (std::uint32_t i = 0; i <= kDepth; ++i) op(w, 59, {id_ptr_fn_uint, id_counter0 + i, 7});
158 const auto unary = [&](std::uint16_t code, std::uint32_t type, std::uint32_t a) {
159 op(w, code, {type, next, a});
160 return next++;
161 };
162 const auto binary = [&](std::uint16_t code, std::uint32_t type, std::uint32_t a, std::uint32_t b) {
163 op(w, code, {type, next, a, b});
164 return next++;
165 };
166 const auto push_word = [&](std::uint32_t index) {
167 op(w, 65, {id_ptr_push_uint, next, id_push, id_index0, id_index0 + index});
168 return unary(61, id_uint, next++);
169 };
170 const std::uint32_t lo = push_word(4), hi = push_word(5);
171 op(w, 65, {id_ptr_push_ulong, next, id_push, id_index0 + 1});
172 const std::uint32_t heap = unary(61, id_ulong, next++);
173 const std::uint32_t lo64 = unary(113, id_ulong, lo), hi64 = unary(113, id_ulong, hi);
174 const std::uint32_t high = binary(196, id_ulong, hi64, id_c64_32);
175 const std::uint32_t va = binary(197, id_ulong, high, lo64);
176 const std::uint32_t base = binary(128, id_ulong, va, heap);
177 const std::uint32_t root = push_word(6);
178 const auto slot = [&](std::uint32_t r) {
179 op(w, 65, {id_ptr_fn_uint, next, id_vregs, id_index0 + r});
180 return next++;
181 };
182 const auto load_reg = [&](std::uint32_t r) { return unary(61, id_uint, slot(r)); };
183 const auto store_reg = [&](std::uint32_t r, std::uint32_t value) {
184 const std::uint32_t p = slot(r);
185 op(w, 62, {p, value});
186 };
187 for (std::uint32_t i = 0; i < kRegisters; ++i) {
188 const std::uint32_t seeded = binary(128, id_uint, root, id_index0 + i);
189 store_reg(i, binary(198, id_uint, id_const0 + i % kConstants, seeded));
190 }
191 struct Open {
192 Kind kind;
193 std::uint32_t merge, header, cont, counter;
194 unsigned left;
195 };
196 std::vector<Open> open;
197 unsigned loops = 0;
198 const auto pick = [&](std::uint32_t n) { return std::uint8_t(random() % n); };
199 const auto close = [&] {
200 const Open o = open.back();
201 open.pop_back();
202 if (o.kind == Kind::if_) {
203 op(w, 249, {o.merge});
204 op(w, 248, {o.merge});
205 program.code.push_back({Kind::end_if});
206 } else {
207 op(w, 249, {o.cont});
208 op(w, 248, {o.cont});
209 const std::uint32_t n = unary(61, id_uint, o.counter);
210 op(w, 62, {o.counter, binary(128, id_uint, n, id_index0 + 1)});
211 op(w, 249, {o.header});
212 op(w, 248, {o.merge});
213 program.code.push_back({Kind::end_loop});
214 --loops;
215 }
216 };
217 while (w.size() * 4 + 256 < bytes) {
218 const std::uint32_t roll = std::uint32_t(random() % 100);
219 if (roll < 4 && open.size() < kDepth) {
220 const std::uint8_t a = pick(kRegisters), b = pick(kRegisters);
221 const std::uint32_t condition = binary(176, id_bool, load_reg(a), load_reg(b)); // ULessThan
222 const std::uint32_t then = next++, merge = next++;
223 op(w, 247, {merge, 0});
224 op(w, 250, {condition, then, merge});
225 op(w, 248, {then});
226 open.push_back({Kind::if_, merge, 0, 0, 0, 10 + unsigned(random() % 30)});
227 program.code.push_back({Kind::if_, 0, a, b, 0});
228 } else if (roll < 5 && open.size() < kDepth && loops < 1) {
229 const std::uint8_t count = std::uint8_t(2 + random() % 3);
230 const std::uint32_t counter = id_counter0 + loops++;
231 op(w, 62, {counter, id_index0});
232 const std::uint32_t header = next++, check = next++, body = next++, cont = next++, merge = next++;
233 op(w, 249, {header});
234 op(w, 248, {header});
235 op(w, 246, {merge, cont, 0});
236 op(w, 249, {check});
237 op(w, 248, {check});
238 const std::uint32_t n = unary(61, id_uint, counter);
239 const std::uint32_t more = binary(176, id_bool, n, id_index0 + count);
240 op(w, 250, {more, body, merge});
241 op(w, 248, {body});
242 open.push_back({Kind::loop, merge, header, cont, counter, 20 + unsigned(random() % 20)});
243 program.code.push_back({Kind::loop, 0, 0, 0, count});
244 } else {
245 Instruction i{Kind(random() % 10), pick(kRegisters), pick(kRegisters), pick(kRegisters), pick(kConstants)};
246 if (i.kind == Kind::load && random() % 2) i.kind = Kind::add;
247 const std::uint32_t k = id_const0 + i.c % kConstants;
248 std::uint32_t value = 0;
249 const std::uint32_t a = load_reg(i.a), b = load_reg(i.b);
250 switch (i.kind) {
251 case Kind::add: value = binary(128, id_uint, binary(128, id_uint, a, b), k); break;
252 case Kind::sub: value = binary(130, id_uint, binary(130, id_uint, a, b), k); break;
253 case Kind::mul: value = binary(132, id_uint, binary(132, id_uint, a, b), k); break;
254 case Kind::xor_: value = binary(198, id_uint, binary(198, id_uint, a, b), k); break;
255 case Kind::and_: value = binary(199, id_uint, a, binary(197, id_uint, b, k)); break;
256 case Kind::or_: value = binary(197, id_uint, a, binary(199, id_uint, b, k)); break;
257 case Kind::shl: value = binary(198, id_uint, binary(196, id_uint, a, id_index0 + (i.c & 31)), b); break;
258 case Kind::shr: value = binary(198, id_uint, binary(194, id_uint, a, id_index0 + (i.c & 31)), b); break;
259 case Kind::select: {
260 const std::uint32_t c = load_reg(i.c % kRegisters);
261 const std::uint32_t less = binary(176, id_bool, a, b);
262 op(w, 169, {id_uint, next, less, c, a});
263 value = next++;
264 break;
265 }
266 default: { // load
267 const std::uint32_t index = binary(128, id_uint, binary(199, id_uint, a, id_mask), id_base);
268 const std::uint32_t offset = binary(196, id_ulong, unary(113, id_ulong, index), id_c64_2);
269 const std::uint32_t address = binary(128, id_ulong, base, offset);
270 const std::uint32_t data = unary(120, id_ptr_data, address);
271 op(w, 65, {id_ptr_phys_uint, next, data, id_index0});
272 const std::uint32_t pointer = next++;
273 op(w, 61, {id_uint, next, pointer, 2, 4});
274 const std::uint32_t loaded = next++;
275 value = binary(128, id_uint, b, loaded);
276 break;
277 }
278 }
279 store_reg(i.d, value);
280 program.code.push_back(i);
281 }
282 if (!open.empty() && !open.back().left--) close();
283 }
284 while (!open.empty()) close();
285 std::uint32_t result = load_reg(0);
286 for (std::uint32_t i = 1; i < kRegisters; ++i) result = binary(198, id_uint, result, load_reg(i));
287 const std::uint32_t out_offset = binary(196, id_ulong, unary(113, id_ulong, root), id_c64_2);
288 const std::uint32_t out_data = unary(120, id_ptr_data, binary(128, id_ulong, base, out_offset));
289 op(w, 65, {id_ptr_phys_uint, next, out_data, id_index0});
290 op(w, 62, {next++, result, 2, 4});
291 op(w, 253, {});
292 op(w, 56, {});
293 w[3] = next;
294 if (out) *out = std::move(program);
295 return w;
296}
297
298} // namespace bigmodule
diff --git a/runtime/test/check_console_paths.cmake b/runtime/test/check_console_paths.cmake
index bdd74a7d1..9f9a699b1 100644
--- a/runtime/test/check_console_paths.cmake
+++ b/runtime/test/check_console_paths.cmake
@@ -1,12 +1,12 @@
1# Redirect the loader's stdout so both console paths must survive as UTF-8. 1# Redirect the loader's stdout so the console paths (GAME:, the overlay and T:'s folder in it) must survive as UTF-8.
2execute_process( 2execute_process(
3 COMMAND ${RUNNER} "${LOADER}" --game-dir "game-Игра" --overlay "overlay-保存" 3 COMMAND ${RUNNER} "${LOADER}" --game-dir "game-Игра" --overlay "overlay-保存"
4 --run "${GUEST}" -- hello 42 4 --run "${GUEST}" -- hello 42
5 TIMEOUT 90 ENCODING UTF-8 5 TIMEOUT 90 ENCODING UTF-8
6 RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) 6 RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error)
7if(NOT code STREQUAL "0" OR 7if(NOT code STREQUAL "0" OR
8 NOT output MATCHES "console paths: GAME: -> [^\n]*game-Игра, writes -> [^\n]*overlay-保存\r?\n") 8 NOT output MATCHES "console paths: GAME: -> [^\n]*game-Игра, writes -> [^\n]*overlay-保存, T: -> [^\n]*overlay-保存[\\/]\\.gta6rt-temp[\\/][^\n]*pid[0-9]+\r?\n")
9 message(FATAL_ERROR "Runtime did not report both Unicode paths (exit ${code})\n${output}\n${error}") 9 message(FATAL_ERROR "Runtime did not report the Unicode paths (exit ${code})\n${output}\n${error}")
10endif() 10endif()
11if(NOT output MATCHES "(^|\n)tiny_game: OK(\r?\n|$)" OR 11if(NOT output MATCHES "(^|\n)tiny_game: OK(\r?\n|$)" OR
12 NOT output MATCHES "(^|\n)game exited with code 0(\r?\n|$)") 12 NOT output MATCHES "(^|\n)game exited with code 0(\r?\n|$)")
diff --git a/runtime/test/check_game_dir.cmake b/runtime/test/check_game_dir.cmake
index 039a1ade3..1c973fd54 100644
--- a/runtime/test/check_game_dir.cmake
+++ b/runtime/test/check_game_dir.cmake
@@ -1,7 +1,8 @@
1# Run the stand-in game from its own folder by bare name, as a player would (`gta6rt --run game.exe`), and again 1# Run the stand-in game from its own folder by bare name, as a player would (`gta6rt --run game.exe`), and again
2# with `--game-dir .`. In both, GAME: has to name that folder as an absolute path: the guest moves its current 2# with `--game-dir .`. In both, GAME: has to name that folder as an absolute path: the guest moves its current
3# directory away and then reads GAME:\tiny_game_probe.txt (argument game-file). Before, a bare name left GAME: with 3# directory away and then reads GAME:\tiny_game_probe.txt (argument game-file). Before, a bare name left GAME: with
4# an empty root (`console paths: GAME: -> , writes -> overlay`) and the open failed with ERROR_PATH_NOT_FOUND. 4# an empty root (`console paths: GAME: -> , writes -> overlay`) and the open failed with ERROR_PATH_NOT_FOUND. The line
5# also names T:'s folder, this process's own below <overlay>\.gta6rt-temp.
5# The verdict is checked from the output, as check_loaded_gdk.cmake does, because under Wine an exit status alone 6# The verdict is checked from the output, as check_loaded_gdk.cmake does, because under Wine an exit status alone
6# can look successful. 7# can look successful.
7get_filename_component(guest_dir "${GUEST}" DIRECTORY) 8get_filename_component(guest_dir "${GUEST}" DIRECTORY)
@@ -23,7 +24,7 @@ foreach(variant "bare" "dot")
23 # An absolute GAME: root: a drive letter (Windows, and Wine's Z:) or a leading slash, and an overlay inside it. 24 # An absolute GAME: root: a drive letter (Windows, and Wine's Z:) or a leading slash, and an overlay inside it.
24 if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_game: PASS GAME:" 25 if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_game: PASS GAME:"
25 OR NOT output MATCHES "(^|\n)tiny_game: OK(\n|$)" 26 OR NOT output MATCHES "(^|\n)tiny_game: OK(\n|$)"
26 OR NOT output MATCHES "(^|\n)console paths: GAME: -> ([A-Za-z]:|[\\/])[^\n]*, writes -> ([A-Za-z]:|[\\/])[^\n]*overlay(\n|$)" 27 OR NOT output MATCHES "(^|\n)console paths: GAME: -> ([A-Za-z]:|[\\/])[^\n]*, writes -> ([A-Za-z]:|[\\/])[^\n]*overlay, T: -> ([A-Za-z]:|[\\/])[^\n]*overlay[\\/]\\.gta6rt-temp[\\/][0-9]+-[0-9]+-[0-9]+-pid[0-9]+(\n|$)"
27 OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)") 28 OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)")
28 string(APPEND failures "--- ${variant}: returned ${code}\n${output}\n") 29 string(APPEND failures "--- ${variant}: returned ${code}\n${output}\n")
29 endif() 30 endif()
diff --git a/runtime/test/compile_helper_test.cpp b/runtime/test/compile_helper_test.cpp
new file mode 100644
index 000000000..7ef8d176e
--- /dev/null
+++ b/runtime/test/compile_helper_test.cpp
@@ -0,0 +1,176 @@
1// The compile helper's file protocol (shims/d3d12_compile_helper.h): request lines, their order, and the markers that
2// keep two processes from compiling one entry at once. No Vulkan, no helper process.
3#include "../shims/d3d12_compile_helper.h"
4
5#include <chrono>
6#include <cstdio>
7#include <filesystem>
8#include <fstream>
9#include <string>
10#include <thread>
11
12namespace fs = std::filesystem;
13namespace helper = rt::d3d12::compile_helper;
14
15#define CHECK(condition) do { \
16 if (!(condition)) { \
17 std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
18 return 1; \
19 } \
20} while (0)
21
22static int test_lines() {
23 const auto line = helper::parse_request(helper::format_request("fspx_compute/lib_cs_00001_ab", 4096));
24 CHECK(line.name == "fspx_compute/lib_cs_00001_ab" && line.priority == 4096);
25 const auto bare = helper::parse_request("name only");
26 CHECK(bare.name == "name only" && bare.priority == 0); // an older writer's request is urgent
27 return 0;
28}
29
30static int test_paths() {
31 const fs::path file = fs::path("J") / "cs-0123456789abcdef.bin";
32 CHECK(helper::request_path(file) == fs::path("J") / "requests" / "cs-0123456789abcdef.req");
33 CHECK(helper::failed_path(file) == fs::path("J") / "requests" / "cs-0123456789abcdef.failed");
34 CHECK(helper::building_path(file) == fs::path("J") / "requests" / "cs-0123456789abcdef.building");
35 return 0;
36}
37
38static int test_order(const fs::path& dir) {
39 const auto requests = dir / "requests";
40 fs::create_directories(requests);
41 const auto now = fs::file_time_type::clock::now();
42 const auto put = [&](const char* stem, const std::string& line, std::chrono::seconds age) {
43 const auto path = requests / (std::string(stem) + ".req");
44 std::ofstream(path, std::ios::binary) << line << "\n";
45 fs::last_write_time(path, now - age);
46 };
47 put("cs-0000000000000001", helper::format_request("warm-old", 500000), std::chrono::seconds(30));
48 put("cs-0000000000000002", helper::format_request("dispatch-new", 0), std::chrono::seconds(1));
49 put("cs-0000000000000003", helper::format_request("dispatch-old", 0), std::chrono::seconds(20));
50 put("cs-0000000000000004", helper::format_request("warm-small", 1000), std::chrono::seconds(5));
51 std::ofstream(requests / "cs-0000000000000005.failed") << "not a request\n";
52 const auto list = helper::list_requests(requests);
53 CHECK(list.size() == 4);
54 // Urgent (dispatch) first, oldest first among equals, then warm-ups by size.
55 CHECK(list[0].name == "dispatch-old" && list[1].name == "dispatch-new");
56 CHECK(list[2].name == "warm-small" && list[3].name == "warm-old");
57 CHECK(list[0].stem == "cs-0000000000000003");
58 return 0;
59}
60
61static int test_markers(const fs::path& dir) {
62 const auto file = dir / "cs-00000000000000aa.bin";
63 CHECK(helper::mark_building(file));
64 CHECK(!helper::mark_building(file)); // this process has it already
65 helper::unmark_building(file);
66 CHECK(!fs::exists(helper::building_path(file))); // the held handle's close removes the lock file
67 CHECK(helper::mark_building(file));
68 helper::unmark_building(file);
69 // A marker left behind names a process that no longer holds it (a killed helper) and is taken over: it is named
70 // after this very process, which is the reused process id that used to make it look busy forever.
71 std::ofstream(helper::building_path(file), std::ios::binary | std::ios::trunc)
72 << std::to_string(GetCurrentProcessId()) << "\n";
73 CHECK(fs::exists(helper::building_path(file)));
74 CHECK(helper::mark_building(file));
75 helper::unmark_building(file);
76 CHECK(!fs::exists(helper::building_path(file)));
77 // A lock file another opener holds is a live build: no claim, and nothing removes it.
78 const HANDLE held = CreateFileW(helper::building_path(file).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW,
79 FILE_ATTRIBUTE_NORMAL, nullptr);
80 CHECK(held != INVALID_HANDLE_VALUE);
81 CHECK(!helper::mark_building(file));
82 CHECK(fs::exists(helper::building_path(file)));
83 CloseHandle(held);
84 fs::remove(helper::building_path(file));
85 CHECK(helper::mark_building(file));
86 helper::unmark_building(file);
87 return 0;
88}
89
90// What state() answers for a request the helper has taken: no .req and no .failed means it is not coming (the helper
91// removes .req before it writes .failed and before the build that writes the journal file), so it is failed rather
92// than pending for as long as the helper lives.
93static int test_state(const fs::path& dir) {
94 auto& client = helper::Client::instance();
95 client.pretend_helper_running_for_test(); // no helper process is started
96 const leonida::cached_pso::Identity identity;
97 const auto file = dir / "cs-00000000000000bb.bin";
98 std::string why;
99 CHECK(client.request(file, "fspx_compute/lib_cs_00001", 4000, identity, &why));
100 CHECK(fs::exists(helper::request_path(file)));
101 CHECK(client.state(file, identity, &why) == helper::Client::State::pending);
102 // A bump of the priority keeps a .failed: it is the answer to this same request.
103 helper::write_line(helper::failed_path(file), "no compute entry of that name");
104 CHECK(client.request(file, "fspx_compute/lib_cs_00001", 0, identity, &why));
105 CHECK(fs::exists(helper::failed_path(file)));
106 CHECK(helper::read_line(helper::failed_path(file)) == "no compute entry of that name");
107 why.clear();
108 CHECK(client.state(file, identity, &why) == helper::Client::State::failed);
109 CHECK(why.find("no compute entry of that name") != std::string::npos);
110 // A fresh request drops an older failure, so asking again can retry.
111 CHECK(client.request(file, "fspx_compute/lib_cs_00001", 0, identity, &why));
112 CHECK(!fs::exists(helper::failed_path(file)));
113 // .req gone, no .failed, no journal file: failed.
114 const auto gone = dir / "cs-00000000000000cc.bin";
115 CHECK(client.request(gone, "fspx_compute/lib_cs_00002", 0, identity, &why));
116 CHECK(client.state(gone, identity, &why) == helper::Client::State::pending);
117 fs::remove(helper::request_path(gone));
118 why.clear();
119 CHECK(client.state(gone, identity, &why) == helper::Client::State::failed);
120 CHECK(!why.empty());
121 // .req gone because the helper has started building it (it holds the lock file): pending, also past the pending
122 // bound, since giving up would only start the same build in the game. Failed once the lock is let go with no file.
123 const auto building = dir / "cs-00000000000000ee.bin";
124 SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", "100");
125 CHECK(client.request(building, "fspx_compute/lib_cs_00004", 0, identity, &why));
126 const HANDLE lock = CreateFileW(helper::building_path(building).c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW,
127 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, nullptr);
128 CHECK(lock != INVALID_HANDLE_VALUE);
129 fs::remove(helper::request_path(building));
130 CHECK(helper::building_held(building));
131 CHECK(client.state(building, identity, &why) == helper::Client::State::pending);
132 std::this_thread::sleep_for(std::chrono::milliseconds(250));
133 CHECK(client.state(building, identity, &why) == helper::Client::State::pending);
134 CloseHandle(lock);
135 CHECK(!helper::building_held(building));
136 why.clear();
137 CHECK(client.state(building, identity, &why) == helper::Client::State::failed);
138 SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", nullptr);
139 return 0;
140}
141
142// A pending request the helper never answers is failed after LEONIDA_COMPILE_HELPER_PENDING_MS, so a skipped dispatch
143// becomes a build here instead of never running.
144static int test_pending_bound(const fs::path& dir) {
145 auto& client = helper::Client::instance();
146 client.pretend_helper_running_for_test();
147 const leonida::cached_pso::Identity identity;
148 const auto file = dir / "cs-00000000000000dd.bin";
149 SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", "150");
150 std::string why;
151 CHECK(client.request(file, "fspx_compute/lib_cs_00003", 0, identity, &why));
152 CHECK(client.state(file, identity, &why) == helper::Client::State::pending);
153 std::this_thread::sleep_for(std::chrono::milliseconds(300));
154 why.clear();
155 CHECK(client.state(file, identity, &why) == helper::Client::State::failed);
156 CHECK(why.find("150 ms") != std::string::npos);
157 SetEnvironmentVariableA("LEONIDA_COMPILE_HELPER_PENDING_MS", nullptr);
158 return 0;
159}
160
161int main() {
162 const auto dir = fs::temp_directory_path() /
163 ("leonida_compile_helper_test_" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
164 std::error_code ec;
165 fs::create_directories(dir, ec);
166 int failed = test_lines();
167 if (!failed) failed = test_paths();
168 if (!failed) failed = test_order(dir);
169 if (!failed) failed = test_markers(dir);
170 if (!failed) failed = test_state(dir);
171 if (!failed) failed = test_pending_bound(dir);
172 fs::remove_all(dir, ec);
173 if (failed) return failed;
174 std::printf("compile_helper_test: ok\n");
175 return 0;
176}
diff --git a/runtime/test/console_heap_vsharp_slots_test.cpp b/runtime/test/console_heap_vsharp_slots_test.cpp
new file mode 100644
index 000000000..ebb74be45
--- /dev/null
+++ b/runtime/test/console_heap_vsharp_slots_test.cpp
@@ -0,0 +1,259 @@
1// Portable CPU-only unit test for leonida::ConsoleHeapVsharpSlots (runtime/src/console_heap_vsharp_slots.h).
2// Verifies bit-for-bit equivalence with a linear scan of 32-byte descriptor slots, boundary handling, range clears,
3// callback-time bit clearing (as in refresh_console_heap invalidation passes), and a 5.5 MiB heap stress check.
4#include "../src/console_heap_vsharp_slots.h"
5
6#include <array>
7#include <cstdint>
8#include <cstdio>
9#include <cstring>
10#include <vector>
11
12#define EXPECT(condition) \
13 do { \
14 if (!(condition)) { \
15 std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \
16 return 1; \
17 } \
18 } while (0)
19
20namespace {
21
22using leonida::ConsoleHeapVsharpSlots;
23
24std::vector<std::size_t> collect(const ConsoleHeapVsharpSlots& slots) {
25 std::vector<std::size_t> out;
26 slots.for_each([&](std::size_t slot) { out.push_back(slot); });
27 return out;
28}
29
30int test_predicate_exactness() {
31 // Primary buffer V#: top 2 bits of w[3] are 0, w[2] (num_records) != 0.
32 std::uint32_t primary[8] = {0x1000, 0x20, 64, 0x3fffffffu, 0, 0, 0, 0};
33 EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(primary));
34
35 // Counter-only buffer V#: w[2] == 0, w[6] != 0, top 2 bits of w[3] == 0.
36 std::uint32_t counter[8] = {0, 0, 0, 0, 0x2000, 0, 16, 0};
37 EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(counter));
38
39 // Empty / zeroed V#: w[2] == 0 and w[6] == 0.
40 std::uint32_t empty[8] = {0x1000, 0, 0, 0x00010000u, 0x2000, 0, 0, 0};
41 EXPECT(!ConsoleHeapVsharpSlots::is_live_vsharp(empty));
42
43 // Image T# (w[3] >> 30 != 0): must NOT be treated as a buffer V# even if w[2]/w[6] are non-zero.
44 for (std::uint32_t hi : {1u, 2u, 3u}) {
45 std::uint32_t tsharp[8] = {0x1000, 0, 128, (hi << 30) | 0x55u, 0, 0, 64, 0};
46 EXPECT(!ConsoleHeapVsharpSlots::is_live_vsharp(tsharp));
47 }
48
49 // not_tsharp zeroes lower 16 bytes (w[0..3] = 0) while leaving upper 16 bytes (w[4..7]):
50 // if w[6] is non-zero, predicate matches the legacy `!(w[3] >> 30) && (w[2] || w[6])` check.
51 std::uint32_t not_tsharp_with_hi[8] = {0, 0, 0, 0, 0, 0, 1, 0};
52 EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(not_tsharp_with_hi));
53 return 0;
54}
55
56int test_boundaries_and_ranges() {
57 // Zero-size heap.
58 ConsoleHeapVsharpSlots zero;
59 zero.reset(0);
60 EXPECT(zero.empty() && zero.slot_count() == 0 && zero.live_count() == 0);
61 zero.set(0, true);
62 zero.clear(0);
63 zero.clear_range(0, 10);
64 EXPECT(zero.empty() && !zero.test(0) && collect(zero).empty());
65
66 // Word boundary sizes: 1, 63, 64, 65, 128, 129, 257.
67 for (std::size_t n : {std::size_t(1), std::size_t(63), std::size_t(64), std::size_t(65), std::size_t(128),
68 std::size_t(129), std::size_t(257)}) {
69 ConsoleHeapVsharpSlots s;
70 s.reset(n);
71 EXPECT(s.slot_count() == n && s.empty());
72 // Out-of-range writes are ignored.
73 s.set(n, true);
74 s.set(n + 100, true);
75 EXPECT(s.empty() && !s.test(n));
76
77 // Set every slot, check idempotency and exact ordering.
78 for (std::size_t i = 0; i < n; ++i) s.set(i, true);
79 s.set(0, true);
80 s.set(n - 1, true);
81 EXPECT(s.live_count() == n);
82 const auto all = collect(s);
83 EXPECT(all.size() == n);
84 for (std::size_t i = 0; i < n; ++i) EXPECT(all[i] == i && s.test(i));
85
86 // Inverted / empty / past-end clear_range is a no-op.
87 s.clear_range(5, 5);
88 s.clear_range(10, 2);
89 s.clear_range(n, n + 64);
90 EXPECT(s.live_count() == n);
91
92 // Partial single-word and multi-word clear_range.
93 if (n >= 129) {
94 s.clear_range(3, 19); // within word 0
95 s.clear_range(60, 128); // spans word 0 tail + all of word 1
96 EXPECT(s.live_count() == n - 16 - 68);
97 EXPECT(s.test(2) && !s.test(3) && !s.test(18) && s.test(19));
98 EXPECT(s.test(59) && !s.test(60) && !s.test(127) && s.test(128));
99 }
100
101 // Clear past end clamps cleanly.
102 s.clear_range(0, n + 500);
103 EXPECT(s.empty() && s.live_count() == 0 && collect(s).empty());
104 }
105 return 0;
106}
107
108int test_in_place_invalidation_mutation() {
109 // Mirrors refresh_console_heap: for_each visits each live V# slot and calls fix_console_slot, which may clear
110 // that slot's bit when its backing buffer was released.
111 ConsoleHeapVsharpSlots s;
112 s.reset(260);
113 const std::vector<std::size_t> initial = {0, 1, 62, 63, 64, 65, 127, 128, 191, 255, 259};
114 for (std::size_t slot : initial) s.set(slot, true);
115 EXPECT(s.live_count() == initial.size());
116
117 std::vector<std::size_t> visited;
118 s.for_each([&](std::size_t slot) {
119 visited.push_back(slot);
120 // Simulate releasing every even-numbered slot during the invalidation pass.
121 if ((slot & 1u) == 0) s.set(slot, false);
122 });
123 EXPECT(visited == initial);
124
125 std::vector<std::size_t> remaining;
126 for (std::size_t slot : initial)
127 if ((slot & 1u) != 0) remaining.push_back(slot);
128 EXPECT(s.live_count() == remaining.size());
129 EXPECT(collect(s) == remaining);
130
131 // Clear the remaining slots and confirm empty fast path visits nothing.
132 s.for_each([&](std::size_t slot) { s.clear(slot); });
133 EXPECT(s.empty() && collect(s).empty());
134 return 0;
135}
136
137int test_differential_equivalence_against_linear_copy() {
138 // Differential model: maintain a synthetic 32-byte-per-slot `heap.copy` buffer alongside ConsoleHeapVsharpSlots
139 // across thousands of random writes, deferred zeroes, page-range zeroes, and invalidation passes.
140 constexpr std::size_t kSlots = 1029;
141 std::vector<std::array<std::uint32_t, 8>> gpu_copy(kSlots);
142 for (auto& slot : gpu_copy) slot.fill(0);
143
144 ConsoleHeapVsharpSlots tracked;
145 tracked.reset(kSlots);
146
147 auto linear_scan = [&] {
148 std::vector<std::size_t> expected;
149 for (std::size_t i = 0; i < kSlots; ++i)
150 if (ConsoleHeapVsharpSlots::is_live_vsharp(gpu_copy[i].data())) expected.push_back(i);
151 return expected;
152 };
153
154 std::uint64_t rng = 0x9e3779b97f4a7c15ull;
155 auto next_u32 = [&]() -> std::uint32_t {
156 rng ^= rng >> 12;
157 rng ^= rng << 25;
158 rng ^= rng >> 27;
159 return static_cast<std::uint32_t>((rng * 0x2545f4914f6cdd1dull) >> 32);
160 };
161
162 for (unsigned step = 0; step < 4000; ++step) {
163 const unsigned op = next_u32() % 10;
164 if (op < 6) {
165 // Simulate fix_console_slot writing a descriptor to heap.copy.
166 const std::size_t slot = next_u32() % kSlots;
167 std::array<std::uint32_t, 8> w{};
168 const unsigned kind = next_u32() % 5;
169 if (kind == 0) {
170 // Live primary V#
171 w[0] = next_u32();
172 w[2] = (next_u32() % 256) + 1;
173 w[3] = next_u32() & 0x3fffffffu;
174 } else if (kind == 1) {
175 // Live counter V# only
176 w[6] = (next_u32() % 64) + 1;
177 } else if (kind == 2) {
178 // Empty V# (zero records)
179 w[0] = 0;
180 w[2] = 0;
181 w[3] = next_u32() & 0x3fffffffu;
182 w[6] = 0;
183 } else if (kind == 3) {
184 // Image T#
185 w[2] = 128;
186 w[3] = (2u << 30) | (next_u32() & 0x3fffffffu);
187 w[6] = 32;
188 } else {
189 // not_tsharp (lower 16B zeroed, upper 16B arbitrary)
190 w[4] = next_u32();
191 w[6] = (next_u32() & 1u) ? 7u : 0u;
192 }
193 gpu_copy[slot] = w;
194 tracked.set(slot, ConsoleHeapVsharpSlots::is_live_vsharp(w.data()));
195 } else if (op < 8) {
196 // Simulate fix_console_slots deferred zeroing.
197 const std::size_t slot = next_u32() % kSlots;
198 gpu_copy[slot].fill(0);
199 tracked.clear(slot);
200 } else if (op == 8) {
201 // Simulate for_each_zeroed (both page-aligned 128-slot and arbitrary sub-ranges).
202 const std::size_t first = next_u32() % (kSlots + 16);
203 const std::size_t len = (next_u32() % 200);
204 const std::size_t end = first + len;
205 for (std::size_t i = first; i < end && i < kSlots; ++i) gpu_copy[i].fill(0);
206 tracked.clear_range(first, end);
207 } else {
208 // Simulate refresh_console_heap invalidation pass clearing a subset of visited slots.
209 const std::vector<std::size_t> expected = linear_scan();
210 std::vector<std::size_t> got;
211 tracked.for_each([&](std::size_t slot) {
212 got.push_back(slot);
213 if ((slot % 3) == 0) {
214 gpu_copy[slot].fill(0);
215 tracked.set(slot, false);
216 }
217 });
218 EXPECT(got == expected);
219 }
220
221 if ((step & 63) == 63) {
222 const std::vector<std::size_t> expected = linear_scan();
223 EXPECT(tracked.live_count() == expected.size());
224 EXPECT(collect(tracked) == expected);
225 }
226 }
227 EXPECT(collect(tracked) == linear_scan());
228 return 0;
229}
230
231int test_retail_sized_heap_sparse_scan() {
232 // 5.5 MiB resource heap = 180,224 32-byte slots (matching retail console descriptor heap).
233 constexpr std::size_t kRetailSlots = (5632u * 1024u) / 32u;
234 ConsoleHeapVsharpSlots tracked;
235 tracked.reset(kRetailSlots);
236
237 const std::vector<std::size_t> hot = {0, 63, 64, 4095, 4096, 65536, 131072, kRetailSlots - 1};
238 for (std::size_t slot : hot) tracked.set(slot, true);
239 EXPECT(tracked.live_count() == hot.size());
240 EXPECT(collect(tracked) == hot);
241
242 // Zero a 4 KiB page (128 slots) containing slots 4096..4223.
243 tracked.clear_range(4096, 4096 + 128);
244 EXPECT(!tracked.test(4096) && tracked.test(4095));
245 EXPECT(tracked.live_count() == hot.size() - 1);
246 return 0;
247}
248
249} // namespace
250
251int main() {
252 if (test_predicate_exactness()) return 1;
253 if (test_boundaries_and_ranges()) return 1;
254 if (test_in_place_invalidation_mutation()) return 1;
255 if (test_differential_equivalence_against_linear_copy()) return 1;
256 if (test_retail_sized_heap_sparse_scan()) return 1;
257 std::printf("console_heap_vsharp_slots_test: ok\n");
258 return 0;
259}
diff --git a/runtime/test/d3d12_big_compute_test.cpp b/runtime/test/d3d12_big_compute_test.cpp
new file mode 100644
index 000000000..c6469719e
--- /dev/null
+++ b/runtime/test/d3d12_big_compute_test.cpp
@@ -0,0 +1,978 @@
1// Large pipelines that a submission compiles (LEONIDA_SERIAL_BIG_COMPILES, LEONIDA_BIG_COMPILE_BUDGET_MB), through the D3D12
2// layer on a GPU: real compute modules of more than 128 KiB (big_compute_module.h), small ones, and graphics pipelines of more than
3// 1 MiB. Both settings are read once for each process, so the test runs once for each: with a fixed budget, one that holds
4// nothing, the one read from the machine, one at a time and without a limit. Every run
5// - stores what the CPU computes for each dispatch, and draws the graphics pipelines' cells;
6// - compiles as many large ones at once as the setting allows and no more, and the small ones meanwhile;
7// - gives a pipeline the driver refuses the result it has always had, and its place to the next;
8// - compiles each pipeline once when two queues need the same ones;
9// - ends when the device's last references go while its workers compile and wait for memory.
10// `warmup`: a submission's compiles go before those of the warm-up thread, which waits without holding a pipeline state.
11// `eager`: pipeline states compiled when they are created (LEONIDA_LAZY_COMPUTE=0), by several threads, keep the budget too.
12// The calls that create pipelines are watched, and held back, through the device's vkGetDeviceProcAddr.
13// Self-contained: builds its SPIR-V in memory. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
14#include "big_compute_module.h"
15#include "vk_test_device.h"
16#include "d3d12_test_shaders.h"
17#include "test_temp_dir.h"
18#include "../shims/d3d12_com.h"
19#include "../shims/d3d12_pipeline_compile.h"
20#include "../src/large_module_gate.h"
21#include "../src/shader_library.h"
22
23#include <algorithm>
24#include <atomic>
25#include <bit>
26#include <chrono>
27#include <condition_variable>
28#include <cstdint>
29#include <cstdio>
30#include <cstdlib>
31#include <cstring>
32#include <fstream>
33#include <map>
34#include <memory>
35#include <mutex>
36#include <set>
37#include <string>
38#include <thread>
39#include <type_traits>
40#include <utility>
41#include <vector>
42
43namespace {
44
45using namespace std::chrono_literals;
46using d3d12test::Ref;
47using leonida::ReplayResult;
48using bigmodule::Words;
49using bigmodule::op;
50
51constexpr unsigned kBig = 6, kSmall = 4, kCompute = kBig + kSmall, kGraphics = 2;
52constexpr std::size_t kBigBytes = 132 * 1024, kSmallBytes = 12 * 1024;
53constexpr unsigned kExtent = 4; // the render target; each graphics pipeline draws one 2x2 cell
54constexpr unsigned kWords = bigmodule::kLoadBase + bigmodule::kLoadWords;
55
56#define CHECK(expr) \
57 do { \
58 if (!(expr)) { \
59 std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); \
60 return false; \
61 } \
62 } while (0)
63
64// ---- What the settings of this process say. ----
65
66std::string setting(const char* name) {
67 char text[64]{};
68 std::size_t length = 0;
69 return getenv_s(&length, text, name) == 0 && length > 1 ? text : "";
70}
71const bool serial = setting("LEONIDA_SERIAL_BIG_COMPILES") == "1";
72const bool unlimited = setting("LEONIDA_SERIAL_BIG_COMPILES") == "0";
73const bool budgeted = !serial && !unlimited;
74const auto fixed_budget = leonida::large_compile_budget(setting("LEONIDA_BIG_COMPILE_BUDGET_MB").c_str()).fixed;
75
76// ---- The driver's pipeline calls, watched. ----
77
78struct Start {
79 std::thread::id thread;
80 int program = -1; // compute: the index of its module
81 bool large = false;
82};
83
84struct Hooks {
85 std::mutex mutex;
86 std::condition_variable changed;
87 std::map<std::uint64_t, int> programs; // the hash of a compute module's words: its index
88 std::map<VkShaderModule, std::pair<std::size_t, int>> modules; // bytes, program
89 bool closed = false; // large creations wait while it is
90 std::chrono::milliseconds linger{0}; // and each takes at least this long, as does what follows it on its thread
91 std::vector<Start> started;
92 int large_in = 0, most_large = 0, small_done = 0, large_compute_in = 0, most_large_compute = 0;
93 std::uint64_t reserved = 0; // the estimates of the large ones in the driver
94 int over = 0; // how often several were in past the budget, or two where one is allowed
95 int fail_large = -1; // the large compute create (counted from 0) the driver refuses
96 int large_compute = 0;
97 bool track = false; // threads that create a pipeline are counted until they end
98 int live = 0, in_flight = 0, cache_reads = 0;
99 bool cache_read_during_create = false, cache_read_with_workers = false;
100
101 void reset() {
102 std::lock_guard lock(mutex);
103 closed = track = cache_read_during_create = cache_read_with_workers = false;
104 started.clear();
105 most_large = small_done = most_large_compute = over = large_compute = cache_reads = 0;
106 fail_large = -1;
107 linger = 0ms;
108 }
109 void open() {
110 std::lock_guard lock(mutex);
111 closed = false;
112 changed.notify_all();
113 }
114 template<typename Until>
115 bool wait(Until&& until) {
116 std::unique_lock lock(mutex);
117 return changed.wait_for(lock, 20s, until);
118 }
119 bool wait_large(int count) {
120 return wait([&] { return large_in >= count; });
121 }
122 std::size_t creates() {
123 std::lock_guard lock(mutex);
124 return started.size();
125 }
126} hooks;
127
128struct Tracked {
129 bool on = false;
130 ~Tracked() {
131 if (!on) return;
132 std::lock_guard lock(hooks.mutex);
133 --hooks.live;
134 }
135};
136thread_local Tracked tracked;
137
138PFN_vkGetInstanceProcAddr real_instance_proc = nullptr;
139PFN_vkGetDeviceProcAddr real_device_proc = nullptr;
140PFN_vkCreateShaderModule real_create_module = nullptr;
141PFN_vkDestroyShaderModule real_destroy_module = nullptr;
142PFN_vkCreateGraphicsPipelines real_create_graphics = nullptr;
143PFN_vkCreateComputePipelines real_create_compute = nullptr;
144PFN_vkGetPipelineCacheData real_cache_data = nullptr;
145
146std::uint64_t hash(const std::uint32_t* words, std::size_t count) {
147 std::uint64_t h = 0xcbf29ce484222325u;
148 for (std::size_t i = 0; i < count; ++i) h = (h ^ words[i]) * 0x100000001b3u;
149 return h;
150}
151
152struct Creation {
153 bool large = false, compute = false, refused = false;
154 std::uint64_t estimate = 0;
155};
156
157Creation enter_create(bool compute, std::initializer_list<VkShaderModule> modules) {
158 std::unique_lock lock(hooks.mutex);
159 Creation c;
160 c.compute = compute;
161 std::size_t bytes = 0;
162 Start start{std::this_thread::get_id(), -1, false};
163 for (const VkShaderModule module : modules) {
164 const auto found = hooks.modules.find(module);
165 if (found == hooks.modules.end()) continue;
166 bytes += found->second.first;
167 if (compute) start.program = found->second.second;
168 }
169 c.large = start.large = bytes > (compute ? 128 * 1024 : leonida::PipelineCompiles::large_spirv_bytes - 1);
170 c.estimate = leonida::large_module_estimate(bytes);
171 ++hooks.in_flight;
172 hooks.started.push_back(start);
173 if (hooks.track && !tracked.on) {
174 tracked.on = true;
175 ++hooks.live;
176 }
177 if (c.large) {
178 ++hooks.large_in;
179 if (compute) ++hooks.large_compute_in;
180 hooks.most_large = std::max(hooks.most_large, hooks.large_in);
181 hooks.most_large_compute = std::max(hooks.most_large_compute, hooks.large_compute_in);
182 hooks.reserved += c.estimate;
183 // One large compute module at a time; with a budget, several only within it.
184 if (serial && hooks.large_compute_in > 1) ++hooks.over;
185 if (budgeted && fixed_budget && hooks.large_in > 1 && hooks.reserved > *fixed_budget) ++hooks.over;
186 if (compute && hooks.large_compute++ == hooks.fail_large) c.refused = true;
187 }
188 hooks.changed.notify_all();
189 if (c.large) hooks.changed.wait(lock, [] { return !hooks.closed; });
190 const auto linger = hooks.linger;
191 lock.unlock();
192 if (c.large && linger > 0ms) std::this_thread::sleep_for(linger);
193 return c;
194}
195
196void leave_create(const Creation& c) {
197 std::lock_guard lock(hooks.mutex);
198 --hooks.in_flight;
199 if (c.large) {
200 --hooks.large_in;
201 if (c.compute) --hooks.large_compute_in;
202 hooks.reserved -= c.estimate;
203 } else {
204 ++hooks.small_done;
205 }
206 hooks.changed.notify_all();
207}
208
209VKAPI_ATTR VkResult VKAPI_CALL create_module(VkDevice device, const VkShaderModuleCreateInfo* info,
210 const VkAllocationCallbacks* allocator, VkShaderModule* out) {
211 const VkResult result = real_create_module(device, info, allocator, out);
212 if (result == VK_SUCCESS) {
213 std::lock_guard lock(hooks.mutex);
214 const auto found = hooks.programs.find(hash(info->pCode, info->codeSize / 4));
215 hooks.modules[*out] = {info->codeSize, found == hooks.programs.end() ? -1 : found->second};
216 }
217 return result;
218}
219
220// Called between the place a compile gives back and the next one its thread asks for: with a linger, time for another
221// thread to take that place.
222VKAPI_ATTR void VKAPI_CALL destroy_module(VkDevice device, VkShaderModule module, const VkAllocationCallbacks* allocator) {
223 std::chrono::milliseconds linger;
224 {
225 std::lock_guard lock(hooks.mutex);
226 linger = hooks.linger;
227 }
228 if (linger > 0ms) std::this_thread::sleep_for(linger);
229 real_destroy_module(device, module, allocator);
230}
231
232VKAPI_ATTR VkResult VKAPI_CALL create_graphics(VkDevice device, VkPipelineCache cache, std::uint32_t count,
233 const VkGraphicsPipelineCreateInfo* infos,
234 const VkAllocationCallbacks* allocator, VkPipeline* out) {
235 VkShaderModule modules[2]{};
236 for (std::uint32_t i = 0; i < std::min(infos->stageCount, 2u); ++i) modules[i] = infos->pStages[i].module;
237 const Creation c = enter_create(false, {modules[0], modules[1]});
238 const VkResult result = real_create_graphics(device, cache, count, infos, allocator, out);
239 leave_create(c);
240 return result;
241}
242
243VKAPI_ATTR VkResult VKAPI_CALL create_compute(VkDevice device, VkPipelineCache cache, std::uint32_t count,
244 const VkComputePipelineCreateInfo* infos,
245 const VkAllocationCallbacks* allocator, VkPipeline* out) {
246 const Creation c = enter_create(true, {infos->stage.module});
247 const VkResult result = c.refused ? VK_ERROR_UNKNOWN
248 : real_create_compute(device, cache, count, infos, allocator, out);
249 leave_create(c);
250 return result;
251}
252
253VKAPI_ATTR VkResult VKAPI_CALL cache_data(VkDevice device, VkPipelineCache cache, std::size_t* size, void* data) {
254 {
255 std::lock_guard lock(hooks.mutex);
256 ++hooks.cache_reads;
257 if (hooks.in_flight) hooks.cache_read_during_create = true;
258 if (hooks.live > (tracked.on ? 1 : 0)) hooks.cache_read_with_workers = true;
259 }
260 return real_cache_data(device, cache, size, data);
261}
262
263VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) {
264 const PFN_vkVoidFunction real = real_device_proc(device, name);
265 if (!real) return nullptr;
266 const auto watch = [&](const char* which, auto& kept, auto* mine) -> PFN_vkVoidFunction {
267 if (std::strcmp(name, which)) return nullptr;
268 kept = reinterpret_cast<std::remove_reference_t<decltype(kept)>>(real);
269 return reinterpret_cast<PFN_vkVoidFunction>(mine);
270 };
271 if (const auto f = watch("vkCreateShaderModule", real_create_module, create_module)) return f;
272 if (const auto f = watch("vkDestroyShaderModule", real_destroy_module, destroy_module)) return f;
273 if (const auto f = watch("vkCreateGraphicsPipelines", real_create_graphics, create_graphics)) return f;
274 if (const auto f = watch("vkCreateComputePipelines", real_create_compute, create_compute)) return f;
275 if (const auto f = watch("vkGetPipelineCacheData", real_cache_data, cache_data)) return f;
276 return real;
277}
278
279VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) {
280 if (!std::strcmp(name, "vkGetDeviceProcAddr")) {
281 real_device_proc = reinterpret_cast<PFN_vkGetDeviceProcAddr>(real_instance_proc(instance, name));
282 return reinterpret_cast<PFN_vkVoidFunction>(device_proc);
283 }
284 return real_instance_proc(instance, name);
285}
286
287// ---- The shaders. ----
288
289std::uint32_t bits(float f) { return std::bit_cast<std::uint32_t>(f); }
290
291// 1.25 MiB of OpString, which compile to nothing: a graphics pipeline that is large.
292void pad(Words& w, std::uint32_t first_id) {
293 for (std::uint32_t i = 0; i < 5; ++i) {
294 const std::size_t at = w.size();
295 w.resize(at + 65535, 0x20202020u);
296 w[at] = 65535u << 16 | 7;
297 w[at + 1] = first_id + i;
298 w.back() = 0;
299 }
300}
301
302// A full-screen triangle from VertexIndex.
303Words vertex_words() {
304 Words w = {0x07230203u, 0x00010500u, 0u, 42u, 0u};
305 op(w, 17, {1}); // Capability Shader
306 op(w, 14, {0, 1}); // MemoryModel Logical GLSL450
307 op(w, 15, {0, 4, 0x6e69616du, 0u, 10, 11}); // EntryPoint Vertex "main"
308 op(w, 71, {10, 11, 0}); // BuiltIn Position
309 op(w, 71, {11, 11, 42}); // BuiltIn VertexIndex
310 op(w, 19, {1});
311 op(w, 33, {2, 1});
312 op(w, 22, {3, 32});
313 op(w, 23, {6, 3, 4});
314 op(w, 21, {15, 32, 1});
315 op(w, 32, {7, 3, 6});
316 op(w, 32, {8, 1, 15});
317 op(w, 59, {7, 10, 3});
318 op(w, 59, {8, 11, 1});
319 op(w, 43, {15, 24, 1});
320 op(w, 43, {15, 25, 2});
321 op(w, 43, {3, 26, bits(2.0f)});
322 op(w, 43, {3, 27, bits(-1.0f)});
323 op(w, 43, {3, 28, bits(0.0f)});
324 op(w, 43, {3, 29, bits(1.0f)});
325 op(w, 54, {1, 4, 0, 2});
326 op(w, 248, {30});
327 op(w, 61, {15, 31, 11});
328 op(w, 196, {15, 32, 31, 24}); // index << 1
329 op(w, 199, {15, 33, 32, 25}); // & 2
330 op(w, 199, {15, 34, 31, 25}); // index & 2
331 op(w, 111, {3, 35, 33});
332 op(w, 111, {3, 36, 34});
333 op(w, 133, {3, 37, 35, 26});
334 op(w, 133, {3, 38, 36, 26});
335 op(w, 129, {3, 39, 37, 27});
336 op(w, 129, {3, 40, 38, 27});
337 op(w, 80, {6, 41, 39, 40, 28, 29});
338 op(w, 62, {10, 41});
339 op(w, 253, {});
340 op(w, 56, {});
341 return w;
342}
343
344// The colour (n / 255, 1 - n / 255, 0, 1).
345Words fragment_words(unsigned n) {
346 Words w = {0x07230203u, 0x00010500u, 0u, 40u, 0u};
347 op(w, 17, {1});
348 op(w, 14, {0, 1});
349 op(w, 15, {4, 4, 0x6e69616du, 0u, 9}); // EntryPoint Fragment "main"
350 op(w, 16, {4, 7}); // OriginUpperLeft
351 pad(w, 30);
352 op(w, 71, {9, 30, 0}); // Location 0
353 op(w, 19, {1});
354 op(w, 33, {2, 1});
355 op(w, 22, {3, 32});
356 op(w, 23, {6, 3, 4});
357 op(w, 32, {10, 3, 6});
358 op(w, 59, {10, 9, 3});
359 op(w, 43, {3, 20, bits(float(n) / 255.0f)});
360 op(w, 43, {3, 21, bits(float(255 - n) / 255.0f)});
361 op(w, 43, {3, 22, bits(0.0f)});
362 op(w, 43, {3, 23, bits(1.0f)});
363 op(w, 44, {6, 24, 20, 21, 22, 23});
364 op(w, 54, {1, 4, 0, 2});
365 op(w, 248, {11});
366 op(w, 62, {9, 24});
367 op(w, 253, {});
368 op(w, 56, {});
369 return w;
370}
371
372std::vector<std::uint8_t> program(unsigned stage, unsigned n) {
373 return d3d12test::fssm_program({0x42434f00u + stage, n, 0xbf810000u});
374}
375
376std::vector<bigmodule::Program> programs(kCompute); // what each compute module runs
377std::vector<std::size_t> module_bytes(kCompute);
378
379bool write_library(const std::filesystem::path& dir) {
380 const auto write = [&](const std::string& name, const Words& words) {
381 std::ofstream f(dir / (name + ".spv"), std::ios::binary | std::ios::trunc);
382 f.write(reinterpret_cast<const char*>(words.data()), std::streamsize(words.size() * 4));
383 return bool(f);
384 };
385 CHECK(write("vs", vertex_words()));
386 std::ofstream index(dir / "index.json", std::ios::binary | std::ios::trunc);
387 index << "{\"vs\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(0, 0))
388 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []}";
389 for (unsigned n = 0; n < kGraphics; ++n) {
390 const std::string name = "ps" + std::to_string(n);
391 CHECK(write(name, fragment_words(n)));
392 index << ",\n\"" << name << "\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(1, n))
393 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"inputs\": [], \"outputs\": [0]}";
394 }
395 for (unsigned n = 0; n < kCompute; ++n) {
396 const std::string name = "cs" + std::to_string(n);
397 // Every large one a little larger than the one before, so that the order by size is known.
398 const Words words = bigmodule::make(n < kBig ? kBigBytes + n * 1024 : kSmallBytes, 20251125 + n, &programs[n]);
399 module_bytes[n] = words.size() * 4;
400 CHECK((module_bytes[n] > 128 * 1024) == (n < kBig));
401 hooks.programs[hash(words.data(), words.size())] = int(n);
402 CHECK(write(name, words));
403 index << ",\n\"" << name << "\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program(2, n))
404 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [1, 1, 1], \"wave64\": false}";
405 }
406 index << "}";
407 return bool(index);
408}
409
410// ---- The device and what it runs. ----
411
412struct Setup {
413 vktest::Device* vk;
414 std::string library;
415
416 bool device(const char* threads, Ref<ID3D12Device>& out) const {
417 _putenv_s("LEONIDA_PIPELINE_THREADS", threads);
418 rt::d3d12::VulkanDeviceInfo info{};
419 info.get_instance_proc = instance_proc;
420 info.instance = vk->instance;
421 info.physical = vk->physical;
422 info.device = vk->device;
423 info.queue = vk->queue;
424 info.queue_family = vk->family;
425 info.buffer_device_address = true;
426 info.subgroup = vk->subgroup;
427 info.features = vk->enabled;
428 info.shader_dir = library;
429 CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&out.p))));
430 return true;
431 }
432};
433
434struct Pipelines {
435 Ref<ID3D12RootSignature> root;
436 std::vector<ID3D12PipelineState*> compute, graphics;
437 ~Pipelines() { release(); }
438 void release() {
439 for (auto* s : compute)
440 if (s) s->Release();
441 for (auto* s : graphics) s->Release();
442 compute.clear();
443 graphics.clear();
444 }
445
446 static ID3D12PipelineState* compute_state(ID3D12Device* dev, ID3D12RootSignature* root, unsigned n) {
447 const auto cs = d3d12test::shader_container(program(2, n));
448 D3D12_COMPUTE_PIPELINE_STATE_DESC pd{};
449 pd.pRootSignature = root;
450 pd.CS = {cs.data(), cs.size()};
451 ID3D12PipelineState* state = nullptr;
452 return SUCCEEDED(dev->CreateComputePipelineState(&pd, IID_PPV_ARGS(&state))) ? state : nullptr;
453 }
454
455 // The compute states on `threads` threads.
456 bool create(ID3D12Device* dev, unsigned threads = 1) {
457 D3D12_ROOT_PARAMETER params[2]{};
458 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
459 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
460 params[1].Constants.Num32BitValues = 1;
461 D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{};
462 desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
463 desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
464 const auto blob = d3d12test::serialize_root_signature(desc);
465 CHECK(SUCCEEDED(dev->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p))));
466 compute.assign(kCompute, nullptr);
467 std::vector<std::thread> creating;
468 for (unsigned t = 1; t < threads; ++t)
469 creating.emplace_back([&, t] {
470 for (unsigned n = t; n < kCompute; n += threads) compute[n] = compute_state(dev, root.p, n);
471 });
472 for (unsigned n = 0; n < kCompute; n += threads) compute[n] = compute_state(dev, root.p, n);
473 for (auto& t : creating) t.join();
474 CHECK(std::find(compute.begin(), compute.end(), nullptr) == compute.end());
475 const auto vs = d3d12test::shader_container(program(0, 0));
476 for (unsigned n = 0; n < kGraphics; ++n) {
477 const auto ps = d3d12test::shader_container(program(1, n));
478 D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{};
479 pd.pRootSignature = root.p;
480 pd.VS = {vs.data(), vs.size()};
481 pd.PS = {ps.data(), ps.size()};
482 for (auto& rt : pd.BlendState.RenderTarget) {
483 rt.SrcBlend = rt.SrcBlendAlpha = D3D12_BLEND_ONE;
484 rt.DestBlend = rt.DestBlendAlpha = D3D12_BLEND_ZERO;
485 rt.BlendOp = rt.BlendOpAlpha = D3D12_BLEND_OP_ADD;
486 rt.LogicOp = D3D12_LOGIC_OP_NOOP;
487 rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
488 }
489 pd.SampleMask = UINT_MAX;
490 pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
491 pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
492 pd.RasterizerState.DepthClipEnable = TRUE;
493 pd.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
494 pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
495 pd.NumRenderTargets = 1;
496 pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
497 pd.SampleDesc = {1, 0};
498 ID3D12PipelineState* state = nullptr;
499 CHECK(SUCCEEDED(dev->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&state))));
500 graphics.push_back(state);
501 }
502 return true;
503 }
504};
505
506// A queue and a list that dispatches `compute` (and draws the graphics pipelines), then copies what they wrote back.
507struct Frame {
508 std::vector<unsigned> compute;
509 bool graphics = false;
510 Ref<ID3D12Resource> target, buffer, readback;
511 Ref<ID3D12DescriptorHeap> rtvs;
512 Ref<ID3D12CommandQueue> queue;
513 Ref<ID3D12CommandAllocator> allocator;
514 Ref<ID3D12GraphicsCommandList> list;
515 Ref<ID3D12Fence> fence;
516 UINT64 fence_value = 0;
517 D3D12_PLACED_SUBRESOURCE_FOOTPRINT foot{};
518
519 bool create(ID3D12Device* dev, const Pipelines& p, std::vector<unsigned> dispatched, bool draws) {
520 compute = std::move(dispatched);
521 graphics = draws;
522 const D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT}, back{D3D12_HEAP_TYPE_READBACK};
523 D3D12_RESOURCE_DESC td{};
524 td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
525 td.Width = td.Height = kExtent;
526 td.DepthOrArraySize = td.MipLevels = 1;
527 td.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
528 td.SampleDesc = {1, 0};
529 td.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
530 CHECK(SUCCEEDED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_RENDER_TARGET,
531 nullptr, IID_PPV_ARGS(&target.p))));
532 const auto bd = d3d12test::buffer_desc(4 * kWords, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
533 CHECK(SUCCEEDED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &bd,
534 D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
535 IID_PPV_ARGS(&buffer.p))));
536 UINT64 image_bytes = 0;
537 dev->GetCopyableFootprints(&td, 0, 1, 0, &foot, nullptr, nullptr, &image_bytes);
538 CHECK(image_bytes <= 4096);
539 const auto rd = d3d12test::buffer_desc(4096 + 4 * kWords);
540 CHECK(SUCCEEDED(dev->CreateCommittedResource(&back, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COPY_DEST,
541 nullptr, IID_PPV_ARGS(&readback.p))));
542 const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1};
543 CHECK(SUCCEEDED(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs.p))));
544 const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart();
545 dev->CreateRenderTargetView(target.p, nullptr, rtv);
546 const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT};
547 CHECK(SUCCEEDED(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p))));
548 CHECK(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
549 CHECK(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))));
550 CHECK(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr,
551 IID_PPV_ARGS(&list.p))));
552 const FLOAT clear[4] = {0, 0, 0, 0};
553 list->ClearRenderTargetView(rtv, clear, 0, nullptr);
554 list->SetComputeRootSignature(p.root.p);
555 list->SetComputeRootUnorderedAccessView(0, buffer->GetGPUVirtualAddress());
556 for (const unsigned n : compute) {
557 list->SetPipelineState(p.compute[n]);
558 list->SetComputeRoot32BitConstant(1, n, 0);
559 list->Dispatch(1, 1, 1);
560 }
561 if (graphics) {
562 list->SetGraphicsRootSignature(p.root.p);
563 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
564 list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
565 const D3D12_VIEWPORT vp{0, 0, float(kExtent), float(kExtent), 0, 1};
566 list->RSSetViewports(1, &vp);
567 for (unsigned n = 0; n < kGraphics; ++n) {
568 const D3D12_RECT cell{LONG(2 * n), 0, LONG(2 * n + 2), 2};
569 list->RSSetScissorRects(1, &cell);
570 list->SetPipelineState(p.graphics[n]);
571 list->DrawInstanced(3, 1, 0, 0);
572 }
573 }
574 const D3D12_RESOURCE_BARRIER to_source[2] = {
575 d3d12test::transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE),
576 d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)};
577 list->ResourceBarrier(2, to_source);
578 D3D12_TEXTURE_COPY_LOCATION src{target.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
579 src.SubresourceIndex = 0;
580 D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
581 dst.PlacedFootprint = foot;
582 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
583 list->CopyBufferRegion(readback.p, 4096, buffer.p, 0, 4 * kWords);
584 const D3D12_RESOURCE_BARRIER back_again[2] = {
585 d3d12test::transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET),
586 d3d12test::transition(buffer.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)};
587 list->ResourceBarrier(2, back_again);
588 CHECK(SUCCEEDED(list->Close()));
589 return true;
590 }
591
592 ReplayResult submit() {
593 ID3D12CommandList* lists[] = {list.p};
594 queue->ExecuteCommandLists(1, lists);
595 const ReplayResult result = rt::d3d12::last_execute_result(queue.p);
596 queue->Signal(fence.p, ++fence_value);
597 fence->SetEventOnCompletion(fence_value, nullptr);
598 return result;
599 }
600
601 // What the shaders stored and drew; `dropped` is the compute program that was not built, whose word stays 0. The
602 // readback buffer is cleared, so stale bytes cannot pass.
603 bool right(int dropped = -1) {
604 void* mapped = nullptr;
605 CHECK(SUCCEEDED(readback->Map(0, nullptr, &mapped)) && mapped);
606 auto* bytes = static_cast<std::uint8_t*>(mapped);
607 bool ok = true;
608 std::uint32_t words[kWords];
609 std::memcpy(words, bytes + 4096, sizeof words);
610 for (const unsigned n : compute) {
611 const std::uint32_t want = int(n) == dropped ? 0 : programs[n].run(n);
612 if (words[n] != want) {
613 std::fprintf(stderr, "compute program %u stored 0x%08x, not 0x%08x\n", n, words[n], want);
614 ok = false;
615 }
616 }
617 for (unsigned n = 0; graphics && n < kGraphics; ++n)
618 for (unsigned y = 0; y < 2; ++y)
619 for (unsigned x = 2 * n; x < 2 * n + 2; ++x) {
620 const auto* pixel = bytes + foot.Offset + y * foot.Footprint.RowPitch + 4 * x;
621 if (pixel[0] != n || pixel[1] != 255 - n || pixel[2] != 0 || pixel[3] != 255) {
622 std::fprintf(stderr, "graphics pipeline %u drew %u %u %u %u\n", n, pixel[0], pixel[1], pixel[2],
623 pixel[3]);
624 ok = false;
625 }
626 }
627 std::memset(bytes, 0xee, 4096 + 4 * kWords);
628 readback->Unmap(0, nullptr);
629 return ok;
630 }
631};
632
633std::vector<unsigned> all_compute() {
634 std::vector<unsigned> out;
635 for (unsigned n = 0; n < kCompute; ++n) out.push_back(n);
636 return out;
637}
638
639std::uint64_t estimate(unsigned n) { return leonida::large_module_estimate(module_bytes[n]); }
640
641// How many of the large compute modules are in the driver at once, with five threads to compile them; 0: not known (the
642// budget is read from the machine).
643int expected_at_once() {
644 if (serial) return 1;
645 if (unlimited) return 5;
646 if (!fixed_budget) return 0;
647 // The first wave is the largest, in order, while they fit.
648 std::uint64_t sum = 0;
649 int count = 0;
650 for (unsigned n = kBig; n-- > 0 && sum + estimate(n) <= *fixed_budget; ++count) sum += estimate(n);
651 return std::clamp(count, 1, 5);
652}
653
654// The large compute modules are held back in the driver until as many as may be are in, and no more come.
655bool side_by_side(const Setup& setup) {
656 Ref<ID3D12Device> dev;
657 CHECK(setup.device("4", dev));
658 Pipelines pipelines;
659 Frame frame;
660 hooks.reset();
661 CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), false));
662 CHECK(hooks.creates() == 0); // nothing is compiled at creation
663 const int at_once = expected_at_once();
664 hooks.closed = true;
665 ReplayResult result = ReplayResult::unsupported;
666 std::thread submitting([&] { result = frame.submit(); });
667 const bool filled = hooks.wait_large(std::max(at_once, 1));
668 // With a thread to spare, the small ones are compiled while the large ones wait (unlimited: every thread has a large one).
669 const bool small_ones = unlimited || !at_once || hooks.wait([] { return hooks.small_done == int(kSmall); });
670 std::this_thread::sleep_for(300ms);
671 int held = 0;
672 {
673 std::lock_guard lock(hooks.mutex);
674 held = hooks.large_in;
675 }
676 hooks.open();
677 submitting.join();
678 CHECK(filled);
679 CHECK(!at_once || held == at_once);
680 CHECK(small_ones);
681 CHECK(result == ReplayResult::success && frame.right());
682 CHECK(hooks.over == 0);
683 CHECK(hooks.creates() == kCompute); // each once
684 CHECK(!at_once || hooks.most_large <= at_once || unlimited);
685 CHECK(frame.submit() == ReplayResult::success && frame.right() && hooks.creates() == kCompute);
686 return true;
687}
688
689// The same values whatever compiles them, without workers (each where prepare() meets it) and with them.
690bool same_values(const Setup& setup) {
691 for (const char* threads : {"0", "16"}) {
692 Ref<ID3D12Device> dev;
693 CHECK(setup.device(threads, dev));
694 Pipelines pipelines;
695 Frame frame;
696 hooks.reset();
697 CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), true));
698 CHECK(frame.submit() == ReplayResult::success && frame.right());
699 CHECK(hooks.over == 0);
700 CHECK(hooks.creates() == kCompute + kGraphics);
701 CHECK(*threads != '0' || hooks.most_large == 1);
702 }
703 return true;
704}
705
706// A graphics pipeline whose estimate is past the budget (or the one at a time of serial) is in alone among the large ones,
707// and the small ones are compiled beside it.
708bool graphics_among_the_large(const Setup& setup) {
709 Ref<ID3D12Device> dev;
710 CHECK(setup.device("4", dev));
711 Pipelines pipelines;
712 Frame frame;
713 hooks.reset();
714 CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), true));
715 hooks.closed = true;
716 ReplayResult result = ReplayResult::unsupported;
717 std::thread submitting([&] { result = frame.submit(); });
718 const bool one = hooks.wait_large(1);
719 const bool small_ones = unlimited || !expected_at_once() ||
720 hooks.wait([] { return hooks.small_done == int(kSmall); });
721 std::this_thread::sleep_for(300ms);
722 int held = 0;
723 bool first_is_graphics = false;
724 {
725 std::lock_guard lock(hooks.mutex);
726 held = hooks.large_in;
727 for (const Start& s : hooks.started)
728 if (s.large) {
729 first_is_graphics = s.program < 0;
730 break;
731 }
732 }
733 hooks.open();
734 submitting.join();
735 CHECK(one && small_ones);
736 if (budgeted && fixed_budget) CHECK(held == 1 && first_is_graphics); // the largest first
737 if (serial) CHECK(held == 1);
738 CHECK(result == ReplayResult::success && frame.right());
739 CHECK(hooks.over == 0);
740 CHECK(hooks.creates() == kCompute + kGraphics);
741 return true;
742}
743
744// Two large graphics pipelines and nothing else: one after the other, or both at once without a limit.
745bool graphics_only(const Setup& setup) {
746 Ref<ID3D12Device> dev;
747 CHECK(setup.device("4", dev));
748 Pipelines pipelines;
749 Frame frame;
750 hooks.reset();
751 CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, {}, true));
752 hooks.closed = true;
753 ReplayResult result = ReplayResult::unsupported;
754 std::thread submitting([&] { result = frame.submit(); });
755 const int at_once = unlimited ? 2 : 1;
756 const bool filled = hooks.wait_large(at_once);
757 std::this_thread::sleep_for(300ms);
758 int held = 0;
759 {
760 std::lock_guard lock(hooks.mutex);
761 held = hooks.large_in;
762 }
763 hooks.open();
764 submitting.join();
765 CHECK(filled);
766 if (!budgeted || fixed_budget) CHECK(held == at_once);
767 CHECK(result == ReplayResult::success && frame.right());
768 CHECK(hooks.over == 0 && hooks.creates() == kGraphics);
769 return true;
770}
771
772// The driver refuses one large compute module: its dispatch is dropped, the rest runs, and it is not tried again. Its place
773// goes to the next.
774bool refused(const Setup& setup) {
775 for (const char* threads : {"0", "4"}) {
776 Ref<ID3D12Device> dev;
777 CHECK(setup.device(threads, dev));
778 Pipelines pipelines;
779 Frame frame;
780 hooks.reset();
781 CHECK(pipelines.create(dev.p) && frame.create(dev.p, pipelines, all_compute(), false));
782 hooks.fail_large = 2;
783 CHECK(frame.submit() == ReplayResult::success);
784 int dropped = -1;
785 {
786 std::lock_guard lock(hooks.mutex);
787 int seen = 0;
788 for (const Start& s : hooks.started)
789 if (s.large && s.program >= 0 && seen++ == 2) dropped = s.program;
790 }
791 CHECK(dropped >= 0);
792 CHECK(frame.right(dropped));
793 CHECK(hooks.creates() == kCompute);
794 CHECK(frame.submit() == ReplayResult::success && frame.right(dropped));
795 CHECK(hooks.creates() == kCompute);
796 }
797 return true;
798}
799
800// Two queues submit the same pipelines at once: each is compiled once, the budget is kept, and nobody waits for ever.
801bool two_queues(const Setup& setup) {
802 Ref<ID3D12Device> dev;
803 CHECK(setup.device("4", dev));
804 Pipelines pipelines;
805 Frame frames[2];
806 CHECK(pipelines.create(dev.p));
807 auto backwards = all_compute();
808 std::reverse(backwards.begin(), backwards.end());
809 CHECK(frames[0].create(dev.p, pipelines, all_compute(), true));
810 CHECK(frames[1].create(dev.p, pipelines, backwards, true));
811 hooks.reset();
812 ReplayResult results[2]{};
813 std::thread threads[2];
814 for (int i = 0; i < 2; ++i) threads[i] = std::thread([&, i] { results[i] = frames[i].submit(); });
815 for (auto& t : threads) t.join();
816 for (int i = 0; i < 2; ++i) CHECK(results[i] == ReplayResult::success && frames[i].right());
817 CHECK(hooks.creates() == kCompute + kGraphics);
818 CHECK(hooks.over == 0);
819 return true;
820}
821
822// The device's last references are released by the thread whose submission compiles, with large ones waiting for room.
823bool device_destroyed(const Setup& setup) {
824 _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "1"); // read the cache at teardown, write no file
825 Ref<ID3D12Device> dev;
826 CHECK(setup.device("4", dev));
827 auto pipelines = std::make_unique<Pipelines>();
828 auto frame = std::make_unique<Frame>();
829 hooks.reset();
830 CHECK(pipelines->create(dev.p) && frame->create(dev.p, *pipelines, all_compute(), true));
831 hooks.track = true;
832 hooks.closed = true;
833 ReplayResult result = ReplayResult::unsupported;
834 bool ok = false;
835 std::thread submitting([&] {
836 result = frame->submit();
837 ok = frame->right();
838 frame.reset();
839 pipelines.reset();
840 });
841 const bool compiling = hooks.wait_large(1);
842 std::this_thread::sleep_for(100ms);
843 dev.reset();
844 hooks.open();
845 submitting.join();
846 _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0");
847 CHECK(compiling);
848 CHECK(result == ReplayResult::success && ok);
849 CHECK(hooks.cache_reads > 0);
850 CHECK(!hooks.cache_read_during_create);
851 CHECK(!hooks.cache_read_with_workers);
852 CHECK(hooks.live == 0);
853 return true;
854}
855
856// One place for large compiles. The warm-up thread has it, and wants the next one after it; a submission that needs four
857// others, one of which the warm-up thread waits to build, gets them all first, and builds that one itself.
858bool warmup(const Setup& setup) {
859 Ref<ID3D12Device> dev;
860 CHECK(setup.device("4", dev));
861 Pipelines pipelines;
862 Frame frame;
863 hooks.reset();
864 hooks.closed = true;
865 hooks.linger = 100ms;
866 CHECK(pipelines.create(dev.p));
867 if (!hooks.wait_large(1)) {
868 hooks.open();
869 CHECK(!"the warm-up thread compiles a large one");
870 }
871 std::thread::id warm;
872 int first = -1;
873 {
874 std::lock_guard lock(hooks.mutex);
875 for (const Start& s : hooks.started)
876 if (s.large) warm = s.thread, first = s.program;
877 }
878 CHECK(first == 0); // their sizes rise with their numbers
879 const std::vector<unsigned> wanted = {4, 5, 3, 1}; // 1 is what the warm-up thread builds after 0
880 CHECK(frame.create(dev.p, pipelines, wanted, false));
881 const std::size_t before = hooks.creates();
882 ReplayResult result = ReplayResult::unsupported;
883 std::thread submitting([&] { result = frame.submit(); });
884 std::this_thread::sleep_for(500ms);
885 const bool waits = hooks.creates() == before; // the place is taken
886 hooks.open();
887 submitting.join();
888 const bool done = result == ReplayResult::success && frame.right();
889 rt::d3d12::PipelineCompiler::instance().wait_idle(); // the warm-up thread builds the rest
890 std::vector<Start> started;
891 {
892 std::lock_guard lock(hooks.mutex);
893 started = hooks.started;
894 }
895 CHECK(waits);
896 CHECK(done);
897 CHECK(hooks.over == 0 && hooks.most_large == 1);
898 std::set<int> once;
899 for (const Start& s : started) once.insert(s.program);
900 CHECK(started.size() == kCompute && once.size() == kCompute); // each once
901 std::erase_if(started, [](const Start& s) { return !s.large; });
902 std::set<int> built;
903 for (std::size_t i = 1; i <= wanted.size(); ++i) {
904 CHECK(started[i].thread != warm); // none of the warm-up's between two of the submission's
905 built.insert(started[i].program);
906 }
907 CHECK(built == std::set<int>(wanted.begin(), wanted.end()));
908 for (std::size_t i = wanted.size() + 1; i < started.size(); ++i) CHECK(started[i].thread == warm);
909 return true;
910}
911
912// The large ones that four threads create at once are held back in the driver until as many as may be are in.
913bool eager(const Setup& setup) {
914 Ref<ID3D12Device> dev;
915 CHECK(setup.device("4", dev));
916 Pipelines pipelines;
917 Frame frame;
918 hooks.reset();
919 hooks.closed = true;
920 bool created = false;
921 std::thread creating([&] { created = pipelines.create(dev.p, 4); });
922 const bool one = hooks.wait_large(1);
923 std::this_thread::sleep_for(300ms);
924 int held = 0;
925 {
926 std::lock_guard lock(hooks.mutex);
927 held = hooks.large_in;
928 }
929 hooks.open();
930 creating.join();
931 CHECK(one && created);
932 CHECK(held == expected_at_once());
933 CHECK(hooks.over == 0 && hooks.creates() == kCompute);
934 CHECK(frame.create(dev.p, pipelines, all_compute(), false));
935 CHECK(frame.submit() == ReplayResult::success && frame.right());
936 CHECK(hooks.creates() == kCompute);
937 return true;
938}
939
940bool run(const Setup& setup, const std::string& scenario) {
941 if (scenario == "warmup") return warmup(setup);
942 if (scenario == "eager") return eager(setup);
943 return side_by_side(setup) && same_values(setup) && graphics_among_the_large(setup) && graphics_only(setup) &&
944 refused(setup) && two_queues(setup) && device_destroyed(setup);
945}
946
947} // namespace
948
949int main(int argc, char** argv) {
950 const std::string scenario = argc > 1 ? argv[1] : "";
951 vktest::Device vk;
952 vk.request_buffer_device_address = true;
953 const auto status = vk.initialize();
954 if (status == vktest::DeviceStatus::unavailable) return 77;
955 if (status != vktest::DeviceStatus::ready) return 1;
956 VkPhysicalDeviceProperties properties{};
957 vk.instance_fn<PFN_vkGetPhysicalDeviceProperties>("vkGetPhysicalDeviceProperties")(vk.physical, &properties);
958 if (!vk.buffer_device_address || !vk.enabled.shaderInt64) {
959 std::printf("SKIP: the GPU lacks bufferDeviceAddress or shaderInt64\n");
960 return 77;
961 }
962 if (properties.limits.maxPushConstantsSize < 144) {
963 std::printf("SKIP: maxPushConstantsSize %u, below the 144-byte block\n", properties.limits.maxPushConstantsSize);
964 return 77;
965 }
966 real_instance_proc = vk.instance_proc;
967 _putenv_s("LEONIDA_PIPELINE_CACHE_BYTES", "0"); // no session file in or out
968 if (scenario != "warmup") _putenv_s("LEONIDA_COMPUTE_WARMUP", "0"); // every compile is a submission's
969 const testfiles::ScratchDir library("leonida_big_compute_test");
970 if (!write_library(library.path())) return 1;
971 if (!run({&vk, library.path().string()}, scenario)) return 1;
972 if (vk.validation_errors()) {
973 std::fprintf(stderr, "FAIL: %u validation errors\n", vk.validation_errors());
974 return 1;
975 }
976 std::printf("d3d12_big_compute_test: passed on %s\n", properties.deviceName);
977 return 0;
978}
diff --git a/runtime/test/d3d12_compile_teardown_test.cpp b/runtime/test/d3d12_compile_teardown_test.cpp
index 116c2459d..f9344c069 100644
--- a/runtime/test/d3d12_compile_teardown_test.cpp
+++ b/runtime/test/d3d12_compile_teardown_test.cpp
@@ -16,7 +16,8 @@
16// racing many PSOs released at once with builds queued and one usually running, repeated. 16// racing many PSOs released at once with builds queued and one usually running, repeated.
17// restart a device made after the worker stopped gets a new one, and its builds run. 17// restart a device made after the worker stopped gets a new one, and its builds run.
18// exit stop_pipeline_compiles with a device alive: the queue goes, later builds are refused, a warm-up 18// exit stop_pipeline_compiles with a device alive: the queue goes, later builds are refused, a warm-up
19// is skipped and a dispatch (LEONIDA_ASYNC_PIPELINES on) builds its pipeline in place and runs. 19// is skipped and a dispatch (LEONIDA_ASYNC_PIPELINES on) builds its pipeline in place and runs;
20// save_pipeline_caches_at_exit then writes the session cache with the device alive, once.
20// After each case the compiler's thread is gone and the process's thread count is back where it was. 21// After each case the compiler's thread is gone and the process's thread count is back where it was.
21// No game data: the shader is test/glsl/cs_user_data.comp, the programs are made-up FSSM bytes. 22// No game data: the shader is test/glsl/cs_user_data.comp, the programs are made-up FSSM bytes.
22#include "shader_fixture_path.h" 23#include "shader_fixture_path.h"
@@ -423,6 +424,14 @@ int main() {
423 424
424 auto& compiler = PipelineCompiler::instance(); 425 auto& compiler = PipelineCompiler::instance();
425 EXPECT(!compiler.worker_running()); 426 EXPECT(!compiler.worker_running());
427 // llvmpipe keeps no pipelines in a VkPipelineCache (measured: vkGetPipelineCacheData returns the 32-byte header
428 // alone after the build), and the runtime writes no file of a bare header (save_session_pipeline_cache).
429 VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
430 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver};
431 reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
432 d.instance_proc(d.instance, "vkGetPhysicalDeviceProperties2"))(d.physical, &properties);
433 const bool caches = driver.driverID != VK_DRIVER_ID_MESA_LLVMPIPE;
434 const auto session_file = cache_dir / "pipeline_cache.session.bin";
426 435
427 // --- cache: one PSO built by the warm-up thread; the device writes the session cache at teardown ------------- 436 // --- cache: one PSO built by the warm-up thread; the device writes the session cache at teardown -------------
428 { 437 {
@@ -433,14 +442,7 @@ int main() {
433 EXPECT(built(s.psos[0])); 442 EXPECT(built(s.psos[0]));
434 s.release(); 443 s.release();
435 EXPECT(!compiler.worker_running()); 444 EXPECT(!compiler.worker_running());
436 // llvmpipe keeps no pipelines in a VkPipelineCache (measured: vkGetPipelineCacheData returns the 32-byte 445 EXPECT(std::filesystem::exists(session_file) == caches);
437 // header alone after the build), and the runtime writes no file of a bare header (save_session_pipeline_cache).
438 VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
439 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver};
440 reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
441 d.instance_proc(d.instance, "vkGetPhysicalDeviceProperties2"))(d.physical, &properties);
442 const bool caches = driver.driverID != VK_DRIVER_ID_MESA_LLVMPIPE;
443 EXPECT(std::filesystem::exists(cache_dir / "pipeline_cache.session.bin") == caches);
444 std::printf("cache: built in the background, session cache %s at teardown, worker joined\n", 446 std::printf("cache: built in the background, session cache %s at teardown, worker joined\n",
445 caches ? "written" : "not written (the driver keeps no pipelines in its cache)"); 447 caches ? "written" : "not written (the driver keeps no pipelines in its cache)");
446 } 448 }
@@ -660,10 +662,19 @@ int main() {
660 if (s.dispatch(pso, fresh)) return 1; 662 if (s.dispatch(pso, fresh)) return 1;
661 EXPECT(built(pso)); 663 EXPECT(built(pso));
662 EXPECT(compiler.stats().submitted == before.submitted); 664 EXPECT(compiler.stats().submitted == before.submitted);
665 // The process ends with the device alive (a title never releases it): the exit save writes the session
666 // cache now, not at a teardown that will not come, and only once.
667 std::error_code ec;
668 std::filesystem::remove(session_file, ec);
669 EXPECT(!std::filesystem::exists(session_file));
670 EXPECT(rt::d3d12::save_pipeline_caches_at_exit(1000));
671 EXPECT(std::filesystem::exists(session_file) == caches);
672 EXPECT(!rt::d3d12::save_pipeline_caches_at_exit(1000));
663 s.release(); // the device's teardown after the exit stop: nothing left to cancel or join 673 s.release(); // the device's teardown after the exit stop: nothing left to cancel or join
664 EXPECT(!compiler.worker_running()); 674 EXPECT(!compiler.worker_running());
665 EXPECT(rt::d3d12::live_pipeline_states() == 0); // no PSO of any case leaked 675 EXPECT(rt::d3d12::live_pipeline_states() == 0); // no PSO of any case leaked
666 std::printf("exit: queue dropped, later builds refused, a dispatch built its pipeline in place and ran\n"); 676 std::printf("exit: queue dropped, later builds refused, a dispatch built its pipeline in place and ran, "
677 "session cache %s with the device alive, once\n", caches ? "written" : "not written (llvmpipe)");
667 } 678 }
668 std::printf("ok\n"); 679 std::printf("ok\n");
669 return 0; 680 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 000000000..f25076759
--- /dev/null
+++ b/runtime/test/d3d12_compute_journal_test.cpp
@@ -0,0 +1,153 @@
1// Exercise one production compute PSO in each invocation. The same authored module, root signature and device
2// should give the same journal key in separate cold/warm processes. The readback proves the dispatch actually ran;
3// a journal hit or write is a separate observation from the production runtime, not inferred from these words.
4#include "vk_test_device.h"
5#include "d3d12_test_shaders.h"
6#include "shader_fixture_path.h"
7#include "test_temp_dir.h"
8#include "../shims/d3d12_com.h"
9#include "../src/shader_library.h"
10
11#include <array>
12#include <cstdio>
13#include <cstring>
14#include <fstream>
15
16using namespace d3d12test;
17
18#define CHECK(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0)
19
20namespace {
21int dispatch_once(ID3D12Device* dev, const std::vector<std::uint8_t>& container, UINT expected_sum) {
22 D3D12_ROOT_PARAMETER param{};
23 param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
24 D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
25 root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
26 root_desc.Desc_1_0 = {1, &param, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE};
27 const auto bytes = serialize_root_signature(root_desc);
28 CHECK(!bytes.empty());
29 Ref<ID3D12RootSignature> root;
30 CHECK(SUCCEEDED(dev->CreateRootSignature(0, bytes.data(), bytes.size(), IID_PPV_ARGS(&root.p))));
31 D3D12_COMPUTE_PIPELINE_STATE_DESC desc{};
32 desc.pRootSignature = root.p;
33 desc.CS = {container.data(), container.size()};
34 Ref<ID3D12PipelineState> pso;
35 CHECK(SUCCEEDED(dev->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso.p))));
36
37 using Counters = std::array<UINT, 2>;
38 const auto buffer = [&](Ref<ID3D12Resource>& dst, D3D12_HEAP_TYPE type, D3D12_RESOURCE_STATES state,
39 D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
40 const D3D12_HEAP_PROPERTIES heap{type};
41 const auto resource = buffer_desc(sizeof(Counters), flags);
42 return SUCCEEDED(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &resource, state, nullptr,
43 IID_PPV_ARGS(&dst.p)));
44 };
45 Ref<ID3D12Resource> upload, result, readback;
46 CHECK(buffer(upload, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ));
47 CHECK(buffer(result, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST,
48 D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS));
49 CHECK(buffer(readback, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST));
50 const D3D12_RANGE none{0, 0}, both{0, sizeof(Counters)};
51 void* mapped = nullptr;
52 CHECK(SUCCEEDED(upload->Map(0, &none, &mapped)) && mapped);
53 std::memset(mapped, 0, sizeof(Counters));
54 upload->Unmap(0, &both);
55
56 constexpr auto type = D3D12_COMMAND_LIST_TYPE_COMPUTE;
57 const D3D12_COMMAND_QUEUE_DESC queue_desc{type};
58 Ref<ID3D12CommandQueue> queue;
59 Ref<ID3D12CommandAllocator> allocator;
60 Ref<ID3D12GraphicsCommandList> list;
61 Ref<ID3D12Fence> fence;
62 CHECK(SUCCEEDED(dev->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
63 CHECK(SUCCEEDED(dev->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p))));
64 CHECK(SUCCEEDED(dev->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p))));
65 CHECK(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
66
67 list->CopyBufferRegion(result.p, 0, upload.p, 0, sizeof(Counters));
68 const auto ready = transition(result.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
69 list->ResourceBarrier(1, &ready);
70 list->SetComputeRootSignature(root.p);
71 list->SetPipelineState(pso.p);
72 const auto va = result->GetGPUVirtualAddress();
73 CHECK(va != 0);
74 list->SetComputeRootUnorderedAccessView(0, va);
75 list->Dispatch(4, 1, 1); // each group adds 1 to counter 0 and groupID.x + the authored term to counter 1
76 const auto copy = transition(result.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
77 list->ResourceBarrier(1, &copy);
78 list->CopyBufferRegion(readback.p, 0, result.p, 0, sizeof(Counters));
79 CHECK(SUCCEEDED(list->Close()));
80 ID3D12CommandList* lists[] = {list.p};
81 queue->ExecuteCommandLists(1, lists);
82 CHECK(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
83 CHECK(SUCCEEDED(queue->Signal(fence.p, 1)));
84 CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
85 mapped = nullptr;
86 CHECK(SUCCEEDED(readback->Map(0, &both, &mapped)) && mapped);
87 Counters got{};
88 std::memcpy(got.data(), mapped, sizeof(got));
89 readback->Unmap(0, &none);
90 if (got[0] != 4 || got[1] != expected_sum) {
91 std::fprintf(stderr, "compute journal: expected (4,%u), got (%u,%u)\n", expected_sum, got[0], got[1]);
92 return 1;
93 }
94 return 0;
95}
96} // namespace
97
98int main(int argc, char** argv) {
99 const bool second = argc == 2 && std::strcmp(argv[1], "--second-shader") == 0;
100 if (argc != 1 && !second) {
101 std::fputs("usage: d3d12_compute_journal_test [--second-shader]\n", stderr);
102 return 2;
103 }
104 // One additional constant per group in the second module: (1+2+3+4) versus (2+3+4+5).
105 const UINT expected_sum = second ? 14u : 10u;
106 const testfiles::ScratchDir scratch("leonida_compute_journal_test");
107 // Default CTest runs use disposable caches. An explicit cache directory lets the host preserve the exact
108 // same state for the second process; never infer a hit from runtime duration.
109 if (!GetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", nullptr, 0)) {
110 CHECK(SetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", (scratch.path() / "cache").c_str()));
111 }
112 {
113 vktest::Device vk;
114 vk.request_buffer_device_address = true;
115 const auto status = vk.initialize();
116 if (status == vktest::DeviceStatus::unavailable) return 77;
117 CHECK(status == vktest::DeviceStatus::ready);
118 if (!vk.buffer_device_address || !vk.pipeline_cache_control_enabled()) {
119 std::puts("SKIP: requires bufferDeviceAddress and enabled Vulkan 1.3 pipelineCreationCacheControl");
120 return 77;
121 }
122 const auto program = fssm_program({second ? 0x4a435332u : 0x4a435331u, 0x10203040u});
123 const auto container = shader_container(program);
124 const auto shader = vktest::shader_fixture_path(second ? LEONIDA_TEST_COUNTER_V2_SPV : LEONIDA_TEST_COUNTER_SPV);
125 CHECK(testfiles::copy_file(shader, scratch.path() / "counter.spv"));
126 std::ofstream index(scratch.path() / "index.json", std::ios::binary);
127 index << "{\"counter\":{\"stage\":\"cs\",\"fssm_sha256\":\"" << leonida::sha256_hex(program)
128 << "\",\"bindings\":[],\"push_constant_bytes\":144,\"local_size\":[1,1,1],"
129 "\"uses_code_base\":false,\"wave64\":false}}";
130 index.close();
131 CHECK(index);
132 rt::d3d12::VulkanDeviceInfo info{};
133 info.get_instance_proc = vk.instance_proc;
134 info.instance = vk.instance;
135 info.physical = vk.physical;
136 info.device = vk.device;
137 info.queue = vk.queue;
138 info.queue_family = vk.family;
139 info.buffer_device_address = vk.buffer_device_address;
140 info.pipeline_cache_control = vk.pipeline_cache_control_enabled();
141 info.shader_dir = scratch.path().string();
142 Ref<ID3D12Device> dev;
143 CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev.p))));
144 if (rt::d3d12::device_max_push_constants_size(dev.p) < 144) {
145 std::puts("SKIP: authored shader requires 144 push-constant bytes");
146 return 77;
147 }
148 CHECK(dispatch_once(dev.p, container, expected_sum) == 0);
149 }
150 CHECK(vktest::validation_error_count() == 0); // includes device teardown
151 std::printf("compute journal: direct Dispatch(4,1,1) copied both expected words (4,%u)\n", expected_sum);
152 return 0;
153}
diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp
index e1dcef0fd..05591a780 100644
--- a/runtime/test/d3d12_compute_test.cpp
+++ b/runtime/test/d3d12_compute_test.cpp
@@ -10,6 +10,7 @@
10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 10// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
11#include "shader_fixture_path.h" 11#include "shader_fixture_path.h"
12#include "test_temp_dir.h" 12#include "test_temp_dir.h"
13#include "d3d12_test_shaders.h"
13#include "vk_test_device.h" 14#include "vk_test_device.h"
14#include "host_wine.h" 15#include "host_wine.h"
15#include "../shims/d3d12_com.h" 16#include "../shims/d3d12_com.h"
@@ -42,7 +43,6 @@ using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE
42 std::uint64_t, const IID*, void**); 43 std::uint64_t, const IID*, void**);
43// Device slot 67 as amd_fidelityfx_upscaler_xbox.dll calls it: (desc, riid, out). 44// Device slot 67 as amd_fidelityfx_upscaler_xbox.dll calls it: (desc, riid, out).
44using XboxNativeComputePipelineFn = HRESULT(WINAPI*)(void* device, const void*, const IID*, void**); 45using XboxNativeComputePipelineFn = HRESULT(WINAPI*)(void* device, const void*, const IID*, void**);
45using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
46 46
47template<class T> 47template<class T>
48struct Ref { 48struct Ref {
@@ -103,19 +103,9 @@ std::vector<std::uint8_t> shader_container(const std::vector<std::uint8_t>& fssm
103 return out; 103 return out;
104} 104}
105 105
106// The shared helper: Windows 10's in-box d3d12.dll refuses the heap-directly-indexed flags at every version.
106std::vector<std::uint8_t> serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { 107std::vector<std::uint8_t> serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) {
107 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); 108 return d3d12test::serialize_root_signature(desc);
108 const auto fn = d3d12 ? reinterpret_cast<SerializeFn>(
109 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
110 : nullptr;
111 std::vector<std::uint8_t> out;
112 ID3DBlob* blob = nullptr;
113 if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) {
114 const auto* p = static_cast<const std::uint8_t*>(blob->GetBufferPointer());
115 out.assign(p, p + blob->GetBufferSize());
116 blob->Release();
117 }
118 return out;
119} 109}
120 110
121D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) { 111D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) {
@@ -495,6 +485,14 @@ int main() {
495 D3D12_RESOURCE_STATE_COMMON, nullptr, 485 D3D12_RESOURCE_STATE_COMMON, nullptr,
496 IID_PPV_ARGS(&inside.p)))); 486 IID_PPV_ARGS(&inside.p))));
497 EXPECT(inside->GetGPUVirtualAddress() + (1u << 20) <= capped_arena); 487 EXPECT(inside->GetGPUVirtualAddress() + (1u << 20) <= capped_arena);
488 // The existing buffer and the reserved range prevent a contiguous arena-sized allocation.
489 // A valid default buffer can still use a dedicated allocation and report a usable relative VA.
490 const auto no_slice = buffer_desc(capped_arena, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
491 Ref<ID3D12Resource> dedicated;
492 EXPECT(SUCCEEDED(capped->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &no_slice,
493 D3D12_RESOURCE_STATE_COMMON, nullptr,
494 IID_PPV_ARGS(&dedicated.p))));
495 EXPECT(dedicated->GetGPUVirtualAddress() >= capped_arena);
498 EXPECT(capped->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &too_large, D3D12_RESOURCE_STATE_COMMON, 496 EXPECT(capped->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &too_large, D3D12_RESOURCE_STATE_COMMON,
499 nullptr, IID_PPV_ARGS(&past.p)) == E_OUTOFMEMORY && !past.p); 497 nullptr, IID_PPV_ARGS(&past.p)) == E_OUTOFMEMORY && !past.p);
500 std::printf("arena: %llu MiB (device limits: maxBufferSize %llu MiB, maxMemoryAllocationSize %llu MiB); " 498 std::printf("arena: %llu MiB (device limits: maxBufferSize %llu MiB, maxMemoryAllocationSize %llu MiB); "
diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp
index 3d65fc740..25fa1f654 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) {
1402 return 0; 1402 return 0;
1403} 1403}
1404 1404
1405// LEONIDA_TEXTURE_REFRESH_ASYNC=1 (the d3d12_mapped_plane_async test): a texture the title maps and writes, and then
1406// reads on the GPU in its very first submission, has its bytes there, though the refresh pass runs on a worker: the
1407// submission fills a mapped texture that was never filled before it records anything (fill_first_mapped_textures).
1408int check_mapped_plane_first_use(ID3D12Device* device) {
1409 const char* who = "persistent slot-133 plane, first use";
1410 constexpr UINT width = 256, height = 8, size = width * height;
1411 void* pages = VirtualAlloc(nullptr, 65536, MEM_RESERVE, PAGE_NOACCESS);
1412 EXPECT(pages);
1413 EXPECT(VirtualAlloc(pages, size, MEM_COMMIT, PAGE_READWRITE) == pages);
1414 std::memset(pages, 61, size);
1415 GpuReader gpu;
1416 EXPECT(!gpu.init(device, size));
1417 D3D12_RESOURCE_DESC desc{};
1418 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
1419 desc.Width = width;
1420 desc.Height = height;
1421 desc.Format = DXGI_FORMAT_R8_UNORM;
1422 desc.SampleDesc.Count = desc.DepthOrArraySize = desc.MipLevels = 1;
1423 leonida::title_xg_layouts::note({UINT(desc.Dimension), UINT(desc.Format), height, 1, 1, width}, 1);
1424 Ref<ID3D12Resource> texture;
1425 EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture.p)), S_OK);
1426 void* mapped = nullptr;
1427 EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK);
1428 EXPECT(mapped == pages);
1429 EXPECT_HR(gpu.allocator->Reset(), S_OK);
1430 EXPECT_HR(gpu.list->Reset(gpu.allocator.p, nullptr), S_OK);
1431 D3D12_RESOURCE_BARRIER barrier{};
1432 barrier.Transition = {texture.p, 0, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE};
1433 gpu.list->ResourceBarrier(1, &barrier);
1434 D3D12_TEXTURE_COPY_LOCATION src{texture.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
1435 D3D12_TEXTURE_COPY_LOCATION dst{gpu.readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
1436 dst.PlacedFootprint.Footprint = {desc.Format, width, height, 1, width};
1437 gpu.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
1438 EXPECT_HR(gpu.list->Close(), S_OK);
1439 ID3D12CommandList* lists[]{gpu.list.p};
1440 gpu.queue->ExecuteCommandLists(1, lists);
1441 EXPECT_HR(gpu.queue->Signal(gpu.fence.p, 1), S_OK);
1442 EXPECT_HR(gpu.fence->SetEventOnCompletion(1, gpu.done), S_OK);
1443 EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0);
1444 void* read = nullptr;
1445 EXPECT_HR(gpu.readback->Map(0, nullptr, &read), S_OK);
1446 const auto* bytes = static_cast<const std::uint8_t*>(read);
1447 const bool filled = std::all_of(bytes, bytes + size, [](auto value) { return value == 61; });
1448 gpu.readback->Unmap(0, nullptr);
1449 EXPECT(filled);
1450 texture->Unmap(0, nullptr);
1451 texture.p->Release();
1452 texture.p = nullptr;
1453 VirtualFree(pages, 0, MEM_RELEASE);
1454 return 0;
1455}
1456
1405// Several threads write the same watched pages while submissions keep making them read-only again. Two threads that 1457// Several threads write the same watched pages while submissions keep making them read-only again. Two threads that
1406// fault on one page race: the first fault reopens it, a submission can protect it again before the second fault is 1458// fault on one page race: the first fault reopens it, a submission can protect it again before the second fault is
1407// handled, and the second write must still be retried, not refused (refused, the process ends: seen natively). After 1459// 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<Case>& cases, const char* who) {
1990 2042
1991int main(int argc, char** argv) { 2043int main(int argc, char** argv) {
1992 const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0; 2044 const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0;
1993 if (argc != 1 && !prefix_only) return 2; 2045 const bool async_plane = argc == 2 && std::strcmp(argv[1], "--mapped-plane-async") == 0;
2046 if (argc != 1 && !prefix_only && !async_plane) return 2;
2047 if (async_plane) _putenv_s("LEONIDA_TEXTURE_REFRESH_ASYNC", "1"); // read once, at the device's first refresh
1994 _putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0"); 2048 _putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0");
1995 _putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0"); 2049 _putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0");
1996 vktest::Device vk; 2050 vktest::Device vk;
@@ -2018,6 +2072,15 @@ int main(int argc, char** argv) {
2018 const int result = check_host_prefix_buffers(ours.p); 2072 const int result = check_host_prefix_buffers(ours.p);
2019 return result || vk.validation_errors() ? 1 : 0; 2073 return result || vk.validation_errors() ? 1 : 0;
2020 } 2074 }
2075 if (async_plane) {
2076 int result = vk.host_image_copy ? check_mapped_plane_first_use(ours.p) : 0;
2077 auto no_host_copy = info; // the staged upload too
2078 no_host_copy.host_image_copy = false;
2079 Ref<ID3D12Device> staged;
2080 if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1;
2081 result += check_mapped_plane_first_use(staged.p);
2082 return result || vk.validation_errors() ? 1 : 0;
2083 }
2021 failures += check(ours.p, "vulkan"); 2084 failures += check(ours.p, "vulkan");
2022 const std::vector<Case> vulkan_cases = open_cases(ours.p); 2085 const std::vector<Case> vulkan_cases = open_cases(ours.p);
2023 print_cases(vulkan_cases, "vulkan"); 2086 print_cases(vulkan_cases, "vulkan");
diff --git a/runtime/test/d3d12_f16_halves_test.cpp b/runtime/test/d3d12_f16_halves_test.cpp
index bbd516e5c..866153041 100644
--- a/runtime/test/d3d12_f16_halves_test.cpp
+++ b/runtime/test/d3d12_f16_halves_test.cpp
@@ -123,6 +123,61 @@ std::vector<std::uint32_t> make_16param_vs() {
123 return w; 123 return w;
124} 124}
125 125
126// Fullscreen triangle VS exporting 10 raw params (0..9) with packed f16 bits in param7.
127std::vector<std::uint32_t> make_10param_vs() {
128 constexpr std::uint32_t kBound = 45;
129 std::vector<std::uint32_t> w = {kSpirvMagic, 0x00010500u, 0, kBound, 0};
130 put_inst(w, kOpCapability, {1});
131 put_inst(w, kOpMemoryModel, {0, 1});
132 std::vector<std::uint32_t> ep = {kExecModelVertex, 24, 0x6e69616du, 0x00000000u, 8, 9};
133 for (std::uint32_t id = 31; id <= 40; ++id) ep.push_back(id);
134 put_inst_vec(w, kOpEntryPoint, ep);
135
136 put_inst(w, kOpDecorate, {8, 11, 42}); // BuiltIn VertexIndex
137 put_inst(w, kOpDecorate, {9, 11, 0}); // BuiltIn Position
138 for (std::uint32_t p = 0; p < 10; ++p) put_inst(w, kOpDecorate, {31 + p, kDecorationLocation, p});
139
140 put_inst(w, 19, {1});
141 put_inst(w, 33, {2, 1});
142 put_inst(w, kOpTypeFloat, {3, 32});
143 put_inst(w, kOpTypeVector, {4, 3, 4});
144 put_inst(w, kOpTypeInt, {5, 32, 1});
145 put_inst(w, kOpTypePointer, {6, kStorageInput, 5});
146 put_inst(w, kOpTypePointer, {7, kStorageOutput, 4});
147 put_inst(w, 20, {20});
148
149 put_inst(w, kOpConstantNull, {4, 10});
150 put_inst(w, 43, {3, 11, 0xbf800000u});
151 put_inst(w, 43, {3, 12, 0x40400000u});
152 put_inst(w, 43, {3, 13, 0x00000000u});
153 put_inst(w, 43, {3, 14, 0x3f800000u});
154 put_inst(w, 44, {4, 15, 11, 11, 13, 14});
155 put_inst(w, 44, {4, 16, 12, 11, 13, 14});
156 put_inst(w, 44, {4, 17, 11, 12, 13, 14});
157 put_inst(w, 43, {5, 18, 0u});
158 put_inst(w, 43, {5, 19, 1u});
159 put_inst(w, 43, {3, 21, 0x3a003400u});
160 put_inst(w, 43, {3, 22, 0x3c003800u});
161 put_inst(w, 44, {4, 23, 21, 22, 13, 14});
162
163 put_inst(w, kOpVariable, {6, 8, kStorageInput});
164 put_inst(w, kOpVariable, {7, 9, kStorageOutput});
165 for (std::uint32_t id = 31; id <= 40; ++id) put_inst(w, kOpVariable, {7, id, kStorageOutput});
166
167 put_inst(w, kOpFunction, {1, 24, 0, 2});
168 put_inst(w, 248, {25});
169 put_inst(w, kOpLoad, {5, 26, 8});
170 put_inst(w, 170, {20, 27, 26, 18});
171 put_inst(w, 170, {20, 28, 26, 19});
172 put_inst(w, 169, {4, 29, 28, 16, 17});
173 put_inst(w, 169, {4, 30, 27, 15, 29});
174 put_inst(w, kOpStore, {9, 30});
175 for (std::uint32_t p = 0; p < 10; ++p) put_inst(w, kOpStore, {31 + p, p == 7 ? 23u : 10u});
176 put_inst(w, kOpReturn, {});
177 put_inst(w, kOpFunctionEnd, {});
178 return w;
179}
180
126// Fragment shader reading `num_raw` raw inputs (Location 0..num_raw-1) plus decoded halves of param7 at 181// Fragment shader reading `num_raw` raw inputs (Location 0..num_raw-1) plus decoded halves of param7 at
127// `lo_loc` and `hi_loc`, writing vec4(lo.x, hi.x, lo.y, hi.y) to MRT 0. 182// `lo_loc` and `hi_loc`, writing vec4(lo.x, hi.x, lo.y, hi.y) to MRT 0.
128std::vector<std::uint32_t> make_f16_ps(std::uint32_t num_raw, std::uint32_t lo_loc, std::uint32_t hi_loc) { 183std::vector<std::uint32_t> make_f16_ps(std::uint32_t num_raw, std::uint32_t lo_loc, std::uint32_t hi_loc) {
@@ -184,27 +239,38 @@ int main() {
184 const auto vs_prog = fssm_program({0x56530378, 0xbf810000}); 239 const auto vs_prog = fssm_program({0x56530378, 0xbf810000});
185 const auto ps1_prog = fssm_program({0x50530378, 0x00000001}); 240 const auto ps1_prog = fssm_program({0x50530378, 0x00000001});
186 const auto ps2_prog = fssm_program({0x50530378, 0x00000002}); 241 const auto ps2_prog = fssm_program({0x50530378, 0x00000002});
242 const auto vs_low_prog = fssm_program({0x56530378, 0xbf810010});
243 const auto ps_low_prog = fssm_program({0x50530378, 0x00000010});
187 const auto vs_c = shader_container(vs_prog); 244 const auto vs_c = shader_container(vs_prog);
188 const auto ps1_c = shader_container(ps1_prog); 245 const auto ps1_c = shader_container(ps1_prog);
189 const auto ps2_c = shader_container(ps2_prog); 246 const auto ps2_c = shader_container(ps2_prog);
247 const auto vs_low_c = shader_container(vs_low_prog);
248 const auto ps_low_c = shader_container(ps_low_prog);
190 249
191 const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_f16_halves_gpu_test"; 250 const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_f16_halves_gpu_test";
192 std::filesystem::create_directories(lib_dir); 251 std::filesystem::create_directories(lib_dir);
193 write_spv(lib_dir / "vs_16p.spv", make_16param_vs()); 252 write_spv(lib_dir / "vs_16p.spv", make_16param_vs());
253 write_spv(lib_dir / "vs_10p.spv", make_10param_vs());
194 write_spv(lib_dir / "ps_packed.spv", make_f16_ps(15, 20, 21)); 254 write_spv(lib_dir / "ps_packed.spv", make_f16_ps(15, 20, 21));
195 write_spv(lib_dir / "ps_reloc.spv", make_f16_ps(14, 14, 15)); 255 write_spv(lib_dir / "ps_reloc.spv", make_f16_ps(14, 14, 15));
256 write_spv(lib_dir / "ps_low.spv", make_f16_ps(8, 8, 9));
196 { 257 {
197 std::ofstream idx(lib_dir / "index.json", std::ios::binary | std::ios::trunc); 258 std::ofstream idx(lib_dir / "index.json", std::ios::binary | std::ios::trunc);
198 idx << "{\"vs_16p\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_prog) 259 idx << "{\"vs_16p\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_prog)
199 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [], " 260 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [], "
200 "\"f16_halves\": {\"0\": [28, 29], \"1\": [26, 27], \"2\": [24, 25], \"3\": [22, 23], " 261 "\"f16_halves\": {\"0\": [28, 29], \"1\": [26, 27], \"2\": [24, 25], \"3\": [22, 23], "
201 "\"4\": [20, 21], \"5\": [18, 19], \"6\": [16, 17]}},\n" 262 "\"4\": [20, 21], \"5\": [18, 19], \"6\": [16, 17]}},\n"
263 " \"vs_10p\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_low_prog)
264 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [], \"f16_halves\": {}},\n"
202 " \"ps_packed\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps1_prog) 265 " \"ps_packed\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps1_prog)
203 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " 266 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], "
204 "\"f16_halves\": {\"7\": [20, 21]}},\n" 267 "\"f16_halves\": {\"7\": [20, 21]}},\n"
205 " \"ps_reloc\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps2_prog) 268 " \"ps_reloc\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps2_prog)
206 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " 269 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], "
207 "\"f16_halves\": {\"7\": [14, 15]}}}"; 270 "\"f16_halves\": {\"7\": [14, 15]}},\n"
271 " \"ps_low\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_low_prog)
272 << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], "
273 "\"f16_halves\": {\"7\": [8, 9]}}}";
208 } 274 }
209 275
210 rt::d3d12::VulkanDeviceInfo info{}; 276 rt::d3d12::VulkanDeviceInfo info{};
@@ -363,5 +429,151 @@ int main() {
363 429
364 EXPECT(run_case("ps_packed (synth param7 + demote static halves)", ps1_c)); 430 EXPECT(run_case("ps_packed (synth param7 + demote static halves)", ps1_c));
365 EXPECT(run_case("ps_reloc (relocate colliding PS + VS halves to 28,29)", ps2_c)); 431 EXPECT(run_case("ps_reloc (relocate colliding PS + VS halves to 28,29)", ps2_c));
432
433 // Verify low f16_half_top_location (14) through CreateGraphicsPipelineState and lazy build at first draw:
434 {
435 rt::d3d12::VulkanDeviceInfo low_info = info;
436 low_info.f16_half_top_location = 14;
437
438 ID3D12Device* low_inner = nullptr;
439 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(low_info, IID_PPV_ARGS(&low_inner))));
440 Ref<ID3D12Device> low_device;
441 EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(low_inner, __uuidof(ID3D12Device),
442 reinterpret_cast<void**>(&low_device.p), false)));
443 rt::d3d12::set_device_outer(low_inner, low_device.p);
444
445 Ref<ID3D12RootSignature> low_root;
446 EXPECT(SUCCEEDED(low_device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&low_root.p))));
447
448 // 1. Out-of-budget pipeline with 16 params rejected at CreateGraphicsPipelineState
449 D3D12_GRAPHICS_PIPELINE_STATE_DESC oob_pd{};
450 oob_pd.pRootSignature = low_root.p;
451 oob_pd.VS = {vs_c.data(), vs_c.size()};
452 oob_pd.PS = {ps2_c.data(), ps2_c.size()};
453 oob_pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
454 oob_pd.SampleMask = 0xffffffffu;
455 oob_pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
456 oob_pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
457 oob_pd.RasterizerState.DepthClipEnable = TRUE;
458 oob_pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
459 oob_pd.NumRenderTargets = 1;
460 oob_pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
461 oob_pd.SampleDesc.Count = 1;
462 Ref<ID3D12PipelineState> oob_pso;
463 EXPECT(FAILED(low_device->CreateGraphicsPipelineState(&oob_pd, IID_PPV_ARGS(&oob_pso.p))));
464 std::printf("ps_oob (16 raw params rejected with top_location 14) OK\n");
465
466 // 2. In-budget pipeline (10 params, halves relocated to 13,14) created and executed lazily on draw
467 Ref<ID3D12CommandQueue> low_queue;
468 EXPECT(SUCCEEDED(low_device->CreateCommandQueue(&qd, IID_PPV_ARGS(&low_queue.p))));
469 Ref<ID3D12CommandAllocator> low_alloc;
470 EXPECT(SUCCEEDED(low_device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&low_alloc.p))));
471 Ref<ID3D12GraphicsCommandList> low_list;
472 EXPECT(SUCCEEDED(low_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, low_alloc.p, nullptr,
473 IID_PPV_ARGS(&low_list.p))));
474 EXPECT(SUCCEEDED(low_list->Close()));
475 Ref<ID3D12Fence> low_fence;
476 EXPECT(SUCCEEDED(low_device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&low_fence.p))));
477
478 Ref<ID3D12Resource> low_rt_res;
479 EXPECT(SUCCEEDED(low_device->CreateCommittedResource(&default_hp, D3D12_HEAP_FLAG_NONE, &rt_desc,
480 D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
481 IID_PPV_ARGS(&low_rt_res.p))));
482 Ref<ID3D12DescriptorHeap> low_rtv_heap;
483 EXPECT(SUCCEEDED(low_device->CreateDescriptorHeap(&rtv_hd, IID_PPV_ARGS(&low_rtv_heap.p))));
484 const D3D12_CPU_DESCRIPTOR_HANDLE low_rtv_h{
485 SIZE_T(reinterpret_cast<XboxHeapHandleFn>(slot(low_rtv_heap.p, 9))(low_rtv_heap.p))};
486 low_device->CreateRenderTargetView(low_rt_res.p, nullptr, low_rtv_h);
487
488 Ref<ID3D12Resource> low_rb_res;
489 EXPECT(SUCCEEDED(low_device->CreateCommittedResource(&rb_hp, D3D12_HEAP_FLAG_NONE, &rb_desc,
490 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
491 IID_PPV_ARGS(&low_rb_res.p))));
492
493 D3D12_GRAPHICS_PIPELINE_STATE_DESC in_pd = oob_pd;
494 in_pd.VS = {vs_low_c.data(), vs_low_c.size()};
495 in_pd.PS = {ps_low_c.data(), ps_low_c.size()};
496 Ref<ID3D12PipelineState> low_pso;
497 EXPECT(SUCCEEDED(low_device->CreateGraphicsPipelineState(&in_pd, IID_PPV_ARGS(&low_pso.p))));
498 EXPECT(SUCCEEDED(low_alloc->Reset()));
499 EXPECT(SUCCEEDED(low_list->Reset(low_alloc.p, low_pso.p)));
500 const float clear_col[4] = {0.0f, 0.0f, 0.0f, 0.0f};
501 low_list->ClearRenderTargetView(low_rtv_h, clear_col, 0, nullptr);
502 low_list->OMSetRenderTargets(1, &low_rtv_h, FALSE, nullptr);
503 const D3D12_VIEWPORT vp = {0.0f, 0.0f, float(kSize), float(kSize), 0.0f, 1.0f};
504 const D3D12_RECT sc = {0, 0, LONG(kSize), LONG(kSize)};
505 low_list->RSSetViewports(1, &vp);
506 low_list->RSSetScissorRects(1, &sc);
507 low_list->SetGraphicsRootSignature(low_root.p);
508 low_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
509 low_list->DrawInstanced(3, 1, 0, 0);
510
511 D3D12_RESOURCE_BARRIER to_copy{};
512 to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
513 to_copy.Transition = {low_rt_res.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
514 D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE};
515 low_list->ResourceBarrier(1, &to_copy);
516 D3D12_TEXTURE_COPY_LOCATION dst{};
517 dst.pResource = low_rb_res.p;
518 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
519 dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, 256};
520 D3D12_TEXTURE_COPY_LOCATION src{};
521 src.pResource = low_rt_res.p;
522 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
523 low_list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
524 D3D12_RESOURCE_BARRIER to_rt = to_copy;
525 to_rt.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE;
526 to_rt.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
527 low_list->ResourceBarrier(1, &to_rt);
528 EXPECT(SUCCEEDED(low_list->Close()));
529
530 ID3D12CommandList* cl = low_list.p;
531 low_queue->ExecuteCommandLists(1, &cl);
532 EXPECT(SUCCEEDED(low_queue->Signal(low_fence.p, 1)));
533 EXPECT(SUCCEEDED(low_fence->SetEventOnCompletion(1, nullptr)));
534
535 void* mapped = nullptr;
536 const D3D12_RANGE read_range = {0, kSize * 256};
537 EXPECT(SUCCEEDED(low_rb_res->Map(0, &read_range, &mapped)) && mapped != nullptr);
538 const auto* px = static_cast<const std::uint8_t*>(mapped) + (kSize / 2) * 256 + (kSize / 2) * 4;
539 const int r = px[0], g = px[1], b = px[2], a = px[3];
540 low_rb_res->Unmap(0, nullptr);
541 const bool ok = std::abs(r - 64) <= 1 && std::abs(g - 191) <= 1 && std::abs(b - 128) <= 1 && a == 255;
542 if (!ok) {
543 std::fprintf(stderr, "ps_low_top_location (lazy build at first draw with top_location 14): pixel=(%d,%d,%d,%d), expected~(64,191,128,255)\n", r, g, b, a);
544 return 1;
545 }
546 std::printf("ps_low_top_location (lazy build at first draw with top_location 14): rendered pixel=(%d,%d,%d,%d) OK\n", r, g, b, a);
547
548 // Check the linked SPIR-V stage modules: with f16_half_top_location = 14, every relocated f16
549 // output/input Location must be <= 14 (specifically, relocated to 13 and 14). Without the fix,
550 // stage_words() defaulted top_location to 29 and relocated them to Location 28 & 29.
551 std::vector<std::vector<std::uint32_t>> words;
552 std::string stage_error;
553 EXPECT(rt::d3d12::pipeline_stage_words(low_pso.p, words, stage_error));
554 EXPECT(words.size() >= 2);
555 for (std::size_t s = 0; s < 2; ++s) {
556 Module mod;
557 EXPECT(mod.parse(words[s]));
558 std::uint32_t highest_loc = 0;
559 for (const auto& inst : mod.insts) {
560 if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation) {
561 highest_loc = std::max(highest_loc, inst.words[3]);
562 }
563 }
564 if (highest_loc > 14) {
565 std::fprintf(stderr, "ps_low_top_location stage %zu highest Location %u exceeds top_location 14\n",
566 s, highest_loc);
567 return 1;
568 }
569 if (highest_loc != 14) {
570 std::fprintf(stderr, "ps_low_top_location stage %zu expected highest Location 14, got %u\n",
571 s, highest_loc);
572 return 1;
573 }
574 std::printf("ps_low_top_location stage %zu linked SPIR-V highest Location=%u <= 14 OK\n", s, highest_loc);
575 }
576 }
577
366 return 0; 578 return 0;
367} 579}
diff --git a/runtime/test/d3d12_indirect_rt_test.cpp b/runtime/test/d3d12_indirect_rt_test.cpp
index 3a58e48c0..7b237ef30 100644
--- a/runtime/test/d3d12_indirect_rt_test.cpp
+++ b/runtime/test/d3d12_indirect_rt_test.cpp
@@ -1,12 +1,18 @@
1// Real GPU test for: 1// Real GPU test for:
2// 1) D3D12 draw-signature creation and a native Vulkan counted-draw pixel reference. 2// Real GPU test for:
3// The pixel reference tests suballocated argument/count offsets, not D3D12 command replay. 3// 1) ExecuteIndirect with CountBuffer (ID3D12Device::CreateCommandSignature +
4// ID3D12GraphicsCommandList::ExecuteIndirect -> vkCmdDrawIndirectCount, Vulkan 1.2 core), and the argument clamp
5// pass (runtime/src/vulkan_indirect_clamp.h): a draw record asking for four billion instances is clamped on the
6// GPU and renders the same triangle as the in-range one, instead of running until the host resets the driver.
7// The same pixel reference is also run natively: D3D12 draw-signature creation and a Vulkan counted-draw pixel
8// reference over suballocated argument/count offsets, independent of the D3D12 command replay.
4// 2) Hardware Ray Tracing / BVH (ID3D12Device5::GetRaytracingAccelerationStructurePrebuildInfo + 9// 2) Hardware Ray Tracing / BVH (ID3D12Device5::GetRaytracingAccelerationStructurePrebuildInfo +
5// ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure BLAS + TLAS + RayQueryKHR 10// ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure BLAS + TLAS + RayQueryKHR
6// hit vs. miss; clean SKIP on GPUs without VK_KHR_acceleration_structure / VK_KHR_ray_query). 11// hit vs. miss; clean SKIP on GPUs without VK_KHR_acceleration_structure / VK_KHR_ray_query).
7// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (Core + Synchronization Validation). 12// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (Core + Synchronization Validation).
8 13
9#include "../shims/d3d12_com.h" 14#include "../shims/d3d12_com.h"
15#include "../src/vulkan_indirect_clamp.h"
10#include "vulkan_loader.h" 16#include "vulkan_loader.h"
11#include "../src/vulkan_device_filter.h" 17#include "../src/vulkan_device_filter.h"
12 18
@@ -76,6 +82,38 @@ D3D12_RESOURCE_DESC make_buf_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D
76 return d; 82 return d;
77} 83}
78 84
85// A driver whose GENERIC acceleration structures do not sit at buffer address + offset, through the device's own
86// function lookup (VulkanDeviceInfo::get_instance_proc): vkGetAccelerationStructureDeviceAddressKHR answers the real
87// address plus kShiftedAsDelta. Only resource creation and the address lookup run on such a device, no builds: the
88// shifted address names no real structure.
89constexpr VkDeviceAddress kShiftedAsDelta = 0x10000000;
90PFN_vkGetInstanceProcAddr g_real_gipa = nullptr;
91PFN_vkGetDeviceProcAddr g_real_gdpa = nullptr;
92PFN_vkGetAccelerationStructureDeviceAddressKHR g_real_as_address = nullptr;
93
94VKAPI_ATTR VkDeviceAddress VKAPI_CALL shifted_as_address(VkDevice device,
95 const VkAccelerationStructureDeviceAddressInfoKHR* info) {
96 const VkDeviceAddress real = g_real_as_address(device, info);
97 return real ? real + kShiftedAsDelta : 0;
98}
99
100VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL shifted_gdpa(VkDevice device, const char* name) {
101 if (!std::strcmp(name, "vkGetAccelerationStructureDeviceAddressKHR")) {
102 g_real_as_address =
103 reinterpret_cast<PFN_vkGetAccelerationStructureDeviceAddressKHR>(g_real_gdpa(device, name));
104 return g_real_as_address ? reinterpret_cast<PFN_vkVoidFunction>(&shifted_as_address) : nullptr;
105 }
106 return g_real_gdpa(device, name);
107}
108
109VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL shifted_gipa(VkInstance instance, const char* name) {
110 if (!std::strcmp(name, "vkGetDeviceProcAddr")) {
111 g_real_gdpa = reinterpret_cast<PFN_vkGetDeviceProcAddr>(g_real_gipa(instance, name));
112 return reinterpret_cast<PFN_vkVoidFunction>(&shifted_gdpa);
113 }
114 return g_real_gipa(instance, name);
115}
116
79} // namespace 117} // namespace
80 118
81int main() { 119int main() {
@@ -291,6 +329,7 @@ int main() {
291 DF(vkCreateComputePipelines); 329 DF(vkCreateComputePipelines);
292 DF(vkDestroyPipeline); 330 DF(vkDestroyPipeline);
293 DF(vkCreateDescriptorSetLayout); 331 DF(vkCreateDescriptorSetLayout);
332 DF(vkGetAccelerationStructureDeviceAddressKHR);
294 DF(vkDestroyDescriptorSetLayout); 333 DF(vkDestroyDescriptorSetLayout);
295 DF(vkCreateDescriptorPool); 334 DF(vkCreateDescriptorPool);
296 DF(vkDestroyDescriptorPool); 335 DF(vkDestroyDescriptorPool);
@@ -500,6 +539,51 @@ int main() {
500 cbai.commandBufferCount = 1; 539 cbai.commandBufferCount = 1;
501 vkAllocateCommandBuffers(vk_dev, &cbai, &cb); 540 vkAllocateCommandBuffers(vk_dev, &cbai, &cb);
502 541
542 leonida::ReplayFunctions rf{};
543 rf.external_graphics_scope = true; // bind the graphics pipeline inside our own rendering scope below
544 rf.draw_indirect_count = vkCmdDrawIndirectCount;
545 // The argument clamp pass (runtime/src/vulkan_indirect_clamp.h), installed as gta6rt installs it: every
546 // record of the ExecuteIndirect is copied on the GPU into scratch with its values bounded before the draw
547 // reads it, so a record left by a skipped compute pass cannot ask for four billion vertices or instances.
548 // A device without bufferDeviceAddress keeps the raw path.
549 VkPhysicalDeviceMemoryProperties mem_props{};
550 reinterpret_cast<PFN_vkGetPhysicalDeviceMemoryProperties>(
551 gipa(instance, "vkGetPhysicalDeviceMemoryProperties"))(physical, &mem_props);
552 const auto clamp_allocate = [&](const VkMemoryRequirements& requirements) -> VkDeviceMemory {
553 VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO};
554 flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
555 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags};
556 ai.allocationSize = requirements.size;
557 const auto allocate = reinterpret_cast<PFN_vkAllocateMemory>(gdpa(vk_dev, "vkAllocateMemory"));
558 for (const std::uint32_t type : leonida::memory_type_order(mem_props, requirements.memoryTypeBits,
559 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0,
560 requirements.size)) {
561 ai.memoryTypeIndex = type;
562 VkDeviceMemory out = VK_NULL_HANDLE;
563 if (allocate(vk_dev, &ai, nullptr, &out) == VK_SUCCESS) return out;
564 }
565 return VK_NULL_HANDLE;
566 };
567 leonida::IndirectArgumentClamp clamp(gdpa, vk_dev, mem_props, chosen.limits, clamp_allocate);
568 auto clamp_batch = clamp.batch();
569 // LEONIDA_INDIRECT_CLAMP=0 turns the pass off at replay time, and then the raw argument buffer is read
570 // again: this test must not record its own pass either.
571 const bool clamp_on = clamp.loaded() && leonida::indirect_clamp_enabled();
572 if (clamp_on) {
573 rf.prepare_indirect_clamp = [&clamp_batch](VkBuffer args, VkDeviceSize args_offset, VkBuffer count,
574 VkDeviceSize count_offset, std::uint32_t kind,
575 std::uint32_t stride, std::uint32_t max_count,
576 leonida::ClampedIndirect& out) {
577 return clamp_batch->prepare(args, args_offset, count, count_offset, kind, stride, max_count, out);
578 };
579 rf.emit_indirect_clamp = [&clamp](VkCommandBuffer buffer, const leonida::ClampedIndirect& job) {
580 clamp.emit(buffer, job);
581 };
582 }
583
584 // The native reference draws the same suballocated offsets with vkCmdDrawIndirectCount directly: a
585 // Vulkan-level pixel oracle for the counted draw, not a D3D12 command replay. Both bindings start after
586 // poison prefixes, and the buffer holds the same two records the command list replays below.
503 auto run_native_count = [&](VkDeviceSize count_offset, std::uint8_t exp_r, std::uint8_t exp_g, 587 auto run_native_count = [&](VkDeviceSize count_offset, std::uint8_t exp_r, std::uint8_t exp_g,
504 std::uint8_t exp_b) -> int { 588 std::uint8_t exp_b) -> int {
505 VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; 589 VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
@@ -580,8 +664,166 @@ int main() {
580 return 0; 664 return 0;
581 }; 665 };
582 666
667 // The same two records through the D3D12 command list and leonida::replay, so the ExecuteIndirect
668 // CountBuffer path - and the clamp pass it emits - is exercised, not just the native Vulkan call.
669 auto run_indirect_count = [&](std::uint64_t count_offset, std::uint8_t exp_r, std::uint8_t exp_g,
670 std::uint8_t exp_b) -> int {
671 leonida::CommandList ir;
672 ir.execute_indirect({leonida::IndirectKind::draw, sizeof(D3D12_DRAW_ARGUMENTS), 2u,
673 rt::d3d12::resource_id(arg_buf), 0, rt::d3d12::resource_id(count_buf),
674 count_offset});
675 ir.close();
676
677 // The clamp pass is recorded here, before the drawing scope: vkCmdCopyBuffer and a memory barrier with
678 // a transfer access are outside it (VUID-vkCmdCopyBuffer-renderpass), which is also where gta6rt
679 // emits it for an indirect draw. replay then reads the clamped scratch whose records it is told about.
680 leonida::ClampedIndirect clamped{};
681 const bool has_clamp = clamp_on;
682 if (has_clamp) {
683 if (!clamp_batch->prepare(rt::d3d12::vulkan_buffer(arg_buf), argument_base,
684 rt::d3d12::vulkan_buffer(count_buf), count_base + count_offset,
685 leonida::indirect_clamp_draw, sizeof(D3D12_DRAW_ARGUMENTS), 2u, clamped))
686 return fail("clamp prepare");
687 }
688
689 VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
690 bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
691 vkBeginCommandBuffer(cb, &bi);
692 if (has_clamp) clamp.emit(cb, clamped);
693
694 VkImageMemoryBarrier b_to_rt{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
695 b_to_rt.srcAccessMask = 0;
696 b_to_rt.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
697 b_to_rt.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
698 b_to_rt.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
699 b_to_rt.image = rt::d3d12::vulkan_image(rt);
700 b_to_rt.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
701 vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
702 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0, nullptr, 1,
703 &b_to_rt);
704
705 VkRenderingAttachmentInfo att{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO};
706 att.imageView = rt_view;
707 att.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
708 att.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
709 att.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
710 att.clearValue.color.float32[3] = 1.0f;
711 VkRenderingInfo ri{VK_STRUCTURE_TYPE_RENDERING_INFO};
712 ri.renderArea = {{0, 0}, {kW, kH}};
713 ri.layerCount = 1;
714 ri.colorAttachmentCount = 1;
715 ri.pColorAttachments = &att;
716 vkCmdBeginRendering(cb, &ri);
717 VkViewport vp{0, 0, float(kW), float(kH), 0, 1};
718 VkRect2D sc{{0, 0}, {kW, kH}};
719 vkCmdSetViewport(cb, 0, 1, &vp);
720 vkCmdSetScissor(cb, 0, 1, &sc);
721 vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pso);
722
723 const auto resolver = [&](leonida::ResourceId id) -> const leonida::ResourceBinding* {
724 // Treat the two upload buffers as backing stores for slices that start after a prefix.
725 static leonida::ResourceBinding arg_b{}, cnt_b{};
726 arg_b.buffer = rt::d3d12::vulkan_buffer(arg_buf);
727 arg_b.buffer_offset = argument_base;
728 arg_b.size = buffer_size - argument_base;
729 cnt_b.buffer = rt::d3d12::vulkan_buffer(count_buf);
730 cnt_b.buffer_offset = count_base;
731 cnt_b.size = buffer_size - count_base;
732 if (id == rt::d3d12::resource_id(arg_buf)) return &arg_b;
733 if (id == rt::d3d12::resource_id(count_buf)) return &cnt_b;
734 return nullptr;
735 };
736 if (has_clamp) {
737 rf.prepare_indirect_clamp = [&clamped](VkBuffer, VkDeviceSize, VkBuffer, VkDeviceSize, std::uint32_t,
738 std::uint32_t, std::uint32_t,
739 leonida::ClampedIndirect& out) {
740 out = clamped; // prepared and emitted above, before the drawing scope
741 return true;
742 };
743 rf.emit_indirect_clamp = [](VkCommandBuffer, const leonida::ClampedIndirect&) {};
744 } else {
745 rf.prepare_indirect_clamp = {};
746 rf.emit_indirect_clamp = {};
747 }
748 const auto replayed = leonida::replay(ir, cb, resolver, rf);
749 if (replayed != leonida::ReplayResult::success) {
750 std::fprintf(stderr, "replay result %d (clamped=%d)\n", int(replayed), int(has_clamp));
751 return fail("leonida::replay(ExecuteIndirect CountBuffer)");
752 }
753
754 vkCmdEndRendering(cb);
755
756 VkImageMemoryBarrier b_to_src{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
757 b_to_src.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
758 b_to_src.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
759 b_to_src.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
760 b_to_src.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
761 b_to_src.image = rt::d3d12::vulkan_image(rt);
762 b_to_src.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
763 vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
764 0, 0, nullptr, 0, nullptr, 1, &b_to_src);
765
766 VkBufferImageCopy bic{};
767 bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
768 bic.imageExtent = {kW, kH, 1};
769 vkCmdCopyImageToBuffer(cb, rt::d3d12::vulkan_image(rt), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
770 rt::d3d12::vulkan_buffer(rb), 1, &bic);
771
772 VkMemoryBarrier host_b{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
773 host_b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
774 host_b.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
775 vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host_b, 0,
776 nullptr, 0, nullptr);
777 if (vkEndCommandBuffer(cb) != VK_SUCCESS) return fail("end replayed counted draw");
778
779 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO};
780 si.commandBufferCount = 1;
781 si.pCommandBuffers = &cb;
782 vkQueueSubmit(vk_queue, 1, &si, VK_NULL_HANDLE);
783 vkQueueWaitIdle(vk_queue);
784 // The clamp's record scratch is idle now: hand it back for the next run, as a completed submission does.
785 clamp.retire(VK_NULL_HANDLE, 0);
786 clamp.collect();
787
788 void* mp = nullptr;
789 if (FAILED(rb->Map(0, nullptr, &mp)) || !mp) return fail("map replayed counted-draw readback");
790 const auto* px = static_cast<const std::uint8_t*>(mp);
791 const bool ok = std::abs(int(px[0]) - int(exp_r)) <= 1 && std::abs(int(px[1]) - int(exp_g)) <= 1 &&
792 std::abs(int(px[2]) - int(exp_b)) <= 1 && px[3] == 255;
793 rb->Unmap(0, nullptr);
794 if (!ok) return fail("replayed counted-draw pixel mismatch");
795 return 0;
796 };
797
583 if (run_native_count(0, 0, 0, 0) != 0) return 1; // count = 0 -> black 798 if (run_native_count(0, 0, 0, 0) != 0) return 1; // count = 0 -> black
584 if (run_native_count(4, 32, 160, 240) != 0) return 1; // count = 1 -> triangle 799 if (run_native_count(4, 32, 160, 240) != 0) return 1; // count = 1 -> triangle
800 if (run_indirect_count(0, 0, 0, 0) != 0) return 1; // count = 0 -> black, through replay
801 if (run_indirect_count(4, 32, 160, 240) != 0) return 1; // count = 1 -> triangle, through replay
802 if (clamp_on) {
803 // What a skipped or mistranslated compute pass leaves: an instance count of four billion, and a count
804 // buffer past max_command_count. The clamp cuts the instances to 2^26 / 3 and the count to
805 // max_command_count, so this draw completes in milliseconds instead of running until the host resets
806 // the display driver - and the triangle it renders is the same one.
807 void* mapped = nullptr;
808 if (FAILED(arg_buf->Map(0, nullptr, &mapped))) return fail("Map(indirect arguments) again");
809 auto* draws = reinterpret_cast<D3D12_DRAW_ARGUMENTS*>(static_cast<std::uint8_t*>(mapped) + argument_base);
810 draws[0] = {3, 0xFFFFFFFFu, 0, 0};
811 arg_buf->Unmap(0, nullptr);
812 if (FAILED(count_buf->Map(0, nullptr, &mapped))) return fail("Map(indirect count) again");
813 *reinterpret_cast<std::uint32_t*>(static_cast<std::uint8_t*>(mapped) + count_base) = 0xFFFFFFFFu;
814 count_buf->Unmap(0, nullptr);
815 if (run_indirect_count(0, 32, 160, 240) != 0) return 1; // count is clamped to max_command_count
816 // Read the pass's counters: destroying the batch releases its slots, as a completed submission does.
817 clamp_batch.reset();
818 const auto counters = clamp.counters();
819 if (counters.records_clamped != 1 || counters.counts_clamped != 1)
820 return fail("clamp counters after a garbage record");
821 std::printf(" [PASS] a draw record of 0xFFFFFFFF instances is clamped on the GPU (%llu record(s), "
822 "%llu count(s), %llu over the batch budget)\n",
823 static_cast<unsigned long long>(counters.records_clamped),
824 static_cast<unsigned long long>(counters.counts_clamped),
825 static_cast<unsigned long long>(counters.over_budget));
826 }
585 827
586 vkDestroyCommandPool(vk_dev, pool, nullptr); 828 vkDestroyCommandPool(vk_dev, pool, nullptr);
587 vkDestroyImageView(vk_dev, rt_view, nullptr); 829 vkDestroyImageView(vk_dev, rt_view, nullptr);
@@ -590,7 +832,8 @@ int main() {
590 rb->Release(); 832 rb->Release();
591 rt->Release(); 833 rt->Release();
592 std::printf(" [PASS] native Vulkan counted-draw reference with suballocated argument/count offsets " 834 std::printf(" [PASS] native Vulkan counted-draw reference with suballocated argument/count offsets "
593 "(count=0 black, count=1 solid triangle)\n"); 835 "(count=0 black, count=1 solid triangle), and the same records through the D3D12\n"
836 " ExecuteIndirect replay (count=0 black, count=1 triangle)\n");
594 } else { 837 } else {
595 std::printf(" [SKIP] native counted-draw reference: drawIndirectCount unsupported\n"); 838 std::printf(" [SKIP] native counted-draw reference: drawIndirectCount unsupported\n");
596 } 839 }
@@ -757,6 +1000,63 @@ int main() {
757 rt::d3d12::vulkan_acceleration_structure(dev, tlas_ptr_buf->GetGPUVirtualAddress()); 1000 rt::d3d12::vulkan_acceleration_structure(dev, tlas_ptr_buf->GetGPUVirtualAddress());
758 if (!tlas_vk || !tlas_ptr_vk) return fail("vulkan_acceleration_structure(TLAS)"); 1001 if (!tlas_vk || !tlas_ptr_vk) return fail("vulkan_acceleration_structure(TLAS)");
759 1002
1003 // The instance above holds the BLAS's GetGPUVirtualAddress(). Vulkan wants a value obtained from
1004 // vkGetAccelerationStructureDeviceAddressKHR there (VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-12281),
1005 // so every AS resource's GPU VA must be what the driver reports for the structure behind it. GPU-assisted
1006 // validation only accepts addresses it has seen that call return.
1007 if (!vkGetAccelerationStructureDeviceAddressKHR) return fail("vkGetAccelerationStructureDeviceAddressKHR");
1008 for (ID3D12Resource* as_buf : {blas_buf, tlas_buf, tlas_ptr_buf}) {
1009 const D3D12_GPU_VIRTUAL_ADDRESS va = as_buf->GetGPUVirtualAddress();
1010 VkAccelerationStructureDeviceAddressInfoKHR dai{
1011 VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR};
1012 dai.accelerationStructure = rt::d3d12::vulkan_acceleration_structure(dev, va);
1013 if (!dai.accelerationStructure) return fail("vulkan_acceleration_structure(AS resource)");
1014 const VkDeviceAddress driver_va = vkGetAccelerationStructureDeviceAddressKHR(vk_dev, &dai);
1015 if (driver_va != va) {
1016 std::fprintf(stderr,
1017 "FAIL: AS resource GPU VA 0x%llx, vkGetAccelerationStructureDeviceAddressKHR 0x%llx\n",
1018 static_cast<unsigned long long>(va), static_cast<unsigned long long>(driver_va));
1019 return 1;
1020 }
1021 }
1022 std::printf(" [PASS] AS resource GPU VAs are the driver's acceleration structure addresses\n");
1023
1024 // The same on a driver that answers another address than buffer address + offset: the resource's GPU VA is
1025 // the driver's, the arena address still names the structure, and releasing the resource forgets both.
1026 {
1027 g_real_gipa = gipa;
1028 rt::d3d12::VulkanDeviceInfo shifted_info = info;
1029 shifted_info.get_instance_proc = &shifted_gipa;
1030 ID3D12Device5* shifted = nullptr;
1031 if (FAILED(rt::d3d12::create_vulkan_device(shifted_info, IID_PPV_ARGS(&shifted))) || !shifted)
1032 return fail("create_vulkan_device(shifted AS addresses)");
1033 ID3D12Resource* as_buf = nullptr;
1034 if (FAILED(shifted->CreateCommittedResource(&def_hp, D3D12_HEAP_FLAG_NONE, &blas_desc,
1035 D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE,
1036 nullptr, IID_PPV_ARGS(&as_buf))))
1037 return fail("CreateCommittedResource(AS, shifted addresses)");
1038 const D3D12_GPU_VIRTUAL_ADDRESS va = as_buf->GetGPUVirtualAddress();
1039 VkAccelerationStructureDeviceAddressInfoKHR dai{
1040 VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR};
1041 dai.accelerationStructure = rt::d3d12::vulkan_acceleration_structure(shifted, va);
1042 if (!dai.accelerationStructure) return fail("shifted AS: the GPU VA does not name the structure");
1043 const VkDeviceAddress buffer_va = vkGetAccelerationStructureDeviceAddressKHR(vk_dev, &dai);
1044 if (va != buffer_va + kShiftedAsDelta) {
1045 std::fprintf(stderr, "FAIL: shifted AS: GPU VA 0x%llx, driver address 0x%llx\n",
1046 static_cast<unsigned long long>(va),
1047 static_cast<unsigned long long>(buffer_va + kShiftedAsDelta));
1048 return 1;
1049 }
1050 if (rt::d3d12::vulkan_acceleration_structure(shifted, buffer_va) != dai.accelerationStructure)
1051 return fail("shifted AS: the arena address does not name the structure");
1052 as_buf->Release();
1053 if (rt::d3d12::vulkan_acceleration_structure(shifted, va) ||
1054 rt::d3d12::vulkan_acceleration_structure(shifted, buffer_va))
1055 return fail("shifted AS: an address still names the structure after Release");
1056 shifted->Release();
1057 std::printf(" [PASS] a driver address other than buffer address + offset is the GPU VA; both freed\n");
1058 }
1059
760 // BLAS compaction size (inline postbuild + standalone 2-source EmitPostbuild), CLONE, COMPACT, and 1060 // BLAS compaction size (inline postbuild + standalone 2-source EmitPostbuild), CLONE, COMPACT, and
761 // negative rejection checks. 1061 // negative rejection checks.
762 ID3D12Fence* copy_fence = nullptr; 1062 ID3D12Fence* copy_fence = nullptr;
diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp
index 97a4e8600..05d6fe153 100644
--- a/runtime/test/d3d12_m4_compute_test.cpp
+++ b/runtime/test/d3d12_m4_compute_test.cpp
@@ -28,6 +28,7 @@
28#include "vk_test_device.h" 28#include "vk_test_device.h"
29#include "d3d12_test_shaders.h" 29#include "d3d12_test_shaders.h"
30#include "../shims/d3d12_com.h" 30#include "../shims/d3d12_com.h"
31#include "../shims/d3d12_pipeline_compile.h"
31#include "../shims/d3d12_xs_device.h" 32#include "../shims/d3d12_xs_device.h"
32#include "../src/shader_library.h" 33#include "../src/shader_library.h"
33#include "../src/vulkan_indirect_clamp.h" 34#include "../src/vulkan_indirect_clamp.h"
@@ -96,7 +97,8 @@ Reference reference() {
96 97
97} // namespace 98} // namespace
98 99
99int main() { 100int main(int argc, char** argv) {
101 const bool check_journal = argc == 2 && std::strcmp(argv[1], "--check-async-journal") == 0;
100 vktest::Device d; 102 vktest::Device d;
101 d.queue_count_wanted = 2; // the copy queue and the compute queue each get a VkQueue where the family has two 103 d.queue_count_wanted = 2; // the copy queue and the compute queue each get a VkQueue where the family has two
102 const auto device_status = d.initialize(); 104 const auto device_status = d.initialize();
@@ -129,6 +131,7 @@ int main() {
129 info.queue_family = d.family; 131 info.queue_family = d.family;
130 if (distinct_queues) info.command_queues = d.queues; 132 if (distinct_queues) info.command_queues = d.queues;
131 info.buffer_device_address = true; 133 info.buffer_device_address = true;
134 info.pipeline_cache_control = d.pipeline_cache_control();
132 info.bindless = d.bindless; 135 info.bindless = d.bindless;
133 info.bindless_partially_bound = d.partially_bound; 136 info.bindless_partially_bound = d.partially_bound;
134 info.image_view_min_lod = d.image_view_min_lod; 137 info.image_view_min_lod = d.image_view_min_lod;
@@ -167,6 +170,24 @@ int main() {
167 pso_desc.CS = {indirect_container.data(), indirect_container.size()}; 170 pso_desc.CS = {indirect_container.data(), indirect_container.size()};
168 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_indirect.p)))); 171 EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_indirect.p))));
169 172
173 if (check_journal) {
174 // Check publication while the device and both PSOs are still alive. The async policy can
175 // drop a dispatch whose worker has not yet published its handle, so wait for these two.
176 EXPECT(rt::d3d12::async_replay_compile());
177 const auto deadline = GetTickCount64() + 30000;
178 while (rt::d3d12::PipelineCompiler::instance().stats().completed < 2 && GetTickCount64() < deadline)
179 Sleep(1);
180 EXPECT(rt::d3d12::PipelineCompiler::instance().stats().completed >= 2);
181 const auto* cache_dir = _wgetenv(L"LEONIDA_PIPELINE_CACHE_DIR");
182 EXPECT(cache_dir && *cache_dir);
183 unsigned entries = 0;
184 const auto dir = std::filesystem::path(cache_dir) / L"pipeline_cache.d";
185 EXPECT(std::filesystem::is_directory(dir));
186 for (const auto& file : std::filesystem::directory_iterator(dir))
187 if (file.path().extension() == L".bin" && file.file_size() > 32) ++entries;
188 EXPECT(entries == 2);
189 }
190
170 D3D12_INDIRECT_ARGUMENT_DESC argument{}; 191 D3D12_INDIRECT_ARGUMENT_DESC argument{};
171 argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; 192 argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
172 D3D12_COMMAND_SIGNATURE_DESC signature_desc{}; 193 D3D12_COMMAND_SIGNATURE_DESC signature_desc{};
diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp
index 2d9bc5212..775cfeb58 100644
--- a/runtime/test/d3d12_mesh_test.cpp
+++ b/runtime/test/d3d12_mesh_test.cpp
@@ -5,15 +5,16 @@
5// - With it: MeshShaderTier 1; CreatePipelineState builds an MS + PS PSO and a VS + PS PSO from streams laid out as 5// - With it: MeshShaderTier 1; CreatePipelineState builds an MS + PS PSO and a VS + PS PSO from streams laid out as
6// d3dx12.h lays them out (each subobject a type and its description, pointer-aligned); streams the PC runtime 6// d3dx12.h lays them out (each subobject a type and its description, pointer-aligned); streams the PC runtime
7// refuses (MS with VS, CS with PS, a subobject twice or in two versions, an unknown type, a truncated stream) are E_INVALIDARG, and 7// refuses (MS with VS, CS with PS, a subobject twice or in two versions, an unknown type, a truncated stream) are E_INVALIDARG, and
8// state not built yet (an amplification shader, a depth-bounds test) is E_NOTIMPL. 8// state not built yet (an amplification shader) is E_NOTIMPL; a depth-bounds test builds where the device
9// reports DepthBoundsTestSupported, and is E_NOTIMPL where it does not.
9// - Draws: DispatchMesh(2, 2, 1) with root constants (0, 0) and a red tint fills the top-left quadrant; 10// - Draws: DispatchMesh(2, 2, 1) with root constants (0, 0) and a red tint fills the top-left quadrant;
10// DispatchMesh(1, 1, 2) moved by (1, -1) with a green tint fills the top half of the bottom-right one, so the 11// DispatchMesh(1, 1, 2) moved by (1, -1) with a green tint fills the top half of the bottom-right one, so the
11// Y and Z counts reach the shader; the stream's VS PSO draws a full-screen triangle through a viewport on the 12// Y and Z counts reach the shader; the stream's VS PSO draws a full-screen triangle through a viewport on the
12// bottom-left quadrant (yellow). Each pixel is read back and compared. 13// bottom-left quadrant (yellow). Each pixel is read back and compared.
13// - A vertex draw with the mesh PSO, and DispatchMesh with the VS one, fail at execution (ReplayResult:: 14// - A vertex draw with the mesh PSO, and DispatchMesh with the VS one, fail at execution (ReplayResult::
14// invalid_draw); a mesh grid beyond D3D12's limits fails at Close; an empty grid records nothing. 15// invalid_draw); a mesh grid beyond D3D12's limits fails at Close; an empty grid records nothing.
15// - A DISPATCH_MESH command signature is created only with the extension; ExecuteIndirect with it records nothing 16// - A DISPATCH_MESH command signature is created only with the extension; ExecuteIndirect with it draws as
16// yet, so its list closes. 17// DispatchMesh (one record {2, 1, 1} fills two cells), and without graphics state it records nothing and closes.
17// The shaders are GLSL written to the translator's contract (test/glsl/ms_draw.mesh, ps_draw.frag, vs_fullscreen.vert). 18// The shaders are GLSL written to the translator's contract (test/glsl/ms_draw.mesh, ps_draw.frag, vs_fullscreen.vert).
18// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. 19// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
19#include "vk_test_device.h" 20#include "vk_test_device.h"
@@ -317,7 +318,14 @@ int main(int argc, char** argv) {
317 D3D12_DEPTH_STENCIL_DESC1 bounds{}; 318 D3D12_DEPTH_STENCIL_DESC1 bounds{};
318 bounds.DepthBoundsTestEnable = TRUE; 319 bounds.DepthBoundsTestEnable = TRUE;
319 bad.add(DepthStencil1Subobject{.inner = bounds}); 320 bad.add(DepthStencil1Subobject{.inner = bounds});
320 EXPECT(create(device.p, bad, refused) == E_NOTIMPL && !refused.p); 321 {
322 D3D12_FEATURE_DATA_D3D12_OPTIONS2 o2{};
323 EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS2, &o2, sizeof o2)));
324 Ref<ID3D12PipelineState> with_bounds;
325 const HRESULT bounds_hr = create(device.p, bad, with_bounds);
326 EXPECT(o2.DepthBoundsTestSupported ? SUCCEEDED(bounds_hr) && with_bounds.p
327 : bounds_hr == E_NOTIMPL && !with_bounds.p);
328 }
321 329
322 // A console stream: its numbering has no gap at 23, so its mesh shader is 24 (the PC's AS) and its 330 // A console stream: its numbering has no gap at 23, so its mesh shader is 24 (the PC's AS) and its
323 // RASTERIZER1 26 (the PC's DEPTH_STENCIL2). An AS without an MS is no PC stream, so the layer reads it with the 331 // 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) {
468 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); 476 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
469 std::memcpy(pixels.data(), mapped, pixels.size()); 477 std::memcpy(pixels.data(), mapped, pixels.size());
470 478
479 // ExecuteIndirect with a DISPATCH_MESH signature draws as DispatchMesh (vkCmdDrawMeshTasksIndirectEXT after
480 // the clamp pass): one record {2, 1, 1} at upload + 768 fills columns 0 and 1 of row 0, the top half of the
481 // top-left quadrant, red; the rest of the cleared target stays blue.
482 {
483 const std::uint32_t record[3] = {2, 1, 1};
484 std::memcpy(up + 768, record, sizeof record);
485 const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH};
486 const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0};
487 Ref<ID3D12CommandSignature> sig;
488 Ref<ID3D12Fence> indirect_fence;
489 EXPECT(SUCCEEDED(device->CreateCommandSignature(&mesh_sig, nullptr, IID_PPV_ARGS(&sig.p))) && sig.p);
490 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&indirect_fence.p))));
491 EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, mesh_pso.p)));
492 D3D12_RESOURCE_BARRIER again =
493 transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET);
494 list->ResourceBarrier(1, &again);
495 list->ClearRenderTargetView(rtv, blue, 0, nullptr);
496 list->SetGraphicsRootSignature(root.p);
497 list->RSSetViewports(1, &viewport);
498 list->RSSetScissorRects(1, &scissor);
499 list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
500 list->SetGraphicsRoot32BitConstants(0, 2, origin, 0);
501 list->SetGraphicsRootConstantBufferView(1, upload_va);
502 list->ExecuteIndirect(sig.p, 1, upload.p, 768, nullptr, 0);
503 list->ResourceBarrier(1, &to_copy);
504 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
505 EXPECT(list->Close() == S_OK);
506 queue->ExecuteCommandLists(1, lists);
507 EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
508 EXPECT(SUCCEEDED(queue->Signal(indirect_fence.p, 1)) &&
509 SUCCEEDED(indirect_fence->SetEventOnCompletion(1, nullptr)));
510 unsigned wrong = 0;
511 for (UINT row = 0; row < size; ++row) {
512 for (UINT col = 0; col < size; ++col) {
513 const bool red = row < size / 4 && col < size / 2;
514 const std::uint8_t want[4] = {std::uint8_t(red ? 255 : 0), 0, std::uint8_t(red ? 0 : 255), 255};
515 const auto* got = static_cast<const std::uint8_t*>(mapped) + row * 256 + col * 4;
516 if (std::equal(want, want + 4, got)) continue;
517 if (wrong++ < 6)
518 std::fprintf(stderr, "indirect mesh pixel (%u, %u): got %u,%u,%u,%u want %u,%u,%u,%u\n", col,
519 row, got[0], got[1], got[2], got[3], want[0], want[1], want[2], want[3]);
520 }
521 }
522 EXPECT(!wrong);
523 std::printf("ExecuteIndirect DISPATCH_MESH {2, 1, 1} drew as DispatchMesh(2, 1, 1): %u pixels matched\n",
524 size * size);
525 }
526
471 // The wrong kind of draw for the pipeline fails at execution: a vertex draw with the mesh PSO, then 527 // The wrong kind of draw for the pipeline fails at execution: a vertex draw with the mesh PSO, then
472 // DispatchMesh with the VS PSO. 528 // DispatchMesh with the VS PSO.
473 for (const bool vertex_draw : {true, false}) { 529 for (const bool vertex_draw : {true, false}) {
@@ -591,8 +647,8 @@ int main(int argc, char** argv) {
591 enabled ? "" : " (LEONIDA_GRAPHICS_DIRECT_HEAPS=0: not written)"); 647 enabled ? "" : " (LEONIDA_GRAPHICS_DIRECT_HEAPS=0: not written)");
592 } 648 }
593 // A DISPATCH_MESH command signature (D3D12_DISPATCH_MESH_ARGUMENTS, 12 bytes) is created; a stride below its 649 // A DISPATCH_MESH command signature (D3D12_DISPATCH_MESH_ARGUMENTS, 12 bytes) is created; a stride below its
594 // 12 bytes is refused as the PC runtime refuses it. ExecuteIndirect with it records nothing yet (#3777 replays 650 // 12 bytes is refused as the PC runtime refuses it. ExecuteIndirect with it and no viewport records
595 // it), so the list still closes. 651 // nothing, so the list still closes.
596 { 652 {
597 const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; 653 const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH};
598 const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0}; 654 const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0};
diff --git a/runtime/test/d3d12_placed_depth_test.h b/runtime/test/d3d12_placed_depth_test.h
index 5ef9f88a9..73818e19b 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
34 const D3D12_CLEAR_VALUE* clear = nullptr) { 34 const D3D12_CLEAR_VALUE* clear = nullptr) {
35 return create(xbox, va, &shape, UINT_MAX, clear, IID_PPV_ARGS(&result.p)); 35 return create(xbox, va, &shape, UINT_MAX, clear, IID_PPV_ARGS(&result.p));
36 }; 36 };
37 if (opaque) {
38 auto packed = xbox_desc;
39 packed.Format = static_cast<DXGI_FORMAT>(118);
40 packed.Width = 1280;
41 packed.Height = 720;
42 Ptr<ID3D12Resource> target;
43 // The image is privately backed; reserve a full placement for its title VA.
44 Pages packed_pages{VirtualAlloc(nullptr, 8u << 20, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)};
45 const auto packed_va = reinterpret_cast<UINT64>(packed_pages.ptr);
46 if (!packed_va || FAILED(place(packed_va, packed, target)) ||
47 target->GetGPUVirtualAddress() != packed_va) return false;
48 target.reset();
49 }
37 Ptr<ID3D12Resource> first, alias, next, invalid; 50 Ptr<ID3D12Resource> first, alias, next, invalid;
38 if (FAILED(place(address, xbox_desc, first)) || FAILED(place(address, xbox_desc, alias)) || 51 if (FAILED(place(address, xbox_desc, first)) || FAILED(place(address, xbox_desc, alias)) ||
39 FAILED(place(address + allocation.SizeInBytes, xbox_desc, next))) return false; 52 FAILED(place(address + allocation.SizeInBytes, xbox_desc, next))) return false;
diff --git a/runtime/test/d3d12_set_descriptor_heaps_test.cpp b/runtime/test/d3d12_set_descriptor_heaps_test.cpp
index 62ffb1ffe..1251f77a7 100644
--- a/runtime/test/d3d12_set_descriptor_heaps_test.cpp
+++ b/runtime/test/d3d12_set_descriptor_heaps_test.cpp
@@ -344,6 +344,20 @@ bool check_tracking_lifetime_and_direct_indexing(DeviceHeaps& ours) {
344 const rt::d3d12::RootArgumentLayout* layout = rt::d3d12::root_signature_layout(root.p); 344 const rt::d3d12::RootArgumentLayout* layout = rt::d3d12::root_signature_layout(root.p);
345 CHECK(layout && (layout->flags & di_flags) == di_flags); 345 CHECK(layout && (layout->flags & di_flags) == di_flags);
346 346
347 // Direct heap indexing passes remapped console_descriptor_table_va into recorded user data.
348 ID3D12DescriptorHeap* heaps[2] = {ours.cbv1.p, ours.smp1.p};
349 list->SetDescriptorHeaps(2, heaps);
350 list->SetComputeRootSignature(root.p);
351 list->Dispatch(1, 1, 1);
352 std::vector<leonida::Command> cmds;
353 CHECK(rt::d3d12::recorded_commands(list.p, cmds) && !cmds.empty());
354 const auto* disp = std::get_if<leonida::Dispatch>(&cmds.back());
355 CHECK(disp != nullptr);
356 const auto expected_cbv = static_cast<std::uint32_t>(rt::d3d12::console_descriptor_table_va(cbv1_va));
357 const auto expected_smp = static_cast<std::uint32_t>(rt::d3d12::console_descriptor_table_va(smp1_va));
358 CHECK(disp->user_data[layout->compute_arguments_end] == expected_cbv);
359 CHECK(disp->user_data[layout->compute_arguments_end + 1] == expected_smp);
360
347 CHECK(!rt::d3d12::bound_descriptor_heap_bases(nullptr, got_cbv, got_smp)); 361 CHECK(!rt::d3d12::bound_descriptor_heap_bases(nullptr, got_cbv, got_smp));
348 return true; 362 return true;
349} 363}
diff --git a/runtime/test/d3d12_texture_tiles_test.cpp b/runtime/test/d3d12_texture_tiles_test.cpp
index fc08c3422..4d15415f3 100644
--- a/runtime/test/d3d12_texture_tiles_test.cpp
+++ b/runtime/test/d3d12_texture_tiles_test.cpp
@@ -6,9 +6,11 @@
6 6
7#include <algorithm> 7#include <algorithm>
8#include <array> 8#include <array>
9#include <cctype>
9#include <cstdint> 10#include <cstdint>
10#include <cstdio> 11#include <cstdio>
11#include <cstring> 12#include <cstring>
13#include <string>
12#include <vector> 14#include <vector>
13 15
14#define EXPECT(condition) do { \ 16#define EXPECT(condition) do { \
@@ -248,14 +250,55 @@ bool run(ID3D12Device& device, UINT width, UINT height, UINT64 tile_copy_offset,
248 return true; 250 return true;
249} 251}
250 252
251ComPtr<ID3D12Device> native_device() { 253// D3D12 on the adapter `luid` names, when it has tiled resources tier 2 or more; null otherwise.
254ComPtr<ID3D12Device> tiled_device(IDXGIFactory4& factory, LUID luid, bool print = true) {
255 ComPtr<IDXGIAdapter1> adapter;
256 if (!luid.LowPart && !luid.HighPart) return {};
257 if (FAILED(factory.EnumAdapterByLuid(luid, IID_PPV_ARGS(&adapter)))) return {};
258 DXGI_ADAPTER_DESC1 desc{};
259 ComPtr<ID3D12Device> device;
260 D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
261 if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) ||
262 FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device))) ||
263 FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))) ||
264 options.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_2)
265 return {};
266 if (print)
267 std::printf("Native D3D12: %ls (the layer's adapter), tiled resources tier %u\n", desc.Description,
268 unsigned(options.TiledResourcesTier));
269 return device;
270}
271
272// The host adapter for the native half. LEONIDA_HOST_ADAPTER picks it as in d3d12_copy_compare.h: "warp", or part of
273// an adapter name (case-insensitive); a value that names no adapter with tiled resources tier 2 skips the native half
274// rather than testing another GPU. Unset: the adapter behind the layer's Vulkan device (`layer_luid`, as
275// host_adapter.h picks it), so a PC with two GPUs compares the layer with its own GPU's driver; when that adapter
276// has no tier 2, the first hardware adapter with tier 2 or more.
277ComPtr<ID3D12Device> native_device(LUID layer_luid) {
252 ComPtr<IDXGIFactory4> factory; 278 ComPtr<IDXGIFactory4> factory;
253 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return {}; 279 if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return {};
280 char want[128] = {};
281 GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want));
282 std::string needle(want);
283 std::transform(needle.begin(), needle.end(), needle.begin(), [](unsigned char c) { return char(std::tolower(c)); });
284 if (needle.empty())
285 if (auto device = tiled_device(*factory.Get(), layer_luid)) return device;
254 for (UINT i = 0;; ++i) { 286 for (UINT i = 0;; ++i) {
255 ComPtr<IDXGIAdapter1> adapter; 287 ComPtr<IDXGIAdapter1> adapter;
256 if (factory->EnumAdapters1(i, &adapter) != S_OK) return {}; 288 if (needle == "warp") {
289 if (i > 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) break;
290 } else if (factory->EnumAdapters1(i, &adapter) != S_OK) {
291 break;
292 }
257 DXGI_ADAPTER_DESC1 desc{}; 293 DXGI_ADAPTER_DESC1 desc{};
258 if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue; 294 if (FAILED(adapter->GetDesc1(&desc))) continue;
295 if (needle.empty()) {
296 if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue;
297 } else if (needle != "warp") {
298 std::string name;
299 for (const wchar_t* c = desc.Description; *c; ++c) name += char(std::tolower(*c < 128 ? *c : '?'));
300 if (name.find(needle) == std::string::npos) continue;
301 }
259 ComPtr<ID3D12Device> device; 302 ComPtr<ID3D12Device> device;
260 if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) continue; 303 if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) continue;
261 D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; 304 D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
@@ -264,6 +307,10 @@ ComPtr<ID3D12Device> native_device() {
264 std::printf("Native D3D12: %ls, tiled resources tier %u\n", desc.Description, unsigned(options.TiledResourcesTier)); 307 std::printf("Native D3D12: %ls, tiled resources tier %u\n", desc.Description, unsigned(options.TiledResourcesTier));
265 return device; 308 return device;
266 } 309 }
310 if (!needle.empty())
311 std::printf("Native D3D12: no adapter matching LEONIDA_HOST_ADAPTER=%s with tiled resources tier 2 or more; "
312 "native half skipped\n", want);
313 return {};
267} 314}
268 315
269} // namespace 316} // namespace
@@ -283,7 +330,22 @@ int main() {
283 std::fputs("A texture with multiple mips did not use the committed fallback\n", stderr); 330 std::fputs("A texture with multiple mips did not use the committed fallback\n", stderr);
284 return 1; 331 return 1;
285 } 332 }
286 auto native = native_device(); 333 const LUID layer_luid = vulkan->GetAdapterLuid();
334 auto native = native_device(layer_luid);
335 if (native) {
336 // Unset LEONIDA_HOST_ADAPTER means the layer's own GPU whenever its driver can run the cases: comparing with
337 // another GPU's driver measures that driver, not the layer.
338 char want[2] = {};
339 const LUID host_luid = native->GetAdapterLuid();
340 ComPtr<IDXGIFactory4> factory;
341 if (!GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)) &&
342 SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) && tiled_device(*factory.Get(), layer_luid, false) &&
343 (host_luid.LowPart != layer_luid.LowPart || host_luid.HighPart != layer_luid.HighPart)) {
344 std::fprintf(stderr, "Native D3D12 runs on another adapter than the layer's, which has tiled resources "
345 "tier 2 or more\n");
346 return 1;
347 }
348 }
287 const auto* info = rt::d3d12::vulkan_device_info(vulkan.Get()); 349 const auto* info = rt::d3d12::vulkan_device_info(vulkan.Get());
288 const bool dedicated_copy = info && !info->copy_queues.empty() && info->copy_family != info->queue_family; 350 const bool dedicated_copy = info && !info->copy_queues.empty() && info->copy_family != info->queue_family;
289 struct ReplayCase { 351 struct ReplayCase {
diff --git a/runtime/test/d3d12_texture_uav_test.cpp b/runtime/test/d3d12_texture_uav_test.cpp
index f8ef5177b..d6774438e 100644
--- a/runtime/test/d3d12_texture_uav_test.cpp
+++ b/runtime/test/d3d12_texture_uav_test.cpp
@@ -243,15 +243,93 @@ bool flush_descriptors(ID3D12Device* device) {
243 return rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success; 243 return rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success;
244} 244}
245 245
246bool rejects_partial_clear(ID3D12Device* device, ID3D12Resource* resource, D3D12_CPU_DESCRIPTOR_HANDLE view) { 246bool check_partial_clear(ID3D12Device* device, ID3D12Resource* resource, D3D12_CPU_DESCRIPTOR_HANDLE whole,
247 D3D12_CPU_DESCRIPTOR_HANDLE partial, const D3D12_RESOURCE_DESC& shape,
248 UINT mip, UINT first, UINT writable) {
249 ComPtr<ID3D12CommandQueue> queue;
250 const D3D12_COMMAND_QUEUE_DESC qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT};
251 EXPECT(SUCCEEDED(device->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&queue))));
252 ComPtr<ID3D12Fence> fence;
253 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))));
247 ComPtr<ID3D12CommandAllocator> allocator; 254 ComPtr<ID3D12CommandAllocator> allocator;
248 ComPtr<ID3D12GraphicsCommandList> list; 255 ComPtr<ID3D12GraphicsCommandList> list;
249 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); 256 EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))));
250 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, 257 EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr,
251 IID_PPV_ARGS(&list)))); 258 IID_PPV_ARGS(&list))));
252 const UINT colors[4] = {42, 0, 0, 0}; 259 const UINT clear_value[4] = {42, 0, 0, 0};
253 list->ClearUnorderedAccessViewUint({}, view, resource, colors, 0, nullptr); 260 ID3D12CommandList* lists[] = {list.Get()};
254 return list->Close() == E_INVALIDARG; 261 if (shape.Format == DXGI_FORMAT_R32_TYPELESS) {
262 // The view is UINT and the backing is SFLOAT. 3D clear format reinterpretation is still unsupported.
263 list->ClearUnorderedAccessViewUint({}, partial, resource, clear_value, 0, nullptr);
264 EXPECT(SUCCEEDED(list->Close()));
265 queue->ExecuteCommandLists(1, lists);
266 return rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::unsupported;
267 }
268 const UINT w = std::max(1u, UINT(shape.Width) >> mip);
269 const UINT h = std::max(1u, shape.Height >> mip);
270 const UINT d = std::max(1u, UINT(shape.DepthOrArraySize) >> mip);
271 const UINT pitch = (w * 4 + 255) / 256 * 256;
272 const UINT64 total = UINT64(pitch) * h * d;
273 D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK};
274 D3D12_RESOURCE_DESC rb_desc{};
275 rb_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
276 rb_desc.Width = total;
277 rb_desc.Height = rb_desc.DepthOrArraySize = rb_desc.MipLevels = 1;
278 rb_desc.SampleDesc.Count = 1;
279 rb_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
280 ComPtr<ID3D12Resource> readback;
281 EXPECT(SUCCEEDED(device->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &rb_desc,
282 D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
283 IID_PPV_ARGS(&readback))));
284 // A known, nonzero sentinel makes loss of a neighboring slice observable even on a newly allocated image.
285 constexpr UINT sentinel = std::bit_cast<UINT>(1.0f);
286 const UINT seed[4] = {sentinel, 0, 0, 0};
287 list->ClearUnorderedAccessViewUint({}, whole, resource, seed, 0, nullptr);
288 D3D12_RESOURCE_BARRIER order{};
289 order.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
290 order.UAV.pResource = resource;
291 list->ResourceBarrier(1, &order);
292 const bool floating = shape.Format == DXGI_FORMAT_R32_FLOAT;
293 if (floating) {
294 const FLOAT float_value[4] = {42.0f, 0, 0, 0};
295 list->ClearUnorderedAccessViewFloat({}, partial, resource, float_value, 0, nullptr);
296 } else {
297 list->ClearUnorderedAccessViewUint({}, partial, resource, clear_value, 0, nullptr);
298 }
299 D3D12_RESOURCE_BARRIER to_src{};
300 to_src.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
301 to_src.Transition = {resource, mip, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE};
302 list->ResourceBarrier(1, &to_src);
303 D3D12_TEXTURE_COPY_LOCATION dst{};
304 dst.pResource = readback.Get();
305 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
306 dst.PlacedFootprint = {0, {shape.Format, w, h, d, pitch}};
307 D3D12_TEXTURE_COPY_LOCATION src{};
308 src.pResource = resource;
309 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
310 src.SubresourceIndex = mip;
311 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
312 D3D12_RESOURCE_BARRIER to_uav = to_src;
313 std::swap(to_uav.Transition.StateBefore, to_uav.Transition.StateAfter);
314 list->ResourceBarrier(1, &to_uav);
315 EXPECT(list->Close() == S_OK);
316 queue->ExecuteCommandLists(1, lists);
317 EXPECT(rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success);
318 EXPECT(SUCCEEDED(queue->Signal(fence.Get(), 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)));
319 void* mapped = nullptr;
320 EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
321 const auto* bytes = static_cast<const std::uint8_t*>(mapped);
322 const UINT cleared = floating ? std::bit_cast<UINT>(42.0f) : clear_value[0];
323 for (UINT z = 0; z < d; ++z) {
324 const UINT want = (z >= first && z < first + writable) ? cleared : sentinel;
325 for (UINT y = 0; y < h; ++y) {
326 const auto* row = reinterpret_cast<const UINT*>(bytes + (UINT64(z) * h + y) * pitch);
327 for (UINT x = 0; x < w; ++x)
328 EXPECT(row[x] == want);
329 }
330 }
331 readback->Unmap(0, nullptr);
332 return true;
255} 333}
256 334
257bool check_case(ID3D12Device* device, Compute* compute, Kind kind, const D3D12_RESOURCE_DESC& shape, 335bool check_case(ID3D12Device* device, Compute* compute, Kind kind, const D3D12_RESOURCE_DESC& shape,
@@ -282,7 +360,14 @@ bool check_case(ID3D12Device* device, Compute* compute, Kind kind, const D3D12_R
282 (decoded.first_layer == first && decoded.layer_count == writable)); 360 (decoded.first_layer == first && decoded.layer_count == writable));
283 device->CopyDescriptorsSimple(1, copy, source, uav_heap); 361 device->CopyDescriptorsSimple(1, copy, source, uav_heap);
284 EXPECT(read_slot(copy) == key); 362 EXPECT(read_slot(copy) == key);
285 if (partial) EXPECT(rejects_partial_clear(device, resource.Get(), copy)); 363 if (partial) {
364 // Reuse the original slot for the whole-mip seed; the copied descriptor must still select its W range.
365 auto whole = desc;
366 whole.Texture3D.FirstWSlice = 0;
367 whole.Texture3D.WSize = ~0u;
368 device->CreateUnorderedAccessView(resource.Get(), nullptr, &whole, source);
369 EXPECT(check_partial_clear(device, resource.Get(), source, copy, shape, mip, first, writable));
370 }
286 if (partial && first > 0) { 371 if (partial && first > 0) {
287 // A second view of the same volume and mip must not collide with the copied T#. 372 // A second view of the same volume and mip must not collide with the copied T#.
288 auto other = desc; 373 auto other = desc;
diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp
index 81a3b2fe5..e5ef14304 100644
--- a/runtime/test/d3d12_title_va_test.cpp
+++ b/runtime/test/d3d12_title_va_test.cpp
@@ -13,10 +13,11 @@
13// into a bound table itself, a created CBV and a root view. 13// into a bound table itself, a created CBV and a root view.
14// Negative controls: a second title buffer with other data must not be what the first one's V# reads; an arena 14// Negative controls: a second title buffer with other data must not be what the first one's V# reads; an arena
15// buffer's V# keeps its VA; the title's range is forgotten when the buffer is released; a raw arena V# and a 15// buffer's V# keeps its VA; the title's range is forgotten when the buffer is released; a raw arena V# and a
16// 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 16// 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
17// Khronos validation layer. 17// Khronos validation layer.
18#include "shader_fixture_path.h" 18#include "shader_fixture_path.h"
19#include "test_temp_dir.h" 19#include "test_temp_dir.h"
20#include "d3d12_test_shaders.h"
20#include "vk_test_device.h" 21#include "vk_test_device.h"
21#include "../shims/d3d12_com.h" 22#include "../shims/d3d12_com.h"
22#include "../shims/d3d12_xs_device.h" 23#include "../shims/d3d12_xs_device.h"
@@ -46,7 +47,6 @@ namespace {
46using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX 47using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX
47using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, 48using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t,
48 std::uint64_t, const IID*, void**); 49 std::uint64_t, const IID*, void**);
49using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
50 50
51template<class T> 51template<class T>
52struct Ref { 52struct Ref {
@@ -106,19 +106,9 @@ std::vector<std::uint8_t> shader_container(const std::vector<std::uint8_t>& fssm
106 return out; 106 return out;
107} 107}
108 108
109// The shared helper: Windows 10's in-box d3d12.dll refuses the heap-directly-indexed flags at every version.
109std::vector<std::uint8_t> serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { 110std::vector<std::uint8_t> serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) {
110 const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); 111 return d3d12test::serialize_root_signature(desc);
111 const auto fn = d3d12 ? reinterpret_cast<SerializeFn>(
112 reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
113 : nullptr;
114 std::vector<std::uint8_t> out;
115 ID3DBlob* blob = nullptr;
116 if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) {
117 const auto* p = static_cast<const std::uint8_t*>(blob->GetBufferPointer());
118 out.assign(p, p + blob->GetBufferSize());
119 blob->Release();
120 }
121 return out;
122} 112}
123 113
124D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { 114D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) {
@@ -731,7 +721,9 @@ int check_title_memory(Context& c, int& checks, bool geometry) {
731 static_cast<unsigned long long>(aliases.translated(leonida::TitleVaAliases::root_view) - root_before)); 721 static_cast<unsigned long long>(aliases.translated(leonida::TitleVaAliases::root_view) - root_before));
732 EXPECT(raw_ok == kElements && cbv_ok == kElements && root_ok == kElements); 722 EXPECT(raw_ok == kElements && cbv_ok == kElements && root_ok == kElements);
733 EXPECT(rewritten && arena_kept && image_kept); 723 EXPECT(rewritten && arena_kept && image_kept);
734 // Neither unrelated host memory nor a reserved-only title page has a GPU copy. 724 // Committed memory that is not the title's (the runtime's own, say) and that no allocation of the device's holds:
725 // heap_base + its address is no allocation either, so its view gets no base and no records, as a title range
726 // with no committed page does (it gets no copy). Neither is counted as left untranslated, and neither has a copy.
735 const std::uint64_t untranslated_before = aliases.untranslated(leonida::TitleVaAliases::created_view); 727 const std::uint64_t untranslated_before = aliases.untranslated(leonida::TitleVaAliases::created_view);
736 void* host = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); 728 void* host = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
737 void* gone = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE, PAGE_READWRITE); 729 void* gone = VirtualAlloc(nullptr, 65536, MEM_TOP_DOWN | MEM_RESERVE, PAGE_READWRITE);
diff --git a/runtime/test/d3d12_uav_clear_test.cpp b/runtime/test/d3d12_uav_clear_test.cpp
index 2d13ba59b..567010ecd 100644
--- a/runtime/test/d3d12_uav_clear_test.cpp
+++ b/runtime/test/d3d12_uav_clear_test.cpp
@@ -9,6 +9,8 @@
9// No shaders or game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation 9// No shaders or game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation
10// error fails the test. 10// error fails the test.
11#include "vk_test_device.h" 11#include "vk_test_device.h"
12#include "d3d12_texture_uav_oracle.h"
13#include "host_wine.h"
12#include "../shims/d3d12_com.h" 14#include "../shims/d3d12_com.h"
13#include "../src/gfx10_descriptors.h" 15#include "../src/gfx10_descriptors.h"
14#include "../src/uav_clear.h" 16#include "../src/uav_clear.h"
@@ -159,6 +161,9 @@ struct Clear {
159 std::uint32_t mip = 0; // texture 161 std::uint32_t mip = 0; // texture
160 std::uint32_t first_layer = 0; 162 std::uint32_t first_layer = 0;
161 std::uint32_t layer_count = 1; 163 std::uint32_t layer_count = 1;
164 bool tagged_volume = false; // encode volume_uav_flag + volume_uav_word(first_layer, layer_count)
165 bool packed_uav = false; // also set packed_uav_flag (emulated RGB9E5)
166 std::uint32_t descriptor_depth = 0; // override the raw 3D T# depth independently of the resource
162}; 167};
163 168
164struct BufferCase { 169struct BufferCase {
@@ -182,16 +187,18 @@ struct Harness {
182 ID3D12CommandQueue* queue = nullptr; 187 ID3D12CommandQueue* queue = nullptr;
183 ID3D12Fence* fence = nullptr; 188 ID3D12Fence* fence = nullptr;
184 UINT64 fence_value = 0; 189 UINT64 fence_value = 0;
185 std::byte* slots = nullptr; // CPU descriptor heap 190 D3D12_CPU_DESCRIPTOR_HANDLE cpu_start{};
191 ID3D12DescriptorHeap* native_visible = nullptr; // WARP needs matching CPU and GPU descriptors
186 UINT step = 0; 192 UINT step = 0;
187 193
188 D3D12_CPU_DESCRIPTOR_HANDLE slot(UINT i) const { return {reinterpret_cast<SIZE_T>(slots + std::size_t(i) * step)}; } 194 D3D12_CPU_DESCRIPTOR_HANDLE slot(UINT i) const { return {cpu_start.ptr + SIZE_T(i) * step}; }
189 195
190 template<class Words> 196 template<class Words>
191 D3D12_CPU_DESCRIPTOR_HANDLE write(UINT i, const Words& words) const { 197 D3D12_CPU_DESCRIPTOR_HANDLE write(UINT i, const Words& words) const {
192 std::memset(slots + std::size_t(i) * step, 0, step); 198 const auto cpu = slot(i);
193 std::memcpy(slots + std::size_t(i) * step, words.data(), sizeof(words)); 199 std::memset(reinterpret_cast<void*>(cpu.ptr), 0, step);
194 return slot(i); 200 std::memcpy(reinterpret_cast<void*>(cpu.ptr), words.data(), sizeof(words));
201 return cpu;
195 } 202 }
196 203
197 // Records with `body`, executes, waits. The result of the replay. 204 // Records with `body`, executes, waits. The result of the replay.
@@ -199,24 +206,26 @@ struct Harness {
199 leonida::ReplayResult run(HRESULT& close, Body&& body) { 206 leonida::ReplayResult run(HRESULT& close, Body&& body) {
200 Ref<ID3D12CommandAllocator> allocator; 207 Ref<ID3D12CommandAllocator> allocator;
201 Ref<ID3D12GraphicsCommandList> list; 208 Ref<ID3D12GraphicsCommandList> list;
202 if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) || 209 const auto type = queue->GetDesc().Type;
203 FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, 210 if (FAILED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p))) ||
204 IID_PPV_ARGS(&list.p)))) 211 FAILED(device->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p))))
205 return leonida::ReplayResult::unsupported; 212 return leonida::ReplayResult::unsupported;
213 if (native_visible) list->SetDescriptorHeaps(1, &native_visible);
206 body(list.p); 214 body(list.p);
207 close = list->Close(); 215 close = list->Close();
208 if (FAILED(close)) return leonida::ReplayResult::success; 216 if (FAILED(close)) return leonida::ReplayResult::success;
209 ID3D12CommandList* lists[] = {list.p}; 217 ID3D12CommandList* lists[] = {list.p};
210 queue->ExecuteCommandLists(1, lists); 218 queue->ExecuteCommandLists(1, lists);
211 const auto result = rt::d3d12::last_execute_result(queue); 219 const auto result = native_visible ? leonida::ReplayResult::success : rt::d3d12::last_execute_result(queue);
212 queue->Signal(fence, ++fence_value); 220 if (FAILED(queue->Signal(fence, ++fence_value)) || FAILED(fence->SetEventOnCompletion(fence_value, nullptr)))
213 fence->SetEventOnCompletion(fence_value, nullptr); 221 return leonida::ReplayResult::unsupported;
214 return result; 222 return result;
215 } 223 }
216 224
217 Ref<ID3D12Resource> committed(const D3D12_RESOURCE_DESC& desc, D3D12_HEAP_TYPE type) const { 225 Ref<ID3D12Resource> committed(const D3D12_RESOURCE_DESC& desc, D3D12_HEAP_TYPE type) const {
218 Ref<ID3D12Resource> out; 226 Ref<ID3D12Resource> out;
219 D3D12_HEAP_PROPERTIES heap{type}; 227 D3D12_HEAP_PROPERTIES heap{type};
228 heap.CreationNodeMask = heap.VisibleNodeMask = 1;
220 device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, 229 device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc,
221 type == D3D12_HEAP_TYPE_READBACK ? D3D12_RESOURCE_STATE_COPY_DEST 230 type == D3D12_HEAP_TYPE_READBACK ? D3D12_RESOURCE_STATE_COPY_DEST
222 : D3D12_RESOURCE_STATE_UNORDERED_ACCESS, 231 : D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
@@ -371,19 +380,42 @@ int run_texture(Harness& h, const TextureCase& test) {
371 image.width = test.width; 380 image.width = test.width;
372 image.height = test.height; 381 image.height = test.height;
373 image.depth = test.volume ? test.layers : 1; 382 image.depth = test.volume ? test.layers : 1;
374 image.first_layer = c.first_layer; 383 if (c.descriptor_depth) image.depth = c.descriptor_depth;
375 image.layer_count = c.layer_count; 384 image.first_layer = test.volume ? 0 : c.first_layer;
385 image.layer_count = test.volume ? 1 : c.layer_count;
376 image.first_mip = c.mip; 386 image.first_mip = c.mip;
377 image.mip_count = 1; 387 image.mip_count = 1;
378 image.resource_mips = test.mips; 388 image.resource_mips = test.mips;
379 const auto view = h.write(i, g::encode(image)); 389 auto encoded = g::encode(image);
390 if (test.volume && c.tagged_volume) {
391 encoded[4] |= g::volume_uav_flag;
392 encoded[7] = g::volume_uav_word(c.first_layer, c.layer_count) |
393 (c.packed_uav ? g::packed_uav_flag : 0u);
394 }
395 const auto view = h.slot(i);
396 D3D12_GPU_DESCRIPTOR_HANDLE gpu_view{};
397 if (h.native_visible) {
398 const UINT depth = std::max(1u, UINT(test.layers) >> c.mip);
399 D3D12_UNORDERED_ACCESS_VIEW_DESC d{};
400 d.Format = test.format;
401 d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
402 d.Texture3D = {c.mip, c.tagged_volume ? c.first_layer : 0u, c.tagged_volume ? c.layer_count : depth};
403 h.device->CreateUnorderedAccessView(texture.p, nullptr, &d, view);
404 const auto dest = h.native_visible->GetCPUDescriptorHandleForHeapStart();
405 h.device->CopyDescriptorsSimple(1, {dest.ptr + SIZE_T(i) * h.step}, view,
406 D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
407 gpu_view = h.native_visible->GetGPUDescriptorHandleForHeapStart();
408 gpu_view.ptr += UINT64(i) * h.step;
409 } else {
410 h.write(i, encoded);
411 }
380 const auto* rects = c.rects.empty() ? nullptr : c.rects.data(); 412 const auto* rects = c.rects.empty() ? nullptr : c.rects.data();
381 if (c.is_float) { 413 if (c.is_float) {
382 const float v[4] = {std::bit_cast<float>(c.values[0]), std::bit_cast<float>(c.values[1]), 414 const float v[4] = {std::bit_cast<float>(c.values[0]), std::bit_cast<float>(c.values[1]),
383 std::bit_cast<float>(c.values[2]), std::bit_cast<float>(c.values[3])}; 415 std::bit_cast<float>(c.values[2]), std::bit_cast<float>(c.values[3])};
384 list->ClearUnorderedAccessViewFloat({0}, view, texture.p, v, UINT(c.rects.size()), rects); 416 list->ClearUnorderedAccessViewFloat(gpu_view, view, texture.p, v, UINT(c.rects.size()), rects);
385 } else { 417 } else {
386 list->ClearUnorderedAccessViewUint({0}, view, texture.p, c.values.data(), UINT(c.rects.size()), rects); 418 list->ClearUnorderedAccessViewUint(gpu_view, view, texture.p, c.values.data(), UINT(c.rects.size()), rects);
387 } 419 }
388 D3D12_RESOURCE_BARRIER uav{}; 420 D3D12_RESOURCE_BARRIER uav{};
389 uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; 421 uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
@@ -395,10 +427,12 @@ int run_texture(Harness& h, const TextureCase& test) {
395 const Sub& sub = subs[s]; 427 const Sub& sub = subs[s];
396 if (sub.mip != c.mip) continue; 428 if (sub.mip != c.mip) continue;
397 if (!test.volume && (sub.layer < c.first_layer || sub.layer >= c.first_layer + c.layer_count)) continue; 429 if (!test.volume && (sub.layer < c.first_layer || sub.layer >= c.first_layer + c.layer_count)) continue;
430 const UINT z_begin = (test.volume && c.tagged_volume) ? c.first_layer : 0u;
431 const UINT z_end = (test.volume && c.tagged_volume) ? (c.first_layer + c.layer_count) : sub.depth;
398 std::vector<D3D12_RECT> rects_or_all = c.rects; 432 std::vector<D3D12_RECT> rects_or_all = c.rects;
399 if (rects_or_all.empty()) rects_or_all.push_back({0, 0, LONG(sub.width), LONG(sub.height)}); 433 if (rects_or_all.empty()) rects_or_all.push_back({0, 0, LONG(sub.width), LONG(sub.height)});
400 for (const auto& r : rects_or_all) 434 for (const auto& r : rects_or_all)
401 for (UINT z = 0; z < sub.depth; ++z) 435 for (UINT z = z_begin; z < z_end; ++z)
402 for (LONG y = std::max<LONG>(r.top, 0); y < std::min<LONG>(r.bottom, sub.height); ++y) 436 for (LONG y = std::max<LONG>(r.top, 0); y < std::min<LONG>(r.bottom, sub.height); ++y)
403 for (LONG x = std::max<LONG>(r.left, 0); x < std::min<LONG>(r.right, sub.width); ++x) 437 for (LONG x = std::max<LONG>(r.left, 0); x < std::min<LONG>(r.right, sub.width); ++x)
404 std::memcpy(&model[s][((std::size_t(z) * sub.height + y) * sub.width + x) * texel], 438 std::memcpy(&model[s][((std::size_t(z) * sub.height + y) * sub.width + x) * texel],
@@ -430,11 +464,89 @@ int run_texture(Harness& h, const TextureCase& test) {
430 for (UINT z = 0; z < s.depth; ++z) 464 for (UINT z = 0; z < s.depth; ++z)
431 for (UINT y = 0; y < s.height; ++y) { 465 for (UINT y = 0; y < s.height; ++y) {
432 char what[96]; 466 char what[96];
433 std::snprintf(what, sizeof(what), "%s mip %u layer %u z %u row %u", test.name, s.mip, s.layer, z, y); 467 std::snprintf(what, sizeof(what), "%s %s mip %u layer %u z %u row %u",
468 h.native_visible ? "WARP" : "Vulkan", test.name, s.mip, s.layer, z, y);
434 compare(what, static_cast<const std::uint8_t*>(data) + s.offset + (UINT64(z) * s.height + y) * s.pitch, 469 compare(what, static_cast<const std::uint8_t*>(data) + s.offset + (UINT64(z) * s.height + y) * s.pitch,
435 &model[i][(std::size_t(z) * s.height + y) * s.width * texel], std::size_t(s.width) * texel); 470 &model[i][(std::size_t(z) * s.height + y) * s.width * texel], std::size_t(s.width) * texel);
436 } 471 }
437 } 472 }
473 readback->Unmap(0, nullptr);
474 return 0;
475}
476
477int check_predicated_volume(ID3D12Device* device, D3D12_COMMAND_LIST_TYPE type, UINT family, bool predicate_family) {
478 Ref<ID3D12CommandQueue> queue;
479 Ref<ID3D12Fence> fence;
480 Ref<ID3D12DescriptorHeap> heap;
481 const D3D12_COMMAND_QUEUE_DESC queue_desc{type};
482 const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2};
483 EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))));
484 EXPECT(queue->GetDesc().Type == type);
485 EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
486 EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p))));
487 Harness h;
488 h.device = device;
489 h.queue = queue.p;
490 h.fence = fence.p;
491 h.cpu_start = heap->GetCPUDescriptorHandleForHeapStart();
492 h.step = device->GetDescriptorHandleIncrementSize(heap_desc.Type);
493
494 D3D12_HEAP_PROPERTIES properties{D3D12_HEAP_TYPE_DEFAULT};
495 properties.CreationNodeMask = properties.VisibleNodeMask = 1;
496 const auto buffer = buffer_desc(8);
497 Ref<ID3D12Resource> predicate;
498 EXPECT(SUCCEEDED(device->CreateCommittedResource(&properties, D3D12_HEAP_FLAG_NONE, &buffer,
499 D3D12_RESOURCE_STATE_PREDICATION, nullptr, IID_PPV_ARGS(&predicate.p))));
500 D3D12_RESOURCE_DESC desc{};
501 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
502 desc.Width = desc.Height = desc.DepthOrArraySize = 4;
503 desc.MipLevels = 1;
504 desc.SampleDesc.Count = 1;
505 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
506 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
507 auto volume = h.committed(desc, D3D12_HEAP_TYPE_DEFAULT);
508 EXPECT(volume.p);
509 g::Image image{};
510 image.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
511 image.type = g::ImageType::image_3d;
512 image.width = image.height = image.depth = 4;
513 auto words = g::encode(image);
514 const auto whole = h.write(0, words);
515 words[4] |= g::volume_uav_flag;
516 words[7] = g::volume_uav_word(1, 2);
517 const auto partial = h.write(1, words);
518 const UINT values[4] = {1, 2, 3, 4};
519 const D3D12_RECT rect{0, 0, 2, 2};
520
521 HRESULT close = E_FAIL;
522 const auto run = [&](auto&& body) {
523 close = E_FAIL;
524 return h.run(close, [&](ID3D12GraphicsCommandList* list) {
525 list->SetPredication(predicate.p, 0, D3D12_PREDICATION_OP_EQUAL_ZERO);
526 body(list);
527 });
528 };
529 const auto control = run([](ID3D12GraphicsCommandList* list) {
530 list->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO);
531 });
532 EXPECT(close == S_OK && fence->GetCompletedValue() == h.fence_value);
533 // The predicate reducer currently belongs to the direct family. A dedicated compute queue may
534 // refuse the entire batch before replay. The shared-family compute control must reach the clear.
535 EXPECT(control == leonida::ReplayResult::success ||
536 (!predicate_family && control == leonida::ReplayResult::unsupported));
537 EXPECT(run([&](ID3D12GraphicsCommandList* list) {
538 list->ClearUnorderedAccessViewUint({0}, partial, volume.p, values, 0, nullptr);
539 }) == leonida::ReplayResult::unsupported);
540 EXPECT(close == S_OK && fence->GetCompletedValue() == h.fence_value);
541 if (type == D3D12_COMMAND_LIST_TYPE_DIRECT) {
542 EXPECT(run([&](ID3D12GraphicsCommandList* list) {
543 list->ClearUnorderedAccessViewUint({0}, whole, volume.p, values, 1, &rect);
544 }) == leonida::ReplayResult::unsupported);
545 EXPECT(close == S_OK && fence->GetCompletedValue() == h.fence_value);
546 }
547 std::printf("3D UAV predication: %s family %u, predicate control %s, staged clear refused\n",
548 type == D3D12_COMMAND_LIST_TYPE_DIRECT ? "direct" : "compute", family,
549 control == leonida::ReplayResult::success ? "passed" : "refused before replay");
438 return 0; 550 return 0;
439} 551}
440 552
@@ -444,6 +556,7 @@ int main() {
444 if (conversion_checks()) return 1; 556 if (conversion_checks()) return 1;
445 557
446 vktest::Device d; 558 vktest::Device d;
559 d.all_queue_types = true;
447 const auto device_status = d.initialize(); 560 const auto device_status = d.initialize();
448 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips 561 if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips
449 if (device_status != vktest::DeviceStatus::ready) return 1; 562 if (device_status != vktest::DeviceStatus::ready) return 1;
@@ -455,6 +568,10 @@ int main() {
455 info.device = d.device; 568 info.device = d.device;
456 info.queue = d.queue; 569 info.queue = d.queue;
457 info.queue_family = d.family; 570 info.queue_family = d.family;
571 info.command_queues = d.queues;
572 info.compute_queues = {d.compute_queue};
573 info.compute_family = d.compute_family;
574 info.conditional_rendering = d.conditional_rendering;
458 Ref<ID3D12Device> device; 575 Ref<ID3D12Device> device;
459 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); 576 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p))));
460 Ref<ID3D12CommandQueue> queue; 577 Ref<ID3D12CommandQueue> queue;
@@ -470,7 +587,7 @@ int main() {
470 h.device = device.p; 587 h.device = device.p;
471 h.queue = queue.p; 588 h.queue = queue.p;
472 h.fence = fence.p; 589 h.fence = fence.p;
473 h.slots = reinterpret_cast<std::byte*>(heap->GetCPUDescriptorHandleForHeapStart().ptr); 590 h.cpu_start = heap->GetCPUDescriptorHandleForHeapStart();
474 h.step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); 591 h.step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
475 EXPECT(h.step >= sizeof(g::ImageWords)); 592 EXPECT(h.step >= sizeof(g::ImageWords));
476 593
@@ -573,7 +690,8 @@ int main() {
573 690
574 const auto texture_clear = [](VkFormat format, bool is_float, std::array<std::uint32_t, 4> values, 691 const auto texture_clear = [](VkFormat format, bool is_float, std::array<std::uint32_t, 4> values,
575 std::uint32_t mip, std::uint32_t first_layer, std::uint32_t layer_count, 692 std::uint32_t mip, std::uint32_t first_layer, std::uint32_t layer_count,
576 std::vector<D3D12_RECT> rects = {}) { 693 std::vector<D3D12_RECT> rects = {}, bool tagged_volume = false,
694 bool packed_uav = false) {
577 Clear c; 695 Clear c;
578 c.format = format; 696 c.format = format;
579 c.is_float = is_float; 697 c.is_float = is_float;
@@ -582,6 +700,8 @@ int main() {
582 c.first_layer = first_layer; 700 c.first_layer = first_layer;
583 c.layer_count = layer_count; 701 c.layer_count = layer_count;
584 c.rects = std::move(rects); 702 c.rects = std::move(rects);
703 c.tagged_volume = tagged_volume;
704 c.packed_uav = packed_uav;
585 return c; 705 return c;
586 }; 706 };
587 const std::vector<TextureCase> textures = { 707 const std::vector<TextureCase> textures = {
@@ -649,8 +769,50 @@ int main() {
649 {texture_clear(VK_FORMAT_B8G8R8A8_UNORM, true, floats(1.0f, 0.5f, 0.0f, 1.0f), 0, 0, 1)}}, 769 {texture_clear(VK_FORMAT_B8G8R8A8_UNORM, true, floats(1.0f, 0.5f, 0.0f, 1.0f), 0, 0, 1)}},
650 {"RGBA8_UNORM volume, one mip", DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, 4, 4, 2, 4, true, 770 {"RGBA8_UNORM volume, one mip", DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, 4, 4, 2, 4, true,
651 {texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {1, 2, 3, 4}, 1, 0, 1)}}, 771 {texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {1, 2, 3, 4}, 1, 0, 1)}},
772 {"RGBA8_UNORM volume, partial W slices, non-zero mips and rectangles", DXGI_FORMAT_R8G8B8A8_UNORM,
773 VK_FORMAT_R8G8B8A8_UNORM, 8, 8, 3, 8, true,
774 {texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {0x11, 0x22, 0x33, 0x44}, 0, 0, 8, {}, true),
775 texture_clear(VK_FORMAT_R8G8B8A8_UNORM, true, floats(1.0f, 0.25f, 0.0f, 1.0f), 0, 2, 3, {}, true),
776 texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {0xaa, 0xbb, 0xcc, 0xdd}, 0, 5, 3,
777 {{-1, 1, 4, 5}, {2, 3, 12, 7}}, true),
778 texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {0x55, 0x66, 0x77, 0x88}, 1, 1, 2, {}, true),
779 texture_clear(VK_FORMAT_R8G8B8A8_UNORM, true, floats(0.0f, 1.0f, 0.25f, 1.0f), 1, 0, 4,
780 {{1, 1, 3, 3}}, false),
781 texture_clear(VK_FORMAT_R8G8B8A8_UNORM, false, {0xfe, 0xed, 0xfa, 0xce}, 2, 1, 1, {}, true)}},
782 {"R8_UNORM volume, tiny 1..3-byte rect payloads and partial W", DXGI_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM,
783 6, 6, 1, 4, true,
784 {texture_clear(VK_FORMAT_R8_UNORM, false, {0x22, 0, 0, 0}, 0, 0, 4, {}, true),
785 texture_clear(VK_FORMAT_R8_UNORM, false, {0x7b, 0, 0, 0}, 0, 1, 1, {{2, 2, 3, 3}}, true),
786 texture_clear(VK_FORMAT_R8_UNORM, true, floats(0.25f, 0, 0, 0), 0, 2, 2, {{1, 4, 4, 5}}, true)}},
787 {"R16_UINT volume, tiny 2-byte rect payload and partial W", DXGI_FORMAT_R16_UINT, VK_FORMAT_R16_UINT,
788 4, 4, 1, 4, true,
789 {texture_clear(VK_FORMAT_R16_UINT, false, {0x1234, 0, 0, 0}, 0, 0, 4, {}, true),
790 texture_clear(VK_FORMAT_R16_UINT, false, {0xbeef, 0, 0, 0}, 0, 2, 1, {{1, 1, 2, 2}}, true)}},
791 {"R32G32_SINT volume, 8-byte partial W and rectangles", DXGI_FORMAT_R32G32_SINT, VK_FORMAT_R32G32_SINT,
792 8, 4, 1, 4, true,
793 {texture_clear(VK_FORMAT_R32G32_SINT, false, {0x11111111u, 0x22222222u, 0, 0}, 0, 0, 4, {}, true),
794 texture_clear(VK_FORMAT_R32G32_SINT, true, floats(-7.9f, 7.9f, 0, 0), 0, 1, 2, {{1, 1, 6, 3}}, true)}},
795 {"RGBA32_UINT volume, 16-byte partial W and rectangles", DXGI_FORMAT_R32G32B32A32_UINT,
796 VK_FORMAT_R32G32B32A32_UINT, 8, 6, 2, 4, true,
797 {texture_clear(VK_FORMAT_R32G32B32A32_UINT, false, {1, 2, 3, 4}, 0, 0, 4, {}, true),
798 texture_clear(VK_FORMAT_R32G32B32A32_UINT, false, {9, 8, 7, 6}, 0, 1, 2, {{1, 1, 5, 4}}, true),
799 texture_clear(VK_FORMAT_R32G32B32A32_UINT, true, floats(2.9f, -1.0f, 1e10f, NAN), 1, 1, 1, {}, true)}},
800 {"RGBA16_SFLOAT volume, large tiled slice (> 64 KiB)", DXGI_FORMAT_R16G16B16A16_FLOAT,
801 VK_FORMAT_R16G16B16A16_SFLOAT, 128, 96, 1, 3, true,
802 {texture_clear(VK_FORMAT_R16G16B16A16_SFLOAT, false, {0x3c00, 0x4000, 0xc000, 0x3800}, 0, 0, 3, {}, true),
803 texture_clear(VK_FORMAT_R16G16B16A16_SFLOAT, true, floats(0.25f, -8.0f, 1.0f, 0.0f), 0, 1, 1, {}, true)}},
652 }; 804 };
653 std::vector<TextureCase> all_textures = textures; 805 std::vector<TextureCase> all_textures = textures;
806 for (const auto depth : {2u, 8u}) {
807 // An untagged T# covers both W slices of mip 1 of a four-deep resource, regardless of its DEPTH.
808 auto clear = texture_clear(VK_FORMAT_R32_UINT, false, {97, 0, 0, 0}, 1, 0, 2);
809 clear.descriptor_depth = depth;
810 all_textures.push_back({
811 depth == 2 ? "untagged 3D T# depth 2" : "untagged 3D T# depth 8",
812 DXGI_FORMAT_R32_UINT, VK_FORMAT_R32_UINT, 4, 4, 2, 4, true,
813 {texture_clear(VK_FORMAT_R32_UINT, false, {13, 0, 0, 0}, 0, 0, 4),
814 texture_clear(VK_FORMAT_R32_UINT, false, {31, 0, 0, 0}, 1, 0, 2), clear}});
815 }
654 { 816 {
655 D3D12_FEATURE_DATA_FORMAT_SUPPORT e5_support{DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; 817 D3D12_FEATURE_DATA_FORMAT_SUPPORT e5_support{DXGI_FORMAT_R9G9B9E5_SHAREDEXP};
656 if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &e5_support, sizeof(e5_support))) && 818 if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &e5_support, sizeof(e5_support))) &&
@@ -677,6 +839,24 @@ int main() {
677 {0x12345678u, 0x9abcdef0u, 0u, 0u}, 0, 0, 1, {{2, 3, 4, 5}})); 839 {0x12345678u, 0x9abcdef0u, 0u, 0u}, 0, 0, 1, {{2, 3, 4, 5}}));
678 } 840 }
679 all_textures.push_back(std::move(e5)); 841 all_textures.push_back(std::move(e5));
842
843 TextureCase e5_vol{"R9G9B9E5_SHAREDEXP volume, partial W slices and rectangles",
844 DXGI_FORMAT_R9G9B9E5_SHAREDEXP, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, 8, 8, 2, 4, true,
845 {texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true,
846 floats(0.5f, 0.25f, 0.125f, 0.0f), 0, 0, 4, {}, true, !native_storage),
847 texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true,
848 floats(1.0f, 2.0f, 4.0f, 0.0f), 0, 1, 2, {{1, 2, 6, 5}}, true,
849 !native_storage),
850 // Seed both mip-1 slices so skipping or widening the zero-valued Uint clear is visible.
851 texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true,
852 floats(1.0f, 2.0f, 4.0f, 0.0f), 1, 0, 2, {}, true, !native_storage),
853 texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, false,
854 {0x3f800000u, 0xffffffffu, 1u, 2u}, 1, 1, 1, {}, true,
855 !native_storage),
856 texture_clear(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, true,
857 floats(4.0f, 2.0f, 1.0f, 0.0f), 1, 0, 1, {{1, 1, 3, 3}}, true,
858 !native_storage)}};
859 all_textures.push_back(std::move(e5_vol));
680 } 860 }
681 } 861 }
682 { 862 {
@@ -697,6 +877,63 @@ int main() {
697 for (const auto& test : all_textures) 877 for (const auto& test : all_textures)
698 if (run_texture(h, test)) return 1; 878 if (run_texture(h, test)) return 1;
699 879
880 // The same bounded W view (including its first and last untouched neighbors) and nonzero mip on
881 // both APIs. Submit the clear and copy on the same command-list type and compare every texel.
882 const std::array volume_parity = {
883 TextureCase{"3D Uint clear parity", DXGI_FORMAT_R32_UINT, VK_FORMAT_R32_UINT, 8, 8, 2, 8, true,
884 {texture_clear(VK_FORMAT_R32_UINT, false, {13, 0, 0, 0}, 0, 0, 8),
885 texture_clear(VK_FORMAT_R32_UINT, false, {31, 0, 0, 0}, 1, 0, 4),
886 texture_clear(VK_FORMAT_R32_UINT, false, {57, 0, 0, 0}, 1, 1, 2, {}, true),
887 texture_clear(VK_FORMAT_R32_UINT, false, {99, 0, 0, 0}, 1, 1, 2, {{1, 1, 3, 3}}, true)}},
888 TextureCase{"3D Float clear parity", DXGI_FORMAT_R32_FLOAT, VK_FORMAT_R32_SFLOAT, 8, 8, 2, 8, true,
889 {texture_clear(VK_FORMAT_R32_SFLOAT, true, floats(0.5f, 0, 0, 0), 0, 0, 8),
890 texture_clear(VK_FORMAT_R32_SFLOAT, true, floats(0.25f, 0, 0, 0), 1, 0, 4),
891 texture_clear(VK_FORMAT_R32_SFLOAT, true, floats(-2.0f, 0, 0, 0), 1, 1, 2, {}, true),
892 texture_clear(VK_FORMAT_R32_SFLOAT, true, floats(4.5f, 0, 0, 0), 1, 1, 2, {{1, 1, 3, 3}}, true)}},
893 };
894 const auto run_volume_parity = [&](Harness& target) {
895 for (const auto type : {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_TYPE_COMPUTE}) {
896 Ref<ID3D12CommandQueue> q;
897 const D3D12_COMMAND_QUEUE_DESC desc{type};
898 EXPECT(SUCCEEDED(target.device->CreateCommandQueue(&desc, IID_PPV_ARGS(&q.p))));
899 EXPECT(q->GetDesc().Type == type);
900 Harness pass = target;
901 pass.queue = q.p;
902 for (const auto& test : volume_parity)
903 if (run_texture(pass, test)) return 1;
904 target.fence_value = pass.fence_value;
905 }
906 return 0;
907 };
908 const auto mismatches_before_parity = mismatches;
909 EXPECT(run_volume_parity(h) == 0);
910 if (!hostwine::host_is_wine()) {
911 uav_oracle::detail::Context warp;
912 const auto status = warp.prepare_device();
913 EXPECT(status != uav_oracle::Status::failed);
914 if (status == uav_oracle::Status::ready) {
915 Ref<ID3D12DescriptorHeap> cpu, visible;
916 Ref<ID3D12Fence> host_fence;
917 auto hd = heap_desc;
918 EXPECT(SUCCEEDED(warp.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&cpu.p))));
919 hd.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
920 EXPECT(SUCCEEDED(warp.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&visible.p))));
921 EXPECT(SUCCEEDED(warp.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&host_fence.p))));
922 Harness host;
923 host.device = warp.device.Get();
924 host.fence = host_fence.p;
925 host.cpu_start = cpu->GetCPUDescriptorHandleForHeapStart();
926 host.native_visible = visible.p;
927 host.step = host.device->GetDescriptorHandleIncrementSize(hd.Type);
928 EXPECT(run_volume_parity(host) == 0);
929 EXPECT(mismatches == mismatches_before_parity);
930 std::printf("3D UAV clear parity: Vulkan (direct family %u, compute family %u) and WARP "
931 "direct/compute Uint/Float readbacks matched\n", d.family, d.compute_family);
932 } else {
933 std::puts("3D UAV clear WARP comparison skipped: WARP unavailable");
934 }
935 }
936
700 // Refused while recording (Close says E_INVALIDARG): no values, an empty slot, no resource. 937 // Refused while recording (Close says E_INVALIDARG): no values, an empty slot, no resource.
701 { 938 {
702 Ref<ID3D12Resource> buffer = h.committed(buffer_desc(256), D3D12_HEAP_TYPE_DEFAULT); 939 Ref<ID3D12Resource> buffer = h.committed(buffer_desc(256), D3D12_HEAP_TYPE_DEFAULT);
@@ -707,7 +944,7 @@ int main() {
707 return close; 944 return close;
708 }; 945 };
709 const auto good = h.write(0, buffer_view(buffer->GetGPUVirtualAddress(), whole(64))); 946 const auto good = h.write(0, buffer_view(buffer->GetGPUVirtualAddress(), whole(64)));
710 std::memset(h.slots + h.step, 0, h.step); 947 std::memset(reinterpret_cast<void*>(h.slot(1).ptr), 0, h.step);
711 EXPECT(check([&](ID3D12GraphicsCommandList* l) { 948 EXPECT(check([&](ID3D12GraphicsCommandList* l) {
712 l->ClearUnorderedAccessViewUint({0}, good, buffer.p, nullptr, 0, nullptr); 949 l->ClearUnorderedAccessViewUint({0}, good, buffer.p, nullptr, 0, nullptr);
713 }) == E_INVALIDARG); 950 }) == E_INVALIDARG);
@@ -723,7 +960,7 @@ int main() {
723 }) == E_INVALIDARG); 960 }) == E_INVALIDARG);
724 961
725 // Refused at execution, before anything is submitted: a buffer view of a texture, a texture view of a 962 // Refused at execution, before anything is submitted: a buffer view of a texture, a texture view of a
726 // buffer, a mip the texture does not have, a buffer view past the end, a rectangle clear of a volume. 963 // buffer, a mip the texture does not have, and a buffer view past the end.
727 D3D12_RESOURCE_DESC desc{}; 964 D3D12_RESOURCE_DESC desc{};
728 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; 965 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
729 desc.Width = desc.Height = 4; 966 desc.Width = desc.Height = 4;
@@ -754,7 +991,7 @@ int main() {
754 const auto replay = [&](auto&& body) { 991 const auto replay = [&](auto&& body) {
755 HRESULT close = E_FAIL; 992 HRESULT close = E_FAIL;
756 const auto result = h.run(close, body); 993 const auto result = h.run(close, body);
757 return close == S_OK ? result : leonida::ReplayResult::success; 994 return close == S_OK ? result : leonida::ReplayResult::list_open;
758 }; 995 };
759 EXPECT(replay([&](ID3D12GraphicsCommandList* l) { 996 EXPECT(replay([&](ID3D12GraphicsCommandList* l) {
760 l->ClearUnorderedAccessViewUint({0}, good, texture.p, values, 0, nullptr); 997 l->ClearUnorderedAccessViewUint({0}, good, texture.p, values, 0, nullptr);
@@ -768,9 +1005,47 @@ int main() {
768 EXPECT(replay([&](ID3D12GraphicsCommandList* l) { 1005 EXPECT(replay([&](ID3D12GraphicsCommandList* l) {
769 l->ClearUnorderedAccessViewUint({0}, past_view, buffer.p, values, 0, nullptr); 1006 l->ClearUnorderedAccessViewUint({0}, past_view, buffer.p, values, 0, nullptr);
770 }) == leonida::ReplayResult::invalid_subresource); 1007 }) == leonida::ReplayResult::invalid_subresource);
1008 // Untagged whole-volume rectangle clear now succeeds on Vulkan.
771 EXPECT(replay([&](ID3D12GraphicsCommandList* l) { 1009 EXPECT(replay([&](ID3D12GraphicsCommandList* l) {
772 l->ClearUnorderedAccessViewUint({0}, v_view, volume.p, values, 1, &rect); 1010 l->ClearUnorderedAccessViewUint({0}, v_view, volume.p, values, 1, &rect);
773 }) == leonida::ReplayResult::unsupported); 1011 }) == leonida::ReplayResult::success);
1012 // Out-of-range 3D W slice range is refused at execution as invalid_subresource.
1013 auto bad_w = g::encode(image);
1014 bad_w[4] |= g::volume_uav_flag;
1015 bad_w[7] = g::volume_uav_word(2, 3); // 2 + 3 > 4
1016 const auto bad_w_view = h.write(6, bad_w);
1017 EXPECT(replay([&](ID3D12GraphicsCommandList* l) {
1018 l->ClearUnorderedAccessViewUint({0}, bad_w_view, volume.p, values, 0, nullptr);
1019 }) == leonida::ReplayResult::invalid_subresource);
1020 auto part_w = g::encode(image);
1021 part_w[4] |= g::volume_uav_flag;
1022 part_w[7] = g::volume_uav_word(1, 2);
1023 const auto part_w_view = h.write(7, part_w);
1024 for (auto type : {D3D12_COMMAND_LIST_TYPE_COPY, D3D12_COMMAND_LIST_TYPE_BUNDLE}) {
1025 Ref<ID3D12CommandAllocator> allocator;
1026 Ref<ID3D12GraphicsCommandList> list;
1027 EXPECT(SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p))));
1028 EXPECT(SUCCEEDED(device->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p))));
1029 list->ClearUnorderedAccessViewUint({0}, part_w_view, volume.p, values, 1, &rect);
1030 EXPECT(list->Close() == E_INVALIDARG);
1031 }
1032 }
1033 if (d.conditional_rendering) {
1034 EXPECT(check_predicated_volume(device.p, D3D12_COMMAND_LIST_TYPE_DIRECT, d.family, true) == 0);
1035 EXPECT(check_predicated_volume(device.p, D3D12_COMMAND_LIST_TYPE_COMPUTE, d.compute_family,
1036 d.compute_family == d.family) == 0);
1037 if (d.compute_family != d.family) {
1038 // Exercise the COMPUTE-list clear guard after a successful predicate capture, even on
1039 // devices where the regular compute queue cannot use the direct-family predicate reducer.
1040 auto shared = info;
1041 shared.compute_family = d.family;
1042 shared.compute_queues = {d.queue};
1043 Ref<ID3D12Device> shared_device;
1044 EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(shared, IID_PPV_ARGS(&shared_device.p))));
1045 EXPECT(check_predicated_volume(shared_device.p, D3D12_COMMAND_LIST_TYPE_COMPUTE, d.family, true) == 0);
1046 }
1047 } else {
1048 std::puts("3D UAV GPU predication checks skipped: VK_EXT_conditional_rendering unavailable");
774 } 1049 }
775 } 1050 }
776 1051
diff --git a/runtime/test/d3d12_unbound_tsharp_rules_test.cpp b/runtime/test/d3d12_unbound_tsharp_rules_test.cpp
new file mode 100644
index 000000000..bc9aa1ca9
--- /dev/null
+++ b/runtime/test/d3d12_unbound_tsharp_rules_test.cpp
@@ -0,0 +1,394 @@
1// Tests for console descriptor heap T# binding rules and per-reason refusal tracking (RT-UNBOUND-TSHARP-REASONS).
2// Verifies:
3// 1. 1D rule: dimension and layer count compatibility ("T# type or samples do not fit the texture").
4// 2. Array rule: layer range bounds ("T# names layers the texture lacks").
5// 3. Cube rule: minimum layer requirement ("cube T# on fewer than six layers").
6// 4. MSAA rule: sample count matching ("T# type or samples do not fit the texture").
7// 5. Unbound T# reason tracking: distinct slots and total refusal counts tracked per reason.
8#include "../shims/d3d12_com.h"
9#include "../shims/d3d12_xs_device.h"
10#include "../src/gfx10_descriptors.h"
11
12#include <cstdio>
13#include <cstdlib>
14#include <cstring>
15#include <string>
16
17namespace {
18
19int g_checks = 0;
20int g_failures = 0;
21
22void check(bool condition, const char* what) {
23 ++g_checks;
24 if (!condition) {
25 ++g_failures;
26 std::fprintf(stderr, "FAIL: %s\n", what);
27 }
28}
29
30template <class T>
31struct Ref {
32 T* p = nullptr;
33 ~Ref() {
34 if (p) p->Release();
35 }
36 T** put() {
37 if (p) {
38 p->Release();
39 p = nullptr;
40 }
41 return &p;
42 }
43 T* operator->() const { return p; }
44};
45
46} // namespace
47
48int main() {
49 namespace g = leonida::gfx10;
50
51 // Test 1: Unbound T# statistics and per-reason tracking
52 {
53 rt::d3d12::reset_unbound_tsharp_stats();
54 std::array<std::uint32_t, 8> dummy_words{};
55
56 const char* reason_type = "T# type or samples do not fit the texture";
57 const char* reason_layers = "T# names layers the texture lacks";
58
59 // Slot 0x00 refused for type
60 rt::d3d12::note_refused_tsharp_for_test(0x10000, 0x00, dummy_words, reason_type);
61 // Slot 0x20 refused for type
62 rt::d3d12::note_refused_tsharp_for_test(0x10000, 0x20, dummy_words, reason_type);
63 // Slot 0x00 refused again for type (repeated scan)
64 rt::d3d12::note_refused_tsharp_for_test(0x10000, 0x00, dummy_words, reason_type);
65 // Slot 0x40 refused for layers
66 rt::d3d12::note_refused_tsharp_for_test(0x10000, 0x40, dummy_words, reason_layers);
67
68 const auto stats = rt::d3d12::unbound_tsharp_stats();
69 check(stats.total_distinct_slots == 3, "total distinct slots is 3");
70 check(stats.total_refusals == 4, "total refusals is 4");
71
72 const auto it_type = stats.by_reason.find(reason_type);
73 check(it_type != stats.by_reason.end(), "reason_type recorded in stats");
74 if (it_type != stats.by_reason.end()) {
75 check(it_type->second.distinct_slots == 2, "type reason distinct slots is 2");
76 check(it_type->second.total_refusals == 3, "type reason total refusals is 3");
77 }
78
79 const auto it_layers = stats.by_reason.find(reason_layers);
80 check(it_layers != stats.by_reason.end(), "reason_layers recorded in stats");
81 if (it_layers != stats.by_reason.end()) {
82 check(it_layers->second.distinct_slots == 1, "layers reason distinct slots is 1");
83 check(it_layers->second.total_refusals == 1, "layers reason total refusals is 1");
84 }
85 }
86
87 // Initialize standalone Vulkan D3D12 device for resource binding rule tests
88 Ref<ID3D12Device> device;
89 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(device.put())))) {
90 std::puts("SKIP: no Vulkan D3D12 device");
91 return 77;
92 }
93
94 const D3D12_HEAP_PROPERTIES heap_props{
95 .Type = D3D12_HEAP_TYPE_DEFAULT,
96 .CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN,
97 .MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN,
98 .CreationNodeMask = 1,
99 .VisibleNodeMask = 1,
100 };
101
102 // Test 2: 1D Texture binding rules
103 {
104 D3D12_RESOURCE_DESC desc{};
105 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D;
106 desc.Width = 64;
107 desc.Height = 1;
108 desc.DepthOrArraySize = 1;
109 desc.MipLevels = 1;
110 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
111 desc.SampleDesc.Count = 1;
112 desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
113
114 Ref<ID3D12Resource> res_1d;
115 check(SUCCEEDED(device->CreateCommittedResource(&heap_props, D3D12_HEAP_FLAG_NONE, &desc,
116 D3D12_RESOURCE_STATE_COMMON, nullptr,
117 IID_PPV_ARGS(res_1d.put()))),
118 "created 1D texture");
119
120 const std::uint64_t addr = rt::d3d12::resource_image_address(res_1d.p);
121 check(addr != 0, "1D texture has registered image address");
122
123 // Case 2a: T# specifies 2D type for a 1D texture -> refuse type_fits
124 {
125 g::Image img{};
126 img.address = addr;
127 img.type = g::ImageType::image_2d;
128 img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
129 img.width = 64;
130 img.height = 1;
131 img.layer_count = 1;
132 img.mip_count = 1;
133 const auto words = g::encode(img);
134
135 const char* why = nullptr;
136 const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why);
137 check(result == rt::d3d12::TitleImage::refused, "2D T# on 1D texture refused");
138 check(why && std::string(why) == "T# type or samples do not fit the texture",
139 "2D T# on 1D texture explains type mismatch");
140 }
141
142 // Case 2b: T# specifies 1D type but layer_count > 1 -> refuse type_fits
143 {
144 g::Image img{};
145 img.address = addr;
146 img.type = g::ImageType::image_1d;
147 img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
148 img.width = 64;
149 img.height = 1;
150 img.layer_count = 2;
151 img.mip_count = 1;
152 const auto words = g::encode(img);
153
154 const char* why = nullptr;
155 const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why);
156 check(result == rt::d3d12::TitleImage::refused, "1D T# with layer_count > 1 on 1D texture refused");
157 check(why && std::string(why) == "T# type or samples do not fit the texture",
158 "1D T# with layer_count > 1 explains type mismatch");
159 }
160
161 // Case 2c: T# specifies 1D type and layer_count == 1 -> bound
162 {
163 g::Image img{};
164 img.address = addr;
165 img.type = g::ImageType::image_1d;
166 img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
167 img.width = 64;
168 img.height = 1;
169 img.layer_count = 1;
170 img.mip_count = 1;
171 const auto words = g::encode(img);
172
173 const char* why = nullptr;
174 const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why);
175 check(result == rt::d3d12::TitleImage::bound, "matching 1D T# bound successfully");
176 }
177 }
178
179 // Test 3: 2D Array and Cube binding rules
180 {
181 D3D12_RESOURCE_DESC desc{};
182 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
183 desc.Width = 64;
184 desc.Height = 64;
185 desc.DepthOrArraySize = 4; // 4 layers
186 desc.MipLevels = 2;
187 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
188 desc.SampleDesc.Count = 1;
189 desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
190
191 Ref<ID3D12Resource> res_array;
192 check(SUCCEEDED(device->CreateCommittedResource(&heap_props, D3D12_HEAP_FLAG_NONE, &desc,
193 D3D12_RESOURCE_STATE_COMMON, nullptr,
194 IID_PPV_ARGS(res_array.put()))),
195 "created 2D array texture");
196
197 const std::uint64_t addr = rt::d3d12::resource_image_address(res_array.p);
198 check(addr != 0, "2D array texture has registered image address");
199
200 // Case 3a: T# names layers the texture lacks (first_layer + layer_count > 4) -> refuse layers
201 {
202 g::Image img{};
203 img.address = addr;
204 img.type = g::ImageType::image_2d_array;
205 img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
206 img.width = 64;
207 img.height = 64;
208 img.first_layer = 2;
209 img.layer_count = 3; // 2 + 3 = 5 > 4
210 img.mip_count = 1;
211 const auto words = g::encode(img);
212
213 const char* why = nullptr;
214 const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why);
215 check(result == rt::d3d12::TitleImage::refused, "T# with excessive layers refused");
216 check(why && std::string(why) == "T# names layers the texture lacks",
217 "excessive layers explains layers mismatch");
218 }
219
220 // Case 3b: Cube T# on texture with fewer than six layers (desc.DepthOrArraySize = 4 < 6) -> refuse cube
221 {
222 g::Image img{};
223 img.address = addr;
224 img.type = g::ImageType::cube;
225 img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
226 img.width = 64;
227 img.height = 64;
228 img.first_layer = 0;
229 img.layer_count = 6; // cube needs at least 6 faces, but texture only has 4 layers
230 img.mip_count = 1;
231 const auto words = g::encode(img);
232
233 const char* why = nullptr;
234 const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why);
235 check(result == rt::d3d12::TitleImage::refused, "cube T# on 4 layers refused");
236 check(why && std::string(why) == "cube T# on fewer than six layers",
237 "cube T# explains fewer than six layers");
238 }
239
240 // Case 3c: T# names valid sub-array (first_layer = 1, layer_count = 2 <= 4) -> bound
241 {
242 g::Image img{};
243 img.address = addr;
244 img.type = g::ImageType::image_2d_array;
245 img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
246 img.width = 64;
247 img.height = 64;
248 img.first_layer = 1;
249 img.layer_count = 2;
250 img.mip_count = 1;
251 const auto words = g::encode(img);
252
253 const char* why = nullptr;
254 const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why);
255 check(result == rt::d3d12::TitleImage::bound, "valid sub-array T# bound successfully");
256 }
257
258 // Case 3d: T# names mips the texture lacks (first_mip + mip_count > 2) -> refuse mips
259 {
260 g::Image img{};
261 img.address = addr;
262 img.type = g::ImageType::image_2d_array;
263 img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
264 img.width = 64;
265 img.height = 64;
266 img.first_layer = 0;
267 img.layer_count = 1;
268 img.first_mip = 1;
269 img.mip_count = 2; // 1 + 2 = 3 > 2
270 const auto words = g::encode(img);
271
272 const char* why = nullptr;
273 const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why);
274 check(result == rt::d3d12::TitleImage::refused, "T# with excessive mips refused");
275 check(why && std::string(why) == "T# names mips the texture lacks",
276 "excessive mips explains mips mismatch");
277 }
278 }
279
280 // Test 4: MSAA Texture binding rules
281 {
282 D3D12_RESOURCE_DESC desc{};
283 desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
284 desc.Width = 64;
285 desc.Height = 64;
286 desc.DepthOrArraySize = 1;
287 desc.MipLevels = 1;
288 desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
289 desc.SampleDesc.Count = 4; // 4x MSAA
290 desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
291 desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
292
293 Ref<ID3D12Resource> res_msaa;
294 check(SUCCEEDED(device->CreateCommittedResource(&heap_props, D3D12_HEAP_FLAG_NONE, &desc,
295 D3D12_RESOURCE_STATE_COMMON, nullptr,
296 IID_PPV_ARGS(res_msaa.put()))),
297 "created 4x MSAA texture");
298
299 const std::uint64_t addr = rt::d3d12::resource_image_address(res_msaa.p);
300 check(addr != 0, "MSAA texture has registered image address");
301
302 // Case 4a: Non-MSAA T# on MSAA texture -> refuse type_fits
303 {
304 g::Image img{};
305 img.address = addr;
306 img.type = g::ImageType::image_2d;
307 img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
308 img.width = 64;
309 img.height = 64;
310 img.layer_count = 1;
311 img.mip_count = 1;
312 const auto words = g::encode(img);
313
314 const char* why = nullptr;
315 const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why);
316 check(result == rt::d3d12::TitleImage::refused, "non-MSAA T# on MSAA texture refused");
317 check(why && std::string(why) == "T# type or samples do not fit the texture",
318 "non-MSAA T# explains type or samples mismatch");
319 }
320
321 // Case 4b: MSAA T# with mismatched samples (samples = 2 != 4) -> refuse type_fits
322 {
323 g::Image img{};
324 img.address = addr;
325 img.type = g::ImageType::image_2d_msaa;
326 img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
327 img.width = 64;
328 img.height = 64;
329 img.samples = 2;
330 img.layer_count = 1;
331 img.mip_count = 1;
332 const auto words = g::encode(img);
333
334 const char* why = nullptr;
335 const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why);
336 check(result == rt::d3d12::TitleImage::refused, "mismatched samples T# refused");
337 check(why && std::string(why) == "T# type or samples do not fit the texture",
338 "mismatched samples explains type or samples mismatch");
339 }
340
341 // Case 4c: Matching 4x MSAA T# -> bound
342 {
343 g::Image img{};
344 img.address = addr;
345 img.type = g::ImageType::image_2d_msaa;
346 img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
347 img.width = 64;
348 img.height = 64;
349 img.samples = 4;
350 img.layer_count = 1;
351 img.mip_count = 1;
352 const auto words = g::encode(img);
353
354 const char* why = nullptr;
355 const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why);
356 check(result == rt::d3d12::TitleImage::bound, "matching 4x MSAA T# bound successfully");
357 }
358 }
359
360 // Test 5: Unknown texture address and invalid T# words
361 {
362 // Unknown address
363 {
364 g::Image img{};
365 img.address = 0xdeadbeef00ull;
366 img.type = g::ImageType::image_2d;
367 img.format = g::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM);
368 img.width = 64;
369 img.height = 64;
370 img.layer_count = 1;
371 img.mip_count = 1;
372 const auto words = g::encode(img);
373
374 const char* why = nullptr;
375 const auto result = rt::d3d12::test_bind_title_image(device.p, words, &why);
376 check(result == rt::d3d12::TitleImage::unknown, "unknown address returns TitleImage::unknown");
377 check(why && std::string(why) == "no texture at T# address",
378 "unknown address explains no texture at T# address");
379 }
380
381 // Not a valid T# (decode failure)
382 {
383 std::array<std::uint32_t, 8> raw_words{0x1, 0x2, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0};
384 const char* why = nullptr;
385 const auto result = rt::d3d12::test_bind_title_image(device.p, raw_words, &why);
386 check(result == rt::d3d12::TitleImage::not_tsharp, "invalid words return TitleImage::not_tsharp");
387 check(why && std::string(why) == "not a valid T# (swizzle, levels or layers)",
388 "invalid words explains not a valid T#");
389 }
390 }
391
392 std::printf("d3d12_unbound_tsharp_rules_test: %d checks, %d failures\n", g_checks, g_failures);
393 return g_failures == 0 ? 0 : 1;
394}
diff --git a/runtime/test/d3d12_unmapped_vsharp_test.cpp b/runtime/test/d3d12_unmapped_vsharp_test.cpp
index 83fe2c090..2e072ce40 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
152 std::memcpy(cpu + slot * kDescriptor, w.data(), sizeof(w)); 152 std::memcpy(cpu + slot * kDescriptor, w.data(), sizeof(w));
153 }; 153 };
154 put(0, raw_vsharp(unmapped)); 154 put(0, raw_vsharp(unmapped));
155 for (int i = 4; i < 131; ++i) put(i, raw_vsharp(unmapped));
156 put(1, raw_vsharp(b.arena_va)); 155 put(1, raw_vsharp(b.arena_va));
157 put(2, raw_vsharp(b.upload_va & 0xFFFFFFFFFFFFull)); 156 put(2, raw_vsharp(b.upload_va & 0xFFFFFFFFFFFFull));
158 auto image_like = raw_vsharp(unmapped); 157 auto image_like = raw_vsharp(unmapped);
diff --git a/runtime/test/d3d12_vram_budget_test.cpp b/runtime/test/d3d12_vram_budget_test.cpp
new file mode 100644
index 000000000..0f69d7548
--- /dev/null
+++ b/runtime/test/d3d12_vram_budget_test.cpp
@@ -0,0 +1,103 @@
1// rt::d3d12::vulkan_vram_budget on the standalone Vulkan-backed device: the GPU memory in use and the budget the
2// title HUD shows (shims/title_hud.h), from VK_EXT_memory_budget. The device enables the extension exactly when the
3// GPU has it; then, with a 64 MiB default-heap buffer alive, the device-local budget and the usage are non-zero.
4// The device publishes that figure for the HUD and the dev overlay (src/memory_figures.h) and withdraws it when it
5// is released. Without the extension the figure is not available, and the test skips (77) after checking that.
6// Also skips without a Vulkan GPU. No shaders or game data.
7#include "../shims/d3d12_com.h"
8
9#include <cstdint>
10#include <cstdio>
11#include <cstring>
12#include <vector>
13
14#define EXPECT(condition) do { \
15 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
16} while (0)
17
18namespace {
19
20template<class T>
21struct Ref {
22 T* p = nullptr;
23 ~Ref() {
24 if (p) p->Release();
25 }
26};
27
28constexpr std::uint64_t kMiB = 1ull << 20;
29
30bool physical_has_memory_budget(const rt::d3d12::VulkanDeviceInfo& info) {
31 const auto enumerate = reinterpret_cast<PFN_vkEnumerateDeviceExtensionProperties>(
32 info.get_instance_proc(info.instance, "vkEnumerateDeviceExtensionProperties"));
33 if (!enumerate) return false;
34 std::uint32_t count = 0;
35 if (enumerate(info.physical, nullptr, &count, nullptr) != VK_SUCCESS) return false;
36 std::vector<VkExtensionProperties> extensions(count);
37 if (enumerate(info.physical, nullptr, &count, extensions.data()) != VK_SUCCESS) return false;
38 for (const auto& e : extensions)
39 if (!std::strcmp(e.extensionName, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) return true;
40 return false;
41}
42
43void print(const char* when, const leonida::VramBudget& b) {
44 std::printf("%s: %s, device-local %llu of %llu MiB, other heaps %llu MiB\n", when,
45 b.available ? "available" : "not available", (unsigned long long)(b.local_usage / kMiB),
46 (unsigned long long)(b.local_budget / kMiB), (unsigned long long)(b.shared_usage / kMiB));
47}
48
49} // namespace
50
51int main() {
52 Ref<ID3D12Device> device;
53 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))) || !device.p) {
54 std::printf("SKIP: no Vulkan device\n");
55 return 77;
56 }
57 const rt::d3d12::VulkanDeviceInfo* info = rt::d3d12::vulkan_device_info(device.p);
58 EXPECT(info && info->get_instance_proc && info->instance && info->physical);
59 EXPECT(!rt::d3d12::vulkan_vram_budget(nullptr).available);
60
61 // Enabled exactly when the GPU has it.
62 const bool supported = physical_has_memory_budget(*info);
63 EXPECT(info->memory_budget == supported);
64 // What the title HUD and the dev overlay show (src/memory_figures.h): this device's figure once it has one.
65 EXPECT(leonida::memory_figures::latest_vram().available == supported);
66 if (!supported) {
67 EXPECT(!rt::d3d12::vulkan_vram_budget(device.p).available); // the HUD and the overlay show "n/a"
68 std::printf("SKIP: the GPU has no VK_EXT_memory_budget; the figure is not available\n");
69 return 77;
70 }
71
72 print("before", rt::d3d12::vulkan_vram_budget(device.p));
73 D3D12_HEAP_PROPERTIES heap{};
74 heap.Type = D3D12_HEAP_TYPE_DEFAULT;
75 D3D12_RESOURCE_DESC desc{};
76 desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
77 desc.Width = 64 * kMiB;
78 desc.Height = 1;
79 desc.DepthOrArraySize = 1;
80 desc.MipLevels = 1;
81 desc.SampleDesc.Count = 1;
82 desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
83 Ref<ID3D12Resource> buffer;
84 EXPECT(SUCCEEDED(device.p->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON,
85 nullptr, IID_PPV_ARGS(&buffer.p))));
86 const leonida::VramBudget after = rt::d3d12::vulkan_vram_budget(device.p);
87 print("with a 64 MiB buffer", after);
88 EXPECT(after.available);
89 EXPECT(after.local_budget > 0);
90 EXPECT(after.local_usage + after.shared_usage > 0);
91 const leonida::VramBudget published = leonida::memory_figures::latest_vram();
92 EXPECT(published.available && published.local_budget > 0); // may be the read before the buffer: cached
93
94 // A released device withdraws its figure: nothing reads a device that is gone.
95 buffer.p->Release();
96 buffer.p = nullptr;
97 device.p->Release();
98 device.p = nullptr;
99 EXPECT(!leonida::memory_figures::latest_vram().available);
100 std::printf("d3d12_vram_budget: VK_EXT_memory_budget enabled; usage and budget read from the device and published"
101 " while it lives\n");
102 return 0;
103}
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp
index 9df462d3f..ef60f1855 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
2423 fail("unknown feature unexpectedly answered"); 2423 fail("unknown feature unexpectedly answered");
2424 2424
2425 // Local invariants for what this layer actually implements. 2425 // Local invariants for what this layer actually implements.
2426 if (o2.DepthBoundsTestSupported || 2426 // DepthBoundsTestSupported follows the device's depthBounds feature.
2427 o2.ProgrammableSamplePositionsTier != D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED) 2427 if (o2.ProgrammableSamplePositionsTier != D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED)
2428 fail("OPTIONS2 unexpected support"); 2428 fail("OPTIONS2 unexpected support");
2429 if (o3.CastingFullyTypedFormatSupported || 2429 if (o3.CastingFullyTypedFormatSupported ||
2430 o3.WriteBufferImmediateSupportFlags != D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE || 2430 o3.WriteBufferImmediateSupportFlags != D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE ||
@@ -6766,8 +6766,11 @@ int main() {
6766 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&timestamps.p)))); 6766 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&timestamps.p))));
6767 query_desc = {D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0, 0}; 6767 query_desc = {D3D12_QUERY_HEAP_TYPE_OCCLUSION, 0, 0};
6768 EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && !refused.p); 6768 EXPECT(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG && !refused.p);
6769 // The layer has no stream output, so stream-output statistics heaps are made without a Vulkan pool and 6769 // D3D-302: an SO_STATISTICS heap is a real transform-feedback pool on a device with
6770 // every query reads zero (D3D-302). 6770 // VK_EXT_transform_feedback whose transformFeedbackQueries property is set (indexed on the stream); without
6771 // them the heap is made without a Vulkan pool and every query reads zero. A stream past
6772 // maxTransformFeedbackStreams reads zero too. StreamOutput PSOs are still refused, so no stream output runs
6773 // and the resolved counts are 0 in either case.
6771 query_desc = {D3D12_QUERY_HEAP_TYPE_SO_STATISTICS, 3, 0}; 6774 query_desc = {D3D12_QUERY_HEAP_TYPE_SO_STATISTICS, 3, 0};
6772 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&so.p)))); 6775 EXPECT(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&so.p))));
6773 query_desc = {D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 2, 0}; 6776 query_desc = {D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 2, 0};
diff --git a/runtime/test/descriptor_table_test.cpp b/runtime/test/descriptor_table_test.cpp
index 387bd0c60..287d68cde 100644
--- a/runtime/test/descriptor_table_test.cpp
+++ b/runtime/test/descriptor_table_test.cpp
@@ -546,6 +546,49 @@ int test_capacity_overflow() {
546 return 0; 546 return 0;
547} 547}
548 548
549// The entry's last dword is what a `descriptor_table` tagged module reads next to the index: the occupied bit and
550// the arrays the index is bound in (kind_sampled_bit / kind_storage_bit). A plain module never reads it, so a table
551// inserted without a kind must serialize exactly as before (marker, no kind bits).
552int test_kind_word() {
553 DescriptorTable table(16);
554 const DescriptorKey image = make_tsharp_key(std::array<std::uint32_t, 8>{0x00001000u, 0x00000000u, 0u, 0u,
555 0u, 0u, 0u, 0u}.data());
556 const std::uint32_t kind = kind_sampled_bit(1) | kind_storage_bit(1);
557 EXPECT(table.insert(image, 5, kind));
558 EXPECT(table.lookup(image) == 5);
559 const auto words = table.build_gpu_buffer();
560 EXPECT(words[0] == 15);
561 const std::uint32_t slot = (hash_descriptor_key(image.data(), DescriptorHashKind::fnv1a) & 15);
562 if (words[1 + slot * 10 + 8] != 5) return 1; // find the slot the key landed in
563 EXPECT((words[1 + slot * 10 + 9] & kSlotOccupiedMarker) != 0);
564 EXPECT((words[1 + slot * 10 + 9] & kKindMask) == kind);
565
566 // A plain entry: the marker and no kind bits, as before the marker existed.
567 const DescriptorKey plain = make_tsharp_key(std::array<std::uint32_t, 8>{0x00002000u, 0u, 0u, 0u, 0u, 0u, 0u,
568 0u}.data());
569 EXPECT(table.insert(plain, 6));
570 std::uint32_t found[10];
571 EXPECT(table.read_slot(slot, found));
572 (void)found;
573 DescriptorEntry entry{};
574 entry.kind = kSlotOccupiedMarker;
575 EXPECT(slot_occupied(entry) && slot_kind(entry) == 0);
576
577 // The same index with a new kind is a change the GPU copy needs.
578 EXPECT(table.insert_or_update(image.data(), 5, kind_sampled_bit(2)) ==
579 DescriptorTable::InsertResult::replaced);
580 EXPECT(table.insert_or_update(image.data(), 5, kind_sampled_bit(2)) ==
581 DescriptorTable::InsertResult::unchanged);
582 const auto changed = table.take_changes();
583 EXPECT(!changed.slots.empty() || changed.all);
584
585 // clear_occupied drops the marker but keeps the kind, which is what a shader reads.
586 const auto gpu = table.build_gpu_buffer(true);
587 EXPECT((gpu[1 + slot * 10 + 9] & kSlotOccupiedMarker) == 0);
588 EXPECT((gpu[1 + slot * 10 + 9] & kKindMask) == kind_sampled_bit(2));
589 return 0;
590}
591
549int main() { 592int main() {
550 EXPECT(test_unresolvable_hash_collision() == 0); 593 EXPECT(test_unresolvable_hash_collision() == 0);
551 EXPECT(test_capacity_overflow() == 0); 594 EXPECT(test_capacity_overflow() == 0);
@@ -565,6 +608,7 @@ int main() {
565 EXPECT(test_multithreaded_insert_and_lookup() == 0); 608 EXPECT(test_multithreaded_insert_and_lookup() == 0);
566 EXPECT(test_clear_resets_table() == 0); 609 EXPECT(test_clear_resets_table() == 0);
567 EXPECT(test_erase_and_reinsert() == 0); 610 EXPECT(test_erase_and_reinsert() == 0);
611 EXPECT(test_kind_word() == 0);
568 612
569 std::printf("descriptor_table_test: all tests passed (0 failures)\n"); 613 std::printf("descriptor_table_test: all tests passed (0 failures)\n");
570 return 0; 614 return 0;
diff --git a/runtime/test/dev_overlay_test.cpp b/runtime/test/dev_overlay_test.cpp
new file mode 100644
index 000000000..55a5a31cc
--- /dev/null
+++ b/runtime/test/dev_overlay_test.cpp
@@ -0,0 +1,166 @@
1// src/dev_overlay.h: the text of a sample, the counter differences, the phase bookkeeping behind its "now" line
2// (submit_phases.h), the pipeline builds in flight (dev_status.h) and the memory figures it shares with the title HUD
3// (memory_figures.h). No window, GPU or game file.
4#include "dev_overlay.h"
5
6#include <chrono>
7#include <cstdint>
8#include <cstdio>
9#include <string>
10#include <thread>
11#include <vector>
12
13#define CHECK(condition) do { \
14 if (!(condition)) { \
15 std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
16 return 1; \
17 } \
18} while (0)
19
20namespace sp = leonida::submit_phases;
21namespace dov = leonida::dev_overlay;
22
23static bool has(const std::vector<std::string>& lines, const char* part) {
24 for (const auto& line : lines)
25 if (line.find(part) != std::string::npos) return true;
26 return false;
27}
28
29// memory_figures.h, which the overlay and the title HUD share: the private bytes Wine reports, the text of both
30// figures with and without one, and the device's published GPU memory, read at most once per refresh.
31static int check_memory_figures() {
32 namespace mf = leonida::memory_figures;
33 constexpr std::uint64_t kGiB = 1ull << 30;
34
35 // Wine fills PagefileUsage and leaves PrivateUsage 0; Windows fills both with the same value.
36 mf::ProcessMemory ram;
37 CHECK(mf::ram_text(ram) == "RAM n/a"); // GetProcessMemoryInfo failed
38 ram.read = true;
39 ram.working_set = kGiB;
40 CHECK(mf::ram_text(ram) == "RAM n/a (ws 1.0)");
41 ram.pagefile_usage = 5 * kGiB / 2;
42 CHECK(mf::private_bytes(ram) == 5 * kGiB / 2 && mf::ram_text(ram) == "RAM 2.5 GB (ws 1.0)");
43 ram.private_usage = 5 * kGiB / 2;
44 CHECK(mf::private_bytes(ram) == 5 * kGiB / 2 && mf::ram_text(ram) == "RAM 2.5 GB (ws 1.0)");
45
46 leonida::VramBudget vram;
47 CHECK(mf::vram_text(vram) == "VRAM n/a");
48 vram.available = true;
49 vram.local_usage = 3 * kGiB + kGiB / 2;
50 vram.local_budget = 16 * kGiB;
51 vram.shared_usage = kGiB / 2;
52 CHECK(mf::vram_text(vram) == "VRAM 3.5/16.0 GB +0.5 shared");
53
54 // The overlay's line with both figures.
55 dov::Sample s;
56 s.ram = ram;
57 s.vram = vram;
58 CHECK(has(dov::lines(s, 1), "RAM 2.5 GB (ws 1.0) VRAM 3.5/16.0 GB +0.5 shared"));
59
60 // The published figure: none until a device publishes a reader; then read at most once per refresh_ms; another
61 // device's withdrawal leaves it; its own takes it away.
62 struct Fake {
63 int reads = 0;
64 leonida::VramBudget figure;
65 };
66 static Fake device;
67 static const int other = 0;
68 device.figure = vram;
69 auto& publisher = mf::vram_publisher();
70 using clock = std::chrono::steady_clock;
71 const clock::time_point t0 = clock::now();
72 CHECK(!publisher.latest(t0).available);
73 mf::publish_vram_reader(
74 [](const void* context) {
75 auto* fake = static_cast<Fake*>(const_cast<void*>(context));
76 ++fake->reads;
77 return fake->figure;
78 },
79 &device);
80 CHECK(publisher.latest(t0).local_usage == 3 * kGiB + kGiB / 2 && device.reads == 1);
81 device.figure.local_usage = 4 * kGiB;
82 CHECK(publisher.latest(t0 + mf::refresh_ms / 2).local_usage == 3 * kGiB + kGiB / 2 && device.reads == 1);
83 CHECK(publisher.latest(t0 + mf::refresh_ms).local_usage == 4 * kGiB && device.reads == 2);
84 mf::withdraw_vram_reader(&other);
85 CHECK(mf::latest_vram().available);
86 mf::withdraw_vram_reader(&device);
87 CHECK(!mf::latest_vram().available);
88 return 0;
89}
90
91int main() {
92 // A total that went down was reset by its log line: what it holds is the new part.
93 std::uint64_t before = 0;
94 CHECK(dov::grown(10, before) == 10 && before == 10);
95 CHECK(dov::grown(25, before) == 15);
96 CHECK(dov::grown(4, before) == 4 && before == 4);
97
98 // Nested scopes: the inner one is running, then the outer one again, then none.
99 CHECK(sp::running().phase == -1);
100 {
101 const sp::Scope replay(sp::replay);
102 CHECK(sp::running().phase == sp::replay);
103 {
104 const sp::Scope textures(sp::textures);
105 CHECK(sp::running().phase == sp::textures);
106 }
107 CHECK(sp::running().phase == sp::replay);
108 }
109 CHECK(sp::running().phase == -1);
110
111 // Two threads whose scopes overlap and end in the order they began: no phase stays behind.
112 {
113 std::atomic<int> step{0};
114 std::thread a([&] {
115 const sp::Scope heaps(sp::heaps);
116 step = 1;
117 while (step.load() < 2) std::this_thread::yield();
118 });
119 std::thread b([&] {
120 while (step.load() < 1) std::this_thread::yield();
121 const sp::Scope shadows(sp::shadows);
122 step = 2;
123 while (step.load() < 3) std::this_thread::yield();
124 });
125 a.join();
126 CHECK(sp::running().phase == sp::shadows);
127 step = 3;
128 b.join();
129 CHECK(sp::running().phase == -1);
130 }
131
132 // The builds in flight and the last one's name, cut to its buffer.
133 auto& builds = leonida::dev_status::builds();
134 const auto done = builds.done.load();
135 {
136 const leonida::dev_status::Build one("one");
137 const leonida::dev_status::Build two(std::string(500, 'x').c_str());
138 CHECK(builds.active.load() == 2 && builds.last() == std::string(95, 'x'));
139 }
140 CHECK(builds.active.load() == 0 && builds.done.load() == done + 2);
141
142 dov::Sample s;
143 auto text = dov::lines(s, 12);
144 CHECK(text.size() == 7);
145 // No counters and no device figure: "n/a", never a false 0.
146 CHECK(has(text, "RAM n/a VRAM n/a"));
147 CHECK(has(text, "12 s") && has(text, "now: the title's own code") && has(text, "pipelines: 0 built"));
148 CHECK(!has(text, "building"));
149 s.frames = 8.44;
150 s.phase = sp::textures;
151 s.phase_for = 3.9;
152 s.phase_ms[sp::shadows] = 2;
153 s.phase_ms[sp::geometry] = 1.5;
154 s.building = 3;
155 s.built = 853;
156 s.build = std::string(200, 'n'); // longer than the line's part for it
157 s.drawn = 3029;
158 s.skipped = 38363;
159 text = dov::lines(s, 147);
160 CHECK(has(text, "8.4 fps") && has(text, "now: refreshing textures for 3 s") && has(text, "copies 3.5"));
161 CHECK(has(text, "853 built, 3 building (nnn") && has(text, "3029 drawn, 38363 skipped"));
162 for (const auto& line : text) CHECK(line.size() < 160);
163 if (const int failed = check_memory_figures()) return failed;
164 std::puts("dev_overlay_test: ok");
165 return 0;
166}
diff --git a/runtime/test/dxgi_swapchain_count_test.cpp b/runtime/test/dxgi_swapchain_count_test.cpp
index fbbca182a..c0ca5f6ad 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
267 g = Fake{}; 267 g = Fake{};
268 g.min_image_count = minimum; 268 g.min_image_count = minimum;
269 g.returned_images = native; 269 g.returned_images = native;
270 std::mutex mutex; 270 leonida::SubmitMutex mutex;
271 leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast<VkInstance>(1), 271 leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast<VkInstance>(1),
272 reinterpret_cast<VkPhysicalDevice>(2), get_device_proc, 272 reinterpret_cast<VkPhysicalDevice>(2), get_device_proc,
273 reinterpret_cast<VkDevice>(3), reinterpret_cast<VkQueue>(4), 0, mutex, 273 reinterpret_cast<VkDevice>(3), reinterpret_cast<VkQueue>(4), 0, mutex,
@@ -375,7 +375,7 @@ int run_failed_resize(const char* label, std::uint32_t requested, std::uint32_t
375 g = Fake{}; 375 g = Fake{};
376 g.min_image_count = 2; 376 g.min_image_count = 2;
377 g.returned_images = native; 377 g.returned_images = native;
378 std::mutex mutex; 378 leonida::SubmitMutex mutex;
379 leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast<VkInstance>(1), 379 leonida::VulkanSwapchain swapchain(get_instance_proc, reinterpret_cast<VkInstance>(1),
380 reinterpret_cast<VkPhysicalDevice>(2), get_device_proc, 380 reinterpret_cast<VkPhysicalDevice>(2), get_device_proc,
381 reinterpret_cast<VkDevice>(3), reinterpret_cast<VkQueue>(4), 0, mutex, 381 reinterpret_cast<VkDevice>(3), reinterpret_cast<VkQueue>(4), 0, mutex,
diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp
index 493ffd6bf..af37935f6 100644
--- a/runtime/test/file_system_test.cpp
+++ b/runtime/test/file_system_test.cpp
@@ -8,6 +8,7 @@
8#include <aclapi.h> 8#include <aclapi.h>
9 9
10#include <algorithm> 10#include <algorithm>
11#include <atomic>
11#include <clocale> 12#include <clocale>
12#include <cstring> 13#include <cstring>
13#include <cstdio> 14#include <cstdio>
@@ -118,6 +119,81 @@ int count(const std::vector<std::wstring>& names, const wchar_t* name) {
118 119
119bool contains(const std::vector<std::wstring>& names, const wchar_t* name) { return count(names, name) != 0; } 120bool contains(const std::vector<std::wstring>& names, const wchar_t* name) { return count(names, name) != 0; }
120 121
122// The folder "T:\" names in another process `pid`: the one below <overlay>\.gta6rt-temp whose name ends in
123// "-pid<pid>" or "-pid<pid>-<n>" (rt::fs::scratch_dir() in that process). Empty when there is none, as when every
124// process shared .gta6rt-temp.
125std::filesystem::path t_folder(const std::filesystem::path& overlay, DWORD pid) {
126 const std::wstring marker = L"-pid" + std::to_wstring(pid);
127 std::error_code ec;
128 for (auto it = std::filesystem::directory_iterator(overlay / ".gta6rt-temp", ec);
129 !ec && it != std::filesystem::directory_iterator(); it.increment(ec)) {
130 const std::wstring name = it->path().filename().wstring();
131 const size_t at = name.rfind(marker);
132 std::error_code type_ec;
133 if (it->is_directory(type_ec) && at != std::wstring::npos &&
134 (at + marker.size() == name.size() || name[at + marker.size()] == L'-'))
135 return it->path();
136 }
137 return {};
138}
139
140// This process's T: folder in the configured overlay.
141std::filesystem::path own_t_folder(const std::filesystem::path& overlay) {
142 return rt::fs::overlay_dir() == overlay ? rt::fs::scratch_dir() : std::filesystem::path();
143}
144
145// file_system_test started by itself as a second process (run_t_drive_child below): it opens T:\crash.dmp with
146// CREATE_NEW on the overlay its parent uses, writes "child process" and exits with 0, or with the open's Win32 error.
147constexpr wchar_t kChildPackage[] = L"LEONIDA_FS_TEST_CHILD_PACKAGE";
148constexpr wchar_t kChildOverlay[] = L"LEONIDA_FS_TEST_CHILD_OVERLAY";
149
150std::wstring environment(const wchar_t* name) {
151 std::wstring buffer(32768, L'\0');
152 const DWORD n = ::GetEnvironmentVariableW(name, buffer.data(), static_cast<DWORD>(buffer.size()));
153 if (n == 0 || n >= buffer.size()) return {};
154 buffer.resize(n);
155 return buffer;
156}
157
158int t_drive_child(const std::wstring& package, const std::wstring& overlay) {
159 rt::fs::configure(package, overlay);
160 const auto create_w = resolve<CreateFileWFn>("kernel32.dll", "CreateFileW");
161 if (!create_w) return 1000;
162 const HANDLE h = create_w(L"T:\\crash.dmp", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr);
163 if (h == INVALID_HANDLE_VALUE) return static_cast<int>(::GetLastError());
164 DWORD written = 0;
165 ::WriteFile(h, "child process", 13, &written, nullptr);
166 ::CloseHandle(h);
167 return 0;
168}
169
170// Runs t_drive_child in a new process of this executable on the given folders. Returns its exit code (~0u when it
171// could not be started or did not finish) and its process id in `pid`.
172DWORD run_t_drive_child(const std::filesystem::path& package, const std::filesystem::path& overlay, DWORD& pid) {
173 pid = 0;
174 std::wstring self(32768, L'\0');
175 const DWORD length = ::GetModuleFileNameW(nullptr, self.data(), static_cast<DWORD>(self.size()));
176 if (length == 0 || length >= self.size()) return ~0u;
177 self.resize(length);
178 std::wstring command = L"\"" + self + L"\"";
179 ::SetEnvironmentVariableW(kChildPackage, package.c_str());
180 ::SetEnvironmentVariableW(kChildOverlay, overlay.c_str());
181 STARTUPINFOW startup{};
182 startup.cb = sizeof(startup);
183 PROCESS_INFORMATION process{};
184 const BOOL started = ::CreateProcessW(self.c_str(), command.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr,
185 &startup, &process);
186 ::SetEnvironmentVariableW(kChildPackage, nullptr);
187 ::SetEnvironmentVariableW(kChildOverlay, nullptr);
188 if (!started) return ~0u;
189 DWORD code = ~0u;
190 if (::WaitForSingleObject(process.hProcess, 60000) == WAIT_OBJECT_0) ::GetExitCodeProcess(process.hProcess, &code);
191 pid = process.dwProcessId;
192 ::CloseHandle(process.hThread);
193 ::CloseHandle(process.hProcess);
194 return code;
195}
196
121// Denies the current user `rights` on a folder while it lives and puts the folder's old DACL back when it goes, on 197// Denies the current user `rights` on a folder while it lives and puts the folder's old DACL back when it goes, on
122// every way out of the check. Both changes go through one handle opened before the deny. Under Wine the DACL is the 198// every way out of the check. Both changes go through one handle opened before the deny. Under Wine the DACL is the
123// folder's unix mode: a deny of FILE_LIST_DIRECTORY clears its owner and group read bits (server/file.c, sd_to_mode), 199// folder's unix mode: a deny of FILE_LIST_DIRECTORY clears its owner and group read bits (server/file.c, sd_to_mode),
@@ -244,6 +320,8 @@ void check_read_file_first_touch(const std::filesystem::path& root) {
244} // namespace 320} // namespace
245 321
246int main() { 322int main() {
323 if (const std::wstring child_overlay = environment(kChildOverlay); !child_overlay.empty())
324 return t_drive_child(environment(kChildPackage), child_overlay);
247 // A folder of this run's own: Wine hands each fresh prefix the same small process ids, so a folder named after 325 // A folder of this run's own: Wine hands each fresh prefix the same small process ids, so a folder named after
248 // the process id alone can be one an earlier run left behind. 326 // the process id alone can be one an earlier run left behind.
249 LARGE_INTEGER now{}; 327 LARGE_INTEGER now{};
@@ -850,6 +928,75 @@ void run_checks(const std::filesystem::path& root) {
850 } 928 }
851 } 929 }
852 930
931 // RemoveDirectory of a folder on one thread and, on another, a creating open of a file in it (CREATE_NEW,
932 // CREATE_ALWAYS, OPEN_ALWAYS) or CreateDirectory of a folder in it. The host orders the two: the remove goes first
933 // and the create fails with ERROR_PATH_NOT_FOUND, or the create goes first and the remove fails with
934 // ERROR_DIR_NOT_EMPTY. Both succeeding left the removed folder back in the title's view with the new entry in it.
935 // Each round takes a folder of its own that only the package has, empty in the title's view, and starts the two
936 // threads together; the remover waits a few more spins each round so the calls meet at different points.
937 {
938 constexpr int kRounds = 2000;
939 const auto race = [&](bool make_folder, const wchar_t* prefix, const char* what) {
940 for (int i = 0; i < kRounds; ++i)
941 std::filesystem::create_directories(package / "rmrace" / (prefix + std::to_wstring(i)));
942 int create_first = 0, remove_first = 0, both = 0, other = 0, back = 0;
943 for (int i = 0; i < kRounds; ++i) {
944 const std::wstring folder = L"GAME:\\rmrace\\" + (prefix + std::to_wstring(i));
945 const std::wstring child = folder + (make_folder ? L"\\sub" : L"\\new.tmp");
946 const DWORD disposition = i % 3 == 0 ? CREATE_NEW : i % 3 == 1 ? CREATE_ALWAYS : OPEN_ALWAYS;
947 std::atomic<int> ready{0};
948 HANDLE handle = INVALID_HANDLE_VALUE;
949 bool made = false;
950 DWORD create_error = 0;
951 std::thread creator([&] {
952 ready.fetch_add(1);
953 while (ready.load() < 2) {
954 }
955 if (make_folder) {
956 made = mkdir_w(child.c_str(), nullptr) != FALSE;
957 } else {
958 handle = create_w(child.c_str(), GENERIC_WRITE, 0, nullptr, disposition, 0, nullptr);
959 made = handle != INVALID_HANDLE_VALUE;
960 }
961 create_error = made ? 0 : GetLastError();
962 });
963 ready.fetch_add(1);
964 while (ready.load() < 2) {
965 }
966 for (int spin = 0; spin < (i % 64) * 64; ++spin) YieldProcessor();
967 const bool removed = rmdir_w(folder.c_str()) != FALSE;
968 const DWORD remove_error = removed ? 0 : GetLastError();
969 creator.join();
970 if (handle != INVALID_HANDLE_VALUE) ::CloseHandle(handle);
971 if (made && removed) {
972 ++both;
973 } else if (made && remove_error == ERROR_DIR_NOT_EMPTY) {
974 ++create_first;
975 } else if (removed && create_error == ERROR_PATH_NOT_FOUND) {
976 ++remove_first;
977 } else {
978 ++other;
979 }
980 // A folder the remove took away stays away, whatever the create did.
981 if (removed) {
982 SetLastError(0);
983 if (attributes_w(folder.c_str()) != INVALID_FILE_ATTRIBUTES || GetLastError() != ERROR_FILE_NOT_FOUND)
984 ++back;
985 }
986 }
987 std::printf("NOTE %s against RemoveDirectoryW, %d rounds: create first %d, remove first %d, both succeeded "
988 "%d, other %d, removed folder back %d\n",
989 what, kRounds, create_first, remove_first, both, other, back);
990 const std::string w = what;
991 check(both == 0, (w + " and RemoveDirectoryW of its folder never both succeed").c_str());
992 check(other == 0, (w + " or RemoveDirectoryW fails as on the host (ERROR_PATH_NOT_FOUND or "
993 "ERROR_DIR_NOT_EMPTY)").c_str());
994 check(back == 0, (w + ": a folder RemoveDirectoryW removed stays removed").c_str());
995 };
996 race(false, L"f", "a creating CreateFileW");
997 race(true, L"d", "CreateDirectoryW");
998 }
999
853 // MoveFile: the destination is in the overlay; a moved package file is deleted by a marker. 1000 // MoveFile: the destination is in the overlay; a moved package file is deleted by a marker.
854 { 1001 {
855 check(move_w(L"GAME:\\misc\\one.txt", L"GAME:\\misc\\moved.txt") != FALSE, "MoveFileW moves a package file"); 1002 check(move_w(L"GAME:\\misc\\one.txt", L"GAME:\\misc\\moved.txt") != FALSE, "MoveFileW moves a package file");
@@ -1274,18 +1421,18 @@ void run_checks(const std::filesystem::path& root) {
1274 "on a fresh overlay CreateDirectoryW(T:\\shadercache) succeeds"); 1421 "on a fresh overlay CreateDirectoryW(T:\\shadercache) succeeds");
1275 std::filesystem::path fresh = fresh_overlay(); 1422 std::filesystem::path fresh = fresh_overlay();
1276 check(copy_w(L"GAME:\\data\\hello.txt", L"T:\\hello.tmp", FALSE) != FALSE && 1423 check(copy_w(L"GAME:\\data\\hello.txt", L"T:\\hello.tmp", FALSE) != FALSE &&
1277 read_path(fresh / ".gta6rt-temp" / "hello.tmp") == "package", 1424 read_path(own_t_folder(fresh) / "hello.tmp") == "package",
1278 "on a fresh overlay CopyFileW(GAME:\\data\\hello.txt, T:\\hello.tmp) succeeds"); 1425 "on a fresh overlay CopyFileW(GAME:\\data\\hello.txt, T:\\hello.tmp) succeeds");
1279 fresh = fresh_overlay(); 1426 fresh = fresh_overlay();
1280 SetLastError(0); 1427 SetLastError(0);
1281 check(rmdir_w(L"T:\\") == FALSE && GetLastError() == ERROR_ACCESS_DENIED && 1428 check(rmdir_w(L"T:\\") == FALSE && GetLastError() == ERROR_ACCESS_DENIED &&
1282 std::filesystem::is_directory(fresh / ".gta6rt-temp"), 1429 std::filesystem::is_directory(own_t_folder(fresh)),
1283 "T:\\ cannot be removed, like GAME:\\"); 1430 "T:\\ cannot be removed, like GAME:\\");
1284 fresh = fresh_overlay(); 1431 fresh = fresh_overlay();
1285 SetLastError(0); 1432 SetLastError(0);
1286 check(move_w(L"T:\\", L"GAME:\\moved") == FALSE && GetLastError() == ERROR_ACCESS_DENIED && 1433 check(move_w(L"T:\\", L"GAME:\\moved") == FALSE && GetLastError() == ERROR_ACCESS_DENIED &&
1287 attributes_w(L"GAME:\\moved") == INVALID_FILE_ATTRIBUTES && 1434 attributes_w(L"GAME:\\moved") == INVALID_FILE_ATTRIBUTES &&
1288 std::filesystem::is_directory(fresh / ".gta6rt-temp"), 1435 std::filesystem::is_directory(own_t_folder(fresh)),
1289 "T:\\ cannot be moved"); 1436 "T:\\ cannot be moved");
1290 fresh_overlay(); 1437 fresh_overlay();
1291 attributes_w(L"T:\\"); 1438 attributes_w(L"T:\\");
@@ -1302,8 +1449,8 @@ void run_checks(const std::filesystem::path& root) {
1302 ::WriteFile(h, "scratch", 7, &written, nullptr); 1449 ::WriteFile(h, "scratch", 7, &written, nullptr);
1303 ::CloseHandle(h); 1450 ::CloseHandle(h);
1304 } 1451 }
1305 check(read_path(overlay / ".gta6rt-temp" / "cache" / "scratch.bin") == "scratch", 1452 check(read_path(own_t_folder(overlay) / "cache" / "scratch.bin") == "scratch",
1306 "a T: file lands in the overlay's scratch folder"); 1453 "a T: file lands in this process's scratch folder in the overlay");
1307 check(!std::filesystem::exists(package / "cache" / "scratch.bin") && !std::filesystem::exists(package / ".gta6rt-temp"), 1454 check(!std::filesystem::exists(package / "cache" / "scratch.bin") && !std::filesystem::exists(package / ".gta6rt-temp"),
1308 "and the package is untouched"); 1455 "and the package is untouched");
1309 h = create_w(L"t:/cache/scratch.bin", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); 1456 h = create_w(L"t:/cache/scratch.bin", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
@@ -1323,6 +1470,8 @@ void run_checks(const std::filesystem::path& root) {
1323 // as an explicit GAME: or G: path, refused like any other invalid name, in every spelling parse_console() 1470 // as an explicit GAME: or G: path, refused like any other invalid name, in every spelling parse_console()
1324 // normalises (RT-294). T:\ still names the scratch folder, and an ordinary dotted name is not reserved. 1471 // normalises (RT-294). T:\ still names the scratch folder, and an ordinary dotted name is not reserved.
1325 write_path(overlay / ".gta6rt-temp" / "runtime.tmp", "runtime"); 1472 write_path(overlay / ".gta6rt-temp" / "runtime.tmp", "runtime");
1473 if (const std::filesystem::path t_dir = own_t_folder(overlay); !t_dir.empty())
1474 write_path(t_dir / "runtime.tmp", "runtime");
1326 write_path(overlay / ".gta6rt-deleted" / "data" / "gone.txt", ""); 1475 write_path(overlay / ".gta6rt-deleted" / "data" / "gone.txt", "");
1327 write_path(overlay / ".gta6rt-other" / "ok.txt", "ok"); 1476 write_path(overlay / ".gta6rt-other" / "ok.txt", "ok");
1328 for (const wchar_t* reserved : {L"GAME:\\.gta6rt-temp\\runtime.tmp", L"GAME:\\.GTA6RT-TEMP\\runtime.tmp", 1477 for (const wchar_t* reserved : {L"GAME:\\.gta6rt-temp\\runtime.tmp", L"GAME:\\.GTA6RT-TEMP\\runtime.tmp",
@@ -1347,7 +1496,8 @@ void run_checks(const std::filesystem::path& root) {
1347 if (markers != INVALID_HANDLE_VALUE) find_close(markers); 1496 if (markers != INVALID_HANDLE_VALUE) find_close(markers);
1348 SetLastError(0); 1497 SetLastError(0);
1349 const HANDLE probe = create_w(L"GAME:\\.gta6rt-temp\\probe.txt", GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); 1498 const HANDLE probe = create_w(L"GAME:\\.gta6rt-temp\\probe.txt", GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr);
1350 check(probe == INVALID_HANDLE_VALUE && !std::filesystem::exists(overlay / ".gta6rt-temp" / "probe.txt"), 1499 check(probe == INVALID_HANDLE_VALUE && !std::filesystem::exists(overlay / ".gta6rt-temp" / "probe.txt") &&
1500 !std::filesystem::exists(own_t_folder(overlay) / "probe.txt"),
1351 "a write through GAME:\\.gta6rt-temp creates nothing in the scratch folder"); 1501 "a write through GAME:\\.gta6rt-temp creates nothing in the scratch folder");
1352 if (probe != INVALID_HANDLE_VALUE) ::CloseHandle(probe); 1502 if (probe != INVALID_HANDLE_VALUE) ::CloseHandle(probe);
1353 check(mkdir_w(L"GAME:\\.gta6rt-copy\\sub", nullptr) == FALSE && !std::filesystem::exists(overlay / ".gta6rt-copy" / "sub"), 1503 check(mkdir_w(L"GAME:\\.gta6rt-copy\\sub", nullptr) == FALSE && !std::filesystem::exists(overlay / ".gta6rt-copy" / "sub"),
@@ -1376,6 +1526,157 @@ void run_checks(const std::filesystem::path& root) {
1376 rt::fs::configure(package, overlay); 1526 rt::fs::configure(package, overlay);
1377 } 1527 }
1378 1528
1529 // T: is the title's temporary drive, which on the console no other run shares: each process gets a folder of its
1530 // own below <overlay>\.gta6rt-temp. With one folder for every run, the title's crash dump and crash log, made with
1531 // CREATE_NEW, failed with ERROR_FILE_EXISTS on names an earlier run had left (old upstream issue 7913, measured
1532 // under Wine).
1533 {
1534 const std::filesystem::path t_overlay = root / "t_overlay";
1535 const std::filesystem::path temp = t_overlay / ".gta6rt-temp";
1536 // What earlier runs left: a file in the folder they all shared, and one in an earlier process's own folder.
1537 write_path(temp / "crash.dmp", "earlier run");
1538 write_path(temp / "20200101-000000-000-pid1" / "crash.dmp", "earlier process");
1539 write_path(package / "crash.dmp", "package"); // and a GAME: file of the same name
1540 rt::fs::configure(package, t_overlay);
1541
1542 SetLastError(0);
1543 HANDLE h = create_w(L"T:\\crash.dmp", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr);
1544 const DWORD create_error = h == INVALID_HANDLE_VALUE ? GetLastError() : 0;
1545 check(h != INVALID_HANDLE_VALUE,
1546 "CreateFileW(T:\\crash.dmp, CREATE_NEW) succeeds when earlier runs left that name in .gta6rt-temp");
1547 if (create_error) std::printf(" (failed with Win32 error %lu)\n", static_cast<unsigned long>(create_error));
1548 if (h != INVALID_HANDLE_VALUE) {
1549 DWORD written = 0;
1550 ::WriteFile(h, "this process", 12, &written, nullptr);
1551 ::CloseHandle(h);
1552 }
1553 const std::filesystem::path mine = own_t_folder(t_overlay);
1554 check(!mine.empty() && mine.parent_path() == temp && read_path(mine / "crash.dmp") == "this process",
1555 "T:\\crash.dmp lands in this process's own folder <overlay>\\.gta6rt-temp\\<start time>-pid<id>");
1556 const std::wstring name = mine.filename().wstring();
1557 const auto digits = [&](size_t from, size_t n) {
1558 if (name.size() < from + n) return false;
1559 for (size_t i = from; i < from + n; ++i)
1560 if (name[i] < L'0' || name[i] > L'9') return false;
1561 return true;
1562 };
1563 check(digits(0, 8) && name.size() > 20 && name[8] == L'-' && digits(9, 6) && name[15] == L'-' &&
1564 digits(16, 3) && name.compare(19, 4, L"-pid") == 0,
1565 "the folder is named YYYYMMDD-HHMMSS-mmm-pid<id>, the process's start time and id");
1566 check(name == rt::fs::scratch_stem(), "with no folder of that name yet, it is the stem itself");
1567 check(read_path(temp / "crash.dmp") == "earlier run" &&
1568 read_path(temp / "20200101-000000-000-pid1" / "crash.dmp") == "earlier process" &&
1569 read_path(package / "crash.dmp") == "package",
1570 "the earlier runs' files and the package file of the same name are left as they were");
1571
1572 // The same folder for every T: call of this process, also after configure() names the overlay again.
1573 rt::fs::configure(package, t_overlay);
1574 h = create_w(L"t:/crash.dmp", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
1575 check(h != INVALID_HANDLE_VALUE && read_handle(h) == "this process",
1576 "T: keeps naming the same folder for the rest of the process");
1577 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
1578 const std::vector<std::wstring> t_names = list(first_w, next_w, find_close, L"T:\\*");
1579 check(count(t_names, L"crash.dmp") == 1 && !contains(t_names, L"20200101-000000-000-pid1") &&
1580 !contains(t_names, L".gta6rt-temp"),
1581 "a T:\\ listing shows this process's files only");
1582 SetLastError(0);
1583 check(create_w(L"T:\\..\\crash.dmp", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr) ==
1584 INVALID_HANDLE_VALUE &&
1585 GetLastError() == ERROR_INVALID_NAME,
1586 "T:\\.. cannot climb into the shared .gta6rt-temp folder");
1587 SetLastError(0);
1588 check(rmdir_w(L"T:\\") == FALSE && GetLastError() == ERROR_ACCESS_DENIED && std::filesystem::is_directory(mine),
1589 "this process's T:\\ folder cannot be removed, like GAME:\\");
1590
1591 // A second process on the same overlay gets a folder of its own, and its CREATE_NEW of the same name succeeds.
1592 DWORD child_pid = 0;
1593 const DWORD child_code = run_t_drive_child(package, t_overlay, child_pid);
1594 check(child_code == 0,
1595 "a second process's CreateFileW(T:\\crash.dmp, CREATE_NEW) on the same overlay succeeds");
1596 if (child_code != 0)
1597 std::printf(" (the second process exited with %lu)\n", static_cast<unsigned long>(child_code));
1598 const std::filesystem::path theirs = child_pid ? t_folder(t_overlay, child_pid) : std::filesystem::path();
1599 check(!theirs.empty() && theirs != mine && theirs.parent_path() == temp &&
1600 read_path(theirs / "crash.dmp") == "child process",
1601 "the second process wrote into a folder of its own");
1602 check(read_path(mine / "crash.dmp") == "this process", "and this process's T: file is unchanged");
1603
1604 // A reused process id in the same millisecond gives the same stem as a folder an earlier run kept. The folder
1605 // is reserved with a create-only call, so that one (and the next name, taken too) is never used again.
1606 const std::filesystem::path stale_overlay = root / "t_stale_overlay";
1607 const std::filesystem::path stale = stale_overlay / ".gta6rt-temp" / rt::fs::scratch_stem();
1608 const std::filesystem::path stale_2 = stale_overlay / ".gta6rt-temp" / (rt::fs::scratch_stem() + L"-2");
1609 write_path(stale / "crash.dmp", "same stem, earlier run");
1610 std::filesystem::create_directories(stale_2);
1611 rt::fs::configure(package, stale_overlay);
1612 h = create_w(L"T:\\crash.dmp", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr);
1613 check(h != INVALID_HANDLE_VALUE,
1614 "CreateFileW(T:\\crash.dmp, CREATE_NEW) succeeds when a kept folder has this process's own stem");
1615 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
1616 check(rt::fs::scratch_dir() == stale_overlay / ".gta6rt-temp" / (rt::fs::scratch_stem() + L"-3") &&
1617 std::filesystem::exists(rt::fs::scratch_dir() / "crash.dmp"),
1618 "T: is <stem>-3 when <stem> and <stem>-2 already existed");
1619 check(read_path(stale / "crash.dmp") == "same stem, earlier run" && std::filesystem::is_empty(stale_2),
1620 "and the folders that already existed are left as they were");
1621
1622 // Concurrent first T: calls on a new overlay reserve one folder between them.
1623 const std::filesystem::path race_overlay = root / "t_race_overlay";
1624 rt::fs::configure(package, race_overlay);
1625 {
1626 std::vector<std::thread> threads;
1627 for (int i = 0; i < 8; ++i) threads.emplace_back([&] { attributes_w(L"T:\\"); });
1628 for (auto& thread : threads) thread.join();
1629 }
1630 size_t reserved = 0;
1631 for (const auto& entry : std::filesystem::directory_iterator(race_overlay / ".gta6rt-temp")) {
1632 (void)entry;
1633 ++reserved;
1634 }
1635 check(reserved == 1 && std::filesystem::is_directory(rt::fs::scratch_dir()),
1636 "eight threads making their first T: call at once reserve one folder");
1637 rt::fs::configure(package, t_overlay);
1638
1639 // GAME: is not affected: reads come from the package, writes land in the overlay's mirror of the package.
1640 h = create_w(L"GAME:\\crash.dmp", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
1641 check(h != INVALID_HANDLE_VALUE && read_handle(h) == "package",
1642 "GAME:\\crash.dmp still reads the package file");
1643 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
1644 h = create_w(L"GAME:\\data\\t_written.txt", GENERIC_WRITE, 0, nullptr, CREATE_NEW, 0, nullptr);
1645 check(h != INVALID_HANDLE_VALUE, "a GAME: write-open still succeeds");
1646 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
1647 check(std::filesystem::exists(t_overlay / "data" / "t_written.txt") &&
1648 !std::filesystem::exists(mine / "data") &&
1649 !std::filesystem::exists(package / "data" / "t_written.txt"),
1650 "and lands at <overlay>\\data, not in T:'s folder or the package");
1651 rt::fs::configure(package, overlay);
1652 }
1653
1654 // reserve_unique_dir: a create-only CreateDirectoryW per name, so the folder it returns is new; a name that exists
1655 // (a folder or a file) is skipped, and after max_tries names the call fails instead of reusing one.
1656 {
1657 const std::filesystem::path base = root / "reserve";
1658 std::filesystem::create_directories(base / "stem");
1659 write_path(base / "stem-2" / "old.txt", "old");
1660 DWORD error = 1;
1661 const std::filesystem::path third = rt::fs::reserve_unique_dir(base, L"stem", error);
1662 check(third == base / "stem-3" && error == 0 && std::filesystem::is_directory(third) &&
1663 std::filesystem::is_empty(third),
1664 "reserve_unique_dir(base, stem) with stem and stem-2 taken makes stem-3, new and empty");
1665 check(read_path(base / "stem-2" / "old.txt") == "old", "and leaves the taken folders alone");
1666 check(rt::fs::reserve_unique_dir(base, L"stem", error) == base / "stem-4",
1667 "a second call never hands out stem-3 again: it makes stem-4");
1668 write_path(base / "stem-5", "a file");
1669 check(rt::fs::reserve_unique_dir(base, L"stem", error) == base / "stem-6",
1670 "a file with the next name counts as taken too");
1671 error = 0;
1672 check(rt::fs::reserve_unique_dir(base, L"stem", error, 6).empty() && error == ERROR_ALREADY_EXISTS,
1673 "with every name up to max_tries taken it fails with ERROR_ALREADY_EXISTS");
1674 const std::filesystem::path fresh_base = root / "reserve_new" / "deep";
1675 check(rt::fs::reserve_unique_dir(fresh_base, L"stem", error) == fresh_base / "stem" &&
1676 std::filesystem::is_directory(fresh_base / "stem"),
1677 "a missing base folder is made first, and the stem itself is the first name");
1678 }
1679
1379 // An open that writes needs its folder to exist in the title's view, and a failed open changes nothing. 1680 // An open that writes needs its folder to exist in the title's view, and a failed open changes nothing.
1380 { 1681 {
1381 const auto overlay_has = [&](const wchar_t* name) { return std::filesystem::exists(overlay / name); }; 1682 const auto overlay_has = [&](const wchar_t* name) { return std::filesystem::exists(overlay / name); };
@@ -1650,9 +1951,11 @@ void run_checks(const std::filesystem::path& root) {
1650 check(h != INVALID_HANDLE_VALUE && ::WriteFile(h, "test", 4, &written, nullptr) && written == 4, 1951 check(h != INVALID_HANDLE_VALUE && ::WriteFile(h, "test", 4, &written, nullptr) && written == 4,
1651 "T: creates and writes its scratch directory under a long overlay root"); 1952 "T: creates and writes its scratch directory under a long overlay root");
1652 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h); 1953 if (h != INVALID_HANDLE_VALUE) ::CloseHandle(h);
1653 check(read_guest(L"T:\\scratch.bin") == "test" && 1954 const std::filesystem::path scratch_folder = rt::fs::scratch_dir(); // configured on scratch_overlay above
1654 read_path(extended(scratch_overlay / ".gta6rt-temp" / "scratch.bin")) == "test", 1955 check(read_guest(L"T:\\scratch.bin") == "test" && !scratch_folder.empty() &&
1655 "T: reads from the same long backing directory"); 1956 scratch_folder.parent_path() == scratch_overlay / ".gta6rt-temp" &&
1957 read_path(extended(scratch_folder / "scratch.bin")) == "test",
1958 "T: reads from the same long backing directory, this process's own folder in it");
1656 rt::fs::configure(package, overlay); 1959 rt::fs::configure(package, overlay);
1657 1960
1658 std::error_code cleanup_error; 1961 std::error_code cleanup_error;
diff --git a/runtime/test/fixtures/tiny_game.cpp b/runtime/test/fixtures/tiny_game.cpp
index 21feaad5f..69a696d30 100644
--- a/runtime/test/fixtures/tiny_game.cpp
+++ b/runtime/test/fixtures/tiny_game.cpp
@@ -120,6 +120,7 @@ int main(int argc, char** argv) {
120 }; 120 };
121 check(configured("LEONIDA_D3D12", "vulkan"), "first-run UI Vulkan backend"); 121 check(configured("LEONIDA_D3D12", "vulkan"), "first-run UI Vulkan backend");
122 check(configured("LEONIDA_PIPELINE_COMPILE", "on-demand"), "first-run UI pipeline profile"); 122 check(configured("LEONIDA_PIPELINE_COMPILE", "on-demand"), "first-run UI pipeline profile");
123 check(configured("LEONIDA_KEYBOARD_PAD", "1"), "first-run UI keyboard pad reads keys only with focus");
123 check(configured("LEONIDA_ARENA_MB", "768"), "first-run UI caller override"); 124 check(configured("LEONIDA_ARENA_MB", "768"), "first-run UI caller override");
124 } 125 }
125 126
diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp
index 7f92d51a7..bb632793b 100644
--- a/runtime/test/frame_pacer_test.cpp
+++ b/runtime/test/frame_pacer_test.cpp
@@ -38,6 +38,23 @@ bool blocked(std::future<Result>& f) {
38 return f.wait_for(std::chrono::milliseconds(40)) == std::future_status::timeout; 38 return f.wait_for(std::chrono::milliseconds(40)) == std::future_status::timeout;
39} 39}
40 40
41// True when the wait has returned; otherwise the pacer is suspended, which lets the waiter go, so that a failure ends
42// the test instead of hanging it on the fake clock.
43bool finishes(std::future<Result>& f, FramePacer& pacer) {
44 if (f.wait_for(std::chrono::seconds(10)) == std::future_status::ready) return true;
45 pacer.suspend();
46 return false;
47}
48
49// Display time of `token`'s frame, or no_deadline when the pacer has none (not shown, or replaced and never shown).
50std::uint64_t display_time(FramePacer& pacer, std::uint64_t token) {
51 std::uint32_t count = 1;
52 FrameStatistic stat{};
53 if (pacer.get_frame_statistics(token, stat_display, &count, &stat) != pacer_hr::ok || count != 1)
54 return no_deadline;
55 return stat.time_us;
56}
57
41bool setup(FramePacer& pacer, std::uint32_t latency, std::uint32_t offset = 0) { 58bool setup(FramePacer& pacer, std::uint32_t latency, std::uint32_t offset = 0) {
42 return pacer.set_frame_interval(period, latency, 0) == pacer_hr::ok && 59 return pacer.set_frame_interval(period, latency, 0) == pacer_hr::ok &&
43 pacer.schedule_frame_event(frame_event_origin, offset, 0) == pacer_hr::ok; 60 pacer.schedule_frame_event(frame_event_origin, offset, 0) == pacer_hr::ok;
@@ -254,6 +271,94 @@ int main() {
254 EXPECT(pacer.frames_in_flight() == 1); 271 EXPECT(pacer.frames_in_flight() == 1);
255 } 272 }
256 273
274 // Presents beyond the latency while the event is armed (several presents per wait): at most `latency` frames are
275 // in flight. A present into a full queue replaces the newest queued frame (mailbox) and the older ones keep their
276 // vblanks, so the next wait passes when the oldest is shown, within one period and not 999. Latency 1, 2 and 3.
277 for (std::uint32_t latency = 1; latency <= 3; ++latency) {
278 ManualFrameClock clock;
279 FramePacer pacer(clock);
280 EXPECT(setup(pacer, latency));
281 clock.advance_us(period); // origin 1
282 std::uint64_t token = 0;
283 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &token) == pacer_hr::ok && token == 1);
284
285 // 1000 blank presents with no wait between them: they queue for vblanks 2 .. latency + 1, and no further.
286 for (int i = 0; i < 1000; ++i) pacer.note_untokened_present();
287 EXPECT(pacer.frames_in_flight() == latency);
288 auto wait = wait_async(pacer, infinite_timeout_ms);
289 EXPECT(blocked(wait));
290 clock.advance_us(period); // vblank 2 shows the oldest: the wait passes with origin 2, not 999 periods later
291 EXPECT(finishes(wait, pacer));
292 Result r = wait.get();
293 EXPECT(r.hr == pacer_hr::ok && r.token == 2);
294 EXPECT(pacer.frames_in_flight() == latency - 1);
295 clock.advance_us(std::uint64_t(period) * (latency - 1)); // vblank latency + 1 shows the newest
296 EXPECT(pacer.frames_in_flight() == 0);
297
298 // Tokened frames: latency + 1 tokens handed out with nothing in flight, then all presented at once.
299 std::uint64_t tokens[4] = {};
300 for (std::uint32_t i = 0; i <= latency; ++i) {
301 clock.advance_us(period);
302 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tokens[i]) == pacer_hr::ok);
303 EXPECT(tokens[i] == 3 + i);
304 }
305 const std::uint64_t now = std::uint64_t(period) * (2 * latency + 2);
306 for (std::uint32_t i = 0; i < latency; ++i) { // `latency` presents fill the queue: nothing is replaced
307 EXPECT(pacer.check_present_token(tokens[i]) == pacer_hr::ok);
308 pacer.commit_present_token(tokens[i], 1);
309 }
310 EXPECT(pacer.frames_in_flight() == latency);
311 pacer.commit_present_token(tokens[latency], 1); // replaces the newest queued frame and takes its vblank
312 EXPECT(pacer.frames_in_flight() == latency);
313 wait = wait_async(pacer, infinite_timeout_ms);
314 EXPECT(blocked(wait));
315 clock.advance_us(period);
316 EXPECT(finishes(wait, pacer));
317 r = wait.get();
318 EXPECT(r.hr == pacer_hr::ok && r.token == latency + 4);
319 clock.advance_us(std::uint64_t(period) * (latency - 1));
320 EXPECT(pacer.frames_in_flight() == 0);
321 for (std::uint32_t i = 0; i + 1 < latency; ++i) // the older frames keep their vblanks
322 EXPECT(display_time(pacer, tokens[i]) == now + std::uint64_t(period) * (i + 1));
323 EXPECT(display_time(pacer, tokens[latency - 1]) == no_deadline); // replaced: never shown
324 EXPECT(display_time(pacer, tokens[latency]) == now + std::uint64_t(period) * latency);
325
326 // One present per wait, each a quarter period after its origin: nothing is replaced, each frame is shown at the
327 // vblank after its origin, and that vblank is the next origin.
328 token = r.token;
329 clock.advance_us(period); // back on an origin
330 for (int frame = 0; frame < 8; ++frame) {
331 const std::uint64_t origin = clock.now_us();
332 std::uint64_t next = 0;
333 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &next) == pacer_hr::ok && next == token + 1);
334 token = next;
335 clock.advance_us(period / 4);
336 pacer.commit_present_token(token, 1);
337 EXPECT(pacer.frames_in_flight() == 1);
338 clock.advance_us(period - period / 4);
339 EXPECT(pacer.frames_in_flight() == 0);
340 EXPECT(display_time(pacer, token) == origin + period);
341 }
342 }
343
344 // SetFrameIntervalX lowering the latency below the frames already queued: the next present cuts the queue back
345 // to the new latency from the newest end, and the oldest frame keeps its vblank.
346 {
347 ManualFrameClock clock;
348 FramePacer pacer(clock);
349 EXPECT(setup(pacer, 3));
350 for (int i = 0; i < 3; ++i) pacer.note_untokened_present(); // vblanks 1, 2 and 3
351 EXPECT(pacer.frames_in_flight() == 3);
352 EXPECT(pacer.set_frame_interval(period, 1, 0) == pacer_hr::ok);
353 EXPECT(pacer.frames_in_flight() == 3); // already queued: left alone until the next present
354 pacer.note_untokened_present();
355 EXPECT(pacer.frames_in_flight() == 1);
356 clock.advance_us(period - 1);
357 EXPECT(pacer.frames_in_flight() == 1);
358 clock.advance_us(1); // vblank 1, the oldest frame's
359 EXPECT(pacer.frames_in_flight() == 0);
360 }
361
257 // Tokens: only one that was never handed out is refused. Null, stale and repeated ones are accepted and reported 362 // Tokens: only one that was never handed out is refused. Null, stale and repeated ones are accepted and reported
258 // as such, so a title that presents with Token = 0, twice with one token, or out of order does not freeze. 363 // as such, so a title that presents with Token = 0, twice with one token, or out of order does not freeze.
259 { 364 {
@@ -777,6 +882,44 @@ int main() {
777 EXPECT(uncap.target_interval_us == 0 && near(uncap.drift_us, 0.0) && uncap.p50_us == period); 882 EXPECT(uncap.target_interval_us == 0 && near(uncap.drift_us, 0.0) && uncap.p50_us == period);
778 } 883 }
779 884
885 // BL-6 with the bounded queue: the statistics are of PresentX calls, so a frame replaced in a full queue (never
886 // shown) still counts as a present, with its real present-to-present interval; the replacement adds no interval,
887 // removes none, and the frames that are shown keep their vblanks. Latency 1, so every extra present replaces.
888 {
889 auto near = [](double a, double b) { return (a > b ? a - b : b - a) < 1e-6; };
890 ManualFrameClock clock;
891 FramePacer pacer(clock);
892 EXPECT(setup(pacer, 1));
893 clock.advance_us(period); // origin 1
894 std::uint64_t tok1 = 0;
895 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tok1) == pacer_hr::ok && tok1 == 1);
896 clock.advance_us(1000);
897 pacer.commit_present_token(tok1, 1); // latency 1000; queued for vblank 2
898 clock.advance_us(2000);
899 pacer.note_untokened_present(); // interval 2000; replaces tok1 and takes vblank 2
900 clock.advance_us(4000);
901 pacer.note_untokened_present(); // interval 4000; replaces the blank frame
902 EXPECT(pacer.frames_in_flight() == 1);
903 clock.advance_us(period - 7000); // vblank 2, origin 2
904 EXPECT(pacer.frames_in_flight() == 0);
905 EXPECT(display_time(pacer, tok1) == no_deadline); // replaced: never shown
906 std::uint64_t tok2 = 0;
907 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tok2) == pacer_hr::ok && tok2 == 2);
908 clock.advance_us(8000);
909 pacer.commit_present_token(tok2, 1); // interval period + 1000; latency 8000; vblank 3
910 clock.advance_us(period - 8000);
911 EXPECT(display_time(pacer, tok2) == 3 * std::uint64_t(period));
912
913 // 4 presents (2 of them replaced), 3 intervals {2000, 4000, 17000}: nearest-rank p50 4000, p95 and p99 17000.
914 const FramePacingSummary s = pacer.pacing_summary();
915 EXPECT(s.frames == 4 && s.samples == 3 && s.target_interval_us == period);
916 EXPECT(near(s.mean_us, (2000.0 + 4000.0 + period + 1000.0) / 3.0));
917 EXPECT(near(s.drift_us, s.mean_us - double(period)));
918 EXPECT(s.p50_us == 4000 && s.p95_us == period + 1000 && s.p99_us == period + 1000);
919 // Origin-to-present latencies of the tokened presents, the replaced tok1 included: {1000, 8000}.
920 EXPECT(s.latency_samples == 2 && s.latency_p50_us == 1000 && s.latency_p99_us == 8000);
921 }
922
780 std::printf("frame_pacer_test: all cases pass\n"); 923 std::printf("frame_pacer_test: all cases pass\n");
781 return 0; 924 return 0;
782} 925}
diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp
index b6658f51c..be9dc5398 100644
--- a/runtime/test/gameinput_test.cpp
+++ b/runtime/test/gameinput_test.cpp
@@ -1742,8 +1742,15 @@ int main(int argc, char** argv) {
1742 Sleep(350); 1742 Sleep(350);
1743 g_focus = true; 1743 g_focus = true;
1744 rt::gameinput::poll(); 1744 rt::gameinput::poll();
1745 // A scripted press lasts its 300 ms and then until the title has read the pads six times since it began
1746 // (update_keyboard_pad: kReads, at most kMaxHold seconds), so a title that polls slowly still sees it. Each
1747 // pad_state() is one GetCurrentReading, and this is the third since the X began.
1748 check(pad_state(input, nullptr).buttons == (GameInputGamepadX | GameInputGamepadB),
1749 "long script: past its 300 ms the press is still held while the title has read the pads fewer than six times");
1750 for (int i = 0; i < 6; ++i) pad_state(input, nullptr);
1751 rt::gameinput::poll();
1745 check(pad_state(input, nullptr).buttons == GameInputGamepadB, 1752 check(pad_state(input, nullptr).buttons == GameInputGamepadB,
1746 "long script: the timed press ends while the physical key stays held"); 1753 "long script: the timed press ends once the title has read it, while the physical key stays held");
1747 input->Release(); 1754 input->Release();
1748 std::printf("%d checks, %d failures\n", g_checks, g_failures); 1755 std::printf("%d checks, %d failures\n", g_checks, g_failures);
1749 return g_failures ? 1 : 0; 1756 return g_failures ? 1 : 0;
diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp
index 920283f41..caac93dc0 100644
--- a/runtime/test/geometry_views_test.cpp
+++ b/runtime/test/geometry_views_test.cpp
@@ -4,16 +4,31 @@
4// 1. a new view is copied whole; 4// 1. a new view is copied whole;
5// 2. a write into one tile of a 1 MiB view (16 tiles) copies that tile's 64 KiB again, not the view; 5// 2. a write into one tile of a 1 MiB view (16 tiles) copies that tile's 64 KiB again, not the view;
6// 3. a write into a tile two views share is read once and copied into both; 6// 3. a write into a tile two views share is read once and copied into both;
7// 4. two written tiles of one view are two tile copies (LEONIDA_GEOMETRY_WHOLE_VIEWS=1, whole views, fails 2-4). 7// 4. two written tiles of one view are two tile copies (LEONIDA_GEOMETRY_WHOLE_VIEWS=1, whole views, fails 2-4);
8// 5. a small cap refuses past its budget without re-trying while nothing changed;
9// 6. retiring a range defers freeing until its GPU ticket completes, then returns budget and lets refused ranges retry;
10// 7. releasing every view in a sub-4 MiB block via geometry_writes::note_released destroys the block and frees its budget;
11// 8. note_released ignores ranges outside the watched tile bounds and queues ranges inside them;
12// 9. overflowing the release queue (65537 disjoint ranges) collapses to one covering range and retires covered views;
13// 10. reaping the last view in a standard 4 MiB block keeps it as a spare and the next view reuses it;
14// 11. under a cap, an unfitting 4 MiB spare is destroyed so a larger request can succeed (or fail if still over cap);
15// 12. one note_released reaches every GeometryViews instance, and a destroyed instance unsubscribes cleanly;
16// 13. a submission's sequence on an idle GPU (completed == submitted): a view retired by the drain in before_execute_
17// (kAfterExecutes) is freed only after every replay begun before the retirement recorded its submissions and those
18// completed (a ticket read in the drain reaps it at once); its answers made without an alias are invalidated
19// (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device.
8#include <windows.h> 20#include <windows.h>
9 21
10#include <cstdint> 22#include <cstdint>
11#include <cstdio> 23#include <cstdio>
12#include <cstdlib> 24#include <cstdlib>
13#include <cstring> 25#include <cstring>
26#include <utility>
27#include <memory>
14#include <vector> 28#include <vector>
15 29
16#include "../shims/d3d12_geometry_views.h" 30#include "../shims/d3d12_geometry_views.h"
31#include "../src/title_va_alias.h"
17 32
18namespace { 33namespace {
19 34
@@ -27,6 +42,10 @@ void check(bool condition, const char* what) {
27} 42}
28 43
29// The Vulkan calls TitleBufferWindows::allocate makes, over host memory. 44// The Vulkan calls TitleBufferWindows::allocate makes, over host memory.
45int g_live_buffers = 0;
46int g_gone_blocks = 0; // FakeDevice::title_block_gone calls
47int g_live_allocs = 0;
48int g_total_allocs = 0;
30struct FakeBuffer { 49struct FakeBuffer {
31 VkDeviceSize size = 0; 50 VkDeviceSize size = 0;
32 void* memory = nullptr; 51 void* memory = nullptr;
@@ -34,6 +53,7 @@ struct FakeBuffer {
34VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*, 53VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*,
35 VkBuffer* out) { 54 VkBuffer* out) {
36 auto* b = new FakeBuffer{info->size}; 55 auto* b = new FakeBuffer{info->size};
56 ++g_live_buffers;
37 *out = reinterpret_cast<VkBuffer>(b); 57 *out = reinterpret_cast<VkBuffer>(b);
38 return VK_SUCCESS; 58 return VK_SUCCESS;
39} 59}
@@ -57,9 +77,11 @@ VKAPI_ATTR VkDeviceAddress VKAPI_CALL address(VkDevice, const VkBufferDeviceAddr
57 return VkDeviceAddress(reinterpret_cast<std::uintptr_t>(reinterpret_cast<FakeBuffer*>(info->buffer)->memory)); 77 return VkDeviceAddress(reinterpret_cast<std::uintptr_t>(reinterpret_cast<FakeBuffer*>(info->buffer)->memory));
58} 78}
59VKAPI_ATTR void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks*) { 79VKAPI_ATTR void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks*) {
80 --g_live_buffers;
60 delete reinterpret_cast<FakeBuffer*>(buffer); 81 delete reinterpret_cast<FakeBuffer*>(buffer);
61} 82}
62VKAPI_ATTR void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks*) { 83VKAPI_ATTR void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks*) {
84 --g_live_allocs;
63 VirtualFree(memory, 0, MEM_RELEASE); 85 VirtualFree(memory, 0, MEM_RELEASE);
64} 86}
65 87
@@ -85,10 +107,16 @@ struct FakeDevice {
85 VkDeviceAddress address = 0; 107 VkDeviceAddress address = 0;
86 } arena; 108 } arena;
87 void share(VkBufferCreateInfo&) {} 109 void share(VkBufferCreateInfo&) {}
110 void title_block_gone(VkDeviceAddress, VkDeviceSize) { ++g_gone_blocks; }
88 VkDeviceMemory allocate(const VkMemoryRequirements& r, VkMemoryPropertyFlags required, 111 VkDeviceMemory allocate(const VkMemoryRequirements& r, VkMemoryPropertyFlags required,
89 VkMemoryPropertyFlags preferred, VkMemoryPropertyFlags* chosen, bool) { 112 VkMemoryPropertyFlags preferred, VkMemoryPropertyFlags* chosen, bool) {
90 if (chosen) *chosen = required | preferred; 113 if (chosen) *chosen = required | preferred;
91 return reinterpret_cast<VkDeviceMemory>(VirtualAlloc(nullptr, r.size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); 114 void* mem = VirtualAlloc(nullptr, r.size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
115 if (mem) {
116 ++g_live_allocs;
117 ++g_total_allocs;
118 }
119 return reinterpret_cast<VkDeviceMemory>(mem);
92 } 120 }
93}; 121};
94 122
@@ -118,7 +146,8 @@ int main() {
118 const auto base = reinterpret_cast<std::uintptr_t>(title); 146 const auto base = reinterpret_cast<std::uintptr_t>(title);
119 147
120 FakeDevice device; 148 FakeDevice device;
121 rt::d3d12::GeometryViews views; 149 const auto views_owner = std::make_unique<rt::d3d12::GeometryViews>();
150 auto& views = *views_owner;
122 g_copies.clear(); 151 g_copies.clear();
123 const std::uint64_t va = views.resolve(device, base, kView, copy); 152 const std::uint64_t va = views.resolve(device, base, kView, copy);
124 check(va != 0 && g_copies.size() == 1 && g_copies[0] == kView, "a new 1 MiB view is copied whole"); 153 check(va != 0 && g_copies.size() == 1 && g_copies[0] == kView, "a new 1 MiB view is copied whole");
@@ -161,6 +190,326 @@ int main() {
161 check(!std::memcmp(copy_bytes, title, kView), "the copy matches the title's pages"); 190 check(!std::memcmp(copy_bytes, title, kView), "the copy matches the title's pages");
162 191
163 views.release(device); 192 views.release(device);
193 VirtualFree(title, 0, MEM_RELEASE);
194
195 // 5-7. Small cap (2 MiB): fill, cap refusal (cached while nothing freed), deferred retirement for in-flight GPU
196 // work, retry after reap, and full block reclamation via geometry_writes::note_released.
197 auto* small_title =
198 static_cast<std::uint8_t*>(VirtualAlloc(nullptr, 3 * kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
199 if (!small_title) return 1;
200 for (std::size_t i = 0; i < 3 * kView; ++i) small_title[i] = std::uint8_t((i * 13) ^ 0x5a);
201 const auto sbase = reinterpret_cast<std::uintptr_t>(small_title);
202 const auto range_a = sbase;
203 const auto range_b = sbase + kView;
204 const auto range_c = sbase + 2 * kView;
205
206 const auto capped_owner = std::make_unique<rt::d3d12::GeometryViews>(2 * kView);
207
208 auto& capped = *capped_owner;
209 const std::uint64_t va_a = capped.resolve(device, range_a, kView, copy);
210 const std::uint64_t va_b = capped.resolve(device, range_b, kView, copy);
211 check(va_a != 0 && va_b != 0 && capped.bytes() == 2 * kView && capped.reserved() == 2 * kView &&
212 capped.live_views() == 2,
213 "small cap fills to its 2 MiB budget");
214
215 // 5. Third 1 MiB view is refused; a repeat resolve without freeing short-circuits without re-counting a refusal.
216 const std::uint64_t va_c1 = capped.resolve(device, range_c, kView, copy);
217 check(va_c1 == 0 && capped.cap_refusals() == 1, "view past the 2 MiB cap is refused");
218 const std::uint64_t va_c2 = capped.resolve(device, range_c, kView, copy);
219 check(va_c2 == 0 && capped.cap_refusals() == 1,
220 "repeated resolve of a refused range short-circuits while nothing has been freed");
221
222 // 6. Retire A while GPU ticket 5 is still in flight: A disappears from lookup/find immediately, but its storage
223 // and budget are held until completed_ticket reaches 5.
224 std::uint64_t alias_removed_source = 0;
225 VkDeviceSize alias_removed_va = 0;
226 const std::size_t retired_a = capped.retire_range(
227 range_a, range_a + kView, 5, [&](std::uintptr_t src, std::size_t, VkDeviceSize v) {
228 alias_removed_source = src;
229 alias_removed_va = v;
230 });
231 check(retired_a == 1 && alias_removed_source == range_a && alias_removed_va == va_a,
232 "retiring A's range reports A's view and invokes the alias-removal callback");
233 std::uint64_t lookup_host = 0, lookup_bytes = 0;
234 check(capped.find(range_a, kView) == 0 && !capped.lookup(device.arena.address + va_a, lookup_host, lookup_bytes) &&
235 capped.live_views() == 1 && capped.retired_count() == 1,
236 "retired view is immediately unlinked from find and lookup");
237
238 check(capped.reap(device, 4) == 0 && capped.retired_count() == 1 && capped.bytes() == 2 * kView &&
239 capped.free_generation() == 0 && g_live_buffers == 1 && g_live_allocs == 1,
240 "reap before GPU ticket completes does not free an in-use view");
241 check(capped.resolve(device, range_c, kView, copy) == 0 && capped.cap_refusals() == 1,
242 "refused range stays refused while retired view is still in flight");
243
244 // GPU completes ticket 5: A's sub-range is reclaimed and free_generation bumps, letting C retry and succeed.
245 check(capped.reap(device, 5) == 1 && capped.retired_count() == 0 && capped.bytes() == kView &&
246 capped.free_generation() == 1 && capped.block_count() == 1,
247 "reap at GPU ticket 5 reclaims A's budget while keeping B's block live");
248 const std::uint64_t va_c3 = capped.resolve(device, range_c, kView, copy);
249 check(va_c3 != 0 && capped.bytes() == 2 * kView && capped.live_views() == 2,
250 "previously refused range retries and succeeds after budget is freed");
251 check(capped.lookup(device.arena.address + va_c3, lookup_host, lookup_bytes) && lookup_bytes == kView &&
252 !std::memcmp(reinterpret_cast<const void*>(lookup_host), small_title + 2 * kView, kView),
253 "retried view holds C's title bytes");
254
255 // 7. Release B and C via the xmem notification bridge (geometry_writes::note_released + drain_released):
256 // once their GPU ticket completes, the block becomes empty and its Vulkan buffer and memory are destroyed.
257 leonida::geometry_writes::note_released(range_b, range_c + kView);
258 check(capped.has_released(), "note_released queues released title ranges");
259 capped.drain_released(device, 6, 5);
260 check(!capped.has_released() && capped.live_views() == 0 && capped.retired_count() == 2 &&
261 g_live_buffers == 1 && g_live_allocs == 1,
262 "drain_released retires B and C at ticket 6 and defers freeing while completed ticket is 5");
263 check(capped.reap(device, 6) == 2 && capped.retired_count() == 0 && capped.bytes() == 0 &&
264 capped.reserved() == 0 && capped.block_count() == 0 && g_live_buffers == 0 && g_live_allocs == 0,
265 "reaping the last views in a block destroys its Vulkan buffer and returns all reserved budget");
266
267 // A fresh 2 MiB view now fits in the fully reclaimed cap.
268 const std::uint64_t va_full = capped.resolve(device, range_a, 2 * kView, copy);
269 check(va_full != 0 && capped.bytes() == 2 * kView && capped.reserved() == 2 * kView && capped.live_views() == 1,
270 "a fresh 2 MiB view succeeds after full reclamation");
271
272 capped.release(device);
273 check(g_live_buffers == 0 && g_live_allocs == 0, "teardown frees all remaining Vulkan buffers and memory");
274 VirtualFree(small_title, 0, MEM_RELEASE);
275
276 // 8-11. Watched-bounds filtering, release-queue overflow collapse, 4 MiB spare block reuse and cap eviction.
277 auto* pool_title =
278 static_cast<std::uint8_t*>(VirtualAlloc(nullptr, 6 * kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
279 if (!pool_title) return 1;
280 for (std::size_t i = 0; i < 6 * kView; ++i) pool_title[i] = std::uint8_t((i * 17) ^ 0x3c);
281 const auto pbase = reinterpret_cast<std::uintptr_t>(pool_title);
282
283 // 8. note_released outside [watched_lo, watched_hi) is ignored; inside is queued.
284 const auto watched_owner = std::make_unique<rt::d3d12::GeometryViews>(6 * kView);
285 auto& watched = *watched_owner;
286 const std::uint64_t va_w1 = watched.resolve(device, pbase, kView, copy);
287 const std::uint64_t va_w2 = watched.resolve(device, pbase + kView, kView, copy);
288 check(va_w1 != 0 && va_w2 != 0 && watched.live_views() == 2 && watched.block_count() == 1 &&
289 watched.empty_blocks() == 0,
290 "two 1 MiB views share one 4 MiB block");
291 const auto watched_lo = leonida::geometry_writes::state().watched_lo.load(std::memory_order_acquire);
292 const auto watched_hi = leonida::geometry_writes::state().watched_hi.load(std::memory_order_acquire);
293 check(watched_lo <= pbase && watched_hi >= pbase + 2 * kView, "watched bounds cover resolved views");
294 leonida::geometry_writes::note_released(watched_lo - 4096, watched_lo);
295 leonida::geometry_writes::note_released(watched_hi, watched_hi + 4096);
296 check(!watched.has_released(), "note_released outside watched bounds is not queued");
297 leonida::geometry_writes::note_released(pbase, pbase + 4096);
298 check(watched.has_released(), "note_released inside watched bounds is queued");
299 std::vector<std::pair<std::uintptr_t, std::uintptr_t>> drained;
300 leonida::geometry_writes::take_released(watched.release_queue(), drained);
301 check(drained.size() == 1 && drained[0].first == pbase && drained[0].second == pbase + 4096 &&
302 !watched.has_released(),
303 "take_released returns the queued in-bounds range");
304 // A GPU-only twin freed by its own address lies outside the watched (CPU) bounds but still counts: its CPU view
305 // holds the views. Only the address arithmetic of the pair is used; nothing is mapped at the GPU address.
306 const std::uintptr_t gpu_twin = std::uintptr_t(0x600000000000ull);
307 leonida::title_gpu_views::note_reservation(pbase, 2 * kView, false);
308 check(leonida::title_gpu_views::note_reservation(gpu_twin, 2 * kView, true), "the GPU-only twin pairs");
309 leonida::geometry_writes::note_released(gpu_twin + 2 * kView, gpu_twin + 2 * kView + 4096);
310 check(!watched.has_released(), "a range past the twin is not queued");
311 leonida::geometry_writes::note_released(gpu_twin + kView, gpu_twin + kView + 4096);
312 check(watched.has_released(), "a range of the GPU-only twin over a watched view is queued");
313 watched.drain_released(device, 3, 0);
314 check(watched.live_views() == 1 && watched.retired_count() == 1 && watched.find(pbase + kView, kView) == 0 &&
315 watched.find(pbase, kView) == va_w1,
316 "draining the twin's range retires the view at its CPU address only");
317 const std::uint64_t va_w2b = watched.resolve(device, pbase + kView, kView, copy);
318 check(va_w2b != 0, "the retired view is made again on the next resolve");
319
320 // 9. Queue overflow: 65537 disjoint ranges collapse into one covering range; drain retires every covered view.
321 constexpr std::size_t kOverflowCount = 65537;
322 for (std::size_t i = 0; i < kOverflowCount; ++i)
323 leonida::geometry_writes::note_released(pbase + i * 16, pbase + i * 16 + 8);
324 leonida::geometry_writes::take_released(watched.release_queue(), drained);
325 check(drained.size() == 1 && drained[0].first == pbase &&
326 drained[0].second == pbase + (kOverflowCount - 1) * 16 + 8 && !watched.has_released(),
327 "65537 disjoint ranges collapse into a single covering range");
328 for (std::size_t i = 0; i < kOverflowCount; ++i)
329 leonida::geometry_writes::note_released(pbase + i * 16, pbase + i * 16 + 8);
330 watched.drain_released(device, 10, 9);
331 check(!watched.has_released() && watched.live_views() == 0 && watched.retired_count() == 2,
332 "drain_released after overflow retires every view inside the collapsed range");
333 watched.release(device);
334 check(g_live_buffers == 0 && g_live_allocs == 0, "watched teardown frees its block");
335
336 // 10. Spare 4 MiB block: retiring and reaping the sole view keeps the block empty and the next view reuses it.
337 const auto spare_owner = std::make_unique<rt::d3d12::GeometryViews>(6 * kView);
338 auto& spare = *spare_owner;
339 const std::uint64_t va_s1 = spare.resolve(device, pbase, kView, copy);
340 const int allocs_after_first = g_total_allocs;
341 check(va_s1 != 0 && spare.block_count() == 1 && spare.empty_blocks() == 0 && spare.reserved() == 4 * kView &&
342 g_live_buffers == 1 && g_live_allocs == 1,
343 "first view under a 6 MiB cap allocates one standard 4 MiB block");
344 check(spare.retire_range(pbase + kView - 16, pbase + kView, 1) == 1 && spare.reap(device, 1) == 1,
345 "retiring a tail subrange and reaping frees the view");
346 check(spare.live_views() == 0 && spare.block_count() == 1 && spare.empty_blocks() == 1 &&
347 spare.reserved() == 4 * kView && g_live_buffers == 1 && g_live_allocs == 1,
348 "reaping the last view keeps the empty 4 MiB block as a spare");
349 const std::uint64_t va_s2 = spare.resolve(device, pbase + kView, kView, copy);
350 check(va_s2 != 0 && spare.block_count() == 1 && spare.empty_blocks() == 0 && g_live_buffers == 1 &&
351 g_live_allocs == 1 && g_total_allocs == allocs_after_first,
352 "a new view reuses the spare 4 MiB block with no new allocation");
353
354 // 11. Spare given up under the cap: destroy the unfitting 4 MiB spare so a larger request succeeds, and still
355 // refuse a request that remains over the cap after the spare is destroyed.
356 check(spare.retire_range(pbase + kView, pbase + 2 * kView, 2) == 1 && spare.reap(device, 2) == 1 &&
357 spare.block_count() == 1 && spare.empty_blocks() == 1 && spare.reserved() == 4 * kView,
358 "reaping the reused view returns the 4 MiB block to spare");
359 const std::uint64_t va_big = spare.resolve(device, pbase, 5 * kView, copy);
360 check(va_big != 0 && spare.block_count() == 1 && spare.empty_blocks() == 0 && spare.reserved() == 5 * kView &&
361 g_live_buffers == 1 && g_live_allocs == 1,
362 "a 5 MiB request under a 6 MiB cap destroys the 4 MiB spare and succeeds");
363 spare.release(device);
364 check(g_live_buffers == 0 && g_live_allocs == 0, "spare teardown frees its block");
365
366 const auto tight_owner = std::make_unique<rt::d3d12::GeometryViews>(9 * kView);
367
368 auto& tight = *tight_owner;
369 const std::uint64_t va_t1 = tight.resolve(device, pbase, 3 * kView, copy);
370 const std::uint64_t va_t2 = tight.resolve(device, pbase + 3 * kView, 2 * kView, copy);
371 check(va_t1 != 0 && va_t2 != 0 && tight.block_count() == 2 && tight.reserved() == 8 * kView,
372 "two views that do not share one 4 MiB block reserve 8 MiB");
373 check(tight.retire_range(pbase + 3 * kView, pbase + 5 * kView, 1) == 1 && tight.reap(device, 1) == 1 &&
374 tight.block_count() == 2 && tight.empty_blocks() == 1 && tight.reserved() == 8 * kView,
375 "reaping the second block leaves one 4 MiB spare alongside one live 4 MiB block");
376 const std::uint64_t va_over = tight.resolve(device, pbase, 6 * kView, copy);
377 check(va_over == 0 && tight.cap_refusals() == 1 && tight.block_count() == 1 && tight.empty_blocks() == 0 &&
378 tight.reserved() == 4 * kView && g_live_buffers == 1 && g_live_allocs == 1,
379 "a 6 MiB request drops the 4 MiB spare and is refused because only 5 MiB of cap remain");
380 const std::uint64_t va_fit = tight.resolve(device, pbase, 5 * kView, copy);
381 check(va_fit != 0 && tight.block_count() == 2 && tight.reserved() == 9 * kView && g_live_buffers == 2 &&
382 g_live_allocs == 2,
383 "a 5 MiB request succeeds in the cap freed by dropping the spare");
384 tight.release(device);
385 check(g_live_buffers == 0 && g_live_allocs == 0, "tight cap teardown frees all blocks");
386
387 VirtualFree(pool_title, 0, MEM_RELEASE);
388
389 // 12. Two GeometryViews instances over the same title extent both receive one note_released; a destroyed instance
390 // unsubscribes so later releases do not touch it and surviving instances still receive them.
391 auto* shared_title =
392 static_cast<std::uint8_t*>(VirtualAlloc(nullptr, 2 * kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
393 if (!shared_title) return 1;
394 for (std::size_t i = 0; i < 2 * kView; ++i) shared_title[i] = std::uint8_t((i * 29) ^ 0xa5);
395 const auto shbase = reinterpret_cast<std::uintptr_t>(shared_title);
396
397 {
398 const auto dev_a_owner = std::make_unique<rt::d3d12::GeometryViews>(2 * kView);
399 auto& dev_a = *dev_a_owner;
400 const auto dev_b_owner = std::make_unique<rt::d3d12::GeometryViews>(2 * kView);
401 auto& dev_b = *dev_b_owner;
402 const std::uint64_t va_a1 = dev_a.resolve(device, shbase, kView, copy);
403 const std::uint64_t va_b1 = dev_b.resolve(device, shbase, kView, copy);
404 check(va_a1 != 0 && va_b1 != 0 && dev_a.live_views() == 1 && dev_b.live_views() == 1 &&
405 dev_a.bytes() == kView && dev_b.bytes() == kView,
406 "two GeometryViews instances resolve the same title range");
407
408 leonida::geometry_writes::note_released(shbase, shbase + kView);
409 check(dev_a.has_released() && dev_b.has_released(),
410 "one note_released queues the range in both instances");
411
412 dev_a.drain_released(device, 1, 1);
413 check(!dev_a.has_released() && dev_a.live_views() == 0 && dev_a.retired_count() == 0 && dev_a.bytes() == 0 &&
414 dev_b.has_released() && dev_b.live_views() == 1 && dev_b.bytes() == kView,
415 "draining the first instance retires and reaps its view without emptying the second instance's queue");
416
417 dev_b.drain_released(device, 1, 1);
418 check(!dev_b.has_released() && dev_b.live_views() == 0 && dev_b.retired_count() == 0 && dev_b.bytes() == 0,
419 "draining the second instance also retires and reaps its view");
420
421 const std::uint64_t va_keep = dev_a.resolve(device, shbase + kView, kView, copy);
422 check(va_keep != 0 && dev_a.live_views() == 1 && dev_a.bytes() == kView,
423 "surviving instance resolves a second range");
424 {
425 const auto ephemeral_owner = std::make_unique<rt::d3d12::GeometryViews>(2 * kView);
426 auto& ephemeral = *ephemeral_owner;
427 const std::uint64_t va_eph = ephemeral.resolve(device, shbase + kView, kView, copy);
428 check(va_eph != 0 && ephemeral.live_views() == 1, "scoped instance resolves the same range");
429 ephemeral.release(device);
430 }
431 leonida::geometry_writes::note_released(shbase + kView, shbase + 2 * kView);
432 check(dev_a.has_released(), "note_released after another instance is destroyed reaches the surviving instance");
433 dev_a.drain_released(device, 2, 2);
434 check(!dev_a.has_released() && dev_a.live_views() == 0 && dev_a.retired_count() == 0 && dev_a.bytes() == 0,
435 "surviving instance retires and reaps after the destroyed instance unsubscribed");
436
437 dev_a.release(device);
438 dev_b.release(device);
439 }
440 check(g_live_buffers == 0 && g_live_allocs == 0, "multi-instance teardown frees all blocks");
441 VirtualFree(shared_title, 0, MEM_RELEASE);
442
443 // 13. DeviceState's order for one submission: execute_begin, drain_geometry_releases (kAfterExecutes) and the
444 // console heaps in before_execute_, the replay records its submission, execute_end. Another queue's replay began
445 // before the release (its heap slots may already name the view); one more begins after the retirement.
446 auto* fly_title = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
447 if (!fly_title) return 1;
448 for (std::size_t i = 0; i < kView; ++i) fly_title[i] = std::uint8_t(i * 13 + 1);
449 const auto flybase = reinterpret_cast<std::uintptr_t>(fly_title);
450 {
451 const auto fly_owner = std::make_unique<rt::d3d12::GeometryViews>(2 * kView);
452 auto& fly = *fly_owner;
453 const auto named_blocks = [&] {
454 std::size_t n = 0;
455 fly.pool().for_each_block([&](VkDeviceAddress address, VkDeviceSize) { n += address != 0; });
456 return n;
457 };
458 const std::uint64_t va_f = fly.resolve(device, flybase, kView, copy);
459 check(va_f != 0 && fly.live_views() == 1 && named_blocks() == 1, "a view in its own block, published");
460 const std::uint64_t layout = fly.pool().layout_generation();
461 const int gone = g_gone_blocks;
462
463 std::uint64_t submitted = 7; // completed == submitted below: the GPU is idle
464 const std::uint64_t other = fly.execute_begin();
465 const std::uint64_t own = fly.execute_begin();
466 leonida::TitleVaAliases aliases;
467 aliases.record_removals(true);
468 std::uint64_t cursor = 0;
469 {
470 leonida::DescriptorRanges skip;
471 aliases.changed_ranges(cursor, skip);
472 }
473 const std::uint64_t invalidations = aliases.invalidations();
474 leonida::geometry_writes::note_released(flybase, flybase + kView);
475 fly.drain_released(device, rt::d3d12::GeometryViews::kAfterExecutes, submitted,
476 [&](std::uintptr_t source, std::size_t size, VkDeviceSize va) {
477 aliases.forget_copy(source, size, va);
478 });
479 check(fly.live_views() == 0 && fly.find(flybase, kView) == 0 && fly.retired_count() == 1 &&
480 fly.bytes() == kView && g_gone_blocks == gone,
481 "a view retired in before_execute_ is not reaped there, though the GPU is idle");
482
483 leonida::DescriptorRanges changed;
484 const bool read = aliases.changed_ranges(cursor, changed);
485 changed.merge();
486 std::vector<std::pair<std::uint64_t, std::uint64_t>> removed;
487 aliases.take_removed(removed);
488 check(read && aliases.invalidations() != invalidations && changed.overlaps(flybase, kView) &&
489 removed.size() == 1 && removed[0].first == va_f && removed[0].second == kView,
490 "the retirement invalidates the heap slots and key answers made through the view without an alias");
491
492 submitted = 8; // this replay's submission
493 fly.execute_end(own, [&] { return submitted; });
494 check(fly.reap(device, 8) == 0 && fly.retired_count() == 1 && fly.bytes() == kView,
495 "not freed while a replay begun before the retirement is still in progress");
496
497 const std::uint64_t later = fly.execute_begin();
498 submitted = 9; // the other queue's submission
499 fly.execute_end(other, [&] { return submitted; });
500 check(fly.reap(device, 8) == 0 && fly.retired_count() == 1,
501 "once those replays recorded theirs, the view waits for the last of their tickets");
502 check(fly.reap(device, 9) == 1 && fly.retired_count() == 0 && fly.bytes() == 0,
503 "freed once that ticket completed; a replay begun after the retirement does not hold it");
504 fly.execute_end(later, [&] { return submitted; });
505
506 check(named_blocks() == 0 && fly.pool().layout_generation() != layout && g_gone_blocks == gone + 1 &&
507 g_live_buffers == 0,
508 "the destroyed block leaves the lock-free block list and the device is told");
509 fly.release(device);
510 }
511 VirtualFree(fly_title, 0, MEM_RELEASE);
512
164 std::printf("%d checks, %d failures\n", g_checks, g_failures); 513 std::printf("%d checks, %d failures\n", g_checks, g_failures);
165 return g_failures ? 1 : 0; 514 return g_failures ? 1 : 0;
166} 515}
diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp
index efd0ce4ee..f30d7f026 100644
--- a/runtime/test/gfx10_descriptors_test.cpp
+++ b/runtime/test/gfx10_descriptors_test.cpp
@@ -114,6 +114,25 @@ int main() {
114 CHECK(is_image(words) && decode(words, out) && out == in); 114 CHECK(is_image(words) && decode(words, out) && out == in);
115 } 115 }
116 116
117 ImageWords volume_words = encode(Image{.type = ImageType::image_3d, .depth = 16,
118 .first_mip = 1, .mip_count = 2, .resource_mips = 4});
119 volume_words[4] |= 37u << 16;
120 CHECK(decode(volume_words, image) && image.first_layer == 37 && image.depth == 16);
121 CHECK(!has_hardware_volume_uav_slice_offset(volume_words, image));
122 const auto volume_range = vulkan_subresource_range(image, VK_IMAGE_ASPECT_COLOR_BIT);
123 CHECK(volume_range.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT);
124 CHECK(volume_range.baseMipLevel == 1 && volume_range.levelCount == 2);
125 CHECK(volume_range.baseArrayLayer == 0 && volume_range.layerCount == 1);
126 volume_words = encode(Image{.type = ImageType::image_3d, .depth = 7, .first_mip = 1, .resource_mips = 4});
127 volume_words[4] |= 2u << 16;
128 volume_words[5] |= 1u;
129 CHECK(decode(volume_words, image) && has_hardware_volume_uav_slice_offset(volume_words, image));
130 volume_words[4] &= 0xffffu;
131 CHECK(decode(volume_words, image) && !has_hardware_volume_uav_slice_offset(volume_words, image));
132
133 const auto array_range = vulkan_subresource_range(images[2], VK_IMAGE_ASPECT_COLOR_BIT);
134 CHECK(array_range.baseArrayLayer == 3 && array_range.layerCount == 7);
135
117 // Bits this header does not encode are ignored: SW_MODE and BC_SWIZZLE (word 3), PITCH_MSB (word 4), PERF_MOD 136 // Bits this header does not encode are ignored: SW_MODE and BC_SWIZZLE (word 3), PITCH_MSB (word 4), PERF_MOD
118 // and the rest of word 5, the compression and metadata fields of words 6 and 7, RESOURCE_LEVEL (word 2 bit 31). 137 // and the rest of word 5, the compression and metadata fields of words 6 and 7, RESOURCE_LEVEL (word 2 bit 31).
119 ImageWords busy = encode(images[3]); 138 ImageWords busy = encode(images[3]);
diff --git a/runtime/test/glsl/cs_indirect_dispatch_count.comp b/runtime/test/glsl/cs_indirect_dispatch_count.comp
index 05bc68517..e08053790 100644
--- a/runtime/test/glsl/cs_indirect_dispatch_count.comp
+++ b/runtime/test/glsl/cs_indirect_dispatch_count.comp
@@ -3,6 +3,9 @@
3// which start at s4), plus the 144-byte user-data contract. 3// which start at s4), plus the 144-byte user-data contract.
4#extension GL_EXT_buffer_reference : require 4#extension GL_EXT_buffer_reference : require
5#extension GL_EXT_buffer_reference_uvec2 : require 5#extension GL_EXT_buffer_reference_uvec2 : require
6#ifndef TEST_COUNTER_TERM
7#define TEST_COUNTER_TERM 1u
8#endif
6layout(local_size_x = 1) in; 9layout(local_size_x = 1) in;
7layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; }; 10layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; };
8layout(push_constant) uniform UserData { uint s[32]; uvec2 heap_base; uvec2 code_base; } pc; 11layout(push_constant) uniform UserData { uint s[32]; uvec2 heap_base; uvec2 code_base; } pc;
@@ -14,5 +17,5 @@ uvec2 add64(uvec2 a, uvec2 b) {
14void main() { 17void main() {
15 Words result = Words(add64(pc.heap_base, uvec2(pc.s[4], pc.s[5]))); 18 Words result = Words(add64(pc.heap_base, uvec2(pc.s[4], pc.s[5])));
16 atomicAdd(result.w[0], 1u); 19 atomicAdd(result.w[0], 1u);
17 atomicAdd(result.w[1], gl_WorkGroupID.x + 1u); 20 atomicAdd(result.w[1], gl_WorkGroupID.x + TEST_COUNTER_TERM);
18} 21}
diff --git a/runtime/test/indirect_clamp_safety_test.cpp b/runtime/test/indirect_clamp_safety_test.cpp
new file mode 100644
index 000000000..3a296e91b
--- /dev/null
+++ b/runtime/test/indirect_clamp_safety_test.cpp
@@ -0,0 +1,419 @@
1// Pure-CPU mock-Vulkan tests for runtime/src/vulkan_indirect_clamp.h and runtime/src/vulkan_scratch.h:
2// - multi-queue-family sharing (VK_SHARING_MODE_CONCURRENT) on both scratch chunks and HostArea counter buffers;
3// - freeing VkDeviceMemory before retrying the next memory type when vkBindBufferMemory fails in make_area();
4// - zeroing released counter slots so an aborted/unsubmitted batch never double-counts stale counters;
5// - rejecting non-4-byte-aligned argument_offset and count_offset;
6// - thread-safe concurrent prepare() + release() while areas_ grows (TSan clean).
7// No GPU, Vulkan loader, or game files required.
8#ifndef VK_NO_PROTOTYPES
9#define VK_NO_PROTOTYPES
10#endif
11#include "../src/vulkan_indirect_clamp.h"
12
13#include <atomic>
14#include <cstdint>
15#include <cstdio>
16#include <cstring>
17#include <memory>
18#include <mutex>
19#include <thread>
20#include <unordered_map>
21#include <vector>
22
23#define CHECK(cond) \
24 do { \
25 if (!(cond)) { \
26 std::fprintf(stderr, "line %d: CHECK failed: %s\n", __LINE__, #cond); \
27 return 1; \
28 } \
29 } while (0)
30
31namespace {
32
33struct BufferRecord {
34 VkBufferUsageFlags usage = 0;
35 VkSharingMode sharing_mode = VK_SHARING_MODE_EXCLUSIVE;
36 std::vector<std::uint32_t> families;
37 VkDeviceSize size = 0;
38};
39
40struct MockState {
41 std::mutex mutex;
42 std::uint64_t next_handle = 1;
43 std::uint32_t fail_bind_type = UINT32_MAX;
44 int alloc_memory_calls = 0;
45 int free_memory_calls = 0;
46 int create_buffer_calls = 0;
47 int destroy_buffer_calls = 0;
48 std::unordered_map<std::uintptr_t, BufferRecord> buffers;
49 std::unordered_map<std::uintptr_t, std::uint32_t> mem_types;
50 std::unordered_map<std::uintptr_t, std::unique_ptr<std::uint8_t[]>> host_maps;
51 std::unordered_map<std::uintptr_t, std::uint8_t*> buffer_host;
52};
53
54MockState* g_mock = nullptr;
55
56template <typename Handle>
57Handle make_handle(std::uint64_t id) {
58 return reinterpret_cast<Handle>(static_cast<std::uintptr_t>(id));
59}
60
61VKAPI_ATTR VkResult VKAPI_CALL mock_create_buffer(VkDevice, const VkBufferCreateInfo* info,
62 const VkAllocationCallbacks*, VkBuffer* out) {
63 std::lock_guard lock(g_mock->mutex);
64 ++g_mock->create_buffer_calls;
65 const auto id = ++g_mock->next_handle;
66 BufferRecord rec{};
67 rec.usage = info->usage;
68 rec.sharing_mode = info->sharingMode;
69 rec.size = info->size;
70 if (info->pQueueFamilyIndices && info->queueFamilyIndexCount)
71 rec.families.assign(info->pQueueFamilyIndices, info->pQueueFamilyIndices + info->queueFamilyIndexCount);
72 g_mock->buffers[static_cast<std::uintptr_t>(id)] = std::move(rec);
73 *out = make_handle<VkBuffer>(id);
74 return VK_SUCCESS;
75}
76
77VKAPI_ATTR void VKAPI_CALL mock_destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks*) {
78 std::lock_guard lock(g_mock->mutex);
79 ++g_mock->destroy_buffer_calls;
80 g_mock->buffers.erase(reinterpret_cast<std::uintptr_t>(buffer));
81 g_mock->buffer_host.erase(reinterpret_cast<std::uintptr_t>(buffer));
82}
83
84VKAPI_ATTR void VKAPI_CALL mock_get_buffer_memory_requirements(VkDevice, VkBuffer buffer,
85 VkMemoryRequirements* req) {
86 std::lock_guard lock(g_mock->mutex);
87 const auto it = g_mock->buffers.find(reinterpret_cast<std::uintptr_t>(buffer));
88 req->size = it != g_mock->buffers.end() ? it->second.size : 256;
89 req->alignment = 256;
90 req->memoryTypeBits = 0x3u;
91}
92
93VKAPI_ATTR VkResult VKAPI_CALL mock_allocate_memory(VkDevice, const VkMemoryAllocateInfo* info,
94 const VkAllocationCallbacks*, VkDeviceMemory* out) {
95 std::lock_guard lock(g_mock->mutex);
96 ++g_mock->alloc_memory_calls;
97 const auto id = ++g_mock->next_handle;
98 g_mock->mem_types[static_cast<std::uintptr_t>(id)] = info->memoryTypeIndex;
99 g_mock->host_maps[static_cast<std::uintptr_t>(id)] = std::make_unique<std::uint8_t[]>(size_t(info->allocationSize));
100 std::memset(g_mock->host_maps[static_cast<std::uintptr_t>(id)].get(), 0, size_t(info->allocationSize));
101 *out = make_handle<VkDeviceMemory>(id);
102 return VK_SUCCESS;
103}
104
105VKAPI_ATTR void VKAPI_CALL mock_free_memory(VkDevice, VkDeviceMemory mem, const VkAllocationCallbacks*) {
106 std::lock_guard lock(g_mock->mutex);
107 ++g_mock->free_memory_calls;
108 g_mock->mem_types.erase(reinterpret_cast<std::uintptr_t>(mem));
109 g_mock->host_maps.erase(reinterpret_cast<std::uintptr_t>(mem));
110}
111
112VKAPI_ATTR VkResult VKAPI_CALL mock_bind_buffer_memory(VkDevice, VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize) {
113 std::lock_guard lock(g_mock->mutex);
114 const auto it = g_mock->mem_types.find(reinterpret_cast<std::uintptr_t>(mem));
115 if (it != g_mock->mem_types.end() && it->second == g_mock->fail_bind_type)
116 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
117 const auto mit = g_mock->host_maps.find(reinterpret_cast<std::uintptr_t>(mem));
118 if (mit != g_mock->host_maps.end()) g_mock->buffer_host[reinterpret_cast<std::uintptr_t>(buffer)] = mit->second.get();
119 return VK_SUCCESS;
120}
121
122VKAPI_ATTR VkResult VKAPI_CALL mock_map_memory(VkDevice, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize,
123 VkMemoryMapFlags, void** ppData) {
124 std::lock_guard lock(g_mock->mutex);
125 const auto it = g_mock->host_maps.find(reinterpret_cast<std::uintptr_t>(mem));
126 if (it == g_mock->host_maps.end()) return VK_ERROR_MEMORY_MAP_FAILED;
127 *ppData = it->second.get() + offset;
128 return VK_SUCCESS;
129}
130
131VKAPI_ATTR void VKAPI_CALL mock_unmap_memory(VkDevice, VkDeviceMemory) {}
132
133VKAPI_ATTR VkDeviceAddress VKAPI_CALL mock_get_buffer_device_address(VkDevice, const VkBufferDeviceAddressInfo* info) {
134 return static_cast<VkDeviceAddress>(0x10000000ull + reinterpret_cast<std::uintptr_t>(info->buffer) * 0x1000ull);
135}
136
137VKAPI_ATTR VkResult VKAPI_CALL mock_get_semaphore_counter_value(VkDevice, VkSemaphore, std::uint64_t* value) {
138 *value = UINT64_MAX;
139 return VK_SUCCESS;
140}
141
142VKAPI_ATTR VkResult VKAPI_CALL mock_device_wait_idle(VkDevice) { return VK_SUCCESS; }
143
144VKAPI_ATTR VkResult VKAPI_CALL mock_create_shader_module(VkDevice, const VkShaderModuleCreateInfo*,
145 const VkAllocationCallbacks*, VkShaderModule* out) {
146 std::lock_guard lock(g_mock->mutex);
147 *out = make_handle<VkShaderModule>(++g_mock->next_handle);
148 return VK_SUCCESS;
149}
150VKAPI_ATTR void VKAPI_CALL mock_destroy_shader_module(VkDevice, VkShaderModule, const VkAllocationCallbacks*) {}
151
152VKAPI_ATTR VkResult VKAPI_CALL mock_create_pipeline_layout(VkDevice, const VkPipelineLayoutCreateInfo*,
153 const VkAllocationCallbacks*, VkPipelineLayout* out) {
154 std::lock_guard lock(g_mock->mutex);
155 *out = make_handle<VkPipelineLayout>(++g_mock->next_handle);
156 return VK_SUCCESS;
157}
158VKAPI_ATTR void VKAPI_CALL mock_destroy_pipeline_layout(VkDevice, VkPipelineLayout, const VkAllocationCallbacks*) {}
159
160VKAPI_ATTR VkResult VKAPI_CALL mock_create_compute_pipelines(VkDevice, VkPipelineCache, std::uint32_t,
161 const VkComputePipelineCreateInfo*,
162 const VkAllocationCallbacks*, VkPipeline* out) {
163 std::lock_guard lock(g_mock->mutex);
164 *out = make_handle<VkPipeline>(++g_mock->next_handle);
165 return VK_SUCCESS;
166}
167VKAPI_ATTR void VKAPI_CALL mock_destroy_pipeline(VkDevice, VkPipeline, const VkAllocationCallbacks*) {}
168
169VKAPI_ATTR void VKAPI_CALL mock_cmd_pipeline_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags,
170 VkDependencyFlags, std::uint32_t, const VkMemoryBarrier*,
171 std::uint32_t, const VkBufferMemoryBarrier*, std::uint32_t,
172 const VkImageMemoryBarrier*) {}
173VKAPI_ATTR void VKAPI_CALL mock_cmd_bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}
174VKAPI_ATTR void VKAPI_CALL mock_cmd_push_constants(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t,
175 std::uint32_t, const void*) {}
176VKAPI_ATTR void VKAPI_CALL mock_cmd_dispatch(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) {}
177VKAPI_ATTR void VKAPI_CALL mock_cmd_fill_buffer(VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, std::uint32_t) {}
178VKAPI_ATTR void VKAPI_CALL mock_cmd_copy_buffer(VkCommandBuffer, VkBuffer, VkBuffer, std::uint32_t,
179 const VkBufferCopy*) {}
180
181VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_get_device_proc_addr(VkDevice, const char* name) {
182#define ENTRY(fn_name, impl) \
183 if (std::strcmp(name, #fn_name) == 0) return reinterpret_cast<PFN_vkVoidFunction>(impl)
184 ENTRY(vkCreateBuffer, mock_create_buffer);
185 ENTRY(vkDestroyBuffer, mock_destroy_buffer);
186 ENTRY(vkGetBufferMemoryRequirements, mock_get_buffer_memory_requirements);
187 ENTRY(vkAllocateMemory, mock_allocate_memory);
188 ENTRY(vkFreeMemory, mock_free_memory);
189 ENTRY(vkBindBufferMemory, mock_bind_buffer_memory);
190 ENTRY(vkMapMemory, mock_map_memory);
191 ENTRY(vkUnmapMemory, mock_unmap_memory);
192 ENTRY(vkGetBufferDeviceAddress, mock_get_buffer_device_address);
193 ENTRY(vkGetSemaphoreCounterValue, mock_get_semaphore_counter_value);
194 ENTRY(vkDeviceWaitIdle, mock_device_wait_idle);
195 ENTRY(vkCreateShaderModule, mock_create_shader_module);
196 ENTRY(vkDestroyShaderModule, mock_destroy_shader_module);
197 ENTRY(vkCreatePipelineLayout, mock_create_pipeline_layout);
198 ENTRY(vkDestroyPipelineLayout, mock_destroy_pipeline_layout);
199 ENTRY(vkCreateComputePipelines, mock_create_compute_pipelines);
200 ENTRY(vkDestroyPipeline, mock_destroy_pipeline);
201 ENTRY(vkCmdPipelineBarrier, mock_cmd_pipeline_barrier);
202 ENTRY(vkCmdBindPipeline, mock_cmd_bind_pipeline);
203 ENTRY(vkCmdPushConstants, mock_cmd_push_constants);
204 ENTRY(vkCmdDispatch, mock_cmd_dispatch);
205 ENTRY(vkCmdFillBuffer, mock_cmd_fill_buffer);
206 ENTRY(vkCmdCopyBuffer, mock_cmd_copy_buffer);
207#undef ENTRY
208 return nullptr;
209}
210
211VkPhysicalDeviceMemoryProperties make_memory_props() {
212 VkPhysicalDeviceMemoryProperties mem{};
213 mem.memoryHeapCount = 2;
214 mem.memoryHeaps[0] = {VkDeviceSize(1) << 30, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT};
215 mem.memoryHeaps[1] = {VkDeviceSize(4) << 30, 0};
216 mem.memoryTypeCount = 2;
217 mem.memoryTypes[0] = {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0};
218 mem.memoryTypes[1] = {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 1};
219 return mem;
220}
221
222VkPhysicalDeviceLimits make_limits() {
223 VkPhysicalDeviceLimits limits{};
224 limits.maxComputeWorkGroupCount[0] = 65535u;
225 return limits;
226}
227
228leonida::ScratchBuffers::Allocate make_scratch_allocator() {
229 return [](const VkMemoryRequirements& req) -> VkDeviceMemory {
230 VkMemoryAllocateInfo info{};
231 info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
232 info.allocationSize = req.size;
233 info.memoryTypeIndex = 1; // never blocked by fail_bind_type = 0
234 VkDeviceMemory mem = VK_NULL_HANDLE;
235 mock_allocate_memory(VK_NULL_HANDLE, &info, nullptr, &mem);
236 return mem;
237 };
238}
239
240} // namespace
241
242int main() {
243 using namespace leonida;
244 const VkDevice dummy_device = make_handle<VkDevice>(1);
245 const VkBuffer args_buf = make_handle<VkBuffer>(0x100);
246 const VkBuffer count_buf = make_handle<VkBuffer>(0x200);
247
248 // 1. Multi-family sharing: both scratch chunks and HostArea counter buffers must use VK_SHARING_MODE_CONCURRENT.
249 {
250 MockState state;
251 g_mock = &state;
252 const std::vector<std::uint32_t> families = {0u, 2u};
253 IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(),
254 make_scratch_allocator(), nullptr, families);
255 CHECK(clamp.loaded());
256 auto batch = clamp.batch();
257 ClampedIndirect job{};
258 CHECK(batch->prepare(args_buf, 0, count_buf, 0, indirect_clamp_draw, 16, 4, job));
259 CHECK(job.buffer != VK_NULL_HANDLE && job.stats_buffer != VK_NULL_HANDLE);
260 const auto scratch_it = state.buffers.find(reinterpret_cast<std::uintptr_t>(job.buffer));
261 const auto area_it = state.buffers.find(reinterpret_cast<std::uintptr_t>(job.stats_buffer));
262 CHECK(scratch_it != state.buffers.end() && area_it != state.buffers.end());
263 CHECK(scratch_it->second.sharing_mode == VK_SHARING_MODE_CONCURRENT);
264 CHECK(scratch_it->second.families == families);
265 CHECK(area_it->second.sharing_mode == VK_SHARING_MODE_CONCURRENT);
266 CHECK(area_it->second.families == families);
267 batch.reset();
268 clamp.retire(VK_NULL_HANDLE, 0);
269 clamp.collect();
270 }
271
272 // 1b. Single-family stays VK_SHARING_MODE_EXCLUSIVE.
273 {
274 MockState state;
275 g_mock = &state;
276 IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(),
277 make_scratch_allocator(), nullptr, {0u});
278 auto batch = clamp.batch();
279 ClampedIndirect job{};
280 CHECK(batch->prepare(args_buf, 0, VK_NULL_HANDLE, 0, indirect_clamp_dispatch, 12, 2, job));
281 CHECK(state.buffers.at(reinterpret_cast<std::uintptr_t>(job.buffer)).sharing_mode ==
282 VK_SHARING_MODE_EXCLUSIVE);
283 CHECK(state.buffers.at(reinterpret_cast<std::uintptr_t>(job.stats_buffer)).sharing_mode ==
284 VK_SHARING_MODE_EXCLUSIVE);
285 }
286
287 // 2. vkBindBufferMemory failure on the first memory type in make_area() must free that VkDeviceMemory before
288 // retrying the next type (zero leaked allocations).
289 {
290 MockState state;
291 state.fail_bind_type = 0u;
292 g_mock = &state;
293 {
294 IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(),
295 make_scratch_allocator());
296 auto batch = clamp.batch();
297 ClampedIndirect job{};
298 CHECK(batch->prepare(args_buf, 0, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job));
299 // 2 host-area memory attempts (type 0 failed bind & freed immediately, type 1 succeeded) + 1 scratch alloc.
300 CHECK(state.alloc_memory_calls == 3);
301 CHECK(state.free_memory_calls == 1);
302 }
303 CHECK(state.alloc_memory_calls == state.free_memory_calls);
304 CHECK(state.create_buffer_calls == state.destroy_buffer_calls);
305 }
306
307 // 3. Released counter slots are zeroed so a subsequent aborted batch reusing the same slot never double-counts
308 // the prior submission's counters.
309 {
310 MockState state;
311 g_mock = &state;
312 IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(),
313 make_scratch_allocator());
314 VkBuffer area_buf = VK_NULL_HANDLE;
315 VkDeviceSize slot_off = 0;
316 {
317 auto batch1 = clamp.batch();
318 ClampedIndirect job1{};
319 CHECK(batch1->prepare(args_buf, 0, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job1));
320 area_buf = job1.stats_buffer;
321 slot_off = job1.stats_offset;
322 std::uint8_t* host = state.buffer_host.at(reinterpret_cast<std::uintptr_t>(area_buf));
323 const std::uint32_t gpu_written[12] = {5u, 1u, 2u, 3u, 0u, 0u, 0u, 0u, 7u, 4u, 3u, 2u};
324 std::memcpy(host + slot_off, gpu_written, sizeof(gpu_written));
325 }
326 const auto after1 = clamp.counters();
327 CHECK(after1.records_clamped == 5 && after1.counts_clamped == 1 && after1.over_budget == 2 &&
328 after1.zeroed == 3);
329 CHECK(after1.mesh_records == 7 && after1.mesh_yz_records == 4 &&
330 after1.mesh_max_y == 3 && after1.mesh_max_z == 2);
331
332 // Batch 2 reuses the exact same slot (LIFO free_slots_) and is destroyed without GPU submission.
333 {
334 auto batch2 = clamp.batch();
335 ClampedIndirect job2{};
336 CHECK(batch2->prepare(args_buf, 0, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job2));
337 CHECK(job2.stats_buffer == area_buf && job2.stats_offset == slot_off);
338 }
339 const auto after2 = clamp.counters();
340 CHECK(after2.records_clamped == 5 && after2.counts_clamped == 1 && after2.over_budget == 2 &&
341 after2.zeroed == 3);
342 CHECK(after2.mesh_records == 7 && after2.mesh_yz_records == 4 &&
343 after2.mesh_max_y == 3 && after2.mesh_max_z == 2);
344 }
345
346 // 4. Non-4-byte-aligned argument_offset or count_offset is rejected before allocating scratch.
347 {
348 MockState state;
349 g_mock = &state;
350 IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(),
351 make_scratch_allocator());
352 auto batch = clamp.batch();
353 ClampedIndirect job{};
354 CHECK(!batch->prepare(args_buf, 2, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job));
355 CHECK(!batch->prepare(args_buf, 0, count_buf, 6, indirect_clamp_draw, 16, 1, job));
356 CHECK(batch->calls() == 0);
357 // An uncounted call ignores count_offset == 0 and still succeeds on 4-byte-aligned argument_offset.
358 CHECK(batch->prepare(args_buf, 4, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job));
359 CHECK(batch->calls() == 1);
360 }
361
362 // 5. Concurrent area growth during prepare() + background batch release() + counters() under TSan.
363 {
364 MockState state;
365 g_mock = &state;
366 IndirectArgumentClamp clamp(mock_get_device_proc_addr, dummy_device, make_memory_props(), make_limits(),
367 make_scratch_allocator(), nullptr, {0u, 1u});
368 std::mutex queue_mutex;
369 std::vector<std::unique_ptr<IndirectArgumentClamp::Batch>> completed;
370 std::atomic<bool> done{false};
371
372 std::thread releaser([&] {
373 while (!done.load(std::memory_order_acquire)) {
374 std::unique_ptr<IndirectArgumentClamp::Batch> b;
375 {
376 std::lock_guard lock(queue_mutex);
377 if (!completed.empty()) {
378 b = std::move(completed.back());
379 completed.pop_back();
380 }
381 }
382 if (b) b.reset();
383 else std::this_thread::yield();
384 (void)clamp.counters();
385 }
386 for (;;) {
387 std::unique_ptr<IndirectArgumentClamp::Batch> b;
388 {
389 std::lock_guard lock(queue_mutex);
390 if (completed.empty()) break;
391 b = std::move(completed.back());
392 completed.pop_back();
393 }
394 b.reset();
395 }
396 });
397
398 // Allocate > 128 slots across several batches so areas_ grows and reallocates while releaser runs.
399 for (int b = 0; b < 8; ++b) {
400 auto batch = clamp.batch();
401 for (int i = 0; i < 40; ++i) {
402 ClampedIndirect job{};
403 CHECK(batch->prepare(args_buf, 0, VK_NULL_HANDLE, 0, indirect_clamp_draw, 16, 1, job));
404 CHECK(job.stats_buffer != VK_NULL_HANDLE);
405 }
406 clamp.retire(VK_NULL_HANDLE, 0);
407 clamp.collect();
408 {
409 std::lock_guard lock(queue_mutex);
410 completed.push_back(std::move(batch));
411 }
412 }
413 done.store(true, std::memory_order_release);
414 releaser.join();
415 }
416
417 std::printf("indirect_clamp_safety_test: all checks passed\n");
418 return 0;
419}
diff --git a/runtime/test/indirect_topology_and_stats_test.cpp b/runtime/test/indirect_topology_and_stats_test.cpp
new file mode 100644
index 000000000..79b6756b4
--- /dev/null
+++ b/runtime/test/indirect_topology_and_stats_test.cpp
@@ -0,0 +1,409 @@
1// Portable CPU-only tests for stateful indirect draw topology coverage and per-reason indirect_stats reporting.
2// No GPU, driver, or game data required.
3#include "../src/vulkan_replay.h"
4
5#include <cstdio>
6#include <cstdlib>
7#include <cstring>
8#include <string>
9#include <thread>
10#include <vector>
11
12#define CHECK(cond) \
13 do { \
14 if (!(cond)) { \
15 std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
16 std::exit(1); \
17 } \
18 } while (0)
19
20namespace {
21
22template <class T>
23T fake_handle(std::uintptr_t value) {
24 return reinterpret_cast<T>(value);
25}
26
27struct RecordedDraw {
28 VkPipeline pipeline = VK_NULL_HANDLE;
29 VkPrimitiveTopology topology = VK_PRIMITIVE_TOPOLOGY_MAX_ENUM;
30 VkBool32 primitive_restart = VK_FALSE;
31 bool indexed = false;
32 bool counted = false;
33 std::uint32_t max_count = 0;
34};
35
36struct Harness;
37Harness* g_harness = nullptr;
38
39struct Harness {
40 leonida::GraphicsPipeline pipeline{};
41 leonida::ResourceBinding args{};
42 leonida::ResourceBinding counts{};
43 leonida::ReplayFunctions vk{};
44 std::vector<RecordedDraw> draws;
45 std::uint32_t last_variant_flags = 0;
46 std::uint32_t variant_calls = 0;
47
48 VkPipeline bound_pipeline = VK_NULL_HANDLE;
49 VkPrimitiveTopology bound_topology = VK_PRIMITIVE_TOPOLOGY_MAX_ENUM;
50 VkBool32 bound_restart = VK_FALSE;
51
52 static VKAPI_ATTR void VKAPI_CALL cb_begin_rendering(VkCommandBuffer, const VkRenderingInfo*) {}
53 static VKAPI_ATTR void VKAPI_CALL cb_end_rendering(VkCommandBuffer) {}
54 static VKAPI_ATTR void VKAPI_CALL cb_bind_vb2(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkBuffer*,
55 const VkDeviceSize*, const VkDeviceSize*, const VkDeviceSize*) {}
56 static VKAPI_ATTR void VKAPI_CALL cb_bind_ib(VkCommandBuffer, VkBuffer, VkDeviceSize, VkIndexType) {}
57 static VKAPI_ATTR void VKAPI_CALL cb_bind_ib2(VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, VkIndexType) {}
58 static VKAPI_ATTR void VKAPI_CALL cb_set_vp(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}
59 static VKAPI_ATTR void VKAPI_CALL cb_set_sc(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}
60 static VKAPI_ATTR void VKAPI_CALL cb_set_topo(VkCommandBuffer, VkPrimitiveTopology t) {
61 g_harness->bound_topology = t;
62 }
63 static VKAPI_ATTR void VKAPI_CALL cb_set_restart(VkCommandBuffer, VkBool32 en) {
64 g_harness->bound_restart = en;
65 }
66 static VKAPI_ATTR void VKAPI_CALL cb_set_stencil(VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}
67 static VKAPI_ATTR void VKAPI_CALL cb_set_blend(VkCommandBuffer, const float[4]) {}
68 static VKAPI_ATTR void VKAPI_CALL cb_bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline p) {
69 g_harness->bound_pipeline = p;
70 }
71 static VKAPI_ATTR void VKAPI_CALL cb_push_constants(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags,
72 std::uint32_t, std::uint32_t, const void*) {}
73 static VKAPI_ATTR void VKAPI_CALL cb_draw(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t,
74 std::uint32_t) {}
75 static VKAPI_ATTR void VKAPI_CALL cb_draw_indexed(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t,
76 std::int32_t, std::uint32_t) {}
77 static VKAPI_ATTR void VKAPI_CALL cb_draw_indirect(VkCommandBuffer, VkBuffer, VkDeviceSize, std::uint32_t count,
78 std::uint32_t) {
79 g_harness->draws.push_back(
80 {g_harness->bound_pipeline, g_harness->bound_topology, g_harness->bound_restart, false, false, count});
81 }
82 static VKAPI_ATTR void VKAPI_CALL cb_draw_indexed_indirect(VkCommandBuffer, VkBuffer, VkDeviceSize,
83 std::uint32_t count, std::uint32_t) {
84 g_harness->draws.push_back(
85 {g_harness->bound_pipeline, g_harness->bound_topology, g_harness->bound_restart, true, false, count});
86 }
87 static VKAPI_ATTR void VKAPI_CALL cb_draw_indirect_count(VkCommandBuffer, VkBuffer, VkDeviceSize, VkBuffer,
88 VkDeviceSize, std::uint32_t max_count, std::uint32_t) {
89 g_harness->draws.push_back(
90 {g_harness->bound_pipeline, g_harness->bound_topology, g_harness->bound_restart, false, true, max_count});
91 }
92 static VKAPI_ATTR void VKAPI_CALL cb_draw_indexed_indirect_count(VkCommandBuffer, VkBuffer, VkDeviceSize, VkBuffer,
93 VkDeviceSize, std::uint32_t max_count,
94 std::uint32_t) {
95 g_harness->draws.push_back(
96 {g_harness->bound_pipeline, g_harness->bound_topology, g_harness->bound_restart, true, true, max_count});
97 }
98
99 Harness() {
100 g_harness = this;
101 pipeline.pipeline = fake_handle<VkPipeline>(0x1001);
102 pipeline.layout = fake_handle<VkPipelineLayout>(0x2001);
103 pipeline.push_stages = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
104 pipeline.rectangle_variant_topology = leonida::topology_rect_list;
105 pipeline.variant = [this](std::uint32_t flags) {
106 ++variant_calls;
107 last_variant_flags = flags;
108 if (flags & leonida::GraphicsPipeline::rectangle_stage)
109 return fake_handle<VkPipeline>(0x1000 + flags);
110 return fake_handle<VkPipeline>(0x1001);
111 };
112
113 args.buffer = fake_handle<VkBuffer>(0x3001);
114 args.buffer_offset = 64;
115 args.size = 256;
116 args.indirect_arguments = true;
117
118 counts.buffer = fake_handle<VkBuffer>(0x3002);
119 counts.buffer_offset = 128;
120 counts.size = 64;
121 counts.indirect_arguments = true;
122
123 vk.graphics_pipeline = [this](std::uintptr_t id) -> const leonida::GraphicsPipeline* {
124 return id == 7 ? &pipeline : nullptr;
125 };
126 vk.buffer_at = [](std::uint64_t va, std::uint64_t& size, VkBuffer& buf, VkDeviceSize& off) {
127 if (va != 0x10000) return false;
128 buf = fake_handle<VkBuffer>(0x3003);
129 off = 16;
130 size = 256;
131 return true;
132 };
133 vk.image_view = [](const leonida::ResourceBinding&, const VkImageSubresourceRange&) {
134 return fake_handle<VkImageView>(0x4001);
135 };
136 vk.begin_rendering = &cb_begin_rendering;
137 vk.end_rendering = &cb_end_rendering;
138 vk.bind_vertex_buffers2 = &cb_bind_vb2;
139 vk.bind_index_buffer = &cb_bind_ib;
140 vk.bind_robust_index_view = &cb_bind_ib2;
141 vk.set_viewport = &cb_set_vp;
142 vk.set_scissor = &cb_set_sc;
143 vk.set_primitive_topology = &cb_set_topo;
144 vk.set_primitive_restart_enable = &cb_set_restart;
145 vk.set_stencil_reference = &cb_set_stencil;
146 vk.set_blend_constants = &cb_set_blend;
147 vk.bind_pipeline = &cb_bind_pipeline;
148 vk.push_constants = &cb_push_constants;
149 vk.draw = &cb_draw;
150 vk.draw_indexed = &cb_draw_indexed;
151 vk.draw_indirect = &cb_draw_indirect;
152 vk.draw_indexed_indirect = &cb_draw_indexed_indirect;
153 vk.draw_indirect_count = &cb_draw_indirect_count;
154 vk.draw_indexed_indirect_count = &cb_draw_indexed_indirect_count;
155 vk.draw_indirect_first_instance = true;
156 vk.multi_draw_indirect = true;
157 vk.draw_indirect_count_enabled = true;
158 vk.max_draw_indirect_count = UINT32_MAX;
159 }
160
161 ~Harness() {
162 if (g_harness == this) g_harness = nullptr;
163 }
164
165 leonida::ReplayResult run_indirect(const leonida::Draw& draw, const leonida::IndirectDrawArgs& arg) {
166 g_harness = this;
167 draws.clear();
168 bound_pipeline = VK_NULL_HANDLE;
169 bound_topology = VK_PRIMITIVE_TOPOLOGY_MAX_ENUM;
170 bound_restart = VK_FALSE;
171 leonida::CommandList list;
172 CHECK(list.draw_indirect(leonida::Draw{draw}, arg));
173 CHECK(list.close());
174 const auto resolve = [this](leonida::ResourceId id) -> const leonida::ResourceBinding* {
175 if (id == 1) return &args;
176 if (id == 2) return &counts;
177 return nullptr;
178 };
179 return leonida::replay(list, VK_NULL_HANDLE, resolve, vk);
180 }
181};
182
183leonida::Draw make_base_draw(std::uint32_t topology, bool indexed, std::uint32_t index_format = 57) {
184 leonida::Draw d{};
185 d.pipeline = 7;
186 d.topology = topology;
187 d.viewport = {0.0f, 0.0f, 64.0f, 64.0f, 0.0f, 1.0f};
188 d.scissor = {0, 0, 64, 64};
189 d.indexed = indexed;
190 if (indexed) d.index = {0x10000, 64, index_format}; // 57 = R16_UINT, 42 = R32_UINT
191 return d;
192}
193
194void test_topology_predicate() {
195 using leonida::indirect_stats::topology_supported;
196 for (std::uint32_t t = 0; t <= 100; ++t) {
197 const bool expected = (t == 1 || t == 2 || t == 3 || t == 4 || t == 5 || t == 10 || t == 11 || t == 12 ||
198 t == 13 || t == leonida::topology_rect_list);
199 CHECK(topology_supported(t) == expected);
200 }
201 CHECK(!topology_supported(0));
202 CHECK(!topology_supported(leonida::topology_quad_list));
203 CHECK(!topology_supported(33)); // D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST
204 CHECK(!topology_supported(64)); // D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST
205}
206
207void test_supported_topologies_emit() {
208 struct Case {
209 std::uint32_t d3d_topology;
210 VkPrimitiveTopology vk_topology;
211 bool is_strip;
212 bool expects_rect_stage;
213 };
214 constexpr Case cases[] = {
215 {1, VK_PRIMITIVE_TOPOLOGY_POINT_LIST, false, false},
216 {2, VK_PRIMITIVE_TOPOLOGY_LINE_LIST, false, false},
217 {3, VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, true, false},
218 {4, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, false, false},
219 {5, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, true, false},
220 {10, VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY, false, false},
221 {11, VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY, true, false},
222 {12, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY, false, false},
223 {13, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY, true, false},
224 {leonida::topology_rect_list, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, false, true},
225 };
226
227 Harness h;
228 for (const auto& c : cases) {
229 for (const bool indexed : {false, true}) {
230 for (const bool counted : {false, true}) {
231 for (const std::uint32_t strip_cut : {0u, 1u, 2u}) {
232 for (const std::uint32_t idx_fmt : {57u, 42u}) {
233 if (!indexed && idx_fmt == 42u) continue;
234 h.pipeline.strip_cut = strip_cut;
235 h.variant_calls = 0;
236 h.last_variant_flags = 0;
237 const leonida::Draw d = make_base_draw(c.d3d_topology, indexed, idx_fmt);
238 leonida::IndirectDrawArgs arg{};
239 arg.argument_buffer = 1;
240 arg.argument_offset = 0;
241 arg.stride = indexed ? 20 : 16;
242 arg.max_count = 3;
243 if (counted) {
244 arg.count_buffer = 2;
245 arg.count_offset = 4;
246 }
247 CHECK(h.run_indirect(d, arg) == leonida::ReplayResult::success);
248 CHECK(h.draws.size() == 1);
249 const auto& got = h.draws[0];
250 CHECK(got.topology == c.vk_topology);
251 CHECK(got.indexed == indexed);
252 CHECK(got.counted == counted);
253 CHECK(got.max_count == 3);
254 const bool cut_matches = (strip_cut == 1 && idx_fmt == 57) || (strip_cut == 2 && idx_fmt == 42);
255 const VkBool32 want_restart = (indexed && c.is_strip && cut_matches) ? VK_TRUE : VK_FALSE;
256 CHECK(got.primitive_restart == want_restart);
257 if (c.expects_rect_stage) {
258 CHECK(h.variant_calls == 1);
259 CHECK((h.last_variant_flags & leonida::GraphicsPipeline::rectangle_stage) != 0);
260 CHECK(got.pipeline == fake_handle<VkPipeline>(0x1000 + h.last_variant_flags));
261 } else {
262 CHECK(h.variant_calls == 0);
263 CHECK(got.pipeline == h.pipeline.pipeline);
264 }
265 }
266 }
267 }
268 }
269 }
270}
271
272void test_rect_list_builtin_and_fallback() {
273 // 1. PSO created with topology_type_rect_list (19) already contains the GS -> rectangle_variant_topology == 0.
274 {
275 Harness h;
276 h.pipeline.rectangle_variant_topology = 0;
277 const leonida::Draw d = make_base_draw(leonida::topology_rect_list, false);
278 leonida::IndirectDrawArgs arg{1, 0, 16, 1, 0, 0};
279 CHECK(h.run_indirect(d, arg) == leonida::ReplayResult::success);
280 CHECK(h.draws.size() == 1);
281 CHECK(h.variant_calls == 0);
282 CHECK(h.draws[0].pipeline == h.pipeline.pipeline);
283 CHECK(h.draws[0].topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
284 }
285
286 // 2. Indirect RECTLIST when the pipeline cannot build a rectangle_stage variant -> skips cleanly with topology,
287 // never fails the command list (both without and with vk.compiles).
288 for (const bool with_compiles : {false, true}) {
289 Harness h;
290 h.pipeline.variant = [](std::uint32_t) { return VkPipeline(VK_NULL_HANDLE); };
291 h.pipeline.built = [](std::uint32_t) { return VkPipeline(VK_NULL_HANDLE); };
292 leonida::PipelineCompiles compiles;
293 if (with_compiles) h.vk.compiles = &compiles;
294
295 const auto before = leonida::indirect_stats::reason_skips(leonida::indirect_stats::topology);
296 const leonida::Draw d = make_base_draw(leonida::topology_rect_list, false);
297 leonida::IndirectDrawArgs arg{1, 0, 16, 2, 0, 0};
298 CHECK(h.run_indirect(d, arg) == leonida::ReplayResult::success);
299 CHECK(h.draws.empty());
300 CHECK(compiles.empty());
301 CHECK(leonida::indirect_stats::reason_skips(leonida::indirect_stats::topology) == before + 1);
302 }
303
304 // 3. Direct RECTLIST when rectangle_stage variant cannot be built still returns unsupported (unchanged).
305 {
306 Harness h;
307 h.pipeline.variant = [](std::uint32_t) { return VkPipeline(VK_NULL_HANDLE); };
308 leonida::CommandList list;
309 leonida::Draw d = make_base_draw(leonida::topology_rect_list, false);
310 d.count = 3;
311 d.instances = 1;
312 CHECK(list.draw(d) && list.close());
313 const auto res = leonida::replay(list, VK_NULL_HANDLE,
314 [](leonida::ResourceId) -> const leonida::ResourceBinding* { return nullptr; },
315 h.vk);
316 CHECK(res == leonida::ReplayResult::unsupported);
317 }
318}
319
320void test_unsupported_topologies_skip() {
321 Harness h;
322 constexpr std::uint32_t unsupported[] = {0, 6, 7, 9, 14, 18, leonida::topology_quad_list, 33, 64};
323 for (const std::uint32_t topo : unsupported) {
324 const auto before = leonida::indirect_stats::reason_skips(leonida::indirect_stats::topology);
325 const leonida::Draw d = make_base_draw(topo, false);
326 leonida::IndirectDrawArgs arg{1, 0, 16, 1, 0, 0};
327 CHECK(h.run_indirect(d, arg) == leonida::ReplayResult::success);
328 CHECK(h.draws.empty());
329 CHECK(leonida::indirect_stats::reason_skips(leonida::indirect_stats::topology) == before + 1);
330 }
331}
332
333std::string capture_report(const leonida::indirect_stats::Counts& counts) {
334 std::FILE* f = std::tmpfile();
335 CHECK(f != nullptr);
336 counts.report(f);
337 std::rewind(f);
338 char buf[1536]{};
339 const std::size_t n = std::fread(buf, 1, sizeof(buf) - 1, f);
340 std::fclose(f);
341 return std::string(buf, n);
342}
343
344void test_counts_report_and_concurrency() {
345 using namespace leonida::indirect_stats;
346
347 // 1. Clean prefix with no bracketed breakdown when all per-reason counts are zero.
348 {
349 Counts c;
350 c.values[static_cast<unsigned>(Event::recorded)].store(16);
351 c.values[static_cast<unsigned>(Event::emitted)].store(15);
352 const std::string line = capture_report(c);
353 CHECK(line == "[rt] indirect graphics: recorded=16 emitted=15 record_skips=0 replay_skips=0\n");
354 }
355
356 // 2. Non-zero per-reason counts appear in stable enum order inside [...].
357 {
358 Counts c;
359 c.values[static_cast<unsigned>(Event::recorded)].store(4096);
360 c.values[static_cast<unsigned>(Event::emitted)].store(3918);
361 c.values[static_cast<unsigned>(Event::record_skip)].store(53405);
362 c.values[static_cast<unsigned>(Event::replay_skip)].store(7);
363 c.by_reason[compound].store(2);
364 c.by_reason[mesh].store(53000);
365 c.by_reason[topology].store(403);
366 c.by_reason[pending_pipeline].store(7);
367 const std::string line = capture_report(c);
368 CHECK(line ==
369 "[rt] indirect graphics: recorded=4096 emitted=3918 record_skips=53405 replay_skips=7 "
370 "[compound=2, mesh=53000, topology=403, pending_pipeline=7]\n");
371 }
372
373 // 3. Out-of-range reason is ignored safely without corrupting counts.
374 {
375 const auto before_total = counts().values[static_cast<unsigned>(Event::record_skip)].load();
376 skip(Event::record_skip, reason_count);
377 CHECK(counts().values[static_cast<unsigned>(Event::record_skip)].load() == before_total);
378 CHECK(reason_skips(reason_count) == 0);
379 }
380
381 // 4. Multi-threaded skip increments are race-free and exact.
382 {
383 const auto mesh_before = reason_skips(mesh);
384 const auto div_before = reason_skips(divisor);
385 std::vector<std::thread> threads;
386 for (int t = 0; t < 4; ++t) {
387 threads.emplace_back([t] {
388 for (int i = 0; i < 250; ++i) {
389 skip(Event::record_skip, (t % 2 == 0) ? mesh : divisor);
390 }
391 });
392 }
393 for (auto& th : threads) th.join();
394 CHECK(reason_skips(mesh) == mesh_before + 500);
395 CHECK(reason_skips(divisor) == div_before + 500);
396 }
397}
398
399} // namespace
400
401int main() {
402 test_topology_predicate();
403 test_supported_topologies_emit();
404 test_rect_list_builtin_and_fallback();
405 test_unsupported_topologies_skip();
406 test_counts_report_and_concurrency();
407 std::printf("indirect_topology_and_stats_test: PASS\n");
408 return 0;
409}
diff --git a/runtime/test/int3_skip_test.cpp b/runtime/test/int3_skip_test.cpp
index 3c06302eb..9fa05386e 100644
--- a/runtime/test/int3_skip_test.cpp
+++ b/runtime/test/int3_skip_test.cpp
@@ -1,9 +1,21 @@
1// LEONIDA_SKIP_INT3 (shims/startup_trace.h): with the variable set and a trace open, an int3 is logged once per 1// LEONIDA_SKIP_INT3 (shims/startup_trace.h): with the variable set and a trace open, an int3 is logged once per
2// address and stepped over, so execution continues. A separate executable because the variable is read once. 2// address and stepped over, so execution continues.
3//
4// Each case runs in a child process of its own (`int3_skip_test --case NAME`), so a case that crashes fails alone and
5// each one opens the trace with its own environment:
6// real a real int3 at two sites, one of them hit twice: execution continues, one event per address
7// windows a synthetic breakpoint with Rip on the 0xCC (Windows): Rip ends one past it, one event
8// wine Rip one byte past the 0xCC (Wine, old upstream 7599): the same result
9// null null EXCEPTION_POINTERS, ExceptionRecord or ContextRecord: no skip and no crash
10// init the variable is read when the trace opens: removed after open(), int3s are still skipped
11// off without the variable, nothing is skipped
3#include <windows.h> 12#include <windows.h>
4 13
5#include <cstdio> 14#include <cstdio>
15#include <cstring>
16#include <filesystem>
6#include <fstream> 17#include <fstream>
18#include <memory>
7#include <sstream> 19#include <sstream>
8#include <string> 20#include <string>
9 21
@@ -35,31 +47,195 @@ __declspec(noinline) void site_b(int& reached) {
35 ++reached; 47 ++reached;
36} 48}
37 49
38} // namespace 50// A trace file of this process; the text is read back after close().
51struct Trace {
52 std::wstring path;
53 Trace() {
54 wchar_t temp[MAX_PATH];
55 GetTempPathW(MAX_PATH, temp);
56 path = std::wstring(temp) + L"int3_skip_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl";
57 DeleteFileW(path.c_str());
58 check(rt::startup_trace::open(path.c_str()), "open the startup trace file");
59 }
60 std::string close_and_read() {
61 rt::startup_trace::close();
62 std::string log;
63 {
64 std::ifstream in{std::filesystem::path(path)};
65 std::stringstream text;
66 text << in.rdbuf();
67 log = text.str();
68 }
69 DeleteFileW(path.c_str());
70 return log;
71 }
72};
73
74// A synthetic EXCEPTION_BREAKPOINT for skip_int3, as the vectored handler receives it.
75struct Breakpoint {
76 EXCEPTION_RECORD record{};
77 std::unique_ptr<CONTEXT> context = std::make_unique<CONTEXT>(); // heap: a 16-byte-aligned member pads the struct
78 EXCEPTION_POINTERS pointers{};
79 Breakpoint(const unsigned char* address, const unsigned char* rip) {
80 record.ExceptionCode = EXCEPTION_BREAKPOINT;
81 record.ExceptionAddress = const_cast<unsigned char*>(address);
82 record.NumberParameters = 1;
83 context->ContextFlags = CONTEXT_CONTROL;
84 context->Rip = reinterpret_cast<DWORD64>(rip);
85 pointers.ExceptionRecord = &record;
86 pointers.ContextRecord = context.get();
87 }
88 bool skip() { return rt::startup_trace::detail::skip_int3(&pointers); }
89 bool rip_is(const unsigned char* p) const { return context->Rip == reinterpret_cast<DWORD64>(p); }
90};
91
92// nop, int3, nop: the int3 at code + 1, with a byte on each side that is not one.
93alignas(16) unsigned char g_code[4] = {0x90, 0xCC, 0x90, 0x90};
39 94
40int main() { 95std::string event_at(const unsigned char* at) {
41 SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1"); // before the first exception: the flag is read once 96 const std::string where = rt::startup_trace::where(reinterpret_cast<uint64_t>(at));
42 wchar_t temp[MAX_PATH]; 97 return "\"kind\":\"int3_skipped\",\"at\":" + rt::startup_trace::quote(where);
43 GetTempPathW(MAX_PATH, temp); 98}
44 const std::wstring path = std::wstring(temp) + L"int3_skip_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl";
45 DeleteFileW(path.c_str());
46 check(rt::startup_trace::open(path.c_str()), "open the startup trace file");
47 99
100void case_real() {
101 SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1");
102 Trace trace;
48 int reached = 0; 103 int reached = 0;
49 for (int i = 0; i < 2; ++i) site_a(reached); // the same site twice: one event 104 for (int i = 0; i < 2; ++i) site_a(reached); // the same site twice: one event
50 site_b(reached); // another site 105 site_b(reached); // another site
51 check(reached == 3, "execution continues past every int3"); 106 check(reached == 3, "execution continues past every int3");
52 rt::startup_trace::close(); 107 const std::string log = trace.close_and_read();
53
54 std::ifstream in(path);
55 std::stringstream text;
56 text << in.rdbuf();
57 const std::string log = text.str();
58 in.close();
59 DeleteFileW(path.c_str());
60 check(count(log, "\"kind\":\"int3_skipped\"") == 2, "exactly two int3_skipped events (one per address)"); 108 check(count(log, "\"kind\":\"int3_skipped\"") == 2, "exactly two int3_skipped events (one per address)");
61 check(count(log, "\"kind\":\"exception\"") == 0, "a skipped int3 is not also logged as an exception"); 109 check(count(log, "\"kind\":\"exception\"") == 0, "a skipped int3 is not also logged as an exception");
62 check(log.find("\"at\":\"host:") != std::string::npos, "the event names the address"); 110 check(log.find("\"at\":\"host:") != std::string::npos, "the event names the address");
111}
112
113void case_windows() {
114 SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1");
115 Trace trace;
116 const unsigned char* at = g_code + 1;
117 Breakpoint first(at, at);
118 check(first.skip(), "Rip on the 0xCC: skipped");
119 check(first.rip_is(at + 1), "Rip on the 0xCC: Rip ends one byte past it");
120 Breakpoint again(at, at);
121 check(again.skip() && again.rip_is(at + 1), "the same site again: skipped the same way");
122 Breakpoint no_int3(g_code + 3, g_code + 3);
123 check(!no_int3.skip() && no_int3.rip_is(g_code + 3), "no 0xCC at or before Rip: not skipped, Rip unchanged");
124 Breakpoint elsewhere(g_code, at);
125 check(!elsewhere.skip() && elsewhere.rip_is(at), "ExceptionAddress not at the int3 or past it: not skipped");
126 const std::string log = trace.close_and_read();
127 check(count(log, "\"kind\":\"int3_skipped\"") == 1, "one int3_skipped event for the site");
128 check(log.find(event_at(at)) != std::string::npos, "the event names the 0xCC byte");
129}
130
131void case_wine() {
132 SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1");
133 Trace trace;
134 const unsigned char* at = g_code + 1;
135 Breakpoint past(at + 1, at + 1); // ExceptionAddress and Rip one byte past the 0xCC
136 check(past.skip(), "Rip one byte past the 0xCC: skipped");
137 check(past.rip_is(at + 1), "Rip one byte past the 0xCC: Rip ends one byte past it");
138 Breakpoint mixed(at, at + 1); // ExceptionAddress on the 0xCC, Rip past it
139 check(mixed.skip() && mixed.rip_is(at + 1), "ExceptionAddress on the 0xCC, Rip past it: skipped");
140 const std::string log = trace.close_and_read();
141 check(count(log, "\"kind\":\"int3_skipped\"") == 1, "one int3_skipped event for the site");
142 check(log.find(event_at(at)) != std::string::npos, "the event names the 0xCC byte, not the byte after it");
143}
144
145// nop, int3, int3, nop: a run of int3 padding.
146alignas(16) unsigned char g_padding[4] = {0x90, 0xCC, 0xCC, 0x90};
147
148void case_padding() {
149 SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1");
150 Trace trace;
151 const unsigned char* at = g_padding + 1;
152 Breakpoint mixed(at, at + 1); // ExceptionAddress on the first 0xCC, Rip on the second
153 check(mixed.skip() && mixed.rip_is(at + 1),
154 "ExceptionAddress on an int3 followed by another, Rip past it: the int3 ExceptionAddress names is skipped");
155 const std::string log = trace.close_and_read();
156 check(count(log, "\"kind\":\"int3_skipped\"") == 1, "one int3_skipped event");
157 check(log.find(event_at(at)) != std::string::npos, "the event names the int3 ExceptionAddress names");
158}
159
160void case_null() {
161 SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1");
162 Trace trace;
163 check(!rt::startup_trace::detail::skip_int3(nullptr), "null EXCEPTION_POINTERS: not skipped");
164 Breakpoint no_record(g_code + 1, g_code + 1);
165 no_record.pointers.ExceptionRecord = nullptr;
166 check(!no_record.skip() && no_record.rip_is(g_code + 1), "null ExceptionRecord: not skipped");
167 Breakpoint no_context(g_code + 1, g_code + 1);
168 no_context.pointers.ContextRecord = nullptr;
169 check(!no_context.skip(), "null ContextRecord: not skipped");
170 const std::string log = trace.close_and_read();
171 check(count(log, "\"kind\":\"int3_skipped\"") == 0, "no int3_skipped event");
172}
173
174void case_init() {
175 SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", L"1");
176 Trace trace;
177 SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr); // read when the trace opened, not at the first int3
178 check(rt::startup_trace::detail::skip_int3_on.load(), "the flag holds the value read when the trace opened");
179 Breakpoint bp(g_code + 1, g_code + 1);
180 check(bp.skip() && bp.rip_is(g_code + 2), "an int3 after the variable is removed is still skipped");
181 trace.close_and_read();
182}
183
184void case_off() {
185 SetEnvironmentVariableW(L"LEONIDA_SKIP_INT3", nullptr);
186 Trace trace;
187 check(!rt::startup_trace::detail::skip_int3_on.load(), "without the variable the flag is off");
188 Breakpoint bp(g_code + 1, g_code + 1);
189 check(!bp.skip() && bp.rip_is(g_code + 1), "without the variable an int3 is not skipped");
190 trace.close_and_read();
191}
192
193struct Case {
194 const char* name;
195 void (*run)();
196};
197constexpr Case kCases[] = {{"real", case_real}, {"windows", case_windows}, {"wine", case_wine},
198 {"padding", case_padding}, {"null", case_null}, {"init", case_init},
199 {"off", case_off}};
200
201// Runs `this-exe --case NAME` and returns its exit code.
202DWORD run_child(const char* name) {
203 wchar_t exe[MAX_PATH];
204 GetModuleFileNameW(nullptr, exe, MAX_PATH);
205 std::wstring command = L"\"" + std::wstring(exe) + L"\" --case ";
206 for (const char* c = name; *c; ++c) command += static_cast<wchar_t>(*c);
207 STARTUPINFOW si{};
208 si.cb = sizeof si;
209 PROCESS_INFORMATION pi{};
210 if (!CreateProcessW(exe, command.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) return 0xFFFFFFFF;
211 WaitForSingleObject(pi.hProcess, INFINITE);
212 DWORD code = 0xFFFFFFFF;
213 GetExitCodeProcess(pi.hProcess, &code);
214 CloseHandle(pi.hThread);
215 CloseHandle(pi.hProcess);
216 return code;
217}
218
219} // namespace
220
221int main(int argc, char** argv) {
222 if (argc == 3 && std::strcmp(argv[1], "--case") == 0) {
223 for (const Case& c : kCases)
224 if (std::strcmp(argv[2], c.name) == 0) {
225 c.run();
226 std::fflush(stdout);
227 return g_failed ? 1 : 0;
228 }
229 std::printf("unknown case %s\n", argv[2]);
230 return 2;
231 }
232 for (const Case& c : kCases) {
233 std::printf("-- %s\n", c.name);
234 std::fflush(stdout);
235 const DWORD code = run_child(c.name);
236 if (code != 0) std::printf("FAIL case %s exited with 0x%08lx\n", c.name, static_cast<unsigned long>(code));
237 if (code != 0) ++g_failed;
238 }
63 std::printf("%s\n", g_failed ? "FAILED" : "all checks passed"); 239 std::printf("%s\n", g_failed ? "FAILED" : "all checks passed");
64 return g_failed ? 1 : 0; 240 return g_failed ? 1 : 0;
65} 241}
diff --git a/runtime/test/keyboard_pad_retry_test.cpp b/runtime/test/keyboard_pad_retry_test.cpp
new file mode 100644
index 000000000..6c4e41757
--- /dev/null
+++ b/runtime/test/keyboard_pad_retry_test.cpp
@@ -0,0 +1,137 @@
1// No SDL, Windows, window, input sampling or worker. The shim instantiates this exact lifecycle with its SDL backend.
2#include "../shims/keyboard_pad_connection.h"
3
4#include <cstdio>
5#include <cstdlib>
6#include <limits>
7#include <string>
8
9#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); std::exit(1); } } while (0)
10
11namespace {
12using Connection = rt::gameinput::detail::KeyboardPadConnection<int, int>;
13
14struct Fake {
15 std::uint64_t clock = 0;
16 unsigned clock_reads = 0;
17 int live = 0, handle = 0, serial = 0;
18 bool attach_ok = true, open_ok = true, detach_ok = true;
19 std::string events;
20
21 std::uint64_t now() { ++clock_reads; return clock; }
22 int attach() {
23 CHECK(!live && !handle); // never leak or create two virtual devices
24 events += 'A';
25 return attach_ok ? (live = ++serial) : 0;
26 }
27 int open(int id) {
28 CHECK(id && id == live && !handle);
29 events += 'O';
30 return open_ok ? (handle = live + 10) : 0;
31 }
32 void close(int js) {
33 CHECK(js && js == handle);
34 events += 'C';
35 handle = 0;
36 }
37 bool detach(int id) {
38 CHECK(id && id == serial && !handle);
39 events += 'D';
40 if (id != live) return false; // SDL returns false for an already-removed device
41 if (detach_ok) live = 0;
42 return detach_ok;
43 }
44 bool is_virtual(int id) const { return id != 0 && id == live; }
45 void failed() { events += '!'; }
46 void attached() { CHECK(handle); events += '+'; }
47 void removed() { CHECK(!live && !handle); events += '-'; }
48};
49
50void throttled_recovery() {
51 Connection pad;
52 Fake b;
53 b.attach_ok = false;
54 CHECK(!pad.update(false, b) && b.events.empty() && !b.clock_reads);
55 CHECK(!pad.update(true, b) && b.events == "A!"); // first failure, including at clock zero
56 for (b.clock = 2'000; b.clock < 1'000'000; b.clock += 2'000) CHECK(!pad.update(true, b));
57 b.clock = 999'999;
58 CHECK(!pad.update(true, b) && b.events == "A!");
59 ++b.clock;
60 CHECK(!pad.update(true, b) && b.events == "A!A"); // no extra warning
61 b.clock += 8'500'000;
62 CHECK(!pad.update(true, b) && b.events == "A!AA"); // one attempt, no catch-up loop
63 b.attach_ok = true;
64 b.clock += 999'999;
65 CHECK(!pad.update(true, b));
66 ++b.clock;
67 CHECK(pad.update(true, b) && b.events == "A!AAAO+");
68 CHECK(pad.id == b.live && pad.js == b.handle);
69 const unsigned previous = b.clock_reads;
70 for (int n = 0; n < 500; ++n) CHECK(pad.update(true, b));
71 CHECK(b.events == "A!AAAO+" && previous == b.clock_reads); // hot path does not even read the retry clock
72 CHECK(!pad.update(false, b) && b.events == "A!AAAO+CD-" && !pad.id && !pad.js);
73 CHECK(!pad.update(false, b) && b.events == "A!AAAO+CD-");
74 b.attach_ok = false;
75 CHECK(!pad.update(true, b) && b.events == "A!AAAO+CD-A!"); // new outage reports once
76 CHECK(!pad.update(false, b));
77 b.attach_ok = true;
78 CHECK(pad.update(true, b) && b.events == "A!AAAO+CD-A!AO+"); // no old cooldown after off
79}
80
81void partial_open_and_cleanup() {
82 Connection pad;
83 Fake b;
84 b.open_ok = false;
85 CHECK(!pad.update(true, b) && b.events == "AO!D" && !pad.id && !pad.js);
86 b.clock += 1'000'000;
87 b.detach_ok = false;
88 CHECK(!pad.update(true, b) && b.events == "AO!DAOD");
89 CHECK(pad.id == b.live && !pad.js);
90 b.clock += 1'000'000;
91 CHECK(!pad.update(true, b) && b.events == "AO!DAODD"); // no new attach while old ID is owned
92 b.open_ok = b.detach_ok = true;
93 b.clock += 1'000'000;
94 CHECK(pad.update(true, b) && b.events == "AO!DAODDDAO+");
95 b.events.clear();
96 b.detach_ok = false;
97 CHECK(!pad.update(false, b) && b.events == "CD" && !pad.js && pad.id);
98 CHECK(!pad.update(false, b) && b.events == "CD"); // no second close/removal or per-poll detach
99 b.clock += 1'000'000;
100 CHECK(!pad.update(false, b) && b.events == "CDD");
101 b.detach_ok = true;
102 CHECK(pad.update(true, b) && b.events == "CDDD-AO+"); // finish real removal before reattaching
103 CHECK(!pad.update(false, b) && b.events == "CDDD-AO+CD-");
104}
105
106void elapsed_clock_rollover() {
107 Connection pad;
108 Fake b;
109 b.clock = std::numeric_limits<std::uint64_t>::max() - 9;
110 b.attach_ok = false;
111 CHECK(!pad.update(true, b));
112 b.clock += 999'999;
113 b.attach_ok = true;
114 CHECK(!pad.update(true, b) && b.events == "A!");
115 ++b.clock;
116 CHECK(pad.update(true, b) && b.events == "A!AO+");
117}
118
119void already_removed_during_cleanup() {
120 Connection pad;
121 Fake b;
122 b.open_ok = b.detach_ok = false;
123 CHECK(!pad.update(true, b) && b.events == "AO!D" && pad.id == b.live && !pad.js);
124 b.live = 0; // SDL no longer owns this virtual ID when cleanup retries
125 b.clock += 1'000'000;
126 b.open_ok = b.detach_ok = true;
127 CHECK(pad.update(true, b) && b.events == "AO!DDAO+" && pad.id == 2);
128}
129} // namespace
130
131int main() {
132 throttled_recovery();
133 partial_open_and_cleanup();
134 elapsed_clock_rollover();
135 already_removed_during_cleanup();
136 std::puts("keyboard pad retry: cadence, recovery, partial ownership, off/re-enable and rollover passed");
137}
diff --git a/runtime/test/large_module_gate.h b/runtime/test/large_module_gate.h
index ea805c926..fcd29ed0e 100644
--- a/runtime/test/large_module_gate.h
+++ b/runtime/test/large_module_gate.h
@@ -1,181 +1,4 @@
1// How many large SPIR-V modules vk_pipeline_check lets into the driver at once, by a memory budget. 1// Moved to runtime/src: the runtime uses it too (large_module_gate.h there).
2//
3// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute
4// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB.
5// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6
6// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin
7// over the measurement.
8//
9// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas
10// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each
11// large module.
12#pragma once 2#pragma once
13 3
14#include <algorithm> 4#include "../src/large_module_gate.h"
15#include <condition_variable>
16#include <cstdint>
17#include <cstdio>
18#include <mutex>
19#include <string>
20
21#ifdef _WIN32
22#ifndef NOMINMAX
23#define NOMINMAX
24#endif
25#include <windows.h>
26#endif
27#if defined(__GLIBC__)
28#include <malloc.h>
29#endif
30
31namespace leonida {
32
33inline constexpr uint64_t kBytesPerSpirvByte = 512;
34
35inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; }
36
37#if defined(__linux__)
38// The first unsigned number in a file ("max" and unreadable files give no value).
39inline bool read_u64_file(const std::string& path, uint64_t& value) {
40 std::FILE* f = std::fopen(path.c_str(), "r");
41 if (!f) return false;
42 unsigned long long v = 0;
43 const bool ok = std::fscanf(f, "%llu", &v) == 1;
44 std::fclose(f);
45 value = v;
46 return ok;
47}
48
49// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or
50// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests.
51inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup",
52 const std::string& cgroup_root = "/sys/fs/cgroup") {
53 std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r");
54 if (!f) return UINT64_MAX;
55 char line[4096];
56 std::string rel;
57 while (std::fgets(line, sizeof(line), f)) {
58 std::string l(line);
59 if (l.rfind("0::", 0) == 0) { // the cgroup v2 line
60 rel = l.substr(3);
61 while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back();
62 break;
63 }
64 }
65 std::fclose(f);
66 uint64_t room = UINT64_MAX;
67 for (std::string dir = rel; !dir.empty();) {
68 // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root.
69 const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir;
70 uint64_t max = 0, current = 0;
71 if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current))
72 room = std::min(room, max > current ? max - current : 0);
73 const auto slash = dir.find_last_of('/');
74 if (dir == "/" || slash == std::string::npos) break;
75 dir.resize(slash == 0 ? 1 : slash);
76 }
77 return room;
78}
79#endif
80
81// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate).
82inline uint64_t available_memory_bytes() {
83#ifdef _WIN32
84 MEMORYSTATUSEX status{};
85 status.dwLength = sizeof(status);
86 return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0;
87#elif defined(__linux__)
88 std::FILE* f = std::fopen("/proc/meminfo", "r");
89 if (!f) return 0;
90 char line[256];
91 unsigned long long kb = 0;
92 bool found = false;
93 while (std::fgets(line, sizeof(line), f))
94 if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; }
95 std::fclose(f);
96 if (!found) return 0;
97 const uint64_t room = cgroup_memory_room();
98 return std::max<uint64_t>(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown"
99#else
100 return 0;
101#endif
102}
103
104// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it).
105inline void release_free_memory() {
106#if defined(__GLIBC__)
107 malloc_trim(0);
108#endif
109}
110
111// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in
112// when none is, so a module bigger than the whole budget still compiles (alone among the large ones).
113class LargeModuleGate {
114public:
115 LargeModuleGate(uint64_t budget, unsigned max_inflight)
116 : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {}
117
118 bool admits(uint64_t estimate) const {
119 std::lock_guard<std::mutex> g(mu_);
120 return admits_locked(estimate);
121 }
122 void enter(uint64_t estimate) {
123 std::unique_lock<std::mutex> l(mu_);
124 cv_.wait(l, [&] { return admits_locked(estimate); });
125 used_ += estimate;
126 ++inflight_;
127 }
128 void leave(uint64_t estimate) {
129 {
130 std::lock_guard<std::mutex> g(mu_);
131 used_ -= estimate;
132 --inflight_;
133 }
134 cv_.notify_all();
135 }
136 unsigned inflight() const {
137 std::lock_guard<std::mutex> g(mu_);
138 return inflight_;
139 }
140 uint64_t budget() const { return budget_; }
141 unsigned max_inflight() const { return max_inflight_; }
142
143 // Holds a place from construction until destruction (or release()), then hands freed memory back.
144 class Ticket {
145 public:
146 Ticket() = default;
147 Ticket(LargeModuleGate& gate, uint64_t estimate) : gate_(&gate), estimate_(estimate) { gate.enter(estimate); }
148 Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; }
149 Ticket& operator=(Ticket&& o) noexcept {
150 if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; }
151 return *this;
152 }
153 Ticket(const Ticket&) = delete;
154 Ticket& operator=(const Ticket&) = delete;
155 ~Ticket() { release(); }
156 void release() {
157 if (!gate_) return;
158 gate_->leave(estimate_);
159 gate_ = nullptr;
160 release_free_memory();
161 }
162 private:
163 LargeModuleGate* gate_ = nullptr;
164 uint64_t estimate_ = 0;
165 };
166
167private:
168 bool admits_locked(uint64_t estimate) const {
169 if (inflight_ == 0) return true;
170 return inflight_ < max_inflight_ && used_ + estimate <= budget_;
171 }
172
173 const uint64_t budget_;
174 const unsigned max_inflight_;
175 mutable std::mutex mu_;
176 std::condition_variable cv_;
177 uint64_t used_ = 0;
178 unsigned inflight_ = 0;
179};
180
181} // namespace leonida
diff --git a/runtime/test/loader_test.cpp b/runtime/test/loader_test.cpp
index d985ba423..6930878a9 100644
--- a/runtime/test/loader_test.cpp
+++ b/runtime/test/loader_test.cpp
@@ -654,6 +654,93 @@ void test_initialise_rejects() {
654 } 654 }
655} 655}
656 656
657// IMAGE_FILE_RELOCS_STRIPPED against a relocation directory, when the preferred base is taken. Measured on the
658// Windows 11 (26200) loader with synthetic DLLs (runtime/README.md): with no relocation directory the flag refuses
659// the move and an image with the flag clear is moved with nothing fixed up; with a relocation table the image is
660// moved and fixed up whatever the flag says. The DllMain stub stores through an absolute address in this process,
661// not in the image, so it runs correctly wherever the image lands.
662void test_moved_without_relocations() {
663 auto img = make_image();
664 auto* nt = nt_of(img);
665 nt->FileHeader.Characteristics |= IMAGE_FILE_DLL;
666 nt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x1C0000000);
667 nt->OptionalHeader.AddressOfEntryPoint = 0x1040;
668 emit_store_stub(img, 0x240, reinterpret_cast<uint64_t>(&g_main_ran), 5, 1);
669 const uint64_t preferred = nt->OptionalHeader.ImageBase;
670 void* held = VirtualAlloc(reinterpret_cast<void*>(preferred), 0x2000, MEM_RESERVE, PAGE_NOACCESS);
671 if (!held) {
672 // Something else holds it already, which is the case under test as well; but make sure it is held.
673 MEMORY_BASIC_INFORMATION info{};
674 if (!VirtualQuery(reinterpret_cast<void*>(preferred), &info, sizeof info) || info.State == MEM_FREE)
675 return failed("an image without relocations moves when its base is taken", "cannot hold its base");
676 }
677 {
678 const char* what = "an image without relocations, flag clear, moves when its base is taken";
679 g_main_ran = 0;
680 auto p = write_image(img);
681 try {
682 rt::Loader loader(g_dir);
683 rt::Module& m = loader.load(p);
684 if (reinterpret_cast<uint64_t>(m.base) == preferred || !m.relocated)
685 failed(what, "it was not moved");
686 else if (std::memcmp(m.base + 0x1000, text_raw(img), 0x200) != 0)
687 failed(what, "the mapped section doesn't match the file (something was fixed up)");
688 else {
689 loader.initialise();
690 if (g_main_ran != 5) failed(what, "its DllMain never ran at the new address");
691 else pass(what);
692 }
693 } catch (const std::exception& e) {
694 failed(what, e.what());
695 }
696 }
697 {
698 auto stripped = img;
699 nt_of(stripped)->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
700 std::string error;
701 const char* what = "an image with IMAGE_FILE_RELOCS_STRIPPED is refused when its base is taken";
702 if (load(write_image(stripped), error) == 0) failed(what, "the image loaded");
703 else if (error.find("stripped") == std::string::npos) failed(what, "refused for another reason: " + error);
704 else pass(what);
705 }
706 if (held) VirtualFree(held, 0, MEM_RELEASE);
707 {
708 // At a free base such an image maps, as it did before. Not Windows parity: the Windows 11 loader refused these
709 // DLLs (error 487) at a free base too, for a reason not yet known; runtime/README.md keeps the question.
710 auto stripped = img;
711 nt_of(stripped)->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
712 expect_loads("an image with IMAGE_FILE_RELOCS_STRIPPED and no relocations maps at its free base", stripped);
713 }
714 {
715 // With a relocation table the flag does not stop the move: the table is applied, as Windows does it.
716 // ImageBase 0 makes the loader move it; the one DIR64 entry points at the qword at RVA 0x1100.
717 const char* what = "an image with IMAGE_FILE_RELOCS_STRIPPED and a relocation table is moved and fixed up";
718 auto stripped = make_image();
719 auto* snt = nt_of(stripped);
720 snt->FileHeader.Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
721 snt->OptionalHeader.ImageBase = 0;
722 snt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC] = {0x1000, 0x0A};
723 auto* block = reinterpret_cast<IMAGE_BASE_RELOCATION*>(stripped.data() + 0x200);
724 block->VirtualAddress = 0x1000;
725 block->SizeOfBlock = 0x0A;
726 reinterpret_cast<uint16_t*>(block + 1)[0] = (IMAGE_REL_BASED_DIR64 << 12) | 0x100;
727 uint64_t original;
728 std::memcpy(&original, stripped.data() + 0x300, sizeof original);
729 auto p = write_image(stripped);
730 try {
731 rt::Loader loader(g_dir);
732 rt::Module& m = loader.load(p);
733 uint64_t moved;
734 std::memcpy(&moved, m.base + 0x1100, sizeof moved);
735 if (!m.relocated) failed(what, "it was not moved");
736 else if (moved != original + reinterpret_cast<uint64_t>(m.base)) failed(what, "the pointer wasn't fixed up");
737 else pass(what);
738 } catch (const std::exception& e) {
739 failed(what, e.what());
740 }
741 }
742}
743
657// The images below jump to host observers so notifications remain observable after the mappings are freed. 744// The images below jump to host observers so notifications remain observable after the mappings are freed.
658// The FLS destructor itself starts in mapped code: leaving it registered would call unmapped memory at exit. 745// The FLS destructor itself starts in mapped code: leaving it registered would call unmapped memory at exit.
659void emit_jump_stub(std::vector<uint8_t>& img, size_t off, uint64_t target) { 746void emit_jump_stub(std::vector<uint8_t>& img, size_t off, uint64_t target) {
@@ -1471,6 +1558,7 @@ int main() {
1471 test_section_bounds(); 1558 test_section_bounds();
1472 test_truncation(); 1559 test_truncation();
1473 test_relocations(); 1560 test_relocations();
1561 test_moved_without_relocations();
1474 test_exports(); 1562 test_exports();
1475 test_empty_named_export(); 1563 test_empty_named_export();
1476 test_imports(); 1564 test_imports();
diff --git a/runtime/test/pipeline_cache_journal_test.cpp b/runtime/test/pipeline_cache_journal_test.cpp
new file mode 100644
index 000000000..c3793c96c
--- /dev/null
+++ b/runtime/test/pipeline_cache_journal_test.cpp
@@ -0,0 +1,337 @@
1// The pipeline journal's file naming, reading and writing (pipeline_cache_journal.h). No Vulkan, no GPU.
2#include "../src/pipeline_cache_journal.h"
3
4#include <chrono>
5#include <cstdint>
6#include <cstdio>
7#include <cstring>
8#include <filesystem>
9#include <fstream>
10#include <string>
11#include <vector>
12
13namespace fs = std::filesystem;
14namespace journal = leonida::pipeline_journal;
15namespace store = leonida::pipeline_cache_store;
16
17#define CHECK(condition) do { \
18 if (!(condition)) { \
19 std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
20 return 1; \
21 } \
22} while (0)
23
24static void put32(std::uint8_t* p, std::uint32_t value) {
25 for (int i = 0; i < 4; ++i) p[i] = static_cast<std::uint8_t>(value >> (8 * i));
26}
27
28static leonida::cached_pso::Identity identity() {
29 leonida::cached_pso::Identity id;
30 id.vendor = 0x10de;
31 id.device = 0x2782;
32 for (int i = 0; i < 16; ++i) id.cache_uuid[i] = static_cast<std::uint8_t>(0xa0 + i);
33 return id;
34}
35
36// A VkPipelineCacheHeaderVersionOne for `id` followed by `payload` bytes.
37static std::vector<char> blob(const leonida::cached_pso::Identity& id, std::size_t payload) {
38 std::vector<char> out(store::header_bytes + payload, '\x5a');
39 auto* p = reinterpret_cast<std::uint8_t*>(out.data());
40 put32(p, store::header_bytes);
41 put32(p + 4, store::header_version_one);
42 put32(p + 8, id.vendor);
43 put32(p + 12, id.device);
44 std::memcpy(p + 16, id.cache_uuid, sizeof(id.cache_uuid));
45 return out;
46}
47
48static int test_hash() {
49 const std::uint32_t words[] = {0x07230203, 0x00010600, 1, 2, 3};
50 journal::Hasher a, b, c;
51 a.text("cs");
52 a.bytes(words, sizeof(words));
53 a.value(std::uint32_t(32));
54 b.text("cs");
55 b.bytes(words, sizeof(words));
56 b.value(std::uint32_t(32));
57 CHECK(a.digest() == b.digest()); // deterministic: the next boot finds the same file
58 c.text("cs");
59 c.bytes(words, sizeof(words));
60 c.value(std::uint32_t(64)); // another subgroup size is another pipeline
61 CHECK(a.digest() != c.digest());
62 journal::Hasher d, e;
63 d.text("ab");
64 d.text("c");
65 e.text("a");
66 e.text("bc");
67 CHECK(d.digest() != e.digest()); // text is length-prefixed
68 return 0;
69}
70
71static int test_path() {
72 const auto path = journal::entry_path("dir", "cs", 0x0123456789abcdefull);
73 CHECK(path.filename().string() == "cs-0123456789abcdef.bin");
74 CHECK(journal::entry_path("dir", "cs", 1).filename().string() == "cs-0000000000000001.bin");
75 return 0;
76}
77
78static int test_files(const fs::path& dir) {
79 const auto id = identity();
80 const auto path = journal::entry_path(dir / "pipeline_cache.d", "cs", 42);
81 CHECK(journal::read_entry(path, id).empty()); // missing
82
83 // write_entry creates the directory and publishes the whole blob.
84 const auto data = blob(id, 1000);
85 CHECK(!journal::write_entry(path, data.data(), data.size()));
86 CHECK(journal::read_entry(path, id) == data);
87
88 // A second write replaces the first.
89 const auto next = blob(id, 10);
90 CHECK(!journal::write_entry(path, next.data(), next.size()));
91 CHECK(journal::read_entry(path, id) == next);
92
93 // Another device or driver (pipeline-cache UUID): not read, so the build starts over and rewrites it.
94 auto other = id;
95 other.cache_uuid[3] ^= 1;
96 CHECK(journal::read_entry(path, other).empty());
97 other = id;
98 other.device = 0x1234;
99 CHECK(journal::read_entry(path, other).empty());
100
101 // Truncated to less than a header, or over the read limit: not read.
102 {
103 std::ofstream(path, std::ios::binary | std::ios::trunc).write(next.data(), 16);
104 }
105 CHECK(journal::read_entry(path, id).empty());
106 CHECK(!journal::write_entry(path, data.data(), data.size()));
107 CHECK(journal::read_entry(path, id, data.size() - 1).empty());
108 CHECK(journal::read_entry(path, id, data.size()) == data);
109
110 CHECK(journal::directory_bytes(path.parent_path()) == data.size());
111 CHECK(journal::directory_bytes(dir / "missing") == 0);
112
113 // No staging files are left behind.
114 std::size_t files = 0;
115 for (const auto& item : fs::directory_iterator(path.parent_path())) {
116 (void)item;
117 ++files;
118 }
119 CHECK(files == 1);
120 return 0;
121}
122
123// When a build writes its file, and when the shared cache's answer was a compile.
124static int test_policy() {
125 // No file (or one the driver declined): always written, whatever the feedback or time.
126 CHECK(journal::should_write(false, 1, 0));
127 CHECK(journal::should_write(false, -1, 0));
128 CHECK(journal::should_write(false, 0, 0));
129 // From the file: the feedback decides; without feedback, the length of the driver call.
130 CHECK(!journal::should_write(true, 1, 5000));
131 CHECK(journal::should_write(true, 0, 1));
132 CHECK(!journal::should_write(true, -1, journal::unreported_compile_ms - 1));
133 CHECK(journal::should_write(true, -1, journal::unreported_compile_ms));
134 // FAIL_ON_PIPELINE_COMPILE_REQUIRED: a slow pipeline without the hit bit was compiled; a fast one came out of
135 // the driver's own disk cache, and a hit or no feedback is never taken for a compile.
136 CHECK(journal::probe_compiled(0, journal::probe_compile_ms));
137 CHECK(!journal::probe_compiled(0, journal::probe_compile_ms - 1));
138 CHECK(!journal::probe_compiled(1, 60000));
139 CHECK(!journal::probe_compiled(-1, 60000));
140 return 0;
141}
142
143static int test_accounting() {
144 CHECK(journal::replace_bytes(100, 0, 30) == 130); // a new file
145 CHECK(journal::replace_bytes(100, 40, 30) == 90); // a rewrite replaces the old size
146 CHECK(journal::replace_bytes(10, 40, 30) == 30); // never below zero
147 const auto t0 = fs::file_time_type::clock::now();
148 using std::chrono::hours;
149 const std::vector<journal::EntryInfo> entries = {
150 {"a", 40, t0 - hours(3)}, {"b", 40, t0 - hours(1)}, {"c", 40, t0 - hours(2)}, {"d", 40, t0}};
151 CHECK(journal::plan_eviction(entries, 160, 120).empty()); // at the budget: nothing goes
152 // Over it: least recently used first (a, then c), until the target holds.
153 const auto out = journal::plan_eviction(entries, 150, 100);
154 CHECK(out.size() == 2 && out[0] == 0 && out[1] == 2);
155 CHECK(journal::plan_eviction(entries, 0, 0).size() == 4);
156 return 0;
157}
158
159static int test_names() {
160 CHECK(journal::entry_name("cs-0123456789abcdef.bin"));
161 CHECK(!journal::entry_name("cs-0123456789abcde.bin")); // 15 digits
162 CHECK(!journal::entry_name("cs-0123456789ABCDEF.bin")); // entry_path writes lowercase
163 CHECK(!journal::entry_name("-0123456789abcdef.bin"));
164 CHECK(!journal::entry_name("pipeline_cache.session.bin"));
165 CHECK(journal::staging_name("cs-0123456789abcdef.bin.tmp.123456.0"));
166 CHECK(!journal::staging_name("cs-0123456789abcdef.bin.tmp.123456"));
167 CHECK(!journal::staging_name("cs-0123456789abcdef.bin.tmp.12x.0"));
168 CHECK(!journal::staging_name("pipeline_cache.session.bin.tmp.1.0")); // the session file's, swept elsewhere
169 return 0;
170}
171
172static void put_file(const fs::path& path, std::size_t bytes, fs::file_time_type when) {
173 std::ofstream(path, std::ios::binary | std::ios::trunc) << std::string(bytes, 'x');
174 fs::last_write_time(path, when);
175}
176
177static int test_tidy(const fs::path& root) {
178 const auto dir = root / "tidy";
179 fs::create_directories(dir);
180 const auto now = fs::file_time_type::clock::now();
181 using std::chrono::hours;
182 using std::chrono::minutes;
183 const auto a = journal::entry_path(dir, "cs", 0xa), b = journal::entry_path(dir, "cs", 0xb),
184 c = journal::entry_path(dir, "cs", 0xc);
185 put_file(a, 400, now - hours(5));
186 put_file(b, 400, now - hours(1));
187 put_file(c, 400, now - hours(3));
188 const fs::path old_stage = a.string() + ".tmp.111.0", new_stage = b.string() + ".tmp.222.1";
189 put_file(old_stage, 50, now - minutes(30));
190 put_file(new_stage, 50, now - minutes(2));
191 put_file(dir / "notes.txt", 999, now - hours(9));
192
193 // Under the budget: only the old staging file goes; the young one may still be being written.
194 auto result = journal::tidy(dir, 2000, minutes(10), now);
195 CHECK(result.swept == 1 && result.evicted == 0 && result.entries == 3 && result.bytes == 1200);
196 CHECK(!fs::exists(old_stage) && fs::exists(new_stage) && fs::exists(dir / "notes.txt"));
197
198 // Over it: the least recently used go until three quarters is left (1200 > 1000; 750 holds b alone).
199 result = journal::tidy(dir, 1000, minutes(10), now);
200 CHECK(result.evicted == 2 && result.entries == 1 && result.bytes == 400);
201 CHECK(!fs::exists(a) && !fs::exists(c) && fs::exists(b));
202
203 // A hit refreshes a file's last use, which keeps it over older ones.
204 put_file(a, 400, now - hours(5));
205 journal::touch(a, now);
206 put_file(c, 400, now - hours(3));
207 result = journal::tidy(dir, 1000, minutes(10), now); // 1200 again: c (3 h) is now the oldest, then b (1 h)
208 CHECK(fs::exists(a) && !fs::exists(c) && !fs::exists(b) && result.entries == 1);
209 CHECK(journal::tidy(root / "missing", 1000).entries == 0);
210 return 0;
211}
212
213static int test_entry_file(const fs::path& dir) {
214 const auto id = identity();
215 const auto path = journal::entry_path(dir, "cs", 77);
216 auto missing = journal::read_entry_file(path, id);
217 CHECK(missing.data.empty() && missing.bytes == 0);
218 // A foreign file still reports its size, which its rewrite replaces in the budget.
219 auto other = id;
220 other.device ^= 1;
221 const auto data = blob(other, 100);
222 CHECK(!journal::write_entry(path, data.data(), data.size()));
223 const auto foreign = journal::read_entry_file(path, id);
224 CHECK(foreign.data.empty() && foreign.bytes == data.size());
225 const auto own = journal::read_entry_file(path, other);
226 CHECK(own.data == data && own.bytes == data.size());
227 return 0;
228}
229
230static int test_overlay(const fs::path& dir) {
231 using std::chrono::hours;
232 const auto local = dir / "overlay" / "pipeline_cache.d", seed = dir / "seed";
233 const auto dst = journal::entry_path(local, "cs", 1), src = journal::entry_path(seed, "cs", 1);
234 const auto id = identity();
235 auto wrong = id;
236 wrong.cache_uuid[0] ^= 1;
237 const auto donor = blob(id, 32), rebuilt = blob(id, 53), stale = blob(wrong, 45);
238 CHECK(!journal::write_entry(src, donor.data(), donor.size()));
239 const auto now = fs::file_time_type::clock::now();
240 fs::last_write_time(src, now - hours(8));
241 const auto donor_time = fs::last_write_time(src);
242 const auto roots = journal::resolve_roots(local, seed);
243 CHECK(!roots.writable.empty() && fs::equivalent(roots.seed, seed));
244
245 // No local entry: donor bytes may seed the driver, but do not count against the writable budget.
246 constexpr auto runtime = journal::ReadRole::runtime;
247 constexpr auto builder = journal::ReadRole::materialize_local;
248 auto entry = journal::read_with_seed(dst, roots.seed, id, runtime);
249 CHECK(entry.from_seed && entry.data == donor && entry.bytes == 0 && entry.used == fs::file_time_type{});
250 // Same roots, but the host building a requested local file must still see a miss.
251 CHECK(!journal::entry_usable(dst, id) && journal::entry_usable(src, id));
252 const auto missing_build = journal::read_with_seed(dst, roots.seed, id, builder);
253 CHECK(missing_build.data.empty() && !missing_build.from_seed && missing_build.bytes == 0);
254 journal::touch_local_hit(dst, entry, now);
255 CHECK(!fs::exists(local) && fs::last_write_time(src) == donor_time);
256 CHECK(journal::replace_bytes(1000, entry.bytes, rebuilt.size()) == 1000 + rebuilt.size());
257 CHECK(journal::read_with_seed(dst, {}, id, runtime).data.empty());
258 CHECK(journal::read_with_seed(dst, seed, wrong, runtime).data.empty());
259 CHECK(journal::read_with_seed(dst, seed, id, runtime, donor.size() - 1).data.empty());
260 CHECK(journal::read_with_seed(dst, seed, id, runtime, donor.size()).data == donor);
261 CHECK(journal::read_with_seed(journal::entry_path(local, "cs", 2), seed, id, runtime).data.empty());
262
263 // Even with a stale local object the recorded byte count and LRU timestamp belong to that object.
264 CHECK(!journal::write_entry(dst, stale.data(), stale.size()));
265 fs::last_write_time(dst, now - hours(3));
266 const auto stale_time = fs::last_write_time(dst);
267 entry = journal::read_with_seed(dst, seed, id, runtime);
268 CHECK(entry.from_seed && entry.data == donor && entry.bytes == stale.size() && entry.used == stale_time);
269 const auto stale_build = journal::read_with_seed(dst, roots.seed, id, builder);
270 CHECK(stale_build.data.empty() && !stale_build.from_seed && stale_build.bytes == stale.size() &&
271 stale_build.used == stale_time && !journal::entry_usable(dst, id));
272 journal::touch_local_hit(dst, entry, now);
273 CHECK(fs::last_write_time(dst) == stale_time && fs::last_write_time(src) == donor_time);
274 CHECK(journal::read_entry(dst, wrong) == stale); // neither promoted nor rewritten by the hit
275 auto used = journal::tidy(roots.writable, stale.size());
276 CHECK(used.entries == 1 && used.bytes == stale.size() && used.evicted == 0);
277 CHECK(journal::replace_bytes(used.bytes, entry.bytes, rebuilt.size()) == rebuilt.size());
278
279 CHECK(!journal::write_entry(dst, rebuilt.data(), 3)); // truncated local is not a seed hit on the local file
280 entry = journal::read_with_seed(dst, seed, id, runtime);
281 CHECK(entry.from_seed && entry.data == donor && entry.bytes == 3 && fs::file_size(dst) == 3);
282 CHECK(!journal::write_entry(dst, rebuilt.data(), rebuilt.size()));
283 fs::last_write_time(dst, now - hours(3));
284 entry = journal::read_with_seed(dst, seed, id, runtime);
285 CHECK(!entry.from_seed && entry.data == rebuilt && entry.bytes == rebuilt.size());
286 CHECK(journal::entry_usable(dst, id));
287 CHECK(!journal::entry_usable(dst, id, rebuilt.size() - 1) && journal::entry_usable(dst, id, rebuilt.size()));
288 const auto ready_build = journal::read_with_seed(dst, roots.seed, id, builder);
289 CHECK(!ready_build.from_seed && ready_build.data == rebuilt && ready_build.bytes == rebuilt.size());
290 journal::touch_local_hit(dst, entry, now);
291 const auto refreshed = fs::last_write_time(dst);
292 CHECK(refreshed > entry.used);
293 entry = journal::read_with_seed(dst, seed, id, runtime);
294 journal::touch_local_hit(dst, entry, now + std::chrono::minutes(30));
295 CHECK(fs::last_write_time(dst) == refreshed);
296 used = journal::tidy(roots.writable, 0);
297 CHECK(used.evicted == 1 && used.bytes == 0 && !fs::exists(dst));
298 CHECK(journal::read_entry(src, id) == donor && fs::last_write_time(src) == donor_time);
299
300 const auto unset = journal::resolve_roots(local, {});
301 CHECK(unset.writable == local && unset.seed.empty());
302 const auto disabled = [](const fs::path& sink, const fs::path& source) {
303 const auto r = journal::resolve_roots(sink, source);
304 return r.writable.empty() && r.seed.empty();
305 };
306 CHECK(disabled({}, seed) && disabled(local, "relative") && disabled(local, dir / "no-seed"));
307 CHECK(disabled(local, src) && disabled(src, seed));
308 CHECK(disabled(seed / ".", seed) && disabled(seed / "missing" / "journal", seed) && disabled(dir, seed));
309#ifdef _WIN32
310 if (fs::exists(dir / "SEED")) CHECK(disabled(dir / "SEED", seed));
311#endif
312 return 0;
313}
314
315int main() {
316 const auto dir = fs::temp_directory_path() /
317 ("leonida_pipeline_journal_test_" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
318 std::error_code ec;
319 fs::create_directories(dir, ec);
320 if (ec) {
321 std::fprintf(stderr, "cannot create %s\n", dir.string().c_str());
322 return 1;
323 }
324 int failed = test_hash();
325 if (!failed) failed = test_path();
326 if (!failed) failed = test_files(dir);
327 if (!failed) failed = test_policy();
328 if (!failed) failed = test_accounting();
329 if (!failed) failed = test_names();
330 if (!failed) failed = test_tidy(dir);
331 if (!failed) failed = test_entry_file(dir);
332 if (!failed) failed = test_overlay(dir);
333 fs::remove_all(dir, ec);
334 if (failed) return failed;
335 std::printf("pipeline_cache_journal_test: ok\n");
336 return 0;
337}
diff --git a/runtime/test/replay_pipeline_compile_unlock_test.cpp b/runtime/test/replay_pipeline_compile_unlock_test.cpp
new file mode 100644
index 000000000..045f81864
--- /dev/null
+++ b/runtime/test/replay_pipeline_compile_unlock_test.cpp
@@ -0,0 +1,291 @@
1// VulkanQueue::execute_now() releases resource_mutex_ and tracker_mutex_ while compiling unbuilt pipelines under
2// pipeline_mutex_ alone, so add_resource()/remove_resource() and other queues do not stall behind shader compiles,
3// remove_pipeline() still waits until compilation finishes, failed non-strict dispatches build only once, and
4// pass-1 re-preparation observes resource updates made while resource_mutex_ was unlocked. No GPU or game data.
5#include "../src/vulkan_backend.h"
6
7#include <atomic>
8#include <chrono>
9#include <condition_variable>
10#include <cstdint>
11#include <cstdio>
12#include <memory>
13#include <mutex>
14#include <string_view>
15#include <thread>
16#include <vector>
17
18#define EXPECT(condition) do { \
19 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
20} while (0)
21
22namespace {
23
24using namespace leonida;
25
26template<class T>
27T handle(std::uintptr_t n) {
28 return reinterpret_cast<T>(n);
29}
30
31VulkanDeviceFunctions driver{};
32std::atomic<std::uintptr_t> next_handle{10};
33std::mutex record_mutex;
34std::vector<std::pair<VkBuffer, VkBuffer>> recorded_copies;
35
36PFN_vkVoidFunction VKAPI_CALL mock_get_device_proc(VkDevice, const char* name) {
37#define MOCK_DEVICE_FUNCTION(n) \
38 if (std::string_view(name) == #n) return reinterpret_cast<PFN_vkVoidFunction>(driver.n);
39 LEONIDA_VK_DEVICE_FUNCTIONS(MOCK_DEVICE_FUNCTION)
40#undef MOCK_DEVICE_FUNCTION
41 return nullptr;
42}
43
44void init_mock_driver() {
45 driver = {};
46 driver.vkCreateCommandPool = +[](VkDevice, const VkCommandPoolCreateInfo*, const VkAllocationCallbacks*,
47 VkCommandPool* out) {
48 *out = handle<VkCommandPool>(next_handle.fetch_add(1));
49 return VK_SUCCESS;
50 };
51 driver.vkDestroyCommandPool = +[](VkDevice, VkCommandPool, const VkAllocationCallbacks*) {};
52 driver.vkCreateSemaphore = +[](VkDevice, const VkSemaphoreCreateInfo*, const VkAllocationCallbacks*,
53 VkSemaphore* out) {
54 *out = handle<VkSemaphore>(next_handle.fetch_add(1));
55 return VK_SUCCESS;
56 };
57 driver.vkDestroySemaphore = +[](VkDevice, VkSemaphore, const VkAllocationCallbacks*) {};
58 driver.vkGetSemaphoreCounterValue = +[](VkDevice, VkSemaphore, std::uint64_t* value) {
59 *value = UINT64_MAX;
60 return VK_SUCCESS;
61 };
62 driver.vkQueueWaitIdle = +[](VkQueue) { return VK_SUCCESS; };
63 driver.vkAllocateCommandBuffers = +[](VkDevice, const VkCommandBufferAllocateInfo* info, VkCommandBuffer* out) {
64 for (std::uint32_t i = 0; i < info->commandBufferCount; ++i)
65 out[i] = handle<VkCommandBuffer>(next_handle.fetch_add(1));
66 return VK_SUCCESS;
67 };
68 driver.vkResetCommandBuffer = +[](VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; };
69 driver.vkBeginCommandBuffer = +[](VkCommandBuffer, const VkCommandBufferBeginInfo*) { return VK_SUCCESS; };
70 driver.vkEndCommandBuffer = +[](VkCommandBuffer) { return VK_SUCCESS; };
71 driver.vkQueueSubmit = +[](VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) { return VK_SUCCESS; };
72 driver.vkCmdPipelineBarrier = +[](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags,
73 std::uint32_t, const VkMemoryBarrier*, std::uint32_t,
74 const VkBufferMemoryBarrier*, std::uint32_t, const VkImageMemoryBarrier*) {};
75 driver.vkCmdBindPipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {};
76 driver.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t,
77 std::uint32_t, const void*) {};
78 driver.vkCmdDispatch = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) {};
79 driver.vkCmdCopyBuffer = +[](VkCommandBuffer, VkBuffer src, VkBuffer dst, std::uint32_t, const VkBufferCopy*) {
80 std::lock_guard lock(record_mutex);
81 recorded_copies.emplace_back(src, dst);
82 };
83 driver.vkCmdCopyBufferToImage = +[](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout, std::uint32_t,
84 const VkBufferImageCopy*) {};
85 driver.vkCmdCopyImageToBuffer = +[](VkCommandBuffer, VkImage, VkImageLayout, VkBuffer, std::uint32_t,
86 const VkBufferImageCopy*) {};
87 driver.vkCmdCopyImage = +[](VkCommandBuffer, VkImage, VkImageLayout, VkImage, VkImageLayout, std::uint32_t,
88 const VkImageCopy*) {};
89}
90
91struct SlowPipeline {
92 std::mutex mutex;
93 std::condition_variable cv;
94 bool entered = false;
95 bool allow_finish = false;
96 bool fail = false;
97 std::atomic<int> builds{0};
98 VkPipeline handle_out = VK_NULL_HANDLE;
99
100 VkPipeline build() {
101 builds.fetch_add(1, std::memory_order_relaxed);
102 {
103 std::unique_lock lock(mutex);
104 entered = true;
105 cv.notify_all();
106 cv.wait(lock, [this] { return allow_finish; });
107 if (!fail) handle_out = handle<VkPipeline>(0x7001);
108 return handle_out;
109 }
110 }
111
112 VkPipeline find() {
113 std::unique_lock lock(mutex, std::try_to_lock);
114 return lock.owns_lock() ? handle_out : VK_NULL_HANDLE;
115 }
116
117 void release() {
118 std::lock_guard lock(mutex);
119 allow_finish = true;
120 cv.notify_all();
121 }
122};
123
124// Exercises concurrent add_resource/remove_resource, a second queue submission, resource replacement observed on
125// pass-1 re-prepare, and remove_pipeline() waiting on pipeline_mutex_ while a slow compile runs.
126int test_unlocks_resources_during_compile(bool with_workers) {
127 {
128 std::lock_guard lock(record_mutex);
129 recorded_copies.clear();
130 }
131 VulkanContext context(mock_get_device_proc, handle<VkDevice>(1), false);
132 if (with_workers) context.set_pipeline_workers(std::make_unique<PipelineWorkers>(2));
133
134 ResourceBinding src{};
135 src.buffer = handle<VkBuffer>(101);
136 src.size = 64;
137 ResourceBinding dst_old{};
138 dst_old.buffer = handle<VkBuffer>(102);
139 dst_old.size = 64;
140 ResourceBinding dst_new{};
141 dst_new.buffer = handle<VkBuffer>(202);
142 dst_new.size = 64;
143 context.add_resource(1, src);
144 context.add_resource(2, dst_old);
145
146 SlowPipeline slow;
147 constexpr std::uintptr_t slow_id = 0x100;
148 constexpr std::uintptr_t fast_id = 0x200;
149
150 ComputePipeline slow_pso{};
151 slow_pso.layout = handle<VkPipelineLayout>(5);
152 slow_pso.build_context = &slow;
153 slow_pso.build = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->build(); };
154 slow_pso.built = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->find(); };
155 context.add_pipeline(slow_id, slow_pso);
156
157 ComputePipeline fast_pso{};
158 fast_pso.layout = handle<VkPipelineLayout>(5);
159 fast_pso.pipeline = handle<VkPipeline>(0x8001);
160 context.add_pipeline(fast_id, fast_pso);
161
162 VulkanQueue queue_a(context, handle<VkQueue>(1), 0, VulkanQueue::QueueKind::compute);
163 VulkanQueue queue_b(context, handle<VkQueue>(2), 0, VulkanQueue::QueueKind::compute);
164 EXPECT(queue_a.ok() && queue_b.ok());
165
166 CommandList list_a;
167 EXPECT(list_a.dispatch({slow_id, {}, 1, 1, 1}));
168 EXPECT(list_a.copy_buffer({2, 0, 1, 0, 64}));
169 EXPECT(list_a.close());
170
171 CommandList list_b;
172 EXPECT(list_b.dispatch({fast_id, {}, 1, 1, 1}));
173 EXPECT(list_b.close());
174
175 ReplayResult result_a = ReplayResult::unsupported;
176 std::thread thread_a([&] {
177 const CommandList* ptr = &list_a;
178 result_a = queue_a.execute({&ptr, 1});
179 });
180
181 // Wait for thread_a (or a PipelineWorkers thread) to enter slow.build().
182 {
183 std::unique_lock lock(slow.mutex);
184 const bool entered = slow.cv.wait_for(lock, std::chrono::seconds(5), [&] { return slow.entered; });
185 if (!entered) {
186 slow.allow_finish = true;
187 slow.cv.notify_all();
188 lock.unlock();
189 thread_a.join();
190 EXPECT(false);
191 }
192 }
193
194 // While compilation is paused:
195 // 1. add_resource() / remove_resource() and a second queue submission must complete without blocking.
196 std::atomic<bool> resources_unblocked{false};
197 ReplayResult result_b = ReplayResult::unsupported;
198 std::thread resource_thread([&] {
199 ResourceBinding temp{};
200 temp.buffer = handle<VkBuffer>(303);
201 temp.size = 64;
202 context.add_resource(3, temp);
203 context.remove_resource(3);
204 // Replace resource 2 while resource_mutex_ is unlocked so pass-1 re-prepare must bind dst_new.
205 context.remove_resource(2);
206 context.add_resource(2, dst_new);
207 const CommandList* ptr = &list_b;
208 result_b = queue_b.execute({&ptr, 1});
209 resources_unblocked.store(true, std::memory_order_release);
210 });
211
212 const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2);
213 while (!resources_unblocked.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < deadline)
214 std::this_thread::sleep_for(std::chrono::milliseconds(5));
215
216 if (!resources_unblocked.load(std::memory_order_acquire)) {
217 slow.release();
218 resource_thread.join();
219 thread_a.join();
220 EXPECT(false);
221 }
222 resource_thread.join();
223 EXPECT(result_b == ReplayResult::success);
224
225 // 2. remove_pipeline() must wait on pipeline_mutex_ until compilation finishes (protecting ComputePipeline*).
226 std::atomic<bool> remove_started{false};
227 std::atomic<bool> remove_finished{false};
228 std::thread remove_thread([&] {
229 remove_started.store(true, std::memory_order_release);
230 context.remove_pipeline(slow_id);
231 remove_finished.store(true, std::memory_order_release);
232 });
233 while (!remove_started.load(std::memory_order_acquire))
234 std::this_thread::sleep_for(std::chrono::milliseconds(1));
235 std::this_thread::sleep_for(std::chrono::milliseconds(30));
236 const bool removed_early = remove_finished.load(std::memory_order_acquire);
237
238 slow.release();
239 thread_a.join();
240 remove_thread.join();
241
242 EXPECT(!removed_early);
243 EXPECT(remove_finished.load(std::memory_order_acquire));
244 EXPECT(result_a == ReplayResult::success);
245 EXPECT(slow.builds.load() == 1);
246 {
247 std::lock_guard lock(record_mutex);
248 EXPECT(recorded_copies.size() == 1);
249 EXPECT(recorded_copies[0].first == src.buffer && recorded_copies[0].second == dst_new.buffer);
250 }
251 return 0;
252}
253
254// A non-strict failed compute dispatch must not invoke build() a second time on pass-1 re-prepare.
255int test_failed_compute_dispatch_built_once() {
256 VulkanContext context(mock_get_device_proc, handle<VkDevice>(1), false);
257 SlowPipeline failing;
258 failing.fail = true;
259 failing.allow_finish = true;
260
261 constexpr std::uintptr_t fail_id = 0x300;
262 ComputePipeline pso{};
263 pso.layout = handle<VkPipelineLayout>(5);
264 pso.build_context = &failing;
265 pso.build = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->build(); };
266 pso.built = [](void* ctx) { return static_cast<SlowPipeline*>(ctx)->find(); };
267 context.add_pipeline(fail_id, pso);
268
269 VulkanQueue queue(context, handle<VkQueue>(3), 0, VulkanQueue::QueueKind::compute);
270 EXPECT(queue.ok());
271
272 CommandList list;
273 EXPECT(list.dispatch({fail_id, {}, 1, 1, 1}));
274 EXPECT(list.close());
275 const CommandList* ptr = &list;
276 const ReplayResult r = queue.execute({&ptr, 1});
277 EXPECT(r == (strict_replay() ? ReplayResult::unresolved_resource : ReplayResult::success));
278 EXPECT(failing.builds.load() == 1);
279 return 0;
280}
281
282} // namespace
283
284int main() {
285 init_mock_driver();
286 if (test_unlocks_resources_during_compile(true) != 0) return 1;
287 if (test_unlocks_resources_during_compile(false) != 0) return 1;
288 if (test_failed_compute_dispatch_built_once() != 0) return 1;
289 std::printf("replay_pipeline_compile_unlock_test: passed\n");
290 return 0;
291}
diff --git a/runtime/test/replay_pipeline_compiles_test.cpp b/runtime/test/replay_pipeline_compiles_test.cpp
index 35b6057ed..a8983f7ce 100644
--- a/runtime/test/replay_pipeline_compiles_test.cpp
+++ b/runtime/test/replay_pipeline_compiles_test.cpp
@@ -2,13 +2,16 @@
2// prepared twice, once with every pipeline built where prepare() meets it and once with them left to PipelineCompiles 2// prepared twice, once with every pipeline built where prepare() meets it and once with them left to PipelineCompiles
3// and built on PipelineWorkers. Both have to give the same result, the same pipeline to every draw and dispatch, the same 3// and built on PipelineWorkers. Both have to give the same result, the same pipeline to every draw and dispatch, the same
4// commands dropped, and the same pipelines built, each once. Fixed cases, then random ones. Run a second time with 4// commands dropped, and the same pipelines built, each once. Fixed cases, then random ones. Run a second time with
5// LEONIDA_STRICT_REPLAY=1, where a dispatch without a pipeline fails its list. No GPU: pipelines and resources are fakes. 5// LEONIDA_STRICT_REPLAY=1, where a dispatch without a pipeline fails its list. Also which large pipelines compile at once
6// within a budget (PipelineCompiles::build). No GPU: pipelines and resources are fakes.
7#include "../src/large_module_gate.h"
6#include "../src/pipeline_workers.h" 8#include "../src/pipeline_workers.h"
7#include "../src/vulkan_replay.h" 9#include "../src/vulkan_replay.h"
8 10
9#include <algorithm> 11#include <algorithm>
10#include <atomic> 12#include <atomic>
11#include <chrono> 13#include <chrono>
14#include <condition_variable>
12#include <cstdint> 15#include <cstdint>
13#include <cstdio> 16#include <cstdio>
14#include <functional> 17#include <functional>
@@ -39,9 +42,10 @@ T handle(std::uintptr_t n) {
39constexpr ResourceId color_id = 1, depth_id = 2, arguments_id = 3; 42constexpr ResourceId color_id = 1, depth_id = 2, arguments_id = 3;
40constexpr std::uint64_t bad_va = 0xbad0000; 43constexpr std::uint64_t bad_va = 0xbad0000;
41 44
42// The large pipelines being built now, and how often there were two. 45// The large pipelines being built now, and how often there were two, where they are to compile one after another.
43std::atomic<int> large_now = 0; 46std::atomic<int> large_now = 0;
44std::atomic<int> large_together = 0; 47std::atomic<int> large_together = 0;
48std::atomic<bool> large_one_at_a_time = true;
45 49
46// What a pipeline state owns: its variants, built on demand under its own lock, and what was asked of it. 50// What a pipeline state owns: its variants, built on demand under its own lock, and what was asked of it.
47struct Owner { 51struct Owner {
@@ -60,7 +64,7 @@ struct Owner {
60 if (failed && compute) return VK_NULL_HANDLE; // a refused compute pipeline is not tried again 64 if (failed && compute) return VK_NULL_HANDLE; // a refused compute pipeline is not tried again
61 attempts.push_back(flags); 65 attempts.push_back(flags);
62 if (large) { 66 if (large) {
63 if (++large_now > 1) ++large_together; 67 if (++large_now > 1 && large_one_at_a_time) ++large_together;
64 const auto end = std::chrono::steady_clock::now() + std::chrono::microseconds(20); 68 const auto end = std::chrono::steady_clock::now() + std::chrono::microseconds(20);
65 while (std::chrono::steady_clock::now() < end) std::this_thread::yield(); 69 while (std::chrono::steady_clock::now() < end) std::this_thread::yield();
66 --large_now; 70 --large_now;
@@ -84,6 +88,7 @@ struct PipelineSpec {
84 bool fails = false; 88 bool fails = false;
85 bool with_built = true; 89 bool with_built = true;
86 bool large = false; 90 bool large = false;
91 std::uint64_t estimate = 0;
87 bool skipped = false; // compute: never built, its dispatches are dropped 92 bool skipped = false; // compute: never built, its dispatches are dropped
88 bool bindless = false; // compute: needs a set 0, which these functions cannot bind 93 bool bindless = false; // compute: needs a set 0, which these functions cannot bind
89 bool async = false; // its null handle may be waiting for another worker: never left to PipelineCompiles 94 bool async = false; // its null handle may be waiting for another worker: never left to PipelineCompiles
@@ -114,6 +119,7 @@ struct Registry {
114 ComputePipeline p{}; 119 ComputePipeline p{};
115 p.layout = handle<VkPipelineLayout>(7); 120 p.layout = handle<VkPipelineLayout>(7);
116 p.large = spec.large; 121 p.large = spec.large;
122 p.estimate = spec.estimate;
117 p.async_build = spec.async; 123 p.async_build = spec.async;
118 p.skipped = spec.skipped; 124 p.skipped = spec.skipped;
119 if (spec.bindless) p.bindless_set = handle<VkDescriptorSet>(6); 125 if (spec.bindless) p.bindless_set = handle<VkDescriptorSet>(6);
@@ -138,6 +144,7 @@ struct Registry {
138 } 144 }
139 p.mesh = spec.mesh; 145 p.mesh = spec.mesh;
140 p.large = spec.large; 146 p.large = spec.large;
147 p.estimate = spec.estimate;
141 p.vertex_slots = spec.vertices ? 1 : 0; 148 p.vertex_slots = spec.vertices ? 1 : 0;
142 if (spec.rectangle) p.rectangle_variant_topology = 17; 149 if (spec.rectangle) p.rectangle_variant_topology = 17;
143 p.variant = [&owner](std::uint32_t flags) { return owner.build(flags); }; 150 p.variant = [&owner](std::uint32_t flags) { return owner.build(flags); };
@@ -273,12 +280,12 @@ struct Outcome {
273 std::multiset<std::pair<std::uintptr_t, std::uint32_t>> built; 280 std::multiset<std::pair<std::uintptr_t, std::uint32_t>> built;
274 std::size_t jobs = 0; 281 std::size_t jobs = 0;
275 std::size_t runs = 0; 282 std::size_t runs = 0;
276 std::size_t units = 0; // what run() was given: the large pipelines together are one 283 std::size_t units = 0; // what run() was given: the large pipelines together are one (no budget)
277}; 284};
278 285
279// `workers` null: prepare() builds each pipeline itself, as without workers. 286// `workers` null: prepare() builds each pipeline itself, as without workers.
280Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<PipelineSpec>& specs, 287Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<PipelineSpec>& specs,
281 PipelineWorkers* workers) { 288 PipelineWorkers* workers, const std::function<std::uint64_t()>& budget = {}) {
282 Registry registry(specs); 289 Registry registry(specs);
283 ReplayFunctions vk = functions(registry); 290 ReplayFunctions vk = functions(registry);
284 PipelineCompiles compiles; 291 PipelineCompiles compiles;
@@ -294,7 +301,8 @@ Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<Pip
294 ++out.runs; 301 ++out.runs;
295 out.units = count; 302 out.units = count;
296 workers->run(count, job); 303 workers->run(count, job);
297 }); 304 },
305 budget);
298 if (out.result == ReplayResult::success) 306 if (out.result == ReplayResult::success)
299 for (std::size_t i = 0; i < lists.size(); ++i) { 307 for (std::size_t i = 0; i < lists.size(); ++i) {
300 for (std::size_t c = 0; c < prepared[i].commands.size(); ++c) { 308 for (std::size_t c = 0; c < prepared[i].commands.size(); ++c) {
@@ -312,10 +320,13 @@ Outcome prepare_all(const std::vector<CommandList>& lists, const std::vector<Pip
312} 320}
313 321
314Outcome compare(const std::string& name, const std::vector<PipelineSpec>& specs, 322Outcome compare(const std::string& name, const std::vector<PipelineSpec>& specs,
315 const std::vector<std::vector<CommandSpec>>& commands, PipelineWorkers& workers) { 323 const std::vector<std::vector<CommandSpec>>& commands, PipelineWorkers& workers,
324 const std::function<std::uint64_t()>& budget = {}) {
316 const auto lists = record(commands); 325 const auto lists = record(commands);
317 const Outcome serial = prepare_all(lists, specs, nullptr); 326 const Outcome serial = prepare_all(lists, specs, nullptr);
318 const Outcome together = prepare_all(lists, specs, &workers); 327 large_one_at_a_time = !budget;
328 const Outcome together = prepare_all(lists, specs, &workers, budget);
329 large_one_at_a_time = true;
319 check(serial.result == together.result, name + ": another result"); 330 check(serial.result == together.result, name + ": another result");
320 check(serial.pipelines == together.pipelines, name + ": another pipeline for a draw or dispatch"); 331 check(serial.pipelines == together.pipelines, name + ": another pipeline for a draw or dispatch");
321 if (serial.result == ReplayResult::success) 332 if (serial.result == ReplayResult::success)
@@ -516,6 +527,7 @@ void random_submissions(PipelineWorkers& workers) {
516 s.with_built = chance(90); 527 s.with_built = chance(90);
517 s.async = chance(8); 528 s.async = chance(8);
518 s.large = chance(15); 529 s.large = chance(15);
530 s.estimate = rng() % 12;
519 s.bindless = chance(2); 531 s.bindless = chance(2);
520 s.skipped = s.compute && chance(4); 532 s.skipped = s.compute && chance(4);
521 if (s.skipped) s.fails = s.pending = true; 533 if (s.skipped) s.fails = s.pending = true;
@@ -540,13 +552,352 @@ void random_submissions(PipelineWorkers& workers) {
540 c.mesh = c.pipeline <= specs.size() && specs[c.pipeline - 1].mesh; 552 c.mesh = c.pipeline <= specs.size() && specs[c.pipeline - 1].mesh;
541 list.push_back(c); 553 list.push_back(c);
542 } 554 }
543 succeeded += compare("random submission " + std::to_string(round), specs, commands, workers).result == 555 const std::uint64_t memory = rng() % 24; // 0: no budget
544 ReplayResult::success; 556 const auto budget = [memory] { return memory; };
557 const bool limited = chance(50);
558 succeeded += compare("random submission " + std::to_string(round), specs, commands, workers,
559 limited ? std::function<std::uint64_t()>(budget) : std::function<std::uint64_t()>{})
560 .result == ReplayResult::success;
545 } 561 }
546 check(succeeded > 1000 && succeeded < 2900, "the random submissions both succeed and fail: " + 562 check(succeeded > 1000 && succeeded < 2900, "the random submissions both succeed and fail: " +
547 std::to_string(succeeded)); 563 std::to_string(succeeded));
548} 564}
549 565
566// Re-preparing after a prior compile pass reuses prior outcomes (both built handles and non-strict failed compute
567// dispatches) without re-invoking build() or failing the submission.
568void prior_compiles_reuse(PipelineWorkers& workers) {
569 Registry registry({
570 {.compute = true, .pending = true, .fails = false, .with_built = true},
571 {.compute = true, .pending = true, .fails = true, .with_built = true},
572 });
573 const std::vector<CommandList> lists = record({{
574 CommandSpec{.kind = CommandSpec::dispatch, .pipeline = 1},
575 CommandSpec{.kind = CommandSpec::dispatch, .pipeline = 2},
576 }});
577 std::vector<PreparedList> prepared(1);
578 ReplayFunctions vk = functions(registry);
579 PipelineCompiles first;
580 vk.compiles = &first;
581 const ReplayResult r0 = prepare(lists[0], resolve, vk, prepared[0]);
582 check(r0 == ReplayResult::success && first.size() == 2, "prior_compiles_reuse: pass 0 collected both");
583 first.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { workers.run(count, job); });
584 const ReplayResult c0 = check_compiled_pipelines(first, r0);
585 if (strict_replay()) {
586 check(c0 == ReplayResult::unresolved_resource, "prior_compiles_reuse: strict fails on failed dispatch");
587 return;
588 }
589 check(c0 == ReplayResult::success, "prior_compiles_reuse: non-strict tolerates failed dispatch");
590 check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1,
591 "prior_compiles_reuse: each pipeline built once on pass 0");
592 // Reset the failed flag on owner 2 so any redundant build() call on pass 1 would be caught in attempts.
593 registry.owners[1]->failed = false;
594
595 PipelineCompiles second;
596 vk.compiles = &second;
597 const ReplayResult r1 = prepare(lists[0], resolve, vk, prepared[0]);
598 const ReplayResult b1 = build_pipelines(
599 second, std::span(prepared), r1,
600 [&](std::size_t count, const std::function<void(std::size_t)>& job) { workers.run(count, job); },
601 {}, &first);
602 check(b1 == ReplayResult::success, "prior_compiles_reuse: pass 1 succeeded");
603 check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1,
604 "prior_compiles_reuse: pass 1 did not re-invoke build() on prior failure");
605 check(prepared[0].commands[0].pipeline.pipeline == handle<VkPipeline>(0x1001),
606 "prior_compiles_reuse: built compute handle attached");
607 check(prepared[0].commands[1].pipeline.pipeline == VK_NULL_HANDLE,
608 "prior_compiles_reuse: failed compute dispatch stays dropped");
609}
610
611// Serial compilation stops at the first refused graphics draw (matching pre-unlock serial semantics and
612// d3d12_pipeline_workers::refused_graphics) instead of compiling later pipelines in the same submission.
613void serial_stops_at_refused_draw() {
614 Registry registry({
615 {.compute = false, .pending = true, .fails = false},
616 {.compute = false, .pending = true, .fails = true},
617 {.compute = false, .pending = true, .fails = false},
618 {.compute = false, .pending = true, .fails = false},
619 });
620 const std::vector<CommandList> lists = record({{
621 CommandSpec{.kind = CommandSpec::draw, .pipeline = 1},
622 CommandSpec{.kind = CommandSpec::draw, .pipeline = 2},
623 CommandSpec{.kind = CommandSpec::draw, .pipeline = 3},
624 CommandSpec{.kind = CommandSpec::draw, .pipeline = 4},
625 }});
626 std::vector<PreparedList> prepared(1);
627 ReplayFunctions vk = functions(registry);
628 PipelineCompiles compiles;
629 vk.compiles = &compiles;
630 const ReplayResult r = prepare(lists[0], resolve, vk, prepared[0]);
631 check(r == ReplayResult::success && compiles.size() == 4, "serial_stops: collected all 4 draws");
632 const ReplayResult out = build_pipelines_serial(compiles, std::span(prepared), r);
633 check(out == ReplayResult::unsupported, "serial_stops: refused draw returns unsupported");
634 check(registry.owners[0]->attempts.size() == 1 && registry.owners[1]->attempts.size() == 1,
635 "serial_stops: built first draw and attempted refused second draw");
636 check(registry.owners[2]->attempts.empty() && registry.owners[3]->attempts.empty(),
637 "serial_stops: did not compile draws past the first refused draw");
638}
639
640// ---- Large pipelines within a budget. ----
641
642// Pipelines that note the order they start in. One with `hold` does not end before `release` is called.
643struct Shop {
644 struct Item {
645 Shop* shop = nullptr;
646 ComputePipeline pipeline{};
647 std::string name;
648 bool hold = false;
649 };
650 std::mutex mutex;
651 std::condition_variable changed;
652 std::vector<std::string> started;
653 std::vector<std::unique_ptr<Item>> items;
654 bool released = false;
655 int large_in = 0, most_large_in = 0;
656 LargeModuleGate* gate = nullptr; // set: a large one takes its place there, as in the layer
657
658 ComputePipeline& add(const std::string& name, std::uint64_t estimate, bool large, bool hold = false) {
659 auto& item = *items.emplace_back(std::make_unique<Item>());
660 item.shop = this;
661 item.name = name;
662 item.hold = hold;
663 item.pipeline.large = large;
664 item.pipeline.estimate = estimate;
665 item.pipeline.build_context = &item;
666 item.pipeline.build = [](void* context) {
667 auto& i = *static_cast<Item*>(context);
668 Shop& shop = *i.shop;
669 LargeModuleGate::Ticket place;
670 if (shop.gate && i.pipeline.large) place = LargeModuleGate::Ticket(*shop.gate, i.pipeline.estimate);
671 std::unique_lock lock(shop.mutex);
672 shop.started.push_back(i.name);
673 if (i.pipeline.large) shop.most_large_in = std::max(shop.most_large_in, ++shop.large_in);
674 shop.changed.notify_all();
675 if (i.hold) shop.changed.wait_for(lock, std::chrono::seconds(10), [&] { return shop.released; });
676 if (i.pipeline.large) --shop.large_in;
677 return handle<VkPipeline>(std::uintptr_t(&i) | 1);
678 };
679 return item.pipeline;
680 }
681 void fill(PipelineCompiles& compiles) {
682 for (auto& item : items) compiles.add(item->pipeline, PipelineCompiles::User::dispatch);
683 }
684 // Whether `count` have started, within 10 s.
685 bool wait_started(std::size_t count) {
686 std::unique_lock lock(mutex);
687 return changed.wait_for(lock, std::chrono::seconds(10), [&] { return started.size() >= count; });
688 }
689 void release() {
690 std::lock_guard lock(mutex);
691 released = true;
692 changed.notify_all();
693 }
694};
695
696// On `threads` threads, which take the jobs in order.
697void on_threads(unsigned threads, std::size_t count, const std::function<void(std::size_t)>& job) {
698 std::atomic<std::size_t> next = 0;
699 std::vector<std::thread> workers;
700 for (unsigned t = 0; t < threads; ++t)
701 workers.emplace_back([&] {
702 for (std::size_t i; (i = next++) < count;) job(i);
703 });
704 for (auto& w : workers) w.join();
705}
706
707using Names = std::vector<std::string>;
708
709// The order and the jobs of the run, on one thread: the largest first, then the others, and the budget read once.
710void budget_order() {
711 struct Case {
712 std::vector<std::uint64_t> large;
713 std::uint64_t budget;
714 std::size_t lanes;
715 Names order; // of the large ones
716 };
717 for (const Case& c : {Case{{5, 2, 3, 2, 1}, 5, 3, {"5", "3", "2", "2", "1"}},
718 Case{{5, 2, 3, 2, 1}, 4, 2, {"5", "3", "2", "2", "1"}},
719 Case{{5, 2, 3, 2, 1}, 0, 1, {"5", "2", "3", "2", "1"}}, // no budget: in the order they came
720 Case{{5, 2, 3, 2, 1}, 100, 5, {"5", "3", "2", "2", "1"}},
721 Case{{9}, 5, 1, {"9"}}, // more than the budget: one, alone
722 Case{{9, 9}, 5, 1, {"9", "9"}},
723 Case{{9, 1}, 5, 1, {"9", "1"}},
724 Case{{4, 4}, 8, 2, {"4", "4"}}}) {
725 Shop shop;
726 for (const auto size : c.large) shop.add(std::to_string(size), size, true);
727 for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false);
728 PipelineCompiles compiles;
729 shop.fill(compiles);
730 std::size_t units = 0;
731 unsigned reads = 0;
732 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
733 units = count;
734 for (std::size_t i = 0; i < count; ++i) job(i);
735 }, [&] { ++reads; return c.budget; });
736 Names want = c.order;
737 for (int i = 0; i < 3; ++i) want.push_back("s" + std::to_string(i));
738 const std::string name = "budget " + std::to_string(c.budget) + " of " + std::to_string(c.large.size());
739 check(shop.started == want, name + ": another order");
740 check(units == c.lanes + 3, name + ": " + std::to_string(units) + " jobs, not " + std::to_string(c.lanes + 3));
741 check(reads == 1, name + ": the budget read " + std::to_string(reads) + " times");
742 for (std::size_t i = 0; i < shop.items.size(); ++i)
743 check(compiles.built(PipelineCompiles::Ticket(i + 1)) != VK_NULL_HANDLE, name + ": not built");
744 }
745 // Without a large pipeline the budget is not read, and the jobs are the pipelines.
746 Shop shop;
747 for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false);
748 PipelineCompiles compiles;
749 shop.fill(compiles);
750 std::size_t units = 0;
751 unsigned reads = 0;
752 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
753 units = count;
754 for (std::size_t i = 0; i < count; ++i) job(i);
755 }, [&] { ++reads; return 100u; });
756 check(units == 3 && reads == 0, "the budget read for pipelines that are not large");
757}
758
759// A large one that does not fit beside the one in is not waited for while others are left: they come first.
760void budget_others_first() {
761 Shop shop;
762 shop.add("8", 8, true, true);
763 shop.add("4a", 4, true);
764 shop.add("4b", 4, true);
765 for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false);
766 PipelineCompiles compiles;
767 shop.fill(compiles);
768 std::thread building([&] {
769 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
770 check(count == 2 + 3, "two lanes: the two of 4 fit 8 together");
771 on_threads(2, count, job);
772 }, [] { return 8; });
773 });
774 const bool all = shop.wait_started(6); // "8" is held: the other lane does the rest
775 Names seen;
776 {
777 std::lock_guard lock(shop.mutex);
778 seen = shop.started;
779 }
780 shop.release();
781 building.join();
782 check(all && seen.size() == 6 && seen[0] == "8", "the large one first");
783 check(all && std::set<std::string>(seen.begin() + 1, seen.begin() + 4) == std::set<std::string>{"s0", "s1", "s2"},
784 "the others before the large ones that do not fit");
785 check(all && seen[4] == "4a" && seen[5] == "4b", "then the next large ones");
786}
787
788// Those that fit together start together, before the others.
789void budget_fits_together() {
790 Shop shop;
791 shop.add("3", 3, true, true);
792 shop.add("5", 5, true, true);
793 for (int i = 0; i < 2; ++i) shop.add("s" + std::to_string(i), 0, false);
794 PipelineCompiles compiles;
795 shop.fill(compiles);
796 std::thread building([&] {
797 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { on_threads(2, count, job); },
798 [] { return 8; });
799 });
800 const bool both = shop.wait_started(2);
801 Names seen;
802 {
803 std::lock_guard lock(shop.mutex);
804 seen = shop.started;
805 }
806 shop.release();
807 building.join();
808 check(both && std::set<std::string>(seen.begin(), seen.begin() + 2) == std::set<std::string>{"3", "5"},
809 "two that fit the budget are in together");
810 check(shop.most_large_in == 2, "two that fit the budget at once");
811}
812
813// The room that a large one leaves is the next large one's, before the others.
814void budget_room_is_given_back() {
815 Shop shop;
816 shop.add("5", 5, true, true);
817 for (const char* name : {"3a", "3b", "3c"}) shop.add(name, 3, true);
818 for (int i = 0; i < 3; ++i) shop.add("s" + std::to_string(i), 0, false);
819 PipelineCompiles compiles;
820 shop.fill(compiles);
821 std::thread building([&] {
822 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
823 check(count == 2 + 3, "two lanes: two of 3 fit 8, three do not");
824 on_threads(2, count, job);
825 }, [] { return 8; });
826 });
827 const bool all = shop.wait_started(7); // "5" is held: the other lane has room for one of 3 at a time
828 Names seen;
829 {
830 std::lock_guard lock(shop.mutex);
831 seen = shop.started;
832 }
833 shop.release();
834 building.join();
835 check(all && Names(seen.begin(), seen.begin() + 4) == Names{"5", "3a", "3b", "3c"},
836 "a large one does not leave its room");
837}
838
839// Graphics and compute pipelines share the budget: what each is expected to take counts alike.
840void budget_graphics_and_compute() {
841 Shop shop;
842 shop.add("3", 3, true);
843 shop.add("4", 4, true);
844 GraphicsPipeline graphics{};
845 graphics.large = true;
846 graphics.estimate = 5;
847 graphics.variant = [&](std::uint32_t) {
848 std::lock_guard lock(shop.mutex);
849 shop.started.push_back("5");
850 return handle<VkPipeline>(5);
851 };
852 PipelineCompiles compiles;
853 shop.fill(compiles);
854 compiles.add(graphics, 0);
855 std::size_t units = 0;
856 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
857 units = count;
858 for (std::size_t i = 0; i < count; ++i) job(i);
859 }, [] { return 8; });
860 check(shop.started == Names{"5", "4", "3"}, "the largest first, graphics or compute");
861 check(units == 2, "3 and 4 fit 8, and 5 does not beside them");
862}
863
864// The lanes are no more than could be in: a thread is not kept waiting for room there is none of.
865void budget_lanes_are_bounded() {
866 Shop shop;
867 for (int i = 0; i < 3; ++i) shop.add("5" + std::to_string(i), 5, true);
868 for (int i = 0; i < 6; ++i) shop.add("s" + std::to_string(i), 0, false);
869 PipelineCompiles compiles;
870 shop.fill(compiles);
871 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) {
872 check(count == 2 + 6, "10 bytes hold two of 5");
873 on_threads(4, count, job);
874 }, [] { return 10; });
875 check(shop.started.size() == 9 && shop.most_large_in <= 2, "no more than two large ones at once");
876}
877
878// Every one of them is built once, with the gate of the runtime holding what does not fit, whatever sizes and budget.
879void budget_random(PipelineWorkers& workers) {
880 std::mt19937 rng(20251127);
881 for (int round = 0; round < 300; ++round) {
882 Shop shop;
883 const std::uint64_t budget = rng() % 20;
884 LargeModuleGate gate([budget] { return budget; });
885 shop.gate = &gate;
886 const unsigned large = rng() % 10, others = rng() % 10;
887 for (unsigned i = 0; i < large; ++i) shop.add("l" + std::to_string(i), rng() % 12, true);
888 for (unsigned i = 0; i < others; ++i) shop.add("s" + std::to_string(i), 0, false);
889 PipelineCompiles compiles;
890 shop.fill(compiles);
891 compiles.build([&](std::size_t count, const std::function<void(std::size_t)>& job) { workers.run(count, job); },
892 [budget] { return budget; });
893 Names names = shop.started;
894 std::sort(names.begin(), names.end());
895 check(std::adjacent_find(names.begin(), names.end()) == names.end() && names.size() == large + others,
896 "random budget " + std::to_string(round) + ": a pipeline built twice or not at all");
897 check(gate.inflight() == 0, "random budget " + std::to_string(round) + ": a place not given back");
898 }
899}
900
550} // namespace 901} // namespace
551 902
552int main() { 903int main() {
@@ -555,8 +906,17 @@ int main() {
555 cases(workers); 906 cases(workers);
556 if (threads) many(workers); 907 if (threads) many(workers);
557 reused_lists(workers); 908 reused_lists(workers);
909 prior_compiles_reuse(workers);
558 random_submissions(workers); 910 random_submissions(workers);
911 budget_random(workers);
559 } 912 }
913 serial_stops_at_refused_draw();
914 budget_order();
915 budget_others_first();
916 budget_fits_together();
917 budget_room_is_given_back();
918 budget_graphics_and_compute();
919 budget_lanes_are_bounded();
560 check(large_together == 0, "two large pipelines were built at once"); 920 check(large_together == 0, "two large pipelines were built at once");
561 if (failures) return 1; 921 if (failures) return 1;
562 std::printf("replay_pipeline_compiles_test: passed\n"); 922 std::printf("replay_pipeline_compiles_test: passed\n");
diff --git a/runtime/test/replay_query_predication_test.cpp b/runtime/test/replay_query_predication_test.cpp
index 87056a499..352067bca 100644
--- a/runtime/test/replay_query_predication_test.cpp
+++ b/runtime/test/replay_query_predication_test.cpp
@@ -7,7 +7,8 @@
7// inside ordinary, the composite sum-and-normalize binary resolve, helper dispatches inside overlapping statistics 7// inside ordinary, the composite sum-and-normalize binary resolve, helper dispatches inside overlapping statistics
8// queries, the single-list refusal (D3D-252) and, with a pool, its replay (D3D-399). Cases 15 and 16 check queries 8// queries, the single-list refusal (D3D-252) and, with a pool, its replay (D3D-399). Cases 15 and 16 check queries
9// that hold mesh draws, split between the full and the mesh-compatible pool, alone and overlapping (D3D-291). No GPU or 9// that hold mesh draws, split between the full and the mesh-compatible pool, alone and overlapping (D3D-291). No GPU or
10// game data. 10// game data. Case 18 checks SO_STATISTICS: overlapping queries on one stream are refused
11// (VUID-vkCmdBeginQueryIndexedEXT-queryPool-04753) and streams past maxTransformFeedbackStreams resolve zero (D3D-302).
11#include "../src/vulkan_replay.h" 12#include "../src/vulkan_replay.h"
12#include <cstdint> 13#include <cstdint>
13#include <cstdio> 14#include <cstdio>
@@ -774,6 +775,105 @@ int main() {
774 "the mesh pool counts the fragment and compute invocations"); 775 "the mesh pool counts the fragment and compute invocations");
775 } 776 }
776 777
778 // 18. D3D-302: two overlapping SO_STATISTICS queries on one stream would be two active indexed queries in one
779 // pool (VUID-vkCmdBeginQueryIndexedEXT-queryPool-04753). prepare() refuses them; different streams are fine.
780 // A stream past the pool's maxTransformFeedbackStreams runs nothing and resolves zero.
781 {
782 QueryPool so{handle<VkQueryPool>(8), d3d12_query_heap::so_statistics, 4, false,
783 std::vector<bool>(4, false), {}, 4};
784 ReplayFunctions indexed = vk;
785 indexed.query_pool = [&](QueryHeapId id) -> QueryPool* { return id == 8 ? &so : nullptr; };
786 indexed.begin_query_indexed = +[](VkCommandBuffer, VkQueryPool pool, std::uint32_t index,
787 std::uint32_t stream, VkQueryControlFlags) {
788 g_trace->events.push_back(query_event("begin_indexed", pool, index) + "/" + std::to_string(stream));
789 };
790 indexed.end_query_indexed = +[](VkCommandBuffer, VkQueryPool pool, std::uint32_t index,
791 std::uint32_t stream) {
792 g_trace->events.push_back(query_event("end_indexed", pool, index) + "/" + std::to_string(stream));
793 };
794
795 {
796 CommandList list;
797 expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0");
798 expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 1}), "record second SO begin stream 0");
799 expect(list.end_query({8, d3d12_query::so_statistics_stream0, 1}), "record second SO end stream 0");
800 expect(list.end_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0");
801 expect(list.close(), "close overlapping SO stream list");
802 PreparedList prepared;
803 expect(prepare(list, resolve, indexed, prepared) == ReplayResult::invalid_query,
804 "two overlapping SO_STATISTICS queries on one stream are refused");
805 }
806 {
807 CommandList list;
808 expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0");
809 expect(list.begin_query({8, d3d12_query::so_statistics_stream0 + 1, 1}), "record SO begin stream 1");
810 expect(list.end_query({8, d3d12_query::so_statistics_stream0 + 1, 1}), "record SO end stream 1");
811 expect(list.end_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0");
812 expect(list.close(), "close two-stream SO list");
813 PreparedList prepared;
814 expect(prepare(list, resolve, indexed, prepared) == ReplayResult::success,
815 "overlapping SO_STATISTICS queries on different streams are fine");
816 }
817 // The VUID holds per command buffer, not per pool: one stream in two heaps is refused too, while queries that
818 // take turns on that stream are fine.
819 QueryPool so2{handle<VkQueryPool>(9), d3d12_query_heap::so_statistics, 4, false,
820 std::vector<bool>(4, false), {}, 4};
821 ReplayFunctions two_heaps = indexed;
822 two_heaps.query_pool = [&](QueryHeapId id) -> QueryPool* {
823 return id == 8 ? &so : id == 9 ? &so2 : nullptr;
824 };
825 {
826 CommandList list;
827 expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0, heap 8");
828 expect(list.begin_query({9, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0, heap 9");
829 expect(list.end_query({9, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0, heap 9");
830 expect(list.end_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0, heap 8");
831 expect(list.close(), "close two-heap SO stream list");
832 PreparedList prepared;
833 expect(prepare(list, resolve, two_heaps, prepared) == ReplayResult::invalid_query,
834 "overlapping SO_STATISTICS queries on one stream in two heaps are refused");
835 }
836 {
837 CommandList list;
838 expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0, heap 8");
839 expect(list.end_query({8, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0, heap 8");
840 expect(list.begin_query({9, d3d12_query::so_statistics_stream0, 0}), "record SO begin stream 0, heap 9");
841 expect(list.end_query({9, d3d12_query::so_statistics_stream0, 0}), "record SO end stream 0, heap 9");
842 expect(list.close(), "close two-heap SO stream list in turn");
843 PreparedList prepared;
844 expect(prepare(list, resolve, two_heaps, prepared) == ReplayResult::success,
845 "SO_STATISTICS queries on one stream in two heaps, one after the other, are fine");
846 }
847 // A one-stream pool: stream 0 runs, stream 1 is zero-filled and emits nothing.
848 so.streams = 1;
849 {
850 Trace trace;
851 g_trace = &trace;
852 CommandList list;
853 expect(list.begin_query({8, d3d12_query::so_statistics_stream0 + 1, 0}), "record unsupported SO begin");
854 expect(list.end_query({8, d3d12_query::so_statistics_stream0 + 1, 0}), "record unsupported SO end");
855 expect(list.resolve_queries({8, d3d12_query::so_statistics_stream0 + 1, 0, 1, 1, 0}),
856 "record unsupported SO resolve");
857 expect(list.close(), "close unsupported stream list");
858 expect(replay(list, VK_NULL_HANDLE, resolve, indexed) == ReplayResult::success,
859 "a stream past maxTransformFeedbackStreams replays");
860 expect(trace.fills == 1 && trace.events == std::vector<std::string>{"fill"},
861 "a stream past maxTransformFeedbackStreams emits no query and resolves zero");
862 }
863 {
864 Trace trace;
865 g_trace = &trace;
866 CommandList list;
867 expect(list.begin_query({8, d3d12_query::so_statistics_stream0, 0}), "record supported SO begin");
868 expect(list.end_query({8, d3d12_query::so_statistics_stream0, 0}), "record supported SO end");
869 expect(list.close(), "close supported stream list");
870 expect(replay(list, VK_NULL_HANDLE, resolve, indexed) == ReplayResult::success,
871 "stream 0 on a one-stream pool replays");
872 expect(trace.events == std::vector<std::string>{"begin_indexed 8:0/0", "end_indexed 8:0/0"},
873 "stream 0 on a one-stream pool begins and ends indexed on stream 0");
874 }
875 }
876
777 if (failures) return 1; 877 if (failures) return 1;
778 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); 878 std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches");
779 return 0; 879 return 0;
diff --git a/runtime/test/replay_uav_clear_offset_test.cpp b/runtime/test/replay_uav_clear_offset_test.cpp
index a11da272a..65247e08c 100644
--- a/runtime/test/replay_uav_clear_offset_test.cpp
+++ b/runtime/test/replay_uav_clear_offset_test.cpp
@@ -14,6 +14,7 @@ struct Write {
14 char kind; // 'f' fill, 'u' update, 'c' copy (dst; src in from) 14 char kind; // 'f' fill, 'u' update, 'c' copy (dst; src in from)
15 VkDeviceSize offset, size, from; 15 VkDeviceSize offset, size, from;
16 VkBuffer buffer = VK_NULL_HANDLE, source = VK_NULL_HANDLE; 16 VkBuffer buffer = VK_NULL_HANDLE, source = VK_NULL_HANDLE;
17 std::uint32_t word = 0;
17}; 18};
18std::vector<Write> writes; 19std::vector<Write> writes;
19 20
@@ -38,8 +39,8 @@ void reset_texture_capture() {
38VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, 39VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags,
39 std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, 40 std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*,
40 std::uint32_t, const VkImageMemoryBarrier*) {} 41 std::uint32_t, const VkImageMemoryBarrier*) {}
41VKAPI_ATTR void VKAPI_CALL fill(VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size, std::uint32_t) { 42VKAPI_ATTR void VKAPI_CALL fill(VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size, std::uint32_t word) {
42 writes.push_back({'f', offset, size, 0, buffer}); 43 writes.push_back({'f', offset, size, 0, buffer, VK_NULL_HANDLE, word});
43} 44}
44VKAPI_ATTR void VKAPI_CALL update(VkCommandBuffer, VkBuffer, VkDeviceSize offset, VkDeviceSize size, const void*) { 45VKAPI_ATTR void VKAPI_CALL update(VkCommandBuffer, VkBuffer, VkDeviceSize offset, VkDeviceSize size, const void*) {
45 writes.push_back({'u', offset, size, 0}); 46 writes.push_back({'u', offset, size, 0});
@@ -447,7 +448,264 @@ int main() {
447 expect(image_clears == 1 && attachment_clears == 0, 448 expect(image_clears == 1 && attachment_clears == 0,
448 "non-attachable view format whole-view clear uses vkCmdClearColorImage"); 449 "non-attachable view format whole-view clear uses vkCmdClearColorImage");
449 450
451 // ---- 3D volume partial-W and XY rectangle UAV clears (direct and compute queues) ----
452 {
453 ResourceBinding vol{};
454 vol.image = reinterpret_cast<VkImage>(std::uintptr_t{0x4000});
455 vol.format = VK_FORMAT_R8G8B8A8_UNORM;
456 vol.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
457 vol.width = 8;
458 vol.height = 6;
459 vol.depth = 4;
460 vol.mip_levels = 2;
461 vol.array_layers = 1;
462 vol.volume = true;
463 vol.color_attachment = false;
464
465 static std::vector<VkBufferImageCopy> vol_copies;
466 VkDeviceSize last_scratch_req = 0;
467 unsigned scratch_allocs = 0;
468 unsigned prepared_predicates = 0;
469 bool resolved_volume = false;
470 bool scratch_ok = true;
471 VkDeviceSize scratch_offset_out = 256;
472
473 auto make_vol_vk = [&](bool compute_queue) {
474 ReplayFunctions v = tex_vk;
475 v.graphics_family = !compute_queue;
476 v.queue_stages = compute_queue ? detail::queue_stages_compute : 0;
477 if (compute_queue) {
478 v.begin_rendering = nullptr;
479 v.image_view = {};
480 }
481 v.begin_conditional_rendering = [](VkCommandBuffer, const VkConditionalRenderingBeginInfoEXT*) {};
482 v.end_conditional_rendering = [](VkCommandBuffer) {};
483 v.prepare_predicate = [&](VkBuffer source, VkDeviceSize offset, PredicateCapture& out) {
484 ++prepared_predicates;
485 out = {source, offset, scratch, 0, VK_NULL_HANDLE};
486 return true;
487 };
488 v.capture_predicate = [](VkCommandBuffer, const PredicateCapture&) {};
489 v.copy_scratch = [&](VkDeviceSize size, VkBuffer& buffer, VkDeviceSize& offset) {
490 ++scratch_allocs;
491 last_scratch_req = size;
492 if (!scratch_ok) return false;
493 buffer = scratch;
494 offset = scratch_offset_out;
495 return true;
496 };
497 v.copy_buffer_to_image = [](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout layout,
498 std::uint32_t count, const VkBufferImageCopy* regions) {
499 expect(layout == VK_IMAGE_LAYOUT_GENERAL && count == 1, "3D clear copy uses GENERAL and count 1");
500 vol_copies.push_back(regions[0]);
501 };
502 return v;
503 };
504
505 auto run_vol = [&](const ResourceBinding& b, const UavView& view, bool is_float,
506 std::array<std::uint32_t, 4> values, std::span<const Rect> rects,
507 const ReplayFunctions& v, bool predicate = false) {
508 writes.clear();
509 vol_copies.clear();
510 reset_texture_capture();
511 last_scratch_req = 0;
512 scratch_allocs = 0;
513 prepared_predicates = 0;
514 resolved_volume = false;
515 CommandList list;
516 ResourceBinding pred_buf{};
517 pred_buf.buffer = reinterpret_cast<VkBuffer>(std::uintptr_t{0x5000});
518 pred_buf.size = 64;
519 if (predicate) expect(list.set_predication({9, 0, d3d12_predication::equal_zero}), "record predicate");
520 expect(list.clear_unordered_access(view, is_float, values, rects), "record volume clear");
521 expect(list.close(), "close volume clear list");
522 return replay(list, VK_NULL_HANDLE,
523 [&](ResourceId id) -> const ResourceBinding* {
524 if (id == 2) { resolved_volume = true; return &b; }
525 if (id == 9) return &pred_buf;
526 return nullptr;
527 },
528 v);
529 };
530
531 const auto direct_vol = make_vol_vk(false);
532 const auto compute_vol = make_vol_vk(true);
533
534 // Whole-mip, non-rect 3D clear stays on vkCmdClearColorImage with zero scratch.
535 expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 0, 4, true}, false, {1, 2, 3, 4}, {},
536 direct_vol) == ReplayResult::success &&
537 image_clears == 1 && scratch_allocs == 0 && vol_copies.empty(),
538 "whole-mip 3D clear keeps vkCmdClearColorImage fast path");
539
540 // Partial W slice on mip 0 (FirstWSlice=1, WSize=2) on both direct and compute queues.
541 for (bool comp : {false, true}) {
542 const auto& v = comp ? compute_vol : direct_vol;
543 expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 1, 2, true}, false, {1, 2, 3, 4}, {},
544 v) == ReplayResult::success,
545 comp ? "partial 3D clear replays on compute queue" : "partial 3D clear replays on direct queue");
546 expect(image_clears == 0 && scratch_allocs == 1 && last_scratch_req == 8 * 6 * 4 &&
547 writes.size() == 1 && writes[0].kind == 'f' && vol_copies.size() == 2,
548 "partial 3D clear fills one 2D slice and emits 2 depth-1 copies");
549 if (vol_copies.size() == 2) {
550 expect(vol_copies[0].imageSubresource.mipLevel == 0 &&
551 vol_copies[0].imageSubresource.baseArrayLayer == 0 &&
552 vol_copies[0].imageSubresource.layerCount == 1 &&
553 vol_copies[0].imageOffset.z == 1 && vol_copies[0].imageExtent.depth == 1 &&
554 vol_copies[1].imageOffset.z == 2 && vol_copies[1].imageExtent.depth == 1 &&
555 vol_copies[0].bufferOffset == 256 && vol_copies[1].bufferOffset == 256,
556 "partial 3D copies target Z=1 and Z=2 on array layer 0");
557 }
558 }
559
560 // Non-zero mip (mip 1 -> 4x3x2), partial W (FirstWSlice=1, WSize=1) with clipped & overlapping rects.
561 const std::array<Rect, 2> overlap{{{-2, 1, 3, 4}, {1, 0, 5, 2}}};
562 expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 1, 1, 1, true}, false, {9, 8, 7, 6},
563 overlap, direct_vol) == ReplayResult::success &&
564 vol_copies.size() == 2 && last_scratch_req == 3 * 2 * 4,
565 "mip-1 partial 3D overlapping rects clip to 4x3 and emit separate copies");
566 if (vol_copies.size() == 2) {
567 expect(vol_copies[0].imageSubresource.mipLevel == 1 && vol_copies[0].imageOffset.x == 0 &&
568 vol_copies[0].imageOffset.y == 1 && vol_copies[0].imageOffset.z == 1 &&
569 vol_copies[0].imageExtent.width == 3 && vol_copies[0].imageExtent.height == 2 &&
570 vol_copies[1].imageOffset.x == 1 && vol_copies[1].imageOffset.y == 0 &&
571 vol_copies[1].imageOffset.z == 1 && vol_copies[1].imageExtent.width == 3 &&
572 vol_copies[1].imageExtent.height == 2,
573 "mip-1 clipped rect offsets and extents match");
574 }
575
576 // Empty clipped rect skips without allocating scratch or emitting commands.
577 const Rect offscreen{10, 10, 12, 12};
578 expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 1, 2, true}, false, {1, 2, 3, 4},
579 std::span<const Rect>(&offscreen, 1), direct_vol) == ReplayResult::success &&
580 scratch_allocs == 0 && writes.empty() && vol_copies.empty(),
581 "empty clipped 3D rect skips without scratch");
582
583 // Tiny 1..3-byte payloads pad fill to 4 bytes and copy exact texel extent.
584 ResourceBinding vol_r8 = vol;
585 vol_r8.format = VK_FORMAT_R8_UINT;
586 const Rect one_px{2, 2, 3, 3};
587 for (int width : {1, 2, 3}) {
588 const Rect tiny{2, 2, 2 + width, 3};
589 expect(run_vol(vol_r8, {2, false, VK_FORMAT_R8_UINT, 0, 0, 0, 0, 2, 1, true}, false, {0x5a, 0, 0, 0},
590 std::span<const Rect>(&tiny, 1), direct_vol) == ReplayResult::success &&
591 last_scratch_req == 4 && writes.size() == 1 && writes[0].kind == 'f' &&
592 writes[0].word == 0x5a5a5a5au && writes[0].size == 4 && vol_copies.size() == 1 &&
593 vol_copies[0].imageExtent.width == std::uint32_t(width) &&
594 vol_copies[0].imageExtent.height == 1 && vol_copies[0].imageOffset.z == 2,
595 "1/2/3-byte R8 volume clear fills one private word and copies the exact extent");
596 }
597 auto vol_r16 = vol;
598 vol_r16.format = VK_FORMAT_R16_UINT;
599 expect(run_vol(vol_r16, {2, false, VK_FORMAT_R16_UINT, 0, 0, 0, 0, 2, 1, true}, false, {0xcdef, 0, 0, 0},
600 std::span<const Rect>(&one_px, 1), direct_vol) == ReplayResult::success &&
601 writes.size() == 1 && writes[0].word == 0xcdefcdefu && writes[0].size == 4 &&
602 vol_copies.size() == 1 && vol_copies[0].imageExtent.width == 1,
603 "one R16 texel uses padded scratch without widening the copy");
604
605 // Wide 16-byte format exceeding 64 KiB per slice tiles cleanly with single vkCmdUpdateBuffer <= 65536 B.
606 ResourceBinding big_vol = vol;
607 big_vol.format = VK_FORMAT_R32G32B32A32_UINT;
608 big_vol.width = 128;
609 big_vol.height = 64;
610 big_vol.depth = 3;
611 big_vol.mip_levels = 1;
612 expect(run_vol(big_vol, {2, false, VK_FORMAT_R32G32B32A32_UINT, 0, 0, 0, 0, 1, 2, true}, false,
613 {1, 2, 3, 4}, {}, direct_vol) == ReplayResult::success &&
614 scratch_allocs == 1 && last_scratch_req == 65536 && writes.size() == 1 &&
615 writes[0].kind == 'u' && writes[0].size == 65536 && vol_copies.size() == 4,
616 "128x64x2 RGBA32_UINT partial 3D clear tiles into 64 KiB update_buffer chunks");
617 if (vol_copies.size() == 4) {
618 expect(vol_copies[0].imageOffset.y == 0 && vol_copies[0].imageExtent.height == 32 &&
619 vol_copies[0].imageOffset.z == 1 && vol_copies[1].imageOffset.y == 32 &&
620 vol_copies[1].imageExtent.height == 32 && vol_copies[1].imageOffset.z == 1 &&
621 vol_copies[2].imageOffset.y == 0 && vol_copies[2].imageOffset.z == 2 &&
622 vol_copies[3].imageOffset.y == 32 && vol_copies[3].imageOffset.z == 2,
623 "tiled 3D copies cover full 128x64 across both slices");
624 }
625
626 // Emulated R9G9B9E5_SHAREDEXP on R32_UINT 3D backing replays partial W slice.
627 ResourceBinding vol_e5 = vol;
628 vol_e5.format = VK_FORMAT_R32_UINT;
629 expect(run_vol(vol_e5, {2, false, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, 0, 0, 0, 0, 1, 2, true}, true,
630 {fbits(1.0f), fbits(2.0f), fbits(4.0f), 0}, {}, direct_vol) == ReplayResult::success &&
631 vol_copies.size() == 2 && writes.size() == 1 && writes[0].kind == 'f' && writes[0].word == 0x94010040u,
632 "emulated RGB9E5 volume float clear packs RGB 1, 2, 4 into one shared-exponent word");
633 expect(run_vol(vol_e5, {2, false, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, 0, 0, 0, 0, 1, 2, true}, false,
634 {1, 2, 4, 8}, {}, direct_vol) == ReplayResult::success &&
635 vol_copies.size() == 2 && writes.size() == 1 && writes[0].word == 0,
636 "emulated RGB9E5 volume uint clear writes zero even for nonzero inputs");
637
638 // Error and safety contracts: zero commands emitted on any rejection.
639 // Out-of-range W slices.
640 expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 2, 3, true}, false, {1, 2, 3, 4}, {},
641 direct_vol) == ReplayResult::invalid_subresource &&
642 writes.empty() && vol_copies.empty(),
643 "out-of-range 3D W slice range is rejected as invalid_subresource");
644 expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 1, 2, 1, true}, false, {1, 2, 3, 4}, {},
645 direct_vol) == ReplayResult::invalid_subresource &&
646 writes.empty() && vol_copies.empty(),
647 "out-of-range mip-1 3D FirstWSlice is rejected as invalid_subresource");
648 CommandList invalid;
649 expect(!invalid.clear_unordered_access({2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 0, 0, true}, false,
650 {1, 2, 3, 4}) && invalid.commands().empty(),
651 "zero 3D WSize is rejected while recording");
652
653 // Typeless 3D format mismatch refused (both exact_clear_format true and false on staged path).
654 ResourceBinding vol_f32 = vol;
655 vol_f32.format = VK_FORMAT_R32_SFLOAT;
656 expect(run_vol(vol_f32, {2, false, VK_FORMAT_R32_UINT, 0, 0, 0, 0, 1, 2, true}, false, {1, 0, 0, 0}, {},
657 direct_vol) == ReplayResult::unsupported &&
658 writes.empty() && vol_copies.empty(),
659 "typeless 3D format mismatch is refused");
660 expect(run_vol(vol_f32, {2, false, VK_FORMAT_R32_UINT, 0, 0, 0, 0, 1, 2, false}, false, {1, 0, 0, 0}, {},
661 direct_vol) == ReplayResult::unsupported &&
662 writes.empty() && vol_copies.empty(),
663 "staged 3D format mismatch without exact_clear_format is also refused");
664
665 // Predicated partial 3D / 3D rect clear refused on BOTH direct and compute lists.
666 expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 1, 2, true}, false, {1, 2, 3, 4}, {},
667 direct_vol, true) == ReplayResult::unsupported &&
668 prepared_predicates == 1 && resolved_volume && scratch_allocs == 0 && writes.empty() && vol_copies.empty(),
669 "predicated partial 3D clear is refused on direct list");
670 expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 0, 4, true}, false, {1, 2, 3, 4},
671 std::span<const Rect>(&one_px, 1), compute_vol, true) == ReplayResult::unsupported &&
672 prepared_predicates == 1 && resolved_volume && scratch_allocs == 0 && writes.empty() && vol_copies.empty(),
673 "predicated 3D rect clear is refused on compute list");
674
675 // Failed scratch allocation, misaligned offset for 16-byte / 4-byte formats, and offset overflow.
676 scratch_ok = false;
677 expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 1, 2, true}, false, {1, 2, 3, 4}, {},
678 direct_vol) == ReplayResult::unsupported &&
679 writes.empty() && vol_copies.empty(),
680 "3D staged clear rejects failed scratch allocation");
681 scratch_ok = true;
682 scratch_offset_out = 8; // 8-byte aligned, NOT 16-byte aligned for RGBA32_UINT
683 expect(run_vol(big_vol, {2, false, VK_FORMAT_R32G32B32A32_UINT, 0, 0, 0, 0, 1, 1, true}, false, {1, 2, 3, 4},
684 std::span<const Rect>(&one_px, 1), direct_vol) == ReplayResult::unsupported &&
685 writes.empty() && vol_copies.empty(),
686 "16-byte 3D clear rejects 8-byte-only aligned scratch offset");
687 scratch_offset_out = 2; // not 4-byte aligned
688 expect(run_vol(vol, {2, false, VK_FORMAT_R8G8B8A8_UNORM, 0, 0, 0, 0, 1, 1, true}, false, {1, 2, 3, 4}, {},
689 direct_vol) == ReplayResult::unsupported &&
690 writes.empty() && vol_copies.empty(),
691 "4-byte 3D clear rejects 2-byte aligned scratch offset");
692 scratch_offset_out = UINT64_MAX - 15; // aligned to 16, but the exclusive end is unrepresentable
693 expect(run_vol(big_vol, {2, false, VK_FORMAT_R32G32B32A32_UINT, 0, 0, 0, 0, 1, 1, true}, false, {1, 2, 3, 4},
694 std::span<const Rect>(&one_px, 1), direct_vol) == ReplayResult::unsupported &&
695 writes.empty() && vol_copies.empty(),
696 "3D clear rejects scratch offset + fill_bytes overflow");
697 scratch_offset_out = 256;
698
699 // Missing update_buffer callback for 16-byte 3D staged clear.
700 ReplayFunctions no_update = direct_vol;
701 no_update.update_buffer = nullptr;
702 expect(run_vol(big_vol, {2, false, VK_FORMAT_R32G32B32A32_UINT, 0, 0, 0, 0, 1, 1, true}, false, {1, 2, 3, 4},
703 std::span<const Rect>(&one_px, 1), no_update) == ReplayResult::unsupported &&
704 writes.empty() && vol_copies.empty(),
705 "16-byte 3D clear without vkCmdUpdateBuffer is rejected");
706 }
707
450 if (failures) return 1; 708 if (failures) return 1;
451 std::printf("replay_uav_clear_offset: buffer offsets and typeless texture view-format clears all passed\n"); 709 std::printf("replay_uav_clear_offset: buffer offsets, typeless texture view-format clears, and 3D sliced/rect clears all passed\n");
452 return 0; 710 return 0;
453} 711}
diff --git a/runtime/test/root_sig_public_flags_test.cpp b/runtime/test/root_sig_public_flags_test.cpp
new file mode 100644
index 000000000..8b8c5d76e
--- /dev/null
+++ b/runtime/test/root_sig_public_flags_test.cpp
@@ -0,0 +1,443 @@
1// The d3d12_xs root-signature flag mask leaves every public D3D12_ROOT_SIGNATURE_FLAGS value alone (old upstream
2// PR 7140).
3//
4// The shims clear bits 24-31 (kXboxRootSignatureFlagHighByte) of a root signature's flags before the host serializer
5// or deserializer sees them, on every descriptor and every RTS0 blob, whoever built it. Every public flag in d3d12.h
6// is in the low 16 bits (the highest is SAMPLER_HEAP_DIRECTLY_INDEXED, 0x800), so a descriptor whose flags fit in 16
7// bits must come out of the shims exactly as it went in. That is the case for the retail executable's root
8// signatures (old upstream PR 7140: a 1.1 descriptor with Flags 0x80, and a decoder whose Flags is a zero-extended
9// 16-bit read).
10//
11// Checked here:
12// - the helpers, for every flag value in [0, 0xFFFF]: versioned 1.0/1.1/1.2 and legacy descriptors keep the value, and
13// an RTS0 blob carrying it is not rewritten;
14// - the registered shims against the host d3d12.dll, for each public flag, 0x80 alone and all of them: the serializers
15// give the host's result byte for byte (1.0 and 1.1) wherever the host takes the description, the deserializer
16// returns the same flags. Where the host refuses a description only for the heap-indexed flags (Windows 10's in-box
17// d3d12.dll, kDirectlyIndexedFlags), the shims serialize it on purpose: their blob is the host's blob for the
18// flags without those bits, with the full flags in RTS0 and a valid container hash;
19// - a blob carrying 0x03000000 on top of 0x80 has exactly those two bits cleared and nothing else changed.
20#include <windows.h>
21#include <d3d12.h>
22
23#include <cstdint>
24#include <cstdio>
25#include <cstring>
26#include <vector>
27
28#include "d3d12_xs_rootsig.h"
29#include "shims.h"
30
31namespace {
32
33int g_failures = 0;
34
35void check(bool condition, const char* what) {
36 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
37 if (!condition) ++g_failures;
38}
39
40struct Blobs {
41 ID3DBlob* blob = nullptr;
42 ID3DBlob* error = nullptr;
43 ~Blobs() {
44 if (blob) blob->Release();
45 if (error) error->Release();
46 }
47};
48
49// Every D3D12_ROOT_SIGNATURE_FLAGS value in d3d12.h (Windows SDK 10.0.26100, DirectX-Headers 1.721).
50constexpr D3D12_ROOT_SIGNATURE_FLAGS kPublicFlags[] = {
51 D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT,
52 D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS,
53 D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS,
54 D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS,
55 D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS,
56 D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS,
57 D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT,
58 D3D12_ROOT_SIGNATURE_FLAG_LOCAL_ROOT_SIGNATURE,
59 D3D12_ROOT_SIGNATURE_FLAG_DENY_AMPLIFICATION_SHADER_ROOT_ACCESS,
60 D3D12_ROOT_SIGNATURE_FLAG_DENY_MESH_SHADER_ROOT_ACCESS,
61 D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED,
62 D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED,
63};
64
65constexpr uint32_t all_public_flags() {
66 uint32_t all = 0;
67 for (D3D12_ROOT_SIGNATURE_FLAGS f : kPublicFlags) all |= static_cast<uint32_t>(f);
68 return all;
69}
70
71static_assert(all_public_flags() == 0xFFFu, "the public flags are the twelve bits 0x1..0x800");
72static_assert((all_public_flags() & rt::d3d12_xs::kXboxRootSignatureFlagHighByte) == 0,
73 "no public root-signature flag is in the byte the shims clear");
74
75// The executable's direct call site (old upstream PR 7140): version 1.1, no parameters, no samplers, Flags 0x80.
76constexpr uint32_t kExecutableFlags = 0x80u;
77static_assert(kExecutableFlags == D3D12_ROOT_SIGNATURE_FLAG_LOCAL_ROOT_SIGNATURE, "0x80 is a public flag");
78
79constexpr uint32_t kXboxFlags = 0x03000000u;
80
81D3D12_ROOT_SIGNATURE_FLAGS as_flags(uint32_t v) { return static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(v); }
82
83D3D12_VERSIONED_ROOT_SIGNATURE_DESC versioned(D3D_ROOT_SIGNATURE_VERSION version, uint32_t flags) {
84 D3D12_VERSIONED_ROOT_SIGNATURE_DESC d{};
85 d.Version = version;
86 switch (version) {
87 case D3D_ROOT_SIGNATURE_VERSION_1_0: d.Desc_1_0.Flags = as_flags(flags); break;
88 case D3D_ROOT_SIGNATURE_VERSION_1_1: d.Desc_1_1.Flags = as_flags(flags); break;
89 default: d.Desc_1_2.Flags = as_flags(flags); break;
90 }
91 return d;
92}
93
94uint32_t flags_of(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& d) {
95 switch (d.Version) {
96 case D3D_ROOT_SIGNATURE_VERSION_1_0: return static_cast<uint32_t>(d.Desc_1_0.Flags);
97 case D3D_ROOT_SIGNATURE_VERSION_1_1: return static_cast<uint32_t>(d.Desc_1_1.Flags);
98 default: return static_cast<uint32_t>(d.Desc_1_2.Flags);
99 }
100}
101
102// Version and every member of the descriptor the version selects (the union arms share their layout up to Flags).
103bool same_fields(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& a, const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& b) {
104 if (a.Version != b.Version) return false;
105 switch (a.Version) {
106 case D3D_ROOT_SIGNATURE_VERSION_1_0:
107 return a.Desc_1_0.NumParameters == b.Desc_1_0.NumParameters &&
108 a.Desc_1_0.pParameters == b.Desc_1_0.pParameters &&
109 a.Desc_1_0.NumStaticSamplers == b.Desc_1_0.NumStaticSamplers &&
110 a.Desc_1_0.pStaticSamplers == b.Desc_1_0.pStaticSamplers && a.Desc_1_0.Flags == b.Desc_1_0.Flags;
111 case D3D_ROOT_SIGNATURE_VERSION_1_1:
112 return a.Desc_1_1.NumParameters == b.Desc_1_1.NumParameters &&
113 a.Desc_1_1.pParameters == b.Desc_1_1.pParameters &&
114 a.Desc_1_1.NumStaticSamplers == b.Desc_1_1.NumStaticSamplers &&
115 a.Desc_1_1.pStaticSamplers == b.Desc_1_1.pStaticSamplers && a.Desc_1_1.Flags == b.Desc_1_1.Flags;
116 default:
117 return a.Desc_1_2.NumParameters == b.Desc_1_2.NumParameters &&
118 a.Desc_1_2.pParameters == b.Desc_1_2.pParameters &&
119 a.Desc_1_2.NumStaticSamplers == b.Desc_1_2.NumStaticSamplers &&
120 a.Desc_1_2.pStaticSamplers == b.Desc_1_2.pStaticSamplers && a.Desc_1_2.Flags == b.Desc_1_2.Flags;
121 }
122}
123
124// Byte offset of the RTS0 flags dword in a DXBC container, or 0 when there is none.
125size_t rts0_flags_offset(const std::vector<uint8_t>& blob) {
126 if (blob.size() < 32 || std::memcmp(blob.data(), "DXBC", 4) != 0) return 0;
127 uint32_t count = 0;
128 std::memcpy(&count, blob.data() + 28, 4);
129 for (uint32_t i = 0; i < count && 32 + i * 4 + 4 <= blob.size(); ++i) {
130 uint32_t off = 0;
131 std::memcpy(&off, blob.data() + 32 + i * 4, 4);
132 if (off <= blob.size() && blob.size() - off >= 8 + 24 && std::memcmp(blob.data() + off, "RTS0", 4) == 0)
133 return off + 8 + 20;
134 }
135 return 0;
136}
137
138std::vector<uint8_t> bytes_of(ID3DBlob* blob) {
139 const auto* p = static_cast<const uint8_t*>(blob->GetBufferPointer());
140 return {p, p + blob->GetBufferSize()};
141}
142
143void rehash(std::vector<uint8_t>& blob) {
144 uint32_t hash[4];
145 rt::d3d12_xs::dxbc_checksum(blob.data(), blob.size(), hash);
146 std::memcpy(blob.data() + 4, hash, sizeof(hash));
147}
148
149// The host refused flags `f` and took them without kDirectlyIndexedFlags (`host_plain`, its blob for those). The shims
150// serialize again without the two bits and put them back (serialize_*_keeping_heap_flags, d3d12_xs_rootsig.h), so
151// their blob must be `host_plain` byte for byte except the RTS0 flags dword, which holds all of `f`, and the
152// container hash, which must be valid.
153bool is_heap_flag_fallback(const std::vector<uint8_t>& host_plain, const std::vector<uint8_t>& ours, uint32_t f) {
154 const size_t at = rts0_flags_offset(ours);
155 if (!at || ours.size() != host_plain.size() || rts0_flags_offset(host_plain) != at) return false;
156 uint32_t stored = 0;
157 std::memcpy(&stored, ours.data() + at, 4);
158 if (stored != f) return false;
159 for (size_t i = 0; i < ours.size(); ++i)
160 if ((i < 4 || i >= 20) && (i < at || i >= at + 4) && ours[i] != host_plain[i]) return false;
161 uint32_t hash[4];
162 rt::d3d12_xs::dxbc_checksum(ours.data(), ours.size(), hash);
163 return std::memcmp(hash, ours.data() + 4, sizeof(hash)) == 0;
164}
165
166// The helpers, over the whole range the executable's decoder can produce.
167void test_helpers_keep_16_bit_flags(const std::vector<uint8_t>& clean_blob) {
168 const D3D_ROOT_SIGNATURE_VERSION versions[] = {D3D_ROOT_SIGNATURE_VERSION_1_0, D3D_ROOT_SIGNATURE_VERSION_1_1,
169 D3D_ROOT_SIGNATURE_VERSION_1_2};
170 const char* names[] = {"1.0", "1.1", "1.2"};
171 for (int v = 0; v < 3; ++v) {
172 uint32_t changed = 0;
173 for (uint32_t f = 0; f <= 0xFFFFu; ++f) {
174 const D3D12_VERSIONED_ROOT_SIGNATURE_DESC in = versioned(versions[v], f);
175 D3D12_VERSIONED_ROOT_SIGNATURE_DESC out{};
176 const bool known = rt::d3d12_xs::copy_versioned_root_signature_desc_clear_xbox_flags(in, out);
177 if (!known || !same_fields(in, out) || flags_of(out) != f) ++changed;
178 }
179 char what[160];
180 std::snprintf(what, sizeof(what),
181 "versioned %s helper: all 65536 flag values in [0, 0xFFFF] come out unchanged (%u changed)",
182 names[v], changed);
183 check(changed == 0, what);
184 }
185
186 uint32_t legacy_changed = 0;
187 for (uint32_t f = 0; f <= 0xFFFFu; ++f) {
188 D3D12_ROOT_SIGNATURE_DESC in{};
189 in.Flags = as_flags(f);
190 D3D12_ROOT_SIGNATURE_DESC out{};
191 rt::d3d12_xs::copy_root_signature_desc_clear_xbox_flags(in, out);
192 if (out.NumParameters != in.NumParameters || out.pParameters != in.pParameters ||
193 out.NumStaticSamplers != in.NumStaticSamplers || out.pStaticSamplers != in.pStaticSamplers ||
194 out.Flags != in.Flags)
195 ++legacy_changed;
196 }
197 check(legacy_changed == 0, "legacy helper: all 65536 flag values in [0, 0xFFFF] come out unchanged");
198
199 const size_t at = rts0_flags_offset(clean_blob);
200 check(at != 0, "the host serializer's blob has an RTS0 part");
201 if (!at) return;
202 std::vector<uint8_t> blob = clean_blob;
203 uint32_t rewritten = 0;
204 for (uint32_t f = 0; f <= 0xFFFFu; ++f) {
205 std::memcpy(blob.data() + at, &f, 4);
206 std::vector<uint8_t> out;
207 if (rt::d3d12_xs::copy_rts0_blob_clear_xbox_flags(blob.data(), blob.size(), out) || !out.empty()) ++rewritten;
208 }
209 check(rewritten == 0, "blob helper: an RTS0 blob with flags in [0, 0xFFFF] is never rewritten");
210}
211
212void test_serializer_shim_matches_host() {
213 using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
214 using LegacyFn = HRESULT(WINAPI*)(const D3D12_ROOT_SIGNATURE_DESC*, D3D_ROOT_SIGNATURE_VERSION, ID3DBlob**,
215 ID3DBlob**);
216 auto shim = reinterpret_cast<SerializeFn>(rt::shims::find("d3d12_xs.dll", "D3D12SerializeVersionedRootSignature"));
217 auto legacy = reinterpret_cast<LegacyFn>(rt::shims::find("d3d12_xs.dll", "D3D12SerializeRootSignature"));
218 check(shim && legacy, "shim registry exposes both d3d12_xs serializers");
219 if (!shim || !legacy) return;
220
221 std::vector<uint32_t> values;
222 for (D3D12_ROOT_SIGNATURE_FLAGS f : kPublicFlags) values.push_back(static_cast<uint32_t>(f));
223 values.push_back(all_public_flags());
224 values.push_back(0);
225
226 // Probed once, as the shim does: does the host serialize an empty 1.2 description?
227 bool host_serializes_1_2 = false;
228 {
229 const D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty12 = versioned(D3D_ROOT_SIGNATURE_VERSION_1_2, 0);
230 Blobs b;
231 host_serializes_1_2 = SUCCEEDED(D3D12SerializeVersionedRootSignature(&empty12, &b.blob, &b.error));
232 std::printf("host serializer %s root signature 1.2\n", host_serializes_1_2 ? "takes" : "refuses");
233 }
234
235 const D3D_ROOT_SIGNATURE_VERSION versions[] = {D3D_ROOT_SIGNATURE_VERSION_1_0, D3D_ROOT_SIGNATURE_VERSION_1_1,
236 D3D_ROOT_SIGNATURE_VERSION_1_2};
237 const char* names[] = {"1.0", "1.1", "1.2"};
238 for (int v = 0; v < 3; ++v) {
239 int differ = 0, same_bytes = 0, host_refused = 0, heap_fallback = 0, lost_flags = 0, touched_input = 0;
240 for (uint32_t f : values) {
241 const D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc = versioned(versions[v], f);
242 const D3D12_VERSIONED_ROOT_SIGNATURE_DESC before = desc;
243 Blobs host, ours;
244 const HRESULT hr_host = D3D12SerializeVersionedRootSignature(&desc, &host.blob, &host.error);
245 const HRESULT hr_ours = shim(&desc, &ours.blob, &ours.error);
246 if (!same_fields(desc, before)) ++touched_input;
247 if (SUCCEEDED(hr_host)) {
248 if (FAILED(hr_ours) || !ours.blob || !host.blob || bytes_of(host.blob) != bytes_of(ours.blob)) ++differ;
249 else ++same_bytes;
250 } else {
251 ++host_refused;
252 // A host that serializes only up to 1.1 refuses every 1.2 description, and the shim rewrites those
253 // as 1.1. A host that refuses the heap-indexed flags (Windows 10) gets them serialized anyway when it
254 // takes the description without them. Otherwise (1.0, 1.1, or 1.2 on a host that takes 1.2) the shim
255 // must refuse what the host refuses.
256 const bool rewritten_as_1_1 = versions[v] == D3D_ROOT_SIGNATURE_VERSION_1_2 && !host_serializes_1_2;
257 const uint32_t plain_flags = f & ~rt::d3d12_xs::kDirectlyIndexedFlags;
258 bool host_takes_plain = false;
259 if (!rewritten_as_1_1 && plain_flags != f) {
260 const D3D12_VERSIONED_ROOT_SIGNATURE_DESC plain = versioned(versions[v], plain_flags);
261 Blobs host_plain;
262 host_takes_plain =
263 SUCCEEDED(D3D12SerializeVersionedRootSignature(&plain, &host_plain.blob, &host_plain.error)) &&
264 host_plain.blob;
265 if (host_takes_plain) {
266 ++heap_fallback;
267 if (hr_ours != S_OK || !ours.blob ||
268 !is_heap_flag_fallback(bytes_of(host_plain.blob), bytes_of(ours.blob), f))
269 ++differ;
270 }
271 }
272 if (!rewritten_as_1_1 && !host_takes_plain && SUCCEEDED(hr_ours)) ++differ;
273 }
274 if (SUCCEEDED(hr_ours) && ours.blob) {
275 ID3D12VersionedRootSignatureDeserializer* de = nullptr;
276 if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(ours.blob->GetBufferPointer(),
277 ours.blob->GetBufferSize(),
278 IID_PPV_ARGS(&de))) || !de) {
279 ++lost_flags;
280 } else {
281 const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* got = de->GetUnconvertedRootSignatureDesc();
282 if (!got || flags_of(*got) != f) ++lost_flags;
283 de->Release();
284 }
285 }
286 }
287 char what[240];
288 std::snprintf(what, sizeof(what),
289 "versioned %s: the shim serializes each public flag, 0x80 and all of them as the host does "
290 "(%d byte-identical, %d refused by the host, %d of those kept with the heap-indexed flags, "
291 "%d different)",
292 names[v], same_bytes, host_refused, heap_fallback, differ);
293 check(differ == 0, what);
294 std::snprintf(what, sizeof(what), "versioned %s: every blob the shim returns deserializes with the same flags",
295 names[v]);
296 check(lost_flags == 0, what);
297 std::snprintf(what, sizeof(what), "versioned %s: the caller's descriptor is never modified", names[v]);
298 check(touched_input == 0, what);
299 }
300
301 // The legacy entry point, 1.0 only (it has no 1.1 descriptor), with the same heap-indexed fallback.
302 int differ = 0, legacy_fallback = 0;
303 for (uint32_t f : values) {
304 D3D12_ROOT_SIGNATURE_DESC desc{};
305 desc.Flags = as_flags(f);
306 Blobs host, ours;
307 const HRESULT hr_host = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &host.blob,
308 &host.error);
309 const HRESULT hr_ours = legacy(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &ours.blob, &ours.error);
310 if (SUCCEEDED(hr_host)) {
311 if (FAILED(hr_ours) || !host.blob || !ours.blob || bytes_of(host.blob) != bytes_of(ours.blob)) ++differ;
312 continue;
313 }
314 const uint32_t plain_flags = f & ~rt::d3d12_xs::kDirectlyIndexedFlags;
315 bool host_takes_plain = false;
316 if (plain_flags != f) {
317 D3D12_ROOT_SIGNATURE_DESC plain{};
318 plain.Flags = as_flags(plain_flags);
319 Blobs host_plain;
320 host_takes_plain = SUCCEEDED(D3D12SerializeRootSignature(&plain, D3D_ROOT_SIGNATURE_VERSION_1_0,
321 &host_plain.blob, &host_plain.error)) &&
322 host_plain.blob;
323 if (host_takes_plain) {
324 ++legacy_fallback;
325 if (hr_ours != S_OK || !ours.blob ||
326 !is_heap_flag_fallback(bytes_of(host_plain.blob), bytes_of(ours.blob), f))
327 ++differ;
328 }
329 }
330 if (!host_takes_plain && SUCCEEDED(hr_ours)) ++differ;
331 }
332 char legacy_what[200];
333 std::snprintf(legacy_what, sizeof(legacy_what),
334 "legacy serializer shim gives the host's result for each public flag, 0x80 and all of them "
335 "(%d kept with the heap-indexed flags the host refuses)",
336 legacy_fallback);
337 check(differ == 0, legacy_what);
338
339 // Call site 1 of old upstream PR 7140, by name.
340 const D3D12_VERSIONED_ROOT_SIGNATURE_DESC exe = versioned(D3D_ROOT_SIGNATURE_VERSION_1_1, kExecutableFlags);
341 Blobs host, ours;
342 const HRESULT hr_host = D3D12SerializeVersionedRootSignature(&exe, &host.blob, &host.error);
343 const HRESULT hr_ours = shim(&exe, &ours.blob, &ours.error);
344 check(SUCCEEDED(hr_host) && SUCCEEDED(hr_ours) && host.blob && ours.blob &&
345 bytes_of(host.blob) == bytes_of(ours.blob),
346 "1.1, no parameters, Flags 0x80 (the executable's direct call): the shim's blob is the host's, byte for byte");
347 if (ours.blob) {
348 const std::vector<uint8_t> b = bytes_of(ours.blob);
349 const size_t at = rts0_flags_offset(b);
350 uint32_t stored = 0;
351 if (at) std::memcpy(&stored, b.data() + at, 4);
352 check(at && stored == kExecutableFlags, "the shim's blob stores RTS0 flags 0x80");
353 }
354}
355
356void test_deserializer(const std::vector<uint8_t>& clean_blob) {
357 using DeserializeFn = HRESULT(WINAPI*)(const void*, SIZE_T, REFIID, void**);
358 auto shim = reinterpret_cast<DeserializeFn>(rt::shims::find("d3d12_xs.dll", "D3D12CreateRootSignatureDeserializer"));
359 check(shim != nullptr, "shim registry exposes d3d12_xs!D3D12CreateRootSignatureDeserializer");
360 const size_t at = rts0_flags_offset(clean_blob);
361 if (!shim || !at) return;
362
363 auto flags_through = [&](const std::vector<uint8_t>& blob, bool through_shim, uint32_t& flags) {
364 ID3D12RootSignatureDeserializer* de = nullptr;
365 const HRESULT hr = through_shim ? shim(blob.data(), blob.size(), IID_PPV_ARGS(&de))
366 : D3D12CreateRootSignatureDeserializer(blob.data(), blob.size(),
367 IID_PPV_ARGS(&de));
368 if (FAILED(hr) || !de) return false;
369 flags = static_cast<uint32_t>(de->GetRootSignatureDesc()->Flags);
370 de->Release();
371 return true;
372 };
373
374 // Each public flag, 0x80 and all of them, written into a correctly hashed 1.1 blob.
375 int differ = 0;
376 std::vector<uint32_t> values;
377 for (D3D12_ROOT_SIGNATURE_FLAGS f : kPublicFlags) values.push_back(static_cast<uint32_t>(f));
378 values.push_back(all_public_flags());
379 for (uint32_t f : values) {
380 std::vector<uint8_t> blob = clean_blob;
381 std::memcpy(blob.data() + at, &f, 4);
382 rehash(blob);
383 uint32_t host_flags = 0, shim_flags = 0;
384 const bool host_ok = flags_through(blob, false, host_flags);
385 const bool shim_ok = flags_through(blob, true, shim_flags);
386 if (host_ok != shim_ok || (shim_ok && (shim_flags != f || host_flags != f))) ++differ;
387 }
388 check(differ == 0, "the deserializer shim returns each public flag, 0x80 and all of them as the host does");
389
390 // A blob carrying the Xbox bits on top of 0x80: exactly 0x03000000 is cleared, nothing else changes.
391 std::vector<uint8_t> xbox = clean_blob;
392 const uint32_t xbox_flags = kXboxFlags | kExecutableFlags;
393 std::memcpy(xbox.data() + at, &xbox_flags, 4);
394 rehash(xbox);
395 std::vector<uint8_t> cleared;
396 const bool rewritten = rt::d3d12_xs::copy_rts0_blob_clear_xbox_flags(xbox.data(), xbox.size(), cleared);
397 check(rewritten && cleared.size() == xbox.size(), "a blob with flags 0x03000080 is rewritten");
398 if (!rewritten || cleared.size() != xbox.size()) return;
399 uint32_t got = 0;
400 std::memcpy(&got, cleared.data() + at, 4);
401 check(got == kExecutableFlags && (xbox_flags ^ got) == kXboxFlags,
402 "0x03000080 becomes 0x80: only bits 24 and 25 are cleared");
403 bool rest_same = true;
404 for (size_t i = 0; i < xbox.size(); ++i)
405 if ((i < 4 || i >= 20) && (i < at || i >= at + 4) && xbox[i] != cleared[i]) rest_same = false;
406 check(rest_same, "every byte outside the flags dword and the container hash is unchanged");
407 uint32_t hash[4];
408 rt::d3d12_xs::dxbc_checksum(cleared.data(), cleared.size(), hash);
409 check(std::memcmp(hash, cleared.data() + 4, sizeof(hash)) == 0, "the rewritten blob carries a valid container hash");
410 uint32_t shim_flags = 0;
411 check(flags_through(xbox, true, shim_flags) && shim_flags == kExecutableFlags,
412 "the deserializer shim hands back 0x80 for a blob with flags 0x03000080");
413
414 // The mask is the documented byte (d3d12_xs_rootsig.h): the other high bits go too, the low 24 stay.
415 const uint32_t high_and_low = 0xFC000000u | 0x00FF0000u | kExecutableFlags;
416 std::memcpy(xbox.data() + at, &high_and_low, 4);
417 rehash(xbox);
418 const uint32_t low_kept = 0x00FF0000u | kExecutableFlags;
419 check(rt::d3d12_xs::copy_rts0_blob_clear_xbox_flags(xbox.data(), xbox.size(), cleared) &&
420 std::memcmp(cleared.data() + at, &low_kept, 4) == 0,
421 "flags 0xFCFF0080 become 0x00FF0080: bits 24-31 are cleared, bits 0-23 kept");
422}
423
424} // namespace
425
426int main() {
427 std::printf("root_sig_public_flags_test: the d3d12_xs flag mask keeps every public root-signature flag\n");
428 // A clean 1.1 blob from the host serializer: no parameters, no samplers, flags 0.
429 std::vector<uint8_t> clean;
430 {
431 const D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty = versioned(D3D_ROOT_SIGNATURE_VERSION_1_1, 0);
432 Blobs b;
433 const HRESULT hr = D3D12SerializeVersionedRootSignature(&empty, &b.blob, &b.error);
434 check(SUCCEEDED(hr) && b.blob, "the host serializes an empty 1.1 root signature");
435 if (b.blob) clean = bytes_of(b.blob);
436 }
437 if (!clean.empty()) test_helpers_keep_16_bit_flags(clean);
438 test_serializer_shim_matches_host();
439 if (!clean.empty()) test_deserializer(clean);
440 std::printf("root_sig_public_flags_test: %s (%d failure%s)\n", g_failures ? "FAILED" : "OK", g_failures,
441 g_failures == 1 ? "" : "s");
442 return g_failures ? 1 : 0;
443}
diff --git a/runtime/test/root_signature_test.cpp b/runtime/test/root_signature_test.cpp
index c7f726599..8ecf580ef 100644
--- a/runtime/test/root_signature_test.cpp
+++ b/runtime/test/root_signature_test.cpp
@@ -131,6 +131,39 @@ int main() {
131 check(!r.ok && r.error.find("64-dword") != std::string::npos, 131 check(!r.ok && r.error.find("64-dword") != std::string::npos,
132 "65 constants refused by cost limit"); 132 "65 constants refused by cost limit");
133 } 133 }
134 // 64 constants are within the cost limit, as on the host: pack() and the graphics stages refuse them only for
135 // the spill past the user SGPRs, and that is what the error says; compute spills them whole.
136 {
137 RootSignature sig;
138 sig.params = {consts(64)};
139 const PackResult r = pack(sig);
140 check(!r.ok && r.error.find("64-dword") == std::string::npos && r.error.find("spill") != std::string::npos,
141 "64 constants pass the cost limit (refused only as a spill)");
142 const StagePackResult p = pack_stage(sig, Stage::Pixel);
143 check(!p.ok && p.error.find("64-dword") == std::string::npos && p.error.find("spill") != std::string::npos,
144 "pack_stage: 64 constants pass the cost limit for a pixel shader (refused only as a spill)");
145 const StagePackResult c = pack_stage(sig, Stage::Compute);
146 check(c.ok && c.d3d12_cost == 64 && c.spill_dword == std::vector<uint32_t>({0}) && c.spill_dwords == 64,
147 "pack_stage: 64 constants pass the cost limit for compute, spilled whole");
148 sig.params = {consts(32), consts(0), consts(32)};
149 check(pack(sig).error.find("spill") != std::string::npos, "32 + 0 + 32 constants cost 64, not more");
150 }
151 // A constant parameter of 0 values is valid on the host (the serializer warns, CreateRootSignature answers
152 // S_OK). It takes no dwords and no cost: the parameters around it pack as if it were absent.
153 {
154 RootSignature sig;
155 sig.params = {consts(0), consts(2), consts(0), view(), consts(0)};
156 const PackResult r = pack(sig);
157 check(r.ok && r.dword_count == 2 + 2 && r.d3d12_cost == 2 + 2, "zero-value constants pack to no dwords");
158 check(r.provenance.size() == 4 && r.provenance[0].param_index == 1 && r.provenance[1].param_index == 1 &&
159 r.provenance[2].param_index == 3 && r.provenance[2].sub_index == 0 &&
160 r.provenance[3].param_index == 3 && r.provenance[3].sub_index == 1,
161 "zero-value constants leave no provenance; their neighbours keep their dwords");
162 RootSignature alone;
163 alone.params = {consts(0)};
164 const PackResult a = pack(alone);
165 check(a.ok && a.dword_count == 0 && a.d3d12_cost == 0, "a lone zero-value constant parameter packs");
166 }
134 // A count that wraps a 32-bit sum (1 + 0xFFFFFFFF) is still refused, not packed past dwords[32]. 167 // A count that wraps a 32-bit sum (1 + 0xFFFFFFFF) is still refused, not packed past dwords[32].
135 { 168 {
136 rt::rootsig::RootSignature sig; 169 rt::rootsig::RootSignature sig;
@@ -188,6 +221,19 @@ int main() {
188 const PackResult r = pack(d.sig); 221 const PackResult r = pack(d.sig);
189 check(r.ok && r.dword_count == 3 + 2, "parsed RTS0 packs to 5 dwords"); 222 check(r.ok && r.dword_count == 3 + 2, "parsed RTS0 packs to 5 dwords");
190 } 223 }
224 // The same blob with 0 values in its constant parameter: parsed and packed, the CBV taking the first dwords.
225 {
226 std::vector<uint8_t> payload = build_payload();
227 payload[56] = 0; // the constants' value count (payload at 48: register, space, count)
228 const DecodeResult d = parse_rts0(payload.data(), payload.size());
229 check(d.ok && d.sig.params.size() == 2 && d.sig.params[0].num_values == 0,
230 "RTS0 with a zero-value constant parameter parses");
231 const PackResult r = pack(d.sig);
232 check(r.ok && r.dword_count == 2 && r.provenance[0].param_index == 1, "zero-value RTS0 packs the CBV at 0");
233 const StagePackResult c = pack_stage(d.sig, Stage::Compute);
234 check(c.ok && c.first_sgpr.size() == 2 && c.first_sgpr[0] == 4 && c.first_sgpr[1] == 4 && c.end_sgpr == 6,
235 "pack_stage: zero-value RTS0 puts the CBV at s4");
236 }
191 237
192 // RTS0 controls: unknown version, wild offsets and truncation fail loudly. 238 // RTS0 controls: unknown version, wild offsets and truncation fail loudly.
193 { 239 {
@@ -541,9 +587,26 @@ int main() {
541 bad_param.type = static_cast<ParamType>(0xffffffffu); 587 bad_param.type = static_cast<ParamType>(0xffffffffu);
542 invalid_sig.params = {bad_param}; 588 invalid_sig.params = {bad_param};
543 check(!pack_stage(invalid_sig, Stage::Compute).ok, "pack_stage: invalid parameter enum rejected"); 589 check(!pack_stage(invalid_sig, Stage::Compute).ok, "pack_stage: invalid parameter enum rejected");
590 // Zero-value constants are accepted (the host takes them) and take no SGPRs: the next parameter starts where
591 // they would have.
544 RootSignature zero; 592 RootSignature zero;
545 zero.params = {consts(0)}; 593 zero.params = {consts(0)};
546 check(!pack_stage(zero, Stage::Compute).ok, "pack_stage: zero-value constants rejected"); 594 const StagePackResult lone = pack_stage(zero, Stage::Compute);
595 check(lone.ok && lone.first_sgpr.size() == 1 && lone.first_sgpr[0] == 4 && lone.end_sgpr == 4 &&
596 lone.spill_dwords == 0,
597 "pack_stage: zero-value constants accepted");
598 zero.params = {consts(1), consts(0), table(), consts(0), consts(26)};
599 const StagePackResult mixed = pack_stage(zero, Stage::Compute);
600 check(mixed.ok && mixed.first_sgpr.size() == 5 && mixed.first_sgpr[0] == 4 && mixed.first_sgpr[1] == 5 &&
601 mixed.first_sgpr[2] == 5 && mixed.first_sgpr[3] == 6 && mixed.first_sgpr[4] == 6 &&
602 mixed.end_sgpr == 32 && mixed.spill_dwords == 0 && mixed.d3d12_cost == 1 + 1 + 26,
603 "pack_stage: zero-value constants between others fill compute exactly, offsets unchanged");
604 // In the compute spill array a zero-value constant takes no dwords either: the next parameter shares its offset.
605 zero.params = {consts(28), table(), consts(0), consts(1)};
606 const StagePackResult spilled = pack_stage(zero, Stage::Compute);
607 check(spilled.ok && spilled.end_sgpr == 32 &&
608 spilled.spill_dword == std::vector<uint32_t>({kNoSpill, 0, 1, 1}) && spilled.spill_dwords == 2,
609 "pack_stage: zero-value constants in the compute spill array take no dwords");
547 RootSignature costly; 610 RootSignature costly;
548 costly.params = {consts(32), consts(33)}; 611 costly.params = {consts(32), consts(33)};
549 const StagePackResult costly_r = pack_stage(costly, Stage::Compute); 612 const StagePackResult costly_r = pack_stage(costly, Stage::Compute);
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp
index 2448ab7b8..ee49c48eb 100644
--- a/runtime/test/shader_library_test.cpp
+++ b/runtime/test/shader_library_test.cpp
@@ -820,6 +820,80 @@ int main() {
820 std::filesystem::remove_all(dir); 820 std::filesystem::remove_all(dir);
821 } 821 }
822 822
823 // The descriptor-table layout marker (`descriptor_table` in each module's meta, descriptor_table.h): absent is
824 // the old plain layout. The kind word is additive - a tagged module reads it, a plain one ignores it and reads
825 // the index at the same place - so one tagged module needs the tagged layout however many plain ones a merged or
826 // partial index holds; counting entries would let a plain majority hand every tagged module an all-zero kind, and
827 // every image read through another dimension's array would fall back. LEONIDA_DESCRIPTOR_TABLE overrides in the
828 // device, through descriptor_table_layout_from_env.
829 {
830 const auto root = dir / "table_layouts";
831 const auto write_index = [](const std::filesystem::path& folder, const std::string& modules) {
832 std::filesystem::create_directories(folder);
833 std::ofstream index(folder / "index.json", std::ios::binary);
834 index << "{" << modules << "}";
835 };
836 const auto module = [](const char* name, const char* marker) {
837 std::string out = "{\"stage\": \"vs\", \"fssm_sha256\": \"" + std::string(name) + "\"";
838 if (marker) out += ", \"descriptor_table\": \"" + std::string(marker) + "\"";
839 return out + "}";
840 };
841 const auto census = [](const ShaderLibrary& library, std::size_t tagged, std::size_t plain) {
842 return library.descriptor_table_census().tagged == tagged &&
843 library.descriptor_table_census().plain == plain;
844 };
845
846 // A library translated before the kind word (or with --descriptor-table plain) is plain.
847 write_index(root, "\"a\": " + module("aa", nullptr) + ", \"b\": " + module("bb", nullptr));
848 ShaderLibrary all_plain;
849 CHECK(all_plain.load(root.string(), &error));
850 CHECK(census(all_plain, 0, 2) &&
851 all_plain.descriptor_table_layout() == DescriptorTableLayout::plain);
852
853 write_index(root, "\"a\": " + module("aa", "tagged") + ", \"b\": " + module("bb", "tagged"));
854 ShaderLibrary all_tagged;
855 CHECK(all_tagged.load(root.string(), &error));
856 CHECK(census(all_tagged, 2, 0) &&
857 all_tagged.descriptor_table_layout() == DescriptorTableLayout::tagged);
858
859 // One tagged module among plain ones: the tagged layout (the old vote gave the plain majority's choice and
860 // every image of another dimension fell back).
861 write_index(root, "\"a\": " + module("aa", "tagged") + ", \"b\": " + module("bb", nullptr) + ", \"c\": " +
862 module("cc", "plain") + ", \"d\": " + module("dd", nullptr));
863 ShaderLibrary tagged_minority;
864 CHECK(tagged_minority.load(root.string(), &error));
865 CHECK(census(tagged_minority, 1, 3) &&
866 tagged_minority.descriptor_table_layout() == DescriptorTableLayout::tagged);
867
868 write_index(root, "\"a\": " + module("aa", nullptr) + ", \"b\": " + module("bb", "tagged"));
869 ShaderLibrary tied;
870 CHECK(tied.load(root.string(), &error));
871 CHECK(census(tied, 1, 1) && tied.descriptor_table_layout() == DescriptorTableLayout::tagged);
872
873 // A sub-index's marker counts too, and loading a folder replaces the census rather than adding to it.
874 write_index(root, "\"a\": " + module("aa", nullptr) + ", \"b\": " + module("bb", nullptr));
875 write_index(root / "fspx", "\"upscaler\": " + module("cc", "tagged"));
876 ShaderLibrary sub_index;
877 CHECK(sub_index.load(root.string(), &error));
878 CHECK(census(sub_index, 1, 2) && sub_index.descriptor_table_layout() == DescriptorTableLayout::tagged);
879 CHECK(sub_index.load(root.string(), &error) && census(sub_index, 1, 2)); // reload, not accumulate
880 std::filesystem::remove_all(root / "fspx");
881 CHECK(sub_index.load(root.string(), &error) && census(sub_index, 0, 2) &&
882 sub_index.descriptor_table_layout() == DescriptorTableLayout::plain);
883
884 // LEONIDA_DESCRIPTOR_TABLE: an exact layout name wins over the vote; anything else is ignored, and a refused
885 // value leaves the caller's layout alone.
886 DescriptorTableLayout chosen = DescriptorTableLayout::tagged;
887 CHECK(descriptor_table_layout_from_env("plain", &chosen) && chosen == DescriptorTableLayout::plain);
888 CHECK(descriptor_table_layout_from_env("tagged", &chosen) && chosen == DescriptorTableLayout::tagged);
889 CHECK(!descriptor_table_layout_from_env(nullptr, &chosen));
890 CHECK(!descriptor_table_layout_from_env("", &chosen));
891 CHECK(!descriptor_table_layout_from_env("Plain", &chosen));
892 CHECK(!descriptor_table_layout_from_env("other", &chosen));
893 CHECK(chosen == DescriptorTableLayout::tagged);
894 std::filesystem::remove_all(dir);
895 }
896
823 if (const int line = fspx_checks()) return line; 897 if (const int line = fspx_checks()) return line;
824 898
825 // FSPX entries: found by fspx_code_sha256, in the main index or in <dir>/fspx/index.json (named "fspx/<name>"). 899 // FSPX entries: found by fspx_code_sha256, in the main index or in <dir>/fspx/index.json (named "fspx/<name>").
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index 03a7ecd22..377f7025e 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -198,6 +198,10 @@ def translate_tests(work, names):
198 # 128-byte push constants: the tail in a set-1 uniform block. The values the test programs accept (vk_pc_tail.h). 198 # 128-byte push constants: the tail in a set-1 uniform block. The values the test programs accept (vk_pc_tail.h).
199 if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"): 199 if (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on"):
200 cmd.append("--pc-tail-ubo") 200 cmd.append("--pc-tail-ubo")
201 # The descriptor-table entry layout: tagged (the default) is what the runtime fills. plain is the old one, for a
202 # module translated before the kind word existed (and for the runtime test that must show the old behaviour).
203 if os.environ.get("LEONIDA_DESCRIPTOR_TABLE"):
204 cmd += ["--descriptor-table", os.environ["LEONIDA_DESCRIPTOR_TABLE"]]
201 return subprocess.run(cmd).returncode 205 return subprocess.run(cmd).returncode
202 206
203 207
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 4653a37f2..39a3179a4 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -108,7 +108,7 @@ WAVE32_DUMPS = ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm
108 "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", 108 "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32",
109 "cs_w32_lds_subdword", "cs_w32_lds_wide", 109 "cs_w32_lds_subdword", "cs_w32_lds_wide",
110 "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", 110 "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext",
111 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", 111 "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec",
112 "cs_mask_vgpr_exec", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", 112 "cs_mask_vgpr_exec", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi",
113 "cs_w32_exec_computed") 113 "cs_w32_exec_computed")
114# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is 114# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is
@@ -117,7 +117,7 @@ WAVE32_DUMPS = ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm
117# otherwise pick a narrower size and return different words (#774). 117# otherwise pick a narrower size and return different words (#774).
118WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} 118WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"}
119WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", 119WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const",
120 "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_permlane_fi", 120 "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_permlane_fi",
121 "cs_w32_exec_computed") 121 "cs_w32_exec_computed")
122CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), 122CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]),
123 ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), 123 ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]),
@@ -164,6 +164,12 @@ CS_DUMPS = [*CS_DPP, ("cs_smem_vcc_base", CS_SMEM_VCC), ("cs_store", CS_STORE),
164 # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) 164 # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header)
165 ("cs_lds_xchg64_ext", [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, 165 ("cs_lds_xchg64_ext", [0x11110003, 0x33333333, 0xF00FF000, 0x04030201,
166 0x40302010, 0x70500705, 0x3FC00000, 0x80000000]), 166 0x40302010, 0x70500705, 0x3FC00000, 0x80000000]),
167 # ds_wrxchg2_rtn_b32's pair cases and ds_wrxchg2st64_rtn_b32
168 # (cs_w32_wrxchg2_ext.asm / cs_w32_wrxchg2st64.asm headers)
169 ("cs_w32_wrxchg2_ext", [0x77777777, 0x88880008, 0x99990009, 0xDEADBEEF,
170 0xAAAAAAAA, 0xBBBBBBBB, 0x12341234, 0x56785678]),
171 ("cs_w32_wrxchg2st64", [0x33333333, 0x44444444, 0x55550005, 0x66660006,
172 0xB0B00084, 0xB0B00088, 0xB0B00140, 0xB0B002C0]),
167 # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) 173 # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header)
168 ("cs_lds_atomics_ext", [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, 174 ("cs_lds_atomics_ext", [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F,
169 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700]), 175 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700]),
@@ -776,7 +782,8 @@ W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]),
776 ("cs_w64x_cmp_sdst", [10240, 6144, 2053, 8224, 7714, 6184, 4144, 5])] 782 ("cs_w64x_cmp_sdst", [10240, 6144, 2053, 8224, 7714, 6184, 4144, 5])]
777# A 40-thread group (one partial wave) cannot use --require-wave64 (full subgroups), so it asks for subgroup size 64. 783# A 40-thread group (one partial wave) cannot use --require-wave64 (full subgroups), so it asks for subgroup size 64.
778W64X_PARTIAL = [("cs_w64x_partial", [40, 40, 528, 0, 0, 532, 539, 524820]), 784W64X_PARTIAL = [("cs_w64x_partial", [40, 40, 528, 0, 0, 532, 539, 524820]),
779 ("cs_w64x_partial_scmp", [0, 1, 0, 1, 1, 1, 1, 0])] 785 ("cs_w64x_partial_scmp", [0, 1, 0, 1, 1, 1, 1, 0]),
786 ("cs_w64x_partial_swizzle", [508, 523, 0, 0, 528, 0, 531, 0])]
780PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000), 787PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000),
781 # exp mrt0 done (no vm) with every lane on, EXEC off afterwards: written (.asm header, measured on gfx1036) 788 # exp mrt0 done (no vm) with every lane on, EXEC off afterwards: written (.asm header, measured on gfx1036)
782 "ps_exp_color_mask": (0x40000000, 0x40800000, 0x40000000, 0x40800000), 789 "ps_exp_color_mask": (0x40000000, 0x40800000, 0x40000000, 0x40800000),
diff --git a/runtime/test/shaders/cs_w32_wrxchg2_ext.asm b/runtime/test/shaders/cs_w32_wrxchg2_ext.asm
new file mode 100644
index 000000000..8744ddeca
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_wrxchg2_ext.asm
@@ -0,0 +1,91 @@
1; GPU test for ds_wrxchg2_rtn_b32, part two: the four cases cs_w32_new_ops.asm leaves out
2; (docs/design.md "ds_wrxchg2_rtn_b32, ds_wrxchg2st64_rtn_b32" row). cs_w32_new_ops covers the first
3; returned word and data1 in LDS with offset0:2 offset1:5; this fixture covers:
4;
5; - the SECOND returned word of the pair, which is data0 when both offsets name one dword
6; - both offsets on one dword (the second exchange reads back what the first wrote)
7; - vdst aliasing the data VGPRs (the data must be read before vdst is written)
8; - that an exchange at one base leaves a neighbouring LDS word alone
9;
10; LDS 4 KiB (RSRC2 0x40088), group 32x1x1, only lane 0 runs (32 lanes on one LDS address would race:
11; which lane's exchange runs first is up to the hardware). LDS is seeded by ds_write_b32 before each case.
12; Every word is stored raw, in this order:
13;
14; out[0] both offsets on one dword: ds_wrxchg2_rtn_b32 at base 0x200, offset0:1 offset1:1
15; (both = element 0x204). Seeded M[0x204]=0x77777777, data0=0x88880008, data1=0x99990009.
16; vdst[0] = the word the first exchange took out of M -> 0x77777777
17; out[1] vdst[1] = the second exchange's return, which is data0, not the
18; word the first exchange wrote -> 0x88880008
19; out[2] M[0x204] after both: data1 landed -> 0x99990009
20; out[3] M[0x700], seeded 0xDEADBEEF before the exchange and read after it:
21; the exchange touched only 0x204 -> 0xDEADBEEF
22; out[4] vdst aliases the data VGPRs: ds_wrxchg2_rtn_b32 v[4:5], ... with v4=0x12341234 v5=0x56785678
23; at base 0x300, offset0:0 offset1:2, M[0x300]=0xAAAAAAAA, M[0x308]=0xBBBBBBBB.
24; vdst[0] = the old word, so the data was read before the write -> 0xAAAAAAAA
25; out[5] vdst[1] = the old word at 0x308 -> 0xBBBBBBBB
26; out[6] M[0x300] after: data0 -> 0x12341234
27; out[7] M[0x308] after: data1 -> 0x56785678
28;
29; Run: vk_compute_test cs_w32_wrxchg2_ext.spv 1 dump
30; -> out[0..7] = 0x77777777 0x88880008 0x99990009 0xDEADBEEF
31; 0xAAAAAAAA 0xBBBBBBBB 0x12341234 0x56785678
32; rsrc2: 0x40088
33; group: 32,1,1
34; mattr: +wavefrontsize32,-wavefrontsize64
35v_cmpx_eq_u32_e32 0, v0
36
37; --- both offsets on one dword (element 0x204) ---
38v_mov_b32_e32 v1, 0x204
39v_mov_b32_e32 v4, 0x77777777
40ds_write_b32 v1, v4
41v_mov_b32_e32 v2, 0x700
42v_mov_b32_e32 v5, 0xDEADBEEF
43ds_write_b32 v2, v5
44s_waitcnt lgkmcnt(0)
45v_mov_b32_e32 v1, 0x200
46v_mov_b32_e32 v4, 0x88880008
47v_mov_b32_e32 v5, 0x99990009
48ds_wrxchg2_rtn_b32 v[12:13], v1, v4, v5 offset0:1 offset1:1
49s_waitcnt lgkmcnt(0)
50v_mov_b32_e32 v21, 0
51buffer_store_dword v12, v21, s[0:3], 0 offen
52v_mov_b32_e32 v21, 4
53buffer_store_dword v13, v21, s[0:3], 0 offen
54v_mov_b32_e32 v1, 0x204
55ds_read_b32 v10, v1
56v_mov_b32_e32 v2, 0x700
57ds_read_b32 v11, v2
58s_waitcnt lgkmcnt(0)
59v_mov_b32_e32 v21, 8
60buffer_store_dword v10, v21, s[0:3], 0 offen
61v_mov_b32_e32 v21, 12
62buffer_store_dword v11, v21, s[0:3], 0 offen
63
64; --- vdst aliases the data VGPRs ---
65v_mov_b32_e32 v1, 0x300
66v_mov_b32_e32 v4, 0xAAAAAAAA
67ds_write_b32 v1, v4
68v_mov_b32_e32 v2, 0x308
69v_mov_b32_e32 v5, 0xBBBBBBBB
70ds_write_b32 v2, v5
71s_waitcnt lgkmcnt(0)
72v_mov_b32_e32 v1, 0x300
73v_mov_b32_e32 v4, 0x12341234
74v_mov_b32_e32 v5, 0x56785678
75ds_wrxchg2_rtn_b32 v[4:5], v1, v4, v5 offset0:0 offset1:2
76s_waitcnt lgkmcnt(0)
77v_mov_b32_e32 v21, 16
78buffer_store_dword v4, v21, s[0:3], 0 offen
79v_mov_b32_e32 v21, 20
80buffer_store_dword v5, v21, s[0:3], 0 offen
81ds_read_b32 v10, v1
82s_waitcnt lgkmcnt(0)
83v_mov_b32_e32 v21, 24
84buffer_store_dword v10, v21, s[0:3], 0 offen
85v_mov_b32_e32 v1, 0x308
86ds_read_b32 v11, v1
87s_waitcnt lgkmcnt(0)
88v_mov_b32_e32 v21, 28
89buffer_store_dword v11, v21, s[0:3], 0 offen
90
91s_endpgm
diff --git a/runtime/test/shaders/cs_w32_wrxchg2st64.asm b/runtime/test/shaders/cs_w32_wrxchg2st64.asm
new file mode 100644
index 000000000..2f2b25a9a
--- /dev/null
+++ b/runtime/test/shaders/cs_w32_wrxchg2st64.asm
@@ -0,0 +1,93 @@
1; GPU test for ds_wrxchg2st64_rtn_b32 (docs/design.md "ds_wrxchg2_rtn_b32, ds_wrxchg2st64_rtn_b32"
2; row). Neither this form nor the row's st64 step is covered by a GPU fixture on main: cs_w32_new_ops
3; runs ds_wrxchg2_rtn_b32 only, and cs_lds_xchg64_ext runs the _b64 pair forms. The row and the gfx1100
4; measurement both say the st64 unit is 64 dwords = 256 bytes, i.e. offset0:1 and offset1:2 address
5; vaddr + 256 and vaddr + 512; this fixture pins that on a GPU.
6;
7; LDS 4 KiB (RSRC2 0x40088), group 32x1x1, only lane 0 runs. Base 0x80, so the two elements are at
8; 0x180 and 0x280 and neither is where a non-st64 unit would have put them (0x84 and 0x88) - those two
9; words are seeded too and must come back untouched, which is what proves the step size.
10; Every word is stored raw, in this order:
11;
12; out[0] vdst[0] = the old word at 0x180 -> 0x33333333
13; out[1] vdst[1] = the old word at 0x280 -> 0x44444444
14; out[2] M[0x180] after: data0 -> 0x55550005
15; out[3] M[0x280] after: data1 -> 0x66660006
16; out[4] M[0x84], where a 4-byte step would have written data0: untouched -> 0xB0B00084
17; out[5] M[0x88], where a 4-byte step would have written data1: untouched -> 0xB0B00088
18; out[6] M[0x140], one 256-byte step short of 0x180: untouched -> 0xB0B00140
19; out[7] M[0x2c0], one 256-byte step past 0x280: untouched -> 0xB0B002C0
20;
21; Run: vk_compute_test cs_w32_wrxchg2st64.spv 1 dump
22; -> out[0..7] = 0x33333333 0x44444444 0x55550005 0x66660006
23; 0xB0B00084 0xB0B00088 0xB0B00140 0xB0B002C0
24; rsrc2: 0x40088
25; group: 32,1,1
26; mattr: +wavefrontsize32,-wavefrontsize64
27v_cmpx_eq_u32_e32 0, v0
28
29; --- seed the two real elements and the four words the exchange must not touch ---
30v_mov_b32_e32 v1, 0x180
31v_mov_b32_e32 v4, 0x33333333
32ds_write_b32 v1, v4
33v_mov_b32_e32 v1, 0x280
34v_mov_b32_e32 v4, 0x44444444
35ds_write_b32 v1, v4
36v_mov_b32_e32 v1, 0x84
37v_mov_b32_e32 v4, 0xB0B00084
38ds_write_b32 v1, v4
39v_mov_b32_e32 v1, 0x88
40v_mov_b32_e32 v4, 0xB0B00088
41ds_write_b32 v1, v4
42v_mov_b32_e32 v1, 0x140
43v_mov_b32_e32 v4, 0xB0B00140
44ds_write_b32 v1, v4
45v_mov_b32_e32 v1, 0x2C0
46v_mov_b32_e32 v4, 0xB0B002C0
47ds_write_b32 v1, v4
48s_waitcnt lgkmcnt(0)
49
50; --- the st64 pair exchange: base 0x80, offset0:1 offset1:2 ---
51v_mov_b32_e32 v4, 0x55550005
52v_mov_b32_e32 v5, 0x66660006
53v_mov_b32_e32 v1, 0x80
54ds_wrxchg2st64_rtn_b32 v[12:13], v1, v4, v5 offset0:1 offset1:2
55s_waitcnt lgkmcnt(0)
56
57v_mov_b32_e32 v21, 0
58buffer_store_dword v12, v21, s[0:3], 0 offen
59v_mov_b32_e32 v21, 4
60buffer_store_dword v13, v21, s[0:3], 0 offen
61
62; --- read back the two elements and the four words that must be untouched ---
63v_mov_b32_e32 v1, 0x180
64ds_read_b32 v10, v1
65v_mov_b32_e32 v2, 0x280
66ds_read_b32 v11, v2
67s_waitcnt lgkmcnt(0)
68v_mov_b32_e32 v21, 8
69buffer_store_dword v10, v21, s[0:3], 0 offen
70v_mov_b32_e32 v21, 12
71buffer_store_dword v11, v21, s[0:3], 0 offen
72
73v_mov_b32_e32 v1, 0x84
74ds_read_b32 v3, v1
75v_mov_b32_e32 v1, 0x88
76ds_read_b32 v6, v1
77s_waitcnt lgkmcnt(0)
78v_mov_b32_e32 v21, 16
79buffer_store_dword v3, v21, s[0:3], 0 offen
80v_mov_b32_e32 v21, 20
81buffer_store_dword v6, v21, s[0:3], 0 offen
82
83v_mov_b32_e32 v1, 0x140
84ds_read_b32 v3, v1
85v_mov_b32_e32 v1, 0x2C0
86ds_read_b32 v6, v1
87s_waitcnt lgkmcnt(0)
88v_mov_b32_e32 v21, 24
89buffer_store_dword v3, v21, s[0:3], 0 offen
90v_mov_b32_e32 v21, 28
91buffer_store_dword v6, v21, s[0:3], 0 offen
92
93s_endpgm
diff --git a/runtime/test/shaders/cs_w64x_partial_swizzle.asm b/runtime/test/shaders/cs_w64x_partial_swizzle.asm
new file mode 100644
index 000000000..44ac9061d
--- /dev/null
+++ b/runtime/test/shaders/cs_w64x_partial_swizzle.asm
@@ -0,0 +1,78 @@
1; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm
2; Partial wave64, ds_swizzle_b32 / ds_bpermute_b32 from a lane that doesn't exist: a 40x1x1 group is one wave with
3; lanes 0-39 running and 40-63 missing. A source lane that doesn't exist reads 0 (RDNA2 ISA, ds_swizzle/ds_bpermute of
4; a lane that isn't running; on gfx1036 through tools/hw_oracle, 40 threads, native wave64: lanes 32-39 of SWAP 8 and
5; of BROADCAST 16,15 read 0). The exchange sits after a vote and an s_cbranch_execz, as in the crosslane_fuzz
6; programs that found it (seed 48315): with --wave64-emulate, RADV (Mesa 26.3.1) turned the store, barrier and load of
7; the exchange slot into a subgroup swizzle that fetched the missing lane's register, so lanes 32-39 read garbage
8; that changed between runs although the slot was zeroed.
9; v1 = lane, v2 = 500 + lane, s8 = s_bcnt1 of EXEC (40, an exchange before the branch).
10; v3 = ds_swizzle SWAP 8 of v2 (source lane ^ 8): lane 0 -> 8 -> 508, lane 31 -> 23 -> 523, lane 33 -> 41 -> 0,
11; lane 39 -> 47 -> 0.
12; v4 = ds_bpermute with addr = (lane ^ 8) * 4 (each half its own 32 lanes): lane 20 -> 28 -> 528, lane 33 -> 41 -> 0.
13; v5 = ds_swizzle BROADCAST 16,15 (lane 15 of each group of 16): lane 20 -> 31 -> 531, lane 35 -> 47 -> 0.
14; Stores: out[0] lane 0 v3, out[1] lane 31 v3, out[2] lane 33 v3, out[3] lane 39 v3, out[4] lane 20 v4,
15; out[5] lane 33 v4, out[6] lane 20 v5, out[7] lane 35 v5.
16; As for cs_w64x_partial, 40 threads can't have full subgroups: check.py asks for subgroup size 64 (32 when emulated).
17; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_w64x_partial_swizzle.spv 1 dump
18; -> out[0..7] = 508 523 0 0 528 0 531 0
19; mattr: +wavefrontsize64,-wavefrontsize32
20; group: 40,1,1
21v_mbcnt_lo_u32_b32 v1, -1, 0
22v_mbcnt_hi_u32_b32 v1, -1, v1
23v_add_nc_u32_e32 v2, 500, v1
24v_mov_b32_e32 v3, 99
25v_mov_b32_e32 v4, 99
26v_mov_b32_e32 v5, 99
27s_mov_b64 s[6:7], exec
28s_bcnt1_i32_b64 s8, exec
29v_cmp_gt_u32_e64 s[4:5], 48, v1
30s_and_saveexec_b64 s[10:11], s[4:5]
31s_cbranch_execz 9
32ds_swizzle_b32 v3, v2 offset:swizzle(SWAP,8)
33ds_swizzle_b32 v5, v2 offset:swizzle(BROADCAST,16,15)
34v_xor_b32_e32 v6, 8, v1
35v_lshlrev_b32_e32 v6, 2, v6
36ds_bpermute_b32 v4, v6, v2
37s_waitcnt lgkmcnt(0)
38s_mov_b64 exec, s[6:7]
39v_cmpx_eq_u32_e32 0, v1
40v_mov_b32_e32 v20, v3
41v_mov_b32_e32 v21, 0
42buffer_store_dword v20, v21, s[0:3], 0 offen
43s_mov_b64 exec, s[6:7]
44v_cmpx_eq_u32_e32 31, v1
45v_mov_b32_e32 v20, v3
46v_mov_b32_e32 v21, 4
47buffer_store_dword v20, v21, s[0:3], 0 offen
48s_mov_b64 exec, s[6:7]
49v_cmpx_eq_u32_e32 33, v1
50v_mov_b32_e32 v20, v3
51v_mov_b32_e32 v21, 8
52buffer_store_dword v20, v21, s[0:3], 0 offen
53s_mov_b64 exec, s[6:7]
54v_cmpx_eq_u32_e32 39, v1
55v_mov_b32_e32 v20, v3
56v_mov_b32_e32 v21, 12
57buffer_store_dword v20, v21, s[0:3], 0 offen
58s_mov_b64 exec, s[6:7]
59v_cmpx_eq_u32_e32 20, v1
60v_mov_b32_e32 v20, v4
61v_mov_b32_e32 v21, 16
62buffer_store_dword v20, v21, s[0:3], 0 offen
63s_mov_b64 exec, s[6:7]
64v_cmpx_eq_u32_e32 33, v1
65v_mov_b32_e32 v20, v4
66v_mov_b32_e32 v21, 20
67buffer_store_dword v20, v21, s[0:3], 0 offen
68s_mov_b64 exec, s[6:7]
69v_cmpx_eq_u32_e32 20, v1
70v_mov_b32_e32 v20, v5
71v_mov_b32_e32 v21, 24
72buffer_store_dword v20, v21, s[0:3], 0 offen
73s_mov_b64 exec, s[6:7]
74v_cmpx_eq_u32_e32 35, v1
75v_mov_b32_e32 v20, v5
76v_mov_b32_e32 v21, 28
77buffer_store_dword v20, v21, s[0:3], 0 offen
78s_endpgm
diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py
index e28d03d2f..35936afe8 100644
--- a/runtime/test/shaders/w64_graphics.py
+++ b/runtime/test/shaders/w64_graphics.py
@@ -30,8 +30,15 @@ The vs_w64_* fixtures (TEST-251) are vertex shaders: Vulkan cannot require a ver
30come from RADV, which runs the VS stage as wave64 by default and as wave32 with RADV_PERFTEST=gewave32 (GFX10+). 30come from RADV, which runs the VS stage as wave64 by default and as wave32 with RADV_PERFTEST=gewave32 (GFX10+).
31Each draws 960 vertices with zero area (VKH_VERTICES) and stores four words per vertex to the heap; vs_w64_c_lane_id 31Each draws 960 vertices with zero area (VKH_VERTICES) and stores four words per vertex to the heap; vs_w64_c_lane_id
32doubles as the probe that the wave size really changed, and without RADV only the default-size checks run. RADV packs 32doubles as the probe that the wave size really changed, and without RADV only the default-size checks run. RADV packs
3362 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run is a repacking, not the two halves of 3362 or 64 vertices into a wave64 and 30 or 32 into a wave32, and the wave32 waves are the two halves of the wave64 ones:
34the 64-lane waves: a stricter test of tiers A and B, which key every word on the vertex index. 34waves of 64, 62, 64, 62 ... vertices starting at vertices 0, 64, 126, 190 ... at wave64, and of 32, 32, 32, 30 ...
35starting at 0, 32, 64, 96, 126 ... at wave32 (a period of 126 vertices both ways). Each vertex's wave32 lane is its
36wave64 lane & 31 (vs_w64_c_lane_id, all 960 vertices; RADV Mesa 26.3.1 on a gfx1036 iGPU (Raphael) and an RX 7900 XTX
37(NAVI31, RDNA3); TEST-1700). GFX12 gives the same waves and starts, with every wave32 wave inside one half of a wave64
38wave (RX 9070 XT, GFX1201, RDNA4, RADV Mesa 26.2.6; from sperm's old upstream PR 7354). So the 32-lane run is the
39cut into halves the tiers describe, not a repacking: it does not move a vertex into another wave or lane group. Mind
40it when writing a VS fixture: waves start at even vertices that are not all multiples of 4 (126, 252, ...), so the
41lane ^ 1 of a vertex v holds vertex v ^ 1, but lane ^ 2, ^ 3 or ^ 16 need not hold v ^ 2, v ^ 3 or v ^ 16.
35 42
36The gs_w64_* fixtures are legacy geometry shaders, switched the same way (gewave32 covers the whole NGG stage). Each is 43The gs_w64_* fixtures are legacy geometry shaders, switched the same way (gewave32 covers the whole NGG stage). Each is
37drawn after vs_ids with VKH_GS, finds its triangle from the vertex number vs_ids passes in TEXCOORD0, and stores four 44drawn after vs_ids with VKH_GS, finds its triangle from the vertex number vs_ids passes in TEXCOORD0, and stores four
diff --git a/runtime/test/spirv_f16_halves_test.cpp b/runtime/test/spirv_f16_halves_test.cpp
index 61604f14a..8cd2c4796 100644
--- a/runtime/test/spirv_f16_halves_test.cpp
+++ b/runtime/test/spirv_f16_halves_test.cpp
@@ -419,6 +419,25 @@ int main() {
419 CHECK(vs_w == vs_orig && ps_w == ps_orig); 419 CHECK(vs_w == vs_orig && ps_w == ps_orig);
420 } 420 }
421 421
422 // 11. Custom top_location relocates halves into <= top_location.
423 {
424 ShaderEntry vs_e, ps_e;
425 vs_e.f16_halves = {};
426 ps_e.f16_halves = {{0, {28, 29}}};
427 // 10 raw VS outputs (0..9); top_location = 14 leaves slots 10..14 free.
428 auto vs_w = build_vs(0x00010500u, 10, vs_e.f16_halves);
429 auto ps_w = build_ps(0x00010500u, {0}, ps_e.f16_halves);
430 std::string err;
431 CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err, 14));
432 std::map<std::uint32_t, std::uint32_t> vs_locs;
433 int unpacks = 0, privs = 0;
434 std::set<std::uint32_t> ep_iface;
435 CHECK(verify_spirv_structure(vs_w, kStorageOutput, vs_locs, unpacks, privs, ep_iface));
436 for (const auto& [loc, var] : vs_locs) {
437 CHECK(loc <= 14);
438 }
439 }
440
422 std::printf("spirv_f16_halves_test: all checks passed\n"); 441 std::printf("spirv_f16_halves_test: all checks passed\n");
423 return 0; 442 return 0;
424} 443}
diff --git a/runtime/test/startup_trace_test.cpp b/runtime/test/startup_trace_test.cpp
index 170ea39d5..2b8671099 100644
--- a/runtime/test/startup_trace_test.cpp
+++ b/runtime/test/startup_trace_test.cpp
@@ -7,7 +7,8 @@
7// 0x1220 reads address 0 (an access violation the test catches) 7// 0x1220 reads address 0 (an access violation the test catches)
8// The loader maps it with the trace open, the test calls the three functions, closes the trace and checks the lines: 8// The loader maps it with the trace open, the test calls the three functions, closes the trace and checks the lines:
9// map, unimplemented_call with the caller as module+RVA, debug_string with the text, exception with the faulting 9// map, unimplemented_call with the caller as module+RVA, debug_string with the text, exception with the faulting
10// RVA and access kind. No game data and no GPU are involved. 10// RVA and access kind. A second image with delay imports checks delay_import_unimplemented (make_delay_image).
11// No game data and no GPU are involved.
11// LEONIDA_TEST_DIR names the folder for the image and the trace, as for loader_test; the default is the temp folder. 12// LEONIDA_TEST_DIR names the folder for the image and the trace, as for loader_test; the default is the temp folder.
12#include <windows.h> 13#include <windows.h>
13 14
@@ -279,6 +280,102 @@ void test_trace(const fs::path& dir) {
279 check(find_line(lines, "exit") == &lines.back(), "exit comes last"); 280 check(find_line(lines, "exit") == &lines.back(), "exit comes last");
280} 281}
281 282
283// A DLL image with no code: one ordinary import that binds to nothing, and two delay-import descriptors, one naming a
284// function nothing serves and one naming kernel32!GetTickCount (bound to the host). Delay imports are bound when the
285// image is loaded, so the trace names the missing one then; the ordinary missing import and the bound delay import
286// give no such event.
287constexpr const char* kDelayImageName = "delay_image.bin";
288
289std::vector<uint8_t> make_delay_image() {
290 std::vector<uint8_t> b(0x600, 0);
291 auto* dos = reinterpret_cast<IMAGE_DOS_HEADER*>(b.data());
292 dos->e_magic = IMAGE_DOS_SIGNATURE;
293 dos->e_lfanew = 0x80;
294 auto* nt = reinterpret_cast<IMAGE_NT_HEADERS64*>(b.data() + dos->e_lfanew);
295 nt->Signature = IMAGE_NT_SIGNATURE;
296 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64;
297 nt->FileHeader.NumberOfSections = 1;
298 nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64);
299 nt->FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_LARGE_ADDRESS_AWARE;
300 nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
301 nt->OptionalHeader.ImageBase = 0x1a0000000;
302 nt->OptionalHeader.SizeOfHeaders = 0x200;
303 nt->OptionalHeader.SizeOfImage = 0x2000;
304 nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
305 nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
306 auto* sec = IMAGE_FIRST_SECTION(nt);
307 std::memcpy(sec->Name, ".data", 6);
308 sec->VirtualAddress = kTextRva;
309 sec->Misc.VirtualSize = 0x400;
310 sec->PointerToRawData = 0x200;
311 sec->SizeOfRawData = 0x400;
312 sec->Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
313
314 uint8_t* data = b.data() + 0x200;
315 auto put_string = [&](uint32_t off, const char* s) { std::strcpy(reinterpret_cast<char*>(data + off), s); };
316 // One name table entry and its terminator at `lookup_off`, the import's hint/name at `hint_off`.
317 auto put_thunk = [&](uint32_t lookup_off, uint32_t hint_off, const char* name) {
318 *reinterpret_cast<uint64_t*>(data + lookup_off) = kTextRva + hint_off;
319 put_string(hint_off + 2, name);
320 };
321 put_string(0x100, "leonida_trace_probe.dll");
322 put_string(0x120, "kernel32.dll");
323
324 auto* d = reinterpret_cast<IMAGE_IMPORT_DESCRIPTOR*>(data);
325 d->Name = kTextRva + 0x100;
326 d->OriginalFirstThunk = kTextRva + 0x140;
327 d->FirstThunk = kTextRva + 0x160;
328 put_thunk(0x140, 0x180, "NormalProbeMissing");
329
330 const struct {
331 uint32_t dll_off, int_off, iat_off, hint_off;
332 const char* name;
333 } delayed[2] = {{0x100, 0x1A0, 0x1C0, 0x1E0, "DelayProbeMissing"}, {0x120, 0x200, 0x220, 0x240, "GetTickCount"}};
334 for (int i = 0; i < 2; ++i) {
335 auto* dd = reinterpret_cast<IMAGE_DELAYLOAD_DESCRIPTOR*>(data + 0x40) + i;
336 dd->Attributes.AllAttributes = 1; // dlattrRva
337 dd->DllNameRVA = kTextRva + delayed[i].dll_off;
338 dd->ImportNameTableRVA = kTextRva + delayed[i].int_off;
339 dd->ImportAddressTableRVA = kTextRva + delayed[i].iat_off;
340 put_thunk(delayed[i].int_off, delayed[i].hint_off, delayed[i].name);
341 }
342
343 auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
344 dir.VirtualAddress = kTextRva;
345 dir.Size = 2 * sizeof(IMAGE_IMPORT_DESCRIPTOR);
346 auto& ddir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT];
347 ddir.VirtualAddress = kTextRva + 0x40;
348 ddir.Size = 3 * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR);
349 return b;
350}
351
352void test_delay_import_trace(const fs::path& dir) {
353 const fs::path image = write_file(dir / kDelayImageName, make_delay_image());
354 const fs::path trace = dir / "delay_trace.jsonl";
355 check(rt::startup_trace::open(trace.c_str()), "open the delay-import trace file");
356 {
357 rt::Loader loader(dir);
358 rt::Module& m = loader.load(image);
359 int unimplemented = 0, host = 0;
360 for (const auto& r : m.imports) {
361 unimplemented += r.binding == rt::Binding::Unimplemented;
362 host += r.binding == rt::Binding::Host;
363 }
364 check(m.imports.size() == 3 && unimplemented == 2 && host == 1,
365 "the delay image binds 3 imports: 2 unimplemented, 1 host");
366 }
367 rt::startup_trace::close();
368
369 const auto lines = read_lines(trace);
370 int events = 0;
371 for (auto& l : lines) events += l.find("\"kind\":\"delay_import_unimplemented\"") != std::string::npos;
372 const std::string* e = find_line(lines, "delay_import_unimplemented");
373 check(events == 1, "one delay_import_unimplemented event (got " + std::to_string(events) + ")");
374 check(has(e, "\"module\":\"" + std::string(kDelayImageName) + "\"") &&
375 has(e, "\"import\":\"leonida_trace_probe.dll!DelayProbeMissing\""),
376 "delay_import_unimplemented names the module and the delay import");
377}
378
282} // namespace 379} // namespace
283 380
284int wmain() { 381int wmain() {
@@ -287,6 +384,7 @@ int wmain() {
287 test_disabled_is_silent(); 384 test_disabled_is_silent();
288 test_existing_file_is_kept(dir); 385 test_existing_file_is_kept(dir);
289 test_trace(dir); 386 test_trace(dir);
387 test_delay_import_trace(dir);
290 std::error_code ec; 388 std::error_code ec;
291 fs::remove_all(dir, ec); 389 fs::remove_all(dir, ec);
292 } catch (const std::exception& e) { 390 } catch (const std::exception& e) {
diff --git a/runtime/test/submit_mutex_test.cpp b/runtime/test/submit_mutex_test.cpp
new file mode 100644
index 000000000..345f30887
--- /dev/null
+++ b/runtime/test/submit_mutex_test.cpp
@@ -0,0 +1,209 @@
1// leonida::SubmitMutex (src/vulkan_device_fault.h), on the CPU: the submit lock's owner and hold tracking, its waiter
2// count, let_submit_finish (the handoff a pipeline create makes to submits before entering the driver) and the
3// compile gate between pipeline creates and queue submissions. Windows only: the owner is a Win32 thread id. No GPU,
4// no game data.
5#include "../src/vulkan_device_fault.h"
6
7#include <windows.h>
8
9#include <atomic>
10#include <chrono>
11#include <cstdio>
12#include <mutex>
13#include <thread>
14
15#define EXPECT(condition) do { \
16 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
17} while (0)
18
19namespace {
20
21using leonida::SubmitMutex;
22using namespace std::chrono_literals;
23
24std::int64_t now_ms() { return leonida::diagnostic_ms(); }
25
26// Polls `done` for up to two seconds.
27template<class Done> bool eventually(Done&& done) {
28 for (int i = 0; i < 2000; ++i) {
29 if (done()) return true;
30 std::this_thread::sleep_for(1ms);
31 }
32 return done();
33}
34
35int owner_tracking() {
36 SubmitMutex m;
37 EXPECT(m.owner() == 0 && m.waiting() == 0);
38 const std::int64_t before = now_ms();
39 m.lock();
40 EXPECT(m.owner() == GetCurrentThreadId());
41 EXPECT(m.since_ms() >= before && m.since_ms() <= now_ms());
42 // The holder's own thread: nothing to let through, no wait (it would deadlock on the lock it holds).
43 EXPECT(m.let_submit_finish(true) == 0);
44 EXPECT(m.let_submit_finish(false) == 0);
45 m.unlock();
46 EXPECT(m.owner() == 0);
47 EXPECT(m.try_lock());
48 EXPECT(m.owner() == GetCurrentThreadId());
49 m.unlock();
50 // Free: no wait at all.
51 EXPECT(m.let_submit_finish(true) == 0);
52 std::printf("owner and hold tracking, holder's own thread returns at once\n");
53 return 0;
54}
55
56int waits_for_holder() {
57 SubmitMutex m;
58 std::atomic<bool> held{false}, released{false};
59 std::thread holder([&] {
60 m.lock();
61 held = true;
62 std::this_thread::sleep_for(200ms);
63 released = true;
64 m.unlock();
65 });
66 EXPECT(eventually([&] { return held.load(); }));
67 EXPECT(m.owner() != 0 && m.owner() != GetCurrentThreadId());
68 const std::int64_t waited = m.let_submit_finish(false);
69 const bool after_release = released.load();
70 holder.join();
71 EXPECT(after_release);
72 EXPECT(waited >= 100);
73 std::printf("let_submit_finish(false) waited %lld ms for another thread's hold\n", static_cast<long long>(waited));
74 return 0;
75}
76
77int waits_for_queued_submitter() {
78 // A holds the lock, B queues behind it in lock(); the worker's handoff returns only after B has had its turn.
79 SubmitMutex m;
80 std::atomic<bool> a_held{false}, b_done{false};
81 std::atomic<std::int64_t> b_released_at{0};
82 std::thread a([&] {
83 m.lock();
84 a_held = true;
85 std::this_thread::sleep_for(150ms);
86 m.unlock();
87 });
88 EXPECT(eventually([&] { return a_held.load(); }));
89 std::thread b([&] {
90 m.lock();
91 std::this_thread::sleep_for(100ms);
92 b_released_at = now_ms();
93 b_done = true;
94 m.unlock();
95 });
96 EXPECT(eventually([&] { return m.waiting() == 1; })); // B is counted while it waits
97 const std::int64_t waited = m.let_submit_finish(true);
98 const bool b_had_turn = b_done.load();
99 const std::int64_t returned_at = now_ms();
100 a.join();
101 b.join();
102 EXPECT(b_had_turn);
103 EXPECT(returned_at >= b_released_at.load());
104 EXPECT(m.waiting() == 0 && m.owner() == 0);
105 std::printf("let_submit_finish(true) let a queued submitter go first (%lld ms)\n", static_cast<long long>(waited));
106 return 0;
107}
108
109int handoff_is_capped() {
110 // Two threads keep the lock busy back to back (one always queued): the worker still gets its turn after the cap.
111 SubmitMutex m;
112 std::atomic<bool> stop{false};
113 auto churn = [&] {
114 while (!stop) {
115 m.lock();
116 std::this_thread::sleep_for(10ms);
117 m.unlock();
118 }
119 };
120 std::thread a(churn), b(churn);
121 EXPECT(eventually([&] { return m.owner() != 0 && m.waiting() != 0; }));
122 const std::int64_t waited = m.let_submit_finish(true, 100);
123 stop = true;
124 a.join();
125 b.join();
126 std::printf("capped handoff: %lld ms\n", static_cast<long long>(waited));
127 EXPECT(waited >= 90 && waited < 600);
128 std::printf("let_submit_finish(true, 100) under a steady stream of submits returned after %lld ms\n",
129 static_cast<long long>(waited));
130 return 0;
131}
132
133int compile_gate() {
134 if (!SubmitMutex::compile_gate_enabled()) {
135 std::printf("compile gate off (LEONIDA_COMPILE_GATE=0): not checked\n");
136 return 0;
137 }
138 SubmitMutex m;
139 // Nothing in the driver: a submission passes at once.
140 {
141 const std::int64_t start = now_ms();
142 const SubmitMutex::SubmitTurn turn(m);
143 EXPECT(now_ms() - start < 50);
144 }
145 // A submission waits for the create in the driver; a create arriving meanwhile waits behind the submission.
146 std::atomic<bool> creating{false};
147 std::atomic<std::int64_t> create_left_at{0}, submit_entered_at{0}, submit_left_at{0}, second_entered_at{0};
148 std::atomic<std::int64_t> second_waited{-1};
149 std::thread create([&] {
150 const SubmitMutex::CompileTurn turn(m);
151 creating = true;
152 std::this_thread::sleep_for(250ms);
153 create_left_at = now_ms();
154 });
155 EXPECT(eventually([&] { return creating.load(); }));
156 std::thread submit([&] {
157 m.lock(); // as a submitter does: the submit lock, then the gate around vkQueueSubmit
158 {
159 const SubmitMutex::SubmitTurn turn(m);
160 submit_entered_at = now_ms();
161 std::this_thread::sleep_for(100ms);
162 submit_left_at = now_ms();
163 }
164 m.unlock();
165 });
166 EXPECT(eventually([&] { return m.gate_waiter() != 0; })); // waiting at the gate, with the submit lock held
167 EXPECT(m.owner() == m.gate_waiter());
168 std::thread second([&] {
169 const SubmitMutex::CompileTurn turn(m);
170 second_entered_at = now_ms();
171 second_waited = turn.waited_ms();
172 });
173 create.join();
174 submit.join();
175 second.join();
176 EXPECT(submit_entered_at.load() >= create_left_at.load()); // never in the driver together with a create
177 EXPECT(second_entered_at.load() >= submit_left_at.load()); // the waiting submission went first
178 EXPECT(second_waited.load() >= 50);
179 EXPECT(m.gate_waiter() == 0);
180 const SubmitMutex::GateStats stats = m.gate_stats();
181 EXPECT(stats.submits == 1 && stats.submit_max_ms >= 100);
182 EXPECT(stats.creates == 1 && stats.create_max_ms >= 50);
183 std::printf("compile gate: submission waited %lld ms for a create, a later create waited %lld ms behind it\n",
184 static_cast<long long>(stats.submit_max_ms), static_cast<long long>(stats.create_max_ms));
185 // Creates share the gate.
186 {
187 const SubmitMutex::CompileTurn first(m);
188 std::atomic<std::int64_t> other_waited{-1};
189 std::thread other([&] {
190 const SubmitMutex::CompileTurn turn(m);
191 other_waited = turn.waited_ms();
192 });
193 other.join();
194 EXPECT(other_waited.load() == 0);
195 }
196 std::printf("compile gate: creates pass it together\n");
197 return 0;
198}
199
200} // namespace
201
202int main() {
203 std::setvbuf(stdout, nullptr, _IONBF, 0);
204 if (owner_tracking() || waits_for_holder() || waits_for_queued_submitter() || handoff_is_capped() ||
205 compile_gate())
206 return 1;
207 std::printf("submit_mutex_test: all passed\n");
208 return 0;
209}
diff --git a/runtime/test/title_hud_test.cpp b/runtime/test/title_hud_test.cpp
new file mode 100644
index 000000000..661f4d30c
--- /dev/null
+++ b/runtime/test/title_hud_test.cpp
@@ -0,0 +1,190 @@
1// shims/title_hud.h: LEONIDA_TITLE_HUD's counters reach the title bar of a window owned by another thread, and a
2// window that stops pumping messages does not hold the HUD thread. The memory figures: VK_EXT_memory_budget's heaps
3// summed, DXGI's as the fallback, "n/a" where neither has one, and the private bytes Wine reports. A real Win32
4// window and made-up budgets; no GPU needed (d3d12_vram_budget_test reads a real device's).
5#include "title_hud.h"
6#include "../src/vulkan_memory_budget.h"
7
8#include <windows.h>
9
10#include <atomic>
11#include <cstdint>
12#include <cstdio>
13#include <string>
14
15#define CHECK(condition) do { \
16 if (!(condition)) { \
17 std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
18 return 1; \
19 } \
20} while (0)
21
22static std::wstring title_of(HWND window) {
23 wchar_t text[512] = {};
24 InternalGetWindowText(window, text, 512); // no message: the window's own thread may be busy
25 return text;
26}
27
28// Pumps this thread's messages for `ms`, presenting every 16 ms when `present` is set.
29static void pump(DWORD ms, rt::d3d12_xs::TitleHud* present) {
30 const ULONGLONG end = GetTickCount64() + ms;
31 while (GetTickCount64() < end) {
32 MSG msg;
33 while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
34 TranslateMessage(&msg);
35 DispatchMessageW(&msg);
36 }
37 if (present) present->note_present();
38 Sleep(16);
39 }
40}
41
42constexpr std::uint64_t kGiB = 1ull << 30;
43
44// The memory figures without a window: VK_EXT_memory_budget's heaps summed, DXGI's answer as the fallback, and this
45// process's own private bytes. Made-up values except the last. The text and the private-bytes choice are
46// src/memory_figures.h's, shared with the dev overlay; dev_overlay_test checks them.
47static int check_figures() {
48 using rt::d3d12_xs::TitleHud;
49 namespace mf = leonida::memory_figures;
50
51 // Two device-local heaps (VRAM and a BAR window) and system memory.
52 VkPhysicalDeviceMemoryProperties heaps{};
53 heaps.memoryHeapCount = 3;
54 heaps.memoryHeaps[0] = {16 * kGiB, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT};
55 heaps.memoryHeaps[1] = {32 * kGiB, 0};
56 heaps.memoryHeaps[2] = {kGiB / 4, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT};
57 VkPhysicalDeviceMemoryBudgetPropertiesEXT budget{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT};
58 budget.heapUsage[0] = 3 * kGiB + kGiB / 4;
59 budget.heapBudget[0] = 15 * kGiB + kGiB * 3 / 4;
60 budget.heapUsage[1] = kGiB / 2;
61 budget.heapBudget[1] = 24 * kGiB;
62 budget.heapUsage[2] = kGiB / 4;
63 budget.heapBudget[2] = kGiB / 4;
64 budget.heapUsage[3] = 7 * kGiB; // past memoryHeapCount: not counted
65 budget.heapBudget[3] = 7 * kGiB;
66 const leonida::VramBudget summed = leonida::sum_vram_budget(heaps, budget);
67 CHECK(summed.available);
68 CHECK(summed.local_usage == 3 * kGiB + kGiB / 2 && summed.local_budget == 16 * kGiB);
69 CHECK(summed.shared_usage == kGiB / 2);
70 CHECK(mf::vram_text(summed) == "VRAM 3.5/16.0 GB +0.5 shared");
71
72 // A device that reports no budget for its device-local heaps has no figure, not a 0.
73 const VkPhysicalDeviceMemoryBudgetPropertiesEXT empty{
74 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT};
75 CHECK(!leonida::sum_vram_budget(heaps, empty).available);
76
77 // DXGI: Wine's QueryVideoMemoryInfo answers S_OK with no usage, which is not a figure; Windows' is.
78 DXGI_QUERY_VIDEO_MEMORY_INFO local{}, non_local{};
79 local.Budget = 24 * kGiB;
80 CHECK(!TitleHud::dxgi_budget(local, non_local).available);
81 local.CurrentUsage = 2 * kGiB;
82 non_local.CurrentUsage = kGiB;
83 const leonida::VramBudget dxgi = TitleHud::dxgi_budget(local, non_local);
84 CHECK(dxgi.available && dxgi.local_usage == 2 * kGiB && dxgi.local_budget == 24 * kGiB &&
85 dxgi.shared_usage == kGiB);
86
87 // This process's own counters: its private bytes are never 0, on Windows or under Wine (where only PagefileUsage
88 // is filled).
89 const mf::ProcessMemory own = mf::process_memory();
90 std::fprintf(stderr, "own counters: PrivateUsage %llu, PagefileUsage %llu, WorkingSetSize %llu\n",
91 (unsigned long long)own.private_usage, (unsigned long long)own.pagefile_usage,
92 (unsigned long long)own.working_set);
93 CHECK(own.read && mf::private_bytes(own) > 0);
94 return 0;
95}
96
97int main() {
98 if (const int failed = check_figures()) return failed;
99 WNDCLASSW cls{};
100 cls.lpfnWndProc = DefWindowProcW;
101 cls.hInstance = GetModuleHandleW(nullptr);
102 cls.lpszClassName = L"LeonidaTitleHudTest";
103 CHECK(RegisterClassW(&cls));
104 HWND window = CreateWindowExW(WS_EX_NOACTIVATE, cls.lpszClassName, L"before", WS_OVERLAPPEDWINDOW, 0, 0, 64, 64,
105 nullptr, nullptr, cls.hInstance, nullptr);
106 CHECK(window);
107 {
108 rt::d3d12_xs::TitleHud hud(window);
109 // Presents at ~60 Hz for 1.5 s: the title shows a frame rate and the counters.
110 pump(1500, &hud);
111 const std::wstring text = title_of(window);
112 std::fwprintf(stderr, L"title: %ls\n", text.c_str());
113 CHECK(text.rfind(L"Leonida | ", 0) == 0);
114 CHECK(text.find(L" fps ") != std::wstring::npos && text.find(L" ms (worst ") != std::wstring::npos);
115 CHECK(text.find(L"RAM ") != std::wstring::npos && text.find(L"VRAM ") != std::wstring::npos);
116 // The private bytes are read under Wine as well ("VRAM n/a" may show: no device behind this HUD).
117 CHECK(text.find(L"| RAM n/a") == std::wstring::npos);
118 CHECK(text.find(L"PSO -") != std::wstring::npos); // no LEONIDA_MEM_PROBE: no pipeline counters
119 const int fps = _wtoi(text.c_str() + 10);
120 CHECK(fps >= 10 && fps <= 120); // a loose band: Sleep(16) on a loaded machine is not 60 Hz
121
122 // Presents stop while the window still pumps: the title says how long since the last frame.
123 pump(1300, nullptr);
124 const std::wstring stalled = title_of(window);
125 std::fwprintf(stderr, L"title: %ls\n", stalled.c_str());
126 CHECK(stalled.find(L"0 fps, no frame for ") != std::wstring::npos);
127
128 // The window's thread stops pumping: the HUD's SendMessageTimeout gives up and the HUD thread is not stuck,
129 // so the destructor below returns.
130 Sleep(1200);
131 }
132 {
133 // A VRAM source (the device's VK_EXT_memory_budget in the runtime) is what the title shows, and it is read
134 // at most once per refresh, on the HUD's thread.
135 std::atomic<unsigned> reads{0};
136 rt::d3d12_xs::TitleHud hud(window, [&reads] {
137 ++reads;
138 leonida::VramBudget fake;
139 fake.available = true;
140 fake.local_usage = 3 * kGiB + kGiB / 2;
141 fake.local_budget = 20 * kGiB;
142 fake.shared_usage = kGiB / 2;
143 return fake;
144 });
145 pump(1300, &hud);
146 const std::wstring text = title_of(window);
147 std::fwprintf(stderr, L"title: %ls\n", text.c_str());
148 CHECK(text.find(L"| VRAM 3.5/20.0 GB +0.5 shared |") != std::wstring::npos);
149 CHECK(reads.load() >= 1 && reads.load() <= 3); // 1.3 s at one refresh per 500 ms
150 }
151 {
152 // No source of its own: the HUD shows what a device published (src/memory_figures.h), the figure the dev
153 // overlay shows as well.
154 static const int device = 0;
155 leonida::memory_figures::publish_vram_reader(
156 [](const void*) {
157 leonida::VramBudget fake;
158 fake.available = true;
159 fake.local_usage = 5 * kGiB;
160 fake.local_budget = 12 * kGiB;
161 return fake;
162 },
163 &device);
164 {
165 rt::d3d12_xs::TitleHud hud(window);
166 pump(700, &hud);
167 const std::wstring text = title_of(window);
168 std::fwprintf(stderr, L"title: %ls\n", text.c_str());
169 CHECK(text.find(L"| VRAM 5.0/12.0 GB +0.0 shared |") != std::wstring::npos);
170 }
171 leonida::memory_figures::withdraw_vram_reader(&device);
172 }
173 {
174 // A source with no figure (a device without VK_EXT_memory_budget): DXGI's figure where it has one (Windows),
175 // else "n/a" (Wine, whose DXGI answers 0; check_figures covers that choice).
176 rt::d3d12_xs::TitleHud hud(window, [] { return leonida::VramBudget{}; });
177 pump(700, &hud);
178 const std::wstring text = title_of(window);
179 std::fwprintf(stderr, L"title: %ls\n", text.c_str());
180 CHECK(text.find(L"| VRAM ") != std::wstring::npos && text.find(L"VRAM 3.5/20.0") == std::wstring::npos);
181 }
182 const ULONGLONG before = GetTickCount64();
183 {
184 rt::d3d12_xs::TitleHud quick(window);
185 } // stops at once, without waiting a whole interval
186 CHECK(GetTickCount64() - before < 1000);
187 DestroyWindow(window);
188 std::printf("title_hud: counters in the title bar of another thread's window; a busy window does not hold it\n");
189 return 0;
190}
diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp
index fe378a3bf..f2f869391 100644
--- a/runtime/test/title_va_alias_test.cpp
+++ b/runtime/test/title_va_alias_test.cpp
@@ -85,6 +85,44 @@ int main() {
85 a.remove(title, arena); 85 a.remove(title, arena);
86 a.remove(title + 0x40000, 0x7000000); 86 a.remove(title + 0x40000, 0x7000000);
87 EXPECT(a.size() == 0); 87 EXPECT(a.size() == 0);
88 // Replacing part of an alias removes the entire old interval. Other heaps read independently.
89 std::uint64_t cursor = 0;
90 leonida::DescriptorRanges past;
91 EXPECT(a.changed_ranges(cursor, past));
92 auto second = cursor;
93 EXPECT(a.add(title, size, arena));
94 EXPECT(a.add(title+16, 32, arena+4096));
95 for (auto* reader : {&cursor, &second}) {
96 leonida::DescriptorRanges delta;
97 EXPECT(a.changed_ranges(*reader, delta));
98 delta.merge();
99 EXPECT(delta.overlaps(title+size-1, 1) && delta.overlaps(title-16, 17));
100 EXPECT(!delta.overlaps(title+size, 1) && !delta.overlaps(title-16, 16));
101 }
102 leonida::DescriptorRangeChanges backing;
103 for (unsigned i = 0; i < 4097; ++i) backing.record(UINT64_MAX-3, 4);
104 cursor = 0;
105 EXPECT(!backing.read(cursor, past));
106 backing.record(UINT64_MAX-3, 4);
107 leonida::DescriptorRanges last;
108 EXPECT(backing.read(cursor,last));
109 last.merge();
110 EXPECT(last.overlaps(UINT64_MAX,1) && !last.overlaps(0,1));
111 // shader_side: whether an address is one the layer wrote for the title (inside some range's copy), so a scan that
112 // sees an already rewritten V# again leaves it alone rather than taking it for an unmapped address.
113 EXPECT(!a.shader_side(arena));
114 EXPECT(a.add(title, size, arena) && a.add_twin(title + 0x200000, title + 0x400000, 0x1000, 0x9000000));
115 EXPECT(a.shader_side(arena) && a.shader_side(arena + size - 1) && !a.shader_side(arena + size));
116 EXPECT(a.shader_side(0x9000fff) && !a.shader_side(0x9001000) && !a.shader_side(title));
117 a.remove(title + 0x200000, 0x9000000);
118 EXPECT(a.shader_side(0x9000000)); // the twin still names it
119 a.remove(title + 0x400000, 0x9000000);
120 EXPECT(!a.shader_side(0x9000000));
121 // A range replaced by an overlapping one leaves the index with the new copy only.
122 EXPECT(a.add(title + 0x100, 0x100, 0xA000000));
123 EXPECT(!a.shader_side(arena) && a.shader_side(0xA0000ff) && !a.shader_side(0xA000100));
124 a.remove(title + 0x100, 0xA000000);
125 EXPECT(a.size() == 0 && !a.shader_side(0xA000000));
88 std::printf("title_va_alias: translation inside a title-placed range, identity outside it and after release\n"); 126 std::printf("title_va_alias: translation inside a title-placed range, identity outside it and after release\n");
89 return 0; 127 return 0;
90} 128}
diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp
index 194df74a9..dc33e7d91 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) {
738 return submit() == VK_SUCCESS && ok; 738 return submit() == VK_SUCCESS && ok;
739 }; 739 };
740 740
741 const float orange_pixel[4] = {1.0f, 128.0f / 255.0f, 0.0f, 1.0f};
742 const float fallback_pixels[4] = {0.0f, 0.0f, 0.0f, 0.0f};
743
744 // The mirror (BindlessSet::MirrorViews): a 2D-array T# read by a 2D op finds its slice 0 bound in the 2D
745 // arrays at the T#'s own index. The index spaces are per dimension and dense, so slot N of one dimension
746 // and a 2D-array image's mirror slot N coincide: the set records which image owns a mirror slot, not just
747 // that it is used.
748 {
749 // A 2D-array image of two layers (layer 0 orange, layer 1 blue) with its own 2D-array and storage views
750 // plus a 2D view of layer 0, which is what a mirror binds. The storage view puts the index in the
751 // storage range, as in the index-space checks below.
752 const auto make_layered = [&](VkImage* image, VkImageView* layers, VkImageView* layer0) {
753 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
754 ii.imageType = VK_IMAGE_TYPE_2D;
755 ii.format = VK_FORMAT_R8G8B8A8_UNORM;
756 ii.extent = {1, 1, 1};
757 ii.mipLevels = 1;
758 ii.arrayLayers = 2;
759 ii.samples = VK_SAMPLE_COUNT_1_BIT;
760 ii.tiling = VK_IMAGE_TILING_OPTIMAL;
761 ii.usage = sampled_usage | VK_IMAGE_USAGE_STORAGE_BIT;
762 VkResult r = vkCreateImage(dev, &ii, nullptr, image);
763 if (r) return r;
764 VkMemoryRequirements mr;
765 vkGetImageMemoryRequirements(dev, *image, &mr);
766 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
767 ai.allocationSize = mr.size;
768 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
769 VkDeviceMemory m = VK_NULL_HANDLE;
770 if ((r = vkAllocateMemory(dev, &ai, nullptr, &m))) return r;
771 allocations.push_back(m);
772 if ((r = vkBindImageMemory(dev, *image, m, 0))) return r;
773 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
774 vi.image = *image;
775 vi.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY;
776 vi.format = VK_FORMAT_R8G8B8A8_UNORM;
777 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 2};
778 if ((r = vkCreateImageView(dev, &vi, nullptr, layers))) return r;
779 vi.viewType = VK_IMAGE_VIEW_TYPE_2D;
780 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
781 return vkCreateImageView(dev, &vi, nullptr, layer0);
782 };
783 const auto upload_layered = [&](VkImage image) {
784 constexpr std::uint32_t blue = 0xffff0000u; // r = 0, g = 0, b = 255, a = 255
785 std::memcpy(static_cast<char*>(upload_map) + 1028, &blue, 4);
786 VkResult r = vkResetCommandBuffer(cmd, 0);
787 if (r) return r;
788 if ((r = vkBeginCommandBuffer(cmd, &begin))) return r;
789 VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
790 b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
791 b.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
792 b.image = image;
793 b.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 2};
794 b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
795 b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
796 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0,
797 nullptr, 0, nullptr, 1, &b);
798 for (std::uint32_t layer = 0; layer < 2; ++layer) {
799 VkBufferImageCopy c{};
800 c.bufferOffset = 1024 + layer * 4;
801 c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, layer, 1};
802 c.imageExtent = {1, 1, 1};
803 vkCmdCopyBufferToImage(cmd, upload, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c);
804 }
805 b.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
806 b.newLayout = VK_IMAGE_LAYOUT_GENERAL; // sampled and storage
807 b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
808 b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
809 vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0,
810 nullptr, 0, nullptr, 1, &b);
811 return submit();
812 };
813 // A 3D image with a storage view: its own index space, whose slot numbers are the 2D arrays' too.
814 const auto make_volume = [&](VkImage* image, VkImageView* view) {
815 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
816 ii.imageType = VK_IMAGE_TYPE_3D;
817 ii.format = VK_FORMAT_R8G8B8A8_UNORM;
818 ii.extent = {1, 1, 1};
819 ii.mipLevels = 1;
820 ii.arrayLayers = 1;
821 ii.samples = VK_SAMPLE_COUNT_1_BIT;
822 ii.tiling = VK_IMAGE_TILING_OPTIMAL;
823 ii.usage = sampled_usage | VK_IMAGE_USAGE_STORAGE_BIT;
824 VkResult r = vkCreateImage(dev, &ii, nullptr, image);
825 if (r) return r;
826 VkMemoryRequirements mr;
827 vkGetImageMemoryRequirements(dev, *image, &mr);
828 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
829 ai.allocationSize = mr.size;
830 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
831 VkDeviceMemory m = VK_NULL_HANDLE;
832 if ((r = vkAllocateMemory(dev, &ai, nullptr, &m))) return r;
833 allocations.push_back(m);
834 if ((r = vkBindImageMemory(dev, *image, m, 0))) return r;
835 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
836 vi.image = *image;
837 vi.viewType = VK_IMAGE_VIEW_TYPE_3D;
838 vi.format = VK_FORMAT_R8G8B8A8_UNORM;
839 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
840 return vkCreateImageView(dev, &vi, nullptr, view);
841 };
842 const auto add_mirrored = [&](VkImageView layers, VkImageView layer0, std::uint32_t* index,
843 std::uint32_t* kind) {
844 StorageViews storage;
845 storage.as_float = layers;
846 BindlessSet::MirrorViews mirror{};
847 mirror.sampled = layer0;
848 mirror.sampled_layout = VK_IMAGE_LAYOUT_GENERAL;
849 mirror.storage.as_float = layer0;
850 *index = set.add_image(ImageDimension::dim_2d_array, layers, VK_IMAGE_LAYOUT_GENERAL, storage, 0,
851 &mirror, kind);
852 return *index != 0;
853 };
854 const auto draw_with = [&](const DescriptorKey& key) {
855 std::memcpy(static_cast<char*>(heap_map) + table_va, key.data(), 32);
856 return draw();
857 };
858
859 const std::uint32_t free_2d = set.free_images(ImageDimension::dim_2d);
860 const std::uint32_t free_array = set.free_images(ImageDimension::dim_2d_array);
861 VkImage layered = VK_NULL_HANDLE;
862 VkImageView layered_view = VK_NULL_HANDLE, layer0 = VK_NULL_HANDLE;
863 CHECK(make_layered(&layered, &layered_view, &layer0));
864 CHECK(upload_layered(layered));
865
866 std::uint32_t index = 0, kind = 0;
867 EXPECT(add_mirrored(layered_view, layer0, &index, &kind));
868 // The allocation is in both index spaces: the T#'s dimension and the 2D arrays (the mirror's slot).
869 EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d - 1);
870 EXPECT(set.free_images(ImageDimension::dim_2d_array) == free_array - 1);
871 // The entry names the 2D-array arrays and their storage arrays, and the 2D ones the mirror is bound in.
872 EXPECT(kind == (kind_sampled_bit(1) | kind_storage_bit(1) | kind_sampled_bit(0) | kind_storage_bit(0)));
873 EXPECT(set.image_kind_at(ImageDimension::dim_2d_array, index) == kind);
874 EXPECT(set.image_kind_at(ImageDimension::dim_2d, index) ==
875 (kind_sampled_bit(0) | kind_storage_bit(0)));
876 EXPECT(set.insert_key(tsharp, index, kind));
877 EXPECT(flush());
878 CHECK(draw());
879 compare("mirror: a 2D-array T# read by a 2D op", orange_pixel);
880 // Removing the image puts the 2D slot back to its fallback. Its entry still names 2D (the kind it had),
881 // so a 2D op reads that slot: it must hold zeros, not the removed mirror.
882 EXPECT(set.erase_key(tsharp));
883 set.remove_image(ImageDimension::dim_2d_array, index);
884 EXPECT(flush());
885 EXPECT((set.image_kind_at(ImageDimension::dim_2d_array, index) & kind_sampled_bit(0)) == 0);
886 EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d);
887 EXPECT(set.free_images(ImageDimension::dim_2d_array) == free_array);
888 EXPECT(set.insert_key(tsharp, index, kind));
889 EXPECT(flush());
890 CHECK(draw());
891 compare("mirror: removed, the 2D slot holds the fallback", fallback_pixels);
892 EXPECT(set.erase_key(tsharp));
893
894 // The aliasing scenario the owner records: a 2D-array image with its mirror at slot N and a 3D image at
895 // its own index N (both index spaces are dense, so both take the lowest storage slot). Neither may claim
896 // the other's slot, and removing either must leave the other's binding alone.
897 VkImage layered2 = VK_NULL_HANDLE;
898 VkImageView layered2_view = VK_NULL_HANDLE, layer0_2 = VK_NULL_HANDLE;
899 CHECK(make_layered(&layered2, &layered2_view, &layer0_2));
900 CHECK(upload_layered(layered2));
901 std::uint32_t array_index = 0, array_kind = 0;
902 EXPECT(add_mirrored(layered2_view, layer0_2, &array_index, &array_kind));
903 VkImage volume = VK_NULL_HANDLE;
904 VkImageView volume_view = VK_NULL_HANDLE;
905 CHECK(make_volume(&volume, &volume_view));
906 StorageViews volume_storage;
907 volume_storage.as_float = volume_view;
908 const std::uint32_t volume_index = set.add_image(ImageDimension::dim_3d, volume_view,
909 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, volume_storage);
910 EXPECT(volume_index != 0 && volume_index == array_index); // the same slot number, two index spaces
911 const std::uint32_t volume_kind = set.image_kind_at(ImageDimension::dim_3d, volume_index);
912 // The 3D image does not own the 2D mirror: a 2D op reading its T# takes the 2D fallback.
913 EXPECT(volume_kind == (kind_sampled_bit(2) | kind_storage_bit(2)));
914 EXPECT((volume_kind & kind_sampled_bit(0)) == 0);
915 EXPECT(set.image_kind_at(ImageDimension::dim_2d_array, array_index) == array_kind);
916 DescriptorKey volume_key = tsharp; // the same FORMAT (word 1), a different key
917 volume_key[7] ^= 0x10u;
918 EXPECT(set.insert_key(tsharp, array_index, array_kind));
919 EXPECT(set.insert_key(volume_key, volume_index, volume_kind));
920 EXPECT(flush());
921 CHECK(draw_with(volume_key));
922 compare("alias: a 3D T# at another image's mirror slot", fallback_pixels);
923 CHECK(draw_with(tsharp));
924 compare("alias: the mirror, with the 3D image at the same slot", orange_pixel);
925 // Removing the 3D image must not take the 2D-array image's mirror with it.
926 EXPECT(set.erase_key(volume_key));
927 set.remove_image(ImageDimension::dim_3d, volume_index);
928 EXPECT(flush());
929 EXPECT(set.image_kind_at(ImageDimension::dim_2d_array, array_index) == array_kind);
930 CHECK(draw_with(tsharp));
931 compare("alias: the mirror survives the 3D image's removal", orange_pixel);
932 // And removing the 2D-array image frees the 2D slot: a 3D image at that slot number names no mirror.
933 const std::uint32_t volume_again = set.add_image(ImageDimension::dim_3d, volume_view,
934 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, volume_storage);
935 EXPECT(volume_again == volume_index);
936 EXPECT(set.insert_key(volume_key, volume_again, set.image_kind_at(ImageDimension::dim_3d, volume_again)));
937 EXPECT(set.erase_key(tsharp));
938 set.remove_image(ImageDimension::dim_2d_array, array_index);
939 EXPECT(flush());
940 EXPECT((set.image_kind_at(ImageDimension::dim_3d, volume_again) & kind_sampled_bit(0)) == 0);
941 EXPECT(set.free_images(ImageDimension::dim_2d) == free_2d);
942 CHECK(draw_with(volume_key));
943 compare("alias: no mirror once the 2D-array image is gone", fallback_pixels);
944 EXPECT(set.erase_key(volume_key));
945 set.remove_image(ImageDimension::dim_3d, volume_again);
946 EXPECT(flush());
947 // The steps below expect tsharp at the heap's T# again.
948 std::memcpy(static_cast<char*>(heap_map) + table_va, tsharp.data(), 32);
949 vkDestroyImageView(dev, volume_view, nullptr);
950 vkDestroyImage(dev, volume, nullptr);
951 for (const VkImageView view : {layered_view, layer0, layered2_view, layer0_2})
952 vkDestroyImageView(dev, view, nullptr);
953 vkDestroyImage(dev, layered, nullptr);
954 vkDestroyImage(dev, layered2, nullptr);
955 }
956
741 // Index spaces. An image with storage views gets an index the storage arrays hold; one without goes above 957 // Index spaces. An image with storage views gets an index the storage arrays hold; one without goes above
742 // them where the dimension has room. A dimension that is full gives 0, and removed indices come back. 958 // them where the dimension has room. A dimension that is full gives 0, and removed indices come back.
743 StorageViews as_storage; 959 StorageViews as_storage;
@@ -763,6 +979,61 @@ int main(int argc, char** argv) {
763 const std::uint32_t sampler_index = set.add_sampler(nearest); 979 const std::uint32_t sampler_index = set.add_sampler(nearest);
764 EXPECT(decoy_sampler == 1 && sampler_index == 2 && set.free_samplers() == set.sampler_capacity() - 3); 980 EXPECT(decoy_sampler == 1 && sampler_index == 2 && set.free_samplers() == set.sampler_capacity() - 3);
765 981
982 // The T#'s own type is the truth. This shader samples in 2D; the 3D image's index is 1 in the 3D arrays,
983 // and index 1 of the 2D arrays is `stored_view` (its own image, a red texel). The entry says the index is
984 // bound in the 3D arrays only, so the 2D read must use the 2D array's fallback and read zeros - not
985 // `stored_view`, which is what indexing the instruction's array with the other dimension's index would do.
986 {
987 EXPECT(stored_index == 1);
988 VkImage volume = VK_NULL_HANDLE;
989 VkImageView volume_view = VK_NULL_HANDLE;
990 {
991 const VkImageUsageFlags usage =
992 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_STORAGE_BIT;
993 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
994 ii.imageType = VK_IMAGE_TYPE_3D;
995 ii.format = VK_FORMAT_R8G8B8A8_UNORM;
996 ii.extent = {2, 2, 2};
997 ii.mipLevels = 1;
998 ii.arrayLayers = 1;
999 ii.samples = VK_SAMPLE_COUNT_1_BIT;
1000 ii.tiling = VK_IMAGE_TILING_OPTIMAL;
1001 ii.usage = usage;
1002 CHECK(vkCreateImage(dev, &ii, nullptr, &volume));
1003 VkMemoryRequirements mr;
1004 vkGetImageMemoryRequirements(dev, volume, &mr);
1005 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
1006 ai.allocationSize = mr.size;
1007 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
1008 VkDeviceMemory memory = VK_NULL_HANDLE;
1009 CHECK(vkAllocateMemory(dev, &ai, nullptr, &memory));
1010 allocations.push_back(memory);
1011 CHECK(vkBindImageMemory(dev, volume, memory, 0));
1012 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
1013 vi.image = volume;
1014 vi.viewType = VK_IMAGE_VIEW_TYPE_3D;
1015 vi.format = VK_FORMAT_R8G8B8A8_UNORM;
1016 vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
1017 CHECK(vkCreateImageView(dev, &vi, nullptr, &volume_view));
1018 }
1019 // A storage view puts it in the low index region, so its index is 1: the same slot number as
1020 // `stored_view` in the 2D arrays, which a dimension-blind read would pick up.
1021 StorageViews volume_storage;
1022 volume_storage.as_float = volume_view;
1023 const std::uint32_t volume_index = set.add_image(ImageDimension::dim_3d, volume_view,
1024 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, volume_storage);
1025 EXPECT(volume_index == stored_index); // the same slot number, a different index space
1026 EXPECT(set.insert_key(tsharp, volume_index, ImageDimension::dim_3d));
1027 EXPECT(flush());
1028 EXPECT(draw() == VK_SUCCESS);
1029 const float zeros[4] = {0.0f, 0.0f, 0.0f, 0.0f};
1030 compare("a 3D T# read by a 2D op", zeros);
1031 EXPECT(set.erase_key(tsharp));
1032 set.remove_image(ImageDimension::dim_3d, volume_index);
1033 vkDestroyImageView(dev, volume_view, nullptr);
1034 vkDestroyImage(dev, volume, nullptr);
1035 }
1036
766 if (atomic_mode) { 1037 if (atomic_mode) {
767 // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from 1038 // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from
768 // every pixel of the 64x64 draw (64 pixels per 2D texel), each found through its own T# key. Odd 1039 // 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) {
815 indices[k] = set.add_image(k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d, views[k], 1086 indices[k] = set.add_image(k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d, views[k],
816 VK_IMAGE_LAYOUT_GENERAL, storage); 1087 VK_IMAGE_LAYOUT_GENERAL, storage);
817 EXPECT(indices[k] != 0); 1088 EXPECT(indices[k] != 0);
818 EXPECT(set.insert_key(keys[k], indices[k])); 1089 EXPECT(set.insert_key(keys[k], indices[k],
1090 k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d));
819 } 1091 }
820 EXPECT(flush()); 1092 EXPECT(flush());
821 1093
@@ -963,9 +1235,10 @@ int main(int argc, char** argv) {
963 const auto target = (slots - 4 + i % kDescriptorProbes) & (slots - 1); 1235 const auto target = (slots - 4 + i % kDescriptorProbes) & (slots - 1);
964 while ((hash_descriptor_key(key) & (slots - 1)) != target) ++key[7]; 1236 while ((hash_descriptor_key(key) & (slots - 1)) != target) ++key[7];
965 } 1237 }
966 for (std::uint32_t i = 0; i < kDescriptorProbes; ++i) set.insert_key(keys[i], decoy_index); 1238 for (std::uint32_t i = 0; i < kDescriptorProbes; ++i)
1239 set.insert_key(keys[i], decoy_index, ImageDimension::dim_2d);
967 EXPECT(!set.flush_replaces_table() && flush()); 1240 EXPECT(!set.flush_replaces_table() && flush());
968 EXPECT(set.insert_key(keys.back(), gradient_index)); 1241 EXPECT(set.insert_key(keys.back(), gradient_index, ImageDimension::dim_2d));
969 EXPECT(slot_count() == slots && set.flush_replaces_table()); 1242 EXPECT(slot_count() == slots && set.flush_replaces_table());
970 EXPECT(flush() && !set.flush_replaces_table()); 1243 EXPECT(flush() && !set.flush_replaces_table());
971 for (const auto& key : keys) { 1244 for (const auto& key : keys) {
@@ -979,12 +1252,13 @@ int main(int argc, char** argv) {
979 std::uint32_t ahead = 0; 1252 std::uint32_t ahead = 0;
980 for (std::uint32_t k = 1; ahead < 3; ++k) { 1253 for (std::uint32_t k = 1; ahead < 3; ++k) {
981 if ((hash_descriptor_key(numbered(k)) & (slots - 1)) != home) continue; 1254 if ((hash_descriptor_key(numbered(k)) & (slots - 1)) != home) continue;
982 set.insert_key(numbered(k), decoy_index); 1255 set.insert_key(numbered(k), decoy_index, ImageDimension::dim_2d);
983 ++ahead; 1256 ++ahead;
984 } 1257 }
985 set.insert_key(tsharp, gradient_index); 1258 set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d);
986 set.insert_key(make_ssharp_key(ssharp.data()), sampler_index); 1259 set.insert_key(make_ssharp_key(ssharp.data()), sampler_index);
987 for (std::uint32_t k = 100000; k < 100006; ++k) set.insert_key(numbered(k), decoy_index); 1260 for (std::uint32_t k = 100000; k < 100006; ++k)
1261 set.insert_key(numbered(k), decoy_index, ImageDimension::dim_2d);
988 const std::uint32_t depth = probe_depth(table.build_gpu_buffer(), tsharp); 1262 const std::uint32_t depth = probe_depth(table.build_gpu_buffer(), tsharp);
989 EXPECT(slot_count() == slots && depth == 3 && !set.flush_replaces_table()); 1263 EXPECT(slot_count() == slots && depth == 3 && !set.flush_replaces_table());
990 EXPECT(flush()); 1264 EXPECT(flush());
@@ -1000,9 +1274,10 @@ int main(int argc, char** argv) {
1000 compare("2 miss", zeros); 1274 compare("2 miss", zeros);
1001 1275
1002 // 3. The table grows: a new, larger buffer behind binding 2. 1276 // 3. The table grows: a new, larger buffer behind binding 2.
1003 set.insert_key(tsharp, gradient_index); 1277 set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d);
1004 EXPECT(!set.flush_replaces_table()); // one more entry, in place 1278 EXPECT(!set.flush_replaces_table()); // one more entry, in place
1005 for (std::uint32_t k = 200000; k < 200200; ++k) set.insert_key(numbered(k), decoy_index); 1279 for (std::uint32_t k = 200000; k < 200200; ++k)
1280 set.insert_key(numbered(k), decoy_index, ImageDimension::dim_2d);
1006 EXPECT(slot_count() > slots && table.lookup(tsharp) == gradient_index && set.flush_replaces_table()); 1281 EXPECT(slot_count() > slots && table.lookup(tsharp) == gradient_index && set.flush_replaces_table());
1007 const VkDescriptorSet before_growth = set.set(); 1282 const VkDescriptorSet before_growth = set.set();
1008 const std::uint64_t made_before = set.generations_made(); 1283 const std::uint64_t made_before = set.generations_made();
@@ -1020,12 +1295,13 @@ int main(int argc, char** argv) {
1020 const float orange_colour[4] = {1.0f, 128.0f / 255.0f, 0.0f, 1.0f}; 1295 const float orange_colour[4] = {1.0f, 128.0f / 255.0f, 0.0f, 1.0f};
1021 // Rewriting the same mapping is a no-op. Changing it makes a new generation even with no table growth. 1296 // Rewriting the same mapping is a no-op. Changing it makes a new generation even with no table growth.
1022 const std::uint32_t grown_slots = slot_count(); 1297 const std::uint32_t grown_slots = slot_count();
1023 EXPECT(set.insert_key(tsharp, gradient_index) && !set.flush_replaces_table()); 1298 EXPECT(set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d) && !set.flush_replaces_table());
1024 EXPECT(set.insert_key(tsharp, decoy_index) && slot_count() == grown_slots && set.flush_replaces_table()); 1299 EXPECT(set.insert_key(tsharp, decoy_index, ImageDimension::dim_2d) && slot_count() == grown_slots &&
1300 set.flush_replaces_table());
1025 EXPECT(flush() && !set.flush_replaces_table()); 1301 EXPECT(flush() && !set.flush_replaces_table());
1026 CHECK(draw()); 1302 CHECK(draw());
1027 compare("4 rebound", orange_colour); 1303 compare("4 rebound", orange_colour);
1028 EXPECT(set.insert_key(tsharp, gradient_index) && set.flush_replaces_table()); 1304 EXPECT(set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d) && set.flush_replaces_table());
1029 EXPECT(flush()); 1305 EXPECT(flush());
1030 CHECK(draw()); 1306 CHECK(draw());
1031 compare("5 restored", nullptr); 1307 compare("5 restored", nullptr);
@@ -1033,7 +1309,7 @@ int main(int argc, char** argv) {
1033 // A submit that never reached the queue must keep the table upload pending: the retry has to see the new 1309 // A submit that never reached the queue must keep the table upload pending: the retry has to see the new
1034 // mapping instead of the fallback or the old index (a recovered submit failure, the case a device reports 1310 // mapping instead of the fallback or the old index (a recovered submit failure, the case a device reports
1035 // through table_upload_result(false)). 1311 // through table_upload_result(false)).
1036 EXPECT(set.insert_key(tsharp, decoy_index) && set.flush_replaces_table()); 1312 EXPECT(set.insert_key(tsharp, decoy_index, ImageDimension::dim_2d) && set.flush_replaces_table());
1037 vkResetCommandBuffer(cmd, 0); 1313 vkResetCommandBuffer(cmd, 0);
1038 CHECK(vkBeginCommandBuffer(cmd, &begin)); 1314 CHECK(vkBeginCommandBuffer(cmd, &begin));
1039 EXPECT(set.flush(cmd, 1)); // recorded in a command buffer that is never submitted 1315 EXPECT(set.flush(cmd, 1)); // recorded in a command buffer that is never submitted
@@ -1043,7 +1319,7 @@ int main(int argc, char** argv) {
1043 EXPECT(flush()); 1319 EXPECT(flush());
1044 CHECK(draw()); 1320 CHECK(draw());
1045 compare("6 rebound after a failed submit", orange_colour); 1321 compare("6 rebound after a failed submit", orange_colour);
1046 EXPECT(set.insert_key(tsharp, gradient_index) && set.flush_replaces_table()); 1322 EXPECT(set.insert_key(tsharp, gradient_index, ImageDimension::dim_2d) && set.flush_replaces_table());
1047 EXPECT(flush()); 1323 EXPECT(flush());
1048 1324
1049 // Another view at the same index, then removal of the index. 1325 // Another view at the same index, then removal of the index.
@@ -1066,7 +1342,7 @@ int main(int argc, char** argv) {
1066 far_image = set.add_image(ImageDimension::dim_2d, gradient_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); 1342 far_image = set.add_image(ImageDimension::dim_2d, gradient_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
1067 for (std::uint32_t i = 0; i < 2100; ++i) far_sampler = set.add_sampler(nearest); 1343 for (std::uint32_t i = 0; i < 2100; ++i) far_sampler = set.add_sampler(nearest);
1068 EXPECT(far_image > 5000 && far_sampler > 2100); 1344 EXPECT(far_image > 5000 && far_sampler > 2100);
1069 set.insert_key(tsharp, far_image); 1345 set.insert_key(tsharp, far_image, ImageDimension::dim_2d);
1070 set.insert_key(make_ssharp_key(ssharp.data()), far_sampler); 1346 set.insert_key(make_ssharp_key(ssharp.data()), far_sampler);
1071 EXPECT(flush()); 1347 EXPECT(flush());
1072 CHECK(draw()); 1348 CHECK(draw());
@@ -1087,7 +1363,7 @@ int main(int argc, char** argv) {
1087 const float blue[4] = {0, 0, 128.0f / 255.0f, 1}; // stored image uses the first gradient texel 1363 const float blue[4] = {0, 0, 128.0f / 255.0f, 1}; // stored image uses the first gradient texel
1088 compare("11 reused high slot", blue); 1364 compare("11 reused high slot", blue);
1089 1365
1090 EXPECT(set.insert_key(tsharp, neighbour)); 1366 EXPECT(set.insert_key(tsharp, neighbour, ImageDimension::dim_2d));
1091 EXPECT(flush()); 1367 EXPECT(flush());
1092 CHECK(draw()); 1368 CHECK(draw());
1093 compare("12 live neighbour", orange_colour); 1369 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 000000000..9ac34f52b
--- /dev/null
+++ b/runtime/test/vk_console_heap_gpu_test.cpp
@@ -0,0 +1,584 @@
1// The console heap translation pass (src/console_heap_fix.comp, src/console_heap_gpu.h) against its CPU reference:
2// synthetic descriptor words only (no game data). Checks the key table mirror on the CPU first, then that the GPU
3// writes every slot exactly as console_heap_translate_slot does and records the same misses, through key table
4// updates, a new range table, a submission that failed (its work queued again) and a miss list that overflows.
5// Exits 77 without a Vulkan device with bufferDeviceAddress.
6#include "vk_test_device.h"
7#include "../src/console_heap_gpu.h"
8
9#include <cstdio>
10#include <cstring>
11#include <random>
12#include <array>
13#include <set>
14#include <vector>
15
16#define EXPECT(x) \
17 do { \
18 if (!(x)) { \
19 std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); \
20 return 1; \
21 } \
22 } while (0)
23
24namespace {
25
26using leonida::ConsoleHeapKeys;
27using leonida::ConsoleHeapRange;
28using leonida::ConsoleHeapTables;
29
30// A buffer V# half: base, stride, records and dword 3 with TYPE bits 30-31 clear.
31void vsharp(std::uint32_t* w, std::uint64_t base, std::uint32_t stride, std::uint32_t records, std::uint32_t dword3) {
32 w[0] = std::uint32_t(base);
33 w[1] = std::uint32_t((base >> 32) & 0xffff) | (stride << 16);
34 w[2] = records;
35 w[3] = dword3 & 0x3fffffffu;
36}
37
38int keys_on_cpu() {
39 ConsoleHeapKeys keys(6); // 64 entries: probe chains overlap
40 const ConsoleHeapKeys::Key a{1, 2, 3, 4}, b{5, 6, 7, 8};
41 EXPECT(keys.find(a) < 0);
42 EXPECT(keys.put(a, 0x1000, 0x100, false));
43 EXPECT(keys.put(b, 0, 0x40, true));
44 std::uint64_t to = 0;
45 bool none = true;
46 EXPECT(keys.lookup(a, to, none) && to == 0x1000 && !none);
47 EXPECT(keys.lookup(b, to, none) && none);
48 EXPECT(keys.size() == 2);
49 // Only positive answers fall in a released shader range; the edge is exclusive.
50 EXPECT(keys.erase_overlapping(0x1100, 0x2000) == 0);
51 EXPECT(keys.erase_overlapping(0x10ff, 0x1100) == 1);
52 EXPECT(keys.find(a) < 0 && keys.find(b) >= 0);
53 // Replacing an answer keeps one entry and moves its index.
54 EXPECT(keys.put(b, 0x5000, 0x10, false));
55 EXPECT(keys.size() == 1);
56 EXPECT(keys.erase_overlapping(0x5008, 0x5009) == 1);
57 EXPECT(keys.size() == 0);
58 // Fill one probe chain: the 17th key with the same start finds no slot.
59 // V#s whose words differ only in high bits (bases megabytes apart): the hash must still spread them. Bare FNV-1a
60 // put all of these in one probe chain.
61 {
62 ConsoleHeapKeys big(20);
63 for (std::uint32_t i = 0; i < 20000; ++i) {
64 const ConsoleHeapKeys::Key k{(i & 0xfffu) << 20, ((i >> 12) << 8) | (64u << 16), 256, 0x2000};
65 EXPECT(big.put(k, 0x100000ull * i, 256, false));
66 }
67 EXPECT(big.size() == 20000);
68 }
69 std::vector<ConsoleHeapKeys::Key> same;
70 for (std::uint32_t i = 0; same.size() < ConsoleHeapKeys::kProbes + 1 && i < 1u << 20; ++i) {
71 const ConsoleHeapKeys::Key k{i, 0, 1, 0};
72 if ((ConsoleHeapKeys::hash(k) & keys.mask()) == 7) same.push_back(k);
73 }
74 EXPECT(same.size() == ConsoleHeapKeys::kProbes + 1);
75 for (std::size_t i = 0; i < ConsoleHeapKeys::kProbes; ++i) EXPECT(keys.put(same[i], 0x100 * i, 1, false));
76 EXPECT(!keys.put(same.back(), 1, 1, false));
77 std::vector<std::uint32_t> updates;
78 keys.take_updates(updates);
79 EXPECT(!updates.empty() && updates.size() % ConsoleHeapKeys::kUpdateWords == 0);
80 EXPECT(!keys.has_updates());
81 // The reference: ranges first (checked only), then keys, else a miss.
82 ConsoleHeapTables ranges;
83 ranges.ranges = {{0x10000, 0x20000, 0x400000, true}, {0x30000, 0x40000, 0x500000, false}};
84 ConsoleHeapKeys k2(8);
85 std::uint32_t w[8] = {};
86 vsharp(w, 0x10100, 16, 4, 0);
87 EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0);
88 EXPECT(w[0] == 0x400100 && (w[1] & 0xffff) == 0 && w[2] == 4);
89 vsharp(w, 0x1ff00, 16, 32, 0); // 512 bytes past a range with 256 left: no records
90 EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && !w[0] && !w[1] && !w[2]);
91 vsharp(w, 0x30000, 0, 64, 0); // an unchecked range: the key table, then a miss
92 EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 1 && !w[2]);
93 // Backed spans leave a base as it is (before the key table); outside the ask table nothing is a miss.
94 ranges.backed = {{0x80000, 0x90000}};
95 ranges.ask = {{0x30000, 0x40000}};
96 ranges.use_ask = true;
97 vsharp(w, 0x80100, 0, 64, 0);
98 EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && w[0] == 0x80100 && w[2] == 64);
99 vsharp(w, 0x8ffc0, 0, 128, 0); // runs past the span: not backed, outside ask: no records, no miss
100 EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && !w[2]);
101 vsharp(w, 0x30000, 0, 64, 0); // in ask: a miss
102 EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 1);
103 // Signed offsets: a base with bit 47 set is the negative shader VA it names.
104 ranges.signed_offsets = true;
105 ranges.backed = {{0xffff800000000000ull, 0xffff800000010000ull}};
106 vsharp(w, 0x800000000100ull, 0, 64, 0);
107 EXPECT(leonida::console_heap_translate_slot(w, ranges, k2) == 0 && w[2] == 64);
108 std::vector<std::pair<std::uint64_t, std::uint64_t>> spans{{10, 20}, {15, 30}, {30, 40}, {50, 60}, {5, 5}};
109 leonida::merge_console_heap_spans(spans);
110 EXPECT(spans.size() == 2 && spans[0].first == 10 && spans[0].second == 40 && spans[1].first == 50);
111 return 0;
112}
113
114struct Case {
115 ConsoleHeapTables t;
116 std::vector<ConsoleHeapRange>& ranges = t.ranges;
117 ConsoleHeapKeys keys{14};
118};
119
120// Random slot words over a mix of classes; bases drawn from the ranges and keys so every path is taken.
121void make_slots(std::mt19937& rng, std::uint32_t* words, std::size_t slots, Case& c,
122 std::vector<ConsoleHeapKeys::Key>& entered) {
123 std::uniform_int_distribution<std::uint32_t> any;
124 for (std::size_t s = 0; s < slots; ++s) {
125 std::uint32_t* w = words + 8 * s;
126 for (int i = 0; i < 8; ++i) w[i] = any(rng);
127 const std::uint32_t kind = any(rng) % 10;
128 if (kind == 0) { // T#: TYPE >= 8
129 w[3] = (w[3] & 0x0fffffffu) | 0x80000000u;
130 continue;
131 }
132 if (kind == 1) { // other words with bits 30-31 set
133 w[3] |= 0x40000000u;
134 continue;
135 }
136 if (kind == 2) {
137 std::memset(w, 0, 32);
138 continue;
139 }
140 for (int half = 0; half < 2; ++half) {
141 std::uint32_t* k = w + 4 * half;
142 const std::uint32_t pick = any(rng) % 8;
143 const std::uint32_t stride = any(rng) % 3 == 0 ? 0 : any(rng) % 64;
144 const std::uint32_t records = 1 + any(rng) % 256;
145 if (pick < 3 && !c.ranges.empty()) {
146 const auto& r = c.ranges[any(rng) % c.ranges.size()];
147 vsharp(k, r.title_va + any(rng) % (r.end - r.title_va), stride, records, any(rng));
148 } else if (pick < 5) {
149 vsharp(k, 0x200000000ull + (any(rng) % 4096) * 64, stride, records, any(rng));
150 if (pick == 3) {
151 const ConsoleHeapKeys::Key key{k[0], k[1], k[2], k[3]};
152 const bool none = any(rng) % 4 == 0;
153 if (c.keys.put(key, 0x10000000ull + (any(rng) % 65536) * 256, 4096, none)) entered.push_back(key);
154 }
155 } else if (pick == 5) {
156 vsharp(k, 0, stride, records, any(rng));
157 } else if (pick == 6) {
158 vsharp(k, 0x300000000ull + any(rng), stride, 0, any(rng)); // no records: left as it is
159 } else if (half == 1) {
160 k[3] |= 0x40000000u; // a counter half that is no V#
161 } else {
162 vsharp(k, 0x400000000ull + any(rng), stride, records, any(rng)); // nowhere: a miss
163 }
164 }
165 }
166}
167
168} // namespace
169
170int main() {
171 if (const int failed = keys_on_cpu()) return failed;
172 std::puts("console heap keys (CPU): ok");
173
174 vktest::Device d;
175 d.request_buffer_device_address = true;
176 const auto status = d.initialize();
177 if (status == vktest::DeviceStatus::unavailable || (status == vktest::DeviceStatus::ready && !d.buffer_device_address)) {
178 std::printf("vk_console_heap_gpu_test: no Vulkan device with bufferDeviceAddress, skipped\n");
179 return 77;
180 }
181 if (status != vktest::DeviceStatus::ready) return 1;
182 VkPhysicalDeviceMemoryProperties memory{};
183 d.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory);
184
185 leonida::ConsoleHeapGpu gpu(d.device_proc, d.device, memory, 14);
186 EXPECT(gpu.init());
187
188 constexpr std::uint32_t kSlots = 6000;
189 void* input_data = nullptr;
190 void* copy_data = nullptr;
191 const VkBuffer input = d.buffer(VkDeviceSize(kSlots) * 32, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &input_data);
192 const VkBuffer copy = d.buffer(VkDeviceSize(kSlots) * 32, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &copy_data);
193 EXPECT(input && copy && input_data && copy_data);
194 const int heap = gpu.add_heap(d.device_address(input), d.device_address(copy), kSlots);
195 EXPECT(heap >= 0);
196 auto* in = static_cast<std::uint32_t*>(input_data);
197 auto* out = static_cast<std::uint32_t*>(copy_data);
198
199 std::mt19937 rng(1234);
200 Case c;
201 c.ranges = {{0x10000, 0x30000, 0x100000, true},
202 {0x40000, 0x48000, 0x0000ffff00000000ull, true}, // bits 32-47 of the answer
203 {0x50000, 0x60000, 0x200000, false},
204 {0x100000000ull, 0x100100000ull, 0x300000, true}};
205 std::vector<ConsoleHeapKeys::Key> entered;
206 make_slots(rng, in, kSlots, c, entered);
207 // The GPU's mirror gets the same keys.
208 gpu.with_keys([&](ConsoleHeapKeys& k) {
209 for (const auto& key : entered) {
210 std::uint64_t to = 0;
211 bool none = false;
212 c.keys.lookup(key, to, none);
213 k.put(key, to, 4096, none);
214 }
215 return 0;
216 });
217 gpu.set_ranges(c.ranges);
218
219 // One round: the listed slots are written as the reference says, the others keep the marker, and the misses
220 // are the reference's.
221 auto round = [&](const std::vector<std::uint32_t>& listed, std::uint64_t ticket, bool expect_overflow) -> int {
222 std::memset(out, 0xcd, std::size_t(kSlots) * 32);
223 gpu.queue(heap, listed.begin(), listed.end());
224 bool recorded = false;
225 EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); }));
226 EXPECT(recorded);
227 gpu.commit(true, ticket);
228 std::set<std::uint32_t> misses;
229 bool overflowed = false;
230 gpu.drain(ticket, [&](int h, std::uint32_t slot, std::uint32_t half) {
231 if (h == heap) misses.insert(slot * 2 + half);
232 }, [&](int) { overflowed = true; });
233 EXPECT(gpu.in_flight() == 0);
234 EXPECT(overflowed == expect_overflow);
235 std::set<std::uint32_t> expected_misses;
236 std::vector<std::uint8_t> is_listed(kSlots, 0);
237 for (const std::uint32_t s : listed) is_listed[s] = 1;
238 for (std::uint32_t s = 0; s < kSlots; ++s) {
239 std::uint32_t w[8];
240 std::memcpy(w, in + 8 * s, 32);
241 if (!is_listed[s]) {
242 for (int i = 0; i < 8; ++i) EXPECT(out[8 * s + i] == 0xcdcdcdcdu);
243 continue;
244 }
245 const unsigned missed = leonida::console_heap_translate_slot(w, c.t, c.keys);
246 if (missed & 1) expected_misses.insert(s * 2);
247 if (missed & 2) expected_misses.insert(s * 2 + 1);
248 if (std::memcmp(w, out + 8 * s, 32)) {
249 std::fprintf(stderr, "slot %u: in %08x %08x %08x %08x %08x %08x %08x %08x\n", s, in[8 * s],
250 in[8 * s + 1], in[8 * s + 2], in[8 * s + 3], in[8 * s + 4], in[8 * s + 5], in[8 * s + 6],
251 in[8 * s + 7]);
252 std::fprintf(stderr, " gpu %08x %08x %08x %08x %08x %08x %08x %08x\n", out[8 * s], out[8 * s + 1],
253 out[8 * s + 2], out[8 * s + 3], out[8 * s + 4], out[8 * s + 5], out[8 * s + 6],
254 out[8 * s + 7]);
255 std::fprintf(stderr, " cpu %08x %08x %08x %08x %08x %08x %08x %08x\n", w[0], w[1], w[2], w[3], w[4],
256 w[5], w[6], w[7]);
257 return 1;
258 }
259 }
260 if (!expect_overflow) EXPECT(misses == expected_misses);
261 else EXPECT(misses.size() == leonida::ConsoleHeapGpu::kMissCapacity);
262 std::printf(" %zu slots, %zu misses\n", listed.size(), misses.size());
263 return 0;
264 };
265
266 std::vector<std::uint32_t> all(kSlots);
267 for (std::uint32_t s = 0; s < kSlots; ++s) all[s] = s;
268 EXPECT(round(all, 1, false) == 0);
269 std::puts("console heap pass, every slot: ok");
270
271 // Key table updates and a new range table: erase some keys, enter answers for some misses, move a range.
272 std::vector<std::uint32_t> some;
273 for (std::uint32_t s = 0; s < kSlots; s += 3) some.push_back(s);
274 std::size_t erased = 0, added = 0;
275 for (std::size_t i = 0; i < entered.size(); i += 2) {
276 c.keys.erase(entered[i]);
277 gpu.with_keys([&](ConsoleHeapKeys& k) { return k.erase(entered[i]); });
278 ++erased;
279 }
280 for (std::uint32_t s = 0; s < kSlots && added < 200; ++s) {
281 std::uint32_t w[8];
282 std::memcpy(w, in + 8 * s, 32);
283 std::uint32_t copy_w[8];
284 std::memcpy(copy_w, w, 32);
285 const unsigned missed = leonida::console_heap_translate_slot(copy_w, c.t, c.keys);
286 if (!(missed & 1)) continue;
287 const ConsoleHeapKeys::Key key{w[0], w[1], w[2], w[3]};
288 c.keys.put(key, 0x7000000000ull + added * 64, 64, added % 5 == 0);
289 gpu.with_keys([&](ConsoleHeapKeys& k) { return k.put(key, 0x7000000000ull + added * 64, 64, added % 5 == 0); });
290 ++added;
291 }
292 c.ranges[0].shader_va = 0x900000;
293 c.ranges[2].checked = true;
294 gpu.set_ranges(c.ranges);
295 EXPECT(round(some, 2, false) == 0);
296 std::printf("console heap pass, %zu keys erased, %zu entered, ranges moved: ok\n", erased, added);
297
298 // A submission that did not reach the queue: its slots and updates come back for the next pass.
299 {
300 const ConsoleHeapKeys::Key key{in[8 * 5], in[8 * 5 + 1], in[8 * 5 + 2], in[8 * 5 + 3]};
301 gpu.queue(heap, 5);
302 bool recorded = false;
303 EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); }));
304 EXPECT(recorded && !gpu.pending());
305 gpu.commit(false, 0);
306 EXPECT(gpu.pending() && gpu.in_flight() == 0);
307 (void)key;
308 }
309 EXPECT(round({5}, 3, false) == 0);
310 // Backed and ask tables: part of the keyed bases become backed (answered before the key table), and only bases
311 // in the ask span miss.
312 c.t.backed = {{0x200000000ull, 0x200008000ull}, {0x10000ull, 0x18000ull}};
313 c.t.ask = {{0x400000000ull, 0x500000000ull}};
314 c.t.use_ask = true;
315 gpu.set_spans(leonida::ConsoleHeapGpu::backed_table, c.t.backed);
316 gpu.set_spans(leonida::ConsoleHeapGpu::ask_table, c.t.ask);
317 EXPECT(round(all, 7, false) == 0);
318 std::puts("console heap pass, backed and ask tables: ok");
319 {
320 // kZeroFirst: words that are no buffer pair and no T# get dwords 0-3 zeroed; the last queue() decides.
321 std::vector<std::uint32_t> flagged;
322 for (std::uint32_t s2 = 0; s2 < kSlots && flagged.size() < 64; ++s2)
323 if (in[8 * s2 + 3] >> 30) flagged.push_back(s2);
324 EXPECT(flagged.size() == 64);
325 std::memset(out, 0xcd, std::size_t(kSlots) * 32);
326 for (std::size_t i = 0; i < flagged.size(); ++i) {
327 gpu.queue(heap, flagged[i] | leonida::ConsoleHeapGpu::kZeroFirst);
328 if (i % 2) gpu.queue(heap, flagged[i]); // queued again without the bit: copied as it is
329 }
330 bool recorded = false;
331 EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); }));
332 gpu.commit(true, 8);
333 gpu.drain(8, [](int, std::uint32_t, std::uint32_t) {}, [](int) {});
334 EXPECT(recorded);
335 for (std::size_t i = 0; i < flagged.size(); ++i) {
336 std::uint32_t w[8];
337 std::memcpy(w, in + 8 * flagged[i], 32);
338 leonida::console_heap_translate_slot(w, c.t, c.keys, i % 2 == 0);
339 EXPECT(!std::memcmp(w, out + 8 * flagged[i], 32));
340 if (i % 2 == 0) EXPECT(!out[8 * flagged[i]] && !out[8 * flagged[i] + 3]);
341 }
342 }
343 std::puts("console heap pass, words that are no descriptor: ok");
344 {
345 // rescan(): one range dispatch rewrites the buffer pairs of [0, n) and leaves every other slot as it was.
346 constexpr std::uint32_t n = 4000;
347 std::memset(out, 0xcd, std::size_t(kSlots) * 32);
348 gpu.rescan(heap, n);
349 EXPECT(gpu.pending());
350 bool recorded = false;
351 EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); }));
352 gpu.commit(true, 9);
353 std::set<std::uint32_t> misses;
354 gpu.drain(9, [&](int h, std::uint32_t slot, std::uint32_t half) { if (h == heap) misses.insert(slot * 2 + half); },
355 [](int) {});
356 EXPECT(recorded);
357 std::set<std::uint32_t> expected;
358 std::size_t pairs = 0;
359 for (std::uint32_t s2 = 0; s2 < kSlots; ++s2) {
360 std::uint32_t w[8];
361 std::memcpy(w, in + 8 * s2, 32);
362 if (s2 >= n || (w[3] >> 30)) {
363 for (int i = 0; i < 8; ++i) EXPECT(out[8 * s2 + i] == 0xcdcdcdcdu);
364 continue;
365 }
366 ++pairs;
367 const unsigned missed = leonida::console_heap_translate_slot(w, c.t, c.keys);
368 if (missed & 1) expected.insert(s2 * 2);
369 if (missed & 2) expected.insert(s2 * 2 + 1);
370 EXPECT(!std::memcmp(w, out + 8 * s2, 32));
371 }
372 EXPECT(misses == expected && pairs > 1000);
373 EXPECT(!gpu.pending());
374 }
375 std::puts("console heap pass, range rescan: ok");
376 {
377 // rescan_filtered(): only the slots whose metadata (left by the last pass over them, the rescan above) meets a
378 // change span are translated again: a title span holding one slot's base, a shader span holding another's
379 // result. The rest keep what they hold, without the title's words being read.
380 constexpr std::uint32_t n = 4000;
381 struct Half {
382 std::uint64_t base, to, span;
383 };
384 std::vector<std::array<Half, 2>> meta(n);
385 std::vector<bool> pair(n, false);
386 for (std::uint32_t s2 = 0; s2 < n; ++s2) {
387 std::uint32_t w[8];
388 std::memcpy(w, in + 8 * s2, 32);
389 if (w[3] >> 30) continue;
390 pair[s2] = true;
391 std::uint32_t before[8];
392 std::memcpy(before, w, 32);
393 leonida::console_heap_translate_slot(w, c.t, c.keys);
394 for (int h = 0; h < 2; ++h) {
395 const std::uint32_t* b = before + 4 * h;
396 const std::uint32_t* a = w + 4 * h;
397 if (!b[2]) {
398 meta[s2][h] = {};
399 continue;
400 }
401 const std::uint64_t stride = (b[1] >> 16) & 0x3fff;
402 const std::uint64_t span = std::min<std::uint64_t>(std::uint64_t(b[2]) * std::max<std::uint64_t>(stride, 1),
403 0xffffffffull);
404 meta[s2][h] = {b[0] | (std::uint64_t(b[1] & 0xffff) << 32),
405 a[2] ? a[0] | (std::uint64_t(a[1] & 0xffff) << 32) : 0, span};
406 }
407 }
408 std::uint32_t by_title = UINT32_MAX, by_result = UINT32_MAX;
409 for (std::uint32_t s2 = 0; s2 < n; ++s2) {
410 if (!pair[s2] || !meta[s2][0].span) continue;
411 if (by_title == UINT32_MAX) by_title = s2;
412 else if (meta[s2][0].to && meta[s2][0].to != meta[by_title][0].base) {
413 by_result = s2;
414 break;
415 }
416 }
417 EXPECT(by_title != UINT32_MAX && by_result != UINT32_MAX);
418 const leonida::ConsoleHeapSpans title{{meta[by_title][0].base, meta[by_title][0].base + 1}};
419 const leonida::ConsoleHeapSpans shader{{meta[by_result][0].to, meta[by_result][0].to + 1}};
420 const auto meets = [](const leonida::ConsoleHeapSpans& spans, std::uint64_t v, std::uint64_t bytes) {
421 for (const auto& [a, b] : spans)
422 if (v < b && a < v + bytes) return true;
423 return false;
424 };
425 std::set<std::uint32_t> touched;
426 for (std::uint32_t s2 = 0; s2 < n; ++s2)
427 for (const Half& h : meta[s2]) {
428 if (!pair[s2] || !h.span) continue;
429 if (meets(title, h.base, 1) || meets(shader, h.base, h.span) || (h.to && meets(shader, h.to, h.span)))
430 touched.insert(s2);
431 }
432 EXPECT(touched.count(by_title) && touched.count(by_result) && touched.size() < 1000);
433 std::memset(out, 0xcd, std::size_t(kSlots) * 32);
434 const auto before = gpu.take_stats();
435 (void)before;
436 gpu.rescan_filtered(heap, n, shader, title);
437 EXPECT(gpu.pending());
438 bool recorded = false;
439 EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); }));
440 gpu.commit(true, 10);
441 gpu.drain(10, [](int, std::uint32_t, std::uint32_t) {}, [](int) {});
442 EXPECT(recorded && !gpu.pending());
443 for (std::uint32_t s2 = 0; s2 < kSlots; ++s2) {
444 if (!touched.count(s2)) {
445 for (int i = 0; i < 8; ++i) EXPECT(out[8 * s2 + i] == 0xcdcdcdcdu);
446 continue;
447 }
448 std::uint32_t w[8];
449 std::memcpy(w, in + 8 * s2, 32);
450 leonida::console_heap_translate_slot(w, c.t, c.keys);
451 EXPECT(!std::memcmp(w, out + 8 * s2, 32));
452 }
453 EXPECT(gpu.take_stats().filtered == n);
454 // A failed submission: the filtered rescan and its spans come back, and the next pass does them.
455 std::memset(out, 0xcd, std::size_t(kSlots) * 32);
456 gpu.rescan_filtered(heap, n, shader, title);
457 EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); }));
458 gpu.commit(false, 0);
459 EXPECT(gpu.pending());
460 EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); }));
461 gpu.commit(true, 11);
462 gpu.drain(11, [](int, std::uint32_t, std::uint32_t) {}, [](int) {});
463 std::size_t rewritten = 0;
464 for (std::uint32_t s2 = 0; s2 < n; ++s2) rewritten += out[8 * s2] != 0xcdcdcdcdu || out[8 * s2 + 3] != 0xcdcdcdcdu;
465 EXPECT(rewritten == touched.size());
466 std::printf("console heap pass, filtered rescan: ok (%zu of %u slots)\n", touched.size(), n);
467 }
468 {
469 // queue_copy(): buffer copies recorded at the start of the pass; their keepalive goes once the pass retires.
470 constexpr VkDeviceSize kBytes = 64 * 1024;
471 void* src_data = nullptr;
472 void* dst_data = nullptr;
473 const VkBuffer src = d.buffer(kBytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &src_data);
474 const VkBuffer dst = d.buffer(kBytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &dst_data);
475 EXPECT(src && dst && src_data && dst_data);
476 auto* sw = static_cast<std::uint32_t*>(src_data);
477 for (std::size_t i = 0; i < kBytes / 4; ++i) sw[i] = std::uint32_t(i * 2654435761u);
478 std::memset(dst_data, 0, kBytes);
479 auto keep = std::make_shared<int>(7);
480 std::weak_ptr<int> watch = keep;
481 gpu.queue_copy(src, 4096, dst, 0, 8192, keep);
482 gpu.queue_copy(src, 0, dst, 32768, 4096, keep);
483 keep.reset();
484 EXPECT(gpu.pending() && !watch.expired());
485 bool recorded = false;
486 EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); }));
487 EXPECT(recorded && !watch.expired());
488 gpu.commit(true, 10);
489 gpu.drain(10, [](int, std::uint32_t, std::uint32_t) {}, [](int) {});
490 EXPECT(watch.expired());
491 const auto* dw = static_cast<const std::uint8_t*>(dst_data);
492 EXPECT(!std::memcmp(dw, static_cast<const std::uint8_t*>(src_data) + 4096, 8192));
493 EXPECT(!std::memcmp(dw + 32768, src_data, 4096));
494 EXPECT(dw[8192] == 0 && dw[32768 + 4096] == 0);
495 }
496 std::puts("console heap pass, queued copies: ok");
497 c.t.backed.clear();
498 c.t.ask = {{0, ~0ull}}; // everything asks again: the overflow cases below need their misses
499 gpu.set_spans(leonida::ConsoleHeapGpu::backed_table, c.t.backed);
500 gpu.set_spans(leonida::ConsoleHeapGpu::ask_table, c.t.ask);
501 std::puts("console heap pass, failed submission queued again: ok");
502
503 // More misses than the list holds: the overflow is reported, and the slots are still written.
504 {
505 constexpr std::uint32_t kStride = 0;
506 for (std::uint32_t s = 0; s < kSlots; ++s) {
507 vsharp(in + 8 * s, 0x500000000ull + s * 0x100, kStride, 16, 0);
508 vsharp(in + 8 * s + 4, 0x600000000ull + s * 0x100, kStride, 16, 0);
509 }
510 std::vector<std::uint32_t> many;
511 for (std::uint32_t s = 0; s < kSlots; ++s) many.push_back(s);
512 // 12,000 misses fit; list them twice over with a second heap view of the same buffers to pass 65,536.
513 const int heap2 = gpu.add_heap(d.device_address(input), d.device_address(copy), kSlots);
514 EXPECT(heap2 >= 0);
515 std::size_t total = 0;
516 for (int h = 0; h < 6; ++h) { // 6 x 12,000 = 72,000 misses in one pass over the two heaps
517 gpu.queue(h % 2 ? heap2 : heap, many.begin(), many.end());
518 total += 2 * many.size();
519 }
520 (void)total;
521 bool recorded = false;
522 EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); }));
523 // Queued twice per heap only counts once: 2 heaps x 12,000 = 24,000 misses, under the list. Queue a heap of
524 // its own instead to pass it.
525 gpu.commit(true, 4);
526 std::size_t misses = 0;
527 bool overflowed = false;
528 gpu.drain(4, [&](int, std::uint32_t, std::uint32_t) { ++misses; }, [&](int) { overflowed = true; });
529 EXPECT(recorded && misses == 24000 && !overflowed);
530 gpu.remove_heap(heap2);
531 }
532 std::puts("console heap pass, a slot queued twice is translated once: ok");
533 {
534 // Six heap views of the same buffers: 6 x 12,000 = 72,000 misses, past the list's 65,536.
535 std::vector<int> views;
536 for (int i = 0; i < 5; ++i) views.push_back(gpu.add_heap(d.device_address(input), d.device_address(copy), kSlots));
537 std::vector<std::uint32_t> many;
538 for (std::uint32_t s = 0; s < kSlots; ++s) many.push_back(s);
539 gpu.queue(heap, many.begin(), many.end());
540 for (const int v : views) {
541 EXPECT(v >= 0);
542 gpu.queue(v, many.begin(), many.end());
543 }
544 bool recorded = false;
545 EXPECT(d.run([&](VkCommandBuffer cb) { return recorded = gpu.record(cb); }));
546 gpu.commit(true, 5);
547 std::size_t misses = 0;
548 bool overflowed = false;
549 gpu.drain(5, [&](int, std::uint32_t, std::uint32_t) { ++misses; }, [&](int) { overflowed = true; });
550 EXPECT(recorded && overflowed && misses == leonida::ConsoleHeapGpu::kMissCapacity);
551 for (std::uint32_t s = 0; s < kSlots; ++s) EXPECT(out[8 * s] == 0 && out[8 * s + 2] == 0);
552 for (const int v : views) gpu.remove_heap(v);
553 }
554 std::puts("console heap pass, miss list overflow: ok");
555 {
556 // Clustered words (bases a megabyte apart) entered in both tables: every slot answered, none missed.
557 Case clustered;
558 for (std::uint32_t s2 = 0; s2 < 3000; ++s2) {
559 for (int half = 0; half < 2; ++half) {
560 const std::uint32_t i = 2 * s2 + std::uint32_t(half);
561 std::uint32_t* k = in + 8 * s2 + 4 * half;
562 vsharp(k, 0x700000000ull + (std::uint64_t(i) << 20), 16, 8, 0x2000);
563 const ConsoleHeapKeys::Key key{k[0], k[1], k[2], k[3]};
564 EXPECT(clustered.keys.put(key, 0x1000000ull + i * 256ull, 128, (i % 7) == 0));
565 EXPECT(gpu.with_keys([&](ConsoleHeapKeys& keys) {
566 return keys.put(key, 0x1000000ull + i * 256ull, 128, (i % 7) == 0);
567 }));
568 }
569 }
570 std::swap(c.keys, clustered.keys);
571 c.ranges.clear();
572 gpu.set_ranges(c.ranges);
573 EXPECT(round(all, 6, false) == 0);
574 }
575 std::puts("console heap pass, clustered words: ok");
576 const auto stats = gpu.take_stats();
577 std::printf("console heap pass: %llu passes, %llu slots, %llu updates, %llu misses, %llu overflows, %llu failed\n",
578 (unsigned long long)stats.passes, (unsigned long long)stats.slots, (unsigned long long)stats.updates,
579 (unsigned long long)stats.misses, (unsigned long long)stats.overflows,
580 (unsigned long long)stats.failed);
581 EXPECT(d.validation_errors() == 0);
582 std::puts("vk_console_heap_gpu_test: ok");
583 return 0;
584}
diff --git a/runtime/test/vk_descriptor_bench.cpp b/runtime/test/vk_descriptor_bench.cpp
index 3dd179268..c048f3745 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) {
710 710
711 for (std::uint32_t i = 0; i < out.t_count; ++i) { 711 for (std::uint32_t i = 0; i < out.t_count; ++i) {
712 t_keys[i] = make_bench_tsharp(i + 1u); 712 t_keys[i] = make_bench_tsharp(i + 1u);
713 table.insert(t_keys[i], 1u + i); 713 // The T#s name sampled 2D images (the tagged contract's kind word): a bench entry carries the same word.
714 table.insert(t_keys[i], 1u + i, leonida::kind_sampled_bit(0));
714 } 715 }
715 for (std::uint32_t i = 0; i < out.s_count; ++i) { 716 for (std::uint32_t i = 0; i < out.s_count; ++i) {
716 s_keys[i] = make_bench_ssharp(i + 1u); 717 s_keys[i] = make_bench_ssharp(i + 1u);
diff --git a/runtime/test/vk_device_markers_test.cpp b/runtime/test/vk_device_markers_test.cpp
new file mode 100644
index 000000000..f6e76fd73
--- /dev/null
+++ b/runtime/test/vk_device_markers_test.cpp
@@ -0,0 +1,142 @@
1// The AMD breadcrumbs of the device-fault report (src/vulkan_device_markers.h, LEONIDA_DEVICE_MARKERS=1) on a real
2// device: dispatches recorded through CheckpointRecorder with the markers on, submitted and waited for, leave their
3// queue's started and finished markers at the last dispatch's seq, and the report calls none of them hung. Two
4// submissions, so the second continues the first one's numbering. The shader is an empty hand-written compute
5// program; nothing is meant to fault or hang. SKIP (77) without a Vulkan device or without VK_AMD_buffer_marker.
6// LEONIDA_VK_VALIDATION=1 runs it under VK_LAYER_KHRONOS_validation (any validation error fails the test).
7#include "vk_test_device.h"
8#include "../src/vulkan_device_fault.h"
9
10#include <array>
11#include <cstdint>
12#include <cstdio>
13#include <vector>
14
15#define EXPECT(condition) do { \
16 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
17} while (0)
18
19namespace {
20
21using namespace leonida;
22
23// OpCapability Shader; OpMemoryModel Logical GLSL450; OpEntryPoint GLCompute %1 "main"; LocalSize 1 1 1;
24// void main() {}
25constexpr std::uint32_t empty_compute[] = {
26 0x07230203u, 0x00010000u, 0u, 5u, 0u,
27 (2u << 16) | 17u, 1u, // OpCapability Shader
28 (3u << 16) | 14u, 0u, 1u, // OpMemoryModel Logical GLSL450
29 (5u << 16) | 15u, 5u, 1u, 0x6e69616du, 0u, // OpEntryPoint GLCompute %1 "main"
30 (6u << 16) | 16u, 1u, 17u, 1u, 1u, 1u, // OpExecutionMode %1 LocalSize 1 1 1
31 (2u << 16) | 19u, 2u, // %2 = OpTypeVoid
32 (3u << 16) | 33u, 3u, 2u, // %3 = OpTypeFunction %2
33 (5u << 16) | 54u, 2u, 1u, 0u, 3u, // %1 = OpFunction %2 None %3
34 (2u << 16) | 248u, 4u, // %4 = OpLabel
35 (1u << 16) | 253u, // OpReturn
36 (1u << 16) | 56u, // OpFunctionEnd
37};
38
39struct Pipeline {
40 const vktest::Device& d;
41 VkShaderModule module = VK_NULL_HANDLE;
42 VkPipelineLayout layout = VK_NULL_HANDLE;
43 VkPipeline pipeline = VK_NULL_HANDLE;
44
45 explicit Pipeline(const vktest::Device& device) : d(device) {
46 VkShaderModuleCreateInfo code{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
47 code.codeSize = sizeof(empty_compute);
48 code.pCode = empty_compute;
49 if (d.fn<PFN_vkCreateShaderModule>("vkCreateShaderModule")(d.device, &code, nullptr, &module) != VK_SUCCESS)
50 return;
51 VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
52 if (d.fn<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(d.device, &layout_info, nullptr, &layout) !=
53 VK_SUCCESS)
54 return;
55 VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
56 info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO};
57 info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
58 info.stage.module = module;
59 info.stage.pName = "main";
60 info.layout = layout;
61 d.fn<PFN_vkCreateComputePipelines>("vkCreateComputePipelines")(d.device, VK_NULL_HANDLE, 1, &info, nullptr,
62 &pipeline);
63 }
64 ~Pipeline() {
65 if (pipeline) d.fn<PFN_vkDestroyPipeline>("vkDestroyPipeline")(d.device, pipeline, nullptr);
66 if (layout) d.fn<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(d.device, layout, nullptr);
67 if (module) d.fn<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(d.device, module, nullptr);
68 }
69};
70
71int run(vktest::Device& d) {
72 VkPhysicalDeviceMemoryProperties memory{};
73 d.instance_fn<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory);
74 DeviceFaultExtensions enabled;
75 enabled.markers = true;
76 // The runtime's devices always have synchronization2 (vulkan13_features.h), and so does this one: the marker
77 // writes take the vkCmdWriteBufferMarker2AMD path, as in a game run.
78 DeviceFaultDiagnostics diagnostics(d.device_proc, d.device, enabled, &memory, true);
79 EXPECT(diagnostics.markers_on());
80 diagnostics.add_queue(d.queue);
81 EXPECT(diagnostics.marker_slot(d.queue).started == 0 && diagnostics.marker_slot(d.queue).finished == 0);
82
83 Pipeline pipeline(d);
84 EXPECT(pipeline.pipeline);
85 const auto bind = d.fn<PFN_vkCmdBindPipeline>("vkCmdBindPipeline");
86 const auto dispatch = d.fn<PFN_vkCmdDispatch>("vkCmdDispatch");
87 const auto pipeline_id = reinterpret_cast<std::uintptr_t>(&pipeline);
88 diagnostics.pipeline_names[pipeline_id] = {"cs_empty_test"};
89 const std::array<std::uint32_t, 32> roots{};
90
91 std::uint64_t last_seq = 0;
92 for (unsigned round = 0; round < 2; ++round) {
93 const unsigned dispatches = round == 0 ? 5 : 3;
94 auto submission = diagnostics.begin_submission(diagnostics.next_execute_call(), d.queue, "direct", 1);
95 EXPECT(submission.markers);
96 const CheckpointRecorder recorder{nullptr, submission, diagnostics.pipeline_names, 0};
97 const bool ran = d.run([&](VkCommandBuffer cb) {
98 for (unsigned i = 0; i < dispatches; ++i) {
99 recorder.dispatch(cb, i, pipeline.pipeline, pipeline_id, roots, {1 + i, 1, 1});
100 bind(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline.pipeline);
101 dispatch(cb, 1 + i, 1, 1);
102 recorder.dispatched(cb);
103 }
104 return true;
105 });
106 EXPECT(ran);
107 EXPECT(submission.dispatches.size() == dispatches);
108 EXPECT(submission.dispatches.front().seq == last_seq + 1);
109 last_seq = submission.dispatches.back().seq;
110 EXPECT(last_seq == (round == 0 ? 5u : 8u));
111 diagnostics.publish(std::move(submission));
112 // vkQueueWaitIdle has returned: every marker the GPU wrote is in the coherent buffer.
113 const MarkerSlot slot = diagnostics.marker_slot(d.queue);
114 std::printf("round %u: started=%u finished=%u, last seq %llu\n", round, slot.started, slot.finished,
115 static_cast<unsigned long long>(last_seq));
116 EXPECT(slot.started == last_seq && slot.finished == last_seq);
117 EXPECT(diagnostics.report_markers(false).empty());
118 }
119 return 0;
120}
121
122} // namespace
123
124int main() {
125 std::setvbuf(stdout, nullptr, _IONBF, 0);
126 vktest::Device d;
127 d.request_buffer_marker = true;
128 const auto status = d.initialize();
129 if (status == vktest::DeviceStatus::unavailable) {
130 std::printf("SKIP: no usable Vulkan device\n");
131 return 77;
132 }
133 if (status != vktest::DeviceStatus::ready) return 1;
134 if (!d.buffer_marker) {
135 std::printf("SKIP: the device has no VK_AMD_buffer_marker\n");
136 return 77;
137 }
138 const int rc = run(d);
139 const unsigned errors = d.validation_errors();
140 std::printf("Vulkan validation errors: %u%s\n", errors, d.validation ? "" : " (validation off)");
141 return rc ? rc : errors ? 1 : 0;
142}
diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp
index cd374e8b6..872e30b93 100644
--- a/runtime/test/vk_harness.cpp
+++ b/runtime/test/vk_harness.cpp
@@ -929,7 +929,8 @@ int main(int argc, char** argv) {
929 LOADD(vkCreateSampler); LOADD(vkCreateDescriptorPool); LOADD(vkAllocateDescriptorSets); 929 LOADD(vkCreateSampler); LOADD(vkCreateDescriptorPool); LOADD(vkAllocateDescriptorSets);
930 LOADD(vkUpdateDescriptorSets); 930 LOADD(vkUpdateDescriptorSets);
931 leonida::DescriptorTable desc_table(16); 931 leonida::DescriptorTable desc_table(16);
932 desc_table.insert(tsharp, 1); 932 // The translated modules read the entry's kind (descriptor_table.h): this T# is a sampled 2D image.
933 desc_table.insert(tsharp, 1, leonida::kind_sampled_bit(0));
933 desc_table.insert(ssharp, 1); 934 desc_table.insert(ssharp, 1);
934 const auto table = desc_table.build_gpu_buffer(true); 935 const auto table = desc_table.build_gpu_buffer(true);
935 VkBuffer tb = VK_NULL_HANDLE; 936 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 34120f00e..f7aae702f 100644
--- a/runtime/test/vk_host_texture_order_test.cpp
+++ b/runtime/test/vk_host_texture_order_test.cpp
@@ -7,13 +7,21 @@
7namespace { 7namespace {
8unsigned waits = 0; 8unsigned waits = 0;
9VkResult wait_result = VK_SUCCESS; 9VkResult wait_result = VK_SUCCESS;
10VkResult VKAPI_CALL idle(VkDevice) { ++waits; return wait_result; } 10std::uint64_t last_timeout = 0;
11// The writes wait for the queue timelines (vkWaitSemaphores, bounded), not for the device.
12VkResult VKAPI_CALL wait_semaphores(VkDevice, const VkSemaphoreWaitInfo* info, std::uint64_t timeout) {
13 ++waits;
14 last_timeout = timeout;
15 return info && info->semaphoreCount ? wait_result : VK_ERROR_UNKNOWN;
16}
17VkResult VKAPI_CALL device_idle(VkDevice) { return VK_ERROR_UNKNOWN; } // must not be called any more
11PFN_vkVoidFunction VKAPI_CALL no_proc(VkDevice, const char*) { return nullptr; } 18PFN_vkVoidFunction VKAPI_CALL no_proc(VkDevice, const char*) { return nullptr; }
12} 19}
13 20
14int main() { 21int main() {
15 leonida::VulkanContext ctx(no_proc, VK_NULL_HANDLE, false); 22 leonida::VulkanContext ctx(no_proc, VK_NULL_HANDLE, false);
16 ctx.vk.vkDeviceWaitIdle = idle; 23 ctx.vk.vkWaitSemaphores = wait_semaphores;
24 ctx.vk.vkDeviceWaitIdle = device_idle;
17 leonida::ResourceBinding binding{}; 25 leonida::ResourceBinding binding{};
18 binding.image = reinterpret_cast<VkImage>(1); 26 binding.image = reinterpret_cast<VkImage>(1);
19 binding.mip_levels = 1; 27 binding.mip_levels = 1;
@@ -32,14 +40,22 @@ int main() {
32 contender.join(); 40 contender.join();
33 return !raced; 41 return !raced;
34 }; 42 };
35 ctx.note_image_work_locked(); 43 const auto progress = reinterpret_cast<VkSemaphore>(std::uintptr_t{0x10});
36 if (ctx.write_host_texture(2, 0, copy) != VK_NOT_READY || copies || waits) return 1; 44 const auto submit = [&] { // a queue submission in flight: a retirement ticket, and image work pending
37 if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 1 || waits != 1) return 1; 45 std::lock_guard lock(ctx.submit_mutex());
38 if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 2 || waits != 1) return 1; 46 ctx.record_submit_locked(progress, 1);
39 ctx.note_image_work_locked(); 47 };
48 submit();
49 if (ctx.write_host_texture(2, 0, copy) != VK_NOT_READY || copies || waits) return 1; // wrong layout: no wait
50 if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 1 || waits != 1) return 2;
51 if (last_timeout == 0 || last_timeout == UINT64_MAX) return 3; // bounded
52 if (ctx.write_host_texture(1, 0, copy) != VK_SUCCESS || copies != 2 || waits != 1) return 4; // wait reused
53 submit();
54 wait_result = VK_TIMEOUT; // the submitted work is not done in time: skipped as not ready, not a failure
55 if (ctx.write_host_texture(1, 0, copy) != VK_NOT_READY || copies != 2 || waits != 2) return 5;
40 wait_result = VK_ERROR_DEVICE_LOST; 56 wait_result = VK_ERROR_DEVICE_LOST;
41 if (ctx.write_host_texture(1, 0, copy) != VK_ERROR_DEVICE_LOST || copies != 2 || waits != 2) return 1; 57 if (ctx.write_host_texture(1, 0, copy) != VK_ERROR_DEVICE_LOST || copies != 2 || waits != 3) return 6;
42 const auto stats = ctx.host_texture_stats(); 58 const auto stats = ctx.host_texture_stats();
43 if (stats.copies != 2 || stats.waits != 2) return 1; 59 if (stats.copies != 2 || stats.waits != 3) return 7;
44 std::puts("ordered texture upload: layout, submit exclusion, wait reuse, wait failure passed"); 60 std::puts("ordered texture upload: layout, submit exclusion, bounded timeline wait, reuse, timeout, loss passed");
45} 61}
diff --git a/runtime/test/vk_image_fuzz.cpp b/runtime/test/vk_image_fuzz.cpp
index 52b59d6e0..cc645e6d3 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) {
495 std::fprintf(stderr, "FAILED add_image -> 0 (line %d)\n", __LINE__); 495 std::fprintf(stderr, "FAILED add_image -> 0 (line %d)\n", __LINE__);
496 return 1; 496 return 1;
497 } 497 }
498 set->insert_key(make_tsharp_key(spec.tsharp), index); 498 set->insert_key(make_tsharp_key(spec.tsharp), index, ImageDimension::dim_2d);
499 const VkPushConstantRange push{.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, .size = push_bytes}; 499 const VkPushConstantRange push{.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, .size = push_bytes};
500 const VkDescriptorSetLayout set_layout = set->layout(); 500 const VkDescriptorSetLayout set_layout = set->layout();
501 VkPipelineLayoutCreateInfo pli{.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, 501 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 0e39d0f62..3ff89524f 100644
--- a/runtime/test/vk_pipeline_check.cpp
+++ b/runtime/test/vk_pipeline_check.cpp
@@ -7,10 +7,10 @@
7// descriptor-free shaders with the standard push-constant range 7// descriptor-free shaders with the standard push-constant range
8// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) 8// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass)
9// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py) 9// paired with minimal partner stubs from <spirv dir>/stubs/ (generated by tools/spirv_stubs.py)
10// VK_EXT_mesh_shader (with meshShaderQueries) and VK_KHR_maintenance8 are always enabled when supported so the 10// VK_EXT_mesh_shader (with meshShaderQueries), VK_KHR_maintenance8 and VK_EXT_transform_feedback are always enabled
11// saved pipeline cache matches the runtime's device key; other optional device extensions are enabled only when 11// when supported so the saved pipeline cache matches the runtime's device key; other optional device extensions are
12// needed by the selected shaders. Shaders whose required features or partner stubs are unavailable are reported as 12// enabled only when needed by the selected shaders. Shaders whose required features or partner stubs are unavailable
13// skipped rather than failed. 13// are reported as skipped rather than failed.
14// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every 14// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every
15// 10 minutes and at the end 15// 10 minutes and at the end
16// --jobs N compile on up to N worker threads (default: half the hardware threads) 16// --jobs N compile on up to N worker threads (default: half the hardware threads)
@@ -30,6 +30,9 @@
30// --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and 30// --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and
31// APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a 31// APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a
32// pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count. 32// pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count.
33// --nv-diagnostics create the device with VK_NV_device_diagnostics_config and the flags the runtime's
34// LEONIDA_DEVICE_FAULT=1 / LEONIDA_AFTERMATH=1 use (shader debug info, resource tracking, automatic
35// checkpoints), to measure what that does to compile times and to cache hits
33// --isolate check in child processes, --isolate-batch modules at a time (default 256), so a module 36// --isolate check in child processes, --isolate-batch modules at a time (default 256), so a module
34// that kills the driver is recorded as failed ("MODULE CRASH") and the pass 37// that kills the driver is recorded as failed ("MODULE CRASH") and the pass
35// goes on. A crashed batch is bisected to the module. Children run one after the other and share 38// 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) {
806 unsigned large_parallel = 0; // 0 = by the memory budget 809 unsigned large_parallel = 0; // 0 = by the memory budget
807 double slow = 30.0; 810 double slow = 30.0;
808 std::string stage_filter = "all"; 811 std::string stage_filter = "all";
809 bool cache_feedback = false, isolate = false, iso_child = false; 812 bool cache_feedback = false, isolate = false, iso_child = false, nv_diagnostics = false;
810 size_t isolate_batch = 256; 813 size_t isolate_batch = 256;
811 for (int i = 2; i < argc; i++) { 814 for (int i = 2; i < argc; i++) {
812 std::string a = argv[i]; 815 std::string a = argv[i];
@@ -851,6 +854,7 @@ int main(int argc, char** argv) {
851 else if (a == "--skip-file") valid = !(skip_path = value()).empty(); 854 else if (a == "--skip-file") valid = !(skip_path = value()).empty();
852 else if (a == "--cache-feedback") cache_feedback = true; 855 else if (a == "--cache-feedback") cache_feedback = true;
853 else if (a == "--isolate") isolate = true; 856 else if (a == "--isolate") isolate = true;
857 else if (a == "--nv-diagnostics") nv_diagnostics = true;
854 else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs 858 else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs
855 else if (a == "--isolate-batch") { // parsed like the other numbers (#1735); at least one per batch 859 else if (a == "--isolate-batch") { // parsed like the other numbers (#1735); at least one per batch
856 valid = number(isolate_batch); 860 valid = number(isolate_batch);
@@ -1122,6 +1126,7 @@ int main(int argc, char** argv) {
1122 1126
1123 // Query the core and optional device features used by the checker. 1127 // Query the core and optional device features used by the checker.
1124 VkPhysicalDeviceMeshShaderFeaturesEXT mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; 1128 VkPhysicalDeviceMeshShaderFeaturesEXT mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
1129 VkPhysicalDeviceTransformFeedbackFeaturesEXT tf{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT};
1125 VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; 1130 VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR};
1126 VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; 1131 VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT};
1127#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME 1132#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
@@ -1144,6 +1149,10 @@ int main(int argc, char** argv) {
1144 link(&f12, reinterpret_cast<VkBaseOutStructure*>(&f12), nullptr, true); 1149 link(&f12, reinterpret_cast<VkBaseOutStructure*>(&f12), nullptr, true);
1145 link(&f13, reinterpret_cast<VkBaseOutStructure*>(&f13), nullptr, true); 1150 link(&f13, reinterpret_cast<VkBaseOutStructure*>(&f13), nullptr, true);
1146 const bool ext_mesh = link(&mesh, reinterpret_cast<VkBaseOutStructure*>(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, true); 1151 const bool ext_mesh = link(&mesh, reinterpret_cast<VkBaseOutStructure*>(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, true);
1152 // The runtime's device enables VK_EXT_transform_feedback (transformFeedback, and geometryStreams when the device
1153 // offers it) whenever the extension is present (D3D-302), and a driver makes it part of a pipeline's cache key, so
1154 // the checker enables it too (docs/pipeline_check.md, "The cache and the runtime's device").
1155 link(&tf, reinterpret_cast<VkBaseOutStructure*>(&tf), VK_EXT_TRANSFORM_FEEDBACK_EXTENSION_NAME, true);
1147 const bool ext_bary = link(&bary, reinterpret_cast<VkBaseOutStructure*>(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary); 1156 const bool ext_bary = link(&bary, reinterpret_cast<VkBaseOutStructure*>(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary);
1148 const bool ext_lock = link(&lock, reinterpret_cast<VkBaseOutStructure*>(&lock), VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, want_lock); 1157 const bool ext_lock = link(&lock, reinterpret_cast<VkBaseOutStructure*>(&lock), VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, want_lock);
1149#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME 1158#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME
@@ -1158,6 +1167,13 @@ int main(int argc, char** argv) {
1158#endif 1167#endif
1159 VkPhysicalDeviceShaderClockFeaturesKHR clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR}; 1168 VkPhysicalDeviceShaderClockFeaturesKHR clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR};
1160 const bool ext_clock = link(&clock, reinterpret_cast<VkBaseOutStructure*>(&clock), VK_KHR_SHADER_CLOCK_EXTENSION_NAME, want_clock); 1169 const bool ext_clock = link(&clock, reinterpret_cast<VkBaseOutStructure*>(&clock), VK_KHR_SHADER_CLOCK_EXTENSION_NAME, want_clock);
1170 VkPhysicalDeviceDiagnosticsConfigFeaturesNV diag_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DIAGNOSTICS_CONFIG_FEATURES_NV};
1171 const bool ext_diag = link(&diag_features, reinterpret_cast<VkBaseOutStructure*>(&diag_features),
1172 VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME, nv_diagnostics);
1173 if (nv_diagnostics && !ext_diag) {
1174 std::fprintf(stderr, "--nv-diagnostics: the device has no %s\n", VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME);
1175 return 1;
1176 }
1161 const bool ext_exe = link(&exe, reinterpret_cast<VkBaseOutStructure*>(&exe), 1177 const bool ext_exe = link(&exe, reinterpret_cast<VkBaseOutStructure*>(&exe),
1162 VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, !stats_path.empty()); 1178 VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, !stats_path.empty());
1163 if (!stats_path.empty() && !ext_exe) { 1179 if (!stats_path.empty() && !ext_exe) {
@@ -1201,6 +1217,15 @@ int main(int argc, char** argv) {
1201 VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; 1217 VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
1202 dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; dci.pNext = &f2; 1218 dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; dci.pNext = &f2;
1203 dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data(); 1219 dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data();
1220 VkDeviceDiagnosticsConfigCreateInfoNV diag_config{VK_STRUCTURE_TYPE_DEVICE_DIAGNOSTICS_CONFIG_CREATE_INFO_NV};
1221 if (ext_diag) {
1222 diag_config.flags = VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_DEBUG_INFO_BIT_NV |
1223 VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_RESOURCE_TRACKING_BIT_NV |
1224 VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_AUTOMATIC_CHECKPOINTS_BIT_NV;
1225 diag_config.pNext = dci.pNext;
1226 dci.pNext = &diag_config;
1227 std::printf("device: VK_NV_device_diagnostics_config on (shader debug info, resource tracking, checkpoints)\n");
1228 }
1204 VkDevice dev; 1229 VkDevice dev;
1205 if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; } 1230 if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; }
1206 leonida::SubgroupSizeCaps runtime_subgroups; 1231 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 000000000..fc833e4ad
--- /dev/null
+++ b/runtime/test/vk_presenter_sparse_capture.h
@@ -0,0 +1,192 @@
1// The positive-only cadence oracle in vk_presenter_sync_test.cpp. Included after its driver counters.
2#pragma once
3
4namespace sparse_test {
5namespace fs = std::filesystem;
6using RGB = std::array<int, 3>;
7constexpr RGB red{255, 0, 0}, blue{0, 0, 255}, black{0, 0, 0};
8
9// Own a newly created owner/SYSTEM-only directory. Never reuse or recursively remove an existing tree.
10struct Folder {
11 fs::path path;
12 bool create(const char* tag) {
13 auto candidate = fs::temp_directory_path() / (std::string("leonida-sparse-") + tag + "-" +
14 std::to_string(GetCurrentProcessId()) + "-" + std::to_string(GetTickCount64()));
15 PSECURITY_DESCRIPTOR sd = nullptr;
16 if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;OICI;FA;;;OW)(A;OICI;FA;;;SY)",
17 SDDL_REVISION_1, &sd, nullptr)) return false;
18 SECURITY_ATTRIBUTES sa{sizeof(sa), sd, FALSE};
19 const bool fresh = CreateDirectoryW(candidate.c_str(), &sa) != FALSE;
20 LocalFree(sd);
21 if (fresh) path = std::move(candidate);
22 return fresh;
23 }
24 ~Folder() {
25 if (path.empty()) return;
26 std::error_code ec;
27 for (auto name : {"index.txt", "frame_00001.ppm", "frame_00004.ppm"}) fs::remove(path / name, ec);
28 fs::remove(path, ec); // leave unknown contents alone on failure
29 }
30};
31const char* sdr_format(VkFormat f) {
32 switch (f) {
33 case VK_FORMAT_B8G8R8A8_UNORM: return "VK_FORMAT_B8G8R8A8_UNORM";
34 case VK_FORMAT_B8G8R8A8_SRGB: return "VK_FORMAT_B8G8R8A8_SRGB";
35 case VK_FORMAT_R8G8B8A8_UNORM: return "VK_FORMAT_R8G8B8A8_UNORM";
36 case VK_FORMAT_R8G8B8A8_SRGB: return "VK_FORMAT_R8G8B8A8_SRGB";
37 default: return nullptr;
38 }
39}
40bool disk_matches(const fs::path& dir, VkExtent2D extent, VkFormat fmt, RGB fourth) {
41 std::set<fs::path> names;
42 for (const auto& e : fs::directory_iterator(dir)) {
43 if (!fs::is_regular_file(e.symlink_status())) return false;
44 names.insert(e.path().filename());
45 }
46 if (names != std::set<fs::path>{"index.txt", "frame_00001.ppm", "frame_00004.ppm"} || !sdr_format(fmt)) return false;
47 const auto w=extent.width, h=extent.height;
48 if (!w || !h || w>1024 || h>1024) return false;
49 const std::string header="P6\n"+std::to_string(w)+" "+std::to_string(h)+"\n255\n";
50 std::ifstream index(dir/"index.txt");
51 for (const int n : {1,4}) {
52 const RGB color = n==1 ? red : fourth;
53 const fs::path file=dir/(n==1 ? "frame_00001.ppm":"frame_00004.ppm");
54 if (fs::file_size(file)!=header.size()+3ull*w*h) return false;
55 std::string expected=header;
56 expected.reserve(header.size()+3ull*w*h);
57 for (size_t i=0; i<size_t(w)*h; ++i) for (int c:color) expected.push_back(static_cast<char>(c));
58 std::ifstream img(file,std::ios::binary);
59 std::string got(expected.size(),'\0');
60 if (!img.read(got.data(),static_cast<std::streamsize>(got.size())) || got!=expected) return false;
61 const auto row="frame "+std::to_string(n)+" format "+std::to_string(int(fmt))+" ("+sdr_format(fmt)+") extent "+
62 std::to_string(w)+"x"+std::to_string(h)+" mean rgb "+std::to_string(color[0])+".00 "+
63 std::to_string(color[1])+".00 "+std::to_string(color[2])+".00";
64 if (!std::getline(index,got) || got!=row) return false;
65 }
66 return index.peek()==std::char_traits<char>::eof();
67}
68
69int run(vktest::Device& d, HWND window) {
70 using namespace leonida;
71 VulkanContext context(driver::get_device,d.device,true);
72 VulkanQueue queue(context,d.queue,d.family);
73 EXPECT(context.loaded() && queue.ok());
74 const auto surface_fn=reinterpret_cast<PFN_vkCreateWin32SurfaceKHR>(d.instance_proc(d.instance,"vkCreateWin32SurfaceKHR"));
75 EXPECT(surface_fn);
76 // Two immutable RGBA8 test sources, filled on this queue once. present_blank supplies the third color.
77 for (ResourceId id : {1u,2u}) {
78 ResourceBinding rb{};
79 rb.width=64;rb.height=64;rb.format=VK_FORMAT_R8G8B8A8_UNORM;rb.depth=rb.mip_levels=rb.array_layers=1;
80 rb.samples=1;rb.color_attachment=true;rb.sampled=true;rb.aspects=VK_IMAGE_ASPECT_COLOR_BIT;
81 rb.image=d.image(rb.format,rb.width,rb.height,1,VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
82 VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
83 EXPECT(rb.image);
84 context.add_resource(id,rb,VK_IMAGE_LAYOUT_UNDEFINED);
85 CommandList list;
86 EXPECT(list.transition({id,0,d3d12_state::common,d3d12_state::render_target}));
87 EXPECT(list.clear_render_target({id,0,0,1},{id==1?1.f:0.f,0,id==2?1.f:0.f,1}));
88 EXPECT(list.transition({id,0,d3d12_state::render_target,d3d12_state::common}) && list.close());
89 const CommandList* input=&list;
90 EXPECT(queue.execute({&input,1})==ReplayResult::success);
91 }
92 EXPECT(queue.idle());
93 EXPECT(!_putenv_s("LEONIDA_CAPTURE_EVERY","3") && !_putenv_s("LEONIDA_CAPTURE_LIMIT","2") &&
94 !_putenv_s("LEONIDA_CAPTURE_SOURCE","0"));
95 enum class Phase { sparse, final_pending, continuous, splash, composed };
96 for (Phase p : {Phase::sparse,Phase::final_pending,Phase::continuous,Phase::splash,Phase::composed}) {
97 Folder folder;
98 EXPECT(folder.create(p==Phase::sparse?"sparse":p==Phase::final_pending?"pending":p==Phase::continuous?"explicit":
99 p==Phase::splash?"splash":"composed"));
100 EXPECT(!_putenv_s("LEONIDA_CAPTURE",folder.path.string().c_str()));
101 VkExtent2D extent{};VkFormat fmt{};
102 {
103 VkWin32SurfaceCreateInfoKHR info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR};
104 info.hinstance=GetModuleHandleW(nullptr);info.hwnd=window;
105 VkSurfaceKHR surface{};EXPECT(surface_fn(d.instance,&info,nullptr,&surface)==VK_SUCCESS);
106 VulkanPresenter present(context,driver::get_instance,d.instance,d.physical,d.queue,d.family,surface);
107 EXPECT(present.ok());
108 if (p==Phase::continuous) EXPECT(present.enable_capture());
109 const unsigned last = p==Phase::final_pending?4:p==Phase::splash?7:8;
110 for (unsigned n=1; n<=last; ++n) {
111 const bool disk=n==1 || n==4;
112 const bool replaced=p==Phase::splash && n>=2 && n<=4;
113 const bool handoff=p==Phase::splash && n==5;
114 const RGB expected=n==1 || replaced ? red : n==4 || handoff ? blue : n%2 ? red : black;
115 driver::capture_copies=0; driver::capture_waw_barriers=0; driver::saw_capture_waw=false;
116 driver::observe_capture=true;
117 if (p==Phase::splash && n==1) {
118 EXPECT(present.present_splash(1,std::make_shared<int>(0)));
119 } else if (replaced || expected==black) EXPECT(present.present_blank(true)==VK_SUCCESS);
120 else if (p==Phase::composed) {
121 const auto before=present.composed_presents();
122 PresentPlanes planes{};
123 planes.plane[0].source=expected==red?1:2;
124 EXPECT(present.present_planes(planes,true)==VK_SUCCESS && present.composed_presents()==before+1);
125 } else EXPECT(present.present(expected==red?1:2,true)==VK_SUCCESS);
126 driver::observe_capture=false;
127 EXPECT(present.presented()==n);
128 const unsigned copies=replaced?2u : disk || p==Phase::continuous || handoff ? 1u : 0u;
129 EXPECT(driver::capture_copies==copies && driver::capture_waw_barriers==copies &&
130 !driver::saw_capture_waw); // also reject a WAW on a frame with no copy
131 std::vector<std::uint8_t> pixels{77};VkExtent2D e{17,18};VkFormat f=VK_FORMAT_UNDEFINED;
132 EXPECT(present.read_back(pixels,&e,&f)==(copies!=0));
133 if (copies) {
134 if (n==1) {extent=e;fmt=f;}
135 EXPECT(e.width==extent.width && e.height==extent.height && f==fmt && sdr_format(f));
136 const bool bgra=f==VK_FORMAT_B8G8R8A8_UNORM || f==VK_FORMAT_B8G8R8A8_SRGB;
137 EXPECT(presenter_capture_matches_rgb(pixels,e.width,e.height,bgra,expected,0));
138 } else EXPECT(pixels.size()==1 && pixels[0]==77 && e.width==17 && e.height==18 && f==VK_FORMAT_UNDEFINED);
139 }
140 if (p==Phase::final_pending) {
141 EXPECT(fs::exists(folder.path/"frame_00001.ppm") && !fs::exists(folder.path/"frame_00004.ppm"));
142 }
143 } // pending final frame 4 is written here, without another present
144 EXPECT(disk_matches(folder.path,extent,fmt,p==Phase::splash?red:blue));
145 }
146 // Splash-only storage is not an ongoing readback request. No disk path, no enable_capture().
147 EXPECT(_putenv_s("LEONIDA_CAPTURE", "") == 0);
148 {
149 VkWin32SurfaceCreateInfoKHR info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR};
150 info.hinstance = GetModuleHandleW(nullptr);
151 info.hwnd = window;
152 VkSurfaceKHR surface{};
153 EXPECT(surface_fn(d.instance, &info, nullptr, &surface) == VK_SUCCESS);
154 VulkanPresenter present(context, driver::get_instance, d.instance, d.physical, d.queue, d.family, surface);
155 EXPECT(present.ok());
156 auto owner = std::make_shared<int>(0);
157 std::weak_ptr<int> held = owner;
158 for (unsigned n = 1; n <= 5; ++n) {
159 driver::capture_copies = 0;
160 driver::capture_waw_barriers = 0;
161 driver::saw_capture_waw = false;
162 driver::observe_capture = true;
163 if (n == 1) EXPECT(present.present_splash(1, std::move(owner))); // show the red shell
164 else if (n == 3 || n == 5) EXPECT(present.present(2, true) == VK_SUCCESS); // blue title
165 else EXPECT(present.present_blank(true) == VK_SUCCESS);
166 driver::observe_capture = false;
167
168 // Initial shell: zero copies. Held black: inspect, then overwrite with the red shell. First blue:
169 // inspect once and release. Subsequent black and blue are ordinary frames, with no copies.
170 const unsigned expected_copies = n == 2 ? 2 : n == 3 ? 1 : 0;
171 EXPECT(present.presented() == n && driver::capture_copies == expected_copies &&
172 driver::capture_waw_barriers == expected_copies && !driver::saw_capture_waw);
173 EXPECT(held.expired() == (n >= 3));
174 std::vector<std::uint8_t> pixels{77};
175 VkExtent2D extent{17, 18};
176 VkFormat format = VK_FORMAT_UNDEFINED;
177 if (n == 2) {
178 EXPECT(present.read_back(pixels, &extent, &format) && sdr_format(format));
179 const bool bgra = format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB;
180 EXPECT(presenter_capture_matches_rgb(pixels, extent.width, extent.height, bgra, red, 0));
181 } else {
182 EXPECT(!present.read_back(pixels, &extent, &format));
183 EXPECT(pixels.size() == 1 && pixels[0] == 77 && extent.width == 17 && extent.height == 18 &&
184 format == VK_FORMAT_UNDEFINED);
185 }
186 }
187 }
188 EXPECT(queue.idle());context.remove_resource(1);context.remove_resource(2);
189 std::puts("sparse capture: frames 1/4, cap, last-fence drain, explicit readback, disk and splash-only handoffs verified");
190 return 0;
191}
192} // namespace sparse_test
diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp
index a54bf6662..ee75ad86f 100644
--- a/runtime/test/vk_presenter_sync_test.cpp
+++ b/runtime/test/vk_presenter_sync_test.cpp
@@ -16,6 +16,7 @@
16#endif 16#endif
17#define VK_USE_PLATFORM_WIN32_KHR 17#define VK_USE_PLATFORM_WIN32_KHR
18#include <windows.h> 18#include <windows.h>
19#include <sddl.h>
19 20
20#include "vk_presenter_capture_colour.h" 21#include "vk_presenter_capture_colour.h"
21#include "vk_test_device.h" 22#include "vk_test_device.h"
@@ -28,7 +29,10 @@
28#include <cstdint> 29#include <cstdint>
29#include <cstdio> 30#include <cstdio>
30#include <cstdlib> 31#include <cstdlib>
32#include <filesystem>
33#include <fstream>
31#include <functional> 34#include <functional>
35#include <set>
32#include <mutex> 36#include <mutex>
33#include <string_view> 37#include <string_view>
34#include <thread> 38#include <thread>
@@ -182,10 +186,14 @@ void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDev
182} 186}
183} // namespace driver 187} // namespace driver
184 188
189#include "vk_presenter_sparse_capture.h"
190
185} // namespace 191} // namespace
186 192
187int main() { 193int main(int argc, char** argv) {
188 using namespace leonida; 194 using namespace leonida;
195 const bool sparse = argc==2 && std::string_view(argv[1])=="--sparse-capture";
196 if (argc!=1 && !sparse) return 2;
189 197
190 vktest::Device d; 198 vktest::Device d;
191 if (!d.create(true)) { 199 if (!d.create(true)) {
@@ -202,7 +210,7 @@ int main() {
202 constexpr std::uint32_t width = 128, height = 96; 210 constexpr std::uint32_t width = 128, height = 96;
203 RECT fr{0, 0, LONG(width), LONG(height)}; 211 RECT fr{0, 0, LONG(width), LONG(height)};
204 AdjustWindowRect(&fr, WS_OVERLAPPEDWINDOW, FALSE); 212 AdjustWindowRect(&fr, WS_OVERLAPPEDWINDOW, FALSE);
205 HWND window = CreateWindowExW(0, wc.lpszClassName, L"Leonida presenter sync test", WS_OVERLAPPEDWINDOW, 80, 80, 213 HWND window = CreateWindowExW(sparse ? WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW : 0, wc.lpszClassName, L"Leonida presenter sync test", WS_OVERLAPPEDWINDOW, 80, 80,
206 fr.right - fr.left, fr.bottom - fr.top, nullptr, nullptr, wc.hInstance, nullptr); 214 fr.right - fr.left, fr.bottom - fr.top, nullptr, nullptr, wc.hInstance, nullptr);
207 EXPECT(window); 215 EXPECT(window);
208 ShowWindow(window, SW_SHOWNOACTIVATE); 216 ShowWindow(window, SW_SHOWNOACTIVATE);
@@ -210,6 +218,12 @@ int main() {
210 pump(); 218 pump();
211 219
212 driver::install(d.instance_proc, d.instance, d.device); 220 driver::install(d.instance_proc, d.instance, d.device);
221 if (sparse) { // positive-only: never enter the failure/concurrency regressions below
222 const int result = sparse_test::run(d, window);
223 DestroyWindow(window);
224 UnregisterClassW(wc.lpszClassName, wc.hInstance);
225 return result || d.validation_errors() ? 1 : 0;
226 }
213 { 227 {
214 VulkanContext context(driver::get_device, d.device, true); 228 VulkanContext context(driver::get_device, d.device, true);
215 EXPECT(context.loaded()); 229 EXPECT(context.loaded());
diff --git a/runtime/test/vk_sampler_test.cpp b/runtime/test/vk_sampler_test.cpp
index 98206931b..a35806d8f 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) {
265 VkBufferDeviceAddressInfo address_info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; 265 VkBufferDeviceAddressInfo address_info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
266 address_info.buffer = heap; 266 address_info.buffer = heap;
267 const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &address_info); 267 const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &address_info);
268 // Descriptor hash table: the T# names image 1, the S# sampler 1. Index 0 of each is a magenta fallback. 268 // Descriptor hash table: the T# names image 1, the S# sampler 1. Index 0 of each is a magenta fallback. The
269 // module is tagged (build.py), so the T# entry names the array its index is bound in: a sampled 2D image.
269 leonida::DescriptorTable table(16); 270 leonida::DescriptorTable table(16);
270 table.insert(tsharp.data(), 1); 271 table.insert(tsharp.data(), 1, leonida::kind_sampled_bit(0));
271 table.insert(leonida::make_ssharp_key(ssharp.data()).data(), 1); 272 table.insert(leonida::make_ssharp_key(ssharp.data()).data(), 1);
272 const auto table_words = table.build_gpu_buffer(true); 273 const auto table_words = table.build_gpu_buffer(true);
273 VkBuffer table_buffer; 274 VkBuffer table_buffer;
diff --git a/runtime/test/vk_sandbox.cpp b/runtime/test/vk_sandbox.cpp
index 7ae9e8db6..11718190d 100644
--- a/runtime/test/vk_sandbox.cpp
+++ b/runtime/test/vk_sandbox.cpp
@@ -395,7 +395,8 @@ int main(int argc, char** argv) {
395 }; 395 };
396 const uint32_t nimg = uint32_t(scene.textures.size()) + 1; // image 0: 1x1 white for untextured draws 396 const uint32_t nimg = uint32_t(scene.textures.size()) + 1; // image 0: 1x1 white for untextured draws
397 leonida::DescriptorTable table(2 * (nimg + 2)); 397 leonida::DescriptorTable table(2 * (nimg + 2));
398 for (uint32_t i = 0; i < nimg; ++i) table.insert(tsharp(i).data(), i); 398 // The module is tagged (build.py), so each T# entry names the array its index is bound in: a sampled 2D image.
399 for (uint32_t i = 0; i < nimg; ++i) table.insert(tsharp(i).data(), i, leonida::kind_sampled_bit(0));
399 uint32_t ssharp[8] = {1024, 12582912, 418381824, 0, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; // the PS's literal S# 400 uint32_t ssharp[8] = {1024, 12582912, 418381824, 0, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; // the PS's literal S#
400 table.insert(ssharp, 0); 401 table.insert(ssharp, 0);
401 for (uint32_t d = 0; d < ndraw; ++d) { 402 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 000000000..6ee7ffd9b
--- /dev/null
+++ b/runtime/test/vk_semaphore_lifetime_test.cpp
@@ -0,0 +1,261 @@
1// Semaphore lifetimes across fence and queue teardown (src/vulkan_backend.h, src/vulkan_device_fault.h). No shaders,
2// no game data.
3// 1. A fence released right after an unheld Signal: the queue keeps the fence, and so its timeline semaphore,
4// until the GPU has run the signal (destroying a semaphore a pending submission signals is undefined,
5// VUID-vkDestroySemaphore-semaphore-05149). The Signal is kept pending on the GPU by a wait on a semaphore the
6// host signals later.
7// 2. The queue whose submission uploaded the bindless table is destroyed, then another queue submits: that
8// submission must not wait on the destroyed queue's progress semaphore.
9// 3. With the device-fault diagnostics on, the submit ring forgets both semaphores before they are destroyed: its
10// progress watch (once a second) and a dump after the teardown never read the counter of a destroyed one.
11// The driver calls are intercepted, so 2 and 3 are checked with or without the validation layer; set
12// LEONIDA_VK_VALIDATION=1 to also run under VK_LAYER_KHRONOS_validation (any validation error fails the test).
13#include "vk_test_device.h"
14#include "../src/vulkan_backend.h"
15
16#include <algorithm>
17#include <atomic>
18#include <chrono>
19#include <cstdint>
20#include <cstring>
21#include <memory>
22#include <mutex>
23#include <set>
24#include <thread>
25#include <utility>
26#include <vector>
27
28#define EXPECT(condition) do { \
29 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
30} while (0)
31
32namespace {
33
34using namespace leonida;
35
36namespace driver {
37PFN_vkGetDeviceProcAddr real_get = nullptr;
38PFN_vkQueueSubmit real_submit = nullptr;
39PFN_vkCreateSemaphore real_create = nullptr;
40PFN_vkDestroySemaphore real_destroy = nullptr;
41PFN_vkGetSemaphoreCounterValue real_counter = nullptr;
42
43std::mutex mutex;
44std::set<VkSemaphore> destroyed; // destroyed and not made again
45std::vector<VkSemaphore> last_signals; // of the last vkQueueSubmit
46std::vector<VkSemaphore> waits_seen; // every wait semaphore submitted since the last reset
47std::atomic<unsigned> dead_waits{0}; // submissions that waited on a destroyed semaphore
48std::atomic<unsigned> dead_reads{0}; // counter reads of a destroyed semaphore
49std::atomic<unsigned> live_reads{0};
50
51VKAPI_ATTR VkResult VKAPI_CALL submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, VkFence fence) {
52 {
53 std::lock_guard lock(mutex);
54 last_signals.clear();
55 for (std::uint32_t i = 0; i < count; ++i) {
56 for (std::uint32_t w = 0; w < submits[i].waitSemaphoreCount; ++w) {
57 const VkSemaphore s = submits[i].pWaitSemaphores[w];
58 waits_seen.push_back(s);
59 if (destroyed.count(s)) dead_waits.fetch_add(1);
60 }
61 for (std::uint32_t s = 0; s < submits[i].signalSemaphoreCount; ++s)
62 last_signals.push_back(submits[i].pSignalSemaphores[s]);
63 }
64 }
65 return real_submit(queue, count, submits, fence);
66}
67
68VKAPI_ATTR VkResult VKAPI_CALL create(VkDevice device, const VkSemaphoreCreateInfo* info,
69 const VkAllocationCallbacks* alloc, VkSemaphore* out) {
70 const VkResult result = real_create(device, info, alloc, out);
71 if (result == VK_SUCCESS) {
72 std::lock_guard lock(mutex);
73 destroyed.erase(*out); // a handle value the driver hands out again is alive again
74 }
75 return result;
76}
77
78VKAPI_ATTR void VKAPI_CALL destroy(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks* alloc) {
79 if (semaphore) {
80 std::lock_guard lock(mutex);
81 destroyed.insert(semaphore);
82 }
83 real_destroy(device, semaphore, alloc);
84}
85
86VKAPI_ATTR VkResult VKAPI_CALL counter(VkDevice device, VkSemaphore semaphore, std::uint64_t* value) {
87 {
88 std::lock_guard lock(mutex);
89 if (destroyed.count(semaphore)) {
90 dead_reads.fetch_add(1);
91 *value = 0;
92 return VK_ERROR_UNKNOWN; // never reaches the driver with a dead handle
93 }
94 }
95 live_reads.fetch_add(1);
96 return real_counter(device, semaphore, value);
97}
98
99VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get(VkDevice device, const char* name) {
100 if (!std::strcmp(name, "vkQueueSubmit")) return reinterpret_cast<PFN_vkVoidFunction>(submit);
101 if (!std::strcmp(name, "vkCreateSemaphore")) return reinterpret_cast<PFN_vkVoidFunction>(create);
102 if (!std::strcmp(name, "vkDestroySemaphore")) return reinterpret_cast<PFN_vkVoidFunction>(destroy);
103 if (!std::strcmp(name, "vkGetSemaphoreCounterValue") || !std::strcmp(name, "vkGetSemaphoreCounterValueKHR"))
104 return reinterpret_cast<PFN_vkVoidFunction>(counter);
105 return real_get(device, name);
106}
107} // namespace driver
108
109// A timeline semaphore the test signals from the host, unknown to the queues' holds (so a wait on it is not held on
110// the CPU: it is submitted, and the GPU waits). Like the runtime's own owners (~VulkanFence, ~VulkanQueue) it tells
111// the submit ring before it goes.
112struct HostGate {
113 const vktest::Device& d;
114 DeviceFaultDiagnostics* ring;
115 VkSemaphore semaphore = VK_NULL_HANDLE;
116 HostGate(const vktest::Device& device, DeviceFaultDiagnostics* diagnostics) : d(device), ring(diagnostics) {
117 VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO};
118 type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE;
119 VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type};
120 driver::create(d.device, &info, nullptr, &semaphore);
121 }
122 ~HostGate() {
123 if (!semaphore) return;
124 if (ring) ring->forget(semaphore);
125 driver::destroy(d.device, semaphore, nullptr);
126 }
127 bool open(std::uint64_t value) const {
128 VkSemaphoreSignalInfo signal{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO};
129 signal.semaphore = semaphore;
130 signal.value = value;
131 return d.fn<PFN_vkSignalSemaphore>("vkSignalSemaphore")(d.device, &signal) == VK_SUCCESS;
132 }
133};
134
135int run(vktest::Device& d) {
136 driver::real_get = d.device_proc;
137 driver::real_submit = d.fn<PFN_vkQueueSubmit>("vkQueueSubmit");
138 driver::real_create = d.fn<PFN_vkCreateSemaphore>("vkCreateSemaphore");
139 driver::real_destroy = d.fn<PFN_vkDestroySemaphore>("vkDestroySemaphore");
140 driver::real_counter = d.fn<PFN_vkGetSemaphoreCounterValue>("vkGetSemaphoreCounterValue");
141 EXPECT(driver::real_submit && driver::real_create && driver::real_destroy && driver::real_counter);
142
143 VulkanContext context(driver::get, d.device, true);
144 EXPECT(context.loaded());
145 context.configure_device_fault(driver::get, DeviceFaultExtensions{}); // the submit ring and its progress watch
146 EXPECT(context.device_fault());
147 bool arm_upload = false;
148 context.set_bindless_prepare([&](VkCommandBuffer) {
149 if (std::exchange(arm_upload, false)) context.note_bindless_upload(); // as a replacing bindless flush does
150 return true;
151 });
152
153 void* map = nullptr;
154 constexpr VkDeviceSize kSize = 4096;
155 const VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
156 VkBuffer a = d.buffer(kSize, usage, &map), b = d.buffer(kSize, usage, &map);
157 EXPECT(a && b);
158 ResourceBinding binding;
159 binding.size = kSize;
160 binding.buffer = a;
161 context.add_resource(1, binding);
162 binding.buffer = b;
163 context.add_resource(2, binding);
164 CommandList copy;
165 EXPECT(copy.copy_buffer({2, 0, 1, 0, kSize}));
166 EXPECT(copy.close());
167 const CommandList* lists[] = {&copy};
168
169 auto stay = std::make_unique<VulkanQueue>(context, d.queue, d.family);
170 EXPECT(stay->ok());
171
172 // 1. Release a fence right after an unheld Signal that the GPU cannot run yet.
173 {
174 HostGate gate(d, context.device_fault());
175 EXPECT(gate.semaphore);
176 auto fence = std::make_shared<VulkanFence>(context, 0);
177 const VkSemaphore fence_semaphore = fence->semaphore();
178 EXPECT(fence_semaphore);
179 std::weak_ptr<VulkanFence> watch = fence;
180 stay->wait(gate.semaphore, 1); // the next submission waits for the host on the GPU
181 EXPECT(stay->signal(fence_semaphore, 1, [&fence] { return std::shared_ptr<void>(fence); }));
182 fence.reset(); // the title's last Release
183 {
184 std::lock_guard lock(driver::mutex);
185 EXPECT(!driver::destroyed.count(fence_semaphore));
186 }
187 EXPECT(!watch.expired()); // the queue keeps it while the Signal is pending
188 EXPECT(gate.open(1));
189 // Each execute drains the pins whose submissions are done.
190 bool released = false;
191 for (int i = 0; i < 200 && !released; ++i) {
192 context.wait_retire_ticket(context.submitted_retire_ticket());
193 EXPECT(stay->execute(lists) == ReplayResult::success);
194 released = watch.expired();
195 if (!released) std::this_thread::sleep_for(std::chrono::milliseconds(5));
196 }
197 EXPECT(released); // and lets it go once the GPU has run it
198 std::lock_guard lock(driver::mutex);
199 EXPECT(driver::destroyed.count(fence_semaphore));
200 std::printf("fence released after an unheld Signal: kept until the signal ran, then destroyed\n");
201 }
202
203 // 2. The queue that uploaded the bindless table goes; another queue submits next.
204 VkSemaphore uploader_progress = VK_NULL_HANDLE;
205 {
206 auto uploader = std::make_unique<VulkanQueue>(context, d.queue, d.family);
207 EXPECT(uploader->ok());
208 arm_upload = true;
209 EXPECT(uploader->execute(lists) == ReplayResult::success);
210 EXPECT(!arm_upload);
211 {
212 std::lock_guard lock(driver::mutex);
213 EXPECT(!driver::last_signals.empty());
214 uploader_progress = driver::last_signals[0]; // a queue's submission signals its progress timeline first
215 }
216 uploader.reset();
217 }
218 {
219 std::lock_guard lock(driver::mutex);
220 EXPECT(driver::destroyed.count(uploader_progress));
221 driver::waits_seen.clear();
222 }
223 EXPECT(stay->execute(lists) == ReplayResult::success);
224 {
225 std::lock_guard lock(driver::mutex);
226 EXPECT(std::find(driver::waits_seen.begin(), driver::waits_seen.end(), uploader_progress) ==
227 driver::waits_seen.end());
228 }
229 EXPECT(driver::dead_waits.load() == 0);
230 std::printf("bindless upload queue destroyed: the next submission on another queue does not wait on it\n");
231
232 // 3. The ring: the progress watch reads counters once a second; a dump now reads every semaphore it still names.
233 std::this_thread::sleep_for(std::chrono::milliseconds(2200));
234 const unsigned reads_before = driver::live_reads.load();
235 context.device_fault()->dump_submits();
236 EXPECT(driver::live_reads.load() > reads_before); // it did read the live ones
237 EXPECT(driver::dead_reads.load() == 0);
238 std::printf("submit ring: no counter read of a destroyed semaphore (%u live reads)\n", driver::live_reads.load());
239
240 stay.reset();
241 context.remove_resource(1);
242 context.remove_resource(2);
243 return 0;
244}
245
246} // namespace
247
248int main() {
249 std::setvbuf(stdout, nullptr, _IONBF, 0);
250 vktest::Device d;
251 const auto status = d.initialize();
252 if (status == vktest::DeviceStatus::unavailable) {
253 std::printf("SKIP: no usable Vulkan device\n");
254 return 77;
255 }
256 if (status != vktest::DeviceStatus::ready) return 1;
257 const int rc = run(d);
258 const unsigned errors = d.validation_errors();
259 std::printf("Vulkan validation errors: %u%s\n", errors, d.validation ? "" : " (validation off)");
260 return rc ? rc : errors ? 1 : 0;
261}
diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp
index 0b4c3c6f9..62e1271f2 100644
--- a/runtime/test/vk_store_test.cpp
+++ b/runtime/test/vk_store_test.cpp
@@ -29,6 +29,7 @@
29#include "vk_shader_fma.h" 29#include "vk_shader_fma.h"
30#include "vk_pc_tail.h" 30#include "vk_pc_tail.h"
31#include "spirv_capability.h" 31#include "spirv_capability.h"
32#include "../src/descriptor_table.h"
32#include "../src/gfx10_descriptors.h" 33#include "../src/gfx10_descriptors.h"
33 34
34#include <cmath> 35#include <cmath>
@@ -54,7 +55,10 @@ static uint32_t key_hash(const uint32_t k[8]) { // same FNV-1a as the transl
54 return h; 55 return h;
55} 56}
56 57
57static void table_insert(std::vector<uint32_t>& t, const uint32_t key[8], uint32_t index) { 58// `kind` is what the translated modules read next to the index (descriptor_table.h): the arrays this image is
59// bound in, sampled and storage.
60static void table_insert(std::vector<uint32_t>& t, const uint32_t key[8], uint32_t index,
61 uint32_t kind) {
58 uint32_t mask = t[0], h = key_hash(key); 62 uint32_t mask = t[0], h = key_hash(key);
59 for (uint32_t k = 0; k < 8; k++) { 63 for (uint32_t k = 0; k < 8; k++) {
60 uint32_t base = ((h + k) & mask) * 10; 64 uint32_t base = ((h + k) & mask) * 10;
@@ -63,6 +67,7 @@ static void table_insert(std::vector<uint32_t>& t, const uint32_t key[8], uint32
63 if (used) continue; 67 if (used) continue;
64 for (int j = 0; j < 8; j++) t[base + 1 + j] = key[j]; 68 for (int j = 0; j < 8; j++) t[base + 1 + j] = key[j];
65 t[base + 9] = index; 69 t[base + 9] = index;
70 t[base + 10] = kind;
66 return; 71 return;
67 } 72 }
68} 73}
@@ -236,10 +241,10 @@ int main(int argc, char** argv) {
236 for (uint32_t k = 0; k < 3; k++) { 241 for (uint32_t k = 0; k < 3; k++) {
237 uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20}; 242 uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20};
238 for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1); 243 for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1);
239 table_insert(table, t, k + 1); // its index in the 2D arrays; 0 is the fallback, as in the runtime 244 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
240 if (cube_mode) { // the cube T# (cs_imgstore_cube.asm): word3 also has TYPE = 0xB, index k + 1 of the 2D arrays 245 if (cube_mode) { // the cube T# (cs_imgstore_cube.asm): word3 also has TYPE = 0xB, index k + 1 of the 2D arrays
241 t[3] |= 0xB0000000u; 246 t[3] |= 0xB0000000u;
242 table_insert(table, t, k + 1); 247 table_insert(table, t, k + 1, leonida::kind_sampled_bit(0) | leonida::kind_storage_bit(0));
243 } 248 }
244 } 249 }
245 // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key 250 // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key
@@ -249,13 +254,13 @@ int main(int argc, char** argv) {
249 wide_desc.address = 0x400000; wide_desc.format = fmts[0]; wide_desc.width = WIDE_W; wide_desc.height = WIDE_H; 254 wide_desc.address = 0x400000; wide_desc.format = fmts[0]; wide_desc.width = WIDE_W; wide_desc.height = WIDE_H;
250 wide_desc.mip_count = wide_desc.resource_mips = WIDE_MIPS; 255 wide_desc.mip_count = wide_desc.resource_mips = WIDE_MIPS;
251 const leonida::gfx10::ImageWords wide_key = leonida::gfx10::encode(wide_desc); 256 const leonida::gfx10::ImageWords wide_key = leonida::gfx10::encode(wide_desc);
252 table_insert(table, wide_key.data(), 4); 257 table_insert(table, wide_key.data(), 4, leonida::kind_sampled_bit(0)); // image_get_resinfo reads binding 0
253 // The volume of the 3D atomics: index 1 of the 3D arrays, behind a T# of the 2D images' pattern (k = 4). 258 // The volume of the 3D atomics: index 1 of the 3D arrays, behind a T# of the 2D images' pattern (k = 4).
254 const uint32_t VOL = 4; 259 const uint32_t VOL = 4;
255 { 260 {
256 // The volume uses the D3D12 layer's whole-mip UAV tag (FirstWSlice=0, WSize=4). 261 // The volume uses the D3D12 layer's whole-mip UAV tag (FirstWSlice=0, WSize=4).
257 uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x80000055, 0x55, 0x55, 0xd7801800}; 262 uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x80000055, 0x55, 0x55, 0xd7801800};
258 table_insert(table, t, 1); 263 table_insert(table, t, 1, leonida::kind_sampled_bit(2) | leonida::kind_storage_bit(2));
259 } 264 }
260 VkBuffer tb; void* tbp; 265 VkBuffer tb; void* tbp;
261 CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp)); 266 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 fd63fca66..eb1be0a2c 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -130,6 +130,7 @@ public:
130 std::uint32_t max_draw_indirect_count = 0; 130 std::uint32_t max_draw_indirect_count = 0;
131 bool request_draw_indirect_first_instance = false; // enable the core feature only for positive indirect draws 131 bool request_draw_indirect_first_instance = false; // enable the core feature only for positive indirect draws
132 bool request_debug_utils = false; // set before create(): enable VK_EXT_debug_utils when the loader has it 132 bool request_debug_utils = false; // set before create(): enable VK_EXT_debug_utils when the loader has it
133 bool pipeline_cache_control() const { return v13_.core && v13_.pipeline_creation_cache_control; }
133 bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported 134 bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported
134 bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) 135 bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address())
135 bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available 136 bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available
@@ -142,6 +143,8 @@ public:
142 bool custom_border_color = false; // VK_EXT_custom_border_color and customBorderColors enabled 143 bool custom_border_color = false; // VK_EXT_custom_border_color and customBorderColors enabled
143 bool custom_border_color_without_format = false; 144 bool custom_border_color_without_format = false;
144 bool shader_output_viewport_index = false; // Vulkan 1.2 shaderOutputViewportIndex enabled 145 bool shader_output_viewport_index = false; // Vulkan 1.2 shaderOutputViewportIndex enabled
146 bool request_buffer_marker = false; // set before initialize(): enable VK_AMD_buffer_marker where available
147 bool buffer_marker = false; // VK_AMD_buffer_marker is enabled
145 bool request_null_descriptor = false; // set before initialize(): enable VK_EXT_robustness2 nullDescriptor 148 bool request_null_descriptor = false; // set before initialize(): enable VK_EXT_robustness2 nullDescriptor
146 bool null_descriptor = false; // VK_EXT_robustness2 and nullDescriptor are enabled 149 bool null_descriptor = false; // VK_EXT_robustness2 and nullDescriptor are enabled
147 // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. 150 // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment.
@@ -189,6 +192,7 @@ public:
189 192
190 unsigned validation_errors() const { return validation_error_count(); } 193 unsigned validation_errors() const { return validation_error_count(); }
191 unsigned known_validation_errors() const { return known_validation_error_count(); } 194 unsigned known_validation_errors() const { return known_validation_error_count(); }
195 bool pipeline_cache_control_enabled() const { return v13_.core && v13_.pipeline_creation_cache_control; }
192 196
193 // presentation: also enable VK_KHR_surface + VK_KHR_win32_surface and VK_KHR_swapchain (Windows only). 197 // presentation: also enable VK_KHR_surface + VK_KHR_win32_surface and VK_KHR_swapchain (Windows only).
194 bool create(bool presentation = false) { return initialize(presentation) == DeviceStatus::ready; } 198 bool create(bool presentation = false) { return initialize(presentation) == DeviceStatus::ready; }
@@ -492,6 +496,7 @@ private:
492 enable.multiViewport = features.features.multiViewport; // d3d12_multi_viewport_test, where available 496 enable.multiViewport = features.features.multiViewport; // d3d12_multi_viewport_test, where available
493 enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available 497 enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available
494 enable.dualSrcBlend = features.features.dualSrcBlend; // d3d12_translated_draw_test --dual-source 498 enable.dualSrcBlend = features.features.dualSrcBlend; // d3d12_translated_draw_test --dual-source
499 enable.depthBounds = features.features.depthBounds; // depth-bounds PSOs (d3d12_mesh_test), where available
495 const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; 500 const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME;
496 501
497 // VK_EXT_host_image_copy where the device has it, for the D3D12 layer's CPU texture copies. 502 // VK_EXT_host_image_copy where the device has it, for the D3D12 layer's CPU texture copies.
@@ -767,6 +772,10 @@ private:
767 if (custom_border_color) device_extensions.push_back(custom_border_color_name); 772 if (custom_border_color) device_extensions.push_back(custom_border_color_name);
768 if (null_descriptor || robust_index_view) device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME); 773 if (null_descriptor || robust_index_view) device_extensions.push_back(VK_EXT_ROBUSTNESS_2_EXTENSION_NAME);
769 if (mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); 774 if (mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME);
775 buffer_marker = request_buffer_marker && std::any_of(extensions.begin(), extensions.end(), [](const auto& e) {
776 return std::strcmp(e.extensionName, VK_AMD_BUFFER_MARKER_EXTENSION_NAME) == 0;
777 });
778 if (buffer_marker) device_extensions.push_back(VK_AMD_BUFFER_MARKER_EXTENSION_NAME);
770 device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); 779 device_info.enabledExtensionCount = std::uint32_t(device_extensions.size());
771 device_info.ppEnabledExtensionNames = device_extensions.data(); 780 device_info.ppEnabledExtensionNames = device_extensions.data();
772 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device); 781 result = instance_fn<PFN_vkCreateDevice>("vkCreateDevice")(physical, &device_info, nullptr, &device);
diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp
index 3dafcaef6..97e93cb04 100644
--- a/runtime/test/vk_texture_test.cpp
+++ b/runtime/test/vk_texture_test.cpp
@@ -327,7 +327,10 @@ int main(int argc, char** argv) {
327 leonida::DescriptorTable desc_table(16); 327 leonida::DescriptorTable desc_table(16);
328 // The heap already holds the original key. Change only the registered key for the miss control. 328 // The heap already holds the original key. Change only the registered key for the miss control.
329 if (fetch_miss) tsharp[7] ^= 1; 329 if (fetch_miss) tsharp[7] ^= 1;
330 desc_table.insert(tsharp, 1); 330 // Index 1 is bound in both sampled arrays the shaders read: images[1] (binding 0, the 2D view) and the 2D-array
331 // images[1] (binding 3, the view of the two cubes). A tagged module reads its instruction's array only when the
332 // entry's kind names it, so the kind carries both: with one bit, a 2D_ARRAY or cube op got the 1x1 fallback.
333 desc_table.insert(tsharp, 1, leonida::kind_sampled_bit(0) | leonida::kind_sampled_bit(1));
331 desc_table.insert(ssharp, 1); 334 desc_table.insert(ssharp, 1);
332 const auto table = desc_table.build_gpu_buffer(true); 335 const auto table = desc_table.build_gpu_buffer(true);
333 VkBuffer tb; VkDeviceMemory tbm; void* tbp; 336 VkBuffer tb; VkDeviceMemory tbm; void* tbp;
diff --git a/runtime/test/vulkan_device_markers_test.cpp b/runtime/test/vulkan_device_markers_test.cpp
new file mode 100644
index 000000000..64693a83d
--- /dev/null
+++ b/runtime/test/vulkan_device_markers_test.cpp
@@ -0,0 +1,300 @@
1// The AMD breadcrumbs of the device-fault report (src/vulkan_device_markers.h, LEONIDA_DEVICE_MARKERS=1), on the
2// CPU: seq numbering, the marker writes a recorded dispatch makes, the history ring, and which dispatch the report
3// calls the likely hang for given marker values. The driver is faked: its marker writes are logged, and a "GPU"
4// applies a prefix of them to the mapped words, as a queue that stopped at that point would have. No GPU, no game
5// data.
6#include "../src/vulkan_device_fault.h"
7
8#include <cstdint>
9#include <cstdio>
10#include <cstring>
11#include <type_traits>
12#include <vector>
13
14#define EXPECT(condition) do { \
15 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
16} while (0)
17
18using namespace leonida;
19
20namespace {
21
22template<typename Handle>
23Handle fake_handle(std::uintptr_t value) {
24 if constexpr (std::is_pointer_v<Handle>) return reinterpret_cast<Handle>(value);
25 else return Handle(value);
26}
27
28struct Write {
29 VkCommandBuffer command_buffer;
30 std::uint64_t stage;
31 VkDeviceSize offset;
32 std::uint32_t marker;
33};
34std::vector<Write> writes;
35std::uint32_t words[2 * DeviceMarkers::max_queues];
36bool mapped = false, unmapped = false, freed = false;
37
38VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*,
39 VkBuffer* buffer) {
40 if (info->size < sizeof(words)) return VK_ERROR_UNKNOWN;
41 *buffer = fake_handle<VkBuffer>(0x100);
42 return VK_SUCCESS;
43}
44VKAPI_ATTR void VKAPI_CALL requirements(VkDevice, VkBuffer, VkMemoryRequirements* out) {
45 *out = {sizeof(words), 4, 0x6};
46}
47VKAPI_ATTR VkResult VKAPI_CALL allocate(VkDevice, const VkMemoryAllocateInfo* info, const VkAllocationCallbacks*,
48 VkDeviceMemory* memory) {
49 if (info->memoryTypeIndex != 2) return VK_ERROR_UNKNOWN; // host-visible, coherent, not device-local
50 *memory = fake_handle<VkDeviceMemory>(0x200);
51 return VK_SUCCESS;
52}
53VKAPI_ATTR VkResult VKAPI_CALL bind(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize) { return VK_SUCCESS; }
54VKAPI_ATTR VkResult VKAPI_CALL map(VkDevice, VkDeviceMemory, VkDeviceSize, VkDeviceSize, VkMemoryMapFlags, void** out) {
55 std::memset(words, 0xcd, sizeof(words));
56 *out = words;
57 mapped = true;
58 return VK_SUCCESS;
59}
60VKAPI_ATTR void VKAPI_CALL unmap(VkDevice, VkDeviceMemory) { unmapped = true; }
61VKAPI_ATTR void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer, const VkAllocationCallbacks*) {}
62VKAPI_ATTR void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) { freed = true; }
63VKAPI_ATTR void VKAPI_CALL write_marker2(VkCommandBuffer command_buffer, VkPipelineStageFlags2 stage, VkBuffer,
64 VkDeviceSize offset, std::uint32_t marker) {
65 writes.push_back({command_buffer, stage, offset, marker});
66}
67VKAPI_ATTR void VKAPI_CALL write_marker(VkCommandBuffer command_buffer, VkPipelineStageFlagBits stage, VkBuffer buffer,
68 VkDeviceSize offset, std::uint32_t marker) {
69 write_marker2(command_buffer, stage, buffer, offset, marker);
70}
71
72VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_proc(VkDevice, const char* name) {
73#define LEONIDA_FAKE(entry, fn) if (!std::strcmp(name, entry)) return reinterpret_cast<PFN_vkVoidFunction>(fn)
74 LEONIDA_FAKE("vkCreateBuffer", create_buffer);
75 LEONIDA_FAKE("vkGetBufferMemoryRequirements", requirements);
76 LEONIDA_FAKE("vkAllocateMemory", allocate);
77 LEONIDA_FAKE("vkBindBufferMemory", bind);
78 LEONIDA_FAKE("vkMapMemory", map);
79 LEONIDA_FAKE("vkUnmapMemory", unmap);
80 LEONIDA_FAKE("vkDestroyBuffer", destroy_buffer);
81 LEONIDA_FAKE("vkFreeMemory", free_memory);
82 LEONIDA_FAKE("vkCmdWriteBufferMarkerAMD", write_marker);
83 LEONIDA_FAKE("vkCmdWriteBufferMarker2AMD", write_marker2);
84#undef LEONIDA_FAKE
85 return nullptr;
86}
87
88VkPhysicalDeviceMemoryProperties memory_types() {
89 VkPhysicalDeviceMemoryProperties memory{};
90 memory.memoryTypeCount = 4;
91 memory.memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
92 memory.memoryTypes[1].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
93 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
94 memory.memoryTypes[2].propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
95 memory.memoryTypes[3].propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
96 VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
97 return memory;
98}
99
100// The "GPU": runs the first `count` logged marker writes, in order.
101void execute(std::size_t count) {
102 for (std::size_t i = 0; i < count && i < writes.size(); ++i)
103 words[writes[i].offset / 4] = writes[i].marker;
104}
105
106struct History { // a plain list in MarkerHistory::for_each order, for judge_markers
107 std::vector<MarkedDispatch> entries;
108 template<typename Visit>
109 void for_each(Visit&& visit) const {
110 for (const auto& d : entries) visit(d);
111 }
112};
113
114int pure_logic() {
115 // Serial order on the 32 bits the GPU writes, across the wrap.
116 EXPECT(marker_after(5, 4) && !marker_after(4, 4) && !marker_after(3, 4));
117 EXPECT(marker_after(0x100000002ull, 0xfffffffeu)); // seq 2^32 + 2 is after marker 2^32 - 2
118 EXPECT(!marker_after(0xfffffffeull, 0x00000003u)); // and 2^32 - 2 is before a wrapped 3
119
120 // The history ring keeps the newest `capacity`, oldest first.
121 MarkerHistory ring;
122 EXPECT(ring.size() == 0);
123 for (std::uint64_t seq = 1; seq <= MarkerHistory::capacity + 5; ++seq) ring.push({seq});
124 EXPECT(ring.size() == MarkerHistory::capacity);
125 std::uint64_t expect = 6, visited = 0;
126 bool ordered = true;
127 ring.for_each([&](const MarkedDispatch& d) { ordered &= d.seq == expect++; ++visited; });
128 EXPECT(ordered && visited == MarkerHistory::capacity);
129
130 // Two queues interleaved: compute has 1 3 5 6 8, direct has 2 4 7.
131 const VkQueue compute = fake_handle<VkQueue>(0x10), direct = fake_handle<VkQueue>(0x20);
132 History history;
133 for (std::uint64_t seq : {1, 3, 5, 6, 8}) history.entries.push_back({seq, 1, compute, "compute"});
134 for (std::uint64_t seq : {2, 4, 7}) history.entries.push_back({seq, 2, direct, "direct"});
135 std::sort(history.entries.begin(), history.entries.end(),
136 [](const auto& a, const auto& b) { return a.seq < b.seq; });
137
138 // compute finished 3, started 6: 5 and 6 run, 5 is the likely hang; 8 was submitted and not started.
139 auto r = judge_markers(compute, {6, 3}, history);
140 EXPECT(!r.idle() && r.unfinished == std::vector<std::uint64_t>({5, 6}) && r.likely_hang == 5 && !r.missing);
141 EXPECT(r.next_queued == 0 && r.queue_kind && !std::strcmp(r.queue_kind, "compute"));
142 // One dispatch started and not finished.
143 r = judge_markers(compute, {5, 3}, history);
144 EXPECT(r.unfinished == std::vector<std::uint64_t>({5}) && r.likely_hang == 5);
145 // direct idle after 4: nothing reported as hung, 7 is the next one it had queued.
146 r = judge_markers(direct, {4, 4}, history);
147 EXPECT(r.idle() && r.unfinished.empty() && !r.likely_hang && r.next_queued == 7 && !r.missing);
148 // Everything done.
149 r = judge_markers(direct, {7, 7}, history);
150 EXPECT(r.idle() && !r.likely_hang && !r.next_queued);
151 // Started past the history's newest dispatch of the queue: nothing to name.
152 r = judge_markers(compute, {9, 8}, history);
153 EXPECT(r.missing && !r.likely_hang && r.unfinished.empty());
154 // A started word behind the finished one (memory a reset scrambled) is read as idle, not as a hang.
155 r = judge_markers(compute, {1, 5}, history);
156 EXPECT(r.idle() && !r.likely_hang && r.next_queued == 6);
157 // No marker yet: every dispatch of the queue is queued, none hung.
158 r = judge_markers(compute, {0, 0}, history);
159 EXPECT(r.idle() && r.next_queued == 1 && !r.likely_hang);
160 // A queue the history does not know.
161 r = judge_markers(fake_handle<VkQueue>(0x30), {0, 0}, history);
162 EXPECT(!r.queue_kind && !r.next_queued);
163
164 // Across the 32-bit wrap: seqs 2^32 - 1, 2^32, 2^32 + 1 on one queue; markers hold their low 32 bits.
165 History wrapped;
166 for (std::uint64_t seq : {0xffffffffull, 0x100000000ull, 0x100000001ull})
167 wrapped.entries.push_back({seq, 1, compute, "compute"});
168 r = judge_markers(compute, {0x00000001u, 0xffffffffu}, wrapped);
169 EXPECT(r.unfinished == std::vector<std::uint64_t>({0x100000000ull, 0x100000001ull}) &&
170 r.likely_hang == 0x100000000ull);
171
172 // Memory type: host-visible and coherent, system memory first.
173 const auto memory = memory_types();
174 EXPECT(DeviceMarkers::memory_type(memory, 0xf) == 2);
175 EXPECT(DeviceMarkers::memory_type(memory, 0x3) == 1); // only device-local ones allowed: the BAR one
176 EXPECT(DeviceMarkers::memory_type(memory, 0x1) == UINT32_MAX);
177 return 0;
178}
179
180// Recording through CheckpointRecorder with the markers on, then the report's verdict for a stopped "GPU".
181int recorded(bool synchronization2) {
182 writes.clear();
183 mapped = unmapped = freed = false;
184 const auto memory = memory_types();
185 DeviceFaultExtensions enabled;
186 enabled.markers = true;
187 const VkQueue compute = fake_handle<VkQueue>(0x10), direct = fake_handle<VkQueue>(0x20);
188 const VkCommandBuffer cb = fake_handle<VkCommandBuffer>(0x30);
189 {
190 DeviceFaultDiagnostics diagnostics(get_proc, VK_NULL_HANDLE, enabled, &memory, synchronization2);
191 EXPECT(diagnostics.markers_on() && mapped);
192 diagnostics.add_queue(compute);
193 diagnostics.add_queue(direct);
194 diagnostics.add_queue(compute); // once is enough
195 EXPECT(words[0] == 0 && words[3] == 0); // the slots start at no dispatch
196 diagnostics.pipeline_names[4] = {"cs_example_a"};
197 diagnostics.pipeline_names[5] = {"cs_example_b"};
198 const std::array<std::uint32_t, 32> roots{};
199
200 // Submission 1 on the compute queue: seqs 1..3. Submission 2 on the direct queue: 4..5.
201 auto first = diagnostics.begin_submission(diagnostics.next_execute_call(), compute, "compute", 1);
202 EXPECT(first.markers && first.markers.offset == 0);
203 const CheckpointRecorder a{nullptr, first, diagnostics.pipeline_names, 0};
204 for (unsigned i = 0; i < 3; ++i) {
205 a.dispatch(cb, 10 + i, VK_NULL_HANDLE, i == 1 ? 5 : 4, roots, {1, 1, 1});
206 a.dispatched(cb);
207 }
208 a.dispatched(cb); // nothing open: no write
209 EXPECT(writes.size() == 6);
210 auto second = diagnostics.begin_submission(diagnostics.next_execute_call(), direct, "direct", 1);
211 EXPECT(second.markers && second.markers.offset == 8);
212 const CheckpointRecorder b{nullptr, second, diagnostics.pipeline_names, 0};
213 for (unsigned i = 0; i < 2; ++i) {
214 b.dispatch(cb, 20 + i, VK_NULL_HANDLE, 4, roots, {}, true, 1, 0, 0, 0, 1, 12);
215 b.dispatched(cb);
216 }
217 EXPECT(writes.size() == 10);
218 // Each dispatch: started (top of pipe, slot +0) then finished (bottom of pipe, slot +4), with its seq.
219 for (std::size_t i = 0; i < writes.size(); ++i) {
220 const Write& w = writes[i];
221 const std::uint32_t seq = std::uint32_t(i / 2 + 1);
222 const bool top = i % 2 == 0;
223 const VkDeviceSize slot = seq <= 3 ? 0 : 8;
224 const std::uint64_t top_stage = synchronization2 ? VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT
225 : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
226 const std::uint64_t bottom_stage = synchronization2 ? VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT
227 : VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
228 EXPECT(w.marker == seq && w.command_buffer == cb && w.offset == slot + (top ? 0 : 4) &&
229 w.stage == (top ? top_stage : bottom_stage));
230 }
231 // The report's list numbers them the same way.
232 EXPECT(first.dispatches.size() == 3 && first.dispatches[0].seq == 1 && first.dispatches[2].seq == 3);
233 EXPECT(second.dispatches.size() == 2 && second.dispatches[1].seq == 5);
234 EXPECT(first.marked.size() == 3 && first.marked[1].shader && !std::strcmp(first.marked[1].shader, "cs_example_b"));
235 diagnostics.publish(std::move(first));
236 diagnostics.publish(std::move(second));
237
238 // Nothing has run: no queue is reported as hung.
239 EXPECT(diagnostics.report_markers(false).empty());
240 // The compute queue stopped inside seq 2 (its started write ran, its finished one did not); the direct queue
241 // ran seq 4 completely and stopped inside 5.
242 execute(3); // seq 1 started and finished, seq 2 started
243 words[2] = 4; words[3] = 4; // direct: seq 4 done
244 words[2] = 5; // seq 5 started
245 auto hangs = diagnostics.report_markers(true);
246 EXPECT(hangs == std::vector<std::uint64_t>({2, 5}));
247 diagnostics.report_stall("synthetic marker check", 2, 1); // the list marks seq 2 and 5 as likely hangs
248 // Everything finished: no hang.
249 execute(writes.size());
250 EXPECT(diagnostics.report_markers(false).empty());
251 const MarkerSlot compute_slot = diagnostics.marker_slot(compute), direct_slot = diagnostics.marker_slot(direct);
252 EXPECT(compute_slot.started == 3 && compute_slot.finished == 3);
253 EXPECT(direct_slot.started == 5 && direct_slot.finished == 5);
254 }
255 EXPECT(unmapped && freed);
256 return 0;
257}
258
259// Without LEONIDA_DEVICE_MARKERS the extension is not asked for, and with it only where the device has it.
260int extension_request() {
261 const VkExtensionProperties with[] = {{VK_AMD_BUFFER_MARKER_EXTENSION_NAME, 1}};
262 VkDeviceCreateInfo device{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
263 const auto no_features = [](VkPhysicalDevice, VkPhysicalDeviceFeatures2*) {};
264 DeviceFaultFeatures features;
265 std::vector<const char*> extensions;
266 DeviceFaultRequest request;
267 EXPECT(!features.enable(VK_NULL_HANDLE, no_features, with, extensions, device, request).markers);
268 EXPECT(extensions.empty());
269 request.markers = true;
270 EXPECT(!features.enable(VK_NULL_HANDLE, no_features, {}, extensions, device, request).markers);
271 EXPECT(extensions.empty());
272 EXPECT(features.enable(VK_NULL_HANDLE, no_features, with, extensions, device, request).markers);
273 EXPECT(extensions.size() == 1 && !std::strcmp(extensions[0], VK_AMD_BUFFER_MARKER_EXTENSION_NAME));
274
275 // Markers enabled but no memory types given: off, the rest of the report unchanged.
276 DeviceFaultExtensions enabled;
277 enabled.markers = true;
278 DeviceFaultDiagnostics diagnostics(get_proc, VK_NULL_HANDLE, enabled);
279 EXPECT(!diagnostics.markers_on());
280 auto submission = diagnostics.begin_submission(diagnostics.next_execute_call(), VK_NULL_HANDLE, "compute", 1);
281 EXPECT(!submission.markers);
282 writes.clear();
283 const CheckpointRecorder recorder{nullptr, submission, diagnostics.pipeline_names, 0};
284 recorder.dispatch(VK_NULL_HANDLE, 0, VK_NULL_HANDLE, 0, {}, {1, 1, 1});
285 recorder.dispatched(VK_NULL_HANDLE);
286 EXPECT(writes.empty() && submission.dispatches[0].seq == 1 && submission.marked.empty());
287 EXPECT(diagnostics.report_markers(true).empty());
288 return 0;
289}
290
291} // namespace
292
293int main() {
294 if (int failed = pure_logic()) return failed;
295 if (int failed = recorded(true)) return failed;
296 if (int failed = recorded(false)) return failed;
297 if (int failed = extension_request()) return failed;
298 std::puts("vulkan_device_markers: ok");
299 return 0;
300}
diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp
index 3deb816b4..8334143fd 100644
--- a/runtime/test/xbox_bvh_builder_test.cpp
+++ b/runtime/test/xbox_bvh_builder_test.cpp
@@ -5,7 +5,9 @@
5// `python -I tools/xdxr_bvh.py check-build <out dir>` (ctest: xbox_bvh_builder + xbox_bvh_builder_check), which 5// `python -I tools/xdxr_bvh.py check-build <out dir>` (ctest: xbox_bvh_builder + xbox_bvh_builder_check), which
6// checks the records and traces rays against brute force. Also checked: the shim's prebuild sizes are the layer's, 6// checks the records and traces rays against brute force. Also checked: the shim's prebuild sizes are the layer's,
7// an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream 7// an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream
8// is accepted, rehydration answers E_NOTIMPL, and builders are released. 8// is accepted, rehydration rebuilds from geometry with S_OK (with the title's scratch, with none, and two elements of
9// one batch without scratch, which the shim gives regions of their own; their structures go to check-build too) and
10// refuses a source-only element, and builders are released.
9// 11//
10// xbox_bvh_builder_test <out dir> the shim 12// xbox_bvh_builder_test <out dir> the shim
11// xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered 13// xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered
@@ -373,11 +375,96 @@ int main(int argc, char** argv) {
373 list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, post[0]); 375 list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, post[0]);
374 if (!submit()) return fail("the compaction did not complete"); 376 if (!submit()) return fail("the compaction did not complete");
375 377
376 // ---- RehydrateRaytracingAccelerationStructureBatched2X: not implemented yet ---- 378 // ---- RehydrateRaytracingAccelerationStructureBatched2X: rebuilds from geometry ----
379 Ref<ID3D12Resource> rehydrated_as, rehydrated_rb;
380 if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav,
381 rehydrated_as.put())) ||
382 FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes,
383 D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, rehydrated_rb.put())))
384 return fail("rehydrated buffers", hr);
385 if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for rehydrate");
386
377 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC rehydrate_desc{}; 387 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC rehydrate_desc{};
388 rehydrate_desc.DestAccelerationStructureData = rehydrated_as->GetGPUVirtualAddress();
389 rehydrate_desc.Inputs = blas_inputs;
390 rehydrate_desc.ScratchAccelerationStructureData = scratch->GetGPUVirtualAddress();
378 const UINT64 source = blas->GetGPUVirtualAddress(); 391 const UINT64 source = blas->GetGPUVirtualAddress();
379 check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == E_NOTIMPL, 392
380 "RehydrateRaytracingAccelerationStructureBatched2X answers E_NOTIMPL (stage 2)"); 393 check(rehydrate(builder, nullptr, 1, &rehydrate_desc, &source) == E_INVALIDARG,
394 "RehydrateRaytracingAccelerationStructureBatched2X rejects null list");
395 check(rehydrate(builder, list.p, 1, nullptr, &source) == E_INVALIDARG,
396 "RehydrateRaytracingAccelerationStructureBatched2X rejects null descs");
397 check(rehydrate(builder, list.p, 0, nullptr, nullptr) == S_OK,
398 "RehydrateRaytracingAccelerationStructureBatched2X with count 0 returns S_OK");
399
400 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC source_only_desc{};
401 source_only_desc.DestAccelerationStructureData = rehydrated_as->GetGPUVirtualAddress();
402 check(rehydrate(builder, list.p, 1, &source_only_desc, &source) == E_NOTIMPL,
403 "RehydrateRaytracingAccelerationStructureBatched2X refuses source-only stream without geometry");
404
405 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC empty_desc{};
406 check(rehydrate(builder, list.p, 1, &empty_desc, nullptr) == S_OK,
407 "RehydrateRaytracingAccelerationStructureBatched2X logs and skips empty structure");
408
409 check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == S_OK,
410 "RehydrateRaytracingAccelerationStructureBatched2X rebuilds BLAS and returns S_OK");
411
412 // The title passes ScratchAccelerationStructureData = 0: the shim supplies scratch. Each of these builds has a
413 // destination of its own, read back below, so a build the shim skipped fails its check.
414 Ref<ID3D12Resource> zero_scratch_as, zero_scratch_rb;
415 if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav,
416 zero_scratch_as.put())) ||
417 FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes,
418 D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, zero_scratch_rb.put())))
419 return fail("zero-scratch buffers", hr);
420 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC zero_scratch_desc = rehydrate_desc;
421 zero_scratch_desc.DestAccelerationStructureData = zero_scratch_as->GetGPUVirtualAddress();
422 zero_scratch_desc.ScratchAccelerationStructureData = 0;
423 check(rehydrate(builder, list.p, 1, &zero_scratch_desc, &source) == S_OK,
424 "RehydrateRaytracingAccelerationStructureBatched2X supplies scratch when ScratchAccelerationStructureData == 0");
425
426 // Two elements of one batch, both without scratch, and no barrier between them (the title puts none): each needs
427 // a scratch region of its own. The second element has half the triangles, and asks for PERFORM_UPDATE with a
428 // source, as the title's dehydrated stream would be: a rehydrate builds it afresh all the same.
429 const UINT pair_tris[2] = {tris, tris / 2};
430 D3D12_RAYTRACING_GEOMETRY_DESC pair_geometry[2] = {geometry, geometry};
431 pair_geometry[1].Triangles.VertexCount = pair_tris[1] * 3;
432 Ref<ID3D12Resource> pair_as[2], pair_rb[2];
433 D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC pair_desc[2]{};
434 for (int i = 0; i < 2; ++i) {
435 if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav,
436 pair_as[i].put())) ||
437 FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes,
438 D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, pair_rb[i].put())))
439 return fail("batch-of-two buffers", hr);
440 pair_desc[i].DestAccelerationStructureData = pair_as[i]->GetGPUVirtualAddress();
441 pair_desc[i].Inputs = blas_inputs;
442 pair_desc[i].Inputs.pGeometryDescs = &pair_geometry[i];
443 }
444 pair_desc[1].Inputs.Flags |= D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE;
445 pair_desc[1].SourceAccelerationStructureData = source;
446 check(rehydrate(builder, list.p, 2, pair_desc, nullptr) == S_OK,
447 "RehydrateRaytracingAccelerationStructureBatched2X builds a batch of two elements without scratch");
448
449 list->ResourceBarrier(1, &barrier);
450 list->CopyBufferRegion(rehydrated_rb.p, 0, rehydrated_as.p, 0, blas_info.ResultDataMaxSizeInBytes);
451 list->CopyBufferRegion(zero_scratch_rb.p, 0, zero_scratch_as.p, 0, blas_info.ResultDataMaxSizeInBytes);
452 for (int i = 0; i < 2; ++i)
453 list->CopyBufferRegion(pair_rb[i].p, 0, pair_as[i].p, 0, blas_info.ResultDataMaxSizeInBytes);
454 if (!submit()) return fail("the rehydrate build did not complete");
455 auto header_units = [](ID3D12Resource* rb) {
456 void* p = nullptr;
457 std::uint32_t units = 0;
458 if (SUCCEEDED(rb->Map(0, nullptr, &p))) {
459 std::memcpy(&units, static_cast<char*>(p) + 4, 4);
460 rb->Unmap(0, nullptr);
461 }
462 return units;
463 };
464 check(header_units(rehydrated_rb.p) > 0, "the rehydrated structure has non-zero totalSizeIn64BNodes header");
465 check(header_units(zero_scratch_rb.p) > 0, "the structure rehydrated without the title's scratch was built");
466 check(header_units(pair_rb[0].p) > 0 && header_units(pair_rb[1].p) > 0,
467 "both elements of the batch without scratch were built");
381 468
382 // ---- dump for xdxr_bvh.py check-build ---- 469 // ---- dump for xdxr_bvh.py check-build ----
383 auto dump = [&](ID3D12Resource* rb, UINT64 size, const std::string& name, const std::string& json) { 470 auto dump = [&](ID3D12Resource* rb, UINT64 size, const std::string& name, const std::string& json) {
@@ -391,15 +478,18 @@ int main(int argc, char** argv) {
391 rb->Unmap(0, nullptr); 478 rb->Unmap(0, nullptr);
392 return ok; 479 return ok;
393 }; 480 };
394 std::string triangles = "["; 481 auto triangle_list = [&](UINT count) {
395 for (UINT t = 0; t < tris; ++t) { 482 std::string out = "[";
396 triangles += t ? ",\n [" : "\n ["; 483 for (UINT t = 0; t < count; ++t) {
397 for (int k = 0; k < 3; ++k) 484 out += t ? ",\n [" : "\n [";
398 triangles += (k ? ", [" : "[") + num(soup[9 * t + 3 * k]) + ", " + num(soup[9 * t + 3 * k + 1]) + ", " + 485 for (int k = 0; k < 3; ++k)
399 num(soup[9 * t + 3 * k + 2]) + "]"; 486 out += (k ? ", [" : "[") + num(soup[9 * t + 3 * k]) + ", " + num(soup[9 * t + 3 * k + 1]) + ", " +
400 triangles += ", 0, " + std::to_string(t) + "]"; 487 num(soup[9 * t + 3 * k + 2]) + "]";
401 } 488 out += ", 0, " + std::to_string(t) + "]";
402 triangles += "]"; 489 }
490 return out + "]";
491 };
492 const std::string triangles = triangle_list(tris);
403 check(dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas", 493 check(dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas",
404 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + 494 "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) +
405 ", \"triangles\": " + triangles + "}\n"), 495 ", \"triangles\": " + triangles + "}\n"),
@@ -419,6 +509,18 @@ int main(int argc, char** argv) {
419 "{\"kind\": \"blas\", \"address\": " + std::to_string(compacted->GetGPUVirtualAddress()) + 509 "{\"kind\": \"blas\", \"address\": " + std::to_string(compacted->GetGPUVirtualAddress()) +
420 ", \"triangles\": " + triangles + "}\n"), 510 ", \"triangles\": " + triangles + "}\n"),
421 "the BLAS compacted through the shim is written for check-build"); 511 "the BLAS compacted through the shim is written for check-build");
512 check(dump(zero_scratch_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas_rehydrated_zero_scratch",
513 "{\"kind\": \"blas\", \"address\": " + std::to_string(zero_scratch_as->GetGPUVirtualAddress()) +
514 ", \"triangles\": " + triangles + "}\n"),
515 "the BLAS rehydrated with the shim's scratch is written for check-build");
516 for (int i = 0; i < 2; ++i) {
517 const std::string name = "shim_blas_rehydrated_batch" + std::to_string(i);
518 check(dump(pair_rb[i].p, blas_info.ResultDataMaxSizeInBytes, name,
519 "{\"kind\": \"blas\", \"address\": " + std::to_string(pair_as[i]->GetGPUVirtualAddress()) +
520 ", \"triangles\": " + triangle_list(pair_tris[i]) + "}\n"),
521 i ? "the batch's second element (its own scratch region) is written for check-build"
522 : "the batch's first element (its own scratch region) is written for check-build");
523 }
422 524
423 // ---- the destructor releases the builder ---- 525 // ---- the destructor releases the builder ----
424 destruct(builder); 526 destruct(builder);
diff --git a/runtime/test/xbox_depth_storage_test.cpp b/runtime/test/xbox_depth_storage_test.cpp
index 4ae4a40a3..8164e819b 100644
--- a/runtime/test/xbox_depth_storage_test.cpp
+++ b/runtime/test/xbox_depth_storage_test.cpp
@@ -2,9 +2,12 @@
2#include "d3d12_test_shaders.h" 2#include "d3d12_test_shaders.h"
3#include "../shims/d3d12_com.h" 3#include "../shims/d3d12_com.h"
4#include "../shims/d3d12_xs_device.h" 4#include "../shims/d3d12_xs_device.h"
5#include "../src/depth24.h"
5#include "../src/title_va_alias.h" 6#include "../src/title_va_alias.h"
6#include <array> 7#include <array>
7#include <cstdio> 8#include <cstdio>
9#include <cstring>
10#include <utility>
8 11
9using namespace d3d12test; 12using namespace d3d12test;
10#define VERIFY(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0) 13#define VERIFY(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0)
@@ -56,46 +59,304 @@ int check_lease(ID3D12Device* dev, ID3D12Device* xbox) {
56} 59}
57 60
58// With the console D16S8 family made as D24S8 (LEONIDA_CONSOLE_D16S8=d24; the default on a GPU with D24S8 61// With the console D16S8 family made as D24S8 (LEONIDA_CONSOLE_D16S8=d24; the default on a GPU with D24S8
59// attachments, every NVIDIA card), the depth provider has no unordered-access form of a format 118 depth-stencil 62// attachments, every NVIDIA card), format 118 keeps its UAVs through the widened R16_TYPELESS + R8_UINT storage
60// texture and refuses it (Resource::enable_depth_stencil_uav). Slots 76 and 133 then make it without unordered 63// planes and Depth24Converter. Check slot 133 (the retail 1280x720 placement), CreateCommittedResource3 with a
61// access, as before the provider, so the title gets its texture instead of asserting. The description is the one 64// castable list, R16_UNORM float + R16_UINT uint + R8_UINT stencil UAV clears, and direct readback of the parent
62// measured where a real boot stopped: 1280x720, one mip, the all-ones layout through slot 133. 65// D24S8 attachment image.
63int check_d16s8_refused_uav(ID3D12Device* xbox) { 66int check_d16s8_d24_uav(ID3D12Device* dev, ID3D12Device* xbox) {
67 constexpr auto xbox_d16s8 = static_cast<DXGI_FORMAT>(118);
68 constexpr auto xbox_d16_plane = static_cast<DXGI_FORMAT>(119);
69 constexpr auto xbox_s8_plane = static_cast<DXGI_FORMAT>(120);
64 D3D12_RESOURCE_DESC tex{}; 70 D3D12_RESOURCE_DESC tex{};
65 tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; 71 tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
66 tex.Width = 1280; 72 tex.Width = 1280;
67 tex.Height = 720; 73 tex.Height = 720;
68 tex.DepthOrArraySize = tex.MipLevels = 1; 74 tex.DepthOrArraySize = tex.MipLevels = 1;
69 tex.SampleDesc.Count = 1; 75 tex.SampleDesc.Count = 1;
70 tex.Format = static_cast<DXGI_FORMAT>(118); 76 tex.Format = xbox_d16s8;
71 tex.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101); 77 tex.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101);
72 tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; 78 tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
73 D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; 79 D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT};
74 D3D12_CLEAR_VALUE clear{}; 80 D3D12_CLEAR_VALUE clear{};
75 clear.Format = tex.Format; 81 clear.Format = tex.Format;
76 clear.DepthStencil.Depth = 1; 82 clear.DepthStencil.Depth = 1;
77 using Create = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT,
78 const D3D12_CLEAR_VALUE*, const IID*, void**);
79 Ref<ID3D12Resource> committed;
80 VERIFY(SUCCEEDED(reinterpret_cast<Create>(slot(xbox, 76))(xbox, &heap, 0, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE,
81 &clear, &__uuidof(ID3D12Resource),
82 reinterpret_cast<void**>(&committed.p))));
83 VERIFY(committed.p && committed->GetDesc().Flags == D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
84 83
84 // Slot 133 placement at 1280x720 with all-ones layout keeps ALLOW_UNORDERED_ACCESS and valid plane UAVs.
85 using Place = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, UINT, const D3D12_CLEAR_VALUE*, 85 using Place = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, UINT, const D3D12_CLEAR_VALUE*,
86 const IID*, void**); 86 const IID*, void**);
87 constexpr SIZE_T pages = 16u << 20; // past the texture's size on any GPU; VirtualAlloc aligns it to 64 KiB 87 constexpr SIZE_T pages = 16u << 20;
88 void* va = VirtualAlloc(nullptr, pages, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); 88 void* va = VirtualAlloc(nullptr, pages, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
89 VERIFY(va); 89 VERIFY(va);
90 Ref<ID3D12Resource> placed; 90 Ref<ID3D12Resource> placed;
91 const HRESULT hr = reinterpret_cast<Place>(slot(xbox, 133))(xbox, reinterpret_cast<UINT64>(va), &tex, 0xFFFFFFFFu, 91 const HRESULT place_hr = reinterpret_cast<Place>(slot(xbox, 133))(xbox, reinterpret_cast<UINT64>(va), &tex,
92 &clear, &__uuidof(ID3D12Resource), 92 0xFFFFFFFFu, &clear, &__uuidof(ID3D12Resource),
93 reinterpret_cast<void**>(&placed.p)); 93 reinterpret_cast<void**>(&placed.p));
94 const bool made = SUCCEEDED(hr) && placed.p && placed->GetDesc().Flags == D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; 94 const bool placed_ok = SUCCEEDED(place_hr) && placed.p && placed->GetDesc().Flags == tex.Flags &&
95 placed = {}; 95 placed->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT;
96 bool placed_views_ok = false;
97 if (placed_ok) {
98 Ref<ID3D12DescriptorHeap> heap_uav;
99 D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 3};
100 if (SUCCEEDED(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap_uav.p)))) {
101 const SIZE_T step = dev->GetDescriptorHandleIncrementSize(hd.Type);
102 const SIZE_T base = heap_uav->GetCPUDescriptorHandleForHeapStart().ptr;
103 const std::pair<DXGI_FORMAT, UINT> plane_views[3] = {
104 {DXGI_FORMAT_R16_UINT, 0}, {DXGI_FORMAT_R16_UNORM, 0}, {DXGI_FORMAT_R8_UINT, 1}};
105 placed_views_ok = true;
106 for (UINT i = 0; i < 3; ++i) {
107 D3D12_UNORDERED_ACCESS_VIEW_DESC uv{};
108 uv.Format = plane_views[i].first;
109 uv.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
110 uv.Texture2D.PlaneSlice = plane_views[i].second;
111 dev->CreateUnorderedAccessView(placed.p, nullptr, &uv, {base + i * step});
112 leonida::gfx10::ImageWords words{};
113 std::memcpy(words.data(), reinterpret_cast<const void*>(base + i * step), sizeof(words));
114 leonida::gfx10::Image image{};
115 if (!leonida::gfx10::decode(words, image) || !rt::d3d12::uav_image_resource(placed.p, image.address))
116 placed_views_ok = false;
117 }
118 }
119 }
120 placed.reset();
96 VirtualFree(va, 0, MEM_RELEASE); 121 VirtualFree(va, 0, MEM_RELEASE);
97 VERIFY(made); 122 VERIFY(placed_ok && placed_views_ok);
98 std::printf("Xbox D16S8 made as D24S8: slots 76 and 133 make the depth-stencil texture without unordered access\n"); 123
124 // CreateCommittedResource3 with a castable format list also keeps ALLOW_UNORDERED_ACCESS (direct and slot 127),
125 // while plain PC D24_UNORM_S8_UINT refuses R16/R8 castable views and refuses ALLOW_UNORDERED_ACCESS.
126 {
127 Ref<ID3D12Device10> dev10;
128 VERIFY(SUCCEEDED(dev->QueryInterface(IID_PPV_ARGS(&dev10.p))));
129 D3D12_RESOURCE_DESC1 desc1{tex.Dimension, 0, 32, 32, 1, 1, xbox_d16s8, tex.SampleDesc,
130 D3D12_TEXTURE_LAYOUT_UNKNOWN, tex.Flags, {}};
131 const DXGI_FORMAT castable[] = {xbox_d16s8, xbox_d16_plane, xbox_s8_plane,
132 DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_R24_UNORM_X8_TYPELESS,
133 DXGI_FORMAT_X24_TYPELESS_G8_UINT, DXGI_FORMAT_R16_TYPELESS,
134 DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R8_UINT};
135 Ref<ID3D12Resource> c3;
136 VERIFY(SUCCEEDED(dev10->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &desc1,
137 D3D12_BARRIER_LAYOUT_COMMON, &clear, nullptr,
138 UINT(std::size(castable)), castable, IID_PPV_ARGS(&c3.p))));
139 VERIFY(c3.p && c3->GetDesc().Flags == tex.Flags && c3->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT);
140 const DXGI_FORMAT bad_view = DXGI_FORMAT_R32_FLOAT;
141 Ref<ID3D12Resource> bad_c3;
142 VERIFY(dev10->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &desc1, D3D12_BARRIER_LAYOUT_COMMON,
143 &clear, nullptr, 1, &bad_view, IID_PPV_ARGS(&bad_c3.p)) == E_INVALIDARG &&
144 !bad_c3.p);
145
146 // Xbox slot 127 forwards to CreateCommittedResource3 with the Xbox layout word replaced.
147 using Slot127 = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
148 const D3D12_RESOURCE_DESC1*, D3D12_BARRIER_LAYOUT, const D3D12_CLEAR_VALUE*,
149 ID3D12ProtectedResourceSession*, UINT, const DXGI_FORMAT*, REFIID, void**);
150 D3D12_RESOURCE_DESC1 xbox_desc1 = desc1;
151 xbox_desc1.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101);
152 Ref<ID3D12Resource> c3x;
153 VERIFY(SUCCEEDED(reinterpret_cast<Slot127>(slot(xbox, 127))(
154 xbox, &heap, D3D12_HEAP_FLAG_NONE, &xbox_desc1, D3D12_BARRIER_LAYOUT_COMMON, &clear, nullptr,
155 UINT(std::size(castable)), castable, IID_PPV_ARGS(&c3x.p))));
156 VERIFY(c3x.p && c3x->GetDesc().Flags == tex.Flags && c3x->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT);
157
158 // Plain PC D24_UNORM_S8_UINT: refuses ALLOW_UNORDERED_ACCESS and refuses R16/R8 castable formats.
159 D3D12_RESOURCE_DESC1 pc_d24 = desc1;
160 pc_d24.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
161 D3D12_CLEAR_VALUE pc_clear = clear;
162 pc_clear.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
163 Ref<ID3D12Resource> refused;
164 VERIFY(dev10->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &pc_d24, D3D12_BARRIER_LAYOUT_COMMON,
165 &pc_clear, nullptr, 0, nullptr, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG &&
166 !refused.p);
167 pc_d24.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
168 for (const DXGI_FORMAT narrow : {DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT,
169 DXGI_FORMAT_R8_UINT}) {
170 VERIFY(dev10->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &pc_d24, D3D12_BARRIER_LAYOUT_COMMON,
171 &pc_clear, nullptr, 1, &narrow, IID_PPV_ARGS(&refused.p)) ==
172 E_INVALIDARG &&
173 !refused.p);
174 }
175
176 // CreateCommittedResource2, CreatePlacedResource/2 (in a heap), and CreateReservedResource with format 118.
177 Ref<ID3D12Device8> dev8;
178 VERIFY(SUCCEEDED(dev->QueryInterface(IID_PPV_ARGS(&dev8.p))));
179 D3D12_RESOURCE_DESC1 d16_no_uav = desc1;
180 d16_no_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
181 Ref<ID3D12Resource> c2;
182 VERIFY(SUCCEEDED(dev8->CreateCommittedResource2(&heap, D3D12_HEAP_FLAG_NONE, &d16_no_uav,
183 D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear, nullptr,
184 IID_PPV_ARGS(&c2.p))));
185 VERIFY(c2.p && c2->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT);
186 VERIFY(dev8->CreateCommittedResource2(&heap, D3D12_HEAP_FLAG_NONE, &desc1, D3D12_RESOURCE_STATE_DEPTH_WRITE,
187 &clear, nullptr, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG &&
188 !refused.p);
189
190 D3D12_RESOURCE_DESC placed_desc{};
191 placed_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
192 placed_desc.Width = placed_desc.Height = 32;
193 placed_desc.DepthOrArraySize = placed_desc.MipLevels = 1;
194 placed_desc.Format = xbox_d16s8;
195 placed_desc.SampleDesc.Count = 1;
196 placed_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
197 const auto placed_alloc = dev->GetResourceAllocationInfo(0, 1, &placed_desc);
198 VERIFY(placed_alloc.SizeInBytes > 0 && placed_alloc.SizeInBytes != UINT64_MAX);
199 D3D12_HEAP_DESC heap_desc{placed_alloc.SizeInBytes, heap, placed_alloc.Alignment, D3D12_HEAP_FLAG_NONE};
200 Ref<ID3D12Heap> placed_heap;
201 VERIFY(SUCCEEDED(dev->CreateHeap(&heap_desc, IID_PPV_ARGS(&placed_heap.p))));
202 Ref<ID3D12Resource> heap_placed;
203 VERIFY(SUCCEEDED(dev->CreatePlacedResource(placed_heap.p, 0, &placed_desc, D3D12_RESOURCE_STATE_DEPTH_WRITE,
204 &clear, IID_PPV_ARGS(&heap_placed.p))));
205 VERIFY(heap_placed.p && heap_placed->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT);
206 D3D12_RESOURCE_DESC placed_uav = placed_desc;
207 placed_uav.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
208 VERIFY(dev->CreatePlacedResource(placed_heap.p, 0, &placed_uav, D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear,
209 IID_PPV_ARGS(&refused.p)) == E_INVALIDARG &&
210 !refused.p);
211 Ref<ID3D12Resource> heap_placed2;
212 VERIFY(SUCCEEDED(dev10->CreatePlacedResource2(placed_heap.p, 0, &d16_no_uav, D3D12_BARRIER_LAYOUT_COMMON,
213 &clear, 0, nullptr, IID_PPV_ARGS(&heap_placed2.p))));
214 VERIFY(heap_placed2.p && heap_placed2->GetDesc().Format == DXGI_FORMAT_D24_UNORM_S8_UINT);
215 for (const DXGI_FORMAT narrow : {DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R8_UINT}) {
216 VERIFY(dev10->CreatePlacedResource2(placed_heap.p, 0, &pc_d24, D3D12_BARRIER_LAYOUT_COMMON, &pc_clear,
217 1, &narrow, IID_PPV_ARGS(&refused.p)) == E_INVALIDARG &&
218 !refused.p);
219 }
220
221 // Reserved resources reject stencil formats (including format 118) because they have no tile shape.
222 D3D12_RESOURCE_DESC reserved_desc = placed_desc;
223 reserved_desc.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE;
224 VERIFY(dev->CreateReservedResource(&reserved_desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear,
225 IID_PPV_ARGS(&refused.p)) == E_INVALIDARG &&
226 !refused.p);
227 }
228
229 // Direct parent D24S8 attachment readback after R16_UNORM float + R16_UINT uint + R8_UINT stencil UAV clears.
230 constexpr UINT w = 32, layers = 2;
231 tex.Width = tex.Height = w;
232 tex.DepthOrArraySize = layers;
233 using Create = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT,
234 const D3D12_CLEAR_VALUE*, const IID*, void**);
235 Ref<ID3D12Resource> depth;
236 VERIFY(SUCCEEDED(reinterpret_cast<Create>(slot(xbox, 76))(xbox, &heap, 0, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE,
237 &clear, &__uuidof(ID3D12Resource),
238 reinterpret_cast<void**>(&depth.p))));
239 const D3D12_RESOURCE_DESC parent_desc = depth->GetDesc();
240 VERIFY(parent_desc.Flags == tex.Flags && parent_desc.Format == DXGI_FORMAT_D24_UNORM_S8_UINT);
241
242 Ref<ID3D12DescriptorHeap> dsv, uav;
243 D3D12_DESCRIPTOR_HEAP_DESC dsv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, layers};
244 D3D12_DESCRIPTOR_HEAP_DESC uav_hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 3};
245 VERIFY(SUCCEEDED(dev->CreateDescriptorHeap(&dsv_hd, IID_PPV_ARGS(&dsv.p))));
246 VERIFY(SUCCEEDED(dev->CreateDescriptorHeap(&uav_hd, IID_PPV_ARGS(&uav.p))));
247 const auto hslot = [&](ID3D12DescriptorHeap* h, D3D12_DESCRIPTOR_HEAP_TYPE t, UINT i) {
248 auto handle = h->GetCPUDescriptorHandleForHeapStart();
249 handle.ptr += i * dev->GetDescriptorHandleIncrementSize(t);
250 return handle;
251 };
252 const UINT16 seed_d[layers] = {0x2000, 0xc000};
253 const UINT8 seed_s[layers] = {0x41, 0x42};
254 for (UINT i = 0; i < layers; ++i) {
255 D3D12_DEPTH_STENCIL_VIEW_DESC dv{};
256 dv.Format = xbox_d16s8;
257 dv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
258 dv.Texture2DArray = {0, i, 1};
259 dev->CreateDepthStencilView(depth.p, &dv, hslot(dsv.p, dsv_hd.Type, i));
260 }
261 const std::pair<DXGI_FORMAT, UINT> uv_cfg[3] = {
262 {DXGI_FORMAT_R16_UNORM, 0}, {DXGI_FORMAT_R16_UINT, 0}, {DXGI_FORMAT_R8_UINT, 1}};
263 for (UINT i = 0; i < 3; ++i) {
264 D3D12_UNORDERED_ACCESS_VIEW_DESC uv{};
265 uv.Format = uv_cfg[i].first;
266 uv.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
267 uv.Texture2DArray = {0, 0, 1, uv_cfg[i].second};
268 dev->CreateUnorderedAccessView(depth.p, nullptr, &uv, hslot(uav.p, uav_hd.Type, i));
269 }
270 D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp[2 * layers]{};
271 UINT64 total = 0;
272 dev->GetCopyableFootprints(&parent_desc, 0, 2 * layers, 0, fp, nullptr, nullptr, &total);
273 auto rb_desc = buffer_desc(total);
274 D3D12_HEAP_PROPERTIES host{D3D12_HEAP_TYPE_READBACK};
275 Ref<ID3D12Resource> readback;
276 VERIFY(SUCCEEDED(dev->CreateCommittedResource(&host, D3D12_HEAP_FLAG_NONE, &rb_desc,
277 D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p))));
278 Ref<ID3D12CommandQueue> queue;
279 Ref<ID3D12CommandAllocator> alloc;
280 Ref<ID3D12GraphicsCommandList> list;
281 Ref<ID3D12Fence> fence;
282 D3D12_COMMAND_QUEUE_DESC qd{};
283 VERIFY(SUCCEEDED(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p))));
284 VERIFY(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p))));
285 VERIFY(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, IID_PPV_ARGS(&list.p))));
286 VERIFY(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))));
287
288 for (UINT i = 0; i < layers; ++i)
289 list->ClearDepthStencilView(hslot(dsv.p, dsv_hd.Type, i),
290 D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL,
291 float(seed_d[i]) / 65535.f, seed_s[i], 0, nullptr);
292 auto to_uav = transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
293 list->ResourceBarrier(1, &to_uav);
294 const D3D12_RECT r_unorm{2, 3, 10, 11}, r_uint{14, 5, 22, 13}, r_stencil{4, 4, 12, 12};
295 const FLOAT fval[4]{0.25f};
296 const UINT uval[4]{0x9123u}, sval[4]{0xa7u};
297 list->ClearUnorderedAccessViewFloat({}, hslot(uav.p, uav_hd.Type, 0), depth.p, fval, 1, &r_unorm);
298 D3D12_RESOURCE_BARRIER uav_bar{};
299 uav_bar.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
300 uav_bar.UAV.pResource = depth.p;
301 list->ResourceBarrier(1, &uav_bar);
302 list->ClearUnorderedAccessViewUint({}, hslot(uav.p, uav_hd.Type, 1), depth.p, uval, 1, &r_uint);
303 list->ClearUnorderedAccessViewUint({}, hslot(uav.p, uav_hd.Type, 2), depth.p, sval, 1, &r_stencil);
304 auto to_copy = transition(depth.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
305 list->ResourceBarrier(1, &to_copy);
306 for (UINT sub = 0; sub < 2 * layers; ++sub) {
307 D3D12_TEXTURE_COPY_LOCATION src{}, dst{};
308 src.pResource = depth.p;
309 src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
310 src.SubresourceIndex = sub;
311 dst.pResource = readback.p;
312 dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
313 dst.PlacedFootprint = fp[sub];
314 list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
315 }
316 VERIFY(SUCCEEDED(list->Close()));
317 ID3D12CommandList* batch[]{list.p};
318 queue->ExecuteCommandLists(1, batch);
319 VERIFY(SUCCEEDED(queue->Signal(fence.p, 1)));
320 const auto end = GetTickCount64() + 5000;
321 while (fence->GetCompletedValue() < 1 && GetTickCount64() < end) Sleep(1);
322 VERIFY(fence->GetCompletedValue() == 1);
323
324 void* mapped{};
325 VERIFY(SUCCEEDED(readback->Map(0, nullptr, &mapped)));
326 const auto* bytes = static_cast<const std::uint8_t*>(mapped);
327 for (UINT i = 0; i < layers; ++i) {
328 for (int y = 0; y < int(w); ++y) {
329 for (int x = 0; x < int(w); ++x) {
330 UINT16 exp_u16 = seed_d[i];
331 if (i == 0 && x >= r_unorm.left && x < r_unorm.right && y >= r_unorm.top && y < r_unorm.bottom)
332 exp_u16 = 0x4000u;
333 if (i == 0 && x >= r_uint.left && x < r_uint.right && y >= r_uint.top && y < r_uint.bottom)
334 exp_u16 = 0x9123u;
335 const std::uint32_t exp_d24 = leonida::depth24_quantize(float(exp_u16) / 65535.f);
336 std::uint32_t got_word = 0;
337 std::memcpy(&got_word, bytes + fp[i].Offset + y * fp[i].Footprint.RowPitch + x * 4, 4);
338 const std::uint32_t got_d24 = got_word & 0xffffffu;
339 if (got_d24 != exp_d24) {
340 std::fprintf(stderr, "D24 parent slice %u (%d,%d): expected %06x got %06x\n",
341 i, x, y, exp_d24, got_d24);
342 readback->Unmap(0, nullptr);
343 return 1;
344 }
345 const UINT8 exp_s = (i == 0 && x >= r_stencil.left && x < r_stencil.right &&
346 y >= r_stencil.top && y < r_stencil.bottom) ? 0xa7u : seed_s[i];
347 const UINT8 got_s = bytes[fp[layers + i].Offset + y * fp[layers + i].Footprint.RowPitch + x];
348 if (got_s != exp_s) {
349 std::fprintf(stderr, "D24 parent stencil slice %u (%d,%d): expected %02x got %02x\n",
350 i, x, y, exp_s, got_s);
351 readback->Unmap(0, nullptr);
352 return 1;
353 }
354 }
355 }
356 }
357 readback->Unmap(0, nullptr);
358 std::printf("Xbox D16S8 made as D24S8: slot 133, CreateCommittedResource3, R16_UNORM/R16_UINT/R8_UINT UAVs "
359 "and D24 parent readback exact\n");
99 return 0; 360 return 0;
100} 361}
101} 362}
@@ -140,11 +401,6 @@ int main() {
140 VERIFY(SUCCEEDED(rt::d3d12_xs::create_device_proxy(dev, __uuidof(ID3D12Device), 401 VERIFY(SUCCEEDED(rt::d3d12_xs::create_device_proxy(dev, __uuidof(ID3D12Device),
141 reinterpret_cast<void**>(&proxy.p), true))); 402 reinterpret_cast<void**>(&proxy.p), true)));
142 rt::d3d12::set_device_outer(dev, proxy.p); 403 rt::d3d12::set_device_outer(dev, proxy.p);
143 if (std::getenv("LEONIDA_TEST_D16S8_REFUSED_UAV")) {
144 VERIFY(check_d16s8_refused_uav(proxy.p) == 0);
145 VERIFY(gpu.validation_errors() == 0);
146 return 0;
147 }
148 VERIFY(check_lease(dev, proxy.p) == 0); 404 VERIFY(check_lease(dev, proxy.p) == 0);
149 const auto allocation = dev->GetResourceAllocationInfo(0, 1, &tex); 405 const auto allocation = dev->GetResourceAllocationInfo(0, 1, &tex);
150 VERIFY(allocation.SizeInBytes >= 768u * 768 * layers * 2 && allocation.SizeInBytes != UINT64_MAX); 406 VERIFY(allocation.SizeInBytes >= 768u * 768 * layers * 2 && allocation.SizeInBytes != UINT64_MAX);
@@ -286,6 +542,9 @@ int main() {
286 std::printf("Xbox D16S8 depth and stencil: %u depth words and %u stencil bytes exact after UAV round trip\n", width*width*layers,width*width*layers); 542 std::printf("Xbox D16S8 depth and stencil: %u depth words and %u stencil bytes exact after UAV round trip\n", width*width*layers,width*width*layers);
287 } 543 }
288 readback->Unmap(0, nullptr); 544 readback->Unmap(0, nullptr);
545 const char* d16s8_mode = std::getenv("LEONIDA_CONSOLE_D16S8");
546 if (with_stencil && d16s8_mode && std::strcmp(d16s8_mode, "d24") == 0)
547 VERIFY(check_d16s8_d24_uav(dev, proxy.p) == 0);
289 VERIFY(gpu.validation_errors() == 0); 548 VERIFY(gpu.validation_errors() == 0);
290 std::printf("Depth D16 / storage R16_UINT, six layers and %u exact texels\n", width * width * layers); 549 std::printf("Depth D16 / storage R16_UINT, six layers and %u exact texels\n", width * width * layers);
291 return 0; 550 return 0;
diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp
index bc311a87e..5f026a61e 100644
--- a/runtime/test/xbox_present_test.cpp
+++ b/runtime/test/xbox_present_test.cpp
@@ -540,8 +540,9 @@ int main() {
540 } 540 }
541 EXPECT(grab(frame)); 541 EXPECT(grab(frame));
542 EXPECT(region_is(frame, 0, 0, width, height, {0, 0, 0}, 0)); 542 EXPECT(region_is(frame, 0, 0, width, height, {0, 0, 0}, 0));
543 // (The blank frame is a frame in flight like any other: with latency 1 the next wait needs it shown first.) 543 // (The blank frame is a frame in flight like any other, but at most `latency` frames are: with latency 1 it
544 EXPECT(xbox.pacer().frames_in_flight() == 2); // the first frame and the blank one 544 // replaces the first frame, which still waits for its vblank, and the next wait needs it shown first.)
545 EXPECT(xbox.pacer().frames_in_flight() == 1);
545 clock.advance_us(period); 546 clock.advance_us(period);
546 std::printf("0 planes (blank): ok\n"); 547 std::printf("0 planes (blank): ok\n");
547 548
diff --git a/runtime/test/xg_xs_test.cpp b/runtime/test/xg_xs_test.cpp
index 18356cb41..c6df1bc24 100644
--- a/runtime/test/xg_xs_test.cpp
+++ b/runtime/test/xg_xs_test.cpp
@@ -415,6 +415,62 @@ int main() {
415 for (unsigned pass = 0; pass < 3; ++pass) poll([] { return true; }); 415 for (unsigned pass = 0; pass < 3; ++pass) poll([] { return true; });
416 check(polled == std::vector<int>{4}, "an expired wall budget advances past priority entries to the next texture"); 416 check(polled == std::vector<int>{4}, "an expired wall budget advances past priority entries to the next texture");
417 417
418 // LEONIDA_TITLE_EVERY_BUDGET_US: the marked textures (mapped or stale) are visited from a cursor of their own
419 // until the budget runs out; the unmarked ones are the round robin's and are skipped here.
420 {
421 Entry m1{true, false, 11}, u1{false, false, 12}, s1{false, true, 13}, m2{true, false, 14};
422 Entry u2{false, false, 15}, s2{false, true, 16};
423 std::map<std::uint64_t, Entry*> marked{{100, &m1}, {200, &u1}, {300, &s1}, {400, &m2}, {500, &u2}};
424 std::uint64_t every = 0;
425 std::vector<int> seen;
426 std::vector<int> urgent_ids; // stands for "mapped and never filled"
427 const auto is_urgent = [&](const Entry& t) {
428 return std::find(urgent_ids.begin(), urgent_ids.end(), t.id) != urgent_ids.end();
429 };
430 const auto visit_marked = [&](auto exhausted) {
431 const auto snapshot = leonida::title_texture_snapshot(marked);
432 leonida::visit_marked_title_textures(
433 snapshot, every,
434 [&](Entry& t) {
435 seen.push_back(t.id);
436 urgent_ids.erase(std::remove(urgent_ids.begin(), urgent_ids.end(), t.id), urgent_ids.end());
437 },
438 is_urgent, exhausted);
439 };
440 visit_marked([] { return false; });
441 check(seen == std::vector<int>{11, 13, 14}, "without a limit every marked texture is visited once, in order");
442 seen.clear();
443 for (unsigned pass = 0; pass < 4; ++pass) visit_marked([] { return true; });
444 check(seen == std::vector<int>{11, 13, 14, 11},
445 "a budget spent after each visit moves one marked texture a pass and wraps");
446 seen.clear();
447 marked.erase(300);
448 marked[350] = &s2;
449 visit_marked([&] { return seen.size() == 2; });
450 check(seen == std::vector<int>{16, 14}, "the cursor survives an erased entry and reaches a new stale one");
451 seen.clear();
452 visit_marked([] { return true; });
453 check(seen == std::vector<int>{11}, "the pass after resumes past the last visited entry");
454 // The cursor now points past 100 (m1). Mark m2 (at 400) urgent, as a mapped texture never filled: it is
455 // visited first whatever the budget, and once filled (no longer urgent) it is not visited a second time
456 // in the same pass's rotation.
457 seen.clear();
458 urgent_ids = {14};
459 visit_marked([] { return true; });
460 check(seen == std::vector<int>{14, 16}, "an urgent texture is visited first, then one rotation step");
461 seen.clear();
462 urgent_ids = {14};
463 visit_marked([] { return false; });
464 check(seen == std::vector<int>{14, 11, 16},
465 "with no limit an urgent texture is still visited once, not again in the rotation");
466 seen.clear();
467 const std::vector<std::pair<std::uint64_t, Entry*>> none;
468 leonida::visit_marked_title_textures(
469 none, every, [&](Entry& t) { seen.push_back(t.id); }, [](const Entry&) { return true; },
470 [] { return false; });
471 check(seen.empty(), "an empty registry visits nothing");
472 }
473
418 // A fill made during a pass submits, and that submission destroys a retired image whose destructor erases its 474 // A fill made during a pass submits, and that submission destroys a retired image whose destructor erases its
419 // registry entry; the registry mutex is recursive for its owner on Windows, so the erase lands inside the pass. 475 // registry entry; the registry mutex is recursive for its owner on Windows, so the erase lands inside the pass.
420 // A walk over a snapshot keeps every entry of the pass alive and in order, which a walk over the registry 476 // A walk over a snapshot keeps every entry of the pass alive and in order, which a walk over the registry
@@ -436,6 +492,42 @@ int main() {
436 } 492 }
437 493
438 { 494 {
495 leonida::TitleTextureRangeIndex index;
496 std::map<std::uint64_t, std::pair<unsigned, unsigned>> ranges;
497 for (unsigned id = 1; id <= 60; ++id) {
498 const auto begin = (id * 17) % 31;
499 ranges[id] = {begin, begin + id};
500 index.set(id, begin, id);
501 }
502 index.erase(12);
503 ranges.erase(12);
504 index.set(13, 5, 9);
505 ranges[13] = {5, 14};
506 index.set(2, 0, 0);
507 ranges.erase(2);
508 bool same = true;
509 for (unsigned from = 0; from < 100; ++from) {
510 for (unsigned to = from; to <= 100; ++to) {
511 std::vector<std::uint64_t> got, want;
512 index.overlapping(from, to, [&](auto key) { got.push_back(key); });
513 std::sort(got.begin(), got.end());
514 for (const auto& [key, range] : ranges)
515 if (from < to && range.first < to && from < range.second) want.push_back(key);
516 same &= got == want;
517 }
518 }
519 check(same, "indexed invalidation matches all CPU overlaps after alias, replacement and removal");
520 index.set(99, (UINT64_MAX >> 1) - 2, 16);
521 unsigned hits = 0;
522 index.overlapping(UINT64_MAX >> 1, (UINT64_MAX >> 1) + 1, [&](auto id) { hits += id == 99; });
523 check(hits == 1, "an interval across bit 63 is indexed without a word-width shift");
524 const auto slice = leonida::title_texture_snapshot(ranges, 12, 4);
525 check(slice.size() == 4 && slice.front().first == 13 && slice.back().first == 16,
526 "bounded refresh resumes at the next live address");
527 check(leonida::title_texture_snapshot(ranges, 61, 4).empty(), "end of sweep permits wrap");
528 }
529
530 {
439 leonida::TitleWriteRanges writes{{20, 30}, {10, 20}, {15, 17}, {60, 75}, {60, 67}, {90, 90}}; 531 leonida::TitleWriteRanges writes{{20, 30}, {10, 20}, {15, 17}, {60, 75}, {60, 67}, {90, 90}};
440 const auto original = writes; 532 const auto original = writes;
441 leonida::merge_title_writes(writes); 533 leonida::merge_title_writes(writes);
@@ -699,6 +791,58 @@ int main() {
699 check(create(&d, &computer) == E_NOTIMPL && computer, "unsupported texture keeps a safe fallback object"); 791 check(create(&d, &computer) == E_NOTIMPL && computer, "unsupported texture keeps a safe fallback object");
700 check(slot<LayoutFn>(computer, 2)(computer, &l) == E_NOTIMPL && l.size == 8192 && 792 check(slot<LayoutFn>(computer, 2)(computer, &l) == E_NOTIMPL && l.size == 8192 &&
701 slot<RefFn>(computer, 1)(computer) == 1, "fallback leaves caller outputs untouched and is safe to release"); 793 slot<RefFn>(computer, 1)(computer) == 1, "fallback leaves caller outputs untouched and is safe to release");
794
795 // A linear 3D texture (layout 0x100) is thin (addrlib HwlComputeSurfaceInfoLinear): rows of 256 bytes, every
796 // depth slice a whole mip chain. The title's texture lock reads mip 0's offset and size from this
797 // computer and, when creation fails, its own uninitialised stack instead: measured with the 32x32x36 R32_UINT
798 // 3D texture it clears 0x48000 bytes at that pointer, which is this layout's size exactly.
799 d = {4, 0, 32, 32, 36, 1, DXGI_FORMAT_R32_UINT, 1, 0, 0x100, 0x300004};
800 if (!make(create, d, computer, "create linear 3D computer")) return 1;
801 std::memset(&l, 0xa5, sizeof(l));
802 check(slot<LayoutFn>(computer, 2)(computer, &l) == S_OK && l.size == 0x48000 && l.alignment == 256 &&
803 l.mips == 1 && l.dimension == 4 && l.plane[0].slice_bytes == 8192 &&
804 l.plane[0].mips[0].offset == 0 && l.plane[0].mips[0].size == 0x48000 &&
805 l.plane[0].mips[0].slice_bytes == 8192 && l.plane[0].mips[0].pitch_bytes == 256,
806 "linear 3D 32x32x36 R32 is 36 slices of 32 rows of 256 bytes");
807 check(slot<SizeFn>(computer, 3)(computer) == 0x48000 && slot<SizeFn>(computer, 4)(computer) == 256,
808 "linear 3D size and alignment agree with slot 2");
809 check(slot<OffsetFn>(computer, 6)(computer, 0, 0, 3, 2, 5, 0, nullptr) == 5 * 8192 + 2 * 256 + 3 * 4,
810 "linear 3D element offset is slice, row, column");
811 {
812 // A mip-0 copy through slots 8 and 9: padded source rows and slices land at 256-byte rows, 8 KiB slices.
813 constexpr unsigned row = 32 * 4 + 12, slice = row * 32 + 20;
814 std::vector<uint8_t> source(slice * 36), read_back(source.size(), 0), memory(l.size, 0);
815 for (size_t i = 0; i < source.size(); ++i) source[i] = uint8_t(i * 7 + 3);
816 check(slot<IntoFn>(computer, 8)(computer, memory.data(), 0, 0, source.data(), row, slice) == S_OK &&
817 std::memcmp(&memory[35 * 8192 + 31 * 256], &source[35 * slice + 31 * row], 32 * 4) == 0 &&
818 slot<FromFn>(computer, 9)(computer, read_back.data(), 0, 0, 0, memory.data(), row, slice) == S_OK &&
819 std::memcmp(&read_back[35 * slice + 31 * row], &source[35 * slice + 31 * row], 32 * 4) == 0,
820 "slots 8 and 9 copy a linear 3D mip slice by slice");
821 check(slot<IntoFn>(computer, 8)(computer, memory.data(), 0, 1, source.data(), row, slice) == E_INVALIDARG,
822 "a 3D texture has no second subresource");
823 }
824 slot<RefFn>(computer, 1)(computer);
825
826 // A linear 3D texture with more than one mip: its chain layout (slice-major or mip-major) is not measured, so the
827 // description is refused rather than given offsets that may be wrong for mips 1+.
828 d = {4, 0, 32, 16, 8, 3, DXGI_FORMAT_R8_UNORM, 1, 0, 0x100, 0};
829 check(!build_texture(d, texture), "linear 3D with mips is refused until a title texture measures it");
830
831 // A render-target or depth flag with an explicit mode takes that mode's layout (measured: 1x1 RGBA32F
832 // descriptions with layout 0x100 and the render-target bit reach the title's CPU upload).
833 d = {3, 0, 1, 1, 1, 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, 0x100, 0x300001};
834 if (!make(create, d, computer, "create linear render-target computer")) return 1;
835 check(slot<LayoutFn>(computer, 2)(computer, &l) == S_OK && l.size == 256 && l.alignment == 256,
836 "explicit linear render target is one 256-byte row");
837 slot<RefFn>(computer, 1)(computer);
838 // Without a mode, the render target is not this model's (it leaves the mode to XG's Z/R choice): the general layout
839 // model lays it out, as it does the other render targets above.
840 void* general = nullptr;
841 d.layout = 0;
842 Texture own{};
843 check(!build_texture(d, own), "a render target without a mode is not the explicit-mode model's");
844 check(create(&d, &general) == S_OK && general, "a render target without a mode uses the general layout model");
845 if (general) slot<RefFn>(general, 1)(general);
702 std::printf("%d checks, %d failures\n", g_checks, g_failures); 846 std::printf("%d checks, %d failures\n", g_checks, g_failures);
703 return g_failures ? 1 : 0; 847 return g_failures ? 1 : 0;
704} 848}
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp
index 27af09aec..cb350820e 100644
--- a/runtime/test/xs_proxy_mock_test.cpp
+++ b/runtime/test/xs_proxy_mock_test.cpp
@@ -137,11 +137,62 @@ struct Mock {
137 UINT clear_dsv_num_rects; 137 UINT clear_dsv_num_rects;
138 const D3D12_RECT* clear_dsv_rects; 138 const D3D12_RECT* clear_dsv_rects;
139 D3D_FEATURE_LEVEL max_level; // device: the highest level FEATURE_LEVELS reports (0: the query is refused) 139 D3D_FEATURE_LEVEL max_level; // device: the highest level FEATURE_LEVELS reports (0: the query is refused)
140 // list: set by a call the Vulkan layer's list takes as invalid (a texture barrier with no resource at slot 80, a
141 // clear at slot 48 of a view made with no resource); Close (slot 9) then fails, as that list's does.
142 bool list_error;
143 // list slot 80 (Barrier): what the last call carried, copied (the proxy's converted groups live for the call).
144 UINT barrier_group_count;
145 D3D12_BARRIER_TYPE barrier_group_types[4];
146 UINT barrier_group_sizes[4];
147 UINT barrier_global_count;
148 D3D12_GLOBAL_BARRIER barrier_globals[8];
149 UINT barrier_texture_count;
150 D3D12_TEXTURE_BARRIER barrier_textures[8];
140}; 151};
141 152
142Mock g_pool[512]; 153Mock g_pool[512];
143unsigned g_pool_used = 0; 154unsigned g_pool_used = 0;
144 155
156// The real handles the mock device last wrote an RTV with no resource at (device slot 20). A mock list's clear of one
157// sets list_error, as the Vulkan layer's empty view record does.
158SIZE_T g_mock_null_rtvs[16];
159unsigned g_mock_null_rtv_count = 0;
160
161void mock_note_rtv(SIZE_T handle, bool no_resource) {
162 for (unsigned i = 0; i < g_mock_null_rtv_count; ++i)
163 if (g_mock_null_rtvs[i] == handle) g_mock_null_rtvs[i--] = g_mock_null_rtvs[--g_mock_null_rtv_count];
164 if (no_resource && g_mock_null_rtv_count < std::size(g_mock_null_rtvs))
165 g_mock_null_rtvs[g_mock_null_rtv_count++] = handle;
166}
167
168bool mock_is_null_rtv(SIZE_T handle) {
169 for (unsigned i = 0; i < g_mock_null_rtv_count; ++i)
170 if (g_mock_null_rtvs[i] == handle) return true;
171 return false;
172}
173
174void mock_barrier(Mock* m, std::uint64_t count, std::uint64_t groups_word) {
175 const auto* groups = reinterpret_cast<const D3D12_BARRIER_GROUP*>(groups_word);
176 m->barrier_group_count = static_cast<UINT>(count);
177 m->barrier_global_count = m->barrier_texture_count = 0;
178 for (UINT g = 0; groups && g < static_cast<UINT>(count); ++g) {
179 const D3D12_BARRIER_GROUP& group = groups[g];
180 if (g < std::size(m->barrier_group_types)) {
181 m->barrier_group_types[g] = group.Type;
182 m->barrier_group_sizes[g] = group.NumBarriers;
183 }
184 for (UINT i = 0; i < group.NumBarriers; ++i) {
185 if (group.Type == D3D12_BARRIER_TYPE_GLOBAL && m->barrier_global_count < std::size(m->barrier_globals)) {
186 m->barrier_globals[m->barrier_global_count++] = group.pGlobalBarriers[i];
187 } else if (group.Type == D3D12_BARRIER_TYPE_TEXTURE) {
188 if (!group.pTextureBarriers[i].pResource) m->list_error = true;
189 if (m->barrier_texture_count < std::size(m->barrier_textures))
190 m->barrier_textures[m->barrier_texture_count++] = group.pTextureBarriers[i];
191 }
192 }
193 }
194}
195
145void** mock_vtable(); 196void** mock_vtable();
146void** mock_list_vtable(); 197void** mock_list_vtable();
147 198
@@ -384,6 +435,7 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) {
384 if (a1) std::memcpy(&m->queue_desc, reinterpret_cast<const void*>(a1), sizeof(m->queue_desc)); 435 if (a1) std::memcpy(&m->queue_desc, reinterpret_cast<const void*>(a1), sizeof(m->queue_desc));
385 return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a2, a3)); 436 return static_cast<std::uint32_t>(mock_create(m, Kind::queue, a2, a3));
386 case 9: return static_cast<std::uint32_t>(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator 437 case 9: return static_cast<std::uint32_t>(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator
438 case 20: mock_note_rtv(static_cast<SIZE_T>(a3), a1 == 0); break; // CreateRenderTargetView(res, desc, dest)
387 // Slot 12 (CreateCommandList) never reaches this switch: the device vtable's slot is the dedicated 439 // Slot 12 (CreateCommandList) never reaches this switch: the device vtable's slot is the dedicated
388 // mock_create_command_list, which needs the sixth word the generic thunk does not declare on some 440 // mock_create_command_list, which needs the sixth word the generic thunk does not declare on some
389 // builds and which picks the list mock's chain breadth from full_chain_lists. 441 // builds and which picks the list mock's chain breadth from full_chain_lists.
@@ -524,6 +576,11 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) {
524 m->om_has_dsv = dsv != nullptr; 576 m->om_has_dsv = dsv != nullptr;
525 m->om_dsv = dsv ? dsv->ptr : 0; 577 m->om_dsv = dsv ? dsv->ptr : 0;
526 } 578 }
579 if (m->kind == Kind::list || m->kind == Kind::command_list) {
580 if (slot == 9) return static_cast<std::uint32_t>(m->list_error ? E_INVALIDARG : S_OK); // Close
581 if (slot == 48 && mock_is_null_rtv(static_cast<SIZE_T>(a1))) m->list_error = true; // ClearRenderTargetView
582 if (slot == 80) mock_barrier(m, a1, a2); // Barrier
583 }
527 return S_OK; 584 return S_OK;
528} 585}
529 586
@@ -2419,7 +2476,8 @@ int check_lists() {
2419 so_view.BufferFilledSizeLocation = p2; 2476 so_view.BufferFilledSizeLocation = p2;
2420 EXPECT(hr_of(raw(list, 49, 0, 1, word(&so_view))) == S_OK && real->calls[45] == 1); 2477 EXPECT(hr_of(raw(list, 49, 0, 1, word(&so_view))) == S_OK && real->calls[45] == 1);
2421 // The console tail past the PC chain is refused with E_NOTIMPL only when the mapped PC slot is missing. 2478 // The console tail past the PC chain is refused with E_NOTIMPL only when the mapped PC slot is missing.
2422 EXPECT(hr_of(raw(list, 146, word(list), 0)) == S_OK && real->calls[80] == 1); // enhanced Barrier -> GCL7 80 2479 // Enhanced Barrier -> GCL7 80; an empty call (no groups) goes through as the PC no-op it is.
2480 EXPECT(hr_of(raw(list, 146, 0, 0)) == S_OK && real->calls[80] == 1);
2423 EXPECT(release(list) == 0 && real->refs == 0); 2481 EXPECT(release(list) == 0 && real->refs == 0);
2424 EXPECT(release(allocator) == 0 && real_allocator->refs == 0); 2482 EXPECT(release(allocator) == 0 && real_allocator->refs == 0);
2425 EXPECT(xs::device_proxy_ref_count(device) == device_refs); 2483 EXPECT(xs::device_proxy_ref_count(device) == device_refs);
@@ -2952,6 +3010,36 @@ int check_render_target_sizes() {
2952 mips.MipLevels = 3; 3010 mips.MipLevels = 3;
2953 EXPECT(ask(&mips, 1).SizeInBytes == (135 + 40 + 12) * 65536ull); 3011 EXPECT(ask(&mips, 1).SizeInBytes == (135 + 40 + 12) * 65536ull);
2954 3012
3013 // A texture the GPU writes through unordered access and the title also clears with the CPU through its lock
3014 // with a layout word naming its mode: 0x100, linear. Its console layout is 36 slices of 32 rows
3015 // of 256 bytes, 0x48000 bytes, where the PC device says 0x30000; the larger size wins, rounded to the
3016 // description's alignment. The title's own layout word decides, though the PC form of the description has lost it.
3017 D3D12_RESOURCE_DESC grid{};
3018 grid.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D;
3019 grid.Width = 32;
3020 grid.Height = 32;
3021 grid.DepthOrArraySize = 36;
3022 grid.MipLevels = 1;
3023 grid.Format = DXGI_FORMAT_R32_UINT;
3024 grid.SampleDesc.Count = 1;
3025 grid.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x100);
3026 grid.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
3027 EXPECT(ask(&grid, 1).SizeInBytes == 0x50000);
3028 // In a list it takes its console size at its own offset.
3029 const D3D12_RESOURCE_DESC grid_and_target[] = {grid, hd};
3030 EXPECT(ask(grid_and_target, 2).SizeInBytes == 0x50000 + 8847360);
3031 // The rule only grows: a mode XG lays out smaller (4 KiB thick blocks, 32x32x40 x 4 B = 0x28000) keeps the PC
3032 // size, and so does a layout word that leaves the mode to XG, or a mode XG's model lacks.
3033 D3D12_RESOURCE_DESC smaller = grid;
3034 smaller.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x105);
3035 EXPECT(ask(&smaller, 1).SizeInBytes == 0x30000);
3036 D3D12_RESOURCE_DESC no_mode = grid;
3037 no_mode.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
3038 EXPECT(ask(&no_mode, 1).SizeInBytes == 0x30000);
3039 D3D12_RESOURCE_DESC unknown_mode = grid;
3040 unknown_mode.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x11b); // SW_64KB_R_X
3041 EXPECT(ask(&unknown_mode, 1).SizeInBytes == 0x30000);
3042
2955 // 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 3043 // 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
2956 // units of 64 KiB for the mock, so code that compares the proxy with the PC device still agrees. 3044 // units of 64 KiB for the mock, so code that compares the proxy with the PC device still agrees.
2957 D3D12_RESOURCE_ALLOCATION_INFO pc{}; 3045 D3D12_RESOURCE_ALLOCATION_INFO pc{};
@@ -4807,10 +4895,18 @@ int check_console_command_list() {
4807 EXPECT(xs::is_command_list_proxy(list7_proxy)); 4895 EXPECT(xs::is_command_list_proxy(list7_proxy));
4808 Mock* real_list7 = reinterpret_cast<Mock*>(xs::command_list_proxy_real_list(list7_proxy)); 4896 Mock* real_list7 = reinterpret_cast<Mock*>(xs::command_list_proxy_real_list(list7_proxy));
4809 EXPECT(real_list7 != nullptr); 4897 EXPECT(real_list7 != nullptr);
4810 // Console slot 146 -> PC slot 80 (since 80 < 81 slots) 4898 // Console slot 146 -> PC slot 80 (since 80 < 81 slots): a valid group goes through with the title's pointer.
4811 raw(list7_proxy, 146, 0x9999, 0, 0, 0); 4899 {
4812 EXPECT(real_list7->calls[80] == 1); 4900 const D3D12_GLOBAL_BARRIER global{D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_SYNC_ALL,
4813 EXPECT(real_list7->args[80][0] == 0x9999); 4901 D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS};
4902 D3D12_BARRIER_GROUP group{};
4903 group.Type = D3D12_BARRIER_TYPE_GLOBAL;
4904 group.NumBarriers = 1;
4905 group.pGlobalBarriers = &global;
4906 raw(list7_proxy, 146, 1, word(&group), 0, 0);
4907 EXPECT(real_list7->calls[80] == 1);
4908 EXPECT(real_list7->args[80][0] == 1 && real_list7->args[80][1] == word(&group));
4909 }
4814 EXPECT(release(list7_proxy) == 0 && real_list7->refs == 0); 4910 EXPECT(release(list7_proxy) == 0 && real_list7->refs == 0);
4815 4911
4816 // Clean up 4912 // Clean up
@@ -4830,6 +4926,249 @@ int check_console_command_list() {
4830 return 0; 4926 return 0;
4831} 4927}
4832 4928
4929// ---- Console list slots 146 and 52: what the console takes as a no-op or a global barrier ----
4930//
4931// The mock list stands in for the Vulkan layer's: a texture barrier with no resource, or a clear of a view made with
4932// no resource, puts it in its error state and its Close fails (checked directly on the mock first, so the cases
4933// below mean something). Through the proxy the barrier becomes a global barrier and the clear is skipped.
4934int check_console_null_barrier_and_clear() {
4935 g_mock_null_rtv_count = 0;
4936 Mock* mock = nullptr;
4937 void* device = make_device(mock, 9, true, true, /*full_chain_lists=*/true);
4938 EXPECT(device);
4939 const IID allocator_iid = __uuidof(ID3D12CommandAllocator);
4940 const IID gcl_iid = __uuidof(ID3D12GraphicsCommandList);
4941 void* allocator = nullptr;
4942 EXPECT(hr_of(raw(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&allocator))) == S_OK);
4943 void* list = nullptr;
4944 EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(allocator), 0, word(&gcl_iid),
4945 word(&list))) == S_OK);
4946 Mock* const real = reinterpret_cast<Mock*>(xs::list_proxy_real_list(list));
4947 EXPECT(real && real->kind == Kind::list);
4948 Mock* const texture_a = new_mock(Kind::resource); // never dereferenced: only the pointers are compared
4949 Mock* const texture_b = new_mock(Kind::resource);
4950 auto* const resource_a = reinterpret_cast<ID3D12Resource*>(texture_a);
4951 auto* const resource_b = reinterpret_cast<ID3D12Resource*>(texture_b);
4952
4953 // A texture barrier with no resource, as the title records it: render target to pixel-shader read.
4954 D3D12_TEXTURE_BARRIER no_resource{};
4955 no_resource.SyncBefore = D3D12_BARRIER_SYNC_RENDER_TARGET;
4956 no_resource.SyncAfter = D3D12_BARRIER_SYNC_PIXEL_SHADING;
4957 no_resource.AccessBefore = D3D12_BARRIER_ACCESS_RENDER_TARGET;
4958 no_resource.AccessAfter = D3D12_BARRIER_ACCESS_SHADER_RESOURCE;
4959 no_resource.LayoutBefore = D3D12_BARRIER_LAYOUT_RENDER_TARGET;
4960 no_resource.LayoutAfter = D3D12_BARRIER_LAYOUT_SHADER_RESOURCE;
4961 no_resource.Subresources.IndexOrFirstMipLevel = 0xffffffffu;
4962 D3D12_BARRIER_GROUP texture_group{};
4963 texture_group.Type = D3D12_BARRIER_TYPE_TEXTURE;
4964 texture_group.NumBarriers = 1;
4965 texture_group.pTextureBarriers = &no_resource;
4966
4967 // The mock models the PC list: the same group sent to it directly fails its Close.
4968 raw(real, 80, 1, word(&texture_group));
4969 EXPECT(real->list_error && hr_of(raw(real, 9)) == E_INVALIDARG);
4970 real->list_error = false;
4971 real->calls[80] = 0;
4972
4973 // 1. Through the proxy: one global barrier with the same sync and access, in the call's own storage; the
4974 // title's group and barrier are not written; Close succeeds.
4975 EXPECT(hr_of(raw(list, 146, 1, word(&texture_group))) == S_OK);
4976 EXPECT(real->calls[80] == 1 && real->args[80][0] == 1 && real->args[80][1] != word(&texture_group));
4977 EXPECT(real->barrier_group_count == 1 && real->barrier_group_types[0] == D3D12_BARRIER_TYPE_GLOBAL &&
4978 real->barrier_group_sizes[0] == 1 && real->barrier_global_count == 1 && real->barrier_texture_count == 0);
4979 EXPECT(real->barrier_globals[0].SyncBefore == D3D12_BARRIER_SYNC_RENDER_TARGET &&
4980 real->barrier_globals[0].SyncAfter == D3D12_BARRIER_SYNC_PIXEL_SHADING &&
4981 real->barrier_globals[0].AccessBefore == D3D12_BARRIER_ACCESS_RENDER_TARGET &&
4982 real->barrier_globals[0].AccessAfter == D3D12_BARRIER_ACCESS_SHADER_RESOURCE);
4983 EXPECT(texture_group.Type == D3D12_BARRIER_TYPE_TEXTURE && texture_group.pTextureBarriers == &no_resource &&
4984 !no_resource.pResource);
4985 EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK);
4986
4987 // 2. Valid barriers pass unchanged: a texture group with resources goes through with the title's own pointer.
4988 D3D12_TEXTURE_BARRIER with_resource[2] = {no_resource, no_resource};
4989 with_resource[0].pResource = resource_a;
4990 with_resource[1].pResource = resource_b;
4991 with_resource[1].Subresources = {2, 1, 0, 1, 0, 1};
4992 D3D12_BARRIER_GROUP valid_group{};
4993 valid_group.Type = D3D12_BARRIER_TYPE_TEXTURE;
4994 valid_group.NumBarriers = 2;
4995 valid_group.pTextureBarriers = with_resource;
4996 EXPECT(hr_of(raw(list, 146, 1, word(&valid_group))) == S_OK);
4997 EXPECT(real->calls[80] == 2 && real->args[80][0] == 1 && real->args[80][1] == word(&valid_group));
4998 EXPECT(real->barrier_texture_count == 2 && real->barrier_global_count == 0 &&
4999 real->barrier_textures[0].pResource == resource_a && real->barrier_textures[1].pResource == resource_b &&
5000 real->barrier_textures[1].LayoutAfter == D3D12_BARRIER_LAYOUT_SHADER_RESOURCE &&
5001 real->barrier_textures[1].Subresources.IndexOrFirstMipLevel == 2);
5002 EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK);
5003
5004 // 3. Mixed: a buffer group, then a texture group of [resource, none, none, resource]. The buffer group passes as
5005 // it is and the texture group splits into texture(1), global(2), texture(1), in order.
5006 const D3D12_BUFFER_BARRIER buffer{D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_SYNC_COMPUTE_SHADING,
5007 D3D12_BARRIER_ACCESS_COPY_DEST, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS,
5008 resource_a, 0, UINT64_MAX};
5009 D3D12_TEXTURE_BARRIER mixed[4] = {with_resource[0], no_resource, no_resource, with_resource[1]};
5010 mixed[2].SyncBefore = D3D12_BARRIER_SYNC_COMPUTE_SHADING;
5011 mixed[2].AccessBefore = D3D12_BARRIER_ACCESS_UNORDERED_ACCESS;
5012 D3D12_BARRIER_GROUP mixed_groups[2]{};
5013 mixed_groups[0].Type = D3D12_BARRIER_TYPE_BUFFER;
5014 mixed_groups[0].NumBarriers = 1;
5015 mixed_groups[0].pBufferBarriers = &buffer;
5016 mixed_groups[1].Type = D3D12_BARRIER_TYPE_TEXTURE;
5017 mixed_groups[1].NumBarriers = 4;
5018 mixed_groups[1].pTextureBarriers = mixed;
5019 EXPECT(hr_of(raw(list, 146, 2, word(mixed_groups))) == S_OK);
5020 EXPECT(real->calls[80] == 3 && real->args[80][0] == 4);
5021 EXPECT(real->barrier_group_types[0] == D3D12_BARRIER_TYPE_BUFFER && real->barrier_group_sizes[0] == 1 &&
5022 real->barrier_group_types[1] == D3D12_BARRIER_TYPE_TEXTURE && real->barrier_group_sizes[1] == 1 &&
5023 real->barrier_group_types[2] == D3D12_BARRIER_TYPE_GLOBAL && real->barrier_group_sizes[2] == 2 &&
5024 real->barrier_group_types[3] == D3D12_BARRIER_TYPE_TEXTURE && real->barrier_group_sizes[3] == 1);
5025 EXPECT(real->barrier_texture_count == 2 && real->barrier_textures[0].pResource == resource_a &&
5026 real->barrier_textures[1].pResource == resource_b);
5027 EXPECT(real->barrier_global_count == 2 &&
5028 real->barrier_globals[0].SyncBefore == D3D12_BARRIER_SYNC_RENDER_TARGET &&
5029 real->barrier_globals[1].SyncBefore == D3D12_BARRIER_SYNC_COMPUTE_SHADING &&
5030 real->barrier_globals[1].AccessBefore == D3D12_BARRIER_ACCESS_UNORDERED_ACCESS &&
5031 real->barrier_globals[1].AccessAfter == D3D12_BARRIER_ACCESS_SHADER_RESOURCE);
5032 EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK);
5033
5034 // 4. Arrays that cannot be read safely are refused whole: nothing reaches the list, which stays valid and keeps
5035 // taking calls.
5036 D3D12_BARRIER_GROUP unknown_type = texture_group;
5037 reinterpret_cast<std::uint32_t&>(unknown_type.Type) = 7;
5038 D3D12_BARRIER_GROUP null_barriers{};
5039 null_barriers.Type = D3D12_BARRIER_TYPE_TEXTURE;
5040 null_barriers.NumBarriers = 3;
5041 D3D12_BARRIER_GROUP huge_group = valid_group;
5042 huge_group.NumBarriers = 0x10000000u;
5043 EXPECT(hr_of(raw(list, 146, 1, 0)) == S_OK); // null array, nonzero count
5044 EXPECT(hr_of(raw(list, 146, 1, word(&unknown_type))) == S_OK); // a group type the layer does not know
5045 EXPECT(hr_of(raw(list, 146, 1, word(&null_barriers))) == S_OK); // null barrier array, nonzero count
5046 EXPECT(hr_of(raw(list, 146, 1, word(&huge_group))) == S_OK); // barrier count over the limit
5047 EXPECT(hr_of(raw(list, 146, 0x40000000u, word(&valid_group))) == S_OK); // group count over the limit
5048 // A malformed group after a convertible one refuses the call as well: nothing of it is recorded.
5049 D3D12_BARRIER_GROUP half_bad[2] = {texture_group, unknown_type};
5050 EXPECT(hr_of(raw(list, 146, 2, word(half_bad))) == S_OK);
5051 EXPECT(real->calls[80] == 3 && !real->list_error);
5052 EXPECT(hr_of(raw(list, 146, 1, word(&texture_group))) == S_OK && real->calls[80] == 4);
5053 EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK);
5054
5055 // 5. ClearRenderTargetView (console 52 -> PC 48) of a view made with no resource is skipped; a view made with a
5056 // resource is still cleared. No custom heap range here, so the handles reach the device unchanged.
5057 const SIZE_T rtv_none = kMockHeapCpuStart + 0x1000;
5058 const SIZE_T rtv_real = rtv_none + kMockDescriptorInc;
5059 const SIZE_T rtv_copy = rtv_none + 4 * kMockDescriptorInc;
5060 const FLOAT color[4] = {0.0f, 0.0f, 0.0f, 0.0f};
5061 raw(device, 20, 0, 0, rtv_none); // CreateRenderTargetView(nullptr, nullptr, handle)
5062 raw(device, 20, word(resource_a), 0, rtv_real);
5063 EXPECT(mock->calls[20] == 2 && mock_is_null_rtv(rtv_none) && !mock_is_null_rtv(rtv_real));
5064 raw(real, 48, rtv_none, word(color), 0, 0); // the mock's model: the direct clear fails the list
5065 EXPECT(real->list_error && hr_of(raw(real, 9)) == E_INVALIDARG);
5066 real->list_error = false;
5067 real->calls[48] = 0;
5068
5069 EXPECT(hr_of(raw(list, 52, rtv_none, word(color), 0, 0)) == S_OK && real->calls[48] == 0);
5070 EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK);
5071 const D3D12_RECT rect{0, 0, 4, 4};
5072 raw(list, 52, rtv_real, word(color), 1, word(&rect));
5073 EXPECT(real->calls[48] == 1 && real->args[48][0] == rtv_real && real->args[48][1] == word(color) &&
5074 real->args[48][2] == 1 && real->args[48][3] == word(&rect));
5075 EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK);
5076
5077 // A view made again at the same handle with a resource is cleared from then on.
5078 raw(device, 20, word(resource_b), 0, rtv_none);
5079 raw(list, 52, rtv_none, word(color), 0, 0);
5080 EXPECT(real->calls[48] == 2 && real->args[48][0] == rtv_none);
5081 raw(device, 20, 0, 0, rtv_none); // and with no resource again: skipped again
5082 raw(list, 52, rtv_none, word(color), 0, 0);
5083 EXPECT(real->calls[48] == 2);
5084
5085 // Descriptor copies move the mark: CopyDescriptorsSimple of the empty view, then of the real one over it.
5086 raw(device, 24, 1, rtv_copy, rtv_none, D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
5087 raw(list, 52, rtv_copy, word(color), 0, 0);
5088 EXPECT(real->calls[48] == 2);
5089 raw(device, 24, 1, rtv_copy, rtv_real, D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
5090 raw(list, 52, rtv_copy, word(color), 0, 0);
5091 EXPECT(real->calls[48] == 3 && real->args[48][0] == rtv_copy);
5092 // A copy of another heap type leaves the RTV marks alone.
5093 raw(device, 24, 1, rtv_copy, rtv_none, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
5094 raw(list, 52, rtv_copy, word(color), 0, 0);
5095 EXPECT(real->calls[48] == 4);
5096 // CopyDescriptors with ranges: one destination range of two from two source ranges of one (empty, then real).
5097 const D3D12_CPU_DESCRIPTOR_HANDLE dest_starts[1] = {{rtv_copy}};
5098 const UINT dest_sizes[1] = {2};
5099 const D3D12_CPU_DESCRIPTOR_HANDLE src_starts[2] = {{rtv_none}, {rtv_real}};
5100 const UINT src_sizes[2] = {1, 1};
5101 raw10(device, 23, {1, word(dest_starts), word(dest_sizes), 2, word(src_starts), word(src_sizes),
5102 D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 0, 0, 0});
5103 EXPECT(mock->calls[23] == 1);
5104 raw(list, 52, rtv_copy, word(color), 0, 0);
5105 EXPECT(real->calls[48] == 4);
5106 raw(list, 52, rtv_copy + kMockDescriptorInc, word(color), 0, 0);
5107 EXPECT(real->calls[48] == 5 && real->args[48][0] == rtv_copy + kMockDescriptorInc);
5108 EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK);
5109
5110 // Releasing an RTV heap drops the marks in its real range, so a heap made later at the same address starts
5111 // unmarked; a mark outside that range stays.
5112 g_heap_hook.next_ptr = nullptr; // a plain PC heap even if a descriptor-heap hook is registered: real handles
5113 D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{};
5114 rtv_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
5115 rtv_heap_desc.NumDescriptors = 4;
5116 const IID heap_iid = __uuidof(ID3D12DescriptorHeap);
5117 void* rtv_heap = nullptr;
5118 EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&rtv_heap_desc), word(&heap_iid), word(&rtv_heap)))));
5119 EXPECT(rtv_heap && xs::is_heap_proxy(rtv_heap) && raw(rtv_heap, 9) == kMockHeapCpuStart);
5120 const SIZE_T in_heap = kMockHeapCpuStart + 2 * kMockDescriptorInc;
5121 raw(device, 20, 0, 0, in_heap);
5122 const unsigned clears = real->calls[48];
5123 raw(list, 52, in_heap, word(color), 0, 0);
5124 EXPECT(real->calls[48] == clears); // marked while the heap lives: skipped
5125 EXPECT(raw(rtv_heap, 2) == 0);
5126 raw(list, 52, in_heap, word(color), 0, 0);
5127 EXPECT(real->calls[48] == clears + 1 && real->args[48][0] == in_heap); // the mark went with the heap
5128 real->list_error = false; // the mock list still takes its own view there as invalid
5129 raw(list, 52, rtv_none, word(color), 0, 0);
5130 EXPECT(real->calls[48] == clears + 1); // outside the released heap: still skipped
5131 // A second RTV heap at the same address: the view made there with a resource is cleared, and a view made with
5132 // no resource is marked again for as long as that heap lives.
5133 void* rtv_heap2 = nullptr;
5134 EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&rtv_heap_desc), word(&heap_iid), word(&rtv_heap2)))));
5135 raw(device, 20, word(resource_a), 0, in_heap);
5136 raw(list, 52, in_heap, word(color), 0, 0);
5137 EXPECT(real->calls[48] == clears + 2 && !real->list_error);
5138 raw(device, 20, 0, 0, in_heap);
5139 raw(list, 52, in_heap, word(color), 0, 0);
5140 EXPECT(real->calls[48] == clears + 2);
5141 EXPECT(raw(rtv_heap2, 2) == 0);
5142 EXPECT(!real->list_error && hr_of(raw(list, 9)) == S_OK);
5143
5144 // The marks are the device's own: another device's clear at a handle marked on the first is forwarded (its mock
5145 // list then takes the view as invalid, which is what that device was told).
5146 Mock* other_mock = nullptr;
5147 void* other = make_device(other_mock, 9, true, true, true);
5148 EXPECT(other);
5149 void* other_allocator = nullptr;
5150 EXPECT(hr_of(raw(other, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&allocator_iid), word(&other_allocator))) == S_OK);
5151 void* other_list = nullptr;
5152 EXPECT(hr_of(raw(other, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(other_allocator), 0, word(&gcl_iid),
5153 word(&other_list))) == S_OK);
5154 Mock* const other_real = reinterpret_cast<Mock*>(xs::list_proxy_real_list(other_list));
5155 raw(other_list, 52, rtv_none, word(color), 0, 0);
5156 EXPECT(other_real->calls[48] == 1 && other_real->args[48][0] == rtv_none);
5157
5158 EXPECT(release(other_list) == 0 && other_real->refs == 0);
5159 EXPECT(release(other_allocator) == 0);
5160 EXPECT(release(other) == 0 && other_mock->refs == 0);
5161 EXPECT(release(list) == 0 && real->refs == 0);
5162 EXPECT(release(allocator) == 0);
5163 EXPECT(release(device) == 0 && mock->refs == 0);
5164 g_mock_null_rtv_count = 0;
5165 std::printf("%s: list slot 146 turns texture barriers with no resource into global barriers (valid groups pass "
5166 "unchanged, unreadable ones are refused whole) and slot 52 skips the clear of an RTV made with no "
5167 "resource; the list stays valid\n",
5168 g_label);
5169 return 0;
5170}
5171
4833// ---- 11. Presentation handler wiring (device slots 78–81 + queue PresentX/SuspendX/ResumeX) ---- 5172// ---- 11. Presentation handler wiring (device slots 78–81 + queue PresentX/SuspendX/ResumeX) ----
4834 5173
4835struct MockPresenter { 5174struct MockPresenter {
@@ -4980,6 +5319,7 @@ int main(int argc, char** argv) {
4980 check_slot74() || 5319 check_slot74() ||
4981 check_xbox_queue_slots() || 5320 check_xbox_queue_slots() ||
4982 check_list_cpu_handles() || 5321 check_list_cpu_handles() ||
5322 check_console_null_barrier_and_clear() ||
4983 check_presentation_wiring() || check_queue_copy_page_mappings()) 5323 check_presentation_wiring() || check_queue_copy_page_mappings())
4984 return 1; 5324 return 1;
4985 if (check_placed_resource_x() || check_depth_provider_refusal()) return 1; 5325 if (check_placed_resource_x() || check_depth_provider_refusal()) return 1;