diff options
| author | Aslan2142 <jan.trencansky@protonmail.com> | 2026-11-26 15:41:00 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-26 15:41:00 +0100 |
| commit | fbf100b1b10e391625585fe6a8bf4e653662ca9a (patch) | |
| tree | 497fe3bc8ef8b45d1ac8c68fa9f85196d08f11ad /runtime | |
| parent | 73516a2902a9872e4d21d1bdbbde4e26059497c5 (diff) | |
| parent | 484b21262a21f9a99148b89ad2458b389faf7bd1 (diff) | |
Merge pull request #2350 from aslan2142/linux-amd-world
Self-merge by a maintainer, on purpose: current main does not get through the world on Linux/AMD, and this brings the regression fixes (the single-wave round-loop fallback of 9f98dcc61, the wave64 choice driven by llvmpipe) together with eleven PRs the world run needed. Tested on main 73516a290: translator suite 500 files / 6,365 tests, 0 failed; 513 standard-library test files pass; check_no_game_data clean on 80 files; Linux ctest 112/112; Wine suite (clang-cl + xwin, RDNA2 iGPU, RADV) with no test going from pass to fail. Not tested: native Windows, NVIDIA. The included PRs are closed in favour of this one with credit to their authors. AI-assisted (Claude Code, Claude Opus 5.5 and Claude Fable 5.2).
Diffstat (limited to 'runtime')
54 files changed, 5695 insertions, 310 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 10ee582b1..b8cef55c6 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt | |||
| @@ -158,6 +158,54 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 158 | message(FATAL_ERROR "LEONIDA_REQUIRE_XMA2_DECODER is enabled, but the Rust XMA2 decoder is unavailable") | 158 | message(FATAL_ERROR "LEONIDA_REQUIRE_XMA2_DECODER is enabled, but the Rust XMA2 decoder is unavailable") |
| 159 | endif() | 159 | endif() |
| 160 | 160 | ||
| 161 | # Rust Opus decoder (runtime/opus_decoder), the same pattern as the XMA2 decoder: cargo at | ||
| 162 | # configure time, a prebuilt -DLEONIDA_OPUS_DECODER_LIB, or the silent path in xapu_queue.cpp. | ||
| 163 | option(LEONIDA_REQUIRE_OPUS_DECODER "Fail configure if the Rust Opus decoder is unavailable" OFF) | ||
| 164 | set(LEONIDA_OPUS_DECODER_LIB "" CACHE FILEPATH | ||
| 165 | "Prebuilt leonida_opus_decoder.lib (skips running cargo at configure time)") | ||
| 166 | include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/opus_decoder.cmake") | ||
| 167 | leonida_resolve_prebuilt_opus_decoder("${LEONIDA_OPUS_DECODER_LIB}" "${CMAKE_BINARY_DIR}" _opus_lib_resolved) | ||
| 168 | if(_opus_lib_resolved) | ||
| 169 | message(STATUS "Using prebuilt Rust Opus decoder: ${_opus_lib_resolved}") | ||
| 170 | else() | ||
| 171 | if(NOT LEONIDA_CARGO) | ||
| 172 | find_program(LEONIDA_CARGO cargo) | ||
| 173 | endif() | ||
| 174 | if(LEONIDA_CARGO) | ||
| 175 | set(_opus_target x86_64-pc-windows-msvc) | ||
| 176 | set(_opus_target_dir ${CMAKE_BINARY_DIR}/opus_decoder) | ||
| 177 | set(_opus_lib ${_opus_target_dir}/${_opus_target}/release/leonida_opus_decoder.lib) | ||
| 178 | set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS | ||
| 179 | ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.toml | ||
| 180 | ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.lock | ||
| 181 | ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/src/lib.rs) | ||
| 182 | execute_process( | ||
| 183 | COMMAND ${LEONIDA_CARGO} build --release --locked --target ${_opus_target} | ||
| 184 | --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.toml | ||
| 185 | --target-dir ${_opus_target_dir} | ||
| 186 | TIMEOUT 300 | ||
| 187 | RESULT_VARIABLE _opus_result) | ||
| 188 | if(_opus_result STREQUAL "0" AND EXISTS "${_opus_lib}") | ||
| 189 | set(_opus_lib_resolved "${_opus_lib}") | ||
| 190 | else() | ||
| 191 | message(WARNING "cargo build of runtime/opus_decoder failed: the XAPU Opus path will be silent") | ||
| 192 | endif() | ||
| 193 | else() | ||
| 194 | message(STATUS "cargo not found: runtime/opus_decoder not built, the XAPU Opus path will be silent") | ||
| 195 | endif() | ||
| 196 | endif() | ||
| 197 | if(_opus_lib_resolved) | ||
| 198 | add_library(leonida_opus_decoder STATIC IMPORTED) | ||
| 199 | set_target_properties(leonida_opus_decoder PROPERTIES | ||
| 200 | IMPORTED_LOCATION "${_opus_lib_resolved}" | ||
| 201 | INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder" | ||
| 202 | INTERFACE_COMPILE_DEFINITIONS LEONIDA_HAVE_OPUS_DECODER=1 | ||
| 203 | INTERFACE_LINK_LIBRARIES "kernel32;ntdll;userenv;ws2_32;dbghelp;synchronization") | ||
| 204 | endif() | ||
| 205 | if(LEONIDA_REQUIRE_OPUS_DECODER AND NOT TARGET leonida_opus_decoder) | ||
| 206 | message(FATAL_ERROR "LEONIDA_REQUIRE_OPUS_DECODER is enabled, but the Rust Opus decoder is unavailable") | ||
| 207 | endif() | ||
| 208 | |||
| 161 | find_package(Python3 COMPONENTS Interpreter REQUIRED) | 209 | find_package(Python3 COMPONENTS Interpreter REQUIRED) |
| 162 | set(bcpack_tools "${CMAKE_CURRENT_SOURCE_DIR}/../tools") | 210 | set(bcpack_tools "${CMAKE_CURRENT_SOURCE_DIR}/../tools") |
| 163 | set(bcpack_tables "${CMAKE_CURRENT_BINARY_DIR}/bcpack_tables.inc") | 211 | set(bcpack_tables "${CMAKE_CURRENT_BINARY_DIR}/bcpack_tables.inc") |
| @@ -199,6 +247,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 199 | shims/com_shim.cpp | 247 | shims/com_shim.cpp |
| 200 | shims/silent_audio.cpp | 248 | shims/silent_audio.cpp |
| 201 | shims/bcrypt_rng.cpp | 249 | shims/bcrypt_rng.cpp |
| 250 | shims/xapu_queue.cpp | ||
| 202 | shims/xapu_chad.cpp | 251 | shims/xapu_chad.cpp |
| 203 | shims/dstorage.cpp | 252 | shims/dstorage.cpp |
| 204 | ) | 253 | ) |
| @@ -352,6 +401,9 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 352 | target_link_libraries(gta6rt PRIVATE leonida_xma2_decoder) | 401 | target_link_libraries(gta6rt PRIVATE leonida_xma2_decoder) |
| 353 | target_link_libraries(acphal_test PRIVATE leonida_xma2_decoder) | 402 | target_link_libraries(acphal_test PRIVATE leonida_xma2_decoder) |
| 354 | endif() | 403 | endif() |
| 404 | if(TARGET leonida_opus_decoder) | ||
| 405 | target_link_libraries(gta6rt PRIVATE leonida_opus_decoder) | ||
| 406 | endif() | ||
| 355 | 407 | ||
| 356 | # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for | 408 | # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for |
| 357 | # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. | 409 | # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. |
| @@ -382,9 +434,11 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 382 | target_link_options(dstorage_test PRIVATE /OPT:NOREF) | 434 | target_link_options(dstorage_test PRIVATE /OPT:NOREF) |
| 383 | target_link_libraries(dstorage_test PRIVATE gta6rt_bcpack psapi) | 435 | target_link_libraries(dstorage_test PRIVATE gta6rt_bcpack psapi) |
| 384 | 436 | ||
| 385 | # xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test. | 437 | # xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test; Opus |
| 438 | # frame counts from hand-made packets. | ||
| 386 | add_executable(xapu_chad_test | 439 | add_executable(xapu_chad_test |
| 387 | test/xapu_chad_test.cpp | 440 | test/xapu_chad_test.cpp |
| 441 | shims/xapu_queue.cpp | ||
| 388 | shims/xapu_chad.cpp | 442 | shims/xapu_chad.cpp |
| 389 | shims/registry.cpp | 443 | shims/registry.cpp |
| 390 | ) | 444 | ) |
| @@ -393,6 +447,20 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 393 | target_compile_options(xapu_chad_test PRIVATE /W4 /permissive- /utf-8) | 447 | target_compile_options(xapu_chad_test PRIVATE /W4 /permissive- /utf-8) |
| 394 | target_link_options(xapu_chad_test PRIVATE /OPT:NOREF) | 448 | target_link_options(xapu_chad_test PRIVATE /OPT:NOREF) |
| 395 | 449 | ||
| 450 | if(TARGET leonida_opus_decoder) | ||
| 451 | # xapu_queue.cpp with the decoder compiled in, against the generated Opus tone. | ||
| 452 | add_executable(xapu_opus_test | ||
| 453 | test/xapu_opus_test.cpp | ||
| 454 | shims/xapu_queue.cpp | ||
| 455 | shims/registry.cpp | ||
| 456 | ) | ||
| 457 | target_include_directories(xapu_opus_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) | ||
| 458 | target_compile_definitions(xapu_opus_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | ||
| 459 | target_compile_options(xapu_opus_test PRIVATE /W4 /permissive- /utf-8) | ||
| 460 | target_link_options(xapu_opus_test PRIVATE /OPT:NOREF) | ||
| 461 | target_link_libraries(xapu_opus_test PRIVATE leonida_opus_decoder) | ||
| 462 | endif() | ||
| 463 | |||
| 396 | # The boot stack's earlier xapu.dll and chad.dll shims (shims/xapu.cpp, shims/chad.cpp), which gta6rt no longer | 464 | # The boot stack's earlier xapu.dll and chad.dll shims (shims/xapu.cpp, shims/chad.cpp), which gta6rt no longer |
| 397 | # links (it serves both DLLs from xapu_chad.cpp): their ABI tests stay as tests of those files. | 465 | # links (it serves both DLLs from xapu_chad.cpp): their ABI tests stay as tests of those files. |
| 398 | # xapu shim ABI test: resolves the registered xapu.dll exports through the registry. | 466 | # xapu shim ABI test: resolves the registered xapu.dll exports through the registry. |
| @@ -814,6 +882,9 @@ if(BUILD_TESTING) | |||
| 814 | add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) | 882 | add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) |
| 815 | add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test) | 883 | add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test) |
| 816 | 884 | ||
| 885 | add_executable(heavy_pipeline_cache_test test/heavy_pipeline_cache_test.cpp) | ||
| 886 | add_test(NAME heavy_pipeline_cache COMMAND heavy_pipeline_cache_test) | ||
| 887 | |||
| 817 | # The per-pipeline journal files compute pipelines are kept in: naming, header check, atomic replacement. | 888 | # 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) | 889 | add_executable(pipeline_cache_journal_test test/pipeline_cache_journal_test.cpp) |
| 819 | add_test(NAME pipeline_cache_journal COMMAND pipeline_cache_journal_test) | 890 | add_test(NAME pipeline_cache_journal COMMAND pipeline_cache_journal_test) |
| @@ -1434,6 +1505,8 @@ if(BUILD_TESTING) | |||
| 1434 | # Which SPIR-V modules declare a storage image or buffer they may write (src/spirv_stores.h), on hand-built words. | 1505 | # Which SPIR-V modules declare a storage image or buffer they may write (src/spirv_stores.h), on hand-built words. |
| 1435 | add_executable(spirv_stores_test test/spirv_stores_test.cpp) | 1506 | add_executable(spirv_stores_test test/spirv_stores_test.cpp) |
| 1436 | add_test(NAME spirv_stores COMMAND spirv_stores_test) | 1507 | add_test(NAME spirv_stores COMMAND spirv_stores_test) |
| 1508 | add_executable(list_value_wait_budget_test test/list_value_wait_budget_test.cpp) | ||
| 1509 | add_test(NAME list_value_wait_budget COMMAND list_value_wait_budget_test) | ||
| 1437 | add_executable(shader_fixture_path_test test/shader_fixture_path_test.cpp) | 1510 | add_executable(shader_fixture_path_test test/shader_fixture_path_test.cpp) |
| 1438 | add_test(NAME shader_fixture_path COMMAND shader_fixture_path_test) | 1511 | add_test(NAME shader_fixture_path COMMAND shader_fixture_path_test) |
| 1439 | add_executable(resource_tiling_test test/resource_tiling_test.cpp) | 1512 | add_executable(resource_tiling_test test/resource_tiling_test.cpp) |
| @@ -1596,6 +1669,9 @@ if(BUILD_TESTING) | |||
| 1596 | if(WIN32 AND TARGET xapu_chad_test) | 1669 | if(WIN32 AND TARGET xapu_chad_test) |
| 1597 | add_test(NAME xapu_chad COMMAND xapu_chad_test) | 1670 | add_test(NAME xapu_chad COMMAND xapu_chad_test) |
| 1598 | endif() | 1671 | endif() |
| 1672 | if(WIN32 AND TARGET xapu_opus_test) | ||
| 1673 | add_test(NAME xapu_opus COMMAND xapu_opus_test) | ||
| 1674 | endif() | ||
| 1599 | if(WIN32 AND TARGET xapu_test) | 1675 | if(WIN32 AND TARGET xapu_test) |
| 1600 | add_test(NAME xapu COMMAND xapu_test) | 1676 | add_test(NAME xapu COMMAND xapu_test) |
| 1601 | endif() | 1677 | endif() |
| @@ -3656,6 +3732,18 @@ if(TARGET Vulkan::Headers) | |||
| 3656 | target_compile_options(d3d12_unmapped_vsharp_test PRIVATE /W4 /permissive- /utf-8) | 3732 | target_compile_options(d3d12_unmapped_vsharp_test PRIVATE /W4 /permissive- /utf-8) |
| 3657 | add_test(NAME d3d12_unmapped_vsharp COMMAND d3d12_unmapped_vsharp_test) | 3733 | add_test(NAME d3d12_unmapped_vsharp COMMAND d3d12_unmapped_vsharp_test) |
| 3658 | set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_CONSOLE_FIX_US=0") | 3734 | set_tests_properties(d3d12_unmapped_vsharp PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_CONSOLE_FIX_US=0") |
| 3735 | # The host-RAM mirror of a console heap's GPU copy (src/console_heap_copy.h) agrees with the copy through the first | ||
| 3736 | # refresh, title writes and a filtered release sweep; run again without the mirror, where the copy must not change. | ||
| 3737 | add_executable(d3d12_console_heap_mirror_test test/d3d12_console_heap_mirror_test.cpp shims/d3d12_xs_device.cpp) | ||
| 3738 | target_link_libraries(d3d12_console_heap_mirror_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) | ||
| 3739 | target_compile_definitions(d3d12_console_heap_mirror_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) | ||
| 3740 | target_compile_options(d3d12_console_heap_mirror_test PRIVATE /W4 /permissive- /utf-8) | ||
| 3741 | add_test(NAME d3d12_console_heap_mirror COMMAND d3d12_console_heap_mirror_test) | ||
| 3742 | set_tests_properties(d3d12_console_heap_mirror PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT | ||
| 3743 | "LEONIDA_CONSOLE_FIX_US=0;LEONIDA_CONSOLE_RELEASE_FILTER=1;LEONIDA_HEAP_MIRROR_CHECK=1") | ||
| 3744 | add_test(NAME d3d12_console_heap_mirror_off COMMAND d3d12_console_heap_mirror_test) | ||
| 3745 | set_tests_properties(d3d12_console_heap_mirror_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT | ||
| 3746 | "LEONIDA_CONSOLE_FIX_US=0;LEONIDA_CONSOLE_RELEASE_FILTER=1;LEONIDA_HEAP_MIRROR=0") | ||
| 3659 | add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp) | 3747 | add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp) |
| 3660 | target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) | 3748 | target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) |
| 3661 | target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | 3749 | target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) |
| @@ -3824,6 +3912,13 @@ if(TARGET Vulkan::Headers) | |||
| 3824 | # is written zero-size, and a dispatch through it reads zeros. | 3912 | # is written zero-size, and a dispatch through it reads zeros. |
| 3825 | add_test(NAME d3d12_title_window_cap COMMAND d3d12_title_va_test --window-cap) | 3913 | add_test(NAME d3d12_title_window_cap COMMAND d3d12_title_va_test --window-cap) |
| 3826 | set_tests_properties(d3d12_title_window_cap PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_TITLE_WINDOWS_MB=0") | 3914 | set_tests_properties(d3d12_title_window_cap PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_TITLE_WINDOWS_MB=0") |
| 3915 | # A window is a read-side mirror refreshed before every submission: what a shader writes into it goes back to | ||
| 3916 | # the title's pages at the next refresh, and the title's own newer words still win (#1537, WRITE_INVALID). | ||
| 3917 | add_test(NAME d3d12_title_window_write_back COMMAND d3d12_title_va_test --window-writeback) | ||
| 3918 | set_tests_properties(d3d12_title_window_write_back PROPERTIES SKIP_RETURN_CODE 77) | ||
| 3919 | # The same return copy for a slot-133 buffer's shadow (the write-back of a compute result the title reads again). | ||
| 3920 | add_test(NAME d3d12_placed_write_back COMMAND d3d12_title_va_test --placed-writeback) | ||
| 3921 | set_tests_properties(d3d12_placed_write_back PROPERTIES SKIP_RETURN_CODE 77) | ||
| 3827 | add_test(NAME d3d12_api_descriptor_copy COMMAND d3d12_title_va_test --api-descriptor-copy) | 3922 | add_test(NAME d3d12_api_descriptor_copy COMMAND d3d12_title_va_test --api-descriptor-copy) |
| 3828 | set_tests_properties(d3d12_api_descriptor_copy PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") | 3923 | set_tests_properties(d3d12_api_descriptor_copy PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") |
| 3829 | add_test(NAME d3d12_api_descriptor_copy_off COMMAND d3d12_title_va_test --api-descriptor-copy-off) | 3924 | add_test(NAME d3d12_api_descriptor_copy_off COMMAND d3d12_title_va_test --api-descriptor-copy-off) |
| @@ -4179,6 +4274,11 @@ if(TARGET Vulkan::Headers) | |||
| 4179 | target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) | 4274 | target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) |
| 4180 | add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) | 4275 | add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) |
| 4181 | set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77) | 4276 | set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77) |
| 4277 | # The same draws through the heavy pipeline cache (src/heavy_pipeline_cache.h): every build first asks the | ||
| 4278 | # offline cache without compiling, and a miss is built against the heavy cache in a folder of its own. | ||
| 4279 | add_test(NAME d3d12_mesh_heavy_cache COMMAND d3d12_mesh_test) | ||
| 4280 | set_tests_properties(d3d12_mesh_heavy_cache PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT | ||
| 4281 | "LEONIDA_HEAVY_PIPELINE_CACHE_MS=1;LEONIDA_PIPELINE_CACHE_DIR=${CMAKE_CURRENT_BINARY_DIR}/heavy_cache_test") | ||
| 4182 | else() | 4282 | else() |
| 4183 | message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built") | 4283 | message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built") |
| 4184 | endif() | 4284 | endif() |
| @@ -4579,6 +4679,12 @@ if(TARGET Vulkan::Headers) | |||
| 4579 | target_compile_options(arena_blocks_test PRIVATE /W4 /permissive- /utf-8) | 4679 | target_compile_options(arena_blocks_test PRIVATE /W4 /permissive- /utf-8) |
| 4580 | endif() | 4680 | endif() |
| 4581 | add_test(NAME arena_blocks COMMAND arena_blocks_test) | 4681 | add_test(NAME arena_blocks COMMAND arena_blocks_test) |
| 4682 | # The address guard's page table (src/address_guard.h; docs/d3d12_vulkan.md, "Address guard"). | ||
| 4683 | add_executable(address_guard_test test/address_guard_test.cpp) | ||
| 4684 | if(WIN32 AND MSVC) | ||
| 4685 | target_compile_options(address_guard_test PRIVATE /W4 /permissive- /utf-8) | ||
| 4686 | endif() | ||
| 4687 | add_test(NAME address_guard COMMAND address_guard_test) | ||
| 4582 | add_executable(title_window_plan_bounds_test test/title_window_plan_bounds_test.cpp) | 4688 | add_executable(title_window_plan_bounds_test test/title_window_plan_bounds_test.cpp) |
| 4583 | if(WIN32 AND MSVC) | 4689 | if(WIN32 AND MSVC) |
| 4584 | target_compile_options(title_window_plan_bounds_test PRIVATE /W4 /permissive- /utf-8) | 4690 | target_compile_options(title_window_plan_bounds_test PRIVATE /W4 /permissive- /utf-8) |
| @@ -4590,6 +4696,12 @@ if(TARGET Vulkan::Headers) | |||
| 4590 | target_compile_options(console_heap_vsharp_slots_test PRIVATE /W4 /permissive- /utf-8) | 4696 | target_compile_options(console_heap_vsharp_slots_test PRIVATE /W4 /permissive- /utf-8) |
| 4591 | endif() | 4697 | endif() |
| 4592 | add_test(NAME console_heap_vsharp_slots COMMAND console_heap_vsharp_slots_test) | 4698 | add_test(NAME console_heap_vsharp_slots COMMAND console_heap_vsharp_slots_test) |
| 4699 | # Host-RAM mirror of a console resource heap's GPU copy (src/console_heap_copy.h). | ||
| 4700 | add_executable(console_heap_copy_test test/console_heap_copy_test.cpp) | ||
| 4701 | if(WIN32 AND MSVC) | ||
| 4702 | target_compile_options(console_heap_copy_test PRIVATE /W4 /permissive- /utf-8) | ||
| 4703 | endif() | ||
| 4704 | add_test(NAME console_heap_copy COMMAND console_heap_copy_test) | ||
| 4593 | # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. | 4705 | # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. |
| 4594 | add_executable(vk_host_texture_order_test test/vk_host_texture_order_test.cpp) | 4706 | add_executable(vk_host_texture_order_test test/vk_host_texture_order_test.cpp) |
| 4595 | target_link_libraries(vk_host_texture_order_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) | 4707 | 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 23a7811ab..84190039c 100644 --- a/runtime/README.md +++ b/runtime/README.md | |||
| @@ -353,7 +353,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | |||
| 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`). | | 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)). | | 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)). | |
| 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. | | 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. | |
| 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). | | 356 | | `LEONIDA_INPUT_SCRIPT` | unset | Timed pad presses, `button@seconds` separated by commas (`a@70,a@85,start@120`), each held 300 ms or its own `button@seconds:hold`; the clock starts with the shim. Works with and without SDL3: with SDL3 it drives the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), without SDL3 one scripted pad that is the only device. Controllers and the keyboard pad still need SDL3. Format and buttons in [docs/gameinput.md](../docs/gameinput.md#environment-variables). | |
| 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. | | 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. | |
| 358 | | `LEONIDA_LOG_ALLOCINFO` | unset | *Diagnostic.* `1` logs every device slot 25 call (`GetResourceAllocationInfo`) with its thread, description and sizes (`shims/d3d12_xs_device.cpp`). | | 358 | | `LEONIDA_LOG_ALLOCINFO` | unset | *Diagnostic.* `1` logs every device slot 25 call (`GetResourceAllocationInfo`) with its thread, description and sizes (`shims/d3d12_xs_device.cpp`). | |
| 359 | | `LEONIDA_LOG_EXE_PIPELINES` | unset | *Diagnostic.* When set, one line per distinct graphics pipeline that uses a program translated from the executable's inline containers. | | 359 | | `LEONIDA_LOG_EXE_PIPELINES` | unset | *Diagnostic.* When set, one line per distinct graphics pipeline that uses a program translated from the executable's inline containers. | |
| @@ -382,6 +382,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | |||
| 382 | | `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. | | 382 | | `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. | |
| 383 | | `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. | | 383 | | `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. | |
| 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. | | 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. | |
| 385 | | `LEONIDA_GEOMETRY_HOST` | unset | Where the geometry copies (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) live. Unset or `0`: device-local memory through the BAR while the driver gives it (several GB of VRAM in a world run). `1`: system memory outside VRAM, write-back where the device offers a cached host type; `2`: system memory, write-combined. The GPU then reads every vertex and index of a copy over the bus, which can cost frame time in geometry-heavy passes. A device whose host-visible memory is all device-local (an integrated GPU) keeps its types. The choice is logged once and in the `geometry buffers` line. | | ||
| 386 | | `LEONIDA_GEOMETRY_REMAP_RELEASE` | on | A remap of physical pages (`XMemMapPhysicalPages`, the scatter call, `CopyPageMappingsBatchX`) that gives a page another frame, or none, retires the geometry copies over it, as freeing or unmapping it does: the title streams by remapping its pools' frames, and the copies of what they held were kept for the device's life. A retired copy is copied once more from the new pages if they are readable, then freed once every submission that may name it has finished. A page mapped again to the frame it had is no change. `0` turns it off. | | ||
| 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. | | 387 | | `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. | |
| 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`. | | 388 | | `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. | | 389 | | `LEONIDA_TITLE_EVERY_BUDGET_US` | `0` | Microseconds one pass over the textures filled from the title's memory may spend on the textures it visits every pass (mapped by the title, or known stale), resuming where the last pass stopped; the texture that crosses the limit is finished. A mapped texture never filled yet is visited first whatever the limit. `0` visits all of them every pass. It limits the synchronous pass only: with `LEONIDA_TEXTURE_REFRESH_ASYNC=1` the pass runs on the refresh worker, and the limit does not apply. | |
| @@ -423,6 +425,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | |||
| 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. | | 425 | | `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. | | 426 | | `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. | | 427 | | `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. | |
| 428 | | `LEONIDA_HEAP_MIRROR` | `1` | `0`: no host-RAM mirror of a console resource heap's copy in the arena (`src/console_heap_copy.h`). With the mirror, the CPU reads of the copy (the `LEONIDA_CONSOLE_RELEASE_FILTER` sweep) come from host RAM, not uncached device memory across PCIe. A copy in an import of host memory, and one the `LEONIDA_CONSOLE_HEAP_GPU` pass writes, never has one. | | ||
| 429 | | `LEONIDA_HEAP_MIRROR_CHECK` | unset | `1`: at every release sweep the mirror is compared with the copy (a read of the whole copy); the first differing slots are logged, and the heap log line counts the checks and differing slots. | | ||
| 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. | | 430 | | `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. | | 431 | | `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. | | 432 | | `LEONIDA_SHADOW_GPU_MB` | `1024` | With `LEONIDA_SHADOW_GPU=1`, the MiB of title memory imported for those copies at most. | |
diff --git a/runtime/cmake/opus_decoder.cmake b/runtime/cmake/opus_decoder.cmake new file mode 100644 index 000000000..1286b15fa --- /dev/null +++ b/runtime/cmake/opus_decoder.cmake | |||
| @@ -0,0 +1,23 @@ | |||
| 1 | # Resolves -DLEONIDA_OPUS_DECODER_LIB=<path> for runtime/CMakeLists.txt. | ||
| 2 | # | ||
| 3 | # When LEONIDA_OPUS_DECODER_LIB is set, the runtime links that prebuilt static library directly and | ||
| 4 | # skips running cargo at configure time. A value that does not name an existing file is a configure | ||
| 5 | # error rather than a silent fallback to silent XAPU output. | ||
| 6 | function(leonida_resolve_prebuilt_opus_decoder lib_input base_dir out_var) | ||
| 7 | if(NOT lib_input) | ||
| 8 | set(${out_var} "" PARENT_SCOPE) | ||
| 9 | return() | ||
| 10 | endif() | ||
| 11 | if(IS_ABSOLUTE "${lib_input}") | ||
| 12 | set(_resolved "${lib_input}") | ||
| 13 | else() | ||
| 14 | cmake_path(ABSOLUTE_PATH lib_input BASE_DIRECTORY "${base_dir}" NORMALIZE OUTPUT_VARIABLE _resolved) | ||
| 15 | endif() | ||
| 16 | if(EXISTS "${_resolved}" AND NOT IS_DIRECTORY "${_resolved}") | ||
| 17 | set(${out_var} "${_resolved}" PARENT_SCOPE) | ||
| 18 | else() | ||
| 19 | message(FATAL_ERROR | ||
| 20 | "LEONIDA_OPUS_DECODER_LIB does not point to an existing file: ${_resolved} " | ||
| 21 | "(pass the path to leonida_opus_decoder.lib or leave it empty to build with cargo)") | ||
| 22 | endif() | ||
| 23 | endfunction() | ||
diff --git a/runtime/opus_decoder/Cargo.lock b/runtime/opus_decoder/Cargo.lock new file mode 100644 index 000000000..1659ab14e --- /dev/null +++ b/runtime/opus_decoder/Cargo.lock | |||
| @@ -0,0 +1,16 @@ | |||
| 1 | # This file is automatically @generated by Cargo. | ||
| 2 | # It is not intended for manual editing. | ||
| 3 | version = 4 | ||
| 4 | |||
| 5 | [[package]] | ||
| 6 | name = "leonida-opus-decoder" | ||
| 7 | version = "0.1.0" | ||
| 8 | dependencies = [ | ||
| 9 | "opus-pure", | ||
| 10 | ] | ||
| 11 | |||
| 12 | [[package]] | ||
| 13 | name = "opus-pure" | ||
| 14 | version = "0.2.5" | ||
| 15 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 16 | checksum = "2da6dcc20af557d030b6f206e75c764bcda8c28a5bd03c73935c7e8fcf5f4f4a" | ||
diff --git a/runtime/opus_decoder/Cargo.toml b/runtime/opus_decoder/Cargo.toml new file mode 100644 index 000000000..e3ed59bc3 --- /dev/null +++ b/runtime/opus_decoder/Cargo.toml | |||
| @@ -0,0 +1,16 @@ | |||
| 1 | [package] | ||
| 2 | name = "leonida-opus-decoder" | ||
| 3 | version = "0.1.0" | ||
| 4 | edition = "2021" | ||
| 5 | license = "GPL-3.0-or-later" | ||
| 6 | publish = false | ||
| 7 | |||
| 8 | [lib] | ||
| 9 | name = "leonida_opus_decoder" | ||
| 10 | crate-type = ["staticlib", "rlib"] | ||
| 11 | |||
| 12 | [dependencies] | ||
| 13 | opus-pure = "0.2.4" | ||
| 14 | |||
| 15 | [profile.release] | ||
| 16 | panic = "unwind" | ||
diff --git a/runtime/opus_decoder/README.md b/runtime/opus_decoder/README.md new file mode 100644 index 000000000..2b516e496 --- /dev/null +++ b/runtime/opus_decoder/README.md | |||
| @@ -0,0 +1,33 @@ | |||
| 1 | # Opus decoder C ABI | ||
| 2 | |||
| 3 | This crate exposes a C ABI around the BSD-3-Clause `opus-pure` package for the console audio | ||
| 4 | decoder (`xapu.dll`). The command protocol lives in `runtime/shims/xapu_chad.cpp`; this crate only | ||
| 5 | decodes one Opus packet into interleaved f32 PCM, resets the decoder, and (for tests) encodes a | ||
| 6 | synthetic tone. | ||
| 7 | |||
| 8 | ## Build | ||
| 9 | |||
| 10 | ```sh | ||
| 11 | cargo fmt --manifest-path runtime/opus_decoder/Cargo.toml -- --check | ||
| 12 | cargo test --manifest-path runtime/opus_decoder/Cargo.toml --locked | ||
| 13 | cargo build --release --manifest-path runtime/opus_decoder/Cargo.toml --locked | ||
| 14 | ``` | ||
| 15 | |||
| 16 | `runtime/CMakeLists.txt` builds this crate for `x86_64-pc-windows-msvc` at configure time when | ||
| 17 | `cargo` is on `PATH` and links it into `gta6rt` and `xapu_chad_test` with | ||
| 18 | `LEONIDA_HAVE_OPUS_DECODER` defined. The first build fetches `opus-pure` from crates.io. Set | ||
| 19 | `CARGO_NET_OFFLINE=true` for a configure that uses only the local Cargo cache. | ||
| 20 | |||
| 21 | Without `cargo`, when the build fails, or with the `cl.exe` fallback of `scripts/build_runtime.ps1`, | ||
| 22 | the XAPU path stays silent. Use `-DLEONIDA_REQUIRE_OPUS_DECODER=ON` to require the decoder in a | ||
| 23 | CMake build. | ||
| 24 | |||
| 25 | To link an already-built `leonida_opus_decoder.lib` without invoking `cargo` during CMake | ||
| 26 | configure, pass `-DLEONIDA_OPUS_DECODER_LIB=<path>`. | ||
| 27 | |||
| 28 | ## Facts and credit | ||
| 29 | |||
| 30 | The `xapu.dll` command protocol (connect input/output, per-stream command budget, activate / | ||
| 31 | process / reset / deactivate, result order) follows Marvisak/VIctory | ||
| 32 | `crates/victory-hle/src/modules/apu.rs` (GPL-3.0-or-later), which this repository already credits for | ||
| 33 | other modules. `opus-pure` is BSD-3-Clause and stays a dependency; no code from it is copied. | ||
diff --git a/runtime/opus_decoder/leonida_opus_decoder.h b/runtime/opus_decoder/leonida_opus_decoder.h new file mode 100644 index 000000000..d5473510d --- /dev/null +++ b/runtime/opus_decoder/leonida_opus_decoder.h | |||
| @@ -0,0 +1,44 @@ | |||
| 1 | #ifndef LEONIDA_OPUS_DECODER_H | ||
| 2 | #define LEONIDA_OPUS_DECODER_H | ||
| 3 | |||
| 4 | #include <stddef.h> | ||
| 5 | #include <stdint.h> | ||
| 6 | |||
| 7 | #ifdef __cplusplus | ||
| 8 | extern "C" { | ||
| 9 | #endif | ||
| 10 | |||
| 11 | /* 120 ms at 48 kHz: the longest Opus packet, in samples per channel. */ | ||
| 12 | #define LEONIDA_OPUS_MAX_FRAMES 5760u | ||
| 13 | |||
| 14 | typedef struct LeonidaOpusDecoder LeonidaOpusDecoder; | ||
| 15 | |||
| 16 | enum LeonidaOpusStatus { | ||
| 17 | LEONIDA_OPUS_OK = 0, | ||
| 18 | LEONIDA_OPUS_INVALID_ARGUMENT = 1, | ||
| 19 | LEONIDA_OPUS_INVALID_FORMAT = 2, | ||
| 20 | LEONIDA_OPUS_DECODER_FAILURE = 3, | ||
| 21 | LEONIDA_OPUS_OUT_OF_MEMORY = 4, | ||
| 22 | LEONIDA_OPUS_PANIC = 5, | ||
| 23 | LEONIDA_OPUS_BUFFER_TOO_SMALL = 6, | ||
| 24 | }; | ||
| 25 | |||
| 26 | int32_t leonida_opus_decoder_create(uint32_t sample_rate, uint32_t channels, | ||
| 27 | LeonidaOpusDecoder **out_decoder); | ||
| 28 | uint32_t leonida_opus_decoder_channels(const LeonidaOpusDecoder *decoder); | ||
| 29 | int32_t leonida_opus_decode_packet(LeonidaOpusDecoder *decoder, | ||
| 30 | const uint8_t *input, size_t input_len, | ||
| 31 | float *out, size_t out_capacity_frames, | ||
| 32 | uint32_t *out_frames); | ||
| 33 | int32_t leonida_opus_decoder_reset(LeonidaOpusDecoder *decoder); | ||
| 34 | void leonida_opus_decoder_destroy(LeonidaOpusDecoder *decoder); | ||
| 35 | /* Test helper: encodes frame_count interleaved f32 frames to one packet at 48 kHz. */ | ||
| 36 | int32_t leonida_opus_encode_test(const float *input, uint32_t frame_count, | ||
| 37 | uint32_t channels, uint8_t *out, | ||
| 38 | size_t out_capacity, size_t *out_len); | ||
| 39 | |||
| 40 | #ifdef __cplusplus | ||
| 41 | } | ||
| 42 | #endif | ||
| 43 | |||
| 44 | #endif | ||
diff --git a/runtime/opus_decoder/src/lib.rs b/runtime/opus_decoder/src/lib.rs new file mode 100644 index 000000000..1e6c7dc83 --- /dev/null +++ b/runtime/opus_decoder/src/lib.rs | |||
| @@ -0,0 +1,244 @@ | |||
| 1 | #![deny(unsafe_op_in_unsafe_fn)] | ||
| 2 | |||
| 3 | //! C ABI around the pure-Rust `opus-pure` decoder, for the console audio decoder (`xapu.dll`). | ||
| 4 | //! | ||
| 5 | //! The command protocol lives in `runtime/shims/xapu_chad.cpp`; this crate only turns one Opus | ||
| 6 | //! packet into interleaved f32 PCM, resets the decoder, and (for tests) encodes a synthetic tone. | ||
| 7 | //! `opus-pure` is BSD-3-Clause; this wrapper is GPL-3.0-or-later, like the rest of the runtime. | ||
| 8 | |||
| 9 | use std::panic::{catch_unwind, AssertUnwindSafe}; | ||
| 10 | use std::ptr; | ||
| 11 | use std::sync::Mutex; | ||
| 12 | |||
| 13 | use opus_pure::{Application, OpusDecoder, OpusEncoder}; | ||
| 14 | |||
| 15 | pub const LEONIDA_OPUS_OK: i32 = 0; | ||
| 16 | pub const LEONIDA_OPUS_INVALID_ARGUMENT: i32 = 1; | ||
| 17 | pub const LEONIDA_OPUS_INVALID_FORMAT: i32 = 2; | ||
| 18 | pub const LEONIDA_OPUS_DECODER_FAILURE: i32 = 3; | ||
| 19 | pub const LEONIDA_OPUS_OUT_OF_MEMORY: i32 = 4; | ||
| 20 | pub const LEONIDA_OPUS_PANIC: i32 = 5; | ||
| 21 | pub const LEONIDA_OPUS_BUFFER_TOO_SMALL: i32 = 6; | ||
| 22 | |||
| 23 | /// 120 ms at 48 kHz, the longest Opus packet, in samples per channel. | ||
| 24 | pub const LEONIDA_OPUS_MAX_FRAMES: usize = 5760; | ||
| 25 | |||
| 26 | #[repr(C)] | ||
| 27 | pub struct LeonidaOpusDecoder { | ||
| 28 | decoder: Mutex<OpusDecoder>, | ||
| 29 | channels: usize, | ||
| 30 | } | ||
| 31 | |||
| 32 | #[no_mangle] | ||
| 33 | pub unsafe extern "C" fn leonida_opus_decoder_channels(decoder: *const LeonidaOpusDecoder) -> u32 { | ||
| 34 | if decoder.is_null() { | ||
| 35 | return 0; | ||
| 36 | } | ||
| 37 | unsafe { (*decoder).channels as u32 } | ||
| 38 | } | ||
| 39 | |||
| 40 | /// Creates a decoder for one mono or stereo Opus stream at `sample_rate` (the title uses 48000). | ||
| 41 | /// | ||
| 42 | /// # Safety | ||
| 43 | /// `out` must be writable for one pointer. The returned decoder must be destroyed once, after | ||
| 44 | /// every call that uses it has finished. | ||
| 45 | #[no_mangle] | ||
| 46 | pub unsafe extern "C" fn leonida_opus_decoder_create( | ||
| 47 | sample_rate: u32, | ||
| 48 | channels: u32, | ||
| 49 | out: *mut *mut LeonidaOpusDecoder, | ||
| 50 | ) -> i32 { | ||
| 51 | if out.is_null() { | ||
| 52 | return LEONIDA_OPUS_INVALID_ARGUMENT; | ||
| 53 | } | ||
| 54 | unsafe { *out = ptr::null_mut() }; | ||
| 55 | if sample_rate == 0 || sample_rate > i32::MAX as u32 || !(1..=2).contains(&channels) { | ||
| 56 | return LEONIDA_OPUS_INVALID_FORMAT; | ||
| 57 | } | ||
| 58 | match catch_unwind(AssertUnwindSafe(|| { | ||
| 59 | OpusDecoder::new(sample_rate as i32, channels as usize).map(|decoder| { | ||
| 60 | Box::new(LeonidaOpusDecoder { | ||
| 61 | decoder: Mutex::new(decoder), | ||
| 62 | channels: channels as usize, | ||
| 63 | }) | ||
| 64 | }) | ||
| 65 | })) { | ||
| 66 | Ok(Ok(decoder)) => { | ||
| 67 | unsafe { *out = Box::into_raw(decoder) }; | ||
| 68 | LEONIDA_OPUS_OK | ||
| 69 | } | ||
| 70 | Ok(Err(_)) => LEONIDA_OPUS_INVALID_FORMAT, | ||
| 71 | Err(_) => LEONIDA_OPUS_PANIC, | ||
| 72 | } | ||
| 73 | } | ||
| 74 | |||
| 75 | /// Decodes one Opus packet into `out` as interleaved f32 frames. | ||
| 76 | /// | ||
| 77 | /// # Safety | ||
| 78 | /// `decoder` must come from `leonida_opus_decoder_create`. `input` must reference `input_len` | ||
| 79 | /// readable bytes; `out` must hold `out_capacity_frames * channels` floats; `out_frames` must be | ||
| 80 | /// writable. Do not destroy the decoder concurrently with this call. | ||
| 81 | #[no_mangle] | ||
| 82 | pub unsafe extern "C" fn leonida_opus_decode_packet( | ||
| 83 | decoder: *mut LeonidaOpusDecoder, | ||
| 84 | input: *const u8, | ||
| 85 | input_len: usize, | ||
| 86 | out: *mut f32, | ||
| 87 | out_capacity_frames: usize, | ||
| 88 | out_frames: *mut u32, | ||
| 89 | ) -> i32 { | ||
| 90 | if decoder.is_null() | ||
| 91 | || input.is_null() | ||
| 92 | || input_len == 0 | ||
| 93 | || out.is_null() | ||
| 94 | || out_frames.is_null() | ||
| 95 | { | ||
| 96 | return LEONIDA_OPUS_INVALID_ARGUMENT; | ||
| 97 | } | ||
| 98 | let decoder = unsafe { &*decoder }; | ||
| 99 | let channels = decoder.channels; | ||
| 100 | let Ok(mut guard) = decoder.decoder.lock() else { | ||
| 101 | return LEONIDA_OPUS_DECODER_FAILURE; | ||
| 102 | }; | ||
| 103 | let packet = unsafe { std::slice::from_raw_parts(input, input_len) }; | ||
| 104 | let mut pcm = vec![0f32; LEONIDA_OPUS_MAX_FRAMES * channels]; | ||
| 105 | match guard.decode(packet, LEONIDA_OPUS_MAX_FRAMES, &mut pcm) { | ||
| 106 | Ok(frames) => { | ||
| 107 | if frames > out_capacity_frames { | ||
| 108 | return LEONIDA_OPUS_BUFFER_TOO_SMALL; | ||
| 109 | } | ||
| 110 | let samples = frames * channels; | ||
| 111 | unsafe { | ||
| 112 | ptr::copy_nonoverlapping(pcm.as_ptr(), out, samples); | ||
| 113 | *out_frames = frames as u32; | ||
| 114 | } | ||
| 115 | LEONIDA_OPUS_OK | ||
| 116 | } | ||
| 117 | Err(_) => LEONIDA_OPUS_DECODER_FAILURE, | ||
| 118 | } | ||
| 119 | } | ||
| 120 | |||
| 121 | /// # Safety | ||
| 122 | /// `decoder` must come from `leonida_opus_decoder_create` and not be used concurrently. | ||
| 123 | #[no_mangle] | ||
| 124 | pub unsafe extern "C" fn leonida_opus_decoder_reset(decoder: *mut LeonidaOpusDecoder) -> i32 { | ||
| 125 | if decoder.is_null() { | ||
| 126 | return LEONIDA_OPUS_INVALID_ARGUMENT; | ||
| 127 | } | ||
| 128 | let decoder = unsafe { &*decoder }; | ||
| 129 | let Ok(mut guard) = decoder.decoder.lock() else { | ||
| 130 | return LEONIDA_OPUS_DECODER_FAILURE; | ||
| 131 | }; | ||
| 132 | let _ = guard.reset_state(); | ||
| 133 | LEONIDA_OPUS_OK | ||
| 134 | } | ||
| 135 | |||
| 136 | /// # Safety | ||
| 137 | /// `decoder` must be a live handle and must not be used after this call. | ||
| 138 | #[no_mangle] | ||
| 139 | pub unsafe extern "C" fn leonida_opus_decoder_destroy(decoder: *mut LeonidaOpusDecoder) { | ||
| 140 | if !decoder.is_null() { | ||
| 141 | unsafe { drop(Box::from_raw(decoder)) }; | ||
| 142 | } | ||
| 143 | } | ||
| 144 | |||
| 145 | /// Test helper: encodes `frame_count` interleaved f32 frames to one Opus packet at 48 kHz. | ||
| 146 | /// | ||
| 147 | /// # Safety | ||
| 148 | /// `input` must hold `frame_count * channels` floats; `out` must hold `out_capacity` bytes; | ||
| 149 | /// `out_len` must be writable. | ||
| 150 | #[no_mangle] | ||
| 151 | pub unsafe extern "C" fn leonida_opus_encode_test( | ||
| 152 | input: *const f32, | ||
| 153 | frame_count: u32, | ||
| 154 | channels: u32, | ||
| 155 | out: *mut u8, | ||
| 156 | out_capacity: usize, | ||
| 157 | out_len: *mut usize, | ||
| 158 | ) -> i32 { | ||
| 159 | if input.is_null() | ||
| 160 | || out.is_null() | ||
| 161 | || out_len.is_null() | ||
| 162 | || frame_count == 0 | ||
| 163 | || !(1..=2).contains(&channels) | ||
| 164 | { | ||
| 165 | return LEONIDA_OPUS_INVALID_ARGUMENT; | ||
| 166 | } | ||
| 167 | let samples = frame_count as usize * channels as usize; | ||
| 168 | let input = unsafe { std::slice::from_raw_parts(input, samples) }; | ||
| 169 | let mut encoder = match OpusEncoder::new(48_000, channels as usize, Application::Audio) { | ||
| 170 | Ok(encoder) => encoder, | ||
| 171 | Err(_) => return LEONIDA_OPUS_INVALID_FORMAT, | ||
| 172 | }; | ||
| 173 | let mut packet = vec![0u8; out_capacity.max(4000)]; | ||
| 174 | match encoder.encode(input, frame_count as usize, &mut packet) { | ||
| 175 | Ok(bytes) if bytes <= out_capacity => { | ||
| 176 | unsafe { | ||
| 177 | ptr::copy_nonoverlapping(packet.as_ptr(), out, bytes); | ||
| 178 | *out_len = bytes; | ||
| 179 | } | ||
| 180 | LEONIDA_OPUS_OK | ||
| 181 | } | ||
| 182 | Ok(_) => LEONIDA_OPUS_BUFFER_TOO_SMALL, | ||
| 183 | Err(_) => LEONIDA_OPUS_DECODER_FAILURE, | ||
| 184 | } | ||
| 185 | } | ||
| 186 | |||
| 187 | #[cfg(test)] | ||
| 188 | mod tests { | ||
| 189 | use super::*; | ||
| 190 | |||
| 191 | #[test] | ||
| 192 | fn encodes_and_decodes_a_tone() { | ||
| 193 | const FRAMES: u32 = 960; | ||
| 194 | const CHANNELS: u32 = 2; | ||
| 195 | let mut tone = Vec::with_capacity((FRAMES * CHANNELS) as usize); | ||
| 196 | for i in 0..FRAMES { | ||
| 197 | let sample = ((i as f32) * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5; | ||
| 198 | tone.push(sample); | ||
| 199 | tone.push(sample); | ||
| 200 | } | ||
| 201 | let mut packet = [0u8; 1500]; | ||
| 202 | let mut packet_len = 0usize; | ||
| 203 | // SAFETY: the buffers are owned by this test. | ||
| 204 | let encoded = unsafe { | ||
| 205 | leonida_opus_encode_test( | ||
| 206 | tone.as_ptr(), | ||
| 207 | FRAMES, | ||
| 208 | CHANNELS, | ||
| 209 | packet.as_mut_ptr(), | ||
| 210 | packet.len(), | ||
| 211 | &mut packet_len, | ||
| 212 | ) | ||
| 213 | }; | ||
| 214 | assert_eq!(encoded, LEONIDA_OPUS_OK); | ||
| 215 | assert!(packet_len > 0); | ||
| 216 | |||
| 217 | let mut decoder = ptr::null_mut(); | ||
| 218 | // SAFETY: `decoder` is writable for one pointer. | ||
| 219 | assert_eq!( | ||
| 220 | unsafe { leonida_opus_decoder_create(48_000, CHANNELS, &mut decoder) }, | ||
| 221 | LEONIDA_OPUS_OK | ||
| 222 | ); | ||
| 223 | let mut pcm = vec![0f32; LEONIDA_OPUS_MAX_FRAMES * CHANNELS as usize]; | ||
| 224 | let mut frames = 0u32; | ||
| 225 | // SAFETY: the packet and PCM buffers are owned by this test. | ||
| 226 | let decoded = unsafe { | ||
| 227 | leonida_opus_decode_packet( | ||
| 228 | decoder, | ||
| 229 | packet.as_ptr(), | ||
| 230 | packet_len, | ||
| 231 | pcm.as_mut_ptr(), | ||
| 232 | LEONIDA_OPUS_MAX_FRAMES, | ||
| 233 | &mut frames, | ||
| 234 | ) | ||
| 235 | }; | ||
| 236 | assert_eq!(decoded, LEONIDA_OPUS_OK); | ||
| 237 | assert_eq!(frames, FRAMES); | ||
| 238 | let energy: f32 = | ||
| 239 | pcm[..(frames * CHANNELS) as usize].iter().map(|s| s * s).sum::<f32>() / (frames * CHANNELS) as f32; | ||
| 240 | assert!(energy > 0.01, "decoded a tone, energy {energy}"); | ||
| 241 | // SAFETY: created above, destroyed once. | ||
| 242 | unsafe { leonida_opus_decoder_destroy(decoder) }; | ||
| 243 | } | ||
| 244 | } | ||
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index ca2b02789..76e946b47 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h | |||
| @@ -169,6 +169,9 @@ struct VulkanDeviceInfo { | |||
| 169 | bool occlusion_query_precise = false; | 169 | bool occlusion_query_precise = false; |
| 170 | bool prepare_on_bind = false; | 170 | bool prepare_on_bind = false; |
| 171 | bool cold_graphics_compile = false; // Driver supports a cache-only create and reports when compilation is pending. | 171 | bool cold_graphics_compile = false; // Driver supports a cache-only create and reports when compilation is pending. |
| 172 | // pipelineCreationCacheControl is on for the heavy pipeline cache (src/heavy_pipeline_cache.h): a pipeline the | ||
| 173 | // offline cache does not have is created against the cache of pipeline_cache.heavy.bin, written back as it grows. | ||
| 174 | bool heavy_pipeline_cache = false; | ||
| 172 | bool pipeline_statistics_query = false; | 175 | bool pipeline_statistics_query = false; |
| 173 | bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device | 176 | bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device |
| 174 | // VK_KHR_swapchain_maintenance1 (or VK_EXT_swapchain_maintenance1) and its swapchainMaintenance1 feature are | 177 | // VK_KHR_swapchain_maintenance1 (or VK_EXT_swapchain_maintenance1) and its swapchainMaintenance1 feature are |
| @@ -387,6 +390,10 @@ std::uint64_t device_arena_size(ID3D12Device* device); | |||
| 387 | // Copies `bytes` of the device's GPU address arena at console VA `va` (what shaders read there: a heap's GPU copy, | 390 | // Copies `bytes` of the device's GPU address arena at console VA `va` (what shaders read there: a heap's GPU copy, |
| 388 | // the null slots after it) into `out`. False without an arena or when the range is not inside it. For tests. | 391 | // the null slots after it) into `out`. False without an arena or when the range is not inside it. For tests. |
| 389 | bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes); | 392 | bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes); |
| 393 | // The slots whose host-RAM mirror differs from the GPU copy of the console descriptor heap at `console_va` | ||
| 394 | // (src/console_heap_copy.h), compared now: 0 when they agree, -1 when there is no such heap or it has no mirror. | ||
| 395 | // For tests. | ||
| 396 | long long console_heap_mirror_mismatches(ID3D12Device* device, std::uint64_t console_va); | ||
| 390 | 397 | ||
| 391 | // The blocks of device memory that textures share (src/image_memory.h): how many, their bytes, and the textures in | 398 | // The blocks of device memory that textures share (src/image_memory.h): how many, their bytes, and the textures in |
| 392 | // them. For tests. | 399 | // them. For tests. |
diff --git a/runtime/shims/d3d12_compute_input_probe.h b/runtime/shims/d3d12_compute_input_probe.h index 70ac61e52..fdec0348e 100644 --- a/runtime/shims/d3d12_compute_input_probe.h +++ b/runtime/shims/d3d12_compute_input_probe.h | |||
| @@ -195,7 +195,7 @@ bool gpu_words_now(State& state, std::uint64_t at, std::array<std::uint32_t, 8>& | |||
| 195 | for (const auto& heap : state.console_heaps) { | 195 | for (const auto& heap : state.console_heaps) { |
| 196 | const auto delta = at - heap->shader_va; | 196 | const auto delta = at - heap->shader_va; |
| 197 | if (heap->copy && delta <= heap->bytes && sizeof(out) <= heap->bytes - delta) { | 197 | if (heap->copy && delta <= heap->bytes && sizeof(out) <= heap->bytes - delta) { |
| 198 | std::memcpy(out.data(), heap->copy + delta, sizeof(out)); | 198 | std::memcpy(out.data(), heap->copy.gpu() + delta, sizeof(out)); |
| 199 | return true; | 199 | return true; |
| 200 | } | 200 | } |
| 201 | } | 201 | } |
| @@ -249,7 +249,7 @@ void recheck(State& state) { | |||
| 249 | if (!lock.owns_lock()) std::fputs("[rt] compute-input: after loss, console heaps locked\n", stderr); | 249 | if (!lock.owns_lock()) std::fputs("[rt] compute-input: after loss, console heaps locked\n", stderr); |
| 250 | else | 250 | else |
| 251 | for (const auto& heap : state.console_heaps) | 251 | for (const auto& heap : state.console_heaps) |
| 252 | if (heap->copy) scan("console", heap->shader_va, heap->copy, heap->bytes); | 252 | if (heap->copy) scan("console", heap->shader_va, heap->copy.gpu(), heap->bytes); |
| 253 | } | 253 | } |
| 254 | { | 254 | { |
| 255 | std::unique_lock lock(state.visible_heap_mutex, std::try_to_lock); | 255 | std::unique_lock lock(state.visible_heap_mutex, std::try_to_lock); |
| @@ -294,7 +294,7 @@ Backing descriptor(State& state, std::uint64_t seq, std::size_t list, std::size_ | |||
| 294 | for (const auto& heap : state.console_heaps) { | 294 | for (const auto& heap : state.console_heaps) { |
| 295 | const auto delta = at - heap->shader_va; | 295 | const auto delta = at - heap->shader_va; |
| 296 | if (heap->copy && delta <= heap->bytes && sizeof(gpu) <= heap->bytes - delta) { | 296 | if (heap->copy && delta <= heap->bytes && sizeof(gpu) <= heap->bytes - delta) { |
| 297 | std::memcpy(gpu.data(), heap->copy + delta, sizeof(gpu)); | 297 | std::memcpy(gpu.data(), heap->copy.view() + delta, sizeof(gpu)); |
| 298 | have_gpu = true; | 298 | have_gpu = true; |
| 299 | break; | 299 | break; |
| 300 | } | 300 | } |
diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h index feb4ff52e..ebfab4b74 100644 --- a/runtime/shims/d3d12_geometry_views.h +++ b/runtime/shims/d3d12_geometry_views.h | |||
| @@ -9,13 +9,14 @@ | |||
| 9 | #include <mutex> | 9 | #include <mutex> |
| 10 | #include <set> | 10 | #include <set> |
| 11 | #include <shared_mutex> | 11 | #include <shared_mutex> |
| 12 | #include <type_traits> | ||
| 12 | #include <unordered_map> | 13 | #include <unordered_map> |
| 13 | #include <utility> | 14 | #include <utility> |
| 14 | #include <vector> | 15 | #include <vector> |
| 15 | 16 | ||
| 16 | namespace rt::d3d12 { | 17 | namespace rt::d3d12 { |
| 17 | 18 | ||
| 18 | // One persistent device-local copy for each geometry extent. The console heap retains its original indices. | 19 | // One persistent copy for each geometry extent, in device-local memory (or system memory: LEONIDA_GEOMETRY_HOST). The console heap retains its original indices. |
| 19 | // Every CPU mapping of a source tile is watched; a physical remap changes which aliases must be watched. | 20 | // 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 | // 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 | // in-flight GPU submissions up to their retire ticket have completed; previously cap-refused ranges retry |
| @@ -30,6 +31,7 @@ class GeometryViews { | |||
| 30 | struct NoopRetire { | 31 | struct NoopRetire { |
| 31 | void operator()(Address, std::size_t, VkDeviceSize) const noexcept {} | 32 | void operator()(Address, std::size_t, VkDeviceSize) const noexcept {} |
| 32 | }; | 33 | }; |
| 34 | struct NoCopy {}; | ||
| 33 | struct View { | 35 | struct View { |
| 34 | Address source{}; | 36 | Address source{}; |
| 35 | std::size_t size{}; | 37 | std::size_t size{}; |
| @@ -121,7 +123,7 @@ class GeometryViews { | |||
| 121 | std::atomic<std::uint64_t> free_generation_{0}; | 123 | std::atomic<std::uint64_t> free_generation_{0}; |
| 122 | std::uint64_t serial_{}, bytes_{}, cap_refusals_{}, allocation_failures_{}, ready_{}, uploads_{}, uploaded_{}; | 124 | std::uint64_t serial_{}, bytes_{}, cap_refusals_{}, allocation_failures_{}, ready_{}, uploads_{}, uploaded_{}; |
| 123 | std::uint64_t submissions_{}, dirty_refreshes_{}, refilled_{}, tile_fills_{}; | 125 | std::uint64_t submissions_{}, dirty_refreshes_{}, refilled_{}, tile_fills_{}; |
| 124 | std::uint64_t evicted_{}, reaped_{}, retries_succeeded_{}; | 126 | std::uint64_t evicted_{}, reaped_{}, retries_succeeded_{}, final_copies_{}; |
| 125 | std::unordered_map<Address, std::size_t> tile_reads_; // refresh(): offset in tile_scratch_, SIZE_MAX unreadable | 127 | std::unordered_map<Address, std::size_t> tile_reads_; // refresh(): offset in tile_scratch_, SIZE_MAX unreadable |
| 126 | // refresh() scratch: per view, whether it waits on a tile (pinned), is filled whole, was touched, was counted; | 128 | // refresh() scratch: per view, whether it waits on a tile (pinned), is filled whole, was touched, was counted; |
| 127 | // and the tiles found written, in address order. | 129 | // and the tiles found written, in address order. |
| @@ -213,6 +215,7 @@ class GeometryViews { | |||
| 213 | 215 | ||
| 214 | public: | 216 | public: |
| 215 | explicit GeometryViews(std::uint64_t cap_override = 0) : cap_override_(cap_override) { | 217 | explicit GeometryViews(std::uint64_t cap_override = 0) : cap_override_(cap_override) { |
| 218 | pool_.set_system_memory(system_memory_setting()); | ||
| 216 | leonida::geometry_writes::subscribe(releases_); | 219 | leonida::geometry_writes::subscribe(releases_); |
| 217 | } | 220 | } |
| 218 | ~GeometryViews() { leonida::geometry_writes::unsubscribe(releases_); } | 221 | ~GeometryViews() { leonida::geometry_writes::unsubscribe(releases_); } |
| @@ -231,6 +234,16 @@ public: | |||
| 231 | 234 | ||
| 232 | std::uint64_t effective_cap() const { return cap_override_ ? cap_override_ : cap(); } | 235 | std::uint64_t effective_cap() const { return cap_override_ ? cap_override_ : cap(); } |
| 233 | 236 | ||
| 237 | // LEONIDA_GEOMETRY_HOST: where the copies live. Unset or 0: device-local memory (the BAR) while the driver gives it; | ||
| 238 | // 1: system memory, write-back (cached) where the device offers it; 2: system memory, write-combined. The GPU then | ||
| 239 | // reads the copies over the bus (VRAM saved, each read of a vertex or index slower). | ||
| 240 | static int system_memory_setting() { | ||
| 241 | const char* v = std::getenv("LEONIDA_GEOMETRY_HOST"); | ||
| 242 | if (!v || !*v || *v == '0') return TitleBufferWindows::kDeviceLocal; | ||
| 243 | return *v == '2' ? TitleBufferWindows::kSystemUncached : TitleBufferWindows::kSystemCached; | ||
| 244 | } | ||
| 245 | int system_memory() const { return pool_.system_memory(); } | ||
| 246 | |||
| 234 | bool has_released() const { return leonida::geometry_writes::has_released(releases_); } | 247 | 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; } | 248 | bool has_retired() const { return retired_count_.load(std::memory_order_acquire) != 0; } |
| 236 | bool has_pending_reclaim() const { return has_released() || has_retired(); } | 249 | bool has_pending_reclaim() const { return has_released() || has_retired(); } |
| @@ -258,6 +271,10 @@ public: | |||
| 258 | std::lock_guard lock(mutex_); | 271 | std::lock_guard lock(mutex_); |
| 259 | return evicted_; | 272 | return evicted_; |
| 260 | } | 273 | } |
| 274 | std::uint64_t final_copies() const { | ||
| 275 | std::lock_guard lock(mutex_); | ||
| 276 | return final_copies_; | ||
| 277 | } | ||
| 261 | std::uint64_t reaped() const { | 278 | std::uint64_t reaped() const { |
| 262 | std::lock_guard lock(mutex_); | 279 | std::lock_guard lock(mutex_); |
| 263 | return reaped_; | 280 | return reaped_; |
| @@ -393,9 +410,14 @@ public: | |||
| 393 | // Retires every live view overlapping [begin, end), unlinking it from lookup/refresh/watch immediately and | 410 | // 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 | 411 | // 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). | 412 | // (kAfterExecutes: through the submissions of every replay in progress now, see execute_end). |
| 396 | template<class OnRetire = NoopRetire> | 413 | // With `final_copy` (a refresh's copy), a ready view whose title range is readable now is copied from it once more |
| 414 | // before it leaves the refresh: a range the title remapped holds new bytes, and a list recorded before the remap | ||
| 415 | // that took the view's address (a root view) and runs in a submission the view waits for reads those, as it would | ||
| 416 | // have read them in the console's memory, and as the refresh this retirement replaces would have copied them. | ||
| 417 | // Freed or unmapped memory is not readable, so such a view keeps what it held. | ||
| 418 | template<class OnRetire = NoopRetire, class Copy = NoCopy> | ||
| 397 | std::size_t retire_range(Address begin, Address end, std::uint64_t retire_ticket = 0, | 419 | std::size_t retire_range(Address begin, Address end, std::uint64_t retire_ticket = 0, |
| 398 | OnRetire&& on_retire = {}) { | 420 | OnRetire&& on_retire = {}, Copy&& final_copy = {}) { |
| 399 | if (end <= begin) return 0; | 421 | if (end <= begin) return 0; |
| 400 | struct CallbackItem { | 422 | struct CallbackItem { |
| 401 | Address source; | 423 | Address source; |
| @@ -425,6 +447,13 @@ public: | |||
| 425 | const std::size_t first_retired = retired_.size(); | 447 | const std::size_t first_retired = retired_.size(); |
| 426 | for (const auto id : ids) { | 448 | for (const auto id : ids) { |
| 427 | View& v = views_[id]; | 449 | View& v = views_[id]; |
| 450 | if constexpr (!std::is_same_v<std::decay_t<Copy>, NoCopy>) { | ||
| 451 | if (v.ready && final_copy(v.dst, reinterpret_cast<const std::uint8_t*>(v.source), v.size) == | ||
| 452 | GeometryCopy::copied) { | ||
| 453 | ++final_copies_; | ||
| 454 | uploaded_ += v.size; | ||
| 455 | } | ||
| 456 | } | ||
| 428 | detach_tiles_locked(id, v.source, v.size); | 457 | detach_tiles_locked(id, v.source, v.size); |
| 429 | if (v.ready) { | 458 | if (v.ready) { |
| 430 | --ready_; | 459 | --ready_; |
| @@ -495,21 +524,21 @@ public: | |||
| 495 | return freed; | 524 | return freed; |
| 496 | } | 525 | } |
| 497 | 526 | ||
| 498 | // Drains released title ranges recorded by xmem (retiring matching views at `retire_ticket`) and reaps retired | 527 | // Drains released title ranges recorded by xmem (retiring matching views at `retire_ticket`, with `final_copy` as |
| 499 | // views whose GPU work completed by `completed_ticket`. | 528 | // retire_range takes it) and reaps retired views whose GPU work completed by `completed_ticket`. |
| 500 | template<class Device, class OnRetire = NoopRetire> | 529 | template<class Device, class OnRetire = NoopRetire, class Copy = NoCopy> |
| 501 | void drain_released(Device& device, std::uint64_t retire_ticket, std::uint64_t completed_ticket, | 530 | void drain_released(Device& device, std::uint64_t retire_ticket, std::uint64_t completed_ticket, |
| 502 | OnRetire&& on_retire = {}) { | 531 | OnRetire&& on_retire = {}, Copy&& final_copy = {}) { |
| 503 | std::vector<std::pair<Address, Address>> ranges; | 532 | std::vector<std::pair<Address, Address>> ranges; |
| 504 | leonida::geometry_writes::take_released(releases_, ranges); | 533 | leonida::geometry_writes::take_released(releases_, ranges); |
| 505 | for (const auto& [begin, end] : ranges) { | 534 | for (const auto& [begin, end] : ranges) { |
| 506 | retire_range(begin, end, retire_ticket, on_retire); | 535 | retire_range(begin, end, retire_ticket, on_retire, final_copy); |
| 507 | leonida::title_gpu_views::Range pair{}; | 536 | leonida::title_gpu_views::Range pair{}; |
| 508 | if (end > begin && leonida::title_gpu_views::view_at(begin, 1, pair) && | 537 | if (end > begin && leonida::title_gpu_views::view_at(begin, 1, pair) && |
| 509 | begin >= pair.gpu && begin - pair.gpu < pair.size) { | 538 | begin >= pair.gpu && begin - pair.gpu < pair.size) { |
| 510 | const Address offset = begin - pair.gpu; | 539 | const Address offset = begin - pair.gpu; |
| 511 | const Address span = (std::min)(end - begin, pair.size - offset); | 540 | const Address span = (std::min)(end - begin, pair.size - offset); |
| 512 | retire_range(pair.cpu + offset, pair.cpu + offset + span, retire_ticket, on_retire); | 541 | retire_range(pair.cpu + offset, pair.cpu + offset + span, retire_ticket, on_retire, final_copy); |
| 513 | } | 542 | } |
| 514 | } | 543 | } |
| 515 | reap(device, completed_ticket); | 544 | reap(device, completed_ticket); |
| @@ -666,14 +695,17 @@ public: | |||
| 666 | if (!effective_cap()) return; | 695 | if (!effective_cap()) return; |
| 667 | std::lock_guard lock(mutex_); | 696 | std::lock_guard lock(mutex_); |
| 668 | std::fprintf(stderr, "[rt] geometry buffers: seen %zu, backed %zu (%llu bytes), populated %llu, cap %llu MiB, " | 697 | std::fprintf(stderr, "[rt] geometry buffers: seen %zu, backed %zu (%llu bytes), populated %llu, cap %llu MiB, " |
| 669 | "cap refused %llu, retried ok %llu, evicted %llu (reaped %llu, retired %zu), " | 698 | "cap refused %llu, retried ok %llu, evicted %llu (reaped %llu, retired %zu, copied at " |
| 670 | "allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, reserved %llu bytes\n", | 699 | "retirement %llu), allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, " |
| 700 | "reserved %llu bytes (%s)\n", | ||
| 671 | keys_.size() + refused_.size(), live_views_, (unsigned long long)bytes_, (unsigned long long)ready_, | 701 | keys_.size() + refused_.size(), live_views_, (unsigned long long)bytes_, (unsigned long long)ready_, |
| 672 | (unsigned long long)(effective_cap() >> 20), (unsigned long long)cap_refusals_, | 702 | (unsigned long long)(effective_cap() >> 20), (unsigned long long)cap_refusals_, |
| 673 | (unsigned long long)retries_succeeded_, (unsigned long long)evicted_, | 703 | (unsigned long long)retries_succeeded_, (unsigned long long)evicted_, |
| 674 | (unsigned long long)reaped_, retired_.size(), (unsigned long long)allocation_failures_, | 704 | (unsigned long long)reaped_, retired_.size(), (unsigned long long)final_copies_, |
| 705 | (unsigned long long)allocation_failures_, | ||
| 675 | (unsigned long long)uploads_, (unsigned long long)uploaded_, tiles_.size(), | 706 | (unsigned long long)uploads_, (unsigned long long)uploaded_, tiles_.size(), |
| 676 | static_cast<unsigned long long>(pool_.reserved())); | 707 | static_cast<unsigned long long>(pool_.reserved()), |
| 708 | pool_.system_memory() ? "system memory" : "device-local"); | ||
| 677 | std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes (%llu views by " | 709 | std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes (%llu views by " |
| 678 | "their written tiles only); %.3f s checking and refreshing sources, %llu bytes cleared\n", | 710 | "their written tiles only); %.3f s checking and refreshing sources, %llu bytes cleared\n", |
| 679 | static_cast<unsigned long long>(dirty_refreshes_), static_cast<unsigned long long>(submissions_), | 711 | static_cast<unsigned long long>(dirty_refreshes_), static_cast<unsigned long long>(submissions_), |
diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h index 06927cb4b..c85809e8e 100644 --- a/runtime/shims/d3d12_title_buffer_windows.h +++ b/runtime/shims/d3d12_title_buffer_windows.h | |||
| @@ -38,6 +38,10 @@ class TitleBufferWindows { | |||
| 38 | std::chrono::steady_clock::time_point failed_at_{}; | 38 | std::chrono::steady_clock::time_point failed_at_{}; |
| 39 | bool failed_ = false; | 39 | bool failed_ = false; |
| 40 | 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 |
| 41 | // SystemMemory: where a device_local allocation goes instead (set_system_memory; GeometryViews from | ||
| 42 | // LEONIDA_GEOMETRY_HOST). | ||
| 43 | int system_memory_ = 0; | ||
| 44 | bool system_memory_logged_ = false; | ||
| 41 | std::uint64_t quick_refusals_ = 0; | 45 | std::uint64_t quick_refusals_ = 0; |
| 42 | // The blocks' (device address, capacity), readable without the owner's lock: published in order, a slot never | 46 | // 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 | 47 | // reused before release(). A destroyed block's slot keeps its other fields and only its address goes to 0 (the |
| @@ -73,7 +77,38 @@ class TitleBufferWindows { | |||
| 73 | blocks_.erase(it); | 77 | blocks_.erase(it); |
| 74 | } | 78 | } |
| 75 | 79 | ||
| 80 | // The memory types a system-memory block may take: host-visible ones outside device-local memory (the GPU reads | ||
| 81 | // them over the bus), the write-back (cached) ones only when `cached`, else the write-combined ones only. None of | ||
| 82 | // them: every type `bits` allows (an integrated GPU, whose memory is all device-local). | ||
| 83 | template<class Device> | ||
| 84 | static std::uint32_t system_memory_types(const Device& d, std::uint32_t bits, bool cached) { | ||
| 85 | if constexpr (requires { d.memory.memoryTypes[0].propertyFlags; d.memory.memoryTypeCount; }) { | ||
| 86 | std::uint32_t host = 0, wanted = 0; | ||
| 87 | for (std::uint32_t i = 0; i < d.memory.memoryTypeCount && i < 32; ++i) { | ||
| 88 | if (!(bits & (1u << i))) continue; | ||
| 89 | const VkMemoryPropertyFlags f = d.memory.memoryTypes[i].propertyFlags; | ||
| 90 | if ((f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) || !(f & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) || | ||
| 91 | !(f & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) | ||
| 92 | continue; | ||
| 93 | host |= 1u << i; | ||
| 94 | if (bool(f & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) == cached) wanted |= 1u << i; | ||
| 95 | } | ||
| 96 | return wanted ? wanted : host ? host : bits; | ||
| 97 | } else { | ||
| 98 | (void)d; | ||
| 99 | (void)cached; | ||
| 100 | return bits; | ||
| 101 | } | ||
| 102 | } | ||
| 103 | |||
| 76 | public: | 104 | public: |
| 105 | // Where blocks asked for as device_local go: kDeviceLocal (Resizable BAR while the driver gives it, the default), | ||
| 106 | // kSystemCached (host memory outside VRAM, write-back where the device offers it: what VIctory gives its copies | ||
| 107 | // of title memory) or kSystemUncached (host memory outside VRAM, write-combined). The GPU reads the system-memory | ||
| 108 | // kinds over the bus. Set before the first allocation. | ||
| 109 | static constexpr int kDeviceLocal = 0, kSystemCached = 1, kSystemUncached = 2; | ||
| 110 | void set_system_memory(int kind) { system_memory_ = kind; } | ||
| 111 | int system_memory() const { return system_memory_; } | ||
| 77 | VkDeviceSize reserved() const { return reserved_; } | 112 | VkDeviceSize reserved() const { return reserved_; } |
| 78 | // f(device address, capacity) for each live block; from any thread. | 113 | // f(device address, capacity) for each live block; from any thread. |
| 79 | template <class F> | 114 | template <class F> |
| @@ -186,10 +221,26 @@ public: | |||
| 186 | // story load the driver refused every 4 MiB device-local, host-visible block with a device address | 221 | // story load the driver refused every 4 MiB device-local, host-visible block with a device address |
| 187 | // (VK_ERROR_OUT_OF_HOST_MEMORY, speed-8/-9) while host memory still served: once that happens, later blocks | 222 | // (VK_ERROR_OUT_OF_HOST_MEMORY, speed-8/-9) while host memory still served: once that happens, later blocks |
| 188 | // go straight to host memory instead of through DeviceState::allocate's sleeping retries first. | 223 | // go straight to host memory instead of through DeviceState::allocate's sleeping retries first. |
| 224 | // A device_local request under set_system_memory takes system memory instead, out of the types that are not | ||
| 225 | // device-local (memory_type_order would otherwise give the first host-visible type, which can be the BAR). | ||
| 189 | VkMemoryPropertyFlags chosen = 0; | 226 | VkMemoryPropertyFlags chosen = 0; |
| 190 | const bool want_local = device_local && !local_refused_; | 227 | const bool system = device_local && system_memory_ != kDeviceLocal; |
| 191 | b.memory = d.allocate(req, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, | 228 | const bool want_local = device_local && !local_refused_ && !system; |
| 192 | want_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &chosen, true); | 229 | VkMemoryRequirements types = req; |
| 230 | if (system) types.memoryTypeBits = system_memory_types(d, req.memoryTypeBits, system_memory_ == kSystemCached); | ||
| 231 | b.memory = d.allocate(types, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, | ||
| 232 | want_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | ||
| 233 | : system && system_memory_ == kSystemCached ? VK_MEMORY_PROPERTY_HOST_CACHED_BIT | ||
| 234 | : 0, | ||
| 235 | &chosen, true); | ||
| 236 | if (b.memory && system && !system_memory_logged_) { | ||
| 237 | system_memory_logged_ = true; | ||
| 238 | std::fprintf(stderr, "[rt] d3d12: title buffer copies in system memory (LEONIDA_GEOMETRY_HOST): memory " | ||
| 239 | "flags 0x%x (%s, %s)\n", | ||
| 240 | unsigned(chosen), | ||
| 241 | (chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ? "device-local: no other type" : "not VRAM", | ||
| 242 | (chosen & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) ? "write-back" : "write-combined"); | ||
| 243 | } | ||
| 193 | if (b.memory && want_local && !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { | 244 | if (b.memory && want_local && !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { |
| 194 | local_refused_ = true; | 245 | local_refused_ = true; |
| 195 | std::fprintf(stderr, "[rt] d3d12: title buffer windows: device-local memory refused a %llu KiB block; " | 246 | std::fprintf(stderr, "[rt] d3d12: title buffer windows: device-local memory refused a %llu KiB block; " |
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index eabbd0cd1..eedc0662e 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp | |||
| @@ -32,6 +32,7 @@ | |||
| 32 | #include "dxgi_com.h" | 32 | #include "dxgi_com.h" |
| 33 | #include "../src/arena_size.h" | 33 | #include "../src/arena_size.h" |
| 34 | #include "../src/value_write_sink.h" | 34 | #include "../src/value_write_sink.h" |
| 35 | #include "../src/address_guard.h" | ||
| 35 | #include "../src/arena_blocks.h" | 36 | #include "../src/arena_blocks.h" |
| 36 | #include "../src/gfx10_descriptors.h" | 37 | #include "../src/gfx10_descriptors.h" |
| 37 | #include "../src/depth24_fragment.h" | 38 | #include "../src/depth24_fragment.h" |
| @@ -47,6 +48,7 @@ | |||
| 47 | #include "../src/pipeline_cache_file.h" | 48 | #include "../src/pipeline_cache_file.h" |
| 48 | #include "../src/pipeline_profile.h" | 49 | #include "../src/pipeline_profile.h" |
| 49 | #include "../src/submit_phases.h" | 50 | #include "../src/submit_phases.h" |
| 51 | #include "../src/heavy_pipeline_cache.h" | ||
| 50 | #include "../src/pipeline_cache_store.h" | 52 | #include "../src/pipeline_cache_store.h" |
| 51 | #include "../src/pipeline_cache_journal.h" | 53 | #include "../src/pipeline_cache_journal.h" |
| 52 | #include "../src/large_module_gate.h" | 54 | #include "../src/large_module_gate.h" |
| @@ -65,6 +67,7 @@ | |||
| 65 | #include "../src/spirv_f16_halves.h" | 67 | #include "../src/spirv_f16_halves.h" |
| 66 | #include "../src/spirv_stores.h" | 68 | #include "../src/spirv_stores.h" |
| 67 | #include "../src/title_va_alias.h" | 69 | #include "../src/title_va_alias.h" |
| 70 | #include "../src/console_heap_copy.h" | ||
| 68 | #include "../src/console_heap_vsharp_slots.h" | 71 | #include "../src/console_heap_vsharp_slots.h" |
| 69 | #include "../src/title_window_plan.h" | 72 | #include "../src/title_window_plan.h" |
| 70 | #include "../src/vulkan_present.h" | 73 | #include "../src/vulkan_present.h" |
| @@ -127,6 +130,8 @@ constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex an | |||
| 127 | constexpr auto kQuadIndicesPerQuad = std::uint32_t(leonida::quad_triangle_indices.size()); | 130 | constexpr auto kQuadIndicesPerQuad = std::uint32_t(leonida::quad_triangle_indices.size()); |
| 128 | constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; | 131 | constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; |
| 129 | constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); | 132 | constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); |
| 133 | // LEONIDA_ADDRESS_GUARD's header and sinks follow the quad indices (src/address_guard.h). | ||
| 134 | static_assert(kArenaReserved <= leonida::address_guard::kGuardHeader); | ||
| 130 | static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); | 135 | static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); |
| 131 | // pipeline_cache_store.h reads this layout without vulkan.h (D3D-704); remember the two. | 136 | // pipeline_cache_store.h reads this layout without vulkan.h (D3D-704); remember the two. |
| 132 | static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == leonida::pipeline_cache_store::header_bytes); | 137 | static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == leonida::pipeline_cache_store::header_bytes); |
| @@ -159,6 +164,18 @@ void log_once(const char* what, int value) { | |||
| 159 | if (first_diagnostic(what, value)) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); | 164 | if (first_diagnostic(what, value)) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); |
| 160 | } | 165 | } |
| 161 | 166 | ||
| 167 | // LEONIDA_ADDRESS_GUARD=1: the address guard (docs/d3d12_vulkan.md, "Address guard"). The arena keeps its guard | ||
| 168 | // header and sinks at heap_base + 0x70000..0x80000 and a page table of every backing outside it is kept current | ||
| 169 | // before each submission, so shaders translated with `rdna2spirv.py --address-guard` read 0 from, and drop stores | ||
| 170 | // to, an address nothing backs. Without it those shaders find no header and check nothing. | ||
| 171 | bool address_guard_enabled() { | ||
| 172 | static const bool on = [] { | ||
| 173 | wchar_t value[2]{}; | ||
| 174 | return GetEnvironmentVariableW(L"LEONIDA_ADDRESS_GUARD", value, 2) == 1 && value[0] == L'1'; | ||
| 175 | }(); | ||
| 176 | return on; | ||
| 177 | } | ||
| 178 | |||
| 162 | // Matches the offset interpretation of the selected shader pack. | 179 | // Matches the offset interpretation of the selected shader pack. |
| 163 | bool signed_vsharp_offsets() { | 180 | bool signed_vsharp_offsets() { |
| 164 | static const bool on = [] { | 181 | static const bool on = [] { |
| @@ -225,18 +242,24 @@ bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, | |||
| 225 | // (streaming, file reads, XG copies) or whole planes (video), never a few bytes inside a page. The same sampling as | 242 | // (streaming, file reads, XG copies) or whole planes (video), never a few bytes inside a page. The same sampling as |
| 226 | // OpenScarlett's texture hash before submission (src/gpu/d3d12_xs/device_x.cpp, f8e24d4, MIT), with more samples. | 243 | // OpenScarlett's texture hash before submission (src/gpu/d3d12_xs/device_x.cpp, f8e24d4, MIT), with more samples. |
| 227 | // False when a page faults (the title unmapped it). No C++ objects here: it is a __try frame. | 244 | // False when a page faults (the title unmapped it). No C++ objects here: it is a __try frame. |
| 228 | inline std::uint64_t mix_words(std::uint64_t h, const std::uint8_t* at, std::size_t n) { | 245 | #pragma pack(push, 1) |
| 246 | struct UnalignedWord64 { | ||
| 247 | std::uint64_t value; | ||
| 248 | }; | ||
| 249 | #pragma pack(pop) | ||
| 250 | |||
| 251 | LEONIDA_GUARDED_NO_BUILTIN inline std::uint64_t mix_words(std::uint64_t h, const std::uint8_t* at, std::size_t n) { | ||
| 229 | for (std::size_t i = 0; i + 8 <= n; i += 8) { | 252 | for (std::size_t i = 0; i + 8 <= n; i += 8) { |
| 230 | std::uint64_t w; | 253 | const std::uint64_t w = reinterpret_cast<const UnalignedWord64*>(at + i)->value; |
| 231 | std::memcpy(&w, at + i, 8); | ||
| 232 | h = (h ^ w) * 0x100000001b3ull; | 254 | h = (h ^ w) * 0x100000001b3ull; |
| 233 | h ^= h >> 29; | 255 | h ^= h >> 29; |
| 234 | } | 256 | } |
| 235 | return h; | 257 | return h; |
| 236 | } | 258 | } |
| 237 | // The reads of hash_guarded, in a frame of its own: an inline load inside the __try is not covered by clang-cl | 259 | // The reads of hash_guarded, in a frame of its own: an inline load inside the __try is not covered by clang-cl |
| 238 | // without /EHa (src/guarded_copy.h). | 260 | // without /EHa, and a CRT memcpy call is not covered under Wine (src/guarded_copy.h). |
| 239 | __declspec(noinline) std::uint64_t hash_bytes(const std::uint8_t* p, std::size_t bytes, bool every_byte) { | 261 | __declspec(noinline) LEONIDA_GUARDED_NO_BUILTIN std::uint64_t hash_bytes(const std::uint8_t* p, std::size_t bytes, |
| 262 | bool every_byte) { | ||
| 240 | std::uint64_t h = 0x9e3779b97f4a7c15ull ^ bytes; | 263 | std::uint64_t h = 0x9e3779b97f4a7c15ull ^ bytes; |
| 241 | if (bytes <= (256u << 10) || every_byte) { | 264 | if (bytes <= (256u << 10) || every_byte) { |
| 242 | h = mix_words(h, p, bytes & ~std::size_t(7)); | 265 | h = mix_words(h, p, bytes & ~std::size_t(7)); |
| @@ -373,6 +396,43 @@ public: | |||
| 373 | ShadowPages(const ShadowPages&) = delete; | 396 | ShadowPages(const ShadowPages&) = delete; |
| 374 | ShadowPages& operator=(const ShadowPages&) = delete; | 397 | ShadowPages& operator=(const ShadowPages&) = delete; |
| 375 | 398 | ||
| 399 | // What the GPU writes into the copies of [from, to) goes back to the title's pages: the pages are made writable | ||
| 400 | // first (the tracker guards them) and every target is copied from its shadow. Returns the bytes written. Called | ||
| 401 | // before the next refresh, so a page the title writes again is copied forward over the result, as on a GPU that | ||
| 402 | // shares the memory. | ||
| 403 | std::size_t write_back(std::uintptr_t from, std::uintptr_t to) { | ||
| 404 | from = std::max(from, first_), to = std::min(to, last_); | ||
| 405 | if (from >= to) return 0; | ||
| 406 | AcquireSRWLockExclusive(&lock_); | ||
| 407 | // A page the title wrote since it was last copied holds the newer bytes already: its GPU result is dropped and | ||
| 408 | // the refresh's own copy carries the title's. A guarded page (read-only since that copy) or one asked about and | ||
| 409 | // found unchanged takes the GPU's. | ||
| 410 | const auto held = [&](std::size_t i) { | ||
| 411 | const std::uint8_t s = state_[i]; | ||
| 412 | return (s & kZero) || (!(s & kProtected) && !(s & kClean)); | ||
| 413 | }; | ||
| 414 | std::size_t written = 0; | ||
| 415 | for (std::uintptr_t at = from & ~(kPage - 1); at < ((to + kPage - 1) & ~(kPage - 1));) { | ||
| 416 | std::size_t pages = 0; | ||
| 417 | while (at + (pages + 1) * kPage <= ((to + kPage - 1) & ~(kPage - 1)) && | ||
| 418 | held((at - first_) / kPage + pages) == held((at - first_) / kPage)) | ||
| 419 | ++pages; | ||
| 420 | if (!held((at - first_) / kPage)) { | ||
| 421 | const std::uintptr_t a = std::max(at, from), b = std::min(at + pages * kPage, to); | ||
| 422 | reopen_locked(at, at + pages * kPage); | ||
| 423 | for (const Target& t : targets_) { | ||
| 424 | const std::uintptr_t x = std::max(a, t.begin), y = std::min(b, t.end); | ||
| 425 | if (x >= y || !t.shadow) continue; | ||
| 426 | std::memcpy(reinterpret_cast<void*>(x), t.shadow + (x - t.begin), y - x); | ||
| 427 | written += y - x; | ||
| 428 | } | ||
| 429 | } | ||
| 430 | at += pages * kPage; | ||
| 431 | } | ||
| 432 | ReleaseSRWLockExclusive(&lock_); | ||
| 433 | return written; | ||
| 434 | } | ||
| 435 | |||
| 376 | // The bytes of all targets, and how many there are. | 436 | // The bytes of all targets, and how many there are. |
| 377 | std::size_t size() const { return target_bytes_; } | 437 | std::size_t size() const { return target_bytes_; } |
| 378 | std::size_t targets() const { return targets_.size(); } | 438 | std::size_t targets() const { return targets_.size(); } |
| @@ -1387,6 +1447,30 @@ std::filesystem::path pipeline_cache_session_path() { | |||
| 1387 | return path; | 1447 | return path; |
| 1388 | } | 1448 | } |
| 1389 | 1449 | ||
| 1450 | // The pipelines the offline seed does not have, kept next to it and written while the game runs | ||
| 1451 | // (src/heavy_pipeline_cache.h). | ||
| 1452 | std::filesystem::path pipeline_cache_heavy_path() { | ||
| 1453 | std::filesystem::path path = pipeline_cache_path(); | ||
| 1454 | if (!path.empty()) path.replace_filename(L"pipeline_cache.heavy.bin"); | ||
| 1455 | return path; | ||
| 1456 | } | ||
| 1457 | |||
| 1458 | // LEONIDA_HEAVY_PIPELINE_CACHE_MS: a compile at least this long schedules a write of the heavy cache; 0 turns the | ||
| 1459 | // heavy cache off. One line for a value that is not a number. | ||
| 1460 | std::uint32_t heavy_pipeline_cache_ms() { | ||
| 1461 | static const std::uint32_t ms = [] { | ||
| 1462 | char text[32] = {}; | ||
| 1463 | size_t length = 0; | ||
| 1464 | const bool present = getenv_s(&length, text, "LEONIDA_HEAVY_PIPELINE_CACHE_MS") == 0 && length > 1; | ||
| 1465 | const auto threshold = leonida::heavy_pipeline_cache::parse_threshold(present ? text : ""); | ||
| 1466 | if (!threshold.valid) | ||
| 1467 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAVY_PIPELINE_CACHE_MS=%s is not a number of milliseconds; " | ||
| 1468 | "using %u\n", text, threshold.ms); | ||
| 1469 | return threshold.ms; | ||
| 1470 | }(); | ||
| 1471 | return ms; | ||
| 1472 | } | ||
| 1473 | |||
| 1390 | std::size_t pipeline_cache_save_limit(); | 1474 | std::size_t pipeline_cache_save_limit(); |
| 1391 | 1475 | ||
| 1392 | // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): where each compute pipeline's own cache file goes, beside | 1476 | // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): where each compute pipeline's own cache file goes, beside |
| @@ -1670,6 +1754,66 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev | |||
| 1670 | else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); | 1754 | else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); |
| 1671 | } | 1755 | } |
| 1672 | 1756 | ||
| 1757 | // The heavy cache, seeded from pipeline_cache.heavy.bin when it is there and made for this device; empty otherwise. | ||
| 1758 | VkPipelineCache create_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, | ||
| 1759 | const leonida::cached_pso::Identity& identity) { | ||
| 1760 | const auto path = pipeline_cache_heavy_path(); | ||
| 1761 | clean_stale_cache_files(path); | ||
| 1762 | VkPipelineCache cache = VK_NULL_HANDLE; | ||
| 1763 | { | ||
| 1764 | const PipelineCacheSeed seed(path); | ||
| 1765 | if (seed.data() && seed.compatible(identity)) { | ||
| 1766 | const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, | ||
| 1767 | seed.size(), seed.data()}; | ||
| 1768 | if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) == VK_SUCCESS) { | ||
| 1769 | std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from pipeline_cache.heavy.bin\n", seed.size()); | ||
| 1770 | return cache; | ||
| 1771 | } | ||
| 1772 | std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.heavy.bin; starting it empty\n"); | ||
| 1773 | } else if (seed.data()) { | ||
| 1774 | std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin does not match this Vulkan device; starting " | ||
| 1775 | "it empty\n"); | ||
| 1776 | } | ||
| 1777 | } | ||
| 1778 | const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; | ||
| 1779 | if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) != VK_SUCCESS) return VK_NULL_HANDLE; | ||
| 1780 | return cache; | ||
| 1781 | } | ||
| 1782 | |||
| 1783 | // Writes the heavy cache whole: a staging file renamed over pipeline_cache.heavy.bin, so the file on disk is always | ||
| 1784 | // a complete blob. It only holds what the offline seed missed, so it has no size limit of its own. | ||
| 1785 | bool save_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, | ||
| 1786 | std::uint64_t compiles, std::uint64_t hits) { | ||
| 1787 | if (!cache || !vk.vkGetPipelineCacheData) return false; | ||
| 1788 | const auto path = pipeline_cache_heavy_path(); | ||
| 1789 | if (path.empty()) return false; | ||
| 1790 | const auto start = compile_us(); | ||
| 1791 | std::size_t size = 0; | ||
| 1792 | if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || | ||
| 1793 | size <= sizeof(VkPipelineCacheHeaderVersionOne)) | ||
| 1794 | return false; | ||
| 1795 | CacheStagingFile staging(path, size); | ||
| 1796 | if (!staging.data) { | ||
| 1797 | std::fprintf(stderr, "[rt] d3d12: could not map a staging file for %zu heavy pipeline cache bytes\n", size); | ||
| 1798 | return false; | ||
| 1799 | } | ||
| 1800 | auto written = size; | ||
| 1801 | const VkResult result = vk.vkGetPipelineCacheData(device, cache, &written, staging.data); | ||
| 1802 | // VK_INCOMPLETE means the cache grew after the size query and the blob is a truncated snapshot; it must not | ||
| 1803 | // replace a complete file. The writer tries again later with a fresh size. | ||
| 1804 | const bool ok = result == VK_SUCCESS && written > sizeof(VkPipelineCacheHeaderVersionOne) && written <= size && | ||
| 1805 | staging.publish(path, written); | ||
| 1806 | if (ok) | ||
| 1807 | std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.heavy.bin in %.1f s (%llu slow builds " | ||
| 1808 | "and %llu other builds past the offline cache so far)\n", | ||
| 1809 | written, double(compile_us() - start) / 1e6, static_cast<unsigned long long>(compiles), | ||
| 1810 | static_cast<unsigned long long>(hits)); | ||
| 1811 | else | ||
| 1812 | std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin not written (%d); the previous file is kept\n", | ||
| 1813 | int(result)); | ||
| 1814 | return ok; | ||
| 1815 | } | ||
| 1816 | |||
| 1673 | // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, | 1817 | // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, |
| 1674 | // for a wave32 shader on a 64-wide default, reads lanes that are not its own), unless the translator's | 1818 | // for a wave32 shader on a 64-wide default, reads lanes that are not its own), unless the translator's |
| 1675 | // partition-invariance tier says otherwise. Logged once per stage with the first shader's name, then again at 10, 100, | 1819 | // partition-invariance tier says otherwise. Logged once per stage with the first shader's name, then again at 10, 100, |
| @@ -2305,6 +2449,105 @@ struct DeviceState { | |||
| 2305 | return pipeline_cache_handle; | 2449 | return pipeline_cache_handle; |
| 2306 | } | 2450 | } |
| 2307 | 2451 | ||
| 2452 | // The heavy pipeline cache (src/heavy_pipeline_cache.h) and the thread that writes it. | ||
| 2453 | std::once_flag heavy_cache_once; | ||
| 2454 | VkPipelineCache heavy_cache_handle = VK_NULL_HANDLE; | ||
| 2455 | std::mutex heavy_mutex; | ||
| 2456 | std::condition_variable heavy_wake; | ||
| 2457 | leonida::heavy_pipeline_cache::WriteSchedule heavy_schedule; // under heavy_mutex | ||
| 2458 | bool heavy_stop = false; // under heavy_mutex | ||
| 2459 | std::thread heavy_writer; // started at the first slow build | ||
| 2460 | std::atomic<std::uint64_t> heavy_compiles{0}, heavy_hits{0}; | ||
| 2461 | std::atomic<bool> heavy_changed{false}; // a build went into the heavy cache since it was loaded | ||
| 2462 | |||
| 2463 | VkPipelineCache heavy_cache() { | ||
| 2464 | std::call_once(heavy_cache_once, [this] { | ||
| 2465 | if (context->vk.vkCreatePipelineCache) | ||
| 2466 | heavy_cache_handle = create_heavy_pipeline_cache(context->vk, info.device, pso_identity); | ||
| 2467 | }); | ||
| 2468 | return heavy_cache_handle; | ||
| 2469 | } | ||
| 2470 | |||
| 2471 | // A build past the offline cache took `took_ms`: a slow one schedules a write. | ||
| 2472 | void note_heavy_build(ULONGLONG took_ms) { | ||
| 2473 | heavy_changed = true; | ||
| 2474 | if (took_ms < heavy_pipeline_cache_ms()) { | ||
| 2475 | ++heavy_hits; | ||
| 2476 | return; | ||
| 2477 | } | ||
| 2478 | ++heavy_compiles; | ||
| 2479 | std::lock_guard lock(heavy_mutex); | ||
| 2480 | if (heavy_stop) return; | ||
| 2481 | heavy_schedule.note_heavy(GetTickCount64()); | ||
| 2482 | if (!heavy_writer.joinable()) { | ||
| 2483 | try { | ||
| 2484 | heavy_writer = std::thread([this] { write_heavy_cache_loop(); }); | ||
| 2485 | } catch (const std::exception&) { | ||
| 2486 | return; // no thread: the cache is still written at teardown | ||
| 2487 | } | ||
| 2488 | } | ||
| 2489 | heavy_wake.notify_one(); | ||
| 2490 | } | ||
| 2491 | |||
| 2492 | void write_heavy_cache_loop() { | ||
| 2493 | SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); | ||
| 2494 | std::unique_lock lock(heavy_mutex); | ||
| 2495 | while (!heavy_stop) { | ||
| 2496 | if (!heavy_schedule.dirty()) { | ||
| 2497 | heavy_wake.wait(lock); | ||
| 2498 | continue; | ||
| 2499 | } | ||
| 2500 | const std::uint64_t now = GetTickCount64(); | ||
| 2501 | if (!heavy_schedule.due(now)) { | ||
| 2502 | heavy_wake.wait_for(lock, std::chrono::milliseconds(heavy_schedule.due_ms() - now)); | ||
| 2503 | continue; | ||
| 2504 | } | ||
| 2505 | const std::uint64_t generation = heavy_schedule.generation(); | ||
| 2506 | lock.unlock(); | ||
| 2507 | const bool saved = save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, | ||
| 2508 | heavy_compiles.load(), heavy_hits.load()); | ||
| 2509 | lock.lock(); | ||
| 2510 | // A failed write leaves the cache dirty: it is tried again after a growing delay, not only at teardown. | ||
| 2511 | if (saved) heavy_schedule.written(generation, now); | ||
| 2512 | else heavy_schedule.failed(now); | ||
| 2513 | } | ||
| 2514 | } | ||
| 2515 | |||
| 2516 | // At device teardown, with no build running: stop the writer and write the cache if any build went into it. | ||
| 2517 | // Fast builds never schedule a write, so this is where they are kept: without an offline seed every build is | ||
| 2518 | // a miss, and these are the builds pipeline_cache.session.bin used to keep. | ||
| 2519 | void finish_heavy_cache() { | ||
| 2520 | { | ||
| 2521 | std::lock_guard lock(heavy_mutex); | ||
| 2522 | heavy_stop = true; | ||
| 2523 | } | ||
| 2524 | heavy_wake.notify_all(); | ||
| 2525 | if (heavy_writer.joinable()) heavy_writer.join(); | ||
| 2526 | if (!heavy_cache_handle) return; | ||
| 2527 | if (heavy_changed.load() && !active_compiles.load()) | ||
| 2528 | save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, heavy_compiles.load(), | ||
| 2529 | heavy_hits.load()); | ||
| 2530 | context->vk.vkDestroyPipelineCache(info.device, heavy_cache_handle, nullptr); | ||
| 2531 | heavy_cache_handle = VK_NULL_HANDLE; | ||
| 2532 | } | ||
| 2533 | |||
| 2534 | // vkCreateGraphicsPipelines through `create(cache, flags)` (compute pipelines have their journal). With the heavy | ||
| 2535 | // cache, the offline cache is asked first without compiling; a pipeline it does not have is built against the heavy | ||
| 2536 | // cache, which a slow build then writes back to disk. A caller that already asked for a cache-only create keeps it. | ||
| 2537 | template <class Create> | ||
| 2538 | VkResult create_pipeline(VkPipelineCreateFlags flags, Create&& create) { | ||
| 2539 | constexpr VkPipelineCreateFlags cache_only = VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT; | ||
| 2540 | const VkPipelineCache corpus = pipeline_cache(); | ||
| 2541 | if (!info.heavy_pipeline_cache || (flags & cache_only)) return create(corpus, flags); | ||
| 2542 | const VkResult cached = create(corpus, flags | cache_only); | ||
| 2543 | if (cached != VK_PIPELINE_COMPILE_REQUIRED) return cached; | ||
| 2544 | const VkPipelineCache heavy = heavy_cache(); | ||
| 2545 | const ULONGLONG started = GetTickCount64(); | ||
| 2546 | const VkResult built = create(heavy ? heavy : corpus, flags); | ||
| 2547 | if (built == VK_SUCCESS && heavy) note_heavy_build(GetTickCount64() - started); | ||
| 2548 | return built; | ||
| 2549 | } | ||
| 2550 | |||
| 2308 | QueueClock clock; // device-wide calibration entry points | 2551 | QueueClock clock; // device-wide calibration entry points |
| 2309 | std::vector<std::uint32_t> timestamp_bits; | 2552 | std::vector<std::uint32_t> timestamp_bits; |
| 2310 | 2553 | ||
| @@ -2442,6 +2685,7 @@ struct DeviceState { | |||
| 2442 | if (!pages) return; | 2685 | if (!pages) return; |
| 2443 | const leonida::submit_phases::Scope timed(leonida::submit_phases::shadows); | 2686 | const leonida::submit_phases::Scope timed(leonida::submit_phases::shadows); |
| 2444 | std::lock_guard lock(shadow_mutex); | 2687 | std::lock_guard lock(shadow_mutex); |
| 2688 | write_back_titles(); // what the last submission wrote in the copies, before the forward copy below | ||
| 2445 | if (shadows.empty()) return; | 2689 | if (shadows.empty()) return; |
| 2446 | const auto start = clock::now(); | 2690 | const auto start = clock::now(); |
| 2447 | // LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses, which no guard | 2691 | // LEONIDA_SHADOW_ALIAS_MS (0 by default: every submission): pages xmem maps at two addresses, which no guard |
| @@ -2568,7 +2812,24 @@ struct DeviceState { | |||
| 2568 | std::atomic<std::size_t> title_window_count{0}; // title_windows.size(), read without the mutex | 2812 | std::atomic<std::size_t> title_window_count{0}; // title_windows.size(), read without the mutex |
| 2569 | std::uint64_t title_window_bytes = 0; | 2813 | std::uint64_t title_window_bytes = 0; |
| 2570 | std::uint64_t title_window_cap = 64ull << 20; | 2814 | std::uint64_t title_window_cap = 64ull << 20; |
| 2571 | // The stream pools' mappings (title_gpu_views): one per readable run of a pool, kept for the device's life. | 2815 | // What the GPU wrote into a copy of the title's memory goes back to the title's pages: the ranges reached since |
| 2816 | // the last submission (title_va_alias.h note_reached), copied back at the next refresh before the forward copy. | ||
| 2817 | // A window is a read-side mirror, so without this a UAV or a raw write lands in the copy and the title never sees | ||
| 2818 | // it (#1537, the WRITE_INVALID stop at the world start). | ||
| 2819 | std::mutex title_write_back_mutex; // its own: taken under shadow_mutex, never the other way round | ||
| 2820 | std::map<std::uint64_t, std::uint64_t> title_write_back; // start -> end, of the submission about to run | ||
| 2821 | std::deque<std::pair<std::uint64_t, std::map<std::uint64_t, std::uint64_t>>> title_write_back_pending; // by ticket | ||
| 2822 | std::uint64_t title_write_back_refused = 0; // ranges past the caps, logged once | ||
| 2823 | std::uint64_t title_write_back_bytes = 0; // queued for this submission | ||
| 2824 | std::uint64_t title_write_back_total = 0; // copied back, all submissions | ||
| 2825 | std::uint64_t title_write_back_calls = 0; // log line count | ||
| 2826 | std::uint64_t title_write_back_unfenced = 0; | ||
| 2827 | static constexpr std::size_t kTitleWriteBackBatches = 64; // pending batches before the oldest goes back unfenced | ||
| 2828 | static constexpr std::size_t kTitleWriteBackRanges = 8192; // ranges kept per submission | ||
| 2829 | static constexpr std::uint64_t kTitleWriteBackBytes = 64ull << 20; // bytes copied back per submission | ||
| 2830 | // The stream pools' mappings (title_gpu_views): one per readable run of a pool. A window is kept for the device's | ||
| 2831 | // life; a geometry copy goes when its view is retired (the pages were freed, unmapped or remapped: | ||
| 2832 | // drain_geometry_releases), and the next request for those pages makes a new one. | ||
| 2572 | struct PoolSpan { | 2833 | struct PoolSpan { |
| 2573 | std::uint64_t source; // the readable side of the pair the copy is made from | 2834 | std::uint64_t source; // the readable side of the pair the copy is made from |
| 2574 | std::uint64_t twin; // the extent's address in the pair's other view (0 when there is none) | 2835 | std::uint64_t twin; // the extent's address in the pair's other view (0 when there is none) |
| @@ -2579,6 +2840,7 @@ struct DeviceState { | |||
| 2579 | std::vector<PoolSpan> pool_spans; | 2840 | std::vector<PoolSpan> pool_spans; |
| 2580 | std::atomic<std::size_t> pool_span_count{0}; | 2841 | std::atomic<std::size_t> pool_span_count{0}; |
| 2581 | std::uint64_t pool_span_bytes = 0; | 2842 | std::uint64_t pool_span_bytes = 0; |
| 2843 | std::uint64_t pool_spans_retired = 0; // geometry-copy extents whose view was retired (forget_pool_span) | ||
| 2582 | std::uint64_t title_window_refusals = 0; // windows neither the budget nor the arena allowed | 2844 | std::uint64_t title_window_refusals = 0; // windows neither the budget nor the arena allowed |
| 2583 | std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views) | 2845 | std::uint64_t unbacked_requests = 0; // title addresses no backing could be made for (zero-size views) |
| 2584 | 2846 | ||
| @@ -2600,26 +2862,67 @@ struct DeviceState { | |||
| 2600 | // another queue's replay that translated its slots before this retirement may still name it. A ticket read here | 2862 | // another queue's replay that translated its slots before this retirement may still name it. A ticket read here |
| 2601 | // would be one short of this submission, which records its own only after before_execute_ (and with an idle GPU | 2863 | // would be one short of this submission, which records its own only after before_execute_ (and with an idle GPU |
| 2602 | // the view would be reaped in this very call). | 2864 | // the view would be reaped in this very call). |
| 2865 | // A retired view's last copy is made here from the title's pages as they are now (GeometryViews::retire_range): a | ||
| 2866 | // range the title remapped (xmem's RemapReleases) holds its new bytes, which the refresh below would have copied. | ||
| 2867 | // A stream-pool extent it backed leaves pool_spans: the next request for those pages makes a new mapping. | ||
| 2603 | void drain_geometry_releases() { | 2868 | void drain_geometry_releases() { |
| 2604 | if (!context || !geometry.has_pending_reclaim()) return; | 2869 | if (!context || !geometry.has_pending_reclaim()) return; |
| 2605 | const std::uint64_t completed_ticket = geometry.has_retired() ? context->completed_retire_ticket() : 0; | 2870 | const std::uint64_t completed_ticket = geometry.has_retired() ? context->completed_retire_ticket() : 0; |
| 2606 | geometry.drain_released(*this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket, | 2871 | geometry.drain_released( |
| 2607 | forget_geometry_alias); | 2872 | *this, rt::d3d12::GeometryViews::kAfterExecutes, completed_ticket, |
| 2873 | [this](std::uintptr_t source, std::size_t size, VkDeviceSize va) { | ||
| 2874 | forget_geometry_alias(source, size, va); | ||
| 2875 | forget_pool_span(va); | ||
| 2876 | }, | ||
| 2877 | copy_geometry); | ||
| 2878 | } | ||
| 2879 | void forget_pool_span(VkDeviceSize va) { | ||
| 2880 | std::lock_guard windows(title_window_mutex); | ||
| 2881 | const auto it = std::find_if(pool_spans.begin(), pool_spans.end(), | ||
| 2882 | [&](const PoolSpan& span) { return span.geometry && span.shader_va == va; }); | ||
| 2883 | if (it == pool_spans.end()) return; | ||
| 2884 | pool_span_bytes -= it->size; | ||
| 2885 | pool_spans.erase(it); | ||
| 2886 | pool_span_count.store(pool_spans.size(), std::memory_order_relaxed); | ||
| 2887 | ++pool_spans_retired; | ||
| 2608 | } | 2888 | } |
| 2609 | // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases). | 2889 | // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases). |
| 2610 | static std::vector<std::uint64_t>& geometry_execute_serials() { | 2890 | // A plain aggregate on purpose: a C++ thread_local with a destructor in gta6rt.exe adds TLS callbacks to the image |
| 2611 | thread_local std::vector<std::uint64_t> serials; | 2891 | // the loader's TLS index-0 move must not have (pe_loader.cpp reserve_tls_index0; VulkanContext::stage_xdxr_table |
| 2892 | // keeps its range list a member for the same reason). A std::vector here made the title's CRT abort at startup. | ||
| 2893 | struct GeometryExecuteSerials { | ||
| 2894 | static constexpr unsigned kCapacity = 32; // a replay has not been seen nested this deep | ||
| 2895 | std::uint64_t serials[kCapacity]{}; | ||
| 2896 | unsigned count{}; | ||
| 2897 | unsigned skipped{}; // replays begun while the stack was full: the innermost, ended first | ||
| 2898 | }; | ||
| 2899 | static GeometryExecuteSerials& geometry_execute_serials() { | ||
| 2900 | thread_local GeometryExecuteSerials serials; | ||
| 2612 | return serials; | 2901 | return serials; |
| 2613 | } | 2902 | } |
| 2614 | void geometry_execute_begin() { | 2903 | void geometry_execute_begin() { |
| 2615 | if (!geometry.cap()) return; | 2904 | if (!geometry.cap()) return; |
| 2616 | geometry_execute_serials().push_back(geometry.execute_begin()); | 2905 | auto& serials = geometry_execute_serials(); |
| 2906 | if (serials.count == GeometryExecuteSerials::kCapacity) { | ||
| 2907 | static std::atomic<bool> logged{false}; | ||
| 2908 | if (!logged.exchange(true)) | ||
| 2909 | std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists nested more than %u deep; a geometry view retired " | ||
| 2910 | "in the extra replay is not deferred to it\n", | ||
| 2911 | GeometryExecuteSerials::kCapacity); | ||
| 2912 | ++serials.skipped; | ||
| 2913 | return; | ||
| 2914 | } | ||
| 2915 | serials.serials[serials.count++] = geometry.execute_begin(); | ||
| 2617 | } | 2916 | } |
| 2618 | void geometry_execute_end() { | 2917 | void geometry_execute_end() { |
| 2918 | if (!geometry.cap()) return; | ||
| 2619 | auto& serials = geometry_execute_serials(); | 2919 | auto& serials = geometry_execute_serials(); |
| 2620 | if (!geometry.cap() || serials.empty()) return; | 2920 | if (serials.skipped != 0) { |
| 2621 | const std::uint64_t serial = serials.back(); | 2921 | --serials.skipped; |
| 2622 | serials.pop_back(); | 2922 | return; |
| 2923 | } | ||
| 2924 | if (serials.count == 0) return; | ||
| 2925 | const std::uint64_t serial = serials.serials[--serials.count]; | ||
| 2623 | geometry.execute_end(serial, [this] { return context->submitted_retire_ticket(); }); | 2926 | geometry.execute_end(serial, [this] { return context->submitted_retire_ticket(); }); |
| 2624 | } | 2927 | } |
| 2625 | static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { | 2928 | static rt::d3d12::GeometryCopy copy_geometry(std::uint8_t* to, const std::uint8_t* from, std::size_t size) { |
| @@ -2733,6 +3036,93 @@ struct DeviceState { | |||
| 2733 | return offset; | 3036 | return offset; |
| 2734 | } | 3037 | } |
| 2735 | 3038 | ||
| 3039 | // A binding of the title's memory reached for the coming submission: keep its range for the copy back after it. | ||
| 3040 | // Over-inclusive on purpose (a read-only view costs a copy, a write is never missed: a V# has no read/write bit). | ||
| 3041 | void note_title_write(std::uint64_t va, std::uint64_t bytes) { | ||
| 3042 | static const bool on = [] { | ||
| 3043 | char value[2] = {}; | ||
| 3044 | std::size_t length = 0; | ||
| 3045 | return getenv_s(&length, value, sizeof(value), "LEONIDA_TITLE_WRITEBACK") != 0 || value[0] != '0'; | ||
| 3046 | }(); | ||
| 3047 | if (!on || !va || !bytes) return; | ||
| 3048 | std::uint64_t lo = 0, hi = 0; | ||
| 3049 | if (!leonida::title_va_aliases().title_memory(va, lo, hi) || va >= hi) return; | ||
| 3050 | const std::uint64_t end = va + std::min(bytes, hi - va); | ||
| 3051 | std::lock_guard lock(title_write_back_mutex); | ||
| 3052 | auto it = title_write_back.lower_bound(va); | ||
| 3053 | if (it != title_write_back.begin()) { | ||
| 3054 | auto previous = std::prev(it); | ||
| 3055 | if (previous->second >= va) { | ||
| 3056 | if (previous->second < end) previous->second = end; | ||
| 3057 | return; | ||
| 3058 | } | ||
| 3059 | } | ||
| 3060 | if (it != title_write_back.end() && it->first <= end) { | ||
| 3061 | it->second = std::max(it->second, end); | ||
| 3062 | return; | ||
| 3063 | } | ||
| 3064 | if (title_write_back.size() >= kTitleWriteBackRanges || title_write_back_bytes >= kTitleWriteBackBytes) { | ||
| 3065 | if (!title_write_back_refused++) | ||
| 3066 | log_once("past LEONIDA_TITLE_WRITEBACK's caps: reached ranges are not copied back this submission; " | ||
| 3067 | "ranges refused:", | ||
| 3068 | 1); | ||
| 3069 | return; | ||
| 3070 | } | ||
| 3071 | title_write_back_bytes += end - va; | ||
| 3072 | title_write_back.emplace(va, end); | ||
| 3073 | } | ||
| 3074 | |||
| 3075 | // What the GPU wrote into those copies goes back to the title's pages, so a later read by the title or the next | ||
| 3076 | // forward copy sees it. Only once the submission that wrote them has completed: a batch carries the ticket of the | ||
| 3077 | // submission after it (a submission's commands are recorded before it exists), and is copied back when the | ||
| 3078 | // context reports that ticket done. Runs at the start of a refresh, under shadow_mutex and before the forward | ||
| 3079 | // copies, so a page the title wrote again is copied forward over the result. | ||
| 3080 | void write_back_titles() { | ||
| 3081 | if (!&context) return; | ||
| 3082 | const std::uint64_t done = context->completed_retire_ticket(); | ||
| 3083 | std::vector<std::pair<uint64_t, std::uint64_t>> finished; // one entry per range, collected under the lock | ||
| 3084 | { | ||
| 3085 | std::lock_guard lock(title_write_back_mutex); | ||
| 3086 | if (!title_write_back.empty()) { | ||
| 3087 | // The ranges of the submission about to execute, which is the next ticket. | ||
| 3088 | title_write_back_pending.push_back({context->submitted_retire_ticket() + 1, | ||
| 3089 | std::move(title_write_back)}); | ||
| 3090 | title_write_back.clear(); | ||
| 3091 | title_write_back_bytes = 0; | ||
| 3092 | } | ||
| 3093 | bool forced = false; | ||
| 3094 | while (!title_write_back_pending.empty() && | ||
| 3095 | (title_write_back_pending.front().first <= done || | ||
| 3096 | title_write_back_pending.size() > kTitleWriteBackBatches)) { | ||
| 3097 | forced = forced || title_write_back_pending.front().first > done; | ||
| 3098 | for (const auto& [begin, end] : title_write_back_pending.front().second) | ||
| 3099 | finished.push_back({begin, end}); | ||
| 3100 | title_write_back_pending.pop_front(); | ||
| 3101 | } | ||
| 3102 | // A queue held deep (console ordering) can leave batches waiting: the oldest go back anyway, once each. | ||
| 3103 | if (forced && !title_write_back_unfenced++) | ||
| 3104 | log_once("more than 64 title write-back batches wait on their submissions: the oldest are copied " | ||
| 3105 | "back without their ticket; batches:", | ||
| 3106 | 1); | ||
| 3107 | } | ||
| 3108 | if (finished.empty()) return; | ||
| 3109 | std::uint64_t written = 0, ranges = 0; | ||
| 3110 | for (const auto& [begin, end] : finished) | ||
| 3111 | for (const ShadowPagesPtr& s : shadows) | ||
| 3112 | if (end > s->first() && begin < s->last()) { | ||
| 3113 | const std::uint64_t bytes = s->write_back(begin, end); | ||
| 3114 | written += bytes; | ||
| 3115 | ranges += bytes != 0; | ||
| 3116 | } | ||
| 3117 | title_write_back_total += written; | ||
| 3118 | if (!written) return; | ||
| 3119 | if (++title_write_back_calls <= 4 || !(title_write_back_calls & (title_write_back_calls - 1))) | ||
| 3120 | std::fprintf(stderr, "[rt] d3d12: %llu KiB of the GPU's writes in %llu reached range(s) went back to the " | ||
| 3121 | "title's pages (%llu KiB so far)\n", | ||
| 3122 | static_cast<unsigned long long>(written >> 10), static_cast<unsigned long long>(ranges), | ||
| 3123 | static_cast<unsigned long long>(title_write_back_total >> 10)); | ||
| 3124 | } | ||
| 3125 | |||
| 2736 | // A stream pool's address (a CPU view paired with a GPU-only alias). Rule B | 3126 | // A stream pool's address (a CPU view paired with a GPU-only alias). Rule B |
| 2737 | // first: the CPU view is where the host reads the frames, so that is what the copy is made from; the GPU-only | 3127 | // first: the CPU view is where the host reads the frames, so that is what the copy is made from; the GPU-only |
| 2738 | // pages are the same frames through the title's queue slot 31 and are read only when the CPU view is not | 3128 | // pages are the same frames through the title's queue slot 31 and are read only when the CPU view is not |
| @@ -3471,6 +3861,45 @@ struct DeviceState { | |||
| 3471 | static constexpr unsigned kVsharpPathCount = 6; | 3861 | static constexpr unsigned kVsharpPathCount = 6; |
| 3472 | std::array<std::atomic<std::uint64_t>, kVsharpPathCount> vsharp_paths{}; | 3862 | std::array<std::atomic<std::uint64_t>, kVsharpPathCount> vsharp_paths{}; |
| 3473 | 3863 | ||
| 3864 | // LEONIDA_UNBACKED_VSHARP=1 (diagnostic): the buffer V#s fix_vsharp writes empty because nothing backs their base. | ||
| 3865 | // One line for each of the first 120 distinct bases (span and stride), and every 8192 such V#s a summary by 4 GiB | ||
| 3866 | // range of the base, so the address ranges the world's data comes from can be compared with the title memory. | ||
| 3867 | static void note_unbacked_vsharp(uint64_t base, uint64_t span, uint32_t stride, const uint32_t* w) { | ||
| 3868 | static const bool on = [] { | ||
| 3869 | const char* v = std::getenv("LEONIDA_UNBACKED_VSHARP"); | ||
| 3870 | return v && *v == '1'; | ||
| 3871 | }(); | ||
| 3872 | if (!on) return; | ||
| 3873 | static std::mutex mutex; | ||
| 3874 | static std::unordered_map<uint64_t, uint64_t> seen; // base -> span | ||
| 3875 | static std::map<uint64_t, uint64_t> by_range; // base >> 32 -> distinct bases | ||
| 3876 | static uint64_t count = 0; | ||
| 3877 | std::lock_guard lock(mutex); | ||
| 3878 | ++count; | ||
| 3879 | if (seen.emplace(base, span).second) { | ||
| 3880 | ++by_range[base >> 32]; | ||
| 3881 | if (seen.size() <= 120) | ||
| 3882 | std::fprintf(stderr, | ||
| 3883 | "[rt] unbacked-vsharp: #%zu base 0x%llx span %llu stride %u words %08x %08x %08x %08x\n", | ||
| 3884 | seen.size(), static_cast<unsigned long long>(base), static_cast<unsigned long long>(span), | ||
| 3885 | stride, w[0], w[1], w[2], w[3]); | ||
| 3886 | } | ||
| 3887 | if (!(count % 8192)) { | ||
| 3888 | std::vector<std::pair<uint64_t, uint64_t>> top; | ||
| 3889 | for (const auto& [range, n] : by_range) top.emplace_back(n, range); | ||
| 3890 | std::sort(top.rbegin(), top.rend()); | ||
| 3891 | std::string text; | ||
| 3892 | char item[64]; | ||
| 3893 | for (std::size_t i = 0; i < top.size() && i < 10; ++i) { | ||
| 3894 | std::snprintf(item, sizeof(item), "%s0x%llx00000000 x%llu", i ? "; " : "", | ||
| 3895 | static_cast<unsigned long long>(top[i].second), static_cast<unsigned long long>(top[i].first)); | ||
| 3896 | text += item; | ||
| 3897 | } | ||
| 3898 | std::fprintf(stderr, "[rt] unbacked-vsharp: %llu empty V#s, %zu distinct bases; by 4 GiB range: %s\n", | ||
| 3899 | static_cast<unsigned long long>(count), seen.size(), text.c_str()); | ||
| 3900 | } | ||
| 3901 | } | ||
| 3902 | |||
| 3474 | VsharpResult fix_vsharp(uint32_t* w, VsharpPath path) { | 3903 | VsharpResult fix_vsharp(uint32_t* w, VsharpPath path) { |
| 3475 | if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer | 3904 | if ((w[3] >> 30) || !w[2]) return VsharpResult::unchanged; // image, empty slot or raw pointer |
| 3476 | const uint64_t base = uint64_t(w[0]) | (uint64_t(w[1] & 0xffff) << 32); | 3905 | const uint64_t base = uint64_t(w[0]) | (uint64_t(w[1] & 0xffff) << 32); |
| @@ -3490,6 +3919,7 @@ struct DeviceState { | |||
| 3490 | std::fprintf(stderr, "[rt] d3d12: %s V# at 0x%llx (%llu bytes) has no GPU backing; zero records\n", | 3919 | std::fprintf(stderr, "[rt] d3d12: %s V# at 0x%llx (%llu bytes) has no GPU backing; zero records\n", |
| 3491 | where, (unsigned long long)base, (unsigned long long)span); | 3920 | where, (unsigned long long)base, (unsigned long long)span); |
| 3492 | } | 3921 | } |
| 3922 | note_unbacked_vsharp(base, span, stride, w); | ||
| 3493 | w[0] = w[1] = w[2] = 0; | 3923 | w[0] = w[1] = w[2] = 0; |
| 3494 | return VsharpResult::empty; | 3924 | return VsharpResult::empty; |
| 3495 | } | 3925 | } |
| @@ -3685,13 +4115,13 @@ struct DeviceState { | |||
| 3685 | [](const PoolSpan& span) { return span.geometry; }); | 4115 | [](const PoolSpan& span) { return span.geometry; }); |
| 3686 | std::fprintf(stderr, | 4116 | std::fprintf(stderr, |
| 3687 | "[rt] d3d12: title memory: %zu windows (%llu KiB of a %llu MiB budget, %llu refused), %zu " | 4117 | "[rt] d3d12: title memory: %zu windows (%llu KiB of a %llu MiB budget, %llu refused), %zu " |
| 3688 | "stream-pool extents (one mapping each, %llu KiB; %lld by geometry copy), %llu addresses " | 4118 | "stream-pool extents (one mapping each, %llu KiB; %lld by geometry copy, %llu retired with " |
| 3689 | "given a zero-size view\n", | 4119 | "their copy), %llu addresses given a zero-size view\n", |
| 3690 | title_windows.size(), static_cast<unsigned long long>(title_window_bytes >> 10), | 4120 | title_windows.size(), static_cast<unsigned long long>(title_window_bytes >> 10), |
| 3691 | static_cast<unsigned long long>(title_window_cap >> 20), | 4121 | static_cast<unsigned long long>(title_window_cap >> 20), |
| 3692 | static_cast<unsigned long long>(title_window_refusals), pool_spans.size(), | 4122 | static_cast<unsigned long long>(title_window_refusals), pool_spans.size(), |
| 3693 | static_cast<unsigned long long>(pool_span_bytes >> 10), | 4123 | static_cast<unsigned long long>(pool_span_bytes >> 10), |
| 3694 | static_cast<long long>(geometry_spans), | 4124 | static_cast<long long>(geometry_spans), static_cast<unsigned long long>(pool_spans_retired), |
| 3695 | static_cast<unsigned long long>(unbacked_requests)); | 4125 | static_cast<unsigned long long>(unbacked_requests)); |
| 3696 | } | 4126 | } |
| 3697 | } | 4127 | } |
| @@ -3758,7 +4188,10 @@ struct DeviceState { | |||
| 3758 | VkDeviceSize guard = 0; // null bytes after the GPU copy (heap_guard_bytes/heap_guard_for), its allocation | 4188 | VkDeviceSize guard = 0; // null bytes after the GPU copy (heap_guard_bytes/heap_guard_for), its allocation |
| 3759 | bool resource_heap = false; // a CBV/SRV/UAV heap; a sampler heap's S#s are copied as written | 4189 | bool resource_heap = false; // a CBV/SRV/UAV heap; a sampler heap's S#s are copied as written |
| 3760 | bool imported = false; | 4190 | bool imported = false; |
| 3761 | std::uint8_t* copy = nullptr; // writable GPU mirror of the console heap | 4191 | // The translated copy shaders read, and its host-RAM mirror (src/console_heap_copy.h): written only through |
| 4192 | // copy.write()/copy.zero(), read on the CPU only through copy.view(). | ||
| 4193 | leonida::ConsoleHeapCopy copy; | ||
| 4194 | std::uint64_t mirror_checks = 0, mirror_mismatches = 0; // LEONIDA_HEAP_MIRROR_CHECK, since the last log line | ||
| 3762 | // Keep large scratch allocations out of the low addresses the title can use for its heap. | 4195 | // Keep large scratch allocations out of the low addresses the title can use for its heap. |
| 3763 | std::unique_ptr<std::uint8_t, FreeConsoleScratch> scratch; | 4196 | std::unique_ptr<std::uint8_t, FreeConsoleScratch> scratch; |
| 3764 | std::uint8_t* input{}; | 4197 | std::uint8_t* input{}; |
| @@ -3937,7 +4370,7 @@ struct DeviceState { | |||
| 3937 | } | 4370 | } |
| 3938 | if (empty) heap.empty_slots.insert(std::uint32_t(slot)); | 4371 | if (empty) heap.empty_slots.insert(std::uint32_t(slot)); |
| 3939 | else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot)); | 4372 | else if (!heap.empty_slots.empty()) heap.empty_slots.erase(std::uint32_t(slot)); |
| 3940 | std::memcpy(heap.copy + slot * kDescriptorSize, w, kDescriptorSize); | 4373 | heap.copy.write(slot * kDescriptorSize, w, kDescriptorSize); |
| 3941 | heap.live_vsharps.set(slot, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w)); | 4374 | heap.live_vsharps.set(slot, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w)); |
| 3942 | return settled; | 4375 | return settled; |
| 3943 | } | 4376 | } |
| @@ -3985,7 +4418,7 @@ struct DeviceState { | |||
| 3985 | }(); | 4418 | }(); |
| 3986 | const std::size_t end = std::min<std::size_t>(offset + bytes, std::size_t(heap.bytes)); | 4419 | const std::size_t end = std::min<std::size_t>(offset + bytes, std::size_t(heap.bytes)); |
| 3987 | if (!heap.resource_heap) { | 4420 | if (!heap.resource_heap) { |
| 3988 | std::memcpy(heap.copy + offset, heap.input + offset, end - offset); | 4421 | heap.copy.write(offset, heap.input + offset, end - offset); |
| 3989 | return; | 4422 | return; |
| 3990 | } | 4423 | } |
| 3991 | for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; | 4424 | for (std::size_t at = offset & ~std::size_t(kDescriptorSize - 1); at + kDescriptorSize <= end; |
| @@ -3998,8 +4431,14 @@ struct DeviceState { | |||
| 3998 | if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) && | 4431 | if (budget_us && !heap.fix_over && !(++heap.fix_count & 15) && |
| 3999 | std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) | 4432 | std::chrono::steady_clock::now() - heap.fix_start >= std::chrono::microseconds(budget_us)) |
| 4000 | heap.fix_over = true; | 4433 | heap.fix_over = true; |
| 4001 | if (heap.fix_over) { | 4434 | // Buffer V#s (!(w3 >> 30)) only rebase address offsets, so they are fast and must never be |
| 4002 | std::memset(heap.copy + at, 0, kDescriptorSize); | 4435 | // deferred or nulled: at the first world frame lib_cs_01144 reads its loop bound from a buffer |
| 4436 | // slot; nulling it causes an infinite loop and device loss. Only image T#s are deferred past budget. | ||
| 4437 | std::uint32_t w3 = 0; | ||
| 4438 | std::memcpy(&w3, heap.previous + at + 12, sizeof(w3)); | ||
| 4439 | const bool is_buffer_vsharp = !(w3 >> 30); | ||
| 4440 | if (heap.fix_over && !is_buffer_vsharp) { | ||
| 4441 | heap.copy.zero(at, kDescriptorSize); | ||
| 4003 | heap.live_vsharps.clear(slot); | 4442 | heap.live_vsharps.clear(slot); |
| 4004 | ++heap.deferred_fixes; | 4443 | ++heap.deferred_fixes; |
| 4005 | if (!heap.retry[slot]) { | 4444 | if (!heap.retry[slot]) { |
| @@ -4092,6 +4531,59 @@ struct DeviceState { | |||
| 4092 | unbound_tsharp_tracker().note(heap.console_va, offset, words, why); | 4531 | unbound_tsharp_tracker().note(heap.console_va, offset, words, why); |
| 4093 | } | 4532 | } |
| 4094 | 4533 | ||
| 4534 | // LEONIDA_HEAP_MIRROR=0: no host-RAM mirror of a console heap's copy in the arena (src/console_heap_copy.h); the | ||
| 4535 | // release sweep then reads the copy itself, as before the mirror. | ||
| 4536 | static bool heap_mirror_enabled() { | ||
| 4537 | static const bool on = [] { | ||
| 4538 | char value[4] = {}; | ||
| 4539 | return !(GetEnvironmentVariableA("LEONIDA_HEAP_MIRROR", value, sizeof(value)) == 1 && value[0] == '0'); | ||
| 4540 | }(); | ||
| 4541 | return on; | ||
| 4542 | } | ||
| 4543 | // LEONIDA_HEAP_MIRROR_CHECK=1: the mirror compared with the copy at every release sweep (it reads the whole copy, | ||
| 4544 | // so it costs what the mirror saves), the first slots that differ logged. | ||
| 4545 | static bool heap_mirror_check_enabled() { | ||
| 4546 | static const bool on = [] { | ||
| 4547 | char value[4] = {}; | ||
| 4548 | return GetEnvironmentVariableA("LEONIDA_HEAP_MIRROR_CHECK", value, sizeof(value)) == 1 && value[0] == '1'; | ||
| 4549 | }(); | ||
| 4550 | return on; | ||
| 4551 | } | ||
| 4552 | // The slots whose mirror differs from the copy (0: none, or no mirror); the first few logged, for the first | ||
| 4553 | // sweeps that find any. | ||
| 4554 | std::size_t check_console_heap_mirror(ConsoleHeap& heap) { // console_heap_mutex held | ||
| 4555 | if (!heap.copy.mirrored()) return 0; | ||
| 4556 | constexpr std::size_t kShown = 8; | ||
| 4557 | std::vector<std::size_t> slots; | ||
| 4558 | const std::size_t count = heap.copy.mismatches(kDescriptorSize, kShown, slots); | ||
| 4559 | ++heap.mirror_checks; | ||
| 4560 | heap.mirror_mismatches += count; | ||
| 4561 | static std::atomic<unsigned> reports{0}; | ||
| 4562 | if (count && reports.fetch_add(1, std::memory_order_relaxed) < 16) { | ||
| 4563 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAP_MIRROR_CHECK: console descriptor heap 0x%llx: %zu slots of " | ||
| 4564 | "the host mirror differ from the copy\n", | ||
| 4565 | static_cast<unsigned long long>(heap.console_va), count); | ||
| 4566 | for (const std::size_t slot : slots) { | ||
| 4567 | std::uint32_t mirror[8], copy[8]; | ||
| 4568 | std::memcpy(mirror, heap.copy.view() + slot * kDescriptorSize, sizeof(mirror)); | ||
| 4569 | std::memcpy(copy, heap.copy.gpu() + slot * kDescriptorSize, sizeof(copy)); | ||
| 4570 | std::fprintf(stderr, "[rt] d3d12: slot %zu: mirror %08x %08x %08x %08x %08x %08x %08x %08x, copy %08x " | ||
| 4571 | "%08x %08x %08x %08x %08x %08x %08x\n", | ||
| 4572 | slot, mirror[0], mirror[1], mirror[2], mirror[3], mirror[4], mirror[5], mirror[6], mirror[7], | ||
| 4573 | copy[0], copy[1], copy[2], copy[3], copy[4], copy[5], copy[6], copy[7]); | ||
| 4574 | } | ||
| 4575 | } | ||
| 4576 | return count; | ||
| 4577 | } | ||
| 4578 | // Tests: the mirror of the console heap at `console_va` compared with its copy now. -1: no such heap, or no mirror. | ||
| 4579 | long long console_heap_mirror_mismatches(std::uint64_t console_va) { | ||
| 4580 | std::lock_guard lock(console_heap_mutex); | ||
| 4581 | for (const auto& heap : console_heaps) | ||
| 4582 | if (heap->console_va == console_va) | ||
| 4583 | return heap->copy.mirrored() ? static_cast<long long>(check_console_heap_mirror(*heap)) : -1; | ||
| 4584 | return -1; | ||
| 4585 | } | ||
| 4586 | |||
| 4095 | void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held | 4587 | void refresh_console_heap(ConsoleHeap& heap) { // console_heap_mutex held |
| 4096 | if (heap.imported) return; // directly imported sampler heap | 4588 | if (heap.imported) return; // directly imported sampler heap |
| 4097 | if (heap.gpu >= 0) return refresh_console_heap_gpu(heap); | 4589 | if (heap.gpu >= 0) return refresh_console_heap_gpu(heap); |
| @@ -4102,7 +4594,7 @@ struct DeviceState { | |||
| 4102 | const auto t0 = clock::now(); | 4594 | const auto t0 = clock::now(); |
| 4103 | heap.copied += heap.pages->refresh(); | 4595 | heap.copied += heap.pages->refresh(); |
| 4104 | heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) { | 4596 | heap.pages->for_each_zeroed([&](std::size_t offset, std::size_t bytes) { |
| 4105 | std::memset(heap.copy + offset, 0, bytes); | 4597 | heap.copy.zero(offset, bytes); |
| 4106 | std::memset(heap.previous + offset, 0, bytes); | 4598 | std::memset(heap.previous + offset, 0, bytes); |
| 4107 | const auto first = std::uint32_t(offset / kDescriptorSize); | 4599 | const auto first = std::uint32_t(offset / kDescriptorSize); |
| 4108 | const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); | 4600 | const auto end = std::uint32_t((offset + bytes) / kDescriptorSize); |
| @@ -4153,13 +4645,16 @@ struct DeviceState { | |||
| 4153 | ++heap.rescans; | 4645 | ++heap.rescans; |
| 4154 | const auto rescan_start = clock::now(); | 4646 | const auto rescan_start = clock::now(); |
| 4155 | // Even an unchanged title slot may name a buffer released since the last submission. | 4647 | // Even an unchanged title slot may name a buffer released since the last submission. |
| 4156 | // Walk the host-RAM V# bitset instead of reading every slot of `heap.copy` (which may be uncached WC VRAM). | 4648 | // Walk the host-RAM V# bitset instead of reading every slot of `heap.copy` (which may be uncached WC VRAM), |
| 4649 | // and read the copy's words from its host-RAM mirror. | ||
| 4650 | if (heap_mirror_check_enabled()) check_console_heap_mirror(heap); | ||
| 4651 | const std::uint8_t* const translated = heap.copy.view(); | ||
| 4157 | heap.live_vsharps.for_each([&](std::size_t slot) { | 4652 | heap.live_vsharps.for_each([&](std::size_t slot) { |
| 4158 | ++heap.release_candidates; | 4653 | ++heap.release_candidates; |
| 4159 | if (filtered) { | 4654 | if (filtered) { |
| 4160 | const auto at = slot * kDescriptorSize; | 4655 | const auto at = slot * kDescriptorSize; |
| 4161 | const auto* src = reinterpret_cast<const uint32_t*>(heap.previous + at); | 4656 | const auto* src = reinterpret_cast<const uint32_t*>(heap.previous + at); |
| 4162 | const auto* dst = reinterpret_cast<const uint32_t*>(heap.copy + at); | 4657 | const auto* dst = reinterpret_cast<const uint32_t*>(translated + at); |
| 4163 | if (!affected(src, dst) && !affected(src + 4, dst + 4)) return; | 4658 | if (!affected(src, dst) && !affected(src + 4, dst + 4)) return; |
| 4164 | } | 4659 | } |
| 4165 | ++heap.release_fixes; | 4660 | ++heap.release_fixes; |
| @@ -4248,6 +4743,13 @@ struct DeviceState { | |||
| 4248 | (unsigned long long)heap->release_fixes, (unsigned long long)heap->release_rebases, | 4743 | (unsigned long long)heap->release_fixes, (unsigned long long)heap->release_rebases, |
| 4249 | (unsigned long long)heap->release_full); | 4744 | (unsigned long long)heap->release_full); |
| 4250 | heap->release_sweeps = heap->release_candidates = heap->release_fixes = heap->release_rebases = heap->release_full = 0; | 4745 | heap->release_sweeps = heap->release_candidates = heap->release_fixes = heap->release_rebases = heap->release_full = 0; |
| 4746 | if (heap_mirror_check_enabled() && heap->copy.mirrored()) | ||
| 4747 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAP_MIRROR_CHECK: console descriptor heap 0x%llx: %llu " | ||
| 4748 | "checks, %llu slots differing in all\n", | ||
| 4749 | static_cast<unsigned long long>(heap->console_va), | ||
| 4750 | static_cast<unsigned long long>(heap->mirror_checks), | ||
| 4751 | static_cast<unsigned long long>(heap->mirror_mismatches)); | ||
| 4752 | heap->mirror_checks = heap->mirror_mismatches = 0; | ||
| 4251 | if (heap->resource_heap) { | 4753 | if (heap->resource_heap) { |
| 4252 | std::uint64_t paths[kVsharpPathCount]; | 4754 | std::uint64_t paths[kVsharpPathCount]; |
| 4253 | for (unsigned i = 0; i < kVsharpPathCount; ++i) | 4755 | for (unsigned i = 0; i < kVsharpPathCount; ++i) |
| @@ -4405,7 +4907,7 @@ struct DeviceState { | |||
| 4405 | heap->input = heap->scratch.get(); | 4907 | heap->input = heap->scratch.get(); |
| 4406 | heap->previous = heap->scratch.get() + bytes; | 4908 | heap->previous = heap->scratch.get() + bytes; |
| 4407 | heap->shader_va = offset; | 4909 | heap->shader_va = offset; |
| 4408 | heap->copy = arena.mapped + offset; | 4910 | heap->copy.attach(arena.mapped + offset, std::size_t(bytes), heap_mirror_enabled()); |
| 4409 | heap->guard = guard; | 4911 | heap->guard = guard; |
| 4410 | heap->imported = false; | 4912 | heap->imported = false; |
| 4411 | in_arena = true; | 4913 | in_arena = true; |
| @@ -4428,7 +4930,7 @@ struct DeviceState { | |||
| 4428 | if (heap->scratch) { | 4930 | if (heap->scratch) { |
| 4429 | auto* backing = heap->scratch.get(); | 4931 | auto* backing = heap->scratch.get(); |
| 4430 | if (import_console_heap(*heap, reinterpret_cast<std::uintptr_t>(backing), bytes + guard)) { | 4932 | if (import_console_heap(*heap, reinterpret_cast<std::uintptr_t>(backing), bytes + guard)) { |
| 4431 | heap->copy = backing; | 4933 | heap->copy.attach(backing, std::size_t(bytes), false); // host RAM already: no mirror |
| 4432 | heap->guard = guard; | 4934 | heap->guard = guard; |
| 4433 | } | 4935 | } |
| 4434 | heap->input = backing + bytes + guard; | 4936 | heap->input = backing + bytes + guard; |
| @@ -4465,9 +4967,10 @@ struct DeviceState { | |||
| 4465 | "a heap index past it reads the arena's next bytes; guard MiB", | 4967 | "a heap index past it reads the arena's next bytes; guard MiB", |
| 4466 | int(guard >> 20)); | 4968 | int(guard >> 20)); |
| 4467 | heap->shader_va = offset; | 4969 | heap->shader_va = offset; |
| 4468 | heap->copy = arena.mapped + offset; | 4970 | // A sampler heap's copy is read by no CPU sweep: no mirror. |
| 4971 | heap->copy.attach(arena.mapped + offset, std::size_t(bytes), resource_heap && heap_mirror_enabled()); | ||
| 4469 | } | 4972 | } |
| 4470 | std::memset(heap->copy, 0, std::size_t(bytes + heap->guard)); | 4973 | heap->copy.zero(0, std::size_t(bytes + heap->guard)); |
| 4471 | if (!heap->input) { | 4974 | if (!heap->input) { |
| 4472 | heap->mirror.assign(std::size_t(bytes), 0); | 4975 | heap->mirror.assign(std::size_t(bytes), 0); |
| 4473 | heap->made.assign(std::size_t(bytes), 0); | 4976 | heap->made.assign(std::size_t(bytes), 0); |
| @@ -5009,6 +5512,7 @@ struct DeviceState { | |||
| 5009 | return; | 5512 | return; |
| 5010 | } | 5513 | } |
| 5011 | heap.gpu = index; | 5514 | heap.gpu = index; |
| 5515 | heap.copy.drop_mirror(); // the pass writes the copy from now on; the CPU neither writes nor reads it | ||
| 5012 | heap.vsharp_bits.assign((heap.bytes / kDescriptorSize + 63) / 64, 0); | 5516 | heap.vsharp_bits.assign((heap.bytes / kDescriptorSize + 63) / 64, 0); |
| 5013 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx (%llu slots) is " | 5517 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_CONSOLE_HEAP_GPU: console descriptor heap 0x%llx (%llu slots) is " |
| 5014 | "translated by the pass (heap %d)\n", | 5518 | "translated by the pass (heap %d)\n", |
| @@ -5319,6 +5823,148 @@ struct DeviceState { | |||
| 5319 | gpu_counts.backed_ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); | 5823 | gpu_counts.backed_ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); |
| 5320 | } | 5824 | } |
| 5321 | 5825 | ||
| 5826 | // LEONIDA_ADDRESS_GUARD=1 (docs/d3d12_vulkan.md, "Address guard"): the page table the guarded shaders read, a | ||
| 5827 | // host-visible buffer of its own whose address minus heap_base is in the guard header at arena offset | ||
| 5828 | // kGuardHeader. Built from the same backings as the console heap pass's backed table (gpu_backings, the | ||
| 5829 | // geometry copies' blocks and the separate window buffers), but whole and at once: a backing made since the last | ||
| 5830 | // submission must not read 0. | ||
| 5831 | struct AddressGuard { | ||
| 5832 | VkBuffer buffer = VK_NULL_HANDLE; | ||
| 5833 | VkDeviceMemory memory = VK_NULL_HANDLE; | ||
| 5834 | std::uint32_t* words = nullptr; | ||
| 5835 | std::unique_ptr<leonida::address_guard::AddressGuardTable> table; | ||
| 5836 | std::uint64_t generation = ~0ull, blocks = ~0ull, heaps = ~0ull; // heaps: the console heaps' ranges, hashed | ||
| 5837 | std::uint32_t refused_logged = 0, overflow_logged = 0; | ||
| 5838 | std::uint64_t updates = 0, words_written = 0; | ||
| 5839 | std::chrono::steady_clock::time_point logged{}; | ||
| 5840 | std::mutex mutex; | ||
| 5841 | } guard; | ||
| 5842 | |||
| 5843 | // Make the page table and write the header (called once the arena is mapped). False leaves the guard off: the | ||
| 5844 | // header keeps no magic, so guarded shaders check nothing. | ||
| 5845 | bool create_address_guard() { | ||
| 5846 | namespace ag = leonida::address_guard; | ||
| 5847 | if (!context || !arena.mapped || arena.size < ag::kGuardEnd) return false; | ||
| 5848 | auto& vk = context->vk; | ||
| 5849 | guard.table = std::make_unique<ag::AddressGuardTable>(); | ||
| 5850 | VkBufferCreateInfo create{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; | ||
| 5851 | create.size = guard.table->bytes(); | ||
| 5852 | create.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; | ||
| 5853 | create.sharingMode = VK_SHARING_MODE_EXCLUSIVE; | ||
| 5854 | if (vk.vkCreateBuffer(info.device, &create, nullptr, &guard.buffer) != VK_SUCCESS) { | ||
| 5855 | guard.buffer = VK_NULL_HANDLE; | ||
| 5856 | return false; | ||
| 5857 | } | ||
| 5858 | VkMemoryRequirements requirements{}; | ||
| 5859 | vk.vkGetBufferMemoryRequirements(info.device, guard.buffer, &requirements); | ||
| 5860 | guard.memory = allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, | ||
| 5861 | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, true); | ||
| 5862 | void* mapped = nullptr; | ||
| 5863 | if (!guard.memory || vk.vkBindBufferMemory(info.device, guard.buffer, guard.memory, 0) != VK_SUCCESS || | ||
| 5864 | vk.vkMapMemory(info.device, guard.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { | ||
| 5865 | destroy_address_guard(); | ||
| 5866 | return false; | ||
| 5867 | } | ||
| 5868 | guard.words = static_cast<std::uint32_t*>(mapped); | ||
| 5869 | std::memcpy(guard.words, guard.table->words().data(), guard.table->bytes()); | ||
| 5870 | VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; | ||
| 5871 | address.buffer = guard.buffer; | ||
| 5872 | const VkDeviceAddress table = vk.vkGetBufferDeviceAddress(info.device, &address); | ||
| 5873 | auto* header = reinterpret_cast<ag::AddressGuardHeader*>(arena.mapped + ag::kGuardHeader); | ||
| 5874 | std::memset(arena.mapped + ag::kGuardHeader, 0, std::size_t(ag::kGuardEnd - ag::kGuardHeader)); | ||
| 5875 | header->limit = arena.size; | ||
| 5876 | header->table = table - arena.address; | ||
| 5877 | std::atomic_thread_fence(std::memory_order_release); | ||
| 5878 | header->magic = ag::magic(); // last: a shader that sees it sees the rest | ||
| 5879 | std::fprintf(stderr, "[rt] d3d12: address guard on (LEONIDA_ADDRESS_GUARD): %llu KiB page table, header at " | ||
| 5880 | "heap_base + 0x%llx; shaders translated with --address-guard read 0 from memory nothing " | ||
| 5881 | "backs and drop their stores there\n", | ||
| 5882 | static_cast<unsigned long long>(guard.table->bytes() >> 10), | ||
| 5883 | static_cast<unsigned long long>(ag::kGuardHeader)); | ||
| 5884 | return true; | ||
| 5885 | } | ||
| 5886 | void destroy_address_guard() { | ||
| 5887 | if (!context) return; | ||
| 5888 | auto& vk = context->vk; | ||
| 5889 | if (guard.buffer) vk.vkDestroyBuffer(info.device, guard.buffer, nullptr); | ||
| 5890 | if (guard.memory) vk.vkFreeMemory(info.device, guard.memory, nullptr); | ||
| 5891 | guard.buffer = VK_NULL_HANDLE; | ||
| 5892 | guard.memory = VK_NULL_HANDLE; | ||
| 5893 | guard.words = nullptr; | ||
| 5894 | } | ||
| 5895 | |||
| 5896 | // Before each submission: the page table says exactly what is backed now, and refusals since the last line are | ||
| 5897 | // logged (at most once a second). Rebuilt only when a backing came or went; only changed words are written. | ||
| 5898 | void update_address_guard() { | ||
| 5899 | namespace ag = leonida::address_guard; | ||
| 5900 | if (!guard.words) return; | ||
| 5901 | // A console descriptor heap whose GPU copy lies outside the arena (an import of the title's pages, which | ||
| 5902 | // shaders read at shader_va = its device address minus heap_base) is read through heap_base + VA like a | ||
| 5903 | // buffer, but no gpu_backing names it: its bytes and the null guard after them are entered here. Without | ||
| 5904 | // this the guard refused every descriptor-table load from such a heap (run 28: a 38 MB imported heap at | ||
| 5905 | // shader VA 0x87e00000, past a 2 GiB arena). Collected before guard.mutex, in console_heap_mutex's order. | ||
| 5906 | std::vector<std::pair<std::uint64_t, std::uint64_t>> heap_spans; | ||
| 5907 | std::uint64_t heap_signature = 0xcbf29ce484222325ull; | ||
| 5908 | { | ||
| 5909 | std::lock_guard heaps(console_heap_mutex); | ||
| 5910 | for (const auto& h : console_heaps) { | ||
| 5911 | if (!h || !h->bytes) continue; | ||
| 5912 | const std::uint64_t begin = h->shader_va, end = h->shader_va + h->bytes + h->guard; | ||
| 5913 | heap_signature = (heap_signature ^ begin) * 0x100000001b3ull; | ||
| 5914 | heap_signature = (heap_signature ^ end) * 0x100000001b3ull; | ||
| 5915 | if (!(begin < arena.size && end <= arena.size)) heap_spans.emplace_back(begin, end); | ||
| 5916 | } | ||
| 5917 | } | ||
| 5918 | std::lock_guard lock(guard.mutex); | ||
| 5919 | const std::uint64_t generation = backing_generation.load(std::memory_order_relaxed); | ||
| 5920 | const std::uint64_t blocks = geometry.pool().layout_generation() + external_windows.layout_generation(); | ||
| 5921 | if (generation != guard.generation || blocks != guard.blocks || heap_signature != guard.heaps) { | ||
| 5922 | guard.generation = generation; | ||
| 5923 | guard.blocks = blocks; | ||
| 5924 | guard.heaps = heap_signature; | ||
| 5925 | std::vector<std::pair<std::uint64_t, std::uint64_t>> spans = heap_spans; | ||
| 5926 | { | ||
| 5927 | std::lock_guard backing_lock(backing_mutex); | ||
| 5928 | gpu_backings.for_each([&](std::uint64_t va, std::uint64_t bytes) { | ||
| 5929 | const std::uint64_t offset = va - arena.address; | ||
| 5930 | // The arena's own ranges pass on the limit compare; only what lies outside needs pages. | ||
| 5931 | if (bytes && !(offset < arena.size && bytes <= arena.size - offset)) | ||
| 5932 | spans.emplace_back(offset, offset + bytes); | ||
| 5933 | }); | ||
| 5934 | } | ||
| 5935 | const auto block = [&](VkDeviceAddress address, VkDeviceSize bytes) { | ||
| 5936 | const std::uint64_t offset = address - arena.address; | ||
| 5937 | if (address && bytes) spans.emplace_back(offset, offset + bytes); | ||
| 5938 | }; | ||
| 5939 | geometry.pool().for_each_block(block); | ||
| 5940 | external_windows.for_each_block(block); | ||
| 5941 | guard.words_written += guard.table->assign(spans, [&](std::size_t i, std::uint32_t v) { | ||
| 5942 | std::atomic_ref(guard.words[i]).store(v, std::memory_order_relaxed); | ||
| 5943 | }); | ||
| 5944 | ++guard.updates; | ||
| 5945 | if (guard.table->overflowed() != guard.overflow_logged) { | ||
| 5946 | guard.overflow_logged = guard.table->overflowed(); | ||
| 5947 | std::fprintf(stderr, "[rt] d3d12: address guard: %u 4 GiB chunk(s) of backings past the page table's " | ||
| 5948 | "%u blocks are not checked\n", | ||
| 5949 | guard.overflow_logged, guard.table->blocks_used()); | ||
| 5950 | } | ||
| 5951 | } | ||
| 5952 | auto* header = reinterpret_cast<ag::AddressGuardHeader*>(arena.mapped + ag::kGuardHeader); | ||
| 5953 | const std::uint32_t refused = std::atomic_ref(header->refused).load(std::memory_order_relaxed); | ||
| 5954 | const auto now = std::chrono::steady_clock::now(); | ||
| 5955 | if (refused != guard.refused_logged && now - guard.logged >= std::chrono::seconds(1)) { | ||
| 5956 | guard.logged = now; | ||
| 5957 | std::fprintf(stderr, "[rt] d3d12: address guard: %u access(es) refused so far (+%u), the last at heap " | ||
| 5958 | "offset 0x%llx by module 0x%08x; %llu table update(s), %llu word(s) written\n", | ||
| 5959 | refused, refused - guard.refused_logged, | ||
| 5960 | static_cast<unsigned long long>(header->last_refused), | ||
| 5961 | std::atomic_ref(header->last_module).load(std::memory_order_relaxed), | ||
| 5962 | static_cast<unsigned long long>(guard.updates), | ||
| 5963 | static_cast<unsigned long long>(guard.words_written)); | ||
| 5964 | guard.refused_logged = refused; | ||
| 5965 | } | ||
| 5966 | } | ||
| 5967 | |||
| 5322 | // The ask table: the title's memory and both addresses of its GPU-window pairs. A V# base outside them that the | 5968 | // The ask table: the title's memory and both addresses of its GPU-window pairs. A V# base outside them that the |
| 5323 | // other tables do not answer is one vsharp_address could only answer 0 for. | 5969 | // other tables do not answer is one vsharp_address could only answer 0 for. |
| 5324 | void update_gpu_ask() { | 5970 | void update_gpu_ask() { |
| @@ -6972,6 +7618,12 @@ struct DeviceState { | |||
| 6972 | return nullptr; | 7618 | return nullptr; |
| 6973 | } | 7619 | } |
| 6974 | }; | 7620 | }; |
| 7621 | // TitleBufferWindows::system_memory_types reads the memory types through these (LEONIDA_GEOMETRY_HOST): without them | ||
| 7622 | // it would leave every type allowed, the BAR included. | ||
| 7623 | static_assert(requires(const DeviceState& d) { | ||
| 7624 | d.memory.memoryTypes[0].propertyFlags; | ||
| 7625 | d.memory.memoryTypeCount; | ||
| 7626 | }); | ||
| 6975 | 7627 | ||
| 6976 | // The Vulkan format for a texture this layer can create, with the D24 fallback; VK_FORMAT_UNDEFINED, after a log | 7628 | // The Vulkan format for a texture this layer can create, with the D24 fallback; VK_FORMAT_UNDEFINED, after a log |
| 6977 | // line, when it cannot. Committed and placed textures share it so both refuse the same formats for the same reason. | 7629 | // line, when it cannot. Committed and placed textures share it so both refuse the same formats for the same reason. |
| @@ -11191,8 +11843,11 @@ public: | |||
| 11191 | log_once("conservative rasterization needs enabled VK_EXT_conservative_rasterization and Tier 1 precision", 1); | 11843 | log_once("conservative rasterization needs enabled VK_EXT_conservative_rasterization and Tier 1 precision", 1); |
| 11192 | return E_INVALIDARG; | 11844 | return E_INVALIDARG; |
| 11193 | } | 11845 | } |
| 11194 | if (r.FillMode != D3D12_FILL_MODE_SOLID || | 11846 | // A mesh pipeline has no input assembler, so its stream need not set the topology type: what is rasterized |
| 11195 | topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; | 11847 | // is the module's output, and it has to be triangles as well. |
| 11848 | if (r.FillMode != D3D12_FILL_MODE_SOLID) return E_INVALIDARG; | ||
| 11849 | if (mesh ? !leonida::conservative_raster::mesh_outputs_triangles(stages[0].words) | ||
| 11850 | : topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; | ||
| 11196 | // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. | 11851 | // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. |
| 11197 | if (r.ForcedSampleCount) | 11852 | if (r.ForcedSampleCount) |
| 11198 | return stream_unsupported("target-independent rasterization; forced sample count", int(r.ForcedSampleCount)); | 11853 | return stream_unsupported("target-independent rasterization; forced sample count", int(r.ForcedSampleCount)); |
| @@ -12074,7 +12729,11 @@ private: | |||
| 12074 | const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline"); | 12729 | const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline"); |
| 12075 | const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", | 12730 | const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", |
| 12076 | program, fragment, unbound); | 12731 | program, fragment, unbound); |
| 12077 | const auto result = device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &info, nullptr, &pipeline); | 12732 | const auto result = device_.create_pipeline(flags, [&](VkPipelineCache with, VkPipelineCreateFlags f) { |
| 12733 | info.flags = f; | ||
| 12734 | pipeline = VK_NULL_HANDLE; | ||
| 12735 | return device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, with, 1, &info, nullptr, &pipeline); | ||
| 12736 | }); | ||
| 12078 | if (status) *status = result; | 12737 | if (status) *status = result; |
| 12079 | profile.finish(int(result)); | 12738 | profile.finish(int(result)); |
| 12080 | trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result); | 12739 | trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result); |
| @@ -12890,6 +13549,57 @@ void DeviceState::drain_titles_gone() { | |||
| 12890 | // these words, as write_image_descriptor does. Every field the layer does not encode (tiling, compression, | 13549 | // these words, as write_image_descriptor does. Every field the layer does not encode (tiling, compression, |
| 12891 | // performance hints) only makes the key differ, so a title-built T# still finds its texture. Checked against the | 13550 | // performance hints) only makes the key differ, so a title-built T# still finds its texture. Checked against the |
| 12892 | // texture first: a view of mips, layers or a dimension it lacks would be an invalid Vulkan view. | 13551 | // texture first: a view of mips, layers or a dimension it lacks would be an invalid Vulkan view. |
| 13552 | // LEONIDA_UNKNOWN_TSHARP=1 (diagnostic): one line for each distinct base address a title-written T# names with no | ||
| 13553 | // texture there (its shape, the tiling bits SW_MODE = dword 3 bits 20..24 by the GFX10 layout, unverified, and whether | ||
| 13554 | // the address is title memory), up to 300 addresses, and every 8192 such lookups a summary by format, type and tiling. | ||
| 13555 | // What a texture made from the T# on its first read would have to create. | ||
| 13556 | void note_unknown_tsharp(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image) { | ||
| 13557 | static const bool on = [] { | ||
| 13558 | const char* v = std::getenv("LEONIDA_UNKNOWN_TSHARP"); | ||
| 13559 | return v && *v == '1'; | ||
| 13560 | }(); | ||
| 13561 | if (!on) return; | ||
| 13562 | struct Shape { | ||
| 13563 | std::uint32_t format, type, sw, width, height, depth, mips, layers; | ||
| 13564 | }; | ||
| 13565 | static std::mutex mutex; | ||
| 13566 | static std::unordered_map<std::uint64_t, Shape> seen; | ||
| 13567 | static std::map<std::string, std::uint64_t> by_shape; | ||
| 13568 | static std::uint64_t lookups = 0, in_title = 0; | ||
| 13569 | const Shape s{image.format, std::uint32_t(image.type), (words[3] >> 20) & 0x1f, image.width, image.height, | ||
| 13570 | image.depth, image.resource_mips, image.layer_count}; | ||
| 13571 | std::uint64_t lo = 0, hi = 0; | ||
| 13572 | const bool title = leonida::title_va_aliases().title_memory(image.address, lo, hi); | ||
| 13573 | std::lock_guard lock(mutex); | ||
| 13574 | ++lookups; | ||
| 13575 | if (seen.emplace(image.address, s).second) { | ||
| 13576 | in_title += title; | ||
| 13577 | char key[64]; | ||
| 13578 | std::snprintf(key, sizeof(key), "fmt %u type %u sw %u", s.format, s.type, s.sw); | ||
| 13579 | ++by_shape[key]; | ||
| 13580 | if (seen.size() <= 300) | ||
| 13581 | std::fprintf(stderr, | ||
| 13582 | "[rt] unknown-tsharp: #%zu base 0x%llx fmt %u type %u sw %u %ux%ux%u mips %u layers %u%s\n", | ||
| 13583 | seen.size(), static_cast<unsigned long long>(image.address), s.format, s.type, s.sw, s.width, | ||
| 13584 | s.height, s.depth, s.mips, s.layers, title ? " (title memory)" : " (not title memory)"); | ||
| 13585 | if (seen.size() <= 24) | ||
| 13586 | std::fprintf(stderr, "[rt] unknown-tsharp: #%zu words %08x %08x %08x %08x %08x %08x %08x %08x\n", seen.size(), | ||
| 13587 | words[0], words[1], words[2], words[3], words[4], words[5], words[6], words[7]); | ||
| 13588 | } | ||
| 13589 | if (!(lookups % 8192)) { | ||
| 13590 | std::vector<std::pair<std::uint64_t, std::string>> top; | ||
| 13591 | for (const auto& [k, n] : by_shape) top.emplace_back(n, k); | ||
| 13592 | std::sort(top.rbegin(), top.rend()); | ||
| 13593 | std::string text; | ||
| 13594 | for (std::size_t i = 0; i < top.size() && i < 10; ++i) | ||
| 13595 | text += (i ? "; " : "") + top[i].second + " x" + std::to_string(top[i].first); | ||
| 13596 | std::fprintf(stderr, | ||
| 13597 | "[rt] unknown-tsharp: %llu lookups, %zu distinct addresses (%llu in title memory); by shape: %s\n", | ||
| 13598 | static_cast<unsigned long long>(lookups), seen.size(), static_cast<unsigned long long>(in_title), | ||
| 13599 | text.c_str()); | ||
| 13600 | } | ||
| 13601 | } | ||
| 13602 | |||
| 12893 | TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why) { | 13603 | TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWords& words, const char** why) { |
| 12894 | namespace g = leonida::gfx10; | 13604 | namespace g = leonida::gfx10; |
| 12895 | const auto refuse = [why](const char* reason) { | 13605 | const auto refuse = [why](const char* reason) { |
| @@ -12923,6 +13633,7 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord | |||
| 12923 | } | 13633 | } |
| 12924 | if (!owner) { | 13634 | if (!owner) { |
| 12925 | if (why) *why = "no texture at T# address"; | 13635 | if (why) *why = "no texture at T# address"; |
| 13636 | note_unknown_tsharp(words, image); | ||
| 12926 | return TitleImage::unknown; | 13637 | return TitleImage::unknown; |
| 12927 | } | 13638 | } |
| 12928 | const Resource& r = *owner; | 13639 | const Resource& r = *owner; |
| @@ -13601,6 +14312,8 @@ public: | |||
| 13601 | const phases::Scope timed(phases::geometry); | 14312 | const phases::Scope timed(phases::geometry); |
| 13602 | state_.geometry.refresh(DeviceState::copy_geometry); | 14313 | state_.geometry.refresh(DeviceState::copy_geometry); |
| 13603 | } | 14314 | } |
| 14315 | // Last, once the heap refresh, the windows and the geometry copies have made what this submission reads. | ||
| 14316 | state_.update_address_guard(); | ||
| 13604 | const phases::Scope timed(phases::textures); | 14317 | const phases::Scope timed(phases::textures); |
| 13605 | if (async_texture_refresh()) { | 14318 | if (async_texture_refresh()) { |
| 13606 | if (!t_in_title_textures) { | 14319 | if (!t_in_title_textures) { |
| @@ -13643,6 +14356,9 @@ public: | |||
| 13643 | [](void* device, std::uint64_t table, std::uint32_t descriptors) { | 14356 | [](void* device, std::uint64_t table, std::uint32_t descriptors) { |
| 13644 | static_cast<DeviceState*>(device)->scan_title_table(table, descriptors); | 14357 | static_cast<DeviceState*>(device)->scan_title_table(table, descriptors); |
| 13645 | }); | 14358 | }); |
| 14359 | leonida::title_va_aliases().set_noter([](void* device, std::uint64_t va, std::uint64_t bytes) { | ||
| 14360 | static_cast<DeviceState*>(device)->note_title_write(va, bytes); | ||
| 14361 | }); | ||
| 13646 | state_.image_memory = std::make_unique<leonida::ImageMemory>( | 14362 | state_.image_memory = std::make_unique<leonida::ImageMemory>( |
| 13647 | [device = info.device, make = state_.context->vk.vkAllocateMemory](std::uint32_t type, std::uint64_t bytes) { | 14363 | [device = info.device, make = state_.context->vk.vkAllocateMemory](std::uint32_t type, std::uint64_t bytes) { |
| 13648 | VkMemoryAllocateInfo block{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; | 14364 | VkMemoryAllocateInfo block{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; |
| @@ -14269,14 +14985,20 @@ public: | |||
| 14269 | // Under the arena's lock: an insert rebalances the tree and rewrites child links, which a walk on | 14985 | // Under the arena's lock: an insert rebalances the tree and rewrites child links, which a walk on |
| 14270 | // another thread must not see half done. | 14986 | // another thread must not see half done. |
| 14271 | std::lock_guard lock(arena.mutex); | 14987 | std::lock_guard lock(arena.mutex); |
| 14272 | arena.blocks.reset(null_bytes + kArenaReserved, arena.size); | 14988 | // LEONIDA_ADDRESS_GUARD: the guard header and sinks at [0x70000, 0x80000) are never handed out either |
| 14273 | arena.first = null_bytes + kArenaReserved; | 14989 | // (inside the null region when there is one, else just past the quad indices). |
| 14990 | arena.first = std::max<VkDeviceSize>(null_bytes + kArenaReserved, | ||
| 14991 | address_guard_enabled() ? leonida::address_guard::kGuardEnd : 0); | ||
| 14992 | arena.blocks.reset(arena.first, arena.size); | ||
| 14274 | char check[2] = {}; | 14993 | char check[2] = {}; |
| 14275 | size_t check_length = 0; | 14994 | size_t check_length = 0; |
| 14276 | arena.check_all = getenv_s(&check_length, check, "LEONIDA_ARENA_CHECK") == 0 && check_length > 1 && | 14995 | arena.check_all = getenv_s(&check_length, check, "LEONIDA_ARENA_CHECK") == 0 && check_length > 1 && |
| 14277 | check[0] != '0'; | 14996 | check[0] != '0'; |
| 14278 | } | 14997 | } |
| 14279 | arena.peak_end = null_bytes + kArenaReserved; | 14998 | arena.peak_end = arena.first; |
| 14999 | if (address_guard_enabled() && !state_.create_address_guard()) | ||
| 15000 | std::fprintf(stderr, "[rt] d3d12: LEONIDA_ADDRESS_GUARD=1 but the address guard could not be set up; " | ||
| 15001 | "guarded shaders check nothing\n"); | ||
| 14280 | char log[4] = {}; | 15002 | char log[4] = {}; |
| 14281 | length = 0; | 15003 | length = 0; |
| 14282 | arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; | 15004 | arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; |
| @@ -14383,12 +15105,14 @@ public: | |||
| 14383 | state_.bindless.reset(); | 15105 | state_.bindless.reset(); |
| 14384 | } | 15106 | } |
| 14385 | state_.report_arena(); | 15107 | state_.report_arena(); |
| 15108 | state_.destroy_address_guard(); | ||
| 14386 | if (state_.context && state_.arena.buffer) { | 15109 | if (state_.context && state_.arena.buffer) { |
| 14387 | leonida::fsdraw::forget_arena(state_.arena.mapped); | 15110 | leonida::fsdraw::forget_arena(state_.arena.mapped); |
| 14388 | auto& vk = state_.context->vk; | 15111 | auto& vk = state_.context->vk; |
| 14389 | vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); | 15112 | vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); |
| 14390 | if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); | 15113 | if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); |
| 14391 | } | 15114 | } |
| 15115 | state_.finish_heavy_cache(); | ||
| 14392 | if (state_.pipeline_cache_handle) { | 15116 | if (state_.pipeline_cache_handle) { |
| 14393 | // Nothing should be building into the cache now (the compiler's jobs for this device are gone, and so | 15117 | // Nothing should be building into the cache now (the compiler's jobs for this device are gone, and so |
| 14394 | // is every PSO). If something is, its pipelines are half in the cache: keep the previous session file. | 15118 | // is every PSO). If something is, its pipelines are half in the cache: keep the previous session file. |
| @@ -15514,6 +16238,8 @@ private: | |||
| 15514 | const bool guard = check_pages_before_read(); | 16238 | const bool guard = check_pages_before_read(); |
| 15515 | if (!guard && !t.memory.pending()) return true; | 16239 | if (!guard && !t.memory.pending()) return true; |
| 15516 | const bool mapped = t.mapped && refresh_mapped_pages(); | 16240 | const bool mapped = t.mapped && refresh_mapped_pages(); |
| 16241 | if (!title_pass_ && guard && !mapped) | ||
| 16242 | t.memory.sync_map(title_map_generation_, static_cast<std::uintptr_t>(t.cpu), t.layout.layout.size); | ||
| 15517 | const auto commit = mapped ? leonida::kernel_writes::state().committer.load(std::memory_order_acquire) : nullptr; | 16243 | const auto commit = mapped ? leonida::kernel_writes::state().committer.load(std::memory_order_acquire) : nullptr; |
| 15518 | const bool waited = t.memory.pending(); | 16244 | const bool waited = t.memory.pending(); |
| 15519 | // The answer is kept (generation 0) until a map change over the texture, a write into it or the periodic | 16245 | // The answer is kept (generation 0) until a map change over the texture, a write into it or the periodic |
| @@ -17820,7 +18546,7 @@ public: | |||
| 17820 | // imported, or a shadow copied from them before every submission) and kept until the device goes, up to | 18546 | // imported, or a shadow copied from them before every submission) and kept until the device goes, up to |
| 17821 | // LEONIDA_TITLE_BUFFERS_MB (512 by default). | 18547 | // LEONIDA_TITLE_BUFFERS_MB (512 by default). |
| 17822 | void make_title_buffer(std::uint64_t va, std::uint64_t bytes) { | 18548 | void make_title_buffer(std::uint64_t va, std::uint64_t bytes) { |
| 17823 | if (!state_.context) return; | 18549 | if (!&context()) return; |
| 17824 | static const bool check_size = [] { | 18550 | static const bool check_size = [] { |
| 17825 | wchar_t flag[2]{}; | 18551 | wchar_t flag[2]{}; |
| 17826 | return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_BUFFER_COVERAGE", flag, 2) == 1 && flag[0] == L'0'); | 18552 | return !(GetEnvironmentVariableW(L"LEONIDA_TITLE_BUFFER_COVERAGE", flag, 2) == 1 && flag[0] == L'0'); |
| @@ -20341,6 +21067,14 @@ bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t b | |||
| 20341 | return true; | 21067 | return true; |
| 20342 | } | 21068 | } |
| 20343 | 21069 | ||
| 21070 | long long console_heap_mirror_mismatches(ID3D12Device* device, std::uint64_t console_va) { | ||
| 21071 | if (!device) return -1; | ||
| 21072 | ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); | ||
| 21073 | if (!real) real = device; | ||
| 21074 | Device* d = Device::from<Device>(real); | ||
| 21075 | return d ? d->state().console_heap_mirror_mismatches(console_va) : -1; | ||
| 21076 | } | ||
| 21077 | |||
| 20344 | namespace { | 21078 | namespace { |
| 20345 | const leonida::BindlessSet* bindless_of(ID3D12Device* device) { | 21079 | const leonida::BindlessSet* bindless_of(ID3D12Device* device) { |
| 20346 | if (!device) return nullptr; | 21080 | if (!device) return nullptr; |
| @@ -20911,8 +21645,12 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 20911 | v13.compute_full_subgroups, info.subgroup); | 21645 | v13.compute_full_subgroups, info.subgroup); |
| 20912 | const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); | 21646 | const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); |
| 20913 | const auto mode = compile_mode ? std::string_view(compile_mode) : std::string_view{}; | 21647 | const auto mode = compile_mode ? std::string_view(compile_mode) : std::string_view{}; |
| 20914 | v13.enable_pipeline_cache_control = mode == "cache-only" && v13.core && v13.pipeline_cache_control; | 21648 | // pipelineCreationCacheControl: for LEONIDA_PIPELINE_COMPILE=cache-only, and for the heavy pipeline cache unless |
| 20915 | info.cold_graphics_compile = v13.enable_pipeline_cache_control; | 21649 | // LEONIDA_HEAVY_PIPELINE_CACHE_MS=0 turns it off. |
| 21650 | v13.enable_pipeline_cache_control = | ||
| 21651 | (mode == "cache-only" || heavy_pipeline_cache_ms()) && v13.core && v13.pipeline_cache_control; | ||
| 21652 | info.cold_graphics_compile = mode == "cache-only" && v13.enable_pipeline_cache_control; | ||
| 21653 | info.heavy_pipeline_cache = heavy_pipeline_cache_ms() && v13.enable_pipeline_cache_control; | ||
| 20916 | info.prepare_on_bind = mode == "on-demand"; | 21654 | info.prepare_on_bind = mode == "on-demand"; |
| 20917 | void* v13_chain = v13.enable(ext_chain); | 21655 | void* v13_chain = v13.enable(ext_chain); |
| 20918 | // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. | 21656 | // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. |
diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 87cc26dd3..c5f12dc05 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp | |||
| @@ -2289,6 +2289,12 @@ HRESULT queue_copy_page_mappings(ChildProxy* self, UINT count, const xmem::PageB | |||
| 2289 | if (!map && rt::xmem::copy_page_mappings_fn) map = ©_page_mappings_default; | 2289 | if (!map && rt::xmem::copy_page_mappings_fn) map = ©_page_mappings_default; |
| 2290 | if (!map || !count) return S_OK; | 2290 | if (!map || !count) return S_OK; |
| 2291 | if (!batches || flags) return E_INVALIDARG; | 2291 | if (!batches || flags) return E_INVALIDARG; |
| 2292 | // Which implementation remaps, once: a boot's read-fault reports belong to that route's tests. | ||
| 2293 | static std::atomic<bool> route_logged{false}; | ||
| 2294 | if (!route_logged.exchange(true, std::memory_order_relaxed)) | ||
| 2295 | std::fprintf(stderr, "[rt] d3d12_xs: CopyPageMappingsBatchX remaps through %s\n", | ||
| 2296 | map == ©_page_mappings_default ? "xmem's range callback (copy_page_mappings_fn)" | ||
| 2297 | : "the installed batch hook (set_copy_page_mappings_hook)"); | ||
| 2292 | auto* queue = reinterpret_cast<ID3D12CommandQueue*>(self->real); | 2298 | auto* queue = reinterpret_cast<ID3D12CommandQueue*>(self->real); |
| 2293 | using clock = std::chrono::steady_clock; | 2299 | using clock = std::chrono::steady_clock; |
| 2294 | const auto t0 = clock::now(); | 2300 | const auto t0 = clock::now(); |
| @@ -2840,6 +2846,32 @@ struct UploadArena { | |||
| 2840 | 2846 | ||
| 2841 | constexpr std::size_t kUploadChunkMin = 8 << 20; // one chunk serves a title's whole frame of uploads | 2847 | constexpr std::size_t kUploadChunkMin = 8 << 20; // one chunk serves a title's whole frame of uploads |
| 2842 | 2848 | ||
| 2849 | // LEONIDA_UPLOAD_LOG=1 (diagnostic): each upload chunk (its CPU base, device address and size), and the first 96 and | ||
| 2850 | // then every 8192nd AllocateUploadMemory result as an offset into its chunk, so the addresses the title builds | ||
| 2851 | // descriptors from can be matched with the memory it was handed. | ||
| 2852 | inline bool upload_log() { | ||
| 2853 | static const bool on = [] { | ||
| 2854 | const char* v = std::getenv("LEONIDA_UPLOAD_LOG"); | ||
| 2855 | return v && *v == '1'; | ||
| 2856 | }(); | ||
| 2857 | return on; | ||
| 2858 | } | ||
| 2859 | inline void log_upload_result(const UploadChunk* chunk, std::uint64_t result, std::uint64_t size, | ||
| 2860 | std::uint64_t alignment) { | ||
| 2861 | if (!upload_log() || !chunk) return; | ||
| 2862 | static std::atomic<std::uint64_t> calls{0}; | ||
| 2863 | const std::uint64_t n = ++calls; | ||
| 2864 | if (n > 96 && (n % 8192)) return; | ||
| 2865 | const std::uint64_t base = reinterpret_cast<std::uint64_t>(chunk->cpu_base); | ||
| 2866 | std::fprintf(stderr, | ||
| 2867 | "[rt] upload-log: #%llu result 0x%llx = chunk 0x%llx + offset 0x%llx (size %llu, alignment %llu; " | ||
| 2868 | "chunk device address 0x%llx)\n", | ||
| 2869 | static_cast<unsigned long long>(n), static_cast<unsigned long long>(result), | ||
| 2870 | static_cast<unsigned long long>(base), static_cast<unsigned long long>(result - base), | ||
| 2871 | static_cast<unsigned long long>(size), static_cast<unsigned long long>(alignment), | ||
| 2872 | static_cast<unsigned long long>(chunk->gpu_base)); | ||
| 2873 | } | ||
| 2874 | |||
| 2843 | UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { | 2875 | UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { |
| 2844 | auto* chunk = new (std::nothrow) UploadChunk{}; | 2876 | auto* chunk = new (std::nothrow) UploadChunk{}; |
| 2845 | if (!chunk) return nullptr; | 2877 | if (!chunk) return nullptr; |
| @@ -2865,6 +2897,24 @@ UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { | |||
| 2865 | chunk->resource = resource; | 2897 | chunk->resource = resource; |
| 2866 | chunk->cpu_base = static_cast<std::uint8_t*>(cpu); | 2898 | chunk->cpu_base = static_cast<std::uint8_t*>(cpu); |
| 2867 | chunk->gpu_base = resource->GetGPUVirtualAddress(); | 2899 | chunk->gpu_base = resource->GetGPUVirtualAddress(); |
| 2900 | // LEONIDA_UPLOAD_ALIAS=1 (experiment): the title takes the pointer AllocateUploadMemory hands it for a GPU | ||
| 2901 | // address too (the console's memory is unified) and writes it into the descriptors it builds itself. Entered in | ||
| 2902 | // the title VA table, the chunk's CPU range answers with the chunk's console VA (its device address minus | ||
| 2903 | // heap_base), so a V# the title wrote with such a pointer is rewritten to the chunk instead of left empty. A | ||
| 2904 | // chunk below the arena has a negative console VA, usable in a V# only with LEONIDA_IMPORT_BELOW_ARENA=1. | ||
| 2905 | static const bool alias = [] { | ||
| 2906 | const char* v = std::getenv("LEONIDA_UPLOAD_ALIAS"); | ||
| 2907 | return v && *v == '1'; | ||
| 2908 | }(); | ||
| 2909 | if (alias) { | ||
| 2910 | const bool added = leonida::title_va_aliases().add(reinterpret_cast<std::uint64_t>(chunk->cpu_base), | ||
| 2911 | chunk->size, chunk->gpu_base); | ||
| 2912 | std::fprintf(stderr, "[rt] d3d12_xs: upload chunk 0x%llx (%llu bytes) entered as an alias of console VA " | ||
| 2913 | "0x%llx: %s\n", | ||
| 2914 | static_cast<unsigned long long>(reinterpret_cast<std::uint64_t>(chunk->cpu_base)), | ||
| 2915 | static_cast<unsigned long long>(chunk->size), static_cast<unsigned long long>(chunk->gpu_base), | ||
| 2916 | added ? "ok" : "refused"); | ||
| 2917 | } | ||
| 2868 | return chunk; | 2918 | return chunk; |
| 2869 | } | 2919 | } |
| 2870 | if (resource) resource->Release(); | 2920 | if (resource) resource->Release(); |
| @@ -2912,7 +2962,9 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_ | |||
| 2912 | const std::size_t aligned = (chunk->used + (alignment - 1)) & ~(static_cast<std::size_t>(alignment) - 1); | 2962 | const std::size_t aligned = (chunk->used + (alignment - 1)) & ~(static_cast<std::size_t>(alignment) - 1); |
| 2913 | if (aligned >= chunk->used && aligned <= chunk->size && need <= chunk->size - aligned) { | 2963 | if (aligned >= chunk->used && aligned <= chunk->size && need <= chunk->size - aligned) { |
| 2914 | chunk->used = aligned + need; | 2964 | chunk->used = aligned + need; |
| 2915 | return reinterpret_cast<std::uint64_t>(chunk->cpu_base + aligned); | 2965 | const std::uint64_t result = reinterpret_cast<std::uint64_t>(chunk->cpu_base + aligned); |
| 2966 | log_upload_result(chunk, result, size, alignment); | ||
| 2967 | return result; | ||
| 2916 | } | 2968 | } |
| 2917 | } | 2969 | } |
| 2918 | const std::size_t chunk_size = need + alignment > kUploadChunkMin ? need + alignment : kUploadChunkMin; | 2970 | const std::size_t chunk_size = need + alignment > kUploadChunkMin ? need + alignment : kUploadChunkMin; |
| @@ -2926,7 +2978,14 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_ | |||
| 2926 | arena->chunks = chunk; | 2978 | arena->chunks = chunk; |
| 2927 | const std::size_t aligned = (alignment - 1) & ~(static_cast<std::size_t>(alignment) - 1); // 0-based | 2979 | const std::size_t aligned = (alignment - 1) & ~(static_cast<std::size_t>(alignment) - 1); // 0-based |
| 2928 | chunk->used = aligned + need; | 2980 | chunk->used = aligned + need; |
| 2929 | return reinterpret_cast<std::uint64_t>(chunk->cpu_base + aligned); | 2981 | if (upload_log()) |
| 2982 | std::fprintf(stderr, "[rt] upload-log: new chunk at 0x%llx, device address 0x%llx, %llu bytes (%s)\n", | ||
| 2983 | static_cast<unsigned long long>(reinterpret_cast<std::uint64_t>(chunk->cpu_base)), | ||
| 2984 | static_cast<unsigned long long>(chunk->gpu_base), static_cast<unsigned long long>(chunk->size), | ||
| 2985 | chunk->resource ? "mapped upload buffer" : "VirtualAlloc fallback"); | ||
| 2986 | const std::uint64_t result = reinterpret_cast<std::uint64_t>(chunk->cpu_base + aligned); | ||
| 2987 | log_upload_result(chunk, result, size, alignment); | ||
| 2988 | return result; | ||
| 2930 | } | 2989 | } |
| 2931 | 2990 | ||
| 2932 | // An address inside an upload chunk becomes the chunk's device address plus the offset; anything else — a | 2991 | // An address inside an upload chunk becomes the chunk's device address plus the offset; anything else — a |
| @@ -2949,6 +3008,9 @@ void destroy_upload_state(void* upload_state) { | |||
| 2949 | for (UploadChunk* chunk = arena->chunks; chunk;) { | 3008 | for (UploadChunk* chunk = arena->chunks; chunk;) { |
| 2950 | UploadChunk* next = chunk->next; | 3009 | UploadChunk* next = chunk->next; |
| 2951 | if (chunk->resource) { | 3010 | if (chunk->resource) { |
| 3011 | const char* alias = std::getenv("LEONIDA_UPLOAD_ALIAS"); | ||
| 3012 | if (alias && *alias == '1') | ||
| 3013 | leonida::title_va_aliases().remove(reinterpret_cast<std::uint64_t>(chunk->cpu_base), chunk->gpu_base); | ||
| 2952 | chunk->resource->Unmap(0, nullptr); | 3014 | chunk->resource->Unmap(0, nullptr); |
| 2953 | chunk->resource->Release(); | 3015 | chunk->resource->Release(); |
| 2954 | } else { | 3016 | } else { |
diff --git a/runtime/shims/d3d12_xs_list_values.h b/runtime/shims/d3d12_xs_list_values.h index e49eefa98..b4f24bbbb 100644 --- a/runtime/shims/d3d12_xs_list_values.h +++ b/runtime/shims/d3d12_xs_list_values.h | |||
| @@ -31,8 +31,10 @@ | |||
| 31 | // - The thread that signals a gate runs the work the layer held behind it (QueueHolds: the held lists' submission, | 31 | // - The thread that signals a gate runs the work the layer held behind it (QueueHolds: the held lists' submission, |
| 32 | // the shadow refresh, a deferred Present). That is the releaser, a second thread: the pump only decides, so | 32 | // the shadow refresh, a deferred Present). That is the releaser, a second thread: the pump only decides, so |
| 33 | // writes keep landing and other gates keep timing out while held work runs. | 33 | // writes keep landing and other gates keep timing out while held work runs. |
| 34 | // Bounded: a gate is signalled after LEONIDA_VALUE_WAIT_TIMEOUT_MS (default 200 ms) whatever memory holds, counted | 34 | // Bounded: a gate is signalled after LEONIDA_VALUE_WAIT_TIMEOUT_MS (default 200 ms) of idle wait time, counted from |
| 35 | // from when the gates before it on its queue opened, and logged once per address. Short timeouts (4 ms) go to an | 35 | // when the gates before it on its queue opened and paused (up to a finite cap scaled with the gate's own budget) while |
| 36 | // the releaser is running held work, while an acyclic matching producer write is in flight, or while unrelated | ||
| 37 | // unblocked GPU work is running (src/list_value_wait_budget.h); logged once per address. Short timeouts (4 ms) go to an | ||
| 36 | // address that timed out three times in a row, and, once four gates in a row timed out (the title waits for values | 38 | // address that timed out three times in a row, and, once four gates in a row timed out (the title waits for values |
| 37 | // no modelled write stores, a new address each frame), to every wait whose address was never met: a frame then pays | 39 | // no modelled write stores, a new address each frame), to every wait whose address was never met: a frame then pays |
| 38 | // a few milliseconds, not the full timeout, per such wait. A wait cut short is watched for the rest of the full | 40 | // a few milliseconds, not the full timeout, per such wait. A wait cut short is watched for the rest of the full |
| @@ -56,10 +58,12 @@ | |||
| 56 | #include <memory> | 58 | #include <memory> |
| 57 | #include <mutex> | 59 | #include <mutex> |
| 58 | #include <new> | 60 | #include <new> |
| 61 | #include <span> | ||
| 59 | #include <utility> | 62 | #include <utility> |
| 60 | #include <vector> | 63 | #include <vector> |
| 61 | 64 | ||
| 62 | #include "d3d12_xs_device.h" // console_value_met, ListValueStats | 65 | #include "d3d12_xs_device.h" // console_value_met, ListValueStats |
| 66 | #include "../src/list_value_wait_budget.h" // leonida::list_value_wait: work-aware timeout clock & producer graph | ||
| 63 | #include "../src/title_page_watch.h" // leonida::kernel_writes::store | 67 | #include "../src/title_page_watch.h" // leonida::kernel_writes::store |
| 64 | #include "../src/value_write_sink.h" // leonida::value_sink: the arena and xmem's PAGE_NOACCESS pages | 68 | #include "../src/value_write_sink.h" // leonida::value_sink: the arena and xmem's PAGE_NOACCESS pages |
| 65 | 69 | ||
| @@ -362,7 +366,8 @@ public: | |||
| 362 | if (writes.empty() || exiting_.load(std::memory_order_relaxed)) return; // stop(): see there | 366 | if (writes.empty() || exiting_.load(std::memory_order_relaxed)) return; // stop(): see there |
| 363 | { | 367 | { |
| 364 | std::lock_guard lock(mutex_); | 368 | std::lock_guard lock(mutex_); |
| 365 | writes_.push_back({std::move(queue), value, std::move(writes)}); | 369 | const std::uint64_t after_gate = max_pending_gate_locked(queue.get()); |
| 370 | writes_.push_back({std::move(queue), value, std::move(writes), after_gate}); | ||
| 366 | } | 371 | } |
| 367 | start_or_settle(); | 372 | start_or_settle(); |
| 368 | } | 373 | } |
| @@ -396,7 +401,7 @@ public: | |||
| 396 | gate.value = value; | 401 | gate.value = value; |
| 397 | gate.started = true; | 402 | gate.started = true; |
| 398 | gate.since = Clock::now(); | 403 | gate.since = Clock::now(); |
| 399 | gate.deadline = Clock::time_point::max(); | 404 | gate.last_tick = gate.since; |
| 400 | gate.after = after; | 405 | gate.after = after; |
| 401 | gate.action = std::move(action); | 406 | gate.action = std::move(action); |
| 402 | gates_.push_back(std::move(gate)); | 407 | gates_.push_back(std::move(gate)); |
| @@ -502,13 +507,15 @@ private: | |||
| 502 | std::shared_ptr<QueueValues> queue; | 507 | std::shared_ptr<QueueValues> queue; |
| 503 | std::uint64_t value; | 508 | std::uint64_t value; |
| 504 | std::vector<Write> writes; | 509 | std::vector<Write> writes; |
| 510 | std::uint64_t after_gate = 0; // highest pending gate value on `queue` ahead of this write group | ||
| 505 | }; | 511 | }; |
| 506 | struct Gate { | 512 | struct Gate { |
| 507 | std::shared_ptr<QueueValues> queue; | 513 | std::shared_ptr<QueueValues> queue; |
| 508 | std::uint64_t value = 0; | 514 | std::uint64_t value = 0; |
| 509 | std::vector<Wait> waits; | 515 | std::vector<Wait> waits; |
| 510 | Clock::time_point deadline; // set by start_gate | 516 | leonida::list_value_wait::GateTimeoutState timeout{}; // work-aware timeout clock (set by start_gate) |
| 511 | Clock::time_point since; | 517 | Clock::time_point last_tick{}; |
| 518 | Clock::time_point since{}; | ||
| 512 | bool started = false; // the gates before it on its queue have opened: its time runs | 519 | bool started = false; // the gates before it on its queue have opened: its time runs |
| 513 | bool cut_short = false; // given the short timeout | 520 | bool cut_short = false; // given the short timeout |
| 514 | std::uint64_t after = 0; // action gates: the queue's `written` value the action runs behind | 521 | std::uint64_t after = 0; // action gates: the queue's `written` value the action runs behind |
| @@ -632,12 +639,21 @@ private: | |||
| 632 | releasing_ = true; | 639 | releasing_ = true; |
| 633 | } | 640 | } |
| 634 | SetEvent(wake_); // the pump may be in an untimed wait: it watches the Signals from here on | 641 | SetEvent(wake_); // the pump may be in an untimed wait: it watches the Signals from here on |
| 642 | struct PendingReleaseGuard { | ||
| 643 | std::atomic<std::size_t>* count; | ||
| 644 | std::size_t remaining; | ||
| 645 | ~PendingReleaseGuard() { | ||
| 646 | if (remaining) count->fetch_sub(remaining, std::memory_order_release); | ||
| 647 | } | ||
| 648 | } pending_guard{&pending_releases_, batch.size()}; | ||
| 635 | for (Release& release : batch) { | 649 | for (Release& release : batch) { |
| 636 | if (stop_.load(std::memory_order_relaxed)) break; | 650 | if (stop_.load(std::memory_order_relaxed)) break; |
| 637 | signal_value_.store(release.value, std::memory_order_relaxed); | 651 | signal_value_.store(release.value, std::memory_order_relaxed); |
| 638 | signal_since_ms_.store(GetTickCount64() | 1, std::memory_order_relaxed); // never 0 while inside | 652 | signal_since_ms_.store(GetTickCount64() | 1, std::memory_order_relaxed); // never 0 while inside |
| 639 | signal(release); | 653 | signal(release); |
| 640 | signal_since_ms_.store(0, std::memory_order_relaxed); | 654 | signal_since_ms_.store(0, std::memory_order_relaxed); |
| 655 | pending_releases_.fetch_sub(1, std::memory_order_release); | ||
| 656 | --pending_guard.remaining; | ||
| 641 | } | 657 | } |
| 642 | std::lock_guard lock(release_mutex_); | 658 | std::lock_guard lock(release_mutex_); |
| 643 | releasing_ = false; | 659 | releasing_ = false; |
| @@ -721,36 +737,114 @@ private: | |||
| 721 | writes_.swap(rest); | 737 | writes_.swap(rest); |
| 722 | } | 738 | } |
| 723 | 739 | ||
| 724 | // The gates whose waits are met, whose time is up or whose action's turn has come, taken off the list in each | 740 | // Highest pending gate value currently in `gates_` for `queue` (0 if none). Called with mutex_ held. |
| 741 | std::uint64_t max_pending_gate_locked(const QueueValues* queue) const { | ||
| 742 | std::uint64_t highest = 0; | ||
| 743 | for (const Gate& g : gates_) | ||
| 744 | if (g.queue.get() == queue && g.value > highest) highest = g.value; | ||
| 745 | return highest; | ||
| 746 | } | ||
| 747 | |||
| 748 | // The gates whose waits are met, whose idle time is up or whose action's turn has come, taken off the list in each | ||
| 725 | // queue's order (a queue's gate values rise in submission order, so a later one must not be signalled first: it | 749 | // queue's order (a queue's gate values rise in submission order, so a later one must not be signalled first: it |
| 726 | // would open the earlier one too). `force` (no threads): every gate, now. Called with mutex_ held. | 750 | // would open the earlier one too). A memory gate's timeout clock pauses while held work is being released, while |
| 727 | void take_open(bool force, std::vector<Release>& opening) { | 751 | // an acyclic matching producer write is in flight, or (up to a cap) while unrelated unblocked GPU work is running |
| 728 | std::vector<const QueueValues*> blocked; | 752 | // (src/list_value_wait_budget.h). `force` (no threads): every gate, now. Called with mutex_ held. |
| 753 | void take_open(bool force, bool landed_any, std::vector<Release>& opening) { | ||
| 754 | if (gates_.empty()) return; | ||
| 729 | const auto now = Clock::now(); | 755 | const auto now = Clock::now(); |
| 730 | for (auto it = gates_.begin(); it != gates_.end();) { | 756 | namespace lvw = leonida::list_value_wait; |
| 731 | const QueueValues* queue = it->queue.get(); | 757 | |
| 732 | if (std::find(blocked.begin(), blocked.end(), queue) != blocked.end()) { | 758 | // Build the lightweight producer/gate dependency view lazily only if a started memory gate is still unmet. |
| 733 | ++it; | 759 | bool graph_built = false; |
| 734 | continue; | 760 | std::vector<lvw::PendingWrite> flat_writes; |
| 761 | std::vector<lvw::PendingWriteGroup> view_writes; | ||
| 762 | std::vector<lvw::WaitPredicate> flat_waits; | ||
| 763 | std::vector<lvw::PendingGate> view_gates; | ||
| 764 | std::vector<std::pair<std::size_t, std::size_t>> gate_wait_ranges; // (offset, count) into flat_waits | ||
| 765 | const auto ensure_graph = [&] { | ||
| 766 | if (graph_built) return; | ||
| 767 | graph_built = true; | ||
| 768 | std::size_t total_writes = 0; | ||
| 769 | for (const WriteGroup& wg : writes_) total_writes += wg.writes.size(); | ||
| 770 | flat_writes.reserve(total_writes); | ||
| 771 | view_writes.reserve(writes_.size()); | ||
| 772 | for (const WriteGroup& wg : writes_) { | ||
| 773 | const std::size_t start = flat_writes.size(); | ||
| 774 | for (const Write& w : wg.writes) | ||
| 775 | flat_writes.push_back({w.address, w.value, w.bytes, w.kind != WriteKind::value}); | ||
| 776 | view_writes.push_back({wg.queue.get(), wg.after_gate, | ||
| 777 | std::span<const lvw::PendingWrite>(flat_writes).subspan(start, wg.writes.size())}); | ||
| 778 | } | ||
| 779 | std::size_t total_waits = 0; | ||
| 780 | for (const Gate& g : gates_) | ||
| 781 | if (!g.action) total_waits += g.waits.size(); | ||
| 782 | flat_waits.reserve(total_waits); | ||
| 783 | gate_wait_ranges.reserve(gates_.size()); | ||
| 784 | for (const Gate& g : gates_) { | ||
| 785 | const std::size_t start = flat_waits.size(); | ||
| 786 | if (!g.action) { | ||
| 787 | for (const Wait& w : g.waits) | ||
| 788 | if (!met_now(w)) flat_waits.push_back({w.address, w.reference, w.comparison, w.wide}); | ||
| 789 | } | ||
| 790 | gate_wait_ranges.emplace_back(start, flat_waits.size() - start); | ||
| 791 | } | ||
| 792 | view_gates.reserve(gates_.size()); | ||
| 793 | for (std::size_t i = 0; i < gates_.size(); ++i) { | ||
| 794 | const auto [off, cnt] = gate_wait_ranges[i]; | ||
| 795 | view_gates.push_back({gates_[i].queue.get(), gates_[i].value, static_cast<bool>(gates_[i].action), | ||
| 796 | std::span<const lvw::WaitPredicate>(flat_waits).subspan(off, cnt)}); | ||
| 735 | } | 797 | } |
| 798 | }; | ||
| 799 | |||
| 800 | std::vector<const QueueValues*> blocked; | ||
| 801 | std::vector<bool> opened(gates_.size(), false); | ||
| 802 | for (std::size_t idx = 0; idx < gates_.size(); ++idx) { | ||
| 803 | Gate& gate = gates_[idx]; | ||
| 804 | const QueueValues* queue = gate.queue.get(); | ||
| 805 | if (std::find(blocked.begin(), blocked.end(), queue) != blocked.end()) continue; | ||
| 736 | bool open = force; | 806 | bool open = force; |
| 737 | if (it->action) { | 807 | if (gate.action) { |
| 738 | open = open || queue->written->GetCompletedValue() >= it->after; | 808 | open = open || queue->written->GetCompletedValue() >= gate.after; |
| 739 | } else { | 809 | } else { |
| 740 | if (!it->started) start_gate(*it, now); | 810 | if (!gate.started) start_gate(gate, now); |
| 741 | bool met = true; | 811 | bool met = true; |
| 742 | for (const Wait& wait : it->waits) met = met && met_now(wait); | 812 | for (const Wait& wait : gate.waits) met = met && met_now(wait); |
| 743 | open = open || met || now >= it->deadline; | 813 | bool timed_out = false; |
| 744 | if (open) note_outcome(*it, met || force); | 814 | if (!open && !met) { |
| 815 | const std::uint64_t dt_us = | ||
| 816 | now > gate.last_tick | ||
| 817 | ? static_cast<std::uint64_t>( | ||
| 818 | std::chrono::duration_cast<std::chrono::microseconds>(now - gate.last_tick).count()) | ||
| 819 | : 0u; | ||
| 820 | gate.last_tick = now; | ||
| 821 | const bool releaser_busy = | ||
| 822 | landed_any || !opening.empty() || pending_releases_.load(std::memory_order_acquire) != 0; | ||
| 823 | lvw::PauseReason reason = lvw::PauseReason::releaser_busy; | ||
| 824 | if (!releaser_busy) { | ||
| 825 | ensure_graph(); | ||
| 826 | reason = lvw::pause_reason(false, view_writes, view_gates, idx, console_value_met); | ||
| 827 | } | ||
| 828 | timed_out = gate.timeout.advance(dt_us, reason); | ||
| 829 | } else { | ||
| 830 | gate.last_tick = now; | ||
| 831 | } | ||
| 832 | open = open || met || timed_out; | ||
| 833 | if (open) note_outcome(gate, met || force, now); | ||
| 745 | } | 834 | } |
| 746 | if (open) { | 835 | if (open) { |
| 747 | opening.push_back({std::move(it->queue), it->value, std::move(it->action)}); | 836 | opening.push_back({std::move(gate.queue), gate.value, std::move(gate.action)}); |
| 748 | it = gates_.erase(it); | 837 | opened[idx] = true; |
| 749 | } else { | 838 | } else { |
| 750 | blocked.push_back(queue); | 839 | blocked.push_back(queue); |
| 751 | ++it; | ||
| 752 | } | 840 | } |
| 753 | } | 841 | } |
| 842 | if (!opening.empty()) { | ||
| 843 | std::deque<Gate> rest; | ||
| 844 | for (std::size_t idx = 0; idx < gates_.size(); ++idx) | ||
| 845 | if (!opened[idx]) rest.push_back(std::move(gates_[idx])); | ||
| 846 | gates_.swap(rest); | ||
| 847 | } | ||
| 754 | } | 848 | } |
| 755 | 849 | ||
| 756 | // Writes landed, then gates opened: the pump's one step. `force` runs on the caller's thread when the threads do | 850 | // Writes landed, then gates opened: the pump's one step. `force` runs on the caller's thread when the threads do |
| @@ -763,12 +857,15 @@ private: | |||
| 763 | busy_ = true; | 857 | busy_ = true; |
| 764 | take_landed(force, landing); | 858 | take_landed(force, landing); |
| 765 | } | 859 | } |
| 860 | const bool landed_any = !landing.empty(); | ||
| 766 | for (const WriteGroup& group : landing) land(group); | 861 | for (const WriteGroup& group : landing) land(group); |
| 767 | std::vector<Release> opening; | 862 | std::vector<Release> opening; |
| 768 | { | 863 | { |
| 769 | std::lock_guard lock(mutex_); | 864 | std::lock_guard lock(mutex_); |
| 770 | watch_late(); | 865 | watch_late(); |
| 771 | take_open(force, opening); | 866 | take_open(force, landed_any, opening); |
| 867 | if (!force && !opening.empty()) | ||
| 868 | pending_releases_.fetch_add(opening.size(), std::memory_order_release); | ||
| 772 | } | 869 | } |
| 773 | if (!opening.empty()) { | 870 | if (!opening.empty()) { |
| 774 | if (force) { | 871 | if (force) { |
| @@ -919,7 +1016,10 @@ private: | |||
| 919 | gate.started = true; | 1016 | gate.started = true; |
| 920 | gate.cut_short = cut_short; | 1017 | gate.cut_short = cut_short; |
| 921 | gate.since = now; | 1018 | gate.since = now; |
| 922 | gate.deadline = now + std::chrono::milliseconds(cut_short ? kDemotedTimeoutMs : full); | 1019 | gate.last_tick = now; |
| 1020 | const unsigned gate_ms = cut_short ? kDemotedTimeoutMs : full; | ||
| 1021 | const auto caps = leonida::list_value_wait::default_pause_caps(gate_ms, cut_short); | ||
| 1022 | gate.timeout.reset(static_cast<std::uint64_t>(gate_ms) * 1000u, caps.active_us, caps.max_us); | ||
| 923 | } | 1023 | } |
| 924 | 1024 | ||
| 925 | // A wait for `address` was met (in time, or late): the address has met history and its timeouts in a row end. | 1025 | // A wait for `address` was met (in time, or late): the address has met history and its timeouts in a row end. |
| @@ -961,15 +1061,15 @@ private: | |||
| 961 | } | 1061 | } |
| 962 | 1062 | ||
| 963 | // Called with mutex_ held. | 1063 | // Called with mutex_ held. |
| 964 | void note_outcome(const Gate& gate, bool met) { | 1064 | void note_outcome(const Gate& gate, bool met, Clock::time_point now) { |
| 965 | if (met) { | 1065 | if (met) { |
| 966 | bump(counters().gates_met); | 1066 | bump(counters().gates_met); |
| 967 | timeouts_in_a_row_ = 0; | 1067 | timeouts_in_a_row_ = 0; |
| 968 | for (const Wait& wait : gate.waits) note_met(wait.address); | 1068 | for (const Wait& wait : gate.waits) note_met(wait.address); |
| 969 | if (gate.cut_short && !gate.waits.empty()) lift_demotion(gate.waits.front().address); | 1069 | if (gate.cut_short && !gate.waits.empty()) lift_demotion(gate.waits.front().address); |
| 970 | if (logged_met_ < 4) { // the first few, to show the model at work in a boot log | 1070 | if (logged_met_ < 4 && !gate.waits.empty()) { // the first few, to show the model at work in a boot log |
| 971 | ++logged_met_; | 1071 | ++logged_met_; |
| 972 | const double ms = std::chrono::duration<double, std::milli>(Clock::now() - gate.since).count(); | 1072 | const double ms = std::chrono::duration<double, std::milli>(now - gate.since).count(); |
| 973 | std::fprintf(stderr, "[rt] d3d12_xs: a queue's wait for 0x%llx was met after %.2f ms\n", | 1073 | std::fprintf(stderr, "[rt] d3d12_xs: a queue's wait for 0x%llx was met after %.2f ms\n", |
| 974 | static_cast<unsigned long long>(gate.waits.front().address), ms); | 1074 | static_cast<unsigned long long>(gate.waits.front().address), ms); |
| 975 | } | 1075 | } |
| @@ -990,14 +1090,14 @@ private: | |||
| 990 | for (const Wait& wait : gate.waits) { | 1090 | for (const Wait& wait : gate.waits) { |
| 991 | if (met_now(wait)) continue; | 1091 | if (met_now(wait)) continue; |
| 992 | if (gate.cut_short && !watched && late_.size() < kMaxLate) { | 1092 | if (gate.cut_short && !watched && late_.size() < kMaxLate) { |
| 993 | late_.push_back({wait, gate.since + std::chrono::milliseconds(full)}); | 1093 | late_.push_back({wait, now + std::chrono::milliseconds(full)}); |
| 994 | watched = true; | 1094 | watched = true; |
| 995 | } | 1095 | } |
| 996 | Streak* streak = find_streak(wait.address); | 1096 | Streak* streak = find_streak(wait.address); |
| 997 | if (!streak) streak = add_streak(wait.address); | 1097 | if (!streak) streak = add_streak(wait.address); |
| 998 | ++streak->timeouts; | 1098 | ++streak->timeouts; |
| 999 | std::uint64_t now = 0; | 1099 | std::uint64_t current = 0; |
| 1000 | read_value(wait.address, wait.wide, now); | 1100 | read_value(wait.address, wait.wide, current); |
| 1001 | if (!streak->logged) { | 1101 | if (!streak->logged) { |
| 1002 | streak->logged = true; | 1102 | streak->logged = true; |
| 1003 | static std::atomic<unsigned> addresses{0}; | 1103 | static std::atomic<unsigned> addresses{0}; |
| @@ -1008,7 +1108,7 @@ private: | |||
| 1008 | gate.cut_short ? kDemotedTimeoutMs : full, | 1108 | gate.cut_short ? kDemotedTimeoutMs : full, |
| 1009 | static_cast<unsigned long long>(wait.address), wait.wide ? 64u : 32u, | 1109 | static_cast<unsigned long long>(wait.address), wait.wide ? 64u : 32u, |
| 1010 | wait.comparison, static_cast<unsigned long long>(wait.reference), | 1110 | wait.comparison, static_cast<unsigned long long>(wait.reference), |
| 1011 | static_cast<unsigned long long>(now)); | 1111 | static_cast<unsigned long long>(current)); |
| 1012 | } | 1112 | } |
| 1013 | if (streak->timeouts == kDemoteAfter) { | 1113 | if (streak->timeouts == kDemoteAfter) { |
| 1014 | static std::atomic<unsigned> demoted{0}; | 1114 | static std::atomic<unsigned> demoted{0}; |
| @@ -1041,6 +1141,7 @@ private: | |||
| 1041 | std::condition_variable release_ready_; | 1141 | std::condition_variable release_ready_; |
| 1042 | std::deque<Release> releases_; | 1142 | std::deque<Release> releases_; |
| 1043 | bool releasing_ = false; | 1143 | bool releasing_ = false; |
| 1144 | std::atomic<std::size_t> pending_releases_{0}; // queued + active releases, read lock-free in take_open() | ||
| 1044 | std::atomic<std::uint64_t> signal_since_ms_{0}; // GetTickCount64 when the releaser's current Signal began, or 0 | 1145 | std::atomic<std::uint64_t> signal_since_ms_{0}; // GetTickCount64 when the releaser's current Signal began, or 0 |
| 1045 | std::atomic<std::uint64_t> signal_value_{0}; | 1146 | std::atomic<std::uint64_t> signal_value_{0}; |
| 1046 | std::atomic<DWORD> releaser_tid_{0}; | 1147 | std::atomic<DWORD> releaser_tid_{0}; |
diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp index fe800fe68..103a5c9df 100644 --- a/runtime/shims/dstorage.cpp +++ b/runtime/shims/dstorage.cpp | |||
| @@ -10,6 +10,8 @@ | |||
| 10 | // it has. Completion is therefore in queue order, as the API guarantees. | 10 | // it has. Completion is therefore in queue order, as the API guarantees. |
| 11 | // - Compressed requests stage RFC 1950 inflate, BCPack BC block reconstruction and DirectStorage | 11 | // - Compressed requests stage RFC 1950 inflate, BCPack BC block reconstruction and DirectStorage |
| 12 | // macro-unshuffle before publishing the destination. Physical page numbers resolve in xmem at execution. | 12 | // macro-unshuffle before publishing the destination. Physical page numbers resolve in xmem at execution. |
| 13 | // - A queue half full submits itself, but a read into physical pages and everything enqueued behind it wait for | ||
| 14 | // the title's own Submit: the title may fill the page list only then (hold_pages below). | ||
| 13 | // Nothing here goes online or touches the GPU. | 15 | // Nothing here goes online or touches the GPU. |
| 14 | #include <windows.h> | 16 | #include <windows.h> |
| 15 | #include <d3d12.h> | 17 | #include <d3d12.h> |
| @@ -38,6 +40,7 @@ | |||
| 38 | #include "../src/shader_directory.h" | 40 | #include "../src/shader_directory.h" |
| 39 | #include "../src/dstorage_swizzle.h" | 41 | #include "../src/dstorage_swizzle.h" |
| 40 | #include "../src/dstorage_trace.h" | 42 | #include "../src/dstorage_trace.h" |
| 43 | #include "../src/dstorage_hold.h" | ||
| 41 | #include "dstorage_xs_abi.h" | 44 | #include "dstorage_xs_abi.h" |
| 42 | #include "dstorage_staging.h" | 45 | #include "dstorage_staging.h" |
| 43 | #include "startup_trace.h" | 46 | #include "startup_trace.h" |
| @@ -542,6 +545,47 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3 | |||
| 542 | return S_OK; | 545 | return S_OK; |
| 543 | } | 546 | } |
| 544 | 547 | ||
| 548 | // ---- Reads into physical pages wait for the title's Submit ------------------------------------------------------- | ||
| 549 | // | ||
| 550 | // A request into physical pages names them through a pointer into the title's own page-number table, and a title may | ||
| 551 | // fill that table for a batch only in its submit path, right before Submit. A queue that submits itself at half its | ||
| 552 | // capacity then starts such a read early: it finds page 0 and fails, or finds the number the slot held before and | ||
| 553 | // writes the data into a page that now belongs to something else, with no error at all. So a self-submit stops at | ||
| 554 | // the first read into physical pages: that read and every entry behind it (the queue completes in order) wait for | ||
| 555 | // the title's Submit. A full queue still submits everything, since the title cannot call Submit while it waits in an | ||
| 556 | // enqueue, and Close does as before. The idea is from VIctory (Marvisak/VIctory eddde73, carried in | ||
| 557 | // fxceless/victory-fork 79cfdd9); the code here is written anew for this queue. | ||
| 558 | // | ||
| 559 | // LEONIDA_DSTORAGE_HOLD_PAGES=0 restores the old self-submit of everything. A hold has a time limit, so that a | ||
| 560 | // title path that never calls Submit and counted on the self-submit cannot stall for good: held entries that have | ||
| 561 | // waited LEONIDA_DSTORAGE_HOLD_MS milliseconds (2000 unless set) are submitted, page lists as they are, and counted | ||
| 562 | // as a timed release. 0 is no limit: they wait for Submit, however long. Both are read when a queue is created. | ||
| 563 | constexpr uint32_t kDefaultHoldMs = 2000; | ||
| 564 | |||
| 565 | uint32_t environment_number(const wchar_t* name, uint32_t fallback) { | ||
| 566 | wchar_t value[16]{}; | ||
| 567 | const DWORD n = GetEnvironmentVariableW(name, value, 16); | ||
| 568 | if (n == 0 || n >= 16) return fallback; | ||
| 569 | wchar_t* end = nullptr; | ||
| 570 | const unsigned long parsed = std::wcstoul(value, &end, 10); | ||
| 571 | return end && *end == 0 ? static_cast<uint32_t>(parsed) : fallback; | ||
| 572 | } | ||
| 573 | |||
| 574 | // One line with every counter, at each power of two of the counter that moved: countable in a truncated log | ||
| 575 | // without a line per event. | ||
| 576 | void log_hold(const char* event, uint64_t n, unsigned capacity, size_t held_now) { | ||
| 577 | if (n & (n - 1)) return; | ||
| 578 | const auto& h = leonida::dstorage::hold_stats(); | ||
| 579 | std::lock_guard lock(log_mutex()); | ||
| 580 | std::fprintf(stderr, "[rt] ds-hold event=%s self_submits=%llu held_reads=%llu full_releases=%llu " | ||
| 581 | "timed_releases=%llu page0_entries=%llu capacity=%u held_now=%zu\n", event, | ||
| 582 | static_cast<unsigned long long>(h.self_submits.load()), | ||
| 583 | static_cast<unsigned long long>(h.held_reads.load()), | ||
| 584 | static_cast<unsigned long long>(h.full_releases.load()), | ||
| 585 | static_cast<unsigned long long>(h.timed_releases.load()), | ||
| 586 | static_cast<unsigned long long>(h.page0_entries.load()), capacity, held_now); | ||
| 587 | } | ||
| 588 | |||
| 545 | // ---- Queues ------------------------------------------------------------------------------------------------------- | 589 | // ---- Queues ------------------------------------------------------------------------------------------------------- |
| 546 | 590 | ||
| 547 | // Only sampled when request tracing is enabled. Times include work done by the file/decode worker. | 591 | // Only sampled when request tracing is enabled. Times include work done by the file/decode worker. |
| @@ -576,7 +620,10 @@ struct Entry { | |||
| 576 | 620 | ||
| 577 | class Queue final : public IDStorageQueueX2 { | 621 | class Queue final : public IDStorageQueueX2 { |
| 578 | public: | 622 | public: |
| 579 | explicit Queue(const DSTORAGE_QUEUE_DESC1& desc) : desc_(desc) { | 623 | explicit Queue(const DSTORAGE_QUEUE_DESC1& desc) |
| 624 | : desc_(desc), | ||
| 625 | hold_pages_(environment_number(L"LEONIDA_DSTORAGE_HOLD_PAGES", 1) != 0), | ||
| 626 | hold_release_ms_(environment_number(L"LEONIDA_DSTORAGE_HOLD_MS", kDefaultHoldMs)) { | ||
| 580 | error_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); | 627 | error_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); |
| 581 | clear_record_locked(); | 628 | clear_record_locked(); |
| 582 | std::lock_guard lock(stats().mutex); | 629 | std::lock_guard lock(stats().mutex); |
| @@ -781,15 +828,64 @@ private: | |||
| 781 | bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; } | 828 | bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; } |
| 782 | size_t used_locked() const { return entries_.size() + in_flight_; } | 829 | size_t used_locked() const { return entries_.size() + in_flight_; } |
| 783 | 830 | ||
| 831 | // A read into physical pages: its page list may not be filled before the title's Submit (hold_pages above). | ||
| 832 | static bool into_pages(const Entry& e) { | ||
| 833 | return e.type == Entry::Type::Request && (e.request.Options.AsUINT64 & options::kDestinationPages) != 0; | ||
| 834 | } | ||
| 835 | |||
| 836 | // The queue has reached half its capacity and holds nothing yet. Submits up to the first read into physical | ||
| 837 | // pages, which waits with everything behind it for the title's Submit. | ||
| 838 | void self_submit_locked() { | ||
| 839 | auto& h = leonida::dstorage::hold_stats(); | ||
| 840 | if (!hold_pages_) { | ||
| 841 | log_hold("self-submit", ++h.self_submits, desc_.Capacity, 0); | ||
| 842 | submit_locked(); | ||
| 843 | return; | ||
| 844 | } | ||
| 845 | size_t end = submitted_; | ||
| 846 | while (end < entries_.size() && !into_pages(entries_[end])) ++end; | ||
| 847 | if (end < entries_.size()) { | ||
| 848 | uint64_t reads = 0; | ||
| 849 | for (size_t i = end; i < entries_.size(); ++i) reads += into_pages(entries_[i]); | ||
| 850 | h.held_reads += reads; | ||
| 851 | holding_ = true; | ||
| 852 | hold_warned_ = false; | ||
| 853 | held_since_ = std::chrono::steady_clock::now(); | ||
| 854 | } | ||
| 855 | const size_t held_now = entries_.size() - end; | ||
| 856 | const bool hold = holding_; // submit_locked ends a hold when it submits everything | ||
| 857 | submit_locked(end); | ||
| 858 | holding_ = hold; | ||
| 859 | if (holding_) work_.notify_one(); // the worker starts timing the hold | ||
| 860 | log_hold("self-submit", ++h.self_submits, desc_.Capacity, held_now); | ||
| 861 | } | ||
| 862 | |||
| 784 | void enqueue(Entry&& e) { | 863 | void enqueue(Entry&& e) { |
| 785 | { | 864 | { |
| 786 | std::unique_lock lock(mutex_); | 865 | std::unique_lock lock(mutex_); |
| 787 | // A full queue waits for the worker to free a slot. With auto-submit on, half the queue is always | 866 | // A full queue waits for the worker to free a slot. With auto-submit on, half the queue was submitted |
| 788 | // submitted by then; with it off, only a Submit from another thread frees one (as the reference warns). | 867 | // by then, except what is held for the title's Submit: the title cannot make that call while it waits |
| 789 | space_.wait(lock, [&] { return closing_ || used_locked() < usable(); }); | 868 | // here, so a full queue submits the held entries too, page lists as they are. With auto-submit off, |
| 869 | // only a Submit from another thread frees a slot (as the reference warns). | ||
| 870 | space_.wait(lock, [&] { | ||
| 871 | if (closing_ || used_locked() < usable()) return true; | ||
| 872 | if (holding_) { | ||
| 873 | const size_t held_now = entries_.size() - submitted_; | ||
| 874 | submit_locked(); | ||
| 875 | log_hold("full-queue", ++leonida::dstorage::hold_stats().full_releases, desc_.Capacity, held_now); | ||
| 876 | log_once("full-hold", "a full queue submitted reads into physical pages before the title's " | ||
| 877 | "Submit (their page lists may not be filled yet)"); | ||
| 878 | } | ||
| 879 | return false; | ||
| 880 | }); | ||
| 790 | if (!closing_) { | 881 | if (!closing_) { |
| 791 | entries_.push_back(std::move(e)); | 882 | entries_.push_back(std::move(e)); |
| 792 | if (auto_submit() && entries_.size() - submitted_ >= half()) submit_locked(); | 883 | if (holding_) { |
| 884 | // Behind a held read: it waits with it, whatever it is. No second self-submit until the hold ends. | ||
| 885 | if (into_pages(entries_.back())) ++leonida::dstorage::hold_stats().held_reads; | ||
| 886 | } else if (auto_submit() && entries_.size() - submitted_ >= half()) { | ||
| 887 | self_submit_locked(); | ||
| 888 | } | ||
| 793 | return; | 889 | return; |
| 794 | } | 890 | } |
| 795 | } | 891 | } |
| @@ -801,10 +897,16 @@ private: | |||
| 801 | release_references(e); | 897 | release_references(e); |
| 802 | } | 898 | } |
| 803 | 899 | ||
| 804 | void submit_locked() { | 900 | // Submits the entries before "end". Without one it submits all of them and ends a hold: the title's Submit, a |
| 901 | // full queue, Close, a hold that ran out of time. | ||
| 902 | void submit_locked(size_t end = SIZE_MAX) { | ||
| 903 | if (end >= entries_.size()) { | ||
| 904 | end = entries_.size(); | ||
| 905 | holding_ = false; | ||
| 906 | } | ||
| 805 | uint32_t requests = 0; | 907 | uint32_t requests = 0; |
| 806 | uint64_t source_bytes = 0, destination_bytes = 0; | 908 | uint64_t source_bytes = 0, destination_bytes = 0; |
| 807 | for (size_t i = submitted_; i < entries_.size(); ++i) { | 909 | for (size_t i = submitted_; i < end; ++i) { |
| 808 | Entry& e = entries_[i]; | 910 | Entry& e = entries_[i]; |
| 809 | if (e.file) e.file_counted = e.file->add_pending(); | 911 | if (e.file) e.file_counted = e.file->add_pending(); |
| 810 | if (e.counted) { | 912 | if (e.counted) { |
| @@ -820,12 +922,49 @@ private: | |||
| 820 | p.TotalRequestSourceByteCount += source_bytes; | 922 | p.TotalRequestSourceByteCount += source_bytes; |
| 821 | p.TotalRequestDestinationByteCount += destination_bytes; | 923 | p.TotalRequestDestinationByteCount += destination_bytes; |
| 822 | } | 924 | } |
| 823 | if (entries_.size() > submitted_) { | 925 | if (end > submitted_) { |
| 824 | submitted_ = entries_.size(); | 926 | submitted_ = end; |
| 825 | work_.notify_one(); | 927 | work_.notify_one(); |
| 826 | } | 928 | } |
| 827 | } | 929 | } |
| 828 | 930 | ||
| 931 | // How long the worker sleeps before it looks at a hold again: until the time limit runs out, a quarter of a | ||
| 932 | // second at most (and exactly that without a limit, for the five-second line). | ||
| 933 | std::chrono::milliseconds hold_wait_locked() const { | ||
| 934 | long long ms = 250; | ||
| 935 | if (hold_release_ms_) { | ||
| 936 | const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>( | ||
| 937 | std::chrono::steady_clock::now() - held_since_).count(); | ||
| 938 | ms = std::clamp<long long>(static_cast<long long>(hold_release_ms_) - waited, 1, 250); | ||
| 939 | } | ||
| 940 | return std::chrono::milliseconds(ms); | ||
| 941 | } | ||
| 942 | |||
| 943 | // On the worker while entries are held: a hold with a time limit ends when it runs out (a timed release), and | ||
| 944 | // one without says once that it has lasted five seconds (a title that never calls Submit would show up as this | ||
| 945 | // line and nothing after it). | ||
| 946 | void hold_tick_locked() { | ||
| 947 | if (!holding_) return; | ||
| 948 | const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>( | ||
| 949 | std::chrono::steady_clock::now() - held_since_).count(); | ||
| 950 | const size_t held_now = entries_.size() - submitted_; | ||
| 951 | if (hold_release_ms_ && waited >= static_cast<long long>(hold_release_ms_)) { | ||
| 952 | submit_locked(); | ||
| 953 | log_hold("timed", ++leonida::dstorage::hold_stats().timed_releases, desc_.Capacity, held_now); | ||
| 954 | log_once("timed-hold", "timed release: reads into physical pages held for the title's Submit were " | ||
| 955 | "submitted after LEONIDA_DSTORAGE_HOLD_MS without one (their page lists may " | ||
| 956 | "not be filled; the ds-hold line counts these)"); | ||
| 957 | } else if (waited >= 5000 && !hold_warned_) { | ||
| 958 | hold_warned_ = true; | ||
| 959 | std::lock_guard lock(log_mutex()); | ||
| 960 | std::fprintf(stderr, "[rt] dstorage: %zu entries behind a read into physical pages have waited %lld ms " | ||
| 961 | "for the title's Submit (queue %p, capacity %u; LEONIDA_DSTORAGE_HOLD_MS=<n> " | ||
| 962 | "submits them after n ms, LEONIDA_DSTORAGE_HOLD_PAGES=0 never holds)\n", | ||
| 963 | held_now, static_cast<long long>(waited), static_cast<void*>(this), | ||
| 964 | unsigned(desc_.Capacity)); | ||
| 965 | } | ||
| 966 | } | ||
| 967 | |||
| 829 | struct Prepared { | 968 | struct Prepared { |
| 830 | Entry& entry; | 969 | Entry& entry; |
| 831 | HRESULT result = S_OK; | 970 | HRESULT result = S_OK; |
| @@ -859,7 +998,11 @@ private: | |||
| 859 | bool paired = false; | 998 | bool paired = false; |
| 860 | { | 999 | { |
| 861 | std::unique_lock lock(mutex_); | 1000 | std::unique_lock lock(mutex_); |
| 862 | work_.wait(lock, [&] { return submitted_ > 0 || closed_; }); | 1001 | while (!(submitted_ > 0 || closed_)) { |
| 1002 | if (!holding_) work_.wait(lock); | ||
| 1003 | else if (work_.wait_for(lock, hold_wait_locked()) == std::cv_status::timeout) | ||
| 1004 | hold_tick_locked(); | ||
| 1005 | } | ||
| 863 | if (submitted_ == 0) return; | 1006 | if (submitted_ == 0) return; |
| 864 | head = std::move(entries_.front()); | 1007 | head = std::move(entries_.front()); |
| 865 | entries_.pop_front(); | 1008 | entries_.pop_front(); |
| @@ -1088,6 +1231,10 @@ private: | |||
| 1088 | std::vector<uint64_t> numbers(1 + (buffer.size() - 1 + offset) / 65536); | 1231 | std::vector<uint64_t> numbers(1 + (buffer.size() - 1 + offset) / 65536); |
| 1089 | if (!guarded_move(numbers.data(), pages, numbers.size() * sizeof(numbers[0]))) | 1232 | if (!guarded_move(numbers.data(), pages, numbers.size() * sizeof(numbers[0]))) |
| 1090 | return E_DSTORAGE_ACCESS_VIOLATION; | 1233 | return E_DSTORAGE_ACCESS_VIOLATION; |
| 1234 | // Page 0 is never a title page: a destination list that names it was not filled when its request ran, and | ||
| 1235 | // the request fails below. Counted, since each one is data the title asked for and did not get. | ||
| 1236 | if (write && std::find(numbers.begin(), numbers.end(), uint64_t{0}) != numbers.end()) | ||
| 1237 | log_hold("page0", ++leonida::dstorage::hold_stats().page0_entries, 0, 0); | ||
| 1091 | if (rt::xmem::transfer_physical(numbers, offset, buffer, write)) return S_OK; | 1238 | if (rt::xmem::transfer_physical(numbers, offset, buffer, write)) return S_OK; |
| 1092 | return HRESULT_FROM_WIN32(GetLastError()); | 1239 | return HRESULT_FROM_WIN32(GetLastError()); |
| 1093 | } | 1240 | } |
| @@ -1305,6 +1452,11 @@ private: | |||
| 1305 | std::condition_variable work_, space_, idle_; | 1452 | std::condition_variable work_, space_, idle_; |
| 1306 | std::deque<Entry> entries_; | 1453 | std::deque<Entry> entries_; |
| 1307 | size_t submitted_ = 0; // the first submitted_ entries are submitted | 1454 | size_t submitted_ = 0; // the first submitted_ entries are submitted |
| 1455 | const bool hold_pages_; // LEONIDA_DSTORAGE_HOLD_PAGES | ||
| 1456 | const uint32_t hold_release_ms_; // LEONIDA_DSTORAGE_HOLD_MS (kDefaultHoldMs unless set); 0: no time limit | ||
| 1457 | bool holding_ = false; // under mutex_: a self-submit left entries for the title's Submit | ||
| 1458 | bool hold_warned_ = false; // under mutex_: this hold's five-second line was written | ||
| 1459 | std::chrono::steady_clock::time_point held_since_{}; // under mutex_ | ||
| 1308 | size_t in_flight_ = 0; | 1460 | size_t in_flight_ = 0; |
| 1309 | bool closing_ = false; | 1461 | bool closing_ = false; |
| 1310 | bool closed_ = false; | 1462 | bool closed_ = false; |
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index fa5889d6a..5abb2a2fe 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp | |||
| @@ -1887,7 +1887,9 @@ void update_keyboard_pad() { | |||
| 1887 | clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours()); | 1887 | clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours()); |
| 1888 | for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); | 1888 | for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); |
| 1889 | // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard | 1889 | // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard |
| 1890 | // pad, in seconds since the pad's first update, each held 300 ms. For unattended boots: the title's first prompt | 1890 | // pad, in seconds since the pad's first update, each held 300 ms or its own button@seconds:hold, and then until the |
| 1891 | // title has read the pads kReads times since it began (never past kMaxHold seconds, or the hold if it is longer, so | ||
| 1892 | // a title that stops reading does not keep the button). For unattended boots: the title's first prompt | ||
| 1891 | // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). The parser, the timeline and the | 1893 | // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). The parser, the timeline and the |
| 1892 | // button names are gameinput_script.h's, shared with the scripted pad of a build without SDL3. | 1894 | // button names are gameinput_script.h's, shared with the scripted pad of a build without SDL3. |
| 1893 | namespace script = rt::gameinput::script; | 1895 | namespace script = rt::gameinput::script; |
| @@ -1899,7 +1901,21 @@ void update_keyboard_pad() { | |||
| 1899 | s.presses.size(), s.rejected); | 1901 | s.presses.size(), s.rejected); |
| 1900 | return s; | 1902 | return s; |
| 1901 | }(); | 1903 | }(); |
| 1902 | if (!scripted.empty()) { | 1904 | // LEONIDA_INPUT_FILE=<path> (local, for headless runs whose display takes no keyboard input): every line appended |
| 1905 | // to the file names one button of gameinput_script.h's table ("a", "down", ...) and becomes a press at once, held | ||
| 1906 | // like a scripted one (300 ms and six readings, at most 5 s). The file is read again at most every 250 ms. | ||
| 1907 | struct FilePress { | ||
| 1908 | uint32_t bit; | ||
| 1909 | double at; | ||
| 1910 | uint64_t began; | ||
| 1911 | bool started; | ||
| 1912 | }; | ||
| 1913 | static std::vector<FilePress> file_presses; | ||
| 1914 | static const std::string input_file = [] { | ||
| 1915 | const char* v = std::getenv("LEONIDA_INPUT_FILE"); | ||
| 1916 | return std::string(v ? v : ""); | ||
| 1917 | }(); | ||
| 1918 | if (!scripted.empty() || !input_file.empty()) { | ||
| 1903 | static const ULONGLONG origin = GetTickCount64(); | 1919 | static const ULONGLONG origin = GetTickCount64(); |
| 1904 | const double now = (GetTickCount64() - origin) / 1000.0; | 1920 | const double now = (GetTickCount64() - origin) / 1000.0; |
| 1905 | script::Held held{}; | 1921 | script::Held held{}; |
| @@ -1908,15 +1924,51 @@ void update_keyboard_pad() { | |||
| 1908 | static std::vector<uint64_t> began(scripted.presses.size(), 0); | 1924 | static std::vector<uint64_t> began(scripted.presses.size(), 0); |
| 1909 | static std::vector<char> started(scripted.presses.size(), 0); | 1925 | static std::vector<char> started(scripted.presses.size(), 0); |
| 1910 | const uint64_t calls = g_reading_calls.load(std::memory_order_relaxed); | 1926 | const uint64_t calls = g_reading_calls.load(std::memory_order_relaxed); |
| 1927 | if (!input_file.empty()) { | ||
| 1928 | static ULONGLONG last_read = 0; | ||
| 1929 | static std::size_t lines_done = 0; | ||
| 1930 | const ULONGLONG tick = GetTickCount64(); | ||
| 1931 | if (tick - last_read >= 250) { | ||
| 1932 | last_read = tick; | ||
| 1933 | if (FILE* f = std::fopen(input_file.c_str(), "r")) { | ||
| 1934 | char line[64]; | ||
| 1935 | std::size_t n = 0; | ||
| 1936 | while (std::fgets(line, sizeof(line), f)) { | ||
| 1937 | if (++n <= lines_done) continue; | ||
| 1938 | lines_done = n; | ||
| 1939 | std::string name(line); | ||
| 1940 | while (!name.empty() && (name.back() == '\n' || name.back() == '\r' || name.back() == ' ')) | ||
| 1941 | name.pop_back(); | ||
| 1942 | bool known = false; | ||
| 1943 | for (const script::Button& b : script::kButtons) | ||
| 1944 | if (name == b.name) { | ||
| 1945 | file_presses.push_back({b.bit, now, 0, false}); | ||
| 1946 | known = true; | ||
| 1947 | } | ||
| 1948 | std::fprintf(stderr, "[rt] gameinput: input file line %zu \"%s\" at %.1f s%s\n", n, | ||
| 1949 | name.c_str(), now, known ? "" : " (unknown button, ignored)"); | ||
| 1950 | } | ||
| 1951 | std::fclose(f); | ||
| 1952 | } | ||
| 1953 | } | ||
| 1954 | for (auto& p : file_presses) { | ||
| 1955 | if (now < p.at || now >= p.at + kMaxHold) continue; | ||
| 1956 | if (!p.started) { | ||
| 1957 | p.started = true; | ||
| 1958 | p.began = calls; | ||
| 1959 | } | ||
| 1960 | if (now < p.at + 0.3 || calls - p.began < kReads) held.buttons |= p.bit; | ||
| 1961 | } | ||
| 1962 | } | ||
| 1911 | for (std::size_t i = 0; i < scripted.presses.size(); ++i) { | 1963 | for (std::size_t i = 0; i < scripted.presses.size(); ++i) { |
| 1912 | const auto& press = scripted.presses[i]; | 1964 | const auto& press = scripted.presses[i]; |
| 1913 | bool active = false; | 1965 | bool active = false; |
| 1914 | if (now >= press.at && now < press.at + kMaxHold) { | 1966 | if (now >= press.at && now < press.at + std::max(press.hold, kMaxHold)) { |
| 1915 | if (!started[i]) { | 1967 | if (!started[i]) { |
| 1916 | started[i] = 1; | 1968 | started[i] = 1; |
| 1917 | began[i] = calls; | 1969 | began[i] = calls; |
| 1918 | } | 1970 | } |
| 1919 | active = now < press.at + 0.3 || calls - began[i] < kReads; | 1971 | active = now < press.at + press.hold || calls - began[i] < kReads; |
| 1920 | } | 1972 | } |
| 1921 | if (!active) continue; | 1973 | if (!active) continue; |
| 1922 | if (press.stick) held.stick = press.stick; | 1974 | if (press.stick) held.stick = press.stick; |
| @@ -1924,7 +1976,7 @@ void update_keyboard_pad() { | |||
| 1924 | } | 1976 | } |
| 1925 | if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down | 1977 | if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down |
| 1926 | for (const script::Button& b : script::kButtons) { | 1978 | for (const script::Button& b : script::kButtons) { |
| 1927 | if (!(scripted.named & b.bit)) continue; | 1979 | if (!(scripted.named & b.bit) && input_file.empty()) continue; |
| 1928 | const auto button = static_cast<SDL_GamepadButton>(b.sdl); | 1980 | const auto button = static_cast<SDL_GamepadButton>(b.sdl); |
| 1929 | SDL_SetJoystickVirtualButton(g_keyboard.js, button, (held.buttons & b.bit) || down[button]); | 1981 | SDL_SetJoystickVirtualButton(g_keyboard.js, button, (held.buttons & b.bit) || down[button]); |
| 1930 | } | 1982 | } |
diff --git a/runtime/shims/gameinput_script.h b/runtime/shims/gameinput_script.h index 759506750..5be554424 100644 --- a/runtime/shims/gameinput_script.h +++ b/runtime/shims/gameinput_script.h | |||
| @@ -5,10 +5,13 @@ | |||
| 5 | // | 5 | // |
| 6 | // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" | 6 | // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" |
| 7 | // | 7 | // |
| 8 | // Each entry is button@seconds, the seconds counted from the shim's first update. A press is held for kHoldSeconds, | 8 | // Each entry is button@seconds[:hold], the seconds counted from the shim's first update. A press is held for `hold` |
| 9 | // then released. Buttons: a b x y start back lb rb up down left right; rsup and rsdown throw the right stick fully up | 9 | // seconds (kHoldSeconds when the entry has none), then released: a longer hold reaches a title that reads its pad |
| 10 | // or down for the same time (they replay the stick throws the press log writes). Spaces around an entry are allowed; | 10 | // only every few seconds, as the retail title does at world-start frame rates. Buttons: a b x y start back lb rb |
| 11 | // empty entries, unknown buttons and invalid times (negative, non-finite, trailing text) are counted as rejected. | 11 | // up down left right; rsup and rsdown throw the right stick fully up or down for the same time (they replay the |
| 12 | // stick throws the press log writes). Spaces around an entry are allowed; empty entries, unknown buttons, invalid | ||
| 13 | // times (negative, non-finite, trailing text) and invalid holds (zero, negative, non-finite, more than | ||
| 14 | // kMaxHoldSeconds) are counted as rejected. | ||
| 12 | #pragma once | 15 | #pragma once |
| 13 | #include <algorithm> | 16 | #include <algorithm> |
| 14 | #include <cctype> | 17 | #include <cctype> |
| @@ -24,6 +27,7 @@ | |||
| 24 | namespace rt::gameinput::script { | 27 | namespace rt::gameinput::script { |
| 25 | 28 | ||
| 26 | constexpr double kHoldSeconds = 0.3; | 29 | constexpr double kHoldSeconds = 0.3; |
| 30 | constexpr double kMaxHoldSeconds = 600; // a typo such as b@10:1100 should not hold B for the whole run | ||
| 27 | 31 | ||
| 28 | // One scriptable button: its name in the script and the press log, its GameInput gamepad bit, and its SDL3 | 32 | // One scriptable button: its name in the script and the press log, its GameInput gamepad bit, and its SDL3 |
| 29 | // SDL_GamepadButton number, which the "scripted press of button <n>" line has always carried (tools/stage_timeline.py | 33 | // SDL_GamepadButton number, which the "scripted press of button <n>" line has always carried (tools/stage_timeline.py |
| @@ -46,6 +50,7 @@ struct Press { | |||
| 46 | uint32_t button = 0; // a GameInput gamepad bit, or 0 for a stick throw | 50 | uint32_t button = 0; // a GameInput gamepad bit, or 0 for a stick throw |
| 47 | int stick = 0; // +1 rsup, -1 rsdown (GameInput's +Y is up) | 51 | int stick = 0; // +1 rsup, -1 rsdown (GameInput's +Y is up) |
| 48 | double at = 0; // seconds | 52 | double at = 0; // seconds |
| 53 | double hold = kHoldSeconds; | ||
| 49 | }; | 54 | }; |
| 50 | 55 | ||
| 51 | struct Script { | 56 | struct Script { |
| @@ -72,17 +77,22 @@ inline Script parse(std::string text) { | |||
| 72 | const char* time = item.c_str() + sep + 1; | 77 | const char* time = item.c_str() + sep + 1; |
| 73 | char* tail; | 78 | char* tail; |
| 74 | const double seconds = std::strtod(time, &tail); | 79 | const double seconds = std::strtod(time, &tail); |
| 75 | if (tail == time || !std::isfinite(seconds) || seconds < 0 || | 80 | if (tail == time || !std::isfinite(seconds) || seconds < 0) continue; |
| 76 | item.find_first_not_of(whitespace, static_cast<size_t>(tail - item.c_str())) != std::string::npos) | 81 | double hold = kHoldSeconds; |
| 77 | continue; | 82 | if (*tail == ':') { |
| 83 | const char* hold_text = tail + 1; | ||
| 84 | hold = std::strtod(hold_text, &tail); | ||
| 85 | if (tail == hold_text || !std::isfinite(hold) || hold <= 0 || hold > kMaxHoldSeconds) continue; | ||
| 86 | } | ||
| 87 | if (item.find_first_not_of(whitespace, static_cast<size_t>(tail - item.c_str())) != std::string::npos) continue; | ||
| 78 | const auto is = [&](const char* name) { return item.compare(first, sep - first, name) == 0; }; | 88 | const auto is = [&](const char* name) { return item.compare(first, sep - first, name) == 0; }; |
| 79 | if (is("rsup") || is("rsdown")) { | 89 | if (is("rsup") || is("rsdown")) { |
| 80 | out.presses.push_back({0, is("rsup") ? 1 : -1, seconds}); | 90 | out.presses.push_back({0, is("rsup") ? 1 : -1, seconds, hold}); |
| 81 | continue; | 91 | continue; |
| 82 | } | 92 | } |
| 83 | for (const Button& b : kButtons) { | 93 | for (const Button& b : kButtons) { |
| 84 | if (is(b.name)) { | 94 | if (is(b.name)) { |
| 85 | out.presses.push_back({b.bit, 0, seconds}); | 95 | out.presses.push_back({b.bit, 0, seconds, hold}); |
| 86 | out.named |= b.bit; | 96 | out.named |= b.bit; |
| 87 | break; | 97 | break; |
| 88 | } | 98 | } |
| @@ -102,7 +112,7 @@ struct Held { | |||
| 102 | inline Held held_at(const Script& script, double seconds) { | 112 | inline Held held_at(const Script& script, double seconds) { |
| 103 | Held h; | 113 | Held h; |
| 104 | for (const Press& p : script.presses) { | 114 | for (const Press& p : script.presses) { |
| 105 | if (seconds < p.at || seconds >= p.at + kHoldSeconds) continue; | 115 | if (seconds < p.at || seconds >= p.at + p.hold) continue; |
| 106 | if (p.stick) h.stick = p.stick; | 116 | if (p.stick) h.stick = p.stick; |
| 107 | else h.buttons |= p.button; | 117 | else h.buttons |= p.button; |
| 108 | } | 118 | } |
diff --git a/runtime/shims/xapu_chad.cpp b/runtime/shims/xapu_chad.cpp index 35bda2b72..e46a61c97 100644 --- a/runtime/shims/xapu_chad.cpp +++ b/runtime/shims/xapu_chad.cpp | |||
| @@ -1,24 +1,8 @@ | |||
| 1 | // xapu.dll and chad.dll: the console's audio processing unit (APU) and audio DSP command queues. No PC has either, | 1 | // chad.dll: the console's audio DSP command queue. No PC has one, so this gives the title a connection whose calls |
| 2 | // so these give the title connections whose calls succeed, a zeroed shared buffer, a result for each stream open and | 2 | // succeed and zeroed DSP status: nothing the title submits is processed. xapu.dll, the APU command queue, is in |
| 3 | // close, and zeroed DSP status: the audio the APU would render stays silent, and nothing the title submits is processed. | 3 | // xapu_queue.cpp. |
| 4 | // | 4 | // |
| 5 | // Read from the executable's call sites (counts in docs/runtime_imports.md), statically, never run: | 5 | // Read from the executable's call sites (counts in docs/runtime_imports.md), statically, never run: |
| 6 | // XApuConnect(block24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte | ||
| 7 | // output is read later as the base of a CPU-visible buffer: per-stream | ||
| 8 | // input at base + slot * 0x280 and output at base + 0x14000 + | ||
| 9 | // slot * 0x1E00. The first argument is a 24-byte global of the title | ||
| 10 | // that other title code also addresses; whether it is an input or an | ||
| 11 | // output is not known, so it is left untouched. | ||
| 12 | // XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type | ||
| 13 | // (1, 2 and 3 seen), the second a stream slot. | ||
| 14 | // XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues. | ||
| 15 | // XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative | ||
| 16 | // HRESULT skips that result. The loop reads a type at +0, a stream slot | ||
| 17 | // at +4 and a dword at +0x34. Its per-slot state machine takes a type 1 | ||
| 18 | // result as "opened" and returns the slot to the title's free list only | ||
| 19 | // on a type 2 result, after the title enqueued a type 2 command. | ||
| 20 | // XApuDisconnect(handle, 0x20) 1 site; the return value is never read. The constant second | ||
| 21 | // argument is not declared here: nothing reads it. | ||
| 22 | // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*) 1 site; success is a return of 0. The | 6 | // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*) 1 site; success is a return of 0. The |
| 23 | // buffer comes from the title's XMemAlloc and stays the title's. | 7 | // buffer comes from the title's XMemAlloc and stays the title's. |
| 24 | // XDspActivate(handle, desc*, out*, out*) 1 site; success is a return of 0, else the caller returns -1. The two | 8 | // XDspActivate(handle, desc*, out*, out*) 1 site; success is a return of 0, else the caller returns -1. The two |
| @@ -30,12 +14,6 @@ | |||
| 30 | // at +4 equals *id. | 14 | // at +4 equals *id. |
| 31 | // XDspDeactivate, XDspDisconnect 1 site each, tail calls: the caller returns what they return. | 15 | // XDspDeactivate, XDspDisconnect 1 site each, tail calls: the caller returns what they return. |
| 32 | // | 16 | // |
| 33 | // HYPOTHESIS: the shared buffer is 0x14000 + 128 * 0x1E00 bytes. 128 slots is what fits 0x14000 at the 0x280 input | ||
| 34 | // stride, and the DSP connect passes 0x80 as its stream limit; no call site shows a bound. The 16-byte output is | ||
| 35 | // written as {base, size}; only the base is measured. | ||
| 36 | // HYPOTHESIS: a type 1 (open) or type 2 (close) command produces one result of the same type for the same slot; the | ||
| 37 | // title's state machine fits that, the console is not measured. Without the close result the title's 256 stream ids | ||
| 38 | // run out. Only the two dwords are written; other command types are accepted with S_OK and produce no result. | ||
| 39 | // HYPOTHESIS: XDspActivate's outputs point at zeroed memory owned by the connection. XDspSubmitCommand leaves *id at | 17 | // HYPOTHESIS: XDspActivate's outputs point at zeroed memory owned by the connection. XDspSubmitCommand leaves *id at |
| 40 | // the title's 0, so the zeroed status reads as "command 0 done, no error" and the title does not wait. | 18 | // the title's 0, so the zeroed status reads as "command 0 done, no error" and the title does not wait. |
| 41 | #include <windows.h> | 19 | #include <windows.h> |
| @@ -43,7 +21,6 @@ | |||
| 43 | 21 | ||
| 44 | #include <cstdint> | 22 | #include <cstdint> |
| 45 | #include <cstring> | 23 | #include <cstring> |
| 46 | #include <deque> | ||
| 47 | #include <mutex> | 24 | #include <mutex> |
| 48 | #include <new> | 25 | #include <new> |
| 49 | #include <set> | 26 | #include <set> |
| @@ -54,30 +31,13 @@ | |||
| 54 | 31 | ||
| 55 | namespace { | 32 | namespace { |
| 56 | 33 | ||
| 57 | constexpr size_t kApuBufferSize = 0x14000 + 128 * 0x1E00; | ||
| 58 | |||
| 59 | // shortcut: results past this cap are dropped (each leaks one stream id); raise it if a title that never dequeues | ||
| 60 | // must still work. | ||
| 61 | constexpr size_t kMaxResults = 4096; | ||
| 62 | |||
| 63 | struct ApuResult { | ||
| 64 | uint32_t type; | ||
| 65 | uint32_t slot; | ||
| 66 | }; | ||
| 67 | |||
| 68 | struct ApuConnection { | ||
| 69 | void* buffer; | ||
| 70 | std::mutex mutex; | ||
| 71 | std::deque<ApuResult> results; | ||
| 72 | }; | ||
| 73 | |||
| 74 | struct DspConnection { | 34 | struct DspConnection { |
| 75 | uint8_t status[256]; | 35 | uint8_t status[256]; |
| 76 | uint8_t stream[256]; | 36 | uint8_t stream[256]; |
| 77 | }; | 37 | }; |
| 78 | 38 | ||
| 79 | // gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command type, with | 39 | // gta6rt --trace FILE: the first call of each function, with the caller, so the first boot shows what the title sends |
| 80 | // the caller, so the first boot shows what the title sends without a line per call. | 40 | // without a line per call. |
| 81 | void note(const char* api, uint64_t value, const void* caller) { | 41 | void note(const char* api, uint64_t value, const void* caller) { |
| 82 | if (!rt::startup_trace::enabled()) return; | 42 | if (!rt::startup_trace::enabled()) return; |
| 83 | static std::mutex mutex; | 43 | static std::mutex mutex; |
| @@ -92,71 +52,6 @@ void note(const char* api, uint64_t value, const void* caller) { | |||
| 92 | rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)))); | 52 | rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)))); |
| 93 | } | 53 | } |
| 94 | 54 | ||
| 95 | HRESULT __stdcall XApuConnect(void* block24, void* out16, void** handle) { | ||
| 96 | note("XApuConnect", 0, _ReturnAddress()); | ||
| 97 | if (!handle) return E_INVALIDARG; | ||
| 98 | *handle = nullptr; | ||
| 99 | void* buffer = VirtualAlloc(nullptr, kApuBufferSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed | ||
| 100 | if (!buffer) return E_OUTOFMEMORY; | ||
| 101 | auto* c = new (std::nothrow) ApuConnection; // a throwing new would unwind into the title | ||
| 102 | if (!c) { | ||
| 103 | VirtualFree(buffer, 0, MEM_RELEASE); | ||
| 104 | return E_OUTOFMEMORY; | ||
| 105 | } | ||
| 106 | c->buffer = buffer; | ||
| 107 | *handle = c; | ||
| 108 | (void)block24; | ||
| 109 | if (out16) { | ||
| 110 | const uint64_t info[2] = {reinterpret_cast<uint64_t>(buffer), kApuBufferSize}; | ||
| 111 | std::memcpy(out16, info, sizeof info); | ||
| 112 | } | ||
| 113 | return S_OK; | ||
| 114 | } | ||
| 115 | |||
| 116 | HRESULT __stdcall XApuDisconnect(void* handle) { | ||
| 117 | note("XApuDisconnect", 0, _ReturnAddress()); | ||
| 118 | auto* c = static_cast<ApuConnection*>(handle); | ||
| 119 | if (!c) return E_INVALIDARG; | ||
| 120 | VirtualFree(c->buffer, 0, MEM_RELEASE); | ||
| 121 | delete c; | ||
| 122 | return S_OK; | ||
| 123 | } | ||
| 124 | |||
| 125 | HRESULT __stdcall XApuEnqueueCommand(void* handle, const uint32_t* command, uint64_t flags) { | ||
| 126 | note("XApuEnqueueCommand", command ? command[0] : ~0ull, _ReturnAddress()); | ||
| 127 | (void)flags; | ||
| 128 | auto* c = static_cast<ApuConnection*>(handle); | ||
| 129 | if (!c || !command) return E_INVALIDARG; | ||
| 130 | if (command[0] == 1 || command[0] == 2) { | ||
| 131 | try { | ||
| 132 | const std::lock_guard lock(c->mutex); | ||
| 133 | if (c->results.size() < kMaxResults) c->results.push_back({command[0], command[1]}); | ||
| 134 | } catch (...) { // out of memory: the result is lost, nothing may unwind into the title | ||
| 135 | } | ||
| 136 | } | ||
| 137 | return S_OK; | ||
| 138 | } | ||
| 139 | |||
| 140 | uint32_t __stdcall XApuGetResultCount(void* handle, uint64_t flags) { | ||
| 141 | note("XApuGetResultCount", 0, _ReturnAddress()); | ||
| 142 | (void)flags; | ||
| 143 | auto* c = static_cast<ApuConnection*>(handle); | ||
| 144 | if (!c) return 0; | ||
| 145 | const std::lock_guard lock(c->mutex); | ||
| 146 | return static_cast<uint32_t>(c->results.size()); | ||
| 147 | } | ||
| 148 | |||
| 149 | HRESULT __stdcall XApuDequeueResult(void* handle, void* result) { | ||
| 150 | note("XApuDequeueResult", 0, _ReturnAddress()); | ||
| 151 | auto* c = static_cast<ApuConnection*>(handle); | ||
| 152 | if (!c || !result) return E_INVALIDARG; | ||
| 153 | const std::lock_guard lock(c->mutex); | ||
| 154 | if (c->results.empty()) return E_FAIL; | ||
| 155 | std::memcpy(result, &c->results.front(), sizeof(ApuResult)); // the rest stays as the caller zeroed it | ||
| 156 | c->results.pop_front(); | ||
| 157 | return S_OK; | ||
| 158 | } | ||
| 159 | |||
| 160 | HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* buffer, uint32_t a, uint32_t b, uint32_t max_streams, | 55 | HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* buffer, uint32_t a, uint32_t b, uint32_t max_streams, |
| 161 | uint32_t flags, void** handle) { | 56 | uint32_t flags, void** handle) { |
| 162 | note("XDspConnectWithMaximumStreamLimit", max_streams, _ReturnAddress()); | 57 | note("XDspConnectWithMaximumStreamLimit", max_streams, _ReturnAddress()); |
| @@ -199,14 +94,6 @@ HRESULT __stdcall XDspSubmitCommand(void*, void*, uint32_t*) { | |||
| 199 | 94 | ||
| 200 | } // namespace | 95 | } // namespace |
| 201 | 96 | ||
| 202 | SHIM_TABLE(xapu, | ||
| 203 | {"xapu.dll", "XApuConnect", reinterpret_cast<void*>(&XApuConnect)}, | ||
| 204 | {"xapu.dll", "XApuDequeueResult", reinterpret_cast<void*>(&XApuDequeueResult)}, | ||
| 205 | {"xapu.dll", "XApuDisconnect", reinterpret_cast<void*>(&XApuDisconnect)}, | ||
| 206 | {"xapu.dll", "XApuEnqueueCommand", reinterpret_cast<void*>(&XApuEnqueueCommand)}, | ||
| 207 | {"xapu.dll", "XApuGetResultCount", reinterpret_cast<void*>(&XApuGetResultCount)}, | ||
| 208 | ); | ||
| 209 | |||
| 210 | SHIM_TABLE(chad, | 97 | SHIM_TABLE(chad, |
| 211 | {"chad.dll", "XDspActivate", reinterpret_cast<void*>(&XDspActivate)}, | 98 | {"chad.dll", "XDspActivate", reinterpret_cast<void*>(&XDspActivate)}, |
| 212 | {"chad.dll", "XDspConnectWithMaximumStreamLimit", reinterpret_cast<void*>(&XDspConnectWithMaximumStreamLimit)}, | 99 | {"chad.dll", "XDspConnectWithMaximumStreamLimit", reinterpret_cast<void*>(&XDspConnectWithMaximumStreamLimit)}, |
diff --git a/runtime/shims/xapu_queue.cpp b/runtime/shims/xapu_queue.cpp new file mode 100644 index 000000000..e754376ba --- /dev/null +++ b/runtime/shims/xapu_queue.cpp | |||
| @@ -0,0 +1,438 @@ | |||
| 1 | // xapu.dll: the console's audio processing unit (APU) command queue. No PC has one, so this keeps the queue the title | ||
| 2 | // talks to - one result per accepted command, in command order, with the console's error codes. With | ||
| 3 | // runtime/opus_decoder built (LEONIDA_HAVE_OPUS_DECODER) a process command decodes its Opus packet to PCM; without | ||
| 4 | // it the result carries the frame count its table-of-contents byte gives and silence in its output. | ||
| 5 | // | ||
| 6 | // Read from the executable's call sites (counts in docs/runtime_imports.md, shapes in docs/audio_hal_exe_calls.md), | ||
| 7 | // statically, never run: | ||
| 8 | // XApuConnect(input24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte | ||
| 9 | // output is read later as the base of a CPU-visible buffer: per-stream | ||
| 10 | // input at base + slot * 0x280 and output at base + 0x14000 + | ||
| 11 | // slot * 0x1E00. The first argument is a 24-byte global of the title | ||
| 12 | // that other title code also addresses. | ||
| 13 | // XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type | ||
| 14 | // (1, 2 and 3 seen), the second a stream slot. | ||
| 15 | // XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues. | ||
| 16 | // XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative | ||
| 17 | // HRESULT skips that result. The loop reads a type at +0, a stream slot | ||
| 18 | // at +4 and a dword at +0x34. Its per-slot state machine takes a type 1 | ||
| 19 | // result as "opened" and returns the slot to the title's free list only | ||
| 20 | // on a type 2 result, after the title enqueued a type 2 command. | ||
| 21 | // XApuDisconnect(handle, 0x20) 1 site; the return value is never read. | ||
| 22 | // | ||
| 23 | // Where the layouts come from. The signatures, structure layouts, command kinds, option bits and error codes below | ||
| 24 | // are facts recorded by Marvisak/VIctory (GPL-3.0-or-later, crates/victory-hle/src/modules/apu.rs at commit ffe310e), | ||
| 25 | // whose runtime runs the retail executable through these calls; see docs/related_projects.md. Nothing of its code is | ||
| 26 | // copied; this file is written from those facts. They agree with every shape above: the first argument of | ||
| 27 | // XApuConnect is an input, the dword the title reads at +0x34 of a result is its output byte count, and a type 1 | ||
| 28 | // (activate) or type 2 (deactivate) command gives a result of the same kind for the same stream. | ||
| 29 | // HRESULT XApuConnect(const ConnectInput*, ConnectOutput*, Connection** out) | ||
| 30 | // HRESULT XApuDisconnect(Connection*, uint32_t) the second argument is not read | ||
| 31 | // HRESULT XApuEnqueueCommand(Connection*, const void* command, uint32_t* accepted_so_far) may be null | ||
| 32 | // HRESULT XApuDequeueResult(Connection*, Result* out) 0x8AC81001 while no result is ready | ||
| 33 | // uint32_t XApuGetResultCount(Connection*, uint32_t* dequeued_so_far) may be null; returns the results ready | ||
| 34 | // A connection is for one kind of processing; kind 1 is Opus decoding to 32-bit float PCM at 48 kHz, and any other | ||
| 35 | // kind is E_NOTIMPL. Every command starts with the 24-byte CommandId. A command refused at once (unknown kind, | ||
| 36 | // stream out of range, or the stream already holding `commands_per_stream` results not dequeued) gives no result; | ||
| 37 | // every other command gives one, with its error, if any, in the result. | ||
| 38 | // | ||
| 39 | // Without runtime/opus_decoder a process command's frame count comes from the Opus packet's table-of-contents byte | ||
| 40 | // (RFC 6716, section 3.1), clipped from first_frame, to frame_count and to what output_bytes holds, and that output | ||
| 41 | // range is written with zeros, so the title sees streams advance at the right rate and the audio stays silent. With | ||
| 42 | // the crate, fill() decodes the packet and writes its PCM instead. | ||
| 43 | #include <windows.h> | ||
| 44 | #include <intrin.h> | ||
| 45 | |||
| 46 | #include <cstddef> | ||
| 47 | #include <cstdint> | ||
| 48 | #include <cstdio> | ||
| 49 | #include <cstring> | ||
| 50 | #include <deque> | ||
| 51 | #include <mutex> | ||
| 52 | #include <new> | ||
| 53 | #include <set> | ||
| 54 | #include <string> | ||
| 55 | #include <vector> | ||
| 56 | |||
| 57 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 58 | #include "leonida_opus_decoder.h" | ||
| 59 | #endif | ||
| 60 | |||
| 61 | #include "shims.h" | ||
| 62 | #include "startup_trace.h" | ||
| 63 | |||
| 64 | namespace { | ||
| 65 | |||
| 66 | constexpr HRESULT kNotImpl = static_cast<HRESULT>(rt::shims::kENotImpl); | ||
| 67 | constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u); | ||
| 68 | constexpr HRESULT kNoResult = static_cast<HRESULT>(0x8AC81001u); | ||
| 69 | constexpr HRESULT kInvalidCommand = static_cast<HRESULT>(0x8AC81002u); | ||
| 70 | constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u); | ||
| 71 | constexpr HRESULT kAlreadyActive = static_cast<HRESULT>(0x8AC81005u); | ||
| 72 | constexpr HRESULT kBadPacket = static_cast<HRESULT>(0x8AC81008u); | ||
| 73 | |||
| 74 | constexpr uint32_t kDecodeOpus = 1; // ConnectInput::processing | ||
| 75 | |||
| 76 | constexpr uint32_t kActivate = 1; // CommandId::kind | ||
| 77 | constexpr uint32_t kDeactivate = 2; | ||
| 78 | constexpr uint32_t kProcess = 3; | ||
| 79 | constexpr uint32_t kReset = 5; // 4 is notify; neither carries anything to do while nothing is decoded | ||
| 80 | |||
| 81 | constexpr uint32_t kSignalWhenDone = 0x1; // CommandId::options: set the result event when the result is ready | ||
| 82 | constexpr uint32_t kResultEvent = 0x8; // ConnectInput::options: create an auto-reset event and hand it out | ||
| 83 | constexpr uint32_t kDeinterleavedOutput = 0x4; // ConnectInput::options: split stereo into two planes | ||
| 84 | constexpr uint32_t kOpusSampleRate = 48000; | ||
| 85 | |||
| 86 | constexpr uint32_t kMaxStreams = 500; | ||
| 87 | constexpr uint32_t kMaxCommandsPerStream = 16; | ||
| 88 | constexpr uint32_t kMaxFrames = 5760; // 120 ms at 48 kHz, the longest Opus packet (RFC 6716, section 3.2.5) | ||
| 89 | |||
| 90 | #pragma pack(push, 1) | ||
| 91 | struct ConnectInput { | ||
| 92 | uint32_t processing; | ||
| 93 | uint32_t streams; | ||
| 94 | uint32_t commands_per_stream; | ||
| 95 | uint32_t memory_bytes; | ||
| 96 | uint32_t frames_per_output; // 0 for decoding | ||
| 97 | uint32_t options; | ||
| 98 | }; | ||
| 99 | struct ConnectOutput { | ||
| 100 | void* memory; // zeroed, for the title's packets and output | ||
| 101 | HANDLE result_event; | ||
| 102 | }; | ||
| 103 | struct CommandId { | ||
| 104 | uint32_t kind; | ||
| 105 | uint32_t stream; | ||
| 106 | uint32_t sequence; | ||
| 107 | uint32_t options; | ||
| 108 | uint64_t context; | ||
| 109 | }; | ||
| 110 | struct ActivateCommand { | ||
| 111 | CommandId id; | ||
| 112 | uint32_t channels; // 1 or 2 | ||
| 113 | uint32_t init_bytes; | ||
| 114 | const void* init; | ||
| 115 | float start_pitch; | ||
| 116 | uint32_t processing_bytes; | ||
| 117 | void* processing; | ||
| 118 | }; | ||
| 119 | struct ProcessCommand { | ||
| 120 | CommandId id; | ||
| 121 | float pitch_ramp; | ||
| 122 | float target_pitch; | ||
| 123 | uint32_t first_frame; | ||
| 124 | uint32_t frame_count; | ||
| 125 | uint32_t input_bytes; | ||
| 126 | const uint8_t* input; | ||
| 127 | uint32_t output_bytes; | ||
| 128 | uint8_t* output; | ||
| 129 | }; | ||
| 130 | struct Result { | ||
| 131 | CommandId id; | ||
| 132 | uint32_t state; | ||
| 133 | uint64_t state_data; | ||
| 134 | uint64_t usec; | ||
| 135 | HRESULT error; | ||
| 136 | uint32_t frames; | ||
| 137 | uint32_t output_bytes; | ||
| 138 | uint8_t* output; | ||
| 139 | float pitch; | ||
| 140 | uint32_t input_bytes; | ||
| 141 | const uint8_t* input; | ||
| 142 | }; | ||
| 143 | #pragma pack(pop) | ||
| 144 | static_assert(sizeof(ConnectInput) == 24, "six dwords"); | ||
| 145 | static_assert(sizeof(ConnectOutput) == 16, "memory and event"); | ||
| 146 | static_assert(sizeof(CommandId) == 24, "kind, stream, sequence, options, context"); | ||
| 147 | static_assert(sizeof(ActivateCommand) == 56, "CommandId and the activate fields"); | ||
| 148 | static_assert(sizeof(ProcessCommand) == 64, "CommandId and the process fields"); | ||
| 149 | static_assert(sizeof(Result) == 0x50, "the result the title dequeues"); | ||
| 150 | static_assert(offsetof(Result, state) == 0x18 && offsetof(Result, error) == 0x2C && | ||
| 151 | offsetof(Result, output_bytes) == 0x34 && offsetof(Result, pitch) == 0x40 && | ||
| 152 | offsetof(Result, input) == 0x48, | ||
| 153 | "the offsets the title and the layout agree on"); | ||
| 154 | |||
| 155 | struct Stream { | ||
| 156 | bool active = false; | ||
| 157 | uint32_t channels = 0; | ||
| 158 | uint32_t pending = 0; // results queued and not dequeued | ||
| 159 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 160 | LeonidaOpusDecoder* decoder = nullptr; | ||
| 161 | #endif | ||
| 162 | }; | ||
| 163 | |||
| 164 | struct Connection { | ||
| 165 | void* memory = nullptr; | ||
| 166 | HANDLE event = nullptr; | ||
| 167 | uint32_t commands_per_stream = 0; | ||
| 168 | bool deinterleaved = false; | ||
| 169 | std::mutex mutex; | ||
| 170 | std::vector<Stream> streams; | ||
| 171 | std::deque<Result> results; | ||
| 172 | uint32_t accepted = 0; | ||
| 173 | uint32_t dequeued = 0; | ||
| 174 | }; | ||
| 175 | |||
| 176 | // gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command kind, with | ||
| 177 | // the caller, so the first boot shows what the title sends without a line per call. | ||
| 178 | void note(const char* api, uint64_t value, const void* caller) { | ||
| 179 | if (!rt::startup_trace::enabled()) return; | ||
| 180 | static std::mutex mutex; | ||
| 181 | static std::set<std::pair<std::string, uint64_t>> seen; | ||
| 182 | { | ||
| 183 | const std::lock_guard lock(mutex); | ||
| 184 | if (!seen.insert({api, value}).second) return; | ||
| 185 | } | ||
| 186 | rt::startup_trace::event( | ||
| 187 | "audio_queue", std::string("\"api\":") + rt::startup_trace::quote(api) + | ||
| 188 | ",\"value\":" + rt::startup_trace::quote(rt::startup_trace::hex(value)) + ",\"caller\":" + | ||
| 189 | rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)))); | ||
| 190 | } | ||
| 191 | |||
| 192 | // Samples per channel at 48 kHz in one Opus packet, from its table-of-contents byte and frame count code (RFC 6716, | ||
| 193 | // section 3.1); 0 for a packet that is not valid. The no-decoder path counts frames this way. | ||
| 194 | uint32_t opus_packet_frames(const uint8_t* packet, uint32_t bytes) { | ||
| 195 | if (!packet || bytes == 0) return 0; | ||
| 196 | static constexpr uint32_t kSilk[4] = {480, 960, 1920, 2880}; // 10, 20, 40, 60 ms | ||
| 197 | static constexpr uint32_t kHybrid[2] = {480, 960}; // 10, 20 ms | ||
| 198 | static constexpr uint32_t kCelt[4] = {120, 240, 480, 960}; // 2.5, 5, 10, 20 ms | ||
| 199 | const uint32_t config = packet[0] >> 3; | ||
| 200 | const uint32_t per_frame = config < 12 ? kSilk[config & 3] : config < 16 ? kHybrid[config & 1] : kCelt[config & 3]; | ||
| 201 | uint32_t count = 0; | ||
| 202 | switch (packet[0] & 3) { | ||
| 203 | case 0: count = 1; break; | ||
| 204 | case 1: | ||
| 205 | case 2: count = 2; break; | ||
| 206 | default: | ||
| 207 | if (bytes < 2) return 0; | ||
| 208 | count = packet[1] & 0x3F; | ||
| 209 | break; | ||
| 210 | } | ||
| 211 | if (count == 0 || count * per_frame > kMaxFrames) return 0; | ||
| 212 | return count * per_frame; | ||
| 213 | } | ||
| 214 | |||
| 215 | // Fills a process command's result: the packet's PCM when runtime/opus_decoder is built, silence (with the frame | ||
| 216 | // count from the table-of-contents byte) otherwise. | ||
| 217 | void fill(Connection& connection, Stream& stream, const ProcessCommand& c, Result& r) { | ||
| 218 | r.input = c.input; | ||
| 219 | r.input_bytes = c.input_bytes; | ||
| 220 | r.output = c.output; | ||
| 221 | if (!c.input || !c.output || c.input_bytes == 0) { | ||
| 222 | r.error = E_INVALIDARG; | ||
| 223 | return; | ||
| 224 | } | ||
| 225 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 226 | if (stream.decoder) { | ||
| 227 | const uint32_t channels = leonida_opus_decoder_channels(stream.decoder); | ||
| 228 | if (channels == 0) { | ||
| 229 | r.error = kInvalidStream; | ||
| 230 | return; | ||
| 231 | } | ||
| 232 | std::vector<float> pcm; | ||
| 233 | try { | ||
| 234 | pcm.resize(size_t(kMaxFrames) * channels); | ||
| 235 | } catch (...) { | ||
| 236 | r.error = E_OUTOFMEMORY; | ||
| 237 | return; | ||
| 238 | } | ||
| 239 | uint32_t decoded = 0; | ||
| 240 | if (leonida_opus_decode_packet(stream.decoder, c.input, c.input_bytes, pcm.data(), kMaxFrames, &decoded) != | ||
| 241 | LEONIDA_OPUS_OK) { | ||
| 242 | r.error = kBadPacket; | ||
| 243 | return; | ||
| 244 | } | ||
| 245 | const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded; | ||
| 246 | uint32_t frames = decoded - first; | ||
| 247 | if (frames > c.frame_count) frames = c.frame_count; | ||
| 248 | const uint32_t room = c.output_bytes / (4 * channels); | ||
| 249 | if (frames > room) frames = room; | ||
| 250 | const uint32_t bytes = frames * channels * 4; | ||
| 251 | if (connection.deinterleaved && channels == 2) { | ||
| 252 | float* out = reinterpret_cast<float*>(c.output); | ||
| 253 | for (uint32_t i = 0; i < frames; ++i) { | ||
| 254 | out[i] = pcm[(first + i) * 2]; | ||
| 255 | out[frames + i] = pcm[(first + i) * 2 + 1]; | ||
| 256 | } | ||
| 257 | } else if (bytes != 0) { | ||
| 258 | std::memcpy(c.output, pcm.data() + first * channels, bytes); | ||
| 259 | } | ||
| 260 | r.frames = frames; | ||
| 261 | r.output_bytes = bytes; | ||
| 262 | return; | ||
| 263 | } | ||
| 264 | #endif | ||
| 265 | const uint32_t decoded = opus_packet_frames(c.input, c.input_bytes); | ||
| 266 | if (decoded == 0) { | ||
| 267 | r.error = kBadPacket; | ||
| 268 | return; | ||
| 269 | } | ||
| 270 | const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded; | ||
| 271 | uint32_t frames = decoded - first; | ||
| 272 | if (frames > c.frame_count) frames = c.frame_count; | ||
| 273 | const uint32_t room = c.output_bytes / (4 * stream.channels); | ||
| 274 | if (frames > room) frames = room; | ||
| 275 | const uint32_t bytes = frames * stream.channels * 4; | ||
| 276 | std::memset(c.output, 0, bytes); // interleaved or not, silence is zeros | ||
| 277 | r.frames = frames; | ||
| 278 | r.output_bytes = bytes; | ||
| 279 | } | ||
| 280 | |||
| 281 | HRESULT __stdcall XApuConnect(const ConnectInput* input, ConnectOutput* output, Connection** out) { | ||
| 282 | note("XApuConnect", input ? input->processing : ~0ull, _ReturnAddress()); | ||
| 283 | if (!input || !output || !out) return E_INVALIDARG; | ||
| 284 | *out = nullptr; | ||
| 285 | ConnectInput in; | ||
| 286 | std::memcpy(&in, input, sizeof(in)); | ||
| 287 | if (in.streams == 0 || in.streams > kMaxStreams || in.commands_per_stream == 0 || | ||
| 288 | in.commands_per_stream > kMaxCommandsPerStream || in.memory_bytes == 0) | ||
| 289 | return E_INVALIDARG; | ||
| 290 | if (in.processing != kDecodeOpus) { | ||
| 291 | std::fprintf(stderr, "[rt] xapu: XApuConnect for processing kind %u: only Opus decoding (1); E_NOTIMPL\n", | ||
| 292 | in.processing); | ||
| 293 | return kNotImpl; | ||
| 294 | } | ||
| 295 | if (in.frames_per_output != 0) return E_INVALIDARG; | ||
| 296 | |||
| 297 | auto* c = new (std::nothrow) Connection; // a throwing new would unwind into the title | ||
| 298 | if (!c) return E_OUTOFMEMORY; | ||
| 299 | try { | ||
| 300 | c->streams.resize(in.streams); | ||
| 301 | } catch (...) { | ||
| 302 | delete c; | ||
| 303 | return E_OUTOFMEMORY; | ||
| 304 | } | ||
| 305 | c->memory = VirtualAlloc(nullptr, in.memory_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed | ||
| 306 | if (!c->memory) { | ||
| 307 | delete c; | ||
| 308 | return E_OUTOFMEMORY; | ||
| 309 | } | ||
| 310 | if (in.options & kResultEvent) { | ||
| 311 | c->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); // auto-reset | ||
| 312 | if (!c->event) { | ||
| 313 | const HRESULT hr = HRESULT_FROM_WIN32(GetLastError()); | ||
| 314 | VirtualFree(c->memory, 0, MEM_RELEASE); | ||
| 315 | delete c; | ||
| 316 | return hr; | ||
| 317 | } | ||
| 318 | } | ||
| 319 | c->commands_per_stream = in.commands_per_stream; | ||
| 320 | c->deinterleaved = (in.options & kDeinterleavedOutput) != 0; | ||
| 321 | const ConnectOutput o{c->memory, c->event}; | ||
| 322 | std::memcpy(output, &o, sizeof(o)); | ||
| 323 | *out = c; | ||
| 324 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 325 | std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets decoded\n", in.streams); | ||
| 326 | #else | ||
| 327 | std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets counted, not decoded\n", | ||
| 328 | in.streams); | ||
| 329 | #endif | ||
| 330 | return S_OK; | ||
| 331 | } | ||
| 332 | |||
| 333 | HRESULT __stdcall XApuDisconnect(Connection* c, uint32_t /*0x20 at the measured site*/) { | ||
| 334 | note("XApuDisconnect", 0, _ReturnAddress()); | ||
| 335 | if (!c) return E_INVALIDARG; | ||
| 336 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 337 | for (Stream& s : c->streams) | ||
| 338 | if (s.decoder) leonida_opus_decoder_destroy(s.decoder); | ||
| 339 | #endif | ||
| 340 | if (c->event) CloseHandle(c->event); | ||
| 341 | VirtualFree(c->memory, 0, MEM_RELEASE); | ||
| 342 | delete c; | ||
| 343 | return S_OK; | ||
| 344 | } | ||
| 345 | |||
| 346 | HRESULT __stdcall XApuEnqueueCommand(Connection* c, const void* command, uint32_t* accepted_so_far) { | ||
| 347 | if (!c || !command) return E_INVALIDARG; | ||
| 348 | CommandId id; | ||
| 349 | std::memcpy(&id, command, sizeof(id)); | ||
| 350 | note("XApuEnqueueCommand", id.kind, _ReturnAddress()); | ||
| 351 | if (id.kind < kActivate || id.kind > kReset) return kInvalidCommand; | ||
| 352 | |||
| 353 | const std::lock_guard lock(c->mutex); | ||
| 354 | if (id.stream >= c->streams.size()) return kInvalidStream; | ||
| 355 | Stream& stream = c->streams[id.stream]; | ||
| 356 | if (stream.pending >= c->commands_per_stream) return kQueueFull; | ||
| 357 | |||
| 358 | Result r{}; | ||
| 359 | r.id = id; | ||
| 360 | r.pitch = 1.0f; | ||
| 361 | if (id.kind == kActivate) { | ||
| 362 | ActivateCommand a; | ||
| 363 | std::memcpy(&a, command, sizeof(a)); | ||
| 364 | if (stream.active) { | ||
| 365 | r.error = kAlreadyActive; | ||
| 366 | } else if (a.channels < 1 || a.channels > 2) { | ||
| 367 | r.error = E_INVALIDARG; | ||
| 368 | } else { | ||
| 369 | stream.active = true; | ||
| 370 | stream.channels = a.channels; | ||
| 371 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 372 | if (leonida_opus_decoder_create(kOpusSampleRate, a.channels, &stream.decoder) != LEONIDA_OPUS_OK) { | ||
| 373 | stream.active = false; | ||
| 374 | stream.channels = 0; | ||
| 375 | r.error = E_INVALIDARG; | ||
| 376 | } | ||
| 377 | #endif | ||
| 378 | } | ||
| 379 | } else if (id.kind == kDeactivate) { | ||
| 380 | stream.active = false; | ||
| 381 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 382 | if (stream.decoder) { | ||
| 383 | leonida_opus_decoder_destroy(stream.decoder); | ||
| 384 | stream.decoder = nullptr; | ||
| 385 | } | ||
| 386 | #endif | ||
| 387 | } else if (id.kind == kReset) { | ||
| 388 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 389 | if (stream.decoder) leonida_opus_decoder_reset(stream.decoder); | ||
| 390 | #endif | ||
| 391 | } else if (id.kind == kProcess) { | ||
| 392 | ProcessCommand p; | ||
| 393 | std::memcpy(&p, command, sizeof(p)); | ||
| 394 | if (!stream.active) r.error = kInvalidStream; | ||
| 395 | else fill(*c, stream, p, r); | ||
| 396 | } | ||
| 397 | try { | ||
| 398 | c->results.push_back(r); | ||
| 399 | } catch (...) { // out of memory: refuse the command, nothing may unwind into the title | ||
| 400 | return E_OUTOFMEMORY; | ||
| 401 | } | ||
| 402 | ++stream.pending; | ||
| 403 | ++c->accepted; | ||
| 404 | if (accepted_so_far) *accepted_so_far = c->accepted; | ||
| 405 | if ((id.options & kSignalWhenDone) && c->event) SetEvent(c->event); | ||
| 406 | return S_OK; | ||
| 407 | } | ||
| 408 | |||
| 409 | HRESULT __stdcall XApuDequeueResult(Connection* c, Result* out) { | ||
| 410 | note("XApuDequeueResult", 0, _ReturnAddress()); | ||
| 411 | if (!c || !out) return E_INVALIDARG; | ||
| 412 | const std::lock_guard lock(c->mutex); | ||
| 413 | if (c->results.empty()) return kNoResult; | ||
| 414 | const Result r = c->results.front(); | ||
| 415 | c->results.pop_front(); | ||
| 416 | --c->streams[r.id.stream].pending; | ||
| 417 | ++c->dequeued; | ||
| 418 | std::memcpy(out, &r, sizeof(r)); | ||
| 419 | return S_OK; | ||
| 420 | } | ||
| 421 | |||
| 422 | uint32_t __stdcall XApuGetResultCount(Connection* c, uint32_t* dequeued_so_far) { | ||
| 423 | note("XApuGetResultCount", 0, _ReturnAddress()); | ||
| 424 | if (!c) return 0; | ||
| 425 | const std::lock_guard lock(c->mutex); | ||
| 426 | if (dequeued_so_far) *dequeued_so_far = c->dequeued; | ||
| 427 | return static_cast<uint32_t>(c->results.size()); | ||
| 428 | } | ||
| 429 | |||
| 430 | } // namespace | ||
| 431 | |||
| 432 | SHIM_TABLE(xapu, | ||
| 433 | {"xapu.dll", "XApuConnect", reinterpret_cast<void*>(&XApuConnect)}, | ||
| 434 | {"xapu.dll", "XApuDequeueResult", reinterpret_cast<void*>(&XApuDequeueResult)}, | ||
| 435 | {"xapu.dll", "XApuDisconnect", reinterpret_cast<void*>(&XApuDisconnect)}, | ||
| 436 | {"xapu.dll", "XApuEnqueueCommand", reinterpret_cast<void*>(&XApuEnqueueCommand)}, | ||
| 437 | {"xapu.dll", "XApuGetResultCount", reinterpret_cast<void*>(&XApuGetResultCount)}, | ||
| 438 | ); | ||
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 384f7bd27..cbd857fce 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp | |||
| @@ -1032,12 +1032,62 @@ constexpr size_t kUnmapRecords = 1024; | |||
| 1032 | UnmapRecord g_unmaps[kUnmapRecords]; | 1032 | UnmapRecord g_unmaps[kUnmapRecords]; |
| 1033 | uint64_t g_unmap_count = 0; | 1033 | uint64_t g_unmap_count = 0; |
| 1034 | thread_local const char* t_unmap_cause = "unmap"; | 1034 | thread_local const char* t_unmap_cause = "unmap"; |
| 1035 | |||
| 1036 | // A remap of physical pages (XMemMapPhysicalPages with pages, the scatter call, CopyPageMappingsBatchX): the pages | ||
| 1037 | // whose frame it took away. unmap_range_locked records each page that held a frame while one is installed (under the | ||
| 1038 | // fault lock: host_heap only, nothing else); when it goes, with g_phys_mutex still held and the fault lock not, every | ||
| 1039 | // page now mapped to another frame than it had (or to none) is reported as released, in runs, so the geometry copies | ||
| 1040 | // over it are retired as over freed or unmapped memory (geometry_writes::note_released, GeometryViews::drain_released): | ||
| 1041 | // the title streams by remapping the frames of its pools, and the copies of what those pages held before were kept | ||
| 1042 | // for the device's life. A page mapped again to the frame it had is no change. LEONIDA_GEOMETRY_REMAP_RELEASE=0: off. | ||
| 1043 | bool remap_releases_enabled() { | ||
| 1044 | static const bool on = [] { | ||
| 1045 | const char* v = std::getenv("LEONIDA_GEOMETRY_REMAP_RELEASE"); | ||
| 1046 | return !v || std::strcmp(v, "0") != 0; | ||
| 1047 | }(); | ||
| 1048 | return on; | ||
| 1049 | } | ||
| 1050 | struct RemapReleases; | ||
| 1051 | thread_local RemapReleases* t_remap_releases = nullptr; | ||
| 1052 | struct RemapReleases { | ||
| 1053 | leonida::host_heap::vector<std::pair<uintptr_t, uint64_t>> pages; // address, the frame it had | ||
| 1054 | bool active = false; | ||
| 1055 | RemapReleases() { | ||
| 1056 | if (!t_remap_releases && remap_releases_enabled()) { | ||
| 1057 | t_remap_releases = this; | ||
| 1058 | active = true; | ||
| 1059 | } | ||
| 1060 | } | ||
| 1061 | RemapReleases(const RemapReleases&) = delete; | ||
| 1062 | RemapReleases& operator=(const RemapReleases&) = delete; | ||
| 1063 | ~RemapReleases(); // g_phys_mutex held, the fault lock not | ||
| 1064 | }; | ||
| 1035 | struct UnmapCause { | 1065 | struct UnmapCause { |
| 1036 | const char* was; | 1066 | const char* was; |
| 1037 | explicit UnmapCause(const char* cause) : was(std::exchange(t_unmap_cause, cause)) {} | 1067 | explicit UnmapCause(const char* cause) : was(std::exchange(t_unmap_cause, cause)) {} |
| 1038 | ~UnmapCause() { t_unmap_cause = was; } | 1068 | ~UnmapCause() { t_unmap_cause = was; } |
| 1039 | }; | 1069 | }; |
| 1040 | 1070 | ||
| 1071 | RemapReleases::~RemapReleases() { | ||
| 1072 | if (!active) return; | ||
| 1073 | t_remap_releases = nullptr; | ||
| 1074 | if (pages.empty()) return; | ||
| 1075 | std::sort(pages.begin(), pages.end()); | ||
| 1076 | uintptr_t run_begin = 0, run_end = 0; | ||
| 1077 | for (const auto& [at, frame] : pages) { | ||
| 1078 | const auto now = g_mapped.find(at); | ||
| 1079 | if (now != g_mapped.end() && now->second == frame) continue; // the frame it had: no change | ||
| 1080 | if (run_end == at && run_end > run_begin) { | ||
| 1081 | run_end = at + kPhysicalPageSize; | ||
| 1082 | continue; | ||
| 1083 | } | ||
| 1084 | if (run_end > run_begin) leonida::geometry_writes::note_released(run_begin, run_end); | ||
| 1085 | run_begin = at; | ||
| 1086 | run_end = at + kPhysicalPageSize; | ||
| 1087 | } | ||
| 1088 | if (run_end > run_begin) leonida::geometry_writes::note_released(run_begin, run_end); | ||
| 1089 | } | ||
| 1090 | |||
| 1041 | // With g_fault_lock held exclusively. Unmaps every page in [start, end); the addresses become placeholders again. A | 1091 | // With g_fault_lock held exclusively. Unmaps every page in [start, end); the addresses become placeholders again. A |
| 1042 | // view that reaches outside the range is unmapped whole, and its pages outside the range are mapped again, so | 1092 | // view that reaches outside the range is unmapped whole, and its pages outside the range are mapped again, so |
| 1043 | // neighbours keep their pages. | 1093 | // neighbours keep their pages. |
| @@ -1064,6 +1114,7 @@ bool unmap_range_locked(uintptr_t start, uintptr_t end) { | |||
| 1064 | // The pages of [start, end) this view held are unmapped now; the ones outside it are mapped again below. | 1114 | // The pages of [start, end) this view held are unmapped now; the ones outside it are mapped again below. |
| 1065 | for (uintptr_t at = (std::max)(base, start); at < (std::min)(view_end, end); at += kPhysicalPageSize) { | 1115 | for (uintptr_t at = (std::max)(base, start); at < (std::min)(view_end, end); at += kPhysicalPageSize) { |
| 1066 | if (const auto mapped = g_mapped.find(at); mapped != g_mapped.end()) { | 1116 | if (const auto mapped = g_mapped.find(at); mapped != g_mapped.end()) { |
| 1117 | if (t_remap_releases) t_remap_releases->pages.emplace_back(at, mapped->second); | ||
| 1067 | note_mapping(mapped->second, at, false); | 1118 | note_mapping(mapped->second, at, false); |
| 1068 | g_mapped.erase(mapped); | 1119 | g_mapped.erase(mapped); |
| 1069 | } | 1120 | } |
| @@ -1575,7 +1626,7 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { | |||
| 1575 | MEMORY_BASIC_INFORMATION seen{}; // the page as the decision saw it | 1626 | MEMORY_BASIC_INFORMATION seen{}; // the page as the decision saw it |
| 1576 | char read_note[1024]; | 1627 | char read_note[1024]; |
| 1577 | DWORD read_note_size = 0; | 1628 | DWORD read_note_size = 0; |
| 1578 | bool plant_read = false, promote = false; | 1629 | bool plant_read = false, promote = false, from_title = false; |
| 1579 | bool queried = false; | 1630 | bool queried = false; |
| 1580 | { | 1631 | { |
| 1581 | const FaultLockShared lock; | 1632 | const FaultLockShared lock; |
| @@ -1594,7 +1645,8 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { | |||
| 1594 | if (where != kNoReservation || access == 1) | 1645 | if (where != kNoReservation || access == 1) |
| 1595 | queried = VirtualQuery(reinterpret_cast<const void*>(accessed), &seen, sizeof(seen)) != 0; | 1646 | queried = VirtualQuery(reinterpret_cast<const void*>(accessed), &seen, sizeof(seen)) != 0; |
| 1596 | const auto pc = reinterpret_cast<uintptr_t>(record->ExceptionAddress); | 1647 | const auto pc = reinterpret_cast<uintptr_t>(record->ExceptionAddress); |
| 1597 | if (access == 0 && result == PageCommit::not_ours && title_code(pc)) { | 1648 | from_title = access == 0 && result == PageCommit::not_ours && title_code(pc); |
| 1649 | if (from_title) { | ||
| 1598 | if (!queried) queried = VirtualQuery(reinterpret_cast<const void*>(accessed), &seen, sizeof(seen)) != 0; | 1650 | if (!queried) queried = VirtualQuery(reinterpret_cast<const void*>(accessed), &seen, sizeof(seen)) != 0; |
| 1599 | read_note_size = describe_read(read_note, pc, accessed, seen); | 1651 | read_note_size = describe_read(read_note, pc, accessed, seen); |
| 1600 | plant_read = where == kInWindow && g_pool_zero_pages; | 1652 | plant_read = where == kInWindow && g_pool_zero_pages; |
| @@ -1670,7 +1722,8 @@ LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { | |||
| 1670 | exit = FaultExit::committed; | 1722 | exit = FaultExit::committed; |
| 1671 | } else if (answered) { | 1723 | } else if (answered) { |
| 1672 | exit = FaultExit::answered; | 1724 | exit = FaultExit::answered; |
| 1673 | } else if (result == PageCommit::committed_before && !escalated) { | 1725 | } else if ((result == PageCommit::committed_before && !escalated) || |
| 1726 | (title_page && access == 0 && result == PageCommit::not_ours && !from_title)) { | ||
| 1674 | exit = FaultExit::passed_guarded; // a guard's (the D3D12 layer's), routine: not noted | 1727 | exit = FaultExit::passed_guarded; // a guard's (the D3D12 layer's), routine: not noted |
| 1675 | } else if (title_page || reserved_write) { | 1728 | } else if (title_page || reserved_write) { |
| 1676 | note_fault(kRefused, accessed, access, result, where, seen); | 1729 | note_fault(kRefused, accessed, access, result, where, seen); |
| @@ -1834,6 +1887,7 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint | |||
| 1834 | } | 1887 | } |
| 1835 | drain_fault_notes(); | 1888 | drain_fault_notes(); |
| 1836 | const std::lock_guard lock(g_phys_mutex); | 1889 | const std::lock_guard lock(g_phys_mutex); |
| 1890 | RemapReleases remap_releases; // reported as it goes: after the fault lock, with g_phys_mutex | ||
| 1837 | const uintptr_t end = start + page_count * kPhysicalPageSize; | 1891 | const uintptr_t end = start + page_count * kPhysicalPageSize; |
| 1838 | const UnmapCause cause(page_array ? "XMemMapPhysicalPages (remap)" : "XMemMapPhysicalPages (unmap)"); | 1892 | const UnmapCause cause(page_array ? "XMemMapPhysicalPages (remap)" : "XMemMapPhysicalPages (unmap)"); |
| 1839 | if (!page_array) { | 1893 | if (!page_array) { |
| @@ -1957,6 +2011,7 @@ BOOL scatter_refused(ScatterFailure reason, uintptr_t address, DWORD error) { | |||
| 1957 | BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_count, const uint64_t* page_array) { | 2011 | BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_count, const uint64_t* page_array) { |
| 1958 | drain_fault_notes(); | 2012 | drain_fault_notes(); |
| 1959 | const std::lock_guard lock(g_phys_mutex); | 2013 | const std::lock_guard lock(g_phys_mutex); |
| 2014 | RemapReleases remap_releases; | ||
| 1960 | if (page_count && !addresses) { | 2015 | if (page_count && !addresses) { |
| 1961 | return scatter_refused(ScatterFailure::missing_addresses, 0, ERROR_INVALID_PARAMETER); | 2016 | return scatter_refused(ScatterFailure::missing_addresses, 0, ERROR_INVALID_PARAMETER); |
| 1962 | } | 2017 | } |
| @@ -1969,6 +2024,7 @@ BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_co | |||
| 1969 | return scatter_refused(ScatterFailure::unaligned, address, ERROR_INVALID_PARAMETER); | 2024 | return scatter_refused(ScatterFailure::unaligned, address, ERROR_INVALID_PARAMETER); |
| 1970 | } | 2025 | } |
| 1971 | const uint64_t page = page_array ? page_array[i] : 0; | 2026 | const uint64_t page = page_array ? page_array[i] : 0; |
| 2027 | const UnmapCause cause(page ? "XMemMapPhysicalPagesScatter (remap)" : "XMemMapPhysicalPagesScatter (unmap)"); | ||
| 1972 | if (page == 0) { | 2028 | if (page == 0) { |
| 1973 | if (!unmap_page(address)) return scatter_refused(ScatterFailure::unmap, address, GetLastError()); | 2029 | if (!unmap_page(address)) return scatter_refused(ScatterFailure::unmap, address, GetLastError()); |
| 1974 | continue; | 2030 | continue; |
| @@ -1991,6 +2047,34 @@ BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_co | |||
| 1991 | // calls with the same page make them. Every source page is looked up before any destination page changes, so a source | 2047 | // calls with the same page make them. Every source page is looked up before any destination page changes, so a source |
| 1992 | // range that overlaps the destination maps what was there before the call. A destination in a GPU-only range is mapped | 2048 | // range that overlaps the destination maps what was there before the call. A destination in a GPU-only range is mapped |
| 1993 | // at its paired CPU range too (title_gpu_views), and a source page missing at a GPU-only address is looked up there. | 2049 | // at its paired CPU range too (title_gpu_views), and a source page missing at a GPU-only address is looked up there. |
| 2050 | // A page of that CPU range the title mapped itself is the title's (title_mapped_twin): the copy leaves it as it is. | ||
| 2051 | |||
| 2052 | // With g_phys_mutex held. True when the paired CPU page at `address` holds a mapping of the title's own: its | ||
| 2053 | // XMemMapPhysicalPages or XMemMapPhysicalPagesScatter call, or a slot-31 copy onto that address. The console's | ||
| 2054 | // CopyPageMappingsBatchX changes only the GPU-only range's page table, so such a page keeps what the title put | ||
| 2055 | // there; only a page the copy mirrored there itself (MapOwner::mirror), a zero plant, or a page with no mapping | ||
| 2056 | // follows the GPU-only range. Each page kept is counted, and the first ones logged. | ||
| 2057 | bool title_mapped_twin(uintptr_t address, uintptr_t gpu, bool unmap) { | ||
| 2058 | MapOwner owner; | ||
| 2059 | { | ||
| 2060 | const FaultLockShared faults; | ||
| 2061 | uintptr_t base = 0; | ||
| 2062 | const View* const view = covering_view(address, base); | ||
| 2063 | if (!view || view->zero || view->owner == MapOwner::mirror) return false; | ||
| 2064 | owner = view->owner; | ||
| 2065 | } | ||
| 2066 | static std::atomic<uint64_t> kept{0}; | ||
| 2067 | const uint64_t n = kept.fetch_add(1, std::memory_order_relaxed) + 1; | ||
| 2068 | if (n <= 8 || (n & (n - 1)) == 0) | ||
| 2069 | std::fprintf(stderr, | ||
| 2070 | "[rt] xmem: slot-31 %s at 0x%llx left the title's %s mapping at its paired CPU page 0x%llx " | ||
| 2071 | "(%llu such pages so far)\n", | ||
| 2072 | unmap ? "unmap" : "copy", static_cast<unsigned long long>(gpu), | ||
| 2073 | owner == MapOwner::scatter ? "scatter" : owner == MapOwner::slot31 ? "slot-31" : "physical", | ||
| 2074 | static_cast<unsigned long long>(address), static_cast<unsigned long long>(n)); | ||
| 2075 | return true; | ||
| 2076 | } | ||
| 2077 | |||
| 1994 | bool copy_page_mappings(void* destination, const void* source, uint64_t pages, bool repeat_first) { | 2078 | bool copy_page_mappings(void* destination, const void* source, uint64_t pages, bool repeat_first) { |
| 1995 | const uintptr_t to = reinterpret_cast<uintptr_t>(destination); | 2079 | const uintptr_t to = reinterpret_cast<uintptr_t>(destination); |
| 1996 | const uintptr_t from = reinterpret_cast<uintptr_t>(source); | 2080 | const uintptr_t from = reinterpret_cast<uintptr_t>(source); |
| @@ -2005,14 +2089,21 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b | |||
| 2005 | return false; | 2089 | return false; |
| 2006 | } | 2090 | } |
| 2007 | const std::lock_guard lock(g_phys_mutex); | 2091 | const std::lock_guard lock(g_phys_mutex); |
| 2092 | RemapReleases remap_releases; | ||
| 2008 | // The destination is usually a GPU-only reservation, which the D3D12 layer reads at its paired CPU view | 2093 | // The destination is usually a GPU-only reservation, which the D3D12 layer reads at its paired CPU view |
| 2009 | // (title_gpu_views::to_cpu); that view gets the same pages, or it would stay reserved and never readable. | 2094 | // (title_gpu_views::to_cpu); that view gets the same pages, or it would stay reserved and never readable. |
| 2010 | const uintptr_t cpu_to = leonida::title_gpu_views::to_cpu(to, pages * kPhysicalPageSize); | 2095 | const uintptr_t cpu_to = leonida::title_gpu_views::to_cpu(to, pages * kPhysicalPageSize); |
| 2011 | const Window* const cpu_window = cpu_to != to ? find_window(cpu_to, pages * kPhysicalPageSize) : nullptr; | 2096 | const Window* const cpu_window = cpu_to != to ? find_window(cpu_to, pages * kPhysicalPageSize) : nullptr; |
| 2012 | if (!source) { | 2097 | if (!source) { |
| 2013 | for (uint64_t i = 0; i < pages; ++i) { | 2098 | for (uint64_t i = 0; i < pages; ++i) { |
| 2014 | if (!unmap_page(to + i * kPhysicalPageSize)) return false; | 2099 | const uintptr_t gpu = to + i * kPhysicalPageSize, cpu = cpu_to + i * kPhysicalPageSize; |
| 2015 | if (cpu_window && !unmap_page(cpu_to + i * kPhysicalPageSize)) return false; | 2100 | { |
| 2101 | const UnmapCause cause("CopyPageMappingsBatchX (unmap)"); | ||
| 2102 | if (!unmap_page(gpu)) return false; | ||
| 2103 | } | ||
| 2104 | if (!cpu_window || title_mapped_twin(cpu, gpu, true)) continue; | ||
| 2105 | const UnmapCause cause("CopyPageMappingsBatchX (unmap paired CPU page)"); | ||
| 2106 | if (!unmap_page(cpu)) return false; | ||
| 2016 | } | 2107 | } |
| 2017 | return true; | 2108 | return true; |
| 2018 | } | 2109 | } |
| @@ -2035,8 +2126,11 @@ bool copy_page_mappings(void* destination, const void* source, uint64_t pages, b | |||
| 2035 | const DWORD cpu_protect = cpu_window ? view_protect(*cpu_window) : 0; | 2126 | const DWORD cpu_protect = cpu_window ? view_protect(*cpu_window) : 0; |
| 2036 | for (uint64_t i = 0; i < pages; ++i) { | 2127 | for (uint64_t i = 0; i < pages; ++i) { |
| 2037 | const uint64_t page = found[static_cast<size_t>(i)]; | 2128 | const uint64_t page = found[static_cast<size_t>(i)]; |
| 2038 | if (!map_page(to + i * kPhysicalPageSize, page, protect, MapOwner::slot31)) return false; | 2129 | const uintptr_t gpu = to + i * kPhysicalPageSize, cpu = cpu_to + i * kPhysicalPageSize; |
| 2039 | if (cpu_window && !map_page(cpu_to + i * kPhysicalPageSize, page, cpu_protect, MapOwner::mirror)) return false; | 2130 | const UnmapCause cause(page ? "CopyPageMappingsBatchX (remap)" : "CopyPageMappingsBatchX (hole)"); |
| 2131 | if (!map_page(gpu, page, protect, MapOwner::slot31)) return false; | ||
| 2132 | if (cpu_window && !title_mapped_twin(cpu, gpu, false) && !map_page(cpu, page, cpu_protect, MapOwner::mirror)) | ||
| 2133 | return false; | ||
| 2040 | } | 2134 | } |
| 2041 | return true; | 2135 | return true; |
| 2042 | } | 2136 | } |
| @@ -2399,6 +2493,7 @@ bool copy_page_mappings(std::uint32_t count, const PageBatch* batches, std::uint | |||
| 2399 | std::vector<uint64_t> frames; | 2493 | std::vector<uint64_t> frames; |
| 2400 | drain_fault_notes(); | 2494 | drain_fault_notes(); |
| 2401 | const std::lock_guard lock(g_phys_mutex); | 2495 | const std::lock_guard lock(g_phys_mutex); |
| 2496 | RemapReleases remap_releases; | ||
| 2402 | try { | 2497 | try { |
| 2403 | for (uint32_t b = 0; b < count; ++b) { | 2498 | for (uint32_t b = 0; b < count; ++b) { |
| 2404 | const auto& batch = batches[b]; | 2499 | const auto& batch = batches[b]; |
diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index 96fb89e7e..6e0017f2b 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h | |||
| @@ -55,7 +55,7 @@ enum class FaultExit : int { | |||
| 55 | answered, // a mapped page committed, or found committed and allowed (another thread's map or commit) | 55 | answered, // a mapped page committed, or found committed and allowed (another thread's map or commit) |
| 56 | planted, // a window page the title never mapped, backed by a zero page | 56 | planted, // a window page the title never mapped, backed by a zero page |
| 57 | committed, // a section page in the title's reservation with no view of xmem's, committed | 57 | committed, // a section page in the title's reservation with no view of xmem's, committed |
| 58 | passed_guarded, // a committed page of xmem's views whose protection refuses the access: its guard's to answer | 58 | passed_guarded, // a committed page whose protection refuses the access, or a host guarded read of an unmapped page |
| 59 | passed_foreign, // memory that is not the title's reservation and not only reserved: someone else's fault | 59 | passed_foreign, // memory that is not the title's reservation and not only reserved: someone else's fault |
| 60 | left_to_title, // the title's reservation, or a write into memory that is only reserved: noted (FaultNote) | 60 | left_to_title, // the title's reservation, or a write into memory that is only reserved: noted (FaultNote) |
| 61 | count | 61 | count |
diff --git a/runtime/src/address_guard.h b/runtime/src/address_guard.h new file mode 100644 index 000000000..dab43d40a --- /dev/null +++ b/runtime/src/address_guard.h | |||
| @@ -0,0 +1,163 @@ | |||
| 1 | // The address guard's page table (docs/d3d12_vulkan.md, "Address guard"): what the runtime backs around heap_base, | ||
| 2 | // for shaders translated with `tools/rdna2spirv.py --address-guard` (LEONIDA_ADDRESS_GUARD=1). Header-only, no | ||
| 3 | // Vulkan: the device writes the words this computes into a mapped buffer. tools/address_guard.py is the Python | ||
| 4 | // reference of the same format and of the check a guarded access makes. | ||
| 5 | // | ||
| 6 | // Layout. A header at arena offset kGuardHeader (64 bytes, AddressGuardHeader), then two sinks: refused loads read | ||
| 7 | // kGuardZero, refused stores and atomics write kGuardDump, each at the access's offset within its 4 KiB page. The | ||
| 8 | // page table is its own buffer; the header holds its address minus heap_base. Table words: kGuardLevel1 level-1 | ||
| 9 | // words indexed by bits 47..32 of the 48-bit heap offset (one per 4 GiB chunk), naming the chunk's level-2 block; | ||
| 10 | // then the blocks, kGuardBlockWords words each, one bit per 4 KiB page (bits 31..12). Block 0 is empty (nothing | ||
| 11 | // backed), block 1 full (everything passes: a chunk the table has no room for), blocks 2.. are allocated. | ||
| 12 | #pragma once | ||
| 13 | |||
| 14 | #include <algorithm> | ||
| 15 | #include <cstdint> | ||
| 16 | #include <cstring> | ||
| 17 | #include <utility> | ||
| 18 | #include <vector> | ||
| 19 | |||
| 20 | namespace leonida::address_guard { | ||
| 21 | |||
| 22 | // Shared with tools/rdna2spirv.py (GUARD_*) and tools/address_guard.py; tests/semantic/test_address_guard.py reads | ||
| 23 | // these lines. | ||
| 24 | constexpr std::uint64_t kGuardHeader = 0x70000; | ||
| 25 | constexpr std::uint64_t kGuardZero = 0x71000; | ||
| 26 | constexpr std::uint64_t kGuardDump = 0x78000; | ||
| 27 | constexpr std::uint64_t kGuardEnd = 0x80000; | ||
| 28 | constexpr std::uint32_t kGuardLevel1 = 1u << 16; | ||
| 29 | constexpr std::uint32_t kGuardBlockWords = 1u << 15; | ||
| 30 | constexpr char kGuardMagicText[] = "LGUARD01"; | ||
| 31 | constexpr std::uint64_t kMask48 = (1ull << 48) - 1; | ||
| 32 | constexpr std::uint32_t kEmptyBlock = 0, kFullBlock = 1, kFirstBlock = 2; | ||
| 33 | |||
| 34 | constexpr std::uint64_t magic() { | ||
| 35 | std::uint64_t v = 0; | ||
| 36 | for (int i = 7; i >= 0; --i) v = v << 8 | std::uint8_t(kGuardMagicText[i]); | ||
| 37 | return v; | ||
| 38 | } | ||
| 39 | |||
| 40 | struct AddressGuardHeader { | ||
| 41 | std::uint64_t magic; // magic(): the shaders check only when it is there | ||
| 42 | std::uint64_t limit; // the arena's size: an access below it passes without a lookup | ||
| 43 | std::uint64_t table; // the page table's device address minus heap_base (mod 2^64) | ||
| 44 | std::uint32_t refused; // the shaders add 1 per refused access | ||
| 45 | std::uint32_t last_module; // the last refusing module's id: FNV-1a of its file stem (shaders write it; diagnostics) | ||
| 46 | std::uint64_t last_refused; // the last refused access's heap offset (written by the shaders, not atomically) | ||
| 47 | std::uint8_t pad[24]; | ||
| 48 | }; | ||
| 49 | static_assert(sizeof(AddressGuardHeader) == 64); | ||
| 50 | static_assert(kGuardHeader + sizeof(AddressGuardHeader) <= kGuardZero && kGuardZero < kGuardDump && | ||
| 51 | kGuardDump < kGuardEnd); | ||
| 52 | |||
| 53 | // The table's contents and the words that changed. Blocks are given to chunks for good: a chunk that loses its last | ||
| 54 | // backing keeps its (now empty) block, so a submission still in flight never reads a block that came to mean | ||
| 55 | // another chunk. When the blocks run out, a new chunk gets the full block (logged by the caller through | ||
| 56 | // overflowed()): its accesses then pass unchecked, as without the guard. | ||
| 57 | class AddressGuardTable { | ||
| 58 | public: | ||
| 59 | explicit AddressGuardTable(std::uint32_t blocks = 62) : blocks_(blocks) { | ||
| 60 | words_.assign(word_count(), 0); | ||
| 61 | std::fill_n(words_.begin() + kGuardLevel1 + std::size_t(kFullBlock) * kGuardBlockWords, kGuardBlockWords, | ||
| 62 | 0xFFFFFFFFu); | ||
| 63 | } | ||
| 64 | |||
| 65 | std::size_t word_count() const { return kGuardLevel1 + std::size_t(kFirstBlock + blocks_) * kGuardBlockWords; } | ||
| 66 | std::size_t bytes() const { return word_count() * sizeof(std::uint32_t); } | ||
| 67 | // The whole table, for the first upload. | ||
| 68 | const std::vector<std::uint32_t>& words() const { return words_; } | ||
| 69 | std::uint32_t blocks_used() const { return used_; } | ||
| 70 | std::uint32_t overflowed() const { return overflowed_; } | ||
| 71 | |||
| 72 | // Make the table say exactly `spans` (heap offset [start, end), 48-bit; a span may wrap through 2^48 for a | ||
| 73 | // negative offset). A page any byte of a span touches is backed: the GPU maps memory in whole pages. Each word | ||
| 74 | // that changes is passed to `write(index, value)`, level-2 words before level-1 ones, so a reader that sees a | ||
| 75 | // chunk's new block also sees its bits. Returns the number of words written. | ||
| 76 | template <class Write> | ||
| 77 | std::size_t assign(const std::vector<std::pair<std::uint64_t, std::uint64_t>>& spans, Write&& write) { | ||
| 78 | next_.assign(std::size_t(used_) * kGuardBlockWords, 0); | ||
| 79 | std::vector<std::uint32_t> level1(words_.begin(), words_.begin() + kGuardLevel1); | ||
| 80 | for (const auto& [start, end] : spans) { | ||
| 81 | if (end == start) continue; | ||
| 82 | const std::uint64_t first = (start & kMask48) >> 12; | ||
| 83 | const std::uint64_t last = ((end - 1) & kMask48) >> 12; | ||
| 84 | if (first <= last) { | ||
| 85 | mark(level1, first, last); | ||
| 86 | } else { // wraps through 2^48: two runs | ||
| 87 | mark(level1, first, (kMask48 >> 12)); | ||
| 88 | mark(level1, 0, last); | ||
| 89 | } | ||
| 90 | } | ||
| 91 | std::size_t written = 0; | ||
| 92 | const std::size_t base = kGuardLevel1 + std::size_t(kFirstBlock) * kGuardBlockWords; | ||
| 93 | for (std::size_t i = 0; i < next_.size(); ++i) { | ||
| 94 | if (words_[base + i] == next_[i]) continue; | ||
| 95 | words_[base + i] = next_[i]; | ||
| 96 | write(base + i, next_[i]); | ||
| 97 | ++written; | ||
| 98 | } | ||
| 99 | for (std::uint32_t i = 0; i < kGuardLevel1; ++i) { | ||
| 100 | if (words_[i] == level1[i]) continue; | ||
| 101 | words_[i] = level1[i]; | ||
| 102 | write(std::size_t(i), level1[i]); | ||
| 103 | ++written; | ||
| 104 | } | ||
| 105 | return written; | ||
| 106 | } | ||
| 107 | |||
| 108 | // The table's bit for the page of heap offset `offset`. | ||
| 109 | bool page_backed(std::uint64_t offset) const { | ||
| 110 | offset &= kMask48; | ||
| 111 | const std::uint32_t block = words_[(offset >> 32) & (kGuardLevel1 - 1)]; | ||
| 112 | const std::uint64_t page = (offset >> 12) & 0xFFFFF; | ||
| 113 | return (words_[kGuardLevel1 + std::size_t(block) * kGuardBlockWords + (page >> 5)] >> (page & 31)) & 1; | ||
| 114 | } | ||
| 115 | |||
| 116 | // What a guarded access of `extent` bytes at heap offset `offset` does (the shaders' %guard_fn): passes when | ||
| 117 | // its first and last byte are below `limit` or on backed pages. `offset` is sign-extended from 48 bits. | ||
| 118 | bool passes(std::uint64_t offset, std::uint64_t extent, std::uint64_t limit) const { | ||
| 119 | if (offset & (1ull << 47)) offset |= ~kMask48; | ||
| 120 | else offset &= kMask48; | ||
| 121 | const std::uint64_t end = offset + extent - 1; | ||
| 122 | if (offset < limit && end < limit) return true; | ||
| 123 | return page_backed(offset) && page_backed(end); | ||
| 124 | } | ||
| 125 | |||
| 126 | private: | ||
| 127 | // Set the bits of pages [first, last] (48-bit page numbers), giving their chunks blocks as needed. | ||
| 128 | void mark(std::vector<std::uint32_t>& level1, std::uint64_t first, std::uint64_t last) { | ||
| 129 | for (std::uint64_t chunk = first >> 20; chunk <= last >> 20; ++chunk) { | ||
| 130 | std::uint32_t& block = level1[chunk]; | ||
| 131 | if (block == kEmptyBlock) { | ||
| 132 | if (used_ < blocks_) { | ||
| 133 | block = kFirstBlock + used_++; | ||
| 134 | next_.resize(std::size_t(used_) * kGuardBlockWords, 0); | ||
| 135 | } else { | ||
| 136 | block = kFullBlock; | ||
| 137 | ++overflowed_; | ||
| 138 | } | ||
| 139 | } | ||
| 140 | if (block < kFirstBlock) continue; | ||
| 141 | std::uint32_t* bits = next_.data() + std::size_t(block - kFirstBlock) * kGuardBlockWords; | ||
| 142 | const std::uint64_t lo = std::max(first, chunk << 20) & 0xFFFFF; | ||
| 143 | const std::uint64_t hi = std::min(last, (chunk << 20) | 0xFFFFF) & 0xFFFFF; | ||
| 144 | for (std::uint64_t page = lo; page <= hi;) { | ||
| 145 | if (!(page & 31) && page + 31 <= hi) { | ||
| 146 | bits[page >> 5] = 0xFFFFFFFFu; | ||
| 147 | page += 32; | ||
| 148 | } else { | ||
| 149 | bits[page >> 5] |= 1u << (page & 31); | ||
| 150 | ++page; | ||
| 151 | } | ||
| 152 | } | ||
| 153 | } | ||
| 154 | } | ||
| 155 | |||
| 156 | std::uint32_t blocks_; | ||
| 157 | std::uint32_t used_ = 0; | ||
| 158 | std::uint32_t overflowed_ = 0; | ||
| 159 | std::vector<std::uint32_t> words_; // what the GPU's copy holds | ||
| 160 | std::vector<std::uint32_t> next_; // the allocated blocks being built by assign() | ||
| 161 | }; | ||
| 162 | |||
| 163 | } // namespace leonida::address_guard | ||
diff --git a/runtime/src/conservative_raster.h b/runtime/src/conservative_raster.h index 469066d17..82d6dfaca 100644 --- a/runtime/src/conservative_raster.h +++ b/runtime/src/conservative_raster.h | |||
| @@ -46,4 +46,21 @@ inline InnerCoverageRequirements inner_coverage_requirements(std::span<const std | |||
| 46 | result.valid = true; | 46 | result.valid = true; |
| 47 | return result; | 47 | return result; |
| 48 | } | 48 | } |
| 49 | |||
| 50 | // True when the mesh shader module outputs triangles (OutputTrianglesEXT, 5298). A module with lines (5269), points (27) | ||
| 51 | // or no output mode does not. Each mesh entry point of a valid module has exactly one of the three. | ||
| 52 | inline bool mesh_outputs_triangles(std::span<const std::uint32_t> words) { | ||
| 53 | if (words.size() < 5 || words[0] != 0x07230203) return false; | ||
| 54 | bool triangles = false; | ||
| 55 | for (std::size_t i = 5; i < words.size();) { | ||
| 56 | const auto count = words[i] >> 16, op = words[i] & 0xffff; | ||
| 57 | if (!count || count > words.size() - i) return false; | ||
| 58 | if (op == 16 && count >= 3) { // OpExecutionMode | ||
| 59 | if (words[i + 2] == 5298) triangles = true; | ||
| 60 | else if (words[i + 2] == 5269 || words[i + 2] == 27) return false; | ||
| 61 | } | ||
| 62 | i += count; | ||
| 63 | } | ||
| 64 | return triangles; | ||
| 65 | } | ||
| 49 | } // namespace leonida::conservative_raster | 66 | } // namespace leonida::conservative_raster |
diff --git a/runtime/src/console_heap_copy.h b/runtime/src/console_heap_copy.h new file mode 100644 index 000000000..96a1f1ad4 --- /dev/null +++ b/runtime/src/console_heap_copy.h | |||
| @@ -0,0 +1,97 @@ | |||
| 1 | #pragma once | ||
| 2 | // A console resource heap's translated copy (DeviceState::ConsoleHeap::copy): the bytes shaders read, and a host-RAM | ||
| 3 | // mirror of them that the CPU reads instead. | ||
| 4 | // | ||
| 5 | // The copy lies in the GPU address arena when the import of host memory is not used (arena.mapped + offset), and the | ||
| 6 | // arena prefers DEVICE_LOCAL | HOST_VISIBLE memory (ReBAR): a CPU read of it is an uncached read across PCIe. The | ||
| 7 | // release sweep of refresh_console_heap with LEONIDA_CONSOLE_RELEASE_FILTER=1 reads words 0-2 of both V# halves of | ||
| 8 | // every live V# slot (about 470k in a game run) to decide whether the slot needs fixing, and that read cost | ||
| 9 | // 0.9-1.0 s a sweep. Every CPU write goes through write() and zero(), which write both the copy and the mirror, so | ||
| 10 | // view() (the mirror, or the copy when there is none) holds what the GPU reads. | ||
| 11 | // | ||
| 12 | // No mirror when the copy is already host RAM (the import of the heap's own scratch), when LEONIDA_HEAP_MIRROR=0, or | ||
| 13 | // once the copy is written by the GPU pass (LEONIDA_CONSOLE_HEAP_GPU: drop_mirror(); the CPU neither writes nor reads | ||
| 14 | // the copy then). The mirror covers the heap's bytes only, not the null guard after them (written once, at creation). | ||
| 15 | // | ||
| 16 | // LEONIDA_HEAP_MIRROR_CHECK=1: refresh_console_heap compares the mirror with the copy at every release sweep | ||
| 17 | // (mismatches()) and logs the first slots that differ. | ||
| 18 | |||
| 19 | #include <algorithm> | ||
| 20 | #include <cstddef> | ||
| 21 | #include <cstdint> | ||
| 22 | #include <cstring> | ||
| 23 | #include <vector> | ||
| 24 | |||
| 25 | namespace leonida { | ||
| 26 | |||
| 27 | class ConsoleHeapCopy { | ||
| 28 | public: | ||
| 29 | // `gpu`: the copy shaders read; `bytes`: the heap's bytes (the mirror's size, when `mirrored`). | ||
| 30 | void attach(std::uint8_t* gpu, std::size_t bytes, bool mirrored) { | ||
| 31 | gpu_ = gpu; | ||
| 32 | bytes_ = bytes; | ||
| 33 | mirror_.clear(); | ||
| 34 | mirror_.shrink_to_fit(); | ||
| 35 | if (gpu && mirrored) mirror_.assign(bytes, 0); | ||
| 36 | } | ||
| 37 | // The mirror goes; view() is the copy from now on. | ||
| 38 | void drop_mirror() { | ||
| 39 | mirror_.clear(); | ||
| 40 | mirror_.shrink_to_fit(); | ||
| 41 | } | ||
| 42 | |||
| 43 | explicit operator bool() const noexcept { return gpu_ != nullptr; } | ||
| 44 | std::uint8_t* gpu() const noexcept { return gpu_; } | ||
| 45 | bool mirrored() const noexcept { return !mirror_.empty(); } | ||
| 46 | std::size_t bytes() const noexcept { return bytes_; } | ||
| 47 | |||
| 48 | // What the CPU reads: the mirror, or the copy itself. | ||
| 49 | const std::uint8_t* view() const noexcept { return mirror_.empty() ? gpu_ : mirror_.data(); } | ||
| 50 | |||
| 51 | // [at, at + n) of the copy, and of the mirror where it reaches. | ||
| 52 | void write(std::size_t at, const void* bytes, std::size_t n) { | ||
| 53 | std::memcpy(gpu_ + at, bytes, n); | ||
| 54 | if (const std::size_t m = mirror_span(at, n)) std::memcpy(mirror_.data() + at, bytes, m); | ||
| 55 | } | ||
| 56 | void zero(std::size_t at, std::size_t n) { | ||
| 57 | std::memset(gpu_ + at, 0, n); | ||
| 58 | if (const std::size_t m = mirror_span(at, n)) std::memset(mirror_.data() + at, 0, m); | ||
| 59 | } | ||
| 60 | |||
| 61 | // LEONIDA_HEAP_MIRROR_CHECK: the slots of `slot_bytes` whose mirror bytes differ from the copy's, at most `limit` | ||
| 62 | // of them in `out` (in ascending order); returns how many slots differ in all. 0 without a mirror. | ||
| 63 | std::size_t mismatches(std::size_t slot_bytes, std::size_t limit, std::vector<std::size_t>& out) const { | ||
| 64 | out.clear(); | ||
| 65 | if (mirror_.empty() || !slot_bytes) return 0; | ||
| 66 | // Read the copy in large blocks: one pass over device memory, compared in host RAM. | ||
| 67 | constexpr std::size_t kBlock = std::size_t(1) << 16; | ||
| 68 | std::vector<std::uint8_t> block; | ||
| 69 | std::size_t count = 0; | ||
| 70 | const std::size_t step = std::max(slot_bytes, kBlock / slot_bytes * slot_bytes); | ||
| 71 | for (std::size_t at = 0; at < bytes_; at += step) { | ||
| 72 | const std::size_t n = std::min(step, bytes_ - at); | ||
| 73 | block.resize(n); | ||
| 74 | std::memcpy(block.data(), gpu_ + at, n); | ||
| 75 | if (!std::memcmp(block.data(), mirror_.data() + at, n)) continue; | ||
| 76 | for (std::size_t s = 0; s < n; s += slot_bytes) { | ||
| 77 | const std::size_t k = std::min(slot_bytes, n - s); | ||
| 78 | if (!std::memcmp(block.data() + s, mirror_.data() + at + s, k)) continue; | ||
| 79 | if (out.size() < limit) out.push_back((at + s) / slot_bytes); | ||
| 80 | ++count; | ||
| 81 | } | ||
| 82 | } | ||
| 83 | return count; | ||
| 84 | } | ||
| 85 | |||
| 86 | private: | ||
| 87 | std::size_t mirror_span(std::size_t at, std::size_t n) const noexcept { | ||
| 88 | if (mirror_.empty() || at >= mirror_.size()) return 0; | ||
| 89 | return std::min(n, mirror_.size() - at); | ||
| 90 | } | ||
| 91 | |||
| 92 | std::uint8_t* gpu_ = nullptr; | ||
| 93 | std::size_t bytes_ = 0; | ||
| 94 | std::vector<std::uint8_t> mirror_; | ||
| 95 | }; | ||
| 96 | |||
| 97 | } // namespace leonida | ||
diff --git a/runtime/src/dstorage_hold.h b/runtime/src/dstorage_hold.h new file mode 100644 index 000000000..1695c1e7c --- /dev/null +++ b/runtime/src/dstorage_hold.h | |||
| @@ -0,0 +1,23 @@ | |||
| 1 | // Counters of the DirectStorage queues' rule "reads into physical pages wait for the title's Submit" | ||
| 2 | // (shims/dstorage.cpp, docs/directstorage.md). Process-wide, so the log line and the test read the same numbers. | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include <atomic> | ||
| 6 | #include <cstdint> | ||
| 7 | |||
| 8 | namespace leonida::dstorage { | ||
| 9 | |||
| 10 | struct HoldStats { | ||
| 11 | std::atomic<uint64_t> self_submits{0}; // a queue half full submitted itself | ||
| 12 | std::atomic<uint64_t> held_reads{0}; // reads into physical pages such a submit left for the title's Submit | ||
| 13 | std::atomic<uint64_t> full_releases{0}; // a full queue submitted its held entries (the title waits in an enqueue) | ||
| 14 | std::atomic<uint64_t> timed_releases{0}; // LEONIDA_DSTORAGE_HOLD_MS ran out before the title's Submit | ||
| 15 | std::atomic<uint64_t> page0_entries{0}; // destination page lists that named page 0 when their data was written | ||
| 16 | }; | ||
| 17 | |||
| 18 | inline HoldStats& hold_stats() { | ||
| 19 | static HoldStats stats; | ||
| 20 | return stats; | ||
| 21 | } | ||
| 22 | |||
| 23 | } // namespace leonida::dstorage | ||
diff --git a/runtime/src/heavy_pipeline_cache.h b/runtime/src/heavy_pipeline_cache.h new file mode 100644 index 000000000..8cad10e66 --- /dev/null +++ b/runtime/src/heavy_pipeline_cache.h | |||
| @@ -0,0 +1,94 @@ | |||
| 1 | // A pipeline cache that survives a crash, for the pipelines the offline corpus does not have (RT-HEAVY-PIPELINE-CACHE). | ||
| 2 | // | ||
| 3 | // The offline seed (pipeline_cache.bin, several GiB) covers what the `pipelines` build stage creates. A pipeline it | ||
| 4 | // misses is compiled on the spot, and some of those take the driver seconds each. pipeline_cache.session.bin cannot | ||
| 5 | // keep them across a crash: it is written at device teardown only, and a cache seeded from the corpus returns the | ||
| 6 | // whole corpus, over its write limit, so it is not written at all. | ||
| 7 | // | ||
| 8 | // So a pipeline is first created against the corpus cache with VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED. | ||
| 9 | // When the driver would have to compile, it is created again against a cache of its own, seeded from | ||
| 10 | // pipeline_cache.heavy.bin. That cache holds only the corpus's misses, so it stays small. After a compile that took | ||
| 11 | // at least LEONIDA_HEAVY_PIPELINE_CACHE_MS (default 500 ms), it is written back to disk on a thread of its own: a | ||
| 12 | // staging file renamed over the old one, so a crash at any point leaves the last complete file. | ||
| 13 | // | ||
| 14 | // This header holds the pure decisions (the threshold and when to write). Vulkan and the file live in the device. | ||
| 15 | #pragma once | ||
| 16 | |||
| 17 | #include <cstdint> | ||
| 18 | #include <cstdlib> | ||
| 19 | |||
| 20 | namespace leonida::heavy_pipeline_cache { | ||
| 21 | |||
| 22 | inline constexpr std::uint32_t default_threshold_ms = 500; | ||
| 23 | |||
| 24 | struct Threshold { | ||
| 25 | std::uint32_t ms = default_threshold_ms; // 0: off | ||
| 26 | bool valid = true; // false: the text was not a number; ms stays the default | ||
| 27 | }; | ||
| 28 | |||
| 29 | // LEONIDA_HEAVY_PIPELINE_CACHE_MS: a compile at least this long schedules a write; 0 turns the heavy cache off. | ||
| 30 | inline Threshold parse_threshold(const char* text) { | ||
| 31 | if (!text || !*text) return {}; | ||
| 32 | std::uint64_t value = 0; | ||
| 33 | for (const char* p = text; *p; ++p) { | ||
| 34 | if (*p < '0' || *p > '9') return {default_threshold_ms, false}; | ||
| 35 | value = value * 10 + std::uint64_t(*p - '0'); | ||
| 36 | if (value > 3'600'000) return {default_threshold_ms, false}; // an hour: past it the text is a mistake | ||
| 37 | } | ||
| 38 | return {std::uint32_t(value), true}; | ||
| 39 | } | ||
| 40 | |||
| 41 | // When the writer thread writes. A heavy compile marks the cache dirty; the write waits `settle_ms` after the | ||
| 42 | // newest one (heavy compiles come in bursts at a load, and each write copies the whole heavy cache) but never more | ||
| 43 | // than `max_delay_ms` after the first unwritten one, so a long burst is still saved as it goes. A write that fails | ||
| 44 | // keeps the cache dirty and is tried again `retry_ms` later, the delay doubling with each failure in a row up to | ||
| 45 | // `max_retry_ms`, so a disk that stays full or a driver that keeps failing does not make the writer spin. | ||
| 46 | class WriteSchedule { | ||
| 47 | public: | ||
| 48 | static constexpr std::uint64_t settle_ms = 3000; | ||
| 49 | static constexpr std::uint64_t max_delay_ms = 20000; | ||
| 50 | static constexpr std::uint64_t retry_ms = 5000; | ||
| 51 | static constexpr std::uint64_t max_retry_ms = 120000; | ||
| 52 | |||
| 53 | void note_heavy(std::uint64_t now_ms) { | ||
| 54 | if (!dirty_) first_ = now_ms; | ||
| 55 | dirty_ = true; | ||
| 56 | last_ = now_ms; | ||
| 57 | ++generation_; | ||
| 58 | } | ||
| 59 | bool dirty() const { return dirty_; } | ||
| 60 | // The time to write at; only meaningful while dirty. | ||
| 61 | std::uint64_t due_ms() const { | ||
| 62 | const std::uint64_t settled = last_ + settle_ms, latest = first_ + max_delay_ms; | ||
| 63 | const std::uint64_t at = settled < latest ? settled : latest; | ||
| 64 | return at > retry_at_ ? at : retry_at_; | ||
| 65 | } | ||
| 66 | bool due(std::uint64_t now_ms) const { return dirty_ && now_ms >= due_ms(); } | ||
| 67 | // Taken when a write starts; the write covers every heavy compile noted up to then. | ||
| 68 | std::uint64_t generation() const { return generation_; } | ||
| 69 | // A write that started at `generation` and `started_ms` is done. A heavy compile noted after it started, even in | ||
| 70 | // the same millisecond tick, keeps the cache dirty for the next write, due as if it were first noted then. | ||
| 71 | void written(std::uint64_t generation, std::uint64_t started_ms) { | ||
| 72 | failures_ = 0; | ||
| 73 | retry_at_ = 0; | ||
| 74 | if (generation_ == generation) dirty_ = false; | ||
| 75 | else first_ = started_ms; | ||
| 76 | } | ||
| 77 | // A write that started at `started_ms` failed: the cache stays dirty and the next try waits out the backoff. | ||
| 78 | void failed(std::uint64_t started_ms) { | ||
| 79 | std::uint64_t delay = retry_ms; | ||
| 80 | for (std::uint32_t i = 0; i < failures_ && delay < max_retry_ms; ++i) delay *= 2; | ||
| 81 | if (delay > max_retry_ms) delay = max_retry_ms; | ||
| 82 | if (failures_ < 64) ++failures_; | ||
| 83 | retry_at_ = started_ms + delay; | ||
| 84 | } | ||
| 85 | std::uint32_t failures() const { return failures_; } | ||
| 86 | |||
| 87 | private: | ||
| 88 | bool dirty_ = false; | ||
| 89 | std::uint64_t first_ = 0, last_ = 0, generation_ = 0; | ||
| 90 | std::uint32_t failures_ = 0; // failed writes in a row | ||
| 91 | std::uint64_t retry_at_ = 0; // no write before this time after a failure | ||
| 92 | }; | ||
| 93 | |||
| 94 | } // namespace leonida::heavy_pipeline_cache | ||
diff --git a/runtime/src/list_value_wait_budget.h b/runtime/src/list_value_wait_budget.h new file mode 100644 index 000000000..8e1fd5219 --- /dev/null +++ b/runtime/src/list_value_wait_budget.h | |||
| @@ -0,0 +1,251 @@ | |||
| 1 | #pragma once | ||
| 2 | // Work-aware timeout clock and cycle-safe producer dependency analysis for console command-list memory waits | ||
| 3 | // (runtime/shims/d3d12_xs_list_values.h, docs/d3d12_xs_console_abi.md §5.5). | ||
| 4 | // | ||
| 5 | // A memory wait gate needs a bounded timeout so an unmodelled write (one the runtime never lands) cannot hang a queue | ||
| 6 | // forever. Counting wall-clock time blindly cuts waits short whenever the runtime is busy running held work (e.g. | ||
| 7 | // multi-second CPU shadow/texture copies inside the releaser) or while an in-flight producer write has not finished on | ||
| 8 | // the GPU yet, running dependent queues out of order. | ||
| 9 | // | ||
| 10 | // This header separates the policy from Windows/D3D12 handles so it can be verified portably under sanitizers: | ||
| 11 | // - `pause_reason()` decides whether submitted or held work can still satisfy a gate without creating a deadlock cycle: | ||
| 12 | // 1. `releaser_busy`: held work from an already-opened gate is currently being released/submitted; | ||
| 13 | // 2. `matching_producer`: an in-flight WriteGroup whose final write to a waited address can satisfy an unmet wait, and | ||
| 14 | // every pending gate preceding that WriteGroup is cycle-free with respect to the waiting queue; | ||
| 15 | // 3. `active_work`: unrelated unblocked GPU work (a WriteGroup or action gate with no pending gate ahead of it) is | ||
| 16 | // still executing, paused only up to `active_pause_cap_us` so a continuously streaming queue cannot starve an | ||
| 17 | // unmodelled wait. | ||
| 18 | // - `GateTimeoutState` tracks idle wait time (`elapsed_us`) separately from paused time, expiring once `elapsed_us` | ||
| 19 | // reaches `budget_us`. Every pause reason (`releaser_busy` and `matching_producer` included) is bounded by a finite | ||
| 20 | // `max_pause_cap_us` so a producer stuck behind an untracked dependency (e.g. a title fence wait or a hung Signal) | ||
| 21 | // still expires instead of hanging forever, and demoted (`cut_short`) gates scale both caps with their short budget. | ||
| 22 | // | ||
| 23 | // Pure C++20 standard library only. | ||
| 24 | |||
| 25 | #include <algorithm> | ||
| 26 | #include <cstddef> | ||
| 27 | #include <cstdint> | ||
| 28 | #include <span> | ||
| 29 | #include <vector> | ||
| 30 | |||
| 31 | namespace leonida::list_value_wait { | ||
| 32 | |||
| 33 | enum class PauseReason : std::uint8_t { | ||
| 34 | none = 0, // no submitted or held work can still satisfy this gate -> timeout clock ticks | ||
| 35 | releaser_busy = 1, // releaser thread is executing or draining opened gates | ||
| 36 | matching_producer = 2, // an acyclic in-flight WriteGroup can satisfy an unmet wait of this gate | ||
| 37 | active_work = 3, // unrelated unblocked submitted work is still executing (bounded by active_pause_cap_us) | ||
| 38 | }; | ||
| 39 | |||
| 40 | struct WaitPredicate { | ||
| 41 | std::uint64_t address = 0; | ||
| 42 | std::uint64_t reference = 0; | ||
| 43 | std::uint32_t comparison = 0; | ||
| 44 | bool wide = false; | ||
| 45 | }; | ||
| 46 | |||
| 47 | struct PendingWrite { | ||
| 48 | std::uint64_t address = 0; | ||
| 49 | std::uint64_t value = 0; | ||
| 50 | std::uint8_t bytes = 0; | ||
| 51 | bool timestamp = false; // GPU/system timestamp: final value is unknown until landing | ||
| 52 | }; | ||
| 53 | |||
| 54 | struct PendingWriteGroup { | ||
| 55 | const void* queue = nullptr; | ||
| 56 | std::uint64_t after_gate = 0; // highest pending gate value on `queue` ahead of this group when submitted (0: none) | ||
| 57 | std::span<const PendingWrite> writes; | ||
| 58 | }; | ||
| 59 | |||
| 60 | struct PendingGate { | ||
| 61 | const void* queue = nullptr; | ||
| 62 | std::uint64_t value = 0; | ||
| 63 | bool is_action = false; // waits only on earlier GPU work on `queue`, never on memory | ||
| 64 | std::span<const WaitPredicate> unmet_waits; // waits not currently satisfied in memory (empty for action gates) | ||
| 65 | }; | ||
| 66 | |||
| 67 | struct PauseCaps { | ||
| 68 | std::uint64_t active_us = 0; // cap on pausing solely for unrelated active_work | ||
| 69 | std::uint64_t max_us = 0; // hard finite cap across ALL pause reasons (releaser_busy, matching_producer, active_work) | ||
| 70 | }; | ||
| 71 | |||
| 72 | // Pause caps scaled with the gate's own timeout budget (`gate_timeout_ms`) and demotion state (`cut_short`): | ||
| 73 | // - Normal gates: `active_us = 300x` and `max_us = 1500x` of `gate_timeout_ms`, capped at 10 min. At the default | ||
| 74 | // 200 ms timeout this allows up to 60 s for unrelated GPU work and up to 300 s (5 min) while the releaser or an | ||
| 75 | // acyclic matching producer is working (covering multi-minute world-phase pipeline builds), while guaranteeing a | ||
| 76 | // finite exit if a producer is held behind an untracked dependency (title fence wait or stuck Signal). | ||
| 77 | // - Demoted (`cut_short`) gates: `active_us = 1x` and `max_us = 4x` of `gate_timeout_ms` (4 ms / 16 ms at the 4 ms | ||
| 78 | // demoted budget), so an unmodelled wait only pays a few milliseconds instead of inheriting the full timeout's cap. | ||
| 79 | inline constexpr PauseCaps default_pause_caps(unsigned gate_timeout_ms, bool cut_short = false) { | ||
| 80 | constexpr std::uint64_t kMaxCapMs = 600000u; // 10 min hard ceiling | ||
| 81 | const std::uint64_t base_ms = gate_timeout_ms ? std::uint64_t{gate_timeout_ms} : 1u; | ||
| 82 | const auto scale_ms = [base_ms](std::uint64_t mult) -> std::uint64_t { | ||
| 83 | return base_ms > kMaxCapMs / mult ? kMaxCapMs : base_ms * mult; | ||
| 84 | }; | ||
| 85 | const std::uint64_t active_ms = cut_short ? (base_ms < kMaxCapMs ? base_ms : kMaxCapMs) : scale_ms(300u); | ||
| 86 | const std::uint64_t max_ms = cut_short ? scale_ms(4u) : scale_ms(1500u); | ||
| 87 | return {active_ms * 1000u, max_ms * 1000u}; | ||
| 88 | } | ||
| 89 | |||
| 90 | inline constexpr std::uint64_t default_active_pause_cap_us(unsigned gate_timeout_ms, bool cut_short = false) { | ||
| 91 | return default_pause_caps(gate_timeout_ms, cut_short).active_us; | ||
| 92 | } | ||
| 93 | |||
| 94 | inline constexpr std::uint64_t default_max_pause_cap_us(unsigned gate_timeout_ms, bool cut_short = false) { | ||
| 95 | return default_pause_caps(gate_timeout_ms, cut_short).max_us; | ||
| 96 | } | ||
| 97 | |||
| 98 | struct GateTimeoutState { | ||
| 99 | std::uint64_t budget_us = 0; | ||
| 100 | std::uint64_t elapsed_us = 0; | ||
| 101 | std::uint64_t active_paused_us = 0; | ||
| 102 | std::uint64_t active_pause_cap_us = 0; | ||
| 103 | std::uint64_t total_paused_us = 0; | ||
| 104 | std::uint64_t max_pause_cap_us = 0; | ||
| 105 | bool paused_ever = false; | ||
| 106 | |||
| 107 | void reset(std::uint64_t budget, std::uint64_t active_cap, std::uint64_t max_cap) { | ||
| 108 | budget_us = budget; | ||
| 109 | elapsed_us = 0; | ||
| 110 | active_paused_us = 0; | ||
| 111 | total_paused_us = 0; | ||
| 112 | max_pause_cap_us = max_cap; | ||
| 113 | active_pause_cap_us = active_cap < max_cap ? active_cap : max_cap; | ||
| 114 | paused_ever = false; | ||
| 115 | } | ||
| 116 | |||
| 117 | // Advances the gate by `dt_us` under `reason`. Returns true once the idle timeout budget is exhausted. | ||
| 118 | // Every pause reason is bounded by `max_pause_cap_us`; unrelated `active_work` is additionally bounded by | ||
| 119 | // `active_pause_cap_us`. | ||
| 120 | bool advance(std::uint64_t dt_us, PauseReason reason) { | ||
| 121 | std::uint64_t room = 0; | ||
| 122 | if (reason == PauseReason::releaser_busy || reason == PauseReason::matching_producer) { | ||
| 123 | room = total_paused_us < max_pause_cap_us ? max_pause_cap_us - total_paused_us : 0u; | ||
| 124 | } else if (reason == PauseReason::active_work) { | ||
| 125 | const std::uint64_t total_room = | ||
| 126 | total_paused_us < max_pause_cap_us ? max_pause_cap_us - total_paused_us : 0u; | ||
| 127 | const std::uint64_t active_room = | ||
| 128 | active_paused_us < active_pause_cap_us ? active_pause_cap_us - active_paused_us : 0u; | ||
| 129 | room = total_room < active_room ? total_room : active_room; | ||
| 130 | } | ||
| 131 | if (room > 0) { | ||
| 132 | if (dt_us == 0) return false; | ||
| 133 | paused_ever = true; | ||
| 134 | const std::uint64_t absorb = dt_us < room ? dt_us : room; | ||
| 135 | total_paused_us += absorb; | ||
| 136 | if (reason == PauseReason::active_work) active_paused_us += absorb; | ||
| 137 | dt_us -= absorb; | ||
| 138 | } | ||
| 139 | if (dt_us > UINT64_MAX - elapsed_us) | ||
| 140 | elapsed_us = UINT64_MAX; | ||
| 141 | else | ||
| 142 | elapsed_us += dt_us; | ||
| 143 | return elapsed_us >= budget_us; | ||
| 144 | } | ||
| 145 | }; | ||
| 146 | |||
| 147 | namespace detail { | ||
| 148 | |||
| 149 | // True when `group`'s final write touching [wait.address, wait.address + need) lands a value that meets `wait` | ||
| 150 | // (or is a timestamp write to the exact address whose runtime value is unknown until landing). | ||
| 151 | template <class MetFn> | ||
| 152 | inline bool write_group_matches_wait(const PendingWriteGroup& group, const WaitPredicate& wait, MetFn&& met) { | ||
| 153 | const std::uint64_t need = wait.wide ? 8u : 4u; | ||
| 154 | if (!wait.address || wait.address > UINT64_MAX - need) return false; | ||
| 155 | const std::uint64_t wait_end = wait.address + need; | ||
| 156 | for (std::size_t i = group.writes.size(); i-- > 0;) { | ||
| 157 | const PendingWrite& w = group.writes[i]; | ||
| 158 | if (!w.bytes || w.address > UINT64_MAX - w.bytes) continue; | ||
| 159 | const std::uint64_t write_end = w.address + w.bytes; | ||
| 160 | if (w.address >= wait_end || wait.address >= write_end) continue; | ||
| 161 | if (w.address == wait.address && w.bytes >= need && | ||
| 162 | (w.timestamp || met(wait.comparison, w.value, wait.reference, wait.wide))) | ||
| 163 | return true; | ||
| 164 | // A later write in the same group overwrote or partially overlapped the waited range with a non-matching value. | ||
| 165 | return false; | ||
| 166 | } | ||
| 167 | return false; | ||
| 168 | } | ||
| 169 | |||
| 170 | // True when no pending gate in `gates` precedes `(queue, after_gate)`. | ||
| 171 | inline bool is_unblocked(std::span<const PendingGate> gates, const void* queue, std::uint64_t after_gate) { | ||
| 172 | if (!after_gate) return true; | ||
| 173 | for (const PendingGate& g : gates) | ||
| 174 | if (g.queue == queue && g.value <= after_gate) return false; | ||
| 175 | return true; | ||
| 176 | } | ||
| 177 | |||
| 178 | // True when `gate_idx` (directly or transitively via matching in-flight writes) depends on a gate on `target_queue`. | ||
| 179 | template <class MetFn> | ||
| 180 | inline bool gate_can_reach_queue(std::size_t gate_idx, const void* target_queue, | ||
| 181 | std::span<const PendingWriteGroup> writes, std::span<const PendingGate> gates, | ||
| 182 | MetFn&& met, std::vector<std::size_t>& visiting) { | ||
| 183 | const PendingGate& g = gates[gate_idx]; | ||
| 184 | if (g.queue == target_queue) return true; | ||
| 185 | if (g.is_action) return false; | ||
| 186 | if (std::find(visiting.begin(), visiting.end(), gate_idx) != visiting.end()) return false; | ||
| 187 | visiting.push_back(gate_idx); | ||
| 188 | for (const WaitPredicate& wait : g.unmet_waits) { | ||
| 189 | for (const PendingWriteGroup& w : writes) { | ||
| 190 | if (!write_group_matches_wait(w, wait, met)) continue; | ||
| 191 | if (!w.after_gate) continue; | ||
| 192 | for (std::size_t b = 0; b < gates.size(); ++b) { | ||
| 193 | if (gates[b].queue != w.queue || gates[b].value > w.after_gate) continue; | ||
| 194 | if (gates[b].queue == target_queue || | ||
| 195 | gate_can_reach_queue(b, target_queue, writes, gates, met, visiting)) { | ||
| 196 | visiting.pop_back(); | ||
| 197 | return true; | ||
| 198 | } | ||
| 199 | } | ||
| 200 | } | ||
| 201 | } | ||
| 202 | visiting.pop_back(); | ||
| 203 | return false; | ||
| 204 | } | ||
| 205 | |||
| 206 | } // namespace detail | ||
| 207 | |||
| 208 | // Decides whether the timeout clock of `gates[target_idx]` should pause on this pump pass. | ||
| 209 | // `met(comparison, value, reference, wide)` must implement the same predicate as `console_value_met`. | ||
| 210 | template <class MetFn> | ||
| 211 | inline PauseReason pause_reason(bool releaser_busy, std::span<const PendingWriteGroup> writes, | ||
| 212 | std::span<const PendingGate> gates, std::size_t target_idx, MetFn&& met) { | ||
| 213 | if (releaser_busy) return PauseReason::releaser_busy; | ||
| 214 | if (target_idx >= gates.size()) return PauseReason::none; | ||
| 215 | const PendingGate& target = gates[target_idx]; | ||
| 216 | if (target.is_action) return PauseReason::none; | ||
| 217 | |||
| 218 | // 1. A matching in-flight WriteGroup whose preceding gates (if any) do not cycle back to `target.queue`. | ||
| 219 | std::vector<std::size_t> visiting; | ||
| 220 | for (const WaitPredicate& wait : target.unmet_waits) { | ||
| 221 | for (const PendingWriteGroup& w : writes) { | ||
| 222 | if (!detail::write_group_matches_wait(w, wait, met)) continue; | ||
| 223 | bool cyclic = false; | ||
| 224 | if (w.after_gate) { | ||
| 225 | for (std::size_t b = 0; b < gates.size(); ++b) { | ||
| 226 | if (gates[b].queue != w.queue || gates[b].value > w.after_gate) continue; | ||
| 227 | visiting.clear(); | ||
| 228 | if (gates[b].queue == target.queue || | ||
| 229 | detail::gate_can_reach_queue(b, target.queue, writes, gates, met, visiting)) { | ||
| 230 | cyclic = true; | ||
| 231 | break; | ||
| 232 | } | ||
| 233 | } | ||
| 234 | } | ||
| 235 | if (!cyclic) return PauseReason::matching_producer; | ||
| 236 | } | ||
| 237 | } | ||
| 238 | |||
| 239 | // 2. Unrelated unblocked submitted GPU work (an unblocked WriteGroup on any queue, or an unblocked action gate on | ||
| 240 | // another queue) that could still write memory via a shader/copy or unblock a CPU producer. | ||
| 241 | for (const PendingWriteGroup& w : writes) { | ||
| 242 | if (detail::is_unblocked(gates, w.queue, w.after_gate)) return PauseReason::active_work; | ||
| 243 | } | ||
| 244 | for (const PendingGate& g : gates) { | ||
| 245 | if (!g.is_action || g.queue == target.queue) continue; | ||
| 246 | if (g.value == 0 || detail::is_unblocked(gates, g.queue, g.value - 1)) return PauseReason::active_work; | ||
| 247 | } | ||
| 248 | return PauseReason::none; | ||
| 249 | } | ||
| 250 | |||
| 251 | } // namespace leonida::list_value_wait | ||
diff --git a/runtime/src/title_geometry_watch.h b/runtime/src/title_geometry_watch.h index ca600fb9b..dfb0ae5b5 100644 --- a/runtime/src/title_geometry_watch.h +++ b/runtime/src/title_geometry_watch.h | |||
| @@ -1,6 +1,7 @@ | |||
| 1 | #pragma once | 1 | #pragma once |
| 2 | 2 | ||
| 3 | #include "title_page_watch.h" | 3 | #include "title_page_watch.h" |
| 4 | #include <algorithm> | ||
| 4 | #include <array> | 5 | #include <array> |
| 5 | #include <cstdint> | 6 | #include <cstdint> |
| 6 | #include <vector> | 7 | #include <vector> |
| @@ -72,7 +73,22 @@ inline void note_released(std::uintptr_t begin, std::uintptr_t end) { | |||
| 72 | std::lock_guard subscribers_lock(s.subscribers_mutex); | 73 | std::lock_guard subscribers_lock(s.subscribers_mutex); |
| 73 | for (ReleaseQueue* q : s.subscribers) { | 74 | for (ReleaseQueue* q : s.subscribers) { |
| 74 | std::lock_guard lock(q->mutex); | 75 | std::lock_guard lock(q->mutex); |
| 75 | if (q->ranges.size() < 65536) { | 76 | bool room = q->ranges.size() < 65536; |
| 77 | if (!room) { | ||
| 78 | // Full: first the ranges that overlap or touch become one (remaps report page runs, often neighbours), and | ||
| 79 | // only when that leaves it more than half full does it all become one covering range. | ||
| 80 | std::sort(q->ranges.begin(), q->ranges.end()); | ||
| 81 | std::size_t kept = 0; | ||
| 82 | for (std::size_t i = 1; i < q->ranges.size(); ++i) { | ||
| 83 | if (q->ranges[i].first <= q->ranges[kept].second) | ||
| 84 | q->ranges[kept].second = (std::max)(q->ranges[kept].second, q->ranges[i].second); | ||
| 85 | else | ||
| 86 | q->ranges[++kept] = q->ranges[i]; | ||
| 87 | } | ||
| 88 | q->ranges.resize(kept + 1); | ||
| 89 | room = q->ranges.size() <= 32768; | ||
| 90 | } | ||
| 91 | if (room) { | ||
| 76 | q->ranges.emplace_back(begin, end); | 92 | q->ranges.emplace_back(begin, end); |
| 77 | } else { | 93 | } else { |
| 78 | std::uintptr_t merged_lo = begin; | 94 | std::uintptr_t merged_lo = begin; |
diff --git a/runtime/src/title_texture_memory.h b/runtime/src/title_texture_memory.h index a97e5bed6..ff9f004e0 100644 --- a/runtime/src/title_texture_memory.h +++ b/runtime/src/title_texture_memory.h | |||
| @@ -1,14 +1,17 @@ | |||
| 1 | #pragma once | 1 | #pragma once |
| 2 | #include <windows.h> | 2 | #include <windows.h> |
| 3 | #include <algorithm> | ||
| 3 | #include <cstddef> | 4 | #include <cstddef> |
| 4 | #include <cstdint> | 5 | #include <cstdint> |
| 5 | #include <limits> | 6 | #include <limits> |
| 6 | 7 | ||
| 8 | #include "title_page_watch.h" | ||
| 9 | |||
| 7 | namespace leonida { | 10 | namespace leonida { |
| 8 | 11 | ||
| 9 | // Keep negative probes until the title changes the map or a writer reports this footprint. With cache_success, | 12 | // Keep negative probes until the title changes the map or a writer reports this footprint. With cache_success, |
| 10 | // positive ones too: a caller that is told of every map change over the footprint (retry) and reads it under a guard | 13 | // positive ones too: a caller that is told of every map change over the footprint (retry or sync_map) and reads it |
| 11 | // (a page gone since faults into a defer) need not walk the pages before every read. | 14 | // under a guard (a page gone since faults into a defer) need not walk the pages before every read. |
| 12 | class TextureReadability { | 15 | class TextureReadability { |
| 13 | public: | 16 | public: |
| 14 | template<class Probe> | 17 | template<class Probe> |
| @@ -16,16 +19,37 @@ public: | |||
| 16 | if (cache_failure && pending_ && !retry_ && generation_ == generation) return false; | 19 | if (cache_failure && pending_ && !retry_ && generation_ == generation) return false; |
| 17 | if (cache_success && probed_ && !pending_ && !retry_ && generation_ == generation) return true; | 20 | if (cache_success && probed_ && !pending_ && !retry_ && generation_ == generation) return true; |
| 18 | generation_ = generation; // snapshot before the probe so a concurrent map change is noticed | 21 | generation_ = generation; // snapshot before the probe so a concurrent map change is noticed |
| 22 | map_generation_ = title_memory_map::generation(); | ||
| 19 | retry_ = false; | 23 | retry_ = false; |
| 20 | probed_ = true; | 24 | probed_ = true; |
| 21 | pending_ = !probe(); | 25 | pending_ = !probe(); |
| 22 | return !pending_; | 26 | return !pending_; |
| 23 | } | 27 | } |
| 28 | // Between refresh passes, check whether the map journal recorded a change over [cpu, cpu + size) since both | ||
| 29 | // this texture's last probe and the last pass's sweep. | ||
| 30 | void sync_map(std::uint64_t pass_generation, std::uintptr_t cpu, std::uint64_t size) { | ||
| 31 | if (!probed_ || retry_) return; | ||
| 32 | const std::uint64_t since = (std::max)(map_generation_, pass_generation); | ||
| 33 | if (title_memory_map::generation() == since) return; | ||
| 34 | const std::uintptr_t end = size > (std::numeric_limits<std::uintptr_t>::max)() - cpu | ||
| 35 | ? (std::numeric_limits<std::uintptr_t>::max)() | ||
| 36 | : cpu + static_cast<std::uintptr_t>(size); | ||
| 37 | std::uint64_t now = 0; | ||
| 38 | bool overlapped = false; | ||
| 39 | if (!title_memory_map::changes_since( | ||
| 40 | since, now, cpu, end, [&](std::uintptr_t, std::uintptr_t) { overlapped = true; }) || | ||
| 41 | overlapped) { | ||
| 42 | retry_ = true; | ||
| 43 | } else { | ||
| 44 | map_generation_ = now; | ||
| 45 | } | ||
| 46 | } | ||
| 24 | void defer() { pending_ = true; } // mapping disappeared between the probe and the read | 47 | void defer() { pending_ = true; } // mapping disappeared between the probe and the read |
| 25 | void retry() { retry_ = true; } | 48 | void retry() { retry_ = true; } |
| 26 | bool pending() const { return pending_; } | 49 | bool pending() const { return pending_; } |
| 27 | private: | 50 | private: |
| 28 | std::uint64_t generation_ = 0; | 51 | std::uint64_t generation_ = 0; |
| 52 | std::uint64_t map_generation_ = 0; | ||
| 29 | bool pending_ = false, retry_ = false, probed_ = false; | 53 | bool pending_ = false, retry_ = false, probed_ = false; |
| 30 | }; | 54 | }; |
| 31 | 55 | ||
diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index f3fd2b410..66a7f5894 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h | |||
| @@ -45,6 +45,9 @@ public: | |||
| 45 | // memory (an arena VA, a buffer of the layer's). | 45 | // memory (an arena VA, a buffer of the layer's). |
| 46 | using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); | 46 | using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); |
| 47 | using TableScanner = void (*)(void* context, std::uint64_t table_va, std::uint32_t descriptors); | 47 | using TableScanner = void (*)(void* context, std::uint64_t table_va, std::uint32_t descriptors); |
| 48 | // Every binding resolved to a copy of the title's memory: [va, va + bytes) as they are reached at (the device keeps | ||
| 49 | // them for the copy back after the submission, see DeviceState::write_back_titles). | ||
| 50 | using Noter = void (*)(void* context, std::uint64_t va, std::uint64_t bytes); | ||
| 48 | 51 | ||
| 49 | // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one | 52 | // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one |
| 50 | // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. | 53 | // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. |
| @@ -180,6 +183,7 @@ public: | |||
| 180 | std::uint64_t to = shader_va(va); | 183 | std::uint64_t to = shader_va(va); |
| 181 | if (to != va) { | 184 | if (to != va) { |
| 182 | translated_[kind].fetch_add(1, std::memory_order_relaxed); | 185 | translated_[kind].fetch_add(1, std::memory_order_relaxed); |
| 186 | note_reached(va, bytes); | ||
| 183 | return to; | 187 | return to; |
| 184 | } | 188 | } |
| 185 | Resolver resolver; | 189 | Resolver resolver; |
| @@ -191,6 +195,7 @@ public: | |||
| 191 | } | 195 | } |
| 192 | if (!resolver || !resolver(context, va, bytes, to)) return va; | 196 | if (!resolver || !resolver(context, va, bytes, to)) return va; |
| 193 | (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed); | 197 | (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed); |
| 198 | if (to != va) note_reached(va, bytes); | ||
| 194 | return to; | 199 | return to; |
| 195 | } | 200 | } |
| 196 | 201 | ||
| @@ -200,6 +205,18 @@ public: | |||
| 200 | if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); | 205 | if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); |
| 201 | } | 206 | } |
| 202 | 207 | ||
| 208 | // [va, va + bytes) is reached as a copy of the title's memory: the device keeps it for the copy back. | ||
| 209 | void note_reached(std::uint64_t va, std::uint64_t bytes) { | ||
| 210 | Noter noter; | ||
| 211 | void* context; | ||
| 212 | { | ||
| 213 | std::lock_guard lock(hook_mutex_); | ||
| 214 | noter = noter_; | ||
| 215 | context = hook_context_; | ||
| 216 | } | ||
| 217 | if (noter) noter(context, va, bytes); | ||
| 218 | } | ||
| 219 | |||
| 203 | // Before a submission: the device rewrites the buffer V#s of the `descriptors` slots the root signature declares | 220 | // Before a submission: the device rewrites the buffer V#s of the `descriptors` slots the root signature declares |
| 204 | // for the table at `table_va` (a console VA in one of its shader-visible CBV/SRV/UAV heaps). | 221 | // for the table at `table_va` (a console VA in one of its shader-visible CBV/SRV/UAV heaps). |
| 205 | void scan_table(std::uint64_t table_va, std::uint32_t descriptors) { | 222 | void scan_table(std::uint64_t table_va, std::uint32_t descriptors) { |
| @@ -344,10 +361,16 @@ public: | |||
| 344 | hook_context_ = nullptr; | 361 | hook_context_ = nullptr; |
| 345 | resolver_ = nullptr; | 362 | resolver_ = nullptr; |
| 346 | scanner_ = nullptr; | 363 | scanner_ = nullptr; |
| 364 | noter_ = nullptr; | ||
| 347 | } | 365 | } |
| 348 | // The resolver alone, for a device that scans its descriptor tables itself. | 366 | // The resolver alone, for a device that scans its descriptor tables itself. |
| 349 | void set_resolver(void* context, Resolver resolver) { set_hooks(context, resolver, nullptr); } | 367 | void set_resolver(void* context, Resolver resolver) { set_hooks(context, resolver, nullptr); } |
| 350 | void clear_resolver(void* context) { clear_hooks(context); } | 368 | void clear_resolver(void* context) { clear_hooks(context); } |
| 369 | // Set after set_hooks, so the hook (and its context) stays the device's: what reached a copy of the title's memory. | ||
| 370 | void set_noter(Noter noter) { | ||
| 371 | std::lock_guard lock(hook_mutex_); | ||
| 372 | noter_ = noter; | ||
| 373 | } | ||
| 351 | 374 | ||
| 352 | std::size_t size() const { return count_.load(std::memory_order_acquire); } | 375 | std::size_t size() const { return count_.load(std::memory_order_acquire); } |
| 353 | std::uint64_t invalidations() const { return invalidations_.load(std::memory_order_acquire); } | 376 | std::uint64_t invalidations() const { return invalidations_.load(std::memory_order_acquire); } |
| @@ -424,6 +447,7 @@ private: | |||
| 424 | BufferMaker maker_ = nullptr; | 447 | BufferMaker maker_ = nullptr; |
| 425 | Resolver resolver_ = nullptr; | 448 | Resolver resolver_ = nullptr; |
| 426 | TableScanner scanner_ = nullptr; | 449 | TableScanner scanner_ = nullptr; |
| 450 | Noter noter_ = nullptr; | ||
| 427 | void* source_context_ = nullptr; | 451 | void* source_context_ = nullptr; |
| 428 | DescriptorSource source_ = nullptr; | 452 | DescriptorSource source_ = nullptr; |
| 429 | std::atomic<std::uint64_t> pulled_{0}; | 453 | std::atomic<std::uint64_t> pulled_{0}; |
diff --git a/runtime/test/address_guard_test.cpp b/runtime/test/address_guard_test.cpp new file mode 100644 index 000000000..02baa7bb8 --- /dev/null +++ b/runtime/test/address_guard_test.cpp | |||
| @@ -0,0 +1,127 @@ | |||
| 1 | // leonida::address_guard::AddressGuardTable (src/address_guard.h): the address guard's page table. Pages any byte | ||
| 2 | // of a span touches are backed, a chunk keeps its level-2 block for good, a released span's bits go, negative | ||
| 3 | // offsets (a buffer below the arena) and spans across 4 GiB chunks work, only changed words are written, level-2 | ||
| 4 | // before level-1, and a chunk past the table's room gets the full block. No GPU, no device. | ||
| 5 | #include "../src/address_guard.h" | ||
| 6 | |||
| 7 | #include <cstdint> | ||
| 8 | #include <cstdio> | ||
| 9 | #include <utility> | ||
| 10 | #include <vector> | ||
| 11 | |||
| 12 | #define EXPECT(condition) do { \ | ||
| 13 | if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ | ||
| 14 | } while (0) | ||
| 15 | |||
| 16 | namespace { | ||
| 17 | |||
| 18 | using leonida::address_guard::AddressGuardTable; | ||
| 19 | using Spans = std::vector<std::pair<std::uint64_t, std::uint64_t>>; | ||
| 20 | namespace ag = leonida::address_guard; | ||
| 21 | |||
| 22 | constexpr std::uint64_t kLimit = 0x80000; // the "arena" | ||
| 23 | constexpr std::uint64_t kGiB = 1ull << 30; | ||
| 24 | |||
| 25 | // A copy of the GPU's table, written only through assign()'s callback, and the order of the writes. | ||
| 26 | struct Gpu { | ||
| 27 | std::vector<std::uint32_t> words; | ||
| 28 | std::vector<std::size_t> order; | ||
| 29 | explicit Gpu(const AddressGuardTable& t) : words(t.words()) {} | ||
| 30 | auto writer() { | ||
| 31 | return [this](std::size_t i, std::uint32_t v) { | ||
| 32 | words[i] = v; | ||
| 33 | order.push_back(i); | ||
| 34 | }; | ||
| 35 | } | ||
| 36 | }; | ||
| 37 | |||
| 38 | int basics() { | ||
| 39 | AddressGuardTable t(4); | ||
| 40 | Gpu gpu(t); | ||
| 41 | EXPECT(t.word_count() == ag::kGuardLevel1 + 6u * ag::kGuardBlockWords); | ||
| 42 | EXPECT(!t.passes(0x90000, 4, kLimit)); | ||
| 43 | EXPECT(t.passes(0x7fffc, 4, kLimit)); // below the limit: no lookup | ||
| 44 | EXPECT(!t.passes(0x7fffc, 8, kLimit)); // its last byte is past it, on an unbacked page | ||
| 45 | |||
| 46 | const Spans spans{{0x90000, 0x90001}, {5 * 4 * kGiB + 0x1000, 5 * 4 * kGiB + 0x3000}}; | ||
| 47 | const std::size_t written = t.assign(spans, gpu.writer()); | ||
| 48 | EXPECT(written > 0); | ||
| 49 | EXPECT(gpu.words == t.words()); | ||
| 50 | EXPECT(t.blocks_used() == 2); | ||
| 51 | EXPECT(t.passes(0x90000, 4, kLimit)); | ||
| 52 | EXPECT(t.passes(0x90ffc, 4, kLimit)); // one byte of the span marks the whole page | ||
| 53 | EXPECT(!t.passes(0x90ffc, 8, kLimit)); // the last byte is on the next page | ||
| 54 | EXPECT(t.passes(5 * 4 * kGiB + 0x2ff0, 16, kLimit)); | ||
| 55 | EXPECT(!t.passes(5 * 4 * kGiB + 0x3000, 4, kLimit)); | ||
| 56 | EXPECT(!t.passes(6 * 4 * kGiB, 4, kLimit)); | ||
| 57 | |||
| 58 | // Level-2 words are written before level-1 ones. | ||
| 59 | bool seen_level1 = false; | ||
| 60 | for (const std::size_t i : gpu.order) { | ||
| 61 | if (i < ag::kGuardLevel1) seen_level1 = true; | ||
| 62 | else EXPECT(!seen_level1); | ||
| 63 | } | ||
| 64 | |||
| 65 | // The same spans again: nothing to write. | ||
| 66 | gpu.order.clear(); | ||
| 67 | EXPECT(t.assign(spans, gpu.writer()) == 0); | ||
| 68 | |||
| 69 | // A release: its bits go, its chunk keeps its block. | ||
| 70 | const std::uint32_t chunk5 = t.words()[5]; | ||
| 71 | EXPECT(chunk5 >= ag::kFirstBlock); | ||
| 72 | EXPECT(t.assign(Spans{{0x90000, 0x91000}}, gpu.writer()) > 0); | ||
| 73 | EXPECT(gpu.words == t.words()); | ||
| 74 | EXPECT(!t.passes(5 * 4 * kGiB + 0x2ff0, 4, kLimit)); | ||
| 75 | EXPECT(t.words()[5] == chunk5); | ||
| 76 | EXPECT(t.passes(0x90000, 4, kLimit)); | ||
| 77 | return 0; | ||
| 78 | } | ||
| 79 | |||
| 80 | int negative_and_wide() { | ||
| 81 | AddressGuardTable t(4); | ||
| 82 | Gpu gpu(t); | ||
| 83 | // A buffer 8 KiB below heap_base (LEONIDA_IMPORT_BELOW_ARENA=1), as the 48-bit offset a V# holds. | ||
| 84 | const std::uint64_t below = (0ull - 0x2000) & ag::kMask48; | ||
| 85 | // One that runs from below heap_base into the arena's first page: wraps through 2^48. | ||
| 86 | const std::uint64_t wrap = (0ull - 0x1000) & ag::kMask48; | ||
| 87 | // A 6 GiB buffer across two chunks: whole words of bits. | ||
| 88 | const std::uint64_t wide = 8 * kGiB + 0x10000; | ||
| 89 | t.assign(Spans{{below, below + 0x1000}, {wrap, 0x1000}, {wide, wide + 6 * kGiB}}, gpu.writer()); | ||
| 90 | EXPECT(gpu.words == t.words()); | ||
| 91 | EXPECT(t.passes(below, 4, kLimit)); | ||
| 92 | EXPECT(t.passes(0ull - 0x2000, 4, kLimit)); // the same offset sign-extended, as the shaders pass it | ||
| 93 | EXPECT(t.passes(0ull - 4, 8, kLimit)); // across zero: both pages backed | ||
| 94 | EXPECT(!t.passes(0ull - 0x3000, 4, kLimit)); | ||
| 95 | EXPECT(t.passes(wide, 4, kLimit)); | ||
| 96 | EXPECT(t.passes(wide + 4 * kGiB, 4, kLimit)); | ||
| 97 | EXPECT(t.passes(wide + 6 * kGiB - 4, 4, kLimit)); | ||
| 98 | EXPECT(!t.passes(wide + 6 * kGiB, 4, kLimit)); | ||
| 99 | EXPECT(!t.passes(wide - 4, 8, kLimit)); | ||
| 100 | EXPECT(t.blocks_used() == 4); // chunks 0xffff, 0 (the wrap), 2 and 3 | ||
| 101 | return 0; | ||
| 102 | } | ||
| 103 | |||
| 104 | int out_of_room() { | ||
| 105 | AddressGuardTable t(1); | ||
| 106 | Gpu gpu(t); | ||
| 107 | t.assign(Spans{{4 * kGiB, 4 * kGiB + 1}, {8 * kGiB, 8 * kGiB + 1}}, gpu.writer()); | ||
| 108 | EXPECT(t.blocks_used() == 1); | ||
| 109 | EXPECT(t.overflowed() == 1); | ||
| 110 | EXPECT(t.passes(4 * kGiB, 4, kLimit)); | ||
| 111 | EXPECT(!t.passes(4 * kGiB + 0x1000, 4, kLimit)); | ||
| 112 | EXPECT(t.passes(8 * kGiB + 0x5000, 4, kLimit)); // the full block: all of that chunk passes | ||
| 113 | EXPECT(t.words()[2] == ag::kFullBlock); | ||
| 114 | return 0; | ||
| 115 | } | ||
| 116 | |||
| 117 | } // namespace | ||
| 118 | |||
| 119 | int main() { | ||
| 120 | // "LGUARD01" little-endian, as tools/address_guard.py packs it and the shaders compare it. | ||
| 121 | static_assert(ag::magic() == 0x313044524155474Cull); | ||
| 122 | if (int r = basics()) return r; | ||
| 123 | if (int r = negative_and_wide()) return r; | ||
| 124 | if (int r = out_of_room()) return r; | ||
| 125 | std::puts("address_guard_test: ok"); | ||
| 126 | return 0; | ||
| 127 | } | ||
diff --git a/runtime/test/conservative_raster_test.cpp b/runtime/test/conservative_raster_test.cpp index b862e5fcb..72ee4d516 100644 --- a/runtime/test/conservative_raster_test.cpp +++ b/runtime/test/conservative_raster_test.cpp | |||
| @@ -1,6 +1,7 @@ | |||
| 1 | #include "../src/conservative_raster.h" | 1 | #include "../src/conservative_raster.h" |
| 2 | #include <cstdio> | 2 | #include <cstdio> |
| 3 | #include <limits> | 3 | #include <limits> |
| 4 | #include <vector> | ||
| 4 | 5 | ||
| 5 | int main() { | 6 | int main() { |
| 6 | using leonida::conservative_raster::tier1; | 7 | using leonida::conservative_raster::tier1; |
| @@ -38,6 +39,18 @@ int main() { | |||
| 38 | const auto requirements = inner_coverage_requirements(module); | 39 | const auto requirements = inner_coverage_requirements(module); |
| 39 | check(requirements.valid && requirements.fully_covered && requirements.post_depth); | 40 | check(requirements.valid && requirements.fully_covered && requirements.post_depth); |
| 40 | check(!inner_coverage_requirements(std::span(module).first(9)).valid); | 41 | check(!inner_coverage_requirements(std::span(module).first(9)).valid); |
| 42 | using leonida::conservative_raster::mesh_outputs_triangles; | ||
| 43 | const auto with_mode = [](std::uint32_t mode) { | ||
| 44 | return std::vector<std::uint32_t>{0x07230203, 0x00010500, 0, 2, 0, (3u << 16) | 16, 1, mode}; | ||
| 45 | }; | ||
| 46 | check(mesh_outputs_triangles(with_mode(5298))); // OutputTrianglesEXT | ||
| 47 | check(!mesh_outputs_triangles(with_mode(5269))); // OutputLinesEXT | ||
| 48 | check(!mesh_outputs_triangles(with_mode(27))); // OutputPoints | ||
| 49 | check(!mesh_outputs_triangles(with_mode(26))); // OutputVertices: no output topology | ||
| 50 | check(!mesh_outputs_triangles({})); | ||
| 51 | auto truncated = with_mode(5298); | ||
| 52 | truncated.pop_back(); | ||
| 53 | check(!mesh_outputs_triangles(truncated)); | ||
| 41 | const std::uint32_t zero_count[] = {0x07230203, 0x00010500, 0, 2, 0, 0}; | 54 | const std::uint32_t zero_count[] = {0x07230203, 0x00010500, 0, 2, 0, 0}; |
| 42 | check(!inner_coverage_requirements(zero_count).valid); | 55 | check(!inner_coverage_requirements(zero_count).valid); |
| 43 | const std::uint32_t ordinary[] = {0x07230203, 0x00010500, 0, 2, 0, (2u << 16) | 17, 1}; | 56 | const std::uint32_t ordinary[] = {0x07230203, 0x00010500, 0, 2, 0, (2u << 16) | 17, 1}; |
diff --git a/runtime/test/console_heap_copy_test.cpp b/runtime/test/console_heap_copy_test.cpp new file mode 100644 index 000000000..48618170e --- /dev/null +++ b/runtime/test/console_heap_copy_test.cpp | |||
| @@ -0,0 +1,168 @@ | |||
| 1 | // Portable CPU-only unit test for leonida::ConsoleHeapCopy (runtime/src/console_heap_copy.h): the host-RAM mirror of a | ||
| 2 | // console heap's translated copy. A plain buffer stands in for the copy in the GPU address arena. Checks that every | ||
| 3 | // write and zero reaches both, that the null guard past the heap stays out of the mirror, that mismatches() finds a | ||
| 4 | // write that bypassed the helpers (the LEONIDA_HEAP_MIRROR_CHECK case), and that without a mirror view() is the copy. | ||
| 5 | // Then times a filtered release sweep over a large heap reading the mirror (the work refresh_console_heap does per | ||
| 6 | // rescan with LEONIDA_CONSOLE_RELEASE_FILTER=1), for reference; no game data. | ||
| 7 | #include "../src/console_heap_copy.h" | ||
| 8 | #include "../src/console_heap_vsharp_slots.h" | ||
| 9 | #include "../src/descriptor_range_changes.h" | ||
| 10 | |||
| 11 | #include <chrono> | ||
| 12 | #include <cstdint> | ||
| 13 | #include <cstdio> | ||
| 14 | #include <cstring> | ||
| 15 | #include <vector> | ||
| 16 | |||
| 17 | #define EXPECT(condition) \ | ||
| 18 | do { \ | ||
| 19 | if (!(condition)) { \ | ||
| 20 | std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); \ | ||
| 21 | return 1; \ | ||
| 22 | } \ | ||
| 23 | } while (0) | ||
| 24 | |||
| 25 | namespace { | ||
| 26 | |||
| 27 | using leonida::ConsoleHeapCopy; | ||
| 28 | constexpr std::size_t kSlot = 32; | ||
| 29 | |||
| 30 | int test_writes_reach_both() { | ||
| 31 | constexpr std::size_t slots = 256, bytes = slots * kSlot, guard = 4096; | ||
| 32 | std::vector<std::uint8_t> gpu(bytes + guard, 0xCD); | ||
| 33 | ConsoleHeapCopy copy; | ||
| 34 | EXPECT(!copy); | ||
| 35 | copy.attach(gpu.data(), bytes, true); | ||
| 36 | EXPECT(copy && copy.mirrored() && copy.gpu() == gpu.data() && copy.bytes() == bytes); | ||
| 37 | EXPECT(copy.view() != gpu.data()); | ||
| 38 | // Creation: the copy and its guard zeroed; the mirror covers the heap only. | ||
| 39 | copy.zero(0, bytes + guard); | ||
| 40 | for (const auto b : gpu) EXPECT(b == 0); | ||
| 41 | std::vector<std::size_t> differ; | ||
| 42 | EXPECT(copy.mismatches(kSlot, 8, differ) == 0 && differ.empty()); | ||
| 43 | |||
| 44 | std::uint32_t w[8] = {0x1000, 0x20, 64, 0x3fffu, 0, 0, 0, 0}; | ||
| 45 | for (std::size_t s = 0; s < slots; s += 3) { | ||
| 46 | w[0] = std::uint32_t(0x1000 + s * 0x40); | ||
| 47 | copy.write(s * kSlot, w, sizeof(w)); | ||
| 48 | } | ||
| 49 | copy.zero(9 * kSlot, kSlot); | ||
| 50 | copy.zero(64 * kSlot, 32 * kSlot); // a zeroed range of slots | ||
| 51 | // A sampler heap's whole range copied at once. | ||
| 52 | std::vector<std::uint8_t> run(5 * kSlot + 7, 0x5A); | ||
| 53 | copy.write(200 * kSlot + 3, run.data(), run.size()); | ||
| 54 | EXPECT(std::memcmp(copy.view(), gpu.data(), bytes) == 0); | ||
| 55 | EXPECT(copy.mismatches(kSlot, 8, differ) == 0); | ||
| 56 | // Past the heap: the copy's guard only, nothing out of the mirror's bounds. | ||
| 57 | copy.zero(bytes - kSlot, kSlot + guard); | ||
| 58 | std::uint32_t tail[8]; | ||
| 59 | std::memcpy(tail, copy.view() + bytes - kSlot, sizeof(tail)); | ||
| 60 | for (const auto t : tail) EXPECT(t == 0); | ||
| 61 | EXPECT(copy.mismatches(kSlot, 8, differ) == 0); | ||
| 62 | std::puts("writes and zeros reach the copy and the mirror; the guard stays out of the mirror"); | ||
| 63 | return 0; | ||
| 64 | } | ||
| 65 | |||
| 66 | int test_mismatch_found() { | ||
| 67 | constexpr std::size_t slots = 8192, bytes = slots * kSlot; // 256 KiB: more than one compare block | ||
| 68 | std::vector<std::uint8_t> gpu(bytes, 0); | ||
| 69 | ConsoleHeapCopy copy; | ||
| 70 | copy.attach(gpu.data(), bytes, true); | ||
| 71 | // Writes that bypass the helpers (a missed write site, or the GPU writing the copy). | ||
| 72 | gpu[5 * kSlot + 4] = 1; | ||
| 73 | gpu[4000 * kSlot] = 2; | ||
| 74 | gpu[4001 * kSlot + 31] = 3; | ||
| 75 | gpu[8191 * kSlot + 16] = 4; | ||
| 76 | std::vector<std::size_t> differ; | ||
| 77 | EXPECT(copy.mismatches(kSlot, 3, differ) == 4); | ||
| 78 | EXPECT(differ.size() == 3 && differ[0] == 5 && differ[1] == 4000 && differ[2] == 4001); | ||
| 79 | EXPECT(copy.mismatches(kSlot, 8, differ) == 4 && differ.size() == 4 && differ[3] == 8191); | ||
| 80 | std::puts("mismatches() finds writes that bypassed the mirror, in slot order"); | ||
| 81 | return 0; | ||
| 82 | } | ||
| 83 | |||
| 84 | int test_without_mirror() { | ||
| 85 | constexpr std::size_t bytes = 64 * kSlot; | ||
| 86 | std::vector<std::uint8_t> gpu(bytes, 0); | ||
| 87 | ConsoleHeapCopy copy; | ||
| 88 | copy.attach(gpu.data(), bytes, false); // the copy is host RAM already | ||
| 89 | EXPECT(!copy.mirrored() && copy.view() == gpu.data()); | ||
| 90 | const std::uint32_t w[8] = {1, 2, 3, 4, 5, 6, 7, 8}; | ||
| 91 | copy.write(3 * kSlot, w, sizeof(w)); | ||
| 92 | EXPECT(!std::memcmp(gpu.data() + 3 * kSlot, w, sizeof(w))); | ||
| 93 | std::vector<std::size_t> differ; | ||
| 94 | EXPECT(copy.mismatches(kSlot, 8, differ) == 0); | ||
| 95 | |||
| 96 | copy.attach(gpu.data(), bytes, true); | ||
| 97 | EXPECT(copy.mirrored()); | ||
| 98 | copy.drop_mirror(); // the GPU pass writes the copy from now on | ||
| 99 | EXPECT(!copy.mirrored() && copy.view() == gpu.data()); | ||
| 100 | std::puts("without a mirror view() is the copy"); | ||
| 101 | return 0; | ||
| 102 | } | ||
| 103 | |||
| 104 | // The filtered release sweep of refresh_console_heap over a heap of 576k slots (18 MiB) with 470k live V# slots, one | ||
| 105 | // released range touching about 2%: the time per sweep with its words read from host RAM. | ||
| 106 | int bench_filtered_sweep() { | ||
| 107 | constexpr std::size_t slots = 576 * 1024, bytes = slots * kSlot; | ||
| 108 | std::vector<std::uint8_t> previous(bytes, 0), gpu(bytes, 0); | ||
| 109 | ConsoleHeapCopy copy; | ||
| 110 | copy.attach(gpu.data(), bytes, true); | ||
| 111 | leonida::ConsoleHeapVsharpSlots live; | ||
| 112 | live.reset(slots); | ||
| 113 | constexpr std::uint64_t kBuffers = 4096, kBufferBytes = 1 << 20, kArena = 1ull << 32; | ||
| 114 | for (std::size_t s = 0; s < slots; ++s) { | ||
| 115 | if (s % 11 == 10) continue; // T#s and empty slots | ||
| 116 | const std::uint64_t base = 0x100000 + (s * 2654435761u % kBuffers) * kBufferBytes + (s % 64) * 256; | ||
| 117 | std::uint32_t w[8] = {std::uint32_t(base), std::uint32_t(base >> 32) & 0xffffu, 256, 0x00027fac, 0, 0, 0, 0}; | ||
| 118 | std::memcpy(previous.data() + s * kSlot, w, sizeof(w)); | ||
| 119 | copy.write(s * kSlot, w, sizeof(w)); | ||
| 120 | live.set(s, leonida::ConsoleHeapVsharpSlots::is_live_vsharp(w)); | ||
| 121 | } | ||
| 122 | leonida::DescriptorRanges backing, aliases; | ||
| 123 | for (std::uint64_t b = 0; b < kBuffers; b += 50) // about 2% of the buffers released | ||
| 124 | backing.ranges.push_back({kArena + 0x100000 + b * kBufferBytes, kArena + 0x100000 + (b + 1) * kBufferBytes - 1}); | ||
| 125 | backing.merge(); | ||
| 126 | const auto bda = [&](std::uint64_t base) { return kArena + base; }; | ||
| 127 | const auto affected = [&](const std::uint32_t* src, const std::uint32_t* dst) { | ||
| 128 | if ((src[3] >> 30) || !src[2]) return false; | ||
| 129 | const std::uint64_t base = std::uint64_t(src[0]) | (std::uint64_t(src[1] & 0xffff) << 32); | ||
| 130 | const std::uint64_t fixed = std::uint64_t(dst[0]) | (std::uint64_t(dst[1] & 0xffff) << 32); | ||
| 131 | const auto stride = (src[1] >> 16) & 0x3fff; | ||
| 132 | const std::uint64_t n = std::uint64_t(src[2]) * (stride ? stride : 1); | ||
| 133 | return aliases.overlaps(base, 1) || backing.overlaps(bda(base), n) || (dst[2] && backing.overlaps(bda(fixed), n)); | ||
| 134 | }; | ||
| 135 | constexpr int kRuns = 9; | ||
| 136 | double best = 1e30, first = 0; | ||
| 137 | std::size_t hits = 0; | ||
| 138 | for (int run = 0; run < kRuns; ++run) { | ||
| 139 | hits = 0; | ||
| 140 | const auto start = std::chrono::steady_clock::now(); | ||
| 141 | const std::uint8_t* const translated = copy.view(); | ||
| 142 | live.for_each([&](std::size_t slot) { | ||
| 143 | const auto at = slot * kSlot; | ||
| 144 | const auto* src = reinterpret_cast<const std::uint32_t*>(previous.data() + at); | ||
| 145 | const auto* dst = reinterpret_cast<const std::uint32_t*>(translated + at); | ||
| 146 | if (affected(src, dst) || affected(src + 4, dst + 4)) ++hits; | ||
| 147 | }); | ||
| 148 | const double took = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count(); | ||
| 149 | if (!run) first = took; | ||
| 150 | best = std::min(best, took); | ||
| 151 | } | ||
| 152 | EXPECT(hits > 0 && hits < live.live_count() / 10); | ||
| 153 | std::printf("filtered sweep over %zu live slots of %zu MiB, %zu affected: %.2f ms (best of %d, first %.2f), words " | ||
| 154 | "from the host mirror\n", | ||
| 155 | live.live_count(), bytes >> 20, hits, best, kRuns, first); | ||
| 156 | return 0; | ||
| 157 | } | ||
| 158 | |||
| 159 | } // namespace | ||
| 160 | |||
| 161 | int main() { | ||
| 162 | if (test_writes_reach_both()) return 1; | ||
| 163 | if (test_mismatch_found()) return 1; | ||
| 164 | if (test_without_mirror()) return 1; | ||
| 165 | if (bench_filtered_sweep()) return 1; | ||
| 166 | std::puts("ok"); | ||
| 167 | return 0; | ||
| 168 | } | ||
diff --git a/runtime/test/console_heap_vsharp_slots_test.cpp b/runtime/test/console_heap_vsharp_slots_test.cpp index ebb74be45..aa56b4fdd 100644 --- a/runtime/test/console_heap_vsharp_slots_test.cpp +++ b/runtime/test/console_heap_vsharp_slots_test.cpp | |||
| @@ -246,6 +246,80 @@ int test_retail_sized_heap_sparse_scan() { | |||
| 246 | return 0; | 246 | return 0; |
| 247 | } | 247 | } |
| 248 | 248 | ||
| 249 | int test_console_fix_budget_buffer_vsharp_non_deferral() { | ||
| 250 | // Verifies that under fix_console_slots budget expiry (fix_over == true), buffer V# descriptors | ||
| 251 | // (!(w[3] >> 30)) are never deferred/nulled, while image T# descriptors ((w[3] >> 30) != 0) are deferred. | ||
| 252 | constexpr std::size_t kSlots = 16; | ||
| 253 | std::vector<std::array<std::uint32_t, 8>> gpu_copy(kSlots); | ||
| 254 | for (auto& slot : gpu_copy) slot.fill(0); | ||
| 255 | |||
| 256 | ConsoleHeapVsharpSlots tracked; | ||
| 257 | tracked.reset(kSlots); | ||
| 258 | |||
| 259 | // Populate slots with alternating buffer V# and image T# descriptors: | ||
| 260 | // Even slots: live buffer V#s | ||
| 261 | // Odd slots: image T#s | ||
| 262 | for (std::size_t i = 0; i < kSlots; ++i) { | ||
| 263 | std::array<std::uint32_t, 8> w{}; | ||
| 264 | if ((i & 1u) == 0) { | ||
| 265 | // Buffer V#: w[3] >> 30 == 0, num_records != 0 | ||
| 266 | w[0] = static_cast<std::uint32_t>(0x1000 + i * 0x100); | ||
| 267 | w[1] = 0x20; | ||
| 268 | w[2] = 256; | ||
| 269 | w[3] = 0x00010000u; // w[3] >> 30 == 0 | ||
| 270 | } else { | ||
| 271 | // Image T#: w[3] >> 30 != 0 | ||
| 272 | w[0] = static_cast<std::uint32_t>(0x5000 + i * 0x100); | ||
| 273 | w[2] = 128; | ||
| 274 | w[3] = (2u << 30) | 0x1234u; // w[3] >> 30 == 2 | ||
| 275 | } | ||
| 276 | gpu_copy[i] = w; | ||
| 277 | tracked.set(i, ConsoleHeapVsharpSlots::is_live_vsharp(w.data())); | ||
| 278 | } | ||
| 279 | |||
| 280 | // Now simulate fix_console_slots when budget is expired (fix_over == true): | ||
| 281 | // Buffer V#s must be fixed in-place and never nulled/deferred; only image T#s are deferred. | ||
| 282 | std::size_t deferred_fixes = 0; | ||
| 283 | std::vector<std::uint32_t> retries; | ||
| 284 | const bool fix_over = true; | ||
| 285 | |||
| 286 | for (std::size_t slot = 0; slot < kSlots; ++slot) { | ||
| 287 | const std::array<std::uint32_t, 8>& input = gpu_copy[slot]; | ||
| 288 | const std::uint32_t w3 = input[3]; | ||
| 289 | const bool is_buffer_vsharp = !(w3 >> 30); | ||
| 290 | |||
| 291 | if (fix_over && !is_buffer_vsharp) { | ||
| 292 | // Image T#: deferred past budget | ||
| 293 | gpu_copy[slot].fill(0); | ||
| 294 | tracked.clear(slot); | ||
| 295 | ++deferred_fixes; | ||
| 296 | retries.push_back(static_cast<std::uint32_t>(slot)); | ||
| 297 | continue; | ||
| 298 | } | ||
| 299 | |||
| 300 | // Buffer V#: fixed immediately, not deferred | ||
| 301 | tracked.set(slot, ConsoleHeapVsharpSlots::is_live_vsharp(input.data())); | ||
| 302 | } | ||
| 303 | |||
| 304 | // All odd slots (image T#s) must have been deferred (nulled) | ||
| 305 | EXPECT(deferred_fixes == kSlots / 2); | ||
| 306 | EXPECT(retries.size() == kSlots / 2); | ||
| 307 | for (std::size_t slot : retries) { | ||
| 308 | EXPECT((slot & 1u) == 1u); | ||
| 309 | EXPECT(!tracked.test(slot)); | ||
| 310 | EXPECT(gpu_copy[slot][0] == 0 && gpu_copy[slot][2] == 0); | ||
| 311 | } | ||
| 312 | |||
| 313 | // All even slots (buffer V#s) must have been preserved and remain live | ||
| 314 | for (std::size_t i = 0; i < kSlots; i += 2) { | ||
| 315 | EXPECT(tracked.test(i)); | ||
| 316 | EXPECT(gpu_copy[i][2] == 256); | ||
| 317 | EXPECT(ConsoleHeapVsharpSlots::is_live_vsharp(gpu_copy[i].data())); | ||
| 318 | } | ||
| 319 | EXPECT(tracked.live_count() == kSlots / 2); | ||
| 320 | return 0; | ||
| 321 | } | ||
| 322 | |||
| 249 | } // namespace | 323 | } // namespace |
| 250 | 324 | ||
| 251 | int main() { | 325 | int main() { |
| @@ -254,6 +328,7 @@ int main() { | |||
| 254 | if (test_in_place_invalidation_mutation()) return 1; | 328 | if (test_in_place_invalidation_mutation()) return 1; |
| 255 | if (test_differential_equivalence_against_linear_copy()) return 1; | 329 | if (test_differential_equivalence_against_linear_copy()) return 1; |
| 256 | if (test_retail_sized_heap_sparse_scan()) return 1; | 330 | if (test_retail_sized_heap_sparse_scan()) return 1; |
| 331 | if (test_console_fix_budget_buffer_vsharp_non_deferral()) return 1; | ||
| 257 | std::printf("console_heap_vsharp_slots_test: ok\n"); | 332 | std::printf("console_heap_vsharp_slots_test: ok\n"); |
| 258 | return 0; | 333 | return 0; |
| 259 | } | 334 | } |
diff --git a/runtime/test/d3d12_console_heap_mirror_test.cpp b/runtime/test/d3d12_console_heap_mirror_test.cpp new file mode 100644 index 000000000..9a1319bb3 --- /dev/null +++ b/runtime/test/d3d12_console_heap_mirror_test.cpp | |||
| @@ -0,0 +1,215 @@ | |||
| 1 | // The host-RAM mirror of a console descriptor heap's GPU copy (src/console_heap_copy.h) through a heap's life, with | ||
| 2 | // LEONIDA_CONSOLE_RELEASE_FILTER=1 (the release sweep reads the mirror to pick the slots to fix): the first refresh, | ||
| 3 | // slots the title rewrites and zeroes after it, and a released buffer whose V#s the sweep must find and null. After | ||
| 4 | // each step the GPU copy holds what it should and the mirror agrees with it byte for byte. Run twice by ctest: with | ||
| 5 | // the mirror, and with LEONIDA_HEAP_MIRROR=0 (no mirror; the sweep reads the copy, as before it), where the copy must | ||
| 6 | // come out the same. Nothing dispatches through a descriptor. No game data. | ||
| 7 | #include "vk_test_device.h" | ||
| 8 | #include "../shims/d3d12_com.h" | ||
| 9 | #include "../src/gfx10_descriptors.h" | ||
| 10 | |||
| 11 | #include <cstdint> | ||
| 12 | #include <cstdio> | ||
| 13 | #include <cstdlib> | ||
| 14 | #include <cstring> | ||
| 15 | |||
| 16 | #define EXPECT(condition) do { \ | ||
| 17 | if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ | ||
| 18 | } while (0) | ||
| 19 | |||
| 20 | namespace { | ||
| 21 | |||
| 22 | template<class T> | ||
| 23 | struct Ref { | ||
| 24 | T* p = nullptr; | ||
| 25 | ~Ref() { reset(); } | ||
| 26 | void reset() { | ||
| 27 | if (p) p->Release(); | ||
| 28 | p = nullptr; | ||
| 29 | } | ||
| 30 | T* operator->() const { return p; } | ||
| 31 | }; | ||
| 32 | |||
| 33 | constexpr UINT kDescriptor = 32; | ||
| 34 | constexpr UINT kViewBytes = 256; | ||
| 35 | constexpr UINT kBufferBytes = 64 * 1024; | ||
| 36 | |||
| 37 | D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { | ||
| 38 | D3D12_RESOURCE_DESC desc{}; | ||
| 39 | desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; | ||
| 40 | desc.Width = bytes; | ||
| 41 | desc.Height = 1; | ||
| 42 | desc.DepthOrArraySize = 1; | ||
| 43 | desc.MipLevels = 1; | ||
| 44 | desc.SampleDesc.Count = 1; | ||
| 45 | desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; | ||
| 46 | return desc; | ||
| 47 | } | ||
| 48 | |||
| 49 | leonida::gfx10::BufferWords raw_vsharp(std::uint64_t address) { | ||
| 50 | leonida::gfx10::Buffer b{}; | ||
| 51 | b.address = address; | ||
| 52 | b.num_records = kViewBytes; | ||
| 53 | b.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); | ||
| 54 | b.oob_select = leonida::gfx10::OobSelect::raw; | ||
| 55 | return leonida::gfx10::encode(b); | ||
| 56 | } | ||
| 57 | |||
| 58 | std::uint64_t base_of(const std::uint32_t* w) { return std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); } | ||
| 59 | bool zero_size(const std::uint32_t* w) { return base_of(w) == 0 && w[2] == 0; } | ||
| 60 | |||
| 61 | struct Heap { | ||
| 62 | static constexpr UINT slots = 4096; | ||
| 63 | static constexpr std::uint64_t bytes = std::uint64_t(slots) * kDescriptor; | ||
| 64 | }; | ||
| 65 | |||
| 66 | // What a slot of the copy is expected to hold: the buffer it names, or nothing. | ||
| 67 | enum class Want { a, b, none, zero }; | ||
| 68 | |||
| 69 | int check(ID3D12Device* device, std::uint64_t shader_va, std::uint64_t title, const Want* want, std::uint64_t a_va, | ||
| 70 | std::uint64_t b_va, bool mirrored, const char* step) { | ||
| 71 | static std::uint32_t copy[Heap::slots][kDescriptor / 4]; | ||
| 72 | EXPECT(rt::d3d12::read_arena(device, shader_va, copy, sizeof(copy))); | ||
| 73 | for (UINT s = 0; s < Heap::slots; ++s) { | ||
| 74 | const std::uint32_t* w = copy[s]; | ||
| 75 | bool ok = true; | ||
| 76 | switch (want[s]) { | ||
| 77 | case Want::a: ok = base_of(w) >= a_va && base_of(w) < a_va + kBufferBytes && w[2] == kViewBytes; break; | ||
| 78 | case Want::b: ok = base_of(w) >= b_va && base_of(w) < b_va + kBufferBytes && w[2] == kViewBytes; break; | ||
| 79 | case Want::none: ok = zero_size(w); break; | ||
| 80 | case Want::zero: for (int i = 0; i < 8; ++i) ok = ok && !w[i]; break; | ||
| 81 | } | ||
| 82 | if (!ok) { | ||
| 83 | std::fprintf(stderr, "%s: slot %u holds %08x %08x %08x %08x, wanted %d\n", step, s, w[0], w[1], w[2], w[3], | ||
| 84 | int(want[s])); | ||
| 85 | return 1; | ||
| 86 | } | ||
| 87 | } | ||
| 88 | const long long differ = rt::d3d12::console_heap_mirror_mismatches(device, title); | ||
| 89 | if (mirrored) EXPECT(differ == 0); | ||
| 90 | else EXPECT(differ == -1); | ||
| 91 | std::printf("%s: copy as expected, %s\n", step, mirrored ? "mirror agrees with it" : "no mirror"); | ||
| 92 | return 0; | ||
| 93 | } | ||
| 94 | |||
| 95 | int run(ID3D12Device* device, bool mirrored) { | ||
| 96 | const D3D12_COMMAND_QUEUE_DESC queue_desc{}; | ||
| 97 | Ref<ID3D12CommandQueue> queue; | ||
| 98 | Ref<ID3D12Fence> fence; | ||
| 99 | EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); | ||
| 100 | EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); | ||
| 101 | UINT64 fence_value = 0; | ||
| 102 | Ref<ID3D12CommandAllocator> allocator; | ||
| 103 | Ref<ID3D12GraphicsCommandList> list; | ||
| 104 | EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); | ||
| 105 | EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, | ||
| 106 | IID_PPV_ARGS(&list.p)))); | ||
| 107 | EXPECT(SUCCEEDED(list->Close())); | ||
| 108 | ID3D12CommandList* lists[] = {list.p}; | ||
| 109 | const auto submit = [&]() -> int { // every submission refreshes the console heaps first | ||
| 110 | queue->ExecuteCommandLists(1, lists); | ||
| 111 | EXPECT(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); | ||
| 112 | EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr))); | ||
| 113 | return 0; | ||
| 114 | }; | ||
| 115 | |||
| 116 | const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; | ||
| 117 | const auto desc = buffer_desc(kBufferBytes); | ||
| 118 | Ref<ID3D12Resource> a, b; | ||
| 119 | EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, | ||
| 120 | D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&a.p)))); | ||
| 121 | EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, | ||
| 122 | D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&b.p)))); | ||
| 123 | const std::uint64_t a_va = a->GetGPUVirtualAddress(), b_va = b->GetGPUVirtualAddress(); | ||
| 124 | EXPECT(a_va && b_va); | ||
| 125 | |||
| 126 | auto* title = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, Heap::bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | ||
| 127 | EXPECT(title); | ||
| 128 | static Want want[Heap::slots]; | ||
| 129 | const auto put = [&](UINT slot, std::uint64_t va, Want w) { | ||
| 130 | const auto words = raw_vsharp(va); | ||
| 131 | std::memcpy(title + slot * kDescriptor, words.data(), sizeof(words)); | ||
| 132 | want[slot] = w; | ||
| 133 | }; | ||
| 134 | for (UINT s = 0; s < Heap::slots; ++s) want[s] = Want::zero; | ||
| 135 | // Before the heap exists: slots 0-1023 name A, 1024-2047 B, the rest empty but for one data slot. | ||
| 136 | for (UINT s = 0; s < 1024; ++s) put(s, a_va + (s % 256) * kViewBytes, Want::a); | ||
| 137 | for (UINT s = 1024; s < 2048; ++s) put(s, b_va + (s % 256) * kViewBytes, Want::b); | ||
| 138 | const std::uint32_t data[8] = {0x12345000u, 0x00007777u, 0x00000400u, 0x40000000u, 1, 2, 3, 4}; | ||
| 139 | std::memcpy(title + 3000 * kDescriptor, data, sizeof(data)); | ||
| 140 | want[3000] = Want::none; // its descriptor half null in the copy (fix_console_slot) | ||
| 141 | |||
| 142 | const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, Heap::slots, | ||
| 143 | D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; | ||
| 144 | Ref<ID3D12DescriptorHeap> heap; | ||
| 145 | const auto title_va = reinterpret_cast<std::uint64_t>(title); | ||
| 146 | EXPECT(SUCCEEDED(rt::d3d12::create_console_descriptor_heap(device, &heap_desc, title_va, Heap::bytes, | ||
| 147 | IID_PPV_ARGS(&heap.p)))); | ||
| 148 | D3D12_DESCRIPTOR_HEAP_DESC got{}; | ||
| 149 | D3D12_GPU_VIRTUAL_ADDRESS shader_va = 0; | ||
| 150 | EXPECT(rt::d3d12::descriptor_heap_info(heap.p, got, shader_va)); | ||
| 151 | if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "first refresh")) return 1; | ||
| 152 | |||
| 153 | // The title rewrites slots after the heap is made (the write watch finds them): a slot of B now names A, new V#s | ||
| 154 | // past what it filled, and a page of A's slots zeroed (128 slots). | ||
| 155 | put(1500, a_va + 0x400, Want::a); | ||
| 156 | for (UINT s = 2048; s < 2112; ++s) put(s, b_va + (s % 256) * kViewBytes, Want::b); | ||
| 157 | std::memset(title + 128 * kDescriptor, 0, 4096); | ||
| 158 | for (UINT s = 128; s < 256; ++s) want[s] = Want::zero; | ||
| 159 | if (submit()) return 1; | ||
| 160 | if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "title writes")) return 1; | ||
| 161 | |||
| 162 | // A goes: the release sweep (filtered: only the V#s naming A) nulls the slots that name it, and only those. Its | ||
| 163 | // memory is given back once its GPU work retires, so a few submissions may pass first. | ||
| 164 | a.reset(); | ||
| 165 | for (UINT s = 0; s < Heap::slots; ++s) | ||
| 166 | if (want[s] == Want::a) want[s] = Want::none; | ||
| 167 | bool nulled = false; | ||
| 168 | for (int pass = 0; pass < 32 && !nulled; ++pass) { | ||
| 169 | if (submit()) return 1; | ||
| 170 | std::uint32_t w[8]; | ||
| 171 | EXPECT(rt::d3d12::read_arena(device, shader_va + 1500 * kDescriptor, w, sizeof(w))); | ||
| 172 | nulled = zero_size(w); | ||
| 173 | } | ||
| 174 | EXPECT(nulled); | ||
| 175 | if (check(device, shader_va, title_va, want, a_va, b_va, mirrored, "A released")) return 1; | ||
| 176 | |||
| 177 | heap.reset(); | ||
| 178 | VirtualFree(title, 0, MEM_RELEASE); | ||
| 179 | return 0; | ||
| 180 | } | ||
| 181 | |||
| 182 | } // namespace | ||
| 183 | |||
| 184 | int main() { | ||
| 185 | char value[4] = {}; | ||
| 186 | const bool mirrored = !(GetEnvironmentVariableA("LEONIDA_HEAP_MIRROR", value, sizeof(value)) == 1 && value[0] == '0'); | ||
| 187 | vktest::Device d; | ||
| 188 | const auto status = d.initialize(); | ||
| 189 | if (status == vktest::DeviceStatus::unavailable) { | ||
| 190 | std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); | ||
| 191 | return 77; | ||
| 192 | } | ||
| 193 | EXPECT(status == vktest::DeviceStatus::ready); | ||
| 194 | { | ||
| 195 | rt::d3d12::VulkanDeviceInfo info{}; | ||
| 196 | info.get_instance_proc = d.instance_proc; | ||
| 197 | info.instance = d.instance; | ||
| 198 | info.physical = d.physical; | ||
| 199 | info.device = d.device; | ||
| 200 | info.queue = d.queue; | ||
| 201 | info.queue_family = d.family; | ||
| 202 | info.buffer_device_address = true; | ||
| 203 | info.subgroup = d.subgroup; | ||
| 204 | Ref<ID3D12Device> device; | ||
| 205 | EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); | ||
| 206 | EXPECT(rt::d3d12::device_arena_size(device.p) > 0); | ||
| 207 | if (run(device.p, mirrored)) return 1; | ||
| 208 | } | ||
| 209 | if (d.validation_errors()) { | ||
| 210 | std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); | ||
| 211 | return 1; | ||
| 212 | } | ||
| 213 | std::puts("ok"); | ||
| 214 | return 0; | ||
| 215 | } | ||
diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 25fa1f654..546c76055 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp | |||
| @@ -1359,6 +1359,141 @@ int check_pending_stream_views(ID3D12Device* device) { | |||
| 1359 | return 0; | 1359 | return 0; |
| 1360 | } | 1360 | } |
| 1361 | 1361 | ||
| 1362 | namespace { | ||
| 1363 | std::atomic<DWORD> g_view_av_thread{0}; | ||
| 1364 | std::atomic<unsigned> g_view_avs{0}; | ||
| 1365 | |||
| 1366 | LONG CALLBACK count_view_av(PEXCEPTION_POINTERS info) { | ||
| 1367 | if (info && info->ExceptionRecord && info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && | ||
| 1368 | GetCurrentThreadId() == g_view_av_thread.load(std::memory_order_relaxed)) { | ||
| 1369 | g_view_avs.fetch_add(1, std::memory_order_relaxed); | ||
| 1370 | } | ||
| 1371 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 1372 | } | ||
| 1373 | } // namespace | ||
| 1374 | |||
| 1375 | // Map changes reported to title_memory_map between submissions must both retire a cached readable answer before a | ||
| 1376 | // synchronous slot-70 view hashes decommitted pages, and wake a pending slot-70 view without waiting for a submission. | ||
| 1377 | int check_placed_view_map_changes(ID3D12Device* device) { | ||
| 1378 | const char* who = "slot-70 view map changes"; | ||
| 1379 | if (!rt::d3d12::bindless_set_layout(device)) return 0; | ||
| 1380 | GpuReader gpu; | ||
| 1381 | EXPECT(!gpu.init(device, 4096)); | ||
| 1382 | auto env_is = [](const char* name, const char* want) { | ||
| 1383 | char buf[16]{}; | ||
| 1384 | const DWORD n = GetEnvironmentVariableA(name, buf, sizeof(buf)); | ||
| 1385 | return n > 0 && n < sizeof(buf) && std::strcmp(buf, want) == 0; | ||
| 1386 | }; | ||
| 1387 | auto index = [&](const leonida::gfx10::ImageWords& descriptor) { | ||
| 1388 | std::uint32_t key[8]; | ||
| 1389 | std::memcpy(key, descriptor.data(), sizeof(key)); | ||
| 1390 | return rt::d3d12::bindless_hash_lookup(device, key); | ||
| 1391 | }; | ||
| 1392 | |||
| 1393 | // 1. Committed >256 KiB texture -> decommit interior 64 KiB + map::changed -> synchronous view takes zero AVs. | ||
| 1394 | { | ||
| 1395 | constexpr SIZE_T bytes = 512 * 1024; | ||
| 1396 | auto* pages = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | ||
| 1397 | EXPECT(pages); | ||
| 1398 | std::memset(pages, 0x5a, bytes); | ||
| 1399 | D3D12_RESOURCE_DESC desc{}; | ||
| 1400 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | ||
| 1401 | desc.Width = 512; | ||
| 1402 | desc.Height = 1024; | ||
| 1403 | desc.DepthOrArraySize = desc.MipLevels = 1; | ||
| 1404 | desc.SampleDesc.Count = 1; | ||
| 1405 | desc.Format = DXGI_FORMAT_R8_UNORM; | ||
| 1406 | desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; | ||
| 1407 | D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; | ||
| 1408 | srv.Format = desc.Format; | ||
| 1409 | srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; | ||
| 1410 | srv.Texture2D.MipLevels = 1; | ||
| 1411 | srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; | ||
| 1412 | leonida::gfx10::ImageWords slot{}; | ||
| 1413 | auto write_view = [&](UINT mapping) { | ||
| 1414 | srv.Shader4ComponentMapping = mapping; | ||
| 1415 | std::array<UINT, 14> resource{}; | ||
| 1416 | std::array<UINT, 16> words{}; | ||
| 1417 | std::memcpy(resource.data(), &desc, sizeof(desc)); | ||
| 1418 | std::memcpy(words.data(), &srv, sizeof(srv)); | ||
| 1419 | return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), | ||
| 1420 | reinterpret_cast<UINT64>(pages), | ||
| 1421 | {reinterpret_cast<SIZE_T>(slot.data())}); | ||
| 1422 | }; | ||
| 1423 | EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING)); | ||
| 1424 | EXPECT(index(slot) != 0); | ||
| 1425 | |||
| 1426 | EXPECT(VirtualFree(pages + 65536, 65536, MEM_DECOMMIT) != FALSE); | ||
| 1427 | leonida::title_memory_map::changed(pages + 65536, 65536); | ||
| 1428 | |||
| 1429 | g_view_avs.store(0, std::memory_order_relaxed); | ||
| 1430 | g_view_av_thread.store(GetCurrentThreadId(), std::memory_order_relaxed); | ||
| 1431 | PVOID veh = AddVectoredExceptionHandler(1, &count_view_av); | ||
| 1432 | EXPECT(veh != nullptr); | ||
| 1433 | const bool wrote_after_unmap = write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0)); | ||
| 1434 | RemoveVectoredExceptionHandler(veh); | ||
| 1435 | g_view_av_thread.store(0, std::memory_order_relaxed); | ||
| 1436 | EXPECT(wrote_after_unmap); | ||
| 1437 | EXPECT(g_view_avs.load(std::memory_order_relaxed) == 0); | ||
| 1438 | |||
| 1439 | EXPECT(VirtualAlloc(pages + 65536, 65536, MEM_COMMIT, PAGE_READWRITE) == pages + 65536); | ||
| 1440 | leonida::title_memory_map::changed(pages + 65536, 65536); | ||
| 1441 | Ref<ID3D12Resource> placement; | ||
| 1442 | desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; | ||
| 1443 | EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&placement.p)), S_OK); | ||
| 1444 | placement.p->Release(); | ||
| 1445 | placement.p = nullptr; | ||
| 1446 | VirtualFree(pages, 0, MEM_RELEASE); | ||
| 1447 | } | ||
| 1448 | |||
| 1449 | // 2. Reserved texture -> commit + map::changed (no texel write note, no submission) -> synchronous view publishes. | ||
| 1450 | { | ||
| 1451 | constexpr SIZE_T bytes = 65536; | ||
| 1452 | void* pages = VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS); | ||
| 1453 | EXPECT(pages); | ||
| 1454 | D3D12_RESOURCE_DESC desc{}; | ||
| 1455 | desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; | ||
| 1456 | desc.Width = 32; | ||
| 1457 | desc.Height = 8; | ||
| 1458 | desc.DepthOrArraySize = desc.MipLevels = 1; | ||
| 1459 | desc.SampleDesc.Count = 1; | ||
| 1460 | desc.Format = DXGI_FORMAT_R8_UNORM; | ||
| 1461 | desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; | ||
| 1462 | D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; | ||
| 1463 | srv.Format = desc.Format; | ||
| 1464 | srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; | ||
| 1465 | srv.Texture2D.MipLevels = 1; | ||
| 1466 | leonida::gfx10::ImageWords first{}, second{}; | ||
| 1467 | auto write_view = [&](UINT mapping, leonida::gfx10::ImageWords& out) { | ||
| 1468 | srv.Shader4ComponentMapping = mapping; | ||
| 1469 | std::array<UINT, 14> resource{}; | ||
| 1470 | std::array<UINT, 16> words{}; | ||
| 1471 | std::memcpy(resource.data(), &desc, sizeof(desc)); | ||
| 1472 | std::memcpy(words.data(), &srv, sizeof(srv)); | ||
| 1473 | return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), | ||
| 1474 | reinterpret_cast<UINT64>(pages), | ||
| 1475 | {reinterpret_cast<SIZE_T>(out.data())}); | ||
| 1476 | }; | ||
| 1477 | EXPECT(write_view(D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, first)); | ||
| 1478 | if (!env_is("LEONIDA_TITLE_IMAGE_DEFER", "0")) EXPECT(!index(first)); | ||
| 1479 | |||
| 1480 | EXPECT(VirtualAlloc(pages, bytes, MEM_COMMIT, PAGE_READWRITE) == pages); | ||
| 1481 | std::memset(pages, 0x33, bytes); | ||
| 1482 | leonida::title_memory_map::changed(pages, bytes); | ||
| 1483 | |||
| 1484 | EXPECT(write_view(D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 0, 0, 0), second)); | ||
| 1485 | if (!env_is("LEONIDA_TITLE_FILL_ASYNC", "1")) EXPECT(index(first) && index(second)); | ||
| 1486 | |||
| 1487 | Ref<ID3D12Resource> placement; | ||
| 1488 | desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; | ||
| 1489 | EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&placement.p)), S_OK); | ||
| 1490 | placement.p->Release(); | ||
| 1491 | placement.p = nullptr; | ||
| 1492 | VirtualFree(pages, 0, MEM_RELEASE); | ||
| 1493 | } | ||
| 1494 | return 0; | ||
| 1495 | } | ||
| 1496 | |||
| 1362 | // A persistent Map can become readable without notifying xmem or calling Map a second time. | 1497 | // A persistent Map can become readable without notifying xmem or calling Map a second time. |
| 1363 | int check_mapped_plane(ID3D12Device* device) { | 1498 | int check_mapped_plane(ID3D12Device* device) { |
| 1364 | const char* who = "persistent slot-133 plane"; | 1499 | const char* who = "persistent slot-133 plane"; |
| @@ -2089,6 +2224,7 @@ int main(int argc, char** argv) { | |||
| 2089 | if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p); | 2224 | if (vk.host_pointer_alignment) failures += check_title_placed_all(ours.p); |
| 2090 | if (vk.host_image_copy) { | 2225 | if (vk.host_image_copy) { |
| 2091 | failures += check_pending_stream_views(ours.p); | 2226 | failures += check_pending_stream_views(ours.p); |
| 2227 | failures += check_placed_view_map_changes(ours.p); | ||
| 2092 | failures += check_shared_bc_placements(ours.p); | 2228 | failures += check_shared_bc_placements(ours.p); |
| 2093 | failures += check_mapped_plane(ours.p); | 2229 | failures += check_mapped_plane(ours.p); |
| 2094 | failures += check_mapped_bc_array(ours.p); | 2230 | failures += check_mapped_bc_array(ours.p); |
| @@ -2099,6 +2235,7 @@ int main(int argc, char** argv) { | |||
| 2099 | no_host_copy.host_image_copy = false; | 2235 | no_host_copy.host_image_copy = false; |
| 2100 | Ref<ID3D12Device> staged; | 2236 | Ref<ID3D12Device> staged; |
| 2101 | if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; | 2237 | if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; |
| 2238 | failures += check_placed_view_map_changes(staged.p); | ||
| 2102 | failures += check_mapped_plane(staged.p); | 2239 | failures += check_mapped_plane(staged.p); |
| 2103 | failures += check_mapped_bc_array(staged.p); | 2240 | failures += check_mapped_bc_array(staged.p); |
| 2104 | } | 2241 | } |
diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index 775cfeb58..7b529546b 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp | |||
| @@ -150,6 +150,7 @@ int main(int argc, char** argv) { | |||
| 150 | rt::d3d12::VulkanDeviceInfo info{}; | 150 | rt::d3d12::VulkanDeviceInfo info{}; |
| 151 | info.prepare_on_bind=d.prepare_on_bind; | 151 | info.prepare_on_bind=d.prepare_on_bind; |
| 152 | info.cold_graphics_compile=d.cold_graphics_compile; | 152 | info.cold_graphics_compile=d.cold_graphics_compile; |
| 153 | info.heavy_pipeline_cache=d.heavy_pipeline_cache; | ||
| 153 | info.get_instance_proc = d.instance_proc; | 154 | info.get_instance_proc = d.instance_proc; |
| 154 | info.instance = d.instance; | 155 | info.instance = d.instance; |
| 155 | info.physical = d.physical; | 156 | info.physical = d.physical; |
| @@ -161,6 +162,7 @@ int main(int argc, char** argv) { | |||
| 161 | info.mesh_shader = mesh; | 162 | info.mesh_shader = mesh; |
| 162 | info.mesh_shader_queries = mesh && d.mesh_shader_queries; | 163 | info.mesh_shader_queries = mesh && d.mesh_shader_queries; |
| 163 | info.pipeline_statistics_query = d.pipeline_statistics_query; | 164 | info.pipeline_statistics_query = d.pipeline_statistics_query; |
| 165 | info.conservative_rasterization = d.conservative_rasterization; | ||
| 164 | return info; | 166 | return info; |
| 165 | }; | 167 | }; |
| 166 | const auto make_device = [&](bool mesh, Ref<ID3D12Device>& device) { | 168 | const auto make_device = [&](bool mesh, Ref<ID3D12Device>& device) { |
| @@ -253,6 +255,34 @@ int main(int argc, char** argv) { | |||
| 253 | vs_stream.add(TopologySubobject{.inner = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE}); | 255 | vs_stream.add(TopologySubobject{.inner = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE}); |
| 254 | vs_stream.add(TargetsSubobject{.inner = one_target()}); | 256 | vs_stream.add(TargetsSubobject{.inner = one_target()}); |
| 255 | EXPECT(SUCCEEDED(create(device.p, vs_stream, vs_pso))); | 257 | EXPECT(SUCCEEDED(create(device.p, vs_stream, vs_pso))); |
| 258 | // Conservative rasterization in a mesh pipeline: its stream has no input assembler, so it need not name a topology | ||
| 259 | // type. A vertex pipeline without TRIANGLE is still refused, as is a wireframe mesh one. | ||
| 260 | { | ||
| 261 | D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; | ||
| 262 | EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options))); | ||
| 263 | if (options.ConservativeRasterizationTier != D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) { | ||
| 264 | std::printf("conservative rasterization tier %d: mesh pipelines checked\n", int(options.ConservativeRasterizationTier)); | ||
| 265 | D3D12_RASTERIZER_DESC conservative{}; | ||
| 266 | conservative.FillMode = D3D12_FILL_MODE_SOLID; | ||
| 267 | conservative.CullMode = D3D12_CULL_MODE_NONE; | ||
| 268 | conservative.DepthClipEnable = TRUE; | ||
| 269 | conservative.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON; | ||
| 270 | Ref<ID3D12PipelineState> made; | ||
| 271 | Stream conservative_mesh = mesh_stream; | ||
| 272 | conservative_mesh.add(RasterizerSubobject{.inner = conservative}); | ||
| 273 | EXPECT(SUCCEEDED(create(device.p, conservative_mesh, made)) && made.p); | ||
| 274 | conservative.FillMode = D3D12_FILL_MODE_WIREFRAME; | ||
| 275 | Stream wireframe_mesh = mesh_stream; | ||
| 276 | wireframe_mesh.add(RasterizerSubobject{.inner = conservative}); | ||
| 277 | EXPECT(create(device.p, wireframe_mesh, refused) == E_INVALIDARG && !refused.p); | ||
| 278 | conservative.FillMode = D3D12_FILL_MODE_SOLID; | ||
| 279 | Stream no_topology_vs; | ||
| 280 | no_topology_vs.add(RootSubobject{.inner = root.p}).add(VsSubobject{.inner = vs}).add(PsSubobject{.inner = ps}); | ||
| 281 | no_topology_vs.add(TargetsSubobject{.inner = one_target()}); | ||
| 282 | no_topology_vs.add(RasterizerSubobject{.inner = conservative}); | ||
| 283 | EXPECT(create(device.p, no_topology_vs, refused) == E_INVALIDARG && !refused.p); | ||
| 284 | } | ||
| 285 | } | ||
| 256 | // A mesh shader translated before the graphics root window would read its root arguments from the wrong | 286 | // A mesh shader translated before the graphics root window would read its root arguments from the wrong |
| 257 | // dwords: refused, with a log line that asks for the shaders stage again. | 287 | // dwords: refused, with a log line that asks for the shaders stage again. |
| 258 | { | 288 | { |
diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index e5ef14304..bf0f14f1e 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp | |||
| @@ -512,7 +512,194 @@ int check_window_overflow(Context& c) { | |||
| 512 | VirtualFree(ring, 0, MEM_RELEASE); | 512 | VirtualFree(ring, 0, MEM_RELEASE); |
| 513 | return 0; | 513 | return 0; |
| 514 | } | 514 | } |
| 515 | // These fixtures register their own pairs without XMem. Retire each before Wine can reuse either VA. | 515 | // What the GPU writes into a title window goes back to the title's pages (#1537, the WRITE_INVALID stop: a window is |
| 516 | // a read-side mirror, so a UAV write used to land in the copy and the title never saw it). The shader's write is read | ||
| 517 | // back through the pages themselves; then a write by the title must survive the next submission's forward copy. | ||
| 518 | struct WriteBack { | ||
| 519 | Context* c; | ||
| 520 | ID3D12CommandAllocator* allocator; | ||
| 521 | ID3D12GraphicsCommandList* list; | ||
| 522 | ID3D12Resource* out; | ||
| 523 | ID3D12DescriptorHeap* heap; | ||
| 524 | UINT64 gpu; | ||
| 525 | }; | ||
| 526 | |||
| 527 | // One submission that dispatches through a root UAV at `va` and waits for it. False on a failed call. | ||
| 528 | int submit_write(WriteBack& s, std::uint64_t va) { | ||
| 529 | EXPECT(s.allocator->Reset() == S_OK); | ||
| 530 | EXPECT(s.list->Reset(s.allocator, s.c->pso) == S_OK); | ||
| 531 | ID3D12DescriptorHeap* heaps[] = {s.heap}; | ||
| 532 | s.list->SetDescriptorHeaps(1, heaps); | ||
| 533 | s.list->SetComputeRootSignature(s.c->root); | ||
| 534 | s.list->SetComputeRoot32BitConstant(0, 0, 0); | ||
| 535 | s.list->SetComputeRoot32BitConstant(0, 1, 1); // the step: a word the shader writes | ||
| 536 | s.list->SetComputeRootUnorderedAccessView(1, va); | ||
| 537 | s.list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{s.gpu}); | ||
| 538 | s.list->Dispatch(1, 1, 1); | ||
| 539 | D3D12_RESOURCE_BARRIER to_copy{}; | ||
| 540 | to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; | ||
| 541 | to_copy.Transition.pResource = s.out; | ||
| 542 | to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; | ||
| 543 | to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; | ||
| 544 | to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; | ||
| 545 | s.list->ResourceBarrier(1, &to_copy); | ||
| 546 | EXPECT(s.list->Close() == S_OK); | ||
| 547 | ID3D12CommandList* lists[] = {s.list}; | ||
| 548 | s.c->queue->ExecuteCommandLists(1, lists); | ||
| 549 | EXPECT(rt::d3d12::last_execute_result(s.c->queue) == leonida::ReplayResult::success); | ||
| 550 | EXPECT(SUCCEEDED(s.c->queue->Signal(s.c->fence, ++s.c->fence_value))); | ||
| 551 | s.c->fence->SetEventOnCompletion(s.c->fence_value, nullptr); // a null event waits, as D3D12 does | ||
| 552 | return 0; | ||
| 553 | } | ||
| 554 | |||
| 555 | // The same gap on a buffer the title places at its own address (slot 133, the retail case for a compute result it | ||
| 556 | // reads back): the pages are not imported here, so the buffer is a shadow, and the write of a root UAV over the | ||
| 557 | // title's VA must reach the pages at the next submission - and the title's own newer words must still win. | ||
| 558 | int check_placed_write_back(Context& c, bool geometry) { | ||
| 559 | void* pages = VirtualAlloc(nullptr, kPages, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); | ||
| 560 | EXPECT(pages); | ||
| 561 | const auto title_va = reinterpret_cast<std::uint64_t>(pages); | ||
| 562 | auto* words = static_cast<std::uint32_t*>(pages); | ||
| 563 | for (UINT i = 0; i < kPages / 4; ++i) words[i] = 0xA0000000u + i * 3u; // never zero, unlike the shader's rows | ||
| 564 | auto& aliases = leonida::title_va_aliases(); | ||
| 565 | aliases.add_title_memory(title_va, kPages); // what the xmem shims do for the title's allocations | ||
| 566 | const D3D12_RESOURCE_DESC desc = buffer_desc(kPages); | ||
| 567 | Ref<ID3D12Resource> placed; | ||
| 568 | EXPECT(SUCCEEDED( | ||
| 569 | rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&placed.p)))); | ||
| 570 | EXPECT(placed->GetGPUVirtualAddress() == title_va); | ||
| 571 | EXPECT(aliases.shader_va(title_va) != title_va); // there is a copy to be reached through | ||
| 572 | |||
| 573 | const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; | ||
| 574 | const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); | ||
| 575 | const auto readback_desc = buffer_desc(kBytes); | ||
| 576 | Ref<ID3D12Resource> out, readback; | ||
| 577 | EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, | ||
| 578 | D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, | ||
| 579 | IID_PPV_ARGS(&out.p)))); | ||
| 580 | EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, | ||
| 581 | D3D12_RESOURCE_STATE_COPY_DEST, nullptr, | ||
| 582 | IID_PPV_ARGS(&readback.p)))); | ||
| 583 | D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, | ||
| 584 | D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; | ||
| 585 | Ref<ID3D12DescriptorHeap> heap; | ||
| 586 | EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); | ||
| 587 | Ref<ID3D12CommandAllocator> allocator; | ||
| 588 | Ref<ID3D12GraphicsCommandList> list; | ||
| 589 | EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); | ||
| 590 | EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, | ||
| 591 | IID_PPV_ARGS(&list.p)))); | ||
| 592 | EXPECT(list->Close() == S_OK); | ||
| 593 | WriteBack s{&c, allocator.p, list.p, out.p, heap.p, | ||
| 594 | reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 10))(heap.p)}; | ||
| 595 | |||
| 596 | const std::vector<std::uint32_t> before(words, words + kElements); | ||
| 597 | EXPECT(submit_write(s, title_va) == 0); | ||
| 598 | UINT untouched = 0; | ||
| 599 | for (UINT i = 0; i < kElements; ++i) untouched += words[i] == before[i]; | ||
| 600 | // An imported buffer is the same memory and needs no copy; only a shadow owes the pages the GPU's words. | ||
| 601 | const bool shadow = !geometry && aliases.shader_va(title_va) >= c.arena; | ||
| 602 | if (shadow) { | ||
| 603 | std::printf("placed buffer write back: %u/%u words still held the title's before the next submission\n", | ||
| 604 | untouched, kElements); | ||
| 605 | EXPECT(untouched == kElements); | ||
| 606 | } | ||
| 607 | |||
| 608 | EXPECT(submit_write(s, title_va) == 0); | ||
| 609 | std::vector<std::uint32_t> written(words, words + kElements); | ||
| 610 | UINT reached = 0, changed = 0, nonzero = 0; | ||
| 611 | for (UINT i = 0; i < kElements; ++i) { | ||
| 612 | reached += written[i] == (0xA0000000u + i * 3u); | ||
| 613 | changed += written[i] != before[i]; | ||
| 614 | nonzero += written[i] != 0; | ||
| 615 | } | ||
| 616 | std::printf("placed buffer write back: %u/%u words reached the pages (%u changed, %u nonzero)\n", kElements - reached, | ||
| 617 | kElements, changed, nonzero); | ||
| 618 | EXPECT(changed == kElements && nonzero > 0); | ||
| 619 | (void)reached; | ||
| 620 | |||
| 621 | // The title writes its own words over the result: the next submission copies them forward and they stay. | ||
| 622 | for (UINT i = 0; i < kElements; ++i) words[i] = 0xB16B00B5u; | ||
| 623 | EXPECT(submit_write(s, title_va) == 0); | ||
| 624 | UINT kept = 0; | ||
| 625 | for (UINT i = 0; i < kElements; ++i) kept += words[i] == 0xB16B00B5u; | ||
| 626 | std::printf("placed buffer write back: the title's own words survived %u/%u\n", kept, kElements); | ||
| 627 | EXPECT(kept == kElements); | ||
| 628 | |||
| 629 | placed.reset(); // the shadow goes, the pages stay writable | ||
| 630 | aliases.remove_title_memory(title_va); | ||
| 631 | VirtualFree(pages, 0, MEM_RELEASE); | ||
| 632 | return 0; | ||
| 633 | } | ||
| 634 | |||
| 635 | int check_window_write_back(Context& c, bool geometry) { | ||
| 636 | constexpr UINT64 ring_bytes = 256 * 1024; | ||
| 637 | auto* ring = static_cast<std::uint32_t*>( | ||
| 638 | VirtualAlloc(nullptr, ring_bytes, MEM_TOP_DOWN | MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); | ||
| 639 | EXPECT(ring); | ||
| 640 | const auto ring_va = reinterpret_cast<std::uint64_t>(ring); | ||
| 641 | for (UINT i = 0; i < ring_bytes / 4; ++i) ring[i] = 0; | ||
| 642 | auto& aliases = leonida::title_va_aliases(); | ||
| 643 | aliases.add_title_memory(ring_va, ring_bytes); | ||
| 644 | |||
| 645 | const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; | ||
| 646 | const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); | ||
| 647 | const auto readback_desc = buffer_desc(kBytes); | ||
| 648 | Ref<ID3D12Resource> out, readback; | ||
| 649 | EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, | ||
| 650 | D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, | ||
| 651 | IID_PPV_ARGS(&out.p)))); | ||
| 652 | EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, | ||
| 653 | D3D12_RESOURCE_STATE_COPY_DEST, nullptr, | ||
| 654 | IID_PPV_ARGS(&readback.p)))); | ||
| 655 | D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, | ||
| 656 | D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; | ||
| 657 | Ref<ID3D12DescriptorHeap> heap; | ||
| 658 | EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); | ||
| 659 | Ref<ID3D12CommandAllocator> allocator; | ||
| 660 | Ref<ID3D12GraphicsCommandList> list; | ||
| 661 | EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); | ||
| 662 | EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, | ||
| 663 | IID_PPV_ARGS(&list.p)))); | ||
| 664 | EXPECT(list->Close() == S_OK); // Reset needs it closed, as the title leaves it | ||
| 665 | WriteBack s{&c, allocator.p, list.p, out.p, heap.p, | ||
| 666 | reinterpret_cast<XboxHeapHandleFn>(slot(heap.p, 10))(heap.p)}; | ||
| 667 | |||
| 668 | // The shader writes the range the root UAV names, which is the title's own pages here, far past the arena: the | ||
| 669 | // resolve already has to make a window for them before the submission. | ||
| 670 | EXPECT(aliases.shader_va(ring_va) == ring_va); | ||
| 671 | EXPECT(submit_write(s, ring_va) == 0); | ||
| 672 | EXPECT(aliases.shader_va(ring_va) != ring_va); // a window was made for the title's pages | ||
| 673 | if (!geometry) EXPECT(ring[0] == 0); // the copy took the write: the pages get it only after the next submission | ||
| 674 | |||
| 675 | // The next submission's refresh copies the GPU's writes back, before it copies the pages forward. | ||
| 676 | EXPECT(submit_write(s, ring_va) == 0); | ||
| 677 | const std::vector<std::uint32_t> written(ring, ring + kElements); | ||
| 678 | UINT nonzero = 0; | ||
| 679 | for (std::uint32_t w : written) nonzero += w != 0; | ||
| 680 | std::printf("write back: %u of %u words the shader wrote are in the title's pages\n", nonzero, kElements); | ||
| 681 | EXPECT(nonzero > 0); | ||
| 682 | |||
| 683 | // The same submission again: the pages keep what they hold, the values do not drift. | ||
| 684 | EXPECT(submit_write(s, ring_va) == 0); | ||
| 685 | UINT stable = 0; | ||
| 686 | for (UINT i = 0; i < kElements; ++i) stable += ring[i] == written[i]; | ||
| 687 | std::printf("write back: the pages kept those words across two submissions %u/%u\n", stable, kElements); | ||
| 688 | EXPECT(stable == kElements); | ||
| 689 | |||
| 690 | // A write by the title after a submission is copied forward over the result again, not overwritten by it. | ||
| 691 | for (UINT i = 0; i < kElements; ++i) ring[i] = 0xB16B00B5u; | ||
| 692 | EXPECT(submit_write(s, ring_va) == 0); | ||
| 693 | UINT kept = 0; | ||
| 694 | for (UINT i = 0; i < kElements; ++i) kept += ring[i] == 0xB16B00B5u; | ||
| 695 | std::printf("write back: the title's own words survived the next submission %u/%u\n", kept, kElements); | ||
| 696 | EXPECT(kept == kElements); | ||
| 697 | |||
| 698 | aliases.remove_title_memory(ring_va); | ||
| 699 | VirtualFree(ring, 0, MEM_RELEASE); | ||
| 700 | return 0; | ||
| 701 | } | ||
| 702 | |||
| 516 | void remove_test_pair(std::uintptr_t gpu, std::uintptr_t cpu) { | 703 | void remove_test_pair(std::uintptr_t gpu, std::uintptr_t cpu) { |
| 517 | auto& state = leonida::title_gpu_views::state(); | 704 | auto& state = leonida::title_gpu_views::state(); |
| 518 | std::unique_lock lock(state.mutex); | 705 | std::unique_lock lock(state.mutex); |
| @@ -987,6 +1174,8 @@ int main(int argc, char** argv) { | |||
| 987 | const bool api_copy = api_copy_off || (argc == 2 && std::strcmp(argv[1], "--api-descriptor-copy") == 0); | 1174 | const bool api_copy = api_copy_off || (argc == 2 && std::strcmp(argv[1], "--api-descriptor-copy") == 0); |
| 988 | const bool rebind = api_copy || mirror_off || second_device || (argc == 2 && std::strcmp(argv[1], "--rebound-tables") == 0); | 1175 | const bool rebind = api_copy || mirror_off || second_device || (argc == 2 && std::strcmp(argv[1], "--rebound-tables") == 0); |
| 989 | const bool window_cap = argc == 2 && std::strcmp(argv[1], "--window-cap") == 0; | 1176 | const bool window_cap = argc == 2 && std::strcmp(argv[1], "--window-cap") == 0; |
| 1177 | const bool window_write_back = argc == 2 && std::strcmp(argv[1], "--window-writeback") == 0; | ||
| 1178 | const bool placed_write_back = argc == 2 && std::strcmp(argv[1], "--placed-writeback") == 0; | ||
| 990 | if (window_cap) { | 1179 | if (window_cap) { |
| 991 | const char* cap = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); | 1180 | const char* cap = std::getenv("LEONIDA_TITLE_WINDOWS_MB"); |
| 992 | if (!cap || std::strcmp(cap, "0")) { | 1181 | if (!cap || std::strcmp(cap, "0")) { |
| @@ -1101,6 +1290,25 @@ int main(int argc, char** argv) { | |||
| 1101 | std::printf("title memory past the window cap: the views were zero-size and the shader read zeros\n"); | 1290 | std::printf("title memory past the window cap: the views were zero-size and the shader read zeros\n"); |
| 1102 | return 0; | 1291 | return 0; |
| 1103 | } | 1292 | } |
| 1293 | if (placed_write_back) { | ||
| 1294 | if (check_placed_write_back(c, geometry)) return 1; | ||
| 1295 | if (d.validation_errors()) { | ||
| 1296 | std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); | ||
| 1297 | return 1; | ||
| 1298 | } | ||
| 1299 | std::printf("title-placed buffer write back: the GPU's writes reached the title's pages\n"); | ||
| 1300 | return 0; | ||
| 1301 | } | ||
| 1302 | if (window_write_back) { | ||
| 1303 | if (check_window_write_back(c, geometry)) return 1; | ||
| 1304 | if (d.validation_errors()) { | ||
| 1305 | std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); | ||
| 1306 | return 1; | ||
| 1307 | } | ||
| 1308 | std::printf("title window write back: the GPU's writes reached the title's pages and the title's own " | ||
| 1309 | "words won\n"); | ||
| 1310 | return 0; | ||
| 1311 | } | ||
| 1104 | if (geometry && check_declined_imports(c)) return 1; | 1312 | if (geometry && check_declined_imports(c)) return 1; |
| 1105 | if (geometry && check_import_over_shadow(c)) return 1; | 1313 | if (geometry && check_import_over_shadow(c)) return 1; |
| 1106 | if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; | 1314 | if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; |
diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index 560110240..b45cc2c84 100644 --- a/runtime/test/d3d12_translated_draw_test.cpp +++ b/runtime/test/d3d12_translated_draw_test.cpp | |||
| @@ -193,6 +193,7 @@ int main(int argc, char** argv) { | |||
| 193 | rt::d3d12::VulkanDeviceInfo info{}; | 193 | rt::d3d12::VulkanDeviceInfo info{}; |
| 194 | info.prepare_on_bind=d.prepare_on_bind; | 194 | info.prepare_on_bind=d.prepare_on_bind; |
| 195 | info.cold_graphics_compile=d.cold_graphics_compile; | 195 | info.cold_graphics_compile=d.cold_graphics_compile; |
| 196 | info.heavy_pipeline_cache=d.heavy_pipeline_cache; | ||
| 196 | info.get_instance_proc = d.instance_proc; | 197 | info.get_instance_proc = d.instance_proc; |
| 197 | info.instance = d.instance; | 198 | info.instance = d.instance; |
| 198 | info.physical = d.physical; | 199 | info.physical = d.physical; |
diff --git a/runtime/test/d3d12_xmem_placed_test.cpp b/runtime/test/d3d12_xmem_placed_test.cpp index 7c64a23cf..33b5d462a 100644 --- a/runtime/test/d3d12_xmem_placed_test.cpp +++ b/runtime/test/d3d12_xmem_placed_test.cpp | |||
| @@ -174,6 +174,82 @@ int queue_remap(ID3D12Device* real, ID3D12Device* proxy) { | |||
| 174 | return 0; | 174 | return 0; |
| 175 | } | 175 | } |
| 176 | 176 | ||
| 177 | // Queue slot 31 as a retail run takes it: no batch hook, so the queue's default adapter sends each range to xmem's | ||
| 178 | // range callback (copy_page_mappings_fn), which mirrors a legacy-paired GPU-only destination at its CPU view. The | ||
| 179 | // source is a GPU-only pool backed only through its CPU alias, and the title maps a page of its own at one CPU twin | ||
| 180 | // while the remap waits behind queue work (deferred with list values, waited for without them). When the remap is | ||
| 181 | // applied, the GPU-only pages change and the title's CPU page keeps its bytes, through the copy and the unmap after it. | ||
| 182 | int queue_remap_default_route(ID3D12Device* real, ID3D12Device* proxy) { | ||
| 183 | using rt::xmem::PageBatch; | ||
| 184 | using rt::xmem::PageRange; | ||
| 185 | auto reserve = reinterpret_cast<XMemVirtualAllocFn>(rt::shims::find("xmem.dll", "XMemVirtualAlloc")); | ||
| 186 | auto allocate = reinterpret_cast<XMemAllocatePhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")); | ||
| 187 | auto map = reinterpret_cast<XMemMapPhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemMapPhysicalPages")); | ||
| 188 | auto free_pages = reinterpret_cast<XMemFreePhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemFreePhysicalPages")); | ||
| 189 | constexpr unsigned n = 2; | ||
| 190 | auto window = [&](DWORD protect) { | ||
| 191 | return static_cast<std::uint8_t*>(reserve(nullptr, n * kPage64k, MEM_RESERVE | kXmem64kPages, 0, protect)); | ||
| 192 | }; | ||
| 193 | // Two pairs, each a CPU range and then the GPU-only range of its size: the pool's and the destination's. | ||
| 194 | auto* pool_cpu = window(PAGE_READWRITE); | ||
| 195 | auto* pool = window(0x801); | ||
| 196 | auto* cpu = window(PAGE_READWRITE); | ||
| 197 | auto* dst = window(0x801); | ||
| 198 | EXPECT(pool_cpu && pool && cpu && dst); | ||
| 199 | EXPECT(leonida::title_gpu_views::to_cpu(uintptr_t(pool)) == uintptr_t(pool_cpu)); | ||
| 200 | EXPECT(leonida::title_gpu_views::to_cpu(uintptr_t(dst)) == uintptr_t(cpu)); | ||
| 201 | std::uint64_t pages[n + 1]{}, count = n + 1; | ||
| 202 | EXPECT(allocate(0x280, &count, pages) && count == n + 1); | ||
| 203 | EXPECT(map(pool_cpu, n, pages)); // the pool's pages are mapped at its CPU alias only | ||
| 204 | for (unsigned i = 0; i < n; ++i) pool_cpu[i * kPage64k] = static_cast<std::uint8_t>(40 + i); | ||
| 205 | |||
| 206 | D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_COPY}; | ||
| 207 | Ref<ID3D12CommandQueue> queue; | ||
| 208 | Ref<ID3D12Fence> gate; | ||
| 209 | EXPECT(SUCCEEDED(proxy->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue.p)))); | ||
| 210 | EXPECT(SUCCEEDED(real->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate.p)))); | ||
| 211 | auto* real_queue = rt::d3d12_xs::queue_proxy_real_queue(queue.p); | ||
| 212 | EXPECT(real_queue && SUCCEEDED(real_queue->Wait(gate.p, 1))); | ||
| 213 | rt::d3d12_xs::set_copy_page_mappings_hook(nullptr); // the retail route: the default adapter | ||
| 214 | using Copy = HRESULT(WINAPI*)(void*, UINT, const PageBatch*, std::uintptr_t, UINT, UINT); | ||
| 215 | auto call = reinterpret_cast<Copy>((*reinterpret_cast<void***>(queue.p))[31]); | ||
| 216 | const PageRange copy_run[] = {{0, 0, n}}; | ||
| 217 | const PageBatch copy_batch{uintptr_t(dst), 1, copy_run}; | ||
| 218 | auto done = std::async(std::launch::async, [&] { return call(queue.p, 1, ©_batch, uintptr_t(pool), n, 0); }); | ||
| 219 | // While the remap waits behind the held work, the title maps a page of its own at the second CPU twin. | ||
| 220 | EXPECT(map(cpu + kPage64k, 1, &pages[n])); | ||
| 221 | cpu[kPage64k] = 77; | ||
| 222 | EXPECT(SUCCEEDED(gate->Signal(1))); | ||
| 223 | EXPECT(SUCCEEDED(done.get())); | ||
| 224 | EXPECT(SUCCEEDED(real_queue->Signal(gate.p, 2))); | ||
| 225 | HANDLE remapped = CreateEventW(nullptr, FALSE, FALSE, nullptr); | ||
| 226 | EXPECT(remapped && SUCCEEDED(gate->SetEventOnCompletion(2, remapped))); | ||
| 227 | const auto completion = WaitForSingleObject(remapped, 10000); | ||
| 228 | CloseHandle(remapped); | ||
| 229 | EXPECT(completion == WAIT_OBJECT_0); | ||
| 230 | EXPECT(dst[0] == 40 && dst[kPage64k] == 41); // the GPU-only pages, found through the pool's CPU alias | ||
| 231 | EXPECT(cpu[0] == 40); // a CPU twin with no mapping of the title's follows the copy | ||
| 232 | EXPECT(cpu[kPage64k] == 77); // the title's own page is kept | ||
| 233 | |||
| 234 | // The unmap: the GPU-only pages and the mirrored twin are unmapped, the title's page stays. | ||
| 235 | const PageRange hole[] = {{2, 0, n}}; | ||
| 236 | const PageBatch unmap_batch{uintptr_t(dst), 1, hole}; | ||
| 237 | EXPECT(SUCCEEDED(call(queue.p, 1, &unmap_batch, uintptr_t(pool), n, 0))); | ||
| 238 | EXPECT(SUCCEEDED(real_queue->Signal(gate.p, 3))); | ||
| 239 | remapped = CreateEventW(nullptr, FALSE, FALSE, nullptr); | ||
| 240 | EXPECT(remapped && SUCCEEDED(gate->SetEventOnCompletion(3, remapped))); | ||
| 241 | EXPECT(WaitForSingleObject(remapped, 10000) == WAIT_OBJECT_0); | ||
| 242 | CloseHandle(remapped); | ||
| 243 | EXPECT(state_is(dst, MEM_RESERVE) && state_is(dst + kPage64k, MEM_RESERVE) && state_is(cpu, MEM_RESERVE)); | ||
| 244 | EXPECT(cpu[kPage64k] == 77); | ||
| 245 | |||
| 246 | EXPECT(map(cpu + kPage64k, 1, nullptr) && map(pool_cpu, n, nullptr)); | ||
| 247 | EXPECT(free_pages(n + 1, pages)); | ||
| 248 | std::puts("queue slot 31 default route: a source through its CPU alias, a deferred copy and an unmap keep the " | ||
| 249 | "title's own CPU twin page"); | ||
| 250 | return 0; | ||
| 251 | } | ||
| 252 | |||
| 177 | // What a GPU copy of `buffer` reads now (a submission: the shadows are refreshed first). | 253 | // What a GPU copy of `buffer` reads now (a submission: the shadows are refreshed first). |
| 178 | int read_back(ID3D12Device* real, ID3D12Resource* buffer, UINT64 size, std::vector<std::uint8_t>& out) { | 254 | int read_back(ID3D12Device* real, ID3D12Resource* buffer, UINT64 size, std::vector<std::uint8_t>& out) { |
| 179 | D3D12_RESOURCE_DESC desc = buffer->GetDesc(); | 255 | D3D12_RESOURCE_DESC desc = buffer->GetDesc(); |
| @@ -547,6 +623,7 @@ int main(int argc, char** argv) { | |||
| 547 | failures += run(real.p, device.p, eager); | 623 | failures += run(real.p, device.p, eager); |
| 548 | failures += exposure_map_ranges(device.p); | 624 | failures += exposure_map_ranges(device.p); |
| 549 | failures += queue_remap(real.p, device.p); | 625 | failures += queue_remap(real.p, device.p); |
| 626 | failures += queue_remap_default_route(real.p, device.p); | ||
| 550 | failures += paired_views(real.p); | 627 | failures += paired_views(real.p); |
| 551 | } | 628 | } |
| 552 | } | 629 | } |
diff --git a/runtime/test/dstorage_test.cpp b/runtime/test/dstorage_test.cpp index c24bcdb65..fa1b529d0 100644 --- a/runtime/test/dstorage_test.cpp +++ b/runtime/test/dstorage_test.cpp | |||
| @@ -18,6 +18,7 @@ | |||
| 18 | #include <span> | 18 | #include <span> |
| 19 | #include "../src/bcpack.h" | 19 | #include "../src/bcpack.h" |
| 20 | #include "../src/bcpack_stream.h" | 20 | #include "../src/bcpack_stream.h" |
| 21 | #include "../src/dstorage_hold.h" | ||
| 21 | #include "../src/title_geometry_watch.h" | 22 | #include "../src/title_geometry_watch.h" |
| 22 | #include "../src/title_page_watch.h" | 23 | #include "../src/title_page_watch.h" |
| 23 | #include "xmem.h" | 24 | #include "xmem.h" |
| @@ -1613,6 +1614,259 @@ void test_extended(Env& env) { | |||
| 1613 | q->Release(); | 1614 | q->Release(); |
| 1614 | } | 1615 | } |
| 1615 | 1616 | ||
| 1617 | // A queue half full submits itself, but a read into physical pages and everything behind it wait for Submit: the | ||
| 1618 | // title may fill the page list right before its own Submit. Until then the list names no page (the read would | ||
| 1619 | // fail) or the page its slot named before (the data would land in a page that belongs to something else). The two | ||
| 1620 | // cases of Marvisak/VIctory eddde73, then the ways a hold ends without Submit. | ||
| 1621 | void test_page_reads_wait_for_submit(Env& env) { | ||
| 1622 | const auto alloc = reinterpret_cast<BOOL(WINAPI*)(uint64_t,uint64_t*,uint64_t*)>( | ||
| 1623 | rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")); | ||
| 1624 | const auto reserve = reinterpret_cast<void*(WINAPI*)(void*,SIZE_T,DWORD,uint64_t,DWORD)>( | ||
| 1625 | rt::shims::find("xmem.dll", "XMemVirtualAlloc")); | ||
| 1626 | const auto map = reinterpret_cast<void*(WINAPI*)(void*,uint64_t,const uint64_t*)>( | ||
| 1627 | rt::shims::find("xmem.dll", "XMemMapPhysicalPages")); | ||
| 1628 | const auto free_pages = reinterpret_cast<BOOL(WINAPI*)(uint64_t,const uint64_t*)>( | ||
| 1629 | rt::shims::find("xmem.dll", "XMemFreePhysicalPages")); | ||
| 1630 | uint64_t pages[2]{}, count = 2; | ||
| 1631 | constexpr size_t page = 65536, bytes = 4096; | ||
| 1632 | auto* window = static_cast<uint8_t*>(reserve(nullptr, 2*page, MEM_RESERVE | 0x20400000, 0x21, PAGE_READWRITE)); | ||
| 1633 | const bool allocated = window && alloc(0x280, &count, pages); | ||
| 1634 | const bool mapped = allocated && map(window, 2, pages) == window; | ||
| 1635 | check(mapped, "two physical pages mapped for the held reads"); | ||
| 1636 | if (!mapped) { | ||
| 1637 | if (allocated) free_pages(count, pages); | ||
| 1638 | if (window) VirtualFree(window, 0, MEM_RELEASE); | ||
| 1639 | return; | ||
| 1640 | } | ||
| 1641 | auto& h = leonida::dstorage::hold_stats(); | ||
| 1642 | const auto plain = pattern(bytes, 9); | ||
| 1643 | const auto into_pages = [&](ULONG_PTR* list) { | ||
| 1644 | DSTORAGE_REQUEST r{}; | ||
| 1645 | r.Options.AsUINT64 = options::kSourceMemory | options::kDestinationPages; | ||
| 1646 | r.DestinationPageArray = list; | ||
| 1647 | r.DestinationPageOffset = 0; | ||
| 1648 | r.Source = plain.data(); | ||
| 1649 | r.SourceSize = r.DestinationSize = static_cast<uint32_t>(bytes); | ||
| 1650 | return r; | ||
| 1651 | }; | ||
| 1652 | const auto into_buffer = [&](uint8_t* out) { | ||
| 1653 | DSTORAGE_REQUEST r{}; | ||
| 1654 | r.Options.AsUINT64 = options::kSourceMemory; | ||
| 1655 | r.Destination = out; | ||
| 1656 | r.Source = plain.data(); | ||
| 1657 | r.SourceSize = r.DestinationSize = 16; | ||
| 1658 | return r; | ||
| 1659 | }; | ||
| 1660 | const auto zero = [&](const uint8_t* at, size_t n) { return std::all_of(at, at + n, [](uint8_t b) { return b == 0; }); }; | ||
| 1661 | const auto holds_plain = [&](const uint8_t* at, size_t n) { return std::memcmp(at, plain.data(), n) == 0; }; | ||
| 1662 | const auto errors = [&] { | ||
| 1663 | DSTORAGE_STATS stats{}; | ||
| 1664 | env.factory->GetStats(&stats); | ||
| 1665 | return stats.ErrorCount; | ||
| 1666 | }; | ||
| 1667 | constexpr int kHalf = 0x40; // of a capacity of 0x80 | ||
| 1668 | std::vector<uint8_t> outs(kHalf * 16); | ||
| 1669 | const auto reset = [&] { | ||
| 1670 | std::memset(window, 0, 2*page); | ||
| 1671 | std::fill(outs.begin(), outs.end(), uint8_t{0}); | ||
| 1672 | }; | ||
| 1673 | |||
| 1674 | // The list still names the slot's previous page when the queue submits itself, the right one by Submit. | ||
| 1675 | { | ||
| 1676 | reset(); | ||
| 1677 | auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); | ||
| 1678 | auto* status = make_status(env, 1); | ||
| 1679 | const uint64_t self = h.self_submits.load(), held = h.held_reads.load(), failed = errors(); | ||
| 1680 | ULONG_PTR list[] = {static_cast<ULONG_PTR>(pages[0])}; | ||
| 1681 | DSTORAGE_REQUEST r = into_buffer(outs.data()); | ||
| 1682 | q->EnqueueRequest(&r); | ||
| 1683 | r = into_pages(list); | ||
| 1684 | q->EnqueueRequest(&r); | ||
| 1685 | for (int i = 2; i < kHalf; ++i) { | ||
| 1686 | r = into_buffer(outs.data() + i * 16); | ||
| 1687 | q->EnqueueRequest(&r); // the last one makes half the capacity | ||
| 1688 | } | ||
| 1689 | check(wait_until([&] { return holds_plain(outs.data(), 16); }), | ||
| 1690 | "the entry ahead of a read into pages starts when the queue submits itself"); | ||
| 1691 | Sleep(50); // time for an early read to land in the old page | ||
| 1692 | check(zero(window, bytes), "a self-submit does not write the page the list named before the title's Submit"); | ||
| 1693 | check(zero(outs.data() + 2 * 16, 16), "entries behind a held read keep their place"); | ||
| 1694 | check(h.self_submits.load() == self + 1 && h.held_reads.load() == held + 1, | ||
| 1695 | "one self-submit and one held read are counted"); | ||
| 1696 | DSTORAGE_QUEUE_INFO info{}; | ||
| 1697 | q->Query(&info); | ||
| 1698 | check(info.EmptySlotCount == 0x7f - (kHalf - 1), | ||
| 1699 | "held entries still take their slots"); | ||
| 1700 | list[0] = static_cast<ULONG_PTR>(pages[1]); // the title fills its page table, then submits | ||
| 1701 | q->EnqueueStatus(status, 0); | ||
| 1702 | check_hr(status->GetHResult(0), E_PENDING, "a status behind a held read is pending"); | ||
| 1703 | q->Submit(); | ||
| 1704 | check(wait_complete(status, 0), "the held entries run at Submit"); | ||
| 1705 | check_hr(status->GetHResult(0), S_OK, "a read held for Submit succeeds"); | ||
| 1706 | check(holds_plain(window + page, bytes), "the read lands in the page its list names at Submit"); | ||
| 1707 | check(zero(window, bytes), "the page the list named before stays untouched"); | ||
| 1708 | bool all = true; | ||
| 1709 | for (int i = 2; i < kHalf; ++i) all = all && holds_plain(outs.data() + i * 16, 16); | ||
| 1710 | check(all, "every entry behind the held read ran"); | ||
| 1711 | check(errors() == failed, "no entry failed"); | ||
| 1712 | status->Release(); | ||
| 1713 | q->Release(); | ||
| 1714 | } | ||
| 1715 | |||
| 1716 | // The list is still empty when the queue submits itself: no failure, the read waits. | ||
| 1717 | { | ||
| 1718 | reset(); | ||
| 1719 | auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); | ||
| 1720 | auto* status = make_status(env, 1); | ||
| 1721 | const uint64_t page0 = h.page0_entries.load(), failed = errors(); | ||
| 1722 | ULONG_PTR list[] = {0}; | ||
| 1723 | DSTORAGE_REQUEST r = into_pages(list); | ||
| 1724 | q->EnqueueRequest(&r); | ||
| 1725 | for (int i = 1; i < kHalf; ++i) { | ||
| 1726 | r = into_buffer(outs.data() + i * 16); | ||
| 1727 | q->EnqueueRequest(&r); | ||
| 1728 | } | ||
| 1729 | Sleep(50); | ||
| 1730 | check(h.page0_entries.load() == page0 && errors() == failed, "an empty page list is not read before Submit"); | ||
| 1731 | list[0] = static_cast<ULONG_PTR>(pages[0]); | ||
| 1732 | q->EnqueueStatus(status, 0); | ||
| 1733 | q->Submit(); | ||
| 1734 | check(wait_complete(status, 0), "the read with a late page list completes"); | ||
| 1735 | check_hr(status->GetHResult(0), S_OK, "a page list filled before Submit is written"); | ||
| 1736 | check(holds_plain(window, bytes) && errors() == failed, "its bytes are in the page"); | ||
| 1737 | status->Release(); | ||
| 1738 | q->Release(); | ||
| 1739 | } | ||
| 1740 | |||
| 1741 | // A full queue: the title waits in an enqueue and cannot call Submit, so the held entries go. | ||
| 1742 | { | ||
| 1743 | reset(); | ||
| 1744 | auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); | ||
| 1745 | auto* status = make_status(env, 1); | ||
| 1746 | const uint64_t full = h.full_releases.load(); | ||
| 1747 | ULONG_PTR list[] = {static_cast<ULONG_PTR>(pages[1])}; | ||
| 1748 | constexpr int kMany = 200; | ||
| 1749 | std::vector<uint8_t> sink(kMany * 16); | ||
| 1750 | std::atomic<bool> done{false}; | ||
| 1751 | std::thread producer([&] { | ||
| 1752 | DSTORAGE_REQUEST r = into_pages(list); | ||
| 1753 | q->EnqueueRequest(&r); | ||
| 1754 | for (int i = 0; i < kMany; ++i) { | ||
| 1755 | r = into_buffer(sink.data() + i * 16); | ||
| 1756 | q->EnqueueRequest(&r); | ||
| 1757 | } | ||
| 1758 | q->EnqueueStatus(status, 0); | ||
| 1759 | done.store(true); | ||
| 1760 | }); | ||
| 1761 | check(wait_until([&] { return done.load(); }), "a full queue with held entries does not wait for Submit"); | ||
| 1762 | producer.join(); | ||
| 1763 | check(h.full_releases.load() == full + 1, "the full queue's release is counted"); | ||
| 1764 | q->Submit(); | ||
| 1765 | check(wait_complete(status, 0), "the full queue's entries complete"); | ||
| 1766 | check_hr(status->GetHResult(0), S_OK, "they succeed"); | ||
| 1767 | bool all = holds_plain(window + page, bytes); | ||
| 1768 | for (int i = 0; i < kMany; ++i) all = all && holds_plain(sink.data() + i * 16, 16); | ||
| 1769 | check(all, "every entry of the full queue has its bytes"); | ||
| 1770 | status->Release(); | ||
| 1771 | q->Release(); | ||
| 1772 | } | ||
| 1773 | |||
| 1774 | // A hold has a time limit: held entries go after LEONIDA_DSTORAGE_HOLD_MS without Submit, 2000 ms unless set. | ||
| 1775 | for (const wchar_t* limit : {static_cast<const wchar_t*>(nullptr), L"200"}) { | ||
| 1776 | reset(); | ||
| 1777 | SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", limit); | ||
| 1778 | auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); | ||
| 1779 | SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", nullptr); | ||
| 1780 | const uint64_t timed = h.timed_releases.load(); | ||
| 1781 | ULONG_PTR list[] = {static_cast<ULONG_PTR>(pages[0])}; | ||
| 1782 | const auto begin = std::chrono::steady_clock::now(); | ||
| 1783 | DSTORAGE_REQUEST r = into_pages(list); | ||
| 1784 | q->EnqueueRequest(&r); | ||
| 1785 | for (int i = 1; i < kHalf; ++i) { | ||
| 1786 | r = into_buffer(outs.data() + i * 16); | ||
| 1787 | q->EnqueueRequest(&r); | ||
| 1788 | } | ||
| 1789 | check(zero(window, bytes), "a hold with a time limit starts as a hold"); | ||
| 1790 | if (!limit) { | ||
| 1791 | Sleep(1000); | ||
| 1792 | check(zero(window, bytes), "the default limit is not over after a second"); | ||
| 1793 | } | ||
| 1794 | check(wait_until([&] { return holds_plain(window, bytes); }), | ||
| 1795 | limit ? "LEONIDA_DSTORAGE_HOLD_MS ends a hold" : "a hold ends by itself without the variable"); | ||
| 1796 | const auto waited = std::chrono::duration_cast<std::chrono::milliseconds>( | ||
| 1797 | std::chrono::steady_clock::now() - begin).count(); | ||
| 1798 | check(waited >= (limit ? 150 : 1900) && waited < (limit ? 2000 : 6000), | ||
| 1799 | limit ? "after about the 200 ms asked for" : "after about the default 2000 ms"); | ||
| 1800 | check(h.timed_releases.load() == timed + 1, "the timed release is counted"); | ||
| 1801 | q->Release(); | ||
| 1802 | } | ||
| 1803 | |||
| 1804 | // LEONIDA_DSTORAGE_HOLD_MS=0: no time limit, the entries wait for Submit. | ||
| 1805 | { | ||
| 1806 | reset(); | ||
| 1807 | SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", L"0"); | ||
| 1808 | auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); | ||
| 1809 | SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_MS", nullptr); | ||
| 1810 | auto* status = make_status(env, 1); | ||
| 1811 | const uint64_t timed = h.timed_releases.load(); | ||
| 1812 | ULONG_PTR list[] = {static_cast<ULONG_PTR>(pages[0])}; | ||
| 1813 | DSTORAGE_REQUEST r = into_pages(list); | ||
| 1814 | q->EnqueueRequest(&r); | ||
| 1815 | for (int i = 1; i < kHalf; ++i) { | ||
| 1816 | r = into_buffer(outs.data() + i * 16); | ||
| 1817 | q->EnqueueRequest(&r); | ||
| 1818 | } | ||
| 1819 | Sleep(2300); // past the default limit | ||
| 1820 | check(zero(window, bytes) && h.timed_releases.load() == timed, "with 0 a hold outlasts the default limit"); | ||
| 1821 | q->EnqueueStatus(status, 0); | ||
| 1822 | q->Submit(); | ||
| 1823 | check(wait_complete(status, 0) && holds_plain(window, bytes), "and ends at Submit"); | ||
| 1824 | status->Release(); | ||
| 1825 | q->Release(); | ||
| 1826 | } | ||
| 1827 | |||
| 1828 | // LEONIDA_DSTORAGE_HOLD_PAGES=0: the self-submit takes everything, as before. | ||
| 1829 | { | ||
| 1830 | reset(); | ||
| 1831 | SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_PAGES", L"0"); | ||
| 1832 | auto* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); | ||
| 1833 | SetEnvironmentVariableW(L"LEONIDA_DSTORAGE_HOLD_PAGES", nullptr); | ||
| 1834 | const uint64_t held = h.held_reads.load(); | ||
| 1835 | ULONG_PTR list[] = {static_cast<ULONG_PTR>(pages[1])}; | ||
| 1836 | DSTORAGE_REQUEST r = into_pages(list); | ||
| 1837 | q->EnqueueRequest(&r); | ||
| 1838 | for (int i = 1; i < kHalf; ++i) { | ||
| 1839 | r = into_buffer(outs.data() + i * 16); | ||
| 1840 | q->EnqueueRequest(&r); | ||
| 1841 | } | ||
| 1842 | check(wait_until([&] { return holds_plain(window + page, bytes); }), | ||
| 1843 | "LEONIDA_DSTORAGE_HOLD_PAGES=0 submits a read into pages with the rest"); | ||
| 1844 | check(h.held_reads.load() == held, "and holds nothing"); | ||
| 1845 | q->Release(); | ||
| 1846 | } | ||
| 1847 | |||
| 1848 | // A list that names page 0 when its data is written fails the entry and is counted. | ||
| 1849 | { | ||
| 1850 | auto* q = make_queue(env, 0x80, false, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); | ||
| 1851 | auto* status = make_status(env, 1); | ||
| 1852 | const uint64_t page0 = h.page0_entries.load(); | ||
| 1853 | ULONG_PTR list[] = {0}; | ||
| 1854 | DSTORAGE_REQUEST r = into_pages(list); | ||
| 1855 | q->EnqueueRequest(&r); | ||
| 1856 | q->EnqueueStatus(status, 0); | ||
| 1857 | q->Submit(); | ||
| 1858 | check(wait_complete(status, 0), "the read with an empty page list completes"); | ||
| 1859 | check_hr(status->GetHResult(0), E_INVALIDARG, "a page list naming page 0 at Submit fails its entry"); | ||
| 1860 | check(h.page0_entries.load() == page0 + 1, "the entry with page 0 in its list is counted"); | ||
| 1861 | status->Release(); | ||
| 1862 | q->Release(); | ||
| 1863 | } | ||
| 1864 | |||
| 1865 | map(window, 2, nullptr); | ||
| 1866 | free_pages(count, pages); | ||
| 1867 | VirtualFree(window, 0, MEM_RELEASE); | ||
| 1868 | } | ||
| 1869 | |||
| 1616 | } // namespace | 1870 | } // namespace |
| 1617 | 1871 | ||
| 1618 | int main() { | 1872 | int main() { |
| @@ -1668,6 +1922,7 @@ int main() { | |||
| 1668 | test_stats_timing(env); | 1922 | test_stats_timing(env); |
| 1669 | test_stats(env); | 1923 | test_stats(env); |
| 1670 | test_extended(env); | 1924 | test_extended(env); |
| 1925 | test_page_reads_wait_for_submit(env); | ||
| 1671 | test_guarded_destinations(env); | 1926 | test_guarded_destinations(env); |
| 1672 | test_zlib(env); // after test_stats, whose request totals it would change | 1927 | test_zlib(env); // after test_stats, whose request totals it would change |
| 1673 | 1928 | ||
diff --git a/runtime/test/gameinput_no_sdl_test.cpp b/runtime/test/gameinput_no_sdl_test.cpp index a131dc7c9..24a29f2a6 100644 --- a/runtime/test/gameinput_no_sdl_test.cpp +++ b/runtime/test/gameinput_no_sdl_test.cpp | |||
| @@ -98,8 +98,10 @@ Pad read_at(IGameInput* input, IGameInputDevice* device, double seconds) { | |||
| 98 | } | 98 | } |
| 99 | 99 | ||
| 100 | int scripted_pad(CreateFn create) { | 100 | int scripted_pad(CreateFn create) { |
| 101 | // Four presses (two overlapping A presses, Menu, a right-stick throw) and three rejected entries. | 101 | // Five presses (two overlapping A presses, Menu, B held 0.8 s, a right-stick throw) and seven rejected entries |
| 102 | SetEnvironmentVariableA("LEONIDA_INPUT_SCRIPT", "a@1, START@2.5 ,a@1.2,rsup@4,bogus@1,a@-1,"); | 102 | // (four of them holds that are zero, negative, missing or too long). |
| 103 | SetEnvironmentVariableA("LEONIDA_INPUT_SCRIPT", | ||
| 104 | "a@1, START@2.5 ,a@1.2,b@3:0.8 ,rsup@4,bogus@1,a@-1,,x@3:0,x@3:-1,x@3:,x@3:601"); | ||
| 103 | rt::gameinput_no_sdl::set_clock(fake_clock); | 105 | rt::gameinput_no_sdl::set_clock(fake_clock); |
| 104 | at(0); | 106 | at(0); |
| 105 | 107 | ||
| @@ -201,6 +203,10 @@ int scripted_pad(CreateFn create) { | |||
| 201 | check(menu.buttons == GameInputGamepadMenu && menu.ui == GameInputUiNavigationMenu, | 203 | check(menu.buttons == GameInputGamepadMenu && menu.ui == GameInputUiNavigationMenu, |
| 202 | "script: START (any case) holds Menu at 2.6 s"); | 204 | "script: START (any case) holds Menu at 2.6 s"); |
| 203 | check(read_at(input, device, 2.85).buttons == 0, "script: Menu is released at 2.85 s"); | 205 | check(read_at(input, device, 2.85).buttons == 0, "script: Menu is released at 2.85 s"); |
| 206 | check(read_at(input, device, 3.05).buttons == GameInputGamepadB, "script: b@3:0.8 holds B at 3.05 s"); | ||
| 207 | check(read_at(input, device, 3.7).buttons == GameInputGamepadB, | ||
| 208 | "script: B is still held at 3.7 s, past the 0.3 s default"); | ||
| 209 | check(read_at(input, device, 3.85).buttons == 0, "script: B is released after its 0.8 s hold"); | ||
| 204 | const Pad up = read_at(input, device, 4.1); | 210 | const Pad up = read_at(input, device, 4.1); |
| 205 | check(up.buttons == 0 && up.right_y == 1.0f && up.ui == GameInputUiNavigationScrollUp, | 211 | check(up.buttons == 0 && up.right_y == 1.0f && up.ui == GameInputUiNavigationScrollUp, |
| 206 | "script: rsup throws the right stick up at 4.1 s"); | 212 | "script: rsup throws the right stick up at 4.1 s"); |
diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp index be9dc5398..09d959f34 100644 --- a/runtime/test/gameinput_test.cpp +++ b/runtime/test/gameinput_test.cpp | |||
| @@ -1718,10 +1718,12 @@ int main(int argc, char** argv) { | |||
| 1718 | check(create(&input) == S_OK && input, "GameInputCreate returns an instance"); | 1718 | check(create(&input) == S_OK && input, "GameInputCreate returns an instance"); |
| 1719 | if (argc == 2 && std::strcmp(argv[1], "--input-script") == 0) { | 1719 | if (argc == 2 && std::strcmp(argv[1], "--input-script") == 0) { |
| 1720 | if (!input) return 1; | 1720 | if (!input) return 1; |
| 1721 | // Only the X after byte 63 is due now. Its later entry must not cancel it. | 1721 | // Only the X after byte 63 and the Y held 0.6 s are due now. X's later entry must not cancel it; the |
| 1722 | // malformed holds at the end hold nothing. | ||
| 1722 | set_env("LEONIDA_INPUT_SCRIPT", | 1723 | set_env("LEONIDA_INPUT_SCRIPT", |
| 1723 | "start@3600,start@3600,start@3600,start@3600,start@3600,start@3600, X@0 \t,x@3600," | 1724 | "start@3600,start@3600,start@3600,start@3600,start@3600,start@3600, X@0 \t,x@3600," |
| 1724 | "unknown@0,a@,a@x,,a@-0.1,a@nan,a@inf,a@1e999,a@0tail, ,"); | 1725 | "unknown@0,a@,a@x,,a@-0.1,a@nan,a@inf,a@1e999,a@0tail, ,y@0:0.6," |
| 1726 | "a@0:0,a@0:-1,a@0:,a@0:x,a@0:inf,a@0:601,a@0:1tail"); | ||
| 1725 | set_env("LEONIDA_KEYBOARD_PAD", "1"); | 1727 | set_env("LEONIDA_KEYBOARD_PAD", "1"); |
| 1726 | rt::gameinput::set_keyboard_source(fake_key_down, fake_focus); | 1728 | rt::gameinput::set_keyboard_source(fake_key_down, fake_focus); |
| 1727 | rt::gameinput::set_cursor_source(fake_cursor); | 1729 | rt::gameinput::set_cursor_source(fake_cursor); |
| @@ -1730,27 +1732,32 @@ int main(int argc, char** argv) { | |||
| 1730 | rt::gameinput::reload_config(); | 1732 | rt::gameinput::reload_config(); |
| 1731 | rt::gameinput::poll(); | 1733 | rt::gameinput::poll(); |
| 1732 | const auto buttons = pad_state(input, nullptr).buttons; | 1734 | const auto buttons = pad_state(input, nullptr).buttons; |
| 1733 | const auto expected = GameInputGamepadX | GameInputGamepadB; | 1735 | const auto expected = GameInputGamepadX | GameInputGamepadB | GameInputGamepadY; |
| 1734 | check((buttons & expected) == expected, "long script: the spaced X after byte 63 and the physical B are held"); | 1736 | check((buttons & expected) == expected, |
| 1737 | "long script: the spaced X after byte 63, the held Y and the physical B are held"); | ||
| 1735 | check((buttons & ~expected) == 0, "malformed script entries hold no extra buttons"); | 1738 | check((buttons & ~expected) == 0, "malformed script entries hold no extra buttons"); |
| 1736 | g_focus = false; | 1739 | g_focus = false; |
| 1737 | set_env("LEONIDA_INPUT_SCRIPT", "y@0"); | 1740 | set_env("LEONIDA_INPUT_SCRIPT", "y@0"); |
| 1738 | rt::gameinput::reload_config(); | 1741 | rt::gameinput::reload_config(); |
| 1739 | rt::gameinput::poll(); | 1742 | rt::gameinput::poll(); |
| 1740 | check(pad_state(input, nullptr).buttons == GameInputGamepadX, | 1743 | check(pad_state(input, nullptr).buttons == (GameInputGamepadX | GameInputGamepadY), |
| 1741 | "scripted X survives focus loss; reload does not replace it with Y"); | 1744 | "scripted X and Y survive focus loss; reload does not replace the script with y@0"); |
| 1742 | Sleep(350); | 1745 | Sleep(350); |
| 1743 | g_focus = true; | 1746 | g_focus = true; |
| 1744 | rt::gameinput::poll(); | 1747 | 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 | 1748 | // A scripted press lasts its hold (300 ms, or button@seconds:hold) and then until the title has read the pads |
| 1746 | // (update_keyboard_pad: kReads, at most kMaxHold seconds), so a title that polls slowly still sees it. Each | 1749 | // six times since it began (update_keyboard_pad: kReads), 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. | 1750 | // pad_state() is one GetCurrentReading, and this is the third since X and Y began. |
| 1748 | check(pad_state(input, nullptr).buttons == (GameInputGamepadX | GameInputGamepadB), | 1751 | check(pad_state(input, nullptr).buttons == (GameInputGamepadX | GameInputGamepadB | GameInputGamepadY), |
| 1749 | "long script: past its 300 ms the press is still held while the title has read the pads fewer than six times"); | 1752 | "long script: past its 300 ms X 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); | 1753 | for (int i = 0; i < 6; ++i) pad_state(input, nullptr); |
| 1751 | rt::gameinput::poll(); | 1754 | rt::gameinput::poll(); |
| 1755 | check(pad_state(input, nullptr).buttons == (GameInputGamepadB | GameInputGamepadY), | ||
| 1756 | "long script: X ends once the title has read it, y@0:0.6 is still held for its time, the key stays held"); | ||
| 1757 | Sleep(400); | ||
| 1758 | rt::gameinput::poll(); | ||
| 1752 | check(pad_state(input, nullptr).buttons == GameInputGamepadB, | 1759 | check(pad_state(input, nullptr).buttons == GameInputGamepadB, |
| 1753 | "long script: the timed press ends once the title has read it, while the physical key stays held"); | 1760 | "long script: Y is released after its 0.6 s hold, the title having read it six times"); |
| 1754 | input->Release(); | 1761 | input->Release(); |
| 1755 | std::printf("%d checks, %d failures\n", g_checks, g_failures); | 1762 | std::printf("%d checks, %d failures\n", g_checks, g_failures); |
| 1756 | return g_failures ? 1 : 0; | 1763 | return g_failures ? 1 : 0; |
diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp index caac93dc0..d1e9a07d8 100644 --- a/runtime/test/geometry_views_test.cpp +++ b/runtime/test/geometry_views_test.cpp | |||
| @@ -16,7 +16,10 @@ | |||
| 16 | // 13. a submission's sequence on an idle GPU (completed == submitted): a view retired by the drain in before_execute_ | 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 | 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 | 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. | 19 | // (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device; |
| 20 | // 14. LEONIDA_GEOMETRY_HOST picks a system-memory type (write-back for 1, write-combined for 2), never the BAR; | ||
| 21 | // 15. a retired view is copied once more from its pages when they are readable (a remap), not when they are not; | ||
| 22 | // 16. a full release queue joins touching ranges before it collapses to one covering range. | ||
| 20 | #include <windows.h> | 23 | #include <windows.h> |
| 21 | 24 | ||
| 22 | #include <cstdint> | 25 | #include <cstdint> |
| @@ -61,7 +64,7 @@ VKAPI_ATTR void VKAPI_CALL requirements(VkDevice, VkBuffer buffer, VkMemoryRequi | |||
| 61 | *out = {}; | 64 | *out = {}; |
| 62 | out->size = reinterpret_cast<FakeBuffer*>(buffer)->size; | 65 | out->size = reinterpret_cast<FakeBuffer*>(buffer)->size; |
| 63 | out->alignment = 65536; | 66 | out->alignment = 65536; |
| 64 | out->memoryTypeBits = 1; | 67 | out->memoryTypeBits = 0xf; // the four types of test 14's device |
| 65 | } | 68 | } |
| 66 | VKAPI_ATTR VkResult VKAPI_CALL bind(VkDevice, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize) { | 69 | VKAPI_ATTR VkResult VKAPI_CALL bind(VkDevice, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize) { |
| 67 | reinterpret_cast<FakeBuffer*>(buffer)->memory = memory; | 70 | reinterpret_cast<FakeBuffer*>(buffer)->memory = memory; |
| @@ -510,6 +513,109 @@ int main() { | |||
| 510 | } | 513 | } |
| 511 | VirtualFree(fly_title, 0, MEM_RELEASE); | 514 | VirtualFree(fly_title, 0, MEM_RELEASE); |
| 512 | 515 | ||
| 516 | // 14. LEONIDA_GEOMETRY_HOST: the copies' memory type. A discrete GPU's types: 0 VRAM, 1 VRAM through the BAR, | ||
| 517 | // 2 system memory write-combined, 3 system memory write-back. 1 takes type 3 (write-back preferred), 2 type 2, | ||
| 518 | // unset any host-visible type with device-local preferred (the BAR); a device whose host-visible types are all | ||
| 519 | // device-local (an integrated GPU) keeps them all. | ||
| 520 | { | ||
| 521 | struct TypedDevice : FakeDevice { | ||
| 522 | VkPhysicalDeviceMemoryProperties memory{}; | ||
| 523 | std::uint32_t bits = 0; | ||
| 524 | VkMemoryPropertyFlags preferred = 0; | ||
| 525 | VkDeviceMemory allocate(const VkMemoryRequirements& r, VkMemoryPropertyFlags required, | ||
| 526 | VkMemoryPropertyFlags wanted, VkMemoryPropertyFlags* chosen, bool address) { | ||
| 527 | bits = r.memoryTypeBits; | ||
| 528 | preferred = wanted; | ||
| 529 | return FakeDevice::allocate(r, required, wanted, chosen, address); | ||
| 530 | } | ||
| 531 | }; | ||
| 532 | constexpr VkMemoryPropertyFlags kLocal = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, | ||
| 533 | kHost = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | | ||
| 534 | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, | ||
| 535 | kCached = VK_MEMORY_PROPERTY_HOST_CACHED_BIT; | ||
| 536 | TypedDevice discrete; | ||
| 537 | discrete.memory.memoryTypeCount = 4; | ||
| 538 | const VkMemoryPropertyFlags discrete_types[4] = {kLocal, kLocal | kHost, kHost, kHost | kCached}; | ||
| 539 | for (int i = 0; i < 4; ++i) discrete.memory.memoryTypes[i].propertyFlags = discrete_types[i]; | ||
| 540 | TypedDevice integrated; | ||
| 541 | integrated.memory.memoryTypeCount = 2; | ||
| 542 | integrated.memory.memoryTypes[0].propertyFlags = kLocal; | ||
| 543 | integrated.memory.memoryTypes[1].propertyFlags = kLocal | kHost | kCached; | ||
| 544 | auto* host_title = | ||
| 545 | static_cast<std::uint8_t*>(VirtualAlloc(nullptr, kView, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); | ||
| 546 | if (!host_title) return 1; | ||
| 547 | const auto hbase = reinterpret_cast<std::uintptr_t>(host_title); | ||
| 548 | const auto made_with = [&](TypedDevice& dev, const char* setting) { | ||
| 549 | _putenv_s("LEONIDA_GEOMETRY_HOST", setting); | ||
| 550 | dev.bits = ~0u; | ||
| 551 | dev.preferred = 0; | ||
| 552 | rt::d3d12::GeometryViews v; | ||
| 553 | const bool made = v.resolve(dev, hbase, kView, copy) != 0; | ||
| 554 | const int kind = v.system_memory(); | ||
| 555 | v.release(dev); | ||
| 556 | return made ? kind : -1; | ||
| 557 | }; | ||
| 558 | check(made_with(discrete, "1") == rt::d3d12::TitleBufferWindows::kSystemCached && discrete.bits == 1u << 3 && | ||
| 559 | discrete.preferred == kCached, | ||
| 560 | "LEONIDA_GEOMETRY_HOST=1 puts the copies in write-back system memory, never the BAR"); | ||
| 561 | check(made_with(discrete, "2") == rt::d3d12::TitleBufferWindows::kSystemUncached && discrete.bits == 1u << 2 && | ||
| 562 | discrete.preferred == 0, | ||
| 563 | "LEONIDA_GEOMETRY_HOST=2 puts them in write-combined system memory"); | ||
| 564 | check(made_with(discrete, "") == rt::d3d12::TitleBufferWindows::kDeviceLocal && discrete.bits == 0xfu && | ||
| 565 | discrete.preferred == kLocal, | ||
| 566 | "unset, every type the buffer allows is tried, device-local first"); | ||
| 567 | check(made_with(integrated, "1") == rt::d3d12::TitleBufferWindows::kSystemCached && integrated.bits == 0xfu, | ||
| 568 | "on a device with no host type outside device-local memory, the types are left as they are"); | ||
| 569 | _putenv_s("LEONIDA_GEOMETRY_HOST", ""); | ||
| 570 | check(g_live_buffers == 0, "the memory-type views free their blocks"); | ||
| 571 | |||
| 572 | // 15. A retired view is copied once more from the title's pages when they are readable (a remap gave them new | ||
| 573 | // bytes), and keeps what it held when they are not (freed or unmapped). | ||
| 574 | rt::d3d12::GeometryViews last; | ||
| 575 | std::memset(host_title, 0x11, kView); | ||
| 576 | const std::uint64_t va_l = last.resolve(device, hbase, kView, copy); | ||
| 577 | std::uint64_t host_l = 0, bytes_l = 0; | ||
| 578 | check(va_l && last.lookup(device.arena.address + va_l, host_l, bytes_l), "a view to retire"); | ||
| 579 | auto* held = reinterpret_cast<const std::uint8_t*>(host_l); | ||
| 580 | // The remapped pages' bytes: the watched tiles are opened first (no fault handler here). | ||
| 581 | leonida::geometry_writes::notify(hbase, hbase + kView, leonida::geometry_writes::Event::open); | ||
| 582 | std::memset(host_title, 0x22, kView); | ||
| 583 | g_copies.clear(); | ||
| 584 | check(last.retire_range(hbase, hbase + kView, 1, [](std::uintptr_t, std::size_t, VkDeviceSize) {}, copy) == 1 && | ||
| 585 | held[0] == 0x22 && held[kView - 1] == 0x22 && last.final_copies() == 1 && g_copies.size() == 1, | ||
| 586 | "a retired view whose pages are readable is copied from them once more"); | ||
| 587 | const std::uint64_t va_l2 = last.resolve(device, hbase, kView, copy); | ||
| 588 | std::uint64_t host_l2 = 0; | ||
| 589 | check(va_l2 && last.lookup(device.arena.address + va_l2, host_l2, bytes_l), "and made again"); | ||
| 590 | auto* held2 = reinterpret_cast<const std::uint8_t*>(host_l2); | ||
| 591 | leonida::geometry_writes::notify(hbase, hbase + kView, leonida::geometry_writes::Event::open); | ||
| 592 | std::memset(host_title, 0x33, kView); | ||
| 593 | const auto unreadable = [](std::uint8_t*, const std::uint8_t*, std::size_t) { | ||
| 594 | return rt::d3d12::GeometryCopy::unreadable; | ||
| 595 | }; | ||
| 596 | check(last.retire_range(hbase, hbase + kView, 2, [](std::uintptr_t, std::size_t, VkDeviceSize) {}, | ||
| 597 | unreadable) == 1 && | ||
| 598 | held2[0] == 0x22 && last.final_copies() == 1, | ||
| 599 | "one whose pages are not readable keeps what it held"); | ||
| 600 | check(last.reap(device, 2) == 2 && last.bytes() == 0, "both are freed at their tickets"); | ||
| 601 | last.release(device); | ||
| 602 | |||
| 603 | // 16. A full release queue first joins ranges that touch (remaps report page runs): 65536 neighbouring ranges | ||
| 604 | // and one apart from them are two ranges, not one covering everything between them. | ||
| 605 | rt::d3d12::GeometryViews coalesce; | ||
| 606 | check(coalesce.resolve(device, hbase, kView, copy) != 0, "a view to watch the pages"); | ||
| 607 | for (std::size_t i = 0; i < 65536; ++i) | ||
| 608 | leonida::geometry_writes::note_released(hbase + i * 8, hbase + i * 8 + 8); | ||
| 609 | leonida::geometry_writes::note_released(hbase + kView - 4096, hbase + kView); | ||
| 610 | std::vector<std::pair<std::uintptr_t, std::uintptr_t>> joined; | ||
| 611 | leonida::geometry_writes::take_released(coalesce.release_queue(), joined); | ||
| 612 | check(joined.size() == 2 && joined[0] == std::make_pair(hbase, hbase + 65536 * 8) && | ||
| 613 | joined[1] == std::make_pair(hbase + kView - 4096, hbase + kView), | ||
| 614 | "65536 touching ranges become one, and a range apart from them stays apart"); | ||
| 615 | coalesce.release(device); | ||
| 616 | VirtualFree(host_title, 0, MEM_RELEASE); | ||
| 617 | } | ||
| 618 | |||
| 513 | std::printf("%d checks, %d failures\n", g_checks, g_failures); | 619 | std::printf("%d checks, %d failures\n", g_checks, g_failures); |
| 514 | return g_failures ? 1 : 0; | 620 | return g_failures ? 1 : 0; |
| 515 | } | 621 | } |
diff --git a/runtime/test/heavy_pipeline_cache_test.cpp b/runtime/test/heavy_pipeline_cache_test.cpp new file mode 100644 index 000000000..8181a047c --- /dev/null +++ b/runtime/test/heavy_pipeline_cache_test.cpp | |||
| @@ -0,0 +1,109 @@ | |||
| 1 | // src/heavy_pipeline_cache.h: the LEONIDA_HEAVY_PIPELINE_CACHE_MS threshold and when the heavy cache is written. | ||
| 2 | // No Vulkan, no GPU, no files. | ||
| 3 | #include "../src/heavy_pipeline_cache.h" | ||
| 4 | |||
| 5 | #include <cstdio> | ||
| 6 | #include <initializer_list> | ||
| 7 | |||
| 8 | #define CHECK(condition) do { \ | ||
| 9 | if (!(condition)) { \ | ||
| 10 | std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ | ||
| 11 | return 1; \ | ||
| 12 | } \ | ||
| 13 | } while (0) | ||
| 14 | |||
| 15 | namespace heavy = leonida::heavy_pipeline_cache; | ||
| 16 | |||
| 17 | static int test_threshold() { | ||
| 18 | CHECK(heavy::parse_threshold(nullptr).ms == heavy::default_threshold_ms); | ||
| 19 | CHECK(heavy::parse_threshold("").ms == heavy::default_threshold_ms); | ||
| 20 | CHECK(heavy::parse_threshold("0").ms == 0 && heavy::parse_threshold("0").valid); // off | ||
| 21 | CHECK(heavy::parse_threshold("2000").ms == 2000); | ||
| 22 | CHECK(heavy::parse_threshold("0750").ms == 750); | ||
| 23 | // Not a number, a sign, a unit or an absurd value: the default, reported as invalid. | ||
| 24 | for (const char* bad : {"-1", "+5", "1s", "1.5", "abc", "3600001", "99999999999999999999"}) { | ||
| 25 | const auto t = heavy::parse_threshold(bad); | ||
| 26 | CHECK(!t.valid && t.ms == heavy::default_threshold_ms); | ||
| 27 | } | ||
| 28 | CHECK(heavy::parse_threshold("3600000").valid); | ||
| 29 | return 0; | ||
| 30 | } | ||
| 31 | |||
| 32 | static int test_schedule() { | ||
| 33 | using S = heavy::WriteSchedule; | ||
| 34 | S s; | ||
| 35 | CHECK(!s.dirty() && !s.due(1'000'000)); | ||
| 36 | // One heavy compile: written once it has settled. | ||
| 37 | s.note_heavy(1000); | ||
| 38 | CHECK(s.dirty() && !s.due(1000 + S::settle_ms - 1) && s.due(1000 + S::settle_ms)); | ||
| 39 | s.written(s.generation(), 1000 + S::settle_ms); | ||
| 40 | CHECK(!s.dirty()); | ||
| 41 | // A burst, one compile a second for a minute: the write does not wait for the burst to end. | ||
| 42 | S burst; | ||
| 43 | for (std::uint64_t t = 10'000; t <= 70'000; t += 1000) { | ||
| 44 | burst.note_heavy(t); | ||
| 45 | if (burst.due(t)) { | ||
| 46 | CHECK(t - 10'000 >= S::max_delay_ms); // first write no later than max_delay after the first compile | ||
| 47 | burst.written(burst.generation(), t); | ||
| 48 | break; | ||
| 49 | } | ||
| 50 | } | ||
| 51 | CHECK(!burst.dirty()); | ||
| 52 | // A compile that finishes while a write is running is not lost: the cache stays dirty for the next write. | ||
| 53 | S racing; | ||
| 54 | racing.note_heavy(5000); | ||
| 55 | const std::uint64_t start = 5000 + S::settle_ms; | ||
| 56 | const std::uint64_t taken = racing.generation(); | ||
| 57 | racing.note_heavy(start + 10); // during the write | ||
| 58 | racing.written(taken, start); | ||
| 59 | CHECK(racing.dirty()); | ||
| 60 | CHECK(racing.due(start + 10 + S::settle_ms)); | ||
| 61 | // The same, inside one tick of a coarse clock: the compile noted at the write's own start time is still kept. | ||
| 62 | S tick; | ||
| 63 | tick.note_heavy(9000); | ||
| 64 | const std::uint64_t at = 9000 + S::settle_ms; | ||
| 65 | const std::uint64_t before = tick.generation(); | ||
| 66 | tick.note_heavy(at); | ||
| 67 | tick.written(before, at); | ||
| 68 | CHECK(tick.dirty()); | ||
| 69 | return 0; | ||
| 70 | } | ||
| 71 | |||
| 72 | static int test_failed_write() { | ||
| 73 | using S = heavy::WriteSchedule; | ||
| 74 | S s; | ||
| 75 | s.note_heavy(1000); | ||
| 76 | std::uint64_t now = 1000 + S::settle_ms; | ||
| 77 | CHECK(s.due(now)); | ||
| 78 | // A failed write keeps the cache dirty and waits out the backoff before the next try. | ||
| 79 | s.failed(now); | ||
| 80 | CHECK(s.dirty() && s.failures() == 1); | ||
| 81 | CHECK(!s.due(now) && !s.due(now + S::retry_ms - 1) && s.due(now + S::retry_ms)); | ||
| 82 | // Failures in a row double the delay up to the cap, so a write that keeps failing does not spin. | ||
| 83 | std::uint64_t expect = S::retry_ms; | ||
| 84 | for (int i = 0; i < 12; ++i) { | ||
| 85 | now = s.due_ms(); | ||
| 86 | s.failed(now); | ||
| 87 | expect = expect * 2 > S::max_retry_ms ? S::max_retry_ms : expect * 2; | ||
| 88 | CHECK(s.due_ms() == now + expect); | ||
| 89 | } | ||
| 90 | CHECK(s.due_ms() - now == S::max_retry_ms); | ||
| 91 | // A heavy compile during the backoff does not bring the retry forward. | ||
| 92 | s.note_heavy(now + 1); | ||
| 93 | CHECK(!s.due(now + S::settle_ms + 1) && s.due(now + S::max_retry_ms)); | ||
| 94 | // A successful write clears the dirty flag and the backoff. | ||
| 95 | now = s.due_ms(); | ||
| 96 | s.written(s.generation(), now); | ||
| 97 | CHECK(!s.dirty() && s.failures() == 0); | ||
| 98 | s.note_heavy(now + 10); | ||
| 99 | CHECK(s.due(now + 10 + S::settle_ms)); | ||
| 100 | return 0; | ||
| 101 | } | ||
| 102 | |||
| 103 | int main() { | ||
| 104 | if (const int r = test_threshold()) return r; | ||
| 105 | if (const int r = test_schedule()) return r; | ||
| 106 | if (const int r = test_failed_write()) return r; | ||
| 107 | std::printf("heavy_pipeline_cache: threshold parsing, the write schedule and retries after a failed write\n"); | ||
| 108 | return 0; | ||
| 109 | } | ||
diff --git a/runtime/test/list_value_wait_budget_test.cpp b/runtime/test/list_value_wait_budget_test.cpp new file mode 100644 index 000000000..6bf9bfbf5 --- /dev/null +++ b/runtime/test/list_value_wait_budget_test.cpp | |||
| @@ -0,0 +1,348 @@ | |||
| 1 | // Portable CPU-only unit tests for runtime/src/list_value_wait_budget.h (RT-LIST-VALUE-WAIT-WORK-AWARE-TIMEOUT): | ||
| 2 | // work-aware timeout pausing, finite pause caps across all pause reasons (including releaser_busy and | ||
| 3 | // matching_producer), demoted-gate cap scaling, cycle detection across multi-queue write/gate chains, overwrite-aware | ||
| 4 | // write matching, action gates, and a mock Pump tick driver. No Windows, D3D12, or Vulkan headers; no game files. | ||
| 5 | #include "../src/list_value_wait_budget.h" | ||
| 6 | |||
| 7 | #include <climits> | ||
| 8 | #include <cstdio> | ||
| 9 | #include <vector> | ||
| 10 | |||
| 11 | #define CHECK(cond) do { \ | ||
| 12 | if (!(cond)) { \ | ||
| 13 | std::fprintf(stderr, "line %d: CHECK failed: %s\n", __LINE__, #cond); \ | ||
| 14 | return 1; \ | ||
| 15 | } \ | ||
| 16 | } while (0) | ||
| 17 | |||
| 18 | namespace { | ||
| 19 | |||
| 20 | constexpr bool test_met(std::uint32_t comparison, std::uint64_t value, std::uint64_t reference, bool wide) { | ||
| 21 | if (!wide) { | ||
| 22 | value &= 0xffffffffu; | ||
| 23 | reference &= 0xffffffffu; | ||
| 24 | } | ||
| 25 | switch (comparison) { | ||
| 26 | case 2: return value < reference; | ||
| 27 | case 3: return value == reference; | ||
| 28 | case 4: return value <= reference; | ||
| 29 | case 5: return value > reference; | ||
| 30 | case 6: return value != reference; | ||
| 31 | case 7: return value >= reference; | ||
| 32 | default: return true; | ||
| 33 | } | ||
| 34 | } | ||
| 35 | |||
| 36 | } // namespace | ||
| 37 | |||
| 38 | int main() { | ||
| 39 | using namespace leonida::list_value_wait; | ||
| 40 | |||
| 41 | int q1_tag = 0, q2_tag = 0, q3_tag = 0; | ||
| 42 | const void* const q1 = &q1_tag; | ||
| 43 | const void* const q2 = &q2_tag; | ||
| 44 | const void* const q3 = &q3_tag; | ||
| 45 | |||
| 46 | // 1. Idle unmodelled wait: PauseReason::none -> expires at exact budget_us. | ||
| 47 | { | ||
| 48 | const WaitPredicate waits[] = {{0x1000, 5, 7, true}}; // >= 5 | ||
| 49 | const PendingGate gates[] = {{q1, 1, false, waits}}; | ||
| 50 | CHECK(pause_reason(false, {}, gates, 0, test_met) == PauseReason::none); | ||
| 51 | |||
| 52 | GateTimeoutState t; | ||
| 53 | const PauseCaps caps = default_pause_caps(200, false); | ||
| 54 | t.reset(200'000, caps.active_us, caps.max_us); | ||
| 55 | CHECK(!t.advance(100'000, PauseReason::none)); | ||
| 56 | CHECK(t.elapsed_us == 100'000 && !t.paused_ever); | ||
| 57 | CHECK(!t.advance(99'999, PauseReason::none)); | ||
| 58 | CHECK(t.advance(1, PauseReason::none)); | ||
| 59 | CHECK(t.elapsed_us == 200'000); | ||
| 60 | } | ||
| 61 | |||
| 62 | // 2. Releaser actively executing held work pauses the timeout clock (covering multi-minute world-phase pipeline | ||
| 63 | // builds without burning idle budget), yet still expires at the finite max_pause_cap_us if a Signal hangs. | ||
| 64 | { | ||
| 65 | const WaitPredicate waits[] = {{0x1000, 5, 7, true}}; | ||
| 66 | const PendingGate gates[] = {{q1, 1, false, waits}}; | ||
| 67 | CHECK(pause_reason(true, {}, gates, 0, test_met) == PauseReason::releaser_busy); | ||
| 68 | |||
| 69 | GateTimeoutState t; | ||
| 70 | const PauseCaps caps = default_pause_caps(200, false); | ||
| 71 | CHECK(caps.active_us == 60'000'000ull && caps.max_us == 300'000'000ull); | ||
| 72 | t.reset(200'000, caps.active_us, caps.max_us); | ||
| 73 | // 120 seconds of releaser executing pipeline builds/copies burns 0 us of idle timeout budget. | ||
| 74 | for (int i = 0; i < 120; ++i) CHECK(!t.advance(1'000'000, PauseReason::releaser_busy)); | ||
| 75 | CHECK(t.elapsed_us == 0 && t.total_paused_us == 120'000'000ull && t.paused_ever); | ||
| 76 | // Once idle again, still gets its full 200 ms budget before expiring. | ||
| 77 | CHECK(!t.advance(199'000, PauseReason::none)); | ||
| 78 | CHECK(t.advance(1'000, PauseReason::none)); | ||
| 79 | |||
| 80 | // Hung Signal (releaser_busy forever) hits the finite max_pause_cap_us and then drains budget_us. | ||
| 81 | GateTimeoutState hung; | ||
| 82 | hung.reset(200'000, caps.active_us, caps.max_us); | ||
| 83 | for (int i = 0; i < 300; ++i) CHECK(!hung.advance(1'000'000, PauseReason::releaser_busy)); | ||
| 84 | CHECK(hung.total_paused_us == 300'000'000ull && hung.elapsed_us == 0); | ||
| 85 | CHECK(!hung.advance(199'000, PauseReason::releaser_busy)); | ||
| 86 | CHECK(hung.advance(1'000, PauseReason::releaser_busy)); | ||
| 87 | CHECK(hung.elapsed_us == 200'000); | ||
| 88 | } | ||
| 89 | |||
| 90 | // 3. Matching unblocked producer write on another queue (Wait-before-Signal) -> PauseReason::matching_producer. | ||
| 91 | { | ||
| 92 | const WaitPredicate waits[] = {{0x2000, 10, 7, true}}; // >= 10 | ||
| 93 | const PendingWrite w_ok[] = {{0x2000, 12, 8, false}}; | ||
| 94 | const PendingWriteGroup groups[] = {{q2, 0, w_ok}}; | ||
| 95 | const PendingGate gates[] = {{q1, 1, false, waits}}; | ||
| 96 | CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::matching_producer); | ||
| 97 | |||
| 98 | // Timestamp write to the same address also matches (final value unknown until landing). | ||
| 99 | const PendingWrite w_ts[] = {{0x2000, 0, 8, true}}; | ||
| 100 | const PendingWriteGroup ts_groups[] = {{q2, 0, w_ts}}; | ||
| 101 | CHECK(pause_reason(false, ts_groups, gates, 0, test_met) == PauseReason::matching_producer); | ||
| 102 | |||
| 103 | // Matching write overwritten later in the same WriteGroup by a non-matching value does NOT match, | ||
| 104 | // falling back to active_work (since q2's group is unblocked). | ||
| 105 | const PendingWrite w_overwritten[] = {{0x2000, 12, 8, false}, {0x2000, 3, 8, false}}; | ||
| 106 | const PendingWriteGroup ow_groups[] = {{q2, 0, w_overwritten}}; | ||
| 107 | CHECK(pause_reason(false, ow_groups, gates, 0, test_met) == PauseReason::active_work); | ||
| 108 | |||
| 109 | // Partial overlap by a later write in the same group invalidates the earlier matching write. | ||
| 110 | const PendingWrite w_partial[] = {{0x2000, 12, 8, false}, {0x2004, 0, 4, false}}; | ||
| 111 | const PendingWriteGroup part_groups[] = {{q2, 0, w_partial}}; | ||
| 112 | CHECK(pause_reason(false, part_groups, gates, 0, test_met) == PauseReason::active_work); | ||
| 113 | |||
| 114 | // 4-byte write cannot satisfy an 8-byte (wide) wait. | ||
| 115 | const PendingWrite w_narrow[] = {{0x2000, 12, 4, false}}; | ||
| 116 | const PendingWriteGroup nar_groups[] = {{q2, 0, w_narrow}}; | ||
| 117 | CHECK(pause_reason(false, nar_groups, gates, 0, test_met) == PauseReason::active_work); | ||
| 118 | |||
| 119 | // 8-byte write CAN satisfy a 4-byte wait (low 32 bits compared). | ||
| 120 | const WaitPredicate wait32[] = {{0x2000, 10, 7, false}}; | ||
| 121 | const PendingWrite w_hi_lo[] = {{0x2000, 0x100000000ull | 12ull, 8, false}}; | ||
| 122 | const PendingWriteGroup hilo_groups[] = {{q2, 0, w_hi_lo}}; | ||
| 123 | const PendingGate gates32[] = {{q1, 1, false, wait32}}; | ||
| 124 | CHECK(pause_reason(false, hilo_groups, gates32, 0, test_met) == PauseReason::matching_producer); | ||
| 125 | } | ||
| 126 | |||
| 127 | // 4. Same-queue ordering: a write submitted BEFORE the gate (after_gate < gate.value) IS a live producer; | ||
| 128 | // a write submitted AFTER the gate (after_gate >= gate.value) is a self-deadlock and MUST NOT pause the gate. | ||
| 129 | { | ||
| 130 | const WaitPredicate waits[] = {{0x3000, 1, 7, true}}; | ||
| 131 | const PendingWrite w[] = {{0x3000, 1, 8, false}}; | ||
| 132 | const PendingGate gates[] = {{q1, 2, false, waits}}; | ||
| 133 | |||
| 134 | const PendingWriteGroup before_gate[] = {{q1, 1, w}}; // after_gate 1 < gate.value 2 (unblocked!) | ||
| 135 | CHECK(pause_reason(false, before_gate, gates, 0, test_met) == PauseReason::matching_producer); | ||
| 136 | |||
| 137 | const PendingWriteGroup behind_gate[] = {{q1, 2, w}}; // after_gate 2 == gate.value 2 (held by itself!) | ||
| 138 | CHECK(pause_reason(false, behind_gate, gates, 0, test_met) == PauseReason::none); | ||
| 139 | } | ||
| 140 | |||
| 141 | // 5. Mutual 2-queue cycle (Q1 waits on Q2's write behind G2; Q2 waits on Q1's write behind G1): | ||
| 142 | // NEITHER gate pauses, so the cycle breaks cleanly instead of deadlocking. | ||
| 143 | { | ||
| 144 | const WaitPredicate w1[] = {{0x4000, 1, 7, true}}; | ||
| 145 | const WaitPredicate w2[] = {{0x5000, 1, 7, true}}; | ||
| 146 | const PendingWrite pw1[] = {{0x5000, 1, 8, false}}; // Q1 writes what Q2 waits for, behind Q1's gate 1 | ||
| 147 | const PendingWrite pw2[] = {{0x4000, 1, 8, false}}; // Q2 writes what Q1 waits for, behind Q2's gate 1 | ||
| 148 | const PendingWriteGroup groups[] = {{q1, 1, pw1}, {q2, 1, pw2}}; | ||
| 149 | const PendingGate gates[] = {{q1, 1, false, w1}, {q2, 1, false, w2}}; | ||
| 150 | CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::none); | ||
| 151 | CHECK(pause_reason(false, groups, gates, 1, test_met) == PauseReason::none); | ||
| 152 | } | ||
| 153 | |||
| 154 | // 6. 3-queue cycle involving a SECOND (non-front) gate on Q2: | ||
| 155 | // Q1 gate 1 waits on W2 (behind Q2 gates 1 & 2); Q2 gate 2 waits on W1 (behind Q1 gate 1). | ||
| 156 | // Checking all gates <= after_gate catches this indirect cycle! | ||
| 157 | { | ||
| 158 | const WaitPredicate w_q1[] = {{0x6000, 1, 7, true}}; | ||
| 159 | const WaitPredicate w_q2_g1[] = {{0x6100, 1, 7, true}}; // unrelated front gate on Q2 | ||
| 160 | const WaitPredicate w_q2_g2[] = {{0x6200, 1, 7, true}}; // second gate on Q2 waits on Q1 | ||
| 161 | const PendingWrite pw_q1[] = {{0x6200, 1, 8, false}}; // behind Q1 gate 1 | ||
| 162 | const PendingWrite pw_q2[] = {{0x6000, 1, 8, false}}; // behind Q2 gate 2 (after_gate = 2) | ||
| 163 | const PendingWriteGroup groups[] = {{q1, 1, pw_q1}, {q2, 2, pw_q2}}; | ||
| 164 | const PendingGate gates[] = { | ||
| 165 | {q1, 1, false, w_q1}, | ||
| 166 | {q2, 1, false, w_q2_g1}, | ||
| 167 | {q2, 2, false, w_q2_g2}, | ||
| 168 | }; | ||
| 169 | CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::none); | ||
| 170 | CHECK(pause_reason(false, groups, gates, 2, test_met) == PauseReason::none); | ||
| 171 | } | ||
| 172 | |||
| 173 | // 7. Acyclic 3-queue chain (Q1 -> Q2 -> Q3 where Q3's gate has no producer): | ||
| 174 | // Q3 does NOT pause (times out first), while Q2 and Q1 wait for their upstream producers to run in order! | ||
| 175 | { | ||
| 176 | const WaitPredicate w_q1[] = {{0x7000, 1, 7, true}}; | ||
| 177 | const WaitPredicate w_q2[] = {{0x7100, 1, 7, true}}; | ||
| 178 | const WaitPredicate w_q3[] = {{0x7200, 1, 7, true}}; // unmodelled wait on Q3 | ||
| 179 | const PendingWrite pw_q2[] = {{0x7000, 1, 8, false}}; // Q2 feeds Q1 (behind Q2 gate 1) | ||
| 180 | const PendingWrite pw_q3[] = {{0x7100, 1, 8, false}}; // Q3 feeds Q2 (behind Q3 gate 1) | ||
| 181 | const PendingWriteGroup groups[] = {{q2, 1, pw_q2}, {q3, 1, pw_q3}}; | ||
| 182 | const PendingGate gates[] = { | ||
| 183 | {q1, 1, false, w_q1}, | ||
| 184 | {q2, 1, false, w_q2}, | ||
| 185 | {q3, 1, false, w_q3}, | ||
| 186 | }; | ||
| 187 | CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::matching_producer); | ||
| 188 | CHECK(pause_reason(false, groups, gates, 1, test_met) == PauseReason::matching_producer); | ||
| 189 | CHECK(pause_reason(false, groups, gates, 2, test_met) == PauseReason::none); | ||
| 190 | } | ||
| 191 | |||
| 192 | // 8. Action gate on another queue counts as active_work when unblocked, and does NOT count when blocked behind a | ||
| 193 | // memory gate on its own queue. | ||
| 194 | { | ||
| 195 | const WaitPredicate w_q1[] = {{0x8000, 1, 7, true}}; | ||
| 196 | const WaitPredicate w_q2[] = {{0x8100, 1, 7, true}}; | ||
| 197 | const PendingGate unblocked_action[] = { | ||
| 198 | {q1, 1, false, w_q1}, | ||
| 199 | {q2, 1, true, {}}, // unblocked action gate on Q2 | ||
| 200 | }; | ||
| 201 | CHECK(pause_reason(false, {}, unblocked_action, 0, test_met) == PauseReason::active_work); | ||
| 202 | |||
| 203 | const PendingGate blocked_action[] = { | ||
| 204 | {q1, 1, false, w_q1}, | ||
| 205 | {q2, 1, false, w_q2}, // memory gate blocking Q2 | ||
| 206 | {q2, 2, true, {}}, // action gate behind Q2's memory gate | ||
| 207 | }; | ||
| 208 | CHECK(pause_reason(false, {}, blocked_action, 0, test_met) == PauseReason::none); | ||
| 209 | } | ||
| 210 | |||
| 211 | // 9. Bounded pause caps: active_work, matching_producer, releaser_busy, combined alternating reasons, and | ||
| 212 | // demoted-gate cap scaling. | ||
| 213 | { | ||
| 214 | CHECK(default_active_pause_cap_us(200) == 60'000'000ull); | ||
| 215 | CHECK(default_max_pause_cap_us(200) == 300'000'000ull); | ||
| 216 | CHECK(default_active_pause_cap_us(30) == 9'000'000ull); | ||
| 217 | CHECK(default_max_pause_cap_us(30) == 45'000'000ull); | ||
| 218 | CHECK(default_active_pause_cap_us(1) == 300'000ull); | ||
| 219 | CHECK(default_max_pause_cap_us(1) == 1'500'000ull); | ||
| 220 | CHECK(default_active_pause_cap_us(30000) == 600'000'000ull); | ||
| 221 | CHECK(default_max_pause_cap_us(30000) == 600'000'000ull); | ||
| 222 | CHECK(default_active_pause_cap_us(UINT_MAX) == 600'000'000ull); | ||
| 223 | CHECK(default_max_pause_cap_us(UINT_MAX) == 600'000'000ull); | ||
| 224 | |||
| 225 | // Demoted (cut_short) gates scale caps with their short 4 ms budget instead of inheriting 60 s / 300 s. | ||
| 226 | const PauseCaps dem = default_pause_caps(4, true); | ||
| 227 | CHECK(dem.active_us == 4'000ull && dem.max_us == 16'000ull); | ||
| 228 | GateTimeoutState dem_active; | ||
| 229 | dem_active.reset(4'000, dem.active_us, dem.max_us); | ||
| 230 | CHECK(!dem_active.advance(4'000, PauseReason::active_work)); // absorbs 4 ms cap | ||
| 231 | CHECK(dem_active.active_paused_us == 4'000 && dem_active.elapsed_us == 0); | ||
| 232 | CHECK(!dem_active.advance(3'999, PauseReason::active_work)); | ||
| 233 | CHECK(dem_active.advance(1, PauseReason::active_work)); // expires at 8 ms total, not 60 s! | ||
| 234 | |||
| 235 | GateTimeoutState dem_prod; | ||
| 236 | dem_prod.reset(4'000, dem.active_us, dem.max_us); | ||
| 237 | CHECK(!dem_prod.advance(16'000, PauseReason::matching_producer)); | ||
| 238 | CHECK(dem_prod.total_paused_us == 16'000 && dem_prod.elapsed_us == 0); | ||
| 239 | CHECK(dem_prod.advance(4'000, PauseReason::matching_producer)); // expires at 20 ms total | ||
| 240 | |||
| 241 | // Normal gate active_work cap (5 s) vs larger max cap (20 s). | ||
| 242 | GateTimeoutState t; | ||
| 243 | t.reset(200'000, 5'000'000, 20'000'000); | ||
| 244 | for (int i = 0; i < 5; ++i) CHECK(!t.advance(1'000'000, PauseReason::active_work)); | ||
| 245 | CHECK(t.active_paused_us == 5'000'000 && t.total_paused_us == 5'000'000 && t.elapsed_us == 0 && t.paused_ever); | ||
| 246 | CHECK(!t.advance(199'000, PauseReason::active_work)); | ||
| 247 | CHECK(t.advance(1'000, PauseReason::active_work)); | ||
| 248 | CHECK(t.elapsed_us == 200'000); | ||
| 249 | |||
| 250 | // Stuck matching_producer + alternating releaser_busy share total_paused_us <= max_pause_cap_us. | ||
| 251 | GateTimeoutState stuck; | ||
| 252 | stuck.reset(200'000, 2'000'000, 10'000'000); | ||
| 253 | CHECK(!stuck.advance(2'000'000, PauseReason::active_work)); // total = 2 s | ||
| 254 | CHECK(!stuck.advance(5'000'000, PauseReason::matching_producer)); // total = 7 s | ||
| 255 | CHECK(!stuck.advance(3'100'000, PauseReason::releaser_busy)); // 3 s paused (hits 10 s cap), 100 ms elapsed | ||
| 256 | CHECK(stuck.total_paused_us == 10'000'000 && stuck.elapsed_us == 100'000); | ||
| 257 | CHECK(!stuck.advance(99'999, PauseReason::matching_producer)); | ||
| 258 | CHECK(stuck.advance(1, PauseReason::matching_producer)); | ||
| 259 | CHECK(stuck.elapsed_us == 200'000); | ||
| 260 | |||
| 261 | // Partial step straddling active_pause_cap_us splits cleanly between active_paused_us and elapsed_us. | ||
| 262 | GateTimeoutState t2; | ||
| 263 | t2.reset(200'000, 500'000, 1'000'000); | ||
| 264 | CHECK(!t2.advance(600'000, PauseReason::active_work)); // 500k paused, 100k elapsed | ||
| 265 | CHECK(t2.active_paused_us == 500'000 && t2.total_paused_us == 500'000 && t2.elapsed_us == 100'000); | ||
| 266 | CHECK(t2.advance(100'000, PauseReason::active_work)); | ||
| 267 | |||
| 268 | // active_cap > max_cap is clamped to max_cap by reset(). | ||
| 269 | GateTimeoutState clamped; | ||
| 270 | clamped.reset(100'000, 9'000'000, 3'000'000); | ||
| 271 | CHECK(clamped.active_pause_cap_us == 3'000'000 && clamped.max_pause_cap_us == 3'000'000); | ||
| 272 | } | ||
| 273 | |||
| 274 | // 10. Overflow-safe address / dt_us guards and zero-dt paused tick. | ||
| 275 | { | ||
| 276 | const WaitPredicate overflow_wait[] = {{UINT64_MAX - 2, 1, 7, true}}; | ||
| 277 | const PendingWrite overflow_write[] = {{UINT64_MAX - 2, 1, 8, false}}; | ||
| 278 | const PendingWriteGroup groups[] = {{q2, 0, overflow_write}}; | ||
| 279 | const PendingGate gates[] = {{q1, 1, false, overflow_wait}}; | ||
| 280 | // Write doesn't match due to address wrap guard, falls back to active_work for the unblocked group. | ||
| 281 | CHECK(pause_reason(false, groups, gates, 0, test_met) == PauseReason::active_work); | ||
| 282 | |||
| 283 | GateTimeoutState t; | ||
| 284 | t.reset(1000, 0, 0); | ||
| 285 | CHECK(t.advance(UINT64_MAX, PauseReason::none)); | ||
| 286 | CHECK(t.elapsed_us == UINT64_MAX); | ||
| 287 | |||
| 288 | GateTimeoutState z; | ||
| 289 | z.reset(0, 1000, 1000); | ||
| 290 | CHECK(!z.advance(0, PauseReason::releaser_busy)); | ||
| 291 | CHECK(!z.paused_ever); | ||
| 292 | } | ||
| 293 | |||
| 294 | // 11. Mock Pump tick loop driving start_gate + pause_reason + GateTimeoutState end-to-end across 1 ms steps. | ||
| 295 | { | ||
| 296 | // (a) 200 ms gate held while releaser runs a 110 s pipeline build, then producer lands at 110.5 s: met! | ||
| 297 | const WaitPredicate waits[] = {{0x9000, 7, 7, true}}; | ||
| 298 | const PendingWrite prod_write[] = {{0x9000, 7, 8, false}}; | ||
| 299 | const PendingWriteGroup prod_groups[] = {{q2, 0, prod_write}}; | ||
| 300 | const PendingGate gates[] = {{q1, 1, false, waits}}; | ||
| 301 | |||
| 302 | GateTimeoutState gate; | ||
| 303 | const PauseCaps full_caps = default_pause_caps(200, false); | ||
| 304 | gate.reset(200'000, full_caps.active_us, full_caps.max_us); | ||
| 305 | for (int ms = 0; ms < 110'000; ++ms) { | ||
| 306 | const PauseReason r = pause_reason(true, prod_groups, gates, 0, test_met); | ||
| 307 | CHECK(r == PauseReason::releaser_busy && !gate.advance(1'000, r)); | ||
| 308 | } | ||
| 309 | for (int ms = 0; ms < 500; ++ms) { | ||
| 310 | const PauseReason r = pause_reason(false, prod_groups, gates, 0, test_met); | ||
| 311 | CHECK(r == PauseReason::matching_producer && !gate.advance(1'000, r)); | ||
| 312 | } | ||
| 313 | CHECK(gate.elapsed_us == 0 && gate.total_paused_us == 110'500'000ull); | ||
| 314 | |||
| 315 | // (b) Same gate with a matching producer stuck behind an untracked title fence wait: expires at 300.2 s! | ||
| 316 | GateTimeoutState stuck_gate; | ||
| 317 | stuck_gate.reset(200'000, full_caps.active_us, full_caps.max_us); | ||
| 318 | int expired_at_ms = -1; | ||
| 319 | for (int ms = 1; ms <= 305'000; ++ms) { | ||
| 320 | const PauseReason r = pause_reason(false, prod_groups, gates, 0, test_met); | ||
| 321 | if (stuck_gate.advance(1'000, r)) { | ||
| 322 | expired_at_ms = ms; | ||
| 323 | break; | ||
| 324 | } | ||
| 325 | } | ||
| 326 | CHECK(expired_at_ms == 300'200); | ||
| 327 | |||
| 328 | // (c) Demoted gate (4 ms budget) with continuous unrelated GPU work on q2: expires at 8 ms! | ||
| 329 | const PendingWrite unrelated[] = {{0xA000, 1, 8, false}}; | ||
| 330 | const PendingWriteGroup unrel_groups[] = {{q2, 0, unrelated}}; | ||
| 331 | GateTimeoutState dem_gate; | ||
| 332 | const PauseCaps dem_caps = default_pause_caps(4, true); | ||
| 333 | dem_gate.reset(4'000, dem_caps.active_us, dem_caps.max_us); | ||
| 334 | int dem_expired_ms = -1; | ||
| 335 | for (int ms = 1; ms <= 100; ++ms) { | ||
| 336 | const PauseReason r = pause_reason(false, unrel_groups, gates, 0, test_met); | ||
| 337 | CHECK(r == PauseReason::active_work); | ||
| 338 | if (dem_gate.advance(1'000, r)) { | ||
| 339 | dem_expired_ms = ms; | ||
| 340 | break; | ||
| 341 | } | ||
| 342 | } | ||
| 343 | CHECK(dem_expired_ms == 8); | ||
| 344 | } | ||
| 345 | |||
| 346 | std::printf("list_value_wait_budget_test: all checks passed\n"); | ||
| 347 | return 0; | ||
| 348 | } | ||
diff --git a/runtime/test/shaders/cs_address_guard.asm b/runtime/test/shaders/cs_address_guard.asm new file mode 100644 index 000000000..fad068a66 --- /dev/null +++ b/runtime/test/shaders/cs_address_guard.asm | |||
| @@ -0,0 +1,57 @@ | |||
| 1 | ; group: 1,1,1 | ||
| 2 | ; rsrc2: 0x8090 | ||
| 3 | ; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm | ||
| 4 | ; The address guard (rdna2spirv.py --address-guard; docs/d3d12_vulkan.md, "Address guard"). Translated with the guard, | ||
| 5 | ; run by scripts/run_address_guard_gpu_test.py on a 2 MiB heap whose page table (built by that script) backs the | ||
| 6 | ; arena (offsets below 0x80000, the header's limit) and the one 4 KiB page at 0x90000, and nothing else. The heap's | ||
| 7 | ; real memory continues past both, so every address below is inside the buffer: with the guard off the same program | ||
| 8 | ; reads and writes it, with the guard on the page table refuses the accesses outside 0x90000..0x90fff. Seeds: | ||
| 9 | ; 0x90000 0xa11ce000 0x90004 0xa11ce004 0x90ffc 0xf00df00d 0x91000 0xf00df00e | ||
| 10 | ; 0xa0000 0xbadbad00 0xa0004 0xbadbad04 0xa0008 0xbadbad08 | ||
| 11 | ; Words stored to out[0..7] with the guard on (off: the second value): | ||
| 12 | ; out[0] global_load_dword at 0x90000, a backed page outside the arena = 0xa11ce000 (0xa11ce000) | ||
| 13 | ; out[1] global_load_dword at 0xa0000, unbacked = 0 (0xbadbad00) | ||
| 14 | ; out[2] global_atomic_add glc at 0xa0008 with 1, unbacked: the old value = 0 (0xbadbad08) | ||
| 15 | ; out[3] global_load_dwordx2 at 0x90ffc: its last byte is on an unbacked page, so all of it is refused | ||
| 16 | ; = 0 (0xf00df00d) | ||
| 17 | ; out[4] its second dword = 0 (0xf00df00e) | ||
| 18 | ; out[5] buffer_load_dword through a V# built in SGPRs, base 0xa0000 = 0 (0xbadbad00) | ||
| 19 | ; out[6] s_load_dword at 0x90004, backed = 0xa11ce004 (0xa11ce004) | ||
| 20 | ; out[7] s_load_dword at 0xa0000, unbacked = 0 (0xbadbad00) | ||
| 21 | ; global_store_dword 0x5707 at 0xa0004 (unbacked) goes to the dump area (0x78004) instead, and the atomic to 0x78008; | ||
| 22 | ; the six refused accesses count themselves at header + 24 (0x70018) and the last one's offset is at 0x70020. | ||
| 23 | ; Run: VKC_HEAP_INIT=<heap> VKC_OUT_WORDS=524288 VKC_DUMP=<file> vk_compute_test cs_address_guard.spv 1 dump | ||
| 24 | v_mov_b32_e32 v0, 0x90000 | ||
| 25 | v_mov_b32_e32 v1, 0 | ||
| 26 | global_load_dword v2, v[0:1], off | ||
| 27 | v_mov_b32_e32 v0, 0xa0000 | ||
| 28 | global_load_dword v3, v[0:1], off | ||
| 29 | v_mov_b32_e32 v4, 0x5707 | ||
| 30 | global_store_dword v[0:1], v4, off offset:4 | ||
| 31 | v_mov_b32_e32 v5, 1 | ||
| 32 | global_atomic_add v5, v[0:1], v5, off offset:8 glc | ||
| 33 | v_mov_b32_e32 v0, 0x90ffc | ||
| 34 | global_load_dwordx2 v[6:7], v[0:1], off | ||
| 35 | s_mov_b32 s4, 0xa0000 | ||
| 36 | s_mov_b32 s5, 0 | ||
| 37 | s_mov_b32 s6, 0x100 | ||
| 38 | s_mov_b32 s7, 0x31016fac | ||
| 39 | v_mov_b32_e32 v8, 0 | ||
| 40 | buffer_load_dword v8, v8, s[4:7], 0 offen | ||
| 41 | s_mov_b32 s8, 0x90000 | ||
| 42 | s_mov_b32 s9, 0 | ||
| 43 | s_load_dword s10, s[8:9], 0x4 | ||
| 44 | s_load_dword s11, s[4:5], 0x0 | ||
| 45 | s_waitcnt vmcnt(0) lgkmcnt(0) | ||
| 46 | v_mov_b32_e32 v9, 0 | ||
| 47 | buffer_store_dword v2, v9, s[0:3], 0 offen | ||
| 48 | buffer_store_dword v3, v9, s[0:3], 0 offen offset:4 | ||
| 49 | buffer_store_dword v5, v9, s[0:3], 0 offen offset:8 | ||
| 50 | buffer_store_dword v6, v9, s[0:3], 0 offen offset:12 | ||
| 51 | buffer_store_dword v7, v9, s[0:3], 0 offen offset:16 | ||
| 52 | buffer_store_dword v8, v9, s[0:3], 0 offen offset:20 | ||
| 53 | v_mov_b32_e32 v10, s10 | ||
| 54 | buffer_store_dword v10, v9, s[0:3], 0 offen offset:24 | ||
| 55 | v_mov_b32_e32 v11, s11 | ||
| 56 | buffer_store_dword v11, v9, s[0:3], 0 offen offset:28 | ||
| 57 | s_endpgm | ||
diff --git a/runtime/test/title_memory_map_test.cpp b/runtime/test/title_memory_map_test.cpp index ba5a518a1..ff226d648 100644 --- a/runtime/test/title_memory_map_test.cpp +++ b/runtime/test/title_memory_map_test.cpp | |||
| @@ -7,7 +7,8 @@ | |||
| 7 | // 3. a reader further behind than the journal holds is told so (it then looks at everything); | 7 | // 3. a reader further behind than the journal holds is told so (it then looks at everything); |
| 8 | // 4. a change with no range overlaps every reader; | 8 | // 4. a change with no range overlaps every reader; |
| 9 | // 5. TextureReadability keeps a positive answer, when asked to, until a retry; | 9 | // 5. TextureReadability keeps a positive answer, when asked to, until a retry; |
| 10 | // 6. a pass over 20,000 waiting textures probes only those under the one mapped block. | 10 | // 6. a pass over 20,000 waiting textures probes only those under the one mapped block; |
| 11 | // 7. between passes, sync_map retries only when a map change overlaps the texture's footprint. | ||
| 11 | #include <windows.h> | 12 | #include <windows.h> |
| 12 | 13 | ||
| 13 | #include <cstdint> | 14 | #include <cstdint> |
| @@ -142,6 +143,48 @@ int main() { | |||
| 142 | check(pass() == 4 && probes == 0, "a pass with no change probes nothing"); | 143 | check(pass() == 4 && probes == 0, "a pass with no change probes nothing"); |
| 143 | } | 144 | } |
| 144 | 145 | ||
| 146 | // 7. Synchronous view checks between passes (sync_map): unrelated map changes cost no probe, an overlapping unmap | ||
| 147 | // defers without reading, and an overlapping map wakes a waiting texture before the next pass. | ||
| 148 | { | ||
| 149 | constexpr std::uintptr_t cpu = kBase + 0x20000000; | ||
| 150 | constexpr std::uint64_t size = 512 * 1024; | ||
| 151 | const std::uint64_t pass_generation = map::generation(); | ||
| 152 | bool mapped = true; | ||
| 153 | unsigned probes = 0; | ||
| 154 | leonida::TextureReadability r; | ||
| 155 | const auto probe = [&] { | ||
| 156 | ++probes; | ||
| 157 | return mapped; | ||
| 158 | }; | ||
| 159 | check(r.check(0, true, probe, true) && probes == 1 && !r.pending(), | ||
| 160 | "sync_map: initial probe caches a readable answer"); | ||
| 161 | for (std::uintptr_t i = 0; i < 32; ++i) | ||
| 162 | map::changed(cpu + size + i * 0x10000, cpu + size + (i + 1) * 0x10000); | ||
| 163 | r.sync_map(pass_generation, cpu, size); | ||
| 164 | check(r.check(0, true, probe, true) && probes == 1, | ||
| 165 | "sync_map: map changes outside the footprint keep the cached answer"); | ||
| 166 | r.sync_map(pass_generation, cpu, size); | ||
| 167 | check(r.check(0, true, probe, true) && probes == 1, | ||
| 168 | "sync_map: a second check at the same generation does nothing"); | ||
| 169 | |||
| 170 | mapped = false; | ||
| 171 | map::changed(cpu + 0x10000, cpu + 0x20000); | ||
| 172 | r.sync_map(pass_generation, cpu, size); | ||
| 173 | check(!r.check(0, true, probe, true) && r.pending() && probes == 2, | ||
| 174 | "sync_map: an overlapping unmap between passes reprobes and defers"); | ||
| 175 | |||
| 176 | map::changed(cpu - 0x10000, cpu); | ||
| 177 | r.sync_map(pass_generation, cpu, size); | ||
| 178 | check(!r.check(0, true, probe, true) && r.pending() && probes == 2, | ||
| 179 | "sync_map: an adjacent non-overlapping change leaves a pending texture waiting"); | ||
| 180 | |||
| 181 | mapped = true; | ||
| 182 | map::changed(cpu, cpu + size); | ||
| 183 | r.sync_map(pass_generation, cpu, size); | ||
| 184 | check(r.check(0, true, probe, true) && !r.pending() && probes == 3, | ||
| 185 | "sync_map: an overlapping map between passes wakes a pending texture at once"); | ||
| 186 | } | ||
| 187 | |||
| 145 | std::printf("%d checks, %d failures\n", g_checks, g_failures); | 188 | std::printf("%d checks, %d failures\n", g_checks, g_failures); |
| 146 | return g_failures ? 1 : 0; | 189 | return g_failures ? 1 : 0; |
| 147 | } | 190 | } |
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index eb1be0a2c..8369d594c 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h | |||
| @@ -123,6 +123,7 @@ public: | |||
| 123 | bool occlusion_query_precise = false; // occlusionQueryPrecise enabled | 123 | bool occlusion_query_precise = false; // occlusionQueryPrecise enabled |
| 124 | bool prepare_on_bind=false; | 124 | bool prepare_on_bind=false; |
| 125 | bool cold_graphics_compile = false; | 125 | bool cold_graphics_compile = false; |
| 126 | bool heavy_pipeline_cache = false; // LEONIDA_HEAVY_PIPELINE_CACHE_MS set and pipelineCreationCacheControl on | ||
| 126 | bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled | 127 | bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled |
| 127 | bool request_multi_draw_indirect = false, request_draw_indirect_count = false; | 128 | bool request_multi_draw_indirect = false, request_draw_indirect_count = false; |
| 128 | bool draw_indirect_count_enabled = false; | 129 | bool draw_indirect_count_enabled = false; |
| @@ -412,8 +413,13 @@ private: | |||
| 412 | // (zero-based VS ids) is in; harmless before. | 413 | // (zero-based VS ids) is in; harmless before. |
| 413 | const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); | 414 | const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); |
| 414 | const bool cache_only = compile_mode && std::strcmp(compile_mode, "cache-only") == 0; | 415 | const bool cache_only = compile_mode && std::strcmp(compile_mode, "cache-only") == 0; |
| 415 | v13_.enable_pipeline_cache_control = cache_only && v13_.core && v13_.pipeline_cache_control; | 416 | // LEONIDA_HEAVY_PIPELINE_CACHE_MS other than 0: the heavy pipeline cache path, as the runtime takes it by default |
| 416 | cold_graphics_compile = v13_.enable_pipeline_cache_control; | 417 | // (src/heavy_pipeline_cache.h). Tests leave it off unless asked. |
| 418 | const char* heavy_ms = std::getenv("LEONIDA_HEAVY_PIPELINE_CACHE_MS"); | ||
| 419 | const bool heavy = heavy_ms && *heavy_ms && std::strcmp(heavy_ms, "0") != 0; | ||
| 420 | v13_.enable_pipeline_cache_control = (cache_only || heavy) && v13_.core && v13_.pipeline_cache_control; | ||
| 421 | cold_graphics_compile = cache_only && v13_.enable_pipeline_cache_control; | ||
| 422 | heavy_pipeline_cache = heavy && v13_.enable_pipeline_cache_control; | ||
| 417 | prepare_on_bind = compile_mode && std::strcmp(compile_mode, "on-demand") == 0; | 423 | prepare_on_bind = compile_mode && std::strcmp(compile_mode, "on-demand") == 0; |
| 418 | VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, | 424 | VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, |
| 419 | v13_.enable(conditional_rendering ? &enable_conditional : nullptr)}; | 425 | v13_.enable(conditional_rendering ? &enable_conditional : nullptr)}; |
diff --git a/runtime/test/xapu_chad_test.cpp b/runtime/test/xapu_chad_test.cpp index dffa74404..7e667492c 100644 --- a/runtime/test/xapu_chad_test.cpp +++ b/runtime/test/xapu_chad_test.cpp | |||
| @@ -1,7 +1,11 @@ | |||
| 1 | // Checks the registered xapu.dll and chad.dll shims in the call shapes the executable uses (runtime/shims/xapu_chad.cpp): | 1 | // Checks the registered xapu.dll and chad.dll shims (runtime/shims/xapu_queue.cpp and runtime/shims/xapu_chad.cpp) |
| 2 | // the connections succeed, the APU's shared buffer is zeroed and writable at the offsets the title reaches, commands | 2 | // in the call shapes the executable uses and against the layouts xapu_queue.cpp documents. |
| 3 | // are accepted, an open and a close each give one result and nothing else does, XDspActivate hands out zeroed status | 3 | // |
| 4 | // and stream memory, and both disconnect. | 4 | // xapu.dll: the connection's limits and its zeroed memory, writable at the offsets the title reaches; one result per |
| 5 | // accepted command, in command order, with its id echoed; the per-stream queue limit; the error codes, returned or in | ||
| 6 | // the result; a process command's frame count taken from the Opus packet's table-of-contents byte (RFC 6716, section | ||
| 7 | // 3.1) and clipped, with silence written; and the result event. The packets are hand-made TOC bytes, not audio. | ||
| 8 | // chad.dll: XDspActivate hands out zeroed status and stream memory, and both disconnect. | ||
| 5 | #include <windows.h> | 9 | #include <windows.h> |
| 6 | 10 | ||
| 7 | #include <cstdint> | 11 | #include <cstdint> |
| @@ -12,10 +16,10 @@ | |||
| 12 | 16 | ||
| 13 | namespace { | 17 | namespace { |
| 14 | 18 | ||
| 15 | using XApuConnectFn = HRESULT(__stdcall*)(void*, void*, void**); | 19 | using XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**); |
| 16 | using XApuDisconnectFn = HRESULT(__stdcall*)(void*); | 20 | using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t); |
| 17 | using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const uint32_t*, uint64_t); | 21 | using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*); |
| 18 | using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint64_t); | 22 | using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*); |
| 19 | using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); | 23 | using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); |
| 20 | using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**); | 24 | using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**); |
| 21 | using XDspActivateFn = HRESULT(__stdcall*)(void*, const void*, void**, void**); | 25 | using XDspActivateFn = HRESULT(__stdcall*)(void*, const void*, void**, void**); |
| @@ -23,6 +27,55 @@ using XDspDeactivateFn = HRESULT(__stdcall*)(void*, uint64_t, uint64_t, uint64_t | |||
| 23 | using XDspDisconnectFn = HRESULT(__stdcall*)(void*); | 27 | using XDspDisconnectFn = HRESULT(__stdcall*)(void*); |
| 24 | using XDspSubmitCommandFn = HRESULT(__stdcall*)(void*, void*, uint32_t*); | 28 | using XDspSubmitCommandFn = HRESULT(__stdcall*)(void*, void*, uint32_t*); |
| 25 | 29 | ||
| 30 | constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u); | ||
| 31 | constexpr HRESULT kNoResult = static_cast<HRESULT>(0x8AC81001u); | ||
| 32 | constexpr HRESULT kInvalidCommand = static_cast<HRESULT>(0x8AC81002u); | ||
| 33 | constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u); | ||
| 34 | constexpr HRESULT kAlreadyActive = static_cast<HRESULT>(0x8AC81005u); | ||
| 35 | constexpr HRESULT kBadPacket = static_cast<HRESULT>(0x8AC81008u); | ||
| 36 | |||
| 37 | #pragma pack(push, 1) | ||
| 38 | struct ConnectInput { | ||
| 39 | uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options; | ||
| 40 | }; | ||
| 41 | struct ConnectOutput { | ||
| 42 | void* memory; | ||
| 43 | HANDLE result_event; | ||
| 44 | }; | ||
| 45 | struct CommandId { | ||
| 46 | uint32_t kind, stream, sequence, options; | ||
| 47 | uint64_t context; | ||
| 48 | }; | ||
| 49 | struct ActivateCommand { | ||
| 50 | CommandId id; | ||
| 51 | uint32_t channels, init_bytes; | ||
| 52 | const void* init; | ||
| 53 | float start_pitch; | ||
| 54 | uint32_t processing_bytes; | ||
| 55 | void* processing; | ||
| 56 | }; | ||
| 57 | struct ProcessCommand { | ||
| 58 | CommandId id; | ||
| 59 | float pitch_ramp, target_pitch; | ||
| 60 | uint32_t first_frame, frame_count, input_bytes; | ||
| 61 | const uint8_t* input; | ||
| 62 | uint32_t output_bytes; | ||
| 63 | uint8_t* output; | ||
| 64 | }; | ||
| 65 | struct Result { | ||
| 66 | CommandId id; | ||
| 67 | uint32_t state; | ||
| 68 | uint64_t state_data, usec; | ||
| 69 | HRESULT error; | ||
| 70 | uint32_t frames, output_bytes; | ||
| 71 | uint8_t* output; | ||
| 72 | float pitch; | ||
| 73 | uint32_t input_bytes; | ||
| 74 | const uint8_t* input; | ||
| 75 | }; | ||
| 76 | #pragma pack(pop) | ||
| 77 | static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts"); | ||
| 78 | |||
| 26 | int g_checks = 0; | 79 | int g_checks = 0; |
| 27 | int g_failures = 0; | 80 | int g_failures = 0; |
| 28 | 81 | ||
| @@ -39,6 +92,8 @@ T get(const char* dll, const char* name) { | |||
| 39 | return reinterpret_cast<T>(fn); | 92 | return reinterpret_cast<T>(fn); |
| 40 | } | 93 | } |
| 41 | 94 | ||
| 95 | CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; } | ||
| 96 | |||
| 42 | } // namespace | 97 | } // namespace |
| 43 | 98 | ||
| 44 | int main() { | 99 | int main() { |
| @@ -56,39 +111,165 @@ int main() { | |||
| 56 | check(rt::shims::owns_dll("xapu.dll") && rt::shims::owns_dll("chad.dll"), "the shims own xapu.dll and chad.dll"); | 111 | check(rt::shims::owns_dll("xapu.dll") && rt::shims::owns_dll("chad.dll"), "the shims own xapu.dll and chad.dll"); |
| 57 | if (g_failures) return 1; | 112 | if (g_failures) return 1; |
| 58 | 113 | ||
| 59 | // XApuConnect(block24*, out16*, handle*), success read as SUCCEEDED. | 114 | // XApuConnect(const ConnectInput*, ConnectOutput*, handle*): the first argument is read, never written. |
| 60 | uint8_t out24[24]; | 115 | ConnectOutput out{}; |
| 61 | uint64_t out16[2] = {}; | ||
| 62 | std::memset(out24, 0xcc, sizeof out24); | ||
| 63 | void* apu = nullptr; | 116 | void* apu = nullptr; |
| 64 | check(SUCCEEDED(connect(out24, out16, &apu)) && apu, "XApuConnect succeeds with a handle"); | 117 | ConnectInput bad{1, 0, 2, 0x10000, 0, 0}; |
| 65 | check(out24[0] == 0xcc && out24[23] == 0xcc, "XApuConnect leaves the title's 24-byte block alone"); | 118 | check(connect(&bad, &out, &apu) == E_INVALIDARG, "zero streams is E_INVALIDARG"); |
| 66 | auto* base = reinterpret_cast<uint8_t*>(out16[0]); | 119 | bad = {1, 501, 2, 0x10000, 0, 0}; |
| 67 | check(base != nullptr && out16[1] >= 0x14000 + 128 * 0x1E00, "XApuConnect returns the shared buffer and its size"); | 120 | check(connect(&bad, &out, &apu) == E_INVALIDARG, "more than 500 streams is E_INVALIDARG"); |
| 68 | if (base) { | 121 | bad = {1, 4, 17, 0x10000, 0, 0}; |
| 69 | const size_t last_output = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; // the end of slot 127's output | 122 | check(connect(&bad, &out, &apu) == E_INVALIDARG, "more than 16 commands per stream is E_INVALIDARG"); |
| 70 | check(base[0] == 0 && base[last_output] == 0, "the shared buffer is zeroed"); | 123 | bad = {1, 4, 2, 0, 0, 0}; |
| 71 | base[127 * 0x280] = 1; | 124 | check(connect(&bad, &out, &apu) == E_INVALIDARG, "no memory is E_INVALIDARG"); |
| 72 | base[last_output] = 1; | 125 | bad = {1, 4, 2, 0x10000, 256, 0}; |
| 73 | check(base[127 * 0x280] == 1 && base[last_output] == 1, "the shared buffer is writable at slot 127"); | 126 | check(connect(&bad, &out, &apu) == E_INVALIDARG, "frames per output for decoding is E_INVALIDARG"); |
| 74 | } | 127 | bad = {2, 4, 2, 0x10000, 0, 0}; |
| 75 | check(connect(out24, out16, nullptr) == E_INVALIDARG, "XApuConnect without a handle pointer fails"); | 128 | check(connect(&bad, &out, &apu) == static_cast<HRESULT>(rt::shims::kENotImpl), |
| 129 | "a processing kind other than Opus decoding is E_NOTIMPL"); | ||
| 130 | check(apu == nullptr, "a failed XApuConnect hands out no handle"); | ||
| 131 | |||
| 132 | // The memory the title addresses: input at base + slot * 0x280, output at base + 0x14000 + slot * 0x1E00. | ||
| 133 | constexpr uint32_t kMemory = 0x14000 + 128 * 0x1E00; | ||
| 134 | const ConnectInput in{1, 128, 2, kMemory, 0, 8}; | ||
| 135 | const ConnectInput in_copy = in; | ||
| 136 | check(SUCCEEDED(connect(&in, &out, &apu)) && apu, "XApuConnect for Opus decoding, 128 streams, 2 commands each"); | ||
| 137 | check(std::memcmp(&in, &in_copy, sizeof in) == 0, "XApuConnect leaves its input alone"); | ||
| 138 | check(out.memory != nullptr && out.result_event != nullptr, "it hands out memory and a result event"); | ||
| 139 | if (!apu || !out.memory) return 1; | ||
| 140 | auto* base = static_cast<uint8_t*>(out.memory); | ||
| 141 | const size_t last_output = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; // the end of slot 127's output | ||
| 142 | check(base[0] == 0 && base[last_output] == 0, "the memory is zeroed"); | ||
| 143 | base[127 * 0x280] = 1; | ||
| 144 | base[last_output] = 1; | ||
| 145 | check(base[127 * 0x280] == 1 && base[last_output] == 1, "the memory is writable at slot 127"); | ||
| 146 | base[127 * 0x280] = 0; | ||
| 147 | base[last_output] = 0; | ||
| 148 | |||
| 149 | Result r{}; | ||
| 150 | check(dequeue(apu, &r) == kNoResult, "XApuDequeueResult with nothing queued is 0x8AC81001"); | ||
| 151 | uint32_t dequeued = 99; | ||
| 152 | check(count(apu, &dequeued) == 0 && dequeued == 0, "XApuGetResultCount: nothing ready, none dequeued"); | ||
| 76 | 153 | ||
| 77 | // Command types 1, 2 and 3 as the title builds them; the third argument is 0 at every site. | 154 | // Activate stream 3 (stereo) and process one packet; the title's sites pass a null third argument. |
| 78 | for (uint32_t type = 1; type <= 3; ++type) { | 155 | const ActivateCommand activate{id(1, 3), 2, 0, nullptr, 1.0f, 0, nullptr}; |
| 79 | uint32_t command[16] = {type, 5}; | 156 | check(enqueue(apu, &activate, nullptr) == S_OK, "activate stream 3 with a null count pointer"); |
| 80 | check(enqueue(apu, command, 0) == S_OK, "XApuEnqueueCommand accepts a command"); | 157 | check(WaitForSingleObject(out.result_event, 0) == WAIT_TIMEOUT, "a command not asking for it leaves the event"); |
| 158 | uint8_t* const packet = base + 3 * 0x280; | ||
| 159 | uint8_t* const pcm = base + 0x14000 + 3 * 0x1E00; | ||
| 160 | packet[0] = (31 << 3) | 0; // one 20 ms CELT frame (config 31, code 0): 960 frames per channel | ||
| 161 | std::memset(pcm, 0x55, 0x1E00 + 16); // the slot and the start of the next, to see nothing past it is written | ||
| 162 | ProcessCommand process{id(3, 3, 1), 0.0f, 1.0f, 0, 960, 40, packet, 960 * 8, pcm}; | ||
| 163 | uint32_t total = 0; | ||
| 164 | check(enqueue(apu, &process, &total) == S_OK && total == 2, "process on stream 3; two commands accepted"); | ||
| 165 | check(WaitForSingleObject(out.result_event, 0) == WAIT_OBJECT_0, "a command asking for it signals the event"); | ||
| 166 | check(WaitForSingleObject(out.result_event, 0) == WAIT_TIMEOUT, "the event resets itself"); | ||
| 167 | check(enqueue(apu, &process, &total) == kQueueFull && total == 2, | ||
| 168 | "a third command on a stream of two is 0x8AC81000 and not counted"); | ||
| 169 | check(count(apu, nullptr) == 2, "two results ready, with a null dequeued pointer"); | ||
| 170 | |||
| 171 | check(dequeue(apu, &r) == S_OK && r.id.kind == 1 && r.id.stream == 3 && r.id.sequence == 7 && | ||
| 172 | r.id.context == 0x1234 && r.error == S_OK && r.pitch == 1.0f, | ||
| 173 | "results come in command order: the activate first, its id echoed"); | ||
| 174 | check(dequeue(apu, &r) == S_OK && r.id.kind == 3 && r.error == S_OK, "the process result follows"); | ||
| 175 | uint32_t dword34 = 0; | ||
| 176 | std::memcpy(&dword34, reinterpret_cast<const uint8_t*>(&r) + 0x34, 4); | ||
| 177 | check(r.frames == 960 && dword34 == 960 * 8 && r.output == pcm && r.input == packet && r.input_bytes == 40, | ||
| 178 | "960 stereo float frames, the byte count at +0x34, the buffers echoed"); | ||
| 179 | bool silent = true; | ||
| 180 | for (int i = 0; i < 960 * 8; ++i) silent = silent && pcm[i] == 0; | ||
| 181 | check(silent && pcm[960 * 8] == 0x55, "the output range is silence, and nothing past it is written"); | ||
| 182 | check(count(apu, &dequeued) == 0 && dequeued == 2, "nothing ready, two dequeued"); | ||
| 183 | |||
| 184 | // The TOC byte's frame size and count (RFC 6716, section 3.1), one stereo packet each. | ||
| 185 | struct Toc { | ||
| 186 | uint8_t toc, count; | ||
| 187 | uint32_t frames; | ||
| 188 | const char* what; | ||
| 189 | } const tocs[] = { | ||
| 190 | {(0 << 3) | 0, 0, 480, "SILK 10 ms, code 0: 480 frames"}, | ||
| 191 | {(3 << 3) | 1, 0, 5760, "SILK 60 ms, code 1 (two frames): 5760 frames"}, | ||
| 192 | {(13 << 3) | 2, 0, 1920, "hybrid 20 ms, code 2 (two frames): 1920 frames"}, | ||
| 193 | {(16 << 3) | 3, 5, 600, "CELT 2.5 ms, code 3 with five frames: 600 frames"}, | ||
| 194 | }; | ||
| 195 | for (const Toc& t : tocs) { | ||
| 196 | packet[0] = t.toc; | ||
| 197 | packet[1] = t.count; | ||
| 198 | process = {id(3, 3), 0.0f, 1.0f, 0, 6000, 40, packet, 0x1E00 * 4, pcm}; | ||
| 199 | r = {}; | ||
| 200 | check(enqueue(apu, &process, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK && | ||
| 201 | r.frames == (t.frames < 0x1E00 * 4 / 8 ? t.frames : 0x1E00 * 4 / 8), | ||
| 202 | t.what); | ||
| 81 | } | 203 | } |
| 82 | check(count(apu, 0) == 2, "the open and the close each queued a result, the type 3 command none"); | 204 | |
| 83 | for (uint32_t type = 1; type <= 2; ++type) { | 205 | // first_frame and frame_count clip like a decode: three 20 ms frames (code 3, count 3) = 2880, from frame 2000. |
| 84 | uint32_t queued[0x50 / 4] = {}; | 206 | packet[0] = (31 << 3) | 3; |
| 85 | check(dequeue(apu, queued) == S_OK && queued[0] == type && queued[1] == 5 && queued[2] == 0 && queued[13] == 0, | 207 | packet[1] = 3; |
| 86 | "XApuDequeueResult returns the type and slot and leaves the rest zeroed"); | 208 | process = {id(3, 3), 0.0f, 1.0f, 2000, 4000, 40, packet, 0x1E00, pcm}; |
| 209 | enqueue(apu, &process, nullptr); | ||
| 210 | dequeue(apu, &r); | ||
| 211 | check(r.error == S_OK && r.frames == 880 && r.output_bytes == 880 * 8, "frames from first_frame to the packet's end"); | ||
| 212 | process.frame_count = 300; | ||
| 213 | enqueue(apu, &process, nullptr); | ||
| 214 | dequeue(apu, &r); | ||
| 215 | check(r.frames == 300, "no more than frame_count"); | ||
| 216 | process.frame_count = 4000; | ||
| 217 | process.output_bytes = 100 * 8 + 7; | ||
| 218 | enqueue(apu, &process, nullptr); | ||
| 219 | dequeue(apu, &r); | ||
| 220 | check(r.frames == 100 && r.output_bytes == 800, "and no more than the output holds"); | ||
| 221 | |||
| 222 | // Errors carried in the result: the command is accepted and its result says what went wrong. | ||
| 223 | packet[1] = 7; // seven 20 ms frames: 140 ms, longer than an Opus packet may be | ||
| 224 | enqueue(apu, &process, nullptr); | ||
| 225 | dequeue(apu, &r); | ||
| 226 | check(r.error == kBadPacket && r.frames == 0, "an impossible packet: 0x8AC81008 in the result"); | ||
| 227 | packet[0] = (31 << 3) | 3; | ||
| 228 | packet[1] = 0; | ||
| 229 | enqueue(apu, &process, nullptr); | ||
| 230 | dequeue(apu, &r); | ||
| 231 | check(r.error == kBadPacket, "a code 3 packet of zero frames: 0x8AC81008"); | ||
| 232 | ProcessCommand empty = process; | ||
| 233 | empty.input_bytes = 0; | ||
| 234 | check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, | ||
| 235 | "an empty input: E_INVALIDARG in the result"); | ||
| 236 | empty = process; | ||
| 237 | empty.output = nullptr; | ||
| 238 | check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, | ||
| 239 | "a null output: E_INVALIDARG in the result"); | ||
| 240 | ProcessCommand stray = process; | ||
| 241 | stray.id.stream = 4; | ||
| 242 | check(enqueue(apu, &stray, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream, | ||
| 243 | "a process on a stream never activated: 0x8AC81003 in the result"); | ||
| 244 | check(enqueue(apu, &activate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kAlreadyActive, | ||
| 245 | "activating an active stream: 0x8AC81005 in the result"); | ||
| 246 | ActivateCommand surround = activate; | ||
| 247 | surround.id.stream = 5; | ||
| 248 | surround.channels = 6; | ||
| 249 | check(enqueue(apu, &surround, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, | ||
| 250 | "six channels: E_INVALIDARG in the result"); | ||
| 251 | |||
| 252 | // Errors returned at once, with no result. | ||
| 253 | stray.id.stream = 128; | ||
| 254 | check(enqueue(apu, &stray, nullptr) == kInvalidStream, "a stream past the connection's is 0x8AC81003"); | ||
| 255 | const CommandId unknown = id(9, 3); | ||
| 256 | check(enqueue(apu, &unknown, nullptr) == kInvalidCommand, "an unknown kind is 0x8AC81002"); | ||
| 257 | check(count(apu, nullptr) == 0, "neither left a result"); | ||
| 258 | |||
| 259 | // Notify and reset give a result; deactivate gives one and closes the stream. | ||
| 260 | for (uint32_t kind : {4u, 5u, 2u}) { | ||
| 261 | const CommandId command = id(kind, 3); | ||
| 262 | check(enqueue(apu, &command, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.id.kind == kind && | ||
| 263 | r.id.stream == 3 && r.error == S_OK, | ||
| 264 | "notify, reset and deactivate each give a result of their kind for their stream"); | ||
| 87 | } | 265 | } |
| 88 | check(count(apu, 0) == 0, "XApuGetResultCount is 0 again"); | 266 | process.id.stream = 3; |
| 89 | uint8_t result[0x50] = {}; | 267 | enqueue(apu, &process, nullptr); |
| 90 | check(FAILED(dequeue(apu, result)), "XApuDequeueResult on the empty queue fails"); | 268 | dequeue(apu, &r); |
| 91 | check(disconnect(apu) == S_OK, "XApuDisconnect succeeds"); | 269 | check(r.error == kInvalidStream, "after deactivate the stream takes no process command"); |
| 270 | check(enqueue(apu, &activate, &total) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK, | ||
| 271 | "and it can be activated again"); | ||
| 272 | check(disconnect(apu, 0x20) == S_OK, "XApuDisconnect(handle, 0x20)"); | ||
| 92 | 273 | ||
| 93 | // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*), success read as a return of 0. | 274 | // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*), success read as a return of 0. |
| 94 | alignas(64) static uint8_t dsp_buffer[4096]; | 275 | alignas(64) static uint8_t dsp_buffer[4096]; |
| @@ -99,10 +280,10 @@ int main() { | |||
| 99 | void* stream = nullptr; | 280 | void* stream = nullptr; |
| 100 | check(dsp_activate(dsp, description, reinterpret_cast<void**>(&status), &stream) == 0, "XDspActivate returns 0"); | 281 | check(dsp_activate(dsp, description, reinterpret_cast<void**>(&status), &stream) == 0, "XDspActivate returns 0"); |
| 101 | check(status && stream && static_cast<void*>(status) != stream, "XDspActivate writes both outputs"); | 282 | check(status && stream && static_cast<void*>(status) != stream, "XDspActivate writes both outputs"); |
| 102 | uint32_t id = 0; | 283 | uint32_t dsp_id = 0; |
| 103 | check(dsp_submit(stream, dsp_buffer, &id) == 0, "XDspSubmitCommand returns 0"); | 284 | check(dsp_submit(stream, dsp_buffer, &dsp_id) == 0, "XDspSubmitCommand returns 0"); |
| 104 | // What the title's wait reads: no error at +0xc and the submitted id at +4. | 285 | // What the title's wait reads: no error at +0xc and the submitted id at +4. |
| 105 | check(status && status[3] == 0 && status[1] == id, "the status block reports the submitted command as done"); | 286 | check(status && status[3] == 0 && status[1] == dsp_id, "the status block reports the submitted command as done"); |
| 106 | check(dsp_deactivate(dsp, 0, 0, 0) == 0, "XDspDeactivate returns 0"); | 287 | check(dsp_deactivate(dsp, 0, 0, 0) == 0, "XDspDeactivate returns 0"); |
| 107 | check(dsp_disconnect(dsp) == 0, "XDspDisconnect returns 0"); | 288 | check(dsp_disconnect(dsp) == 0, "XDspDisconnect returns 0"); |
| 108 | 289 | ||
diff --git a/runtime/test/xapu_opus_test.cpp b/runtime/test/xapu_opus_test.cpp new file mode 100644 index 000000000..30eb33cfe --- /dev/null +++ b/runtime/test/xapu_opus_test.cpp | |||
| @@ -0,0 +1,193 @@ | |||
| 1 | // Checks the decoded path of the registered xapu.dll shim (runtime/shims/xapu_queue.cpp) with | ||
| 2 | // runtime/opus_decoder built: the title's ConnectInput, activate/process/deactivate, one result per | ||
| 3 | // command in order, the 0x50-byte result layout, and a generated 440 Hz stereo packet decoded to | ||
| 4 | // 960 frames of f32 PCM, then clipped by first_frame / frame_count / output_bytes. The packet is | ||
| 5 | // encoded here; no game data. | ||
| 6 | #include <windows.h> | ||
| 7 | |||
| 8 | #include <cmath> | ||
| 9 | #include <cstdint> | ||
| 10 | #include <cstdio> | ||
| 11 | #include <cstring> | ||
| 12 | #include <vector> | ||
| 13 | |||
| 14 | #include "leonida_opus_decoder.h" | ||
| 15 | #include "shims.h" | ||
| 16 | |||
| 17 | namespace { | ||
| 18 | |||
| 19 | using XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**); | ||
| 20 | using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t); | ||
| 21 | using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*); | ||
| 22 | using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*); | ||
| 23 | using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); | ||
| 24 | |||
| 25 | constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u); | ||
| 26 | constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u); | ||
| 27 | |||
| 28 | #pragma pack(push, 1) | ||
| 29 | struct ConnectInput { | ||
| 30 | uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options; | ||
| 31 | }; | ||
| 32 | struct ConnectOutput { | ||
| 33 | void* memory; | ||
| 34 | HANDLE result_event; | ||
| 35 | }; | ||
| 36 | struct CommandId { | ||
| 37 | uint32_t kind, stream, sequence, options; | ||
| 38 | uint64_t context; | ||
| 39 | }; | ||
| 40 | struct ActivateCommand { | ||
| 41 | CommandId id; | ||
| 42 | uint32_t channels, init_bytes; | ||
| 43 | const void* init; | ||
| 44 | float start_pitch; | ||
| 45 | uint32_t processing_bytes; | ||
| 46 | void* processing; | ||
| 47 | }; | ||
| 48 | struct ProcessCommand { | ||
| 49 | CommandId id; | ||
| 50 | float pitch_ramp, target_pitch; | ||
| 51 | uint32_t first_frame, frame_count, input_bytes; | ||
| 52 | const uint8_t* input; | ||
| 53 | uint32_t output_bytes; | ||
| 54 | uint8_t* output; | ||
| 55 | }; | ||
| 56 | struct Result { | ||
| 57 | CommandId id; | ||
| 58 | uint32_t state; | ||
| 59 | uint64_t state_data, usec; | ||
| 60 | HRESULT error; | ||
| 61 | uint32_t frames, output_bytes; | ||
| 62 | uint8_t* output; | ||
| 63 | float pitch; | ||
| 64 | uint32_t input_bytes; | ||
| 65 | const uint8_t* input; | ||
| 66 | }; | ||
| 67 | #pragma pack(pop) | ||
| 68 | static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts"); | ||
| 69 | |||
| 70 | int g_checks = 0; | ||
| 71 | int g_failures = 0; | ||
| 72 | |||
| 73 | void check(bool condition, const char* what) { | ||
| 74 | ++g_checks; | ||
| 75 | std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); | ||
| 76 | if (!condition) ++g_failures; | ||
| 77 | } | ||
| 78 | |||
| 79 | template <typename T> | ||
| 80 | T get(const char* dll, const char* name) { | ||
| 81 | void* fn = rt::shims::find(dll, name); | ||
| 82 | check(fn != nullptr, name); | ||
| 83 | return reinterpret_cast<T>(fn); | ||
| 84 | } | ||
| 85 | |||
| 86 | CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; } | ||
| 87 | |||
| 88 | } // namespace | ||
| 89 | |||
| 90 | int main() { | ||
| 91 | std::printf("xapu_opus_test: decoded xapu.dll path\n"); | ||
| 92 | const auto connect = get<XApuConnectFn>("xapu.dll", "XApuConnect"); | ||
| 93 | const auto disconnect = get<XApuDisconnectFn>("xapu.dll", "XApuDisconnect"); | ||
| 94 | const auto enqueue = get<XApuEnqueueCommandFn>("xapu.dll", "XApuEnqueueCommand"); | ||
| 95 | const auto count = get<XApuGetResultCountFn>("xapu.dll", "XApuGetResultCount"); | ||
| 96 | const auto dequeue = get<XApuDequeueResultFn>("xapu.dll", "XApuDequeueResult"); | ||
| 97 | if (g_failures) return 1; | ||
| 98 | |||
| 99 | constexpr uint32_t kMemory = 0x14000 + 128 * 0x1E00; | ||
| 100 | const ConnectInput in{1, 128, 2, kMemory, 0, 0}; | ||
| 101 | const ConnectInput in_copy = in; | ||
| 102 | ConnectOutput out{}; | ||
| 103 | void* apu = nullptr; | ||
| 104 | check(SUCCEEDED(connect(&in, &out, &apu)) && apu, "XApuConnect for Opus decoding"); | ||
| 105 | check(std::memcmp(&in, &in_copy, sizeof in) == 0, "XApuConnect leaves its input alone"); | ||
| 106 | auto* base = static_cast<uint8_t*>(out.memory); | ||
| 107 | if (!apu || !base) return 1; | ||
| 108 | check(base[0] == 0 && base[kMemory - 1] == 0, "the shared memory is zeroed"); | ||
| 109 | |||
| 110 | const ActivateCommand activate{id(1, 3), 2, 0, nullptr, 1.0f, 0, nullptr}; | ||
| 111 | check(enqueue(apu, &activate, nullptr) == S_OK, "activate stream 3 (stereo)"); | ||
| 112 | |||
| 113 | std::vector<float> tone(960 * 2); | ||
| 114 | for (uint32_t i = 0; i < 960; ++i) { | ||
| 115 | const float sample = static_cast<float>(std::sin(double(i) * 440.0 * 6.283185307179586 / 48000.0)) * 0.5f; | ||
| 116 | tone[2 * i] = sample; | ||
| 117 | tone[2 * i + 1] = sample; | ||
| 118 | } | ||
| 119 | uint8_t encoded[1500]; | ||
| 120 | size_t encoded_len = 0; | ||
| 121 | check(leonida_opus_encode_test(tone.data(), 960, 2, encoded, sizeof encoded, &encoded_len) == LEONIDA_OPUS_OK && | ||
| 122 | encoded_len > 0, | ||
| 123 | "a synthetic 20 ms stereo Opus packet encodes"); | ||
| 124 | std::memcpy(base, encoded, encoded_len); | ||
| 125 | auto* const pcm = base + 0x14000 + 3 * 0x1E00; | ||
| 126 | std::memset(pcm, 0x55, 0x1E00 + 64); | ||
| 127 | ProcessCommand process{id(3, 3, 1), 0.0f, 1.0f, 0, 960, static_cast<uint32_t>(encoded_len), base, 0x1E00, pcm}; | ||
| 128 | uint32_t total = 0; | ||
| 129 | check(enqueue(apu, &process, &total) == S_OK && total == 2, "process on stream 3; two commands accepted"); | ||
| 130 | check(enqueue(apu, &process, &total) == kQueueFull && total == 2, | ||
| 131 | "a third command on a stream of two is 0x8AC81000"); | ||
| 132 | check(count(apu, nullptr) == 2, "two results ready"); | ||
| 133 | |||
| 134 | Result r{}; | ||
| 135 | check(dequeue(apu, &r) == S_OK && r.id.kind == 1 && r.id.stream == 3 && r.error == S_OK, | ||
| 136 | "results come in command order: the activate first"); | ||
| 137 | check(dequeue(apu, &r) == S_OK && r.id.kind == 3 && r.error == S_OK, "the process result follows"); | ||
| 138 | uint32_t dword34 = 0; | ||
| 139 | std::memcpy(&dword34, reinterpret_cast<const uint8_t*>(&r) + 0x34, 4); | ||
| 140 | check(r.frames == 960 && dword34 == 960 * 8 && r.output == pcm && r.input == base && | ||
| 141 | r.input_bytes == static_cast<uint32_t>(encoded_len), | ||
| 142 | "960 stereo float frames, the byte count at +0x34, the buffers echoed"); | ||
| 143 | float energy = 0.0f; | ||
| 144 | const auto* floats = reinterpret_cast<const float*>(pcm); | ||
| 145 | for (uint32_t i = 0; i < 960 * 2; ++i) energy += floats[i] * floats[i]; | ||
| 146 | energy /= 960 * 2; | ||
| 147 | check(energy > 0.01f, "the decoded tone has energy"); | ||
| 148 | check(pcm[960 * 8] == 0x55, "nothing past the decoded range is written"); | ||
| 149 | check(count(apu, nullptr) == 0, "the queue is empty after both results"); | ||
| 150 | |||
| 151 | // first_frame, frame_count and what output_bytes holds each clip the decoded frames. | ||
| 152 | process.first_frame = 500; | ||
| 153 | process.frame_count = 4000; | ||
| 154 | enqueue(apu, &process, nullptr); | ||
| 155 | dequeue(apu, &r); | ||
| 156 | check(r.error == S_OK && r.frames == 460 && r.output_bytes == 460 * 8, "frames from first_frame to the packet's end"); | ||
| 157 | process.frame_count = 300; | ||
| 158 | enqueue(apu, &process, nullptr); | ||
| 159 | dequeue(apu, &r); | ||
| 160 | check(r.frames == 300 && r.output_bytes == 300 * 8, "no more than frame_count"); | ||
| 161 | process.frame_count = 4000; | ||
| 162 | process.output_bytes = 100 * 8 + 7; | ||
| 163 | enqueue(apu, &process, nullptr); | ||
| 164 | dequeue(apu, &r); | ||
| 165 | check(r.frames == 100 && r.output_bytes == 800, "and no more than the output holds"); | ||
| 166 | |||
| 167 | // Errors carried in the result. | ||
| 168 | ProcessCommand empty = process; | ||
| 169 | empty.input_bytes = 0; | ||
| 170 | check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, | ||
| 171 | "an empty input: E_INVALIDARG in the result"); | ||
| 172 | empty = process; | ||
| 173 | empty.output = nullptr; | ||
| 174 | check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, | ||
| 175 | "a null output: E_INVALIDARG in the result"); | ||
| 176 | ProcessCommand stray = process; | ||
| 177 | stray.id.stream = 4; | ||
| 178 | check(enqueue(apu, &stray, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream, | ||
| 179 | "a process on a stream never activated: 0x8AC81003 in the result"); | ||
| 180 | |||
| 181 | // Deactivate closes the stream; activating again creates a fresh decoder. | ||
| 182 | const CommandId deactivate = id(2, 3); | ||
| 183 | check(enqueue(apu, &deactivate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK, | ||
| 184 | "deactivate gives a result and closes the stream"); | ||
| 185 | check(enqueue(apu, &process, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream, | ||
| 186 | "after deactivate the stream takes no process command"); | ||
| 187 | check(enqueue(apu, &activate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK, | ||
| 188 | "the stream can be activated again"); | ||
| 189 | check(disconnect(apu, 0x20) == S_OK, "XApuDisconnect(handle, 0x20)"); | ||
| 190 | |||
| 191 | std::printf("%d checks, %d failures\n", g_checks, g_failures); | ||
| 192 | return g_failures ? 1 : 0; | ||
| 193 | } | ||
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 991388c7f..adc24cca3 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp | |||
| @@ -31,6 +31,7 @@ | |||
| 31 | #include "startup_trace.h" | 31 | #include "startup_trace.h" |
| 32 | #include "xmem.h" | 32 | #include "xmem.h" |
| 33 | #include "../src/title_page_watch.h" | 33 | #include "../src/title_page_watch.h" |
| 34 | #include "../src/title_geometry_watch.h" | ||
| 34 | 35 | ||
| 35 | // The process heap as test_heap_lock_faults needs it (the same gate as d3d12_existing_heap_test's): an allocation that | 36 | // The process heap as test_heap_lock_faults needs it (the same gate as d3d12_existing_heap_test's): an allocation that |
| 36 | // waits while a thread holds the heap's lock. The NT heap's low-fragmentation front end serves most small sizes | 37 | // waits while a thread holds the heap's lock. The NT heap's low-fragmentation front end serves most small sizes |
| @@ -429,6 +430,78 @@ struct PhysicalApi { | |||
| 429 | XMemMapPhysicalPagesScatterFn scatter; | 430 | XMemMapPhysicalPagesScatterFn scatter; |
| 430 | }; | 431 | }; |
| 431 | 432 | ||
| 433 | // A remap that gives watched pages another frame reports them released (geometry_writes::note_released), so the | ||
| 434 | // geometry copies of what they held are retired; a page mapped again to the frame it had is no change. Through | ||
| 435 | // XMemMapPhysicalPages, the scatter call and CopyPageMappingsBatchX. | ||
| 436 | void test_remap_releases(const PhysicalApi& api) { | ||
| 437 | namespace watch = leonida::geometry_writes; | ||
| 438 | constexpr uint64_t kPages = 3; | ||
| 439 | auto* const window = static_cast<uint8_t*>(api.virtual_alloc( | ||
| 440 | nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE)); | ||
| 441 | uint64_t pages[4]{}; | ||
| 442 | uint64_t count = 4; | ||
| 443 | if (!window || api.allocate(0x280, &count, pages) != TRUE || count != 4) { | ||
| 444 | check(false, "remap releases: a window and four physical pages"); | ||
| 445 | return; | ||
| 446 | } | ||
| 447 | const auto base = reinterpret_cast<uintptr_t>(window); | ||
| 448 | watch::ReleaseQueue queue; | ||
| 449 | watch::subscribe(queue); | ||
| 450 | for (uint64_t i = 0; i < kPages; ++i) watch::acquire(base + i * kPage64k); // as a geometry copy over the pages | ||
| 451 | std::vector<std::pair<uintptr_t, uintptr_t>> released; | ||
| 452 | const auto take = [&] { | ||
| 453 | watch::take_released(queue, released); | ||
| 454 | return released; | ||
| 455 | }; | ||
| 456 | const auto covers = [&](uintptr_t from, uintptr_t to) { | ||
| 457 | for (const auto& [lo, hi] : released) | ||
| 458 | if (lo <= from && hi >= to) return true; | ||
| 459 | return false; | ||
| 460 | }; | ||
| 461 | const auto any_overlap = [&](uintptr_t from, uintptr_t to) { | ||
| 462 | for (const auto& [lo, hi] : released) | ||
| 463 | if (lo < to && hi > from) return true; | ||
| 464 | return false; | ||
| 465 | }; | ||
| 466 | |||
| 467 | const uint64_t first[kPages] = {pages[0], pages[1], pages[2]}; | ||
| 468 | check(api.map(window, kPages, first) == window && take().empty(), | ||
| 469 | "remap releases: a first mapping of unmapped pages releases nothing"); | ||
| 470 | check(api.map(window + kPage64k, 1, &pages[1]) == window + kPage64k && take().empty(), | ||
| 471 | "remap releases: a page mapped again to the frame it has is no change"); | ||
| 472 | check(api.map(window + kPage64k, 1, &pages[3]) == window + kPage64k && !take().empty() && | ||
| 473 | covers(base + kPage64k, base + 2 * kPage64k) && !any_overlap(base, base + kPage64k) && | ||
| 474 | !any_overlap(base + 2 * kPage64k, base + 3 * kPage64k), | ||
| 475 | "remap releases: a page given another frame is released, its neighbours are not"); | ||
| 476 | const uint64_t rotated[kPages] = {pages[2], pages[0], pages[1]}; | ||
| 477 | check(api.map(window, kPages, rotated) == window && !take().empty() && covers(base, base + 3 * kPage64k), | ||
| 478 | "remap releases: a run given other frames is released whole"); | ||
| 479 | const uint64_t partly[kPages] = {pages[2], pages[3], pages[1]}; | ||
| 480 | check(api.map(window, kPages, partly) == window && !take().empty() && | ||
| 481 | covers(base + kPage64k, base + 2 * kPage64k) && !any_overlap(base, base + kPage64k) && | ||
| 482 | !any_overlap(base + 2 * kPage64k, base + 3 * kPage64k), | ||
| 483 | "remap releases: of a remapped run, only the page whose frame changed is released"); | ||
| 484 | void* const last = window + 2 * kPage64k; | ||
| 485 | check(api.scatter(&last, 1, &pages[0]) == TRUE && !take().empty() && | ||
| 486 | covers(base + 2 * kPage64k, base + 3 * kPage64k) && !any_overlap(base, base + 2 * kPage64k), | ||
| 487 | "remap releases: the scatter call releases the page it gives another frame"); | ||
| 488 | check(api.scatter(&last, 1, &pages[0]) == TRUE && take().empty(), | ||
| 489 | "remap releases: the scatter call with the frame the page has releases nothing"); | ||
| 490 | // CopyPageMappingsBatchX: page 0 gets the frame at page 1 (kind 0 from a pool at the window itself). | ||
| 491 | const rt::xmem::PageRange range{0, 1, 1}; | ||
| 492 | const rt::xmem::PageBatch batch{base, 1, &range}; | ||
| 493 | check(rt::xmem::copy_page_mappings(1, &batch, base, kPages, 0) && !take().empty() && | ||
| 494 | covers(base, base + kPage64k) && !any_overlap(base + kPage64k, base + 3 * kPage64k), | ||
| 495 | "remap releases: CopyPageMappingsBatchX releases the page it gives another frame"); | ||
| 496 | |||
| 497 | check(api.map(window, kPages, nullptr) == window && !take().empty() && covers(base, base + 3 * kPage64k), | ||
| 498 | "remap releases: unmapping releases the range"); | ||
| 499 | for (uint64_t i = 0; i < kPages; ++i) watch::release(base + i * kPage64k); | ||
| 500 | watch::unsubscribe(queue); | ||
| 501 | api.free_pages(4, pages); | ||
| 502 | VirtualFree(window, 0, MEM_RELEASE); | ||
| 503 | } | ||
| 504 | |||
| 432 | // Physical pages in a 64 KiB-page window, as the measured callers use them: reserve a window, allocate pages, map them, | 505 | // Physical pages in a 64 KiB-page window, as the measured callers use them: reserve a window, allocate pages, map them, |
| 433 | // remap them elsewhere and in another order, unmap, free. | 506 | // remap them elsewhere and in another order, unmap, free. |
| 434 | void test_physical_pages(const PhysicalApi& api) { | 507 | void test_physical_pages(const PhysicalApi& api) { |
| @@ -741,7 +814,19 @@ void test_copy_page_mappings_cpu_view(const PhysicalApi& api) { | |||
| 741 | check(readable(other) && page_holds(other, 0x7300u), | 814 | check(readable(other) && page_holds(other, 0x7300u), |
| 742 | "a GPU-only source page unmapped there is looked up at its CPU range"); | 815 | "a GPU-only source page unmapped there is looked up at its CPU range"); |
| 743 | 816 | ||
| 744 | // A null source unmaps both ranges. | 817 | // A CPU page the title mapped itself is the title's: a copy onto its GPU-only page, or an unmap of it, changes the |
| 818 | // GPU-only page alone (the console's CopyPageMappingsBatchX edits only that range's page table). | ||
| 819 | check(copy(gpu + 2 * kPage64k, pool + kPage64k, 1, false), "a copy onto a GPU-only page whose CPU page is the title's"); | ||
| 820 | check(readable(gpu + 2 * kPage64k) && page_holds(gpu + 2 * kPage64k, 0x7301u), | ||
| 821 | "the GPU-only page shows the copied pool page"); | ||
| 822 | check(readable(cpu + 2 * kPage64k) && page_holds(cpu + 2 * kPage64k, 0x7300u), | ||
| 823 | "the title's own mapping at the paired CPU page is kept, not replaced by the copy"); | ||
| 824 | check(copy(gpu + 2 * kPage64k, nullptr, 1, false), "a null source unmaps a GPU-only page whose CPU page is the title's"); | ||
| 825 | check(!readable(gpu + 2 * kPage64k), "the GPU-only page is unmapped"); | ||
| 826 | check(readable(cpu + 2 * kPage64k) && page_holds(cpu + 2 * kPage64k, 0x7300u), | ||
| 827 | "the title's own mapping at the paired CPU page survives the unmap"); | ||
| 828 | |||
| 829 | // A null source unmaps both ranges where the CPU pages are the copy's own. | ||
| 745 | check(copy(gpu, nullptr, kPool, false), "a null source unmaps the GPU-only range"); | 830 | check(copy(gpu, nullptr, kPool, false), "a null source unmaps the GPU-only range"); |
| 746 | check(!readable(gpu) && !readable(cpu) && !readable(cpu + kPage64k), "the paired CPU range is unmapped with it"); | 831 | check(!readable(gpu) && !readable(cpu) && !readable(cpu + kPage64k), "the paired CPU range is unmapped with it"); |
| 747 | 832 | ||
| @@ -1544,6 +1629,38 @@ void test_physical_pages_commit_on_touch(const PhysicalApi& api) { | |||
| 1544 | check(read_ok, "ReadFile fills a page that commit_physical_range committed"); | 1629 | check(read_ok, "ReadFile fills a page that commit_physical_range committed"); |
| 1545 | 1630 | ||
| 1546 | check(api.map(second, 2, nullptr) == second && api.map(window, kMapped, nullptr) == window, "they unmap"); | 1631 | check(api.map(second, 2, nullptr) == second && api.map(window, kMapped, nullptr) == window, "they unmap"); |
| 1632 | { | ||
| 1633 | // A host guarded read (outside the title image at 0x140000000) of an unmapped window page exits as | ||
| 1634 | // passed_guarded without counting as left_to_title; a title read still counts as left_to_title. | ||
| 1635 | void* const stub_page = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); | ||
| 1636 | const uint8_t mov_eax_rcx_ret[] = {0x8b, 0x01, 0xc3}; | ||
| 1637 | DWORD stub_old = 0; | ||
| 1638 | bool stub_ready = false; | ||
| 1639 | if (stub_page) { | ||
| 1640 | std::memcpy(stub_page, mov_eax_rcx_ret, sizeof(mov_eax_rcx_ret)); | ||
| 1641 | stub_ready = VirtualProtect(stub_page, 4096, PAGE_EXECUTE_READ, &stub_old) != FALSE; | ||
| 1642 | FlushInstructionCache(GetCurrentProcess(), stub_page, sizeof(mov_eax_rcx_ret)); | ||
| 1643 | } | ||
| 1644 | const auto host_read_faults = [&](const void* p) { | ||
| 1645 | __try { | ||
| 1646 | reinterpret_cast<uint32_t (*)(const void*)>(stub_page)(p); | ||
| 1647 | return false; | ||
| 1648 | } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER | ||
| 1649 | : EXCEPTION_CONTINUE_SEARCH) { | ||
| 1650 | return true; | ||
| 1651 | } | ||
| 1652 | }; | ||
| 1653 | const uint64_t guarded_before = rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded); | ||
| 1654 | const uint64_t left_before = rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title); | ||
| 1655 | check(stub_ready && host_read_faults(second) && | ||
| 1656 | rt::xmem::fault_exits(rt::xmem::FaultExit::passed_guarded) == guarded_before + 1 && | ||
| 1657 | rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before, | ||
| 1658 | "a host guarded read of an unmapped window page exits as passed_guarded"); | ||
| 1659 | check(access_faults(reinterpret_cast<volatile uint32_t*>(second), false) && | ||
| 1660 | rt::xmem::fault_exits(rt::xmem::FaultExit::left_to_title) == left_before + 1, | ||
| 1661 | "a title read of an unmapped window page still exits as left_to_title"); | ||
| 1662 | if (stub_page) VirtualFree(stub_page, 0, MEM_RELEASE); | ||
| 1663 | } | ||
| 1547 | check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them"); | 1664 | check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them"); |
| 1548 | } | 1665 | } |
| 1549 | 1666 | ||
| @@ -2655,6 +2772,7 @@ int main(int argc, char** argv) { | |||
| 2655 | // Keep the direct SEC_RESERVE control ahead of the first physical allocation, which installs xmem's VEH. | 2772 | // Keep the direct SEC_RESERVE control ahead of the first physical allocation, which installs xmem's VEH. |
| 2656 | g_section_write_control = measure_section_write_control(); | 2773 | g_section_write_control = measure_section_write_control(); |
| 2657 | test_physical_pages(physical); | 2774 | test_physical_pages(physical); |
| 2775 | test_remap_releases(physical); | ||
| 2658 | if (argc == 2 && std::strcmp(argv[1], "--file-pools") == 0) { | 2776 | if (argc == 2 && std::strcmp(argv[1], "--file-pools") == 0) { |
| 2659 | test_placeholders(physical); | 2777 | test_placeholders(physical); |
| 2660 | print_result(); | 2778 | print_result(); |
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index cb350820e..e80825623 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp | |||
| @@ -4644,6 +4644,85 @@ int check_list_values_more() { | |||
| 4644 | WaitForSingleObject(job, INFINITE); | 4644 | WaitForSingleObject(job, INFINITE); |
| 4645 | CloseHandle(job); | 4645 | CloseHandle(job); |
| 4646 | 4646 | ||
| 4647 | // 11. Work-aware timeout in Pump (src/list_value_wait_budget.h): | ||
| 4648 | // a) a matching in-flight producer pauses a held memory gate past the idle timeout until the producer lands; | ||
| 4649 | // b) a busy releaser executing an action gate pauses a concurrent memory gate past the idle timeout; | ||
| 4650 | // c) a demoted gate (4 ms budget) scales its pause caps with its short budget so unrelated active work does not | ||
| 4651 | // hold it for the full timeout's cap; | ||
| 4652 | // d) a matching producer stuck behind an unsignalled fence still hits a finite pause cap instead of hanging. | ||
| 4653 | const auto write_on_a = [&](int index, std::uint64_t value, std::uint64_t& signal_value) -> bool { | ||
| 4654 | if (FAILED(hr_of(raw(direct, 139, word(allocator), 0)))) return false; | ||
| 4655 | raw(direct, 14, 1, 1, 1); // Dispatch | ||
| 4656 | raw(direct, 72, word(&g_cells2[index]), value, 0, 0); // write64 | ||
| 4657 | if (FAILED(hr_of(raw(direct, 9)))) return false; | ||
| 4658 | g_queue_call_count = 0; | ||
| 4659 | if (submit(qa, direct) != 0) return false; | ||
| 4660 | signal_value = logged_signal(qa_mock, a_written); | ||
| 4661 | return signal_value != 0; | ||
| 4662 | }; | ||
| 4663 | xs::set_list_value_wait_timeout_ms(40); | ||
| 4664 | xs::reset_list_value_stats(); | ||
| 4665 | // 11a. Wait on qb before qa submits its matching write (so relay() misses it and Pump holds a gate). | ||
| 4666 | EXPECT(hold_on(qb, 27, 1)); | ||
| 4667 | std::uint64_t producer_sig = 0; | ||
| 4668 | EXPECT(write_on_a(27, 1, producer_sig)); | ||
| 4669 | EXPECT(!xs::list_values_idle(150)); // >3x the 40 ms idle timeout: pauses while producer is in flight | ||
| 4670 | stats = xs::list_value_stats(); | ||
| 4671 | EXPECT(stats.gates_timed_out == 0 && stats.gates_met == 0 && cell2(27) == 0); | ||
| 4672 | fence_signal(a_written, producer_sig); | ||
| 4673 | EXPECT(xs::list_values_idle(3000) && cell2(27) == 1); | ||
| 4674 | stats = xs::list_value_stats(); | ||
| 4675 | EXPECT(stats.gates_met == 1 && stats.gates_timed_out == 0); | ||
| 4676 | |||
| 4677 | // 11b. Releaser inside a 150 ms action gate pauses a concurrent memory gate past the 40 ms idle timeout. | ||
| 4678 | xs::set_copy_page_mappings_hook([](std::uint32_t, const rt::xmem::PageBatch*, std::uintptr_t, std::uint32_t, | ||
| 4679 | std::uint32_t) -> bool { | ||
| 4680 | Sleep(150); | ||
| 4681 | InterlockedExchange64(reinterpret_cast<volatile LONG64*>(&g_cells2[28]), 1); | ||
| 4682 | return true; | ||
| 4683 | }); | ||
| 4684 | g_queue_call_count = 0; | ||
| 4685 | EXPECT(hr_of(raw(qc, 31, 1, word(remap), 0x7000000000, 16, 0)) == S_OK); | ||
| 4686 | const std::uint64_t action_sig = logged_signal(qc_mock, c_written); | ||
| 4687 | EXPECT(action_sig != 0); | ||
| 4688 | const std::uint64_t met_before_rel = xs::list_value_stats().gates_met; | ||
| 4689 | const std::uint64_t to_before_rel = xs::list_value_stats().gates_timed_out; | ||
| 4690 | EXPECT(hold_on(qb, 28, 1)); | ||
| 4691 | fence_signal(c_written, action_sig); | ||
| 4692 | EXPECT(xs::list_values_idle(3000) && cell2(28) == 1); | ||
| 4693 | xs::set_copy_page_mappings_hook(nullptr); | ||
| 4694 | stats = xs::list_value_stats(); | ||
| 4695 | EXPECT(stats.gates_met == met_before_rel + 1 && stats.gates_timed_out == to_before_rel); | ||
| 4696 | |||
| 4697 | // 11c. Demoted gate (3 timeouts -> 4 ms budget) with unrelated in-flight work on qa times out in a few ms, not | ||
| 4698 | // the 12 s active-work cap of the 40 ms full timeout. | ||
| 4699 | for (int i = 0; i < 3; ++i) EXPECT(hold_on(qb, 29, 1) && xs::list_values_idle(3000)); | ||
| 4700 | std::uint64_t unrelated_sig = 0; | ||
| 4701 | EXPECT(write_on_a(30, 1, unrelated_sig)); | ||
| 4702 | const std::uint64_t short_before_dem = xs::list_value_stats().gates_short; | ||
| 4703 | const std::uint64_t to_before_dem = xs::list_value_stats().gates_timed_out; | ||
| 4704 | started = Clock::now(); | ||
| 4705 | EXPECT(hold_on(qb, 29, 1)); | ||
| 4706 | for (int i = 0; i < 1000 && xs::list_value_stats().gates_timed_out == to_before_dem; ++i) Sleep(1); | ||
| 4707 | const auto demoted_active_ms = ms_since(started); | ||
| 4708 | EXPECT(xs::list_value_stats().gates_timed_out == to_before_dem + 1 && | ||
| 4709 | xs::list_value_stats().gates_short == short_before_dem + 1 && demoted_active_ms < 500); | ||
| 4710 | fence_signal(a_written, unrelated_sig); | ||
| 4711 | EXPECT(xs::list_values_idle(3000)); | ||
| 4712 | |||
| 4713 | // 11d. Stuck matching producer (fence never signals) still hits the finite max pause cap instead of hanging. | ||
| 4714 | const std::uint64_t to_before_stuck = xs::list_value_stats().gates_timed_out; | ||
| 4715 | started = Clock::now(); | ||
| 4716 | EXPECT(hold_on(qb, 29, 1)); | ||
| 4717 | std::uint64_t stuck_sig = 0; | ||
| 4718 | EXPECT(write_on_a(29, 1, stuck_sig)); | ||
| 4719 | for (int i = 0; i < 1000 && xs::list_value_stats().gates_timed_out == to_before_stuck; ++i) Sleep(1); | ||
| 4720 | const auto stuck_producer_ms = ms_since(started); | ||
| 4721 | EXPECT(xs::list_value_stats().gates_timed_out == to_before_stuck + 1 && stuck_producer_ms < 500); | ||
| 4722 | fence_signal(a_written, stuck_sig); | ||
| 4723 | EXPECT(xs::list_values_idle(3000)); | ||
| 4724 | xs::set_list_value_wait_timeout_ms(5000); | ||
| 4725 | |||
| 4647 | // 8. stop() ends both threads. Afterwards nothing new is landed or opened (the process is ending: a gate | 4726 | // 8. stop() ends both threads. Afterwards nothing new is landed or opened (the process is ending: a gate |
| 4648 | // signalled from another thread could open one whose remap was skipped, or go below one still to come), and | 4727 | // signalled from another thread could open one whose remap was skipped, or go below one still to come), and |
| 4649 | // CopyPageMappingsBatchX remaps at the call rather than wait for a queue whose gates stay shut. | 4728 | // CopyPageMappingsBatchX remaps at the call rather than wait for a queue whose gates stay shut. |