diff options
| author | DadaCap <167002618+DadaCap@users.noreply.github.com> | 2026-11-24 21:09:02 +0100 |
|---|---|---|
| committer | DadaCap <167002618+DadaCap@users.noreply.github.com> | 2026-11-24 21:09:02 +0100 |
| commit | bc245e5046124941bbdc7bb5c3bd7c739da4e03e (patch) | |
| tree | 5b780fbcbc1dd131ee635980dfe3e996ac72928f /runtime | |
| parent | 30450e0e96e1df700bbfa9505433c9b9940e8694 (diff) | |
| parent | 58be9cdf8df9a31bc7f6c068991f1aed381f7f4d (diff) | |
Merge remote-tracking branch 'origin/main' into vcc-tuple-resync
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime')
73 files changed, 6232 insertions, 604 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40..e1dc13772 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt | |||
| @@ -106,6 +106,46 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 106 | MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>" | 106 | MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>" |
| 107 | ) | 107 | ) |
| 108 | 108 | ||
| 109 | # Rust XMA2 decoder (runtime/xma_decoder), built at configure time when cargo is on PATH. | ||
| 110 | # Without it (or if that build fails) the runtime still builds and XMA voices output silence. | ||
| 111 | option(LEONIDA_REQUIRE_XMA2_DECODER "Fail configure if the Rust XMA2 decoder is unavailable" OFF) | ||
| 112 | find_program(LEONIDA_CARGO cargo) | ||
| 113 | if(LEONIDA_CARGO) | ||
| 114 | # Cargo's host (or configured default target) can differ from the runtime's MSVC ABI. | ||
| 115 | set(_xma_target x86_64-pc-windows-msvc) | ||
| 116 | set(_xma_target_dir ${CMAKE_BINARY_DIR}/xma_decoder) | ||
| 117 | set(_xma_lib ${_xma_target_dir}/${_xma_target}/release/leonida_xma2_decoder.lib) | ||
| 118 | set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS | ||
| 119 | ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.toml | ||
| 120 | ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.lock | ||
| 121 | ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/src/lib.rs) | ||
| 122 | execute_process( | ||
| 123 | COMMAND ${LEONIDA_CARGO} build --release --locked --target ${_xma_target} | ||
| 124 | --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.toml | ||
| 125 | --target-dir ${_xma_target_dir} | ||
| 126 | TIMEOUT 120 | ||
| 127 | RESULT_VARIABLE _xma_result) | ||
| 128 | if(_xma_result STREQUAL "0" AND EXISTS ${_xma_lib}) | ||
| 129 | add_library(leonida_xma2_decoder STATIC IMPORTED) | ||
| 130 | # Link Rust's Windows SDK dependencies. CMake's C++ target selects its own CRT | ||
| 131 | # (/MD or /MDd); the C ABI keeps allocation and deallocation on the same side. | ||
| 132 | # synchronization: Rust's std imports WaitOnAddress and WakeByAddress*, which MSVC's | ||
| 133 | # default libraries cover but clang-cl with an xwin SDK does not (lld-link: undefined symbol). | ||
| 134 | set_target_properties(leonida_xma2_decoder PROPERTIES | ||
| 135 | IMPORTED_LOCATION ${_xma_lib} | ||
| 136 | INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder | ||
| 137 | INTERFACE_COMPILE_DEFINITIONS LEONIDA_HAVE_XMA2_DECODER=1 | ||
| 138 | INTERFACE_LINK_LIBRARIES "kernel32;ntdll;userenv;ws2_32;dbghelp;synchronization") | ||
| 139 | else() | ||
| 140 | message(WARNING "cargo build of runtime/xma_decoder failed: XMA voices will be silent") | ||
| 141 | endif() | ||
| 142 | else() | ||
| 143 | message(STATUS "cargo not found: runtime/xma_decoder not built, XMA voices will be silent") | ||
| 144 | endif() | ||
| 145 | if(LEONIDA_REQUIRE_XMA2_DECODER AND NOT TARGET leonida_xma2_decoder) | ||
| 146 | message(FATAL_ERROR "LEONIDA_REQUIRE_XMA2_DECODER is enabled, but the Rust XMA2 decoder is unavailable") | ||
| 147 | endif() | ||
| 148 | |||
| 109 | add_executable(gta6rt | 149 | add_executable(gta6rt |
| 110 | src/main.cpp | 150 | src/main.cpp |
| 111 | src/host_cpu.cpp | 151 | src/host_cpu.cpp |
| @@ -113,6 +153,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 113 | shims/registry.cpp | 153 | shims/registry.cpp |
| 114 | shims/file_system.cpp | 154 | shims/file_system.cpp |
| 115 | shims/winhttp_offline.cpp | 155 | shims/winhttp_offline.cpp |
| 156 | shims/ws2_offline.cpp | ||
| 116 | shims/xmem.cpp | 157 | shims/xmem.cpp |
| 117 | shims/xg_xs.cpp | 158 | shims/xg_xs.cpp |
| 118 | shims/acphal.cpp | 159 | shims/acphal.cpp |
| @@ -250,6 +291,11 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 250 | target_compile_options(acphal_test PRIVATE /W4 /permissive- /utf-8) | 291 | target_compile_options(acphal_test PRIVATE /W4 /permissive- /utf-8) |
| 251 | target_link_options(acphal_test PRIVATE /OPT:NOREF) | 292 | target_link_options(acphal_test PRIVATE /OPT:NOREF) |
| 252 | 293 | ||
| 294 | if(TARGET leonida_xma2_decoder) | ||
| 295 | target_link_libraries(gta6rt PRIVATE leonida_xma2_decoder) | ||
| 296 | target_link_libraries(acphal_test PRIVATE leonida_xma2_decoder) | ||
| 297 | endif() | ||
| 298 | |||
| 253 | # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for | 299 | # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for |
| 254 | # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. | 300 | # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. |
| 255 | add_executable(cpu_emulation_test test/cpu_emulation_test.cpp) | 301 | add_executable(cpu_emulation_test test/cpu_emulation_test.cpp) |
| @@ -326,6 +372,18 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 326 | target_compile_options(winhttp_offline_test PRIVATE /W4 /permissive- /utf-8) | 372 | target_compile_options(winhttp_offline_test PRIVATE /W4 /permissive- /utf-8) |
| 327 | target_link_options(winhttp_offline_test PRIVATE /OPT:NOREF) | 373 | target_link_options(winhttp_offline_test PRIVATE /OPT:NOREF) |
| 328 | 374 | ||
| 375 | # Offline Winsock2 for mapped images (ws2_32.dll restricted to loopback); no external network is touched. | ||
| 376 | add_executable(ws2_offline_test | ||
| 377 | test/ws2_offline_test.cpp | ||
| 378 | shims/ws2_offline.cpp | ||
| 379 | shims/registry.cpp | ||
| 380 | ) | ||
| 381 | target_include_directories(ws2_offline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) | ||
| 382 | target_compile_definitions(ws2_offline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | ||
| 383 | target_compile_options(ws2_offline_test PRIVATE /W4 /permissive- /utf-8) | ||
| 384 | target_link_options(ws2_offline_test PRIVATE /OPT:NOREF) | ||
| 385 | target_link_libraries(ws2_offline_test PRIVATE ws2_32) | ||
| 386 | |||
| 329 | # COM lifecycle and helper shims for api-ms-win-core-com-l1-1-*.dll. | 387 | # COM lifecycle and helper shims for api-ms-win-core-com-l1-1-*.dll. |
| 330 | add_executable(com_shim_test | 388 | add_executable(com_shim_test |
| 331 | test/com_shim_test.cpp | 389 | test/com_shim_test.cpp |
| @@ -577,6 +635,10 @@ if(BUILD_TESTING) | |||
| 577 | target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) | 635 | target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) |
| 578 | add_dependencies(loader_test gta6rt_tls_host) | 636 | add_dependencies(loader_test gta6rt_tls_host) |
| 579 | add_test(NAME loader COMMAND loader_test) | 637 | add_test(NAME loader COMMAND loader_test) |
| 638 | # It takes about 10 s under Wine and under a minute on a desktop with a virus scanner. Before #239 it waited on | ||
| 639 | # a "Bad Image" box on the Windows runner until the job's own timeout cancelled the whole job (every Windows | ||
| 640 | # run from 24 Nov 00:37 to 03:32 UTC); a hang like that now fails this test instead. | ||
| 641 | set_tests_properties(loader PROPERTIES TIMEOUT 180) | ||
| 580 | # PE loader tests use two locally built fixtures: a DLL with exports, imports and relocations, and an EXE that | 642 | # PE loader tests use two locally built fixtures: a DLL with exports, imports and relocations, and an EXE that |
| 581 | # imports it so Loader::load exercises recursive module loading. They contain no game data. | 643 | # imports it so Loader::load exercises recursive module loading. They contain no game data. |
| 582 | set(TINY_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/fixtures/$<CONFIG>") | 644 | set(TINY_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/fixtures/$<CONFIG>") |
| @@ -610,6 +672,8 @@ if(BUILD_TESTING) | |||
| 610 | add_executable(tiny_ga_tls test/fixtures/tiny_ga_tls.cpp) | 672 | add_executable(tiny_ga_tls test/fixtures/tiny_ga_tls.cpp) |
| 611 | target_compile_definitions(tiny_ga_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | 673 | target_compile_definitions(tiny_ga_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) |
| 612 | target_compile_options(tiny_ga_tls PRIVATE /W4 /permissive- /utf-8 /GS- /GA) | 674 | target_compile_options(tiny_ga_tls PRIVATE /W4 /permissive- /utf-8 /GS- /GA) |
| 675 | # /GA can remove the _tls_index reference that pulls in the CRT TLS directory. | ||
| 676 | target_link_options(tiny_ga_tls PRIVATE /INCLUDE:_tls_used) | ||
| 613 | set_target_properties(tiny_ga_tls PROPERTIES | 677 | set_target_properties(tiny_ga_tls PROPERTIES |
| 614 | OUTPUT_NAME tiny_ga_tls | 678 | OUTPUT_NAME tiny_ga_tls |
| 615 | RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" | 679 | RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" |
| @@ -1162,6 +1226,7 @@ if(BUILD_TESTING) | |||
| 1162 | endif() | 1226 | endif() |
| 1163 | if(WIN32 AND TARGET acphal_test) | 1227 | if(WIN32 AND TARGET acphal_test) |
| 1164 | add_test(NAME acphal COMMAND acphal_test) | 1228 | add_test(NAME acphal COMMAND acphal_test) |
| 1229 | add_test(NAME acphal_noncached_only COMMAND acphal_test --noncached-only) | ||
| 1165 | endif() | 1230 | endif() |
| 1166 | if(WIN32 AND TARGET cpu_emulation_test) | 1231 | if(WIN32 AND TARGET cpu_emulation_test) |
| 1167 | add_test(NAME cpu_emulation COMMAND cpu_emulation_test) | 1232 | add_test(NAME cpu_emulation COMMAND cpu_emulation_test) |
| @@ -1181,6 +1246,9 @@ if(BUILD_TESTING) | |||
| 1181 | if(WIN32 AND TARGET winhttp_offline_test) | 1246 | if(WIN32 AND TARGET winhttp_offline_test) |
| 1182 | add_test(NAME winhttp_offline COMMAND winhttp_offline_test) | 1247 | add_test(NAME winhttp_offline COMMAND winhttp_offline_test) |
| 1183 | endif() | 1248 | endif() |
| 1249 | if(WIN32 AND TARGET ws2_offline_test) | ||
| 1250 | add_test(NAME ws2_offline COMMAND ws2_offline_test) | ||
| 1251 | endif() | ||
| 1184 | if(WIN32 AND TARGET com_shim_test) | 1252 | if(WIN32 AND TARGET com_shim_test) |
| 1185 | add_test(NAME com_shim COMMAND com_shim_test) | 1253 | add_test(NAME com_shim COMMAND com_shim_test) |
| 1186 | endif() | 1254 | endif() |
| @@ -1411,6 +1479,11 @@ if(TARGET Vulkan::Headers) | |||
| 1411 | add_executable(vk_shader_fma_test test/vk_shader_fma_test.cpp) | 1479 | add_executable(vk_shader_fma_test test/vk_shader_fma_test.cpp) |
| 1412 | target_link_libraries(vk_shader_fma_test PRIVATE Vulkan::Headers) | 1480 | target_link_libraries(vk_shader_fma_test PRIVATE Vulkan::Headers) |
| 1413 | add_test(NAME vk_shader_fma COMMAND vk_shader_fma_test) | 1481 | add_test(NAME vk_shader_fma COMMAND vk_shader_fma_test) |
| 1482 | add_executable(xdxr_builder_validation_test test/xdxr_builder_validation_test.cpp) | ||
| 1483 | target_link_libraries(xdxr_builder_validation_test PRIVATE Vulkan::Headers) | ||
| 1484 | if(BUILD_TESTING) | ||
| 1485 | add_test(NAME xdxr_builder_validation COMMAND xdxr_builder_validation_test) | ||
| 1486 | endif() | ||
| 1414 | # LEONIDA_VK_DEVICE names the GPU in every harness (docs/testing.md, "Choosing the GPU"): a filter that matches no | 1487 | # LEONIDA_VK_DEVICE names the GPU in every harness (docs/testing.md, "Choosing the GPU"): a filter that matches no |
| 1415 | # device fails the run in vk_descriptor_bench and vk_sandbox too, instead of testing another GPU (TEST-1141). | 1488 | # device fails the run in vk_descriptor_bench and vk_sandbox too, instead of testing another GPU (TEST-1141). |
| 1416 | find_package(Python3 COMPONENTS Interpreter QUIET) | 1489 | find_package(Python3 COMPONENTS Interpreter QUIET) |
| @@ -1611,6 +1684,18 @@ if(TARGET Vulkan::Headers) | |||
| 1611 | if(BUILD_TESTING) | 1684 | if(BUILD_TESTING) |
| 1612 | add_test(NAME vk_buffer_registration_oom COMMAND vk_buffer_registration_oom_test) | 1685 | add_test(NAME vk_buffer_registration_oom COMMAND vk_buffer_registration_oom_test) |
| 1613 | endif() | 1686 | endif() |
| 1687 | # VulkanContext::replay_.host_at resolves aliasing placed upload buffers across the full requested byte range. | ||
| 1688 | add_executable(vk_host_at_aliasing_test test/vk_host_at_aliasing_test.cpp) | ||
| 1689 | target_link_libraries(vk_host_at_aliasing_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) | ||
| 1690 | if(WIN32) | ||
| 1691 | target_compile_definitions(vk_host_at_aliasing_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | ||
| 1692 | if(MSVC) | ||
| 1693 | target_compile_options(vk_host_at_aliasing_test PRIVATE /W4 /permissive- /EHsc /utf-8) | ||
| 1694 | endif() | ||
| 1695 | endif() | ||
| 1696 | if(BUILD_TESTING) | ||
| 1697 | add_test(NAME vk_host_at_aliasing COMMAND vk_host_at_aliasing_test) | ||
| 1698 | endif() | ||
| 1614 | # CPU-only: ScratchBuffers chunk alignment, retire/collect/forget, and spare cap (runtime/src/vulkan_scratch.h). | 1699 | # CPU-only: ScratchBuffers chunk alignment, retire/collect/forget, and spare cap (runtime/src/vulkan_scratch.h). |
| 1615 | add_executable(vulkan_scratch_test test/vulkan_scratch_test.cpp) | 1700 | add_executable(vulkan_scratch_test test/vulkan_scratch_test.cpp) |
| 1616 | target_link_libraries(vulkan_scratch_test PRIVATE Vulkan::Headers) | 1701 | target_link_libraries(vulkan_scratch_test PRIVATE Vulkan::Headers) |
| @@ -2181,7 +2266,8 @@ if(TARGET Vulkan::Headers) | |||
| 2181 | add_test(NAME d3d12_rgb9e5_rtv COMMAND d3d12_clear_test --rgb9e5) | 2266 | add_test(NAME d3d12_rgb9e5_rtv COMMAND d3d12_clear_test --rgb9e5) |
| 2182 | set_tests_properties(d3d12_rgb9e5_rtv PROPERTIES SKIP_RETURN_CODE 77) | 2267 | set_tests_properties(d3d12_rgb9e5_rtv PROPERTIES SKIP_RETURN_CODE 77) |
| 2183 | add_test(NAME d3d12_clear COMMAND d3d12_clear_test) | 2268 | add_test(NAME d3d12_clear COMMAND d3d12_clear_test) |
| 2184 | set_tests_properties(d3d12_clear PROPERTIES SKIP_RETURN_CODE 77) | 2269 | add_test(NAME d3d12_clear_restricted_depth COMMAND d3d12_clear_test --restricted-depth) |
| 2270 | set_tests_properties(d3d12_clear d3d12_clear_restricted_depth PROPERTIES SKIP_RETURN_CODE 77) | ||
| 2185 | 2271 | ||
| 2186 | # Synthetic typed-view readbacks against Windows WARP; run explicitly on a Vulkan GPU. | 2272 | # Synthetic typed-view readbacks against Windows WARP; run explicitly on a Vulkan GPU. |
| 2187 | add_executable(d3d12_typeless_rtv_test test/d3d12_typeless_rtv_test.cpp) | 2273 | add_executable(d3d12_typeless_rtv_test test/d3d12_typeless_rtv_test.cpp) |
diff --git a/runtime/cmake/translator_deps.cmake b/runtime/cmake/translator_deps.cmake index 3565fe1e2..42be0f0e2 100644 --- a/runtime/cmake/translator_deps.cmake +++ b/runtime/cmake/translator_deps.cmake | |||
| @@ -1,6 +1,6 @@ | |||
| 1 | # What the SPIR-V that test/shaders/build.py writes comes from, besides the .asm files: build.py and the modules it | 1 | # The shader fixtures use test/shaders/build.py, its local imports and the scripts it runs (tools/rdna2spirv.py |
| 2 | # imports, the scripts it runs (tools/rdna2spirv.py, and tools/vk_subgroup_info.py, whose answer picks | 2 | # and tools/vk_subgroup_info.py, whose answer picks --bary-fallback). Track the shader-stage dependencies in |
| 3 | # --bary-fallback), and every module rdna2spirv.py imports or file it reads (make_game.py's TRANSLATION_SOURCES). | 3 | # make_game.py's TRANSLATION_SOURCES here too, including the native PSO catalog writer. |
| 4 | # Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py | 4 | # Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py |
| 5 | # rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064). | 5 | # rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064). |
| 6 | # tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list. | 6 | # tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list. |
| @@ -16,11 +16,14 @@ set(LEONIDA_TRANSLATOR_DEPS | |||
| 16 | ${_leonida_repo}/tools/gfx10_formats.json | 16 | ${_leonida_repo}/tools/gfx10_formats.json |
| 17 | ${_leonida_repo}/tools/lane_masks.py | 17 | ${_leonida_repo}/tools/lane_masks.py |
| 18 | ${_leonida_repo}/tools/mc_command.py | 18 | ${_leonida_repo}/tools/mc_command.py |
| 19 | ${_leonida_repo}/tools/native_pso_hashes.py | ||
| 19 | ${_leonida_repo}/tools/rdna2_decode.py | 20 | ${_leonida_repo}/tools/rdna2_decode.py |
| 20 | ${_leonida_repo}/tools/rdna2_isa_tables.py | 21 | ${_leonida_repo}/tools/rdna2_isa_tables.py |
| 21 | ${_leonida_repo}/tools/rdna2spirv.py | 22 | ${_leonida_repo}/tools/rdna2spirv.py |
| 22 | ${_leonida_repo}/tools/replace_retry.py | 23 | ${_leonida_repo}/tools/replace_retry.py |
| 23 | ${_leonida_repo}/tools/report_paths.py | 24 | ${_leonida_repo}/tools/report_paths.py |
| 25 | ${_leonida_repo}/tools/shader_carve.py | ||
| 26 | ${_leonida_repo}/tools/shader_carve_accel.py | ||
| 24 | ${_leonida_repo}/tools/shader_ir.py | 27 | ${_leonida_repo}/tools/shader_ir.py |
| 25 | ${_leonida_repo}/tools/shader_meta.py | 28 | ${_leonida_repo}/tools/shader_meta.py |
| 26 | ${_leonida_repo}/tools/shader_stage_manifest.py | 29 | ${_leonida_repo}/tools/shader_stage_manifest.py |
diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp index 5ead016d6..f1c33ddd9 100644 --- a/runtime/shims/acphal.cpp +++ b/runtime/shims/acphal.cpp | |||
| @@ -1,10 +1,12 @@ | |||
| 1 | // acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine | 1 | // acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine |
| 2 | // (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series. | 2 | // (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series. |
| 3 | // | 3 | // |
| 4 | // On a PC there is no SHAPE/ACP hardware and APU physical memory does not exist. | 4 | // Provides: |
| 5 | // This shim creates the APU heap from process memory and manages allocations within it. | 5 | // - A VirtualAlloc-backed APU heap (cached + non-cached) with 32-bit device addresses; |
| 6 | // The SHAPE context arrays are allocated on the process heap; the ACP interface | 6 | // - SHAPE context arrays sized to the documented GDK strides; |
| 7 | // accepts and acknowledges commands to allow audio bring-up to proceed cleanly. | 7 | // - The IAcpHal command and message queue (registration, completion, disconnect, |
| 8 | // flowgraph acknowledgement, and APU notification word writes); | ||
| 9 | // - A background XMA2 decoder pumping enabled SHAPE_XMA_CONTEXT output rings. | ||
| 8 | // | 10 | // |
| 9 | // Signatures from the public GDK reference (devdocs.xbox.com): | 11 | // Signatures from the public GDK reference (devdocs.xbox.com): |
| 10 | // AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS. | 12 | // AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS. |
| @@ -14,21 +16,37 @@ | |||
| 14 | 16 | ||
| 15 | #include <windows.h> | 17 | #include <windows.h> |
| 16 | 18 | ||
| 17 | #include <atomic> | 19 | #include <algorithm> |
| 18 | #include <array> | 20 | #include <array> |
| 21 | #include <atomic> | ||
| 22 | #include <chrono> | ||
| 23 | #include <climits> | ||
| 24 | #include <condition_variable> | ||
| 19 | #include <cstddef> | 25 | #include <cstddef> |
| 20 | #include <cstdint> | 26 | #include <cstdint> |
| 21 | #include <cstdio> | 27 | #include <cstdio> |
| 22 | #include <cstdlib> | 28 | #include <cstdlib> |
| 23 | #include <cstring> | 29 | #include <cstring> |
| 30 | #include <deque> | ||
| 24 | #include <map> | 31 | #include <map> |
| 32 | #include <memory> | ||
| 25 | #include <mutex> | 33 | #include <mutex> |
| 34 | #include <new> | ||
| 35 | #include <optional> | ||
| 26 | #include <set> | 36 | #include <set> |
| 37 | #include <shared_mutex> | ||
| 38 | #include <stop_token> | ||
| 27 | #include <string> | 39 | #include <string> |
| 40 | #include <string_view> | ||
| 41 | #include <system_error> | ||
| 42 | #include <thread> | ||
| 28 | #include <vector> | 43 | #include <vector> |
| 29 | 44 | ||
| 30 | #include "shims.h" | 45 | #include "shims.h" |
| 31 | #include "startup_trace.h" | 46 | #include "startup_trace.h" |
| 47 | #if defined(LEONIDA_HAVE_XMA2_DECODER) | ||
| 48 | #include "leonida_xma2_decoder.h" | ||
| 49 | #endif | ||
| 32 | 50 | ||
| 33 | namespace { | 51 | namespace { |
| 34 | 52 | ||
| @@ -124,24 +142,7 @@ struct SHAPE_DMA_CONTEXT { | |||
| 124 | static_assert(sizeof(SHAPE_DMA_CONTEXT) == 16, "SHAPE_DMA_CONTEXT is 16 bytes per GDK"); | 142 | static_assert(sizeof(SHAPE_DMA_CONTEXT) == 16, "SHAPE_DMA_CONTEXT is 16 bytes per GDK"); |
| 125 | 143 | ||
| 126 | struct SHAPE_XMA_CONTEXT { | 144 | struct SHAPE_XMA_CONTEXT { |
| 127 | uint32_t sizeRead0 : 12; | 145 | uint32_t words[16]; // See the shared word layout above the XMA engine. |
| 128 | uint32_t numLoops : 8; | ||
| 129 | uint32_t validBuffer : 2; | ||
| 130 | uint32_t sizeWrite : 5; | ||
| 131 | uint32_t offsetWrite : 5; | ||
| 132 | uint32_t sizeRead1 : 12; | ||
| 133 | uint32_t sequenceNumber : 12; | ||
| 134 | uint32_t stopSampleAddress : 8; | ||
| 135 | uint32_t subframeOffset : 4; | ||
| 136 | uint32_t reserved0 : 1; | ||
| 137 | uint32_t isLooping : 1; | ||
| 138 | uint32_t subframeSkip : 2; | ||
| 139 | uint32_t packetMetadata : 16; | ||
| 140 | uint32_t currentByteOffset : 26; | ||
| 141 | uint32_t reserved1 : 6; | ||
| 142 | uint32_t loopStartOffset : 26; | ||
| 143 | uint32_t loopEndOffset : 6; | ||
| 144 | uint32_t reserved[11]; // the GDK's 64-byte context: the published field list leaves one trailing word | ||
| 145 | }; | 146 | }; |
| 146 | static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64, "SHAPE_XMA_CONTEXT is 64 bytes per GDK"); | 147 | static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64, "SHAPE_XMA_CONTEXT is 64 bytes per GDK"); |
| 147 | 148 | ||
| @@ -194,21 +195,28 @@ static_assert(offsetof(SHAPE_CONTEXTS, xmaContextArray) == 0x38, | |||
| 194 | 195 | ||
| 195 | // ---- Startup trace helper ---- | 196 | // ---- Startup trace helper ---- |
| 196 | 197 | ||
| 197 | void trace_call(const char* api, const std::string& detail) { | 198 | void trace_call(const char* api, std::string_view detail = {}) noexcept try { |
| 198 | if (!rt::startup_trace::enabled()) return; | 199 | if (!rt::startup_trace::enabled()) return; |
| 199 | static std::mutex mutex; | 200 | static std::mutex mutex; |
| 200 | static std::set<std::string> seen; | 201 | static std::set<std::string> seen; |
| 201 | { | 202 | { |
| 202 | const std::lock_guard lock(mutex); | 203 | const std::lock_guard lock(mutex); |
| 203 | if (!seen.insert(std::string(api) + detail).second) return; | 204 | if (!seen.insert(std::string(api).append(detail)).second) return; |
| 204 | } | 205 | } |
| 205 | rt::startup_trace::event("acphal", | 206 | rt::startup_trace::event("acphal", |
| 206 | std::string("\"api\":\"") + api + "\"" + detail); | 207 | (std::string("\"api\":\"") + api + "\"").append(detail)); |
| 208 | } catch (...) { | ||
| 209 | // Tracing cannot change the result of a guest-facing call. | ||
| 207 | } | 210 | } |
| 208 | 211 | ||
| 209 | // ---- Genuine APU Heap Implementation ---- | 212 | // ---- Genuine APU Heap Implementation ---- |
| 210 | 213 | ||
| 211 | constexpr uint32_t kApuBaseAddress = 0x40000000u; | 214 | constexpr uint32_t kApuBaseAddress = 0x40000000u; |
| 215 | constexpr uint64_t kApuRegionAlignment = 0x10000u; | ||
| 216 | |||
| 217 | uint64_t align_apu_region(uint64_t size) { | ||
| 218 | return (size + kApuRegionAlignment - 1) & ~(kApuRegionAlignment - 1); | ||
| 219 | } | ||
| 212 | 220 | ||
| 213 | struct ApuRegion { | 221 | struct ApuRegion { |
| 214 | void* base = nullptr; | 222 | void* base = nullptr; |
| @@ -241,6 +249,13 @@ struct ApuRegion { | |||
| 241 | return static_cast<uint8_t*>(base) + offset; | 249 | return static_cast<uint8_t*>(base) + offset; |
| 242 | } | 250 | } |
| 243 | 251 | ||
| 252 | uint8_t* span_from_offset(uint32_t offset, std::size_t len) const { | ||
| 253 | if (!base || len == 0 || offset >= size) return nullptr; | ||
| 254 | const uint64_t remaining = size - offset; | ||
| 255 | if (len > remaining) return nullptr; | ||
| 256 | return static_cast<uint8_t*>(base) + offset; | ||
| 257 | } | ||
| 258 | |||
| 244 | void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) { | 259 | void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) { |
| 245 | if (alloc_size == 0 || alignment == 0) return nullptr; | 260 | if (alloc_size == 0 || alignment == 0) return nullptr; |
| 246 | uint64_t at = 0; | 261 | uint64_t at = 0; |
| @@ -281,48 +296,667 @@ ApuRegion g_cached_heap; | |||
| 281 | ApuRegion g_noncached_heap; | 296 | ApuRegion g_noncached_heap; |
| 282 | 297 | ||
| 283 | // Tracked SHAPE context arrays | 298 | // Tracked SHAPE context arrays |
| 284 | std::vector<void*> g_active_shape_arrays; | 299 | struct ShapeArrayFree { |
| 300 | void operator()(void* array) const noexcept { std::free(array); } | ||
| 301 | }; | ||
| 302 | |||
| 303 | using ShapeAllocation = std::array<std::unique_ptr<void, ShapeArrayFree>, 6>; | ||
| 304 | |||
| 305 | std::mutex g_shape_mutex; | ||
| 306 | std::vector<ShapeAllocation> g_shape_allocations; | ||
| 307 | |||
| 308 | // Resolves a contiguous [apu, apu + len) byte range inside the APU heap. | ||
| 309 | uint8_t* apu_span(uint32_t apu, std::size_t len) { | ||
| 310 | if (apu < kApuBaseAddress || len == 0) return nullptr; | ||
| 311 | std::lock_guard lock(g_apu_mutex); | ||
| 312 | const uint32_t offset = apu - kApuBaseAddress; | ||
| 313 | if (g_cached_heap.base && offset < g_cached_heap.size) { | ||
| 314 | return g_cached_heap.span_from_offset(offset, len); | ||
| 315 | } | ||
| 316 | if (g_noncached_heap.base) { | ||
| 317 | const uint64_t cached_span = align_apu_region(g_cached_heap.size); | ||
| 318 | if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) { | ||
| 319 | return g_noncached_heap.span_from_offset( | ||
| 320 | static_cast<uint32_t>(offset - cached_span), len); | ||
| 321 | } | ||
| 322 | } | ||
| 323 | return nullptr; | ||
| 324 | } | ||
| 325 | |||
| 326 | // ---- ACP Command / Message Protocol Constants ---- | ||
| 327 | |||
| 328 | constexpr uint32_t kCmdLoadFlowgraph = 1; | ||
| 329 | constexpr uint32_t kCmdRegisterMessages = 2; | ||
| 330 | constexpr uint32_t kCmdUnregisterMessages = 3; | ||
| 331 | constexpr uint32_t kCmdEnableXma = 5; | ||
| 332 | constexpr uint32_t kCmdEnableXmas = 6; | ||
| 333 | constexpr uint32_t kCmdDisableXma = 7; | ||
| 334 | constexpr uint32_t kCmdDisableXmas = 8; | ||
| 335 | constexpr uint32_t kCmdAdvanceXmaRead = 18; | ||
| 336 | |||
| 337 | constexpr uint32_t kMsgFlowgraphCompleted = 0x02u; | ||
| 338 | constexpr uint32_t kMsgCommandCompleted = 0x10u; | ||
| 339 | constexpr uint32_t kMsgDisconnected = 0x80u; | ||
| 340 | |||
| 341 | // 128 samples per audio frame at 48 kHz = 375 audio frames/second. | ||
| 342 | constexpr uint64_t kAudioFramesPerSecond = 375; | ||
| 343 | |||
| 344 | // ---- XMA2 Hardware Context Decoder Engine ---- | ||
| 345 | // | ||
| 346 | // Each 64-byte SHAPE_XMA_CONTEXT holds 16 32-bit words shared with the title: | ||
| 347 | // Word 0: input 0 packets (0..11), loop count (12..19, 255 = forever), | ||
| 348 | // valid input bits (20..21), output ring blocks (22..26), write block (27..31). | ||
| 349 | // Word 1: input 1 packets (0..11), loop end subframe (12..13), loop start skip subframes | ||
| 350 | // (17..19), initial skip subframes (24..26), rate index (27..28: 24/32/44.1/48 kHz), | ||
| 351 | // stereo (29), output writable (31). | ||
| 352 | // Word 2: read bit offset (0..25), error status (26..30), error flag (31). | ||
| 353 | // Word 3: loop start bit offset (0..25). | ||
| 354 | // Word 4: loop end bit offset (0..25), current input buffer index (31). | ||
| 355 | // Word 5: input 0 APU address. | ||
| 356 | // Word 6: input 1 APU address. | ||
| 357 | // Word 7: output ring APU address. | ||
| 358 | // Word 8: overlap buffer APU address. | ||
| 359 | // Word 9: output read block index (0..4). | ||
| 360 | // | ||
| 361 | // Packets are decoded by the Rust decoder in runtime/xma_decoder when CMake found cargo (LEONIDA_HAVE_XMA2_DECODER); | ||
| 362 | // otherwise each packet becomes silence for its frame count. The read offset (word 2) and the loop points (words 3 | ||
| 363 | // and 4) are used per 2048-byte packet, so the loop-end subframe (word 1 bits 12..13) is not applied. | ||
| 364 | |||
| 365 | constexpr std::size_t kXmaBlockBytes = 256; | ||
| 366 | constexpr std::size_t kXmaSamplesPerBlock = kXmaBlockBytes / 2; | ||
| 367 | constexpr std::size_t kXmaPacketBytes = 2048; | ||
| 368 | constexpr std::size_t kXmaPacketBits = kXmaPacketBytes * 8; | ||
| 369 | constexpr std::size_t kXmaSubframeSamples = 128; | ||
| 370 | constexpr std::size_t kXmaFrameSamples = 512; | ||
| 371 | constexpr uint32_t kXmaErrorInputInvalid = 4; | ||
| 372 | |||
| 373 | #if defined(LEONIDA_HAVE_XMA2_DECODER) | ||
| 374 | constexpr uint32_t kXmaRates[4] = {24000, 32000, 44100, 48000}; | ||
| 375 | struct Xma2DecoderFree { | ||
| 376 | void operator()(LeonidaXma2Decoder* d) const noexcept { leonida_xma2_decoder_destroy(d); } | ||
| 377 | }; | ||
| 378 | struct Xma2PcmFree { | ||
| 379 | void operator()(LeonidaXma2PcmBlock* b) const noexcept { leonida_xma2_pcm_destroy(b); } | ||
| 380 | }; | ||
| 381 | #endif | ||
| 382 | |||
| 383 | struct XmaContextView { | ||
| 384 | uint32_t* words = nullptr; | ||
| 385 | |||
| 386 | uint32_t get(std::size_t index) const { return std::atomic_ref(words[index]).load(); } | ||
| 387 | |||
| 388 | uint32_t field(std::size_t index, uint32_t shift, uint32_t bits) const { | ||
| 389 | const uint32_t mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u); | ||
| 390 | return (get(index) >> shift) & mask; | ||
| 391 | } | ||
| 392 | |||
| 393 | uint32_t set_field(std::size_t index, uint32_t shift, uint32_t bits, uint32_t value) const { | ||
| 394 | const uint32_t raw_mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u); | ||
| 395 | const uint32_t mask = raw_mask << shift; | ||
| 396 | const uint32_t field_value = (value << shift) & mask; | ||
| 397 | std::atomic_ref word(words[index]); | ||
| 398 | uint32_t previous = word.load(); | ||
| 399 | while (!word.compare_exchange_weak(previous, (previous & ~mask) | field_value)) {} | ||
| 400 | return previous; | ||
| 401 | } | ||
| 402 | |||
| 403 | }; | ||
| 404 | |||
| 405 | struct XmaVoice { | ||
| 406 | explicit XmaVoice(uint32_t format_bits) : pcm(0), format(format_bits) {} | ||
| 407 | std::size_t channels() const { return 1u + (format >> 2); } | ||
| 408 | std::size_t queued_samples() const { return pcm.size() - pcm_read; } | ||
| 409 | |||
| 410 | #if defined(LEONIDA_HAVE_XMA2_DECODER) | ||
| 411 | std::unique_ptr<LeonidaXma2Decoder, Xma2DecoderFree> decoder; | ||
| 412 | #endif | ||
| 413 | std::vector<int16_t> pcm; | ||
| 414 | std::size_t pcm_read = 0; | ||
| 415 | std::size_t loop_skip = 0; // samples per channel to drop after a rewind | ||
| 416 | uint32_t format; // SHAPE word 1 bits 27..29, rate and channel layout | ||
| 417 | bool ended = false; | ||
| 418 | }; | ||
| 419 | |||
| 420 | struct XmaVoiceSlot { | ||
| 421 | std::mutex mutex; | ||
| 422 | std::optional<XmaVoice> voice; | ||
| 423 | }; | ||
| 424 | |||
| 425 | class XmaEngine { | ||
| 426 | public: | ||
| 427 | ~XmaEngine() { unbind(); } | ||
| 428 | |||
| 429 | void bind(SHAPE_XMA_CONTEXT* array, uint32_t count) { | ||
| 430 | // Construct with a size so MSVC's Debug iterator allocations can also fail | ||
| 431 | // through this call instead of the noexcept default constructor. | ||
| 432 | std::vector<std::unique_ptr<XmaVoiceSlot>> slots(count); | ||
| 433 | for (auto& slot : slots) slot = std::make_unique<XmaVoiceSlot>(); | ||
| 434 | unbind(); | ||
| 435 | std::unique_lock lock(table_mutex_); | ||
| 436 | array_ = array; | ||
| 437 | voices_.swap(slots); | ||
| 438 | } | ||
| 439 | |||
| 440 | void unbind() { | ||
| 441 | { | ||
| 442 | std::unique_lock lock(table_mutex_); | ||
| 443 | array_ = nullptr; | ||
| 444 | voices_.clear(); | ||
| 445 | active_count_.store(0, std::memory_order_relaxed); | ||
| 446 | } | ||
| 447 | // Once detached, commands cannot start a worker for this table. | ||
| 448 | stop_worker(); | ||
| 449 | } | ||
| 450 | |||
| 451 | bool handle_command(uint32_t command, const void* config) { | ||
| 452 | auto read_word = [config](std::size_t index) -> uint32_t { | ||
| 453 | if (!config) return 0u; | ||
| 454 | uint32_t value = 0; | ||
| 455 | std::memcpy(&value, static_cast<const uint8_t*>(config) + index * sizeof(uint32_t), | ||
| 456 | sizeof(uint32_t)); | ||
| 457 | return value; | ||
| 458 | }; | ||
| 459 | |||
| 460 | switch (command) { | ||
| 461 | case kCmdEnableXma: | ||
| 462 | if (config) enable(read_word(0)); | ||
| 463 | return true; | ||
| 464 | case kCmdDisableXma: | ||
| 465 | if (config) disable(read_word(0)); | ||
| 466 | return true; | ||
| 467 | case kCmdEnableXmas: | ||
| 468 | case kCmdDisableXmas: { | ||
| 469 | std::shared_lock lock(table_mutex_); | ||
| 470 | const std::size_t count = voices_.size(); | ||
| 471 | lock.unlock(); | ||
| 472 | if (!config) return true; | ||
| 473 | for (std::size_t i = 0; i < count; ++i) { | ||
| 474 | const uint32_t bits = read_word(i / 32); | ||
| 475 | if ((bits & (1u << (i % 32))) != 0) { | ||
| 476 | if (command == kCmdEnableXmas) { | ||
| 477 | enable(static_cast<uint32_t>(i)); | ||
| 478 | } else { | ||
| 479 | disable(static_cast<uint32_t>(i)); | ||
| 480 | } | ||
| 481 | } | ||
| 482 | } | ||
| 483 | return true; | ||
| 484 | } | ||
| 485 | case kCmdAdvanceXmaRead: | ||
| 486 | if (config) advance_read(read_word(0), read_word(1)); | ||
| 487 | return true; | ||
| 488 | default: | ||
| 489 | return false; | ||
| 490 | } | ||
| 491 | } | ||
| 492 | |||
| 493 | void enable(uint32_t index) { | ||
| 494 | std::shared_lock table_lock(table_mutex_); | ||
| 495 | XmaContextView ctx = context_locked(index); | ||
| 496 | if (!ctx.words) return; | ||
| 497 | |||
| 498 | { | ||
| 499 | std::lock_guard slot_lock(voices_[index]->mutex); | ||
| 500 | auto& voice = voices_[index]->voice; | ||
| 501 | const uint32_t format = ctx.field(1, 27, 3); | ||
| 502 | // The worker cannot access the voice until the slot is unlocked. | ||
| 503 | ensure_worker_and_wake(); | ||
| 504 | if (!voice) { | ||
| 505 | voice.emplace(format); | ||
| 506 | active_count_.fetch_add(1, std::memory_order_relaxed); | ||
| 507 | } else if (voice->format != format) { | ||
| 508 | voice->pcm.clear(); | ||
| 509 | voice->pcm_read = 0; | ||
| 510 | voice->loop_skip = 0; | ||
| 511 | voice->format = format; | ||
| 512 | #if defined(LEONIDA_HAVE_XMA2_DECODER) | ||
| 513 | voice->decoder.reset(); | ||
| 514 | #endif | ||
| 515 | } | ||
| 516 | voice->ended = false; | ||
| 517 | ctx.set_field(2, 26, 6, 0); | ||
| 518 | } | ||
| 519 | } | ||
| 520 | |||
| 521 | void disable(uint32_t index) { | ||
| 522 | std::shared_lock table_lock(table_mutex_); | ||
| 523 | if (index >= voices_.size()) return; | ||
| 524 | std::lock_guard slot_lock(voices_[index]->mutex); | ||
| 525 | if (voices_[index]->voice.has_value()) { | ||
| 526 | voices_[index]->voice.reset(); | ||
| 527 | active_count_.fetch_sub(1, std::memory_order_relaxed); | ||
| 528 | } | ||
| 529 | } | ||
| 530 | |||
| 531 | void advance_read(uint32_t index, uint32_t blocks) { | ||
| 532 | std::shared_lock table_lock(table_mutex_); | ||
| 533 | XmaContextView ctx = context_locked(index); | ||
| 534 | if (!ctx.words) return; | ||
| 535 | |||
| 536 | bool wake = false; | ||
| 537 | { | ||
| 538 | std::lock_guard slot_lock(voices_[index]->mutex); | ||
| 539 | const uint32_t size = ctx.field(0, 22, 5); | ||
| 540 | if (size == 0) return; | ||
| 541 | const uint32_t read = (ctx.field(9, 0, 5) + blocks % size) % size; | ||
| 542 | ctx.set_field(9, 0, 5, read); | ||
| 543 | if (blocks > 0) { | ||
| 544 | ctx.set_field(1, 31, 1, 1); | ||
| 545 | } | ||
| 546 | wake = voices_[index]->voice.has_value(); | ||
| 547 | } | ||
| 548 | if (wake) ensure_worker_and_wake(); | ||
| 549 | } | ||
| 550 | |||
| 551 | private: | ||
| 552 | XmaContextView context_locked(uint32_t index) const { | ||
| 553 | if (!array_ || index >= voices_.size()) return {}; | ||
| 554 | return XmaContextView{array_[index].words}; | ||
| 555 | } | ||
| 556 | |||
| 557 | // Appends interleaved s16 for one 2048-byte packet. Without the Rust decoder, or when it | ||
| 558 | // fails, the packet becomes silence for its frame count (header bits 26..31) so timing holds. | ||
| 559 | static void decode_packet(XmaVoice& voice, const uint8_t* bytes) { | ||
| 560 | const std::size_t channels = voice.channels(); | ||
| 561 | #if defined(LEONIDA_HAVE_XMA2_DECODER) | ||
| 562 | if (!voice.decoder) { | ||
| 563 | LeonidaXma2Decoder* raw = nullptr; | ||
| 564 | if (leonida_xma2_decoder_create_hardware(kXmaRates[voice.format & 3u], | ||
| 565 | static_cast<uint32_t>(channels), &raw) == LEONIDA_XMA2_OK) { | ||
| 566 | voice.decoder.reset(raw); | ||
| 567 | } | ||
| 568 | } | ||
| 569 | if (voice.decoder) { | ||
| 570 | LeonidaXma2PcmBlock* raw = nullptr; | ||
| 571 | if (leonida_xma2_decode_buffer(voice.decoder.get(), bytes, kXmaPacketBytes, &raw) == LEONIDA_XMA2_OK) { | ||
| 572 | const std::unique_ptr<LeonidaXma2PcmBlock, Xma2PcmFree> block(raw); | ||
| 573 | const int16_t* samples = leonida_xma2_pcm_data(block.get()); | ||
| 574 | const std::size_t count = leonida_xma2_pcm_sample_count(block.get()); | ||
| 575 | if (count != 0) voice.pcm.insert(voice.pcm.end(), samples, samples + count); | ||
| 576 | return; | ||
| 577 | } | ||
| 578 | voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence. | ||
| 579 | } | ||
| 580 | #endif | ||
| 581 | voice.pcm.resize(voice.pcm.size() + static_cast<std::size_t>(bytes[0] >> 2) * kXmaFrameSamples * channels); | ||
| 582 | } | ||
| 583 | |||
| 584 | // Decodes the packet at the read offset of the current input buffer and queues its PCM. | ||
| 585 | // Offsets and loop points are used per packet: a loop plays its end packet in full and | ||
| 586 | // restarts at the start of the packet holding the loop start. | ||
| 587 | static bool decode_one_packet(XmaContextView ctx, XmaVoice& voice) { | ||
| 588 | if (voice.ended) return false; | ||
| 589 | |||
| 590 | const std::size_t channels = voice.channels(); | ||
| 591 | uint32_t current = ctx.field(4, 31, 1); | ||
| 592 | const uint32_t valid = ctx.field(0, 20, 2); | ||
| 593 | |||
| 594 | if (valid == 0) { | ||
| 595 | voice.ended = true; | ||
| 596 | ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u); | ||
| 597 | return voice.queued_samples() != 0; | ||
| 598 | } | ||
| 599 | if ((valid & (1u << current)) == 0) { | ||
| 600 | current ^= 1u; | ||
| 601 | ctx.set_field(4, 31, 1, current); | ||
| 602 | } | ||
| 603 | |||
| 604 | const uint32_t address = (current == 0) ? ctx.get(5) : ctx.get(6); | ||
| 605 | const std::size_t packets = (current == 0) ? ctx.field(0, 0, 12) : ctx.field(1, 0, 12); | ||
| 606 | const std::size_t packet = ctx.field(2, 0, 26) / kXmaPacketBits; | ||
| 607 | const uint8_t* data = apu_span(address & ~0x7FFu, packets * kXmaPacketBytes); | ||
| 608 | if (!data || packet >= packets) { | ||
| 609 | finish_input(ctx, current, packet >= packets ? packet - packets : 0); | ||
| 610 | return true; | ||
| 611 | } | ||
| 612 | |||
| 613 | const uint8_t* packet_data = data + packet * kXmaPacketBytes; | ||
| 614 | const uint8_t packet_skip = packet_data[3]; | ||
| 615 | // Decoding is only requested when less than a ring block remains. Keep that | ||
| 616 | // tail and reuse the packet storage as the voice consumes subsequent packets. | ||
| 617 | voice.pcm.erase(voice.pcm.begin(), voice.pcm.begin() + static_cast<std::ptrdiff_t>(voice.pcm_read)); | ||
| 618 | voice.pcm_read = 0; | ||
| 619 | const std::size_t packet_start = voice.pcm.size(); | ||
| 620 | decode_packet(voice, packet_data); | ||
| 621 | const std::size_t packet_samples = voice.pcm.size() - packet_start; | ||
| 622 | const std::size_t subframe_samples = kXmaSubframeSamples * channels; | ||
| 623 | const std::size_t initial_skip = ctx.field(1, 24, 3); | ||
| 624 | const std::size_t skipped_subframes = std::min(initial_skip, packet_samples / subframe_samples); | ||
| 625 | const std::size_t initial_samples = skipped_subframes * subframe_samples; | ||
| 626 | const std::size_t loop_samples = std::min(voice.loop_skip * channels, packet_samples - initial_samples); | ||
| 627 | const std::size_t skip_samples = initial_samples + loop_samples; | ||
| 628 | if (skip_samples != 0) { | ||
| 629 | const auto first = voice.pcm.begin() + static_cast<std::ptrdiff_t>(packet_start); | ||
| 630 | voice.pcm.erase(first, first + static_cast<std::ptrdiff_t>(skip_samples)); | ||
| 631 | } | ||
| 632 | // Update the context only after the PCM append succeeds. | ||
| 633 | if (skipped_subframes != 0) { | ||
| 634 | ctx.set_field(1, 24, 3, static_cast<uint32_t>(initial_skip - skipped_subframes)); | ||
| 635 | } | ||
| 636 | voice.loop_skip -= loop_samples / channels; | ||
| 637 | |||
| 638 | // XMA2 packet headers link packets from the same stream; 0xff ends the chain. | ||
| 639 | std::size_t next = packet_skip == 0xFFu ? packets : packet + 1 + packet_skip; | ||
| 640 | const uint32_t loops = ctx.field(0, 12, 8); | ||
| 641 | const std::size_t loop_end = ctx.field(4, 0, 26); | ||
| 642 | if (loops > 0 && loop_end != 0 && packet == loop_end / kXmaPacketBits) { | ||
| 643 | next = ctx.field(3, 0, 26) / kXmaPacketBits; | ||
| 644 | voice.loop_skip = static_cast<std::size_t>(ctx.field(1, 17, 3)) * kXmaSubframeSamples; | ||
| 645 | #if defined(LEONIDA_HAVE_XMA2_DECODER) | ||
| 646 | // A frame spilling out of the loop-end packet does not continue in the loop-start packet: | ||
| 647 | // start a fresh decoder there rather than decode the spliced bits. | ||
| 648 | voice.decoder.reset(); | ||
| 649 | #endif | ||
| 650 | if (loops != 255u) ctx.set_field(0, 12, 8, loops - 1u); | ||
| 651 | } | ||
| 652 | if (next >= packets) { | ||
| 653 | finish_input(ctx, current, next - packets); | ||
| 654 | } else { | ||
| 655 | ctx.set_field(2, 0, 26, static_cast<uint32_t>(next * kXmaPacketBits)); | ||
| 656 | } | ||
| 657 | return true; | ||
| 658 | } | ||
| 659 | |||
| 660 | static void finish_input(XmaContextView ctx, uint32_t current, | ||
| 661 | std::size_t skip_packets) { | ||
| 662 | // Publish the next offset before telling the title it can refill this input. | ||
| 663 | ctx.set_field(2, 0, 26, static_cast<uint32_t>(skip_packets * kXmaPacketBits)); | ||
| 664 | const uint32_t other = 1u - current; | ||
| 665 | const uint32_t retired = ctx.set_field(0, 20 + current, 1, 0); | ||
| 666 | // Take the other input if it was queued at retirement. Otherwise a double | ||
| 667 | // refill of the empty pair starts at input 0. A lone input can still run. | ||
| 668 | ctx.set_field(4, 31, 1, (retired & (1u << (20 + other))) != 0 ? other : 0u); | ||
| 669 | } | ||
| 670 | |||
| 671 | static void pump_voice(XmaContextView ctx, XmaVoice& voice) { | ||
| 672 | const uint32_t size = ctx.field(0, 22, 5); | ||
| 673 | if (size == 0 || ctx.field(1, 31, 1) == 0) return; | ||
| 674 | auto* ring = apu_span(ctx.get(7), size * kXmaBlockBytes); | ||
| 675 | if (!ring) return; | ||
| 676 | |||
| 677 | for (uint32_t blocks = 0; blocks < size && ctx.field(1, 31, 1) == 1; ++blocks) { | ||
| 678 | int decode_guard = 0; | ||
| 679 | while (voice.queued_samples() < kXmaSamplesPerBlock && decode_guard++ < 16) { | ||
| 680 | if (!decode_one_packet(ctx, voice)) break; | ||
| 681 | } | ||
| 682 | if (voice.queued_samples() == 0) return; | ||
| 683 | |||
| 684 | const uint32_t write = ctx.field(0, 27, 5) % size; | ||
| 685 | uint8_t* out = ring + write * kXmaBlockBytes; | ||
| 686 | |||
| 687 | for (std::size_t i = 0; i < kXmaSamplesPerBlock; ++i) { | ||
| 688 | int16_t sample = 0; | ||
| 689 | if (voice.pcm_read != voice.pcm.size()) { | ||
| 690 | sample = voice.pcm[voice.pcm_read++]; | ||
| 691 | } | ||
| 692 | const uint16_t raw = static_cast<uint16_t>(sample); | ||
| 693 | out[2 * i] = static_cast<uint8_t>(raw & 0xFFu); | ||
| 694 | out[2 * i + 1] = static_cast<uint8_t>((raw >> 8) & 0xFFu); | ||
| 695 | } | ||
| 696 | |||
| 697 | const uint32_t next_write = (write + 1u) % size; | ||
| 698 | ctx.set_field(0, 27, 5, next_write); | ||
| 699 | if (next_write == ctx.field(9, 0, 5) % size) { | ||
| 700 | ctx.set_field(1, 31, 1, 0); | ||
| 701 | } | ||
| 702 | } | ||
| 703 | } | ||
| 704 | |||
| 705 | void pump_all() { | ||
| 706 | std::shared_lock table_lock(table_mutex_); | ||
| 707 | if (!array_) return; | ||
| 708 | for (std::size_t i = 0; i < voices_.size(); ++i) { | ||
| 709 | std::lock_guard slot_lock(voices_[i]->mutex); | ||
| 710 | auto& voice = voices_[i]->voice; | ||
| 711 | if (!voice) continue; | ||
| 712 | auto ctx = context_locked(static_cast<uint32_t>(i)); | ||
| 713 | try { | ||
| 714 | pump_voice(ctx, *voice); | ||
| 715 | } catch (const std::bad_alloc&) { | ||
| 716 | // Only this voice failed. Retire it and allow the title to enable it again. | ||
| 717 | voice.reset(); | ||
| 718 | active_count_.fetch_sub(1, std::memory_order_relaxed); | ||
| 719 | ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u); | ||
| 720 | } | ||
| 721 | } | ||
| 722 | } | ||
| 723 | |||
| 724 | void ensure_worker_and_wake() { | ||
| 725 | std::lock_guard lock(worker_mutex_); | ||
| 726 | if (!worker_.joinable()) { | ||
| 727 | worker_ = std::jthread([this](std::stop_token stop) { worker_loop(stop); }); | ||
| 728 | } | ||
| 729 | wake_requested_ = true; | ||
| 730 | worker_cv_.notify_one(); | ||
| 731 | } | ||
| 732 | |||
| 733 | // Each worker owns its stop_token, so a stop only ever reaches the thread it was | ||
| 734 | // sent to; a worker started after this call is unaffected by it. | ||
| 735 | void stop_worker() { | ||
| 736 | std::jthread to_join; | ||
| 737 | { | ||
| 738 | std::lock_guard lock(worker_mutex_); | ||
| 739 | if (!worker_.joinable()) return; | ||
| 740 | worker_.request_stop(); | ||
| 741 | worker_cv_.notify_all(); | ||
| 742 | to_join = std::move(worker_); | ||
| 743 | } | ||
| 744 | if (to_join.joinable()) to_join.join(); | ||
| 745 | } | ||
| 746 | |||
| 747 | void worker_loop(std::stop_token stop) { | ||
| 748 | for (;;) { | ||
| 749 | { | ||
| 750 | std::unique_lock lock(worker_mutex_); | ||
| 751 | if (stop.stop_requested()) return; | ||
| 752 | if (active_count_.load(std::memory_order_relaxed) == 0 && !wake_requested_) { | ||
| 753 | worker_cv_.wait(lock, stop, [this]() { return wake_requested_; }); | ||
| 754 | if (stop.stop_requested()) return; | ||
| 755 | } | ||
| 756 | wake_requested_ = false; | ||
| 757 | } | ||
| 758 | |||
| 759 | pump_all(); | ||
| 760 | |||
| 761 | std::unique_lock lock(worker_mutex_); | ||
| 762 | if (stop.stop_requested()) return; | ||
| 763 | if (!wake_requested_ && active_count_.load(std::memory_order_relaxed) > 0) { | ||
| 764 | // One 256-byte output block lasts ~2.67 ms at 48 kHz mono. | ||
| 765 | worker_cv_.wait_for(lock, stop, std::chrono::milliseconds(2), | ||
| 766 | [this]() { return wake_requested_; }); | ||
| 767 | } | ||
| 768 | } | ||
| 769 | } | ||
| 770 | |||
| 771 | mutable std::shared_mutex table_mutex_; | ||
| 772 | SHAPE_XMA_CONTEXT* array_ = nullptr; | ||
| 773 | std::vector<std::unique_ptr<XmaVoiceSlot>> voices_; | ||
| 774 | std::atomic<uint32_t> active_count_{0}; | ||
| 775 | |||
| 776 | std::mutex worker_mutex_; | ||
| 777 | std::condition_variable_any worker_cv_; | ||
| 778 | std::jthread worker_; | ||
| 779 | bool wake_requested_ = false; | ||
| 780 | }; | ||
| 781 | |||
| 782 | XmaEngine g_xma_engine; | ||
| 285 | 783 | ||
| 286 | // ---- IAcpHal Interface Implementation ---- | 784 | // ---- IAcpHal Interface Implementation ---- |
| 287 | 785 | ||
| 288 | struct AcpHalImpl { | 786 | #pragma pack(push, 1) |
| 787 | struct AcpMessage { | ||
| 788 | uint32_t kind = 0; | ||
| 789 | uint32_t dropped = 0; | ||
| 790 | uint32_t usec = 0; | ||
| 791 | uint8_t data[16]{}; | ||
| 792 | }; | ||
| 793 | #pragma pack(pop) | ||
| 794 | static_assert(sizeof(AcpMessage) == 28, "AcpMessage is 28 bytes"); | ||
| 795 | |||
| 796 | void write_u32_le(uint8_t* dst, uint32_t value) { | ||
| 797 | dst[0] = static_cast<uint8_t>(value & 0xFFu); | ||
| 798 | dst[1] = static_cast<uint8_t>((value >> 8) & 0xFFu); | ||
| 799 | dst[2] = static_cast<uint8_t>((value >> 16) & 0xFFu); | ||
| 800 | dst[3] = static_cast<uint8_t>((value >> 24) & 0xFFu); | ||
| 801 | } | ||
| 802 | |||
| 803 | void write_u64_le(uint8_t* dst, uint64_t value) { | ||
| 804 | write_u32_le(dst, static_cast<uint32_t>(value & 0xFFFFFFFFu)); | ||
| 805 | write_u32_le(dst + 4, static_cast<uint32_t>(value >> 32)); | ||
| 806 | } | ||
| 807 | |||
| 808 | struct IAcpHal { | ||
| 809 | virtual HRESULT __stdcall connect(uint32_t commands, uint32_t messages) = 0; | ||
| 810 | virtual HRESULT __stdcall disconnect() = 0; | ||
| 811 | virtual HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame, | ||
| 812 | const void* config, uint32_t notification) = 0; | ||
| 813 | virtual uint32_t __stdcall pop_message(void* out) = 0; | ||
| 814 | virtual uint32_t __stdcall get_num_messages() = 0; | ||
| 815 | virtual HRESULT __stdcall release() = 0; | ||
| 816 | }; | ||
| 817 | |||
| 818 | struct AcpHalImpl final : IAcpHal { | ||
| 819 | std::mutex mutex_; | ||
| 820 | bool connected_ = false; | ||
| 821 | uint32_t mask_ = 0; | ||
| 822 | std::deque<AcpMessage> messages_; | ||
| 823 | std::size_t capacity_ = 0; | ||
| 824 | uint32_t dropped_ = 0; | ||
| 825 | std::chrono::steady_clock::time_point since_ = std::chrono::steady_clock::now(); | ||
| 826 | |||
| 827 | uint64_t elapsed_usec_locked() const { | ||
| 828 | const auto dt = std::chrono::steady_clock::now() - since_; | ||
| 829 | return static_cast<uint64_t>( | ||
| 830 | std::chrono::duration_cast<std::chrono::microseconds>(dt).count()); | ||
| 831 | } | ||
| 832 | |||
| 833 | uint32_t audio_frame_locked() const { | ||
| 834 | return static_cast<uint32_t>((elapsed_usec_locked() * kAudioFramesPerSecond) / 1000000ull); | ||
| 835 | } | ||
| 836 | |||
| 837 | void post_locked(uint32_t kind, const uint8_t* payload, std::size_t len) { | ||
| 838 | if ((mask_ & kind) == 0) return; | ||
| 839 | if (messages_.size() >= capacity_) { | ||
| 840 | if (dropped_ < UINT32_MAX) ++dropped_; | ||
| 841 | return; | ||
| 842 | } | ||
| 843 | AcpMessage msg{}; | ||
| 844 | msg.kind = kind; | ||
| 845 | msg.dropped = dropped_; | ||
| 846 | msg.usec = static_cast<uint32_t>(elapsed_usec_locked()); | ||
| 847 | if (payload && len > 0) { | ||
| 848 | std::memcpy(msg.data, payload, std::min(len, sizeof(msg.data))); | ||
| 849 | } | ||
| 850 | try { | ||
| 851 | messages_.push_back(msg); | ||
| 852 | dropped_ = 0; | ||
| 853 | } catch (const std::bad_alloc&) { | ||
| 854 | if (dropped_ < UINT32_MAX) ++dropped_; | ||
| 855 | } | ||
| 856 | } | ||
| 857 | |||
| 289 | // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked) | 858 | // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked) |
| 290 | virtual HRESULT __stdcall connect(uint32_t, uint32_t) { | 859 | HRESULT __stdcall connect(uint32_t commands, uint32_t messages) override { |
| 291 | trace_call("AcpHal::Connect", ""); | 860 | trace_call("AcpHal::Connect", ""); |
| 861 | if (commands == 0) return E_INVALIDARG; | ||
| 862 | std::lock_guard lock(mutex_); | ||
| 863 | connected_ = true; | ||
| 864 | capacity_ = messages; | ||
| 292 | return S_OK; | 865 | return S_OK; |
| 293 | } | 866 | } |
| 294 | 867 | ||
| 295 | // Slot 1: Disconnect (called at shutdown) | 868 | // Slot 1: Disconnect (called at shutdown) |
| 296 | virtual HRESULT __stdcall disconnect() { | 869 | HRESULT __stdcall disconnect() override { |
| 297 | trace_call("AcpHal::Disconnect", ""); | 870 | trace_call("AcpHal::Disconnect", ""); |
| 871 | std::lock_guard lock(mutex_); | ||
| 872 | if (!connected_) return E_FAIL; | ||
| 873 | post_locked(kMsgDisconnected, nullptr, 0); | ||
| 874 | connected_ = false; | ||
| 298 | return S_OK; | 875 | return S_OK; |
| 299 | } | 876 | } |
| 300 | 877 | ||
| 301 | // Slot 2: SubmitCommand | 878 | // Slot 2: SubmitCommand |
| 302 | // Critical: The title calls slot 2 as (2, 0xf0f0f0f0, -1, config, 0) and | 879 | // Acknowledges command completion, updates registered message masks, dispatches |
| 303 | // a negative result triggers a fatal int3 kernel panic (+0x43ad94e). | 880 | // XMA voice commands, and writes any requested APU notification word. |
| 304 | virtual HRESULT __stdcall submit_command(uint32_t cmd, uint32_t d1, uint32_t d2, | 881 | HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame, |
| 305 | const void* config, uint32_t d3) { | 882 | const void* config, uint32_t notification) override try { |
| 306 | (void)cmd; | 883 | (void)frame; |
| 307 | (void)d1; | 884 | auto read_word = [config](std::size_t index) -> uint32_t { |
| 308 | (void)d2; | 885 | if (!config) return 0u; |
| 309 | (void)config; | 886 | uint32_t value = 0; |
| 310 | (void)d3; | 887 | std::memcpy(&value, static_cast<const uint8_t*>(config) + index * sizeof(uint32_t), |
| 311 | static std::atomic<bool> warned{false}; | 888 | sizeof(uint32_t)); |
| 312 | if (!warned.exchange(true, std::memory_order_relaxed)) { | 889 | return value; |
| 313 | std::fprintf(stderr, | 890 | }; |
| 314 | "[rt] acphal: command accepted and dropped: no audio DSP hardware on PC\n"); | 891 | |
| 892 | const bool handled_xma = g_xma_engine.handle_command(cmd, config); | ||
| 893 | { | ||
| 894 | std::lock_guard lock(mutex_); | ||
| 895 | if (!handled_xma) { | ||
| 896 | switch (cmd) { | ||
| 897 | case kCmdRegisterMessages: | ||
| 898 | mask_ |= read_word(0); | ||
| 899 | break; | ||
| 900 | case kCmdUnregisterMessages: | ||
| 901 | mask_ &= ~read_word(0); | ||
| 902 | break; | ||
| 903 | case kCmdLoadFlowgraph: { | ||
| 904 | uint8_t payload[4]; | ||
| 905 | write_u32_le(payload, read_word(1)); | ||
| 906 | post_locked(kMsgFlowgraphCompleted, payload, sizeof(payload)); | ||
| 907 | break; | ||
| 908 | } | ||
| 909 | default: | ||
| 910 | break; | ||
| 911 | } | ||
| 912 | } | ||
| 913 | if (id != 0) { | ||
| 914 | uint8_t done[16]; | ||
| 915 | write_u32_le(done, cmd); | ||
| 916 | write_u64_le(done + 4, id); | ||
| 917 | write_u32_le(done + 12, audio_frame_locked()); | ||
| 918 | post_locked(kMsgCommandCompleted, done, sizeof(done)); | ||
| 919 | } | ||
| 920 | } | ||
| 921 | |||
| 922 | if (notification != 0) { | ||
| 923 | if (uint8_t* word_bytes = apu_span(notification, sizeof(uint32_t))) { | ||
| 924 | if ((reinterpret_cast<uintptr_t>(word_bytes) & 3u) == 0) { | ||
| 925 | *reinterpret_cast<volatile uint32_t*>(word_bytes) = 1u; | ||
| 926 | } else { | ||
| 927 | static constexpr uint8_t kOneLe[4] = {1, 0, 0, 0}; | ||
| 928 | volatile uint8_t* dst = word_bytes; | ||
| 929 | for (std::size_t i = 0; i < 4; ++i) dst[i] = kOneLe[i]; | ||
| 930 | } | ||
| 931 | } | ||
| 315 | } | 932 | } |
| 933 | |||
| 316 | trace_call("AcpHal::SubmitCommand", ""); | 934 | trace_call("AcpHal::SubmitCommand", ""); |
| 317 | return S_OK; | 935 | return S_OK; |
| 936 | } catch (const std::bad_alloc&) { | ||
| 937 | return E_OUTOFMEMORY; | ||
| 938 | } catch (const std::system_error&) { | ||
| 939 | return E_FAIL; | ||
| 318 | } | 940 | } |
| 319 | 941 | ||
| 320 | // Slots 3 and 4: PopMessage and GetNumMessages (message polling, not called by title) | 942 | // Slot 3: PopMessage — returns 0 without touching `out` when the queue is empty. |
| 321 | virtual uint32_t __stdcall pop_message() { return 0; } | 943 | uint32_t __stdcall pop_message(void* out) override { |
| 322 | virtual uint32_t __stdcall get_num_messages() { return 0; } | 944 | std::lock_guard lock(mutex_); |
| 945 | if (messages_.empty()) return 0u; | ||
| 946 | const AcpMessage msg = messages_.front(); | ||
| 947 | messages_.pop_front(); | ||
| 948 | if (out) std::memcpy(out, &msg, sizeof(msg)); | ||
| 949 | return 1u; | ||
| 950 | } | ||
| 951 | |||
| 952 | // Slot 4: GetNumMessages | ||
| 953 | uint32_t __stdcall get_num_messages() override { | ||
| 954 | std::lock_guard lock(mutex_); | ||
| 955 | return static_cast<uint32_t>(messages_.size()); | ||
| 956 | } | ||
| 323 | 957 | ||
| 324 | // Slot 5: Release | 958 | // Slot 5: Release |
| 325 | virtual HRESULT __stdcall release() { | 959 | HRESULT __stdcall release() override { |
| 326 | trace_call("AcpHal::Release", ""); | 960 | trace_call("AcpHal::Release", ""); |
| 327 | delete this; | 961 | delete this; |
| 328 | return S_OK; | 962 | return S_OK; |
| @@ -333,7 +967,12 @@ struct AcpHalImpl { | |||
| 333 | 967 | ||
| 334 | HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { | 968 | HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { |
| 335 | if (!ppAcpHal) return E_POINTER; | 969 | if (!ppAcpHal) return E_POINTER; |
| 336 | *ppAcpHal = new AcpHalImpl(); | 970 | *ppAcpHal = nullptr; |
| 971 | try { | ||
| 972 | *ppAcpHal = new AcpHalImpl(); | ||
| 973 | } catch (const std::bad_alloc&) { | ||
| 974 | return E_OUTOFMEMORY; | ||
| 975 | } | ||
| 337 | trace_call("AcpHalCreate", ""); | 976 | trace_call("AcpHalCreate", ""); |
| 338 | return S_OK; | 977 | return S_OK; |
| 339 | } | 978 | } |
| @@ -343,63 +982,79 @@ HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { | |||
| 343 | HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { | 982 | HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { |
| 344 | if (!ctx) return E_POINTER; | 983 | if (!ctx) return E_POINTER; |
| 345 | 984 | ||
| 346 | std::lock_guard lock(g_apu_mutex); | 985 | std::lock_guard lock(g_shape_mutex); |
| 347 | 986 | ||
| 348 | auto alloc_array = [](uint32_t count, size_t elem_size) -> void* { | 987 | ShapeAllocation pending{}; |
| 988 | std::size_t array_index = 0; | ||
| 989 | auto alloc_array = [&](uint32_t count, size_t elem_size) -> void* { | ||
| 349 | if (count == 0) return nullptr; | 990 | if (count == 0) return nullptr; |
| 350 | void* ptr = std::calloc(count, elem_size); | 991 | void* ptr = std::calloc(count, elem_size); |
| 351 | if (ptr) g_active_shape_arrays.push_back(ptr); | 992 | if (!ptr) throw std::bad_alloc(); |
| 993 | pending[array_index++].reset(ptr); | ||
| 352 | return ptr; | 994 | return ptr; |
| 353 | }; | 995 | }; |
| 354 | 996 | ||
| 355 | ctx->srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>( | 997 | SHAPE_CONTEXTS result{}; |
| 356 | alloc_array(ctx->numSrcContexts, sizeof(SHAPE_SRC_CONTEXT))); | 998 | result.numSrcContexts = ctx->numSrcContexts; |
| 357 | ctx->eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>( | 999 | result.numEqCompContexts = ctx->numEqCompContexts; |
| 358 | alloc_array(ctx->numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT))); | 1000 | result.numFiltVolContexts = ctx->numFiltVolContexts; |
| 359 | ctx->filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>( | 1001 | result.numDmaContexts = ctx->numDmaContexts; |
| 360 | alloc_array(ctx->numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT))); | 1002 | result.numXmaContexts = ctx->numXmaContexts; |
| 361 | ctx->dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>( | 1003 | result.numPcmContexts = ctx->numPcmContexts; |
| 362 | alloc_array(ctx->numDmaContexts, sizeof(SHAPE_DMA_CONTEXT))); | 1004 | try { |
| 363 | ctx->xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>( | 1005 | result.srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>( |
| 364 | alloc_array(ctx->numXmaContexts, sizeof(SHAPE_XMA_CONTEXT))); | 1006 | alloc_array(result.numSrcContexts, sizeof(SHAPE_SRC_CONTEXT))); |
| 365 | ctx->pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>( | 1007 | result.eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>( |
| 366 | alloc_array(ctx->numPcmContexts, sizeof(SHAPE_PCM_CONTEXT))); | 1008 | alloc_array(result.numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT))); |
| 367 | 1009 | result.filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>( | |
| 368 | // On PC there is no physical APU address translation for host context arrays; | 1010 | alloc_array(result.numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT))); |
| 369 | // assign unique synthetic addresses from the APU base. | 1011 | result.dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>( |
| 370 | ctx->apuSrcContextArray = {ctx->srcContextArray ? kApuBaseAddress : 0}; | 1012 | alloc_array(result.numDmaContexts, sizeof(SHAPE_DMA_CONTEXT))); |
| 371 | ctx->apuEqCompContextArray = {ctx->eqCompContextArray ? kApuBaseAddress + 0x1000 : 0}; | 1013 | result.xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>( |
| 372 | ctx->apuFiltVolContextArray = {ctx->filtVolContextArray ? kApuBaseAddress + 0x2000 : 0}; | 1014 | alloc_array(result.numXmaContexts, sizeof(SHAPE_XMA_CONTEXT))); |
| 373 | ctx->apuDmaContextArray = {ctx->dmaContextArray ? kApuBaseAddress + 0x3000 : 0}; | 1015 | result.pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>( |
| 374 | ctx->apuXmaContextArray = {ctx->xmaContextArray ? kApuBaseAddress + 0x4000 : 0}; | 1016 | alloc_array(result.numPcmContexts, sizeof(SHAPE_PCM_CONTEXT))); |
| 375 | ctx->apuPcmContextArray = {ctx->pcmContextArray ? kApuBaseAddress + 0x5000 : 0}; | 1017 | |
| 376 | 1018 | // Assign synthetic APU addresses to the host-side context arrays. | |
| 377 | trace_call("AcpHalAllocateShapeContexts", | 1019 | result.apuSrcContextArray = {result.srcContextArray ? kApuBaseAddress : 0}; |
| 378 | ",\"src\":" + std::to_string(ctx->numSrcContexts) + | 1020 | result.apuEqCompContextArray = {result.eqCompContextArray ? kApuBaseAddress + 0x1000 : 0}; |
| 379 | ",\"xma\":" + std::to_string(ctx->numXmaContexts) + | 1021 | result.apuFiltVolContextArray = {result.filtVolContextArray ? kApuBaseAddress + 0x2000 : 0}; |
| 380 | ",\"pcm\":" + std::to_string(ctx->numPcmContexts)); | 1022 | result.apuDmaContextArray = {result.dmaContextArray ? kApuBaseAddress + 0x3000 : 0}; |
| 1023 | result.apuXmaContextArray = {result.xmaContextArray ? kApuBaseAddress + 0x4000 : 0}; | ||
| 1024 | result.apuPcmContextArray = {result.pcmContextArray ? kApuBaseAddress + 0x5000 : 0}; | ||
| 1025 | |||
| 1026 | g_shape_allocations.reserve(g_shape_allocations.size() + 1); | ||
| 1027 | if (result.xmaContextArray) g_xma_engine.bind(result.xmaContextArray, result.numXmaContexts); | ||
| 1028 | } catch (const std::bad_alloc&) { | ||
| 1029 | return E_OUTOFMEMORY; | ||
| 1030 | } | ||
| 1031 | |||
| 1032 | // Both the backing arrays and the engine's slots are now fully allocated. | ||
| 1033 | g_shape_allocations.push_back(std::move(pending)); | ||
| 1034 | *ctx = result; | ||
| 1035 | if (rt::startup_trace::enabled()) { | ||
| 1036 | try { | ||
| 1037 | trace_call("AcpHalAllocateShapeContexts", | ||
| 1038 | ",\"src\":" + std::to_string(result.numSrcContexts) + | ||
| 1039 | ",\"xma\":" + std::to_string(result.numXmaContexts) + | ||
| 1040 | ",\"pcm\":" + std::to_string(result.numPcmContexts)); | ||
| 1041 | } catch (const std::bad_alloc&) { | ||
| 1042 | // The allocation succeeded. A missing diagnostic does not invalidate it. | ||
| 1043 | } | ||
| 1044 | } | ||
| 381 | return S_OK; | 1045 | return S_OK; |
| 382 | } | 1046 | } |
| 383 | 1047 | ||
| 384 | // ---- AcpHalReleaseShapeContexts ---- | 1048 | // ---- AcpHalReleaseShapeContexts ---- |
| 385 | 1049 | ||
| 386 | HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) { | 1050 | HRESULT __stdcall AcpHalReleaseShapeContexts(void* /*hal*/) { |
| 387 | std::lock_guard lock(g_apu_mutex); | 1051 | std::lock_guard lock(g_shape_mutex); |
| 388 | 1052 | // Stop and detach the XMA worker before freeing backing arrays. | |
| 389 | // Free all recorded context allocations | 1053 | g_xma_engine.unbind(); |
| 390 | for (void* p : g_active_shape_arrays) { | ||
| 391 | if (p) std::free(p); | ||
| 392 | } | ||
| 393 | g_active_shape_arrays.clear(); | ||
| 394 | 1054 | ||
| 395 | if (ctx) { | 1055 | // The export releases the process-wide SHAPE arrays. The argument is an |
| 396 | ctx->srcContextArray = nullptr; | 1056 | // opaque HAL handle, and allocation descriptors are owned by the caller. |
| 397 | ctx->eqCompContextArray = nullptr; | 1057 | g_shape_allocations.clear(); |
| 398 | ctx->filtVolContextArray = nullptr; | ||
| 399 | ctx->dmaContextArray = nullptr; | ||
| 400 | ctx->xmaContextArray = nullptr; | ||
| 401 | ctx->pcmContextArray = nullptr; | ||
| 402 | } | ||
| 403 | 1058 | ||
| 404 | trace_call("AcpHalReleaseShapeContexts", ""); | 1059 | trace_call("AcpHalReleaseShapeContexts", ""); |
| 405 | return S_OK; | 1060 | return S_OK; |
| @@ -411,6 +1066,9 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes, | |||
| 411 | uint32_t nonCachedSizeInBytes) { | 1066 | uint32_t nonCachedSizeInBytes) { |
| 412 | std::lock_guard lock(g_apu_mutex); | 1067 | std::lock_guard lock(g_apu_mutex); |
| 413 | if (g_apu_heap_created) return E_FAIL; | 1068 | if (g_apu_heap_created) return E_FAIL; |
| 1069 | const uint64_t address_bytes = (nonCachedSizeInBytes ? align_apu_region(cachedSizeInBytes) | ||
| 1070 | : cachedSizeInBytes) + nonCachedSizeInBytes; | ||
| 1071 | if (address_bytes > static_cast<uint64_t>(UINT32_MAX) + 1 - kApuBaseAddress) return E_INVALIDARG; | ||
| 414 | 1072 | ||
| 415 | if (cachedSizeInBytes > 0) { | 1073 | if (cachedSizeInBytes > 0) { |
| 416 | g_cached_heap.base = VirtualAlloc( | 1074 | g_cached_heap.base = VirtualAlloc( |
| @@ -430,17 +1088,23 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes, | |||
| 430 | } | 1088 | } |
| 431 | 1089 | ||
| 432 | g_apu_heap_created = true; | 1090 | g_apu_heap_created = true; |
| 433 | trace_call("ApuCreateHeap", | 1091 | if (rt::startup_trace::enabled()) { |
| 434 | ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) + | 1092 | try { |
| 435 | ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes)); | 1093 | trace_call("ApuCreateHeap", |
| 1094 | ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) + | ||
| 1095 | ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes)); | ||
| 1096 | } catch (const std::bad_alloc&) { | ||
| 1097 | // The heap is ready even if its diagnostic cannot be built. | ||
| 1098 | } | ||
| 1099 | } | ||
| 436 | return S_OK; | 1100 | return S_OK; |
| 437 | } | 1101 | } |
| 438 | 1102 | ||
| 439 | // ---- ApuAlloc ---- | 1103 | // ---- ApuAlloc ---- |
| 440 | 1104 | ||
| 441 | HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, | 1105 | HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, |
| 442 | uint32_t sizeInBytes, uint32_t alignmentInBytes, | 1106 | uint32_t sizeInBytes, uint32_t alignmentInBytes, |
| 443 | uint32_t flags) { | 1107 | uint32_t flags) try { |
| 444 | if (!virtualAddress) return E_POINTER; | 1108 | if (!virtualAddress) return E_POINTER; |
| 445 | *virtualAddress = nullptr; | 1109 | *virtualAddress = nullptr; |
| 446 | if (physicalAddress) *physicalAddress = 0; | 1110 | if (physicalAddress) *physicalAddress = 0; |
| @@ -459,6 +1123,7 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, | |||
| 459 | 1123 | ||
| 460 | if (!target->base) { | 1124 | if (!target->base) { |
| 461 | if (!prefer_noncached) { | 1125 | if (!prefer_noncached) { |
| 1126 | if (g_apu_heap_created) return E_OUTOFMEMORY; | ||
| 462 | // Lazy default cached heap if ApuCreateHeap wasn't called yet | 1127 | // Lazy default cached heap if ApuCreateHeap wasn't called yet |
| 463 | constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024; | 1128 | constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024; |
| 464 | target->base = VirtualAlloc(nullptr, kDefaultHeapSize, | 1129 | target->base = VirtualAlloc(nullptr, kDefaultHeapSize, |
| @@ -485,17 +1150,17 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, | |||
| 485 | 1150 | ||
| 486 | *virtualAddress = ptr; | 1151 | *virtualAddress = ptr; |
| 487 | if (physicalAddress) { | 1152 | if (physicalAddress) { |
| 488 | // Disjoint APU address ranges: | 1153 | // Leave alignment padding between the two synthetic address ranges. |
| 489 | // cached: 0x40000000 .. 0x40000000 + cached_size - 1 | ||
| 490 | // non-cached: 0x40000000 + cached_size .. 0x40000000 + cached_size + noncached_size - 1 | ||
| 491 | uint32_t apu = kApuBaseAddress + offset; | 1154 | uint32_t apu = kApuBaseAddress + offset; |
| 492 | if (target == &g_noncached_heap) { | 1155 | if (target == &g_noncached_heap) { |
| 493 | apu += static_cast<uint32_t>(g_cached_heap.size); | 1156 | apu += static_cast<uint32_t>(align_apu_region(g_cached_heap.size)); |
| 494 | } | 1157 | } |
| 495 | *physicalAddress = apu; | 1158 | *physicalAddress = apu; |
| 496 | } | 1159 | } |
| 497 | 1160 | ||
| 498 | return S_OK; | 1161 | return S_OK; |
| 1162 | } catch (const std::bad_alloc&) { | ||
| 1163 | return E_OUTOFMEMORY; | ||
| 499 | } | 1164 | } |
| 500 | 1165 | ||
| 501 | // ---- ApuFree ---- | 1166 | // ---- ApuFree ---- |
| @@ -530,7 +1195,7 @@ void* __stdcall ApuMapApuAddress(uint32_t apu) { | |||
| 530 | return g_cached_heap.from_offset(offset); | 1195 | return g_cached_heap.from_offset(offset); |
| 531 | } | 1196 | } |
| 532 | if (g_noncached_heap.base) { | 1197 | if (g_noncached_heap.base) { |
| 533 | const uint32_t cached_span = static_cast<uint32_t>(g_cached_heap.size); | 1198 | const uint32_t cached_span = static_cast<uint32_t>(align_apu_region(g_cached_heap.size)); |
| 534 | if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) { | 1199 | if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) { |
| 535 | return g_noncached_heap.from_offset(offset - cached_span); | 1200 | return g_noncached_heap.from_offset(offset - cached_span); |
| 536 | } | 1201 | } |
| @@ -547,7 +1212,7 @@ uint32_t __stdcall ApuMapVirtualAddress(void* virtualAddress) { | |||
| 547 | return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress); | 1212 | return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress); |
| 548 | } | 1213 | } |
| 549 | if (g_noncached_heap.contains(virtualAddress)) { | 1214 | if (g_noncached_heap.contains(virtualAddress)) { |
| 550 | return kApuBaseAddress + static_cast<uint32_t>(g_cached_heap.size) + | 1215 | return kApuBaseAddress + static_cast<uint32_t>(align_apu_region(g_cached_heap.size)) + |
| 551 | g_noncached_heap.to_offset(virtualAddress); | 1216 | g_noncached_heap.to_offset(virtualAddress); |
| 552 | } | 1217 | } |
| 553 | return 0; | 1218 | return 0; |
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index d0f3b528a..07233494b 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h | |||
| @@ -87,6 +87,7 @@ struct VulkanDeviceInfo { | |||
| 87 | std::vector<VkQueue> compute_queues; | 87 | std::vector<VkQueue> compute_queues; |
| 88 | std::vector<VkQueue> copy_queues; | 88 | std::vector<VkQueue> copy_queues; |
| 89 | bool separate_depth_stencil_layouts = true; | 89 | bool separate_depth_stencil_layouts = true; |
| 90 | bool depth_range_unrestricted = false; // VK_EXT_depth_range_unrestricted enabled on this device. | ||
| 90 | std::uint32_t max_push_constants_size = 0; | 91 | std::uint32_t max_push_constants_size = 0; |
| 91 | bool push_constants_need_fallback = false; | 92 | bool push_constants_need_fallback = false; |
| 92 | // maxBufferSize and maxMemoryAllocationSize, which cap the GPU address arena (src/arena_size.h). 0: read from | 93 | // maxBufferSize and maxMemoryAllocationSize, which cap the GPU address arena (src/arena_size.h). 0: read from |
| @@ -175,6 +176,9 @@ struct VulkanDeviceInfo { | |||
| 175 | // shaders have no amplification stage). Mesh-shader PSOs and DispatchMesh work, and CheckFeatureSupport reports | 176 | // shaders have no amplification stage). Mesh-shader PSOs and DispatchMesh work, and CheckFeatureSupport reports |
| 176 | // D3D12_MESH_SHADER_TIER_1; without it mesh PSOs are refused and the tier is NOT_SUPPORTED. | 177 | // D3D12_MESH_SHADER_TIER_1; without it mesh PSOs are refused and the tier is NOT_SUPPORTED. |
| 177 | bool mesh_shader = false; | 178 | bool mesh_shader = false; |
| 179 | // VK_EXT_mesh_shader's meshShaderQueries feature is enabled on `device`, so the clipping invocations of a mesh | ||
| 180 | // segment come from a mesh-primitives query (D3D-MESH-CLIPPING-COUNTER). Without it they read 0. | ||
| 181 | bool mesh_shader_queries = false; | ||
| 178 | // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, | 182 | // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, |
| 179 | // depthBiasClamp or dualSrcBlend are refused unless it is set here. | 183 | // depthBiasClamp or dualSrcBlend are refused unless it is set here. |
| 180 | VkPhysicalDeviceFeatures features{}; | 184 | VkPhysicalDeviceFeatures features{}; |
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339..e9bc19195 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp | |||
| @@ -3096,8 +3096,6 @@ public: | |||
| 3096 | virtual HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64, UINT64, void** out) = 0; | 3096 | virtual HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64, UINT64, void** out) = 0; |
| 3097 | }; | 3097 | }; |
| 3098 | 3098 | ||
| 3099 | // A pipeline state. Compute only for now: the shader is found by the SHA-256 of its FSSM program in the | ||
| 3100 | // translator's index, and the FSSM blob is copied into the arena as the shader's code base. | ||
| 3101 | // A D3D12_PIPELINE_STATE_STREAM_DESC (ID3D12Device2::CreatePipelineState) as the descriptions the PSO creators take. | 3099 | // A D3D12_PIPELINE_STATE_STREAM_DESC (ID3D12Device2::CreatePipelineState) as the descriptions the PSO creators take. |
| 3102 | // The stream is a run of subobjects, each a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE followed by its description at that | 3100 | // The stream is a run of subobjects, each a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE followed by its description at that |
| 3103 | // description's alignment, each subobject starting at pointer alignment (the d3dx12.h layout, `alignas(void*)`). A | 3101 | // description's alignment, each subobject starting at pointer alignment (the d3dx12.h layout, `alignas(void*)`). A |
| @@ -3293,6 +3291,8 @@ HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Pipe | |||
| 3293 | return S_OK; | 3291 | return S_OK; |
| 3294 | } | 3292 | } |
| 3295 | 3293 | ||
| 3294 | // A pipeline state, compute (create_compute) or graphics (create_graphics): each shader is found by the SHA-256 of | ||
| 3295 | // its FSSM program in the translator's index, and the FSSM blob is copied into the arena as the shader's code base. | ||
| 3296 | class PipelineState final | 3296 | class PipelineState final |
| 3297 | : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, | 3297 | : public Child<PipelineState, XboxPipelineStateStubs, ID3D12Object, ID3D12DeviceChild, ID3D12Pageable, |
| 3298 | ID3D12PipelineState> { | 3298 | ID3D12PipelineState> { |
| @@ -5120,6 +5120,8 @@ public: | |||
| 5120 | info.conditional_rendering, info.ray_tracing, | 5120 | info.conditional_rendering, info.ray_tracing, |
| 5121 | info.xdxr_acceleration_structures && | 5121 | info.xdxr_acceleration_structures && |
| 5122 | info.buffer_device_address); | 5122 | info.buffer_device_address); |
| 5123 | state_.context->mesh_queries = info.mesh_shader_queries; | ||
| 5124 | state_.context->set_depth_range_unrestricted(info.depth_range_unrestricted); | ||
| 5123 | if (info.physical && state_.format_properties) { | 5125 | if (info.physical && state_.format_properties) { |
| 5124 | state_.context->set_color_attachment_format( | 5126 | state_.context->set_color_attachment_format( |
| 5125 | [physical = info.physical, get_props = state_.format_properties](VkFormat format) { | 5127 | [physical = info.physical, get_props = state_.format_properties](VkFormat format) { |
| @@ -5187,7 +5189,8 @@ public: | |||
| 5187 | if (info.bindless && state_.context->loaded() && !create_bindless(get_device)) | 5189 | if (info.bindless && state_.context->loaded() && !create_bindless(get_device)) |
| 5188 | std::fprintf(stderr, "[rt] d3d12: the bindless set 0 could not be created\n"); | 5190 | std::fprintf(stderr, "[rt] d3d12: the bindless set 0 could not be created\n"); |
| 5189 | query_luid_and_clock(get_device); | 5191 | query_luid_and_clock(get_device); |
| 5190 | // Timestamps: what the one VkQueue every D3D12 queue submits to can write. | 5192 | // Timestamps: the device's timestampPeriod, enabled when the graphics family (info.queue_family) has |
| 5193 | // timestampValidBits. | ||
| 5191 | VkPhysicalDeviceProperties properties{}; | 5194 | VkPhysicalDeviceProperties properties{}; |
| 5192 | device_properties(info.physical, &properties); | 5195 | device_properties(info.physical, &properties); |
| 5193 | state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias; | 5196 | state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias; |
| @@ -7589,35 +7592,42 @@ public: | |||
| 7589 | return d3d12_trace::result(method, S_OK); | 7592 | return d3d12_trace::result(method, S_OK); |
| 7590 | } | 7593 | } |
| 7591 | case D3D12_FEATURE_D3D12_OPTIONS: { | 7594 | case D3D12_FEATURE_D3D12_OPTIONS: { |
| 7592 | if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS)) return d3d12_trace::result(method, E_INVALIDARG); | 7595 | constexpr UINT kConsoleOptionsSize = sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS) + sizeof(UINT); |
| 7593 | auto* opts = static_cast<D3D12_FEATURE_DATA_D3D12_OPTIONS*>(data); | 7596 | if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS) && size != kConsoleOptionsSize) |
| 7594 | *opts = {}; | 7597 | return d3d12_trace::result(method, E_INVALIDARG); |
| 7598 | D3D12_FEATURE_DATA_D3D12_OPTIONS pc_opts{}; | ||
| 7595 | // Answer what the layer will actually honour, not what the GPU offers: docs/d3d12_vulkan.md 4.1 says a | 7599 | // Answer what the layer will actually honour, not what the GPU offers: docs/d3d12_vulkan.md 4.1 says a |
| 7596 | // false "supported" is worse than a false "unsupported" at boot, and the PSO paths refuse these same | 7600 | // false "supported" is worse than a false "unsupported" at boot, and the PSO paths refuse these same |
| 7597 | // features when they are missing (logic ops, per the mapping vkd3d-proton's | 7601 | // features when they are missing (logic ops, per the mapping vkd3d-proton's |
| 7598 | // d3d12_device_caps_init_feature_options uses). | 7602 | // d3d12_device_caps_init_feature_options uses). |
| 7599 | opts->DoublePrecisionFloatShaderOps = state_.info.features.shaderFloat64; | 7603 | pc_opts.DoublePrecisionFloatShaderOps = state_.info.features.shaderFloat64; |
| 7600 | opts->OutputMergerLogicOp = state_.info.features.logicOp; | 7604 | pc_opts.OutputMergerLogicOp = state_.info.features.logicOp; |
| 7601 | opts->MinPrecisionSupport = D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE; | 7605 | pc_opts.MinPrecisionSupport = D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE; |
| 7602 | opts->TiledResourcesTier = D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED; | 7606 | pc_opts.TiledResourcesTier = D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED; |
| 7603 | opts->ResourceBindingTier = D3D12_RESOURCE_BINDING_TIER_3; // Bindless descriptor indexing supported | 7607 | pc_opts.ResourceBindingTier = D3D12_RESOURCE_BINDING_TIER_3; // Bindless descriptor indexing supported |
| 7604 | // No VK_EXT_shader_stencil_export is enabled and the translator emits no stencil-ref write, so a pixel | 7608 | // No VK_EXT_shader_stencil_export is enabled and the translator emits no stencil-ref write, so a pixel |
| 7605 | // shader that writes the stencil ref would be refused: answer unsupported, the direction 4.1 prefers. | 7609 | // shader that writes the stencil ref would be refused: answer unsupported, the direction 4.1 prefers. |
| 7606 | opts->PSSpecifiedStencilRefSupported = FALSE; | 7610 | pc_opts.PSSpecifiedStencilRefSupported = FALSE; |
| 7607 | opts->TypedUAVLoadAdditionalFormats = TRUE; | 7611 | pc_opts.TypedUAVLoadAdditionalFormats = TRUE; |
| 7608 | // POPS: the translator only declares PixelInterlockOrderedEXT, enabled exactly when the GPU offers | 7612 | // POPS: the translator only declares PixelInterlockOrderedEXT, enabled exactly when the GPU offers |
| 7609 | // VK_EXT_fragment_shader_interlock and its fragmentShaderPixelInterlock feature. | 7613 | // VK_EXT_fragment_shader_interlock and its fragmentShaderPixelInterlock feature. |
| 7610 | opts->ROVsSupported = state_.info.fragment_shader_interlock; | 7614 | pc_opts.ROVsSupported = state_.info.fragment_shader_interlock; |
| 7611 | opts->ConservativeRasterizationTier = state_.conservative_raster_tier; | 7615 | pc_opts.ConservativeRasterizationTier = state_.conservative_raster_tier; |
| 7612 | opts->MaxGPUVirtualAddressBitsPerResource = 40; | 7616 | pc_opts.MaxGPUVirtualAddressBitsPerResource = 40; |
| 7613 | opts->StandardSwizzle64KBSupported = FALSE; | 7617 | pc_opts.StandardSwizzle64KBSupported = FALSE; |
| 7614 | opts->CrossNodeSharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED; | 7618 | pc_opts.CrossNodeSharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED; |
| 7615 | opts->CrossAdapterRowMajorTextureSupported = FALSE; | 7619 | pc_opts.CrossAdapterRowMajorTextureSupported = FALSE; |
| 7616 | // A translated vertex shader writing a layer or viewport index needs both Vulkan 1.2 features enabled | 7620 | // A translated vertex shader writing a layer or viewport index needs both Vulkan 1.2 features enabled |
| 7617 | // (vkCreateShaderModule refuses the module without them, VUID-...-pCode-08740). | 7621 | // (vkCreateShaderModule refuses the module without them, VUID-...-pCode-08740). |
| 7618 | opts->VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation = | 7622 | pc_opts.VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation = |
| 7619 | state_.info.shader_output_layer && state_.info.shader_output_viewport_index; | 7623 | state_.info.shader_output_layer && state_.info.shader_output_viewport_index; |
| 7620 | opts->ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_1; | 7624 | pc_opts.ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_1; |
| 7625 | std::memcpy(data, &pc_opts, sizeof(pc_opts)); | ||
| 7626 | if (size == kConsoleOptionsSize) { | ||
| 7627 | // Console titles query D3D12_FEATURE_D3D12_OPTIONS with a 0x40-byte (16-dword) buffer | ||
| 7628 | // (docs/d3d12_xs_surface.md §7.1): fill the 0x3C-byte PC prefix and zero the trailing 4 bytes. | ||
| 7629 | std::memset(static_cast<std::uint8_t*>(data) + sizeof(pc_opts), 0, sizeof(UINT)); | ||
| 7630 | } | ||
| 7621 | return d3d12_trace::result(method, S_OK); | 7631 | return d3d12_trace::result(method, S_OK); |
| 7622 | } | 7632 | } |
| 7623 | case D3D12_FEATURE_D3D12_OPTIONS1: { | 7633 | case D3D12_FEATURE_D3D12_OPTIONS1: { |
| @@ -7951,8 +7961,7 @@ public: | |||
| 7951 | // Vulkan can still advertise buffer features for their backing formats. | 7961 | // Vulkan can still advertise buffer features for their backing formats. |
| 7952 | if (buffer != 0 && vk_fmt != VK_FORMAT_R8G8B8A8_SRGB && vk_fmt != VK_FORMAT_B8G8R8A8_SRGB) | 7962 | if (buffer != 0 && vk_fmt != VK_FORMAT_R8G8B8A8_SRGB && vk_fmt != VK_FORMAT_B8G8R8A8_SRGB) |
| 7953 | s1 |= D3D12_FORMAT_SUPPORT1_BUFFER; | 7963 | s1 |= D3D12_FORMAT_SUPPORT1_BUFFER; |
| 7954 | // Only what CreateGraphicsPipelineState's input layouts accept (vertex_format): R8/R16 SNORM and SINT | 7964 | // Only what CreateGraphicsPipelineState's input layouts accept (vertex_format). |
| 7955 | // have Vulkan vertex support but no input-layout mapping yet. | ||
| 7956 | VkFormat vertex_vk = VK_FORMAT_UNDEFINED; | 7965 | VkFormat vertex_vk = VK_FORMAT_UNDEFINED; |
| 7957 | UINT vertex_bytes = 0; | 7966 | UINT vertex_bytes = 0; |
| 7958 | if ((buffer & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) && vertex_format(fs->Format, vertex_vk, vertex_bytes)) | 7967 | if ((buffer & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) && vertex_format(fs->Format, vertex_vk, vertex_bytes)) |
| @@ -8003,8 +8012,9 @@ public: | |||
| 8003 | s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; | 8012 | s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; |
| 8004 | // A typed UAV texture read is not a storage-image read: the translator reads it through the | 8013 | // A typed UAV texture read is not a storage-image read: the translator reads it through the |
| 8005 | // texture's sampled binding with the T#'s numeric type (rdna2spirv.py image_read_typed), so a | 8014 | // texture's sampled binding with the T#'s numeric type (rdna2spirv.py image_read_typed), so a |
| 8006 | // format that can be stored can be read. Typed buffer UAVs share the store side's limits: the layer | 8015 | // format that can be stored can be read. Typed buffer UAVs share the store side's limits: a buffer |
| 8007 | // creates no buffer UAV views yet, and rdna2spirv.py FORMATS decodes only some buffer formats. | 8016 | // UAV is a typed V# the layer writes itself (write_buffer_uav, no VkBufferView), and rdna2spirv.py |
| 8017 | // FORMATS decodes only some buffer formats. | ||
| 8008 | s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; | 8018 | s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; |
| 8009 | // Image atomics go through the r32ui storage view, which an R32_UINT UAV view gets | 8019 | // Image atomics go through the r32ui storage view, which an R32_UINT UAV view gets |
| 8010 | // (StorageViews::r32ui). Today that is 2D UAVs only: the translator's image atomics cover 2D and 3D, | 8020 | // (StorageViews::r32ui). Today that is 2D UAVs only: the translator's image atomics cover 2D and 3D, |
| @@ -9490,6 +9500,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 9490 | VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; | 9500 | VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; |
| 9491 | vkGetPhysicalDeviceFeatures2(info.physical, &features); | 9501 | vkGetPhysicalDeviceFeatures2(info.physical, &features); |
| 9492 | info.mesh_shader = mesh_features.meshShader == VK_TRUE; | 9502 | info.mesh_shader = mesh_features.meshShader == VK_TRUE; |
| 9503 | info.mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE; | ||
| 9493 | } | 9504 | } |
| 9494 | } | 9505 | } |
| 9495 | if (!info.mesh_shader) | 9506 | if (!info.mesh_shader) |
| @@ -9526,6 +9537,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 9526 | // are not used. | 9537 | // are not used. |
| 9527 | VkPhysicalDeviceMeshShaderFeaturesEXT enable_mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; | 9538 | VkPhysicalDeviceMeshShaderFeaturesEXT enable_mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; |
| 9528 | enable_mesh.meshShader = VK_TRUE; | 9539 | enable_mesh.meshShader = VK_TRUE; |
| 9540 | // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER). | ||
| 9541 | enable_mesh.meshShaderQueries = info.mesh_shader_queries ? VK_TRUE : VK_FALSE; | ||
| 9529 | 9542 | ||
| 9530 | void* ext_chain = nullptr; | 9543 | void* ext_chain = nullptr; |
| 9531 | if (info.mesh_shader) { | 9544 | if (info.mesh_shader) { |
| @@ -9723,6 +9736,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 9723 | return std::any_of(extensions.begin(), extensions.end(), | 9736 | return std::any_of(extensions.begin(), extensions.end(), |
| 9724 | [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); | 9737 | [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); |
| 9725 | }; | 9738 | }; |
| 9739 | info.depth_range_unrestricted = has_device_extension(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); | ||
| 9726 | VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{ | 9740 | VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{ |
| 9727 | VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; | 9741 | VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; |
| 9728 | if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { | 9742 | if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { |
| @@ -9899,6 +9913,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin | |||
| 9899 | device_info.pEnabledFeatures = &enable; | 9913 | device_info.pEnabledFeatures = &enable; |
| 9900 | std::vector<const char*> device_extensions; | 9914 | std::vector<const char*> device_extensions; |
| 9901 | v13.add_extensions(device_extensions); | 9915 | v13.add_extensions(device_extensions); |
| 9916 | if (info.depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); | ||
| 9902 | if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); | 9917 | if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); |
| 9903 | if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); | 9918 | if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); |
| 9904 | if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); | 9919 | if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); |
diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 7f7040fdd..85aece0bd 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp | |||
| @@ -76,8 +76,25 @@ struct DeviceProxy { | |||
| 76 | std::atomic<std::uint32_t> frame_latency{1}; | 76 | std::atomic<std::uint32_t> frame_latency{1}; |
| 77 | std::atomic<bool> frame_event_scheduled{false}; | 77 | std::atomic<bool> frame_event_scheduled{false}; |
| 78 | std::atomic<std::uint64_t> frame_next_token{1}; | 78 | std::atomic<std::uint64_t> frame_next_token{1}; |
| 79 | // Optional presentation wiring attached via set_presentation_handler (guarded by presentation_lock). | ||
| 80 | SRWLOCK presentation_lock = SRWLOCK_INIT; | ||
| 81 | PresentationHandler presentation{}; | ||
| 79 | }; | 82 | }; |
| 80 | 83 | ||
| 84 | // Runs f(handler) with the presentation lock held shared, so a detach cannot destroy the presentation mid-call. f | ||
| 85 | // returns false, without calling the presentation, when it has no function for the slot; the result says whether | ||
| 86 | // f handled the call. | ||
| 87 | // ponytail: a presenter callback must not call set_presentation_handler (exclusive inside shared deadlocks), and a | ||
| 88 | // detach waits for a WaitFrameEventX in flight up to its timeout. | ||
| 89 | template <typename F> | ||
| 90 | bool call_presentation(DeviceProxy* self, F&& f) { | ||
| 91 | if (!self) return false; | ||
| 92 | AcquireSRWLockShared(&self->presentation_lock); | ||
| 93 | const bool handled = f(static_cast<const PresentationHandler&>(self->presentation)); | ||
| 94 | ReleaseSRWLockShared(&self->presentation_lock); | ||
| 95 | return handled; | ||
| 96 | } | ||
| 97 | |||
| 81 | constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles | 98 | constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles |
| 82 | 99 | ||
| 83 | struct HeapProxy { | 100 | struct HeapProxy { |
| @@ -181,24 +198,27 @@ struct XboxDeviceSlotRoutes { | |||
| 181 | unsigned frame_interval = 78; // SetFrameIntervalX(output, interval_us, latency, flags) | 198 | unsigned frame_interval = 78; // SetFrameIntervalX(output, interval_us, latency, flags) |
| 182 | unsigned schedule_event = 79; // ScheduleFrameEventX(event, offset_us, reserved, flags) | 199 | unsigned schedule_event = 79; // ScheduleFrameEventX(event, offset_us, reserved, flags) |
| 183 | unsigned wait_event = 80; // WaitFrameEventX(event, timeout_ms, reserved, flags, &token) | 200 | unsigned wait_event = 80; // WaitFrameEventX(event, timeout_ms, reserved, flags, &token) |
| 201 | unsigned frame_statistics = 81; // GetFrameStatisticsX(token, type_mask, count, out) | ||
| 184 | unsigned queue_x = 48; // CreateCommandQueueX(desc, riid, out) | 202 | unsigned queue_x = 48; // CreateCommandQueueX(desc, riid, out) |
| 185 | unsigned list_x = 73; // CreateCommandListX(desc, allocator, initial_state, riid, out) | 203 | unsigned list_x = 73; // CreateCommandListX(desc, allocator, initial_state, riid, out) |
| 186 | }; | 204 | }; |
| 187 | 205 | ||
| 188 | unsigned env_device_slot(const char* name, unsigned fallback) { | 206 | // Reads a slot number in lo..hi from `name`: an unset variable gives `fallback`; a bad value is logged (`what` names |
| 207 | // the kind of slot) and ignored. | ||
| 208 | unsigned env_slot(const char* name, unsigned fallback, unsigned lo, unsigned hi, const char* what) { | ||
| 189 | char value[32] = {}; | 209 | char value[32] = {}; |
| 190 | const DWORD length = GetEnvironmentVariableA(name, value, sizeof(value)); | 210 | const DWORD length = GetEnvironmentVariableA(name, value, sizeof(value)); |
| 191 | if (length == 0) return fallback; | 211 | if (length == 0) return fallback; |
| 192 | if (length >= sizeof(value)) { | 212 | if (length >= sizeof(value)) { |
| 193 | std::fprintf(stderr, "[rt] d3d12_xs: %s is too long for a device slot; the default is kept\n", name); | 213 | std::fprintf(stderr, "[rt] d3d12_xs: %s is too long for a %s; the default is kept\n", name, what); |
| 194 | return fallback; | 214 | return fallback; |
| 195 | } | 215 | } |
| 196 | errno = 0; | 216 | errno = 0; |
| 197 | char* end = nullptr; | 217 | char* end = nullptr; |
| 198 | const unsigned long slot = std::strtoul(value, &end, 0); | 218 | const unsigned long slot = std::strtoul(value, &end, 0); |
| 199 | if (errno != 0 || end == value || *end != '\0' || slot < 3 || slot > 127) { | 219 | if (errno != 0 || end == value || *end != '\0' || slot < lo || slot > hi) { |
| 200 | std::fprintf(stderr, "[rt] d3d12_xs: %s=%s is not a device slot in 3..127; the default is kept\n", name, | 220 | std::fprintf(stderr, "[rt] d3d12_xs: %s=%s is not a %s in %u..%u; the default is kept\n", name, value, what, |
| 201 | value); | 221 | lo, hi); |
| 202 | return fallback; | 222 | return fallback; |
| 203 | } | 223 | } |
| 204 | return static_cast<unsigned>(slot); | 224 | return static_cast<unsigned>(slot); |
| @@ -207,23 +227,29 @@ unsigned env_device_slot(const char* name, unsigned fallback) { | |||
| 207 | const XboxDeviceSlotRoutes& xbox_device_slot_routes() { | 227 | const XboxDeviceSlotRoutes& xbox_device_slot_routes() { |
| 208 | static const XboxDeviceSlotRoutes routes = [] { | 228 | static const XboxDeviceSlotRoutes routes = [] { |
| 209 | XboxDeviceSlotRoutes r; | 229 | XboxDeviceSlotRoutes r; |
| 210 | const unsigned frame_interval = env_device_slot("LEONIDA_XS_FRAME_INTERVAL_SLOT", r.frame_interval); | 230 | const unsigned frame_interval = env_slot("LEONIDA_XS_FRAME_INTERVAL_SLOT", r.frame_interval, 3, 127, |
| 211 | const unsigned schedule_event = env_device_slot("LEONIDA_XS_SCHEDULE_EVENT_SLOT", r.schedule_event); | 231 | "device slot"); |
| 212 | const unsigned wait_event = env_device_slot("LEONIDA_XS_WAIT_EVENT_SLOT", r.wait_event); | 232 | const unsigned schedule_event = env_slot("LEONIDA_XS_SCHEDULE_EVENT_SLOT", r.schedule_event, 3, 127, |
| 213 | const unsigned queue_x = env_device_slot("LEONIDA_XS_QUEUE_X_SLOT", r.queue_x); | 233 | "device slot"); |
| 214 | const unsigned list_x = env_device_slot("LEONIDA_XS_LIST_X_SLOT", r.list_x); | 234 | const unsigned wait_event = env_slot("LEONIDA_XS_WAIT_EVENT_SLOT", r.wait_event, 3, 127, "device slot"); |
| 235 | const unsigned frame_statistics = env_slot("LEONIDA_XS_FRAME_STATISTICS_SLOT", r.frame_statistics, 3, 127, | ||
| 236 | "device slot"); | ||
| 237 | const unsigned queue_x = env_slot("LEONIDA_XS_QUEUE_X_SLOT", r.queue_x, 3, 127, "device slot"); | ||
| 238 | const unsigned list_x = env_slot("LEONIDA_XS_LIST_X_SLOT", r.list_x, 3, 127, "device slot"); | ||
| 215 | const bool moved = frame_interval != r.frame_interval || schedule_event != r.schedule_event || | 239 | const bool moved = frame_interval != r.frame_interval || schedule_event != r.schedule_event || |
| 216 | wait_event != r.wait_event || queue_x != r.queue_x || list_x != r.list_x; | 240 | wait_event != r.wait_event || frame_statistics != r.frame_statistics || |
| 241 | queue_x != r.queue_x || list_x != r.list_x; | ||
| 217 | r.frame_interval = frame_interval; | 242 | r.frame_interval = frame_interval; |
| 218 | r.schedule_event = schedule_event; | 243 | r.schedule_event = schedule_event; |
| 219 | r.wait_event = wait_event; | 244 | r.wait_event = wait_event; |
| 245 | r.frame_statistics = frame_statistics; | ||
| 220 | r.queue_x = queue_x; | 246 | r.queue_x = queue_x; |
| 221 | r.list_x = list_x; | 247 | r.list_x = list_x; |
| 222 | if (moved) | 248 | if (moved) |
| 223 | std::fprintf(stderr, | 249 | std::fprintf(stderr, |
| 224 | "[rt] d3d12_xs: Xbox device slots: SetFrameIntervalX=%u ScheduleFrameEventX=%u " | 250 | "[rt] d3d12_xs: Xbox device slots: SetFrameIntervalX=%u ScheduleFrameEventX=%u " |
| 225 | "WaitFrameEventX=%u CreateCommandQueueX=%u CreateCommandListX=%u\n", | 251 | "WaitFrameEventX=%u GetFrameStatisticsX=%u CreateCommandQueueX=%u CreateCommandListX=%u\n", |
| 226 | r.frame_interval, r.schedule_event, r.wait_event, r.queue_x, r.list_x); | 252 | r.frame_interval, r.schedule_event, r.wait_event, r.frame_statistics, r.queue_x, r.list_x); |
| 227 | return r; | 253 | return r; |
| 228 | }(); | 254 | }(); |
| 229 | return routes; | 255 | return routes; |
| @@ -983,6 +1009,10 @@ inline void note_list_slot(unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 | |||
| 983 | static_cast<unsigned long long>(a3), static_cast<unsigned long long>(a4)); | 1009 | static_cast<unsigned long long>(a3), static_cast<unsigned long long>(a4)); |
| 984 | } | 1010 | } |
| 985 | 1011 | ||
| 1012 | // Measured Xbox ID3D12GraphicsCommandListX IID passed to device slot 73 (CreateCommandListX). | ||
| 1013 | constexpr IID kXboxGraphicsCommandListXIid = { | ||
| 1014 | 0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}}; | ||
| 1015 | |||
| 986 | inline bool is_list_iid(const IID& iid) { | 1016 | inline bool is_list_iid(const IID& iid) { |
| 987 | return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || | 1017 | return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || |
| 988 | IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) || | 1018 | IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) || |
| @@ -994,7 +1024,8 @@ inline bool is_list_iid(const IID& iid) { | |||
| 994 | IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || | 1024 | IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || |
| 995 | IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || | 1025 | IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || |
| 996 | IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || | 1026 | IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || |
| 997 | IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)); | 1027 | IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)) || |
| 1028 | IsEqualIID(iid, kXboxGraphicsCommandListXIid); | ||
| 998 | } | 1029 | } |
| 999 | 1030 | ||
| 1000 | inline unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; } | 1031 | inline unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; } |
| @@ -1022,7 +1053,10 @@ inline HRESULT list_query_interface(ListProxy* self, const IID* riid, void** out | |||
| 1022 | if (supports_iid(self->real, *riid)) log_refused_iid("list", *riid); | 1053 | if (supports_iid(self->real, *riid)) log_refused_iid("list", *riid); |
| 1023 | return E_NOINTERFACE; | 1054 | return E_NOINTERFACE; |
| 1024 | } | 1055 | } |
| 1025 | if (!supports_iid(self->real, *riid)) return E_NOINTERFACE; | 1056 | const IID real_iid = IsEqualIID(*riid, kXboxGraphicsCommandListXIid) |
| 1057 | ? __uuidof(ID3D12GraphicsCommandList) | ||
| 1058 | : *riid; | ||
| 1059 | if (!supports_iid(self->real, real_iid)) return E_NOINTERFACE; | ||
| 1026 | *out = self; | 1060 | *out = self; |
| 1027 | list_add_ref(self); | 1061 | list_add_ref(self); |
| 1028 | return S_OK; | 1062 | return S_OK; |
| @@ -1194,6 +1228,40 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) { | |||
| 1194 | return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash | 1228 | return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash |
| 1195 | } | 1229 | } |
| 1196 | 1230 | ||
| 1231 | // PresentX is at queue slot 30 in an older runtime layout and 32 in a newer one (public corroboration, XCL; see | ||
| 1232 | // docs/d3d12_vulkan.md). 30 is the default and LEONIDA_XS_PRESENT_X_SLOT sets the other. SuspendX and ResumeX have no | ||
| 1233 | // default: 0 means not routed, so they answer only when their variable is set. | ||
| 1234 | struct XboxQueueSlotRoutes { | ||
| 1235 | unsigned present_x = 30; // PresentX(plane_count, planes, params) | ||
| 1236 | unsigned suspend_x = 0; // SuspendX(flags) | ||
| 1237 | unsigned resume_x = 0; // ResumeX() | ||
| 1238 | }; | ||
| 1239 | |||
| 1240 | const XboxQueueSlotRoutes& xbox_queue_slot_routes() { | ||
| 1241 | static const XboxQueueSlotRoutes routes = [] { | ||
| 1242 | XboxQueueSlotRoutes r; | ||
| 1243 | r.present_x = env_slot("LEONIDA_XS_PRESENT_X_SLOT", r.present_x, kQueuePublicSlots, kQueueSlots - 1, | ||
| 1244 | "queue slot"); | ||
| 1245 | r.suspend_x = env_slot("LEONIDA_XS_SUSPEND_X_SLOT", r.suspend_x, kQueuePublicSlots, kQueueSlots - 1, | ||
| 1246 | "queue slot"); | ||
| 1247 | r.resume_x = env_slot("LEONIDA_XS_RESUME_X_SLOT", r.resume_x, kQueuePublicSlots, kQueueSlots - 1, | ||
| 1248 | "queue slot"); | ||
| 1249 | // Two routes on one slot cannot both answer: PresentX keeps it, then SuspendX; the later route is unrouted. | ||
| 1250 | if (r.suspend_x && r.suspend_x == r.present_x) { | ||
| 1251 | std::fprintf(stderr, "[rt] d3d12_xs: SuspendX slot %u is PresentX's slot; SuspendX is not routed\n", | ||
| 1252 | r.suspend_x); | ||
| 1253 | r.suspend_x = 0; | ||
| 1254 | } | ||
| 1255 | if (r.resume_x && (r.resume_x == r.present_x || r.resume_x == r.suspend_x)) { | ||
| 1256 | std::fprintf(stderr, "[rt] d3d12_xs: ResumeX slot %u is already routed; ResumeX is not routed\n", | ||
| 1257 | r.resume_x); | ||
| 1258 | r.resume_x = 0; | ||
| 1259 | } | ||
| 1260 | return r; | ||
| 1261 | }(); | ||
| 1262 | return routes; | ||
| 1263 | } | ||
| 1264 | |||
| 1197 | template <ChildKind K, unsigned Slot> | 1265 | template <ChildKind K, unsigned Slot> |
| 1198 | std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, | 1266 | std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, |
| 1199 | std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, | 1267 | std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, |
| @@ -1214,6 +1282,27 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ | |||
| 1214 | } else { | 1282 | } else { |
| 1215 | note_child_slot<K>(Slot); | 1283 | note_child_slot<K>(Slot); |
| 1216 | if (Slot >= self->slot_count) { | 1284 | if (Slot >= self->slot_count) { |
| 1285 | if constexpr (K == ChildKind::queue) { | ||
| 1286 | const XboxQueueSlotRoutes& qroutes = xbox_queue_slot_routes(); | ||
| 1287 | HRESULT hr = S_OK; | ||
| 1288 | if (call_presentation(self->device, [&](const PresentationHandler& p) { | ||
| 1289 | if (Slot == qroutes.present_x && p.present_x) { | ||
| 1290 | hr = p.present_x(p.context, static_cast<UINT>(a1), reinterpret_cast<const void*>(a2), | ||
| 1291 | reinterpret_cast<const void*>(a3)); | ||
| 1292 | return true; | ||
| 1293 | } | ||
| 1294 | if (Slot == qroutes.suspend_x && p.suspend_x) { | ||
| 1295 | hr = p.suspend_x(p.context, static_cast<UINT>(a1)); | ||
| 1296 | return true; | ||
| 1297 | } | ||
| 1298 | if (Slot == qroutes.resume_x && p.resume_x) { | ||
| 1299 | hr = p.resume_x(p.context); | ||
| 1300 | return true; | ||
| 1301 | } | ||
| 1302 | return false; | ||
| 1303 | })) | ||
| 1304 | return hr_to_u64(hr); | ||
| 1305 | } | ||
| 1217 | bool expected = false; | 1306 | bool expected = false; |
| 1218 | if (ChildStats<K>::beyond_warned[Slot].compare_exchange_strong(expected, true, | 1307 | if (ChildStats<K>::beyond_warned[Slot].compare_exchange_strong(expected, true, |
| 1219 | std::memory_order_relaxed)) { | 1308 | std::memory_order_relaxed)) { |
| @@ -1380,8 +1469,14 @@ HRESULT proxy_create_command_queue(DeviceProxy* self, const D3D12_COMMAND_QUEUE_ | |||
| 1380 | // 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces. | 1469 | // 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces. |
| 1381 | HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us, | 1470 | HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us, |
| 1382 | std::uint64_t latency, std::uint64_t flags) { | 1471 | std::uint64_t latency, std::uint64_t flags) { |
| 1383 | (void)output; | 1472 | HRESULT hr = S_OK; |
| 1384 | (void)flags; | 1473 | if (call_presentation(self, [&](const PresentationHandler& p) { |
| 1474 | if (!p.set_frame_interval) return false; | ||
| 1475 | hr = p.set_frame_interval(p.context, reinterpret_cast<IUnknown*>(output), static_cast<UINT>(interval_us), | ||
| 1476 | static_cast<UINT>(latency), static_cast<UINT>(flags)); | ||
| 1477 | return true; | ||
| 1478 | })) | ||
| 1479 | return hr; | ||
| 1385 | self->frame_interval_us.store(static_cast<std::uint32_t>(interval_us), std::memory_order_relaxed); | 1480 | self->frame_interval_us.store(static_cast<std::uint32_t>(interval_us), std::memory_order_relaxed); |
| 1386 | self->frame_latency.store(static_cast<std::uint32_t>(latency ? latency : 1), std::memory_order_relaxed); | 1481 | self->frame_latency.store(static_cast<std::uint32_t>(latency ? latency : 1), std::memory_order_relaxed); |
| 1387 | return S_OK; | 1482 | return S_OK; |
| @@ -1390,22 +1485,31 @@ HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std: | |||
| 1390 | // Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin. | 1485 | // Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin. |
| 1391 | HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us, | 1486 | HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us, |
| 1392 | std::uint64_t flags) { | 1487 | std::uint64_t flags) { |
| 1393 | (void)event; | 1488 | HRESULT hr = S_OK; |
| 1394 | (void)offset_us; | 1489 | if (call_presentation(self, [&](const PresentationHandler& p) { |
| 1395 | (void)flags; | 1490 | if (!p.schedule_frame_event) return false; |
| 1491 | hr = p.schedule_frame_event(p.context, static_cast<UINT>(event), static_cast<UINT>(offset_us), | ||
| 1492 | static_cast<UINT>(flags)); | ||
| 1493 | return true; | ||
| 1494 | })) | ||
| 1495 | return hr; | ||
| 1396 | self->frame_event_scheduled.store(true, std::memory_order_relaxed); | 1496 | self->frame_event_scheduled.store(true, std::memory_order_relaxed); |
| 1397 | return S_OK; | 1497 | return S_OK; |
| 1398 | } | 1498 | } |
| 1399 | 1499 | ||
| 1400 | // Xbox device slot 80 (public HLE): WaitFrameEventX(event, timeout_ms, pEvent, flags, &token). It returns at once with | 1500 | // Xbox device slot 80 (public HLE): WaitFrameEventX(event, timeout_ms, pEvent, flags, &token). When a presenter is |
| 1401 | // a fresh non-zero token (the first-frame choice): there is no vblank source behind the device before a presenter, and | 1501 | // attached, forwards directly to it; otherwise returns at once with a fresh non-zero token so boot tests cannot stall. |
| 1402 | // a zero wait cannot stall the title. A null token pointer is E_POINTER, as a _Out_ parameter. | ||
| 1403 | HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms, | 1502 | HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms, |
| 1404 | std::uint64_t flags, std::uint64_t token_word) { | 1503 | std::uint64_t flags, std::uint64_t token_word) { |
| 1405 | (void)event; | ||
| 1406 | (void)timeout_ms; | ||
| 1407 | (void)flags; | ||
| 1408 | auto* token = reinterpret_cast<std::uint64_t*>(token_word); | 1504 | auto* token = reinterpret_cast<std::uint64_t*>(token_word); |
| 1505 | HRESULT hr = S_OK; | ||
| 1506 | if (call_presentation(self, [&](const PresentationHandler& p) { | ||
| 1507 | if (!p.wait_frame_event) return false; | ||
| 1508 | hr = p.wait_frame_event(p.context, static_cast<UINT>(event), static_cast<DWORD>(timeout_ms), | ||
| 1509 | static_cast<UINT>(flags), token); | ||
| 1510 | return true; | ||
| 1511 | })) | ||
| 1512 | return hr; | ||
| 1409 | if (!token) return E_POINTER; | 1513 | if (!token) return E_POINTER; |
| 1410 | std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); | 1514 | std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); |
| 1411 | if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token | 1515 | if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token |
| @@ -1442,8 +1546,11 @@ HRESULT proxy_create_command_list_x(DeviceProxy* self, std::uint64_t desc_word, | |||
| 1442 | if (!allocator) allocator = reinterpret_cast<ID3D12CommandAllocator*>(allocator_word); | 1546 | if (!allocator) allocator = reinterpret_cast<ID3D12CommandAllocator*>(allocator_word); |
| 1443 | auto* initial_state = reinterpret_cast<ID3D12PipelineState*>(initial_state_word); | 1547 | auto* initial_state = reinterpret_cast<ID3D12PipelineState*>(initial_state_word); |
| 1444 | void* created = nullptr; | 1548 | void* created = nullptr; |
| 1549 | const IID& create_iid = IsEqualIID(*riid, kXboxGraphicsCommandListXIid) | ||
| 1550 | ? __uuidof(ID3D12GraphicsCommandList) | ||
| 1551 | : *riid; | ||
| 1445 | const HRESULT hr = self->real->CreateCommandList(0, type, allocator, initial_state, | 1552 | const HRESULT hr = self->real->CreateCommandList(0, type, allocator, initial_state, |
| 1446 | *riid, &created); | 1553 | create_iid, &created); |
| 1447 | if (FAILED(hr)) return hr; | 1554 | if (FAILED(hr)) return hr; |
| 1448 | return wrap_list(static_cast<IUnknown*>(created), self, riid, out); | 1555 | return wrap_list(static_cast<IUnknown*>(created), self, riid, out); |
| 1449 | } | 1556 | } |
| @@ -2038,6 +2145,22 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 | |||
| 2038 | log_xbox_route_once(Slot, "WaitFrameEventX", a1, a2, a3, a4, a5); | 2145 | log_xbox_route_once(Slot, "WaitFrameEventX", a1, a2, a3, a4, a5); |
| 2039 | return hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5)); | 2146 | return hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5)); |
| 2040 | } | 2147 | } |
| 2148 | if (Slot == routes.frame_statistics) { | ||
| 2149 | HRESULT hr = S_OK; | ||
| 2150 | if (call_presentation(self, [&](const PresentationHandler& p) { | ||
| 2151 | if (!p.get_frame_statistics) return false; | ||
| 2152 | log_xbox_route_once(Slot, "GetFrameStatisticsX", a1, a2, a3, a4, a5); | ||
| 2153 | hr = p.get_frame_statistics(p.context, a1, static_cast<UINT>(a2), reinterpret_cast<UINT*>(a3), | ||
| 2154 | reinterpret_cast<void*>(a4)); | ||
| 2155 | return true; | ||
| 2156 | })) | ||
| 2157 | return hr_to_u64(hr); | ||
| 2158 | // No presenter: no statistics yet (S_FALSE with a zero count, the "not available yet" answer in | ||
| 2159 | // docs/d3d12_vulkan.md), and never the PC slot 81 (ID3D12Device13::OpenExistingHeapFromAddress1). | ||
| 2160 | log_xbox_route_once(Slot, "GetFrameStatisticsX", a1, a2, a3, a4, a5); | ||
| 2161 | if (auto* count = reinterpret_cast<UINT*>(a3)) *count = 0; | ||
| 2162 | return hr_to_u64(S_FALSE); | ||
| 2163 | } | ||
| 2041 | if (Slot == routes.queue_x) { | 2164 | if (Slot == routes.queue_x) { |
| 2042 | log_xbox_route_once(Slot, "CreateCommandQueueX", a1, a2, a3, a4, a5); | 2165 | log_xbox_route_once(Slot, "CreateCommandQueueX", a1, a2, a3, a4, a5); |
| 2043 | return hr_to_u64(proxy_create_command_queue_xbox(self, reinterpret_cast<const std::uint32_t*>(a1), | 2166 | return hr_to_u64(proxy_create_command_queue_xbox(self, reinterpret_cast<const std::uint32_t*>(a1), |
| @@ -2246,6 +2369,15 @@ void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler) { | |||
| 2246 | g_console_descriptor_heap.store(handler, std::memory_order_release); | 2369 | g_console_descriptor_heap.store(handler, std::memory_order_release); |
| 2247 | } | 2370 | } |
| 2248 | 2371 | ||
| 2372 | bool set_presentation_handler(void* device, const PresentationHandler* handler) { | ||
| 2373 | auto* proxy = static_cast<DeviceProxy*>(device_proxy_primary(device)); | ||
| 2374 | if (!proxy) return false; | ||
| 2375 | AcquireSRWLockExclusive(&proxy->presentation_lock); | ||
| 2376 | proxy->presentation = handler ? *handler : PresentationHandler{}; | ||
| 2377 | ReleaseSRWLockExclusive(&proxy->presentation_lock); | ||
| 2378 | return true; | ||
| 2379 | } | ||
| 2380 | |||
| 2249 | ID3D12Device* device_proxy_real_device(const void* device) { | 2381 | ID3D12Device* device_proxy_real_device(const void* device) { |
| 2250 | if (!is_device_proxy(device)) return nullptr; | 2382 | if (!is_device_proxy(device)) return nullptr; |
| 2251 | return static_cast<const DeviceProxy*>(device)->real; | 2383 | return static_cast<const DeviceProxy*>(device)->real; |
| @@ -2258,7 +2390,7 @@ bool device_slot_overridden(unsigned slot) { | |||
| 2258 | return true; | 2390 | return true; |
| 2259 | const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); | 2391 | const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); |
| 2260 | return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event || | 2392 | return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event || |
| 2261 | slot == routes.queue_x || slot == routes.list_x; | 2393 | slot == routes.frame_statistics || slot == routes.queue_x || slot == routes.list_x; |
| 2262 | } | 2394 | } |
| 2263 | 2395 | ||
| 2264 | bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); } | 2396 | bool is_queue_proxy(const void* queue) { return is_child_proxy<ChildKind::queue>(queue); } |
diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 7ee880939..b7f020beb 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h | |||
| @@ -132,6 +132,24 @@ using ConsoleDescriptorHeapHandler = HRESULT (*)(ID3D12Device* real, const D3D12 | |||
| 132 | REFIID riid, void** out); | 132 | REFIID riid, void** out); |
| 133 | void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); | 133 | void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); |
| 134 | 134 | ||
| 135 | // Presentation wiring: connects device frame-event slots (78/79/80/81: SetFrameIntervalX, ScheduleFrameEventX, | ||
| 136 | // WaitFrameEventX, GetFrameStatisticsX; 81 is LEONIDA_XS_FRAME_STATISTICS_SLOT) and queue presentation slots (PresentX | ||
| 137 | // at 30, or LEONIDA_XS_PRESENT_X_SLOT; SuspendX and ResumeX are routed only when LEONIDA_XS_SUSPEND_X_SLOT / | ||
| 138 | // LEONIDA_XS_RESUME_X_SLOT are set) to an external presenter such as rt::d3d12::XboxPresentation without coupling | ||
| 139 | // d3d12_xs_device to Vulkan headers. Passing nullptr detaches the handler and restores the default mock/fallback | ||
| 140 | // behavior. | ||
| 141 | struct PresentationHandler { | ||
| 142 | void* context = nullptr; | ||
| 143 | HRESULT (*set_frame_interval)(void* context, IUnknown* output, UINT interval_us, UINT latency, UINT flags) = nullptr; | ||
| 144 | HRESULT (*schedule_frame_event)(void* context, UINT event, UINT offset_us, UINT flags) = nullptr; | ||
| 145 | HRESULT (*wait_frame_event)(void* context, UINT event, DWORD timeout_ms, UINT flags, std::uint64_t* token) = nullptr; | ||
| 146 | HRESULT (*get_frame_statistics)(void* context, std::uint64_t token, UINT type_mask, UINT* count, void* out) = nullptr; | ||
| 147 | HRESULT (*present_x)(void* context, UINT plane_count, const void* planes, const void* params) = nullptr; | ||
| 148 | HRESULT (*suspend_x)(void* context, UINT flags) = nullptr; | ||
| 149 | HRESULT (*resume_x)(void* context) = nullptr; | ||
| 150 | }; | ||
| 151 | bool set_presentation_handler(void* device, const PresentationHandler* handler); | ||
| 152 | |||
| 135 | // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue | 153 | // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue |
| 136 | // proxies), 9 (allocator proxies), 14, 26 (the console's struct-return form), | 154 | // proxies), 9 (allocator proxies), 14, 26 (the console's struct-return form), |
| 137 | // 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and | 155 | // 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and |
diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index 82dd75493..250fe0209 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp | |||
| @@ -266,7 +266,7 @@ FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { | |||
| 266 | SetLastError(ERROR_PROC_NOT_FOUND); | 266 | SetLastError(ERROR_PROC_NOT_FOUND); |
| 267 | return nullptr; | 267 | return nullptr; |
| 268 | } | 268 | } |
| 269 | if (module && !IS_INTRESOURCE(name)) { | 269 | if (module) { |
| 270 | const DWORD error = GetLastError(); | 270 | const DWORD error = GetLastError(); |
| 271 | const std::string dll = host_module_name(module); | 271 | const std::string dll = host_module_name(module); |
| 272 | void* shim = dll.empty() ? nullptr : find(dll, what); | 272 | void* shim = dll.empty() ? nullptr : find(dll, what); |
diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 6ec36e31c..f041df89f 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp | |||
| @@ -494,7 +494,8 @@ void* find(const std::string& dll_lower, const std::string& name) { | |||
| 494 | 494 | ||
| 495 | bool owns_dll(const std::string& dll_lower) { | 495 | bool owns_dll(const std::string& dll_lower) { |
| 496 | static const char* const host[] = {"kernel32.dll", "kernelbase.dll", "msvcrt.dll", "ucrtbase.dll", "ucrtbased.dll", | 496 | static const char* const host[] = {"kernel32.dll", "kernelbase.dll", "msvcrt.dll", "ucrtbase.dll", "ucrtbased.dll", |
| 497 | "vulkan-1.dll", "ntdll.dll", "user32.dll"}; | 497 | "vulkan-1.dll", "ntdll.dll", "user32.dll", "ws2_32.dll", |
| 498 | "wsock32.dll"}; | ||
| 498 | if (starts_with(dll_lower, "api-ms-") || starts_with(dll_lower, "ext-ms-")) return false; | 499 | if (starts_with(dll_lower, "api-ms-") || starts_with(dll_lower, "ext-ms-")) return false; |
| 499 | for (const char* h : host) | 500 | for (const char* h : host) |
| 500 | if (dll_lower == h) return false; | 501 | if (dll_lower == h) return false; |
diff --git a/runtime/shims/ws2_offline.cpp b/runtime/shims/ws2_offline.cpp new file mode 100644 index 000000000..0a278eb99 --- /dev/null +++ b/runtime/shims/ws2_offline.cpp | |||
| @@ -0,0 +1,949 @@ | |||
| 1 | // ws2_offline: Winsock2 (ws2_32.dll and its wsock32.dll alias) for a mapped title, restricted to loopback only. | ||
| 2 | // | ||
| 3 | // Nothing in Leonida goes online. While winhttp_offline.cpp owns winhttp.dll, a title can also import Winsock2 | ||
| 4 | // functions directly (both by name and by standard Windows ws2_32.dll ordinal) or resolve them through | ||
| 5 | // GetProcAddress / WSAIoctl. Bound straight to the host's ws2_32.dll, those calls could open external sockets or | ||
| 6 | // trigger DNS queries. wsock32.dll exports forward to ws2_32 natively, so its bind/connect/sendto/gethostby* entries | ||
| 7 | // go to the same wrappers. | ||
| 8 | // | ||
| 9 | // ws2_32.dll stays host-owned in rt::shims::owns_dll (partial override, like kernel32.dll), so socket bookkeeping | ||
| 10 | // (WSAStartup, socket, closesocket, select, setsockopt, recv, send, byte-order helpers, freeaddrinfo) continues to | ||
| 11 | // run natively on loopback sockets while every outbound, bind, name-resolution, and extension-lookup entry point is | ||
| 12 | // vetted here: | ||
| 13 | // - connect (#4), WSAConnect, WSAConnectByNameA/W, WSAConnectByList, ConnectEx (from WSAIoctl), sendto (#20), | ||
| 14 | // WSASendTo, and WSASendMsg (direct and via WSAIoctl) permit only IPv4 loopback (127.0.0.0/8), IPv6 loopback | ||
| 15 | // (::1), and IPv4-mapped IPv6 loopback (::ffff:127.0.0.0/104). Every other destination fails with WSAENETUNREACH. | ||
| 16 | // WSAConnectByNameA/W pass "localhost" to the host as the literal 127.0.0.1, so the hosts file is never read. | ||
| 17 | // - bind (#2) rewrites wildcard binds (0.0.0.0 or ::) to 127.0.0.1 or ::1 so no external peer can connect in, | ||
| 18 | // allows explicit loopback binds, and refuses any other address with WSAEADDRNOTAVAIL. | ||
| 19 | // - getaddrinfo, GetAddrInfoW, GetAddrInfoExA/W, gethostbyname (#52), gethostbyaddr (#51), and | ||
| 20 | // WSAAsyncGetHostByName/Addr (#103/#102) permit only null/empty nodes, "localhost", and loopback IP literals; | ||
| 21 | // everything else fails with WSAHOST_NOT_FOUND without sending DNS packets. A dotted octet with a leading zero | ||
| 22 | // (0127.0.0.1) is refused: Windows reads it as octal, so it is not the loopback name it looks like. | ||
| 23 | // - WSALookupServiceBeginA/W (name-service queries) always fail with WSASERVICE_NOT_FOUND. | ||
| 24 | // - getnameinfo / GetNameInfoW force NI_NUMERICHOST for non-loopback addresses (or return WSAHOST_NOT_FOUND when | ||
| 25 | // NI_NAMEREQD is set), avoiding reverse DNS lookups. | ||
| 26 | // - WSAIoctl wraps WSAID_CONNECTEX and WSAID_WSASENDMSG and refuses SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER | ||
| 27 | // with WSAEINVAL so extension functions cannot bypass the checks. The wrappers ask the host for the native | ||
| 28 | // pointer of the socket they are called on, since each Winsock provider has its own. | ||
| 29 | // | ||
| 30 | // Every host ws2_32.dll call is resolved dynamically from System32 so gta6rt needs no static ws2_32.lib link | ||
| 31 | // dependency. Each refused destination is logged once ("[rt] ws2: offline, refused <op> <target>") with no payload. | ||
| 32 | #ifndef _WINSOCK_DEPRECATED_NO_WARNINGS | ||
| 33 | #define _WINSOCK_DEPRECATED_NO_WARNINGS | ||
| 34 | #endif | ||
| 35 | #ifndef WIN32_LEAN_AND_MEAN | ||
| 36 | #define WIN32_LEAN_AND_MEAN | ||
| 37 | #endif | ||
| 38 | #ifndef NOMINMAX | ||
| 39 | #define NOMINMAX | ||
| 40 | #endif | ||
| 41 | |||
| 42 | #include <winsock2.h> | ||
| 43 | #include <ws2tcpip.h> | ||
| 44 | #include <mswsock.h> | ||
| 45 | #include <windows.h> | ||
| 46 | |||
| 47 | #include <cstdint> | ||
| 48 | #include <cstdio> | ||
| 49 | #include <cstring> | ||
| 50 | #include <mutex> | ||
| 51 | #include <set> | ||
| 52 | #include <string> | ||
| 53 | |||
| 54 | #include "shims.h" | ||
| 55 | |||
| 56 | #ifndef SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER | ||
| 57 | #define SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER 0xC8000024u | ||
| 58 | #endif | ||
| 59 | |||
| 60 | namespace rt::ws2 { | ||
| 61 | namespace { | ||
| 62 | |||
| 63 | HMODULE host_ws2() { | ||
| 64 | static HMODULE mod = LoadLibraryExW(L"ws2_32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); | ||
| 65 | return mod; | ||
| 66 | } | ||
| 67 | |||
| 68 | template <typename Fn> | ||
| 69 | Fn host_proc(const char* name) { | ||
| 70 | HMODULE mod = host_ws2(); | ||
| 71 | return mod ? reinterpret_cast<Fn>(GetProcAddress(mod, name)) : nullptr; | ||
| 72 | } | ||
| 73 | |||
| 74 | void set_wsa_error(int err) { | ||
| 75 | using SetErrFn = void(WSAAPI*)(int); | ||
| 76 | static SetErrFn fn = host_proc<SetErrFn>("WSASetLastError"); | ||
| 77 | if (fn) { | ||
| 78 | fn(err); | ||
| 79 | } else { | ||
| 80 | SetLastError(static_cast<DWORD>(err)); | ||
| 81 | } | ||
| 82 | } | ||
| 83 | |||
| 84 | uint16_t read_be16(uint16_t net_val) { | ||
| 85 | const auto* b = reinterpret_cast<const uint8_t*>(&net_val); | ||
| 86 | return static_cast<uint16_t>((static_cast<uint16_t>(b[0]) << 8) | b[1]); | ||
| 87 | } | ||
| 88 | |||
| 89 | bool is_ipv4_loopback_bytes(const uint8_t b[4]) { return b[0] == 127; } | ||
| 90 | |||
| 91 | bool is_ipv4_unspecified_bytes(const uint8_t b[4]) { return b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] == 0; } | ||
| 92 | |||
| 93 | bool is_ipv6_loopback_bytes(const uint8_t b[16]) { | ||
| 94 | // ::1 | ||
| 95 | bool exact_loopback = true; | ||
| 96 | for (int i = 0; i < 15; ++i) { | ||
| 97 | if (b[i] != 0) { | ||
| 98 | exact_loopback = false; | ||
| 99 | break; | ||
| 100 | } | ||
| 101 | } | ||
| 102 | if (exact_loopback && b[15] == 1) return true; | ||
| 103 | |||
| 104 | // ::ffff:127.0.0.0/104 (IPv4-mapped loopback) | ||
| 105 | for (int i = 0; i < 10; ++i) { | ||
| 106 | if (b[i] != 0) return false; | ||
| 107 | } | ||
| 108 | return b[10] == 0xff && b[11] == 0xff && b[12] == 127; | ||
| 109 | } | ||
| 110 | |||
| 111 | bool is_ipv6_unspecified_bytes(const uint8_t b[16]) { | ||
| 112 | for (int i = 0; i < 16; ++i) { | ||
| 113 | if (b[i] != 0) return false; | ||
| 114 | } | ||
| 115 | return true; | ||
| 116 | } | ||
| 117 | |||
| 118 | bool is_loopback_sockaddr(const sockaddr* sa, int namelen) { | ||
| 119 | if (!sa || namelen < static_cast<int>(sizeof(ADDRESS_FAMILY))) return false; | ||
| 120 | if (sa->sa_family == AF_INET) { | ||
| 121 | if (namelen < static_cast<int>(sizeof(sockaddr_in))) return false; | ||
| 122 | sockaddr_in v4{}; | ||
| 123 | std::memcpy(&v4, sa, sizeof(v4)); | ||
| 124 | const auto* b = reinterpret_cast<const uint8_t*>(&v4.sin_addr); | ||
| 125 | return is_ipv4_loopback_bytes(b); | ||
| 126 | } | ||
| 127 | if (sa->sa_family == AF_INET6) { | ||
| 128 | if (namelen < static_cast<int>(sizeof(sockaddr_in6))) return false; | ||
| 129 | sockaddr_in6 v6{}; | ||
| 130 | std::memcpy(&v6, sa, sizeof(v6)); | ||
| 131 | const auto* b = reinterpret_cast<const uint8_t*>(&v6.sin6_addr); | ||
| 132 | return is_ipv6_loopback_bytes(b); | ||
| 133 | } | ||
| 134 | return false; | ||
| 135 | } | ||
| 136 | |||
| 137 | std::string format_sockaddr(const sockaddr* sa, int namelen) { | ||
| 138 | if (!sa || namelen < static_cast<int>(sizeof(ADDRESS_FAMILY))) return "<invalid>"; | ||
| 139 | char buf[96] = {}; | ||
| 140 | if (sa->sa_family == AF_INET && namelen >= static_cast<int>(sizeof(sockaddr_in))) { | ||
| 141 | sockaddr_in v4{}; | ||
| 142 | std::memcpy(&v4, sa, sizeof(v4)); | ||
| 143 | const auto* b = reinterpret_cast<const uint8_t*>(&v4.sin_addr); | ||
| 144 | std::snprintf(buf, sizeof(buf), "%u.%u.%u.%u:%u", b[0], b[1], b[2], b[3], | ||
| 145 | static_cast<unsigned>(read_be16(v4.sin_port))); | ||
| 146 | return buf; | ||
| 147 | } | ||
| 148 | if (sa->sa_family == AF_INET6 && namelen >= static_cast<int>(sizeof(sockaddr_in6))) { | ||
| 149 | sockaddr_in6 v6{}; | ||
| 150 | std::memcpy(&v6, sa, sizeof(v6)); | ||
| 151 | const auto* b = reinterpret_cast<const uint8_t*>(&v6.sin6_addr); | ||
| 152 | std::snprintf(buf, sizeof(buf), "[%02x%02x:%02x%02x:...:%02x%02x]:%u", b[0], b[1], b[2], b[3], b[14], b[15], | ||
| 153 | static_cast<unsigned>(read_be16(v6.sin6_port))); | ||
| 154 | return buf; | ||
| 155 | } | ||
| 156 | std::snprintf(buf, sizeof(buf), "family=%u", static_cast<unsigned>(sa->sa_family)); | ||
| 157 | return buf; | ||
| 158 | } | ||
| 159 | |||
| 160 | void log_refused(const char* op, const std::string& target) { | ||
| 161 | // Intentionally immortal: mapped-DLL teardown can run after normal statics are destroyed. | ||
| 162 | static auto* mutex = new std::mutex; | ||
| 163 | static auto* seen = new std::set<std::string>; | ||
| 164 | const std::string key = std::string(op) + " " + target; | ||
| 165 | std::lock_guard lock(*mutex); | ||
| 166 | if (seen->insert(key).second) { | ||
| 167 | std::fprintf(stderr, "[rt] ws2: offline, refused %s %s\n", op, target.c_str()); | ||
| 168 | } | ||
| 169 | } | ||
| 170 | |||
| 171 | bool ascii_iequals(const char* a, const char* b) { | ||
| 172 | if (!a || !b) return false; | ||
| 173 | while (*a && *b) { | ||
| 174 | unsigned char ca = static_cast<unsigned char>(*a++); | ||
| 175 | unsigned char cb = static_cast<unsigned char>(*b++); | ||
| 176 | if (ca >= 'A' && ca <= 'Z') ca = static_cast<unsigned char>(ca + 32); | ||
| 177 | if (cb >= 'A' && cb <= 'Z') cb = static_cast<unsigned char>(cb + 32); | ||
| 178 | if (ca != cb) return false; | ||
| 179 | } | ||
| 180 | return *a == '\0' && *b == '\0'; | ||
| 181 | } | ||
| 182 | |||
| 183 | std::string narrow_ascii(const wchar_t* w) { | ||
| 184 | std::string out; | ||
| 185 | if (!w) return out; | ||
| 186 | for (; *w; ++w) out += (*w < 0x80) ? static_cast<char>(*w) : '?'; | ||
| 187 | return out; | ||
| 188 | } | ||
| 189 | |||
| 190 | bool parse_ipv4_literal(const char* s, uint8_t out[4]) { | ||
| 191 | if (!s || !*s) return false; | ||
| 192 | const char* p = s; | ||
| 193 | for (int part = 0; part < 4; ++part) { | ||
| 194 | if (*p < '0' || *p > '9') return false; | ||
| 195 | const char* start = p; | ||
| 196 | unsigned val = 0; | ||
| 197 | int digits = 0; | ||
| 198 | while (*p >= '0' && *p <= '9') { | ||
| 199 | val = val * 10u + static_cast<unsigned>(*p - '0'); | ||
| 200 | if (val > 255u) return false; | ||
| 201 | ++p; | ||
| 202 | ++digits; | ||
| 203 | } | ||
| 204 | if (digits == 0) return false; | ||
| 205 | if (digits > 1 && *start == '0') return false; // a leading zero is octal to Windows: 0127 is 87, not 127 | ||
| 206 | out[part] = static_cast<uint8_t>(val); | ||
| 207 | if (part < 3) { | ||
| 208 | if (*p != '.') return false; | ||
| 209 | ++p; | ||
| 210 | } | ||
| 211 | } | ||
| 212 | return *p == '\0'; | ||
| 213 | } | ||
| 214 | |||
| 215 | bool is_loopback_node_a(const char* node) { | ||
| 216 | if (!node || !*node) return true; | ||
| 217 | if (ascii_iequals(node, "localhost") || ascii_iequals(node, "localhost.")) return true; | ||
| 218 | |||
| 219 | uint8_t v4[4] = {}; | ||
| 220 | if (parse_ipv4_literal(node, v4)) return is_ipv4_loopback_bytes(v4); | ||
| 221 | |||
| 222 | // Strip optional brackets and IPv6 zone suffix (%...) for literal check via host inet_pton. | ||
| 223 | std::string clean(node); | ||
| 224 | if (clean.size() >= 2 && clean.front() == '[' && clean.back() == ']') { | ||
| 225 | clean = clean.substr(1, clean.size() - 2); | ||
| 226 | } | ||
| 227 | if (const size_t pct = clean.find('%'); pct != std::string::npos) { | ||
| 228 | clean.resize(pct); | ||
| 229 | } | ||
| 230 | |||
| 231 | using InetPtonFn = INT(WSAAPI*)(INT, PCSTR, PVOID); | ||
| 232 | static InetPtonFn pton = host_proc<InetPtonFn>("inet_pton"); | ||
| 233 | if (pton) { | ||
| 234 | uint8_t v6[16] = {}; | ||
| 235 | if (pton(AF_INET6, clean.c_str(), v6) == 1) return is_ipv6_loopback_bytes(v6); | ||
| 236 | } else if (clean == "::1") { | ||
| 237 | return true; | ||
| 238 | } | ||
| 239 | return false; | ||
| 240 | } | ||
| 241 | |||
| 242 | bool is_loopback_node_w(const wchar_t* node) { | ||
| 243 | if (!node || !*node) return true; | ||
| 244 | for (const wchar_t* p = node; *p; ++p) { | ||
| 245 | if (*p >= 0x80) return false; | ||
| 246 | } | ||
| 247 | const std::string ascii = narrow_ascii(node); | ||
| 248 | return is_loopback_node_a(ascii.c_str()); | ||
| 249 | } | ||
| 250 | |||
| 251 | bool is_localhost_name_a(const char* node) { | ||
| 252 | return ascii_iequals(node, "localhost") || ascii_iequals(node, "localhost."); | ||
| 253 | } | ||
| 254 | |||
| 255 | // ---- Socket connect / send / bind shims ---- | ||
| 256 | |||
| 257 | int WSAAPI connect_offline(SOCKET s, const sockaddr* name, int namelen) { | ||
| 258 | if (!is_loopback_sockaddr(name, namelen)) { | ||
| 259 | log_refused("connect", format_sockaddr(name, namelen)); | ||
| 260 | set_wsa_error(WSAENETUNREACH); | ||
| 261 | return SOCKET_ERROR; | ||
| 262 | } | ||
| 263 | using Fn = int(WSAAPI*)(SOCKET, const sockaddr*, int); | ||
| 264 | static Fn real_fn = host_proc<Fn>("connect"); | ||
| 265 | if (!real_fn) { | ||
| 266 | set_wsa_error(WSAENETUNREACH); | ||
| 267 | return SOCKET_ERROR; | ||
| 268 | } | ||
| 269 | return real_fn(s, name, namelen); | ||
| 270 | } | ||
| 271 | |||
| 272 | int WSAAPI wsa_connect_offline(SOCKET s, const sockaddr* name, int namelen, LPWSABUF caller_data, | ||
| 273 | LPWSABUF callee_data, LPQOS sqos, LPQOS gqos) { | ||
| 274 | if (!is_loopback_sockaddr(name, namelen)) { | ||
| 275 | log_refused("WSAConnect", format_sockaddr(name, namelen)); | ||
| 276 | set_wsa_error(WSAENETUNREACH); | ||
| 277 | return SOCKET_ERROR; | ||
| 278 | } | ||
| 279 | using Fn = int(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS); | ||
| 280 | static Fn real_fn = host_proc<Fn>("WSAConnect"); | ||
| 281 | if (!real_fn) { | ||
| 282 | set_wsa_error(WSAENETUNREACH); | ||
| 283 | return SOCKET_ERROR; | ||
| 284 | } | ||
| 285 | return real_fn(s, name, namelen, caller_data, callee_data, sqos, gqos); | ||
| 286 | } | ||
| 287 | |||
| 288 | BOOL WSAAPI wsa_connect_by_name_a_offline(SOCKET s, LPCSTR nodename, LPCSTR servicename, | ||
| 289 | LPDWORD local_addr_len, LPSOCKADDR local_addr, | ||
| 290 | LPDWORD remote_addr_len, LPSOCKADDR remote_addr, | ||
| 291 | const timeval* timeout, LPWSAOVERLAPPED reserved) { | ||
| 292 | if (!nodename || !*nodename || !is_loopback_node_a(nodename)) { | ||
| 293 | log_refused("WSAConnectByNameA", nodename ? nodename : "<null>"); | ||
| 294 | set_wsa_error(WSAENETUNREACH); | ||
| 295 | return FALSE; | ||
| 296 | } | ||
| 297 | using Fn = BOOL(WSAAPI*)(SOCKET, LPCSTR, LPCSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, const timeval*, | ||
| 298 | LPWSAOVERLAPPED); | ||
| 299 | static Fn real_fn = host_proc<Fn>("WSAConnectByNameA"); | ||
| 300 | if (!real_fn) { | ||
| 301 | set_wsa_error(WSAENETUNREACH); | ||
| 302 | return FALSE; | ||
| 303 | } | ||
| 304 | // The host would resolve "localhost" through its hosts file; hand it the literal instead. | ||
| 305 | LPCSTR node = is_localhost_name_a(nodename) ? "127.0.0.1" : nodename; | ||
| 306 | return real_fn(s, node, servicename, local_addr_len, local_addr, remote_addr_len, remote_addr, timeout, reserved); | ||
| 307 | } | ||
| 308 | |||
| 309 | BOOL WSAAPI wsa_connect_by_name_w_offline(SOCKET s, LPWSTR nodename, LPWSTR servicename, | ||
| 310 | LPDWORD local_addr_len, LPSOCKADDR local_addr, | ||
| 311 | LPDWORD remote_addr_len, LPSOCKADDR remote_addr, | ||
| 312 | const timeval* timeout, LPWSAOVERLAPPED reserved) { | ||
| 313 | if (!nodename || !*nodename || !is_loopback_node_w(nodename)) { | ||
| 314 | log_refused("WSAConnectByNameW", nodename ? narrow_ascii(nodename) : "<null>"); | ||
| 315 | set_wsa_error(WSAENETUNREACH); | ||
| 316 | return FALSE; | ||
| 317 | } | ||
| 318 | using Fn = BOOL(WSAAPI*)(SOCKET, LPWSTR, LPWSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, const timeval*, | ||
| 319 | LPWSAOVERLAPPED); | ||
| 320 | static Fn real_fn = host_proc<Fn>("WSAConnectByNameW"); | ||
| 321 | if (!real_fn) { | ||
| 322 | set_wsa_error(WSAENETUNREACH); | ||
| 323 | return FALSE; | ||
| 324 | } | ||
| 325 | // The host would resolve "localhost" through its hosts file; hand it the literal instead. | ||
| 326 | wchar_t loopback[] = L"127.0.0.1"; | ||
| 327 | LPWSTR node = is_localhost_name_a(narrow_ascii(nodename).c_str()) ? loopback : nodename; | ||
| 328 | return real_fn(s, node, servicename, local_addr_len, local_addr, remote_addr_len, remote_addr, timeout, reserved); | ||
| 329 | } | ||
| 330 | |||
| 331 | BOOL WSAAPI wsa_connect_by_list_offline(SOCKET s, PSOCKET_ADDRESS_LIST addr_list, LPDWORD local_addr_len, | ||
| 332 | LPSOCKADDR local_addr, LPDWORD remote_addr_len, LPSOCKADDR remote_addr, | ||
| 333 | const timeval* timeout, LPWSAOVERLAPPED reserved) { | ||
| 334 | if (!addr_list || addr_list->iAddressCount <= 0) { | ||
| 335 | set_wsa_error(WSAEINVAL); | ||
| 336 | return FALSE; | ||
| 337 | } | ||
| 338 | for (INT i = 0; i < addr_list->iAddressCount; ++i) { | ||
| 339 | const SOCKET_ADDRESS& entry = addr_list->Address[i]; | ||
| 340 | if (!is_loopback_sockaddr(entry.lpSockaddr, entry.iSockaddrLength)) { | ||
| 341 | log_refused("WSAConnectByList", format_sockaddr(entry.lpSockaddr, entry.iSockaddrLength)); | ||
| 342 | set_wsa_error(WSAENETUNREACH); | ||
| 343 | return FALSE; | ||
| 344 | } | ||
| 345 | } | ||
| 346 | using Fn = BOOL(WSAAPI*)(SOCKET, PSOCKET_ADDRESS_LIST, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, const timeval*, | ||
| 347 | LPWSAOVERLAPPED); | ||
| 348 | static Fn real_fn = host_proc<Fn>("WSAConnectByList"); | ||
| 349 | if (!real_fn) { | ||
| 350 | set_wsa_error(WSAENETUNREACH); | ||
| 351 | return FALSE; | ||
| 352 | } | ||
| 353 | return real_fn(s, addr_list, local_addr_len, local_addr, remote_addr_len, remote_addr, timeout, reserved); | ||
| 354 | } | ||
| 355 | |||
| 356 | // sendto, WSASendTo, WSASendMsg and WSAJoinLeaf bind an unbound socket to the wildcard address (Microsoft's remarks | ||
| 357 | // for sendto and WSAJoinLeaf: getsockname then reports 0.0.0.0 or ::), so its port would also take datagrams from other | ||
| 358 | // hosts. Bind such a socket to the loopback address of the (already checked) loopback destination's family first. | ||
| 359 | // Returns false, with WSAEADDRNOTAVAIL set, only if the socket is still unbound afterwards. | ||
| 360 | bool bind_loopback_if_unbound(SOCKET s, const sockaddr* dest) { | ||
| 361 | using NameFn = int(WSAAPI*)(SOCKET, sockaddr*, int*); | ||
| 362 | using BindFn = int(WSAAPI*)(SOCKET, const sockaddr*, int); | ||
| 363 | using LastErrFn = int(WSAAPI*)(); | ||
| 364 | static NameFn real_getsockname = host_proc<NameFn>("getsockname"); | ||
| 365 | static BindFn real_bind = host_proc<BindFn>("bind"); | ||
| 366 | static LastErrFn real_last_error = host_proc<LastErrFn>("WSAGetLastError"); | ||
| 367 | if (!real_getsockname || !real_bind || !real_last_error) { | ||
| 368 | set_wsa_error(WSAEADDRNOTAVAIL); | ||
| 369 | return false; | ||
| 370 | } | ||
| 371 | // Unbound is WSAEINVAL; any other getsockname error (not a socket, ...) is left for the real call to report. | ||
| 372 | const auto unbound = [&] { | ||
| 373 | sockaddr_storage local{}; | ||
| 374 | int local_len = sizeof(local); | ||
| 375 | return real_getsockname(s, reinterpret_cast<sockaddr*>(&local), &local_len) == SOCKET_ERROR && | ||
| 376 | real_last_error() == WSAEINVAL; | ||
| 377 | }; | ||
| 378 | if (!unbound()) return true; | ||
| 379 | |||
| 380 | sockaddr_storage local{}; | ||
| 381 | int local_len = 0; | ||
| 382 | if (dest->sa_family == AF_INET) { | ||
| 383 | auto* v4 = reinterpret_cast<sockaddr_in*>(&local); | ||
| 384 | v4->sin_family = AF_INET; | ||
| 385 | auto* b = reinterpret_cast<uint8_t*>(&v4->sin_addr); | ||
| 386 | b[0] = 127; | ||
| 387 | b[3] = 1; | ||
| 388 | local_len = sizeof(sockaddr_in); | ||
| 389 | } else { | ||
| 390 | sockaddr_in6 to6{}; | ||
| 391 | std::memcpy(&to6, dest, sizeof(to6)); | ||
| 392 | const auto* d = reinterpret_cast<const uint8_t*>(&to6.sin6_addr); | ||
| 393 | auto* v6 = reinterpret_cast<sockaddr_in6*>(&local); | ||
| 394 | v6->sin6_family = AF_INET6; | ||
| 395 | auto* b = reinterpret_cast<uint8_t*>(&v6->sin6_addr); | ||
| 396 | if (d[10] == 0xff && d[11] == 0xff) { // IPv4-mapped loopback destination: ::ffff:127.0.0.1 | ||
| 397 | b[10] = 0xff; | ||
| 398 | b[11] = 0xff; | ||
| 399 | b[12] = 127; | ||
| 400 | b[15] = 1; | ||
| 401 | } else { // ::1 | ||
| 402 | b[15] = 1; | ||
| 403 | } | ||
| 404 | local_len = sizeof(sockaddr_in6); | ||
| 405 | } | ||
| 406 | // A concurrent send on the same socket may have bound it between the two checks; that bind came through here too. | ||
| 407 | if (real_bind(s, reinterpret_cast<const sockaddr*>(&local), local_len) == 0 || !unbound()) return true; | ||
| 408 | log_refused("implicit wildcard bind", format_sockaddr(reinterpret_cast<const sockaddr*>(&local), local_len)); | ||
| 409 | set_wsa_error(WSAEADDRNOTAVAIL); | ||
| 410 | return false; | ||
| 411 | } | ||
| 412 | |||
| 413 | int WSAAPI sendto_offline(SOCKET s, const char* buf, int len, int flags, const sockaddr* to, int tolen) { | ||
| 414 | if (to && tolen > 0 && !is_loopback_sockaddr(to, tolen)) { | ||
| 415 | log_refused("sendto", format_sockaddr(to, tolen)); | ||
| 416 | set_wsa_error(WSAENETUNREACH); | ||
| 417 | return SOCKET_ERROR; | ||
| 418 | } | ||
| 419 | if (to && tolen > 0 && !bind_loopback_if_unbound(s, to)) return SOCKET_ERROR; | ||
| 420 | using Fn = int(WSAAPI*)(SOCKET, const char*, int, int, const sockaddr*, int); | ||
| 421 | static Fn real_fn = host_proc<Fn>("sendto"); | ||
| 422 | if (!real_fn) { | ||
| 423 | set_wsa_error(WSAENETUNREACH); | ||
| 424 | return SOCKET_ERROR; | ||
| 425 | } | ||
| 426 | return real_fn(s, buf, len, flags, to, tolen); | ||
| 427 | } | ||
| 428 | |||
| 429 | int WSAAPI wsa_send_to_offline(SOCKET s, LPWSABUF buffers, DWORD buffer_count, LPDWORD bytes_sent, DWORD flags, | ||
| 430 | const sockaddr* to, int tolen, LPWSAOVERLAPPED overlapped, | ||
| 431 | LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) { | ||
| 432 | if (to && tolen > 0 && !is_loopback_sockaddr(to, tolen)) { | ||
| 433 | log_refused("WSASendTo", format_sockaddr(to, tolen)); | ||
| 434 | set_wsa_error(WSAENETUNREACH); | ||
| 435 | return SOCKET_ERROR; | ||
| 436 | } | ||
| 437 | if (to && tolen > 0 && !bind_loopback_if_unbound(s, to)) return SOCKET_ERROR; | ||
| 438 | using Fn = int(WSAAPI*)(SOCKET, LPWSABUF, DWORD, LPDWORD, DWORD, const sockaddr*, int, LPWSAOVERLAPPED, | ||
| 439 | LPWSAOVERLAPPED_COMPLETION_ROUTINE); | ||
| 440 | static Fn real_fn = host_proc<Fn>("WSASendTo"); | ||
| 441 | if (!real_fn) { | ||
| 442 | set_wsa_error(WSAENETUNREACH); | ||
| 443 | return SOCKET_ERROR; | ||
| 444 | } | ||
| 445 | return real_fn(s, buffers, buffer_count, bytes_sent, flags, to, tolen, overlapped, completion); | ||
| 446 | } | ||
| 447 | |||
| 448 | int WSAAPI wsa_send_msg_offline(SOCKET s, LPWSAMSG msg, DWORD flags, LPDWORD bytes_sent, | ||
| 449 | LPWSAOVERLAPPED overlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) { | ||
| 450 | if (msg && msg->name && msg->namelen > 0 && !is_loopback_sockaddr(msg->name, msg->namelen)) { | ||
| 451 | log_refused("WSASendMsg", format_sockaddr(msg->name, msg->namelen)); | ||
| 452 | set_wsa_error(WSAENETUNREACH); | ||
| 453 | return SOCKET_ERROR; | ||
| 454 | } | ||
| 455 | if (msg && msg->name && msg->namelen > 0 && !bind_loopback_if_unbound(s, msg->name)) return SOCKET_ERROR; | ||
| 456 | using Fn = int(WSAAPI*)(SOCKET, LPWSAMSG, DWORD, LPDWORD, LPWSAOVERLAPPED, LPWSAOVERLAPPED_COMPLETION_ROUTINE); | ||
| 457 | static Fn real_fn = host_proc<Fn>("WSASendMsg"); | ||
| 458 | if (!real_fn) { | ||
| 459 | set_wsa_error(WSAENETUNREACH); | ||
| 460 | return SOCKET_ERROR; | ||
| 461 | } | ||
| 462 | return real_fn(s, msg, flags, bytes_sent, overlapped, completion); | ||
| 463 | } | ||
| 464 | |||
| 465 | int WSAAPI bind_offline(SOCKET s, const sockaddr* name, int namelen) { | ||
| 466 | if (!name || namelen < static_cast<int>(sizeof(ADDRESS_FAMILY))) { | ||
| 467 | set_wsa_error(WSAEINVAL); | ||
| 468 | return SOCKET_ERROR; | ||
| 469 | } | ||
| 470 | using Fn = int(WSAAPI*)(SOCKET, const sockaddr*, int); | ||
| 471 | static Fn real_fn = host_proc<Fn>("bind"); | ||
| 472 | if (!real_fn) { | ||
| 473 | set_wsa_error(WSAEADDRNOTAVAIL); | ||
| 474 | return SOCKET_ERROR; | ||
| 475 | } | ||
| 476 | |||
| 477 | if (name->sa_family == AF_INET && namelen >= static_cast<int>(sizeof(sockaddr_in))) { | ||
| 478 | sockaddr_in v4{}; | ||
| 479 | std::memcpy(&v4, name, sizeof(v4)); | ||
| 480 | auto* b = reinterpret_cast<uint8_t*>(&v4.sin_addr); | ||
| 481 | if (is_ipv4_unspecified_bytes(b)) { | ||
| 482 | b[0] = 127; | ||
| 483 | b[1] = 0; | ||
| 484 | b[2] = 0; | ||
| 485 | b[3] = 1; | ||
| 486 | return real_fn(s, reinterpret_cast<const sockaddr*>(&v4), sizeof(v4)); | ||
| 487 | } | ||
| 488 | if (is_ipv4_loopback_bytes(b)) { | ||
| 489 | return real_fn(s, name, namelen); | ||
| 490 | } | ||
| 491 | } else if (name->sa_family == AF_INET6 && namelen >= static_cast<int>(sizeof(sockaddr_in6))) { | ||
| 492 | sockaddr_in6 v6{}; | ||
| 493 | std::memcpy(&v6, name, sizeof(v6)); | ||
| 494 | auto* b = reinterpret_cast<uint8_t*>(&v6.sin6_addr); | ||
| 495 | if (is_ipv6_unspecified_bytes(b)) { | ||
| 496 | b[15] = 1; | ||
| 497 | return real_fn(s, reinterpret_cast<const sockaddr*>(&v6), sizeof(v6)); | ||
| 498 | } | ||
| 499 | if (is_ipv6_loopback_bytes(b)) { | ||
| 500 | return real_fn(s, name, namelen); | ||
| 501 | } | ||
| 502 | } | ||
| 503 | |||
| 504 | log_refused("bind", format_sockaddr(name, namelen)); | ||
| 505 | set_wsa_error(WSAEADDRNOTAVAIL); | ||
| 506 | return SOCKET_ERROR; | ||
| 507 | } | ||
| 508 | |||
| 509 | // ---- Multicast ---- | ||
| 510 | |||
| 511 | // A multicast group join makes the host announce membership on a real interface and receive the group's traffic | ||
| 512 | // from other hosts, so every join is refused. Leaving a group and the other options pass through. | ||
| 513 | bool is_multicast_join(int level, int optname) { | ||
| 514 | if (level == IPPROTO_IP) { | ||
| 515 | return optname == IP_ADD_MEMBERSHIP || optname == IP_ADD_SOURCE_MEMBERSHIP || optname == MCAST_JOIN_GROUP || | ||
| 516 | optname == MCAST_JOIN_SOURCE_GROUP; | ||
| 517 | } | ||
| 518 | if (level == IPPROTO_IPV6) { | ||
| 519 | return optname == IPV6_ADD_MEMBERSHIP || optname == MCAST_JOIN_GROUP || optname == MCAST_JOIN_SOURCE_GROUP; | ||
| 520 | } | ||
| 521 | return false; | ||
| 522 | } | ||
| 523 | |||
| 524 | int refuse_multicast_join(const char* op, int level, int optname) { | ||
| 525 | log_refused(op, "multicast join (level " + std::to_string(level) + ", option " + std::to_string(optname) + ")"); | ||
| 526 | set_wsa_error(WSAEADDRNOTAVAIL); | ||
| 527 | return SOCKET_ERROR; | ||
| 528 | } | ||
| 529 | |||
| 530 | int WSAAPI setsockopt_offline(SOCKET s, int level, int optname, const char* optval, int optlen) { | ||
| 531 | if (is_multicast_join(level, optname)) return refuse_multicast_join("setsockopt", level, optname); | ||
| 532 | using Fn = int(WSAAPI*)(SOCKET, int, int, const char*, int); | ||
| 533 | static Fn real_fn = host_proc<Fn>("setsockopt"); | ||
| 534 | if (!real_fn) { | ||
| 535 | set_wsa_error(WSAENETDOWN); | ||
| 536 | return SOCKET_ERROR; | ||
| 537 | } | ||
| 538 | return real_fn(s, level, optname, optval, optlen); | ||
| 539 | } | ||
| 540 | |||
| 541 | // wsock32.dll's setsockopt is its own export, not a forwarder: it takes the Winsock 1.1 IPPROTO_IP numbers, maps | ||
| 542 | // 5 (winsock.h IP_ADD_MEMBERSHIP) to the Winsock 2 value and passes numbers it does not know through unchanged (Wine's | ||
| 543 | // dlls/wsock32/socket.c remaps the same table). Refuse both spellings of a join, then let the host wsock32 remap. | ||
| 544 | int WSAAPI wsock32_setsockopt_offline(SOCKET s, int level, int optname, const char* optval, int optlen) { | ||
| 545 | constexpr int kWinsock1AddMembership = 5; | ||
| 546 | if (is_multicast_join(level, optname) || (level == IPPROTO_IP && optname == kWinsock1AddMembership)) { | ||
| 547 | return refuse_multicast_join("wsock32 setsockopt", level, optname); | ||
| 548 | } | ||
| 549 | using Fn = int(WSAAPI*)(SOCKET, int, int, const char*, int); | ||
| 550 | static HMODULE host_wsock32 = LoadLibraryExW(L"wsock32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); | ||
| 551 | static Fn real_fn = host_wsock32 ? reinterpret_cast<Fn>(GetProcAddress(host_wsock32, "setsockopt")) : nullptr; | ||
| 552 | if (!real_fn) { | ||
| 553 | set_wsa_error(WSAENETDOWN); | ||
| 554 | return SOCKET_ERROR; | ||
| 555 | } | ||
| 556 | return real_fn(s, level, optname, optval, optlen); | ||
| 557 | } | ||
| 558 | |||
| 559 | // WSAJoinLeaf joins a multipoint session; a group address is never loopback, so in practice every join is refused. | ||
| 560 | SOCKET WSAAPI wsa_join_leaf_offline(SOCKET s, const sockaddr* name, int namelen, LPWSABUF caller_data, | ||
| 561 | LPWSABUF callee_data, LPQOS sqos, LPQOS gqos, DWORD flags) { | ||
| 562 | if (!is_loopback_sockaddr(name, namelen)) { | ||
| 563 | log_refused("WSAJoinLeaf", format_sockaddr(name, namelen)); | ||
| 564 | set_wsa_error(WSAENETUNREACH); | ||
| 565 | return INVALID_SOCKET; | ||
| 566 | } | ||
| 567 | if (!bind_loopback_if_unbound(s, name)) return INVALID_SOCKET; | ||
| 568 | using Fn = SOCKET(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS, DWORD); | ||
| 569 | static Fn real_fn = host_proc<Fn>("WSAJoinLeaf"); | ||
| 570 | if (!real_fn) { | ||
| 571 | set_wsa_error(WSAENETUNREACH); | ||
| 572 | return INVALID_SOCKET; | ||
| 573 | } | ||
| 574 | return real_fn(s, name, namelen, caller_data, callee_data, sqos, gqos, flags); | ||
| 575 | } | ||
| 576 | |||
| 577 | // ---- Name resolution shims ---- | ||
| 578 | |||
| 579 | INT WSAAPI getaddrinfo_offline(PCSTR node, PCSTR service, const ADDRINFOA* hints, PADDRINFOA* result) { | ||
| 580 | if (result) *result = nullptr; | ||
| 581 | if (!is_loopback_node_a(node)) { | ||
| 582 | log_refused("getaddrinfo", node ? node : "<null>"); | ||
| 583 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 584 | return WSAHOST_NOT_FOUND; | ||
| 585 | } | ||
| 586 | using Fn = INT(WSAAPI*)(PCSTR, PCSTR, const ADDRINFOA*, PADDRINFOA*); | ||
| 587 | static Fn real_fn = host_proc<Fn>("getaddrinfo"); | ||
| 588 | if (!real_fn) { | ||
| 589 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 590 | return WSAHOST_NOT_FOUND; | ||
| 591 | } | ||
| 592 | return real_fn(node, service, hints, result); | ||
| 593 | } | ||
| 594 | |||
| 595 | INT WSAAPI get_addr_info_w_offline(PCWSTR node, PCWSTR service, const ADDRINFOW* hints, PADDRINFOW* result) { | ||
| 596 | if (result) *result = nullptr; | ||
| 597 | if (!is_loopback_node_w(node)) { | ||
| 598 | log_refused("GetAddrInfoW", node ? narrow_ascii(node) : "<null>"); | ||
| 599 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 600 | return WSAHOST_NOT_FOUND; | ||
| 601 | } | ||
| 602 | using Fn = INT(WSAAPI*)(PCWSTR, PCWSTR, const ADDRINFOW*, PADDRINFOW*); | ||
| 603 | static Fn real_fn = host_proc<Fn>("GetAddrInfoW"); | ||
| 604 | if (!real_fn) { | ||
| 605 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 606 | return WSAHOST_NOT_FOUND; | ||
| 607 | } | ||
| 608 | return real_fn(node, service, hints, result); | ||
| 609 | } | ||
| 610 | |||
| 611 | INT WSAAPI get_addr_info_ex_a_offline(PCSTR name, PCSTR service, DWORD ns, LPGUID nsp_id, const ADDRINFOEXA* hints, | ||
| 612 | PADDRINFOEXA* result, timeval* timeout, LPOVERLAPPED overlapped, | ||
| 613 | LPLOOKUPSERVICE_COMPLETION_ROUTINE completion, LPHANDLE cancel_handle) { | ||
| 614 | if (result) *result = nullptr; | ||
| 615 | if (cancel_handle) *cancel_handle = nullptr; | ||
| 616 | if (!is_loopback_node_a(name)) { | ||
| 617 | log_refused("GetAddrInfoExA", name ? name : "<null>"); | ||
| 618 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 619 | return WSAHOST_NOT_FOUND; | ||
| 620 | } | ||
| 621 | using Fn = INT(WSAAPI*)(PCSTR, PCSTR, DWORD, LPGUID, const ADDRINFOEXA*, PADDRINFOEXA*, timeval*, LPOVERLAPPED, | ||
| 622 | LPLOOKUPSERVICE_COMPLETION_ROUTINE, LPHANDLE); | ||
| 623 | static Fn real_fn = host_proc<Fn>("GetAddrInfoExA"); | ||
| 624 | if (!real_fn) { | ||
| 625 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 626 | return WSAHOST_NOT_FOUND; | ||
| 627 | } | ||
| 628 | return real_fn(name, service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle); | ||
| 629 | } | ||
| 630 | |||
| 631 | INT WSAAPI get_addr_info_ex_w_offline(PCWSTR name, PCWSTR service, DWORD ns, LPGUID nsp_id, const ADDRINFOEXW* hints, | ||
| 632 | PADDRINFOEXW* result, timeval* timeout, LPOVERLAPPED overlapped, | ||
| 633 | LPLOOKUPSERVICE_COMPLETION_ROUTINE completion, LPHANDLE cancel_handle) { | ||
| 634 | if (result) *result = nullptr; | ||
| 635 | if (cancel_handle) *cancel_handle = nullptr; | ||
| 636 | if (!is_loopback_node_w(name)) { | ||
| 637 | log_refused("GetAddrInfoExW", name ? narrow_ascii(name) : "<null>"); | ||
| 638 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 639 | return WSAHOST_NOT_FOUND; | ||
| 640 | } | ||
| 641 | using Fn = INT(WSAAPI*)(PCWSTR, PCWSTR, DWORD, LPGUID, const ADDRINFOEXW*, PADDRINFOEXW*, timeval*, LPOVERLAPPED, | ||
| 642 | LPLOOKUPSERVICE_COMPLETION_ROUTINE, LPHANDLE); | ||
| 643 | static Fn real_fn = host_proc<Fn>("GetAddrInfoExW"); | ||
| 644 | if (!real_fn) { | ||
| 645 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 646 | return WSAHOST_NOT_FOUND; | ||
| 647 | } | ||
| 648 | return real_fn(name, service, ns, nsp_id, hints, result, timeout, overlapped, completion, cancel_handle); | ||
| 649 | } | ||
| 650 | |||
| 651 | hostent* WSAAPI gethostbyname_offline(const char* name) { | ||
| 652 | if (!is_loopback_node_a(name)) { | ||
| 653 | log_refused("gethostbyname", name ? name : "<null>"); | ||
| 654 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 655 | return nullptr; | ||
| 656 | } | ||
| 657 | using Fn = hostent*(WSAAPI*)(const char*); | ||
| 658 | static Fn real_fn = host_proc<Fn>("gethostbyname"); | ||
| 659 | if (!real_fn) { | ||
| 660 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 661 | return nullptr; | ||
| 662 | } | ||
| 663 | return real_fn(name); | ||
| 664 | } | ||
| 665 | |||
| 666 | bool is_loopback_raw_addr(const char* addr, int len, int type) { | ||
| 667 | if (!addr) return false; | ||
| 668 | if (type == AF_INET && len == 4) { | ||
| 669 | return is_ipv4_loopback_bytes(reinterpret_cast<const uint8_t*>(addr)); | ||
| 670 | } | ||
| 671 | if (type == AF_INET6 && len == 16) { | ||
| 672 | return is_ipv6_loopback_bytes(reinterpret_cast<const uint8_t*>(addr)); | ||
| 673 | } | ||
| 674 | return false; | ||
| 675 | } | ||
| 676 | |||
| 677 | hostent* WSAAPI gethostbyaddr_offline(const char* addr, int len, int type) { | ||
| 678 | if (!is_loopback_raw_addr(addr, len, type)) { | ||
| 679 | log_refused("gethostbyaddr", "non-loopback"); | ||
| 680 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 681 | return nullptr; | ||
| 682 | } | ||
| 683 | using Fn = hostent*(WSAAPI*)(const char*, int, int); | ||
| 684 | static Fn real_fn = host_proc<Fn>("gethostbyaddr"); | ||
| 685 | if (!real_fn) { | ||
| 686 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 687 | return nullptr; | ||
| 688 | } | ||
| 689 | return real_fn(addr, len, type); | ||
| 690 | } | ||
| 691 | |||
| 692 | HANDLE WSAAPI wsa_async_get_host_by_name_offline(HWND hWnd, u_int wMsg, const char* name, char* buf, int buflen) { | ||
| 693 | if (!is_loopback_node_a(name)) { | ||
| 694 | log_refused("WSAAsyncGetHostByName", name ? name : "<null>"); | ||
| 695 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 696 | return nullptr; | ||
| 697 | } | ||
| 698 | using Fn = HANDLE(WSAAPI*)(HWND, u_int, const char*, char*, int); | ||
| 699 | static Fn real_fn = host_proc<Fn>("WSAAsyncGetHostByName"); | ||
| 700 | if (!real_fn) { | ||
| 701 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 702 | return nullptr; | ||
| 703 | } | ||
| 704 | return real_fn(hWnd, wMsg, name, buf, buflen); | ||
| 705 | } | ||
| 706 | |||
| 707 | HANDLE WSAAPI wsa_async_get_host_by_addr_offline(HWND hWnd, u_int wMsg, const char* addr, int len, int type, | ||
| 708 | char* buf, int buflen) { | ||
| 709 | if (!is_loopback_raw_addr(addr, len, type)) { | ||
| 710 | log_refused("WSAAsyncGetHostByAddr", "non-loopback"); | ||
| 711 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 712 | return nullptr; | ||
| 713 | } | ||
| 714 | using Fn = HANDLE(WSAAPI*)(HWND, u_int, const char*, int, int, char*, int); | ||
| 715 | static Fn real_fn = host_proc<Fn>("WSAAsyncGetHostByAddr"); | ||
| 716 | if (!real_fn) { | ||
| 717 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 718 | return nullptr; | ||
| 719 | } | ||
| 720 | return real_fn(hWnd, wMsg, addr, len, type, buf, buflen); | ||
| 721 | } | ||
| 722 | |||
| 723 | INT WSAAPI getnameinfo_offline(const sockaddr* sa, socklen_t salen, PCHAR host, DWORD host_size, PCHAR serv, | ||
| 724 | DWORD serv_size, INT flags) { | ||
| 725 | if (!is_loopback_sockaddr(sa, static_cast<int>(salen))) { | ||
| 726 | if ((flags & NI_NAMEREQD) != 0) { | ||
| 727 | log_refused("getnameinfo", format_sockaddr(sa, static_cast<int>(salen))); | ||
| 728 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 729 | return WSAHOST_NOT_FOUND; | ||
| 730 | } | ||
| 731 | flags |= NI_NUMERICHOST; | ||
| 732 | } | ||
| 733 | using Fn = INT(WSAAPI*)(const sockaddr*, socklen_t, PCHAR, DWORD, PCHAR, DWORD, INT); | ||
| 734 | static Fn real_fn = host_proc<Fn>("getnameinfo"); | ||
| 735 | if (!real_fn) { | ||
| 736 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 737 | return WSAHOST_NOT_FOUND; | ||
| 738 | } | ||
| 739 | return real_fn(sa, salen, host, host_size, serv, serv_size, flags); | ||
| 740 | } | ||
| 741 | |||
| 742 | INT WSAAPI get_name_info_w_offline(const sockaddr* sa, socklen_t salen, PWCHAR host, DWORD host_size, PWCHAR serv, | ||
| 743 | DWORD serv_size, INT flags) { | ||
| 744 | if (!is_loopback_sockaddr(sa, static_cast<int>(salen))) { | ||
| 745 | if ((flags & NI_NAMEREQD) != 0) { | ||
| 746 | log_refused("GetNameInfoW", format_sockaddr(sa, static_cast<int>(salen))); | ||
| 747 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 748 | return WSAHOST_NOT_FOUND; | ||
| 749 | } | ||
| 750 | flags |= NI_NUMERICHOST; | ||
| 751 | } | ||
| 752 | using Fn = INT(WSAAPI*)(const sockaddr*, socklen_t, PWCHAR, DWORD, PWCHAR, DWORD, INT); | ||
| 753 | static Fn real_fn = host_proc<Fn>("GetNameInfoW"); | ||
| 754 | if (!real_fn) { | ||
| 755 | set_wsa_error(WSAHOST_NOT_FOUND); | ||
| 756 | return WSAHOST_NOT_FOUND; | ||
| 757 | } | ||
| 758 | return real_fn(sa, salen, host, host_size, serv, serv_size, flags); | ||
| 759 | } | ||
| 760 | |||
| 761 | // ---- Name-service queries (WSALookupServiceBegin) ---- | ||
| 762 | |||
| 763 | // Name-service (SAP/RNR) queries would reach the host's providers, so every begin call is refused. | ||
| 764 | int WSAAPI wsa_lookup_service_begin_a_offline(LPWSAQUERYSETA restrictions, DWORD, LPHANDLE lookup) { | ||
| 765 | if (lookup) *lookup = nullptr; | ||
| 766 | const bool named = restrictions && restrictions->lpszServiceInstanceName; | ||
| 767 | log_refused("WSALookupServiceBeginA", named ? restrictions->lpszServiceInstanceName : "<null>"); | ||
| 768 | set_wsa_error(WSASERVICE_NOT_FOUND); | ||
| 769 | return SOCKET_ERROR; | ||
| 770 | } | ||
| 771 | |||
| 772 | int WSAAPI wsa_lookup_service_begin_w_offline(LPWSAQUERYSETW restrictions, DWORD, LPHANDLE lookup) { | ||
| 773 | if (lookup) *lookup = nullptr; | ||
| 774 | const bool named = restrictions && restrictions->lpszServiceInstanceName; | ||
| 775 | log_refused("WSALookupServiceBeginW", named ? narrow_ascii(restrictions->lpszServiceInstanceName) : "<null>"); | ||
| 776 | set_wsa_error(WSASERVICE_NOT_FOUND); | ||
| 777 | return SOCKET_ERROR; | ||
| 778 | } | ||
| 779 | |||
| 780 | // ---- WSAIoctl extension-function interception (ConnectEx / WSASendMsg) ---- | ||
| 781 | |||
| 782 | // The provider's own extension function for `s`. Asked per socket: each Winsock provider has its own pointers. | ||
| 783 | template <typename Fn> | ||
| 784 | Fn host_extension(SOCKET s, const GUID& guid) { | ||
| 785 | using IoctlFn = int(WSAAPI*)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED, | ||
| 786 | LPWSAOVERLAPPED_COMPLETION_ROUTINE); | ||
| 787 | static IoctlFn ioctl = host_proc<IoctlFn>("WSAIoctl"); | ||
| 788 | if (!ioctl) return nullptr; | ||
| 789 | GUID requested = guid; | ||
| 790 | Fn fn = nullptr; | ||
| 791 | DWORD returned = 0; | ||
| 792 | if (ioctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &requested, sizeof(requested), &fn, sizeof(fn), &returned, nullptr, | ||
| 793 | nullptr) != 0) | ||
| 794 | return nullptr; | ||
| 795 | return fn; | ||
| 796 | } | ||
| 797 | |||
| 798 | BOOL PASCAL connect_ex_offline(SOCKET s, const sockaddr* name, int namelen, PVOID send_buf, DWORD send_len, | ||
| 799 | LPDWORD bytes_sent, LPOVERLAPPED overlapped) { | ||
| 800 | if (!is_loopback_sockaddr(name, namelen)) { | ||
| 801 | log_refused("ConnectEx", format_sockaddr(name, namelen)); | ||
| 802 | set_wsa_error(WSAENETUNREACH); | ||
| 803 | return FALSE; | ||
| 804 | } | ||
| 805 | static constexpr GUID kConnectExGuid = WSAID_CONNECTEX; | ||
| 806 | LPFN_CONNECTEX real_fn = host_extension<LPFN_CONNECTEX>(s, kConnectExGuid); | ||
| 807 | if (!real_fn) { | ||
| 808 | set_wsa_error(WSAENETUNREACH); | ||
| 809 | return FALSE; | ||
| 810 | } | ||
| 811 | return real_fn(s, name, namelen, send_buf, send_len, bytes_sent, overlapped); | ||
| 812 | } | ||
| 813 | |||
| 814 | int PASCAL wsa_send_msg_ext_offline(SOCKET s, LPWSAMSG msg, DWORD flags, LPDWORD bytes_sent, | ||
| 815 | LPWSAOVERLAPPED overlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) { | ||
| 816 | if (msg && msg->name && msg->namelen > 0 && !is_loopback_sockaddr(msg->name, msg->namelen)) { | ||
| 817 | log_refused("WSASendMsg(ext)", format_sockaddr(msg->name, msg->namelen)); | ||
| 818 | set_wsa_error(WSAENETUNREACH); | ||
| 819 | return SOCKET_ERROR; | ||
| 820 | } | ||
| 821 | if (msg && msg->name && msg->namelen > 0 && !bind_loopback_if_unbound(s, msg->name)) return SOCKET_ERROR; | ||
| 822 | static constexpr GUID kSendMsgGuid = WSAID_WSASENDMSG; | ||
| 823 | LPFN_WSASENDMSG real_fn = host_extension<LPFN_WSASENDMSG>(s, kSendMsgGuid); | ||
| 824 | if (!real_fn) { | ||
| 825 | set_wsa_error(WSAENETUNREACH); | ||
| 826 | return SOCKET_ERROR; | ||
| 827 | } | ||
| 828 | return real_fn(s, msg, flags, bytes_sent, overlapped, completion); | ||
| 829 | } | ||
| 830 | |||
| 831 | int WSAAPI wsa_ioctl_offline(SOCKET s, DWORD io_control_code, LPVOID in_buf, DWORD in_len, LPVOID out_buf, | ||
| 832 | DWORD out_len, LPDWORD bytes_returned, LPWSAOVERLAPPED overlapped, | ||
| 833 | LPWSAOVERLAPPED_COMPLETION_ROUTINE completion) { | ||
| 834 | using Fn = int(WSAAPI*)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED, | ||
| 835 | LPWSAOVERLAPPED_COMPLETION_ROUTINE); | ||
| 836 | static Fn real_fn = host_proc<Fn>("WSAIoctl"); | ||
| 837 | if (!real_fn) { | ||
| 838 | set_wsa_error(WSAEINVAL); | ||
| 839 | return SOCKET_ERROR; | ||
| 840 | } | ||
| 841 | |||
| 842 | if (io_control_code == SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER) { | ||
| 843 | set_wsa_error(WSAEINVAL); | ||
| 844 | return SOCKET_ERROR; | ||
| 845 | } | ||
| 846 | |||
| 847 | if (io_control_code == SIO_GET_EXTENSION_FUNCTION_POINTER && in_buf && in_len >= sizeof(GUID)) { | ||
| 848 | static constexpr GUID kConnectExGuid = WSAID_CONNECTEX; | ||
| 849 | static constexpr GUID kSendMsgGuid = WSAID_WSASENDMSG; | ||
| 850 | GUID requested{}; | ||
| 851 | std::memcpy(&requested, in_buf, sizeof(requested)); | ||
| 852 | |||
| 853 | if (std::memcmp(&requested, &kConnectExGuid, sizeof(GUID)) == 0) { | ||
| 854 | if (!out_buf || out_len < sizeof(void*) || !bytes_returned) { | ||
| 855 | set_wsa_error(WSAEFAULT); | ||
| 856 | return SOCKET_ERROR; | ||
| 857 | } | ||
| 858 | LPFN_CONNECTEX real_ext = nullptr; | ||
| 859 | DWORD returned = 0; | ||
| 860 | const int rc = real_fn(s, io_control_code, in_buf, in_len, &real_ext, sizeof(real_ext), &returned, | ||
| 861 | overlapped, completion); | ||
| 862 | if (rc != 0) return rc; | ||
| 863 | LPFN_CONNECTEX wrapped = &connect_ex_offline; | ||
| 864 | std::memcpy(out_buf, &wrapped, sizeof(wrapped)); | ||
| 865 | *bytes_returned = sizeof(wrapped); | ||
| 866 | return 0; | ||
| 867 | } | ||
| 868 | if (std::memcmp(&requested, &kSendMsgGuid, sizeof(GUID)) == 0) { | ||
| 869 | if (!out_buf || out_len < sizeof(void*) || !bytes_returned) { | ||
| 870 | set_wsa_error(WSAEFAULT); | ||
| 871 | return SOCKET_ERROR; | ||
| 872 | } | ||
| 873 | LPFN_WSASENDMSG real_ext = nullptr; | ||
| 874 | DWORD returned = 0; | ||
| 875 | const int rc = real_fn(s, io_control_code, in_buf, in_len, &real_ext, sizeof(real_ext), &returned, | ||
| 876 | overlapped, completion); | ||
| 877 | if (rc != 0) return rc; | ||
| 878 | LPFN_WSASENDMSG wrapped = &wsa_send_msg_ext_offline; | ||
| 879 | std::memcpy(out_buf, &wrapped, sizeof(wrapped)); | ||
| 880 | *bytes_returned = sizeof(wrapped); | ||
| 881 | return 0; | ||
| 882 | } | ||
| 883 | } | ||
| 884 | |||
| 885 | return real_fn(s, io_control_code, in_buf, in_len, out_buf, out_len, bytes_returned, overlapped, completion); | ||
| 886 | } | ||
| 887 | |||
| 888 | } // namespace | ||
| 889 | } // namespace rt::ws2 | ||
| 890 | |||
| 891 | namespace { | ||
| 892 | using namespace rt::ws2; | ||
| 893 | } // namespace | ||
| 894 | |||
| 895 | // Both named exports and the fixed Windows ordinals (#2 bind, #4 connect, #20 sendto, #21 setsockopt, | ||
| 896 | // #51 gethostbyaddr, #52 gethostbyname, #102 WSAAsyncGetHostByAddr, #103 WSAAsyncGetHostByName) are registered so | ||
| 897 | // static imports by ordinal and dynamic GetProcAddress lookups resolve to the same offline wrappers. wsock32.dll gets | ||
| 898 | // the same wrappers for the entries it shares with ws2_32, since those exports forward to ws2_32 natively; its | ||
| 899 | // setsockopt is its own export (Winsock 1.1 option numbers), so it gets its own wrapper. | ||
| 900 | SHIM_TABLE(ws2_offline, | ||
| 901 | {"ws2_32.dll", "bind", reinterpret_cast<void*>(&bind_offline)}, | ||
| 902 | {"ws2_32.dll", "#2", reinterpret_cast<void*>(&bind_offline)}, | ||
| 903 | {"ws2_32.dll", "connect", reinterpret_cast<void*>(&connect_offline)}, | ||
| 904 | {"ws2_32.dll", "#4", reinterpret_cast<void*>(&connect_offline)}, | ||
| 905 | {"ws2_32.dll", "sendto", reinterpret_cast<void*>(&sendto_offline)}, | ||
| 906 | {"ws2_32.dll", "#20", reinterpret_cast<void*>(&sendto_offline)}, | ||
| 907 | {"ws2_32.dll", "setsockopt", reinterpret_cast<void*>(&setsockopt_offline)}, | ||
| 908 | {"ws2_32.dll", "#21", reinterpret_cast<void*>(&setsockopt_offline)}, | ||
| 909 | {"ws2_32.dll", "WSAJoinLeaf", reinterpret_cast<void*>(&wsa_join_leaf_offline)}, | ||
| 910 | {"ws2_32.dll", "gethostbyaddr", reinterpret_cast<void*>(&gethostbyaddr_offline)}, | ||
| 911 | {"ws2_32.dll", "#51", reinterpret_cast<void*>(&gethostbyaddr_offline)}, | ||
| 912 | {"ws2_32.dll", "gethostbyname", reinterpret_cast<void*>(&gethostbyname_offline)}, | ||
| 913 | {"ws2_32.dll", "#52", reinterpret_cast<void*>(&gethostbyname_offline)}, | ||
| 914 | {"ws2_32.dll", "WSAAsyncGetHostByAddr", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)}, | ||
| 915 | {"ws2_32.dll", "#102", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)}, | ||
| 916 | {"ws2_32.dll", "WSAAsyncGetHostByName", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)}, | ||
| 917 | {"ws2_32.dll", "#103", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)}, | ||
| 918 | {"ws2_32.dll", "getaddrinfo", reinterpret_cast<void*>(&getaddrinfo_offline)}, | ||
| 919 | {"ws2_32.dll", "GetAddrInfoW", reinterpret_cast<void*>(&get_addr_info_w_offline)}, | ||
| 920 | {"ws2_32.dll", "GetAddrInfoExA", reinterpret_cast<void*>(&get_addr_info_ex_a_offline)}, | ||
| 921 | {"ws2_32.dll", "GetAddrInfoExW", reinterpret_cast<void*>(&get_addr_info_ex_w_offline)}, | ||
| 922 | {"ws2_32.dll", "getnameinfo", reinterpret_cast<void*>(&getnameinfo_offline)}, | ||
| 923 | {"ws2_32.dll", "GetNameInfoW", reinterpret_cast<void*>(&get_name_info_w_offline)}, | ||
| 924 | {"ws2_32.dll", "WSAConnect", reinterpret_cast<void*>(&wsa_connect_offline)}, | ||
| 925 | {"ws2_32.dll", "WSAConnectByNameA", reinterpret_cast<void*>(&wsa_connect_by_name_a_offline)}, | ||
| 926 | {"ws2_32.dll", "WSAConnectByNameW", reinterpret_cast<void*>(&wsa_connect_by_name_w_offline)}, | ||
| 927 | {"ws2_32.dll", "WSAConnectByList", reinterpret_cast<void*>(&wsa_connect_by_list_offline)}, | ||
| 928 | {"ws2_32.dll", "WSASendTo", reinterpret_cast<void*>(&wsa_send_to_offline)}, | ||
| 929 | {"ws2_32.dll", "WSASendMsg", reinterpret_cast<void*>(&wsa_send_msg_offline)}, | ||
| 930 | {"ws2_32.dll", "WSAIoctl", reinterpret_cast<void*>(&wsa_ioctl_offline)}, | ||
| 931 | {"ws2_32.dll", "WSALookupServiceBeginA", reinterpret_cast<void*>(&wsa_lookup_service_begin_a_offline)}, | ||
| 932 | {"ws2_32.dll", "WSALookupServiceBeginW", reinterpret_cast<void*>(&wsa_lookup_service_begin_w_offline)}, | ||
| 933 | {"wsock32.dll", "bind", reinterpret_cast<void*>(&bind_offline)}, | ||
| 934 | {"wsock32.dll", "#2", reinterpret_cast<void*>(&bind_offline)}, | ||
| 935 | {"wsock32.dll", "connect", reinterpret_cast<void*>(&connect_offline)}, | ||
| 936 | {"wsock32.dll", "#4", reinterpret_cast<void*>(&connect_offline)}, | ||
| 937 | {"wsock32.dll", "sendto", reinterpret_cast<void*>(&sendto_offline)}, | ||
| 938 | {"wsock32.dll", "#20", reinterpret_cast<void*>(&sendto_offline)}, | ||
| 939 | {"wsock32.dll", "setsockopt", reinterpret_cast<void*>(&wsock32_setsockopt_offline)}, | ||
| 940 | {"wsock32.dll", "#21", reinterpret_cast<void*>(&wsock32_setsockopt_offline)}, | ||
| 941 | {"wsock32.dll", "gethostbyaddr", reinterpret_cast<void*>(&gethostbyaddr_offline)}, | ||
| 942 | {"wsock32.dll", "#51", reinterpret_cast<void*>(&gethostbyaddr_offline)}, | ||
| 943 | {"wsock32.dll", "gethostbyname", reinterpret_cast<void*>(&gethostbyname_offline)}, | ||
| 944 | {"wsock32.dll", "#52", reinterpret_cast<void*>(&gethostbyname_offline)}, | ||
| 945 | {"wsock32.dll", "WSAAsyncGetHostByAddr", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)}, | ||
| 946 | {"wsock32.dll", "#102", reinterpret_cast<void*>(&wsa_async_get_host_by_addr_offline)}, | ||
| 947 | {"wsock32.dll", "WSAAsyncGetHostByName", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)}, | ||
| 948 | {"wsock32.dll", "#103", reinterpret_cast<void*>(&wsa_async_get_host_by_name_offline)}, | ||
| 949 | ); | ||
diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp index dd5f810cf..f8791e1bf 100644 --- a/runtime/shims/xbox_present.cpp +++ b/runtime/shims/xbox_present.cpp | |||
| @@ -1,6 +1,7 @@ | |||
| 1 | #include "xbox_present.h" | 1 | #include "xbox_present.h" |
| 2 | 2 | ||
| 3 | #include "d3d12_trace.h" | 3 | #include "d3d12_trace.h" |
| 4 | #include "d3d12_xs_device.h" | ||
| 4 | 5 | ||
| 5 | #include "../src/vulkan_present.h" | 6 | #include "../src/vulkan_present.h" |
| 6 | 7 | ||
| @@ -66,6 +67,7 @@ XboxPresentation::XboxPresentation(std::unique_ptr<WindowPresenter> presenter, l | |||
| 66 | } | 67 | } |
| 67 | 68 | ||
| 68 | XboxPresentation::~XboxPresentation() { | 69 | XboxPresentation::~XboxPresentation() { |
| 70 | if (presents_.load() > 0) log_pacing_summary(); | ||
| 69 | { | 71 | { |
| 70 | std::lock_guard lock(worker_mutex_); | 72 | std::lock_guard lock(worker_mutex_); |
| 71 | worker_stop_ = true; | 73 | worker_stop_ = true; |
| @@ -75,6 +77,26 @@ XboxPresentation::~XboxPresentation() { | |||
| 75 | presenter_->set_abort(nullptr); | 77 | presenter_->set_abort(nullptr); |
| 76 | } | 78 | } |
| 77 | 79 | ||
| 80 | void XboxPresentation::log_pacing_summary() const { | ||
| 81 | const leonida::FramePacingSummary s = pacer_.pacing_summary(); | ||
| 82 | std::fprintf(stderr, | ||
| 83 | "[rt] present: pacing summary frames=%llu samples=%llu target_us=%u mean_us=%.1f drift_us=%+.1f " | ||
| 84 | "p50_us=%llu p95_us=%llu p99_us=%llu latency_samples=%llu latency_p50_us=%llu " | ||
| 85 | "latency_p95_us=%llu latency_p99_us=%llu\n", | ||
| 86 | static_cast<unsigned long long>(s.frames), | ||
| 87 | static_cast<unsigned long long>(s.samples), | ||
| 88 | s.target_interval_us, | ||
| 89 | s.mean_us, | ||
| 90 | s.drift_us, | ||
| 91 | static_cast<unsigned long long>(s.p50_us), | ||
| 92 | static_cast<unsigned long long>(s.p95_us), | ||
| 93 | static_cast<unsigned long long>(s.p99_us), | ||
| 94 | static_cast<unsigned long long>(s.latency_samples), | ||
| 95 | static_cast<unsigned long long>(s.latency_p50_us), | ||
| 96 | static_cast<unsigned long long>(s.latency_p95_us), | ||
| 97 | static_cast<unsigned long long>(s.latency_p99_us)); | ||
| 98 | } | ||
| 99 | |||
| 78 | // Windows' SDR white level costs a QueryDisplayConfig and two DisplayConfigGetDeviceInfo calls (measured in | 100 | // Windows' SDR white level costs a QueryDisplayConfig and two DisplayConfigGetDeviceInfo calls (measured in |
| 79 | // xbox_present_test, docs section 4.5): too much for the present path, which would hitch once a second and feed the pacer. | 101 | // xbox_present_test, docs section 4.5): too much for the present path, which would hitch once a second and feed the pacer. |
| 80 | // So it is read here, about once a second while an HDR10 swapchain is in use, and PresentX reads the cached value. | 102 | // So it is read here, about once a second while an HDR10 swapchain is in use, and PresentX reads the cached value. |
| @@ -314,4 +336,39 @@ HRESULT XboxPresentation::ResumeX() { | |||
| 314 | return S_OK; | 336 | return S_OK; |
| 315 | } | 337 | } |
| 316 | 338 | ||
| 339 | bool attach_xbox_presentation(void* device_proxy, XboxPresentation* presentation) { | ||
| 340 | if (!presentation) return rt::d3d12_xs::set_presentation_handler(device_proxy, nullptr); | ||
| 341 | rt::d3d12_xs::PresentationHandler handler{}; | ||
| 342 | handler.context = presentation; | ||
| 343 | handler.set_frame_interval = [](void* ctx, IUnknown* output, UINT interval_us, UINT latency, UINT flags) { | ||
| 344 | return static_cast<XboxPresentation*>(ctx)->SetFrameIntervalX(output, interval_us, latency, flags); | ||
| 345 | }; | ||
| 346 | handler.schedule_frame_event = [](void* ctx, UINT event, UINT offset_us, UINT flags) { | ||
| 347 | return static_cast<XboxPresentation*>(ctx)->ScheduleFrameEventX(event, offset_us, flags); | ||
| 348 | }; | ||
| 349 | handler.wait_frame_event = [](void* ctx, UINT event, DWORD timeout_ms, UINT flags, std::uint64_t* token) { | ||
| 350 | return static_cast<XboxPresentation*>(ctx)->WaitFrameEventX(event, timeout_ms, flags, token); | ||
| 351 | }; | ||
| 352 | handler.get_frame_statistics = [](void* ctx, std::uint64_t token, UINT type_mask, UINT* count, void* out) { | ||
| 353 | return static_cast<XboxPresentation*>(ctx)->GetFrameStatisticsX( | ||
| 354 | token, type_mask, count, static_cast<leonida::FrameStatistic*>(out)); | ||
| 355 | }; | ||
| 356 | handler.present_x = [](void* ctx, UINT plane_count, const void* planes, const void* params) { | ||
| 357 | return static_cast<XboxPresentation*>(ctx)->PresentX( | ||
| 358 | plane_count, static_cast<const XboxPresentPlaneParameters*>(planes), | ||
| 359 | static_cast<const XboxPresentParameters*>(params)); | ||
| 360 | }; | ||
| 361 | handler.suspend_x = [](void* ctx, UINT flags) { | ||
| 362 | return static_cast<XboxPresentation*>(ctx)->SuspendX(flags); | ||
| 363 | }; | ||
| 364 | handler.resume_x = [](void* ctx) { | ||
| 365 | return static_cast<XboxPresentation*>(ctx)->ResumeX(); | ||
| 366 | }; | ||
| 367 | return rt::d3d12_xs::set_presentation_handler(device_proxy, &handler); | ||
| 368 | } | ||
| 369 | |||
| 370 | bool detach_xbox_presentation(void* device_proxy) { | ||
| 371 | return rt::d3d12_xs::set_presentation_handler(device_proxy, nullptr); | ||
| 372 | } | ||
| 373 | |||
| 317 | } // namespace rt::d3d12 | 374 | } // namespace rt::d3d12 |
diff --git a/runtime/shims/xbox_present.h b/runtime/shims/xbox_present.h index 60a317bee..6230d82ea 100644 --- a/runtime/shims/xbox_present.h +++ b/runtime/shims/xbox_present.h | |||
| @@ -171,6 +171,9 @@ public: | |||
| 171 | std::uint64_t presents() const { return presents_; } | 171 | std::uint64_t presents() const { return presents_; } |
| 172 | // Frames shown mid-scan because of ImmediateThresholdPercent. | 172 | // Frames shown mid-scan because of ImmediateThresholdPercent. |
| 173 | std::uint64_t immediate_presents() const { return pacer_.immediate_presents(); } | 173 | std::uint64_t immediate_presents() const { return pacer_.immediate_presents(); } |
| 174 | // Frame-time percentiles, mean drift against target interval, and origin-to-present latency (BL-6). | ||
| 175 | leonida::FramePacingSummary pacing_summary() const { return pacer_.pacing_summary(); } | ||
| 176 | void log_pacing_summary() const; | ||
| 174 | 177 | ||
| 175 | private: | 178 | private: |
| 176 | // PresentX without its `[d3d12-trace]` line. | 179 | // PresentX without its `[d3d12-trace]` line. |
| @@ -199,5 +202,15 @@ private: | |||
| 199 | }; | 202 | }; |
| 200 | 203 | ||
| 201 | inline constexpr UINT xbox_frame_event_origin = leonida::frame_event_origin; | 204 | inline constexpr UINT xbox_frame_event_origin = leonida::frame_event_origin; |
| 205 | inline constexpr UINT xbox_frame_event_vblank = leonida::frame_event_vblank; | ||
| 206 | inline constexpr UINT xbox_frame_event_flip = leonida::frame_event_flip; | ||
| 207 | inline constexpr UINT xbox_frame_wait_token_on_timeout = leonida::frame_wait_flag_token_on_timeout; | ||
| 208 | |||
| 209 | // Seam for the presenter, not yet called by the runtime: gta6rt creates no XboxPresentation, and only | ||
| 210 | // d3d12_boot_movie_test and xbox_present_test construct one. Wires it into a d3d12_xs device proxy's frame-event | ||
| 211 | // slots (78–81) and queue PresentX (slot 30, or LEONIDA_XS_PRESENT_X_SLOT); SuspendX and ResumeX are routed only | ||
| 212 | // when LEONIDA_XS_SUSPEND_X_SLOT / LEONIDA_XS_RESUME_X_SLOT are set. Passing nullptr detaches the presentation. | ||
| 213 | bool attach_xbox_presentation(void* device_proxy, XboxPresentation* presentation); | ||
| 214 | bool detach_xbox_presentation(void* device_proxy); | ||
| 202 | 215 | ||
| 203 | } // namespace rt::d3d12 | 216 | } // namespace rt::d3d12 |
diff --git a/runtime/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp index cc7a91d21..23a5e9d81 100644 --- a/runtime/shims/xgameruntime_offline.cpp +++ b/runtime/shims/xgameruntime_offline.cpp | |||
| @@ -1,5 +1,5 @@ | |||
| 1 | // xgameruntime: XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl and | 1 | // xgameruntime: XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl |
| 2 | // XLauncherImpl, offline: small classes a title calls early. | 2 | // and XLauncherImpl, offline: small classes a title calls early. |
| 3 | // | 3 | // |
| 4 | // Each XGameEvent*, XGameUi* and XGameStreaming* function in xgameruntime.lib asks QueryApiImpl for its class and | 4 | // Each XGameEvent*, XGameUi* and XGameStreaming* function in xgameruntime.lib asks QueryApiImpl for its class and |
| 5 | // calls one slot with its own arguments after `this`. The class and interface ids and the method order are | 5 | // calls one slot with its own arguments after `this`. The class and interface ids and the method order are |
| @@ -18,17 +18,19 @@ | |||
| 18 | // XUserDeviceImpl every device belongs to the offline user; associations and audio endpoints never change, so | 18 | // XUserDeviceImpl every device belongs to the offline user; associations and audio endpoints never change, so |
| 19 | // their change registrations are kept until unregistered and never called back; the user has | 19 | // their change registrations are kept until unregistered and never called back; the user has |
| 20 | // no audio endpoint of its own; finding a controller shows no UI (as on desktop). | 20 | // no audio endpoint of its own; finding a controller shows no UI (as on desktop). |
| 21 | // XAccessibilityImpl high contrast is Off, closed captions can't be configured, no voice is installed (enumerating | 21 | // XAccessibilityImpl high contrast is Off, closed captions can't be configured, one silent voice is installed |
| 22 | // calls back zero times), XSpeechSynthesizerCreate fails (E_FAIL) with a null handle, the other | 22 | // (enumerating calls back once), XSpeechSynthesizerCreate hands out a synthesizer whose |
| 23 | // speech calls refuse the handle they were never given (E_INVALIDARG), speech-to-text display | 23 | // text/SSML streams return a valid 44-byte empty 16 kHz mono 16-bit PCM WAVE header so titles |
| 24 | // calls fail (E_FAIL). | 24 | // that play narration continue cleanly; speech-to-text display calls fail (E_FAIL). |
| 25 | // XLauncherImpl XLaunchUri and the display timeout deferral calls fail (E_FAIL); nothing is launched. | 25 | // XLauncherImpl XLaunchUri fails offline (E_FAIL); XDisplayAcquireTimeoutDeferral / Close acquire and clear a |
| 26 | // real Win32 PowerRequestDisplayRequired handle so the host display stays awake. | ||
| 26 | // | 27 | // |
| 27 | // Slots whose signature the public pages don't give answer with a value that is safe whichever way the caller reads | 28 | // Slots whose signature the public pages don't give answer with a value that is safe whichever way the caller reads |
| 28 | // it: see `client_not_connected` (XGameStreaming) and `offline_failure`. | 29 | // it: see `client_not_connected` (XGameStreaming) and `offline_failure`. |
| 29 | #include <windows.h> | 30 | #include <windows.h> |
| 30 | 31 | ||
| 31 | #include <atomic> | 32 | #include <atomic> |
| 33 | #include <cstddef> | ||
| 32 | #include <cstdint> | 34 | #include <cstdint> |
| 33 | #include <cstdio> | 35 | #include <cstdio> |
| 34 | #include <cstdlib> | 36 | #include <cstdlib> |
| @@ -604,38 +606,94 @@ HRESULT STDMETHODCALLTYPE accessibility_high_contrast(void*, uint32_t* mode) { | |||
| 604 | // 4: HRESULT XClosedCaptionSetEnabled(bool enabled): there are no captions to show; accepted and dropped. | 606 | // 4: HRESULT XClosedCaptionSetEnabled(bool enabled): there are no captions to show; accepted and dropped. |
| 605 | HRESULT STDMETHODCALLTYPE accessibility_captions_set_enabled(void*, bool) { return S_OK; } | 607 | HRESULT STDMETHODCALLTYPE accessibility_captions_set_enabled(void*, bool) { return S_OK; } |
| 606 | 608 | ||
| 607 | // 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(callback, void* context): no voice is installed, so the | 609 | // XSpeechSynthesizerVoiceInformation and its callback, in the GDK reference's member order (the gender is |
| 608 | // callback runs zero times. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured. | 610 | // XSpeechSynthesizerVoiceGender, a uint32_t enum: Female 0, Male 1). |
| 609 | HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* callback, void*) { | 611 | struct SpeechVoiceInformation { |
| 610 | return callback ? S_OK : E_INVALIDARG; | 612 | const char* description; |
| 613 | const char* display_name; | ||
| 614 | uint32_t gender; | ||
| 615 | const char* voice_id; | ||
| 616 | const char* language; | ||
| 617 | }; | ||
| 618 | static_assert(offsetof(SpeechVoiceInformation, voice_id) == 24 && sizeof(SpeechVoiceInformation) == 40, "x64 layout"); | ||
| 619 | using InstalledVoicesCallback = bool(CALLBACK*)(const SpeechVoiceInformation* information, void* context); | ||
| 620 | constexpr SpeechVoiceInformation kSilentVoice = {"Leonida silent voice - English (United States)", | ||
| 621 | "Leonida silent voice", 0, "leonida-silent", "en-US"}; | ||
| 622 | |||
| 623 | // 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(void* context, callback): one voice, the silent one every | ||
| 624 | // synthesizer below speaks with. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured. | ||
| 625 | HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* context, InstalledVoicesCallback callback) { | ||
| 626 | if (!callback) return E_INVALIDARG; | ||
| 627 | callback(&kSilentVoice, context); | ||
| 628 | return S_OK; | ||
| 629 | } | ||
| 630 | |||
| 631 | // Valid 44-byte RIFF/WAVE header for 16 kHz, 16-bit mono PCM with 0 data bytes (silent speech stream). | ||
| 632 | constexpr uint8_t kSilentWave[44] = { | ||
| 633 | 'R', 'I', 'F', 'F', 0x24, 0x00, 0x00, 0x00, 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ', | ||
| 634 | 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x80, 0x3e, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, | ||
| 635 | 0x02, 0x00, 0x10, 0x00, 'd', 'a', 't', 'a', 0x00, 0x00, 0x00, 0x00, | ||
| 636 | }; | ||
| 637 | |||
| 638 | uint8_t g_speech_synth_handle = 0; | ||
| 639 | uint8_t g_speech_stream_handle = 0; | ||
| 640 | |||
| 641 | // 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): silent synthesizer handle. | ||
| 642 | HRESULT STDMETHODCALLTYPE speech_create(void*, void** handle) { | ||
| 643 | if (!handle) return E_POINTER; | ||
| 644 | *handle = &g_speech_synth_handle; | ||
| 645 | return S_OK; | ||
| 646 | } | ||
| 647 | |||
| 648 | // 10: HRESULT XSpeechSynthesizerCloseHandle(XSpeechSynthesizerHandle handle) | ||
| 649 | HRESULT STDMETHODCALLTYPE speech_close_synth(void*, void* handle) { | ||
| 650 | return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG; | ||
| 611 | } | 651 | } |
| 612 | 652 | ||
| 613 | // 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): no synthesizer offline. | 653 | // 11: HRESULT XSpeechSynthesizerSetDefaultVoice(XSpeechSynthesizerHandle handle) |
| 614 | HRESULT STDMETHODCALLTYPE speech_create(void* self, void** handle) { | 654 | HRESULT STDMETHODCALLTYPE speech_set_default_voice(void*, void* handle) { |
| 615 | if (handle) *handle = nullptr; | 655 | return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG; |
| 616 | return offline_failure<kAccessibilityName, 9>(self); | ||
| 617 | } | 656 | } |
| 618 | 657 | ||
| 619 | // 10-12, 14: a synthesizer or stream handle is the first argument, and none was ever handed out: E_INVALIDARG. | 658 | // 12: HRESULT XSpeechSynthesizerSetCustomVoice(XSpeechSynthesizerHandle handle, const char* voiceId): only the |
| 620 | HRESULT STDMETHODCALLTYPE speech_bad_handle(void*) { return E_INVALIDARG; } | 659 | // enumerated voice is installed. |
| 660 | HRESULT STDMETHODCALLTYPE speech_set_custom_voice(void*, void* handle, const char* voice_id) { | ||
| 661 | if (handle != &g_speech_synth_handle || !voice_id) return E_INVALIDARG; | ||
| 662 | return std::strcmp(voice_id, kSilentVoice.voice_id) == 0 ? S_OK : E_INVALIDARG; | ||
| 663 | } | ||
| 621 | 664 | ||
| 622 | // 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text, | 665 | // 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text, |
| 623 | // XSpeechSynthesizerStreamHandle* stream) | 666 | // XSpeechSynthesizerStreamHandle* stream) |
| 624 | HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void*, const char*, void** stream) { | 667 | HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void* synth, const char*, void** stream) { |
| 625 | if (stream) *stream = nullptr; | 668 | if (stream) *stream = nullptr; |
| 626 | return E_INVALIDARG; | 669 | if (synth != &g_speech_synth_handle) return E_INVALIDARG; |
| 670 | if (!stream) return E_POINTER; | ||
| 671 | *stream = &g_speech_stream_handle; | ||
| 672 | return S_OK; | ||
| 673 | } | ||
| 674 | |||
| 675 | // 14: HRESULT XSpeechSynthesizerCloseStreamHandle(XSpeechSynthesizerStreamHandle stream) | ||
| 676 | HRESULT STDMETHODCALLTYPE speech_close_stream(void*, void* stream) { | ||
| 677 | return stream == &g_speech_stream_handle ? S_OK : E_INVALIDARG; | ||
| 627 | } | 678 | } |
| 628 | 679 | ||
| 629 | // 15: HRESULT XSpeechSynthesizerGetStreamDataSize(stream, size_t* size) | 680 | // 15: HRESULT XSpeechSynthesizerGetStreamDataSize(stream, size_t* size) |
| 630 | HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void*, size_t* size) { | 681 | HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void* stream, size_t* size) { |
| 631 | if (size) *size = 0; | 682 | if (size) *size = 0; |
| 632 | return E_INVALIDARG; | 683 | if (stream != &g_speech_stream_handle) return E_INVALIDARG; |
| 684 | if (!size) return E_POINTER; | ||
| 685 | *size = sizeof(kSilentWave); | ||
| 686 | return S_OK; | ||
| 633 | } | 687 | } |
| 634 | 688 | ||
| 635 | // 16: HRESULT XSpeechSynthesizerGetStreamData(stream, size_t size, void* buffer, size_t* used) | 689 | // 16: HRESULT XSpeechSynthesizerGetStreamData(stream, size_t size, void* buffer, size_t* used) |
| 636 | HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void*, size_t, void*, size_t* used) { | 690 | HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void* stream, size_t size, void* buffer, size_t* used) { |
| 637 | if (used) *used = 0; | 691 | if (used) *used = 0; |
| 638 | return E_INVALIDARG; | 692 | if (stream != &g_speech_stream_handle) return E_INVALIDARG; |
| 693 | if (!buffer || size < sizeof(kSilentWave)) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); | ||
| 694 | std::memcpy(buffer, kSilentWave, sizeof(kSilentWave)); | ||
| 695 | if (used) *used = sizeof(kSilentWave); | ||
| 696 | return S_OK; | ||
| 639 | } | 697 | } |
| 640 | 698 | ||
| 641 | // The slots with no offline counterpart whose arguments the layout doesn't give: the caption properties (3) and | 699 | // The slots with no offline counterpart whose arguments the layout doesn't give: the caption properties (3) and |
| @@ -654,11 +712,11 @@ const void* const kAccessibilityVtable[] = { | |||
| 654 | FN(accessibility_offline<7>), // 7 XSpeechToTextSendString | 712 | FN(accessibility_offline<7>), // 7 XSpeechToTextSendString |
| 655 | FN(speech_enumerate_voices), // 8 XSpeechSynthesizerEnumerateInstalledVoices | 713 | FN(speech_enumerate_voices), // 8 XSpeechSynthesizerEnumerateInstalledVoices |
| 656 | FN(speech_create), // 9 XSpeechSynthesizerCreate | 714 | FN(speech_create), // 9 XSpeechSynthesizerCreate |
| 657 | FN(speech_bad_handle), // 10 XSpeechSynthesizerCloseHandle | 715 | FN(speech_close_synth), // 10 XSpeechSynthesizerCloseHandle |
| 658 | FN(speech_bad_handle), // 11 XSpeechSynthesizerSetDefaultVoice | 716 | FN(speech_set_default_voice), // 11 XSpeechSynthesizerSetDefaultVoice |
| 659 | FN(speech_bad_handle), // 12 XSpeechSynthesizerSetCustomVoice | 717 | FN(speech_set_custom_voice), // 12 XSpeechSynthesizerSetCustomVoice |
| 660 | FN(speech_create_stream), // 13 XSpeechSynthesizerCreateStreamFromText | 718 | FN(speech_create_stream), // 13 XSpeechSynthesizerCreateStreamFromText |
| 661 | FN(speech_bad_handle), // 14 XSpeechSynthesizerCloseStreamHandle | 719 | FN(speech_close_stream), // 14 XSpeechSynthesizerCloseStreamHandle |
| 662 | FN(speech_stream_size), // 15 XSpeechSynthesizerGetStreamDataSize | 720 | FN(speech_stream_size), // 15 XSpeechSynthesizerGetStreamDataSize |
| 663 | FN(speech_stream_data), // 16 XSpeechSynthesizerGetStreamData | 721 | FN(speech_stream_data), // 16 XSpeechSynthesizerGetStreamData |
| 664 | FN(accessibility_offline<17>), // 17 XSpeechToTextBeginHypothesisString | 722 | FN(accessibility_offline<17>), // 17 XSpeechToTextBeginHypothesisString |
| @@ -680,11 +738,31 @@ constexpr char kLauncherName[] = "XLauncherImpl"; | |||
| 680 | constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; | 738 | constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; |
| 681 | 739 | ||
| 682 | // 3: HRESULT XLaunchUri(XUserHandle user, const char* uri): nothing is launched; E_FAIL. | 740 | // 3: HRESULT XLaunchUri(XUserHandle user, const char* uri): nothing is launched; E_FAIL. |
| 683 | // 4: HRESULT XDisplayAcquireTimeoutDeferral(XDisplayTimeoutDeferralHandle* handle): none is handed out. | 741 | // 4: HRESULT XDisplayAcquireTimeoutDeferral(XDisplayTimeoutDeferralHandle* handle): Win32 display power request. |
| 684 | // 5: XDisplayCloseTimeoutDeferralHandle(handle): no handle exists; E_FAIL, which a void caller ignores. | 742 | // 5: void XDisplayCloseTimeoutDeferralHandle(XDisplayTimeoutDeferralHandle handle): clears and closes the request. |
| 685 | HRESULT STDMETHODCALLTYPE launcher_acquire_deferral(void* self, void** handle) { | 743 | HRESULT STDMETHODCALLTYPE launcher_acquire_deferral(void*, void** handle) { |
| 686 | if (handle) *handle = nullptr; | 744 | if (!handle) return E_POINTER; |
| 687 | return offline_failure<kLauncherName, 4>(self); | 745 | *handle = nullptr; |
| 746 | wchar_t reason[] = L"Title display timeout deferral"; | ||
| 747 | REASON_CONTEXT ctx{}; | ||
| 748 | ctx.Version = POWER_REQUEST_CONTEXT_VERSION; | ||
| 749 | ctx.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING; | ||
| 750 | ctx.Reason.SimpleReasonString = reason; | ||
| 751 | const HANDLE req = PowerCreateRequest(&ctx); | ||
| 752 | if (req == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(GetLastError()); | ||
| 753 | if (!PowerSetRequest(req, PowerRequestDisplayRequired)) { | ||
| 754 | const DWORD err = GetLastError(); | ||
| 755 | CloseHandle(req); | ||
| 756 | return HRESULT_FROM_WIN32(err); | ||
| 757 | } | ||
| 758 | *handle = req; | ||
| 759 | return S_OK; | ||
| 760 | } | ||
| 761 | |||
| 762 | void STDMETHODCALLTYPE launcher_close_deferral(void*, void* handle) { | ||
| 763 | if (!handle) return; | ||
| 764 | PowerClearRequest(handle, PowerRequestDisplayRequired); | ||
| 765 | CloseHandle(handle); | ||
| 688 | } | 766 | } |
| 689 | 767 | ||
| 690 | HRESULT STDMETHODCALLTYPE launcher_query_interface(void*, REFIID iid, void** out); | 768 | HRESULT STDMETHODCALLTYPE launcher_query_interface(void*, REFIID iid, void** out); |
| @@ -692,7 +770,7 @@ const void* const kLauncherVtable[] = { | |||
| 692 | FN(launcher_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown | 770 | FN(launcher_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown |
| 693 | FN((offline_failure<kLauncherName, 3>)), // 3 XLaunchUri | 771 | FN((offline_failure<kLauncherName, 3>)), // 3 XLaunchUri |
| 694 | FN(launcher_acquire_deferral), // 4 XDisplayAcquireTimeoutDeferral | 772 | FN(launcher_acquire_deferral), // 4 XDisplayAcquireTimeoutDeferral |
| 695 | FN((offline_failure<kLauncherName, 5>)), // 5 XDisplayCloseTimeoutDeferralHandle | 773 | FN(launcher_close_deferral), // 5 XDisplayCloseTimeoutDeferralHandle |
| 696 | }; | 774 | }; |
| 697 | static_assert(std::size(kLauncherVtable) == 6, "IUnknown + IXLauncherImpl's 3 methods"); | 775 | static_assert(std::size(kLauncherVtable) == 6, "IUnknown + IXLauncherImpl's 3 methods"); |
| 698 | ClassObject g_launcher_object{kLauncherVtable}; | 776 | ClassObject g_launcher_object{kLauncherVtable}; |
diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h index fac13eeee..8df3b55d0 100644 --- a/runtime/src/cpu_emulation.h +++ b/runtime/src/cpu_emulation.h | |||
| @@ -272,6 +272,84 @@ inline bool apply(const Decoded& d, CONTEXT* c, EXCEPTION_RECORD* fault = nullpt | |||
| 272 | return true; | 272 | return true; |
| 273 | } | 273 | } |
| 274 | 274 | ||
| 275 | inline uint64_t gpr_read(const CONTEXT* c, int r) { | ||
| 276 | switch (r) { | ||
| 277 | case 0: return c->Rax; case 1: return c->Rcx; case 2: return c->Rdx; case 3: return c->Rbx; | ||
| 278 | case 4: return c->Rsp; case 5: return c->Rbp; case 6: return c->Rsi; case 7: return c->Rdi; | ||
| 279 | case 8: return c->R8; case 9: return c->R9; case 10: return c->R10; case 11: return c->R11; | ||
| 280 | case 12: return c->R12; case 13: return c->R13; case 14: return c->R14; case 15: return c->R15; | ||
| 281 | default: return 0; | ||
| 282 | } | ||
| 283 | } | ||
| 284 | |||
| 285 | enum class ClzeroLoopResult { no_match, ok, faulted }; | ||
| 286 | |||
| 287 | inline void apply_cmp_flags(CONTEXT* c, uint64_t lhs, uint64_t rhs) { | ||
| 288 | const uint64_t diff = lhs - rhs; | ||
| 289 | uint32_t flags = c->EFlags & ~DWORD(0x8D5u); // clear CF(0), PF(2), AF(4), ZF(6), SF(7), OF(11) | ||
| 290 | if (lhs < rhs) flags |= 0x1u; // CF | ||
| 291 | uint8_t lo8 = static_cast<uint8_t>(diff); | ||
| 292 | lo8 ^= lo8 >> 4; | ||
| 293 | lo8 ^= lo8 >> 2; | ||
| 294 | lo8 ^= lo8 >> 1; | ||
| 295 | if ((lo8 & 1u) == 0) flags |= 0x4u; // PF | ||
| 296 | if ((lhs ^ rhs ^ diff) & 0x10u) flags |= 0x10u; // AF | ||
| 297 | if (diff == 0) flags |= 0x40u; // ZF | ||
| 298 | if (diff >> 63) flags |= 0x80u; // SF | ||
| 299 | if (((lhs ^ rhs) & (lhs ^ diff)) >> 63) flags |= 0x800u; // OF | ||
| 300 | c->EFlags = flags; | ||
| 301 | } | ||
| 302 | |||
| 303 | // Fast-path for the Zen 2 zeroing loop: `clzero; add rax, 0x40; cmp rax, reg64; jb -12` (12 bytes). | ||
| 304 | // Zeroes the entire writable span in one memset instead of raising #UD + VirtualQuery per 64-byte line. | ||
| 305 | inline ClzeroLoopResult try_clzero_loop(const uint8_t* code, std::size_t avail, CONTEXT* c, EXCEPTION_RECORD* fault) { | ||
| 306 | if (avail < 12) return ClzeroLoopResult::no_match; | ||
| 307 | if (code[0] != 0x0F || code[1] != 0x01 || code[2] != 0xFC) return ClzeroLoopResult::no_match; | ||
| 308 | if (code[3] != 0x48 || code[4] != 0x83 || code[5] != 0xC0 || code[6] != 0x40) return ClzeroLoopResult::no_match; | ||
| 309 | if ((code[7] != 0x48 && code[7] != 0x4C) || code[8] != 0x39 || (code[9] & 0xC7) != 0xC0) | ||
| 310 | return ClzeroLoopResult::no_match; | ||
| 311 | if (code[10] != 0x72 || code[11] != 0xF4) return ClzeroLoopResult::no_match; | ||
| 312 | |||
| 313 | const int limit_reg = ((code[9] >> 3) & 7) | ((code[7] & 4) << 1); | ||
| 314 | if (limit_reg == 0 || limit_reg == 4) return ClzeroLoopResult::no_match; | ||
| 315 | |||
| 316 | const uint64_t start = c->Rax; | ||
| 317 | const uint64_t limit = gpr_read(c, limit_reg); | ||
| 318 | if ((start & 63) != 0 || limit <= start + 64) return ClzeroLoopResult::no_match; | ||
| 319 | |||
| 320 | uint64_t total = (limit - start + 63) & ~uint64_t(63); | ||
| 321 | constexpr uint64_t kMaxBatch = uint64_t(64) << 20; | ||
| 322 | if (total > kMaxBatch) total = kMaxBatch; | ||
| 323 | const uint64_t end = start + total; | ||
| 324 | |||
| 325 | for (uint64_t cur = start; cur < end;) { | ||
| 326 | const DWORD err = writable(cur); | ||
| 327 | if (err) { | ||
| 328 | if (cur > start) { | ||
| 329 | std::memset(reinterpret_cast<void*>(start), 0, std::size_t(cur - start)); | ||
| 330 | c->Rax = cur; | ||
| 331 | apply_cmp_flags(c, cur, limit); | ||
| 332 | } | ||
| 333 | if (fault) { | ||
| 334 | std::memset(fault, 0, sizeof *fault); | ||
| 335 | fault->ExceptionCode = err; | ||
| 336 | fault->NumberParameters = 2; | ||
| 337 | fault->ExceptionInformation[0] = 1; | ||
| 338 | fault->ExceptionInformation[1] = ULONG_PTR(cur); | ||
| 339 | } | ||
| 340 | return ClzeroLoopResult::faulted; | ||
| 341 | } | ||
| 342 | const uint64_t next_page = (cur & ~uint64_t(0xFFF)) + 0x1000; | ||
| 343 | cur = next_page < end ? next_page : end; | ||
| 344 | } | ||
| 345 | |||
| 346 | std::memset(reinterpret_cast<void*>(start), 0, std::size_t(total)); | ||
| 347 | c->Rax = end; | ||
| 348 | apply_cmp_flags(c, end, limit); | ||
| 349 | if (end >= limit) c->Rip += 12; | ||
| 350 | return ClzeroLoopResult::ok; | ||
| 351 | } | ||
| 352 | |||
| 275 | inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { | 353 | inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { |
| 276 | if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; | 354 | if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; |
| 277 | CONTEXT* c = info->ContextRecord; | 355 | CONTEXT* c = info->ContextRecord; |
| @@ -281,6 +359,25 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { | |||
| 281 | const Decoded d = decode(code, avail); | 359 | const Decoded d = decode(code, avail); |
| 282 | if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; | 360 | if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; |
| 283 | EXCEPTION_RECORD fault; | 361 | EXCEPTION_RECORD fault; |
| 362 | if (d.op == Op::clzero && !d.addr32 && d.length == 3) { | ||
| 363 | const uint64_t fault_rip = c->Rip; | ||
| 364 | const ClzeroLoopResult lr = try_clzero_loop(code, avail, c, &fault); | ||
| 365 | if (lr == ClzeroLoopResult::ok) { | ||
| 366 | if (count(d.op).fetch_add(1, std::memory_order_relaxed) == 0) | ||
| 367 | std::fprintf(stderr, "[rt] cpu: this CPU has no %s; emulating it (first at %p)\n", name(d.op), | ||
| 368 | reinterpret_cast<void*>(fault_rip)); | ||
| 369 | return EXCEPTION_CONTINUE_EXECUTION; | ||
| 370 | } | ||
| 371 | if (lr == ClzeroLoopResult::faulted) { | ||
| 372 | EXCEPTION_RECORD* r = info->ExceptionRecord; | ||
| 373 | r->ExceptionCode = fault.ExceptionCode; | ||
| 374 | r->ExceptionFlags = 0; | ||
| 375 | r->NumberParameters = fault.NumberParameters; | ||
| 376 | r->ExceptionInformation[0] = fault.ExceptionInformation[0]; | ||
| 377 | r->ExceptionInformation[1] = fault.ExceptionInformation[1]; | ||
| 378 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 379 | } | ||
| 380 | } | ||
| 284 | if (!apply(d, c, &fault)) { | 381 | if (!apply(d, c, &fault)) { |
| 285 | // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers | 382 | // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers |
| 286 | // see it instead of the #UD (RIP still points at the instruction). | 383 | // see it instead of the #UD (RIP still points at the instruction). |
diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h index fa9c20df1..afeaf191e 100644 --- a/runtime/src/frame_pacer.h +++ b/runtime/src/frame_pacer.h | |||
| @@ -30,14 +30,17 @@ | |||
| 30 | // suspended) is unchanged. | 30 | // suspended) is unchanged. |
| 31 | 31 | ||
| 32 | #include <algorithm> | 32 | #include <algorithm> |
| 33 | #include <array> | ||
| 33 | #include <atomic> | 34 | #include <atomic> |
| 34 | #include <chrono> | 35 | #include <chrono> |
| 35 | #include <condition_variable> | 36 | #include <condition_variable> |
| 37 | #include <cstddef> | ||
| 36 | #include <cstdint> | 38 | #include <cstdint> |
| 37 | #include <deque> | 39 | #include <deque> |
| 38 | #include <functional> | 40 | #include <functional> |
| 39 | #include <limits> | 41 | #include <limits> |
| 40 | #include <mutex> | 42 | #include <mutex> |
| 43 | #include <vector> | ||
| 41 | 44 | ||
| 42 | namespace leonida { | 45 | namespace leonida { |
| 43 | 46 | ||
| @@ -102,8 +105,14 @@ private: | |||
| 102 | std::function<void()> wake_; | 105 | std::function<void()> wake_; |
| 103 | }; | 106 | }; |
| 104 | 107 | ||
| 105 | // Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. | 108 | // Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. Frame event |
| 109 | // kinds (0: origin, 1: vblank, 2: flip) and wait flags. | ||
| 106 | inline constexpr std::uint32_t frame_event_origin = 0; | 110 | inline constexpr std::uint32_t frame_event_origin = 0; |
| 111 | inline constexpr std::uint32_t frame_event_vblank = 1; | ||
| 112 | inline constexpr std::uint32_t frame_event_flip = 2; | ||
| 113 | inline constexpr std::uint32_t frame_event_count = 3; | ||
| 114 | // Issue a consecutive frame token even when WaitFrameEventX(origin, ...) times out (returns S_FALSE). | ||
| 115 | inline constexpr std::uint32_t frame_wait_flag_token_on_timeout = 2; | ||
| 107 | // Statistics types (bit mask). Interval and render entries are never produced here. | 116 | // Statistics types (bit mask). Interval and render entries are never produced here. |
| 108 | inline constexpr std::uint32_t stat_frame_interval = 0x01; | 117 | inline constexpr std::uint32_t stat_frame_interval = 0x01; |
| 109 | inline constexpr std::uint32_t stat_frame_event = 0x02; | 118 | inline constexpr std::uint32_t stat_frame_event = 0x02; |
| @@ -143,6 +152,25 @@ struct FrameStatistic { | |||
| 143 | float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) | 152 | float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) |
| 144 | }; | 153 | }; |
| 145 | 154 | ||
| 155 | // Fixed-capacity ring buffer size for recent frame-time and origin-to-present latency samples (BL-6). | ||
| 156 | inline constexpr std::size_t frame_pacing_window = 1024; | ||
| 157 | |||
| 158 | // Summary over the most recent `frame_pacing_window` presented frames (p50/p95/p99 and mean drift against target). | ||
| 159 | struct FramePacingSummary { | ||
| 160 | std::uint64_t frames = 0; // total presented frames recorded | ||
| 161 | std::uint64_t samples = 0; // present-to-present intervals in the ring buffer (<= frame_pacing_window) | ||
| 162 | std::uint32_t target_interval_us = 0; // active target interval in us (0 when unpaced or uncapped) | ||
| 163 | double mean_us = 0.0; // mean present-to-present interval over `samples` | ||
| 164 | double drift_us = 0.0; // mean_us - target_interval_us (0 when unpaced/uncapped or samples == 0) | ||
| 165 | std::uint64_t p50_us = 0; // nearest-rank 50th percentile frame interval in us | ||
| 166 | std::uint64_t p95_us = 0; // nearest-rank 95th percentile frame interval in us | ||
| 167 | std::uint64_t p99_us = 0; // nearest-rank 99th percentile frame interval in us | ||
| 168 | std::uint64_t latency_samples = 0; // origin-to-present latency samples in the ring buffer | ||
| 169 | std::uint64_t latency_p50_us = 0; // nearest-rank 50th percentile origin-to-present latency in us | ||
| 170 | std::uint64_t latency_p95_us = 0; // nearest-rank 95th percentile origin-to-present latency in us | ||
| 171 | std::uint64_t latency_p99_us = 0; // nearest-rank 99th percentile origin-to-present latency in us | ||
| 172 | }; | ||
| 173 | |||
| 146 | class FramePacer { | 174 | class FramePacer { |
| 147 | public: | 175 | public: |
| 148 | explicit FramePacer(FrameClock& clock) : clock_(clock) { | 176 | explicit FramePacer(FrameClock& clock) : clock_(clock) { |
| @@ -177,38 +205,42 @@ public: | |||
| 177 | latency_ = std::max(latency, 1u); | 205 | latency_ = std::max(latency, 1u); |
| 178 | epoch_us_ = clock_.now_us(); | 206 | epoch_us_ = clock_.now_us(); |
| 179 | interval_set_ = true; | 207 | interval_set_ = true; |
| 180 | offset_us_ = std::min(offset_us_, period_us - 1); | 208 | for (std::uint32_t k = 0; k < frame_event_count; ++k) { |
| 181 | last_origin_ = 0; // origin 0 is the epoch itself, which has passed | 209 | event_offset_us_[k] = std::min(event_offset_us_[k], period_us - 1); |
| 210 | last_event_tick_[k] = 0; // tick 0 is the epoch itself, which has passed | ||
| 211 | } | ||
| 182 | cv_.notify_all(); | 212 | cv_.notify_all(); |
| 183 | return pacer_hr::ok; | 213 | return pacer_hr::ok; |
| 184 | } | 214 | } |
| 185 | 215 | ||
| 186 | // ScheduleFrameEventX(event, offset, ..., flags). Only the origin event exists here. | 216 | // ScheduleFrameEventX(event, offset, ..., flags). Supports origin (0), vblank (1), and flip (2). |
| 187 | std::int32_t schedule_frame_event(std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags) { | 217 | std::int32_t schedule_frame_event(std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags) { |
| 188 | (void)flags; | 218 | (void)flags; |
| 189 | if (event != frame_event_origin) return pacer_hr::invalid_arg; | 219 | if (event >= frame_event_count) return pacer_hr::invalid_arg; |
| 190 | std::lock_guard guard(mutex_); | 220 | std::lock_guard guard(mutex_); |
| 191 | if (suspended_ || !interval_set_) return pacer_hr::invalid_state; | 221 | if (suspended_ || !interval_set_) return pacer_hr::invalid_state; |
| 192 | if (offset_us >= period_us_) return pacer_hr::invalid_arg; | 222 | if (offset_us >= period_us_) return pacer_hr::invalid_arg; |
| 193 | offset_us_ = offset_us; | 223 | event_offset_us_[event] = offset_us; |
| 194 | armed_ = true; | 224 | event_armed_[event] = true; |
| 195 | // The first origin is the next one that has not come yet: origin n is due at epoch + n * period + offset. | 225 | // The first event is the next one that has not come yet: tick n is due at epoch + n * period + offset. |
| 196 | const std::uint64_t now = clock_.now_us(); | 226 | const std::uint64_t now = clock_.now_us(); |
| 197 | last_origin_ = now >= epoch_us_ + offset_us_ ? std::int64_t((now - epoch_us_ - offset_us_) / period_us_) : 0; | 227 | last_event_tick_[event] = |
| 228 | now >= epoch_us_ + offset_us ? std::int64_t((now - epoch_us_ - offset_us) / period_us_) : 0; | ||
| 198 | cv_.notify_all(); | 229 | cv_.notify_all(); |
| 199 | return pacer_hr::ok; | 230 | return pacer_hr::ok; |
| 200 | } | 231 | } |
| 201 | 232 | ||
| 202 | // WaitFrameEventX(event, timeout, ..., flags, &token). Blocks until the next origin, and while `latency` frames | 233 | // WaitFrameEventX(event, timeout, ..., flags, &token). Origin waits block until the next origin tick and while |
| 203 | // are in flight. pacer_hr::timeout when `timeout_ms` passes first (infinite_timeout_ms: never); the token is left | 234 | // `latency` frames are in flight, issuing a consecutive token on success (or on timeout with |
| 204 | // alone then. invalid_state when nothing is registered, the pacer is suspended, or one of those happens while waiting. | 235 | // frame_wait_flag_token_on_timeout, returning S_FALSE). Vblank/flip waits pace independently per event kind and |
| 236 | // leave `*token` untouched. | ||
| 205 | std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, | 237 | std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, |
| 206 | std::uint64_t* token) { | 238 | std::uint64_t* token) { |
| 207 | (void)flags; | 239 | if (event >= frame_event_count) return pacer_hr::invalid_arg; |
| 208 | if (event != frame_event_origin || !token) return pacer_hr::invalid_arg; | 240 | if (event == frame_event_origin && !token) return pacer_hr::invalid_arg; |
| 209 | std::unique_lock lock(mutex_); | 241 | std::unique_lock lock(mutex_); |
| 210 | ++waiters_; | 242 | ++waiters_; |
| 211 | const std::int32_t result = wait_locked(lock, timeout_ms, token); | 243 | const std::int32_t result = wait_locked(lock, event, timeout_ms, flags, token); |
| 212 | if (--waiters_ == 0) cv_.notify_all(); | 244 | if (--waiters_ == 0) cv_.notify_all(); |
| 213 | return result; | 245 | return result; |
| 214 | } | 246 | } |
| @@ -301,8 +333,9 @@ public: | |||
| 301 | std::lock_guard guard(mutex_); | 333 | std::lock_guard guard(mutex_); |
| 302 | const std::uint64_t now = clock_.now_us(); | 334 | const std::uint64_t now = clock_.now_us(); |
| 303 | retire_locked(now); | 335 | retire_locked(now); |
| 336 | record_present_timing_locked(now, token); | ||
| 304 | last_presented_ = std::max(last_presented_, token); | 337 | last_presented_ = std::max(last_presented_, token); |
| 305 | if (!interval_set_ || !armed_ || uncapped_) { // not paced or uncapped: shows at once | 338 | if (!interval_set_ || !any_armed_locked() || uncapped_) { // not paced or uncapped: shows at once |
| 306 | for (Record& r : records_) | 339 | for (Record& r : records_) |
| 307 | if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } | 340 | if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } |
| 308 | return; | 341 | return; |
| @@ -330,8 +363,9 @@ public: | |||
| 330 | // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. | 363 | // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. |
| 331 | void note_untokened_present() { | 364 | void note_untokened_present() { |
| 332 | std::lock_guard guard(mutex_); | 365 | std::lock_guard guard(mutex_); |
| 333 | if (!interval_set_ || !armed_ || uncapped_) return; | ||
| 334 | const std::uint64_t now = clock_.now_us(); | 366 | const std::uint64_t now = clock_.now_us(); |
| 367 | record_present_timing_locked(now, 0); | ||
| 368 | if (!interval_set_ || !any_armed_locked() || uncapped_) return; | ||
| 335 | retire_locked(now); | 369 | retire_locked(now); |
| 336 | const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; | 370 | const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; |
| 337 | std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; | 371 | std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; |
| @@ -344,7 +378,9 @@ public: | |||
| 344 | void suspend() { | 378 | void suspend() { |
| 345 | std::lock_guard guard(mutex_); | 379 | std::lock_guard guard(mutex_); |
| 346 | suspended_ = true; | 380 | suspended_ = true; |
| 347 | interval_set_ = armed_ = false; | 381 | interval_set_ = false; |
| 382 | has_last_present_ = false; // do not count the suspended pause as a frame interval after resume | ||
| 383 | for (bool& a : event_armed_) a = false; | ||
| 348 | pending_.clear(); | 384 | pending_.clear(); |
| 349 | cv_.notify_all(); | 385 | cv_.notify_all(); |
| 350 | } | 386 | } |
| @@ -352,7 +388,8 @@ public: | |||
| 352 | void resume() { | 388 | void resume() { |
| 353 | std::lock_guard guard(mutex_); | 389 | std::lock_guard guard(mutex_); |
| 354 | suspended_ = false; | 390 | suspended_ = false; |
| 355 | interval_set_ = armed_ = false; | 391 | interval_set_ = false; |
| 392 | for (bool& a : event_armed_) a = false; | ||
| 356 | cv_.notify_all(); | 393 | cv_.notify_all(); |
| 357 | } | 394 | } |
| 358 | 395 | ||
| @@ -366,13 +403,54 @@ public: | |||
| 366 | // Frames that were flipped mid-scan because of ImmediateThresholdPercent. | 403 | // Frames that were flipped mid-scan because of ImmediateThresholdPercent. |
| 367 | std::uint64_t immediate_presents() const { std::lock_guard guard(mutex_); return immediate_presents_; } | 404 | std::uint64_t immediate_presents() const { std::lock_guard guard(mutex_); return immediate_presents_; } |
| 368 | std::uint32_t period_us() const { std::lock_guard guard(mutex_); return period_us_; } | 405 | std::uint32_t period_us() const { std::lock_guard guard(mutex_); return period_us_; } |
| 369 | bool registered() const { std::lock_guard guard(mutex_); return interval_set_ && armed_; } | 406 | bool registered() const { std::lock_guard guard(mutex_); return interval_set_ && any_armed_locked(); } |
| 370 | 407 | ||
| 371 | // The fps cap off (LEONIDA_PRESENT_UNCAP; see the top comment): waits never block and presents count as shown | 408 | // The fps cap off (LEONIDA_PRESENT_UNCAP; see the top comment): waits never block and presents count as shown |
| 372 | // at once. Registration and suspension keep meaning what they did; the flag survives suspend/resume. | 409 | // at once. Registration and suspension keep meaning what they did; the flag survives suspend/resume. |
| 373 | void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; } | 410 | void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; } |
| 374 | bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; } | 411 | bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; } |
| 375 | 412 | ||
| 413 | // Frame-time percentiles, mean drift against the active target interval, and origin-to-present latency over | ||
| 414 | // the last `frame_pacing_window` presented frames (BL-6). | ||
| 415 | FramePacingSummary pacing_summary() const { | ||
| 416 | FramePacingSummary out; | ||
| 417 | std::vector<std::uint64_t> intervals; | ||
| 418 | std::vector<std::uint64_t> latencies; | ||
| 419 | { | ||
| 420 | std::lock_guard guard(mutex_); | ||
| 421 | out.frames = presents_recorded_; | ||
| 422 | out.target_interval_us = (interval_set_ && !uncapped_) ? period_us_ : 0u; | ||
| 423 | intervals.reserve(interval_count_); | ||
| 424 | for (std::size_t i = 0; i < interval_count_; ++i) intervals.push_back(interval_ring_[i]); | ||
| 425 | latencies.reserve(latency_count_); | ||
| 426 | for (std::size_t i = 0; i < latency_count_; ++i) latencies.push_back(latency_ring_[i]); | ||
| 427 | } | ||
| 428 | auto percentile = [](const std::vector<std::uint64_t>& sorted, std::size_t pct) -> std::uint64_t { | ||
| 429 | if (sorted.empty()) return 0; | ||
| 430 | const std::size_t idx = (pct * sorted.size() + 99) / 100 - 1; | ||
| 431 | return sorted[std::min(idx, sorted.size() - 1)]; | ||
| 432 | }; | ||
| 433 | if (!intervals.empty()) { | ||
| 434 | out.samples = intervals.size(); | ||
| 435 | double sum = 0.0; | ||
| 436 | for (std::uint64_t v : intervals) sum += double(v); | ||
| 437 | out.mean_us = sum / double(intervals.size()); | ||
| 438 | if (out.target_interval_us != 0) out.drift_us = out.mean_us - double(out.target_interval_us); | ||
| 439 | std::sort(intervals.begin(), intervals.end()); | ||
| 440 | out.p50_us = percentile(intervals, 50); | ||
| 441 | out.p95_us = percentile(intervals, 95); | ||
| 442 | out.p99_us = percentile(intervals, 99); | ||
| 443 | } | ||
| 444 | if (!latencies.empty()) { | ||
| 445 | out.latency_samples = latencies.size(); | ||
| 446 | std::sort(latencies.begin(), latencies.end()); | ||
| 447 | out.latency_p50_us = percentile(latencies, 50); | ||
| 448 | out.latency_p95_us = percentile(latencies, 95); | ||
| 449 | out.latency_p99_us = percentile(latencies, 99); | ||
| 450 | } | ||
| 451 | return out; | ||
| 452 | } | ||
| 453 | |||
| 376 | private: | 454 | private: |
| 377 | struct Pending { | 455 | struct Pending { |
| 378 | std::uint64_t token; | 456 | std::uint64_t token; |
| @@ -386,6 +464,29 @@ private: | |||
| 386 | bool presented = false, displayed = false; | 464 | bool presented = false, displayed = false; |
| 387 | }; | 465 | }; |
| 388 | 466 | ||
| 467 | void record_present_timing_locked(std::uint64_t now, std::uint64_t token) { | ||
| 468 | ++presents_recorded_; | ||
| 469 | if (has_last_present_ && now >= last_present_us_) { | ||
| 470 | interval_ring_[interval_head_] = now - last_present_us_; | ||
| 471 | interval_head_ = (interval_head_ + 1) % frame_pacing_window; | ||
| 472 | if (interval_count_ < frame_pacing_window) ++interval_count_; | ||
| 473 | } | ||
| 474 | has_last_present_ = true; | ||
| 475 | last_present_us_ = now; | ||
| 476 | if (token != 0) { | ||
| 477 | for (const Record& r : records_) { | ||
| 478 | if (r.token == token) { | ||
| 479 | if (now >= r.origin_us) { | ||
| 480 | latency_ring_[latency_head_] = now - r.origin_us; | ||
| 481 | latency_head_ = (latency_head_ + 1) % frame_pacing_window; | ||
| 482 | if (latency_count_ < frame_pacing_window) ++latency_count_; | ||
| 483 | } | ||
| 484 | break; | ||
| 485 | } | ||
| 486 | } | ||
| 487 | } | ||
| 488 | } | ||
| 489 | |||
| 389 | // Frames whose vblank has come are shown. | 490 | // Frames whose vblank has come are shown. |
| 390 | void retire_locked(std::uint64_t now) { | 491 | void retire_locked(std::uint64_t now) { |
| 391 | while (!pending_.empty() && pending_.front().flip_us <= now) { | 492 | while (!pending_.empty() && pending_.front().flip_us <= now) { |
| @@ -399,45 +500,67 @@ private: | |||
| 399 | } | 500 | } |
| 400 | } | 501 | } |
| 401 | 502 | ||
| 402 | std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t timeout_ms, std::uint64_t* token) { | 503 | bool any_armed_locked() const { |
| 504 | return event_armed_[0] || event_armed_[1] || event_armed_[2]; | ||
| 505 | } | ||
| 506 | |||
| 507 | std::uint64_t issue_token_locked(std::uint64_t origin_us, std::uint64_t due_us) { | ||
| 508 | const std::uint64_t tok = ++issued_; | ||
| 509 | Record record; | ||
| 510 | record.token = tok; | ||
| 511 | record.origin_us = origin_us; | ||
| 512 | record.due_us = due_us; | ||
| 513 | records_.push_back(record); | ||
| 514 | if (records_.size() > 64) records_.pop_front(); | ||
| 515 | return tok; | ||
| 516 | } | ||
| 517 | |||
| 518 | std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t event, std::uint32_t timeout_ms, | ||
| 519 | std::uint32_t flags, std::uint64_t* token) { | ||
| 520 | const bool is_origin = (event == frame_event_origin); | ||
| 521 | const bool token_on_timeout = (flags & frame_wait_flag_token_on_timeout) != 0; | ||
| 403 | const std::uint64_t start = clock_.now_us(); | 522 | const std::uint64_t start = clock_.now_us(); |
| 404 | const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline | 523 | const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline |
| 405 | : start + std::uint64_t(timeout_ms) * 1000; | 524 | : start + std::uint64_t(timeout_ms) * 1000; |
| 406 | for (;;) { | 525 | for (;;) { |
| 407 | if (shutdown_ || suspended_ || !interval_set_ || !armed_) return pacer_hr::invalid_state; | 526 | if (shutdown_ || suspended_ || !interval_set_) return pacer_hr::invalid_state; |
| 527 | if (is_origin ? !event_armed_[frame_event_origin] | ||
| 528 | : (!event_armed_[event] && !event_armed_[frame_event_origin])) { | ||
| 529 | return pacer_hr::invalid_state; | ||
| 530 | } | ||
| 408 | const std::uint64_t now = clock_.now_us(); | 531 | const std::uint64_t now = clock_.now_us(); |
| 409 | retire_locked(now); | 532 | retire_locked(now); |
| 410 | if (uncapped_) { // no vblank grid and no latency throttle: a token at once, due now | 533 | if (uncapped_) { // no vblank grid and no latency throttle |
| 411 | *token = ++issued_; | 534 | if (is_origin) *token = issue_token_locked(now, now); |
| 412 | Record record; | ||
| 413 | record.token = *token; | ||
| 414 | record.origin_us = now; | ||
| 415 | record.due_us = now; | ||
| 416 | records_.push_back(record); | ||
| 417 | if (records_.size() > 64) records_.pop_front(); | ||
| 418 | return pacer_hr::ok; | 535 | return pacer_hr::ok; |
| 419 | } | 536 | } |
| 420 | const std::uint64_t first = epoch_us_ + offset_us_; // origin 0 | 537 | const std::uint32_t offset = event_offset_us_[event]; |
| 421 | const std::int64_t next = last_origin_ + 1; | 538 | const std::uint64_t first = epoch_us_ + offset; // tick 0 |
| 539 | const std::int64_t next = last_event_tick_[event] + 1; | ||
| 422 | const std::uint64_t next_us = first + std::uint64_t(next) * period_us_; | 540 | const std::uint64_t next_us = first + std::uint64_t(next) * period_us_; |
| 423 | std::uint64_t wake = next_us; | 541 | std::uint64_t wake = next_us; |
| 424 | if (now >= next_us) { | 542 | if (now >= next_us) { |
| 425 | if (pending_.size() < latency_) { | 543 | if (!is_origin || pending_.size() < latency_) { |
| 426 | const std::int64_t newest = std::int64_t((now - first) / period_us_); | 544 | const std::int64_t newest = std::int64_t((now - first) / period_us_); |
| 427 | const std::int64_t origin = std::max(next, newest); | 545 | const std::int64_t tick = std::max(next, newest); |
| 428 | last_origin_ = origin; | 546 | last_event_tick_[event] = tick; |
| 429 | *token = ++issued_; | 547 | if (is_origin) { |
| 430 | Record record; | 548 | const std::uint64_t origin_us = first + std::uint64_t(tick) * period_us_; |
| 431 | record.token = *token; | 549 | const std::uint64_t due_us = origin_us - offset + period_us_; |
| 432 | record.origin_us = first + std::uint64_t(origin) * period_us_; | 550 | *token = issue_token_locked(origin_us, due_us); |
| 433 | record.due_us = record.origin_us - offset_us_ + period_us_; | 551 | } |
| 434 | records_.push_back(record); | ||
| 435 | if (records_.size() > 64) records_.pop_front(); | ||
| 436 | return pacer_hr::ok; | 552 | return pacer_hr::ok; |
| 437 | } | 553 | } |
| 438 | wake = pending_.front().flip_us; // blocked by the latency: until the oldest frame is shown | 554 | wake = pending_.front().flip_us; // blocked by the latency: until the oldest frame is shown |
| 439 | } | 555 | } |
| 440 | if (give_up != no_deadline && now >= give_up) return pacer_hr::timeout; | 556 | if (give_up != no_deadline && now >= give_up) { |
| 557 | if (is_origin && token_on_timeout) { | ||
| 558 | // Frame started early on timeout: issue a consecutive token without consuming the tick. | ||
| 559 | *token = issue_token_locked(now, next_us - offset + period_us_); | ||
| 560 | return pacer_hr::false_; | ||
| 561 | } | ||
| 562 | return token_on_timeout ? pacer_hr::false_ : pacer_hr::timeout; | ||
| 563 | } | ||
| 441 | clock_.wait(lock, cv_, give_up == no_deadline ? wake : std::min(wake, give_up)); | 564 | clock_.wait(lock, cv_, give_up == no_deadline ? wake : std::min(wake, give_up)); |
| 442 | } | 565 | } |
| 443 | } | 566 | } |
| @@ -450,16 +573,25 @@ private: | |||
| 450 | 573 | ||
| 451 | bool suspended_ = false; | 574 | bool suspended_ = false; |
| 452 | bool interval_set_ = false; | 575 | bool interval_set_ = false; |
| 453 | bool armed_ = false; | 576 | bool event_armed_[frame_event_count] = {false, false, false}; |
| 454 | bool uncapped_ = false; | 577 | bool uncapped_ = false; |
| 455 | std::uint32_t period_us_ = 0; | 578 | std::uint32_t period_us_ = 0; |
| 456 | std::uint32_t latency_ = 1; | 579 | std::uint32_t latency_ = 1; |
| 457 | std::uint32_t offset_us_ = 0; | 580 | std::uint32_t event_offset_us_[frame_event_count] = {0, 0, 0}; |
| 458 | std::uint64_t epoch_us_ = 0; | 581 | std::uint64_t epoch_us_ = 0; |
| 459 | std::int64_t last_origin_ = 0; // origin 0 is the epoch itself, which has passed | 582 | std::int64_t last_event_tick_[frame_event_count] = {0, 0, 0}; // tick 0 is the epoch itself, which has passed |
| 460 | std::uint64_t issued_ = 0; | 583 | std::uint64_t issued_ = 0; |
| 461 | std::uint64_t last_presented_ = 0; | 584 | std::uint64_t last_presented_ = 0; |
| 462 | std::uint64_t immediate_presents_ = 0; | 585 | std::uint64_t immediate_presents_ = 0; |
| 586 | std::uint64_t presents_recorded_ = 0; | ||
| 587 | bool has_last_present_ = false; | ||
| 588 | std::uint64_t last_present_us_ = 0; | ||
| 589 | std::array<std::uint64_t, frame_pacing_window> interval_ring_{}; | ||
| 590 | std::size_t interval_head_ = 0; | ||
| 591 | std::size_t interval_count_ = 0; | ||
| 592 | std::array<std::uint64_t, frame_pacing_window> latency_ring_{}; | ||
| 593 | std::size_t latency_head_ = 0; | ||
| 594 | std::size_t latency_count_ = 0; | ||
| 463 | std::deque<Pending> pending_; | 595 | std::deque<Pending> pending_; |
| 464 | std::deque<Record> records_; | 596 | std::deque<Record> records_; |
| 465 | }; | 597 | }; |
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index b225cddef..a4a9b4448 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h | |||
| @@ -631,8 +631,9 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_ | |||
| 631 | if (sampler.unnormalized) { | 631 | if (sampler.unnormalized) { |
| 632 | info.unnormalizedCoordinates = VK_TRUE; | 632 | info.unnormalizedCoordinates = VK_TRUE; |
| 633 | // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a | 633 | // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a |
| 634 | // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag. | 634 | // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag; |
| 635 | // The S# allows any address mode with FORCE_UNNORMALIZED, and WRAP is its default (word 0 = 0). | 635 | // -01074: mipLodBias must be zero. The S# allows any address mode or LOD bias with FORCE_UNNORMALIZED, and |
| 636 | // WRAP is its default (word 0 = 0). | ||
| 636 | const auto clamp_or_border = [](VkSamplerAddressMode m) { | 637 | const auto clamp_or_border = [](VkSamplerAddressMode m) { |
| 637 | return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; | 638 | return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; |
| 638 | }; | 639 | }; |
| @@ -640,6 +641,7 @@ inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_ | |||
| 640 | info.addressModeV = clamp_or_border(info.addressModeV); | 641 | info.addressModeV = clamp_or_border(info.addressModeV); |
| 641 | info.minFilter = info.magFilter; | 642 | info.minFilter = info.magFilter; |
| 642 | info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; | 643 | info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; |
| 644 | info.mipLodBias = 0.0f; | ||
| 643 | info.minLod = info.maxLod = 0.0f; | 645 | info.minLod = info.maxLod = 0.0f; |
| 644 | info.anisotropyEnable = VK_FALSE; | 646 | info.anisotropyEnable = VK_FALSE; |
| 645 | info.maxAnisotropy = 1.0f; | 647 | info.maxAnisotropy = 1.0f; |
diff --git a/runtime/src/mods.h b/runtime/src/mods.h index 10155bf19..bd635e9a0 100644 --- a/runtime/src/mods.h +++ b/runtime/src/mods.h | |||
| @@ -78,8 +78,8 @@ struct LoadResult { | |||
| 78 | // "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value. | 78 | // "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value. |
| 79 | inline bool parse_model_id(const std::string& text, uint32_t& out) { | 79 | inline bool parse_model_id(const std::string& text, uint32_t& out) { |
| 80 | if (text.empty()) return false; | 80 | if (text.empty()) return false; |
| 81 | if (text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { | 81 | if (text.size() >= 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { |
| 82 | if (text.size() > 10) return false; | 82 | if (text.size() == 2 || text.size() > 10) return false; |
| 83 | uint32_t v = 0; | 83 | uint32_t v = 0; |
| 84 | for (std::size_t i = 2; i < text.size(); ++i) { | 84 | for (std::size_t i = 2; i < text.size(); ++i) { |
| 85 | const char c = text[i]; | 85 | const char c = text[i]; |
diff --git a/runtime/src/retire_tickets.h b/runtime/src/retire_tickets.h index a48302859..675460cac 100644 --- a/runtime/src/retire_tickets.h +++ b/runtime/src/retire_tickets.h | |||
| @@ -24,7 +24,7 @@ public: | |||
| 24 | while (!pending_.empty()) { | 24 | while (!pending_.empty()) { |
| 25 | const Entry& front = pending_.front(); | 25 | const Entry& front = pending_.front(); |
| 26 | if (!front.idle && !query(front.semaphore, front.value)) break; | 26 | if (!front.idle && !query(front.semaphore, front.value)) break; |
| 27 | completed_ = front.ticket; | 27 | if (front.ticket > completed_) completed_ = front.ticket; |
| 28 | pending_.pop_front(); | 28 | pending_.pop_front(); |
| 29 | } | 29 | } |
| 30 | return completed_; | 30 | return completed_; |
| @@ -34,8 +34,18 @@ public: | |||
| 34 | // that must have them done (and may not hold the lock that guards this object while it waits) waits for. | 34 | // that must have them done (and may not hold the lock that guards this object while it waits) waits for. |
| 35 | std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const { | 35 | std::vector<std::pair<Semaphore, std::uint64_t>> pending_through(std::uint64_t ticket) const { |
| 36 | std::vector<std::pair<Semaphore, std::uint64_t>> out; | 36 | std::vector<std::pair<Semaphore, std::uint64_t>> out; |
| 37 | for (const Entry& entry : pending_) | 37 | for (const Entry& entry : pending_) { |
| 38 | if (entry.ticket <= ticket && !entry.idle) out.emplace_back(entry.semaphore, entry.value); | 38 | if (entry.ticket > ticket || entry.idle) continue; |
| 39 | bool merged = false; | ||
| 40 | for (auto& [sem, val] : out) { | ||
| 41 | if (sem == entry.semaphore) { | ||
| 42 | if (entry.value > val) val = entry.value; | ||
| 43 | merged = true; | ||
| 44 | break; | ||
| 45 | } | ||
| 46 | } | ||
| 47 | if (!merged) out.emplace_back(entry.semaphore, entry.value); | ||
| 48 | } | ||
| 39 | return out; | 49 | return out; |
| 40 | } | 50 | } |
| 41 | 51 | ||
diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 9f752317e..596ad0ae9 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h | |||
| @@ -246,7 +246,7 @@ inline ZlibError inflate_codes(BitReader& in, std::vector<std::uint8_t>& out, co | |||
| 246 | if (d < 0 || d >= 30) return ZlibError::data; | 246 | if (d < 0 || d >= 30) return ZlibError::data; |
| 247 | const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); | 247 | const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); |
| 248 | if (in.failed() || distance > out.size()) return ZlibError::data; | 248 | if (in.failed() || distance > out.size()) return ZlibError::data; |
| 249 | if (out.size() + length > limit) return ZlibError::limit; | 249 | if (out.size() > limit || length > limit - out.size()) return ZlibError::limit; |
| 250 | const std::size_t from = out.size() - distance; | 250 | const std::size_t from = out.size() - distance; |
| 251 | for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); | 251 | for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); |
| 252 | } | 252 | } |
| @@ -284,7 +284,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 284 | if (!reader.byte(x)) return fail(ZlibError::data); | 284 | if (!reader.byte(x)) return fail(ZlibError::data); |
| 285 | const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); | 285 | const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); |
| 286 | if (length != (~complement & 0xffff)) return fail(ZlibError::data); | 286 | if (length != (~complement & 0xffff)) return fail(ZlibError::data); |
| 287 | if (out.size() + length > limit) return fail(ZlibError::limit); | 287 | if (out.size() > limit || length > limit - out.size()) return fail(ZlibError::limit); |
| 288 | for (unsigned i = 0; i < length; ++i) { | 288 | for (unsigned i = 0; i < length; ++i) { |
| 289 | std::uint8_t x; | 289 | std::uint8_t x; |
| 290 | if (!reader.byte(x)) return fail(ZlibError::data); | 290 | if (!reader.byte(x)) return fail(ZlibError::data); |
| @@ -349,7 +349,7 @@ inline bool zlib_inflate(std::span<const std::uint8_t> in, std::vector<std::uint | |||
| 349 | } | 349 | } |
| 350 | // Adler-32, big-endian, after the deflate data's last whole byte. | 350 | // Adler-32, big-endian, after the deflate data's last whole byte. |
| 351 | const std::size_t at = 2 + reader.position(); | 351 | const std::size_t at = 2 + reader.position(); |
| 352 | if (at + 4 > in.size()) return fail(ZlibError::data); | 352 | if (at > in.size() || in.size() - at < 4) return fail(ZlibError::data); |
| 353 | std::uint32_t a = 1, b = 0; | 353 | std::uint32_t a = 1, b = 0; |
| 354 | for (const std::uint8_t x : out) { | 354 | for (const std::uint8_t x : out) { |
| 355 | a = (a + x) % 65521; | 355 | a = (a + x) % 65521; |
| @@ -1045,9 +1045,20 @@ private: | |||
| 1045 | if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) { | 1045 | if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) { |
| 1046 | for (const auto& [key, val] : fh->object) { | 1046 | for (const auto& [key, val] : fh->object) { |
| 1047 | if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue; | 1047 | if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue; |
| 1048 | char* end = nullptr; | 1048 | std::uint64_t param = 0; |
| 1049 | const unsigned long param = std::strtoul(key.c_str(), &end, 10); | 1049 | bool ok = true; |
| 1050 | if (!end || *end != '\0') continue; | 1050 | for (const char c : key) { |
| 1051 | if (c < '0' || c > '9') { | ||
| 1052 | ok = false; | ||
| 1053 | break; | ||
| 1054 | } | ||
| 1055 | param = param * 10u + std::uint64_t(c - '0'); | ||
| 1056 | if (param > UINT32_MAX) { | ||
| 1057 | ok = false; | ||
| 1058 | break; | ||
| 1059 | } | ||
| 1060 | } | ||
| 1061 | if (!ok) continue; | ||
| 1051 | e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; | 1062 | e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; |
| 1052 | } | 1063 | } |
| 1053 | } | 1064 | } |
diff --git a/runtime/src/statistics_sum.comp b/runtime/src/statistics_sum.comp index c4960347c..c4a02a459 100644 --- a/runtime/src/statistics_sum.comp +++ b/runtime/src/statistics_sum.comp | |||
| @@ -2,9 +2,11 @@ | |||
| 2 | 2 | ||
| 3 | // Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one | 3 | // Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one |
| 4 | // invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order. | 4 | // invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order. |
| 5 | // `mesh` segments come from the pool a mesh draw can run in (D3D-291), which counts only clipping, fragment and | 5 | // `mesh` segments come from the pool a mesh draw can run in (D3D-291), which counts only the fragment and compute |
| 6 | // compute: they are copied to counters 5..8 of their record, so CSInvocations sits at 8 and the input-assembly, | 6 | // invocations: they are copied to counters 7 and 8 of their record, so PSInvocations takes the fragment one and |
| 7 | // vertex, geometry and tessellation counters (0..4, 8 and 9 of the D3D12 order) add nothing. | 7 | // CSInvocations the compute one, and every other counter adds nothing. |
| 8 | // The clipping invocations of a mesh segment come from the mesh-primitives count of that segment, copied to | ||
| 9 | // counter 5 (D3D-MESH-CLIPPING-COUNTER); without that count the field stays 0. | ||
| 8 | layout(local_size_x = 11) in; | 10 | layout(local_size_x = 11) in; |
| 9 | layout(set = 0, binding = 0, std430) buffer QueryResults { | 11 | layout(set = 0, binding = 0, std430) buffer QueryResults { |
| 10 | uvec2 total[11]; | 12 | uvec2 total[11]; |
| @@ -15,7 +17,7 @@ layout(push_constant) uniform ResolveRange { uint count; uint mesh; }; | |||
| 15 | void main() { | 17 | void main() { |
| 16 | const uint counter = gl_LocalInvocationID.x; | 18 | const uint counter = gl_LocalInvocationID.x; |
| 17 | uvec2 sum = total[counter]; | 19 | uvec2 sum = total[counter]; |
| 18 | const bool counted = mesh == 0u || (counter >= 5u && counter <= 7u) || counter == 10u; | 20 | const bool counted = mesh == 0u || counter == 5u || counter == 7u || counter == 10u; |
| 19 | const uint source = mesh != 0u && counter == 10u ? 8u : counter; | 21 | const uint source = mesh != 0u && counter == 10u ? 8u : counter; |
| 20 | for (uint i = 0; counted && i < count; ++i) { | 22 | for (uint i = 0; counted && i < count; ++i) { |
| 21 | uvec2 segment = segments[i * 11 + source]; | 23 | uvec2 segment = segments[i * 11 + source]; |
diff --git a/runtime/src/statistics_sum_spirv.h b/runtime/src/statistics_sum_spirv.h index 9c67f0429..a147cd4df 100644 --- a/runtime/src/statistics_sum_spirv.h +++ b/runtime/src/statistics_sum_spirv.h | |||
| @@ -7,7 +7,7 @@ namespace leonida { | |||
| 7 | // From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0, | 7 | // From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0, |
| 8 | // then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time. | 8 | // then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time. |
| 9 | inline constexpr std::uint32_t statistics_sum_spirv[] = { | 9 | inline constexpr std::uint32_t statistics_sum_spirv[] = { |
| 10 | 0x07230203, 0x00010000, 0x0008000b, 0x00000080, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, | 10 | 0x07230203, 0x00010000, 0x0008000b, 0x00000084, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, |
| 11 | 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, | 11 | 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, |
| 12 | 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004, | 12 | 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004, |
| 13 | 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b, | 13 | 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b, |
| @@ -16,7 +16,7 @@ inline constexpr std::uint32_t statistics_sum_spirv[] = { | |||
| 16 | 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021, | 16 | 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021, |
| 17 | 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002, | 17 | 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002, |
| 18 | 0x00050048, 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000022, 0x00000001, | 18 | 0x00050048, 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000022, 0x00000001, |
| 19 | 0x00000023, 0x00000004, 0x00040047, 0x00000072, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, | 19 | 0x00000023, 0x00000004, 0x00040047, 0x0000006f, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, |
| 20 | 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040017, | 20 | 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040017, |
| 21 | 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b, | 21 | 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b, |
| 22 | 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020, | 22 | 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020, |
| @@ -28,42 +28,39 @@ inline constexpr std::uint32_t statistics_sum_spirv[] = { | |||
| 28 | 0x00000002, 0x00000010, 0x00020014, 0x0000001f, 0x0004001e, 0x00000022, 0x00000006, 0x00000006, | 28 | 0x00000002, 0x00000010, 0x00020014, 0x0000001f, 0x0004001e, 0x00000022, 0x00000006, 0x00000006, |
| 29 | 0x00040020, 0x00000023, 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009, | 29 | 0x00040020, 0x00000023, 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009, |
| 30 | 0x0004002b, 0x00000019, 0x00000025, 0x00000001, 0x00040020, 0x00000026, 0x00000009, 0x00000006, | 30 | 0x0004002b, 0x00000019, 0x00000025, 0x00000001, 0x00040020, 0x00000026, 0x00000009, 0x00000006, |
| 31 | 0x0004002b, 0x00000006, 0x0000002e, 0x00000005, 0x0004002b, 0x00000006, 0x00000031, 0x00000007, | 31 | 0x0004002b, 0x00000006, 0x0000002b, 0x00000005, 0x0004002b, 0x00000006, 0x0000002f, 0x00000007, |
| 32 | 0x0004002b, 0x00000006, 0x00000036, 0x0000000a, 0x0004002b, 0x00000006, 0x00000040, 0x00000008, | 32 | 0x0004002b, 0x00000006, 0x00000033, 0x0000000a, 0x0004002b, 0x00000006, 0x0000003d, 0x00000008, |
| 33 | 0x0004002b, 0x00000006, 0x0000005e, 0x00000001, 0x0006002c, 0x00000009, 0x00000072, 0x00000013, | 33 | 0x0004002b, 0x00000006, 0x0000005b, 0x00000001, 0x0006002c, 0x00000009, 0x0000006f, 0x00000013, |
| 34 | 0x0000005e, 0x0000005e, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, | 34 | 0x0000005b, 0x0000005b, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, |
| 35 | 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006, | 35 | 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006, |
| 36 | 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 0x0000001a, 0x0000000f, | 36 | 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 0x0000001a, 0x0000000f, |
| 37 | 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x00050041, 0x00000026, 0x00000027, 0x00000024, | 37 | 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x00050041, 0x00000026, 0x00000027, 0x00000024, |
| 38 | 0x00000025, 0x0004003d, 0x00000006, 0x00000028, 0x00000027, 0x000500aa, 0x0000001f, 0x00000029, | 38 | 0x00000025, 0x0004003d, 0x00000006, 0x00000028, 0x00000027, 0x000500aa, 0x0000001f, 0x00000029, |
| 39 | 0x00000028, 0x0000000c, 0x000400a8, 0x0000001f, 0x0000002a, 0x00000029, 0x000300f7, 0x0000002c, | 39 | 0x00000028, 0x0000000c, 0x000500aa, 0x0000001f, 0x0000002c, 0x0000000f, 0x0000002b, 0x000500a6, |
| 40 | 0x00000000, 0x000400fa, 0x0000002a, 0x0000002b, 0x0000002c, 0x000200f8, 0x0000002b, 0x000500ae, | 40 | 0x0000001f, 0x0000002d, 0x00000029, 0x0000002c, 0x000500aa, 0x0000001f, 0x00000030, 0x0000000f, |
| 41 | 0x0000001f, 0x0000002f, 0x0000000f, 0x0000002e, 0x000500b2, 0x0000001f, 0x00000032, 0x0000000f, | 41 | 0x0000002f, 0x000500a6, 0x0000001f, 0x00000031, 0x0000002d, 0x00000030, 0x000500aa, 0x0000001f, |
| 42 | 0x00000031, 0x000500a7, 0x0000001f, 0x00000033, 0x0000002f, 0x00000032, 0x000200f9, 0x0000002c, | 42 | 0x00000034, 0x0000000f, 0x00000033, 0x000500a6, 0x0000001f, 0x00000035, 0x00000031, 0x00000034, |
| 43 | 0x000200f8, 0x0000002c, 0x000700f5, 0x0000001f, 0x00000034, 0x00000029, 0x00000005, 0x00000033, | 43 | 0x000500ab, 0x0000001f, 0x00000039, 0x00000028, 0x0000000c, 0x000500a7, 0x0000001f, 0x0000003c, |
| 44 | 0x0000002b, 0x000500aa, 0x0000001f, 0x00000037, 0x0000000f, 0x00000036, 0x000500a6, 0x0000001f, | 44 | 0x00000039, 0x00000034, 0x000600a9, 0x00000006, 0x0000003f, 0x0000003c, 0x0000003d, 0x0000000f, |
| 45 | 0x00000038, 0x00000034, 0x00000037, 0x000500ab, 0x0000001f, 0x0000003c, 0x00000028, 0x0000000c, | 45 | 0x000200f9, 0x00000041, 0x000200f8, 0x00000041, 0x000700f5, 0x00000010, 0x00000082, 0x0000001e, |
| 46 | 0x000500a7, 0x0000001f, 0x0000003f, 0x0000003c, 0x00000037, 0x000600a9, 0x00000006, 0x00000042, | 46 | 0x00000005, 0x00000083, 0x00000042, 0x000700f5, 0x00000006, 0x00000071, 0x0000000c, 0x00000005, |
| 47 | 0x0000003f, 0x00000040, 0x0000000f, 0x000200f9, 0x00000044, 0x000200f8, 0x00000044, 0x000700f5, | 47 | 0x0000006b, 0x00000042, 0x000400f6, 0x00000043, 0x00000042, 0x00000000, 0x000200f9, 0x00000045, |
| 48 | 0x00000010, 0x0000007f, 0x0000001e, 0x0000002c, 0x0000007c, 0x00000045, 0x000700f5, 0x00000006, | 48 | 0x000200f8, 0x00000045, 0x000300f7, 0x00000048, 0x00000000, 0x000400fa, 0x00000035, 0x00000047, |
| 49 | 0x0000007d, 0x0000000c, 0x0000002c, 0x0000006e, 0x00000045, 0x000400f6, 0x00000046, 0x00000045, | 49 | 0x00000048, 0x000200f8, 0x00000047, 0x00050041, 0x00000026, 0x0000004a, 0x00000024, 0x0000001a, |
| 50 | 0x00000000, 0x000200f9, 0x00000048, 0x000200f8, 0x00000048, 0x000300f7, 0x0000004b, 0x00000000, | 50 | 0x0004003d, 0x00000006, 0x0000004b, 0x0000004a, 0x000500b0, 0x0000001f, 0x0000004c, 0x00000071, |
| 51 | 0x000400fa, 0x00000038, 0x0000004a, 0x0000004b, 0x000200f8, 0x0000004a, 0x00050041, 0x00000026, | 51 | 0x0000004b, 0x000200f9, 0x00000048, 0x000200f8, 0x00000048, 0x000700f5, 0x0000001f, 0x0000004d, |
| 52 | 0x0000004d, 0x00000024, 0x0000001a, 0x0004003d, 0x00000006, 0x0000004e, 0x0000004d, 0x000500b0, | 52 | 0x00000035, 0x00000045, 0x0000004c, 0x00000047, 0x000400fa, 0x0000004d, 0x00000042, 0x00000043, |
| 53 | 0x0000001f, 0x0000004f, 0x0000007d, 0x0000004e, 0x000200f9, 0x0000004b, 0x000200f8, 0x0000004b, | 53 | 0x000200f8, 0x00000042, 0x00050084, 0x00000006, 0x00000050, 0x00000071, 0x00000013, 0x00050080, |
| 54 | 0x000700f5, 0x0000001f, 0x00000050, 0x00000038, 0x00000048, 0x0000004f, 0x0000004a, 0x000400fa, | 54 | 0x00000006, 0x00000052, 0x00000050, 0x0000003f, 0x00060041, 0x0000001c, 0x00000053, 0x00000018, |
| 55 | 0x00000050, 0x00000045, 0x00000046, 0x000200f8, 0x00000045, 0x00050084, 0x00000006, 0x00000053, | 55 | 0x00000025, 0x00000052, 0x0004003d, 0x00000010, 0x00000054, 0x00000053, 0x00050051, 0x00000006, |
| 56 | 0x0000007d, 0x00000013, 0x00050080, 0x00000006, 0x00000055, 0x00000053, 0x00000042, 0x00060041, | 56 | 0x00000057, 0x00000082, 0x00000000, 0x00050051, 0x00000006, 0x00000059, 0x00000054, 0x00000000, |
| 57 | 0x0000001c, 0x00000056, 0x00000018, 0x00000025, 0x00000055, 0x0004003d, 0x00000010, 0x00000057, | 57 | 0x00050080, 0x00000006, 0x0000005a, 0x00000057, 0x00000059, 0x00050051, 0x00000006, 0x0000005d, |
| 58 | 0x00000056, 0x00050051, 0x00000006, 0x0000005a, 0x0000007f, 0x00000000, 0x00050051, 0x00000006, | 58 | 0x00000054, 0x00000001, 0x000500b0, 0x0000001f, 0x00000061, 0x0000005a, 0x00000057, 0x000600a9, |
| 59 | 0x0000005c, 0x00000057, 0x00000000, 0x00050080, 0x00000006, 0x0000005d, 0x0000005a, 0x0000005c, | 59 | 0x00000006, 0x00000062, 0x00000061, 0x0000005b, 0x0000000c, 0x00050080, 0x00000006, 0x00000063, |
| 60 | 0x00050051, 0x00000006, 0x00000060, 0x00000057, 0x00000001, 0x000500b0, 0x0000001f, 0x00000064, | 60 | 0x0000005d, 0x00000062, 0x00050051, 0x00000006, 0x00000065, 0x00000082, 0x00000001, 0x00050080, |
| 61 | 0x0000005d, 0x0000005a, 0x000600a9, 0x00000006, 0x00000065, 0x00000064, 0x0000005e, 0x0000000c, | 61 | 0x00000006, 0x00000066, 0x00000065, 0x00000063, 0x00050050, 0x00000010, 0x00000083, 0x0000005a, |
| 62 | 0x00050080, 0x00000006, 0x00000066, 0x00000060, 0x00000065, 0x00050051, 0x00000006, 0x00000068, | 62 | 0x00000066, 0x00050080, 0x00000006, 0x0000006b, 0x00000071, 0x00000025, 0x000200f9, 0x00000041, |
| 63 | 0x0000007f, 0x00000001, 0x00050080, 0x00000006, 0x00000069, 0x00000068, 0x00000066, 0x00050050, | 63 | 0x000200f8, 0x00000043, 0x0003003e, 0x0000001d, 0x00000082, 0x000100fd, 0x00010038, |
| 64 | 0x00000010, 0x0000007c, 0x0000005d, 0x00000069, 0x00050080, 0x00000006, 0x0000006e, 0x0000007d, | ||
| 65 | 0x00000025, 0x000200f9, 0x00000044, 0x000200f8, 0x00000046, 0x0003003e, 0x0000001d, 0x0000007f, | ||
| 66 | 0x000100fd, 0x00010038, | ||
| 67 | }; | 64 | }; |
| 68 | 65 | ||
| 69 | } // namespace leonida | 66 | } // namespace leonida |
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e3e4defe8..f4373787b 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h | |||
| @@ -244,12 +244,16 @@ public: | |||
| 244 | 244 | ||
| 245 | // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the | 245 | // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the |
| 246 | // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291). | 246 | // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291). |
| 247 | // Segment i is in `mesh_queries` when mesh[i] is set (four counters: clipping, fragment and compute; see | 247 | // Segment i is in `mesh_queries` when mesh[i] is set (two counters: fragment and compute; see |
| 248 | // statistics_sum.comp), otherwise in `queries` (all eleven). | 248 | // statistics_sum.comp), otherwise in `queries` (all eleven). A mesh segment's clipping invocations come from |
| 249 | void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries, const std::uint8_t* mesh, | 249 | // `primitives_queries`, the mesh-primitives count of that segment (D3D-MESH-CLIPPING-COUNTER); it is null when |
| 250 | std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const { | 250 | // the device has no meshShaderQueries, and the field then reads 0. |
| 251 | void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries, | ||
| 252 | VkQueryPool primitives_queries, const std::uint8_t* mesh, std::uint32_t first, | ||
| 253 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const { | ||
| 251 | constexpr VkDeviceSize result = statistics_counters * word_size; | 254 | constexpr VkDeviceSize result = statistics_counters * word_size; |
| 252 | constexpr VkDeviceSize mesh_slot = 5 * word_size; // CInvocations, where the mesh pool's first counter goes | 255 | constexpr VkDeviceSize mesh_slot = 7 * word_size; // PSInvocations, where the mesh pool's first counter goes |
| 256 | constexpr VkDeviceSize clipping_slot = 5 * word_size; // CInvocations, where the mesh-primitives count goes | ||
| 253 | begin_scratch_write(cb); | 257 | begin_scratch_write(cb); |
| 254 | vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0); | 258 | vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0); |
| 255 | bind(cb, statistics_pipeline_); | 259 | bind(cb, statistics_pipeline_); |
| @@ -258,9 +262,18 @@ public: | |||
| 258 | std::uint32_t chunk = 1; | 262 | std::uint32_t chunk = 1; |
| 259 | while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh) | 263 | while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh) |
| 260 | ++chunk; | 264 | ++chunk; |
| 265 | if (in_mesh) { | ||
| 266 | // The mesh pool holds only the fragment and compute counters, so the clipping field of a mesh | ||
| 267 | // segment reads 0 unless the mesh-primitives count fills it (D3D-MESH-CLIPPING-COUNTER). | ||
| 268 | vk_.vkCmdFillBuffer(cb, scratch_, result, chunk * result, 0); | ||
| 269 | barrier(cb, transfer, transfer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); | ||
| 270 | } | ||
| 261 | vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_, | 271 | vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_, |
| 262 | result + (in_mesh ? mesh_slot : 0), result, | 272 | result + (in_mesh ? mesh_slot : 0), result, |
| 263 | VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); | 273 | VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); |
| 274 | if (in_mesh && primitives_queries) | ||
| 275 | vk_.vkCmdCopyQueryPoolResults(cb, primitives_queries, first, chunk, scratch_, result + clipping_slot, | ||
| 276 | result, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); | ||
| 264 | barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, | 277 | barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, |
| 265 | shader_access); | 278 | shader_access); |
| 266 | dispatch(cb, chunk, 1, in_mesh); | 279 | dispatch(cb, chunk, 1, in_mesh); |
| @@ -923,6 +936,10 @@ struct TileRange { | |||
| 923 | #endif | 936 | #endif |
| 924 | class VulkanContext { | 937 | class VulkanContext { |
| 925 | public: | 938 | public: |
| 939 | // mesh_queries: VK_EXT_mesh_shader's meshShaderQueries feature is enabled on `device`, so a mesh segment's | ||
| 940 | // clipping invocations can come from a mesh-primitives query (D3D-MESH-CLIPPING-COUNTER). Set by the device | ||
| 941 | // that created the context. | ||
| 942 | bool mesh_queries = false; | ||
| 926 | // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). | 943 | // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). |
| 927 | // ray_tracing: VK_KHR_acceleration_structure + VK_KHR_ray_query are enabled on `device`. | 944 | // ray_tracing: VK_KHR_acceleration_structure + VK_KHR_ray_query are enabled on `device`. |
| 928 | // xdxr: acceleration-structure builds write XDXR BVH4 records (xdxr_build.h) instead; needs bufferDeviceAddress. | 945 | // xdxr: acceleration-structure builds write XDXR BVH4 records (xdxr_build.h) instead; needs bufferDeviceAddress. |
| @@ -1000,7 +1017,7 @@ public: | |||
| 1000 | // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. | 1017 | // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. |
| 1001 | replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { | 1018 | replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { |
| 1002 | BufferVaIndex<ResourceId>::Hit hit{}; | 1019 | BufferVaIndex<ResourceId>::Hit hit{}; |
| 1003 | if (!buffer_vas_.find(va, hit)) return HostReadStatus::absent; | 1020 | if (!buffer_vas_.find(va, hit, bytes)) return HostReadStatus::absent; |
| 1004 | const ResourceBinding* b = resolve(hit.id); | 1021 | const ResourceBinding* b = resolve(hit.id); |
| 1005 | if (!b) return HostReadStatus::absent; | 1022 | if (!b) return HostReadStatus::absent; |
| 1006 | if (!b->host) return HostReadStatus::not_cpu_written; | 1023 | if (!b->host) return HostReadStatus::not_cpu_written; |
| @@ -1268,6 +1285,11 @@ public: | |||
| 1268 | replay_.zero_size = size; | 1285 | replay_.zero_size = size; |
| 1269 | } | 1286 | } |
| 1270 | 1287 | ||
| 1288 | void set_depth_range_unrestricted(bool enabled) { | ||
| 1289 | std::unique_lock lock(resource_mutex_); | ||
| 1290 | replay_.depth_range_unrestricted = enabled; | ||
| 1291 | } | ||
| 1292 | |||
| 1271 | // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. | 1293 | // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. |
| 1272 | void set_color_attachment_format(std::function<bool(VkFormat)> check) { | 1294 | void set_color_attachment_format(std::function<bool(VkFormat)> check) { |
| 1273 | std::unique_lock lock(resource_mutex_); | 1295 | std::unique_lock lock(resource_mutex_); |
| @@ -1483,12 +1505,23 @@ public: | |||
| 1483 | void note_bindless_upload() { bindless_upload_pending_ = true; } | 1505 | void note_bindless_upload() { bindless_upload_pending_ = true; } |
| 1484 | 1506 | ||
| 1485 | std::uint64_t completed_retire_ticket() { | 1507 | std::uint64_t completed_retire_ticket() { |
| 1486 | std::lock_guard lock(submit_mutex_); | 1508 | bool lost = false; |
| 1487 | if (is_device_lost()) return 0; | 1509 | std::uint64_t ticket = 0; |
| 1488 | return retire_tickets_.completed([this](VkSemaphore semaphore, std::uint64_t value) { | 1510 | { |
| 1489 | std::uint64_t done = 0; | 1511 | std::lock_guard lock(submit_mutex_); |
| 1490 | return vk.vkGetSemaphoreCounterValue(device_, semaphore, &done) == VK_SUCCESS && done >= value; | 1512 | if (is_device_lost()) return 0; |
| 1491 | }); | 1513 | ticket = retire_tickets_.completed([this, &lost](VkSemaphore semaphore, std::uint64_t value) { |
| 1514 | std::uint64_t done = 0; | ||
| 1515 | const VkResult result = vk.vkGetSemaphoreCounterValue(device_, semaphore, &done); | ||
| 1516 | if (result == VK_ERROR_DEVICE_LOST) lost = true; | ||
| 1517 | return result == VK_SUCCESS && done >= value; | ||
| 1518 | }); | ||
| 1519 | } | ||
| 1520 | // Outside submit_mutex_, as in submit(): notifying the fence dispatcher can run callbacks that submit. | ||
| 1521 | // A DEVICE_LOST seen here is the first Vulkan operation to discover it; it must not be mistaken for | ||
| 1522 | // "this ticket has not completed". | ||
| 1523 | if (lost) mark_device_lost(); | ||
| 1524 | return lost ? 0 : ticket; | ||
| 1492 | } | 1525 | } |
| 1493 | 1526 | ||
| 1494 | void drain_deleted_resources(std::uint64_t current_ticket) { | 1527 | void drain_deleted_resources(std::uint64_t current_ticket) { |
| @@ -2394,9 +2427,11 @@ private: | |||
| 2394 | occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); | 2427 | occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); |
| 2395 | }; | 2428 | }; |
| 2396 | replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, | 2429 | replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, |
| 2397 | const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count, | 2430 | VkQueryPool primitives_pool, const std::uint8_t* mesh, |
| 2398 | VkBuffer dst, VkDeviceSize offset) { | 2431 | std::uint32_t first, std::uint32_t count, VkBuffer dst, |
| 2399 | occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, mesh, first, count, dst, offset); | 2432 | VkDeviceSize offset) { |
| 2433 | occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, primitives_pool, mesh, first, count, dst, | ||
| 2434 | offset); | ||
| 2400 | }; | 2435 | }; |
| 2401 | replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, | 2436 | replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, |
| 2402 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { | 2437 | std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { |
| @@ -2443,18 +2478,26 @@ private: | |||
| 2443 | if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) { | 2478 | if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) { |
| 2444 | statistics->mesh.clear(); | 2479 | statistics->mesh.clear(); |
| 2445 | } else { | 2480 | } else { |
| 2446 | // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): clipping | 2481 | // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): the |
| 2447 | // invocations and primitives, fragment and compute invocations (D3D-291). | 2482 | // fragment and compute invocations, and no other (D3D-291). |
| 2448 | VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; | 2483 | VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; |
| 2449 | info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; | 2484 | info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; |
| 2450 | info.queryCount = statistics_segments; | 2485 | info.queryCount = statistics_segments; |
| 2451 | info.pipelineStatistics = VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT | | 2486 | info.pipelineStatistics = kMeshStatisticsFlags; |
| 2452 | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT | | ||
| 2453 | VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT | | ||
| 2454 | VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT; | ||
| 2455 | if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != | 2487 | if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != |
| 2456 | VK_SUCCESS) | 2488 | VK_SUCCESS) |
| 2457 | return ReplayResult::unsupported; | 2489 | return ReplayResult::unsupported; |
| 2490 | // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type, | ||
| 2491 | // which the pipeline-statistics pool cannot hold. The device needs the meshShaderQueries feature, | ||
| 2492 | // or the clipping field of a mesh segment stays 0. | ||
| 2493 | if (context_.mesh_queries) { | ||
| 2494 | VkQueryPoolCreateInfo primitives{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; | ||
| 2495 | primitives.queryType = VK_QUERY_TYPE_MESH_PRIMITIVES_GENERATED_EXT; | ||
| 2496 | primitives.queryCount = statistics_segments; | ||
| 2497 | if (context_.vk.vkCreateQueryPool(statistics->device, &primitives, nullptr, | ||
| 2498 | &statistics->primitives_pool) != VK_SUCCESS) | ||
| 2499 | return ReplayResult::unsupported; | ||
| 2500 | } | ||
| 2458 | } | 2501 | } |
| 2459 | } | 2502 | } |
| 2460 | // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after | 2503 | // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after |
| @@ -2515,6 +2558,18 @@ private: | |||
| 2515 | discard(); | 2558 | discard(); |
| 2516 | return ReplayResult::unsupported; | 2559 | return ReplayResult::unsupported; |
| 2517 | } | 2560 | } |
| 2561 | // D3D12 ends every ExecuteCommandLists with all its work done and its writes visible to the next one on the | ||
| 2562 | // queue (implicit state decay relies on it), and a list may then touch the same memory without a barrier: | ||
| 2563 | // two submissions copying into one buffer, say. Vulkan orders submissions on a queue only by what their | ||
| 2564 | // barriers say, so this one starts with a full memory barrier against everything submitted before it | ||
| 2565 | // (synchronization validation: WRITE_AFTER_WRITE between vk_queue_test's back-to-back copies). | ||
| 2566 | if (context_.vk.vkCmdPipelineBarrier) { // a mocked context may leave it out | ||
| 2567 | VkMemoryBarrier full{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | ||
| 2568 | full.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 2569 | full.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; | ||
| 2570 | context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, | ||
| 2571 | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, nullptr); | ||
| 2572 | } | ||
| 2518 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); | 2573 | if (!tracker_lock.owns_lock()) tracker_lock.lock(); |
| 2519 | if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { | 2574 | if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { |
| 2520 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; | 2575 | const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; |
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 889bb71f7..bcaea02f8 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h | |||
| @@ -216,7 +216,10 @@ inline VkPipelineStageFlags2 vulkan_sync(std::uint32_t sync) { | |||
| 216 | VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, | 216 | VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, |
| 217 | {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, | 217 | {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, |
| 218 | {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, | 218 | {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, |
| 219 | {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT}, | 219 | // CLEAR as well: two D3D12 copy-scope commands are recorded as Vulkan clear commands, WriteBufferImmediate |
| 220 | // as vkCmdUpdateBuffer and ResolveQueryData's never-written queries as vkCmdFillBuffer, and synchronization2 | ||
| 221 | // puts both in the CLEAR stage, not COPY. | ||
| 222 | {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT}, | ||
| 220 | {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT}, | 223 | {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT}, |
| 221 | {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, | 224 | {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, |
| 222 | {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, | 225 | {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, |
| @@ -716,6 +719,9 @@ struct OcclusionSegmentPool { | |||
| 716 | // segment index whether it runs there. Empty when no segment of the submission holds a mesh draw. | 719 | // segment index whether it runs there. Empty when no segment of the submission holds a mesh draw. |
| 717 | VkQueryPool mesh_pool = VK_NULL_HANDLE; | 720 | VkQueryPool mesh_pool = VK_NULL_HANDLE; |
| 718 | std::vector<std::uint8_t> mesh; | 721 | std::vector<std::uint8_t> mesh; |
| 722 | // The mesh-primitives pool of the mesh segments (D3D-MESH-CLIPPING-COUNTER): one query per segment, begun and | ||
| 723 | // ended with the mesh segment. Null when the device has no meshShaderQueries. | ||
| 724 | VkQueryPool primitives_pool = VK_NULL_HANDLE; | ||
| 719 | 725 | ||
| 720 | OcclusionSegmentPool() = default; | 726 | OcclusionSegmentPool() = default; |
| 721 | OcclusionSegmentPool(const OcclusionSegmentPool&) = delete; | 727 | OcclusionSegmentPool(const OcclusionSegmentPool&) = delete; |
| @@ -723,6 +729,7 @@ struct OcclusionSegmentPool { | |||
| 723 | ~OcclusionSegmentPool() { | 729 | ~OcclusionSegmentPool() { |
| 724 | if (pool) destroy(device, pool, nullptr); | 730 | if (pool) destroy(device, pool, nullptr); |
| 725 | if (mesh_pool) destroy(device, mesh_pool, nullptr); | 731 | if (mesh_pool) destroy(device, mesh_pool, nullptr); |
| 732 | if (primitives_pool) destroy(device, primitives_pool, nullptr); | ||
| 726 | } | 733 | } |
| 727 | }; | 734 | }; |
| 728 | 735 | ||
| @@ -810,6 +817,7 @@ struct ReplayFunctions { | |||
| 810 | PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; | 817 | PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; |
| 811 | PFN_vkCmdClearColorImage clear_color_image = nullptr; | 818 | PFN_vkCmdClearColorImage clear_color_image = nullptr; |
| 812 | PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; | 819 | PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; |
| 820 | bool depth_range_unrestricted = false; // Allows out-of-range float depth clear values. | ||
| 813 | // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. | 821 | // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. |
| 814 | PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers | 822 | PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers |
| 815 | VkPipelineStageFlags2 queue_stages = 0; | 823 | VkPipelineStageFlags2 queue_stages = 0; |
| @@ -875,9 +883,12 @@ struct ReplayFunctions { | |||
| 875 | VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion; | 883 | VkBuffer dst, VkDeviceSize offset)> resolve_binary_occlusion; |
| 876 | // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional | 884 | // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional |
| 877 | // rendering: the segments of a statistics query split around resolves (D3D-162) and mesh draws (D3D-291). | 885 | // rendering: the segments of a statistics query split around resolves (D3D-162) and mesh draws (D3D-291). |
| 878 | // Segment i is in the second pool when mesh[i] is set (mesh may be null: none is). | 886 | // Segment i is in the second pool when mesh[i] is set (mesh may be null: none is). The third pool holds the |
| 879 | std::function<void(VkCommandBuffer, VkQueryPool, VkQueryPool mesh_pool, const std::uint8_t* mesh, | 887 | // mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER); it is null when the device has no |
| 880 | std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset)> | 888 | // meshShaderQueries. |
| 889 | std::function<void(VkCommandBuffer, VkQueryPool, VkQueryPool mesh_pool, VkQueryPool primitives_pool, | ||
| 890 | const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count, VkBuffer dst, | ||
| 891 | VkDeviceSize offset)> | ||
| 881 | sum_statistics; | 892 | sum_statistics; |
| 882 | // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional | 893 | // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional |
| 883 | // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252). | 894 | // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252). |
| @@ -958,6 +969,8 @@ struct QueryResolveRun { | |||
| 958 | bool sum = false; | 969 | bool sum = false; |
| 959 | // Statistics segments: the mesh-compatible pool and the kind of each segment (OcclusionSegmentPool::mesh). | 970 | // Statistics segments: the mesh-compatible pool and the kind of each segment (OcclusionSegmentPool::mesh). |
| 960 | VkQueryPool mesh_pool = VK_NULL_HANDLE; | 971 | VkQueryPool mesh_pool = VK_NULL_HANDLE; |
| 972 | // The mesh-primitives pool of the mesh segments (D3D-MESH-CLIPPING-COUNTER); null without meshShaderQueries. | ||
| 973 | VkQueryPool primitives_pool = VK_NULL_HANDLE; | ||
| 961 | const std::uint8_t* mesh = nullptr; | 974 | const std::uint8_t* mesh = nullptr; |
| 962 | }; | 975 | }; |
| 963 | 976 | ||
| @@ -1598,6 +1611,7 @@ inline ReplayResult prepare_buffer_uav_clear(const ClearUnorderedAccess& clear, | |||
| 1598 | if (offset > UINT64_MAX - p.binding.buffer_offset || | 1611 | if (offset > UINT64_MAX - p.binding.buffer_offset || |
| 1599 | bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear; | 1612 | bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear; |
| 1600 | offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset | 1613 | offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset |
| 1614 | if (offset % std::min(e, 4u)) return ReplayResult::unsupported; | ||
| 1601 | if (e > 4 && bytes % 4) { | 1615 | if (e > 4 && bytes % 4) { |
| 1602 | return ReplayResult::unsupported; | 1616 | return ReplayResult::unsupported; |
| 1603 | } | 1617 | } |
| @@ -1869,27 +1883,48 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { | |||
| 1869 | return ReplayResult::success; | 1883 | return ReplayResult::success; |
| 1870 | } | 1884 | } |
| 1871 | 1885 | ||
| 1872 | // RGBA8 CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel | 1886 | // CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel/block |
| 1873 | // alignment. Stage only the occupied texels through aligned transfer scratch; leave partial-tile padding alone. | 1887 | // alignment (VUID-vkCmdCopyBufferToImage-dstImage-07975). Stage only the occupied texels/blocks through aligned |
| 1874 | inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, bool upload) { | 1888 | // transfer scratch; leave partial-tile padding alone. |
| 1889 | inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, const ResourceBinding& image, | ||
| 1890 | const BlockFormat& fmt, bool upload) { | ||
| 1875 | auto& region = p.buffer_image_copies.front(); | 1891 | auto& region = p.buffer_image_copies.front(); |
| 1876 | const VkDeviceSize row_bytes = VkDeviceSize(region.imageExtent.width) * 4; | 1892 | if (!fmt.bytes || !fmt.block || image.rgb96 || |
| 1877 | const VkDeviceSize pitch = VkDeviceSize(region.bufferRowLength) * 4; | 1893 | (image.depth24_as_float && region.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT)) |
| 1878 | const auto rows = region.imageExtent.height; | 1894 | return false; |
| 1895 | const VkDeviceSize blocks_w = (VkDeviceSize(region.imageExtent.width) + fmt.block - 1) / fmt.block; | ||
| 1896 | const VkDeviceSize rows = (VkDeviceSize(region.imageExtent.height) + fmt.block - 1) / fmt.block; | ||
| 1897 | const VkDeviceSize depth = region.imageExtent.depth; | ||
| 1898 | const VkDeviceSize row_bytes = blocks_w * fmt.bytes; | ||
| 1899 | const VkDeviceSize pitch = | ||
| 1900 | region.bufferRowLength ? VkDeviceSize(region.bufferRowLength / fmt.block) * fmt.bytes : row_bytes; | ||
| 1901 | const VkDeviceSize slice_rows = | ||
| 1902 | region.bufferImageHeight ? VkDeviceSize(region.bufferImageHeight / fmt.block) : rows; | ||
| 1903 | const VkDeviceSize slice_pitch = slice_rows * pitch; | ||
| 1904 | const VkDeviceSize slice_bytes = row_bytes * rows; | ||
| 1905 | const VkDeviceSize total_bytes = slice_bytes * depth; | ||
| 1879 | VkDeviceSize scratch_offset = 0; | 1906 | VkDeviceSize scratch_offset = 0; |
| 1880 | if (!vk.copy_scratch || !vk.copy_scratch(row_bytes * rows, p.tile_scratch, scratch_offset)) return false; | 1907 | if (!total_bytes || !vk.copy_scratch || !vk.copy_scratch(total_bytes, p.tile_scratch, scratch_offset)) return false; |
| 1881 | const auto app_offset = region.bufferOffset; | 1908 | const auto app_offset = region.bufferOffset; |
| 1882 | const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) { | 1909 | const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) { |
| 1883 | p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes}); | 1910 | p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes}); |
| 1884 | }; | 1911 | }; |
| 1885 | if (row_bytes == pitch) { | 1912 | if (row_bytes == pitch && (depth == 1 || slice_rows == rows)) { |
| 1886 | add_copy(app_offset, scratch_offset, row_bytes * rows); | 1913 | add_copy(app_offset, scratch_offset, total_bytes); |
| 1914 | } else if (row_bytes == pitch) { | ||
| 1915 | for (VkDeviceSize z = 0; z < depth; ++z) | ||
| 1916 | add_copy(app_offset + z * slice_pitch, scratch_offset + z * slice_bytes, slice_bytes); | ||
| 1887 | } else { | 1917 | } else { |
| 1888 | for (std::uint32_t row = 0; row < rows; ++row) | 1918 | for (VkDeviceSize z = 0; z < depth; ++z) { |
| 1889 | add_copy(app_offset + row * pitch, scratch_offset + row * row_bytes, row_bytes); | 1919 | const VkDeviceSize linear_slice = app_offset + z * slice_pitch; |
| 1920 | const VkDeviceSize scratch_slice = scratch_offset + z * slice_bytes; | ||
| 1921 | for (VkDeviceSize row = 0; row < rows; ++row) | ||
| 1922 | add_copy(linear_slice + row * pitch, scratch_slice + row * row_bytes, row_bytes); | ||
| 1923 | } | ||
| 1890 | } | 1924 | } |
| 1891 | region.bufferOffset = scratch_offset; | 1925 | region.bufferOffset = scratch_offset; |
| 1892 | region.bufferRowLength = 0; | 1926 | region.bufferRowLength = 0; |
| 1927 | region.bufferImageHeight = 0; | ||
| 1893 | return true; | 1928 | return true; |
| 1894 | } | 1929 | } |
| 1895 | 1930 | ||
| @@ -2300,6 +2335,8 @@ public: | |||
| 2300 | // For each of those segments, whether it holds mesh draws and so runs in statistics_mesh_pool (D3D-291). | 2335 | // For each of those segments, whether it holds mesh draws and so runs in statistics_mesh_pool (D3D-291). |
| 2301 | std::vector<std::uint8_t> statistics_mesh; | 2336 | std::vector<std::uint8_t> statistics_mesh; |
| 2302 | VkQueryPool statistics_mesh_pool = VK_NULL_HANDLE; | 2337 | VkQueryPool statistics_mesh_pool = VK_NULL_HANDLE; |
| 2338 | // The mesh-primitives pool of the list's mesh segments (D3D-MESH-CLIPPING-COUNTER). | ||
| 2339 | VkQueryPool statistics_primitives_pool = VK_NULL_HANDLE; | ||
| 2303 | // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them | 2340 | // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them |
| 2304 | // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run | 2341 | // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run |
| 2305 | // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. | 2342 | // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. |
| @@ -2344,10 +2381,26 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) { | |||
| 2344 | // Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and | 2381 | // Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and |
| 2345 | // ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements | 2382 | // ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements |
| 2346 | // depend on heap state at planning time, so every non-timestamp resolve splits conservatively. | 2383 | // depend on heap state at planning time, so every non-timestamp resolve splits conservatively. |
| 2347 | // A mesh draw cannot run while a query with the input-assembly, vertex, geometry or tessellation counters is active | 2384 | // The counters a mesh draw may count: VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076 leaves the input |
| 2348 | // (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076), though D3D12 allows it and reads those fields as 0. A query | 2385 | // assembly, vertex, geometry, tessellation and clipping bits out of the pipelineStatistics flags of every pool that |
| 2349 | // that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in the full pool | 2386 | // is active during a mesh draw, so a mesh segment runs in a pool with the fragment and compute counters only |
| 2350 | // or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of its own kind. | 2387 | // (D3D-291). D3D12 counts the clipping invocations and primitives of a mesh pipeline, but Vulkan has no counter for |
| 2388 | // them during a mesh draw, so those two fields read 0. | ||
| 2389 | inline constexpr VkQueryPipelineStatisticFlags kMeshStatisticsFlags = | ||
| 2390 | VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT | VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT; | ||
| 2391 | // The bits the same VUID forbids in a pool that is active during a mesh draw. | ||
| 2392 | inline constexpr VkQueryPipelineStatisticFlags kForbiddenMeshStatisticsFlags = | ||
| 2393 | VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT | VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT | | ||
| 2394 | VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT | VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT | | ||
| 2395 | VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT | | ||
| 2396 | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT | | ||
| 2397 | VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT | | ||
| 2398 | VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT; | ||
| 2399 | // A mesh draw cannot run while a query with the input-assembly, vertex, geometry, tessellation or clipping counters | ||
| 2400 | // is active (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076), though D3D12 allows it and reads those fields as | ||
| 2401 | // 0. A query that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in | ||
| 2402 | // the full pool or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of | ||
| 2403 | // its own kind. | ||
| 2351 | // Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw | 2404 | // Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw |
| 2352 | // has its own rendering scope, so a split before one stays outside rendering, as a helper's does. | 2405 | // has its own rendering scope, so a split before one stays outside rendering, as a helper's does. |
| 2353 | inline void plan_statistics_segments(PreparedList& out) { | 2406 | inline void plan_statistics_segments(PreparedList& out) { |
| @@ -2785,9 +2838,15 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun | |||
| 2785 | // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. | 2838 | // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. |
| 2786 | const bool upload = texture_copy->src.footprint; | 2839 | const bool upload = texture_copy->src.footprint; |
| 2787 | const ResourceBinding& image = upload ? p.binding : p.source; | 2840 | const ResourceBinding& image = upload ? p.binding : p.source; |
| 2788 | if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() && | 2841 | if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty()) { |
| 2789 | p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload)) | 2842 | const auto& region = p.buffer_image_copies.front(); |
| 2790 | return ReplayResult::unsupported; | 2843 | const BlockFormat fmt = copy_block_format(image, region.imageSubresource.aspectMask); |
| 2844 | const std::uint32_t alignment = | ||
| 2845 | (region.imageSubresource.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : fmt.bytes; | ||
| 2846 | if (alignment > 1 && region.bufferOffset % alignment && | ||
| 2847 | !detail::stage_unaligned_tile(vk, p, image, fmt, upload)) | ||
| 2848 | return ReplayResult::unsupported; | ||
| 2849 | } | ||
| 2791 | const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && | 2850 | const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && |
| 2792 | !p.buffer_image_copies.empty() && | 2851 | !p.buffer_image_copies.empty() && |
| 2793 | p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; | 2852 | p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; |
| @@ -3191,6 +3250,7 @@ public: | |||
| 3191 | retain(statistics_pool); | 3250 | retain(statistics_pool); |
| 3192 | list.statistics_pool = statistics_pool->pool; | 3251 | list.statistics_pool = statistics_pool->pool; |
| 3193 | list.statistics_mesh_pool = statistics_pool->mesh_pool; | 3252 | list.statistics_mesh_pool = statistics_pool->mesh_pool; |
| 3253 | list.statistics_primitives_pool = statistics_pool->primitives_pool; | ||
| 3194 | list.statistics_base = statistics_base; | 3254 | list.statistics_base = statistics_base; |
| 3195 | } else if (mesh) { | 3255 | } else if (mesh) { |
| 3196 | // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there. | 3256 | // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there. |
| @@ -3247,7 +3307,8 @@ public: | |||
| 3247 | const bool any_mesh = kinds && std::find(kinds + saved.first, kinds + saved.first + saved.count, | 3307 | const bool any_mesh = kinds && std::find(kinds + saved.first, kinds + saved.first + saved.count, |
| 3248 | std::uint8_t(1)) != kinds + saved.first + saved.count; | 3308 | std::uint8_t(1)) != kinds + saved.first + saved.count; |
| 3249 | run = {saved.segments->pool, saved.first, saved.count, run.offset, | 3309 | run = {saved.segments->pool, saved.first, saved.count, run.offset, |
| 3250 | saved.count > 1 || any_mesh, saved.segments->mesh_pool, kinds}; | 3310 | saved.count > 1 || any_mesh, saved.segments->mesh_pool, |
| 3311 | saved.segments->primitives_pool, kinds}; | ||
| 3251 | if (any_mesh && !statistics) return ReplayResult::invalid_query; | 3312 | if (any_mesh && !statistics) return ReplayResult::invalid_query; |
| 3252 | if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; | 3313 | if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; |
| 3253 | if (statistics) needs_statistics_sum |= run.sum; | 3314 | if (statistics) needs_statistics_sum |= run.sum; |
| @@ -3314,6 +3375,9 @@ inline void end_statistics_segment(const PreparedList& list, std::uint32_t segme | |||
| 3314 | const ReplayFunctions& vk) { | 3375 | const ReplayFunctions& vk) { |
| 3315 | if (segment == PreparedQuery::no_segment) return; | 3376 | if (segment == PreparedQuery::no_segment) return; |
| 3316 | vk.end_query(cb, statistics_segment_pool(list, segment), list.statistics_base + segment); | 3377 | vk.end_query(cb, statistics_segment_pool(list, segment), list.statistics_base + segment); |
| 3378 | // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER). | ||
| 3379 | if (list.statistics_primitives_pool && list.statistics_mesh[segment]) | ||
| 3380 | vk.end_query(cb, list.statistics_primitives_pool, list.statistics_base + segment); | ||
| 3317 | } | 3381 | } |
| 3318 | 3382 | ||
| 3319 | inline void begin_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb, | 3383 | inline void begin_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb, |
| @@ -3322,6 +3386,12 @@ inline void begin_statistics_segment(const PreparedList& list, std::uint32_t seg | |||
| 3322 | const auto pool = statistics_segment_pool(list, segment); | 3386 | const auto pool = statistics_segment_pool(list, segment); |
| 3323 | vk.reset_query_pool(cb, pool, list.statistics_base + segment, 1); | 3387 | vk.reset_query_pool(cb, pool, list.statistics_base + segment, 1); |
| 3324 | vk.begin_query(cb, pool, list.statistics_base + segment, 0); | 3388 | vk.begin_query(cb, pool, list.statistics_base + segment, 0); |
| 3389 | // The mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER): a query of its own type, which the | ||
| 3390 | // mesh statistics pool cannot hold. | ||
| 3391 | if (list.statistics_primitives_pool && list.statistics_mesh[segment]) { | ||
| 3392 | vk.reset_query_pool(cb, list.statistics_primitives_pool, list.statistics_base + segment, 1); | ||
| 3393 | vk.begin_query(cb, list.statistics_primitives_pool, list.statistics_base + segment, 0); | ||
| 3394 | } | ||
| 3325 | } | 3395 | } |
| 3326 | 3396 | ||
| 3327 | } // namespace detail | 3397 | } // namespace detail |
| @@ -3382,7 +3452,8 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu | |||
| 3382 | if (!run.pool) { | 3452 | if (!run.pool) { |
| 3383 | vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); | 3453 | vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); |
| 3384 | } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { | 3454 | } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { |
| 3385 | vk.sum_statistics(cb, run.pool, run.mesh_pool, run.mesh, run.first, run.count, dst, run.offset); | 3455 | vk.sum_statistics(cb, run.pool, run.mesh_pool, run.primitives_pool, run.mesh, run.first, run.count, |
| 3456 | dst, run.offset); | ||
| 3386 | } else if (run.sum && binary) { | 3457 | } else if (run.sum && binary) { |
| 3387 | vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); | 3458 | vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); |
| 3388 | } else if (run.sum || binary) { | 3459 | } else if (run.sum || binary) { |
| @@ -3615,10 +3686,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c | |||
| 3615 | const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); | 3686 | const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); |
| 3616 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); | 3687 | auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); |
| 3617 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); | 3688 | detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); |
| 3618 | const float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h | 3689 | float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h |
| 3619 | : p.binding.format == VK_FORMAT_D16_UNORM | 3690 | : p.binding.format == VK_FORMAT_D16_UNORM |
| 3620 | ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm | 3691 | ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm |
| 3621 | : depth_clear->depth; | 3692 | : depth_clear->depth; |
| 3693 | // Without the extension both clear commands require a depth in [0, 1], including for float images. | ||
| 3694 | if (!vk.depth_range_unrestricted) | ||
| 3695 | depth = std::isnan(depth) ? 0.0f : std::clamp(depth, 0.0f, 1.0f); | ||
| 3622 | const VkClearDepthStencilValue value{depth, depth_clear->stencil}; | 3696 | const VkClearDepthStencilValue value{depth, depth_clear->stencil}; |
| 3623 | if (p.rects.empty()) { | 3697 | if (p.rects.empty()) { |
| 3624 | detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), | 3698 | detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), |
diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 4a8a59ddd..33d84bf72 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h | |||
| @@ -46,12 +46,16 @@ public: | |||
| 46 | constexpr VkDeviceSize alignment = 256, minimum = 4u << 20; | 46 | constexpr VkDeviceSize alignment = 256, minimum = 4u << 20; |
| 47 | if (!loaded_ || !bytes) return false; | 47 | if (!loaded_ || !bytes) return false; |
| 48 | for (auto& chunk : current_.chunks) { | 48 | for (auto& chunk : current_.chunks) { |
| 49 | const VkDeviceSize start = (chunk.used + alignment - 1) / alignment * alignment; | 49 | const VkDeviceSize rem = chunk.used % alignment; |
| 50 | if (start <= chunk.size && bytes <= chunk.size - start) { | 50 | const VkDeviceSize pad = rem ? alignment - rem : 0; |
| 51 | chunk.used = start + bytes; | 51 | if (pad <= chunk.size - chunk.used) { |
| 52 | buffer = chunk.buffer; | 52 | const VkDeviceSize start = chunk.used + pad; |
| 53 | offset = start; | 53 | if (bytes <= chunk.size - start) { |
| 54 | return true; | 54 | chunk.used = start + bytes; |
| 55 | buffer = chunk.buffer; | ||
| 56 | offset = start; | ||
| 57 | return true; | ||
| 58 | } | ||
| 55 | } | 59 | } |
| 56 | } | 60 | } |
| 57 | Chunk chunk; | 61 | Chunk chunk; |
diff --git a/runtime/src/xdxr_build.h b/runtime/src/xdxr_build.h index e0851098f..e1c1a233e 100644 --- a/runtime/src/xdxr_build.h +++ b/runtime/src/xdxr_build.h | |||
| @@ -133,7 +133,13 @@ public: | |||
| 133 | // update ignores `pair`. | 133 | // update ignores `pair`. |
| 134 | bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, | 134 | bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector<XdxrTriangles>& geometries, |
| 135 | std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) { | 135 | std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) { |
| 136 | if (!loaded_ || layout.tlas) return false; | 136 | if (!loaded_ || layout.tlas || !layout.size || !dst || !scratch) return false; |
| 137 | std::uint64_t total = 0; | ||
| 138 | for (const auto& geo : geometries) { | ||
| 139 | total += geo.triangle_count; | ||
| 140 | if (total > layout.elements) return false; | ||
| 141 | } | ||
| 142 | if (total != layout.elements) return false; | ||
| 137 | Push p = base(layout, dst, scratch); | 143 | Push p = base(layout, dst, scratch); |
| 138 | if (pair && !update_from) p.flags |= flag_pair; | 144 | if (pair && !update_from) p.flags |= flag_pair; |
| 139 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); | 145 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); |
| @@ -155,7 +161,6 @@ public: | |||
| 155 | dispatch(cb, t, t.count); | 161 | dispatch(cb, t, t.count); |
| 156 | first += geo.triangle_count; | 162 | first += geo.triangle_count; |
| 157 | } | 163 | } |
| 158 | if (first != layout.elements) return false; | ||
| 159 | if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); | 164 | if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); |
| 160 | return true; | 165 | return true; |
| 161 | } | 166 | } |
| @@ -164,7 +169,8 @@ public: | |||
| 164 | // `update_from`: as for record_blas; the instances may move, and name other BLASes. | 169 | // `update_from`: as for record_blas; the instances may move, and name other BLASes. |
| 165 | bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, | 170 | bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, |
| 166 | std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) { | 171 | std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) { |
| 167 | if (!loaded_ || !layout.tlas) return false; | 172 | if (!loaded_ || !layout.tlas || !layout.size || !dst || !scratch || (layout.elements && !instances)) |
| 173 | return false; | ||
| 168 | Push p = base(layout, dst, scratch); | 174 | Push p = base(layout, dst, scratch); |
| 169 | p.bias = split(bias); | 175 | p.bias = split(bias); |
| 170 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); | 176 | if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); |
| @@ -341,7 +347,7 @@ private: | |||
| 341 | // dependency on its results to the caller's barrier (the application's UAV or AS barrier). | 347 | // dependency on its results to the caller's barrier (the application's UAV or AS barrier). |
| 342 | void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) { | 348 | void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) { |
| 343 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p); | 349 | vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p); |
| 344 | vk_.vkCmdDispatch(cb, (threads + 63) / 64, 1, 1); | 350 | vk_.vkCmdDispatch(cb, std::uint32_t((std::uint64_t(threads) + 63u) / 64u), 1, 1); |
| 345 | if (!barrier) return; | 351 | if (!barrier) return; |
| 346 | VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; | 352 | VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; |
| 347 | b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; | 353 | b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; |
diff --git a/runtime/src/xdxr_descs.h b/runtime/src/xdxr_descs.h index b44ce0372..3798b0fe7 100644 --- a/runtime/src/xdxr_descs.h +++ b/runtime/src/xdxr_descs.h | |||
| @@ -99,12 +99,11 @@ constexpr uint32_t kPostbuildInfoOfflineStatistics = 0x10; | |||
| 99 | // The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping | 99 | // The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping |
| 100 | // over types 0, 1 and 2, and stopping at any other type. Null when there is none. | 100 | // over types 0, 1 and 2, and stopping at any other type. Null when there is none. |
| 101 | inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) { | 101 | inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) { |
| 102 | if (desc.size_in_bytes == 0 || desc.stream == nullptr) | 102 | if (desc.size_in_bytes < sizeof(StreamRecord) || desc.stream == nullptr) |
| 103 | return nullptr; | 103 | return nullptr; |
| 104 | const auto* record = static_cast<const StreamRecord*>(desc.stream); | 104 | const auto* record = static_cast<const StreamRecord*>(desc.stream); |
| 105 | const auto* end = reinterpret_cast<const StreamRecord*>(static_cast<const uint8_t*>(desc.stream) + | 105 | const uint64_t count = desc.size_in_bytes / sizeof(StreamRecord); |
| 106 | desc.size_in_bytes); | 106 | for (uint64_t i = 0; i < count; ++i, ++record) { |
| 107 | for (; record < end; ++record) { | ||
| 108 | if (record->type == type) | 107 | if (record->type == type) |
| 109 | return record; | 108 | return record; |
| 110 | if (record->type > 2) | 109 | if (record->type > 2) |
diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp index bd93f7040..be2c6f1e1 100644 --- a/runtime/test/acphal_test.cpp +++ b/runtime/test/acphal_test.cpp | |||
| @@ -6,13 +6,44 @@ | |||
| 6 | 6 | ||
| 7 | #include <windows.h> | 7 | #include <windows.h> |
| 8 | 8 | ||
| 9 | #include <algorithm> | ||
| 10 | #include <atomic> | ||
| 9 | #include <cstddef> | 11 | #include <cstddef> |
| 10 | #include <cstdint> | 12 | #include <cstdint> |
| 11 | #include <cstdio> | 13 | #include <cstdio> |
| 14 | #include <cstdlib> | ||
| 12 | #include <cstring> | 15 | #include <cstring> |
| 16 | #include <new> | ||
| 17 | #include <thread> | ||
| 18 | #include <vector> | ||
| 13 | 19 | ||
| 14 | #include "shims.h" | 20 | #include "shims.h" |
| 15 | 21 | ||
| 22 | // Fail only the calling test thread's designated allocation. | ||
| 23 | static thread_local int allocations_before_failure = -1; | ||
| 24 | static std::atomic<bool> fail_worker_allocation{false}; | ||
| 25 | static std::atomic<bool> count_worker_allocations{false}; | ||
| 26 | static std::atomic<unsigned> worker_allocations{0}; | ||
| 27 | static DWORD test_thread_id; | ||
| 28 | void* operator new(std::size_t size) { | ||
| 29 | if (allocations_before_failure == 0) { | ||
| 30 | allocations_before_failure = -1; | ||
| 31 | throw std::bad_alloc(); | ||
| 32 | } | ||
| 33 | if (fail_worker_allocation.load() && GetCurrentThreadId() != test_thread_id && | ||
| 34 | fail_worker_allocation.exchange(false)) { | ||
| 35 | throw std::bad_alloc(); | ||
| 36 | } | ||
| 37 | if (count_worker_allocations.load() && GetCurrentThreadId() != test_thread_id) { | ||
| 38 | worker_allocations.fetch_add(1, std::memory_order_relaxed); | ||
| 39 | } | ||
| 40 | if (allocations_before_failure > 0) --allocations_before_failure; | ||
| 41 | if (void* memory = std::malloc(size ? size : 1)) return memory; | ||
| 42 | throw std::bad_alloc(); | ||
| 43 | } | ||
| 44 | void operator delete(void* memory) noexcept { std::free(memory); } | ||
| 45 | void operator delete(void* memory, std::size_t) noexcept { std::free(memory); } | ||
| 46 | |||
| 16 | namespace { | 47 | namespace { |
| 17 | 48 | ||
| 18 | using AcpHalCreateFn = HRESULT(__stdcall*)(void**); | 49 | using AcpHalCreateFn = HRESULT(__stdcall*)(void**); |
| @@ -66,9 +97,62 @@ static_assert(sizeof(TestShapeContexts) == 120, "TestShapeContexts is 120 bytes" | |||
| 66 | static_assert(offsetof(TestShapeContexts, xmaContextArray) == 0x38, | 97 | static_assert(offsetof(TestShapeContexts, xmaContextArray) == 0x38, |
| 67 | "xmaContextArray is at offset +0x38"); | 98 | "xmaContextArray is at offset +0x38"); |
| 68 | 99 | ||
| 100 | struct XmaWords { | ||
| 101 | uint32_t* data; | ||
| 102 | |||
| 103 | std::atomic_ref<uint32_t> operator[](std::size_t index) const { | ||
| 104 | return std::atomic_ref(data[index]); | ||
| 105 | } | ||
| 106 | }; | ||
| 107 | |||
| 108 | // Synthetic XMA2 with one nonzero spectral coefficient per channel and frame. | ||
| 109 | void write_xma_packet(uint8_t* packet, uint32_t frames, uint8_t packet_skip, | ||
| 110 | uint32_t rate_index = 3, bool stereo = false) { | ||
| 111 | constexpr uint32_t scale_bands[] = {23, 24, 23, 23}; | ||
| 112 | const uint32_t bands = scale_bands[rate_index]; | ||
| 113 | const uint32_t channels = stereo ? 2u : 1u; | ||
| 114 | const uint32_t frame_bits = stereo ? 90 + 2 * bands : 59 + bands; | ||
| 115 | std::memset(packet, 0xFF, 2048); | ||
| 116 | std::size_t at = 0; | ||
| 117 | auto put = [&](uint32_t value, std::size_t width) { | ||
| 118 | for (std::size_t i = 0; i < width; ++i, ++at) { | ||
| 119 | const auto mask = static_cast<uint8_t>(0x80u >> (at % 8)); | ||
| 120 | packet[at / 8] &= static_cast<uint8_t>(~mask); | ||
| 121 | if ((value >> (width - 1 - i)) & 1u) packet[at / 8] |= mask; | ||
| 122 | } | ||
| 123 | }; | ||
| 124 | put((frames << 26) | (1u << 8) | packet_skip, 32); | ||
| 125 | for (uint32_t frame = 0; frame < frames; ++frame) { | ||
| 126 | put(frame_bits, 15); | ||
| 127 | put(0b10u, 2); // Fixed layout, one 512-sample subframe. | ||
| 128 | if (stereo) put(0, 1); // No optional decorrelation matrix. | ||
| 129 | put(0, 11); // Gain, trim, fill and subframe error flag. | ||
| 130 | if (stereo) put(0b010u, 3); // Two channels without decorrelation. | ||
| 131 | put((1u << channels) - 1, channels); // Coefficients are present in each channel. | ||
| 132 | put(1, 1); // Explicit vector coefficient count. | ||
| 133 | put(0, 8 * channels); // Use only run/level coding. | ||
| 134 | put(0, 6); // Quantizer adjustment. | ||
| 135 | if (stereo) put(0, 5); // No per-channel quantizer modifiers. | ||
| 136 | for (uint32_t channel = 0; channel < channels; ++channel) { | ||
| 137 | put(0, 2); // Scale factor step. | ||
| 138 | put((1u << bands) - 1, bands); // One zero delta per scale band. | ||
| 139 | } | ||
| 140 | for (uint32_t channel = 0; channel < channels; ++channel) { | ||
| 141 | put(0, 1); // Run/level table 0. | ||
| 142 | put(0b00u, 2); // Run 0, level 1. | ||
| 143 | put(channel == 0 ? 1u : 0u, 1); | ||
| 144 | put(0b0101011u, 7); // End of coefficients. | ||
| 145 | } | ||
| 146 | put(0, 1); // Frame padding bit. | ||
| 147 | put(frame + 1 < frames ? 1 : 0, 1); | ||
| 148 | } | ||
| 149 | } | ||
| 150 | |||
| 69 | } // namespace | 151 | } // namespace |
| 70 | 152 | ||
| 71 | int main() { | 153 | int main(int argc, char** argv) { |
| 154 | std::setvbuf(stdout, nullptr, _IONBF, 0); | ||
| 155 | test_thread_id = GetCurrentThreadId(); | ||
| 72 | std::printf("acphal_test: registered acphal.dll shim verification\n"); | 156 | std::printf("acphal_test: registered acphal.dll shim verification\n"); |
| 73 | 157 | ||
| 74 | const auto create = reinterpret_cast<AcpHalCreateFn>( | 158 | const auto create = reinterpret_cast<AcpHalCreateFn>( |
| @@ -107,18 +191,44 @@ int main() { | |||
| 107 | return 1; | 191 | return 1; |
| 108 | } | 192 | } |
| 109 | 193 | ||
| 194 | // Heap configuration is process-wide, so CTest exercises this mode separately. | ||
| 195 | if (argc == 2 && std::strcmp(argv[1], "--noncached-only") == 0) { | ||
| 196 | check(create_heap(0, 0x6000u) == S_OK, "Create only the non-cached APU heap"); | ||
| 197 | void* noncached = nullptr; | ||
| 198 | uint32_t noncached_address = 0; | ||
| 199 | check(alloc(&noncached, &noncached_address, 0x1000, 0x800, 2) == S_OK && noncached != nullptr, | ||
| 200 | "Allocate from the non-cached heap"); | ||
| 201 | void* cached = noncached; | ||
| 202 | uint32_t cached_address = noncached_address; | ||
| 203 | check(alloc(&cached, &cached_address, 0x1000, 0x800, 1) == E_OUTOFMEMORY && | ||
| 204 | cached == nullptr && cached_address == 0, | ||
| 205 | "A missing cached heap stays unavailable after explicit configuration"); | ||
| 206 | check(map_apu(noncached_address) == noncached && map_virtual(noncached) == noncached_address, | ||
| 207 | "A failed cached allocation leaves the non-cached mapping unchanged"); | ||
| 208 | free_mem(noncached); | ||
| 209 | std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures); | ||
| 210 | return g_failures != 0; | ||
| 211 | } | ||
| 212 | |||
| 110 | // 1. AcpHalCreate | 213 | // 1. AcpHalCreate |
| 111 | void* acp = nullptr; | 214 | void* acp = nullptr; |
| 112 | check(create(&acp) == S_OK && acp != nullptr, | 215 | check(create(&acp) == S_OK && acp != nullptr, |
| 113 | "AcpHalCreate returns S_OK with a non-null object"); | 216 | "AcpHalCreate returns S_OK with a non-null object"); |
| 114 | check(create(nullptr) == E_POINTER, | 217 | check(create(nullptr) == E_POINTER, |
| 115 | "AcpHalCreate(nullptr) returns E_POINTER"); | 218 | "AcpHalCreate(nullptr) returns E_POINTER"); |
| 219 | void* failed_hal = acp; | ||
| 220 | allocations_before_failure = 0; | ||
| 221 | const HRESULT create_failure = create(&failed_hal); | ||
| 222 | allocations_before_failure = -1; | ||
| 223 | check(create_failure == E_OUTOFMEMORY && failed_hal == nullptr, | ||
| 224 | "AcpHalCreate returns E_OUTOFMEMORY and clears the output"); | ||
| 116 | 225 | ||
| 117 | if (acp) { | 226 | if (acp) { |
| 118 | using Slot0Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); | 227 | using Slot0Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); |
| 119 | using Slot1Fn = HRESULT(__stdcall*)(void*); | 228 | using Slot1Fn = HRESULT(__stdcall*)(void*); |
| 120 | using Slot2Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, const void*, uint32_t); | 229 | using Slot2Fn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t); |
| 121 | using Slot3Fn = uint32_t(__stdcall*)(void*); | 230 | using Slot3Fn = uint32_t(__stdcall*)(void*, void*); |
| 231 | using Slot4Fn = uint32_t(__stdcall*)(void*); | ||
| 122 | using Slot5Fn = HRESULT(__stdcall*)(void*); | 232 | using Slot5Fn = HRESULT(__stdcall*)(void*); |
| 123 | 233 | ||
| 124 | auto vtable = *static_cast<void* const* const*>(acp); | 234 | auto vtable = *static_cast<void* const* const*>(acp); |
| @@ -139,8 +249,8 @@ int main() { | |||
| 139 | "IAcpHal slot 2 (submit_command) returns S_OK (vital boot unblocker)"); | 249 | "IAcpHal slot 2 (submit_command) returns S_OK (vital boot unblocker)"); |
| 140 | 250 | ||
| 141 | // Slots 3 and 4: Message polling returns 0 | 251 | // Slots 3 and 4: Message polling returns 0 |
| 142 | check(reinterpret_cast<Slot3Fn>(vtable[3])(acp) == 0, "IAcpHal slot 3 returns 0"); | 252 | check(reinterpret_cast<Slot3Fn>(vtable[3])(acp, nullptr) == 0, "IAcpHal slot 3 returns 0"); |
| 143 | check(reinterpret_cast<Slot3Fn>(vtable[4])(acp) == 0, "IAcpHal slot 4 returns 0"); | 253 | check(reinterpret_cast<Slot4Fn>(vtable[4])(acp) == 0, "IAcpHal slot 4 returns 0"); |
| 144 | 254 | ||
| 145 | // Slot 1: Disconnect returns S_OK | 255 | // Slot 1: Disconnect returns S_OK |
| 146 | check(reinterpret_cast<Slot1Fn>(vtable[1])(acp) == S_OK, "IAcpHal slot 1 returns S_OK"); | 256 | check(reinterpret_cast<Slot1Fn>(vtable[1])(acp) == S_OK, "IAcpHal slot 1 returns S_OK"); |
| @@ -150,8 +260,8 @@ int main() { | |||
| 150 | } | 260 | } |
| 151 | 261 | ||
| 152 | // 2. ApuCreateHeap: title passes (cachedSize, nonCachedSize=0x226e00) | 262 | // 2. ApuCreateHeap: title passes (cachedSize, nonCachedSize=0x226e00) |
| 153 | check(create_heap(4 * 1024 * 1024, 0x226e00) == S_OK, | 263 | check(create_heap(4 * 1024 * 1024 + 0x400, 0x226e00) == S_OK, |
| 154 | "ApuCreateHeap(4 MiB, 0x226e00) succeeds"); | 264 | "ApuCreateHeap succeeds with an unaligned cached heap size"); |
| 155 | check(create_heap(4 * 1024 * 1024, 0x226e00) != S_OK, | 265 | check(create_heap(4 * 1024 * 1024, 0x226e00) != S_OK, |
| 156 | "ApuCreateHeap second call fails (heap already created)"); | 266 | "ApuCreateHeap second call fails (heap already created)"); |
| 157 | 267 | ||
| @@ -252,11 +362,513 @@ int main() { | |||
| 252 | check(ctx_all.xmaContextArray != nullptr, "xmaContextArray is allocated"); | 362 | check(ctx_all.xmaContextArray != nullptr, "xmaContextArray is allocated"); |
| 253 | check(ctx_all.pcmContextArray != nullptr, "pcmContextArray is allocated"); | 363 | check(ctx_all.pcmContextArray != nullptr, "pcmContextArray is allocated"); |
| 254 | 364 | ||
| 365 | TestShapeContexts retry_ctx{}; | ||
| 366 | retry_ctx.numXmaContexts = 2; | ||
| 367 | allocations_before_failure = 1; // The tracked allocation can grow, then voice slot allocation fails. | ||
| 368 | HRESULT allocation_result = E_UNEXPECTED; | ||
| 369 | try { | ||
| 370 | allocation_result = alloc_ctx(&retry_ctx); | ||
| 371 | } catch (const std::bad_alloc&) { | ||
| 372 | // An exception across the AcpHal boundary is a regression. | ||
| 373 | } | ||
| 374 | allocations_before_failure = -1; | ||
| 375 | check(allocation_result == E_OUTOFMEMORY && retry_ctx.xmaContextArray == nullptr, | ||
| 376 | "A failed XMA slot allocation returns E_OUTOFMEMORY without publishing a context"); | ||
| 377 | check(alloc_ctx(&retry_ctx) == S_OK && retry_ctx.xmaContextArray != nullptr, | ||
| 378 | "SHAPE allocation can be retried after memory pressure"); | ||
| 379 | |||
| 255 | // Release shape contexts | 380 | // Release shape contexts |
| 381 | std::memset(&ctx_all, 0x55, sizeof(ctx_all)); | ||
| 256 | check(release_ctx(&ctx_all) == S_OK, "AcpHalReleaseShapeContexts succeeds"); | 382 | check(release_ctx(&ctx_all) == S_OK, "AcpHalReleaseShapeContexts succeeds"); |
| 257 | check(ctx_all.xmaContextArray == nullptr, "xmaContextArray is reset to null"); | 383 | const auto* released_argument = reinterpret_cast<const uint8_t*>(&ctx_all); |
| 384 | check(std::all_of(released_argument, released_argument + sizeof(ctx_all), | ||
| 385 | [](uint8_t b) { return b == 0x55; }), | ||
| 386 | "SHAPE release does not write through an opaque or recycled argument"); | ||
| 258 | check(release_ctx(nullptr) == S_OK, "AcpHalReleaseShapeContexts(nullptr) succeeds"); | 387 | check(release_ctx(nullptr) == S_OK, "AcpHalReleaseShapeContexts(nullptr) succeeds"); |
| 259 | 388 | ||
| 389 | // 7. ACP command/message queue protocol (register, complete, overflow drops, disconnect, notify word) | ||
| 390 | { | ||
| 391 | #pragma pack(push, 1) | ||
| 392 | struct TestAcpMessage { | ||
| 393 | uint32_t kind; | ||
| 394 | uint32_t dropped; | ||
| 395 | uint32_t usec; | ||
| 396 | uint8_t data[16]; | ||
| 397 | }; | ||
| 398 | #pragma pack(pop) | ||
| 399 | static_assert(sizeof(TestAcpMessage) == 28, "ACP message is 28 bytes"); | ||
| 400 | |||
| 401 | using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); | ||
| 402 | using DisconnectFn = HRESULT(__stdcall*)(void*); | ||
| 403 | using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t); | ||
| 404 | using PopFn = uint32_t(__stdcall*)(void*, TestAcpMessage*); | ||
| 405 | using CountFn = uint32_t(__stdcall*)(void*); | ||
| 406 | using ReleaseFn = HRESULT(__stdcall*)(void*); | ||
| 407 | |||
| 408 | void* q_acp = nullptr; | ||
| 409 | check(create(&q_acp) == S_OK && q_acp != nullptr, "AcpHalCreate for queue test"); | ||
| 410 | auto vt = *static_cast<void* const* const*>(q_acp); | ||
| 411 | const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]); | ||
| 412 | const auto fn_disconnect = reinterpret_cast<DisconnectFn>(vt[1]); | ||
| 413 | const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]); | ||
| 414 | const auto fn_pop = reinterpret_cast<PopFn>(vt[3]); | ||
| 415 | const auto fn_count = reinterpret_cast<CountFn>(vt[4]); | ||
| 416 | const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]); | ||
| 417 | |||
| 418 | check(fn_connect(q_acp, 0, 16) == E_INVALIDARG, "Connect(commands=0) returns E_INVALIDARG"); | ||
| 419 | check(fn_disconnect(q_acp) == E_FAIL, "Disconnect before Connect returns E_FAIL"); | ||
| 420 | check(fn_connect(q_acp, 16, 2) == S_OK, "Connect(16, 2) succeeds"); | ||
| 421 | |||
| 422 | // Allocate a 4-byte notification word in APU memory. | ||
| 423 | void* notify_va = nullptr; | ||
| 424 | uint32_t notify_apu = 0; | ||
| 425 | check(alloc(¬ify_va, ¬ify_apu, 16, 16, 1) == S_OK && notify_va != nullptr, | ||
| 426 | "ApuAlloc notification word succeeds"); | ||
| 427 | *static_cast<uint32_t*>(notify_va) = 0; | ||
| 428 | |||
| 429 | const uint32_t reg_mask = 0x92u; // FLOWGRAPH_COMPLETED(0x02) | COMMAND_COMPLETED(0x10) | DISCONNECTED(0x80) | ||
| 430 | check(fn_submit(q_acp, 2, 0x1122334455667788ull, 0xffffffffu, ®_mask, notify_apu) == S_OK, | ||
| 431 | "REGISTER_MESSAGES with id and notify word succeeds"); | ||
| 432 | check(*static_cast<volatile uint32_t*>(notify_va) == 1u, | ||
| 433 | "SubmitCommand writes 1 to APU notification word"); | ||
| 434 | check(fn_count(q_acp) == 1u, "COMMAND_COMPLETED queued after REGISTER_MESSAGES"); | ||
| 435 | |||
| 436 | TestAcpMessage msg{}; | ||
| 437 | check(fn_pop(q_acp, &msg) == 1u, "PopMessage retrieves COMMAND_COMPLETED"); | ||
| 438 | uint32_t ack_cmd = 0; | ||
| 439 | uint64_t ack_id = 0; | ||
| 440 | std::memcpy(&ack_cmd, msg.data, 4); | ||
| 441 | std::memcpy(&ack_id, msg.data + 4, 8); | ||
| 442 | check(msg.kind == 0x10u && msg.dropped == 0u && ack_cmd == 2u && ack_id == 0x1122334455667788ull, | ||
| 443 | "COMMAND_COMPLETED payload carries command id and 64-bit token"); | ||
| 444 | |||
| 445 | // Overflow queue of capacity 2 with 4 commands -> 2 dropped, reported on the 5th. | ||
| 446 | for (uint64_t tok = 1; tok <= 4; ++tok) { | ||
| 447 | check(fn_submit(q_acp, 12, tok, 0xffffffffu, nullptr, 0) == S_OK, | ||
| 448 | "SubmitCommand during overflow succeeds"); | ||
| 449 | } | ||
| 450 | check(fn_count(q_acp) == 2u, "Message queue caps at capacity 2"); | ||
| 451 | check(fn_pop(q_acp, &msg) == 1u && fn_pop(q_acp, &msg) == 1u, | ||
| 452 | "Drained the 2 queued messages"); | ||
| 453 | check(fn_submit(q_acp, 12, 5, 0xffffffffu, nullptr, 0) == S_OK, | ||
| 454 | "SubmitCommand 5 after drain succeeds"); | ||
| 455 | check(fn_pop(q_acp, &msg) == 1u && msg.dropped == 2u, | ||
| 456 | "Next queued message reports dropped == 2"); | ||
| 457 | |||
| 458 | // LOAD_FLOWGRAPH posts FLOWGRAPH_COMPLETED carrying word(1). | ||
| 459 | const uint32_t fg_cfg[2] = {0, 0x42u}; | ||
| 460 | check(fn_submit(q_acp, 1, 0, 0xffffffffu, fg_cfg, 0) == S_OK, "LOAD_FLOWGRAPH succeeds"); | ||
| 461 | check(fn_pop(q_acp, &msg) == 1u && msg.kind == 0x02u, "FLOWGRAPH_COMPLETED queued"); | ||
| 462 | uint32_t fg_id = 0; | ||
| 463 | std::memcpy(&fg_id, msg.data, 4); | ||
| 464 | check(fg_id == 0x42u, "FLOWGRAPH_COMPLETED carries flowgraph word"); | ||
| 465 | |||
| 466 | const uint32_t command_completed_mask = 0x10u; | ||
| 467 | check(fn_submit(q_acp, 3, 0x100u, 0xffffffffu, &command_completed_mask, 0) == S_OK && | ||
| 468 | fn_count(q_acp) == 0u, | ||
| 469 | "UNREGISTER_MESSAGES suppresses command-completed messages"); | ||
| 470 | |||
| 471 | // Disconnect posts DISCONNECTED. | ||
| 472 | check(fn_disconnect(q_acp) == S_OK, "Disconnect succeeds when connected"); | ||
| 473 | check(fn_count(q_acp) == 1u, "Disconnect queued DISCONNECTED message"); | ||
| 474 | check(fn_pop(q_acp, &msg) == 1u && msg.kind == 0x80u, "Popped DISCONNECTED message"); | ||
| 475 | |||
| 476 | free_mem(notify_va); | ||
| 477 | check(fn_release(q_acp) == S_OK, "Release queue AcpHal succeeds"); | ||
| 478 | } | ||
| 479 | |||
| 480 | // 8. End-to-end XMA2 context ring decoding via background decoder thread | ||
| 481 | { | ||
| 482 | // Two synthetic XMA2 packets with three mono frames each. Each frame | ||
| 483 | // transmits one positive spectral coefficient so decoded PCM differs from fallback silence. | ||
| 484 | TestShapeContexts xma_ctx{}; | ||
| 485 | xma_ctx.numXmaContexts = 4; | ||
| 486 | check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr, | ||
| 487 | "Allocate 4 XMA SHAPE contexts"); | ||
| 488 | |||
| 489 | void* in_va = nullptr; | ||
| 490 | uint32_t in_apu = 0; | ||
| 491 | check(alloc(&in_va, &in_apu, 0x1000, 0x800, 1) == S_OK && in_va != nullptr, | ||
| 492 | "ApuAlloc 2-packet XMA2 input buffer"); | ||
| 493 | auto* packets = static_cast<uint8_t*>(in_va); | ||
| 494 | write_xma_packet(packets, 3, 0); | ||
| 495 | write_xma_packet(packets + 2048, 3, 0); | ||
| 496 | |||
| 497 | void* out_va = nullptr; | ||
| 498 | uint32_t out_apu = 0; | ||
| 499 | check(alloc(&out_va, &out_apu, 0x400, 0x100, 2) == S_OK && out_va != nullptr, | ||
| 500 | "ApuAlloc 4-block XMA2 output ring"); | ||
| 501 | std::memset(out_va, 0x55, 0x400); | ||
| 502 | |||
| 503 | // Configure voice index 1: 2 packets in input 0, input 0 valid, 4 output blocks, | ||
| 504 | // writable = 1, 48 kHz mono, read_bit = 32. | ||
| 505 | const XmaWords words{static_cast<uint32_t*>(xma_ctx.xmaContextArray) + 16}; | ||
| 506 | words[0] = 2u | (1u << 20) | (4u << 22); | ||
| 507 | words[1] = (1u << 31) | (3u << 27); | ||
| 508 | words[2] = 32u; | ||
| 509 | words[5] = in_apu; | ||
| 510 | words[7] = out_apu; | ||
| 511 | |||
| 512 | using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); | ||
| 513 | using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t); | ||
| 514 | using ReleaseFn = HRESULT(__stdcall*)(void*); | ||
| 515 | |||
| 516 | void* x_acp = nullptr; | ||
| 517 | check(create(&x_acp) == S_OK && x_acp != nullptr, "AcpHalCreate for XMA decode test"); | ||
| 518 | auto vt = *static_cast<void* const* const*>(x_acp); | ||
| 519 | const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]); | ||
| 520 | const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]); | ||
| 521 | const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]); | ||
| 522 | |||
| 523 | check(fn_connect(x_acp, 0x1000, 0x1000) == S_OK, "Connect for XMA decode test"); | ||
| 524 | |||
| 525 | // ENABLE_XMA (cmd 5) on voice 1. | ||
| 526 | const uint32_t enable_arg = 1u; | ||
| 527 | worker_allocations.store(0); | ||
| 528 | count_worker_allocations.store(true); | ||
| 529 | check(fn_submit(x_acp, 5, 0xf1, 0xffffffffu, &enable_arg, 0) == S_OK, | ||
| 530 | "ENABLE_XMA voice 1 succeeds"); | ||
| 531 | |||
| 532 | // Wait up to 500 ms for the background decoder thread to fill the 4-block ring. | ||
| 533 | for (int wait = 0; wait < 500 && ((words[1] >> 31) & 1u) == 1u; ++wait) { | ||
| 534 | Sleep(1); | ||
| 535 | } | ||
| 536 | const bool ring_full = (words[1] >> 31) == 0u; | ||
| 537 | check(ring_full, "Background XMA2 decoder fills ring and clears writable flag"); | ||
| 538 | check(((words[0] >> 27) & 0x1Fu) == 0u, | ||
| 539 | "Write block wrapped back to 0 after filling 4 blocks"); | ||
| 540 | |||
| 541 | const auto* ring_bytes = static_cast<const uint8_t*>(out_va); | ||
| 542 | #if defined(LEONIDA_HAVE_XMA2_DECODER) | ||
| 543 | check(ring_full && std::any_of(ring_bytes, ring_bytes + 0x400, | ||
| 544 | [](uint8_t b) { return b != 0 && b != 0x55; }), | ||
| 545 | "The Rust decoder writes non-silent PCM"); | ||
| 546 | #else | ||
| 547 | check(ring_full && std::all_of(ring_bytes, ring_bytes + 0x400, [](uint8_t b) { return b == 0; }), | ||
| 548 | "The fallback writes silence"); | ||
| 549 | #endif | ||
| 550 | |||
| 551 | // Advance read pointer 4 blocks at a time until input exhausts and INPUT_INVALID fires. | ||
| 552 | const uint32_t advance_args[2] = {1u, 4u}; | ||
| 553 | int written_blocks = ring_full ? 4 : 0; | ||
| 554 | bool advanced = true; | ||
| 555 | for (int step = 0; step < 6; ++step) { | ||
| 556 | advanced &= fn_submit(x_acp, 18, 0xf2 + static_cast<uint64_t>(step), | ||
| 557 | 0xffffffffu, advance_args, 0) == S_OK; | ||
| 558 | // Wait until either ring fills again (writable == 0) or stream hits error bit. | ||
| 559 | for (int wait = 0; wait < 200; ++wait) { | ||
| 560 | const uint32_t w1 = words[1]; | ||
| 561 | const uint32_t w2 = words[2]; | ||
| 562 | if (((w1 >> 31) & 1u) == 0u || ((w2 >> 31) & 1u) == 1u) break; | ||
| 563 | Sleep(1); | ||
| 564 | } | ||
| 565 | if (((words[2] >> 31) & 1u) == 1u && ((words[1] >> 31) & 1u) == 1u) { | ||
| 566 | break; | ||
| 567 | } | ||
| 568 | if ((words[1] >> 31) != 0u) break; | ||
| 569 | written_blocks += 4; | ||
| 570 | } | ||
| 571 | check(advanced, "ADVANCE_XMA_READ succeeds"); | ||
| 572 | check(written_blocks == 24, "Six frames write exactly 24 blocks before input exhaustion"); | ||
| 573 | count_worker_allocations.store(false); | ||
| 574 | const unsigned allocation_count = worker_allocations.load(); | ||
| 575 | std::printf("C++ worker allocations for six PCM frames: %u\n", allocation_count); | ||
| 576 | check(allocation_count > 0 && allocation_count < 16, | ||
| 577 | "PCM storage is reused across packets instead of allocating per sample block"); | ||
| 578 | check(((words[0] >> 20) & 3u) == 0u, "XMA input buffer valid bits cleared on exhaustion"); | ||
| 579 | check(((words[2] >> 31) & 1u) == 1u, "XMA error flag set on exhaustion"); | ||
| 580 | check(((words[2] >> 26) & 0x1Fu) == 4u, "XMA error status is INPUT_INVALID (4)"); | ||
| 581 | |||
| 582 | // DISABLE_XMA (cmd 7) on voice 1. | ||
| 583 | const uint32_t disable_arg = 1u; | ||
| 584 | check(fn_submit(x_acp, 7, 0xf9, 0xffffffffu, &disable_arg, 0) == S_OK, | ||
| 585 | "DISABLE_XMA voice 1 succeeds"); | ||
| 586 | check(fn_release(x_acp) == S_OK, "Release XMA AcpHal succeeds"); | ||
| 587 | free_mem(in_va); | ||
| 588 | free_mem(out_va); | ||
| 589 | check(release_ctx(&xma_ctx) == S_OK, "Release XMA SHAPE contexts joins decoder cleanly"); | ||
| 590 | } | ||
| 591 | |||
| 592 | // 8b. Loops are rounded to whole packets: the loop end packet plays in full and the read | ||
| 593 | // restarts at the packet holding the loop start. One 1-frame packet = 512 samples = 4 blocks. | ||
| 594 | { | ||
| 595 | TestShapeContexts xma_ctx{}; | ||
| 596 | xma_ctx.numXmaContexts = 4; | ||
| 597 | check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr, | ||
| 598 | "Allocate 4 XMA SHAPE contexts for the packet loop test"); | ||
| 599 | |||
| 600 | void* in_va = nullptr; | ||
| 601 | uint32_t in_apu = 0; | ||
| 602 | check(alloc(&in_va, &in_apu, 0x2000, 0x800, 2) == S_OK && in_va != nullptr && | ||
| 603 | (in_apu & 0x7FFu) == 0 && map_apu(in_apu) == in_va, | ||
| 604 | "Non-cached XMA input keeps its requested alignment and round trips"); | ||
| 605 | auto* packets = static_cast<uint8_t*>(in_va); | ||
| 606 | write_xma_packet(packets, 1, 1); // Packet 1 belongs to another stream. | ||
| 607 | write_xma_packet(packets + 0x800, 2, 0); | ||
| 608 | write_xma_packet(packets + 0x1000, 1, 0); | ||
| 609 | |||
| 610 | void* out_va = nullptr; | ||
| 611 | uint32_t out_apu = 0; | ||
| 612 | check(alloc(&out_va, &out_apu, 0x1000, 0x100, 2) == S_OK && out_va != nullptr, | ||
| 613 | "ApuAlloc 16-block loop output ring"); | ||
| 614 | |||
| 615 | // Voice index 2. | ||
| 616 | const XmaWords words{static_cast<uint32_t*>(xma_ctx.xmaContextArray) + 32}; | ||
| 617 | |||
| 618 | using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); | ||
| 619 | using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t); | ||
| 620 | using ReleaseFn = HRESULT(__stdcall*)(void*); | ||
| 621 | |||
| 622 | void* x_acp = nullptr; | ||
| 623 | check(create(&x_acp) == S_OK && x_acp != nullptr, "AcpHalCreate for packet loop test"); | ||
| 624 | auto vt = *static_cast<void* const* const*>(x_acp); | ||
| 625 | const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]); | ||
| 626 | const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]); | ||
| 627 | const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]); | ||
| 628 | check(fn_connect(x_acp, 0x1000, 0x1000) == S_OK, "Connect for packet loop test"); | ||
| 629 | |||
| 630 | auto configure_voice = [&](uint32_t loops, uint32_t input_0_packets, uint32_t ring_size, | ||
| 631 | uint32_t write, uint32_t read) { | ||
| 632 | std::memset(out_va, 0x55, 0x1000); | ||
| 633 | const uint32_t input_1_packets = 3u - input_0_packets; | ||
| 634 | words[0] = input_0_packets | (loops << 12) | | ||
| 635 | ((input_1_packets != 0 ? 3u : 1u) << 20) | (ring_size << 22) | (write << 27); | ||
| 636 | words[1] = (1u << 31) | (3u << 27) | input_1_packets; | ||
| 637 | words[2] = 32u; // read at packet 0 | ||
| 638 | words[3] = 32u; // loop start: packet 0 | ||
| 639 | words[4] = 100u; // loop end: packet 0 | ||
| 640 | words[5] = in_apu; | ||
| 641 | words[6] = in_apu + input_0_packets * 2048u; | ||
| 642 | words[7] = out_apu; | ||
| 643 | words[9] = read; | ||
| 644 | }; | ||
| 645 | |||
| 646 | const uint32_t voice_index = 2u; | ||
| 647 | // Returns the number of blocks written before input exhaustion, or -1 on timeout. | ||
| 648 | auto run_blocks = [&](uint32_t loops, uint32_t input_0_packets = 3, | ||
| 649 | uint32_t initial_skip = 0, uint32_t loop_skip = 0) -> int { | ||
| 650 | configure_voice(loops, input_0_packets, 16, 0, 0); | ||
| 651 | words[1].fetch_or((initial_skip << 24) | (loop_skip << 17)); | ||
| 652 | check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &voice_index, 0) == S_OK, | ||
| 653 | "ENABLE_XMA voice 2 succeeds"); | ||
| 654 | int wait = 0; | ||
| 655 | for (; wait < 1000 && ((words[2] >> 31) & 1u) == 0u; ++wait) { | ||
| 656 | Sleep(1); | ||
| 657 | } | ||
| 658 | const int blocks = ((words[2] >> 31) & 1u) != 0u | ||
| 659 | ? static_cast<int>((words[0] >> 27) & 0x1Fu) | ||
| 660 | : -1; | ||
| 661 | check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &voice_index, 0) == S_OK, | ||
| 662 | "DISABLE_XMA voice 2 succeeds"); | ||
| 663 | return blocks; | ||
| 664 | }; | ||
| 665 | |||
| 666 | check(run_blocks(0) == 8, "Packets 0 and 2 write 8 blocks, skipping packet 1"); | ||
| 667 | check(run_blocks(1) == 12, "One loop of packet 0 writes 12 blocks (packets 0, 0, 2)"); | ||
| 668 | check(((words[0] >> 12) & 0xFFu) == 0u, "Loop count is consumed by the single loop"); | ||
| 669 | const auto* ring_bytes = static_cast<const uint8_t*>(out_va); | ||
| 670 | #if defined(LEONIDA_HAVE_XMA2_DECODER) | ||
| 671 | auto has_signal = [](const uint8_t* start) { | ||
| 672 | return std::any_of(start, start + 0x400, [](uint8_t b) { return b != 0 && b != 0x55; }); | ||
| 673 | }; | ||
| 674 | check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400) && has_signal(ring_bytes + 0x800), | ||
| 675 | "Rust produces signal before and after rewinding the loop"); | ||
| 676 | check(std::memcmp(ring_bytes, ring_bytes + 0x400, 0x400) == 0, | ||
| 677 | "Rewind decodes the first packet from fresh decoder state"); | ||
| 678 | #endif | ||
| 679 | check(run_blocks(1, 3, 2, 1) == 9 && ((words[1] >> 24) & 7u) == 0, | ||
| 680 | "Initial and loop subframe skips consume 3 blocks and clear the initial skip"); | ||
| 681 | check(run_blocks(0, 2) == 8, | ||
| 682 | "A skip to the end of input 0 continues at input 1"); | ||
| 683 | check(run_blocks(0, 1) == 8, | ||
| 684 | "An overshooting skip starts at packet 1 of input 1"); | ||
| 685 | #if defined(LEONIDA_HAVE_XMA2_DECODER) | ||
| 686 | check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400), | ||
| 687 | "Rust produces signal on both sides of the buffer switch"); | ||
| 688 | #endif | ||
| 689 | |||
| 690 | configure_voice(255, 3, 4, 7, 9); | ||
| 691 | check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &voice_index, 0) == S_OK, | ||
| 692 | "Enable infinite loop with out-of-range ring indices"); | ||
| 693 | for (int wait = 0; wait < 1000 && (words[1] >> 31) != 0u; ++wait) Sleep(1); | ||
| 694 | check((words[1] >> 31) == 0u && ((words[0] >> 27) & 0x1Fu) == 1u, | ||
| 695 | "Ring stops at the normalized read index"); | ||
| 696 | check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &voice_index, 0) == S_OK, | ||
| 697 | "Disable infinite loop after filling bounded ring"); | ||
| 698 | check(((words[0] >> 12) & 0xFFu) == 255u, "Infinite loop does not consume its loop count"); | ||
| 699 | check(std::all_of(ring_bytes + 0x400, ring_bytes + 0x1000, | ||
| 700 | [](uint8_t b) { return b == 0x55; }), | ||
| 701 | "Output never writes beyond the configured four-block ring"); | ||
| 702 | |||
| 703 | words[0] = 3u << 22; // three ring blocks | ||
| 704 | words[9] = 2u; | ||
| 705 | const uint32_t advance_args[2] = {2u, UINT32_MAX}; | ||
| 706 | check(fn_submit(x_acp, 18, 0xf5, 0xffffffffu, advance_args, 0) == S_OK && words[9] == 2u, | ||
| 707 | "ADVANCE_XMA_READ wraps at the ring size without overflowing"); | ||
| 708 | |||
| 709 | auto wait_for_ring = [&]() { | ||
| 710 | for (int wait = 0; wait < 1000 && (words[1] >> 31) != 0u; ++wait) Sleep(1); | ||
| 711 | return (words[1] >> 31) == 0u; | ||
| 712 | }; | ||
| 713 | const uint32_t refill_read_args[2] = {voice_index, 4}; | ||
| 714 | |||
| 715 | configure_voice(0, 3, 4, 0, 0); | ||
| 716 | words[0] = 1u | (1u << 20) | (4u << 22); | ||
| 717 | write_xma_packet(packets, 3, 0); | ||
| 718 | check(fn_submit(x_acp, 5, 0xf6, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(), | ||
| 719 | "First packet fills the ring and leaves queued PCM"); | ||
| 720 | TestShapeContexts source_only{}; | ||
| 721 | source_only.numSrcContexts = 1; | ||
| 722 | check(alloc_ctx(&source_only) == S_OK && source_only.srcContextArray != nullptr, | ||
| 723 | "A non-XMA allocation can coexist with the active XMA table"); | ||
| 724 | words[0].fetch_or(1u << 20); | ||
| 725 | check(fn_submit(x_acp, 5, 0xf7, 0xffffffffu, &voice_index, 0) == S_OK, | ||
| 726 | "Re-enable while refilling the current input"); | ||
| 727 | int refills = 0; | ||
| 728 | for (int i = 0; i < 5; ++i) { | ||
| 729 | if (fn_submit(x_acp, 18, 0xf8, 0xffffffffu, refill_read_args, 0) != S_OK || !wait_for_ring()) break; | ||
| 730 | ++refills; | ||
| 731 | } | ||
| 732 | check(refills == 5 && (words[2] >> 31) == 0u && ((words[0] >> 20) & 3u) == 0u, | ||
| 733 | "Refill and repeated enable preserve all six frames and consume the reused input"); | ||
| 734 | check(fn_submit(x_acp, 7, 0xf9, 0xffffffffu, &voice_index, 0) == S_OK, | ||
| 735 | "Disable the single-buffer refill voice"); | ||
| 736 | |||
| 737 | // The next same-stream packet is in the first input's refill, after a short second input. | ||
| 738 | write_xma_packet(packets, 1, 2); | ||
| 739 | write_xma_packet(packets + 0x1000, 2, 0); | ||
| 740 | write_xma_packet(packets + 0x1800, 1, 0); | ||
| 741 | configure_voice(0, 1, 4, 0, 0); | ||
| 742 | words[1] = (words[1] & ~0xFFFu) | 1u; | ||
| 743 | check(fn_submit(x_acp, 5, 0xfa, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(), | ||
| 744 | "Voice fills the ring before the skip crosses two buffers"); | ||
| 745 | words[5] = in_apu + 0x1000u; | ||
| 746 | words[0] = (words[0] & ~0xFFFu) | 2u | (1u << 20); | ||
| 747 | check(fn_submit(x_acp, 18, 0xfb, 0xffffffffu, refill_read_args, 0) == S_OK && wait_for_ring(), | ||
| 748 | "The same-stream packet fills the ring after two buffer crossings"); | ||
| 749 | check(((words[0] >> 20) & 3u) == 0u && (words[4] >> 31) == 0u, | ||
| 750 | "A skip across both buffers lands on the last packet of the reloaded input"); | ||
| 751 | check(fn_submit(x_acp, 7, 0xfc, 0xffffffffu, &voice_index, 0) == S_OK, | ||
| 752 | "Disable the two-buffer refill voice"); | ||
| 753 | |||
| 754 | // Both sides were empty. When both are refilled, the title's first input wins. | ||
| 755 | write_xma_packet(packets, 1, 0); | ||
| 756 | configure_voice(0, 3, 4, 0, 0); | ||
| 757 | words[0] = 1u | (1u << 20) | (4u << 22); | ||
| 758 | const uint32_t voice_bit = 1u << voice_index; | ||
| 759 | check(fn_submit(x_acp, 6, 0, 0xffffffffu, &voice_bit, 0) == S_OK && wait_for_ring(), | ||
| 760 | "ENABLE_XMAS starts the selected voice and exhausts the first input"); | ||
| 761 | write_xma_packet(packets, 2, 0); | ||
| 762 | write_xma_packet(packets + 0x800, 1, 0); | ||
| 763 | words[6] = in_apu + 0x800u; | ||
| 764 | words[1].fetch_or(1u); | ||
| 765 | words[0].fetch_or(3u << 20); | ||
| 766 | check(fn_submit(x_acp, 18, 0, 0xffffffffu, refill_read_args, 0) == S_OK && wait_for_ring(), | ||
| 767 | "A double refill supplies the next PCM blocks"); | ||
| 768 | check(((words[0] >> 20) & 3u) == 2u && (words[4] >> 31) == 1u, | ||
| 769 | "A double refill plays input 0 before input 1"); | ||
| 770 | #if defined(LEONIDA_HAVE_XMA2_DECODER) | ||
| 771 | check(has_signal(ring_bytes), "Rust decodes non-silent PCM after a double refill"); | ||
| 772 | #endif | ||
| 773 | |||
| 774 | check(fn_submit(x_acp, 8, 0, 0xffffffffu, &voice_bit, 0) == S_OK, | ||
| 775 | "Reset the voice before exhausting both inputs"); | ||
| 776 | write_xma_packet(packets, 1, 0); | ||
| 777 | write_xma_packet(packets + 0x800, 1, 0); | ||
| 778 | configure_voice(0, 1, 8, 0, 0); | ||
| 779 | words[1] = (words[1] & ~0xFFFu) | 1u; | ||
| 780 | check(fn_submit(x_acp, 6, 0, 0xffffffffu, &voice_bit, 0) == S_OK && wait_for_ring() && | ||
| 781 | ((words[0] >> 20) & 3u) == 0u, | ||
| 782 | "The voice exhausts input 0 and then input 1"); | ||
| 783 | write_xma_packet(packets, 2, 0); | ||
| 784 | words[0].fetch_or(3u << 20); | ||
| 785 | const uint32_t full_ring[2] = {voice_index, 8}; | ||
| 786 | check(fn_submit(x_acp, 18, 0, 0xffffffffu, full_ring, 0) == S_OK && wait_for_ring() && | ||
| 787 | ((words[0] >> 20) & 3u) == 2u, | ||
| 788 | "A double refill plays input 0 first even after exhausting input 1"); | ||
| 789 | |||
| 790 | // Reconfigure the still-enabled slot and verify that no queued PCM or old format survives. | ||
| 791 | bool reconfigured = true; | ||
| 792 | for (uint32_t rate = 0; rate < 4; ++rate) { | ||
| 793 | const bool stereo = (rate & 1u) == 0; | ||
| 794 | write_xma_packet(packets, 1, 0, rate, stereo); | ||
| 795 | words[0] = 1u | (1u << 20) | (16u << 22); | ||
| 796 | words[2] = 32u; | ||
| 797 | words[4] = 0u; | ||
| 798 | words[9] = 12u; | ||
| 799 | std::memset(out_va, 0, 0x1000); | ||
| 800 | // Enable applies the new format before making the output writable. | ||
| 801 | words[1] = ((rate | (stereo ? 4u : 0u)) << 27); | ||
| 802 | reconfigured &= fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK; | ||
| 803 | reconfigured &= fn_submit(x_acp, 18, 0, 0xffffffffu, refill_read_args, 0) == S_OK; | ||
| 804 | for (int wait = 0; wait < 1000 && (words[2] >> 31) == 0u; ++wait) Sleep(1); | ||
| 805 | reconfigured &= (words[2] >> 31) == 1u && ((words[0] >> 27) & 0x1Fu) == (stereo ? 8u : 4u); | ||
| 806 | #if defined(LEONIDA_HAVE_XMA2_DECODER) | ||
| 807 | reconfigured &= has_signal(ring_bytes); | ||
| 808 | #endif | ||
| 809 | } | ||
| 810 | check(reconfigured, "Re-enabled voices select mono or stereo PCM at all four sample rates"); | ||
| 811 | check(fn_submit(x_acp, 8, 0, 0xffffffffu, &voice_bit, 0) == S_OK, | ||
| 812 | "DISABLE_XMAS stops the selected voice"); | ||
| 813 | |||
| 814 | configure_voice(0, 3, 4, 0, 0); | ||
| 815 | write_xma_packet(packets, 1, 1); | ||
| 816 | fail_worker_allocation.store(true); | ||
| 817 | check(fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK, | ||
| 818 | "Enable a voice before an injected worker allocation failure"); | ||
| 819 | for (int wait = 0; wait < 1000 && (words[2] >> 31) == 0u; ++wait) Sleep(1); | ||
| 820 | check(!fail_worker_allocation.exchange(false) && (words[2] >> 31) != 0u, | ||
| 821 | "Worker allocation failure surfaces an XMA error without terminating the process"); | ||
| 822 | check(fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(), | ||
| 823 | "A voice can run again after a worker allocation failure"); | ||
| 824 | |||
| 825 | check(release_ctx(x_acp) == S_OK, "Release SHAPE contexts through the opaque AcpHal handle"); | ||
| 826 | check(fn_release(x_acp) == S_OK, "Release packet loop AcpHal succeeds"); | ||
| 827 | free_mem(in_va); | ||
| 828 | free_mem(out_va); | ||
| 829 | check(release_ctx(&xma_ctx) == S_OK, "Release packet loop SHAPE contexts"); | ||
| 830 | } | ||
| 831 | |||
| 832 | // 9. ENABLE_XMA racing SHAPE allocation and release, including concurrent releases. | ||
| 833 | { | ||
| 834 | using RaceConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); | ||
| 835 | using RaceSubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t); | ||
| 836 | using RaceReleaseFn = HRESULT(__stdcall*)(void*); | ||
| 837 | |||
| 838 | void* race_acp = nullptr; | ||
| 839 | check(create(&race_acp) == S_OK && race_acp != nullptr, "AcpHalCreate for XMA race test"); | ||
| 840 | auto race_vt = *static_cast<void* const* const*>(race_acp); | ||
| 841 | const auto race_connect = reinterpret_cast<RaceConnectFn>(race_vt[0]); | ||
| 842 | const auto race_submit = reinterpret_cast<RaceSubmitFn>(race_vt[2]); | ||
| 843 | const auto race_release = reinterpret_cast<RaceReleaseFn>(race_vt[5]); | ||
| 844 | check(race_connect(race_acp, 0x1000, 0x1000) == S_OK, "Connect for XMA race test"); | ||
| 845 | |||
| 846 | constexpr int kRaceIterations = 20000; | ||
| 847 | std::atomic<int> bind_failures{0}; | ||
| 848 | std::thread enabler([&]() { | ||
| 849 | const uint32_t enable_arg = 1u; | ||
| 850 | for (int i = 0; i < kRaceIterations; ++i) { | ||
| 851 | race_submit(race_acp, 5, 0xe000u + static_cast<uint64_t>(i), 0xffffffffu, | ||
| 852 | &enable_arg, 0); | ||
| 853 | } | ||
| 854 | }); | ||
| 855 | std::thread releaser([&]() { | ||
| 856 | for (int i = 0; i < kRaceIterations; ++i) { | ||
| 857 | if (release_ctx(nullptr) != S_OK) ++bind_failures; | ||
| 858 | } | ||
| 859 | }); | ||
| 860 | for (int i = 0; i < kRaceIterations; ++i) { | ||
| 861 | TestShapeContexts race_ctx{}; | ||
| 862 | race_ctx.numXmaContexts = 4; | ||
| 863 | if (alloc_ctx(&race_ctx) != S_OK) ++bind_failures; | ||
| 864 | if (release_ctx(&race_ctx) != S_OK) ++bind_failures; | ||
| 865 | } | ||
| 866 | enabler.join(); | ||
| 867 | releaser.join(); | ||
| 868 | check(bind_failures == 0, "20000 bind/release cycles race ENABLE_XMA and independent releases"); | ||
| 869 | check(race_release(race_acp) == S_OK, "Release race AcpHal succeeds"); | ||
| 870 | } | ||
| 871 | |||
| 260 | std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures); | 872 | std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures); |
| 261 | return g_failures ? 1 : 0; | 873 | return g_failures ? 1 : 0; |
| 262 | } | 874 | } |
diff --git a/runtime/test/check_sparse_queue_family.py b/runtime/test/check_sparse_queue_family.py index 27ebc1f5d..b16e4121c 100644 --- a/runtime/test/check_sparse_queue_family.py +++ b/runtime/test/check_sparse_queue_family.py | |||
| @@ -29,6 +29,19 @@ SPARSE_FLAGS = "VkBufferCreateFlags = 7 (VK_BUFFER_CREATE_SPARSE_BINDING_BIT" | |||
| 29 | MODE = re.compile(r"sharingMode:\s+VkSharingMode = (VK_SHARING_MODE_\w+)") | 29 | MODE = re.compile(r"sharingMode:\s+VkSharingMode = (VK_SHARING_MODE_\w+)") |
| 30 | COUNT = re.compile(r"queueFamilyIndexCount:\s+uint32_t = (\d+)") | 30 | COUNT = re.compile(r"queueFamilyIndexCount:\s+uint32_t = (\d+)") |
| 31 | INDICES = re.compile(r"pQueueFamilyIndices\[(\d+)\]:\s+const uint32_t = (\d+)") | 31 | INDICES = re.compile(r"pQueueFamilyIndices\[(\d+)\]:\s+const uint32_t = (\d+)") |
| 32 | CREATE_DEVICE = re.compile(r"^vkCreateDevice\(.*?(?=^vk\w+\(|\Z)", re.M | re.S) | ||
| 33 | QUEUE_FAMILY_PROPS = re.compile(r"^vkGetPhysicalDeviceQueueFamilyProperties\(.*?(?=^vk\w+\(|\Z)", re.M | re.S) | ||
| 34 | PHYS_DEVICE = re.compile(r"physicalDevice:\s+VkPhysicalDevice\s*=\s*([0-9a-fA-Fx]+)") | ||
| 35 | QUEUE_CREATE_COUNT = re.compile(r"queueCreateInfoCount:\s+uint32_t\s*=\s*(\d+)") | ||
| 36 | QUEUE_FAMILY_INDEX = re.compile( | ||
| 37 | r"pQueueCreateInfos\[0\]:(?:(?!pQueueCreateInfos\[|enabledLayerCount).)*?queueFamilyIndex:\s+uint32_t\s*=\s*(\d+)", | ||
| 38 | re.S, | ||
| 39 | ) | ||
| 40 | QUEUE_FAMILY_PROP_COUNT = re.compile(r"pQueueFamilyPropertyCount:\s+uint32_t\*\s*=\s*(\d+)") | ||
| 41 | VK_QUEUE_GRAPHICS_BIT = 0x1 | ||
| 42 | VK_QUEUE_COMPUTE_BIT = 0x2 | ||
| 43 | VK_QUEUE_TRANSFER_BIT = 0x4 | ||
| 44 | VK_QUEUE_SPARSE_BINDING_BIT = 0x8 | ||
| 32 | # Each of the two runs gets 30 s, so both together stay inside the CTest TIMEOUT of 65 s (runtime/CMakeLists.txt). | 45 | # Each of the two runs gets 30 s, so both together stay inside the CTest TIMEOUT of 65 s (runtime/CMakeLists.txt). |
| 33 | RUN_TIMEOUT = 30 | 46 | RUN_TIMEOUT = 30 |
| 34 | ACCESS_VIOLATION = 0xC0000005 # STATUS_ACCESS_VIOLATION, as Windows reports it in the exit code | 47 | ACCESS_VIOLATION = 0xC0000005 # STATUS_ACCESS_VIOLATION, as Windows reports it in the exit code |
| @@ -38,7 +51,118 @@ CALL_HEAD = re.compile(r"^(vk\w+)\(", re.M) | |||
| 38 | CASE = re.compile(r"^RESULT (LAYER_MAP_(?:DIRECT|COPY|COMPUTE)_COPY_COMPUTE) PASS mapped_mismatch=0/65536 unmapped_nonzero=0/65536$", re.M) | 51 | CASE = re.compile(r"^RESULT (LAYER_MAP_(?:DIRECT|COPY|COMPUTE)_COPY_COMPUTE) PASS mapped_mismatch=0/65536 unmapped_nonzero=0/65536$", re.M) |
| 39 | 52 | ||
| 40 | 53 | ||
| 41 | def check_trace(path: Path, expect_exclusive: bool) -> tuple[int, int]: | 54 | def _pick_sparse_queue_families(families: list[tuple[int, int, int, int, int]], |
| 55 | graphics: int) -> tuple[int, int, int]: | ||
| 56 | """Mirror runtime/src/queue_families.h (pick_queue_families + sparse_capable_queue_families).""" | ||
| 57 | def fine_grained(family: tuple[int, int, int, int, int]) -> bool: | ||
| 58 | return family[2:] == (1, 1, 1) | ||
| 59 | |||
| 60 | compute = copy = graphics | ||
| 61 | have_compute = have_copy = False | ||
| 62 | for i, family in enumerate(families): | ||
| 63 | flags, count = family[0], family[1] | ||
| 64 | if count == 0: | ||
| 65 | continue | ||
| 66 | if not have_compute and (flags & VK_QUEUE_COMPUTE_BIT) and not (flags & VK_QUEUE_GRAPHICS_BIT): | ||
| 67 | compute = i | ||
| 68 | have_compute = True | ||
| 69 | if (not have_copy and (flags & VK_QUEUE_TRANSFER_BIT) | ||
| 70 | and not (flags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)) and fine_grained(family)): | ||
| 71 | copy = i | ||
| 72 | have_copy = True | ||
| 73 | if not have_copy and have_compute and fine_grained(families[compute]): | ||
| 74 | copy = compute | ||
| 75 | if not (families[compute][0] & VK_QUEUE_SPARSE_BINDING_BIT): | ||
| 76 | compute = graphics | ||
| 77 | if not (families[copy][0] & VK_QUEUE_SPARSE_BINDING_BIT): | ||
| 78 | copy = graphics | ||
| 79 | return graphics, compute, copy | ||
| 80 | |||
| 81 | |||
| 82 | def single_sparse_queue_family(path: Path) -> bool: | ||
| 83 | """True when vkCreateDevice uses 1 queue family and the physical device yields only 1 sparse-capable family. | ||
| 84 | |||
| 85 | Mirrors runtime/src/queue_families.h (pick_queue_families + sparse_capable_queue_families): Leonida picks the | ||
| 86 | first non-graphics async compute or fine-grained (1x1x1) DMA transfer family, then falls back to graphics if the | ||
| 87 | chosen family lacks SPARSE_BINDING. On single-family GPUs (e.g. Intel Xe-LP iGPUs), VK_SHARING_MODE_CONCURRENT | ||
| 88 | is illegal (VUID-00914). | ||
| 89 | """ | ||
| 90 | text = path.read_text(encoding="utf-8", errors="replace") | ||
| 91 | devices = CREATE_DEVICE.findall(text) | ||
| 92 | if len(devices) != 1: | ||
| 93 | return False | ||
| 94 | pdev_m = PHYS_DEVICE.search(devices[0]) | ||
| 95 | qci_m = QUEUE_CREATE_COUNT.search(devices[0]) | ||
| 96 | if not pdev_m or not qci_m or int(qci_m.group(1)) != 1: | ||
| 97 | return False | ||
| 98 | pdev = pdev_m.group(1) | ||
| 99 | created_graphics: int | None = None | ||
| 100 | if "pQueueCreateInfos[" in devices[0]: | ||
| 101 | qfi_m = QUEUE_FAMILY_INDEX.search(devices[0]) | ||
| 102 | if not qfi_m: | ||
| 103 | return False | ||
| 104 | created_graphics = int(qfi_m.group(1)) | ||
| 105 | |||
| 106 | families: list[tuple[int, int, int, int, int]] | None = None | ||
| 107 | max_expected = 0 | ||
| 108 | for call in QUEUE_FAMILY_PROPS.findall(text): | ||
| 109 | after = call.split("<after returning from implementation>", 1) | ||
| 110 | if "<before calling into implementation>" in call and len(after) != 2: | ||
| 111 | pm = PHYS_DEVICE.search(call) | ||
| 112 | if pm and pm.group(1) == pdev: | ||
| 113 | return False | ||
| 114 | continue | ||
| 115 | body = after[1] if len(after) == 2 else call | ||
| 116 | pm = PHYS_DEVICE.search(body) | ||
| 117 | if not pm or pm.group(1) != pdev: | ||
| 118 | continue | ||
| 119 | cnt_m = QUEUE_FAMILY_PROP_COUNT.search(body) | ||
| 120 | if cnt_m: | ||
| 121 | max_expected = max(max_expected, int(cnt_m.group(1))) | ||
| 122 | if "pQueueFamilyProperties[" not in body: | ||
| 123 | continue | ||
| 124 | if not cnt_m: | ||
| 125 | return False | ||
| 126 | expected = int(cnt_m.group(1)) | ||
| 127 | if expected <= 0: | ||
| 128 | return False | ||
| 129 | chunks = re.split(r"(?=pQueueFamilyProperties\[\d+\]:)", body)[1:] | ||
| 130 | if len(chunks) != expected: | ||
| 131 | return False | ||
| 132 | parsed: dict[int, tuple[int, int, int, int, int]] = {} | ||
| 133 | for chunk in chunks: | ||
| 134 | im = re.match(r"pQueueFamilyProperties\[(\d+)\]:", chunk) | ||
| 135 | fm = re.search(r"queueFlags:\s+VkQueueFlags\s*=\s*(\d+)", chunk) | ||
| 136 | cm = re.search(r"queueCount:\s+uint32_t\s*=\s*(\d+)", chunk) | ||
| 137 | wm = re.search(r"width:\s+uint32_t\s*=\s*(\d+)", chunk) | ||
| 138 | hm = re.search(r"height:\s+uint32_t\s*=\s*(\d+)", chunk) | ||
| 139 | dm = re.search(r"depth:\s+uint32_t\s*=\s*(\d+)", chunk) | ||
| 140 | if not (im and fm and cm and wm and hm and dm): | ||
| 141 | return False | ||
| 142 | idx = int(im.group(1)) | ||
| 143 | if idx >= expected or idx in parsed: | ||
| 144 | return False | ||
| 145 | parsed[idx] = (int(fm.group(1)), int(cm.group(1)), int(wm.group(1)), int(hm.group(1)), int(dm.group(1))) | ||
| 146 | if len(parsed) != expected: | ||
| 147 | return False | ||
| 148 | families = [parsed[i] for i in range(expected)] | ||
| 149 | if not families or len(families) != max_expected: | ||
| 150 | return False | ||
| 151 | |||
| 152 | graphics = (created_graphics if created_graphics is not None | ||
| 153 | else next((i for i, (flags, count, *_) in enumerate(families) | ||
| 154 | if count > 0 and (flags & VK_QUEUE_GRAPHICS_BIT)), None)) | ||
| 155 | if graphics is None or graphics >= len(families): | ||
| 156 | return False | ||
| 157 | g_flags, g_count = families[graphics][0], families[graphics][1] | ||
| 158 | if g_count == 0 or not (g_flags & VK_QUEUE_GRAPHICS_BIT) or not (g_flags & VK_QUEUE_SPARSE_BINDING_BIT): | ||
| 159 | return False | ||
| 160 | |||
| 161 | direct, compute, copy = _pick_sparse_queue_families(families, graphics) | ||
| 162 | return compute == direct and copy == direct | ||
| 163 | |||
| 164 | |||
| 165 | def check_trace(path: Path, expect_exclusive: bool, *, single_family: bool = False) -> tuple[int, int]: | ||
| 42 | rows = path.read_text(encoding="utf-8", errors="replace").splitlines() | 166 | rows = path.read_text(encoding="utf-8", errors="replace").splitlines() |
| 43 | records = 0 | 167 | records = 0 |
| 44 | for i, line in enumerate(rows): | 168 | for i, line in enumerate(rows): |
| @@ -53,8 +177,11 @@ def check_trace(path: Path, expect_exclusive: bool) -> tuple[int, int]: | |||
| 53 | raise AssertionError(f"incomplete API dump sparse VkBuffer at line {i+1}") | 177 | raise AssertionError(f"incomplete API dump sparse VkBuffer at line {i+1}") |
| 54 | sharing, n = mode.group(1), int(count.group(1)) | 178 | sharing, n = mode.group(1), int(count.group(1)) |
| 55 | indices = [(int(slot), int(family)) for slot, family in INDICES.findall(tail)] | 179 | indices = [(int(slot), int(family)) for slot, family in INDICES.findall(tail)] |
| 56 | if expect_exclusive: | 180 | if expect_exclusive or single_family: |
| 57 | if sharing != "VK_SHARING_MODE_EXCLUSIVE" or n != 0 or indices: | 181 | if sharing != "VK_SHARING_MODE_EXCLUSIVE" or n != 0 or indices: |
| 182 | if single_family and not expect_exclusive: | ||
| 183 | raise AssertionError(f"invalid sparse buffer on single-family device at line {i+1}: " | ||
| 184 | f"{sharing}, count={n}, indices={indices}") | ||
| 58 | raise AssertionError(f"baseline negative control not reproduced at line {i+1}") | 185 | raise AssertionError(f"baseline negative control not reproduced at line {i+1}") |
| 59 | elif (sharing != "VK_SHARING_MODE_CONCURRENT" or n < 2 or len(indices) != n | 186 | elif (sharing != "VK_SHARING_MODE_CONCURRENT" or n < 2 or len(indices) != n |
| 60 | or len({slot for slot, _ in indices if slot < n}) != n | 187 | or len({slot for slot, _ in indices if slot < n}) != n |
| @@ -101,13 +228,18 @@ def main() -> int: | |||
| 101 | if not candidates: | 228 | if not candidates: |
| 102 | print("SKIP 77: Vulkan SDK VK_LAYER_LUNARG_api_dump unavailable or did not write trace") | 229 | print("SKIP 77: Vulkan SDK VK_LAYER_LUNARG_api_dump unavailable or did not write trace") |
| 103 | return 77 | 230 | return 77 |
| 104 | calls, infos = check_trace(candidates[0], args.expect_baseline_exclusive) | 231 | single_family = single_sparse_queue_family(candidates[0]) |
| 232 | calls, infos = check_trace(candidates[0], args.expect_baseline_exclusive, single_family=single_family) | ||
| 105 | validation_out, skip = run_pass(exe, validation_env, path) | 233 | validation_out, skip = run_pass(exe, validation_env, path) |
| 106 | if skip: | 234 | if skip: |
| 107 | return skip | 235 | return skip |
| 108 | errors = [line for line in validation_out.splitlines() if "Validation Error" in line or "VUID-" in line] | 236 | errors = [line for line in validation_out.splitlines() if "Validation Error" in line or "VUID-" in line] |
| 109 | if errors: | 237 | if errors: |
| 110 | raise AssertionError(f"Khronos validation reported {len(errors)} error line(s); first: {errors[0][:300]}") | 238 | raise AssertionError(f"Khronos validation reported {len(errors)} error line(s); first: {errors[0][:300]}") |
| 239 | if single_family: | ||
| 240 | print(f"SKIP 77: GPU exposes only 1 sparse-capable queue family; cross-family CONCURRENT sparse buffer " | ||
| 241 | f"contract requires 2+ families ({calls} EXCLUSIVE sparse VkBuffer creations and Khronos validation passed)") | ||
| 242 | return 77 | ||
| 111 | kinds = sorted(CASE.findall(dump_out)) | 243 | kinds = sorted(CASE.findall(dump_out)) |
| 112 | print(f"GPU PASS: {len(kinds)} COPY/COMPUTE sparse queue cases, mapped 65,536 bytes exact, unmapped 65,536 zeros") | 244 | print(f"GPU PASS: {len(kinds)} COPY/COMPUTE sparse queue cases, mapped 65,536 bytes exact, unmapped 65,536 zeros") |
| 113 | print(f"VK API CONTRACT PASS: {calls} sparse VkBuffer creations / {infos} create-info records = " | 245 | print(f"VK API CONTRACT PASS: {calls} sparse VkBuffer creations / {infos} create-info records = " |
diff --git a/runtime/test/cpu_emulation_test.cpp b/runtime/test/cpu_emulation_test.cpp index 4e1ef3cdb..f94f08044 100644 --- a/runtime/test/cpu_emulation_test.cpp +++ b/runtime/test/cpu_emulation_test.cpp | |||
| @@ -145,6 +145,56 @@ void test_apply() { | |||
| 145 | check(fault.ExceptionCode == STATUS_ACCESS_VIOLATION && fault.NumberParameters == 2 && | 145 | check(fault.ExceptionCode == STATUS_ACCESS_VIOLATION && fault.NumberParameters == 2 && |
| 146 | fault.ExceptionInformation[0] == 1 && fault.ExceptionInformation[1] == 0, | 146 | fault.ExceptionInformation[0] == 1 && fault.ExceptionInformation[1] == 0, |
| 147 | "clzero on an unwritable line reports a write access violation at the line"); | 147 | "clzero on an unwritable line reports a write access violation at the line"); |
| 148 | |||
| 149 | // try_clzero_loop EFlags: first-line fault keeps incoming flags, post-prefix fault and >64 MiB batch apply CMP. | ||
| 150 | const uint8_t loop12[] = {0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4}; | ||
| 151 | if (auto* two_pages = static_cast<uint8_t*>(VirtualAlloc(nullptr, 8192, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) { | ||
| 152 | const uint64_t start = reinterpret_cast<uint64_t>(two_pages); | ||
| 153 | DWORD old = 0; | ||
| 154 | VirtualProtect(two_pages, 8192, PAGE_READONLY, &old); | ||
| 155 | c = {}; | ||
| 156 | c.Rax = start; | ||
| 157 | c.Rdx = start + 8192; | ||
| 158 | c.Rip = rip; | ||
| 159 | c.EFlags = 0x202; | ||
| 160 | check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::faulted && | ||
| 161 | c.Rax == start && c.Rip == rip && c.EFlags == 0x202, | ||
| 162 | "clzero loop fault on first line preserves entry EFlags"); | ||
| 163 | |||
| 164 | VirtualProtect(two_pages, 4096, PAGE_READWRITE, &old); | ||
| 165 | std::memset(two_pages, 0x5A, 4096); | ||
| 166 | c = {}; | ||
| 167 | c.Rax = start; | ||
| 168 | c.Rdx = start + 8192; | ||
| 169 | c.Rip = rip; | ||
| 170 | c.EFlags = 0x246; // ZF=1, CF=0 on entry | ||
| 171 | check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::faulted, | ||
| 172 | "clzero loop post-prefix fault reported"); | ||
| 173 | bool prefix_zeroed = true; | ||
| 174 | for (int i = 0; i < 4096; ++i) prefix_zeroed &= two_pages[i] == 0; | ||
| 175 | check(prefix_zeroed && c.Rax == start + 4096 && c.Rip == rip && | ||
| 176 | fault.ExceptionCode == STATUS_ACCESS_VIOLATION && fault.ExceptionInformation[1] == start + 4096 && | ||
| 177 | (c.EFlags & 0xC1u) == 0x81u, | ||
| 178 | "clzero loop post-prefix fault zeroes prefix and applies CMP flags (CF=1, ZF=0, SF=1)"); | ||
| 179 | VirtualFree(two_pages, 0, MEM_RELEASE); | ||
| 180 | } | ||
| 181 | |||
| 182 | constexpr size_t kLargeSpan = (size_t(64) << 20) + 4096; | ||
| 183 | if (auto* large = static_cast<uint8_t*>(VirtualAlloc(nullptr, kLargeSpan, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) { | ||
| 184 | const uint64_t base = reinterpret_cast<uint64_t>(large); | ||
| 185 | c = {}; | ||
| 186 | c.Rax = base; | ||
| 187 | c.Rdx = base + kLargeSpan; | ||
| 188 | c.Rip = rip; | ||
| 189 | c.EFlags = 0x202; | ||
| 190 | check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::ok && | ||
| 191 | c.Rip == rip && c.Rax == base + (uint64_t(64) << 20) && (c.EFlags & 0xC1u) == 0x81u, | ||
| 192 | "clzero loop >64 MiB first batch applies CMP flags (CF=1, ZF=0, SF=1)"); | ||
| 193 | check(ce::try_clzero_loop(loop12, sizeof loop12, &c, &fault) == ce::ClzeroLoopResult::ok && | ||
| 194 | c.Rip == rip + 12 && c.Rax == base + kLargeSpan && (c.EFlags & 0xC1u) == 0x40u, | ||
| 195 | "clzero loop >64 MiB second batch completes with CF=0, ZF=1, SF=0"); | ||
| 196 | VirtualFree(large, 0, MEM_RELEASE); | ||
| 197 | } | ||
| 148 | } | 198 | } |
| 149 | 199 | ||
| 150 | // ---- Running the real encodings ---- | 200 | // ---- Running the real encodings ---- |
| @@ -244,6 +294,33 @@ void test_live(const ce::Host& host) { | |||
| 244 | "clzero with 66 emulated"); | 294 | "clzero with 66 emulated"); |
| 245 | } | 295 | } |
| 246 | 296 | ||
| 297 | // clzero loop fast-path: mov rax, rcx; clzero; add rax, 0x40; cmp rax, rdx; jb -12; ret | ||
| 298 | { | ||
| 299 | alignas(64) static uint8_t buf[512]; | ||
| 300 | std::memset(buf, 0xA5, sizeof buf); | ||
| 301 | Code clz_loop({0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4, 0xC3}); | ||
| 302 | check(run(clz_loop, buf + 64, buf + 320, &ex), "clzero loop ran"); | ||
| 303 | bool loop_ok = true; | ||
| 304 | for (int i = 0; i < 512; ++i) loop_ok &= buf[i] == ((i >= 64 && i < 320) ? 0 : 0xA5); | ||
| 305 | check(loop_ok, "clzero loop zeroed exact span [64, 320)"); | ||
| 306 | |||
| 307 | // REX.R limit register (r8): mov rax, rcx; mov r8, rdx; clzero; add rax, 0x40; cmp rax, r8; jb -12; ret | ||
| 308 | std::memset(buf, 0xA5, sizeof buf); | ||
| 309 | Code clz_r8({0x48, 0x89, 0xC8, 0x49, 0x89, 0xD0, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xC0, | ||
| 310 | 0x72, 0xF4, 0xC3}); | ||
| 311 | check(run(clz_r8, buf + 64, buf + 320, &ex), "clzero loop (r8) ran"); | ||
| 312 | bool r8_ok = true; | ||
| 313 | for (int i = 0; i < 512; ++i) r8_ok &= buf[i] == ((i >= 64 && i < 320) ? 0 : 0xA5); | ||
| 314 | check(r8_ok, "clzero loop (r8) zeroed exact span [64, 320)"); | ||
| 315 | |||
| 316 | // Non-multiple-of-64 limit (300): rounds up to 320, matching native do-while `cmp rax, limit; jb`. | ||
| 317 | std::memset(buf, 0xA5, sizeof buf); | ||
| 318 | check(run(clz_loop, buf + 64, buf + 300, &ex), "clzero loop (unaligned limit) ran"); | ||
| 319 | bool unaligned_ok = true; | ||
| 320 | for (int i = 0; i < 512; ++i) unaligned_ok &= buf[i] == ((i >= 64 && i < 320) ? 0 : 0xA5); | ||
| 321 | check(unaligned_ok, "clzero loop (unaligned limit 300) zeroed span [64, 320)"); | ||
| 322 | } | ||
| 323 | |||
| 247 | // mov rax,rcx; xor ecx,ecx; xor edx,edx; monitorx; xor eax,eax; xor ecx,ecx; mwaitx; ret | 324 | // mov rax,rcx; xor ecx,ecx; xor edx,edx; monitorx; xor eax,eax; xor ecx,ecx; mwaitx; ret |
| 248 | // (no timer: an interrupt or a store ends a native wait; the emulated one returns at once) | 325 | // (no timer: an interrupt or a store ends a native wait; the emulated one returns at once) |
| 249 | Code mon({0x48, 0x89, 0xC8, 0x31, 0xC9, 0x31, 0xD2, 0x0F, 0x01, 0xFA, 0x31, 0xC0, 0x31, 0xC9, 0x0F, 0x01, 0xFB, | 326 | Code mon({0x48, 0x89, 0xC8, 0x31, 0xC9, 0x31, 0xD2, 0x0F, 0x01, 0xFA, 0x31, 0xC0, 0x31, 0xC9, 0x0F, 0x01, 0xFB, |
diff --git a/runtime/test/d3d12_clear_test.cpp b/runtime/test/d3d12_clear_test.cpp index 46c467ca9..abc3b0bd7 100644 --- a/runtime/test/d3d12_clear_test.cpp +++ b/runtime/test/d3d12_clear_test.cpp | |||
| @@ -6,7 +6,9 @@ | |||
| 6 | #include "vk_test_device.h" | 6 | #include "vk_test_device.h" |
| 7 | #include "../shims/d3d12_com.h" | 7 | #include "../shims/d3d12_com.h" |
| 8 | #include <dxgi1_4.h> | 8 | #include <dxgi1_4.h> |
| 9 | #include <algorithm> | ||
| 9 | #include <array> | 10 | #include <array> |
| 11 | #include <cmath> | ||
| 10 | #include <vector> | 12 | #include <vector> |
| 11 | #include <cstring> | 13 | #include <cstring> |
| 12 | #include <cstdint> | 14 | #include <cstdint> |
| @@ -375,10 +377,9 @@ bool check_unlisted_rtvs(ID3D12Device* device) { | |||
| 375 | } // namespace | 377 | } // namespace |
| 376 | 378 | ||
| 377 | // ClearDepthStencilView values at the edge of what D3D12 accepts: on a D32_FLOAT target a depth outside [0, 1] and a | 379 | // ClearDepthStencilView values at the edge of what D3D12 accepts: on a D32_FLOAT target a depth outside [0, 1] and a |
| 378 | // NaN are stored exactly as given, and flags that name no plane clear nothing (the target keeps the value of the clear | 380 | // NaN are stored exactly as given by WARP; flags that name no plane clear nothing. On Vulkan the float values |
| 379 | // before it). WARP shows both in the read-back, and the layer must show the same texels; a call the layer refuses fails | 381 | // can be preserved with unrestricted depth. Also check the legal [0, 1] clear values on a restricted device. |
| 380 | // Close() inside clear_depth_and_read. | 382 | bool check_depth_clear_edge_values(ID3D12Device* host, ID3D12Device* ours, bool unrestricted_depth) { |
| 381 | bool check_depth_clear_edge_values(ID3D12Device* host, ID3D12Device* ours) { | ||
| 382 | constexpr UINT width = 5, height = 3; | 383 | constexpr UINT width = 5, height = 3; |
| 383 | const auto read = [](ID3D12Device* device, FLOAT depth_full, FLOAT depth_part, bool part_no_flags, | 384 | const auto read = [](ID3D12Device* device, FLOAT depth_full, FLOAT depth_part, bool part_no_flags, |
| 384 | std::vector<unsigned char>& depth) { | 385 | std::vector<unsigned char>& depth) { |
| @@ -402,34 +403,40 @@ bool check_depth_clear_edge_values(ID3D12Device* host, ID3D12Device* ours) { | |||
| 402 | std::memcpy(&warp_value, expected.data() + at, 4); | 403 | std::memcpy(&warp_value, expected.data() + at, 4); |
| 403 | std::fprintf(stderr, "%s (%u,%u): WARP cleared %g, expected %g\n", what, x, y, warp_value, want); | 404 | std::fprintf(stderr, "%s (%u,%u): WARP cleared %g, expected %g\n", what, x, y, warp_value, want); |
| 404 | ++wrong; | 405 | ++wrong; |
| 405 | } else if (std::memcmp(got.data() + at, expected.data() + at, 4)) { | 406 | } |
| 406 | FLOAT warp_value, layer_value; | 407 | FLOAT want_layer = want; |
| 407 | std::memcpy(&warp_value, expected.data() + at, 4); | 408 | if (!unrestricted_depth) |
| 409 | want_layer = std::isnan(want) ? 0.0f : std::clamp(want, 0.0f, 1.0f); | ||
| 410 | if (std::memcmp(got.data() + at, &want_layer, 4)) { | ||
| 411 | FLOAT layer_value; | ||
| 408 | std::memcpy(&layer_value, got.data() + at, 4); | 412 | std::memcpy(&layer_value, got.data() + at, 4); |
| 409 | std::fprintf(stderr, "%s (%u,%u): layer cleared %g, WARP %g\n", what, x, y, layer_value, | 413 | std::fprintf(stderr, "%s (%u,%u): layer cleared %g, expected %g\n", what, x, y, layer_value, |
| 410 | warp_value); | 414 | want_layer); |
| 411 | ++wrong; | 415 | ++wrong; |
| 412 | } | 416 | } |
| 413 | } | 417 | } |
| 414 | if (wrong) return false; | 418 | if (wrong) return false; |
| 415 | std::printf("%s: %ux%u depth texels match WARP\n", what, width, height); | 419 | std::printf("%s: %ux%u depth texels matched (%s)\n", what, width, height, |
| 420 | unrestricted_depth ? "WARP parity" : "restricted Vulkan depth"); | ||
| 416 | return true; | 421 | return true; |
| 417 | }; | 422 | }; |
| 418 | if (!compare("depth 1.5 and -0.5 are stored as given", 1.5f, -0.5f, false, 1.5f, -0.5f)) return false; | 423 | if (!compare("depth clear with 1.5 and -0.5", 1.5f, -0.5f, false, 1.5f, -0.5f)) return false; |
| 419 | // NaN is likewise not clamped away; WARP stores the quiet NaN it was given. | 424 | // NaN is likewise not clamped away; WARP stores the quiet NaN it was given. |
| 420 | const FLOAT nan = std::numeric_limits<float>::quiet_NaN(); | 425 | const FLOAT nan = std::numeric_limits<float>::quiet_NaN(); |
| 421 | if (!compare("a NaN depth stays NaN", nan, nan, false, nan, nan)) return false; | 426 | if (!compare("depth clear with NaN", nan, nan, false, nan, nan)) return false; |
| 422 | return compare("flags 0 leaves the target alone", 0.25f, 0.75f, true, 0.25f, 0.25f); | 427 | return compare("flags 0 leaves the target alone", 0.25f, 0.75f, true, 0.25f, 0.25f); |
| 423 | } | 428 | } |
| 424 | 429 | ||
| 425 | int main(int argc, char** argv) { | 430 | int main(int argc, char** argv) { |
| 426 | const bool volume_only = argc == 2 && std::strcmp(argv[1], "--volume") == 0; | 431 | const bool volume_only = argc == 2 && std::strcmp(argv[1], "--volume") == 0; |
| 427 | const bool rgb9e5_only = argc == 2 && std::strcmp(argv[1], "--rgb9e5") == 0; | 432 | const bool rgb9e5_only = argc == 2 && std::strcmp(argv[1], "--rgb9e5") == 0; |
| 428 | if (argc != 1 && !volume_only && !rgb9e5_only) { | 433 | const bool restricted_depth = argc == 2 && std::strcmp(argv[1], "--restricted-depth") == 0; |
| 429 | std::fprintf(stderr, "usage: d3d12_clear_test [--volume|--rgb9e5]\n"); | 434 | if (argc != 1 && !volume_only && !rgb9e5_only && !restricted_depth) { |
| 435 | std::fprintf(stderr, "usage: d3d12_clear_test [--volume|--rgb9e5|--restricted-depth]\n"); | ||
| 430 | return 2; | 436 | return 2; |
| 431 | } | 437 | } |
| 432 | vktest::Device vk; | 438 | vktest::Device vk; |
| 439 | vk.request_depth_range_unrestricted = !restricted_depth && !volume_only && !rgb9e5_only; | ||
| 433 | const auto device_status = vk.initialize(); | 440 | const auto device_status = vk.initialize(); |
| 434 | if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips | 441 | if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips |
| 435 | if (device_status != vktest::DeviceStatus::ready) return 1; | 442 | if (device_status != vktest::DeviceStatus::ready) return 1; |
| @@ -444,6 +451,7 @@ int main(int argc, char** argv) { | |||
| 444 | info.device = vk.device; | 451 | info.device = vk.device; |
| 445 | info.queue = vk.queue; | 452 | info.queue = vk.queue; |
| 446 | info.queue_family = vk.family; | 453 | info.queue_family = vk.family; |
| 454 | info.depth_range_unrestricted = vk.depth_range_unrestricted; | ||
| 447 | if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; | 455 | if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; |
| 448 | if (rgb9e5_only) { | 456 | if (rgb9e5_only) { |
| 449 | D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; | 457 | D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; |
| @@ -470,10 +478,12 @@ int main(int argc, char** argv) { | |||
| 470 | std::fprintf(stderr, "WARP reference unavailable: differential test cannot run\n"); | 478 | std::fprintf(stderr, "WARP reference unavailable: differential test cannot run\n"); |
| 471 | return 1; | 479 | return 1; |
| 472 | } | 480 | } |
| 481 | if (restricted_depth) | ||
| 482 | return check_depth_clear_edge_values(host.p, ours.p, false) ? 0 : 1; | ||
| 473 | if (!check_volume_rtvs(host.p, ours.p)) return 1; | 483 | if (!check_volume_rtvs(host.p, ours.p)) return 1; |
| 474 | if (volume_only) return 0; | 484 | if (volume_only) return 0; |
| 475 | if (!check_unlisted_rtvs(ours.p)) return 1; | 485 | if (!check_unlisted_rtvs(ours.p)) return 1; |
| 476 | if (!check_depth_clear_edge_values(host.p, ours.p)) return 1; | 486 | if (!check_depth_clear_edge_values(host.p, ours.p, vk.depth_range_unrestricted)) return 1; |
| 477 | const float nan = std::numeric_limits<float>::quiet_NaN(), inf = std::numeric_limits<float>::infinity(); | 487 | const float nan = std::numeric_limits<float>::quiet_NaN(), inf = std::numeric_limits<float>::infinity(); |
| 478 | // Integer-format values: negatives, fractions, NaN and overflow exercise the numeric float->int conversion. | 488 | // Integer-format values: negatives, fractions, NaN and overflow exercise the numeric float->int conversion. |
| 479 | const std::array<float, 4> int_values[] = { | 489 | const std::array<float, 4> int_values[] = { |
| @@ -677,7 +687,7 @@ int main(int argc, char** argv) { | |||
| 677 | static_cast<unsigned long long>(validation_errors)); | 687 | static_cast<unsigned long long>(validation_errors)); |
| 678 | if (validation_errors) return 1; | 688 | if (validation_errors) return 1; |
| 679 | if (compare_failed) return compare_failed; | 689 | if (compare_failed) return compare_failed; |
| 680 | if (volume_only || rgb9e5_only) return 0; | 690 | if (volume_only || rgb9e5_only || restricted_depth) return 0; |
| 681 | std::printf("RTV and DSV clears: %u full/rectangle readbacks matched WARP\n", cases_checked); | 691 | std::printf("RTV and DSV clears: %u full/rectangle readbacks matched WARP\n", cases_checked); |
| 682 | return 0; | 692 | return 0; |
| 683 | } | 693 | } |
diff --git a/runtime/test/d3d12_dxr_validation_test.cpp b/runtime/test/d3d12_dxr_validation_test.cpp index 2e09a39ee..a3749acfd 100644 --- a/runtime/test/d3d12_dxr_validation_test.cpp +++ b/runtime/test/d3d12_dxr_validation_test.cpp | |||
| @@ -93,6 +93,28 @@ int run_suite(ID3D12Device* base_dev, const char* name, bool check_strict_valida | |||
| 93 | std::printf("%s: raytracing not supported (tier=%d), skipping\n", name, static_cast<int>(o5.RaytracingTier)); | 93 | std::printf("%s: raytracing not supported (tier=%d), skipping\n", name, static_cast<int>(o5.RaytracingTier)); |
| 94 | return 77; | 94 | return 77; |
| 95 | } | 95 | } |
| 96 | if (check_strict_validation && o5.RaytracingTier == D3D12_RAYTRACING_TIER_NOT_SUPPORTED) { | ||
| 97 | // Leonida reports RaytracingTier == NOT_SUPPORTED even when XDXR or KHR acceleration structures are | ||
| 98 | // available. Probe PrebuildInfo before creating RAYTRACING_ACCELERATION_STRUCTURE buffers, which | ||
| 99 | // CreateCommittedResource refuses when neither backend is active (e.g. LEONIDA_RT_AS=khr on a non-RT GPU). | ||
| 100 | D3D12_RAYTRACING_GEOMETRY_DESC probe_tri{}; | ||
| 101 | probe_tri.Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES; | ||
| 102 | probe_tri.Flags = D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE; | ||
| 103 | probe_tri.Triangles.VertexFormat = DXGI_FORMAT_R32G32B32_FLOAT; | ||
| 104 | probe_tri.Triangles.VertexCount = 3; | ||
| 105 | probe_tri.Triangles.VertexBuffer.StrideInBytes = 12; | ||
| 106 | D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS probe_in{}; | ||
| 107 | probe_in.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; | ||
| 108 | probe_in.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; | ||
| 109 | probe_in.NumDescs = 1; | ||
| 110 | probe_in.pGeometryDescs = &probe_tri; | ||
| 111 | D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO probe_info{}; | ||
| 112 | dev->GetRaytracingAccelerationStructurePrebuildInfo(&probe_in, &probe_info); | ||
| 113 | if (probe_info.ResultDataMaxSizeInBytes == 0 || probe_info.ScratchDataSizeInBytes == 0) { | ||
| 114 | std::printf("%s: neither XDXR nor KHR acceleration structures supported, skipping\n", name); | ||
| 115 | return 77; | ||
| 116 | } | ||
| 117 | } | ||
| 96 | 118 | ||
| 97 | Ref<ID3D12Resource> vb, inst_buf, scratch, blas_buf, tlas_buf, src_as, post_buf; | 119 | Ref<ID3D12Resource> vb, inst_buf, scratch, blas_buf, tlas_buf, src_as, post_buf; |
| 98 | if (!make_buffer(dev.p, 4096, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, | 120 | if (!make_buffer(dev.p, 4096, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, |
| @@ -164,10 +186,6 @@ int run_suite(ID3D12Device* base_dev, const char* name, bool check_strict_valida | |||
| 164 | in.pGeometryDescs = &tri; | 186 | in.pGeometryDescs = &tri; |
| 165 | dev->GetRaytracingAccelerationStructurePrebuildInfo(&in, &info); | 187 | dev->GetRaytracingAccelerationStructurePrebuildInfo(&in, &info); |
| 166 | if (info.ResultDataMaxSizeInBytes == 0 || info.ScratchDataSizeInBytes == 0) { | 188 | if (info.ResultDataMaxSizeInBytes == 0 || info.ScratchDataSizeInBytes == 0) { |
| 167 | if (check_strict_validation && o5.RaytracingTier == D3D12_RAYTRACING_TIER_NOT_SUPPORTED) { | ||
| 168 | std::printf("%s: neither XDXR nor KHR acceleration structures supported, skipping\n", name); | ||
| 169 | return 77; | ||
| 170 | } | ||
| 171 | std::fprintf(stderr, "%s: valid BLAS ARRAY prebuild returned zero\n", name); | 189 | std::fprintf(stderr, "%s: valid BLAS ARRAY prebuild returned zero\n", name); |
| 172 | return 1; | 190 | return 1; |
| 173 | } | 191 | } |
diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index df430c11a..1b99b8d0b 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp | |||
| @@ -138,6 +138,7 @@ int main() { | |||
| 138 | info.buffer_device_address = true; | 138 | info.buffer_device_address = true; |
| 139 | info.shader_dir = library.string(); | 139 | info.shader_dir = library.string(); |
| 140 | info.mesh_shader = mesh; | 140 | info.mesh_shader = mesh; |
| 141 | info.mesh_shader_queries = mesh && d.mesh_shader_queries; | ||
| 141 | info.pipeline_statistics_query = d.pipeline_statistics_query; | 142 | info.pipeline_statistics_query = d.pipeline_statistics_query; |
| 142 | return info; | 143 | return info; |
| 143 | }; | 144 | }; |
| @@ -405,8 +406,15 @@ int main() { | |||
| 405 | // query 2 the two vertex draws alone. A mesh draw has no input assembly or vertex shader, so those fields | 406 | // query 2 the two vertex draws alone. A mesh draw has no input assembly or vertex shader, so those fields |
| 406 | // count only the two full-screen triangles (3 vertices, 1 primitive each). How many clipping and pixel | 407 | // count only the two full-screen triangles (3 vertices, 1 primitive each). How many clipping and pixel |
| 407 | // shader invocations a draw makes is the driver's (RADV's PSInvocations is not the pixel count), so query | 408 | // shader invocations a draw makes is the driver's (RADV's PSInvocations is not the pixel count), so query |
| 408 | // 0 is checked against query 2: more of both is the mesh segment's share. Under LEONIDA_VK_VALIDATION=1 the | 409 | // 0 is checked against query 2: more pixel shader invocations is the mesh segment's share. A mesh segment |
| 409 | // run must stay free of VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076. | 410 | // runs in a pool that counts the fragment and compute invocations only, because |
| 411 | // VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076 leaves the clipping counters out of a pool that is | ||
| 412 | // active during a mesh draw; D3D12 counts the clipping invocations and primitives of a mesh pipeline, so | ||
| 413 | // those two fields read 0 here. Under LEONIDA_VK_VALIDATION=1 the run must stay free of the VUID. | ||
| 414 | // Where the device has the meshShaderQueries feature, the clipping invocations of a mesh segment come | ||
| 415 | // from a mesh-primitives query instead (D3D-MESH-CLIPPING-COUNTER): the number of primitives the mesh | ||
| 416 | // shader emitted that reached the fragment shader. How many that is depends on the driver, so the counts | ||
| 417 | // are compared with each other and not written down. | ||
| 410 | if (d.pipeline_statistics_query) { | 418 | if (d.pipeline_statistics_query) { |
| 411 | const D3D12_QUERY_HEAP_DESC statistics_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 3, 0}; | 419 | const D3D12_QUERY_HEAP_DESC statistics_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 3, 0}; |
| 412 | Ref<ID3D12QueryHeap> statistics; | 420 | Ref<ID3D12QueryHeap> statistics; |
| @@ -472,11 +480,26 @@ int main() { | |||
| 472 | EXPECT(vertex_only.IAVertices == 6 && vertex_only.IAPrimitives == 2); | 480 | EXPECT(vertex_only.IAVertices == 6 && vertex_only.IAPrimitives == 2); |
| 473 | EXPECT(mixed.GSInvocations == 0 && mixed.GSPrimitives == 0 && mixed.HSInvocations == 0 && | 481 | EXPECT(mixed.GSInvocations == 0 && mixed.GSPrimitives == 0 && mixed.HSInvocations == 0 && |
| 474 | mixed.DSInvocations == 0 && mixed.CSInvocations == 0); | 482 | mixed.DSInvocations == 0 && mixed.CSInvocations == 0); |
| 475 | EXPECT(mixed.CInvocations > vertex_only.CInvocations && mixed.PSInvocations > vertex_only.PSInvocations); | 483 | // The clipping invocations of the mesh segments (D3D-MESH-CLIPPING-COUNTER). Without the feature they |
| 484 | // read 0; with it they are the mesh-primitives count of those segments. | ||
| 485 | const auto mesh_clipping = mixed.CInvocations - vertex_only.CInvocations; | ||
| 486 | if (d.mesh_shader_queries) { | ||
| 487 | // The count has to be wired up, not merely self-consistent. A layer that reported the feature but | ||
| 488 | // never created the third pool would leave both counts at 0, and 0 >= 0 would still hold. How many | ||
| 489 | // primitives the mesh shader emits is the driver's, so ask for a positive count and not for a | ||
| 490 | // number: the mesh draw above fills the top-left quadrant, so it emits at least one. | ||
| 491 | EXPECT(mesh_clipping >= mesh_only.CInvocations); | ||
| 492 | EXPECT(mesh_only.CInvocations > 0); | ||
| 493 | } else { | ||
| 494 | EXPECT(mesh_clipping == 0); | ||
| 495 | } | ||
| 496 | EXPECT(mixed.PSInvocations > vertex_only.PSInvocations); | ||
| 476 | EXPECT(mesh_only.IAVertices == 0 && mesh_only.IAPrimitives == 0 && mesh_only.VSInvocations == 0 && | 497 | EXPECT(mesh_only.IAVertices == 0 && mesh_only.IAPrimitives == 0 && mesh_only.VSInvocations == 0 && |
| 477 | mesh_only.GSInvocations == 0 && mesh_only.GSPrimitives == 0 && mesh_only.HSInvocations == 0 && | 498 | mesh_only.GSInvocations == 0 && mesh_only.GSPrimitives == 0 && mesh_only.HSInvocations == 0 && |
| 478 | mesh_only.DSInvocations == 0 && mesh_only.CSInvocations == 0); | 499 | mesh_only.DSInvocations == 0 && mesh_only.CSInvocations == 0); |
| 479 | EXPECT(mesh_only.CInvocations > 0 && mesh_only.PSInvocations > 0); | 500 | // Vulkan has no clipped-primitive counter, so the clipping primitives of a mesh segment stay 0. |
| 501 | EXPECT(mesh_only.CPrimitives == 0 && mesh_only.PSInvocations > 0); | ||
| 502 | if (!d.mesh_shader_queries) EXPECT(mesh_only.CInvocations == 0); | ||
| 480 | } else { | 503 | } else { |
| 481 | std::printf("pipelineStatisticsQuery not available: the D3D-291 statistics check is skipped\n"); | 504 | std::printf("pipelineStatisticsQuery not available: the D3D-291 statistics check is skipped\n"); |
| 482 | } | 505 | } |
diff --git a/runtime/test/d3d12_pipeline_library_host_test.cpp b/runtime/test/d3d12_pipeline_library_host_test.cpp index e8b8c5795..3ed6341d8 100644 --- a/runtime/test/d3d12_pipeline_library_host_test.cpp +++ b/runtime/test/d3d12_pipeline_library_host_test.cpp | |||
| @@ -3,9 +3,9 @@ | |||
| 3 | // corrupt blobs, the other device's serialized blob, the null-output capability check and other interfaces, and on | 3 | // corrupt blobs, the other device's serialized blob, the null-output capability check and other interfaces, and on |
| 4 | // an empty library StorePipeline / LoadComputePipeline / LoadGraphicsPipeline / LoadPipeline with null, empty and | 4 | // an empty library StorePipeline / LoadComputePipeline / LoadGraphicsPipeline / LoadPipeline with null, empty and |
| 5 | // unknown names and null PSOs, descriptions or outputs, and Serialize with null, short and long buffers. Every HRESULT | 5 | // unknown names and null PSOs, descriptions or outputs, and Serialize with null, short and long buffers. Every HRESULT |
| 6 | // is recorded, with whether the output pointer was written; the two records must be the same, step by step. The | 6 | // and output pointer state are recorded. The public argument checks must agree step by step. Serialized sizes and |
| 7 | // serialized size and bytes are each device's own format and are not compared. A step the host runtime faults on is | 7 | // the result of changing a trailing byte are reported for each device's own format. Host faults are reported |
| 8 | // reported and not compared. No shaders or game data. Skips (77) without a Vulkan GPU; without a host D3D12 device | 8 | // separately. No shaders or game data. Skips (77) without a Vulkan GPU. Without a host D3D12 device, |
| 9 | // only the layer's own record is printed. Set LEONIDA_D3D49_VERBOSE=1 to print every step. | 9 | // only the layer's own record is printed. Set LEONIDA_D3D49_VERBOSE=1 to print every step. |
| 10 | #include "vk_test_device.h" | 10 | #include "vk_test_device.h" |
| 11 | #include "../shims/d3d12_com.h" | 11 | #include "../shims/d3d12_com.h" |
| @@ -105,7 +105,9 @@ const Step kSteps[] = { | |||
| 105 | longer.resize(longer.size() + 64, 0); | 105 | longer.resize(longer.size() + 64, 0); |
| 106 | return create(c, longer.data(), longer.size()); | 106 | return create(c, longer.data(), longer.size()); |
| 107 | }}, | 107 | }}, |
| 108 | {"create: its own blob, last byte flipped", [](Context& c) { | 108 | // The layer's empty LPL1 library contains only the header, so its last byte is in the reserved field. |
| 109 | // The native library has its own driver-specific layout. | ||
| 110 | {"create: its own blob, last byte flipped [own format]", [](Context& c) { | ||
| 109 | std::vector<std::uint8_t> flipped(c.own); | 111 | std::vector<std::uint8_t> flipped(c.own); |
| 110 | flipped.back() ^= 0xFF; | 112 | flipped.back() ^= 0xFF; |
| 111 | return create(c, flipped.data(), flipped.size()); | 113 | return create(c, flipped.data(), flipped.size()); |
diff --git a/runtime/test/d3d12_pipeline_library_test.cpp b/runtime/test/d3d12_pipeline_library_test.cpp index 1ba930cc7..fb3c3ad03 100644 --- a/runtime/test/d3d12_pipeline_library_test.cpp +++ b/runtime/test/d3d12_pipeline_library_test.cpp | |||
| @@ -206,8 +206,9 @@ int main() { | |||
| 206 | EXPECT(lib->LoadPipeline(L"gfx", &empty_stream, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p); | 206 | EXPECT(lib->LoadPipeline(L"gfx", &empty_stream, IID_PPV_ARGS(&wrong.p)) == E_INVALIDARG && !wrong.p); |
| 207 | EXPECT(SUCCEEDED(lib->LoadPipeline(L"gfx", &stream_desc, IID_PPV_ARGS(&loaded_any.p))) && loaded_any.p); | 207 | EXPECT(SUCCEEDED(lib->LoadPipeline(L"gfx", &stream_desc, IID_PPV_ARGS(&loaded_any.p))) && loaded_any.p); |
| 208 | 208 | ||
| 209 | constexpr SIZE_T lpl1_header_size = 4 * sizeof(std::uint32_t); | ||
| 209 | const SIZE_T blob_size = lib->GetSerializedSize(); | 210 | const SIZE_T blob_size = lib->GetSerializedSize(); |
| 210 | EXPECT(blob_size >= 16); | 211 | EXPECT(blob_size >= lpl1_header_size); |
| 211 | std::vector<std::uint8_t> blob(blob_size); | 212 | std::vector<std::uint8_t> blob(blob_size); |
| 212 | EXPECT(lib->Serialize(nullptr, blob_size) == E_INVALIDARG); | 213 | EXPECT(lib->Serialize(nullptr, blob_size) == E_INVALIDARG); |
| 213 | EXPECT(lib->Serialize(blob.data(), blob_size - 1) == E_INVALIDARG); | 214 | EXPECT(lib->Serialize(blob.data(), blob_size - 1) == E_INVALIDARG); |
| @@ -216,6 +217,12 @@ int main() { | |||
| 216 | Ref<ID3D12PipelineLibrary> reloaded; | 217 | Ref<ID3D12PipelineLibrary> reloaded; |
| 217 | EXPECT(SUCCEEDED(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&reloaded.p))) && reloaded.p); | 218 | EXPECT(SUCCEEDED(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&reloaded.p))) && reloaded.p); |
| 218 | 219 | ||
| 220 | // The final word in the LPL1 header is reserved and must be zero. | ||
| 221 | blob[lpl1_header_size - 1] ^= 0xFF; | ||
| 222 | Ref<ID3D12PipelineLibrary> rejected; | ||
| 223 | EXPECT(device->CreatePipelineLibrary(blob.data(), blob.size(), IID_PPV_ARGS(&rejected.p)) == E_INVALIDARG && | ||
| 224 | !rejected.p); | ||
| 225 | |||
| 219 | // 4. Execute the loaded compute PSO and loaded graphics PSO on the GPU. | 226 | // 4. Execute the loaded compute PSO and loaded graphics PSO on the GPU. |
| 220 | Ref<ID3D12CommandQueue> queue; | 227 | Ref<ID3D12CommandQueue> queue; |
| 221 | const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; | 228 | const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; |
diff --git a/runtime/test/d3d12_state_map_test.cpp b/runtime/test/d3d12_state_map_test.cpp index 9db6ad0c1..2fec30ba4 100644 --- a/runtime/test/d3d12_state_map_test.cpp +++ b/runtime/test/d3d12_state_map_test.cpp | |||
| @@ -404,7 +404,10 @@ int main() { | |||
| 404 | CHECK(vulkan_sync(y::split) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT); | 404 | CHECK(vulkan_sync(y::split) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT); |
| 405 | CHECK(vulkan_sync(y::render_target) == VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT); | 405 | CHECK(vulkan_sync(y::render_target) == VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT); |
| 406 | CHECK(vulkan_sync(y::copy | y::pixel_shading) == | 406 | CHECK(vulkan_sync(y::copy | y::pixel_shading) == |
| 407 | (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT)); | 407 | (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT)); |
| 408 | // SYNC_COPY covers WriteBufferImmediate (vkCmdUpdateBuffer) and ResolveQueryData's zero fill (vkCmdFillBuffer), | ||
| 409 | // which synchronization2 runs in the CLEAR stage, not COPY (D3D-838). | ||
| 410 | CHECK(vulkan_sync(y::copy) == (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT)); | ||
| 408 | CHECK(vulkan_sync(y::raytracing) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT); | 411 | CHECK(vulkan_sync(y::raytracing) == VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT); |
| 409 | CHECK(vulkan_barrier_access(a::no_access) == VK_ACCESS_2_NONE); | 412 | CHECK(vulkan_barrier_access(a::no_access) == VK_ACCESS_2_NONE); |
| 410 | const auto cb_scope = vulkan_barrier_scope(y::pixel_shading, a::constant_buffer); | 413 | const auto cb_scope = vulkan_barrier_scope(y::pixel_shading, a::constant_buffer); |
| @@ -427,7 +430,8 @@ int main() { | |||
| 427 | widened = scope(y::clear_unordered_access_view, a::copy_source); // CLEAR only writes | 430 | widened = scope(y::clear_unordered_access_view, a::copy_source); // CLEAR only writes |
| 428 | CHECK(widened.stages & VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT); | 431 | CHECK(widened.stages & VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT); |
| 429 | widened = scope(y::copy, a::unordered_access); | 432 | widened = scope(y::copy, a::unordered_access); |
| 430 | CHECK(widened.stages == (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | | 433 | CHECK(widened.stages == (VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_CLEAR_BIT | |
| 434 | VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | | ||
| 431 | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT)); | 435 | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT)); |
| 432 | // Pairs Vulkan already accepts are left exactly as vulkan_sync / vulkan_barrier_access map them. | 436 | // Pairs Vulkan already accepts are left exactly as vulkan_sync / vulkan_barrier_access map them. |
| 433 | const std::pair<std::uint32_t, std::uint32_t> unchanged[] = { | 437 | const std::pair<std::uint32_t, std::uint32_t> unchanged[] = { |
diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index 056e82561..99bb6d1a4 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp | |||
| @@ -5168,6 +5168,12 @@ int main() { | |||
| 5168 | EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))); | 5168 | EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))); |
| 5169 | EXPECT(options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_3); | 5169 | EXPECT(options.ResourceBindingTier == D3D12_RESOURCE_BINDING_TIER_3); |
| 5170 | EXPECT(options.MaxGPUVirtualAddressBitsPerResource == 40); | 5170 | EXPECT(options.MaxGPUVirtualAddressBitsPerResource == 40); |
| 5171 | // Console 0x40-byte (16-dword) D3D12_OPTIONS query (docs/d3d12_xs_surface.md §7.1): 0x3C PC prefix + zero tail. | ||
| 5172 | UINT console_opts[16]{}; | ||
| 5173 | console_opts[15] = 0xdeadbeefu; | ||
| 5174 | EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, console_opts, sizeof(console_opts)))); | ||
| 5175 | EXPECT(std::memcmp(console_opts, &options, sizeof(options)) == 0); | ||
| 5176 | EXPECT(console_opts[15] == 0); | ||
| 5171 | 5177 | ||
| 5172 | D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT va_support{}; | 5178 | D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT va_support{}; |
| 5173 | EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT, &va_support, sizeof(va_support)))); | 5179 | EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT, &va_support, sizeof(va_support)))); |
diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp index 8d089acda..81b647fd2 100644 --- a/runtime/test/frame_pacer_test.cpp +++ b/runtime/test/frame_pacer_test.cpp | |||
| @@ -586,6 +586,155 @@ int main() { | |||
| 586 | EXPECT(ms.count() >= 45 && ms.count() < 1000); | 586 | EXPECT(ms.count() >= 45 && ms.count() < 1000); |
| 587 | } | 587 | } |
| 588 | 588 | ||
| 589 | // TOKEN_ON_TIMEOUT (flag 2) and multi-event pacing (origin poll + blocking flip/vblank wait). | ||
| 590 | { | ||
| 591 | ManualFrameClock clock; | ||
| 592 | FramePacer pacer(clock); | ||
| 593 | EXPECT(pacer.set_frame_interval(period, 3, 0) == pacer_hr::ok); | ||
| 594 | EXPECT(pacer.schedule_frame_event(frame_event_origin, 0, 0) == pacer_hr::ok); | ||
| 595 | EXPECT(pacer.schedule_frame_event(frame_event_vblank, 0, 0) == pacer_hr::ok); | ||
| 596 | EXPECT(pacer.schedule_frame_event(frame_event_flip, 0, 0) == pacer_hr::ok); | ||
| 597 | |||
| 598 | // Origin poll with timeout 0 and TOKEN_ON_TIMEOUT issues a consecutive token and returns S_FALSE. | ||
| 599 | std::uint64_t tok1 = 0; | ||
| 600 | EXPECT(pacer.wait_frame_event(frame_event_origin, 0, frame_wait_flag_token_on_timeout, &tok1) == | ||
| 601 | pacer_hr::false_); | ||
| 602 | EXPECT(tok1 == 1); | ||
| 603 | EXPECT(pacer.check_present_token(tok1) == pacer_hr::ok); | ||
| 604 | |||
| 605 | // A blocking flip wait paces to the next tick and preserves the caller's token unchanged. | ||
| 606 | auto flip_wait = std::async(std::launch::async, [&] { | ||
| 607 | std::uint64_t preserved = tok1; | ||
| 608 | const std::int32_t hr = pacer.wait_frame_event(frame_event_flip, infinite_timeout_ms, 0, &preserved); | ||
| 609 | return Result{hr, preserved}; | ||
| 610 | }); | ||
| 611 | EXPECT(blocked(flip_wait)); | ||
| 612 | clock.advance_us(period); | ||
| 613 | const Result fr = flip_wait.get(); | ||
| 614 | EXPECT(fr.hr == pacer_hr::ok && fr.token == tok1); | ||
| 615 | |||
| 616 | // Second flip wait blocks for the following tick; vblank wait on tick 1 succeeds immediately (independent). | ||
| 617 | EXPECT(pacer.wait_frame_event(frame_event_vblank, 0, 0, nullptr) == pacer_hr::ok); | ||
| 618 | auto flip_wait2 = std::async(std::launch::async, [&] { | ||
| 619 | return Result{pacer.wait_frame_event(frame_event_flip, infinite_timeout_ms, 0, nullptr), 0}; | ||
| 620 | }); | ||
| 621 | EXPECT(blocked(flip_wait2)); | ||
| 622 | clock.advance_us(period); | ||
| 623 | EXPECT(flip_wait2.get().hr == pacer_hr::ok); | ||
| 624 | |||
| 625 | // Origin wait at tick 2 advances consecutively after the early-started token 1. | ||
| 626 | std::uint64_t tok2 = 0; | ||
| 627 | EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tok2) == pacer_hr::ok && tok2 == 2); | ||
| 628 | } | ||
| 629 | |||
| 630 | // BL-6: frame pacing drift reporting (p50/p95/p99 frame times, mean drift vs target interval, | ||
| 631 | // origin-to-present latency, ring-buffer wrap-around, suspend/resume gap exclusion, and uncapped mode). | ||
| 632 | { | ||
| 633 | auto near = [](double a, double b) { return (a > b ? a - b : b - a) < 1e-6; }; | ||
| 634 | |||
| 635 | // 1) Empty and single-frame edge cases. | ||
| 636 | ManualFrameClock clock; | ||
| 637 | FramePacer pacer(clock); | ||
| 638 | EXPECT(setup(pacer, 2)); | ||
| 639 | FramePacingSummary s0 = pacer.pacing_summary(); | ||
| 640 | EXPECT(s0.frames == 0 && s0.samples == 0 && s0.target_interval_us == period); | ||
| 641 | EXPECT(near(s0.mean_us, 0.0) && near(s0.drift_us, 0.0)); | ||
| 642 | EXPECT(s0.p50_us == 0 && s0.p95_us == 0 && s0.p99_us == 0 && s0.latency_samples == 0); | ||
| 643 | |||
| 644 | clock.advance_us(period); | ||
| 645 | std::uint64_t tok = 0; | ||
| 646 | EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tok) == pacer_hr::ok); | ||
| 647 | clock.advance_us(2000); | ||
| 648 | pacer.commit_present_token(tok, 1); | ||
| 649 | FramePacingSummary s1 = pacer.pacing_summary(); | ||
| 650 | EXPECT(s1.frames == 1 && s1.samples == 0 && s1.latency_samples == 1 && s1.latency_p50_us == 2000); | ||
| 651 | EXPECT(near(s1.mean_us, 0.0) && near(s1.drift_us, 0.0)); | ||
| 652 | |||
| 653 | // 2) 100 known intervals (16000 + 100*i us for i = 1..100) and known origin->present latencies: | ||
| 654 | // mean = 16000 + 5050 = 21050.0 us, drift = +5050.0 us, | ||
| 655 | // nearest-rank p50 = 16000 + 50*100 = 21000, p95 = 25500, p99 = 25900. | ||
| 656 | ManualFrameClock clock2; | ||
| 657 | FramePacer pacer2(clock2); | ||
| 658 | EXPECT(setup(pacer2, 4)); | ||
| 659 | // Present an anchor frame first at t = period + 1000 (latency = 1000 us). | ||
| 660 | clock2.advance_us(period); | ||
| 661 | std::uint64_t t = 0; | ||
| 662 | EXPECT(pacer2.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok); | ||
| 663 | clock2.advance_us(1000); | ||
| 664 | pacer2.commit_present_token(t, 1); | ||
| 665 | for (std::uint64_t i = 1; i <= 100; ++i) { | ||
| 666 | const std::uint64_t dt = period + i * 100; | ||
| 667 | clock2.advance_us(dt); | ||
| 668 | // Issue token after dt - (i * 50)? Simpler: issue token at origin (which passed), present immediately. | ||
| 669 | std::uint64_t tok_i = 0; | ||
| 670 | EXPECT(pacer2.wait_frame_event(frame_event_origin, 0, 0, &tok_i) == pacer_hr::ok); | ||
| 671 | pacer2.commit_present_token(tok_i, 1); | ||
| 672 | } | ||
| 673 | const FramePacingSummary s100 = pacer2.pacing_summary(); | ||
| 674 | EXPECT(s100.frames == 101 && s100.samples == 100 && s100.target_interval_us == period); | ||
| 675 | EXPECT(near(s100.mean_us, 21050.0)); | ||
| 676 | EXPECT(near(s100.drift_us, 5050.0)); | ||
| 677 | EXPECT(s100.p50_us == 21000 && s100.p95_us == 25500 && s100.p99_us == 25900); | ||
| 678 | EXPECT(s100.latency_samples == 101); | ||
| 679 | |||
| 680 | // 3) Negative drift (untokened/early presents faster than target period) + exact origin-to-present latency. | ||
| 681 | ManualFrameClock clock3; | ||
| 682 | FramePacer pacer3(clock3); | ||
| 683 | EXPECT(setup(pacer3, 4)); | ||
| 684 | clock3.advance_us(period); | ||
| 685 | EXPECT(pacer3.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok); | ||
| 686 | clock3.advance_us(3000); // latency = 3000 | ||
| 687 | pacer3.commit_present_token(t, 1); | ||
| 688 | clock3.advance_us(10000); // dt = 10000 (< 16000) -> drift = -6000 | ||
| 689 | pacer3.note_untokened_present(); | ||
| 690 | const FramePacingSummary sneg = pacer3.pacing_summary(); | ||
| 691 | EXPECT(sneg.frames == 2 && sneg.samples == 1 && sneg.target_interval_us == period); | ||
| 692 | EXPECT(near(sneg.mean_us, 10000.0) && near(sneg.drift_us, -6000.0)); | ||
| 693 | EXPECT(sneg.p50_us == 10000 && sneg.p95_us == 10000 && sneg.p99_us == 10000); | ||
| 694 | EXPECT(sneg.latency_samples == 1 && sneg.latency_p50_us == 3000 && sneg.latency_p99_us == 3000); | ||
| 695 | |||
| 696 | // 4) Suspend/resume gap is excluded from frame intervals. | ||
| 697 | pacer3.suspend(); | ||
| 698 | clock3.advance_us(5'000'000); // 5 second pause while suspended | ||
| 699 | pacer3.resume(); | ||
| 700 | EXPECT(setup(pacer3, 2)); | ||
| 701 | clock3.advance_us(period); | ||
| 702 | EXPECT(pacer3.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok); | ||
| 703 | pacer3.commit_present_token(t, 1); | ||
| 704 | const FramePacingSummary ssusp = pacer3.pacing_summary(); | ||
| 705 | EXPECT(ssusp.frames == 3 && ssusp.samples == 1 && ssusp.p99_us == 10000); // 5s gap not recorded | ||
| 706 | |||
| 707 | // 5) Ring-buffer wrap-around: fill with slow 32000 us frames, then overwrite entire window with steady 16000 us. | ||
| 708 | ManualFrameClock clock4; | ||
| 709 | FramePacer pacer4(clock4); | ||
| 710 | EXPECT(setup(pacer4, 2)); | ||
| 711 | clock4.advance_us(period); | ||
| 712 | EXPECT(pacer4.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok); | ||
| 713 | pacer4.commit_present_token(t, 1); | ||
| 714 | for (std::size_t i = 0; i < frame_pacing_window; ++i) { | ||
| 715 | clock4.advance_us(period * 2); | ||
| 716 | EXPECT(pacer4.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok); | ||
| 717 | pacer4.commit_present_token(t, 1); | ||
| 718 | } | ||
| 719 | const FramePacingSummary slow = pacer4.pacing_summary(); | ||
| 720 | EXPECT(slow.samples == frame_pacing_window && near(slow.mean_us, double(period * 2)) && | ||
| 721 | near(slow.drift_us, double(period))); | ||
| 722 | for (std::size_t i = 0; i < frame_pacing_window; ++i) { | ||
| 723 | clock4.advance_us(period); | ||
| 724 | EXPECT(pacer4.wait_frame_event(frame_event_origin, 0, 0, &t) == pacer_hr::ok); | ||
| 725 | pacer4.commit_present_token(t, 1); | ||
| 726 | } | ||
| 727 | const FramePacingSummary steady = pacer4.pacing_summary(); | ||
| 728 | EXPECT(steady.frames == 1 + 2 * frame_pacing_window && steady.samples == frame_pacing_window); | ||
| 729 | EXPECT(near(steady.mean_us, double(period)) && near(steady.drift_us, 0.0)); | ||
| 730 | EXPECT(steady.p50_us == period && steady.p95_us == period && steady.p99_us == period); | ||
| 731 | |||
| 732 | // 6) Uncapped mode: target_interval_us == 0 and drift_us == 0 while intervals are still tracked. | ||
| 733 | pacer4.set_uncapped(true); | ||
| 734 | const FramePacingSummary uncap = pacer4.pacing_summary(); | ||
| 735 | EXPECT(uncap.target_interval_us == 0 && near(uncap.drift_us, 0.0) && uncap.p50_us == period); | ||
| 736 | } | ||
| 737 | |||
| 589 | std::printf("frame_pacer_test: all cases pass\n"); | 738 | std::printf("frame_pacer_test: all cases pass\n"); |
| 590 | return 0; | 739 | return 0; |
| 591 | } | 740 | } |
diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp index 523180ee7..85843edb8 100644 --- a/runtime/test/gfx10_descriptors_test.cpp +++ b/runtime/test/gfx10_descriptors_test.cpp | |||
| @@ -359,18 +359,21 @@ int main() { | |||
| 359 | CHECK(info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.mipLodBias == -0.75f); | 359 | CHECK(info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.mipLodBias == -0.75f); |
| 360 | CHECK(info.minLod == 0.5f && info.maxLod == 4.25f); | 360 | CHECK(info.minLod == 0.5f && info.maxLod == 4.25f); |
| 361 | info = vulkan_sampler({.mag_filter = Filter::aniso_point, .mip_filter = MipFilter::linear, .max_anisotropy = 8, | 361 | info = vulkan_sampler({.mag_filter = Filter::aniso_point, .mip_filter = MipFilter::linear, .max_anisotropy = 8, |
| 362 | .compare = CompareFunction::greater, .max_lod = 9.0f, .unnormalized = true}); | 362 | .compare = CompareFunction::greater, .min_lod = 1.5f, .max_lod = 9.0f, |
| 363 | .lod_bias = 2.5f, .unnormalized = true}); | ||
| 363 | CHECK(info.unnormalizedCoordinates == VK_TRUE && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST); | 364 | CHECK(info.unnormalizedCoordinates == VK_TRUE && info.mipmapMode == VK_SAMPLER_MIPMAP_MODE_NEAREST); |
| 364 | CHECK(info.maxLod == 0.0f && info.anisotropyEnable == VK_FALSE && info.compareEnable == VK_FALSE); | 365 | CHECK(info.minLod == 0.0f && info.maxLod == 0.0f && info.mipLodBias == 0.0f); |
| 366 | CHECK(info.anisotropyEnable == VK_FALSE && info.compareEnable == VK_FALSE); | ||
| 365 | // Unnormalised: U and V clamp (wrap, the default S# mode, would be invalid: VUID ...-01075), border stays border, | 367 | // Unnormalised: U and V clamp (wrap, the default S# mode, would be invalid: VUID ...-01075), border stays border, |
| 366 | // W is free; min and mag filter agree (VUID ...-01072). | 368 | // W is free; min and mag filter agree (VUID ...-01072); mipLodBias is zero (VUID ...-01074). |
| 367 | CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && | 369 | CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && |
| 368 | info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && | 370 | info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && |
| 369 | info.addressModeW == VK_SAMPLER_ADDRESS_MODE_REPEAT && info.minFilter == info.magFilter); | 371 | info.addressModeW == VK_SAMPLER_ADDRESS_MODE_REPEAT && info.minFilter == info.magFilter); |
| 370 | info = vulkan_sampler({.address_u = AddressMode::clamp_border, .address_v = AddressMode::mirror, | 372 | info = vulkan_sampler({.address_u = AddressMode::clamp_border, .address_v = AddressMode::mirror, |
| 371 | .min_filter = Filter::bilinear, .unnormalized = true}); | 373 | .min_filter = Filter::bilinear, .lod_bias = -3.25f, .unnormalized = true}); |
| 372 | CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER && | 374 | CHECK(info.addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER && |
| 373 | info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.minFilter == VK_FILTER_NEAREST); | 375 | info.addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE && info.minFilter == VK_FILTER_NEAREST && |
| 376 | info.mipLodBias == 0.0f); | ||
| 374 | CHECK(vulkan_address_mode(AddressMode::mirror) == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT); | 377 | CHECK(vulkan_address_mode(AddressMode::mirror) == VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT); |
| 375 | CHECK(vulkan_address_mode(AddressMode::mirror_once_last_texel) == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE); | 378 | CHECK(vulkan_address_mode(AddressMode::mirror_once_last_texel) == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE); |
| 376 | CHECK(vulkan_address_mode(AddressMode::clamp_half_border) == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); | 379 | CHECK(vulkan_address_mode(AddressMode::clamp_half_border) == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); |
diff --git a/runtime/test/loader_tls_test.cpp b/runtime/test/loader_tls_test.cpp index 625ff6d86..133b27c81 100644 --- a/runtime/test/loader_tls_test.cpp +++ b/runtime/test/loader_tls_test.cpp | |||
| @@ -790,7 +790,8 @@ void test_ga_tls_existing_thread(const fs::path& exe) { | |||
| 790 | { | 790 | { |
| 791 | rt::Loader loader(exe.parent_path()); | 791 | rt::Loader loader(exe.parent_path()); |
| 792 | rt::Module& m = loader.load(exe); | 792 | rt::Module& m = loader.load(exe); |
| 793 | check(m.tls_index != 0, "the /GA fixture gets a module TLS index other than the process EXE's 0"); | 793 | check(m.tls_index != rt::kNoTlsIndex && m.tls_index != 0, |
| 794 | "the /GA fixture gets a valid module TLS index other than the process EXE's 0"); | ||
| 794 | check(m.tls_ga_slot != rt::kNoTlsIndex, "load() rewrites the /GA fixture's index-0 TLS reads"); | 795 | check(m.tls_ga_slot != rt::kNoTlsIndex, "load() rewrites the /GA fixture's index-0 TLS reads"); |
| 795 | get = find_export<int(__cdecl*)()>(m, "ga_tls_get"); | 796 | get = find_export<int(__cdecl*)()>(m, "ga_tls_get"); |
| 796 | set = find_export<void(__cdecl*)(int)>(m, "ga_tls_set"); | 797 | set = find_export<void(__cdecl*)(int)>(m, "ga_tls_set"); |
diff --git a/runtime/test/mods_test.cpp b/runtime/test/mods_test.cpp index a29979b25..e95bc4e16 100644 --- a/runtime/test/mods_test.cpp +++ b/runtime/test/mods_test.cpp | |||
| @@ -41,6 +41,9 @@ int main() { | |||
| 41 | check(!parse_model_id("0x123456789", id), "a hash wider than 32 bits is refused"); | 41 | check(!parse_model_id("0x123456789", id), "a hash wider than 32 bits is refused"); |
| 42 | check(!parse_model_id("0xZZ", id), "a malformed hash is refused"); | 42 | check(!parse_model_id("0xZZ", id), "a malformed hash is refused"); |
| 43 | check(!parse_model_id("", id), "an empty name is refused"); | 43 | check(!parse_model_id("", id), "an empty name is refused"); |
| 44 | id = 0xCAFEBABEu; | ||
| 45 | check(!parse_model_id("0x", id) && id == 0xCAFEBABEu, "a bare 0x prefix is refused"); | ||
| 46 | check(!parse_model_id("0X", id) && id == 0xCAFEBABEu, "a bare 0X prefix is refused"); | ||
| 44 | 47 | ||
| 45 | Mod mod; | 48 | Mod mod; |
| 46 | std::string error; | 49 | std::string error; |
| @@ -53,6 +56,8 @@ int main() { | |||
| 53 | "a condition the runtime cannot honour yet is refused, not ignored"); | 56 | "a condition the runtime cannot honour yet is refused, not ignored"); |
| 54 | check(!parse_mod(R"({"archetype_swaps":[{"from":"cs_mandy","to":"0xD7C0CDFF"}]})", "m", mod, error), | 57 | check(!parse_mod(R"({"archetype_swaps":[{"from":"cs_mandy","to":"0xD7C0CDFF"}]})", "m", mod, error), |
| 55 | "a swap of a model with itself is refused"); | 58 | "a swap of a model with itself is refused"); |
| 59 | check(!parse_mod(R"({"archetype_swaps":[{"from":"0x","to":"cs_mandy"}]})", "m", mod, error), | ||
| 60 | "a bare 0x prefix in an archetype swap is refused"); | ||
| 56 | check(!parse_mod(R"({"enabled":"yes"})", "m", mod, error), "\"enabled\" must be a boolean"); | 61 | check(!parse_mod(R"({"enabled":"yes"})", "m", mod, error), "\"enabled\" must be a boolean"); |
| 57 | check(!parse_mod("[1,2]", "m", mod, error), "a manifest that is not an object is refused"); | 62 | check(!parse_mod("[1,2]", "m", mod, error), "a manifest that is not an object is refused"); |
| 58 | check(parse_mod("{}", "folder_name", mod, error) && mod.name == "folder_name", "the name defaults to the folder"); | 63 | check(parse_mod("{}", "folder_name", mod, error) && mod.name == "folder_name", "the name defaults to the folder"); |
diff --git a/runtime/test/replay_copy_offset_test.cpp b/runtime/test/replay_copy_offset_test.cpp index 7392344ff..b5f93c102 100644 --- a/runtime/test/replay_copy_offset_test.cpp +++ b/runtime/test/replay_copy_offset_test.cpp | |||
| @@ -310,6 +310,103 @@ int main() { | |||
| 310 | dst_buf = saved_dst; | 310 | dst_buf = saved_dst; |
| 311 | } | 311 | } |
| 312 | 312 | ||
| 313 | // 6. tile_footprint unaligned staging honors format alignment (8B, 16B, BC1) and 3D slice layout. | ||
| 314 | { | ||
| 315 | const auto saved_src = src_buf, saved_dst = dst_buf; | ||
| 316 | VkDeviceSize scratch_req = 0; | ||
| 317 | vk.copy_scratch = [&](std::uint64_t bytes, VkBuffer& buf, VkDeviceSize& off) { | ||
| 318 | scratch_req = bytes; | ||
| 319 | buf = handle<VkBuffer>(0xA000); | ||
| 320 | off = 256; | ||
| 321 | return true; | ||
| 322 | }; | ||
| 323 | |||
| 324 | ResourceBinding rgba16f_img{}; | ||
| 325 | rgba16f_img.image = handle<VkImage>(6); | ||
| 326 | rgba16f_img.format = VK_FORMAT_R16G16B16A16_SFLOAT; // 8 bytes/texel | ||
| 327 | rgba16f_img.aspects = VK_IMAGE_ASPECT_COLOR_BIT; | ||
| 328 | rgba16f_img.width = 8; | ||
| 329 | rgba16f_img.height = 4; | ||
| 330 | rgba16f_img.mip_levels = 1; | ||
| 331 | rgba16f_img.array_layers = 1; | ||
| 332 | rgba16f_img.depth = 2; | ||
| 333 | rgba16f_img.volume = true; | ||
| 334 | rgba16f_img.samples = 1; | ||
| 335 | |||
| 336 | ResourceBinding bc1_img{}; | ||
| 337 | bc1_img.image = handle<VkImage>(7); | ||
| 338 | bc1_img.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK; // 8 bytes per 4x4 block | ||
| 339 | bc1_img.aspects = VK_IMAGE_ASPECT_COLOR_BIT; | ||
| 340 | bc1_img.width = 12; | ||
| 341 | bc1_img.height = 8; | ||
| 342 | bc1_img.mip_levels = 1; | ||
| 343 | bc1_img.array_layers = 1; | ||
| 344 | bc1_img.depth = 1; | ||
| 345 | bc1_img.samples = 1; | ||
| 346 | |||
| 347 | const auto resolve_tile = [&](ResourceId id) -> const ResourceBinding* { | ||
| 348 | if (id == 6) return &rgba16f_img; | ||
| 349 | if (id == 7) return &bc1_img; | ||
| 350 | return resolve(id); | ||
| 351 | }; | ||
| 352 | |||
| 353 | // 6a. 8-byte 3D texture with bufferOffset = 4 (4-byte aligned, NOT 8-byte aligned): must stage both slices. | ||
| 354 | src_buf.buffer_offset = 0; | ||
| 355 | src_buf.size = 4096; | ||
| 356 | { | ||
| 357 | const CopyLocation tex{6, false, 0, 0, 0, 0, 0, 0}; | ||
| 358 | // footprint: width=8, height=4, depth=2, row_pitch=256 (32 texels/row, slice_pitch=1024), offset=4 | ||
| 359 | const CopyLocation fp{1, true, 0, 4, 8, 4, 2, 256}; | ||
| 360 | CopyTexture copy{tex, 0, 0, 0, fp, true, {0, 0, 0, 4, 2, 2}}; // 4x2x2 texels -> 32B/row, 2 rows, 2 slices = 128B | ||
| 361 | copy.tile_footprint = true; | ||
| 362 | CommandList list; | ||
| 363 | expect(list.copy_texture(copy) && list.close(), "record 8B 3D tile_footprint upload"); | ||
| 364 | buffer_copies.clear(); | ||
| 365 | b2i_copies.clear(); | ||
| 366 | scratch_req = 0; | ||
| 367 | expect(replay(list, VK_NULL_HANDLE, resolve_tile, vk) == ReplayResult::success, | ||
| 368 | "8B 3D tile_footprint upload with offset=4 replays"); | ||
| 369 | expect(scratch_req == 128, "8B 3D tile_footprint allocates 4*8 * 2 * 2 = 128 bytes of scratch"); | ||
| 370 | expect(buffer_copies.size() == 4, "8B 3D tile_footprint stages 2 rows x 2 slices"); | ||
| 371 | expect(buffer_copies.size() == 4 && | ||
| 372 | buffer_copies[0].srcOffset == 4 && buffer_copies[0].dstOffset == 256 && buffer_copies[0].size == 32 && | ||
| 373 | buffer_copies[1].srcOffset == 260 && buffer_copies[1].dstOffset == 288 && buffer_copies[1].size == 32 && | ||
| 374 | buffer_copies[2].srcOffset == 1028 && buffer_copies[2].dstOffset == 320 && buffer_copies[2].size == 32 && | ||
| 375 | buffer_copies[3].srcOffset == 1284 && buffer_copies[3].dstOffset == 352 && buffer_copies[3].size == 32, | ||
| 376 | "8B 3D tile_footprint row/slice strides match 256B row_pitch and 1024B slice_pitch"); | ||
| 377 | expect(b2i_copies.size() == 1 && b2i_copies[0].bufferOffset == 256 && | ||
| 378 | b2i_copies[0].bufferRowLength == 0 && b2i_copies[0].bufferImageHeight == 0, | ||
| 379 | "8B 3D tile_footprint emits aligned scratch offset and clears row/image height"); | ||
| 380 | } | ||
| 381 | |||
| 382 | // 6b. BC1 (8B per 4x4 block) with bufferOffset = 4: must stage 2x2 blocks = 32B, not texels*4. | ||
| 383 | { | ||
| 384 | const CopyLocation tex{7, false, 0, 0, 0, 0, 0, 0}; | ||
| 385 | // footprint: width=12 (3 blocks), height=8 (2 blocks), row_pitch=256 (32*8B), offset=4 | ||
| 386 | const CopyLocation fp{1, true, 0, 4, 12, 8, 1, 256}; | ||
| 387 | CopyTexture copy{tex, 0, 0, 0, fp, true, {0, 0, 0, 8, 8, 1}}; // 2x2 blocks: 16B/row, 2 rows = 32B | ||
| 388 | copy.tile_footprint = true; | ||
| 389 | CommandList list; | ||
| 390 | expect(list.copy_texture(copy) && list.close(), "record BC1 tile_footprint upload"); | ||
| 391 | buffer_copies.clear(); | ||
| 392 | b2i_copies.clear(); | ||
| 393 | scratch_req = 0; | ||
| 394 | expect(replay(list, VK_NULL_HANDLE, resolve_tile, vk) == ReplayResult::success, | ||
| 395 | "BC1 tile_footprint upload with offset=4 replays"); | ||
| 396 | expect(scratch_req == 32, "BC1 tile_footprint allocates 2*8 * 2 = 32 bytes of scratch"); | ||
| 397 | expect(buffer_copies.size() == 2 && | ||
| 398 | buffer_copies[0].srcOffset == 4 && buffer_copies[0].dstOffset == 256 && buffer_copies[0].size == 16 && | ||
| 399 | buffer_copies[1].srcOffset == 260 && buffer_copies[1].dstOffset == 272 && buffer_copies[1].size == 16, | ||
| 400 | "BC1 tile_footprint copies 16B block rows at 256B pitch"); | ||
| 401 | expect(b2i_copies.size() == 1 && b2i_copies[0].bufferOffset == 256 && b2i_copies[0].bufferRowLength == 0, | ||
| 402 | "BC1 tile_footprint emits aligned scratch offset"); | ||
| 403 | } | ||
| 404 | |||
| 405 | vk.copy_scratch = {}; | ||
| 406 | src_buf = saved_src; | ||
| 407 | dst_buf = saved_dst; | ||
| 408 | } | ||
| 409 | |||
| 313 | if (failures) return 1; | 410 | if (failures) return 1; |
| 314 | std::printf("replay_copy_offset: CopyResource and CopyTexture apply ResourceBinding::buffer_offset\n"); | 411 | std::printf("replay_copy_offset: CopyResource and CopyTexture apply ResourceBinding::buffer_offset\n"); |
| 315 | return 0; | 412 | return 0; |
diff --git a/runtime/test/replay_query_edges_test.cpp b/runtime/test/replay_query_edges_test.cpp index 820dc0dc1..1e3da7c29 100644 --- a/runtime/test/replay_query_edges_test.cpp +++ b/runtime/test/replay_query_edges_test.cpp | |||
| @@ -1,6 +1,7 @@ | |||
| 1 | // Query heap boundaries, resolve helper chunking, arena offsets, query reuse across lists/submissions, and | 1 | // Query heap boundaries, resolve helper chunking, arena offsets, query reuse across lists/submissions, the mesh |
| 2 | // predication around copies. These edge cases are only reached by GPU tests today; this CPU mock lets CI | 2 | // pool of a statistics query and predication around copies. These edge cases are only reached by GPU tests today; |
| 3 | // without a GPU check replay planning, emitted commands, destination guards, and pool ownership on submit failure. | 3 | // this CPU mock lets CI without a GPU check replay planning, emitted commands, destination guards, and pool ownership |
| 4 | // on submit failure. | ||
| 4 | // Shader arithmetic and Vulkan entry points are mocked; no driver is loaded. No GPU or game data. | 5 | // Shader arithmetic and Vulkan entry points are mocked; no driver is loaded. No GPU or game data. |
| 5 | #include "../src/vulkan_backend.h" | 6 | #include "../src/vulkan_backend.h" |
| 6 | 7 | ||
| @@ -61,7 +62,10 @@ struct MockReplay { | |||
| 61 | std::vector<Call> copies; | 62 | std::vector<Call> copies; |
| 62 | std::vector<std::pair<VkQueryPool, unsigned>> resets; | 63 | std::vector<std::pair<VkQueryPool, unsigned>> resets; |
| 63 | std::set<VkQueryPool> statistics_pools; | 64 | std::set<VkQueryPool> statistics_pools; |
| 65 | std::set<VkQueryPool> mesh_pools; // pools with the two counters a mesh draw allows (D3D-291) | ||
| 66 | std::set<VkQueryPool> primitives_pools; // the mesh-primitives count of a mesh segment (D3D-MESH-CLIPPING-COUNTER) | ||
| 64 | std::vector<unsigned> chunks; | 67 | std::vector<unsigned> chunks; |
| 68 | std::vector<unsigned> meshes; // statistics_sum.comp's mesh flag, one per chunk | ||
| 65 | std::vector<unsigned> groups; | 69 | std::vector<unsigned> groups; |
| 66 | std::vector<VkBufferCopy> transfers; | 70 | std::vector<VkBufferCopy> transfers; |
| 67 | std::vector<std::string> events; | 71 | std::vector<std::string> events; |
| @@ -111,8 +115,12 @@ struct MockReplay { | |||
| 111 | copies.push_back({p, first, count, off, stride}); | 115 | copies.push_back({p, first, count, off, stride}); |
| 112 | auto& q = values.at(p); | 116 | auto& q = values.at(p); |
| 113 | expect(first <= q.size() && count <= q.size() - first, "mock query access out of bounds"); | 117 | expect(first <= q.size() && count <= q.size() - first, "mock query access out of bounds"); |
| 118 | // A mesh pool counts two counters, not the eleven of the full pool (D3D-291). | ||
| 119 | const unsigned counters = mesh_pools.count(p) ? 2u | ||
| 120 | : primitives_pools.count(p) ? 1u | ||
| 121 | : (stride == statistics_size ? statistics_counters : 1u); | ||
| 114 | for (unsigned i = 0; i < count; ++i) { | 122 | for (unsigned i = 0; i < count; ++i) { |
| 115 | for (unsigned j = 0; j < (stride == statistics_size ? statistics_counters : 1u); ++j) { | 123 | for (unsigned j = 0; j < counters; ++j) { |
| 116 | word(b, off + i * stride + word_size * j, q[first + i][j]); | 124 | word(b, off + i * stride + word_size * j, q[first + i][j]); |
| 117 | } | 125 | } |
| 118 | } | 126 | } |
| @@ -239,8 +247,8 @@ struct MockReplay { | |||
| 239 | VkDeviceSize off) { | 247 | VkDeviceSize off) { |
| 240 | helper(false, false, p, f, n, b, off); | 248 | helper(false, false, p, f, n, b, off); |
| 241 | }; | 249 | }; |
| 242 | v.sum_statistics = [helper](VkCommandBuffer, VkQueryPool p, VkQueryPool, const std::uint8_t*, unsigned f, | 250 | v.sum_statistics = [helper](VkCommandBuffer, VkQueryPool p, VkQueryPool, VkQueryPool, const std::uint8_t*, |
| 243 | unsigned n, VkBuffer b, VkDeviceSize off) { | 251 | unsigned f, unsigned n, VkBuffer b, VkDeviceSize off) { |
| 244 | helper(true, false, p, f, n, b, off); | 252 | helper(true, false, p, f, n, b, off); |
| 245 | }; | 253 | }; |
| 246 | v.resolve_binary_occlusion = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b, | 254 | v.resolve_binary_occlusion = [helper](VkCommandBuffer, VkQueryPool p, unsigned f, unsigned n, VkBuffer b, |
| @@ -286,26 +294,33 @@ void test_helper_chunks() { | |||
| 286 | const VkDescriptorSet*, unsigned, const unsigned*) {}; | 294 | const VkDescriptorSet*, unsigned, const unsigned*) {}; |
| 287 | vk.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, unsigned off, unsigned size, | 295 | vk.vkCmdPushConstants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, unsigned off, unsigned size, |
| 288 | const void*p) { | 296 | const void*p) { |
| 289 | // The count, then statistics_sum.comp's mesh flag (D3D-291), which no segment here sets. | 297 | // The count, then statistics_sum.comp's mesh flag (D3D-291). |
| 290 | expect(off == 0 && size == 2 * sizeof(unsigned), "chunk push constants"); | 298 | expect(off == 0 && size == 2 * sizeof(unsigned), "chunk push constants"); |
| 291 | expect(static_cast<const unsigned *>(p)[1] == 0, "chunk push constants: no mesh segment"); | 299 | MockReplay::current->chunks.push_back(static_cast<const unsigned *>(p)[0]); |
| 292 | MockReplay::current->chunks.push_back(*static_cast<const unsigned *>(p)); | 300 | MockReplay::current->meshes.push_back(static_cast<const unsigned *>(p)[1]); |
| 293 | }; | 301 | }; |
| 294 | vk.vkCmdDispatch = +[](VkCommandBuffer, unsigned x, unsigned y, unsigned z) { | 302 | vk.vkCmdDispatch = +[](VkCommandBuffer, unsigned x, unsigned y, unsigned z) { |
| 295 | auto& c = *MockReplay::current; | 303 | auto& c = *MockReplay::current; |
| 296 | c.groups.push_back(x); | 304 | c.groups.push_back(x); |
| 297 | expect(y == 1 && z == 1, "dispatch dimensions"); | 305 | expect(y == 1 && z == 1, "dispatch dimensions"); |
| 298 | auto n = c.chunks.back(); | 306 | auto n = c.chunks.back(); |
| 307 | const bool mesh = c.meshes.back() != 0; | ||
| 299 | if (c.mode == MockReplay::binary) { | 308 | if (c.mode == MockReplay::binary) { |
| 300 | for (unsigned i = 0; i < n; ++i) { | 309 | for (unsigned i = 0; i < n; ++i) { |
| 301 | c.word(VK_NULL_HANDLE, word_size * i, c.word(VK_NULL_HANDLE, word_size * i) != 0); | 310 | c.word(VK_NULL_HANDLE, word_size * i, c.word(VK_NULL_HANDLE, word_size * i) != 0); |
| 302 | } | 311 | } |
| 303 | } else { | 312 | } else { |
| 304 | for (unsigned j = 0; j < (c.mode == MockReplay::statistics ? statistics_counters : 1u); ++j) { | 313 | const bool statistics = c.mode == MockReplay::statistics; |
| 305 | unsigned width = c.mode == MockReplay::statistics ? statistics_counters : 1; | 314 | for (unsigned j = 0; j < (statistics ? statistics_counters : 1u); ++j) { |
| 315 | // A mesh segment counts the mesh-primitives count, the fragment and the compute invocations, | ||
| 316 | // and they land in CInvocations, PSInvocations and CSInvocations (statistics_sum.comp, D3D-291 and | ||
| 317 | // D3D-MESH-CLIPPING-COUNTER). | ||
| 318 | if (mesh && statistics && j != 5 && j != 7 && j != 10) continue; | ||
| 319 | const unsigned source = mesh && j == 10 ? 8 : j; | ||
| 320 | unsigned width = statistics ? statistics_counters : 1; | ||
| 306 | auto total = c.word(VK_NULL_HANDLE, word_size * j); | 321 | auto total = c.word(VK_NULL_HANDLE, word_size * j); |
| 307 | for (unsigned i = 0; i < n; ++i) { | 322 | for (unsigned i = 0; i < n; ++i) { |
| 308 | total += c.word(VK_NULL_HANDLE, word_size * (width * (i + 1) + j)); | 323 | total += c.word(VK_NULL_HANDLE, word_size * (width * (i + 1) + source)); |
| 309 | } | 324 | } |
| 310 | c.word(VK_NULL_HANDLE, word_size * j, total); | 325 | c.word(VK_NULL_HANDLE, word_size * j, total); |
| 311 | } | 326 | } |
| @@ -338,6 +353,7 @@ void test_helper_chunks() { | |||
| 338 | auto expected = c.buffers[dst]; | 353 | auto expected = c.buffers[dst]; |
| 339 | c.copies.clear(); | 354 | c.copies.clear(); |
| 340 | c.chunks.clear(); | 355 | c.chunks.clear(); |
| 356 | c.meshes.clear(); | ||
| 341 | c.groups.clear(); | 357 | c.groups.clear(); |
| 342 | c.transfers.clear(); | 358 | c.transfers.clear(); |
| 343 | if (mode == MockReplay::binary) { | 359 | if (mode == MockReplay::binary) { |
| @@ -348,7 +364,8 @@ void test_helper_chunks() { | |||
| 348 | } | 364 | } |
| 349 | } else { | 365 | } else { |
| 350 | if (mode == MockReplay::statistics) { | 366 | if (mode == MockReplay::statistics) { |
| 351 | helper.sum_statistics({}, qp, VK_NULL_HANDLE, nullptr, first, n, dst, output_offset); | 367 | helper.sum_statistics({}, qp, VK_NULL_HANDLE, VK_NULL_HANDLE, nullptr, first, n, dst, |
| 368 | output_offset); | ||
| 352 | } else { | 369 | } else { |
| 353 | helper.sum({}, qp, first, n, dst, output_offset); | 370 | helper.sum({}, qp, first, n, dst, output_offset); |
| 354 | } | 371 | } |
| @@ -363,6 +380,8 @@ void test_helper_chunks() { | |||
| 363 | expect(c.buffers[dst] == expected, "numeric helper result and destination guard bytes"); | 380 | expect(c.buffers[dst] == expected, "numeric helper result and destination guard bytes"); |
| 364 | expect(c.chunks == (extra ? std::vector<unsigned>{capacity, 1} | 381 | expect(c.chunks == (extra ? std::vector<unsigned>{capacity, 1} |
| 365 | : std::vector<unsigned>{capacity}), "exact chunk sizes"); | 382 | : std::vector<unsigned>{capacity}), "exact chunk sizes"); |
| 383 | expect(std::all_of(c.meshes.begin(), c.meshes.end(), [](unsigned m) { return m == 0; }), | ||
| 384 | "no mesh segment in these chunks"); | ||
| 366 | expect(c.copies.size() == 1 + extra && c.copies[0].first == first && (!extra | 385 | expect(c.copies.size() == 1 + extra && c.copies[0].first == first && (!extra |
| 367 | || c.copies[1].first == first + capacity), "chunk query indices end exactly at heap boundary"); | 386 | || c.copies[1].first == first + capacity), "chunk query indices end exactly at heap boundary"); |
| 368 | std::vector<unsigned> expected_groups(1 + extra, 1); | 387 | std::vector<unsigned> expected_groups(1 + extra, 1); |
| @@ -388,10 +407,53 @@ void test_helper_chunks() { | |||
| 388 | expect(c.word(dst, output_offset) == reset_sum, "sum accumulator reset between calls"); | 407 | expect(c.word(dst, output_offset) == reset_sum, "sum accumulator reset between calls"); |
| 389 | c.mode = MockReplay::statistics; | 408 | c.mode = MockReplay::statistics; |
| 390 | c.values[qp][first_query].fill(reset_counter); | 409 | c.values[qp][first_query].fill(reset_counter); |
| 391 | helper.sum_statistics({}, qp, VK_NULL_HANDLE, nullptr, first_query, 1, dst, output_offset); | 410 | helper.sum_statistics({}, qp, VK_NULL_HANDLE, VK_NULL_HANDLE, nullptr, first_query, 1, dst, output_offset); |
| 392 | for (unsigned j = 0; j < statistics_counters; ++j) { | 411 | for (unsigned j = 0; j < statistics_counters; ++j) { |
| 393 | expect(c.word(dst, output_offset + word_size * j) == reset_counter, "statistics accumulator reset"); | 412 | expect(c.word(dst, output_offset + word_size * j) == reset_counter, "statistics accumulator reset"); |
| 394 | } | 413 | } |
| 414 | |||
| 415 | // A statistics query that holds a mesh draw is split so the mesh segments run in the mesh pool (D3D-291). That | ||
| 416 | // pool counts the fragment and compute invocations only, so the sum copies them into the PSInvocations and | ||
| 417 | // CSInvocations fields of their record, and the clipping fields a mesh draw cannot count stay 0. | ||
| 418 | { | ||
| 419 | constexpr unsigned mesh_segments = 3; | ||
| 420 | constexpr std::uint64_t fragment = 40; | ||
| 421 | constexpr std::uint64_t compute = 7; | ||
| 422 | constexpr std::uint64_t generated = 5; // the primitives a mesh segment emits (D3D-MESH-CLIPPING-COUNTER) | ||
| 423 | const std::uint8_t mesh_flags[mesh_segments] = {1, 1, 1}; | ||
| 424 | auto mesh_pool = handle<VkQueryPool>(3); | ||
| 425 | auto primitives_pool = handle<VkQueryPool>(4); | ||
| 426 | c.mesh_pools.insert(mesh_pool); | ||
| 427 | c.primitives_pools.insert(primitives_pool); | ||
| 428 | c.values[mesh_pool].resize(mesh_segments); | ||
| 429 | c.values[primitives_pool].resize(mesh_segments); | ||
| 430 | std::uint64_t fragment_total = 0, compute_total = 0, generated_total = 0; | ||
| 431 | for (unsigned i = 0; i < mesh_segments; ++i) { | ||
| 432 | c.values[mesh_pool][i][0] = fragment + i; // the fragment shader invocations | ||
| 433 | c.values[mesh_pool][i][1] = compute + i; // the compute shader invocations | ||
| 434 | c.values[primitives_pool][i][0] = generated + i; // the primitives the mesh shader emitted | ||
| 435 | fragment_total += c.values[mesh_pool][i][0]; | ||
| 436 | compute_total += c.values[mesh_pool][i][1]; | ||
| 437 | generated_total += c.values[primitives_pool][i][0]; | ||
| 438 | } | ||
| 439 | c.buffers[dst].assign(buffer_bytes, guard_byte); | ||
| 440 | auto expected = c.buffers[dst]; | ||
| 441 | c.copies.clear(); | ||
| 442 | c.chunks.clear(); | ||
| 443 | c.meshes.clear(); | ||
| 444 | c.groups.clear(); | ||
| 445 | c.transfers.clear(); | ||
| 446 | helper.sum_statistics({}, qp, mesh_pool, primitives_pool, mesh_flags, 0, mesh_segments, dst, output_offset); | ||
| 447 | for (unsigned j = 0; j < statistics_counters; ++j) { | ||
| 448 | const std::uint64_t v = j == 5 ? generated_total : j == 7 ? fragment_total : j == 10 ? compute_total : 0; | ||
| 449 | std::memcpy(expected.data() + output_offset + word_size * j, &v, word_size); | ||
| 450 | } | ||
| 451 | expect(c.buffers[dst] == expected, | ||
| 452 | "a mesh segment fills CInvocations, PSInvocations and CSInvocations, and no other field"); | ||
| 453 | expect(c.meshes.size() == 1 && c.meshes[0] == 1, "the mesh chunk says its segments are mesh ones"); | ||
| 454 | expect(c.copies.size() == 2 && c.copies[0].pool == mesh_pool && c.copies[1].pool == primitives_pool, | ||
| 455 | "the mesh segment is read from the mesh pool and the mesh-primitives pool"); | ||
| 456 | } | ||
| 395 | } | 457 | } |
| 396 | 458 | ||
| 397 | void test_query_state() { | 459 | void test_query_state() { |
diff --git a/runtime/test/replay_query_predication_test.cpp b/runtime/test/replay_query_predication_test.cpp index 3ef0b484a..87056a499 100644 --- a/runtime/test/replay_query_predication_test.cpp +++ b/runtime/test/replay_query_predication_test.cpp | |||
| @@ -127,8 +127,8 @@ int main() { | |||
| 127 | vk.query_pool = [&](QueryHeapId id) -> QueryPool* { | 127 | vk.query_pool = [&](QueryHeapId id) -> QueryPool* { |
| 128 | return id == 1 ? &heap : id == 6 ? &statistics_heap : nullptr; | 128 | return id == 1 ? &heap : id == 6 ? &statistics_heap : nullptr; |
| 129 | }; | 129 | }; |
| 130 | vk.sum_statistics = [](VkCommandBuffer, VkQueryPool pool, VkQueryPool, const std::uint8_t*, std::uint32_t first, | 130 | vk.sum_statistics = [](VkCommandBuffer, VkQueryPool pool, VkQueryPool, VkQueryPool, const std::uint8_t*, |
| 131 | std::uint32_t count, VkBuffer, VkDeviceSize) { | 131 | std::uint32_t first, std::uint32_t count, VkBuffer, VkDeviceSize) { |
| 132 | g_trace->events.push_back(query_event("sum_statistics", pool, first) + "+" + std::to_string(count)); | 132 | g_trace->events.push_back(query_event("sum_statistics", pool, first) + "+" + std::to_string(count)); |
| 133 | }; | 133 | }; |
| 134 | vk.resolve_binary_occlusion = [](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, | 134 | vk.resolve_binary_occlusion = [](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, |
| @@ -685,14 +685,18 @@ int main() { | |||
| 685 | auto segments = std::make_shared<OcclusionSegmentPool>(); | 685 | auto segments = std::make_shared<OcclusionSegmentPool>(); |
| 686 | segments->pool = handle<VkQueryPool>(9); | 686 | segments->pool = handle<VkQueryPool>(9); |
| 687 | segments->mesh_pool = handle<VkQueryPool>(10); | 687 | segments->mesh_pool = handle<VkQueryPool>(10); |
| 688 | segments->primitives_pool = handle<VkQueryPool>(11); | ||
| 688 | segments->mesh = prepared.statistics_mesh; | 689 | segments->mesh = prepared.statistics_mesh; |
| 689 | segments->destroy = mock_destroy_pool; | 690 | segments->destroy = mock_destroy_pool; |
| 690 | QueryReplay queries; | 691 | QueryReplay queries; |
| 691 | expect(queries.plan(prepared, {}, 0, true, segments, 0) == ReplayResult::success, "plan mixed list"); | 692 | expect(queries.plan(prepared, {}, 0, true, segments, 0) == ReplayResult::success, "plan mixed list"); |
| 692 | expect(prepared.statistics_mesh_pool == handle<VkQueryPool>(10), "mixed list: the mesh pool is the list's"); | 693 | expect(prepared.statistics_mesh_pool == handle<VkQueryPool>(10), "mixed list: the mesh pool is the list's"); |
| 694 | expect(prepared.statistics_primitives_pool == handle<VkQueryPool>(11), | ||
| 695 | "mixed list: the mesh-primitives pool is the list's"); | ||
| 693 | expect(q[6].resolves.size() == 1 && q[6].resolves[0].sum && q[6].resolves[0].first == 3 && | 696 | expect(q[6].resolves.size() == 1 && q[6].resolves[0].sum && q[6].resolves[0].first == 3 && |
| 694 | q[6].resolves[0].count == 1 && q[6].resolves[0].mesh_pool == handle<VkQueryPool>(10) && | 697 | q[6].resolves[0].count == 1 && q[6].resolves[0].mesh_pool == handle<VkQueryPool>(10) && |
| 695 | q[6].resolves[0].mesh && q[6].resolves[0].mesh[3] == 1, | 698 | q[6].resolves[0].primitives_pool == handle<VkQueryPool>(11) && q[6].resolves[0].mesh && |
| 699 | q[6].resolves[0].mesh[3] == 1, | ||
| 696 | "mixed list: the mesh-only query's resolve sums its one mesh segment"); | 700 | "mixed list: the mesh-only query's resolve sums its one mesh segment"); |
| 697 | expect(queries.needs_statistics_sum, "mixed list: the statistics sum helper is needed"); | 701 | expect(queries.needs_statistics_sum, "mixed list: the statistics sum helper is needed"); |
| 698 | 702 | ||
| @@ -755,6 +759,21 @@ int main() { | |||
| 755 | expect(q[3].statistics_first == 1 && q[3].statistics_count == 3, "overlap-mesh: query 1 sums segments 1-3"); | 759 | expect(q[3].statistics_first == 1 && q[3].statistics_count == 3, "overlap-mesh: query 1 sums segments 1-3"); |
| 756 | } | 760 | } |
| 757 | 761 | ||
| 762 | // 17. D3D-291: the pool a mesh draw runs in must not enable a counter | ||
| 763 | // VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076 forbids, or the validation layer reports the VUID on | ||
| 764 | // every DispatchMesh inside a statistics query. The VUID leaves the fragment and compute invocations | ||
| 765 | // allowed, and those are the two the mesh pool counts; the nine it names are the rest of the eleven. | ||
| 766 | { | ||
| 767 | constexpr VkQueryPipelineStatisticFlags all_counters = 0x7ff; // the counters of a D3D12 statistics heap | ||
| 768 | expect((kMeshStatisticsFlags & kForbiddenMeshStatisticsFlags) == 0, | ||
| 769 | "the mesh pool enables none of the counters the VUID forbids"); | ||
| 770 | expect((all_counters & ~kForbiddenMeshStatisticsFlags) == kMeshStatisticsFlags, | ||
| 771 | "the mesh pool counts every counter the VUID leaves allowed"); | ||
| 772 | expect(kMeshStatisticsFlags == (VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT | | ||
| 773 | VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT), | ||
| 774 | "the mesh pool counts the fragment and compute invocations"); | ||
| 775 | } | ||
| 776 | |||
| 758 | if (failures) return 1; | 777 | if (failures) return 1; |
| 759 | std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); | 778 | std::puts("replay_query_predication_test: query resolves suspend conditional rendering around fills, copies and dispatches"); |
| 760 | return 0; | 779 | return 0; |
diff --git a/runtime/test/replay_uav_clear_offset_test.cpp b/runtime/test/replay_uav_clear_offset_test.cpp index 35818fe8e..b315ed30d 100644 --- a/runtime/test/replay_uav_clear_offset_test.cpp +++ b/runtime/test/replay_uav_clear_offset_test.cpp | |||
| @@ -173,6 +173,18 @@ int main() { | |||
| 173 | range.buffer_offset = UINT64_MAX - 2; | 173 | range.buffer_offset = UINT64_MAX - 2; |
| 174 | expect(run({1, true, VK_FORMAT_R8_UINT, 1, 2, 1, 0, 0, 1}) == ReplayResult::invalid_clear && writes.empty(), | 174 | expect(run({1, true, VK_FORMAT_R8_UINT, 1, 2, 1, 0, 0, 1}) == ReplayResult::invalid_clear && writes.empty(), |
| 175 | "backing range overflow is rejected before scratch allocation or emission"); | 175 | "backing range overflow is rejected before scratch allocation or emission"); |
| 176 | // Misaligned backing buffer_offset must be rejected for multi-byte elements (e.g., e > 4 violates | ||
| 177 | // VUID-vkCmdUpdateBuffer-dstOffset-00032; e == 2/4 would byte-swap/rotate elements in vkCmdFillBuffer). | ||
| 178 | range.buffer_offset = at + 2; | ||
| 179 | expect(run({1, true, VK_FORMAT_R32G32B32A32_UINT, 0, 32, 16, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(), | ||
| 180 | "misaligned backing buffer_offset for 16-byte element clear is rejected before vkCmdUpdateBuffer"); | ||
| 181 | expect(run({1, true, VK_FORMAT_R32_UINT, 0, 16, 4, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(), | ||
| 182 | "misaligned backing buffer_offset for 4-byte element clear is rejected before vkCmdFillBuffer"); | ||
| 183 | range.buffer_offset = at + 1; | ||
| 184 | expect(run({1, true, VK_FORMAT_R16_UINT, 0, 16, 2, 0, 0, 1}) == ReplayResult::unsupported && writes.empty(), | ||
| 185 | "odd backing buffer_offset for 2-byte element clear is rejected before vkCmdFillBuffer"); | ||
| 186 | expect(run({1, true, VK_FORMAT_R8_UINT, 0, 16, 1, 0, 0, 1}) == ReplayResult::success, | ||
| 187 | "odd backing buffer_offset for 1-byte R8 element clear still replays"); | ||
| 176 | range.buffer_offset = at; | 188 | range.buffer_offset = at; |
| 177 | vk.copy_scratch = {}; | 189 | vk.copy_scratch = {}; |
| 178 | 190 | ||
diff --git a/runtime/test/retire_tickets_test.cpp b/runtime/test/retire_tickets_test.cpp index 8eb5e02d0..f1dc836de 100644 --- a/runtime/test/retire_tickets_test.cpp +++ b/runtime/test/retire_tickets_test.cpp | |||
| @@ -30,6 +30,24 @@ int main() { | |||
| 30 | queue_one_destroyed = true; | 30 | queue_one_destroyed = true; |
| 31 | if (tickets.completed(query) != 4 || queried_destroyed) return 4; | 31 | if (tickets.completed(query) != 4 || queried_destroyed) return 4; |
| 32 | 32 | ||
| 33 | // pending_through() must coalesce repeated submissions on the same queue to the highest | ||
| 34 | // timeline value, omit idle queues, and exclude tickets past the requested cutoff. | ||
| 35 | tickets.record(5, 1, 10); | ||
| 36 | tickets.record(6, 2, 20); | ||
| 37 | tickets.record(7, 1, 12); | ||
| 38 | tickets.record(8, 1, 15); | ||
| 39 | tickets.record(9, 2, 25); | ||
| 40 | tickets.queue_idle(2); | ||
| 41 | const auto wait_list = tickets.pending_through(7); | ||
| 42 | if (wait_list.size() != 1 || wait_list[0].first != 1 || wait_list[0].second != 12) return 5; | ||
| 43 | |||
| 44 | // A non-monotonic ticket must not move the completed prefix backward. | ||
| 45 | done[1] = 15; | ||
| 46 | if (tickets.completed(query) != 9) return 6; | ||
| 47 | tickets.record(3, 1, 16); | ||
| 48 | done[1] = 16; | ||
| 49 | if (tickets.completed(query) != 9) return 7; | ||
| 50 | |||
| 33 | std::puts("out-of-order queue completion kept the retirement prefix safe"); | 51 | std::puts("out-of-order queue completion kept the retirement prefix safe"); |
| 34 | return 0; | 52 | return 0; |
| 35 | } | 53 | } |
diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index bf7ad80d1..55105d987 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp | |||
| @@ -8,6 +8,7 @@ | |||
| 8 | #include <filesystem> | 8 | #include <filesystem> |
| 9 | #include <fstream> | 9 | #include <fstream> |
| 10 | #include <initializer_list> | 10 | #include <initializer_list> |
| 11 | #include <limits> | ||
| 11 | #include <sstream> | 12 | #include <sstream> |
| 12 | #include <string> | 13 | #include <string> |
| 13 | #include <vector> | 14 | #include <vector> |
| @@ -570,6 +571,10 @@ int main() { | |||
| 570 | broken.resize(100); // truncated | 571 | broken.resize(100); // truncated |
| 571 | CHECK(!zlib_inflate(broken, out)); | 572 | CHECK(!zlib_inflate(broken, out)); |
| 572 | CHECK(!zlib_inflate(dynamic, out, 599)); // larger than the limit | 573 | CHECK(!zlib_inflate(dynamic, out, 599)); // larger than the limit |
| 574 | const auto max_limit = (std::numeric_limits<std::size_t>::max)(); | ||
| 575 | CHECK(zlib_inflate(stored, out, max_limit) && out.size() == 40); | ||
| 576 | CHECK(zlib_inflate(fixed, out, max_limit) && out == bytes("hello hello hello leonida")); | ||
| 577 | CHECK(zlib_inflate(dynamic, out, max_limit) && out == skewed(600)); | ||
| 573 | CHECK(!zlib_inflate(bytes("not zlib"), out)); | 578 | CHECK(!zlib_inflate(bytes("not zlib"), out)); |
| 574 | 579 | ||
| 575 | Json json; | 580 | Json json; |
| @@ -642,7 +647,9 @@ int main() { | |||
| 642 | "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, " | 647 | "{\"semantic\": \"TEXCOORD\", \"semantic_index\": 3, \"register\": -1, \"system_value\": 0, " |
| 643 | "\"component_type\": \"float\"}]},\n" | 648 | "\"component_type\": \"float\"}]},\n" |
| 644 | " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"inputs\": [0, 1, 28, 29], " | 649 | " \"ps_out\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash << "\", \"inputs\": [0, 1, 28, 29], " |
| 645 | "\"outputs\": [0, 2], \"f16_halves\": {\"0\": [28, 29], \"bad\": [1], \"7\": [20, 21]}},\n" | 650 | "\"outputs\": [0, 2], \"f16_halves\": {\"0\": [28, 29], \"bad\": [1], \"-1\": [1, 2], " |
| 651 | "\"+2\": [3, 4], \" 3\": [5, 6], \"4294967296\": [9, 10], \"99999999999999999999\": [11, 12], " | ||
| 652 | "\"7\": [20, 21]}},\n" | ||
| 646 | " \"ps_native\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, " | 653 | " \"ps_native\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, " |
| 647 | "\"subgroup_size\": 64},\n" | 654 | "\"subgroup_size\": 64},\n" |
| 648 | " \"cs_emulated\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, " | 655 | " \"cs_emulated\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash2 << "\", \"wave64\": true, " |
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index c9fd70e4a..03a7ecd22 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py | |||
| @@ -124,8 +124,6 @@ def cs_fssm_extra(path): | |||
| 124 | 124 | ||
| 125 | 125 | ||
| 126 | def shader_source(name): | 126 | def shader_source(name): |
| 127 | if name == "ps_mullit": | ||
| 128 | return "../../../tests/semantic/fixtures/ps_mullit" | ||
| 129 | return "vs_clip" if name in CLIP_CASES else name | 127 | return "vs_clip" if name in CLIP_CASES else name |
| 130 | 128 | ||
| 131 | 129 | ||
| @@ -216,8 +214,7 @@ def main(): | |||
| 216 | out = Path(sys.argv[1]) | 214 | out = Path(sys.argv[1]) |
| 217 | available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys()) | 215 | available = sorted({p.stem for p in Path(HERE).glob("*.asm")} | CLIP_CASES.keys()) |
| 218 | names = sys.argv[2:] or available | 216 | names = sys.argv[2:] or available |
| 219 | # mullit_readback.py uses the CPU semantic fixture as an explicit build target. | 217 | unknown = sorted(set(names) - set(available)) |
| 220 | unknown = sorted(set(names) - set(available) - {"ps_mullit"}) | ||
| 221 | if unknown: | 218 | if unknown: |
| 222 | sys.exit("Unknown test shaders: " + ", ".join(unknown)) | 219 | sys.exit("Unknown test shaders: " + ", ".join(unknown)) |
| 223 | skipped = [n for n in names if n.startswith("ms_")] | 220 | skipped = [n for n in names if n.startswith("ms_")] |
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 7b3777287..7b4bcdf13 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py | |||
| @@ -358,6 +358,33 @@ def heap_init_env(): | |||
| 358 | return {"VKC_HEAP_INIT": path, "VKC_OUT_WORDS": str(len(HEAP_INIT_FILE) // 4)} | 358 | return {"VKC_HEAP_INIT": path, "VKC_OUT_WORDS": str(len(HEAP_INIT_FILE) // 4)} |
| 359 | 359 | ||
| 360 | 360 | ||
| 361 | def shift64_words(): | ||
| 362 | """cs_w32_shift64: input heap and full expected readback, using Python integers as the oracle.""" | ||
| 363 | values = (0, 1, 0xFFFFFFFF, 0x100000000, 0x7FFFFFFFFFFFFFFF, | ||
| 364 | 0x8000000000000000, 0xFFFFFFFFFFFFFFFF, 0x8123456789ABCDEF) | ||
| 365 | counts = (0, 1, 31, 32, 33, 63, 64, 65) | ||
| 366 | inputs, results = [], [] | ||
| 367 | for value in values: | ||
| 368 | for count in counts: | ||
| 369 | inputs.extend((value & 0xFFFFFFFF, value >> 32, count, 0xA5A5A5A5)) | ||
| 370 | signed = value if value < (1 << 63) else value - (1 << 64) | ||
| 371 | shift = count & 63 | ||
| 372 | for result in (value << shift, value >> shift, signed >> shift): | ||
| 373 | results.extend((result & 0xFFFFFFFF, (result >> 32) & 0xFFFFFFFF)) | ||
| 374 | return [0xEEEEEEEE] * len(results) + inputs, results + inputs | ||
| 375 | |||
| 376 | |||
| 377 | def shift64_test(tools, spirv, env=None): | ||
| 378 | """Verify all three 64-bit shifts for 64 memory-fed cases, including the untouched input records.""" | ||
| 379 | initial, expected = shift64_words() | ||
| 380 | with tempfile.TemporaryDirectory(prefix="leonida-shift64-") as tmp: | ||
| 381 | path = Path(tmp) / "input.bin" | ||
| 382 | path.write_bytes(struct.pack(f"<{len(initial)}I", *initial)) | ||
| 383 | child = dict(os.environ if env is None else env, VKC_HEAP_INIT=str(path)) | ||
| 384 | child.setdefault("VKC_SUBGROUP_SIZE", str(subgroup_size(spirv, "cs_w32_shift64") or 32)) | ||
| 385 | return dump_test(tools, spirv, "cs_w32_shift64", expected, len(expected), child) | ||
| 386 | |||
| 387 | |||
| 361 | # cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back. | 388 | # cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back. |
| 362 | USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF] | 389 | USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF] |
| 363 | USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)} | 390 | USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)} |
| @@ -597,6 +624,17 @@ STORE_WORDS = { | |||
| 597 | # 3D image atomics: the data register afterwards (sint image) and the six texels afterwards (volume) | 624 | # 3D image atomics: the data register afterwards (sint image) and the six texels afterwards (volume) |
| 598 | "cs_imgatomic3d": ({}, dict(enumerate([0x101, 0xDB, 0xF4, 0xCE, 0xE6, 0xFF])), | 625 | "cs_imgatomic3d": ({}, dict(enumerate([0x101, 0xDB, 0xF4, 0xCE, 0xE6, 0xFF])), |
| 599 | {57: 0x111, 19: 3, 44: 0xF4, 6: 0xD00D, 30: 0xE6, 39: 0x10}), | 626 | {57: 0x111, 19: 3, 44: 0xF4, 6: 0xD00D, 30: 0xE6, 39: 0x10}), |
| 627 | # GPU-IMG-ATOMIC-EXT: swap, inc, dec, fmin, fmax and fcmpswap. The 2D cases' texels afterwards (uint image, with the | ||
| 628 | # four that all 64 threads hit at 40..43), the data registers afterwards (sint image: 2D cases at 0..20, 3D cases | ||
| 629 | # at 32..37) and the 3D cases' texels afterwards (volume) | ||
| 630 | "cs_imgatomic_ext": ({0: 0x12345678, 1: 0xABCDEF01, 2: 0, 3: 0x68, 4: 0, 5: 0x68, 6: 0x32, 7: 9, 8: 0x6D, | ||
| 631 | 9: 0x3FC00000, 10: 0xC0400000, 11: 0x40200000, 12: 0x3FC00000, 13: 0x3FC00000, | ||
| 632 | 14: 0x3FC00000, 15: 0x40490FDB, 16: 0x3FC00000, 17: 0x3F800000, 18: 0x7FC00000, | ||
| 633 | 19: 0x78, 20: 0x77, 40: 0xCC, 41: 0x4D, 42: 0x427C0000, 43: 0xC27C0000}, | ||
| 634 | {0: 0x64, 1: 0xABCDEF01, 2: 0x66, 3: 0x67, 4: 0x68, 5: 0x69, 6: 0x6A, 7: 0, 8: 0x1F4, | ||
| 635 | **dict.fromkeys(range(9, 17), 0x3FC00000), 17: 0, 18: 0x7FC00000, 19: 0x77, 20: 0x78, | ||
| 636 | 32: 0x101, 33: 0xDB, 34: 0xF4, 35: 0x3FC00000, 36: 0x3FC00000, 37: 0x3FC00000}, | ||
| 637 | {6: 0xC0400000, 19: 0xDC, 30: 0x40200000, 39: 0x40490FDB, 44: 0x64, 57: 0x0BADF00D}), | ||
| 600 | # image_get_resinfo on a 16x4 image with five levels: (width, height, depth, levels) of levels 0, 1 and 3, then | 638 | # image_get_resinfo on a 16x4 image with five levels: (width, height, depth, levels) of levels 0, 1 and 3, then |
| 601 | # width and height of level 2 and an untouched register, height and levels of level 1, the levels alone, and | 639 | # width and height of level 2 and an untouched register, height and levels of level 1, the levels alone, and |
| 602 | # level 5, past the last (2D depth 0 and the past-the-end zeros measured on RDNA2, SHADER-388) | 640 | # level 5, past the last (2D depth 0 and the past-the-end zeros measured on RDNA2, SHADER-388) |
| @@ -1842,6 +1880,7 @@ def main(): | |||
| 1842 | expected_words=USER_SGPRS_WORDS, env=USER_SGPRS_ENV))) | 1880 | expected_words=USER_SGPRS_WORDS, env=USER_SGPRS_ENV))) |
| 1843 | results.append(("cs_heap_init", compute_test(tools, spirv, "cs_heap_init", "1", "dump", | 1881 | results.append(("cs_heap_init", compute_test(tools, spirv, "cs_heap_init", "1", "dump", |
| 1844 | expected_words=HEAP_INIT_EXPECTED, env=heap_init_env()))) | 1882 | expected_words=HEAP_INIT_EXPECTED, env=heap_init_env()))) |
| 1883 | results.append(("cs_w32_shift64", shift64_test(tools, spirv))) | ||
| 1845 | results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv))) | 1884 | results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv))) |
| 1846 | results.append(("cs_fma_fused", fma_fused_test(tools, spirv))) | 1885 | results.append(("cs_fma_fused", fma_fused_test(tools, spirv))) |
| 1847 | results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump", | 1886 | results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump", |
| @@ -1857,7 +1896,8 @@ def main(): | |||
| 1857 | results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3"))) | 1896 | results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3"))) |
| 1858 | with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp: | 1897 | with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp: |
| 1859 | results.append(("ms_v5_workgroup", mesh_v5_test(tools, spirv, Path(tmp) / "groups.raw"))) | 1898 | results.append(("ms_v5_workgroup", mesh_v5_test(tools, spirv, Path(tmp) / "groups.raw"))) |
| 1860 | for name, args in (("cs_imgstore", []), ("cs_imgload", ["load"]), ("cs_imgload_tfe", ["load"]), | 1899 | for name, args in (("cs_imgstore", []), ("cs_imgstore_cube", ["cube"]), ("cs_imgload", ["load"]), |
| 1900 | ("cs_imgload_tfe", ["load"]), | ||
| 1861 | ("cs_imgload_d16", ["load-d16"]), ("cs_imgload_d16_tfe", ["load-d16"]), | 1901 | ("cs_imgload_d16", ["load-d16"]), ("cs_imgload_d16_tfe", ["load-d16"]), |
| 1862 | ("cs_sample_lz_int_d16", ["load-d16"])): | 1902 | ("cs_sample_lz_int_d16", ["load-d16"])): |
| 1863 | code, out = run(os.path.join(tools, "vk_store_test" + EXE), os.path.join(spirv, name + ".spv"), *args) | 1903 | code, out = run(os.path.join(tools, "vk_store_test" + EXE), os.path.join(spirv, name + ".spv"), *args) |
diff --git a/runtime/test/shaders/cs_div_fmas_f64.asm b/runtime/test/shaders/cs_div_fmas_f64.asm index 41b594752..dfede7187 100644 --- a/runtime/test/shaders/cs_div_fmas_f64.asm +++ b/runtime/test/shaders/cs_div_fmas_f64.asm | |||
| @@ -4,7 +4,8 @@ | |||
| 4 | ; fma(a, a, c) = 2^-60 = 0x3c300000_00000000 fused; rounding a*a first gives 1 + 2^-29 and a result of 0 ("split"). | 4 | ; fma(a, a, c) = 2^-60 = 0x3c300000_00000000 fused; rounding a*a first gives 1 + 2^-29 and a result of 0 ("split"). |
| 5 | ; out[0..1] = 0x00000000 0x3c300000 (split: 0x00000000 0x00000000). Under --fma khr (LEONIDA_FMA=khr) the translator | 5 | ; out[0..1] = 0x00000000 0x3c300000 (split: 0x00000000 0x00000000). Under --fma khr (LEONIDA_FMA=khr) the translator |
| 6 | ; emits OpFmaKHR on doubles (feature shaderFmaFloat64) and only the fused words pass; under the default GLSL Fma a | 6 | ; emits OpFmaKHR on doubles (feature shaderFmaFloat64) and only the fused words pass; under the default GLSL Fma a |
| 7 | ; driver may split (NVIDIA RTX 4090, 621.24, does). | 7 | ; driver may split. The operands here are literals, so a driver that folds the constant Fma while compiling can |
| 8 | ; round it twice: NVIDIA RTX 4090 (621.24) does, while the same values as run-time operands are fused there. | ||
| 8 | s_mov_b64 vcc, 0 | 9 | s_mov_b64 vcc, 0 |
| 9 | v_mov_b32 v0, 0x00400000 | 10 | v_mov_b32 v0, 0x00400000 |
| 10 | v_mov_b32 v1, 0x3ff00000 | 11 | v_mov_b32 v1, 0x3ff00000 |
diff --git a/runtime/test/shaders/cs_div_fmas_f64_rt.asm b/runtime/test/shaders/cs_div_fmas_f64_rt.asm new file mode 100644 index 000000000..cf95b23bb --- /dev/null +++ b/runtime/test/shaders/cs_div_fmas_f64_rt.asm | |||
| @@ -0,0 +1,18 @@ | |||
| 1 | ; group: 1,1,1 | ||
| 2 | ; rsrc2: 0x8090 | ||
| 3 | ; cs_div_fmas_f64 with its operands read at run time: s4..s7 hold a = 1 + 2^-30 (0x3ff00000_00400000) and | ||
| 4 | ; c = -(1 + 2^-29) (0xbff00000_00800000), seeded by vk_compute_test's VKC_SGPRS, so the driver cannot fold the Fma | ||
| 5 | ; while compiling the pipeline. v_div_fmas_f64 with VCC = 0 is fma(a, a, c) = 2^-60 with one rounding, 0 with two. | ||
| 6 | ; Run: VKC_SGPRS=0x00400000,0x3ff00000,0x00800000,0xbff00000 vk_compute_test cs_div_fmas_f64_rt.spv 1 dump | ||
| 7 | ; out[0..1] = 0x00000000 0x3c300000 (split: 0x00000000 0x00000000). Measured fused under the default GLSL Fma on the | ||
| 8 | ; NVIDIA RTX 4090 (621.24), RTX 3070 (621.01) and RTX 5060 Laptop (621.24), all of which except the 5060 split the | ||
| 9 | ; all-constant cs_div_fmas_f64. | ||
| 10 | s_mov_b64 vcc, 0 | ||
| 11 | v_mov_b32 v0, s4 | ||
| 12 | v_mov_b32 v1, s5 | ||
| 13 | v_mov_b32 v2, s6 | ||
| 14 | v_mov_b32 v3, s7 | ||
| 15 | v_div_fmas_f64 v[4:5], v[0:1], v[0:1], v[2:3] | ||
| 16 | v_mov_b32 v6, 0 | ||
| 17 | buffer_store_dwordx2 v[4:5], v6, s[0:3], 0 offen | ||
| 18 | s_endpgm | ||
diff --git a/runtime/test/shaders/cs_imgatomic_ext.asm b/runtime/test/shaders/cs_imgatomic_ext.asm new file mode 100644 index 000000000..e58ecbcb6 --- /dev/null +++ b/runtime/test/shaders/cs_imgatomic_ext.asm | |||
| @@ -0,0 +1,313 @@ | |||
| 1 | ; The six image atomics that cs_imgatomic.asm and cs_imgatomic3d.asm don't run: image_atomic_swap, inc, dec, fmin, fmax | ||
| 2 | ; and fcmpswap, on the 2D r32 uint image (binding 4) and the 3D r32 uint volume (binding 7) (GPU-IMG-ATOMIC-EXT). | ||
| 3 | ; RDNA2 ISA (MIMG), M = the texel before the op, D = the data register, C = the comparand (fcmpswap's second data | ||
| 4 | ; register): swap writes D; inc writes (M >= D) ? 0 : M + 1 and dec (M == 0 || M > D) ? D : M - 1, both compares | ||
| 5 | ; unsigned (cases 19 and 20 have a D that is negative as a signed number); fmin and fmax write the smaller / larger | ||
| 6 | ; of M and D as floats; fcmpswap writes D where M equals C as floats (never with a NaN, +0 equals -0). With glc the | ||
| 7 | ; data register returns M; without glc it is left alone. The cases avoid what the ISA and SPIR-V leave open: no NaN | ||
| 8 | ; in memory for fmin/fmax (the ISA's compare and GLSL NMin differ there), no fmin/fmax of +0 against -0 (NMin may | ||
| 9 | ; return either), and no denormals (RDNA2's flush behaviour is unmeasured). | ||
| 10 | ; Run: vk_store_test cs_imgatomic_ext.spv words. The tool fills the uint image (T# 0x2000...) with M = 100 + i at | ||
| 11 | ; texel i = 8y + x, the sint image (T# 0x3000...) with -2i and the volume (T# 0x5000...) with 200 + i at | ||
| 12 | ; i = 16z + 4y + x. 1.5 = 0x3fc00000, 2.5 = 0x40200000, -3.0 = 0xc0400000, 2.0 = 0x40000000, 1.0 = 0x3f800000, | ||
| 13 | ; pi = 0x40490fdb, NaN = 0x7fc00000. | ||
| 14 | ; First, all 64 threads (no glc), each on one shared texel: inc with D = 0xffffffff on texel 40 (140 + 64 = 0xcc), | ||
| 15 | ; dec with D = 0xffffffff on 41 (141 - 64 = 0x4d), fmax with D = float(t) on 42 (63.0 = 0x427c0000), fmin with | ||
| 16 | ; D = -float(t) on 43 (-63.0 = 0xc27c0000); the fills there are small positive denormals as floats, below every D | ||
| 17 | ; of fmax but 0.0 and above every D of fmin, so the result does not depend on them. Then every lane sets the trap: | ||
| 18 | ; coordinates (2, 3, 3) and data 1 in every data register. After that only thread 0 is on, so the 63 inactive lanes | ||
| 19 | ; keep the trap: an op they ran anyway would land on uint texel 26 or volume texel 62 (swap writes 1 there; the | ||
| 20 | ; fills, 126 and 262, must survive), and an inc applied by every lane would show in its case. 2D case c works on | ||
| 21 | ; uint texel c and stores its data register afterwards into sint texel c; "preset" is what a swap without glc | ||
| 22 | ; puts in the texel first. | ||
| 23 | ; c op D C glc M (preset) uint word c afterwards sint word c | ||
| 24 | ; 0 swap 0x12345678 - yes 100 0x12345678 0x00000064 | ||
| 25 | ; 1 swap 0xabcdef01 - no 101 0xabcdef01 0xabcdef01 | ||
| 26 | ; 2 inc 102 - yes 102 0x00000000 0x00000066 | ||
| 27 | ; 3 inc 200 - yes 103 0x00000068 0x00000067 | ||
| 28 | ; 4 inc 50 - yes 104 0x00000000 0x00000068 | ||
| 29 | ; 5 dec 200 - yes 105 0x00000068 0x00000069 | ||
| 30 | ; 6 dec 50 - yes 106 0x00000032 0x0000006a | ||
| 31 | ; 7 dec 9 - yes 0 (preset) 0x00000009 0x00000000 | ||
| 32 | ; 8 inc 500 - no 108 0x0000006d 0x000001f4 | ||
| 33 | ; 9 fmin 2.5 - yes 1.5 (preset) 0x3fc00000 0x3fc00000 | ||
| 34 | ; 10 fmin -3.0 - yes 1.5 (preset) 0xc0400000 0x3fc00000 | ||
| 35 | ; 11 fmax 2.5 - yes 1.5 (preset) 0x40200000 0x3fc00000 | ||
| 36 | ; 12 fmax -3.0 - yes 1.5 (preset) 0x3fc00000 0x3fc00000 | ||
| 37 | ; 13 fmin NaN - yes 1.5 (preset) 0x3fc00000 0x3fc00000 | ||
| 38 | ; 14 fmax NaN - yes 1.5 (preset) 0x3fc00000 0x3fc00000 | ||
| 39 | ; 15 fcmpswap pi 1.5 yes 1.5 (preset) 0x40490fdb 0x3fc00000 | ||
| 40 | ; 16 fcmpswap pi 2.0 yes 1.5 (preset) 0x3fc00000 0x3fc00000 | ||
| 41 | ; 17 fcmpswap 1.0 -0.0 yes 0 (preset) 0x3f800000 0x00000000 | ||
| 42 | ; 18 fcmpswap 1.0 NaN yes NaN (preset) 0x7fc00000 0x7fc00000 | ||
| 43 | ; 19 inc 0xfffffff0 - yes 119 0x00000078 0x00000077 | ||
| 44 | ; 20 dec 0xfffffff0 - yes 120 0x00000077 0x00000078 | ||
| 45 | ; 3D case j works on volume texel i = 16z + 4y + x (three different coordinates, so a swapped pair lands elsewhere), | ||
| 46 | ; always with glc, and stores its data register afterwards into sint texel 32 + j. | ||
| 47 | ; j op D C (x, y, z) i V (preset) volume word i afterwards sint word 32 + j | ||
| 48 | ; 0 swap 0x0badf00d - (1, 2, 3) 57 257 0x0badf00d 0x00000101 | ||
| 49 | ; 1 inc 300 - (3, 0, 1) 19 219 0x000000dc 0x000000db | ||
| 50 | ; 2 dec 100 - (0, 3, 2) 44 244 0x00000064 0x000000f4 | ||
| 51 | ; 3 fmin -3.0 - (2, 1, 0) 6 1.5 (preset) 0xc0400000 0x3fc00000 | ||
| 52 | ; 4 fmax 2.5 - (2, 3, 1) 30 1.5 (preset) 0x40200000 0x3fc00000 | ||
| 53 | ; 5 fcmpswap pi 1.5 (3, 1, 2) 39 1.5 (preset) 0x40490fdb 0x3fc00000 | ||
| 54 | ; Every other word keeps its fill. | ||
| 55 | s_mov_b32 s8, 0x5000 | ||
| 56 | s_mov_b32 s9, 0x1400000 | ||
| 57 | s_mov_b32 s10, 0x55 | ||
| 58 | s_mov_b32 s11, 0x55 | ||
| 59 | s_mov_b32 s12, 0x55 | ||
| 60 | s_mov_b32 s13, 0x55 | ||
| 61 | s_mov_b32 s14, 0x55 | ||
| 62 | s_mov_b32 s15, 0x55 | ||
| 63 | s_mov_b32 s16, 0x2000 | ||
| 64 | s_mov_b32 s17, 0x1400000 | ||
| 65 | s_mov_b32 s18, 0x22 | ||
| 66 | s_mov_b32 s19, 0x22 | ||
| 67 | s_mov_b32 s20, 0x22 | ||
| 68 | s_mov_b32 s21, 0x22 | ||
| 69 | s_mov_b32 s22, 0x22 | ||
| 70 | s_mov_b32 s23, 0x22 | ||
| 71 | s_mov_b32 s24, 0x3000 | ||
| 72 | s_mov_b32 s25, 0x1500000 | ||
| 73 | s_mov_b32 s26, 0x33 | ||
| 74 | s_mov_b32 s27, 0x33 | ||
| 75 | s_mov_b32 s28, 0x33 | ||
| 76 | s_mov_b32 s29, 0x33 | ||
| 77 | s_mov_b32 s30, 0x33 | ||
| 78 | s_mov_b32 s31, 0x33 | ||
| 79 | v_mov_b32_e32 v2, 5 | ||
| 80 | v_mov_b32_e32 v1, 0 | ||
| 81 | v_mov_b32_e32 v10, -1 | ||
| 82 | image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 83 | v_mov_b32_e32 v1, 1 | ||
| 84 | v_mov_b32_e32 v10, -1 | ||
| 85 | image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 86 | v_mov_b32_e32 v1, 2 | ||
| 87 | v_cvt_f32_u32_e32 v10, v0 | ||
| 88 | image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 89 | v_mov_b32_e32 v1, 3 | ||
| 90 | v_cvt_f32_u32_e32 v10, v0 | ||
| 91 | v_xor_b32_e32 v10, 0x80000000, v10 | ||
| 92 | image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 93 | v_mov_b32_e32 v1, 2 | ||
| 94 | v_mov_b32_e32 v2, 3 | ||
| 95 | v_mov_b32_e32 v3, 3 | ||
| 96 | v_mov_b32_e32 v6, 2 | ||
| 97 | v_mov_b32_e32 v7, 3 | ||
| 98 | v_mov_b32_e32 v10, 1 | ||
| 99 | v_mov_b32_e32 v11, 1 | ||
| 100 | v_mov_b32_e32 v12, 1 | ||
| 101 | v_cmpx_eq_u32_e32 0, v0 | ||
| 102 | v_mov_b32_e32 v1, 0 | ||
| 103 | v_mov_b32_e32 v2, 0 | ||
| 104 | v_mov_b32_e32 v10, 0x12345678 | ||
| 105 | image_atomic_swap v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 106 | s_waitcnt vmcnt(0) | ||
| 107 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 108 | v_mov_b32_e32 v1, 1 | ||
| 109 | v_mov_b32_e32 v2, 0 | ||
| 110 | v_mov_b32_e32 v10, 0xabcdef01 | ||
| 111 | image_atomic_swap v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 112 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 113 | v_mov_b32_e32 v1, 2 | ||
| 114 | v_mov_b32_e32 v2, 0 | ||
| 115 | v_mov_b32_e32 v10, 0x66 | ||
| 116 | image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 117 | s_waitcnt vmcnt(0) | ||
| 118 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 119 | v_mov_b32_e32 v1, 3 | ||
| 120 | v_mov_b32_e32 v2, 0 | ||
| 121 | v_mov_b32_e32 v10, 0xc8 | ||
| 122 | image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 123 | s_waitcnt vmcnt(0) | ||
| 124 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 125 | v_mov_b32_e32 v1, 4 | ||
| 126 | v_mov_b32_e32 v2, 0 | ||
| 127 | v_mov_b32_e32 v10, 50 | ||
| 128 | image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 129 | s_waitcnt vmcnt(0) | ||
| 130 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 131 | v_mov_b32_e32 v1, 5 | ||
| 132 | v_mov_b32_e32 v2, 0 | ||
| 133 | v_mov_b32_e32 v10, 0xc8 | ||
| 134 | image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 135 | s_waitcnt vmcnt(0) | ||
| 136 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 137 | v_mov_b32_e32 v1, 6 | ||
| 138 | v_mov_b32_e32 v2, 0 | ||
| 139 | v_mov_b32_e32 v10, 50 | ||
| 140 | image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 141 | s_waitcnt vmcnt(0) | ||
| 142 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 143 | v_mov_b32_e32 v1, 7 | ||
| 144 | v_mov_b32_e32 v2, 0 | ||
| 145 | v_mov_b32_e32 v12, 0 | ||
| 146 | image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 147 | v_mov_b32_e32 v10, 9 | ||
| 148 | image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 149 | s_waitcnt vmcnt(0) | ||
| 150 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 151 | v_mov_b32_e32 v1, 0 | ||
| 152 | v_mov_b32_e32 v2, 1 | ||
| 153 | v_mov_b32_e32 v10, 0x1f4 | ||
| 154 | image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 155 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 156 | v_mov_b32_e32 v1, 1 | ||
| 157 | v_mov_b32_e32 v2, 1 | ||
| 158 | v_mov_b32_e32 v12, 0x3fc00000 | ||
| 159 | image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 160 | v_mov_b32_e32 v10, 0x40200000 | ||
| 161 | image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 162 | s_waitcnt vmcnt(0) | ||
| 163 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 164 | v_mov_b32_e32 v1, 2 | ||
| 165 | v_mov_b32_e32 v2, 1 | ||
| 166 | v_mov_b32_e32 v12, 0x3fc00000 | ||
| 167 | image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 168 | v_mov_b32_e32 v10, 0xc0400000 | ||
| 169 | image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 170 | s_waitcnt vmcnt(0) | ||
| 171 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 172 | v_mov_b32_e32 v1, 3 | ||
| 173 | v_mov_b32_e32 v2, 1 | ||
| 174 | v_mov_b32_e32 v12, 0x3fc00000 | ||
| 175 | image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 176 | v_mov_b32_e32 v10, 0x40200000 | ||
| 177 | image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 178 | s_waitcnt vmcnt(0) | ||
| 179 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 180 | v_mov_b32_e32 v1, 4 | ||
| 181 | v_mov_b32_e32 v2, 1 | ||
| 182 | v_mov_b32_e32 v12, 0x3fc00000 | ||
| 183 | image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 184 | v_mov_b32_e32 v10, 0xc0400000 | ||
| 185 | image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 186 | s_waitcnt vmcnt(0) | ||
| 187 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 188 | v_mov_b32_e32 v1, 5 | ||
| 189 | v_mov_b32_e32 v2, 1 | ||
| 190 | v_mov_b32_e32 v12, 0x3fc00000 | ||
| 191 | image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 192 | v_mov_b32_e32 v10, 0x7fc00000 | ||
| 193 | image_atomic_fmin v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 194 | s_waitcnt vmcnt(0) | ||
| 195 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 196 | v_mov_b32_e32 v1, 6 | ||
| 197 | v_mov_b32_e32 v2, 1 | ||
| 198 | v_mov_b32_e32 v12, 0x3fc00000 | ||
| 199 | image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 200 | v_mov_b32_e32 v10, 0x7fc00000 | ||
| 201 | image_atomic_fmax v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 202 | s_waitcnt vmcnt(0) | ||
| 203 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 204 | v_mov_b32_e32 v1, 7 | ||
| 205 | v_mov_b32_e32 v2, 1 | ||
| 206 | v_mov_b32_e32 v12, 0x3fc00000 | ||
| 207 | image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 208 | v_mov_b32_e32 v10, 0x40490fdb | ||
| 209 | v_mov_b32_e32 v11, 0x3fc00000 | ||
| 210 | image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 211 | s_waitcnt vmcnt(0) | ||
| 212 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 213 | v_mov_b32_e32 v1, 0 | ||
| 214 | v_mov_b32_e32 v2, 2 | ||
| 215 | v_mov_b32_e32 v12, 0x3fc00000 | ||
| 216 | image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 217 | v_mov_b32_e32 v10, 0x40490fdb | ||
| 218 | v_mov_b32_e32 v11, 0x40000000 | ||
| 219 | image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 220 | s_waitcnt vmcnt(0) | ||
| 221 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 222 | v_mov_b32_e32 v1, 1 | ||
| 223 | v_mov_b32_e32 v2, 2 | ||
| 224 | v_mov_b32_e32 v12, 0 | ||
| 225 | image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 226 | v_mov_b32_e32 v10, 0x3f800000 | ||
| 227 | v_mov_b32_e32 v11, 0x80000000 | ||
| 228 | image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 229 | s_waitcnt vmcnt(0) | ||
| 230 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 231 | v_mov_b32_e32 v1, 2 | ||
| 232 | v_mov_b32_e32 v2, 2 | ||
| 233 | v_mov_b32_e32 v12, 0x7fc00000 | ||
| 234 | image_atomic_swap v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 235 | v_mov_b32_e32 v10, 0x3f800000 | ||
| 236 | v_mov_b32_e32 v11, 0x7fc00000 | ||
| 237 | image_atomic_fcmpswap v[10:11], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 238 | s_waitcnt vmcnt(0) | ||
| 239 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 240 | v_mov_b32_e32 v1, 3 | ||
| 241 | v_mov_b32_e32 v2, 2 | ||
| 242 | v_mov_b32_e32 v10, 0xfffffff0 | ||
| 243 | image_atomic_inc v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 244 | s_waitcnt vmcnt(0) | ||
| 245 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 246 | v_mov_b32_e32 v1, 4 | ||
| 247 | v_mov_b32_e32 v2, 2 | ||
| 248 | v_mov_b32_e32 v10, 0xfffffff0 | ||
| 249 | image_atomic_dec v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc | ||
| 250 | s_waitcnt vmcnt(0) | ||
| 251 | image_store v10, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 252 | v_mov_b32_e32 v1, 1 | ||
| 253 | v_mov_b32_e32 v2, 2 | ||
| 254 | v_mov_b32_e32 v3, 3 | ||
| 255 | v_mov_b32_e32 v10, 0xbadf00d | ||
| 256 | image_atomic_swap v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc | ||
| 257 | s_waitcnt vmcnt(0) | ||
| 258 | v_mov_b32_e32 v6, 0 | ||
| 259 | v_mov_b32_e32 v7, 4 | ||
| 260 | image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 261 | v_mov_b32_e32 v1, 3 | ||
| 262 | v_mov_b32_e32 v2, 0 | ||
| 263 | v_mov_b32_e32 v3, 1 | ||
| 264 | v_mov_b32_e32 v10, 0x12c | ||
| 265 | image_atomic_inc v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc | ||
| 266 | s_waitcnt vmcnt(0) | ||
| 267 | v_mov_b32_e32 v6, 1 | ||
| 268 | v_mov_b32_e32 v7, 4 | ||
| 269 | image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 270 | v_mov_b32_e32 v1, 0 | ||
| 271 | v_mov_b32_e32 v2, 3 | ||
| 272 | v_mov_b32_e32 v3, 2 | ||
| 273 | v_mov_b32_e32 v10, 0x64 | ||
| 274 | image_atomic_dec v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc | ||
| 275 | s_waitcnt vmcnt(0) | ||
| 276 | v_mov_b32_e32 v6, 2 | ||
| 277 | v_mov_b32_e32 v7, 4 | ||
| 278 | image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 279 | v_mov_b32_e32 v1, 2 | ||
| 280 | v_mov_b32_e32 v2, 1 | ||
| 281 | v_mov_b32_e32 v3, 0 | ||
| 282 | v_mov_b32_e32 v12, 0x3fc00000 | ||
| 283 | image_atomic_swap v12, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm | ||
| 284 | v_mov_b32_e32 v10, 0xc0400000 | ||
| 285 | image_atomic_fmin v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc | ||
| 286 | s_waitcnt vmcnt(0) | ||
| 287 | v_mov_b32_e32 v6, 3 | ||
| 288 | v_mov_b32_e32 v7, 4 | ||
| 289 | image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 290 | v_mov_b32_e32 v1, 2 | ||
| 291 | v_mov_b32_e32 v2, 3 | ||
| 292 | v_mov_b32_e32 v3, 1 | ||
| 293 | v_mov_b32_e32 v12, 0x3fc00000 | ||
| 294 | image_atomic_swap v12, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm | ||
| 295 | v_mov_b32_e32 v10, 0x40200000 | ||
| 296 | image_atomic_fmax v10, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc | ||
| 297 | s_waitcnt vmcnt(0) | ||
| 298 | v_mov_b32_e32 v6, 4 | ||
| 299 | v_mov_b32_e32 v7, 4 | ||
| 300 | image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 301 | v_mov_b32_e32 v1, 3 | ||
| 302 | v_mov_b32_e32 v2, 1 | ||
| 303 | v_mov_b32_e32 v3, 2 | ||
| 304 | v_mov_b32_e32 v12, 0x3fc00000 | ||
| 305 | image_atomic_swap v12, v[1:3], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm | ||
| 306 | v_mov_b32_e32 v10, 0x40490fdb | ||
| 307 | v_mov_b32_e32 v11, 0x3fc00000 | ||
| 308 | image_atomic_fcmpswap v[10:11], v[1:3], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_3D unorm glc | ||
| 309 | s_waitcnt vmcnt(0) | ||
| 310 | v_mov_b32_e32 v6, 5 | ||
| 311 | v_mov_b32_e32 v7, 4 | ||
| 312 | image_store v10, v[6:7], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm | ||
| 313 | s_endpgm | ||
diff --git a/runtime/test/shaders/cs_imgload_d16_tfe.asm b/runtime/test/shaders/cs_imgload_d16_tfe.asm index 0739810d1..119653577 100644 --- a/runtime/test/shaders/cs_imgload_d16_tfe.asm +++ b/runtime/test/shaders/cs_imgload_d16_tfe.asm | |||
| @@ -1,8 +1,10 @@ | |||
| 1 | ; tfe status VGPR on a d16 image_load (SHADER-1266): cs_imgload_d16 with tfe on both loads. Under d16 one | 1 | ; tfe status VGPR on a d16 image_load (SHADER-1266): cs_imgload_d16 with tfe on both loads. Under d16 one |
| 2 | ; component fills one VGPR, and with tfe the fetch status follows it, so vdata is v[7:8] and v[11:12]. Every texel is | 2 | ; component fills one VGPR, and with tfe the fetch status follows it, so vdata is v[7:8] and v[11:12]. On a resident |
| 3 | ; resident, so the status is 0. Each status VGPR is seeded with 1000 and added into the result, so a stale status | 3 | ; texel, RDNA2 hardware leaves the status VGPR unchanged. The two status VGPRs are seeded with distinct values |
| 4 | ; moves every texel by 2000. The unpacking and the result are cs_imgload_d16's, checked by vk_store_test load-d16 | 4 | ; (v8 = 0x3e8, v12 = 0x7d0) and independently checked via (v8 ^ 0x3e8) | (v12 ^ 0x7d0) before adding into v11, so |
| 5 | ; (including its saturation row). Suggested by @nnonno91, who ran the same companion on gfx1036 and an RTX 5090 in #8968. | 5 | ; zeroing or modifying either status VGPR shifts every texel. The unpacking and the result are cs_imgload_d16's, |
| 6 | ; checked by vk_store_test load-d16 (including its saturation row). Suggested by @nnonno91, who ran the same | ||
| 7 | ; companion on gfx1036 and an RTX 5090 in #8968. | ||
| 6 | v_and_b32_e32 v1, 7, v0 | 8 | v_and_b32_e32 v1, 7, v0 |
| 7 | v_lshrrev_b32_e32 v2, 3, v0 | 9 | v_lshrrev_b32_e32 v2, 3, v0 |
| 8 | v_cvt_f32_u32_e32 v3, v1 | 10 | v_cvt_f32_u32_e32 v3, v1 |
| @@ -38,14 +40,16 @@ s_mov_b32 s28, 0x33 | |||
| 38 | s_mov_b32 s29, 0x33 | 40 | s_mov_b32 s29, 0x33 |
| 39 | s_mov_b32 s30, 0x33 | 41 | s_mov_b32 s30, 0x33 |
| 40 | s_mov_b32 s31, 0x33 | 42 | s_mov_b32 s31, 0x33 |
| 41 | v_mov_b32_e32 v12, 0x3e8 | 43 | v_mov_b32_e32 v12, 0x7d0 |
| 42 | image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe d16 | 44 | image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe d16 |
| 43 | s_waitcnt vmcnt(0) | 45 | s_waitcnt vmcnt(0) |
| 44 | v_and_b32_e32 v7, 0xffff, v7 | 46 | v_and_b32_e32 v7, 0xffff, v7 |
| 45 | v_bfe_i32 v11, v11, 0, 16 | 47 | v_bfe_i32 v11, v11, 0, 16 |
| 46 | v_add_nc_u32_e32 v11, v7, v11 | 48 | v_add_nc_u32_e32 v11, v7, v11 |
| 49 | v_xor_b32_e32 v8, 0x3e8, v8 | ||
| 50 | v_xor_b32_e32 v12, 0x7d0, v12 | ||
| 51 | v_or_b32_e32 v8, v8, v12 | ||
| 47 | v_add_nc_u32_e32 v11, v8, v11 | 52 | v_add_nc_u32_e32 v11, v8, v11 |
| 48 | v_add_nc_u32_e32 v11, v12, v11 | ||
| 49 | v_mov_b32_e32 v12, 0 | 53 | v_mov_b32_e32 v12, 0 |
| 50 | v_mov_b32_e32 v13, 0 | 54 | v_mov_b32_e32 v13, 0 |
| 51 | v_mov_b32_e32 v14, 0 | 55 | v_mov_b32_e32 v14, 0 |
diff --git a/runtime/test/shaders/cs_imgload_tfe.asm b/runtime/test/shaders/cs_imgload_tfe.asm index 63ad9dc71..6eb3e76f6 100644 --- a/runtime/test/shaders/cs_imgload_tfe.asm +++ b/runtime/test/shaders/cs_imgload_tfe.asm | |||
| @@ -1,9 +1,10 @@ | |||
| 1 | ; tfe status VGPR on image_load (SHADER-1266): cs_imgload with tfe on both loads. With tfe an MIMG read returns one | 1 | ; tfe status VGPR on image_load (SHADER-1266): cs_imgload with tfe on both loads. With tfe an MIMG read reserves one |
| 2 | ; more dword after its data, the fetch status, at vdata[data_count] (RDNA2 ISA, MIMG TFE/LWE). Every texel here is | 2 | ; more dword after its data, the fetch status, at vdata[data_count] (RDNA2 ISA, MIMG TFE/LWE). On a resident texel, |
| 3 | ; resident, so the status is 0. Each status VGPR is seeded with 1000 before its load and added into the result, so a | 3 | ; RDNA2 hardware leaves the status VGPR unchanged. The two status VGPRs are seeded with distinct values (v8 = 0x3e8, |
| 4 | ; status that keeps its old value moves every texel by 1000 or 2000. vk_store_test fills the r32 uint image with | 4 | ; v12 = 0x7d0) and independently checked via (v8 ^ 0x3e8) | (v12 ^ 0x7d0) before adding into v11, so zeroing or |
| 5 | ; 100 + 8y + x and the r32 sint image with -2 (8y + x) before the dispatch; the rgba8 image is stored as in | 5 | ; modifying either status VGPR shifts every texel. vk_store_test fills the r32 uint image with 100 + 8y + x and the |
| 6 | ; cs_imgstore. Run: vk_store_test cs_imgload_tfe.spv load -> sint = 100 - (8y + x), uint unchanged. | 6 | ; r32 sint image with -2 (8y + x) before the dispatch; the rgba8 image is stored as in cs_imgstore. |
| 7 | ; Run: vk_store_test cs_imgload_tfe.spv load -> sint = 100 - (8y + x), uint unchanged. | ||
| 7 | v_and_b32_e32 v1, 7, v0 | 8 | v_and_b32_e32 v1, 7, v0 |
| 8 | v_lshrrev_b32_e32 v2, 3, v0 | 9 | v_lshrrev_b32_e32 v2, 3, v0 |
| 9 | v_cvt_f32_u32_e32 v3, v1 | 10 | v_cvt_f32_u32_e32 v3, v1 |
| @@ -39,12 +40,14 @@ s_mov_b32 s28, 0x33 | |||
| 39 | s_mov_b32 s29, 0x33 | 40 | s_mov_b32 s29, 0x33 |
| 40 | s_mov_b32 s30, 0x33 | 41 | s_mov_b32 s30, 0x33 |
| 41 | s_mov_b32 s31, 0x33 | 42 | s_mov_b32 s31, 0x33 |
| 42 | v_mov_b32_e32 v12, 0x3e8 | 43 | v_mov_b32_e32 v12, 0x7d0 |
| 43 | image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe | 44 | image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe |
| 44 | s_waitcnt vmcnt(0) | 45 | s_waitcnt vmcnt(0) |
| 45 | v_add_nc_u32_e32 v11, v7, v11 | 46 | v_add_nc_u32_e32 v11, v7, v11 |
| 47 | v_xor_b32_e32 v8, 0x3e8, v8 | ||
| 48 | v_xor_b32_e32 v12, 0x7d0, v12 | ||
| 49 | v_or_b32_e32 v8, v8, v12 | ||
| 46 | v_add_nc_u32_e32 v11, v8, v11 | 50 | v_add_nc_u32_e32 v11, v8, v11 |
| 47 | v_add_nc_u32_e32 v11, v12, v11 | ||
| 48 | v_mov_b32_e32 v12, 0 | 51 | v_mov_b32_e32 v12, 0 |
| 49 | v_mov_b32_e32 v13, 0 | 52 | v_mov_b32_e32 v13, 0 |
| 50 | v_mov_b32_e32 v14, 0 | 53 | v_mov_b32_e32 v14, 0 |
diff --git a/runtime/test/shaders/cs_imgstore_cube.asm b/runtime/test/shaders/cs_imgstore_cube.asm new file mode 100644 index 000000000..9763e233f --- /dev/null +++ b/runtime/test/shaders/cs_imgstore_cube.asm | |||
| @@ -0,0 +1,95 @@ | |||
| 1 | ; Typed image_store on dim:SQ_RSRC_IMG_CUBE (GPU-CUBE-STORE): three T#s built in SGPRs (FORMAT 56 rgba8 unorm, 20 r32 | ||
| 2 | ; uint, 21 r32 sint; word3 TYPE = 0xB, SQ_RSRC_IMG_CUBE), 64 threads, thread t at (x, y) = (t & 7, t >> 3) of an 8x8 | ||
| 3 | ; face, each store to all six faces (v3 = face). The translator writes a cube through a six-layer 2D-array storage | ||
| 4 | ; view (bindings 11/12/13, the layer is the face), as the runtime binds a cube UAV (runtime/src/vulkan_bindless.h). | ||
| 5 | ; Run: vk_store_test cs_imgstore_cube.spv cube (checks every texel of all six layers of all three images): | ||
| 6 | ; rgba8 unorm: (x / 7, y / 7, face / 5, 1) | ||
| 7 | ; r32 uint: 100 + 1000 face + 8y + x | ||
| 8 | ; r32 sint: -(1000 face + 8y + x) | ||
| 9 | v_and_b32_e32 v1, 7, v0 | ||
| 10 | v_lshrrev_b32_e32 v2, 3, v0 | ||
| 11 | v_cvt_f32_u32_e32 v4, v1 | ||
| 12 | v_cvt_f32_u32_e32 v5, v2 | ||
| 13 | v_mul_f32_e32 v4, 0x3e124925, v4 | ||
| 14 | v_mul_f32_e32 v5, 0x3e124925, v5 | ||
| 15 | v_mov_b32_e32 v7, 1.0 | ||
| 16 | v_add_nc_u32_e32 v16, 100, v0 | ||
| 17 | v_mov_b32_e32 v9, 0 | ||
| 18 | v_mov_b32_e32 v10, 0 | ||
| 19 | v_mov_b32_e32 v11, 0 | ||
| 20 | v_mov_b32_e32 v13, 0 | ||
| 21 | v_mov_b32_e32 v14, 0 | ||
| 22 | v_mov_b32_e32 v15, 0 | ||
| 23 | s_mov_b32 s8, 0x1000 | ||
| 24 | s_mov_b32 s9, 0x3800000 | ||
| 25 | s_mov_b32 s10, 0x11 | ||
| 26 | s_mov_b32 s11, 0xb0000011 | ||
| 27 | s_mov_b32 s12, 0x11 | ||
| 28 | s_mov_b32 s13, 0x11 | ||
| 29 | s_mov_b32 s14, 0x11 | ||
| 30 | s_mov_b32 s15, 0x11 | ||
| 31 | s_mov_b32 s16, 0x2000 | ||
| 32 | s_mov_b32 s17, 0x1400000 | ||
| 33 | s_mov_b32 s18, 0x22 | ||
| 34 | s_mov_b32 s19, 0xb0000022 | ||
| 35 | s_mov_b32 s20, 0x22 | ||
| 36 | s_mov_b32 s21, 0x22 | ||
| 37 | s_mov_b32 s22, 0x22 | ||
| 38 | s_mov_b32 s23, 0x22 | ||
| 39 | s_mov_b32 s24, 0x3000 | ||
| 40 | s_mov_b32 s25, 0x1500000 | ||
| 41 | s_mov_b32 s26, 0x33 | ||
| 42 | s_mov_b32 s27, 0xb0000033 | ||
| 43 | s_mov_b32 s28, 0x33 | ||
| 44 | s_mov_b32 s29, 0x33 | ||
| 45 | s_mov_b32 s30, 0x33 | ||
| 46 | s_mov_b32 s31, 0x33 | ||
| 47 | v_mov_b32_e32 v3, 0 | ||
| 48 | v_cvt_f32_u32_e32 v6, v3 | ||
| 49 | v_mul_f32_e32 v6, 0x3e4ccccd, v6 | ||
| 50 | image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 51 | v_add_nc_u32_e32 v8, 0, v16 | ||
| 52 | image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 53 | v_sub_nc_u32_e32 v12, 0, v0 | ||
| 54 | image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 55 | v_mov_b32_e32 v3, 1 | ||
| 56 | v_cvt_f32_u32_e32 v6, v3 | ||
| 57 | v_mul_f32_e32 v6, 0x3e4ccccd, v6 | ||
| 58 | image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 59 | v_add_nc_u32_e32 v8, 1000, v16 | ||
| 60 | image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 61 | v_sub_nc_u32_e32 v12, -1000, v0 | ||
| 62 | image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 63 | v_mov_b32_e32 v3, 2 | ||
| 64 | v_cvt_f32_u32_e32 v6, v3 | ||
| 65 | v_mul_f32_e32 v6, 0x3e4ccccd, v6 | ||
| 66 | image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 67 | v_add_nc_u32_e32 v8, 2000, v16 | ||
| 68 | image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 69 | v_sub_nc_u32_e32 v12, -2000, v0 | ||
| 70 | image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 71 | v_mov_b32_e32 v3, 3 | ||
| 72 | v_cvt_f32_u32_e32 v6, v3 | ||
| 73 | v_mul_f32_e32 v6, 0x3e4ccccd, v6 | ||
| 74 | image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 75 | v_add_nc_u32_e32 v8, 3000, v16 | ||
| 76 | image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 77 | v_sub_nc_u32_e32 v12, -3000, v0 | ||
| 78 | image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 79 | v_mov_b32_e32 v3, 4 | ||
| 80 | v_cvt_f32_u32_e32 v6, v3 | ||
| 81 | v_mul_f32_e32 v6, 0x3e4ccccd, v6 | ||
| 82 | image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 83 | v_add_nc_u32_e32 v8, 4000, v16 | ||
| 84 | image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 85 | v_sub_nc_u32_e32 v12, -4000, v0 | ||
| 86 | image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 87 | v_mov_b32_e32 v3, 5 | ||
| 88 | v_cvt_f32_u32_e32 v6, v3 | ||
| 89 | v_mul_f32_e32 v6, 0x3e4ccccd, v6 | ||
| 90 | image_store v[4:7], v[1:3], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 91 | v_add_nc_u32_e32 v8, 5000, v16 | ||
| 92 | image_store v[8:11], v[1:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 93 | v_sub_nc_u32_e32 v12, -5000, v0 | ||
| 94 | image_store v[12:15], v[1:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm | ||
| 95 | s_endpgm | ||
diff --git a/runtime/test/shaders/cs_w32_lds_subdword.asm b/runtime/test/shaders/cs_w32_lds_subdword.asm index cb2f94243..10c5bd214 100644 --- a/runtime/test/shaders/cs_w32_lds_subdword.asm +++ b/runtime/test/shaders/cs_w32_lds_subdword.asm | |||
| @@ -12,23 +12,27 @@ | |||
| 12 | ; out[2] ds_read_i8 offset:2 -> 0xFFFFFFB2 out[3] ds_read_u8 offset:2 -> 0x000000B2 | 12 | ; out[2] ds_read_i8 offset:2 -> 0xFFFFFFB2 out[3] ds_read_u8 offset:2 -> 0x000000B2 |
| 13 | ; out[4] ds_read_i8 offset:3 -> 0x00000011 out[5] ds_read_i16 offset:6 -> 0xFFFFA1B2 | 13 | ; out[4] ds_read_i8 offset:3 -> 0x00000011 out[5] ds_read_i16 offset:6 -> 0xFFFFA1B2 |
| 14 | ; out[6] ds_read_u16 offset:6 -> 0x0000A1B2 out[7] ds_read_i16 offset:4 -> 0xFFFFC3D4 | 14 | ; out[6] ds_read_u16 offset:6 -> 0x0000A1B2 out[7] ds_read_i16 offset:4 -> 0xFFFFC3D4 |
| 15 | ; Every lane writes the same bytes, so the result does not depend on lane order. | 15 | ; Only lane zero accesses LDS and writes the results, avoiding concurrent writes to the same word. |
| 16 | ; Workgroup barriers separate the initial stores, narrow writes, and reads of the same words. | ||
| 16 | ; group: 32,1,1 | 17 | ; group: 32,1,1 |
| 17 | ; Run: vk_compute_test cs_w32_lds_subdword.spv 1 dump | 18 | ; Run: vk_compute_test cs_w32_lds_subdword.spv 1 dump |
| 18 | ; -> out[0..7] = 0x11B2D444 0xA1B2C3D4 0xFFFFFFB2 0x000000B2 0x00000011 0xFFFFA1B2 0x0000A1B2 0xFFFFC3D4 | 19 | ; -> out[0..7] = 0x11B2D444 0xA1B2C3D4 0xFFFFFFB2 0x000000B2 0x00000011 0xFFFFA1B2 0x0000A1B2 0xFFFFC3D4 |
| 19 | ; mattr: +wavefrontsize32,-wavefrontsize64 | 20 | ; mattr: +wavefrontsize32,-wavefrontsize64 |
| 21 | v_cmpx_eq_u32_e32 0, v0 | ||
| 20 | v_mov_b32_e32 v2, 0 | 22 | v_mov_b32_e32 v2, 0 |
| 21 | v_mov_b32_e32 v4, 0x11223344 | 23 | v_mov_b32_e32 v4, 0x11223344 |
| 22 | v_mov_b32_e32 v5, 0x55667788 | 24 | v_mov_b32_e32 v5, 0x55667788 |
| 23 | ds_write_b32 v2, v4 | 25 | ds_write_b32 v2, v4 |
| 24 | ds_write_b32 v2, v5 offset:4 | 26 | ds_write_b32 v2, v5 offset:4 |
| 25 | s_waitcnt lgkmcnt(0) | 27 | s_waitcnt lgkmcnt(0) |
| 28 | s_barrier | ||
| 26 | v_mov_b32_e32 v3, 0xa1b2c3d4 | 29 | v_mov_b32_e32 v3, 0xa1b2c3d4 |
| 27 | ds_write_b8 v2, v3 offset:1 | 30 | ds_write_b8 v2, v3 offset:1 |
| 28 | ds_write_b8_d16_hi v2, v3 offset:2 | 31 | ds_write_b8_d16_hi v2, v3 offset:2 |
| 29 | ds_write_b16 v2, v3 offset:4 | 32 | ds_write_b16 v2, v3 offset:4 |
| 30 | ds_write_b16_d16_hi v2, v3 offset:6 | 33 | ds_write_b16_d16_hi v2, v3 offset:6 |
| 31 | s_waitcnt lgkmcnt(0) | 34 | s_waitcnt lgkmcnt(0) |
| 35 | s_barrier | ||
| 32 | ds_read_b32 v10, v2 | 36 | ds_read_b32 v10, v2 |
| 33 | ds_read_b32 v11, v2 offset:4 | 37 | ds_read_b32 v11, v2 offset:4 |
| 34 | ds_read_i8 v12, v2 offset:2 | 38 | ds_read_i8 v12, v2 offset:2 |
| @@ -38,7 +42,6 @@ ds_read_i16 v15, v2 offset:6 | |||
| 38 | ds_read_u16 v16, v2 offset:6 | 42 | ds_read_u16 v16, v2 offset:6 |
| 39 | ds_read_i16 v17, v2 offset:4 | 43 | ds_read_i16 v17, v2 offset:4 |
| 40 | s_waitcnt lgkmcnt(0) | 44 | s_waitcnt lgkmcnt(0) |
| 41 | v_cmpx_eq_u32_e32 0, v0 | ||
| 42 | v_mov_b32_e32 v21, 0 | 45 | v_mov_b32_e32 v21, 0 |
| 43 | buffer_store_dword v10, v21, s[0:3], 0 offen | 46 | buffer_store_dword v10, v21, s[0:3], 0 offen |
| 44 | v_mov_b32_e32 v21, 4 | 47 | v_mov_b32_e32 v21, 4 |
diff --git a/runtime/test/shaders/cs_w32_shift64.asm b/runtime/test/shaders/cs_w32_shift64.asm new file mode 100644 index 000000000..97920b114 --- /dev/null +++ b/runtime/test/shaders/cs_w32_shift64.asm | |||
| @@ -0,0 +1,29 @@ | |||
| 1 | ; GPU-VALU64-SHIFTS: dynamic 64-bit shifts, including overlapping destinations. | ||
| 2 | ; group: 64,1,1 | ||
| 3 | ; mattr: +wavefrontsize32,-wavefrontsize64 | ||
| 4 | ; check.py seeds 64 records at byte 0x600: {value.lo, value.hi, count, padding}. | ||
| 5 | ; They are the Cartesian product of eight signed/unsigned boundary values and | ||
| 6 | ; counts 0, 1, 31, 32, 33, 63, 64, 65. Each thread reads one record from memory, | ||
| 7 | ; so neither the translator nor the driver can fold the shifts of literal inputs. | ||
| 8 | ; RDNA2 ISA VOP3 opcodes 767..769: count is S0[5:0]; logical shifts zero-fill, | ||
| 9 | ; arithmetic right shift sign-extends. Results are modulo 2^64, low word first. | ||
| 10 | ; Thread i writes six words at 24*i: left, logical right, arithmetic right. | ||
| 11 | ; Left overwrites its count register; logical right overlaps its source's high | ||
| 12 | ; word; arithmetic right overwrites both source words. All inputs must be read | ||
| 13 | ; before either destination word is written. The input records remain unchanged. | ||
| 14 | ; Run with the heap initialized by check.py's shift64_test; compare all 640 words. | ||
| 15 | v_lshlrev_b32_e32 v1, 4, v0 | ||
| 16 | v_mul_lo_u32 v10, v0, 24 | ||
| 17 | buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:1536 | ||
| 18 | s_waitcnt vmcnt(0) | ||
| 19 | v_lshlrev_b64 v[4:5], v4, v[2:3] | ||
| 20 | buffer_store_dwordx2 v[4:5], v10, s[0:3], 0 offen | ||
| 21 | buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:1536 | ||
| 22 | s_waitcnt vmcnt(0) | ||
| 23 | v_lshrrev_b64 v[3:4], v4, v[2:3] | ||
| 24 | buffer_store_dwordx2 v[3:4], v10, s[0:3], 0 offen offset:8 | ||
| 25 | buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:1536 | ||
| 26 | s_waitcnt vmcnt(0) | ||
| 27 | v_ashrrev_i64 v[2:3], v4, v[2:3] | ||
| 28 | buffer_store_dwordx2 v[2:3], v10, s[0:3], 0 offen offset:16 | ||
| 29 | s_endpgm | ||
diff --git a/runtime/test/shaders/mullit_readback.py b/runtime/test/shaders/mullit_readback.py deleted file mode 100644 index 007b516b1..000000000 --- a/runtime/test/shaders/mullit_readback.py +++ /dev/null | |||
| @@ -1,122 +0,0 @@ | |||
| 1 | """Check the ps_mullit semantic fixture with runtime SGPR inputs and RGBA32F readback. | ||
| 2 | |||
| 3 | python -I runtime/test/shaders/build.py <work> vs_ids ps_mullit | ||
| 4 | python -I runtime/test/shaders/mullit_readback.py <work> <harness directory> | ||
| 5 | """ | ||
| 6 | import argparse | ||
| 7 | import itertools | ||
| 8 | import os | ||
| 9 | from pathlib import Path | ||
| 10 | import random | ||
| 11 | import struct | ||
| 12 | import sys | ||
| 13 | import tempfile | ||
| 14 | |||
| 15 | sys.path.insert(0, str(Path(__file__).resolve().parent)) | ||
| 16 | from check import EXE, run | ||
| 17 | |||
| 18 | SIGN = 0x80000000 | ||
| 19 | INF = 0x7f800000 | ||
| 20 | MIN_NORMAL = 0x00800000 | ||
| 21 | ONE = 0x3f800000 | ||
| 22 | LIGHT_OFF = 0xff7fffff | ||
| 23 | PAYLOAD_MASK = 0x40000000 | ||
| 24 | |||
| 25 | |||
| 26 | def lighting_product(x, y, gate): | ||
| 27 | """Return the expected f32 word using integer significands throughout.""" | ||
| 28 | ax, ay = x & ~SIGN, y & ~SIGN | ||
| 29 | if not MIN_NORMAL <= gate <= INF or y in (LIGHT_OFF, SIGN | INF) or ay > INF: | ||
| 30 | return LIGHT_OFF | ||
| 31 | if min(ax, ay) < MIN_NORMAL: | ||
| 32 | return 0 | ||
| 33 | if ax > INF: | ||
| 34 | return x | ||
| 35 | sign = (x ^ y) & SIGN | ||
| 36 | if INF in (ax, ay): | ||
| 37 | return sign | INF | ||
| 38 | |||
| 39 | product = (MIN_NORMAL + ax % MIN_NORMAL) * (MIN_NORMAL + ay % MIN_NORMAL) | ||
| 40 | shift = product.bit_length() - 24 | ||
| 41 | unit = 1 << shift | ||
| 42 | mantissa, remainder = divmod(product, unit) | ||
| 43 | if 2 * remainder > unit or (2 * remainder == unit and mantissa % 2): | ||
| 44 | mantissa += 1 | ||
| 45 | exponent = (ax >> 23) + (ay >> 23) - 127 + shift - 23 | ||
| 46 | if mantissa == 2 * MIN_NORMAL: | ||
| 47 | mantissa //= 2 | ||
| 48 | exponent += 1 | ||
| 49 | # Round before flushing. A product just below MIN_NORMAL can carry into it. | ||
| 50 | if exponent <= 0: | ||
| 51 | return sign | ||
| 52 | if exponent >= 255: | ||
| 53 | return sign | INF | ||
| 54 | return sign | (exponent << 23) | (mantissa - MIN_NORMAL) | ||
| 55 | |||
| 56 | |||
| 57 | def operand_triples(): | ||
| 58 | gates = (ONE, INF, MIN_NORMAL, 1, MIN_NORMAL - 1, 0, SIGN, SIGN | ONE, 0x7fc23456, 0xffa54321) | ||
| 59 | yield from ((0x40400000, 0xc0200000, gate) for gate in gates) | ||
| 60 | yield from itertools.product( | ||
| 61 | (0, SIGN, 1, SIGN | (MIN_NORMAL - 1), 0x7fa12345, 0xffc12345, INF), | ||
| 62 | (0, SIGN | 1, LIGHT_OFF, INF, SIGN | INF, 0x7fc09876, ONE), (ONE,)) | ||
| 63 | yield from itertools.product( | ||
| 64 | (ONE - 4, ONE - 3, ONE - 2, ONE - 1, ONE, SIGN | ONE, 0xbf7ffffe, 0xbf7fffff), | ||
| 65 | (MIN_NORMAL, MIN_NORMAL + 1, MIN_NORMAL + 2), (ONE,)) | ||
| 66 | for x, y in ((INF - 1, 0x40000000), (LIGHT_OFF, 0x40000000), (INF - 1, MIN_NORMAL), | ||
| 67 | (MIN_NORMAL, 0x3f000000), (SIGN | MIN_NORMAL, 0x3f000000), | ||
| 68 | (INF, SIGN | ONE), (ONE, LIGHT_OFF - 1)): | ||
| 69 | yield x, y, ONE | ||
| 70 | # Halfway products round up to 0x3fc00002 and down to 0x3fc00004. | ||
| 71 | yield 0x3fc00000, ONE + 1, ONE | ||
| 72 | yield 0x3fc00000, ONE + 3, ONE | ||
| 73 | rng = random.Random(578) | ||
| 74 | for _ in range(28): | ||
| 75 | x = rng.randrange(MIN_NORMAL, INF) | rng.choice((0, SIGN)) | ||
| 76 | y = rng.randrange(MIN_NORMAL, INF) | rng.choice((0, SIGN)) | ||
| 77 | yield x, y, ONE | ||
| 78 | |||
| 79 | |||
| 80 | def mismatch(data, x, y, gate): | ||
| 81 | result = lighting_product(x, y, gate) | ||
| 82 | modified = lighting_product(x ^ SIGN, y & ~SIGN, gate) | ||
| 83 | expected = (result, modified, LIGHT_OFF, result ^ PAYLOAD_MASK) | ||
| 84 | if len(data) != 4 * 4 * 16: | ||
| 85 | return f"expected 256 bytes, got {len(data)}" | ||
| 86 | for i, pixel in enumerate(struct.iter_unpack("<4I", data)): | ||
| 87 | for channel, want, got in zip("RGBA", expected, pixel): | ||
| 88 | # A float attachment can change a NaN payload. Alpha exposes the raw | ||
| 89 | # R payload as a finite word in exactly those cases. | ||
| 90 | if want & ~SIGN > INF and got & ~SIGN > INF: | ||
| 91 | continue | ||
| 92 | if got != want: | ||
| 93 | return f"pixel {i} {channel}: got {got:#010x}, expected {want:#010x}" | ||
| 94 | return None | ||
| 95 | |||
| 96 | |||
| 97 | def main(): | ||
| 98 | parser = argparse.ArgumentParser(description=__doc__) | ||
| 99 | parser.add_argument("work", type=Path) | ||
| 100 | parser.add_argument("build", type=Path) | ||
| 101 | args = parser.parse_args() | ||
| 102 | spirv = args.work / "spirv" | ||
| 103 | cases = dict.fromkeys(operand_triples()) | ||
| 104 | with tempfile.TemporaryDirectory() as tmp: | ||
| 105 | raw = Path(tmp) / "pixels.raw" | ||
| 106 | for inputs in cases: | ||
| 107 | raw.unlink(missing_ok=True) | ||
| 108 | words = ",".join(map(hex, inputs)) | ||
| 109 | code, output = run(args.build / ("vk_harness" + EXE), spirv / "vs_ids.spv", | ||
| 110 | spirv / "ps_mullit.spv", raw, "4", "4", env=dict(os.environ, VKH_SGPRS=words)) | ||
| 111 | if code: | ||
| 112 | print(f"{words}: vk_harness exited {code}\n{output}", file=sys.stderr) | ||
| 113 | return code | ||
| 114 | problem = mismatch(raw.read_bytes(), *inputs) if raw.is_file() else "missing readback" | ||
| 115 | if problem: | ||
| 116 | sys.exit(f"{words}: {problem}") | ||
| 117 | print(f"{len(cases)} operand triples, {16 * len(cases)} pixels matched") | ||
| 118 | return 0 | ||
| 119 | |||
| 120 | |||
| 121 | if __name__ == "__main__": | ||
| 122 | sys.exit(main()) | ||
diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp index 9769e70be..c31c23b60 100644 --- a/runtime/test/vk_command_replay_test.cpp +++ b/runtime/test/vk_command_replay_test.cpp | |||
| @@ -1265,6 +1265,81 @@ int part_j(vktest::Device& d) { | |||
| 1265 | return 0; | 1265 | return 0; |
| 1266 | } | 1266 | } |
| 1267 | 1267 | ||
| 1268 | // Part K (D3D-838): an enhanced barrier with SYNC_COPY orders a WriteBufferImmediate before it. The write is recorded | ||
| 1269 | // as vkCmdUpdateBuffer, which synchronization2 runs in the CLEAR stage, not COPY, and a DEFAULT-mode write gets no | ||
| 1270 | // barrier of its own (replay leaves it to the application's). So: the write puts a word in src, a SYNC_COPY -> | ||
| 1271 | // SYNC_COPY buffer barrier (COPY_DEST -> COPY_SOURCE) follows, and CopyBufferRegion copies the word to dst. Under | ||
| 1272 | // LEONIDA_VK_VALIDATION=1 synchronization validation reports the read-after-write hazard when the barrier's source | ||
| 1273 | // stages leave CLEAR out; in every run the copied word is checked. | ||
| 1274 | int part_k(vktest::Device& d) { | ||
| 1275 | constexpr VkDeviceSize bytes = 256; | ||
| 1276 | constexpr std::uint64_t va_src = 0x50000; | ||
| 1277 | constexpr std::uint32_t value = 0x5eed1234; | ||
| 1278 | constexpr VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; | ||
| 1279 | void *src_mapped = nullptr, *dst_mapped = nullptr; | ||
| 1280 | const VkBuffer src = d.buffer(bytes, usage, &src_mapped); | ||
| 1281 | const VkBuffer dst = d.buffer(bytes, usage, &dst_mapped); | ||
| 1282 | EXPECT(src && dst && src_mapped && dst_mapped); | ||
| 1283 | std::memset(src_mapped, 0, bytes); | ||
| 1284 | std::memset(dst_mapped, 0, bytes); | ||
| 1285 | |||
| 1286 | constexpr ResourceId src_id = 50, dst_id = 51; | ||
| 1287 | ResourceBinding src_binding{}, dst_binding{}; | ||
| 1288 | src_binding.buffer = src; | ||
| 1289 | src_binding.size = bytes; | ||
| 1290 | src_binding.va = va_src; | ||
| 1291 | dst_binding.buffer = dst; | ||
| 1292 | dst_binding.size = bytes; | ||
| 1293 | const auto resolve = [&](ResourceId id) -> const ResourceBinding* { | ||
| 1294 | if (id == src_id) return &src_binding; | ||
| 1295 | if (id == dst_id) return &dst_binding; | ||
| 1296 | return nullptr; | ||
| 1297 | }; | ||
| 1298 | ReplayFunctions vk{}; | ||
| 1299 | vk.pipeline_barrier = d.fn<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier"); | ||
| 1300 | vk.pipeline_barrier2 = d.fn<PFN_vkCmdPipelineBarrier2>("vkCmdPipelineBarrier2"); | ||
| 1301 | vk.copy_buffer = d.fn<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer"); // replay wants all four copy functions | ||
| 1302 | vk.copy_buffer_to_image = d.fn<PFN_vkCmdCopyBufferToImage>("vkCmdCopyBufferToImage"); | ||
| 1303 | vk.copy_image_to_buffer = d.fn<PFN_vkCmdCopyImageToBuffer>("vkCmdCopyImageToBuffer"); | ||
| 1304 | vk.copy_image = d.fn<PFN_vkCmdCopyImage>("vkCmdCopyImage"); | ||
| 1305 | vk.update_buffer = d.fn<PFN_vkCmdUpdateBuffer>("vkCmdUpdateBuffer"); | ||
| 1306 | vk.buffer_at = [&](std::uint64_t va, std::uint64_t length, VkBuffer& buffer, VkDeviceSize& offset) { | ||
| 1307 | if (va < va_src || va - va_src >= bytes || length > bytes - (va - va_src)) return false; | ||
| 1308 | buffer = src; | ||
| 1309 | offset = va - va_src; | ||
| 1310 | return true; | ||
| 1311 | }; | ||
| 1312 | |||
| 1313 | namespace ac = d3d12_access; | ||
| 1314 | namespace y = d3d12_sync; | ||
| 1315 | CommandList list; | ||
| 1316 | EXPECT(list.write_immediate({va_src + 8, value, write_immediate_mode::normal})); | ||
| 1317 | EXPECT(list.barrier(BufferBarrier{y::copy, y::copy, ac::copy_dest, ac::copy_source, src_id})); | ||
| 1318 | EXPECT(list.copy_buffer({dst_id, 16, src_id, 8, 4})); | ||
| 1319 | EXPECT(list.close()); | ||
| 1320 | |||
| 1321 | const unsigned errors_before = d.validation_errors(); | ||
| 1322 | ReplayResult result = ReplayResult::success; | ||
| 1323 | EXPECT(d.run([&](VkCommandBuffer cb) { | ||
| 1324 | result = replay(list, cb, resolve, vk); | ||
| 1325 | if (result != ReplayResult::success) std::fprintf(stderr, "K: replay returned %d\n", int(result)); | ||
| 1326 | return result == ReplayResult::success; | ||
| 1327 | })); | ||
| 1328 | const unsigned errors = d.validation_errors() - errors_before; | ||
| 1329 | std::uint32_t copied = 0; | ||
| 1330 | std::memcpy(&copied, static_cast<const std::uint8_t*>(dst_mapped) + 16, 4); | ||
| 1331 | if (copied != value) { | ||
| 1332 | std::fprintf(stderr, "K: copied 0x%08x, want 0x%08x\n", copied, value); | ||
| 1333 | ++g_mismatches; | ||
| 1334 | } | ||
| 1335 | if (errors) { | ||
| 1336 | std::fprintf(stderr, "K: %u validation errors: a SYNC_COPY barrier does not cover vkCmdUpdateBuffer\n", errors); | ||
| 1337 | return 1; | ||
| 1338 | } | ||
| 1339 | std::printf("K: SYNC_COPY orders WriteBufferImmediate (vkCmdUpdateBuffer, CLEAR stage) before a copy\n"); | ||
| 1340 | return 0; | ||
| 1341 | } | ||
| 1342 | |||
| 1268 | } // namespace | 1343 | } // namespace |
| 1269 | 1344 | ||
| 1270 | int main() { | 1345 | int main() { |
| @@ -1276,7 +1351,7 @@ int main() { | |||
| 1276 | } | 1351 | } |
| 1277 | EXPECT(status == vktest::DeviceStatus::ready); | 1352 | EXPECT(status == vktest::DeviceStatus::ready); |
| 1278 | if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) || | 1353 | if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) || |
| 1279 | part_g(device) || part_h(device) || part_i(device) || part_j(device)) | 1354 | part_g(device) || part_h(device) || part_i(device) || part_j(device) || part_k(device)) |
| 1280 | return 1; | 1355 | return 1; |
| 1281 | if (g_mismatches) return 1; | 1356 | if (g_mismatches) return 1; |
| 1282 | if (device.validation_errors()) { | 1357 | if (device.validation_errors()) { |
diff --git a/runtime/test/vk_compute_test.cpp b/runtime/test/vk_compute_test.cpp index 5ac0bb1bb..8cc6a2a2f 100644 --- a/runtime/test/vk_compute_test.cpp +++ b/runtime/test/vk_compute_test.cpp | |||
| @@ -152,7 +152,8 @@ static int run(int argc, char** argv) { | |||
| 152 | } | 152 | } |
| 153 | // VKC_HEAP_FILE=<path>[@<offset>]: copy a file into the heap so a shader can read a buffer (a BVH, its | 153 | // VKC_HEAP_FILE=<path>[@<offset>]: copy a file into the heap so a shader can read a buffer (a BVH, its |
| 154 | // descriptor blocks and the records) without the test hard-coding it. The offset is a decimal or 0x hex byte | 154 | // descriptor blocks and the records) without the test hard-coding it. The offset is a decimal or 0x hex byte |
| 155 | // offset (no octal, sign or spaces); addresses the shader sees are Xbox VAs, i.e. heap offsets, as for every | 155 | // offset (no octal, sign or spaces) below 2^32, and the whole file must fit below 2^32 too (the heap is the |
| 156 | // 32-bit GPU window); addresses the shader sees are Xbox VAs, i.e. heap offsets, as for every | ||
| 156 | // other heap buffer here. Two overlaps to keep in mind: "bvh" mode writes its synthetic scene after this copy, | 157 | // other heap buffer here. Two overlaps to keep in mind: "bvh" mode writes its synthetic scene after this copy, |
| 157 | // so a file at 0x100..0x264 is overwritten there, and the output V# starts at heap offset 0, so a file at @0 | 158 | // so a file at 0x100..0x264 is overwritten there, and the output V# starts at heap offset 0, so a file at @0 |
| 158 | // shares bytes with the dispatch's output. | 159 | // shares bytes with the dispatch's output. |
| @@ -175,15 +176,30 @@ static int run(int argc, char** argv) { | |||
| 175 | } | 176 | } |
| 176 | char* end = nullptr; | 177 | char* end = nullptr; |
| 177 | const unsigned long long parsed = std::strtoull(body, &end, hex ? 16 : 10); | 178 | const unsigned long long parsed = std::strtoull(body, &end, hex ? 16 : 10); |
| 178 | if (end == body || *end || parsed > (1ull << 32) || heap_file_path.empty()) { | 179 | // The heap is the 32-bit Xbox GPU window: an offset of 2^32 is one past it (RT-439). |
| 180 | if (end == body || *end || parsed >= (1ull << 32) || heap_file_path.empty()) { | ||
| 179 | std::fprintf(stderr, "VKC_HEAP_FILE: expected <path>[@<offset>], got \"%s\"\n", heap_file_env); | 181 | std::fprintf(stderr, "VKC_HEAP_FILE: expected <path>[@<offset>], got \"%s\"\n", heap_file_env); |
| 180 | return 2; | 182 | return 2; |
| 181 | } | 183 | } |
| 182 | heap_file_at = parsed; | 184 | heap_file_at = parsed; |
| 183 | } | 185 | } |
| 184 | std::ifstream hf(heap_file_path, std::ios::binary); | 186 | // The size is checked on the open file before anything is read, so a file that can't fit is refused |
| 185 | heap_file.assign(std::istreambuf_iterator<char>(hf), {}); | 187 | // without reading it into memory (@shdann on #5878). |
| 186 | if (heap_file.empty()) { | 188 | std::ifstream hf(heap_file_path, std::ios::binary | std::ios::ate); |
| 189 | const std::streamoff length = hf ? static_cast<std::streamoff>(hf.tellg()) : std::streamoff(-1); | ||
| 190 | if (length <= 0) { | ||
| 191 | std::fprintf(stderr, "VKC_HEAP_FILE: cannot read %s\n", heap_file_path.c_str()); | ||
| 192 | return 2; | ||
| 193 | } | ||
| 194 | if (static_cast<unsigned long long>(length) > (1ull << 32) - heap_file_at) { // the last byte too must fit | ||
| 195 | std::fprintf(stderr, "VKC_HEAP_FILE: %s (%lld bytes) at 0x%llx runs past the 4 GiB heap\n", | ||
| 196 | heap_file_path.c_str(), static_cast<long long>(length), | ||
| 197 | static_cast<unsigned long long>(heap_file_at)); | ||
| 198 | return 2; | ||
| 199 | } | ||
| 200 | heap_file.resize(static_cast<std::size_t>(length)); | ||
| 201 | hf.seekg(0); | ||
| 202 | if (!hf.read(heap_file.data(), length)) { | ||
| 187 | std::fprintf(stderr, "VKC_HEAP_FILE: cannot read %s\n", heap_file_path.c_str()); | 203 | std::fprintf(stderr, "VKC_HEAP_FILE: cannot read %s\n", heap_file_path.c_str()); |
| 188 | return 2; | 204 | return 2; |
| 189 | } | 205 | } |
diff --git a/runtime/test/vk_host_at_aliasing_test.cpp b/runtime/test/vk_host_at_aliasing_test.cpp new file mode 100644 index 000000000..06ce1946d --- /dev/null +++ b/runtime/test/vk_host_at_aliasing_test.cpp | |||
| @@ -0,0 +1,257 @@ | |||
| 1 | // VulkanContext::replay_.host_at resolution across aliasing placed buffers (via KHR TLAS array-of-pointers staging). | ||
| 2 | // Public runtime classes with fake Vulkan procedures: no loader, GPU, or game data. | ||
| 3 | #include "../src/vulkan_backend.h" | ||
| 4 | |||
| 5 | #include <array> | ||
| 6 | #include <cstdint> | ||
| 7 | #include <cstdio> | ||
| 8 | #include <cstring> | ||
| 9 | #include <type_traits> | ||
| 10 | #include <vector> | ||
| 11 | |||
| 12 | namespace { | ||
| 13 | |||
| 14 | int failures = 0; | ||
| 15 | int live_buffers = 0; | ||
| 16 | int live_memories = 0; | ||
| 17 | int mapped_count = 0; | ||
| 18 | int as_builds = 0; | ||
| 19 | bool build_saw_array_of_pointers = false; | ||
| 20 | VkDeviceAddress build_instances_address = 0; | ||
| 21 | std::array<std::uint8_t, 256> stage_bytes{}; | ||
| 22 | std::vector<std::uint64_t> staged_addresses; | ||
| 23 | |||
| 24 | void expect(bool ok, const char* what) { | ||
| 25 | if (!ok) { | ||
| 26 | std::fprintf(stderr, "FAIL: %s\n", what); | ||
| 27 | ++failures; | ||
| 28 | } | ||
| 29 | } | ||
| 30 | |||
| 31 | template<typename Handle> | ||
| 32 | Handle handle(std::uintptr_t value) { | ||
| 33 | if constexpr (std::is_pointer_v<Handle>) | ||
| 34 | return reinterpret_cast<Handle>(value); | ||
| 35 | else | ||
| 36 | return static_cast<Handle>(value); | ||
| 37 | } | ||
| 38 | |||
| 39 | constexpr VkDeviceAddress kStageDeviceAddress = 0xfeed0000ull; | ||
| 40 | |||
| 41 | VKAPI_ATTR VkResult VKAPI_CALL mock_create_pool(VkDevice, const VkCommandPoolCreateInfo*, | ||
| 42 | const VkAllocationCallbacks*, VkCommandPool* out) { | ||
| 43 | *out = handle<VkCommandPool>(1); | ||
| 44 | return VK_SUCCESS; | ||
| 45 | } | ||
| 46 | VKAPI_ATTR void VKAPI_CALL mock_destroy_pool(VkDevice, VkCommandPool, const VkAllocationCallbacks*) {} | ||
| 47 | VKAPI_ATTR VkResult VKAPI_CALL mock_create_semaphore(VkDevice, const VkSemaphoreCreateInfo*, | ||
| 48 | const VkAllocationCallbacks*, VkSemaphore* out) { | ||
| 49 | *out = handle<VkSemaphore>(1); | ||
| 50 | return VK_SUCCESS; | ||
| 51 | } | ||
| 52 | VKAPI_ATTR void VKAPI_CALL mock_destroy_semaphore(VkDevice, VkSemaphore, const VkAllocationCallbacks*) {} | ||
| 53 | VKAPI_ATTR VkResult VKAPI_CALL mock_semaphore_counter(VkDevice, VkSemaphore, std::uint64_t* out) { | ||
| 54 | *out = UINT64_MAX; | ||
| 55 | return VK_SUCCESS; | ||
| 56 | } | ||
| 57 | VKAPI_ATTR VkResult VKAPI_CALL mock_queue_wait_idle(VkQueue) { return VK_SUCCESS; } | ||
| 58 | VKAPI_ATTR VkResult VKAPI_CALL mock_allocate_commands(VkDevice, const VkCommandBufferAllocateInfo*, | ||
| 59 | VkCommandBuffer* out) { | ||
| 60 | *out = handle<VkCommandBuffer>(1); | ||
| 61 | return VK_SUCCESS; | ||
| 62 | } | ||
| 63 | VKAPI_ATTR VkResult VKAPI_CALL mock_reset_command(VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; } | ||
| 64 | VKAPI_ATTR VkResult VKAPI_CALL mock_begin_command(VkCommandBuffer, const VkCommandBufferBeginInfo*) { return VK_SUCCESS; } | ||
| 65 | VKAPI_ATTR VkResult VKAPI_CALL mock_end_command(VkCommandBuffer) { return VK_SUCCESS; } | ||
| 66 | VKAPI_ATTR VkResult VKAPI_CALL mock_queue_submit(VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) { | ||
| 67 | return VK_SUCCESS; | ||
| 68 | } | ||
| 69 | VKAPI_ATTR void VKAPI_CALL mock_cmd_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, | ||
| 70 | VkDependencyFlags, std::uint32_t, const VkMemoryBarrier*, std::uint32_t, | ||
| 71 | const VkBufferMemoryBarrier*, std::uint32_t, | ||
| 72 | const VkImageMemoryBarrier*) {} | ||
| 73 | VKAPI_ATTR VkResult VKAPI_CALL mock_create_buffer(VkDevice, const VkBufferCreateInfo*, const VkAllocationCallbacks*, | ||
| 74 | VkBuffer* out) { | ||
| 75 | ++live_buffers; | ||
| 76 | *out = handle<VkBuffer>(0x100 + live_buffers); | ||
| 77 | return VK_SUCCESS; | ||
| 78 | } | ||
| 79 | VKAPI_ATTR void VKAPI_CALL mock_destroy_buffer(VkDevice, VkBuffer, const VkAllocationCallbacks*) { --live_buffers; } | ||
| 80 | VKAPI_ATTR void VKAPI_CALL mock_buffer_memory_reqs(VkDevice, VkBuffer, VkMemoryRequirements* reqs) { | ||
| 81 | reqs->size = stage_bytes.size(); | ||
| 82 | reqs->alignment = 16; | ||
| 83 | reqs->memoryTypeBits = 1u; | ||
| 84 | } | ||
| 85 | VKAPI_ATTR VkResult VKAPI_CALL mock_allocate_memory(VkDevice, const VkMemoryAllocateInfo*, const VkAllocationCallbacks*, | ||
| 86 | VkDeviceMemory* out) { | ||
| 87 | ++live_memories; | ||
| 88 | *out = handle<VkDeviceMemory>(0x200 + live_memories); | ||
| 89 | return VK_SUCCESS; | ||
| 90 | } | ||
| 91 | VKAPI_ATTR void VKAPI_CALL mock_free_memory(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) { --live_memories; } | ||
| 92 | VKAPI_ATTR VkResult VKAPI_CALL mock_bind_buffer_memory(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize) { | ||
| 93 | return VK_SUCCESS; | ||
| 94 | } | ||
| 95 | VKAPI_ATTR VkResult VKAPI_CALL mock_map_memory(VkDevice, VkDeviceMemory, VkDeviceSize offset, VkDeviceSize, | ||
| 96 | VkMemoryMapFlags, void** data) { | ||
| 97 | ++mapped_count; | ||
| 98 | *data = stage_bytes.data() + offset; | ||
| 99 | return VK_SUCCESS; | ||
| 100 | } | ||
| 101 | VKAPI_ATTR void VKAPI_CALL mock_unmap_memory(VkDevice, VkDeviceMemory) { --mapped_count; } | ||
| 102 | VKAPI_ATTR VkDeviceAddress VKAPI_CALL mock_buffer_device_address(VkDevice, const VkBufferDeviceAddressInfo*) { | ||
| 103 | return kStageDeviceAddress; | ||
| 104 | } | ||
| 105 | VKAPI_ATTR void VKAPI_CALL mock_build_as(VkCommandBuffer, std::uint32_t info_count, | ||
| 106 | const VkAccelerationStructureBuildGeometryInfoKHR* infos, | ||
| 107 | const VkAccelerationStructureBuildRangeInfoKHR* const* ranges) { | ||
| 108 | ++as_builds; | ||
| 109 | if (info_count && infos && infos[0].geometryCount && infos[0].pGeometries && | ||
| 110 | infos[0].pGeometries[0].geometryType == VK_GEOMETRY_TYPE_INSTANCES_KHR) { | ||
| 111 | const auto& inst = infos[0].pGeometries[0].geometry.instances; | ||
| 112 | build_saw_array_of_pointers = inst.arrayOfPointers == VK_TRUE; | ||
| 113 | build_instances_address = inst.data.deviceAddress; | ||
| 114 | const std::uint32_t n = ranges && ranges[0] ? ranges[0][0].primitiveCount : 0; | ||
| 115 | staged_addresses.resize(n); | ||
| 116 | for (std::uint32_t i = 0; i < n; ++i) | ||
| 117 | std::memcpy(&staged_addresses[i], stage_bytes.data() + 8ull * i, sizeof(std::uint64_t)); | ||
| 118 | } | ||
| 119 | } | ||
| 120 | |||
| 121 | VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_proc(VkDevice, const char* name) { | ||
| 122 | #define PROC(vk_name, impl) \ | ||
| 123 | if (std::strcmp(name, #vk_name) == 0) return reinterpret_cast<PFN_vkVoidFunction>(impl) | ||
| 124 | PROC(vkCreateCommandPool, mock_create_pool); | ||
| 125 | PROC(vkDestroyCommandPool, mock_destroy_pool); | ||
| 126 | PROC(vkCreateSemaphore, mock_create_semaphore); | ||
| 127 | PROC(vkDestroySemaphore, mock_destroy_semaphore); | ||
| 128 | PROC(vkGetSemaphoreCounterValue, mock_semaphore_counter); | ||
| 129 | PROC(vkQueueWaitIdle, mock_queue_wait_idle); | ||
| 130 | PROC(vkAllocateCommandBuffers, mock_allocate_commands); | ||
| 131 | PROC(vkResetCommandBuffer, mock_reset_command); | ||
| 132 | PROC(vkBeginCommandBuffer, mock_begin_command); | ||
| 133 | PROC(vkEndCommandBuffer, mock_end_command); | ||
| 134 | PROC(vkQueueSubmit, mock_queue_submit); | ||
| 135 | PROC(vkCmdPipelineBarrier, mock_cmd_barrier); | ||
| 136 | PROC(vkCreateBuffer, mock_create_buffer); | ||
| 137 | PROC(vkDestroyBuffer, mock_destroy_buffer); | ||
| 138 | PROC(vkGetBufferMemoryRequirements, mock_buffer_memory_reqs); | ||
| 139 | PROC(vkAllocateMemory, mock_allocate_memory); | ||
| 140 | PROC(vkFreeMemory, mock_free_memory); | ||
| 141 | PROC(vkBindBufferMemory, mock_bind_buffer_memory); | ||
| 142 | PROC(vkMapMemory, mock_map_memory); | ||
| 143 | PROC(vkUnmapMemory, mock_unmap_memory); | ||
| 144 | PROC(vkGetBufferDeviceAddress, mock_buffer_device_address); | ||
| 145 | PROC(vkCmdBuildAccelerationStructuresKHR, mock_build_as); | ||
| 146 | #undef PROC | ||
| 147 | return nullptr; | ||
| 148 | } | ||
| 149 | |||
| 150 | leonida::ResourceBinding make_buffer(std::uintptr_t id, std::uint64_t va, std::uint64_t size, | ||
| 151 | const std::uint8_t* host) { | ||
| 152 | leonida::ResourceBinding b{}; | ||
| 153 | b.buffer = handle<VkBuffer>(id); | ||
| 154 | b.va = va; | ||
| 155 | b.size = size; | ||
| 156 | b.host = host; | ||
| 157 | return b; | ||
| 158 | } | ||
| 159 | |||
| 160 | leonida::ReplayResult run_tlas_pointers(leonida::VulkanContext& ctx, std::uint64_t dst_va, std::uint64_t pointers_va, | ||
| 161 | std::uint32_t instance_count) { | ||
| 162 | leonida::BuildAccelerationStructure b{}; | ||
| 163 | b.is_tlas = true; | ||
| 164 | b.dst_va = dst_va; | ||
| 165 | b.scratch_va = 0x20000; | ||
| 166 | b.instances_va = pointers_va; | ||
| 167 | b.instance_count = instance_count; | ||
| 168 | b.instance_pointers = true; | ||
| 169 | |||
| 170 | leonida::CommandList list; | ||
| 171 | expect(list.build_acceleration_structure(std::move(b)) && list.close(), "invalid TLAS test command list"); | ||
| 172 | leonida::VulkanQueue queue(ctx, handle<VkQueue>(1), 0); | ||
| 173 | expect(queue.ok(), "mock VulkanQueue did not initialize"); | ||
| 174 | const leonida::CommandList* lists[] = {&list}; | ||
| 175 | return queue.execute(lists); | ||
| 176 | } | ||
| 177 | |||
| 178 | } // namespace | ||
| 179 | |||
| 180 | int main() { | ||
| 181 | constexpr std::uint64_t kHeapBase = 0x1000000ull; | ||
| 182 | constexpr std::uint64_t kDstVa = 0x10000ull; | ||
| 183 | constexpr std::uint64_t kInstVa = 0x4000ull; | ||
| 184 | constexpr std::uint64_t kPtrVa = 0x8000ull; | ||
| 185 | constexpr std::uint64_t kGpuVa = 0xc000ull; | ||
| 186 | constexpr std::uint64_t kBaseVa = 0xe000ull; | ||
| 187 | |||
| 188 | { | ||
| 189 | leonida::VulkanContext ctx(mock_proc, handle<VkDevice>(1), false, false, true, false); | ||
| 190 | VkPhysicalDeviceMemoryProperties mem{}; | ||
| 191 | mem.memoryHeapCount = 1; | ||
| 192 | mem.memoryHeaps[0].size = 1024 * 1024; | ||
| 193 | mem.memoryTypes[0].propertyFlags = | ||
| 194 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; | ||
| 195 | mem.memoryTypes[0].heapIndex = 0; | ||
| 196 | mem.memoryTypeCount = 1; | ||
| 197 | ctx.set_occlusion_resolve_memory(mem); | ||
| 198 | ctx.set_heap_base(kHeapBase); | ||
| 199 | ctx.register_acceleration_structure(kDstVa, handle<VkAccelerationStructureKHR>(0x500)); | ||
| 200 | |||
| 201 | // Backing buffer covering both 64-byte instance descriptors. | ||
| 202 | std::array<std::uint8_t, 128> inst_storage{}; | ||
| 203 | ctx.add_resource(1, make_buffer(1, kInstVa, inst_storage.size(), inst_storage.data())); | ||
| 204 | |||
| 205 | // Case 1: Tied-start aliasing upload buffers: ID 10 holds 64 bytes, higher-ID 20 holds only 8 bytes. | ||
| 206 | // host_at(kPtrVa, 16) must pick ID 10 instead of failing on ID 20. | ||
| 207 | std::array<std::uint64_t, 8> big_ptrs{kInstVa, kInstVa + 64}; | ||
| 208 | std::array<std::uint64_t, 1> small_ptrs{kInstVa + 64}; | ||
| 209 | ctx.add_resource(10, make_buffer(10, kPtrVa, big_ptrs.size() * sizeof(std::uint64_t), | ||
| 210 | reinterpret_cast<const std::uint8_t*>(big_ptrs.data()))); | ||
| 211 | ctx.add_resource(20, make_buffer(20, kPtrVa, small_ptrs.size() * sizeof(std::uint64_t), | ||
| 212 | reinterpret_cast<const std::uint8_t*>(small_ptrs.data()))); | ||
| 213 | |||
| 214 | as_builds = 0; | ||
| 215 | staged_addresses.clear(); | ||
| 216 | expect(run_tlas_pointers(ctx, kDstVa, kPtrVa, 2) == leonida::ReplayResult::success, | ||
| 217 | "host_at must resolve aliasing larger placed upload buffer for full byte range"); | ||
| 218 | expect(as_builds == 1 && build_saw_array_of_pointers && build_instances_address == kStageDeviceAddress, | ||
| 219 | "TLAS build did not consume staged KHR pointer buffer"); | ||
| 220 | expect(staged_addresses.size() == 2 && staged_addresses[0] == kHeapBase + kInstVa && | ||
| 221 | staged_addresses[1] == kHeapBase + kInstVa + 64, | ||
| 222 | "staged instance device addresses came from wrong aliasing buffer"); | ||
| 223 | |||
| 224 | // Case 2: Request larger than every aliasing buffer (80 > 64) still fails with invalid_copy. | ||
| 225 | as_builds = 0; | ||
| 226 | expect(run_tlas_pointers(ctx, kDstVa, kPtrVa, 10) == leonida::ReplayResult::invalid_copy && as_builds == 0, | ||
| 227 | "oversized range past every aliasing buffer must fail"); | ||
| 228 | |||
| 229 | // Case 3: Non-CPU-written (DEFAULT/READBACK, host == nullptr) buffer returns unsupported without falling through. | ||
| 230 | ctx.add_resource(30, make_buffer(30, kGpuVa, 64, nullptr)); | ||
| 231 | expect(run_tlas_pointers(ctx, kDstVa, kGpuVa, 2) == leonida::ReplayResult::unsupported, | ||
| 232 | "GPU-only buffer must return unsupported"); | ||
| 233 | |||
| 234 | // Case 4: Offset aliasing: small placed buffer starting inside a larger CPU-mapped placed buffer. | ||
| 235 | std::array<std::uint64_t, 16> offset_big{}; | ||
| 236 | offset_big[4] = kInstVa; | ||
| 237 | offset_big[5] = kInstVa + 64; | ||
| 238 | std::array<std::uint64_t, 1> offset_small{kInstVa}; | ||
| 239 | ctx.add_resource(40, make_buffer(40, kBaseVa, offset_big.size() * sizeof(std::uint64_t), | ||
| 240 | reinterpret_cast<const std::uint8_t*>(offset_big.data()))); | ||
| 241 | ctx.add_resource(41, make_buffer(41, kBaseVa + 32, offset_small.size() * sizeof(std::uint64_t), | ||
| 242 | reinterpret_cast<const std::uint8_t*>(offset_small.data()))); | ||
| 243 | as_builds = 0; | ||
| 244 | staged_addresses.clear(); | ||
| 245 | expect(run_tlas_pointers(ctx, kDstVa, kBaseVa + 32, 2) == leonida::ReplayResult::success && as_builds == 1, | ||
| 246 | "host_at at offset must fall back to aliasing container buffer holding full range"); | ||
| 247 | expect(staged_addresses.size() == 2 && staged_addresses[0] == kHeapBase + kInstVa && | ||
| 248 | staged_addresses[1] == kHeapBase + kInstVa + 64, | ||
| 249 | "offset aliasing staged wrong addresses"); | ||
| 250 | } | ||
| 251 | |||
| 252 | expect(live_buffers == 0 && live_memories == 0 && mapped_count == 0, | ||
| 253 | "mock staging buffers/memories leaked after VulkanContext teardown"); | ||
| 254 | if (failures) return 1; | ||
| 255 | std::puts("vk_host_at_aliasing: ok"); | ||
| 256 | return 0; | ||
| 257 | } | ||
diff --git a/runtime/test/vk_queue_test.cpp b/runtime/test/vk_queue_test.cpp index 744adfab8..8dad391b0 100644 --- a/runtime/test/vk_queue_test.cpp +++ b/runtime/test/vk_queue_test.cpp | |||
| @@ -64,6 +64,33 @@ VKAPI_ATTR VkResult VKAPI_CALL stalling_wait_semaphores(VkDevice device, const V | |||
| 64 | return real_wait_semaphores(device, info, timeout); | 64 | return real_wait_semaphores(device, info, timeout); |
| 65 | } | 65 | } |
| 66 | 66 | ||
| 67 | // Each submission's command buffer starts with a full memory barrier (D3D12's ExecuteCommandLists boundary): counts | ||
| 68 | // the command buffers begun and those whose first barrier is that one. | ||
| 69 | PFN_vkBeginCommandBuffer real_begin = nullptr; | ||
| 70 | PFN_vkCmdPipelineBarrier real_barrier = nullptr; | ||
| 71 | std::uint32_t begun = 0, led_by_full_barrier = 0; | ||
| 72 | bool awaiting_first_barrier = false; | ||
| 73 | |||
| 74 | VKAPI_ATTR VkResult VKAPI_CALL counting_begin(VkCommandBuffer cb, const VkCommandBufferBeginInfo* info) { | ||
| 75 | ++begun; | ||
| 76 | awaiting_first_barrier = true; | ||
| 77 | return real_begin(cb, info); | ||
| 78 | } | ||
| 79 | |||
| 80 | VKAPI_ATTR void VKAPI_CALL watching_barrier(VkCommandBuffer cb, VkPipelineStageFlags src, VkPipelineStageFlags dst, | ||
| 81 | VkDependencyFlags flags, std::uint32_t memory_count, | ||
| 82 | const VkMemoryBarrier* memory, std::uint32_t buffer_count, | ||
| 83 | const VkBufferMemoryBarrier* buffers, std::uint32_t image_count, | ||
| 84 | const VkImageMemoryBarrier* images) { | ||
| 85 | if (awaiting_first_barrier) { | ||
| 86 | awaiting_first_barrier = false; | ||
| 87 | if (src == VK_PIPELINE_STAGE_ALL_COMMANDS_BIT && dst == VK_PIPELINE_STAGE_ALL_COMMANDS_BIT && | ||
| 88 | memory_count == 1 && (memory[0].srcAccessMask & VK_ACCESS_MEMORY_WRITE_BIT)) | ||
| 89 | ++led_by_full_barrier; | ||
| 90 | } | ||
| 91 | real_barrier(cb, src, dst, flags, memory_count, memory, buffer_count, buffers, image_count, images); | ||
| 92 | } | ||
| 93 | |||
| 67 | const char* flags_text(VkQueueFlags f) { | 94 | const char* flags_text(VkQueueFlags f) { |
| 68 | static char buf[32]; | 95 | static char buf[32]; |
| 69 | std::snprintf(buf, sizeof buf, "%s%s%s", f & VK_QUEUE_GRAPHICS_BIT ? "G" : "", f & VK_QUEUE_COMPUTE_BIT ? "C" : "", | 96 | std::snprintf(buf, sizeof buf, "%s%s%s", f & VK_QUEUE_GRAPHICS_BIT ? "G" : "", f & VK_QUEUE_COMPUTE_BIT ? "C" : "", |
| @@ -347,6 +374,38 @@ int main() { | |||
| 347 | EXPECT(compute.execute(clear_lists) == ReplayResult::unsupported); | 374 | EXPECT(compute.execute(clear_lists) == ReplayResult::unsupported); |
| 348 | std::printf("copy and compute queues refuse a render-target clear\n"); | 375 | std::printf("copy and compute queues refuse a render-target clear\n"); |
| 349 | 376 | ||
| 377 | // 4b. Two ExecuteCommandLists copying into the same buffer, with no barrier in either list: D3D12 orders them (each | ||
| 378 | // ends with its work done and visible), so each submission's command buffer must start with a full memory barrier. | ||
| 379 | // Before, none did, and synchronization validation reported WRITE_AFTER_WRITE between them (in 5 below). | ||
| 380 | { | ||
| 381 | void* map = nullptr; | ||
| 382 | VkBuffer twice_src = d.buffer(4096, usage, &map); | ||
| 383 | VkBuffer twice_dst = d.buffer(4096, usage, &map); | ||
| 384 | EXPECT(twice_src && twice_dst); | ||
| 385 | add_buffer(9, twice_src, 4096); | ||
| 386 | add_buffer(10, twice_dst, 4096); | ||
| 387 | CommandList twice; | ||
| 388 | EXPECT(twice.copy_buffer({10, 0, 9, 0, 4096})); | ||
| 389 | EXPECT(twice.close()); | ||
| 390 | const CommandList* twice_lists[] = {&twice}; | ||
| 391 | real_begin = context.vk.vkBeginCommandBuffer; | ||
| 392 | real_barrier = context.vk.vkCmdPipelineBarrier; | ||
| 393 | context.vk.vkBeginCommandBuffer = counting_begin; | ||
| 394 | context.vk.vkCmdPipelineBarrier = watching_barrier; | ||
| 395 | begun = led_by_full_barrier = 0; | ||
| 396 | for (Kind kind : {Kind::direct, Kind::copy}) { | ||
| 397 | VulkanQueue& q = kind == Kind::direct ? direct : copy; | ||
| 398 | EXPECT(q.execute(twice_lists) == ReplayResult::success); | ||
| 399 | EXPECT(q.execute(twice_lists) == ReplayResult::success); | ||
| 400 | EXPECT(q.idle()); | ||
| 401 | } | ||
| 402 | context.vk.vkBeginCommandBuffer = real_begin; | ||
| 403 | context.vk.vkCmdPipelineBarrier = real_barrier; | ||
| 404 | std::printf("ExecuteCommandLists boundary: %u of %u submissions start with a full memory barrier\n", | ||
| 405 | led_by_full_barrier, begun); | ||
| 406 | EXPECT(begun >= 4 && led_by_full_barrier == begun); | ||
| 407 | } | ||
| 408 | |||
| 350 | // 5. A caller that submits faster than the GPU finishes must not grow the queue's command buffers without bound: | 409 | // 5. A caller that submits faster than the GPU finishes must not grow the queue's command buffers without bound: |
| 351 | // at the cap it waits for the oldest one. Big host-visible copies keep the GPU behind the submitting loop. The first | 410 | // at the cap it waits for the oldest one. Big host-visible copies keep the GPU behind the submitting loop. The first |
| 352 | // waits time out (injected), as on a stalled GPU: the cap must hold through a timeout too. | 411 | // waits time out (injected), as on a stalled GPU: the cap must hold through a timeout too. |
diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp index 5567511d0..99a602aeb 100644 --- a/runtime/test/vk_store_test.cpp +++ b/runtime/test/vk_store_test.cpp | |||
| @@ -16,6 +16,10 @@ | |||
| 16 | // at binding 7, where 2D and 3D image atomics address their image, and at index 4 of the sampled array a 16x4 rgba8 | 16 | // at binding 7, where 2D and 3D image atomics address their image, and at index 4 of the sampled array a 16x4 rgba8 |
| 17 | // image with all five mip levels (never read, only queried), behind the T# the runtime writes for such an image. | 17 | // image with all five mip levels (never read, only queried), behind the T# the runtime writes for such an image. |
| 18 | // "signed-zero" checks three direct float stores and all remaining RGBA32 guard words (SHADER-605). | 18 | // "signed-zero" checks three direct float stores and all remaining RGBA32 guard words (SHADER-605). |
| 19 | // "cube" (cs_imgstore_cube.asm, GPU-CUBE-STORE): the shader stores to three cube images (the same three formats, T# | ||
| 20 | // word3 TYPE = SQ_RSRC_IMG_CUBE). As the runtime binds a cube UAV (runtime/src/vulkan_bindless.h), each is a | ||
| 21 | // cube-compatible 8x8 image of six layers whose storage view is a six-layer 2D array, at index k + 1 of the 2D-array | ||
| 22 | // storage arrays (bindings 11 / 12 / 13 for float / uint / sint). Checks every texel of every layer (the face). | ||
| 19 | #include "vulkan_loader.h" | 23 | #include "vulkan_loader.h" |
| 20 | #include "vk_device_pick.h" | 24 | #include "vk_device_pick.h" |
| 21 | #include "vk_shader_fma.h" | 25 | #include "vk_shader_fma.h" |
| @@ -60,7 +64,10 @@ static void table_insert(std::vector<uint32_t>& t, const uint32_t key[8], uint32 | |||
| 60 | } | 64 | } |
| 61 | 65 | ||
| 62 | int main(int argc, char** argv) { | 66 | int main(int argc, char** argv) { |
| 63 | if (argc < 2) { std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|words|signed-zero]\n"); return 2; } | 67 | if (argc < 2) { |
| 68 | std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|words|signed-zero|cube]\n"); | ||
| 69 | return 2; | ||
| 70 | } | ||
| 64 | gipa = load_vulkan(); | 71 | gipa = load_vulkan(); |
| 65 | if (!gipa) return 1; | 72 | if (!gipa) return 1; |
| 66 | #define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name)) | 73 | #define LOADI(name) auto name = reinterpret_cast<PFN_##name>(gipa(inst, #name)) |
| @@ -126,6 +133,7 @@ int main(int argc, char** argv) { | |||
| 126 | // "words" mode: the two images filled as for "load"; the shader's results are whatever it leaves in them. | 133 | // "words" mode: the two images filled as for "load"; the shader's results are whatever it leaves in them. |
| 127 | const bool words_mode = argc > 2 && !std::strcmp(argv[2], "words"); | 134 | const bool words_mode = argc > 2 && !std::strcmp(argv[2], "words"); |
| 128 | const bool signed_zero = argc > 2 && !std::strcmp(argv[2], "signed-zero"); | 135 | const bool signed_zero = argc > 2 && !std::strcmp(argv[2], "signed-zero"); |
| 136 | const bool cube_mode = argc > 2 && !std::strcmp(argv[2], "cube"); | ||
| 129 | if (signed_zero) { | 137 | if (signed_zero) { |
| 130 | LOADI(vkGetPhysicalDeviceProperties2); | 138 | LOADI(vkGetPhysicalDeviceProperties2); |
| 131 | VkPhysicalDeviceFloatControlsProperties controls{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES}; | 139 | VkPhysicalDeviceFloatControlsProperties controls{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES}; |
| @@ -224,6 +232,10 @@ int main(int argc, char** argv) { | |||
| 224 | uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20}; | 232 | uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20}; |
| 225 | for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1); | 233 | for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1); |
| 226 | table_insert(table, t, k + 1); // its index in the 2D arrays; 0 is the fallback, as in the runtime | 234 | table_insert(table, t, k + 1); // its index in the 2D arrays; 0 is the fallback, as in the runtime |
| 235 | if (cube_mode) { // the cube T# (cs_imgstore_cube.asm): word3 also has TYPE = 0xB, index k + 1 of the 2D arrays | ||
| 236 | t[3] |= 0xB0000000u; | ||
| 237 | table_insert(table, t, k + 1); | ||
| 238 | } | ||
| 227 | } | 239 | } |
| 228 | // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key | 240 | // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key |
| 229 | // is the T# of exactly that image (gfx10_descriptors.h), which cs_resinfo.asm builds word for word. | 241 | // is the T# of exactly that image (gfx10_descriptors.h), which cs_resinfo.asm builds word for word. |
| @@ -296,6 +308,26 @@ int main(int argc, char** argv) { | |||
| 296 | vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; | 308 | vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; |
| 297 | CHECK(vkCreateImageView(dev, &vi, nullptr, &vol_view)); | 309 | CHECK(vkCreateImageView(dev, &vi, nullptr, &vol_view)); |
| 298 | } | 310 | } |
| 311 | // Cube mode: three cube-compatible 8x8 images of six layers, each seen through a six-layer 2D-array view. | ||
| 312 | const uint32_t FACES = 6; | ||
| 313 | VkImage cube[3]{}; VkImageView cube_view[3]{}; | ||
| 314 | for (int k = 0; cube_mode && k < 3; k++) { | ||
| 315 | VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; | ||
| 316 | ii.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; | ||
| 317 | ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; ii.mipLevels = 1; | ||
| 318 | ii.arrayLayers = FACES; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; | ||
| 319 | ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; | ||
| 320 | CHECK(vkCreateImage(dev, &ii, nullptr, &cube[k])); | ||
| 321 | VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, cube[k], &mr); | ||
| 322 | VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; | ||
| 323 | mai.allocationSize = mr.size; mai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); | ||
| 324 | VkDeviceMemory m; CHECK(vkAllocateMemory(dev, &mai, nullptr, &m)); | ||
| 325 | CHECK(vkBindImageMemory(dev, cube[k], m, 0)); | ||
| 326 | VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; | ||
| 327 | vi.image = cube[k]; vi.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; vi.format = vkf[k]; | ||
| 328 | vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, FACES}; | ||
| 329 | CHECK(vkCreateImageView(dev, &vi, nullptr, &cube_view[k])); | ||
| 330 | } | ||
| 299 | VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; | 331 | VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; |
| 300 | VkSampler sampler; CHECK(vkCreateSampler(dev, &sci, nullptr, &sampler)); | 332 | VkSampler sampler; CHECK(vkCreateSampler(dev, &sci, nullptr, &sampler)); |
| 301 | // Set 0: binding 0 = sampled images, 1 = samplers, 2 = hash table, 8/9/10 = float/uint/sint 2D storage image arrays. | 333 | // Set 0: binding 0 = sampled images, 1 = samplers, 2 = hash table, 8/9/10 = float/uint/sint 2D storage image arrays. |
| @@ -303,23 +335,27 @@ int main(int argc, char** argv) { | |||
| 303 | // index 4. Binding 0 holds each image's view in its own format (typed image_load reads the uint and sint ones | 335 | // index 4. Binding 0 holds each image's view in its own format (typed image_load reads the uint and sint ones |
| 304 | // through integer aliases); every element of a storage array holds the image of its class, so all of them are | 336 | // through integer aliases); every element of a storage array holds the image of its class, so all of them are |
| 305 | // valid descriptors. Bindings 4 and 7 = the 2D and 3D r32ui storage images of the image atomics: the uint image | 337 | // valid descriptors. Bindings 4 and 7 = the 2D and 3D r32ui storage images of the image atomics: the uint image |
| 306 | // and the volume, in every element. | 338 | // and the volume, in every element. Cube mode adds 11/12/13 = the float/uint/sint 2D-array storage arrays, which |
| 339 | // hold the cube image of their class in every element. | ||
| 307 | constexpr uint32_t N = 5; | 340 | constexpr uint32_t N = 5; |
| 308 | VkDescriptorSetLayoutBinding b[8]{}; | 341 | const uint32_t bindings = cube_mode ? 11 : 8; |
| 342 | VkDescriptorSetLayoutBinding b[11]{}; | ||
| 309 | b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; | 343 | b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; |
| 310 | b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; | 344 | b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; |
| 311 | b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; | 345 | b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; |
| 312 | for (int k = 0; k < 3; k++) b[3 + k] = {uint32_t(8 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; | 346 | for (int k = 0; k < 3; k++) b[3 + k] = {uint32_t(8 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; |
| 313 | b[6] = {4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; | 347 | b[6] = {4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; |
| 314 | b[7] = {7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; | 348 | b[7] = {7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; |
| 349 | for (int k = 0; k < 3; k++) | ||
| 350 | b[8 + k] = {uint32_t(11 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; | ||
| 315 | VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; | 351 | VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; |
| 316 | dli.bindingCount = 8; dli.pBindings = b; | 352 | dli.bindingCount = bindings; dli.pBindings = b; |
| 317 | VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); | 353 | VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); |
| 318 | VkDescriptorPoolSize ps[4] = { | 354 | VkDescriptorPoolSize ps[4] = { |
| 319 | {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N}, | 355 | {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N}, |
| 320 | {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, | 356 | {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, |
| 321 | {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, | 357 | {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, |
| 322 | {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 5 * N}, | 358 | {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, (bindings - 3) * N}, |
| 323 | }; | 359 | }; |
| 324 | VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; | 360 | VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; |
| 325 | dpi.maxSets = 1; dpi.poolSizeCount = 4; dpi.pPoolSizes = ps; | 361 | dpi.maxSets = 1; dpi.poolSizeCount = 4; dpi.pPoolSizes = ps; |
| @@ -335,8 +371,8 @@ int main(int argc, char** argv) { | |||
| 335 | {VK_NULL_HANDLE, wide_view, VK_IMAGE_LAYOUT_GENERAL}}; | 371 | {VK_NULL_HANDLE, wide_view, VK_IMAGE_LAYOUT_GENERAL}}; |
| 336 | VkDescriptorImageInfo smpi{sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; | 372 | VkDescriptorImageInfo smpi{sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; |
| 337 | VkDescriptorImageInfo dii[3][N]; | 373 | VkDescriptorImageInfo dii[3][N]; |
| 338 | VkDescriptorImageInfo r32ui[N], r32ui_3d[N]; | 374 | VkDescriptorImageInfo r32ui[N], r32ui_3d[N], cube_ii[3][N]; |
| 339 | VkWriteDescriptorSet wr[8]{}; | 375 | VkWriteDescriptorSet wr[11]{}; |
| 340 | for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; w.descriptorCount = 1; } | 376 | for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; w.descriptorCount = 1; } |
| 341 | wr[0].dstBinding = 0; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = sii; | 377 | wr[0].dstBinding = 0; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = sii; |
| 342 | wr[0].descriptorCount = N; | 378 | wr[0].descriptorCount = N; |
| @@ -353,7 +389,12 @@ int main(int argc, char** argv) { | |||
| 353 | for (uint32_t e = 0; e < N; e++) r32ui_3d[e] = {VK_NULL_HANDLE, vol_view, VK_IMAGE_LAYOUT_GENERAL}; | 389 | for (uint32_t e = 0; e < N; e++) r32ui_3d[e] = {VK_NULL_HANDLE, vol_view, VK_IMAGE_LAYOUT_GENERAL}; |
| 354 | wr[7].dstBinding = 7; wr[7].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; | 390 | wr[7].dstBinding = 7; wr[7].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; |
| 355 | wr[7].pImageInfo = r32ui_3d; wr[7].descriptorCount = N; | 391 | wr[7].pImageInfo = r32ui_3d; wr[7].descriptorCount = N; |
| 356 | vkUpdateDescriptorSets(dev, 8, wr, 0, nullptr); | 392 | for (int k = 0; cube_mode && k < 3; k++) { |
| 393 | for (uint32_t e = 0; e < N; e++) cube_ii[k][e] = {VK_NULL_HANDLE, cube_view[k], VK_IMAGE_LAYOUT_GENERAL}; | ||
| 394 | wr[8 + k].dstBinding = 11 + k; wr[8 + k].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; | ||
| 395 | wr[8 + k].pImageInfo = cube_ii[k]; wr[8 + k].descriptorCount = N; | ||
| 396 | } | ||
| 397 | vkUpdateDescriptorSets(dev, bindings, wr, 0, nullptr); | ||
| 357 | 398 | ||
| 358 | VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; | 399 | VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; |
| 359 | smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data()); | 400 | smi.codeSize = code.size(); smi.pCode = reinterpret_cast<const uint32_t*>(code.data()); |
| @@ -383,6 +424,11 @@ int main(int argc, char** argv) { | |||
| 383 | const uint32_t image_words = W * W * (signed_zero ? 4 : 1); | 424 | const uint32_t image_words = W * W * (signed_zero ? 4 : 1); |
| 384 | VkBuffer rb[3]; void* rbp[3]; | 425 | VkBuffer rb[3]; void* rbp[3]; |
| 385 | for (int k = 0; k < 3; k++) CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb[k], &rbp[k])); | 426 | for (int k = 0; k < 3; k++) CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb[k], &rbp[k])); |
| 427 | // Cube mode: each cube image's six layers read back one after another, texel (x, y) of face f at 64f + 8y + x. | ||
| 428 | const uint32_t cube_words = W * W * FACES; | ||
| 429 | VkBuffer cube_rb[3]{}; void* cube_rbp[3]{}; | ||
| 430 | for (int k = 0; cube_mode && k < 3; k++) | ||
| 431 | CHECK(make_buffer(cube_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &cube_rb[k], &cube_rbp[k])); | ||
| 386 | // Load and words modes: what the uint and sint images hold before the dispatch, texel (x, y) at i = 8y + x. | 432 | // Load and words modes: what the uint and sint images hold before the dispatch, texel (x, y) at i = 8y + x. |
| 387 | // The last row of the D16 fixture ("load-d16" only) exercises both sides of each 16-bit boundary. | 433 | // The last row of the D16 fixture ("load-d16" only) exercises both sides of each 16-bit boundary. |
| 388 | struct PackedLoad { uint32_t u; int32_t s, sum; }; | 434 | struct PackedLoad { uint32_t u; int32_t s, sum; }; |
| @@ -471,6 +517,17 @@ int main(int argc, char** argv) { | |||
| 471 | vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, | 517 | vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, |
| 472 | nullptr, 0, nullptr, 3 - first_fill, ib + first_fill); | 518 | nullptr, 0, nullptr, 3 - first_fill, ib + first_fill); |
| 473 | } | 519 | } |
| 520 | VkImageMemoryBarrier cube_ib[3]{}; | ||
| 521 | for (int k = 0; cube_mode && k < 3; k++) { | ||
| 522 | cube_ib[k] = ib[0]; | ||
| 523 | cube_ib[k].image = cube[k]; cube_ib[k].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; | ||
| 524 | cube_ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; cube_ib[k].srcAccessMask = 0; | ||
| 525 | cube_ib[k].dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT; | ||
| 526 | cube_ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, FACES}; | ||
| 527 | } | ||
| 528 | if (cube_mode) | ||
| 529 | vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, | ||
| 530 | 0, nullptr, 3, cube_ib); | ||
| 474 | vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); | 531 | vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); |
| 475 | vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, nullptr); | 532 | vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, nullptr); |
| 476 | uint32_t pc[36] = {}; | 533 | uint32_t pc[36] = {}; |
| @@ -493,6 +550,19 @@ int main(int argc, char** argv) { | |||
| 493 | bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1}; | 550 | bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1}; |
| 494 | vkCmdCopyImageToBuffer(cmd, img[k], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb[k], 1, &bic); | 551 | vkCmdCopyImageToBuffer(cmd, img[k], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb[k], 1, &bic); |
| 495 | } | 552 | } |
| 553 | if (cube_mode) { | ||
| 554 | for (int k = 0; k < 3; k++) { | ||
| 555 | cube_ib[k].oldLayout = VK_IMAGE_LAYOUT_GENERAL; cube_ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; | ||
| 556 | cube_ib[k].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; cube_ib[k].dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; | ||
| 557 | } | ||
| 558 | vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, | ||
| 559 | nullptr, 3, cube_ib); | ||
| 560 | for (int k = 0; k < 3; k++) { | ||
| 561 | VkBufferImageCopy bic{}; // all six layers, tightly packed one after another | ||
| 562 | bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, FACES}; bic.imageExtent = {W, W, 1}; | ||
| 563 | vkCmdCopyImageToBuffer(cmd, cube[k], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, cube_rb[k], 1, &bic); | ||
| 564 | } | ||
| 565 | } | ||
| 496 | if (words_mode) { | 566 | if (words_mode) { |
| 497 | vol_ib.oldLayout = VK_IMAGE_LAYOUT_GENERAL; vol_ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; | 567 | vol_ib.oldLayout = VK_IMAGE_LAYOUT_GENERAL; vol_ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; |
| 498 | vol_ib.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; | 568 | vol_ib.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; |
| @@ -514,6 +584,30 @@ int main(int argc, char** argv) { | |||
| 514 | CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); | 584 | CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); |
| 515 | CHECK(vkQueueWaitIdle(q)); | 585 | CHECK(vkQueueWaitIdle(q)); |
| 516 | 586 | ||
| 587 | if (cube_mode) { // every texel of every face, against what cs_imgstore_cube.asm writes there | ||
| 588 | uint32_t bad[3] = {}; | ||
| 589 | for (uint32_t face = 0; face < FACES; face++) | ||
| 590 | for (uint32_t y = 0; y < W; y++) | ||
| 591 | for (uint32_t x = 0; x < W; x++) { | ||
| 592 | const uint32_t i = y * W + x, at = face * W * W + i; | ||
| 593 | const uint8_t* c = static_cast<const uint8_t*>(cube_rbp[0]) + 4 * at; | ||
| 594 | const int er = int(std::lround(x / 7.0 * 255)), eg = int(std::lround(y / 7.0 * 255)); | ||
| 595 | const int eb = int(std::lround(face / 5.0 * 255)); | ||
| 596 | if (std::abs(c[0] - er) > 1 || std::abs(c[1] - eg) > 1 || std::abs(c[2] - eb) > 1 || c[3] != 255) | ||
| 597 | bad[0]++; | ||
| 598 | if (static_cast<const uint32_t*>(cube_rbp[1])[at] != 100 + 1000 * face + i) bad[1]++; | ||
| 599 | if (static_cast<const int32_t*>(cube_rbp[2])[at] != -int32_t(1000 * face + i)) bad[2]++; | ||
| 600 | } | ||
| 601 | const uint32_t at = 4 * W * W + 3 * W + 5; // texel (5, 3) of face 4 | ||
| 602 | const uint8_t* c = static_cast<const uint8_t*>(cube_rbp[0]) + 4 * at; | ||
| 603 | std::printf("rgba8 unorm cube (float view): %u bad, face 4 texel(5,3) = %u %u %u %u\n", bad[0], c[0], c[1], | ||
| 604 | c[2], c[3]); | ||
| 605 | std::printf("r32 uint cube (uint view): %u bad, face 4 texel(5,3) = %u\n", bad[1], | ||
| 606 | static_cast<const uint32_t*>(cube_rbp[1])[at]); | ||
| 607 | std::printf("r32 sint cube (sint view): %u bad, face 4 texel(5,3) = %d\n", bad[2], | ||
| 608 | static_cast<const int32_t*>(cube_rbp[2])[at]); | ||
| 609 | return (bad[0] || bad[1] || bad[2]) ? 1 : 0; | ||
| 610 | } | ||
| 517 | if (signed_zero) { | 611 | if (signed_zero) { |
| 518 | constexpr uint32_t neg = 0x80000000; | 612 | constexpr uint32_t neg = 0x80000000; |
| 519 | constexpr uint32_t stores[] = {neg, 0, 0, 0, neg, 0x3f800000, 0, 0, neg, neg, 0, 0}; | 613 | constexpr uint32_t stores[] = {neg, 0, 0, 0, neg, 0x3f800000, 0, 0, neg, neg, 0, 0}; |
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 5cccd1836..f1083231b 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h | |||
| @@ -106,6 +106,8 @@ public: | |||
| 106 | bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled | 106 | bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled |
| 107 | bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available | 107 | bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available |
| 108 | bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled | 108 | bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled |
| 109 | bool request_depth_range_unrestricted = false; | ||
| 110 | bool depth_range_unrestricted = false; // VK_EXT_depth_range_unrestricted enabled | ||
| 109 | // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the | 111 | // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the |
| 110 | // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. | 112 | // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. |
| 111 | bool swapchain_maintenance1 = false; | 113 | bool swapchain_maintenance1 = false; |
| @@ -118,6 +120,7 @@ public: | |||
| 118 | bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available | 120 | bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available |
| 119 | bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available | 121 | bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available |
| 120 | bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled | 122 | bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled |
| 123 | bool mesh_shader_queries = false; // the meshShaderQueries feature is enabled on the device | ||
| 121 | bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance | 124 | bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance |
| 122 | // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them. | 125 | // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them. |
| 123 | leonida::SubgroupSizeCaps subgroup; | 126 | leonida::SubgroupSizeCaps subgroup; |
| @@ -523,10 +526,13 @@ public: | |||
| 523 | VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; | 526 | VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; |
| 524 | instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query); | 527 | instance_fn<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(physical, &query); |
| 525 | mesh_shader = mesh_features.meshShader == VK_TRUE; | 528 | mesh_shader = mesh_features.meshShader == VK_TRUE; |
| 529 | mesh_shader_queries = mesh_features.meshShaderQueries == VK_TRUE; | ||
| 526 | } | 530 | } |
| 527 | if (mesh_shader) { | 531 | if (mesh_shader) { |
| 528 | mesh_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, *v13_.next()}; | 532 | mesh_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, *v13_.next()}; |
| 529 | mesh_features.meshShader = VK_TRUE; | 533 | mesh_features.meshShader = VK_TRUE; |
| 534 | // The mesh-primitives query, which counts the primitives a mesh shader emits (D3D-MESH-CLIPPING-COUNTER). | ||
| 535 | mesh_features.meshShaderQueries = mesh_shader_queries ? VK_TRUE : VK_FALSE; | ||
| 530 | *v13_.next() = &mesh_features; | 536 | *v13_.next() = &mesh_features; |
| 531 | } | 537 | } |
| 532 | enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available | 538 | enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available |
| @@ -567,6 +573,11 @@ public: | |||
| 567 | enabled = enable; | 573 | enabled = enable; |
| 568 | std::vector<const char*> device_extensions; | 574 | std::vector<const char*> device_extensions; |
| 569 | v13_.add_extensions(device_extensions); | 575 | v13_.add_extensions(device_extensions); |
| 576 | depth_range_unrestricted = request_depth_range_unrestricted && | ||
| 577 | std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { | ||
| 578 | return std::strcmp(e.extensionName, VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME) == 0; | ||
| 579 | }); | ||
| 580 | if (depth_range_unrestricted) device_extensions.push_back(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); | ||
| 570 | conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { | 581 | conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { |
| 571 | return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; | 582 | return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; |
| 572 | }); | 583 | }); |
diff --git a/runtime/test/vulkan_scratch_test.cpp b/runtime/test/vulkan_scratch_test.cpp index 8ca6a819a..f63610615 100644 --- a/runtime/test/vulkan_scratch_test.cpp +++ b/runtime/test/vulkan_scratch_test.cpp | |||
| @@ -8,6 +8,7 @@ | |||
| 8 | #include <cstdint> | 8 | #include <cstdint> |
| 9 | #include <cstdio> | 9 | #include <cstdio> |
| 10 | #include <cstring> | 10 | #include <cstring> |
| 11 | #include <limits> | ||
| 11 | #include <unordered_map> | 12 | #include <unordered_map> |
| 12 | #include <unordered_set> | 13 | #include <unordered_set> |
| 13 | 14 | ||
| @@ -289,6 +290,26 @@ int main() { | |||
| 289 | EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); | 290 | EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); |
| 290 | } | 291 | } |
| 291 | 292 | ||
| 293 | // A chunk whose used byte count is within 255 bytes of UINT64_MAX must not wrap alignment back to offset 0. | ||
| 294 | { | ||
| 295 | FakeVulkan vk; | ||
| 296 | g_vk = &vk; | ||
| 297 | { | ||
| 298 | ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate); | ||
| 299 | VkBuffer buf1 = VK_NULL_HANDLE, buf2 = VK_NULL_HANDLE; | ||
| 300 | VkDeviceSize off1 = 1, off2 = 1; | ||
| 301 | const std::uint64_t near_max = std::numeric_limits<std::uint64_t>::max() - 100u; | ||
| 302 | EXPECT(scratch.get(near_max, buf1, off1)); | ||
| 303 | EXPECT(buf1 != VK_NULL_HANDLE && off1 == 0 && vk.create_buffer_calls == 1); | ||
| 304 | |||
| 305 | EXPECT(scratch.get(16, buf2, off2)); | ||
| 306 | EXPECT(buf2 != VK_NULL_HANDLE && buf2 != buf1 && off2 == 0); | ||
| 307 | EXPECT(vk.create_buffer_calls == 2 && vk.allocate_calls == 2); | ||
| 308 | EXPECT(vk.live_buffers.size() == 2 && vk.live_memory.size() == 2); | ||
| 309 | } | ||
| 310 | EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); | ||
| 311 | } | ||
| 312 | |||
| 292 | std::printf("vulkan_scratch: all checks passed\n"); | 313 | std::printf("vulkan_scratch: all checks passed\n"); |
| 293 | return 0; | 314 | return 0; |
| 294 | } | 315 | } |
diff --git a/runtime/test/ws2_offline_test.cpp b/runtime/test/ws2_offline_test.cpp new file mode 100644 index 000000000..32cdda48c --- /dev/null +++ b/runtime/test/ws2_offline_test.cpp | |||
| @@ -0,0 +1,547 @@ | |||
| 1 | // Checks the offline Winsock2 (ws2_32.dll) shim (runtime/shims/ws2_offline.cpp). | ||
| 2 | // | ||
| 3 | // Resolves every shimmed symbol through rt::shims::find under ws2_32.dll (by name and by standard Windows ordinal), | ||
| 4 | // checks that wsock32.dll resolves its shared entries to the same wrappers, and verifies that external addresses | ||
| 5 | // (RFC 5737 192.0.2.1 / RFC 3849 2001:db8::1), .invalid hostnames, octal-looking 0127.0.0.1 and name-service queries | ||
| 6 | // are refused in-process while loopback (127.0.0.1 / ::1 / localhost) still works. Sends on unbound UDP sockets bind | ||
| 7 | // them to loopback, and multicast joins (setsockopt on both DLLs, WSAJoinLeaf) are refused. Nothing touches the network. | ||
| 8 | #ifndef _WINSOCK_DEPRECATED_NO_WARNINGS | ||
| 9 | #define _WINSOCK_DEPRECATED_NO_WARNINGS | ||
| 10 | #endif | ||
| 11 | #ifndef WIN32_LEAN_AND_MEAN | ||
| 12 | #define WIN32_LEAN_AND_MEAN | ||
| 13 | #endif | ||
| 14 | #ifndef NOMINMAX | ||
| 15 | #define NOMINMAX | ||
| 16 | #endif | ||
| 17 | |||
| 18 | #include <winsock2.h> | ||
| 19 | #include <ws2tcpip.h> | ||
| 20 | #include <mswsock.h> | ||
| 21 | #include <windows.h> | ||
| 22 | |||
| 23 | #include <cstdint> | ||
| 24 | #include <cstdio> | ||
| 25 | #include <cstring> | ||
| 26 | |||
| 27 | #include "shims.h" | ||
| 28 | |||
| 29 | #ifndef SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER | ||
| 30 | #define SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER 0xC8000024u | ||
| 31 | #endif | ||
| 32 | |||
| 33 | namespace { | ||
| 34 | |||
| 35 | int g_checks = 0; | ||
| 36 | int g_failures = 0; | ||
| 37 | |||
| 38 | void check(bool condition, const char* what) { | ||
| 39 | ++g_checks; | ||
| 40 | std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); | ||
| 41 | if (!condition) ++g_failures; | ||
| 42 | } | ||
| 43 | |||
| 44 | template <typename Fn> | ||
| 45 | Fn resolve(const char* sym) { | ||
| 46 | return reinterpret_cast<Fn>(rt::shims::find("ws2_32.dll", sym)); | ||
| 47 | } | ||
| 48 | |||
| 49 | sockaddr_in make_v4(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port) { | ||
| 50 | sockaddr_in sa{}; | ||
| 51 | sa.sin_family = AF_INET; | ||
| 52 | sa.sin_port = htons(port); | ||
| 53 | auto* bytes = reinterpret_cast<uint8_t*>(&sa.sin_addr); | ||
| 54 | bytes[0] = a; | ||
| 55 | bytes[1] = b; | ||
| 56 | bytes[2] = c; | ||
| 57 | bytes[3] = d; | ||
| 58 | return sa; | ||
| 59 | } | ||
| 60 | |||
| 61 | sockaddr_in6 make_v6_doc(uint16_t port) { | ||
| 62 | // 2001:db8::1 (RFC 3849 documentation prefix, non-loopback) | ||
| 63 | sockaddr_in6 sa{}; | ||
| 64 | sa.sin6_family = AF_INET6; | ||
| 65 | sa.sin6_port = htons(port); | ||
| 66 | auto* bytes = reinterpret_cast<uint8_t*>(&sa.sin6_addr); | ||
| 67 | bytes[0] = 0x20; | ||
| 68 | bytes[1] = 0x01; | ||
| 69 | bytes[2] = 0x0d; | ||
| 70 | bytes[3] = 0xb8; | ||
| 71 | bytes[15] = 0x01; | ||
| 72 | return sa; | ||
| 73 | } | ||
| 74 | |||
| 75 | } // namespace | ||
| 76 | |||
| 77 | int main() { | ||
| 78 | WSADATA wsa{}; | ||
| 79 | if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { | ||
| 80 | std::fprintf(stderr, "WSAStartup failed (%d)\n", WSAGetLastError()); | ||
| 81 | return 1; | ||
| 82 | } | ||
| 83 | |||
| 84 | using BindFn = int(WSAAPI*)(SOCKET, const sockaddr*, int); | ||
| 85 | using ConnectFn = int(WSAAPI*)(SOCKET, const sockaddr*, int); | ||
| 86 | using SendToFn = int(WSAAPI*)(SOCKET, const char*, int, int, const sockaddr*, int); | ||
| 87 | using WsaConnectFn = int(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS); | ||
| 88 | using WsaConnectByNameAFn = BOOL(WSAAPI*)(SOCKET, LPCSTR, LPCSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, | ||
| 89 | const timeval*, LPWSAOVERLAPPED); | ||
| 90 | using WsaConnectByNameWFn = BOOL(WSAAPI*)(SOCKET, LPWSTR, LPWSTR, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, | ||
| 91 | const timeval*, LPWSAOVERLAPPED); | ||
| 92 | using WsaConnectByListFn = BOOL(WSAAPI*)(SOCKET, PSOCKET_ADDRESS_LIST, LPDWORD, LPSOCKADDR, LPDWORD, LPSOCKADDR, | ||
| 93 | const timeval*, LPWSAOVERLAPPED); | ||
| 94 | using WsaSendToFn = int(WSAAPI*)(SOCKET, LPWSABUF, DWORD, LPDWORD, DWORD, const sockaddr*, int, LPWSAOVERLAPPED, | ||
| 95 | LPWSAOVERLAPPED_COMPLETION_ROUTINE); | ||
| 96 | using WsaSendMsgFn = int(WSAAPI*)(SOCKET, LPWSAMSG, DWORD, LPDWORD, LPWSAOVERLAPPED, | ||
| 97 | LPWSAOVERLAPPED_COMPLETION_ROUTINE); | ||
| 98 | using WsaIoctlFn = int(WSAAPI*)(SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSAOVERLAPPED, | ||
| 99 | LPWSAOVERLAPPED_COMPLETION_ROUTINE); | ||
| 100 | using GetAddrInfoAFn = INT(WSAAPI*)(PCSTR, PCSTR, const ADDRINFOA*, PADDRINFOA*); | ||
| 101 | using GetAddrInfoWFn = INT(WSAAPI*)(PCWSTR, PCWSTR, const ADDRINFOW*, PADDRINFOW*); | ||
| 102 | using GetNameInfoAFn = INT(WSAAPI*)(const sockaddr*, socklen_t, PCHAR, DWORD, PCHAR, DWORD, INT); | ||
| 103 | using GetHostByNameFn = hostent*(WSAAPI*)(const char*); | ||
| 104 | using GetHostByAddrFn = hostent*(WSAAPI*)(const char*, int, int); | ||
| 105 | using LookupBeginWFn = int(WSAAPI*)(LPWSAQUERYSETW, DWORD, LPHANDLE); | ||
| 106 | |||
| 107 | const auto sh_bind = resolve<BindFn>("bind"); | ||
| 108 | const auto sh_bind_ord = resolve<BindFn>("#2"); | ||
| 109 | const auto sh_connect = resolve<ConnectFn>("connect"); | ||
| 110 | const auto sh_connect_ord = resolve<ConnectFn>("#4"); | ||
| 111 | const auto sh_sendto = resolve<SendToFn>("sendto"); | ||
| 112 | const auto sh_sendto_ord = resolve<SendToFn>("#20"); | ||
| 113 | const auto sh_wsa_connect = resolve<WsaConnectFn>("WSAConnect"); | ||
| 114 | const auto sh_connect_name_a = resolve<WsaConnectByNameAFn>("WSAConnectByNameA"); | ||
| 115 | const auto sh_connect_name_w = resolve<WsaConnectByNameWFn>("WSAConnectByNameW"); | ||
| 116 | const auto sh_connect_list = resolve<WsaConnectByListFn>("WSAConnectByList"); | ||
| 117 | const auto sh_wsa_sendto = resolve<WsaSendToFn>("WSASendTo"); | ||
| 118 | const auto sh_wsa_sendmsg = resolve<WsaSendMsgFn>("WSASendMsg"); | ||
| 119 | const auto sh_wsa_ioctl = resolve<WsaIoctlFn>("WSAIoctl"); | ||
| 120 | const auto sh_getaddrinfo = resolve<GetAddrInfoAFn>("getaddrinfo"); | ||
| 121 | const auto sh_getaddrinfo_w = resolve<GetAddrInfoWFn>("GetAddrInfoW"); | ||
| 122 | const auto sh_getnameinfo = resolve<GetNameInfoAFn>("getnameinfo"); | ||
| 123 | const auto sh_gethostbyname = resolve<GetHostByNameFn>("gethostbyname"); | ||
| 124 | const auto sh_gethostbyname_ord = resolve<GetHostByNameFn>("#52"); | ||
| 125 | const auto sh_gethostbyaddr = resolve<GetHostByAddrFn>("gethostbyaddr"); | ||
| 126 | const auto sh_gethostbyaddr_ord = resolve<GetHostByAddrFn>("#51"); | ||
| 127 | |||
| 128 | check(sh_bind && sh_bind == sh_bind_ord, "bind and #2 resolve to the same shim"); | ||
| 129 | check(sh_connect && sh_connect == sh_connect_ord, "connect and #4 resolve to the same shim"); | ||
| 130 | check(sh_sendto && sh_sendto == sh_sendto_ord, "sendto and #20 resolve to the same shim"); | ||
| 131 | check(sh_gethostbyname && sh_gethostbyname == sh_gethostbyname_ord, "gethostbyname and #52 resolve to the same shim"); | ||
| 132 | check(sh_gethostbyaddr && sh_gethostbyaddr == sh_gethostbyaddr_ord, "gethostbyaddr and #51 resolve to the same shim"); | ||
| 133 | check(sh_wsa_connect && sh_connect_name_a && sh_connect_name_w && sh_connect_list && sh_wsa_sendto && | ||
| 134 | sh_wsa_sendmsg && sh_wsa_ioctl && sh_getaddrinfo && sh_getaddrinfo_w && sh_getnameinfo && | ||
| 135 | rt::shims::find("ws2_32.dll", "#102") && rt::shims::find("ws2_32.dll", "#103"), | ||
| 136 | "all offline Winsock2 shims resolve through the registry"); | ||
| 137 | check(!rt::shims::owns_dll("ws2_32.dll"), | ||
| 138 | "ws2_32.dll stays partially overridden (host socket bookkeeping remains available)"); | ||
| 139 | check(!rt::shims::owns_dll("wsock32.dll"), | ||
| 140 | "wsock32.dll stays partially overridden (host socket bookkeeping remains available)"); | ||
| 141 | |||
| 142 | // wsock32.dll resolves its shared entries to the same wrappers as ws2_32.dll, by name and by ordinal. | ||
| 143 | check(rt::shims::find("wsock32.dll", "connect") == sh_connect && rt::shims::find("wsock32.dll", "#4") == sh_connect, | ||
| 144 | "wsock32.dll connect and #4 resolve to the ws2_32.dll connect shim"); | ||
| 145 | check(rt::shims::find("wsock32.dll", "bind") == sh_bind && rt::shims::find("wsock32.dll", "#2") == sh_bind, | ||
| 146 | "wsock32.dll bind and #2 resolve to the ws2_32.dll bind shim"); | ||
| 147 | check(rt::shims::find("wsock32.dll", "gethostbyname") == sh_gethostbyname && | ||
| 148 | rt::shims::find("wsock32.dll", "#52") == sh_gethostbyname, | ||
| 149 | "wsock32.dll gethostbyname and #52 resolve to the ws2_32.dll shim"); | ||
| 150 | |||
| 151 | // 1. External connect / WSAConnect / WSAConnectByName / WSAConnectByList refused with WSAENETUNREACH. | ||
| 152 | { | ||
| 153 | const SOCKET tcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | ||
| 154 | check(tcp != INVALID_SOCKET, "create IPv4 TCP socket"); | ||
| 155 | const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 443); | ||
| 156 | const sockaddr_in6 ext6 = make_v6_doc(443); | ||
| 157 | |||
| 158 | WSASetLastError(0); | ||
| 159 | check(sh_connect(tcp, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4)) == SOCKET_ERROR && | ||
| 160 | WSAGetLastError() == WSAENETUNREACH, | ||
| 161 | "connect refuses external IPv4 with WSAENETUNREACH"); | ||
| 162 | |||
| 163 | WSASetLastError(0); | ||
| 164 | check(sh_connect(tcp, reinterpret_cast<const sockaddr*>(&ext6), sizeof(ext6)) == SOCKET_ERROR && | ||
| 165 | WSAGetLastError() == WSAENETUNREACH, | ||
| 166 | "connect refuses external IPv6 with WSAENETUNREACH"); | ||
| 167 | |||
| 168 | WSASetLastError(0); | ||
| 169 | check(sh_wsa_connect(tcp, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr, nullptr, nullptr, | ||
| 170 | nullptr) == SOCKET_ERROR && | ||
| 171 | WSAGetLastError() == WSAENETUNREACH, | ||
| 172 | "WSAConnect refuses external IPv4 with WSAENETUNREACH"); | ||
| 173 | |||
| 174 | WSASetLastError(0); | ||
| 175 | check(sh_connect_name_a(tcp, "example.invalid", "443", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == | ||
| 176 | FALSE && | ||
| 177 | WSAGetLastError() == WSAENETUNREACH, | ||
| 178 | "WSAConnectByNameA refuses external hostname with WSAENETUNREACH"); | ||
| 179 | |||
| 180 | wchar_t bad_host[] = L"example.invalid"; | ||
| 181 | wchar_t port_w[] = L"443"; | ||
| 182 | WSASetLastError(0); | ||
| 183 | check(sh_connect_name_w(tcp, bad_host, port_w, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == FALSE && | ||
| 184 | WSAGetLastError() == WSAENETUNREACH, | ||
| 185 | "WSAConnectByNameW refuses external hostname with WSAENETUNREACH"); | ||
| 186 | |||
| 187 | SOCKET_ADDRESS_LIST list{}; | ||
| 188 | sockaddr_in ext4_mut = ext4; | ||
| 189 | list.iAddressCount = 1; | ||
| 190 | list.Address[0].lpSockaddr = reinterpret_cast<LPSOCKADDR>(&ext4_mut); | ||
| 191 | list.Address[0].iSockaddrLength = sizeof(ext4_mut); | ||
| 192 | WSASetLastError(0); | ||
| 193 | check(sh_connect_list(tcp, &list, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == FALSE && | ||
| 194 | WSAGetLastError() == WSAENETUNREACH, | ||
| 195 | "WSAConnectByList refuses non-loopback address list with WSAENETUNREACH"); | ||
| 196 | |||
| 197 | // ConnectEx via WSAIoctl is wrapped and refuses external targets. | ||
| 198 | GUID connect_ex_guid = WSAID_CONNECTEX; | ||
| 199 | LPFN_CONNECTEX connect_ex = nullptr; | ||
| 200 | DWORD returned = 0; | ||
| 201 | const int ioctl_rc = sh_wsa_ioctl(tcp, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_guid, | ||
| 202 | sizeof(connect_ex_guid), &connect_ex, sizeof(connect_ex), &returned, nullptr, | ||
| 203 | nullptr); | ||
| 204 | check(ioctl_rc == 0 && connect_ex != nullptr && returned == sizeof(connect_ex), | ||
| 205 | "WSAIoctl returns wrapped ConnectEx"); | ||
| 206 | if (connect_ex) { | ||
| 207 | OVERLAPPED ov{}; | ||
| 208 | WSASetLastError(0); | ||
| 209 | check(connect_ex(tcp, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr, 0, nullptr, &ov) == | ||
| 210 | FALSE && | ||
| 211 | WSAGetLastError() == WSAENETUNREACH, | ||
| 212 | "wrapped ConnectEx refuses external IPv4 with WSAENETUNREACH"); | ||
| 213 | } | ||
| 214 | |||
| 215 | // SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER is refused. | ||
| 216 | DWORD dummy_ret = 0; | ||
| 217 | WSASetLastError(0); | ||
| 218 | check(sh_wsa_ioctl(tcp, SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER, nullptr, 0, nullptr, 0, &dummy_ret, | ||
| 219 | nullptr, nullptr) == SOCKET_ERROR && | ||
| 220 | WSAGetLastError() == WSAEINVAL, | ||
| 221 | "WSAIoctl refuses SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER"); | ||
| 222 | |||
| 223 | closesocket(tcp); | ||
| 224 | } | ||
| 225 | |||
| 226 | // 2. External datagram sends (sendto, WSASendTo, WSASendMsg direct & via WSAIoctl) refused with WSAENETUNREACH. | ||
| 227 | { | ||
| 228 | const SOCKET udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); | ||
| 229 | check(udp != INVALID_SOCKET, "create IPv4 UDP socket"); | ||
| 230 | const sockaddr_in ext4 = make_v4(192, 0, 2, 2, 53); | ||
| 231 | char payload[] = "ping"; | ||
| 232 | |||
| 233 | WSASetLastError(0); | ||
| 234 | check(sh_sendto(udp, payload, 4, 0, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4)) == SOCKET_ERROR && | ||
| 235 | WSAGetLastError() == WSAENETUNREACH, | ||
| 236 | "sendto refuses external IPv4 with WSAENETUNREACH"); | ||
| 237 | |||
| 238 | WSABUF wbuf{4, payload}; | ||
| 239 | DWORD sent = 0; | ||
| 240 | WSASetLastError(0); | ||
| 241 | check(sh_wsa_sendto(udp, &wbuf, 1, &sent, 0, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr, | ||
| 242 | nullptr) == SOCKET_ERROR && | ||
| 243 | WSAGetLastError() == WSAENETUNREACH, | ||
| 244 | "WSASendTo refuses external IPv4 with WSAENETUNREACH"); | ||
| 245 | |||
| 246 | sockaddr_in ext4_mut = ext4; | ||
| 247 | WSAMSG msg{}; | ||
| 248 | msg.name = reinterpret_cast<LPSOCKADDR>(&ext4_mut); | ||
| 249 | msg.namelen = sizeof(ext4_mut); | ||
| 250 | msg.lpBuffers = &wbuf; | ||
| 251 | msg.dwBufferCount = 1; | ||
| 252 | WSASetLastError(0); | ||
| 253 | check(sh_wsa_sendmsg(udp, &msg, 0, &sent, nullptr, nullptr) == SOCKET_ERROR && | ||
| 254 | WSAGetLastError() == WSAENETUNREACH, | ||
| 255 | "WSASendMsg refuses external IPv4 with WSAENETUNREACH"); | ||
| 256 | |||
| 257 | GUID sendmsg_guid = WSAID_WSASENDMSG; | ||
| 258 | LPFN_WSASENDMSG sendmsg_ext = nullptr; | ||
| 259 | DWORD returned = 0; | ||
| 260 | const int ioctl_rc = sh_wsa_ioctl(udp, SIO_GET_EXTENSION_FUNCTION_POINTER, &sendmsg_guid, sizeof(sendmsg_guid), | ||
| 261 | &sendmsg_ext, sizeof(sendmsg_ext), &returned, nullptr, nullptr); | ||
| 262 | check(ioctl_rc == 0 && sendmsg_ext != nullptr, "WSAIoctl returns wrapped WSASendMsg"); | ||
| 263 | if (sendmsg_ext) { | ||
| 264 | WSASetLastError(0); | ||
| 265 | check(sendmsg_ext(udp, &msg, 0, &sent, nullptr, nullptr) == SOCKET_ERROR && | ||
| 266 | WSAGetLastError() == WSAENETUNREACH, | ||
| 267 | "wrapped WSASendMsg extension refuses external IPv4 with WSAENETUNREACH"); | ||
| 268 | } | ||
| 269 | |||
| 270 | closesocket(udp); | ||
| 271 | } | ||
| 272 | |||
| 273 | // 3. bind narrows wildcard 0.0.0.0 to 127.0.0.1 and refuses non-loopback addresses. | ||
| 274 | { | ||
| 275 | const SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); | ||
| 276 | const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 0); | ||
| 277 | WSASetLastError(0); | ||
| 278 | check(sh_bind(s, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4)) == SOCKET_ERROR && | ||
| 279 | WSAGetLastError() == WSAEADDRNOTAVAIL, | ||
| 280 | "bind refuses non-loopback IPv4 with WSAEADDRNOTAVAIL"); | ||
| 281 | |||
| 282 | const sockaddr_in any4 = make_v4(0, 0, 0, 0, 0); | ||
| 283 | check(sh_bind(s, reinterpret_cast<const sockaddr*>(&any4), sizeof(any4)) == 0, | ||
| 284 | "bind accepts wildcard 0.0.0.0 and rewrites to loopback"); | ||
| 285 | sockaddr_in bound{}; | ||
| 286 | int bound_len = sizeof(bound); | ||
| 287 | check(getsockname(s, reinterpret_cast<sockaddr*>(&bound), &bound_len) == 0 && | ||
| 288 | bound.sin_addr.s_addr == htonl(INADDR_LOOPBACK), | ||
| 289 | "wildcard bind narrowed socket address to 127.0.0.1"); | ||
| 290 | closesocket(s); | ||
| 291 | } | ||
| 292 | |||
| 293 | // 4. DNS lookups refuse external hostnames and permit localhost / 127.0.0.1. | ||
| 294 | { | ||
| 295 | ADDRINFOA* res = nullptr; | ||
| 296 | check(sh_getaddrinfo("example.invalid", "443", nullptr, &res) == WSAHOST_NOT_FOUND && res == nullptr, | ||
| 297 | "getaddrinfo refuses external hostname with WSAHOST_NOT_FOUND"); | ||
| 298 | // Windows reads a leading-zero octet as octal, so 0127.0.0.1 is 87.0.0.1 there; it is refused, not loopback. | ||
| 299 | res = nullptr; | ||
| 300 | check(sh_getaddrinfo("0127.0.0.1", "80", nullptr, &res) == WSAHOST_NOT_FOUND && res == nullptr, | ||
| 301 | "getaddrinfo refuses octal-looking 0127.0.0.1 with WSAHOST_NOT_FOUND"); | ||
| 302 | check(sh_getaddrinfo("127.0.0.1", "80", nullptr, &res) == 0 && res != nullptr, | ||
| 303 | "getaddrinfo permits 127.0.0.1"); | ||
| 304 | if (res) freeaddrinfo(res); | ||
| 305 | res = nullptr; | ||
| 306 | check(sh_getaddrinfo("localhost", "80", nullptr, &res) == 0 && res != nullptr, | ||
| 307 | "getaddrinfo permits localhost"); | ||
| 308 | if (res) freeaddrinfo(res); | ||
| 309 | |||
| 310 | ADDRINFOW* res_w = nullptr; | ||
| 311 | check(sh_getaddrinfo_w(L"example.invalid", L"443", nullptr, &res_w) == WSAHOST_NOT_FOUND && res_w == nullptr, | ||
| 312 | "GetAddrInfoW refuses external hostname with WSAHOST_NOT_FOUND"); | ||
| 313 | check(sh_getaddrinfo_w(L"localhost", L"80", nullptr, &res_w) == 0 && res_w != nullptr, | ||
| 314 | "GetAddrInfoW permits localhost"); | ||
| 315 | if (res_w) FreeAddrInfoW(res_w); | ||
| 316 | |||
| 317 | WSASetLastError(0); | ||
| 318 | check(sh_gethostbyname("example.invalid") == nullptr && WSAGetLastError() == WSAHOST_NOT_FOUND, | ||
| 319 | "gethostbyname refuses external hostname with WSAHOST_NOT_FOUND"); | ||
| 320 | |||
| 321 | const uint8_t ext_bytes[4] = {192, 0, 2, 1}; | ||
| 322 | WSASetLastError(0); | ||
| 323 | check(sh_gethostbyaddr(reinterpret_cast<const char*>(ext_bytes), 4, AF_INET) == nullptr && | ||
| 324 | WSAGetLastError() == WSAHOST_NOT_FOUND, | ||
| 325 | "gethostbyaddr refuses external IPv4 with WSAHOST_NOT_FOUND"); | ||
| 326 | |||
| 327 | const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 80); | ||
| 328 | char host_buf[64] = {}; | ||
| 329 | check(sh_getnameinfo(reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), host_buf, sizeof(host_buf), | ||
| 330 | nullptr, 0, NI_NAMEREQD) == WSAHOST_NOT_FOUND, | ||
| 331 | "getnameinfo with NI_NAMEREQD refuses external IPv4"); | ||
| 332 | check(sh_getnameinfo(reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), host_buf, sizeof(host_buf), | ||
| 333 | nullptr, 0, 0) == 0 && | ||
| 334 | std::strcmp(host_buf, "192.0.2.1") == 0, | ||
| 335 | "getnameinfo without NI_NAMEREQD returns numeric IP without reverse DNS"); | ||
| 336 | } | ||
| 337 | |||
| 338 | // 5. Real loopback UDP round-trip through the shimmed bind and sendto succeeds. | ||
| 339 | { | ||
| 340 | const SOCKET recv_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); | ||
| 341 | const SOCKET send_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); | ||
| 342 | const sockaddr_in loop = make_v4(127, 0, 0, 1, 0); | ||
| 343 | check(sh_bind(recv_sock, reinterpret_cast<const sockaddr*>(&loop), sizeof(loop)) == 0, | ||
| 344 | "loopback UDP receiver bind succeeds"); | ||
| 345 | sockaddr_in dst{}; | ||
| 346 | int dst_len = sizeof(dst); | ||
| 347 | check(getsockname(recv_sock, reinterpret_cast<sockaddr*>(&dst), &dst_len) == 0, | ||
| 348 | "getsockname returns loopback UDP port"); | ||
| 349 | const char msg[] = "ok"; | ||
| 350 | check(sh_sendto(send_sock, msg, 2, 0, reinterpret_cast<const sockaddr*>(&dst), sizeof(dst)) == 2, | ||
| 351 | "loopback sendto succeeds"); | ||
| 352 | char got[8] = {}; | ||
| 353 | const int n = recv(recv_sock, got, sizeof(got), 0); | ||
| 354 | check(n == 2 && got[0] == 'o' && got[1] == 'k', "loopback UDP payload received"); | ||
| 355 | closesocket(send_sock); | ||
| 356 | closesocket(recv_sock); | ||
| 357 | } | ||
| 358 | |||
| 359 | // 6. Name-service queries are refused with WSASERVICE_NOT_FOUND. | ||
| 360 | { | ||
| 361 | const auto sh_lookup_w = resolve<LookupBeginWFn>("WSALookupServiceBeginW"); | ||
| 362 | wchar_t service[] = L"example.invalid"; | ||
| 363 | WSAQUERYSETW restrictions{}; | ||
| 364 | restrictions.dwSize = sizeof(restrictions); | ||
| 365 | restrictions.lpszServiceInstanceName = service; | ||
| 366 | HANDLE lookup = nullptr; | ||
| 367 | WSASetLastError(0); | ||
| 368 | check(sh_lookup_w && sh_lookup_w(&restrictions, 0, &lookup) == SOCKET_ERROR && | ||
| 369 | WSAGetLastError() == WSASERVICE_NOT_FOUND && lookup == nullptr, | ||
| 370 | "WSALookupServiceBeginW refuses with WSASERVICE_NOT_FOUND"); | ||
| 371 | } | ||
| 372 | |||
| 373 | // 7. ConnectEx from WSAIoctl connects to a loopback listener through the host's per-socket pointer. | ||
| 374 | { | ||
| 375 | const SOCKET listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | ||
| 376 | sockaddr_in any = make_v4(127, 0, 0, 1, 0); | ||
| 377 | sockaddr_in listen_addr{}; | ||
| 378 | int listen_len = sizeof(listen_addr); | ||
| 379 | check(sh_bind(listener, reinterpret_cast<const sockaddr*>(&any), sizeof(any)) == 0 && | ||
| 380 | listen(listener, 1) == 0 && getsockname(listener, reinterpret_cast<sockaddr*>(&listen_addr), | ||
| 381 | &listen_len) == 0, | ||
| 382 | "loopback TCP listener is up"); | ||
| 383 | |||
| 384 | const SOCKET client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | ||
| 385 | check(sh_bind(client, reinterpret_cast<const sockaddr*>(&any), sizeof(any)) == 0, | ||
| 386 | "ConnectEx client socket is bound to loopback (ConnectEx requires a bound socket)"); | ||
| 387 | GUID connect_ex_guid = WSAID_CONNECTEX; | ||
| 388 | LPFN_CONNECTEX connect_ex = nullptr; | ||
| 389 | DWORD returned = 0; | ||
| 390 | check(sh_wsa_ioctl(client, SIO_GET_EXTENSION_FUNCTION_POINTER, &connect_ex_guid, sizeof(connect_ex_guid), | ||
| 391 | &connect_ex, sizeof(connect_ex), &returned, nullptr, nullptr) == 0 && | ||
| 392 | connect_ex != nullptr, | ||
| 393 | "WSAIoctl returns a ConnectEx pointer for a bound TCP socket"); | ||
| 394 | |||
| 395 | if (connect_ex) { | ||
| 396 | OVERLAPPED ov{}; | ||
| 397 | ov.hEvent = WSACreateEvent(); | ||
| 398 | check(connect_ex(client, reinterpret_cast<const sockaddr*>(&listen_addr), sizeof(listen_addr), nullptr, 0, | ||
| 399 | nullptr, &ov) == TRUE || | ||
| 400 | (WSAGetLastError() == WSA_IO_PENDING && | ||
| 401 | WSAWaitForMultipleEvents(1, &ov.hEvent, TRUE, 5000, FALSE) == WSA_WAIT_EVENT_0), | ||
| 402 | "wrapped ConnectEx connects to the loopback listener"); | ||
| 403 | DWORD transferred = 0, flags = 0; | ||
| 404 | check(WSAGetOverlappedResult(client, &ov, &transferred, FALSE, &flags) == TRUE, | ||
| 405 | "ConnectEx completes with no error"); | ||
| 406 | WSACloseEvent(ov.hEvent); | ||
| 407 | } | ||
| 408 | |||
| 409 | const SOCKET ext = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | ||
| 410 | sockaddr_in ext_any = make_v4(127, 0, 0, 1, 0); | ||
| 411 | check(sh_bind(ext, reinterpret_cast<const sockaddr*>(&ext_any), sizeof(ext_any)) == 0, | ||
| 412 | "second ConnectEx socket is bound to loopback"); | ||
| 413 | if (connect_ex) { | ||
| 414 | const sockaddr_in ext4 = make_v4(192, 0, 2, 1, 443); | ||
| 415 | OVERLAPPED ov{}; | ||
| 416 | WSASetLastError(0); | ||
| 417 | check(connect_ex(ext, reinterpret_cast<const sockaddr*>(&ext4), sizeof(ext4), nullptr, 0, nullptr, &ov) == | ||
| 418 | FALSE && | ||
| 419 | WSAGetLastError() == WSAENETUNREACH, | ||
| 420 | "wrapped ConnectEx refuses non-loopback 192.0.2.1 with WSAENETUNREACH"); | ||
| 421 | } | ||
| 422 | closesocket(ext); | ||
| 423 | closesocket(client); | ||
| 424 | closesocket(listener); | ||
| 425 | } | ||
| 426 | |||
| 427 | // Implicit binds, multicast joins and WSAJoinLeaf. A send on an unbound datagram socket binds it to the wildcard | ||
| 428 | // address (Microsoft's sendto remarks); the shim binds it to loopback first. Joins are refused before the host. | ||
| 429 | { | ||
| 430 | using SetSockOptFn = int(WSAAPI*)(SOCKET, int, int, const char*, int); | ||
| 431 | using JoinLeafFn = SOCKET(WSAAPI*)(SOCKET, const sockaddr*, int, LPWSABUF, LPWSABUF, LPQOS, LPQOS, DWORD); | ||
| 432 | const auto sh_setsockopt = resolve<SetSockOptFn>("setsockopt"); | ||
| 433 | const auto sh_join_leaf = resolve<JoinLeafFn>("WSAJoinLeaf"); | ||
| 434 | const auto ws1_setsockopt = reinterpret_cast<SetSockOptFn>(rt::shims::find("wsock32.dll", "setsockopt")); | ||
| 435 | check(sh_setsockopt && sh_setsockopt == resolve<SetSockOptFn>("#21"), | ||
| 436 | "setsockopt and #21 resolve to the same shim"); | ||
| 437 | check(sh_join_leaf != nullptr, "WSAJoinLeaf resolves to a shim"); | ||
| 438 | check(ws1_setsockopt && ws1_setsockopt == reinterpret_cast<SetSockOptFn>(rt::shims::find("wsock32.dll", "#21")) && | ||
| 439 | ws1_setsockopt != sh_setsockopt, | ||
| 440 | "wsock32.dll setsockopt and #21 resolve to their own Winsock 1.1 shim"); | ||
| 441 | |||
| 442 | const SOCKET receiver = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); | ||
| 443 | sockaddr_in to = make_v4(127, 0, 0, 1, 0); | ||
| 444 | int to_len = sizeof(to); | ||
| 445 | check(bind(receiver, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 0 && | ||
| 446 | getsockname(receiver, reinterpret_cast<sockaddr*>(&to), &to_len) == 0, | ||
| 447 | "bind a loopback UDP receiver"); | ||
| 448 | const auto local_v4_first_byte = [](SOCKET s) { | ||
| 449 | sockaddr_in local{}; | ||
| 450 | int len = sizeof(local); | ||
| 451 | if (getsockname(s, reinterpret_cast<sockaddr*>(&local), &len) != 0 || local.sin_port == 0) return -1; | ||
| 452 | return static_cast<int>(reinterpret_cast<const uint8_t*>(&local.sin_addr)[0]); | ||
| 453 | }; | ||
| 454 | char payload[] = "ping"; | ||
| 455 | |||
| 456 | const SOCKET control = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); | ||
| 457 | check(sendto(control, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 4 && | ||
| 458 | local_v4_first_byte(control) == 0, | ||
| 459 | "control: the host sendto binds an unbound UDP socket to 0.0.0.0"); | ||
| 460 | const SOCKET unbound = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); | ||
| 461 | check(sh_sendto(unbound, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 4 && | ||
| 462 | local_v4_first_byte(unbound) == 127, | ||
| 463 | "sendto binds an unbound UDP socket to 127.0.0.1 before sending"); | ||
| 464 | const SOCKET unbound_wsa = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); | ||
| 465 | WSABUF wbuf{4, payload}; | ||
| 466 | DWORD sent = 0; | ||
| 467 | check(sh_wsa_sendto(unbound_wsa, &wbuf, 1, &sent, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to), nullptr, | ||
| 468 | nullptr) == 0 && | ||
| 469 | sent == 4 && local_v4_first_byte(unbound_wsa) == 127, | ||
| 470 | "WSASendTo binds an unbound UDP socket to 127.0.0.1 before sending"); | ||
| 471 | check(sh_sendto(unbound, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to), sizeof(to)) == 4 && | ||
| 472 | local_v4_first_byte(unbound) == 127, | ||
| 473 | "a second sendto on the now-bound socket keeps its loopback binding"); | ||
| 474 | |||
| 475 | const SOCKET receiver6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); | ||
| 476 | if (receiver6 != INVALID_SOCKET) { | ||
| 477 | sockaddr_in6 to6{}; | ||
| 478 | to6.sin6_family = AF_INET6; | ||
| 479 | reinterpret_cast<uint8_t*>(&to6.sin6_addr)[15] = 1; // ::1 | ||
| 480 | int to6_len = sizeof(to6); | ||
| 481 | const bool bound6 = bind(receiver6, reinterpret_cast<const sockaddr*>(&to6), sizeof(to6)) == 0 && | ||
| 482 | getsockname(receiver6, reinterpret_cast<sockaddr*>(&to6), &to6_len) == 0; | ||
| 483 | const SOCKET unbound6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); | ||
| 484 | sockaddr_in6 local6{}; | ||
| 485 | int local6_len = sizeof(local6); | ||
| 486 | check(bound6 && sh_sendto(unbound6, payload, 4, 0, reinterpret_cast<const sockaddr*>(&to6), sizeof(to6)) == 4 && | ||
| 487 | getsockname(unbound6, reinterpret_cast<sockaddr*>(&local6), &local6_len) == 0 && | ||
| 488 | reinterpret_cast<const uint8_t*>(&local6.sin6_addr)[15] == 1 && | ||
| 489 | reinterpret_cast<const uint8_t*>(&local6.sin6_addr)[0] == 0, | ||
| 490 | "sendto binds an unbound IPv6 UDP socket to ::1 before sending"); | ||
| 491 | closesocket(unbound6); | ||
| 492 | closesocket(receiver6); | ||
| 493 | } | ||
| 494 | |||
| 495 | // 239.255.0.1 (administratively scoped group); every join is refused before it reaches the host. | ||
| 496 | ip_mreq mreq{}; | ||
| 497 | auto* group = reinterpret_cast<uint8_t*>(&mreq.imr_multiaddr); | ||
| 498 | group[0] = 239; | ||
| 499 | group[1] = 255; | ||
| 500 | group[3] = 1; | ||
| 501 | const auto refused = [](int rc) { return rc == SOCKET_ERROR && WSAGetLastError() == WSAEADDRNOTAVAIL; }; | ||
| 502 | const char* mreq_bytes = reinterpret_cast<const char*>(&mreq); | ||
| 503 | WSASetLastError(0); | ||
| 504 | check(refused(sh_setsockopt(unbound, IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq_bytes, sizeof(mreq))), | ||
| 505 | "setsockopt refuses IP_ADD_MEMBERSHIP with WSAEADDRNOTAVAIL"); | ||
| 506 | WSASetLastError(0); | ||
| 507 | check(refused(sh_setsockopt(unbound, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, mreq_bytes, sizeof(mreq))), | ||
| 508 | "setsockopt refuses IP_ADD_SOURCE_MEMBERSHIP"); | ||
| 509 | WSASetLastError(0); | ||
| 510 | check(refused(sh_setsockopt(unbound, IPPROTO_IP, MCAST_JOIN_GROUP, mreq_bytes, sizeof(mreq))), | ||
| 511 | "setsockopt refuses MCAST_JOIN_GROUP"); | ||
| 512 | WSASetLastError(0); | ||
| 513 | check(refused(sh_setsockopt(unbound, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq_bytes, sizeof(mreq))), | ||
| 514 | "setsockopt refuses IPV6_ADD_MEMBERSHIP"); | ||
| 515 | WSASetLastError(0); | ||
| 516 | check(refused(ws1_setsockopt(unbound, IPPROTO_IP, 5, mreq_bytes, sizeof(mreq))), | ||
| 517 | "wsock32 setsockopt refuses the Winsock 1.1 IP_ADD_MEMBERSHIP (5)"); | ||
| 518 | WSASetLastError(0); | ||
| 519 | check(refused(ws1_setsockopt(unbound, IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq_bytes, sizeof(mreq))), | ||
| 520 | "wsock32 setsockopt refuses the Winsock 2 IP_ADD_MEMBERSHIP (12) it would pass through"); | ||
| 521 | int value = 3; | ||
| 522 | const char* value_bytes = reinterpret_cast<const char*>(&value); | ||
| 523 | check(sh_setsockopt(unbound, IPPROTO_IP, IP_MULTICAST_TTL, value_bytes, sizeof(value)) == 0, | ||
| 524 | "setsockopt passes other IPPROTO_IP options (IP_MULTICAST_TTL)"); | ||
| 525 | check(ws1_setsockopt(unbound, IPPROTO_IP, 7, value_bytes, sizeof(value)) == 0, | ||
| 526 | "wsock32 setsockopt passes the Winsock 1.1 IP_TTL (7) to the host's remap"); | ||
| 527 | value = 65536; | ||
| 528 | check(sh_setsockopt(unbound, SOL_SOCKET, SO_RCVBUF, value_bytes, sizeof(value)) == 0, | ||
| 529 | "setsockopt passes SOL_SOCKET options"); | ||
| 530 | |||
| 531 | const sockaddr_in group_addr = make_v4(239, 255, 0, 1, 5000); | ||
| 532 | WSASetLastError(0); | ||
| 533 | check(sh_join_leaf(unbound, reinterpret_cast<const sockaddr*>(&group_addr), sizeof(group_addr), nullptr, nullptr, | ||
| 534 | nullptr, nullptr, JL_BOTH) == INVALID_SOCKET && | ||
| 535 | WSAGetLastError() == WSAENETUNREACH, | ||
| 536 | "WSAJoinLeaf refuses a multicast group with WSAENETUNREACH"); | ||
| 537 | |||
| 538 | closesocket(unbound_wsa); | ||
| 539 | closesocket(unbound); | ||
| 540 | closesocket(control); | ||
| 541 | closesocket(receiver); | ||
| 542 | } | ||
| 543 | |||
| 544 | WSACleanup(); | ||
| 545 | std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); | ||
| 546 | return g_failures ? 1 : 0; | ||
| 547 | } | ||
diff --git a/runtime/test/xdxr_builder_validation_test.cpp b/runtime/test/xdxr_builder_validation_test.cpp new file mode 100644 index 000000000..5ea6226ff --- /dev/null +++ b/runtime/test/xdxr_builder_validation_test.cpp | |||
| @@ -0,0 +1,183 @@ | |||
| 1 | // Unit tests for XdxrBuilder pre-validation in src/xdxr_build.h (no Vulkan instance, no GPU). | ||
| 2 | // Mismatched geometry sums, null device addresses, uncomputed layouts, and 32-bit overflow counts must fail before | ||
| 3 | // recording any command into the Vulkan command buffer. | ||
| 4 | #include "../src/xdxr_build.h" | ||
| 5 | |||
| 6 | #include <cstdint> | ||
| 7 | #include <cstdio> | ||
| 8 | #include <cstring> | ||
| 9 | #include <type_traits> | ||
| 10 | #include <vector> | ||
| 11 | |||
| 12 | #define CHECK(condition) do { \ | ||
| 13 | if (!(condition)) { \ | ||
| 14 | std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ | ||
| 15 | return 1; \ | ||
| 16 | } \ | ||
| 17 | } while (0) | ||
| 18 | |||
| 19 | namespace { | ||
| 20 | |||
| 21 | template<typename Handle> | ||
| 22 | Handle fake_handle(std::uintptr_t value) { | ||
| 23 | if constexpr (std::is_pointer_v<Handle>) | ||
| 24 | return reinterpret_cast<Handle>(value); | ||
| 25 | else | ||
| 26 | return static_cast<Handle>(value); | ||
| 27 | } | ||
| 28 | |||
| 29 | struct MockRecorder { | ||
| 30 | unsigned binds = 0; | ||
| 31 | unsigned pushes = 0; | ||
| 32 | unsigned dispatches = 0; | ||
| 33 | unsigned barriers = 0; | ||
| 34 | std::uint32_t last_group_count_x = 0; | ||
| 35 | std::uint32_t last_copy_count = 0; | ||
| 36 | |||
| 37 | void reset() { *this = MockRecorder{}; } | ||
| 38 | bool empty() const { return !binds && !pushes && !dispatches && !barriers; } | ||
| 39 | }; | ||
| 40 | |||
| 41 | MockRecorder g_rec; | ||
| 42 | |||
| 43 | VKAPI_ATTR VkResult VKAPI_CALL mock_create_shader_module(VkDevice, const VkShaderModuleCreateInfo*, | ||
| 44 | const VkAllocationCallbacks*, VkShaderModule* out) { | ||
| 45 | *out = fake_handle<VkShaderModule>(1); | ||
| 46 | return VK_SUCCESS; | ||
| 47 | } | ||
| 48 | |||
| 49 | VKAPI_ATTR void VKAPI_CALL mock_destroy_shader_module(VkDevice, VkShaderModule, const VkAllocationCallbacks*) {} | ||
| 50 | |||
| 51 | VKAPI_ATTR VkResult VKAPI_CALL mock_create_pipeline_layout(VkDevice, const VkPipelineLayoutCreateInfo*, | ||
| 52 | const VkAllocationCallbacks*, VkPipelineLayout* out) { | ||
| 53 | *out = fake_handle<VkPipelineLayout>(2); | ||
| 54 | return VK_SUCCESS; | ||
| 55 | } | ||
| 56 | |||
| 57 | VKAPI_ATTR void VKAPI_CALL mock_destroy_pipeline_layout(VkDevice, VkPipelineLayout, const VkAllocationCallbacks*) {} | ||
| 58 | |||
| 59 | VKAPI_ATTR VkResult VKAPI_CALL mock_create_compute_pipelines(VkDevice, VkPipelineCache, std::uint32_t count, | ||
| 60 | const VkComputePipelineCreateInfo*, | ||
| 61 | const VkAllocationCallbacks*, VkPipeline* out) { | ||
| 62 | for (std::uint32_t i = 0; i < count; ++i) out[i] = fake_handle<VkPipeline>(3 + i); | ||
| 63 | return VK_SUCCESS; | ||
| 64 | } | ||
| 65 | |||
| 66 | VKAPI_ATTR void VKAPI_CALL mock_destroy_pipeline(VkDevice, VkPipeline, const VkAllocationCallbacks*) {} | ||
| 67 | |||
| 68 | VKAPI_ATTR void VKAPI_CALL mock_cmd_bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline) { ++g_rec.binds; } | ||
| 69 | |||
| 70 | VKAPI_ATTR void VKAPI_CALL mock_cmd_push_constants(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, | ||
| 71 | std::uint32_t, std::uint32_t size, const void* values) { | ||
| 72 | ++g_rec.pushes; | ||
| 73 | if (size >= 80 && values) { | ||
| 74 | std::uint32_t mode = 0, count = 0; | ||
| 75 | std::memcpy(&mode, static_cast<const std::uint8_t*>(values) + 48, 4); | ||
| 76 | std::memcpy(&count, static_cast<const std::uint8_t*>(values) + 52, 4); | ||
| 77 | if (mode == 12) g_rec.last_copy_count = count; | ||
| 78 | } | ||
| 79 | } | ||
| 80 | |||
| 81 | VKAPI_ATTR void VKAPI_CALL mock_cmd_dispatch(VkCommandBuffer, std::uint32_t x, std::uint32_t, std::uint32_t) { | ||
| 82 | ++g_rec.dispatches; | ||
| 83 | g_rec.last_group_count_x = x; | ||
| 84 | } | ||
| 85 | |||
| 86 | VKAPI_ATTR void VKAPI_CALL mock_cmd_pipeline_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, | ||
| 87 | VkDependencyFlags, std::uint32_t, const VkMemoryBarrier*, | ||
| 88 | std::uint32_t, const VkBufferMemoryBarrier*, std::uint32_t, | ||
| 89 | const VkImageMemoryBarrier*) { | ||
| 90 | ++g_rec.barriers; | ||
| 91 | } | ||
| 92 | |||
| 93 | VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL mock_get_device_proc_addr(VkDevice, const char* name) { | ||
| 94 | if (!name) return nullptr; | ||
| 95 | if (std::strcmp(name, "vkCreateShaderModule") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_create_shader_module); | ||
| 96 | if (std::strcmp(name, "vkDestroyShaderModule") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_destroy_shader_module); | ||
| 97 | if (std::strcmp(name, "vkCreatePipelineLayout") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_create_pipeline_layout); | ||
| 98 | if (std::strcmp(name, "vkDestroyPipelineLayout") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_destroy_pipeline_layout); | ||
| 99 | if (std::strcmp(name, "vkCreateComputePipelines") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_create_compute_pipelines); | ||
| 100 | if (std::strcmp(name, "vkDestroyPipeline") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_destroy_pipeline); | ||
| 101 | if (std::strcmp(name, "vkCmdBindPipeline") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_bind_pipeline); | ||
| 102 | if (std::strcmp(name, "vkCmdPushConstants") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_push_constants); | ||
| 103 | if (std::strcmp(name, "vkCmdDispatch") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_dispatch); | ||
| 104 | if (std::strcmp(name, "vkCmdPipelineBarrier") == 0) return reinterpret_cast<PFN_vkVoidFunction>(mock_cmd_pipeline_barrier); | ||
| 105 | return nullptr; | ||
| 106 | } | ||
| 107 | |||
| 108 | } // namespace | ||
| 109 | |||
| 110 | int main() { | ||
| 111 | using namespace leonida; | ||
| 112 | |||
| 113 | const VkDevice dev = fake_handle<VkDevice>(0x1000); | ||
| 114 | const VkCommandBuffer cb = fake_handle<VkCommandBuffer>(0x2000); | ||
| 115 | XdxrBuilder builder(mock_get_device_proc_addr, dev); | ||
| 116 | CHECK(builder.loaded()); | ||
| 117 | |||
| 118 | XdxrLayout blas1; | ||
| 119 | CHECK(blas1.compute(1, false)); | ||
| 120 | XdxrLayout blas4; | ||
| 121 | CHECK(blas4.compute(4, false)); | ||
| 122 | XdxrLayout tlas0; | ||
| 123 | CHECK(tlas0.compute(0, true)); | ||
| 124 | XdxrLayout tlas4; | ||
| 125 | CHECK(tlas4.compute(4, true)); | ||
| 126 | const XdxrLayout uncomputed{}; | ||
| 127 | |||
| 128 | const std::uint64_t dst = 0x100000; | ||
| 129 | const std::uint64_t scratch = 0x200000; | ||
| 130 | const std::uint64_t instances = 0x300000; | ||
| 131 | |||
| 132 | // 1. Fewer triangles than layout.elements must fail cleanly without recording any commands. | ||
| 133 | g_rec.reset(); | ||
| 134 | CHECK(!builder.record_blas(cb, blas4, {XdxrTriangles{.triangle_count = 3}}, dst, scratch)); | ||
| 135 | CHECK(g_rec.empty()); | ||
| 136 | |||
| 137 | // 2. More triangles than layout.elements must fail cleanly without recording any commands. | ||
| 138 | g_rec.reset(); | ||
| 139 | CHECK(!builder.record_blas(cb, blas4, | ||
| 140 | {XdxrTriangles{.triangle_count = 2}, XdxrTriangles{.triangle_count = 3}}, | ||
| 141 | dst, scratch)); | ||
| 142 | CHECK(g_rec.empty()); | ||
| 143 | |||
| 144 | // 3. Sums that would wrap uint32_t back to layout.elements must be rejected before any dispatch. | ||
| 145 | g_rec.reset(); | ||
| 146 | CHECK(!builder.record_blas(cb, blas1, | ||
| 147 | {XdxrTriangles{.triangle_count = 0x80000001u}, | ||
| 148 | XdxrTriangles{.triangle_count = 0x80000000u}}, | ||
| 149 | dst, scratch)); | ||
| 150 | CHECK(g_rec.empty()); | ||
| 151 | |||
| 152 | // 4. Null addresses, uncomputed layouts, and non-empty TLAS with null instances record nothing. | ||
| 153 | g_rec.reset(); | ||
| 154 | CHECK(!builder.record_blas(cb, blas1, {XdxrTriangles{.triangle_count = 1}}, 0, scratch)); | ||
| 155 | CHECK(!builder.record_blas(cb, blas1, {XdxrTriangles{.triangle_count = 1}}, dst, 0)); | ||
| 156 | CHECK(!builder.record_blas(cb, uncomputed, {}, dst, scratch)); | ||
| 157 | CHECK(!builder.record_tlas(cb, tlas4, instances, 0, scratch)); | ||
| 158 | CHECK(!builder.record_tlas(cb, tlas4, instances, dst, 0)); | ||
| 159 | CHECK(!builder.record_tlas(cb, tlas4, 0, dst, scratch)); | ||
| 160 | CHECK(!builder.record_tlas(cb, uncomputed, instances, dst, scratch)); | ||
| 161 | CHECK(g_rec.empty()); | ||
| 162 | |||
| 163 | // 5. Empty TLAS with null instances pointer is valid and records a build. | ||
| 164 | g_rec.reset(); | ||
| 165 | CHECK(builder.record_tlas(cb, tlas0, 0, dst, scratch)); | ||
| 166 | CHECK(g_rec.binds > 0 && g_rec.dispatches > 0); | ||
| 167 | |||
| 168 | // 6. Valid multi-geometry BLAS records dispatches. | ||
| 169 | g_rec.reset(); | ||
| 170 | CHECK(builder.record_blas(cb, blas4, | ||
| 171 | {XdxrTriangles{.triangle_count = 1}, XdxrTriangles{.triangle_count = 3}}, | ||
| 172 | dst, scratch)); | ||
| 173 | CHECK(g_rec.binds > 0 && g_rec.dispatches > 0 && g_rec.pushes == g_rec.dispatches); | ||
| 174 | |||
| 175 | // 7. Large record_copy dispatches compute group counts without 32-bit overflow. | ||
| 176 | g_rec.reset(); | ||
| 177 | CHECK(builder.record_copy(cb, dst, dst + 0x10000, 0xffffffffull)); | ||
| 178 | CHECK(g_rec.dispatches == 1 && g_rec.last_copy_count == 0x3fffffffu && | ||
| 179 | g_rec.last_group_count_x == (0x3fffffffu + 63u) / 64u); | ||
| 180 | |||
| 181 | std::puts("xdxr_builder_validation: all checks passed"); | ||
| 182 | return 0; | ||
| 183 | } | ||
diff --git a/runtime/test/xdxr_descs_test.cpp b/runtime/test/xdxr_descs_test.cpp index 209fd4fcc..8b857b8d7 100644 --- a/runtime/test/xdxr_descs_test.cpp +++ b/runtime/test/xdxr_descs_test.cpp | |||
| @@ -69,6 +69,19 @@ int stream_lookup() { | |||
| 69 | records[1].type = 0; | 69 | records[1].type = 0; |
| 70 | CHECK(find_stream_record(stream_of(records, 1), 0) == nullptr); | 70 | CHECK(find_stream_record(stream_of(records, 1), 0) == nullptr); |
| 71 | CHECK(find_stream_record(stream_of(records, 2), 0) == &records[1]); | 71 | CHECK(find_stream_record(stream_of(records, 2), 0) == &records[1]); |
| 72 | |||
| 73 | // Trailing bytes shorter than one complete StreamRecord are never read. | ||
| 74 | records[0].type = 0; | ||
| 75 | const size_t small_sizes[] = {1, 4, sizeof(StreamRecord) - 1}; | ||
| 76 | for (size_t bytes : small_sizes) | ||
| 77 | CHECK(find_stream_record(StreamDesc{bytes, records}, 0) == nullptr); | ||
| 78 | records[0].type = 1; | ||
| 79 | records[1].type = 0; | ||
| 80 | const size_t partial_second_sizes[] = {sizeof(StreamRecord) + 1, 2 * sizeof(StreamRecord) - 1}; | ||
| 81 | for (size_t bytes : partial_second_sizes) { | ||
| 82 | CHECK(find_stream_record(StreamDesc{bytes, records}, 1) == &records[0]); | ||
| 83 | CHECK(find_stream_record(StreamDesc{bytes, records}, 0) == nullptr); | ||
| 84 | } | ||
| 72 | return 0; | 85 | return 0; |
| 73 | } | 86 | } |
| 74 | 87 | ||
diff --git a/runtime/test/xgameruntime_offline_test.cpp b/runtime/test/xgameruntime_offline_test.cpp index 7668b6164..66b110054 100644 --- a/runtime/test/xgameruntime_offline_test.cpp +++ b/runtime/test/xgameruntime_offline_test.cpp | |||
| @@ -8,6 +8,7 @@ | |||
| 8 | #include <cstdio> | 8 | #include <cstdio> |
| 9 | #include <cstdlib> | 9 | #include <cstdlib> |
| 10 | #include <cstring> | 10 | #include <cstring> |
| 11 | #include <string> | ||
| 11 | 12 | ||
| 12 | #include <XAsync.h> | 13 | #include <XAsync.h> |
| 13 | #include <XAsyncProvider.h> | 14 | #include <XAsyncProvider.h> |
| @@ -74,7 +75,16 @@ constexpr GUID kAccessibilityClass = {0x3e241977, 0x6237, 0x41e9, {0x85, 0x59, 0 | |||
| 74 | constexpr GUID kAccessibility2 = {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}}; | 75 | constexpr GUID kAccessibility2 = {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}}; |
| 75 | constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; | 76 | constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; |
| 76 | 77 | ||
| 77 | using EnumVoices = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*); | 78 | struct VoiceInformation { // XSpeechSynthesizerVoiceInformation, the GDK reference's member order |
| 79 | const char* description; | ||
| 80 | const char* display_name; | ||
| 81 | uint32_t gender; | ||
| 82 | const char* voice_id; | ||
| 83 | const char* language; | ||
| 84 | }; | ||
| 85 | using VoiceCallback = bool(CALLBACK*)(const VoiceInformation*, void*); | ||
| 86 | using EnumVoices = HRESULT(STDMETHODCALLTYPE*)(void*, void* context, VoiceCallback callback); | ||
| 87 | using SetCustomVoice = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*); | ||
| 78 | using SpeechCreate = HRESULT(STDMETHODCALLTYPE*)(void*, void**); | 88 | using SpeechCreate = HRESULT(STDMETHODCALLTYPE*)(void*, void**); |
| 79 | using SpeechClose = HRESULT(STDMETHODCALLTYPE*)(void*, void*); | 89 | using SpeechClose = HRESULT(STDMETHODCALLTYPE*)(void*, void*); |
| 80 | using SpeechStream = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*, void**); | 90 | using SpeechStream = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*, void**); |
| @@ -93,6 +103,19 @@ void* user_object(HRESULT(WINAPI* query)(const GUID*, REFIID, void**)) { | |||
| 93 | 103 | ||
| 94 | void CALLBACK on_state(void*, uint64_t, uint32_t) {} | 104 | void CALLBACK on_state(void*, uint64_t, uint32_t) {} |
| 95 | 105 | ||
| 106 | struct VoicesSeen { | ||
| 107 | int count = 0; | ||
| 108 | std::string voice_id; | ||
| 109 | std::string language; | ||
| 110 | }; | ||
| 111 | bool CALLBACK on_voice(const VoiceInformation* info, void* context) { | ||
| 112 | auto* seen = static_cast<VoicesSeen*>(context); | ||
| 113 | ++seen->count; | ||
| 114 | seen->voice_id = info && info->voice_id ? info->voice_id : ""; | ||
| 115 | seen->language = info && info->language ? info->language : ""; | ||
| 116 | return true; | ||
| 117 | } | ||
| 118 | |||
| 96 | // XUserDeviceImpl slots 4/5 (device association) and 7/8 (default audio endpoint): kept until unregistered, never | 119 | // XUserDeviceImpl slots 4/5 (device association) and 7/8 (default audio endpoint): kept until unregistered, never |
| 97 | // called back offline. | 120 | // called back offline. |
| 98 | long g_device_callbacks = 0; | 121 | long g_device_callbacks = 0; |
| @@ -290,22 +313,45 @@ int main() { | |||
| 290 | "XHighContrastGetMode reports Off"); | 313 | "XHighContrastGetMode reports Off"); |
| 291 | check(at<SetEnabled>(acc, 4)(acc, true) == S_OK, "XClosedCaptionSetEnabled is accepted"); | 314 | check(at<SetEnabled>(acc, 4)(acc, true) == S_OK, "XClosedCaptionSetEnabled is accepted"); |
| 292 | check(FAILED(at<NoArgs>(acc, 3)(acc)), "the closed-caption properties are not available offline"); | 315 | check(FAILED(at<NoArgs>(acc, 3)(acc)), "the closed-caption properties are not available offline"); |
| 293 | check(at<EnumVoices>(acc, 8)(acc, reinterpret_cast<void*>(&on_state), nullptr) == S_OK && | 316 | VoicesSeen seen; |
| 294 | at<EnumVoices>(acc, 8)(acc, nullptr, nullptr) == E_INVALIDARG, | 317 | check(at<EnumVoices>(acc, 8)(acc, &seen, &on_voice) == S_OK && seen.count == 1 && |
| 295 | "XSpeechSynthesizerEnumerateInstalledVoices: no voices, S_OK (a callback is required)"); | 318 | seen.voice_id == "leonida-silent" && seen.language == "en-US", |
| 296 | void* synth = reinterpret_cast<void*>(1); | 319 | "XSpeechSynthesizerEnumerateInstalledVoices(context, callback): one silent voice, its context passed back"); |
| 297 | check(at<SpeechCreate>(acc, 9)(acc, &synth) == E_FAIL && synth == nullptr, | 320 | check(at<EnumVoices>(acc, 8)(acc, nullptr, nullptr) == E_INVALIDARG, |
| 298 | "XSpeechSynthesizerCreate fails offline and nulls the handle"); | 321 | "XSpeechSynthesizerEnumerateInstalledVoices: a callback is required"); |
| 299 | void* stream = reinterpret_cast<void*>(1); | 322 | void* synth = nullptr; |
| 300 | size_t size = 5, got = 5; | 323 | check(at<SpeechCreate>(acc, 9)(acc, &synth) == S_OK && synth != nullptr && |
| 324 | at<SpeechCreate>(acc, 9)(acc, nullptr) == E_POINTER, | ||
| 325 | "XSpeechSynthesizerCreate returns a silent synthesizer handle"); | ||
| 326 | void* stream = nullptr; | ||
| 327 | size_t size = 0, got = 0; | ||
| 301 | check(at<SpeechClose>(acc, 10)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 11)(acc, nullptr) == E_INVALIDARG && | 328 | check(at<SpeechClose>(acc, 10)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 11)(acc, nullptr) == E_INVALIDARG && |
| 302 | at<SpeechClose>(acc, 12)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 14)(acc, nullptr) == E_INVALIDARG, | 329 | at<SpeechClose>(acc, 12)(acc, nullptr) == E_INVALIDARG && at<SpeechClose>(acc, 14)(acc, nullptr) == E_INVALIDARG, |
| 303 | "close and set-voice calls on a null handle: E_INVALIDARG"); | 330 | "close and set-voice calls on a null handle: E_INVALIDARG"); |
| 331 | check(at<SpeechClose>(acc, 11)(acc, synth) == S_OK, "XSpeechSynthesizerSetDefaultVoice succeeds on valid handle"); | ||
| 332 | check(at<SetCustomVoice>(acc, 12)(acc, synth, seen.voice_id.c_str()) == S_OK && | ||
| 333 | at<SetCustomVoice>(acc, 12)(acc, synth, "not-installed") == E_INVALIDARG && | ||
| 334 | at<SetCustomVoice>(acc, 12)(acc, synth, nullptr) == E_INVALIDARG, | ||
| 335 | "XSpeechSynthesizerSetCustomVoice accepts the enumerated voice only"); | ||
| 304 | check(at<SpeechStream>(acc, 13)(acc, nullptr, "hi", &stream) == E_INVALIDARG && stream == nullptr, | 336 | check(at<SpeechStream>(acc, 13)(acc, nullptr, "hi", &stream) == E_INVALIDARG && stream == nullptr, |
| 305 | "CreateStreamFromText on a null synthesizer: E_INVALIDARG, no stream"); | 337 | "CreateStreamFromText on a null synthesizer: E_INVALIDARG, no stream"); |
| 306 | stream = reinterpret_cast<void*>(1); | 338 | check(at<SpeechStream>(acc, 13)(acc, synth, "Hello", &stream) == S_OK && stream != nullptr, |
| 307 | check(at<SpeechStream>(acc, 21)(acc, nullptr, "<speak/>", &stream) == E_INVALIDARG && stream == nullptr, | 339 | "CreateStreamFromText returns a silent WAVE stream"); |
| 308 | "CreateStreamFromSsml on a null synthesizer: E_INVALIDARG, no stream"); | 340 | check(at<StreamSize>(acc, 15)(acc, stream, &size) == S_OK && size == 44, |
| 341 | "GetStreamDataSize reports the 44-byte empty WAVE header"); | ||
| 342 | uint8_t wav[64] = {}; | ||
| 343 | check(at<StreamData>(acc, 16)(acc, stream, 8, wav, &got) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && got == 0, | ||
| 344 | "GetStreamData rejects an undersized buffer with ERROR_INSUFFICIENT_BUFFER"); | ||
| 345 | check(at<StreamData>(acc, 16)(acc, stream, sizeof(wav), wav, &got) == S_OK && got == 44 && | ||
| 346 | std::memcmp(wav, "RIFF", 4) == 0 && std::memcmp(wav + 8, "WAVEfmt ", 8) == 0 && | ||
| 347 | std::memcmp(wav + 36, "data", 4) == 0, | ||
| 348 | "GetStreamData writes a valid silent 16 kHz mono 16-bit PCM WAVE header"); | ||
| 349 | check(at<SpeechClose>(acc, 14)(acc, stream) == S_OK, "XSpeechSynthesizerCloseStreamHandle succeeds"); | ||
| 350 | stream = nullptr; | ||
| 351 | check(at<SpeechStream>(acc, 21)(acc, synth, "<speak/>", &stream) == S_OK && stream != nullptr && | ||
| 352 | at<SpeechClose>(acc, 14)(acc, stream) == S_OK, | ||
| 353 | "CreateStreamFromSsml returns a silent WAVE stream"); | ||
| 354 | check(at<SpeechClose>(acc, 10)(acc, synth) == S_OK, "XSpeechSynthesizerCloseHandle succeeds"); | ||
| 309 | check(at<StreamSize>(acc, 15)(acc, nullptr, &size) == E_INVALIDARG && size == 0 && | 355 | check(at<StreamSize>(acc, 15)(acc, nullptr, &size) == E_INVALIDARG && size == 0 && |
| 310 | at<StreamData>(acc, 16)(acc, nullptr, 8, nullptr, &got) == E_INVALIDARG && got == 0, | 356 | at<StreamData>(acc, 16)(acc, nullptr, 8, nullptr, &got) == E_INVALIDARG && got == 0, |
| 311 | "stream size and data on a null stream: E_INVALIDARG, zero written"); | 357 | "stream size and data on a null stream: E_INVALIDARG, zero written"); |
| @@ -317,12 +363,17 @@ int main() { | |||
| 317 | void* launcher = nullptr; | 363 | void* launcher = nullptr; |
| 318 | check(query(&kLauncherClass, kLauncherClass, &launcher) == S_OK && launcher, "XLauncherImpl for its class id"); | 364 | check(query(&kLauncherClass, kLauncherClass, &launcher) == S_OK && launcher, "XLauncherImpl for its class id"); |
| 319 | if (!launcher) return 1; | 365 | if (!launcher) return 1; |
| 320 | void* deferral = reinterpret_cast<void*>(1); | 366 | void* deferral = nullptr; |
| 367 | using CloseDeferral = void(STDMETHODCALLTYPE*)(void*, void*); | ||
| 321 | check(at<LaunchUri>(launcher, 3)(launcher, nullptr, "https://example.com") == E_FAIL, | 368 | check(at<LaunchUri>(launcher, 3)(launcher, nullptr, "https://example.com") == E_FAIL, |
| 322 | "XLaunchUri is not available offline"); | 369 | "XLaunchUri is not available offline"); |
| 323 | check(at<AcquireDeferral>(launcher, 4)(launcher, &deferral) == E_FAIL && deferral == nullptr && | 370 | check(at<AcquireDeferral>(launcher, 4)(launcher, nullptr) == E_POINTER, |
| 324 | at<NoArgs>(launcher, 5)(launcher) == E_FAIL, | 371 | "XDisplayAcquireTimeoutDeferral rejects null out pointer"); |
| 325 | "the display timeout deferral is not available offline"); | 372 | check(at<AcquireDeferral>(launcher, 4)(launcher, &deferral) == S_OK && deferral != nullptr, |
| 373 | "XDisplayAcquireTimeoutDeferral acquires a display power request handle"); | ||
| 374 | at<CloseDeferral>(launcher, 5)(launcher, deferral); | ||
| 375 | at<CloseDeferral>(launcher, 5)(launcher, nullptr); | ||
| 376 | check(true, "XDisplayCloseTimeoutDeferralHandle closes handle and ignores null"); | ||
| 326 | GUID other = kLauncherClass; | 377 | GUID other = kLauncherClass; |
| 327 | other.Data1 ^= 1; | 378 | other.Data1 ^= 1; |
| 328 | void* none = reinterpret_cast<void*>(1); | 379 | void* none = reinterpret_cast<void*>(1); |
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 224030247..888bedf24 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp | |||
| @@ -91,6 +91,8 @@ struct Mock { | |||
| 91 | bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do | 91 | bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do |
| 92 | bool create_null; // device: creation returns create_result with no object | 92 | bool create_null; // device: creation returns create_result with no object |
| 93 | HRESULT create_result; // device: what creation returns (S_OK makes the object) | 93 | HRESULT create_result; // device: what creation returns (S_OK makes the object) |
| 94 | bool list_refuse; // device: CreateCommandList refuses every riid with E_NOINTERFACE | ||
| 95 | IID create_riid; // device: copy of the riid its last CreateCommandList got (the caller's may be a local) | ||
| 94 | Mock* last_child; // device: the object its last creation or open made | 96 | Mock* last_child; // device: the object its last creation or open made |
| 95 | unsigned calls[kMockSlots]; | 97 | unsigned calls[kMockSlots]; |
| 96 | std::uint64_t args[kMockSlots][5]; | 98 | std::uint64_t args[kMockSlots][5]; |
| @@ -276,8 +278,10 @@ HRESULT WINAPI mock_create_command_list(Mock* self, std::uint64_t node_mask, std | |||
| 276 | self->args[12][2] = allocator; | 278 | self->args[12][2] = allocator; |
| 277 | self->args[12][3] = initial_state; | 279 | self->args[12][3] = initial_state; |
| 278 | self->args[12][4] = reinterpret_cast<std::uint64_t>(riid); | 280 | self->args[12][4] = reinterpret_cast<std::uint64_t>(riid); |
| 281 | if (riid) self->create_riid = *riid; | ||
| 279 | if (!out) return S_FALSE; | 282 | if (!out) return S_FALSE; |
| 280 | *out = nullptr; | 283 | *out = nullptr; |
| 284 | if (self->list_refuse) return E_NOINTERFACE; | ||
| 281 | if (self->create_null || FAILED(self->create_result)) return self->create_result; | 285 | if (self->create_null || FAILED(self->create_result)) return self->create_result; |
| 282 | Mock* child = new_mock(Kind::command_list); | 286 | Mock* child = new_mock(Kind::command_list); |
| 283 | child->list_level = self->list_level; | 287 | child->list_level = self->list_level; |
| @@ -981,17 +985,27 @@ int check_xbox_slots() { | |||
| 981 | 985 | ||
| 982 | // ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- | 986 | // ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- |
| 983 | 987 | ||
| 988 | struct EnvPresenter { | ||
| 989 | int stats = 0, present = 0, suspend = 0, resume = 0; | ||
| 990 | }; | ||
| 991 | |||
| 984 | int run_env_slots(bool valid) { | 992 | int run_env_slots(bool valid) { |
| 985 | const char* frame_interval = valid ? "96" : "2"; | 993 | const char* frame_interval = valid ? "96" : "2"; |
| 986 | const char* schedule_event = valid ? "97" : "2"; | 994 | const char* schedule_event = valid ? "97" : "2"; |
| 987 | const char* wait_event = valid ? "98" : "2"; | 995 | const char* wait_event = valid ? "98" : "2"; |
| 988 | const char* queue_x = valid ? "99" : "2"; | 996 | const char* queue_x = valid ? "99" : "2"; |
| 989 | const char* list_x = valid ? "100" : "2"; | 997 | const char* list_x = valid ? "100" : "2"; |
| 998 | const char* frame_statistics = valid ? "101" : "2"; | ||
| 999 | const char* suspend_x = valid ? "33" : "2"; // a queue slot beyond the PC table, as SuspendX would be | ||
| 1000 | const char* resume_x = valid ? "30" : "2"; // equal to PresentX's default: ResumeX is unrouted (logged) | ||
| 990 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_INTERVAL_SLOT", frame_interval) != FALSE); | 1001 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_INTERVAL_SLOT", frame_interval) != FALSE); |
| 991 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SCHEDULE_EVENT_SLOT", schedule_event) != FALSE); | 1002 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SCHEDULE_EVENT_SLOT", schedule_event) != FALSE); |
| 992 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_WAIT_EVENT_SLOT", wait_event) != FALSE); | 1003 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_WAIT_EVENT_SLOT", wait_event) != FALSE); |
| 1004 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_STATISTICS_SLOT", frame_statistics) != FALSE); | ||
| 993 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_QUEUE_X_SLOT", queue_x) != FALSE); | 1005 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_QUEUE_X_SLOT", queue_x) != FALSE); |
| 994 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_LIST_X_SLOT", list_x) != FALSE); | 1006 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_LIST_X_SLOT", list_x) != FALSE); |
| 1007 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_SUSPEND_X_SLOT", suspend_x) != FALSE); | ||
| 1008 | EXPECT(SetEnvironmentVariableA("LEONIDA_XS_RESUME_X_SLOT", resume_x) != FALSE); | ||
| 995 | 1009 | ||
| 996 | Mock* mock = nullptr; | 1010 | Mock* mock = nullptr; |
| 997 | void* device = make_device(mock, 11, true); | 1011 | void* device = make_device(mock, 11, true); |
| @@ -1018,6 +1032,36 @@ int run_env_slots(bool valid) { | |||
| 1018 | EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1); | 1032 | EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1); |
| 1019 | EXPECT(release(list) == 0); | 1033 | EXPECT(release(list) == 0); |
| 1020 | EXPECT(release(allocator) == 0); | 1034 | EXPECT(release(allocator) == 0); |
| 1035 | |||
| 1036 | // The presenter answers frame statistics at 101 only (81 is not routed, so the mock refuses it); PresentX | ||
| 1037 | // stays at 30, SuspendX answers at 33, and ResumeX, asked for 30, is unrouted, so 32 is refused. | ||
| 1038 | EnvPresenter env{}; | ||
| 1039 | xs::PresentationHandler h{}; | ||
| 1040 | h.context = &env; | ||
| 1041 | h.get_frame_statistics = [](void* ctx, std::uint64_t, UINT, UINT*, void*) -> HRESULT { | ||
| 1042 | ++static_cast<EnvPresenter*>(ctx)->stats; | ||
| 1043 | return S_FALSE; | ||
| 1044 | }; | ||
| 1045 | h.present_x = [](void* ctx, UINT, const void*, const void*) -> HRESULT { | ||
| 1046 | ++static_cast<EnvPresenter*>(ctx)->present; | ||
| 1047 | return S_OK; | ||
| 1048 | }; | ||
| 1049 | h.suspend_x = [](void* ctx, UINT) -> HRESULT { | ||
| 1050 | ++static_cast<EnvPresenter*>(ctx)->suspend; | ||
| 1051 | return S_OK; | ||
| 1052 | }; | ||
| 1053 | h.resume_x = [](void* ctx) -> HRESULT { | ||
| 1054 | ++static_cast<EnvPresenter*>(ctx)->resume; | ||
| 1055 | return S_OK; | ||
| 1056 | }; | ||
| 1057 | EXPECT(xs::set_presentation_handler(device, &h)); | ||
| 1058 | UINT count = 0; | ||
| 1059 | EXPECT(hr_of(raw(device, 101, 77, 0x1a, word(&count), 0)) == S_FALSE && env.stats == 1); | ||
| 1060 | EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == E_NOTIMPL && env.stats == 1); | ||
| 1061 | EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == S_OK && env.present == 1); | ||
| 1062 | EXPECT(hr_of(raw(queue, 33)) == S_OK && env.suspend == 1); | ||
| 1063 | EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && env.resume == 0); | ||
| 1064 | EXPECT(xs::set_presentation_handler(device, nullptr)); | ||
| 1021 | EXPECT(release(queue) == 0); | 1065 | EXPECT(release(queue) == 0); |
| 1022 | } else { | 1066 | } else { |
| 1023 | // Values outside 3..127 are ignored: the five defaults still answer, and a PC slot that is not a default is | 1067 | // Values outside 3..127 are ignored: the five defaults still answer, and a PC slot that is not a default is |
| @@ -1025,6 +1069,7 @@ int run_env_slots(bool valid) { | |||
| 1025 | EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 0); | 1069 | EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 0); |
| 1026 | EXPECT(hr_of(raw(device, 79, 0, 0, 0, 0)) == S_OK && mock->calls[79] == 0); | 1070 | EXPECT(hr_of(raw(device, 79, 0, 0, 0, 0)) == S_OK && mock->calls[79] == 0); |
| 1027 | EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[80] == 0); | 1071 | EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[80] == 0); |
| 1072 | EXPECT(hr_of(raw(device, 81, 0, 0, 0, 0)) == S_FALSE); // the default GetFrameStatisticsX slot, unattached | ||
| 1028 | EXPECT(hr_of(raw(device, 71)) == S_OK && mock->calls[71] == 1); // not an Xbox slot: forwarded | 1073 | EXPECT(hr_of(raw(device, 71)) == S_OK && mock->calls[71] == 1); // not an Xbox slot: forwarded |
| 1029 | } | 1074 | } |
| 1030 | EXPECT(release(device) == 0 && mock->refs == 0); | 1075 | EXPECT(release(device) == 0 && mock->refs == 0); |
| @@ -1504,6 +1549,39 @@ int check_console_command_list() { | |||
| 1504 | EXPECT(real_queue->array[10][0] == word(unwrapped_list)); | 1549 | EXPECT(real_queue->array[10][0] == word(unwrapped_list)); |
| 1505 | EXPECT(real_queue->array[10][1] == word(real_list)); | 1550 | EXPECT(real_queue->array[10][1] == word(real_list)); |
| 1506 | 1551 | ||
| 1552 | // 5b. Public list revisions the proxy does not model and unknown private IIDs must not trigger a retry. | ||
| 1553 | // Spell out the Windows SDK's ID3D12GraphicsCommandList9 IID so this also builds with older headers. | ||
| 1554 | const IID list9_iid = {0x34ed2808, 0xffe6, 0x4c2b, {0xb1, 0x1a, 0xca, 0xbd, 0x2b, 0x0c, 0x59, 0xe1}}; | ||
| 1555 | const IID unknown_iid = {0x12345678, 0x1234, 0x1234, {1, 2, 3, 4, 5, 6, 7, 8}}; | ||
| 1556 | for (const IID* iid : {&list9_iid, &unknown_iid}) { | ||
| 1557 | const unsigned calls_before = mock_device->calls[12]; | ||
| 1558 | void* unsupported_list = list_proxy; | ||
| 1559 | EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(iid), word(&unsupported_list))) == | ||
| 1560 | E_NOINTERFACE); | ||
| 1561 | EXPECT(!unsupported_list && mock_device->calls[12] == calls_before + 1); | ||
| 1562 | } | ||
| 1563 | |||
| 1564 | // The measured Xbox list IID is created as ID3D12GraphicsCommandList in one call and stays queryable on the proxy. | ||
| 1565 | const IID console_iid = {0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}}; | ||
| 1566 | const unsigned calls12_before = mock_device->calls[12]; | ||
| 1567 | void* console_list = nullptr; | ||
| 1568 | EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&console_iid), word(&console_list))) == S_OK); | ||
| 1569 | EXPECT(xs::is_command_list_proxy(console_list) && mock_device->calls[12] == calls12_before + 1); | ||
| 1570 | EXPECT(IsEqualIID(mock_device->create_riid, __uuidof(ID3D12GraphicsCommandList))); | ||
| 1571 | void* console_list_qi = nullptr; | ||
| 1572 | EXPECT(hr_of(raw(console_list, 0, word(&console_iid), word(&console_list_qi))) == S_OK); | ||
| 1573 | EXPECT(console_list_qi == console_list && release(console_list_qi) == 1); | ||
| 1574 | EXPECT(release(console_list) == 0); | ||
| 1575 | |||
| 1576 | // The PC device refuses even ID3D12GraphicsCommandList for a PC IID: E_NOINTERFACE comes back as is, no retry. | ||
| 1577 | mock_device->list_refuse = true; | ||
| 1578 | const unsigned calls12_refused = mock_device->calls[12]; | ||
| 1579 | console_list = nullptr; | ||
| 1580 | EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&console_list))) == | ||
| 1581 | E_NOINTERFACE); | ||
| 1582 | EXPECT(!console_list && mock_device->calls[12] == calls12_refused + 1); | ||
| 1583 | mock_device->list_refuse = false; | ||
| 1584 | |||
| 1507 | // 6. Test with list_level = 7 (supporting ID3D12GraphicsCommandList7, 81 slots) | 1585 | // 6. Test with list_level = 7 (supporting ID3D12GraphicsCommandList7, 81 slots) |
| 1508 | mock_device->list_level = 7; | 1586 | mock_device->list_level = 7; |
| 1509 | void* list7_proxy = nullptr; | 1587 | void* list7_proxy = nullptr; |
| @@ -1534,6 +1612,99 @@ int check_console_command_list() { | |||
| 1534 | return 0; | 1612 | return 0; |
| 1535 | } | 1613 | } |
| 1536 | 1614 | ||
| 1615 | // ---- 11. Presentation handler wiring (device slots 78–81 + queue PresentX/SuspendX/ResumeX) ---- | ||
| 1616 | |||
| 1617 | struct MockPresenter { | ||
| 1618 | int interval_calls = 0; | ||
| 1619 | UINT last_interval = 0; | ||
| 1620 | int schedule_calls = 0; | ||
| 1621 | UINT last_event = 0; | ||
| 1622 | int wait_calls = 0; | ||
| 1623 | UINT last_flags = 0; | ||
| 1624 | int stats_calls = 0; | ||
| 1625 | int present_calls = 0; | ||
| 1626 | UINT last_planes = 0; | ||
| 1627 | int suspend_calls = 0; | ||
| 1628 | int resume_calls = 0; | ||
| 1629 | }; | ||
| 1630 | |||
| 1631 | int check_presentation_wiring() { | ||
| 1632 | Mock* mock = nullptr; | ||
| 1633 | void* device = make_device(mock, 11, true); | ||
| 1634 | EXPECT(device != nullptr); | ||
| 1635 | void* queue = make_queue(device); | ||
| 1636 | EXPECT(queue != nullptr); | ||
| 1637 | |||
| 1638 | MockPresenter p{}; | ||
| 1639 | xs::PresentationHandler h{}; | ||
| 1640 | h.context = &p; | ||
| 1641 | h.set_frame_interval = [](void* ctx, IUnknown*, UINT us, UINT, UINT) -> HRESULT { | ||
| 1642 | auto* m = static_cast<MockPresenter*>(ctx); | ||
| 1643 | ++m->interval_calls; | ||
| 1644 | m->last_interval = us; | ||
| 1645 | return S_OK; | ||
| 1646 | }; | ||
| 1647 | h.schedule_frame_event = [](void* ctx, UINT ev, UINT, UINT) -> HRESULT { | ||
| 1648 | auto* m = static_cast<MockPresenter*>(ctx); | ||
| 1649 | ++m->schedule_calls; | ||
| 1650 | m->last_event = ev; | ||
| 1651 | return S_OK; | ||
| 1652 | }; | ||
| 1653 | h.wait_frame_event = [](void* ctx, UINT, DWORD, UINT flags, std::uint64_t* tok) -> HRESULT { | ||
| 1654 | auto* m = static_cast<MockPresenter*>(ctx); | ||
| 1655 | ++m->wait_calls; | ||
| 1656 | m->last_flags = flags; | ||
| 1657 | if (tok) *tok = 77; | ||
| 1658 | return S_FALSE; | ||
| 1659 | }; | ||
| 1660 | h.get_frame_statistics = [](void* ctx, std::uint64_t, UINT, UINT* count, void*) -> HRESULT { | ||
| 1661 | auto* m = static_cast<MockPresenter*>(ctx); | ||
| 1662 | ++m->stats_calls; | ||
| 1663 | if (count) *count = 0; | ||
| 1664 | return S_FALSE; | ||
| 1665 | }; | ||
| 1666 | h.present_x = [](void* ctx, UINT plane_count, const void*, const void*) -> HRESULT { | ||
| 1667 | auto* m = static_cast<MockPresenter*>(ctx); | ||
| 1668 | ++m->present_calls; | ||
| 1669 | m->last_planes = plane_count; | ||
| 1670 | return S_OK; | ||
| 1671 | }; | ||
| 1672 | h.suspend_x = [](void* ctx, UINT) -> HRESULT { | ||
| 1673 | ++static_cast<MockPresenter*>(ctx)->suspend_calls; | ||
| 1674 | return S_OK; | ||
| 1675 | }; | ||
| 1676 | h.resume_x = [](void* ctx) -> HRESULT { | ||
| 1677 | ++static_cast<MockPresenter*>(ctx)->resume_calls; | ||
| 1678 | return S_OK; | ||
| 1679 | }; | ||
| 1680 | |||
| 1681 | EXPECT(xs::set_presentation_handler(device, &h)); | ||
| 1682 | EXPECT(hr_of(raw(device, 78, 0, 33333, 2, 0)) == S_OK && p.interval_calls == 1 && p.last_interval == 33333); | ||
| 1683 | EXPECT(hr_of(raw(device, 79, 2, 0, 0, 0)) == S_OK && p.schedule_calls == 1 && p.last_event == 2); | ||
| 1684 | std::uint64_t tok = 0; | ||
| 1685 | EXPECT(hr_of(raw(device, 80, 0, 0, 0, 2, word(&tok))) == S_FALSE && tok == 77 && p.wait_calls == 1 && | ||
| 1686 | p.last_flags == 2); | ||
| 1687 | UINT count = 3; | ||
| 1688 | EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == S_FALSE && count == 0 && p.stats_calls == 1); | ||
| 1689 | |||
| 1690 | // Queue slot 30 routes to PresentX while attached. SuspendX and ResumeX have no default route, so 31/32 are refused | ||
| 1691 | // and never reach the presenter (the env mode, run_env_slots, routes them). | ||
| 1692 | EXPECT(hr_of(raw(queue, 30, 1, 0x1000, 0x2000)) == S_OK && p.present_calls == 1 && p.last_planes == 1); | ||
| 1693 | EXPECT(hr_of(raw(queue, 31, 0)) == E_NOTIMPL && p.suspend_calls == 0); | ||
| 1694 | EXPECT(hr_of(raw(queue, 32)) == E_NOTIMPL && p.resume_calls == 0); | ||
| 1695 | |||
| 1696 | // Detaching restores default E_NOTIMPL refusal on beyond-PC queue slots. | ||
| 1697 | EXPECT(xs::set_presentation_handler(device, nullptr)); | ||
| 1698 | UINT none = 7; // unattached GetFrameStatisticsX: no statistics yet, never the PC slot 81 | ||
| 1699 | EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&none), 0)) == S_FALSE && none == 0 && p.stats_calls == 1); | ||
| 1700 | EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == E_NOTIMPL && p.present_calls == 1); | ||
| 1701 | |||
| 1702 | EXPECT(release(queue) == 0); | ||
| 1703 | EXPECT(release(device) == 0 && mock->refs == 0); | ||
| 1704 | std::printf("%s: presentation handler wiring (slots 78-81 and queue PresentX 30) passed\n", g_label); | ||
| 1705 | return 0; | ||
| 1706 | } | ||
| 1707 | |||
| 1537 | int main(int argc, char** argv) { | 1708 | int main(int argc, char** argv) { |
| 1538 | no_dialogs(); | 1709 | no_dialogs(); |
| 1539 | std::setvbuf(stdout, nullptr, _IONBF, 0); | 1710 | std::setvbuf(stdout, nullptr, _IONBF, 0); |
| @@ -1546,7 +1717,8 @@ int main(int argc, char** argv) { | |||
| 1546 | if (check_tail(true) || check_levels() || check_slot48() || check_fence1() || check_create_failures() || check_open_shared() || | 1717 | if (check_tail(true) || check_levels() || check_slot48() || check_fence1() || check_create_failures() || check_open_shared() || |
| 1547 | check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() || | 1718 | check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() || |
| 1548 | check_custom_heap_properties() || | 1719 | check_custom_heap_properties() || |
| 1549 | check_resource_allocation_info() || check_slot70() || check_committed_resource3_x()) | 1720 | check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() || |
| 1721 | check_presentation_wiring()) | ||
| 1550 | return 1; | 1722 | return 1; |
| 1551 | std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); | 1723 | std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); |
| 1552 | return 0; | 1724 | return 0; |
diff --git a/runtime/xma_decoder/README.md b/runtime/xma_decoder/README.md index 4a6d5fb10..9db801810 100644 --- a/runtime/xma_decoder/README.md +++ b/runtime/xma_decoder/README.md | |||
| @@ -6,8 +6,6 @@ Each decoder handle serializes decode calls. The returned PCM block owns its sam | |||
| 6 | 6 | ||
| 7 | The tests build packets in memory; they do not open or contain audio fixtures. The synthetic C++ smoke test verifies the exported ABI and ownership boundary. | 7 | The tests build packets in memory; they do not open or contain audio fixtures. The synthetic C++ smoke test verifies the exported ABI and ownership boundary. |
| 8 | 8 | ||
| 9 | This PR adds the decoder boundary only; the Windows XAudio2 engine/source-voice adapter is a follow-up stage. | ||
| 10 | |||
| 11 | Run: | 9 | Run: |
| 12 | 10 | ||
| 13 | ```powershell | 11 | ```powershell |
| @@ -17,3 +15,12 @@ cargo build --manifest-path runtime/xma_decoder/Cargo.toml --locked | |||
| 17 | ``` | 15 | ``` |
| 18 | 16 | ||
| 19 | The C++ smoke test is run by the xma2-decoder workflow with MSVC. It links ws2_32, userenv, and ntdll for Rust's Windows standard library. | 17 | The C++ smoke test is run by the xma2-decoder workflow with MSVC. It links ws2_32, userenv, and ntdll for Rust's Windows standard library. |
| 18 | |||
| 19 | ## Use in the runtime | ||
| 20 | |||
| 21 | `runtime/CMakeLists.txt` builds this crate for `x86_64-pc-windows-msvc` at configure time when `cargo` is on `PATH` and links it into `gta6rt` and `acphal_test` with `LEONIDA_HAVE_XMA2_DECODER` defined. The first build fetches the pinned `xma` git dependency. Set `CARGO_NET_OFFLINE=true` for a configure that uses only the local Cargo cache. | ||
| 22 | |||
| 23 | `runtime/shims/acphal.cpp` uses `leonida_xma2_decoder_create_hardware` and decodes whole 2048-byte packets, so loop points are rounded to packets. The shim creates a fresh decoder after a loop rewind or a decoder error. | ||
| 24 | |||
| 25 | Without `cargo`, when that build fails, or with the cl.exe fallback of `scripts/build_runtime.ps1`, XMA voices output silence. | ||
| 26 | Use `-DLEONIDA_REQUIRE_XMA2_DECODER=ON` to require the decoder in a CMake build, as the Windows runtime CI does. | ||
diff --git a/runtime/xma_decoder/leonida_xma2_decoder.h b/runtime/xma_decoder/leonida_xma2_decoder.h index 98dd5c49c..a4c5b4534 100644 --- a/runtime/xma_decoder/leonida_xma2_decoder.h +++ b/runtime/xma_decoder/leonida_xma2_decoder.h | |||
| @@ -25,6 +25,10 @@ enum LeonidaXma2Status { | |||
| 25 | 25 | ||
| 26 | int32_t leonida_xma2_decoder_create(uint32_t sample_rate, uint32_t channels, | 26 | int32_t leonida_xma2_decoder_create(uint32_t sample_rate, uint32_t channels, |
| 27 | LeonidaXma2Decoder **out_decoder); | 27 | LeonidaXma2Decoder **out_decoder); |
| 28 | /* Like leonida_xma2_decoder_create, but decodes like the console's XMA hardware: the first | ||
| 29 | frame is kept and there is no 64-sample start skip; the caller applies the context's skip. */ | ||
| 30 | int32_t leonida_xma2_decoder_create_hardware(uint32_t sample_rate, uint32_t channels, | ||
| 31 | LeonidaXma2Decoder **out_decoder); | ||
| 28 | int32_t leonida_xma2_decode_buffer(LeonidaXma2Decoder *decoder, | 32 | int32_t leonida_xma2_decode_buffer(LeonidaXma2Decoder *decoder, |
| 29 | const uint8_t *input, size_t input_len, | 33 | const uint8_t *input, size_t input_len, |
| 30 | LeonidaXma2PcmBlock **out_block); | 34 | LeonidaXma2PcmBlock **out_block); |
diff --git a/runtime/xma_decoder/src/lib.rs b/runtime/xma_decoder/src/lib.rs index 1b435a0ce..69fedf49e 100644 --- a/runtime/xma_decoder/src/lib.rs +++ b/runtime/xma_decoder/src/lib.rs | |||
| @@ -59,6 +59,28 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create( | |||
| 59 | channels: u32, | 59 | channels: u32, |
| 60 | out_decoder: *mut *mut LeonidaXma2Decoder, | 60 | out_decoder: *mut *mut LeonidaXma2Decoder, |
| 61 | ) -> i32 { | 61 | ) -> i32 { |
| 62 | unsafe { create_with(sample_rate, channels, out_decoder, Xma2Stream::new) } | ||
| 63 | } | ||
| 64 | |||
| 65 | /// Like `leonida_xma2_decoder_create`, but decodes like the console's XMA hardware: the first | ||
| 66 | /// frame is kept and there is no 64-sample start skip; the caller applies the context's skip. | ||
| 67 | /// # Safety | ||
| 68 | /// Same as `leonida_xma2_decoder_create`. | ||
| 69 | #[no_mangle] | ||
| 70 | pub unsafe extern "C" fn leonida_xma2_decoder_create_hardware( | ||
| 71 | sample_rate: u32, | ||
| 72 | channels: u32, | ||
| 73 | out_decoder: *mut *mut LeonidaXma2Decoder, | ||
| 74 | ) -> i32 { | ||
| 75 | unsafe { create_with(sample_rate, channels, out_decoder, Xma2Stream::new_hardware) } | ||
| 76 | } | ||
| 77 | |||
| 78 | unsafe fn create_with<E>( | ||
| 79 | sample_rate: u32, | ||
| 80 | channels: u32, | ||
| 81 | out_decoder: *mut *mut LeonidaXma2Decoder, | ||
| 82 | make: impl FnOnce(u32, usize) -> Result<Xma2Stream, E>, | ||
| 83 | ) -> i32 { | ||
| 62 | if out_decoder.is_null() { | 84 | if out_decoder.is_null() { |
| 63 | return LEONIDA_XMA2_INVALID_ARGUMENT; | 85 | return LEONIDA_XMA2_INVALID_ARGUMENT; |
| 64 | } | 86 | } |
| @@ -68,8 +90,8 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create( | |||
| 68 | } | 90 | } |
| 69 | 91 | ||
| 70 | match catch_unwind(AssertUnwindSafe(|| { | 92 | match catch_unwind(AssertUnwindSafe(|| { |
| 71 | let stream = Xma2Stream::new(sample_rate, channels as usize) | 93 | let stream = |
| 72 | .map_err(|_| LEONIDA_XMA2_INVALID_FORMAT)?; | 94 | make(sample_rate, channels as usize).map_err(|_| LEONIDA_XMA2_INVALID_FORMAT)?; |
| 73 | try_new_handle(LeonidaXma2Decoder { | 95 | try_new_handle(LeonidaXma2Decoder { |
| 74 | stream: Mutex::new(stream), | 96 | stream: Mutex::new(stream), |
| 75 | channels: channels as usize, | 97 | channels: channels as usize, |
| @@ -87,7 +109,8 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create( | |||
| 87 | /// Decodes a buffer containing one or more complete 2048-byte XMA2 packets. | 109 | /// Decodes a buffer containing one or more complete 2048-byte XMA2 packets. |
| 88 | /// | 110 | /// |
| 89 | /// # Safety | 111 | /// # Safety |
| 90 | /// `decoder` must be a live handle returned by `leonida_xma2_decoder_create`. | 112 | /// `decoder` must be a live handle returned by `leonida_xma2_decoder_create` |
| 113 | /// or `leonida_xma2_decoder_create_hardware`. | ||
| 91 | /// `input` must reference `input_len` readable bytes and `out_block` must be writable. | 114 | /// `input` must reference `input_len` readable bytes and `out_block` must be writable. |
| 92 | /// Do not destroy a decoder concurrently with this call. The returned PCM block remains valid | 115 | /// Do not destroy a decoder concurrently with this call. The returned PCM block remains valid |
| 93 | /// until `leonida_xma2_pcm_destroy` is called. | 116 | /// until `leonida_xma2_pcm_destroy` is called. |
| @@ -160,8 +183,8 @@ pub unsafe extern "C" fn leonida_xma2_decode_buffer( | |||
| 160 | /// Destroys a decoder. Passing null is a no-op. | 183 | /// Destroys a decoder. Passing null is a no-op. |
| 161 | /// | 184 | /// |
| 162 | /// # Safety | 185 | /// # Safety |
| 163 | /// A non-null pointer must be a live handle returned by `leonida_xma2_decoder_create`, | 186 | /// A non-null pointer must be a live handle returned by `leonida_xma2_decoder_create` |
| 164 | /// and no calls may be using it concurrently. | 187 | /// or `leonida_xma2_decoder_create_hardware`. No calls may be using it concurrently. |
| 165 | #[no_mangle] | 188 | #[no_mangle] |
| 166 | pub unsafe extern "C" fn leonida_xma2_decoder_destroy(decoder: *mut LeonidaXma2Decoder) { | 189 | pub unsafe extern "C" fn leonida_xma2_decoder_destroy(decoder: *mut LeonidaXma2Decoder) { |
| 167 | if !decoder.is_null() { | 190 | if !decoder.is_null() { |
| @@ -233,6 +256,24 @@ mod tests { | |||
| 233 | } | 256 | } |
| 234 | 257 | ||
| 235 | #[test] | 258 | #[test] |
| 259 | fn create_hardware_accepts_stereo_and_rejects_three_channels() { | ||
| 260 | let mut decoder = ptr::null_mut(); | ||
| 261 | assert_eq!( | ||
| 262 | unsafe { leonida_xma2_decoder_create_hardware(48_000, 2, &mut decoder) }, | ||
| 263 | LEONIDA_XMA2_OK | ||
| 264 | ); | ||
| 265 | assert!(!decoder.is_null()); | ||
| 266 | unsafe { leonida_xma2_decoder_destroy(decoder) }; | ||
| 267 | |||
| 268 | let mut decoder = ptr::dangling_mut(); | ||
| 269 | assert_eq!( | ||
| 270 | unsafe { leonida_xma2_decoder_create_hardware(48_000, 3, &mut decoder) }, | ||
| 271 | LEONIDA_XMA2_INVALID_FORMAT | ||
| 272 | ); | ||
| 273 | assert!(decoder.is_null()); | ||
| 274 | } | ||
| 275 | |||
| 276 | #[test] | ||
| 236 | fn pcm_handle_allocation_failure_clears_output_and_allows_retry() { | 277 | fn pcm_handle_allocation_failure_clears_output_and_allows_retry() { |
| 237 | let mut decoder = ptr::null_mut(); | 278 | let mut decoder = ptr::null_mut(); |
| 238 | assert_eq!( | 279 | assert_eq!( |
diff --git a/runtime/xma_decoder/tests/ffi_contract.rs b/runtime/xma_decoder/tests/ffi_contract.rs index 0eb8e5cf4..6e6185c39 100644 --- a/runtime/xma_decoder/tests/ffi_contract.rs +++ b/runtime/xma_decoder/tests/ffi_contract.rs | |||
| @@ -52,6 +52,28 @@ fn make_decoder(rate: u32, channels: u32) -> *mut LeonidaXma2Decoder { | |||
| 52 | } | 52 | } |
| 53 | 53 | ||
| 54 | #[test] | 54 | #[test] |
| 55 | fn hardware_mode_keeps_all_samples_of_the_first_stereo_frame() { | ||
| 56 | let mut packet = synthetic_silent_packet(2); | ||
| 57 | packet[..4].copy_from_slice(&[4, 0, 1, 0]); // One frame, no continuation from a previous packet. | ||
| 58 | let mut decoder = ptr::null_mut(); | ||
| 59 | let mut block = ptr::null_mut(); | ||
| 60 | unsafe { | ||
| 61 | assert_eq!( | ||
| 62 | leonida_xma2_decoder_create_hardware(48_000, 2, &mut decoder), | ||
| 63 | LEONIDA_XMA2_OK | ||
| 64 | ); | ||
| 65 | assert_eq!( | ||
| 66 | leonida_xma2_decode_buffer(decoder, packet.as_ptr(), packet.len(), &mut block), | ||
| 67 | LEONIDA_XMA2_OK | ||
| 68 | ); | ||
| 69 | let count = leonida_xma2_pcm_sample_count(block); | ||
| 70 | leonida_xma2_pcm_destroy(block); | ||
| 71 | leonida_xma2_decoder_destroy(decoder); | ||
| 72 | assert_eq!(count, 512 * 2); | ||
| 73 | } | ||
| 74 | } | ||
| 75 | |||
| 76 | #[test] | ||
| 55 | fn creation_rejects_invalid_outputs_and_formats() { | 77 | fn creation_rejects_invalid_outputs_and_formats() { |
| 56 | assert_eq!( | 78 | assert_eq!( |
| 57 | unsafe { leonida_xma2_decoder_create(48_000, 2, ptr::null_mut()) }, | 79 | unsafe { leonida_xma2_decoder_create(48_000, 2, ptr::null_mut()) }, |