Merge main into feat/shader-nested-sampler-tables

This commit is contained in:
Yunus Shaikh committed 2026-11-08 10:23:18 -08:00
commit 85e79949ae
974 files changed
+57854 -13719

No files matched your search

+40 -1
View File
@@ -57,6 +57,7 @@ jobs:
register-context: ${{ steps.gate.outputs.register-context }}
write-watch: ${{ steps.gate.outputs.write-watch }}
edge-watch: ${{ steps.gate.outputs.edge-watch }}
pipe-write: ${{ steps.gate.outputs.pipe-write }}
mingw-host-tests: ${{ steps.gate.outputs.mingw-host-tests }}
full: ${{ steps.gate.outputs.full }}
relinker-hosts: ${{ steps.gate.outputs.relinker-hosts }}
@@ -139,9 +140,11 @@ jobs:
),
registerContext: edits('register-context') ||
touches('core/libs/tests/register_context/', 'core/libs/tests/RegisterContext.cpp', libc),
writeWatch: edits('write-watch') || touches('core/libs/tests/write_watch/', 'core/libs/tests/WriteWatch.cpp', libc),
writeWatch: edits('write-watch') || touches('core/libs/tests/write_watch/', 'core/libs/tests/WriteWatch.cpp', 'core/libs/tests/WriteWatchBacking.cpp', libc),
edgeWatch: edits('edge-watch') || touches('core/libs/tests/edge_watch/', 'core/libs/tests/EdgeWatch.cpp',
'core/libs/prx/libkernel/Equeue/src/EdgeWatch.cpp', 'core/libs/prx/libkernel/Equeue/include/EdgeWatch.hpp', libc),
pipeWrite: edits('pipe-write') || touches('core/libs/tests/pipe_write/', 'core/libs/tests/PipeWrite.cpp',
'core/libs/prx/libkernel/Socket/src/Udp.cpp', 'core/libs/prx/libkernel/Socket/include/SocketRuntime.hpp'),
mingwHostTests: edits('eligibility') || edits('windows') || touches(
'core/libs/', 'cmake/', '3rdparty/', '.gitmodules', 'tools/build_mingw_host_only_tests.py',
'tools/build_changed_guest_tests.py', 'tools/configure_seed.py', 'tools/select_tests.py',
@@ -182,6 +185,7 @@ jobs:
core.setOutput('register-context', run.registerContext);
core.setOutput('write-watch', run.writeWatch);
core.setOutput('edge-watch', run.edgeWatch);
core.setOutput('pipe-write', run.pipeWrite);
core.setOutput('mingw-host-tests', false);
core.setOutput('full', true);
core.setOutput('relinker-hosts', relinkerHosts(true, true));
@@ -273,6 +277,7 @@ jobs:
core.setOutput('register-context', registerContext);
core.setOutput('write-watch', writeWatch);
core.setOutput('edge-watch', run.edgeWatch);
core.setOutput('pipe-write', run.pipeWrite);
core.setOutput('mingw-host-tests', !manual && run.mingwHostTests);
core.setOutput('full', full);
core.setOutput('relinker-hosts', relinkerHosts(full, linux, manual));
@@ -767,6 +772,40 @@ jobs:
awk '/Test +#[0-9]+: / && $NF == "sec" { for (i = 1; i <= NF; i++) if ($i ~ /^#[0-9]+:$/) name = $(i + 1); t = $(NF - 1) + 0; if (t > max[name]) max[name] = t }
END { for (name in max) if (max[name] > 30) printf "::warning title=Slow test::%s took %.1f s on %s; tests must finish in 30 s (CONTRIBUTING.md)\n", name, max[name], ENVIRON["RUNNER_OS"] }' ctest.log
pipe-write:
needs: eligibility
if: ${{ needs.eligibility.outputs.pipe-write == 'true' }}
strategy:
fail-fast: false
matrix:
os: [macos-15-intel, macos-15]
runs-on: ${{ matrix.os }}
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.eligibility.outputs.sha }}
persist-credentials: false
- name: Merge the pull request into main
if: ${{ needs.eligibility.outputs.head != '' }}
shell: bash
env:
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
PR_HEAD: ${{ needs.eligibility.outputs.head }}
run: |
read -ra numbers <<< "$PR_NUMBER"
read -ra heads <<< "$PR_HEAD"
refspecs=()
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
git fetch --no-tags --unshallow origin "${refspecs[@]}"
for i in "${!numbers[@]}"; do
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
done
- run: cmake -S core/libs/tests/pipe_write -B build/pipe-write -DCMAKE_BUILD_TYPE=Release
- run: cmake --build build/pipe-write --parallel
- run: ctest --test-dir build/pipe-write --output-on-failure --repeat until-fail:3 --no-tests=error
edge-watch:
needs: eligibility
if: ${{ needs.eligibility.outputs.edge-watch == 'true' }}
+6
View File
@@ -79,9 +79,15 @@
[submodule "3rdparty/quickjs"]
path = 3rdparty/quickjs
url = https://github.com/quickjs-ng/quickjs.git
[submodule "zlib"]
path = 3rdparty/zlib
url = https://github.com/madler/zlib.git
[submodule "3rdparty/sqlite"]
path = 3rdparty/sqlite
url = https://github.com/sqlite/sqlite.git
[submodule "3rdparty/fontconfig"]
path = 3rdparty/fontconfig
url = https://github.com/fontconfig/fontconfig.git
[submodule "3rdparty/curl"]
path = 3rdparty/curl
url = https://github.com/curl/curl.git
+17
View File
@@ -0,0 +1,17 @@
# FidelityFX-FSR
The shader headers of AMD FidelityFX Super Resolution 1.0. The AGC driver compiles them into the presentation's EASU and RCAS shaders, which run under `ANYPS5_UPSCALE=fsr`.
- Source: https://github.com/GPUOpen-Effects/FidelityFX-FSR
- Tag: v1.0.2, commit a21ffb8f6c13233ba336352bdff293894c706575
- License: MIT, in [license.txt](license.txt)
The files are copied unmodified from that commit, at the same paths:
| File | SHA-256 |
|------|---------|
| `ffx-fsr/ffx_a.h` | `f60e2722fcd13989523b9164d776ab382b3692791767f3bf8bb19967f763f3fb` |
| `ffx-fsr/ffx_fsr1.h` | `93c3922362ea7fc99cbcc698ca30c98de4f8c246d1fbb0b09e015ddef38ce3a5` |
| `license.txt` | `db089274ce766da70f5b7d791029c3486f9f9e27c8c79c652689603d3192e802` |
They are copied instead of added as a submodule because every release tag of that repository carries two submodules for AMD's sample, Cauldron and Cauldron-Media, which a recursive checkout would fetch: about 337 MB at depth 1 and 1.47 GB with full history, for 243 KB of headers.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Vendored Submodule
+1
Submodule 3rdparty/curl added at 801bd5138c.
Vendored Submodule
+1
Submodule 3rdparty/zlib added at da607da739.
+5
View File
@@ -290,6 +290,8 @@ if(BUILD_TESTING)
endif()
endforeach()
endif()
add_test(NAME export_gap COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_export_gap.py)
add_test(NAME unwrap_self COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_unwrap_self.py)
add_test(NAME audit_dump COMMAND ${Python3_EXECUTABLE}
@@ -422,6 +424,9 @@ if(BUILD_TESTING)
set_tests_properties(select_tests_${test_class} PROPERTIES TIMEOUT 30)
endif()
endforeach()
add_test(NAME relinker_fuzz_configurations COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_relinker_fuzz_configurations.py)
set_tests_properties(relinker_fuzz_configurations PROPERTIES TIMEOUT 30)
add_test(NAME configure_seed COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedTests)
add_test(NAME configure_seed_paths COMMAND ${Python3_EXECUTABLE}
+71 -10
View File
@@ -223,10 +223,13 @@ if(WIN32)
file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/release-implibs.txt CONTENT "${RELEASE_IMPLIBS}")
endif()
include(prx/libSceFreeType/PostScriptPrivate.cmake)
target_link_libraries(libSceUsbStorageDialog PRIVATE libSceUserService)
add_subdirectory(${CMAKE_SOURCE_DIR}/3rdparty/libfvad ${CMAKE_CURRENT_BINARY_DIR}/webrtc-fvad EXCLUDE_FROM_ALL)
set_target_properties(fvad PROPERTIES C_VISIBILITY_PRESET hidden)
target_compile_options(fvad PRIVATE $<$<C_COMPILER_ID:GNU,Clang,AppleClang>:-fno-sanitize=shift>)
target_sources(libwebrtc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/prx/libwebrtc/Vad.cpp)
target_include_directories(libwebrtc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/3rdparty/libfvad/src)
@@ -510,6 +513,16 @@ if(BUILD_TESTING)
add_test(NAME nid_elf_layout COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_elf_layout.py $<TARGET_FILE:nid_patcher>)
endif()
add_test_executable(guest_appinstutil_declarations_tests tests/GuestAppInstUtilDeclarations.cpp)
target_include_directories(guest_appinstutil_declarations_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_appinstutil_declarations_tests PRIVATE libSceAppInstUtil libkernel libc)
configure_windows_unwind(guest_appinstutil_declarations_tests)
add_test(NAME guest_appinstutil_declarations COMMAND guest_appinstutil_declarations_tests)
set_tests_properties(guest_appinstutil_declarations PROPERTIES TIMEOUT 20)
if(WIN32)
set_tests_properties(guest_appinstutil_declarations PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceAppInstUtil>")
endif()
add_test_executable(guest_kernel_sys_pwrite_tests tests/GuestKernelSysPwrite.cpp
nid/src/NidCompute.cpp nid/src/Sha1.cpp)
target_include_directories(guest_kernel_sys_pwrite_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/nid/include)
@@ -851,6 +864,15 @@ if(BUILD_TESTING)
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceGnmDriverForNeoMode>")
endif()
add_test_executable(guest_abstract_storage_trivial_returns_tests tests/GuestAbstractStorageTrivialReturns.cpp)
target_include_directories(guest_abstract_storage_trivial_returns_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_abstract_storage_trivial_returns_tests PRIVATE libSceAbstractStorage libc)
configure_windows_unwind(guest_abstract_storage_trivial_returns_tests)
add_test(NAME guest_abstract_storage_trivial_returns COMMAND guest_abstract_storage_trivial_returns_tests)
if(WIN32)
set_tests_properties(guest_abstract_storage_trivial_returns PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceAbstractStorage>")
endif()
add_test_executable(guest_gnm_neo_context_state_internal_tests tests/GuestGnmNeoContextStateInternal.cpp)
target_include_directories(guest_gnm_neo_context_state_internal_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_gnm_neo_context_state_internal_tests PRIVATE libSceGnmDriverForNeoMode libc)
@@ -992,6 +1014,15 @@ if(BUILD_TESTING)
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceHttp>")
endif()
add_test_executable(guest_share_utility_advance_tests tests/GuestShareUtilityAdvance.cpp)
target_include_directories(guest_share_utility_advance_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_share_utility_advance_tests PRIVATE libSceShareUtility libc)
configure_windows_unwind(guest_share_utility_advance_tests)
add_test(NAME guest_share_utility_advance COMMAND guest_share_utility_advance_tests)
if(WIN32)
set_tests_properties(guest_share_utility_advance PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceShareUtility>")
endif()
add_test_executable(guest_entitlements_tests tests/GuestEntitlements.cpp)
target_include_directories(guest_entitlements_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_entitlements_tests PRIVATE libSceNpEntitlementAccess libc)
@@ -1133,6 +1164,16 @@ if(BUILD_TESTING)
set_tests_properties(guest_rudp_poll PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceRudp>")
endif()
add_test_executable(guest_rudp_poll_drain_tests tests/GuestRudpPollDrain.cpp)
target_include_directories(guest_rudp_poll_drain_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_rudp_poll_drain_tests PRIVATE libSceRudp libc)
configure_windows_unwind(guest_rudp_poll_drain_tests)
add_test(NAME guest_rudp_poll_drain COMMAND guest_rudp_poll_drain_tests)
set_tests_properties(guest_rudp_poll_drain PROPERTIES TIMEOUT 60)
if(WIN32)
set_tests_properties(guest_rudp_poll_drain PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceRudp>")
endif()
if(WIN32)
add_test_executable(rudp_poll_wait_exception_tests tests/RudpPollWaitException.cpp
prx/libSceRudp/Export.cpp prx/libkernel/Time/TimedWait.cpp)
@@ -1155,6 +1196,7 @@ if(BUILD_TESTING)
endif()
add_test_executable(guest_kernel_sys_ksem_tests tests/GuestKernelSysKsem.cpp)
target_compile_definitions(guest_kernel_sys_ksem_tests PRIVATE ANYPS5_KSEM_TESTING)
target_include_directories(guest_kernel_sys_ksem_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_kernel_sys_ksem_tests PRIVATE libkernel_sys libkernel libc)
configure_windows_unwind(guest_kernel_sys_ksem_tests)
@@ -1165,6 +1207,15 @@ if(BUILD_TESTING)
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
endif()
add_test_executable(guest_system_service_unknown_returns_tests tests/GuestSystemServiceUnknownReturns.cpp)
target_include_directories(guest_system_service_unknown_returns_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_system_service_unknown_returns_tests PRIVATE libSceSystemService libc)
configure_windows_unwind(guest_system_service_unknown_returns_tests)
add_test(NAME guest_system_service_unknown_returns COMMAND guest_system_service_unknown_returns_tests)
if(WIN32)
set_tests_properties(guest_system_service_unknown_returns PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSystemService>")
endif()
add_test_executable(guest_system_gesture_tests tests/GuestSystemGesture.cpp)
target_include_directories(guest_system_gesture_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_system_gesture_tests PRIVATE libSceSystemGesture libc)
@@ -1224,6 +1275,17 @@ if(BUILD_TESTING)
set_tests_properties(savedata_memory_journal PROPERTIES
ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSaveData.native>")
endif()
add_test_executable(guest_json_reader_equivalence_tests tests/GuestJsonReaderEquivalence.cpp)
target_include_directories(guest_json_reader_equivalence_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_json_reader_equivalence_tests PRIVATE libSceJson2 libc)
configure_windows_unwind(guest_json_reader_equivalence_tests)
add_test(NAME guest_json_reader_equivalence COMMAND guest_json_reader_equivalence_tests)
set_tests_properties(guest_json_reader_equivalence PROPERTIES TIMEOUT 20)
if(WIN32)
set_tests_properties(guest_json_reader_equivalence PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceJson2>")
endif()
add_library(host_thread_local_test_library SHARED tests/HostThreadLocalLibrary.cpp)
set_target_properties(host_thread_local_test_library PROPERTIES RUNTIME_OUTPUT_DIRECTORY "$<1:${ANYPS5_TEST_OUTPUT_DIRECTORY}>")
target_include_directories(host_thread_local_test_library PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
@@ -1313,16 +1375,6 @@ if(BUILD_TESTING)
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
endif()
add_test_executable(guest_src_utility_tests tests/GuestSrcUtility.cpp)
target_include_directories(guest_src_utility_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_src_utility_tests PRIVATE libSceSrcUtl libc)
configure_windows_unwind(guest_src_utility_tests)
add_test(NAME guest_src_utility COMMAND guest_src_utility_tests)
if(WIN32)
set_tests_properties(guest_src_utility PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSrcUtl>")
endif()
add_test_executable(guest_crt_tests tests/GuestCrt.cpp)
target_include_directories(guest_crt_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_crt_tests PRIVATE libSceAmpr libc)
@@ -1424,6 +1476,15 @@ if(BUILD_TESTING)
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceAcm>")
endif()
add_test_executable(guest_bemp2sys_decoder_release_tests tests/GuestBemp2sysDecoderRelease.cpp)
target_include_directories(guest_bemp2sys_decoder_release_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_bemp2sys_decoder_release_tests PRIVATE libSceBemp2sys libc)
configure_windows_unwind(guest_bemp2sys_decoder_release_tests)
add_test(NAME guest_bemp2sys_decoder_release COMMAND guest_bemp2sys_decoder_release_tests)
if(WIN32)
set_tests_properties(guest_bemp2sys_decoder_release PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceBemp2sys>")
endif()
add_test_executable(guest_gnm_neo_embedded_tests tests/GuestGnmNeoEmbedded.cpp)
target_include_directories(guest_gnm_neo_embedded_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_gnm_neo_embedded_tests PRIVATE libSceGnmDriverForNeoMode libc)
@@ -188,64 +188,53 @@ int APS5_VABI SystemServiceParamGetString() {
extern "C" {
int APS5_VABI libReactNativeWebAppLauncherInventory__plus_ucrAt9fI7c_nid_no_patch() {
int APS5_VABI EnableSystemMusic() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("+ucrAt9fI7c", libReactNativeWebAppLauncherInventory__plus_ucrAt9fI7c_nid_no_patch);
int APS5_VABI libReactNativeWebAppLauncherInventory_06N_minus_dAyE_plus_HY_nid_no_patch() {
int APS5_VABI SpeechSystemSettings() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("06N-dAyE+HY", libReactNativeWebAppLauncherInventory_06N_minus_dAyE_plus_HY_nid_no_patch);
int APS5_VABI libReactNativeWebAppLauncherInventory_41blU2JCqLQ_nid_no_patch() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("41blU2JCqLQ", libReactNativeWebAppLauncherInventory_41blU2JCqLQ_nid_no_patch);
int APS5_VABI libReactNativeWebAppLauncherInventory_BGgSEXB1Now_nid_no_patch() {
int APS5_VABI GetAccountPsPlusStatus() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("BGgSEXB1Now", libReactNativeWebAppLauncherInventory_BGgSEXB1Now_nid_no_patch);
int APS5_VABI libReactNativeWebAppLauncherInventory_CAK_minus_S2JVdsk_nid_no_patch() {
int APS5_VABI RegisterSystemEventCallback() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("CAK-S2JVdsk", libReactNativeWebAppLauncherInventory_CAK_minus_S2JVdsk_nid_no_patch);
int APS5_VABI libReactNativeWebAppLauncherInventory_QxCdpkEsOgo_nid_no_patch() {
int APS5_VABI GetNetworkConnectionType() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("QxCdpkEsOgo", libReactNativeWebAppLauncherInventory_QxCdpkEsOgo_nid_no_patch);
int APS5_VABI libReactNativeWebAppLauncherInventory_Tjj_plus__plus_S2qvOU_nid_no_patch() {
int APS5_VABI NpWebSendRequest() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("Tjj++S2qvOU", libReactNativeWebAppLauncherInventory_Tjj_plus__plus_S2qvOU_nid_no_patch);
int APS5_VABI libReactNativeWebAppLauncherInventory_f5NHqUziG_plus_4_nid_no_patch() {
int APS5_VABI DisableSystemMusic() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("f5NHqUziG+4", libReactNativeWebAppLauncherInventory_f5NHqUziG_plus_4_nid_no_patch);
int APS5_VABI libReactNativeWebAppLauncherInventory_mI_minus_ltMuVN_plus_Q_nid_no_patch() {
int APS5_VABI EnableSystemMedia() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("mI-ltMuVN+Q", libReactNativeWebAppLauncherInventory_mI_minus_ltMuVN_plus_Q_nid_no_patch);
int APS5_VABI libReactNativeWebAppLauncherInventory_vDup_plus_0mWZf8_nid_no_patch() {
int APS5_VABI CommerceDialogCheckout() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("vDup+0mWZf8", libReactNativeWebAppLauncherInventory_vDup_plus_0mWZf8_nid_no_patch);
int APS5_VABI libReactNativeWebAppLauncherInventory_wR1ucKGDM9Q_nid_no_patch() {
int APS5_VABI CommerceDialogBrowsePsPlus() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("wR1ucKGDM9Q", libReactNativeWebAppLauncherInventory_wR1ucKGDM9Q_nid_no_patch);
int APS5_VABI libReactNativeWebAppLauncherInventory_xPA_minus_tXzPGpc_nid_no_patch() {
int APS5_VABI NpWebCreateRequest() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("xPA-tXzPGpc", libReactNativeWebAppLauncherInventory_xPA_minus_tXzPGpc_nid_no_patch);
}
@@ -51,17 +51,17 @@ int APS5_VABI SystemServiceParamGetInt();
int APS5_VABI SystemServiceParamGetString();
int APS5_VABI libReactNativeWebAppLauncherInventory__plus_ucrAt9fI7c_nid_no_patch();
int APS5_VABI libReactNativeWebAppLauncherInventory_06N_minus_dAyE_plus_HY_nid_no_patch();
int APS5_VABI EnableSystemMusic();
int APS5_VABI SpeechSystemSettings();
int APS5_VABI libReactNativeWebAppLauncherInventory_41blU2JCqLQ_nid_no_patch();
int APS5_VABI libReactNativeWebAppLauncherInventory_BGgSEXB1Now_nid_no_patch();
int APS5_VABI libReactNativeWebAppLauncherInventory_CAK_minus_S2JVdsk_nid_no_patch();
int APS5_VABI libReactNativeWebAppLauncherInventory_QxCdpkEsOgo_nid_no_patch();
int APS5_VABI libReactNativeWebAppLauncherInventory_Tjj_plus__plus_S2qvOU_nid_no_patch();
int APS5_VABI libReactNativeWebAppLauncherInventory_f5NHqUziG_plus_4_nid_no_patch();
int APS5_VABI libReactNativeWebAppLauncherInventory_mI_minus_ltMuVN_plus_Q_nid_no_patch();
int APS5_VABI libReactNativeWebAppLauncherInventory_vDup_plus_0mWZf8_nid_no_patch();
int APS5_VABI libReactNativeWebAppLauncherInventory_wR1ucKGDM9Q_nid_no_patch();
int APS5_VABI libReactNativeWebAppLauncherInventory_xPA_minus_tXzPGpc_nid_no_patch();
int APS5_VABI GetAccountPsPlusStatus();
int APS5_VABI RegisterSystemEventCallback();
int APS5_VABI GetNetworkConnectionType();
int APS5_VABI NpWebSendRequest();
int APS5_VABI DisableSystemMusic();
int APS5_VABI EnableSystemMedia();
int APS5_VABI CommerceDialogCheckout();
int APS5_VABI CommerceDialogBrowsePsPlus();
int APS5_VABI NpWebCreateRequest();
}
@@ -268,94 +268,77 @@ int APS5_VABI sceRemotePlayClientTerminateStreaming() {
extern "C" {
int APS5_VABI libReactNativeModulesVshInventory__plus_I5sPs9FLXw_nid_no_patch() {
int APS5_VABI CryptographyEncryptAES128CBC_HS256() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("+I5sPs9FLXw", libReactNativeModulesVshInventory__plus_I5sPs9FLXw_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory__minus_9hYGDAsb4E_nid_no_patch() {
int APS5_VABI PSNowRequestClientId() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("-9hYGDAsb4E", libReactNativeModulesVshInventory__minus_9hYGDAsb4E_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_BzJsgzD97LU_nid_no_patch() {
int APS5_VABI InitializeAsmNetLib() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("BzJsgzD97LU", libReactNativeModulesVshInventory_BzJsgzD97LU_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_IQNf2nnftNI_nid_no_patch() {
int APS5_VABI PSNowSetFeedbackResult() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("IQNf2nnftNI", libReactNativeModulesVshInventory_IQNf2nnftNI_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_N3mcm_minus_qDFR0_nid_no_patch() {
int APS5_VABI sceRemotePlayClientShowControlCenter() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("N3mcm-qDFR0", libReactNativeModulesVshInventory_N3mcm_minus_qDFR0_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_OME2Be_plus_FlwA_nid_no_patch() {
int APS5_VABI CryptographyDecryptRSA_OAEP_256() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("OME2Be+FlwA", libReactNativeModulesVshInventory_OME2Be_plus_FlwA_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_PLEe_minus_toB_minus_KE_nid_no_patch() {
int APS5_VABI PSNowCancelRequestGame() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("PLEe-toB-KE", libReactNativeModulesVshInventory_PLEe_minus_toB_minus_KE_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_QGGsQrtLW9Y_nid_no_patch() {
int APS5_VABI TerminateAsmNetLib() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("QGGsQrtLW9Y", libReactNativeModulesVshInventory_QGGsQrtLW9Y_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_Rm_plus_rgnBoPIE_nid_no_patch() {
int APS5_VABI sceRemotePlayClientShowQuickMenu() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("Rm+rgnBoPIE", libReactNativeModulesVshInventory_Rm_plus_rgnBoPIE_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_SJU_plus_qK_plus_8yrM_nid_no_patch() {
int APS5_VABI PSNowTestConnection() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("SJU+qK+8yrM", libReactNativeModulesVshInventory_SJU_plus_qK_plus_8yrM_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_T7dL_minus_hEySvU_nid_no_patch() {
int APS5_VABI CryptographyEncryptRSA_OAEP_256() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("T7dL-hEySvU", libReactNativeModulesVshInventory_T7dL_minus_hEySvU_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_b_plus_MJDz3HB6s_nid_no_patch() {
int APS5_VABI sceRemotePlayClientWaitConnectionAsync() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("b+MJDz3HB6s", libReactNativeModulesVshInventory_b_plus_MJDz3HB6s_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_bbsP8_minus_e8GZA_nid_no_patch() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("bbsP8-e8GZA", libReactNativeModulesVshInventory_bbsP8_minus_e8GZA_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_fxEQAPDRhLw_nid_no_patch() {
int APS5_VABI PSNowShouldAskFeedback() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("fxEQAPDRhLw", libReactNativeModulesVshInventory_fxEQAPDRhLw_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_j917Pp4k_minus_CI_nid_no_patch() {
int APS5_VABI LoginMgrDisablePadKeyRemappingNative() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("j917Pp4k-CI", libReactNativeModulesVshInventory_j917Pp4k_minus_CI_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_lZ_minus_JDEqB34k_nid_no_patch() {
int APS5_VABI PSNowIsEntitledToStream() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("lZ-JDEqB34k", libReactNativeModulesVshInventory_lZ_minus_JDEqB34k_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_tKy_minus_Qdg_plus_FRc_nid_no_patch() {
int APS5_VABI sceRemotePlayClientRemoveEventListener() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("tKy-Qdg+FRc", libReactNativeModulesVshInventory_tKy_minus_Qdg_plus_FRc_nid_no_patch);
int APS5_VABI libReactNativeModulesVshInventory_uQfQgwm36L4_nid_no_patch() {
int APS5_VABI GetAsmLibHttpCtxId() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("uQfQgwm36L4", libReactNativeModulesVshInventory_uQfQgwm36L4_nid_no_patch);
}
@@ -71,23 +71,23 @@ int APS5_VABI sceRemotePlayClientStopMicCapture();
int APS5_VABI sceRemotePlayClientTerminateStreaming();
int APS5_VABI libReactNativeModulesVshInventory__plus_I5sPs9FLXw_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory__minus_9hYGDAsb4E_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_BzJsgzD97LU_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_IQNf2nnftNI_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_N3mcm_minus_qDFR0_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_OME2Be_plus_FlwA_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_PLEe_minus_toB_minus_KE_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_QGGsQrtLW9Y_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_Rm_plus_rgnBoPIE_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_SJU_plus_qK_plus_8yrM_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_T7dL_minus_hEySvU_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_b_plus_MJDz3HB6s_nid_no_patch();
int APS5_VABI CryptographyEncryptAES128CBC_HS256();
int APS5_VABI PSNowRequestClientId();
int APS5_VABI InitializeAsmNetLib();
int APS5_VABI PSNowSetFeedbackResult();
int APS5_VABI sceRemotePlayClientShowControlCenter();
int APS5_VABI CryptographyDecryptRSA_OAEP_256();
int APS5_VABI PSNowCancelRequestGame();
int APS5_VABI TerminateAsmNetLib();
int APS5_VABI sceRemotePlayClientShowQuickMenu();
int APS5_VABI PSNowTestConnection();
int APS5_VABI CryptographyEncryptRSA_OAEP_256();
int APS5_VABI sceRemotePlayClientWaitConnectionAsync();
int APS5_VABI libReactNativeModulesVshInventory_bbsP8_minus_e8GZA_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_fxEQAPDRhLw_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_j917Pp4k_minus_CI_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_lZ_minus_JDEqB34k_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_tKy_minus_Qdg_plus_FRc_nid_no_patch();
int APS5_VABI libReactNativeModulesVshInventory_uQfQgwm36L4_nid_no_patch();
int APS5_VABI PSNowShouldAskFeedback();
int APS5_VABI LoginMgrDisablePadKeyRemappingNative();
int APS5_VABI PSNowIsEntitledToStream();
int APS5_VABI sceRemotePlayClientRemoveEventListener();
int APS5_VABI GetAsmLibHttpCtxId();
}
+22 -26
View File
@@ -26,13 +26,9 @@ int APS5_VABI _ZN15AbstractStorage12SerializableC2Ev() {
NotImplemented_nid_no_patch(__func__);
}
int APS5_VABI _ZN15AbstractStorage12SerializableD1Ev() {
NotImplemented_nid_no_patch(__func__);
}
void APS5_VABI _ZN15AbstractStorage12SerializableD1Ev(void*) {}
int APS5_VABI _ZN15AbstractStorage12SerializableD2Ev() {
NotImplemented_nid_no_patch(__func__);
}
void APS5_VABI _ZN15AbstractStorage12SerializableD2Ev(void*) {}
int APS5_VABI _ZN15AbstractStorage14MemfileContent12readExternalESt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
@@ -70,16 +66,16 @@ int APS5_VABI _ZN15AbstractStorage14MemfileContent5WriteEPKvlPl() {
NotImplemented_nid_no_patch(__func__);
}
int APS5_VABI _ZN15AbstractStorage14MemfileContent6RemoveEv() {
NotImplemented_nid_no_patch(__func__);
int APS5_VABI _ZN15AbstractStorage14MemfileContent6RemoveEv(void*) {
return static_cast<int>(0x809E0002u);
}
int APS5_VABI _ZN15AbstractStorage14MemfileContent8SeekByteEliPl() {
NotImplemented_nid_no_patch(__func__);
}
int APS5_VABI _ZN15AbstractStorage14MemfileContent8SeekTimeElPl() {
NotImplemented_nid_no_patch(__func__);
int APS5_VABI _ZN15AbstractStorage14MemfileContent8SeekTimeElPl(void*, std::int64_t, std::int64_t*) {
return static_cast<int>(0x809E0002u);
}
int APS5_VABI _ZN15AbstractStorage14MemfileContentC1ESbIcSt11char_traitsIcENS_8StlAllocIcEEEN3paf6common9SharedPtrINS6_6BufferEEE() {
@@ -250,12 +246,12 @@ int APS5_VABI _ZN15AbstractStorage4Item11GetPathNameEv() {
NotImplemented_nid_no_patch(__func__);
}
int APS5_VABI _ZN15AbstractStorage4Item11SetMetadataEPN23sceMetadataReaderWriter8MetadataE() {
NotImplemented_nid_no_patch(__func__);
int APS5_VABI _ZN15AbstractStorage4Item11SetMetadataEPN23sceMetadataReaderWriter8MetadataE(void*, void*) {
return static_cast<int>(0x809E0005u);
}
int APS5_VABI _ZN15AbstractStorage4Item13ParseMetadataEPN23sceMetadataReaderWriter8MetadataES3_() {
NotImplemented_nid_no_patch(__func__);
int APS5_VABI _ZN15AbstractStorage4Item13ParseMetadataEPN23sceMetadataReaderWriter8MetadataES3_(void*, void*, void*) {
return static_cast<int>(0x809E0005u);
}
int APS5_VABI _ZN15AbstractStorage4Item14GetStorageNameEv() {
@@ -418,16 +414,16 @@ int APS5_VABI _ZN15AbstractStorage9AbsMallocEm() {
NotImplemented_nid_no_patch(__func__);
}
int APS5_VABI _ZNK15AbstractStorage14MemfileContent10GetServiceEv() {
NotImplemented_nid_no_patch(__func__);
int APS5_VABI _ZNK15AbstractStorage14MemfileContent10GetServiceEv(const void*) {
return -1;
}
int APS5_VABI _ZNK15AbstractStorage14MemfileContent13GetCapabilityEv() {
NotImplemented_nid_no_patch(__func__);
int APS5_VABI _ZNK15AbstractStorage14MemfileContent13GetCapabilityEv(const void*) {
return 0x17C1A;
}
int APS5_VABI _ZNK15AbstractStorage14MemfileContent7GetStatEPNS_4StatE() {
NotImplemented_nid_no_patch(__func__);
int APS5_VABI _ZNK15AbstractStorage14MemfileContent7GetStatEPNS_4StatE(const void*, void*) {
return static_cast<int>(0x809E0002u);
}
int APS5_VABI _ZNK15AbstractStorage4Item12GetThumbnailEPSt10shared_ptrINS_7ContentEE() {
@@ -438,16 +434,16 @@ int APS5_VABI _ZNK15AbstractStorage4Item15CreateThumbnailEPvPSt10shared_ptrINS_7
NotImplemented_nid_no_patch(__func__);
}
int APS5_VABI _ZNK15AbstractStorage6Folder7GetTypeEv() {
NotImplemented_nid_no_patch(__func__);
int APS5_VABI _ZNK15AbstractStorage6Folder7GetTypeEv(const void*) {
return 2;
}
int APS5_VABI _ZNK15AbstractStorage7Content7GetTypeEv() {
NotImplemented_nid_no_patch(__func__);
int APS5_VABI _ZNK15AbstractStorage7Content7GetTypeEv(const void*) {
return 3;
}
int APS5_VABI _ZNK15AbstractStorage7Storage7GetTypeEv() {
NotImplemented_nid_no_patch(__func__);
int APS5_VABI _ZNK15AbstractStorage7Storage7GetTypeEv(const void*) {
return 1;
}
}
@@ -8,8 +8,8 @@ int APS5_VABI _ZN15AbstractStorage12Serializable12readExternalESt10shared_ptrINS
int APS5_VABI _ZN15AbstractStorage12Serializable13writeExternalESt10shared_ptrINS_7ContentEE();
int APS5_VABI _ZN15AbstractStorage12SerializableC1Ev();
int APS5_VABI _ZN15AbstractStorage12SerializableC2Ev();
int APS5_VABI _ZN15AbstractStorage12SerializableD1Ev();
int APS5_VABI _ZN15AbstractStorage12SerializableD2Ev();
void APS5_VABI _ZN15AbstractStorage12SerializableD1Ev(void*);
void APS5_VABI _ZN15AbstractStorage12SerializableD2Ev(void*);
int APS5_VABI _ZN15AbstractStorage14MemfileContent12readExternalESt10shared_ptrINS_7ContentEE();
int APS5_VABI _ZN15AbstractStorage14MemfileContent13writeExternalESt10shared_ptrINS_7ContentEE();
int APS5_VABI _ZN15AbstractStorage14MemfileContent14CreateInstanceESbIcSt11char_traitsIcENS_8StlAllocIcEEEN3paf6common9SharedPtrINS6_6BufferEEE();
@@ -19,9 +19,9 @@ int APS5_VABI _ZN15AbstractStorage14MemfileContent4ReadEPvlPl();
int APS5_VABI _ZN15AbstractStorage14MemfileContent5CloseEv();
int APS5_VABI _ZN15AbstractStorage14MemfileContent5FlushEv();
int APS5_VABI _ZN15AbstractStorage14MemfileContent5WriteEPKvlPl();
int APS5_VABI _ZN15AbstractStorage14MemfileContent6RemoveEv();
int APS5_VABI _ZN15AbstractStorage14MemfileContent6RemoveEv(void*);
int APS5_VABI _ZN15AbstractStorage14MemfileContent8SeekByteEliPl();
int APS5_VABI _ZN15AbstractStorage14MemfileContent8SeekTimeElPl();
int APS5_VABI _ZN15AbstractStorage14MemfileContent8SeekTimeElPl(void*, std::int64_t, std::int64_t*);
int APS5_VABI _ZN15AbstractStorage14MemfileContentC1ESbIcSt11char_traitsIcENS_8StlAllocIcEEEN3paf6common9SharedPtrINS6_6BufferEEE();
int APS5_VABI _ZN15AbstractStorage14MemfileContentC2ESbIcSt11char_traitsIcENS_8StlAllocIcEEEN3paf6common9SharedPtrINS6_6BufferEEE();
int APS5_VABI _ZN15AbstractStorage14MemfileContentD0Ev();
@@ -64,8 +64,8 @@ int APS5_VABI _ZN15AbstractStorage15HttpTransactionC2Ev();
int APS5_VABI _ZN15AbstractStorage15HttpTransactionD1Ev();
int APS5_VABI _ZN15AbstractStorage15HttpTransactionD2Ev();
int APS5_VABI _ZN15AbstractStorage4Item11GetPathNameEv();
int APS5_VABI _ZN15AbstractStorage4Item11SetMetadataEPN23sceMetadataReaderWriter8MetadataE();
int APS5_VABI _ZN15AbstractStorage4Item13ParseMetadataEPN23sceMetadataReaderWriter8MetadataES3_();
int APS5_VABI _ZN15AbstractStorage4Item11SetMetadataEPN23sceMetadataReaderWriter8MetadataE(void*, void*);
int APS5_VABI _ZN15AbstractStorage4Item13ParseMetadataEPN23sceMetadataReaderWriter8MetadataES3_(void*, void*, void*);
int APS5_VABI _ZN15AbstractStorage4Item14GetStorageNameEv();
int APS5_VABI _ZN15AbstractStorage4Item6RenameERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE();
int APS5_VABI _ZN15AbstractStorage4Item7GetNameERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE();
@@ -106,13 +106,13 @@ int APS5_VABI _ZN15AbstractStorage7StorageD0Ev();
int APS5_VABI _ZN15AbstractStorage7StorageD1Ev();
int APS5_VABI _ZN15AbstractStorage7StorageD2Ev();
int APS5_VABI _ZN15AbstractStorage9AbsMallocEm();
int APS5_VABI _ZNK15AbstractStorage14MemfileContent10GetServiceEv();
int APS5_VABI _ZNK15AbstractStorage14MemfileContent13GetCapabilityEv();
int APS5_VABI _ZNK15AbstractStorage14MemfileContent7GetStatEPNS_4StatE();
int APS5_VABI _ZNK15AbstractStorage14MemfileContent10GetServiceEv(const void*);
int APS5_VABI _ZNK15AbstractStorage14MemfileContent13GetCapabilityEv(const void*);
int APS5_VABI _ZNK15AbstractStorage14MemfileContent7GetStatEPNS_4StatE(const void*, void*);
int APS5_VABI _ZNK15AbstractStorage4Item12GetThumbnailEPSt10shared_ptrINS_7ContentEE();
int APS5_VABI _ZNK15AbstractStorage4Item15CreateThumbnailEPvPSt10shared_ptrINS_7ContentEE();
int APS5_VABI _ZNK15AbstractStorage6Folder7GetTypeEv();
int APS5_VABI _ZNK15AbstractStorage7Content7GetTypeEv();
int APS5_VABI _ZNK15AbstractStorage7Storage7GetTypeEv();
int APS5_VABI _ZNK15AbstractStorage6Folder7GetTypeEv(const void*);
int APS5_VABI _ZNK15AbstractStorage7Content7GetTypeEv(const void*);
int APS5_VABI _ZNK15AbstractStorage7Storage7GetTypeEv(const void*);
}
+69 -136
View File
@@ -1,3 +1,4 @@
#include "prx/libSceAbstractTwitter/include/Exports.hpp"
#include <cstddef>
#include <cstdint>
#include "SceTypes.hpp"
@@ -6,344 +7,276 @@
extern "C" {
int APS5_VABI sceAbstractTwitterUnknown_JMPK_1KGVfo_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage10TwitterAPI11SendContentEPKvl() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("JMPK-1KGVfo", sceAbstractTwitterUnknown_JMPK_1KGVfo_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_p73mqupCtos_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage10TwitterAPIC1Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("p73mqupCtos", sceAbstractTwitterUnknown_p73mqupCtos_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_gf3h8ObDkuI_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage10TwitterAPID1Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("gf3h8ObDkuI", sceAbstractTwitterUnknown_gf3h8ObDkuI_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_uW4bk_mPlM8_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolder10NewContentERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("uW4bk+mPlM8", sceAbstractTwitterUnknown_uW4bk_mPlM8_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_bXW4ce_oHPA_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolder12RemoveFolderERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("bXW4ce-oHPA", sceAbstractTwitterUnknown_bXW4ce_oHPA_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_DWJep6U_MYQ_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolder13RemoveContentERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("DWJep6U-MYQ", sceAbstractTwitterUnknown_DWJep6U_MYQ_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_y1e_omRUMhY_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolder4OpenENS_8ItemTypeE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("y1e+omRUMhY", sceAbstractTwitterUnknown_y1e_omRUMhY_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_EBRKLWTYXy4_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolder5CloseEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("EBRKLWTYXy4", sceAbstractTwitterUnknown_EBRKLWTYXy4_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_oPzukphzAys_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolder6RemoveEb() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("oPzukphzAys", sceAbstractTwitterUnknown_oPzukphzAys_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_p8qZEIwpBmM_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolder8NextItemEPSt10shared_ptrINS_4ItemEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("p8qZEIwpBmM", sceAbstractTwitterUnknown_p8qZEIwpBmM_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_AMzjf2brlcw_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolder9NewFolderERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_6FolderEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("AMzjf2brlcw", sceAbstractTwitterUnknown_AMzjf2brlcw_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_lfQMRAQl6kI_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolderC1ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("lfQMRAQl6kI", sceAbstractTwitterUnknown_lfQMRAQl6kI_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_kslGRG0HVL4_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolderC2ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("kslGRG0HVL4", sceAbstractTwitterUnknown_kslGRG0HVL4_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_Dkk29mw5RF4_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolderD0Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("Dkk29mw5RF4", sceAbstractTwitterUnknown_Dkk29mw5RF4_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_1rt9PQJV64k_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolderD1Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("1rt9PQJV64k", sceAbstractTwitterUnknown_1rt9PQJV64k_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_ye4sPvqyPfM_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage13TwitterFolderD2Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("ye4sPvqyPfM", sceAbstractTwitterUnknown_ye4sPvqyPfM_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_4VD0OuFSW04_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent11SetMetadataEPN23sceMetadataReaderWriter8MetadataE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("4VD0OuFSW04", sceAbstractTwitterUnknown_4VD0OuFSW04_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_eVXr2Uj_TA0_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent12readExternalESt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("eVXr2Uj+TA0", sceAbstractTwitterUnknown_eVXr2Uj_TA0_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_hRba2mQ9fss_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent13ParseMetadataEPN23sceMetadataReaderWriter8MetadataES3_() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("hRba2mQ9fss", sceAbstractTwitterUnknown_hRba2mQ9fss_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_iA282fSjF30_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent13writeExternalESt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("iA282fSjF30", sceAbstractTwitterUnknown_iA282fSjF30_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_BEGvI6L3BqI_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent4OpenEit() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("BEGvI6L3BqI", sceAbstractTwitterUnknown_BEGvI6L3BqI_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_0soubDsGzXw_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent4ReadEPvlPl() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("0soubDsGzXw", sceAbstractTwitterUnknown_0soubDsGzXw_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_Bof69eeNCCw_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent5CloseEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("Bof69eeNCCw", sceAbstractTwitterUnknown_Bof69eeNCCw_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_qwFemTBSZnY_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent5FlushEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("qwFemTBSZnY", sceAbstractTwitterUnknown_qwFemTBSZnY_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_2EoYjMBr3xs_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent5WriteEPKvlPl() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("2EoYjMBr3xs", sceAbstractTwitterUnknown_2EoYjMBr3xs_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_d2kMlNVjxC8_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent6RemoveEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("d2kMlNVjxC8", sceAbstractTwitterUnknown_d2kMlNVjxC8_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_exxKr58F43o_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent6RenameERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("exxKr58F43o", sceAbstractTwitterUnknown_exxKr58F43o_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_Mnf5YJkQX7s_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent8SeekByteEliPl() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("Mnf5YJkQX7s", sceAbstractTwitterUnknown_Mnf5YJkQX7s_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_z0b3IxfaSbI_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContent8SeekTimeElPl() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("z0b3IxfaSbI", sceAbstractTwitterUnknown_z0b3IxfaSbI_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_ZIM7XSHmna4_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContentC1ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("ZIM7XSHmna4", sceAbstractTwitterUnknown_ZIM7XSHmna4_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown__7Gi8U_26XU_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContentC2ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("-7Gi8U+26XU", sceAbstractTwitterUnknown__7Gi8U_26XU_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_ki9Tj7Fyq90_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContentD0Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("ki9Tj7Fyq90", sceAbstractTwitterUnknown_ki9Tj7Fyq90_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_Q2sTPN_hnYw_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContentD1Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("Q2sTPN-hnYw", sceAbstractTwitterUnknown_Q2sTPN_hnYw_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_MBi5D9Wuwqo_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterContentD2Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("MBi5D9Wuwqo", sceAbstractTwitterUnknown_MBi5D9Wuwqo_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_NvSKi_AG__g_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterService13SearchStorageEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("NvSKi+AG++g", sceAbstractTwitterUnknown_NvSKi_AG__g_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_J_Z0oLcpiv8_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterService23create_storage_instanceERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("J+Z0oLcpiv8", sceAbstractTwitterUnknown_J_Z0oLcpiv8_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_o7r_wKZNjw0_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterService4StopEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("o7r+wKZNjw0", sceAbstractTwitterUnknown_o7r_wKZNjw0_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_TiDaUZArrIc_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterService5StartEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("TiDaUZArrIc", sceAbstractTwitterUnknown_TiDaUZArrIc_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_YVerJp_GbDc_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterServiceC1Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("YVerJp-GbDc", sceAbstractTwitterUnknown_YVerJp_GbDc_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_eEr7LIMuChY_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterServiceC2Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("eEr7LIMuChY", sceAbstractTwitterUnknown_eEr7LIMuChY_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_RghnEC6_6KE_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterServiceD0Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("RghnEC6-6KE", sceAbstractTwitterUnknown_RghnEC6_6KE_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_4YOnvHQco2w_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterServiceD1Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("4YOnvHQco2w", sceAbstractTwitterUnknown_4YOnvHQco2w_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_E_bNjlNe1DU_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterServiceD2Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("E+bNjlNe1DU", sceAbstractTwitterUnknown_E_bNjlNe1DU_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_PkOxC__b9aM_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorage10GetContentERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("PkOxC--b9aM", sceAbstractTwitterUnknown_PkOxC__b9aM_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_7EkyOOXfgDo_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorage11DeserializeESt10shared_ptrINS_7ContentEEPS1_INS_4ItemEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("7EkyOOXfgDo", sceAbstractTwitterUnknown_7EkyOOXfgDo_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_G8VIS1QkWg4_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorage13GetRootFolderEPSt10shared_ptrINS_6FolderEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("G8VIS1QkWg4", sceAbstractTwitterUnknown_G8VIS1QkWg4_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_b7klmKCsFQk_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorage14GetStorageSizeEPlS1_S1_() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("b7klmKCsFQk", sceAbstractTwitterUnknown_b7klmKCsFQk_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_osMzBigeiAM_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorage15CreateRecursiveERKSbIcSt11char_traitsIcENS_8StlAllocIcEEENS_8ItemTypeEPSt10shared_ptrINS_4ItemEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("osMzBigeiAM", sceAbstractTwitterUnknown_osMzBigeiAM_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_3wCEN9TNBU4_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorage15RemoveRecursiveERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("3wCEN9TNBU4", sceAbstractTwitterUnknown_3wCEN9TNBU4_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_gERQO7gDxhs_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorage7GetItemERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_4ItemEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("gERQO7gDxhs", sceAbstractTwitterUnknown_gERQO7gDxhs_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown__dPfbWlRgmU_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorage7IsExistERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("+dPfbWlRgmU", sceAbstractTwitterUnknown__dPfbWlRgmU_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_DutvlYFO68Y_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorage9GetForderERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_6FolderEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("DutvlYFO68Y", sceAbstractTwitterUnknown_DutvlYFO68Y_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_wLljjEtN3vY_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorage9SerializeESt10shared_ptrINS_7ContentEES1_INS_4ItemEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("wLljjEtN3vY", sceAbstractTwitterUnknown_wLljjEtN3vY_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_QLzJT6sH5nI_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorageC1ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("QLzJT6sH5nI", sceAbstractTwitterUnknown_QLzJT6sH5nI_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_IqK5rvqsy9A_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorageC2ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("IqK5rvqsy9A", sceAbstractTwitterUnknown_IqK5rvqsy9A_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_5ovK_oroKlY_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorageD0Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("5ovK+oroKlY", sceAbstractTwitterUnknown_5ovK_oroKlY_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_I7rDjJe4Eok_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorageD1Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("I7rDjJe4Eok", sceAbstractTwitterUnknown_I7rDjJe4Eok_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_5KhQZQnPN50_nid_no_patch() {
int APS5_VABI _ZN15AbstractStorage14TwitterStorageD2Ev() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("5KhQZQnPN50", sceAbstractTwitterUnknown_5KhQZQnPN50_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_fTfAEGjfLoQ_nid_no_patch() {
int APS5_VABI _ZNK15AbstractStorage13TwitterFolder10GetServiceEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("fTfAEGjfLoQ", sceAbstractTwitterUnknown_fTfAEGjfLoQ_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_dwASDRq1150_nid_no_patch() {
int APS5_VABI _ZNK15AbstractStorage13TwitterFolder13GetCapabilityEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("dwASDRq1150", sceAbstractTwitterUnknown_dwASDRq1150_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_nLOlVSvvxRc_nid_no_patch() {
int APS5_VABI _ZNK15AbstractStorage13TwitterFolder7GetStatEPNS_4StatE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("nLOlVSvvxRc", sceAbstractTwitterUnknown_nLOlVSvvxRc_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_4d9S8jMy6Ac_nid_no_patch() {
int APS5_VABI _ZNK15AbstractStorage14TwitterContent10GetServiceEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("4d9S8jMy6Ac", sceAbstractTwitterUnknown_4d9S8jMy6Ac_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_MljG2BSqkMY_nid_no_patch() {
int APS5_VABI _ZNK15AbstractStorage14TwitterContent13GetCapabilityEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("MljG2BSqkMY", sceAbstractTwitterUnknown_MljG2BSqkMY_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_Jzj9ZTh5m1I_nid_no_patch() {
int APS5_VABI _ZNK15AbstractStorage14TwitterContent7GetStatEPNS_4StatE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("Jzj9ZTh5m1I", sceAbstractTwitterUnknown_Jzj9ZTh5m1I_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_M8XjMzOr1aY_nid_no_patch() {
int APS5_VABI _ZNK15AbstractStorage14TwitterService14GetServiceTypeEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("M8XjMzOr1aY", sceAbstractTwitterUnknown_M8XjMzOr1aY_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_PUV6qvRaqCE_nid_no_patch() {
int APS5_VABI _ZNK15AbstractStorage14TwitterStorage10GetServiceEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("PUV6qvRaqCE", sceAbstractTwitterUnknown_PUV6qvRaqCE_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_wzzIp0t1OzU_nid_no_patch() {
int APS5_VABI _ZNK15AbstractStorage14TwitterStorage13GetCapabilityEv() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("wzzIp0t1OzU", sceAbstractTwitterUnknown_wzzIp0t1OzU_nid_no_patch);
int APS5_VABI sceAbstractTwitterUnknown_dP_3UFf8BBw_nid_no_patch() {
int APS5_VABI _ZNK15AbstractStorage14TwitterStorage7GetStatEPNS_4StatE() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("dP+3UFf8BBw", sceAbstractTwitterUnknown_dP_3UFf8BBw_nid_no_patch);
}
@@ -0,0 +1,76 @@
#pragma once
#include "SceTypes.hpp"
extern "C" {
int APS5_VABI _ZN15AbstractStorage10TwitterAPI11SendContentEPKvl();
int APS5_VABI _ZN15AbstractStorage10TwitterAPIC1Ev();
int APS5_VABI _ZN15AbstractStorage10TwitterAPID1Ev();
int APS5_VABI _ZN15AbstractStorage13TwitterFolder10NewContentERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_7ContentEE();
int APS5_VABI _ZN15AbstractStorage13TwitterFolder12RemoveFolderERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb();
int APS5_VABI _ZN15AbstractStorage13TwitterFolder13RemoveContentERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE();
int APS5_VABI _ZN15AbstractStorage13TwitterFolder4OpenENS_8ItemTypeE();
int APS5_VABI _ZN15AbstractStorage13TwitterFolder5CloseEv();
int APS5_VABI _ZN15AbstractStorage13TwitterFolder6RemoveEb();
int APS5_VABI _ZN15AbstractStorage13TwitterFolder8NextItemEPSt10shared_ptrINS_4ItemEE();
int APS5_VABI _ZN15AbstractStorage13TwitterFolder9NewFolderERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_6FolderEE();
int APS5_VABI _ZN15AbstractStorage13TwitterFolderC1ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb();
int APS5_VABI _ZN15AbstractStorage13TwitterFolderC2ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb();
int APS5_VABI _ZN15AbstractStorage13TwitterFolderD0Ev();
int APS5_VABI _ZN15AbstractStorage13TwitterFolderD1Ev();
int APS5_VABI _ZN15AbstractStorage13TwitterFolderD2Ev();
int APS5_VABI _ZN15AbstractStorage14TwitterContent11SetMetadataEPN23sceMetadataReaderWriter8MetadataE();
int APS5_VABI _ZN15AbstractStorage14TwitterContent12readExternalESt10shared_ptrINS_7ContentEE();
int APS5_VABI _ZN15AbstractStorage14TwitterContent13ParseMetadataEPN23sceMetadataReaderWriter8MetadataES3_();
int APS5_VABI _ZN15AbstractStorage14TwitterContent13writeExternalESt10shared_ptrINS_7ContentEE();
int APS5_VABI _ZN15AbstractStorage14TwitterContent4OpenEit();
int APS5_VABI _ZN15AbstractStorage14TwitterContent4ReadEPvlPl();
int APS5_VABI _ZN15AbstractStorage14TwitterContent5CloseEv();
int APS5_VABI _ZN15AbstractStorage14TwitterContent5FlushEv();
int APS5_VABI _ZN15AbstractStorage14TwitterContent5WriteEPKvlPl();
int APS5_VABI _ZN15AbstractStorage14TwitterContent6RemoveEv();
int APS5_VABI _ZN15AbstractStorage14TwitterContent6RenameERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE();
int APS5_VABI _ZN15AbstractStorage14TwitterContent8SeekByteEliPl();
int APS5_VABI _ZN15AbstractStorage14TwitterContent8SeekTimeElPl();
int APS5_VABI _ZN15AbstractStorage14TwitterContentC1ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb();
int APS5_VABI _ZN15AbstractStorage14TwitterContentC2ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb();
int APS5_VABI _ZN15AbstractStorage14TwitterContentD0Ev();
int APS5_VABI _ZN15AbstractStorage14TwitterContentD1Ev();
int APS5_VABI _ZN15AbstractStorage14TwitterContentD2Ev();
int APS5_VABI _ZN15AbstractStorage14TwitterService13SearchStorageEv();
int APS5_VABI _ZN15AbstractStorage14TwitterService23create_storage_instanceERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE();
int APS5_VABI _ZN15AbstractStorage14TwitterService4StopEv();
int APS5_VABI _ZN15AbstractStorage14TwitterService5StartEv();
int APS5_VABI _ZN15AbstractStorage14TwitterServiceC1Ev();
int APS5_VABI _ZN15AbstractStorage14TwitterServiceC2Ev();
int APS5_VABI _ZN15AbstractStorage14TwitterServiceD0Ev();
int APS5_VABI _ZN15AbstractStorage14TwitterServiceD1Ev();
int APS5_VABI _ZN15AbstractStorage14TwitterServiceD2Ev();
int APS5_VABI _ZN15AbstractStorage14TwitterStorage10GetContentERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_7ContentEE();
int APS5_VABI _ZN15AbstractStorage14TwitterStorage11DeserializeESt10shared_ptrINS_7ContentEEPS1_INS_4ItemEE();
int APS5_VABI _ZN15AbstractStorage14TwitterStorage13GetRootFolderEPSt10shared_ptrINS_6FolderEE();
int APS5_VABI _ZN15AbstractStorage14TwitterStorage14GetStorageSizeEPlS1_S1_();
int APS5_VABI _ZN15AbstractStorage14TwitterStorage15CreateRecursiveERKSbIcSt11char_traitsIcENS_8StlAllocIcEEENS_8ItemTypeEPSt10shared_ptrINS_4ItemEE();
int APS5_VABI _ZN15AbstractStorage14TwitterStorage15RemoveRecursiveERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE();
int APS5_VABI _ZN15AbstractStorage14TwitterStorage7GetItemERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_4ItemEE();
int APS5_VABI _ZN15AbstractStorage14TwitterStorage7IsExistERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE();
int APS5_VABI _ZN15AbstractStorage14TwitterStorage9GetForderERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_6FolderEE();
int APS5_VABI _ZN15AbstractStorage14TwitterStorage9SerializeESt10shared_ptrINS_7ContentEES1_INS_4ItemEE();
int APS5_VABI _ZN15AbstractStorage14TwitterStorageC1ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE();
int APS5_VABI _ZN15AbstractStorage14TwitterStorageC2ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE();
int APS5_VABI _ZN15AbstractStorage14TwitterStorageD0Ev();
int APS5_VABI _ZN15AbstractStorage14TwitterStorageD1Ev();
int APS5_VABI _ZN15AbstractStorage14TwitterStorageD2Ev();
int APS5_VABI _ZNK15AbstractStorage13TwitterFolder10GetServiceEv();
int APS5_VABI _ZNK15AbstractStorage13TwitterFolder13GetCapabilityEv();
int APS5_VABI _ZNK15AbstractStorage13TwitterFolder7GetStatEPNS_4StatE();
int APS5_VABI _ZNK15AbstractStorage14TwitterContent10GetServiceEv();
int APS5_VABI _ZNK15AbstractStorage14TwitterContent13GetCapabilityEv();
int APS5_VABI _ZNK15AbstractStorage14TwitterContent7GetStatEPNS_4StatE();
int APS5_VABI _ZNK15AbstractStorage14TwitterService14GetServiceTypeEv();
int APS5_VABI _ZNK15AbstractStorage14TwitterStorage10GetServiceEv();
int APS5_VABI _ZNK15AbstractStorage14TwitterStorage13GetCapabilityEv();
int APS5_VABI _ZNK15AbstractStorage14TwitterStorage7GetStatEPNS_4StatE();
}
@@ -1 +1,2 @@
#pragma once
#include "prx/libSceAbstractTwitter/include/Exports.hpp"
-1
View File
@@ -437,7 +437,6 @@ int APS5_VABI sceAcmBatchJobPriority(AcmBatchInfo* batch, std::uint32_t priority
int APS5_VABI sceAcm_ConvReverb_SharedIr() {
NotImplemented_nid_no_patch(__func__);
return 0;
}
int APS5_VABI sceAcm_IFFT(AcmBatchInfo* batch, std::int32_t transformSize, std::uint32_t transformCount, std::int32_t inputFormat, const void* const* inputs, std::int32_t outputFormat, void* const* outputs, std::int32_t flags) {
+26 -1
View File
@@ -332,6 +332,23 @@ foreach(agcOverlayStage IN ITEMS Vert Frag)
)
list(APPEND agcPresentationShaderHeaders ${agcOverlayShaderHeader})
endforeach()
set(agcFsrIncludeDir ${CMAKE_SOURCE_DIR}/3rdparty/FidelityFX-FSR/ffx-fsr)
foreach(agcFsrFilter IN ITEMS Easu Rcas)
string(TOUPPER "${agcFsrFilter}" agcFsrSymbol)
set(agcFsrShaderSource ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/shaders/Fsr${agcFsrFilter}.frag)
set(agcFsrShaderSpv ${agcTextureDetileGeneratedDir}/Fsr${agcFsrFilter}Frag.spv)
set(agcFsrShaderHeader ${agcTextureDetileGeneratedDir}/Fsr${agcFsrFilter}Frag_spv.h)
add_custom_command(
OUTPUT "${agcFsrShaderHeader}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${agcTextureDetileGeneratedDir}"
COMMAND "$<TARGET_FILE:glslang-standalone>" -V --target-env vulkan1.1 "-I${agcFsrIncludeDir}" -o "${agcFsrShaderSpv}" "${agcFsrShaderSource}"
COMMAND ${CMAKE_COMMAND} -DINPUT=${agcFsrShaderSpv} -DOUTPUT=${agcFsrShaderHeader}
-DSYMBOL=FSR_${agcFsrSymbol}_FRAG_SPV -P "${CMAKE_CURRENT_SOURCE_DIR}/embed_spirv.cmake"
DEPENDS "${agcFsrShaderSource}" "${agcFsrIncludeDir}/ffx_a.h" "${agcFsrIncludeDir}/ffx_fsr1.h" glslang-standalone
VERBATIM
)
list(APPEND agcPresentationShaderHeaders ${agcFsrShaderHeader})
endforeach()
set(agcDriverSources
${CMAKE_CURRENT_SOURCE_DIR}/Export.cpp
@@ -383,6 +400,7 @@ set(agcDriverSources
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Presentation.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Queues/QueueWorker.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Queues/Submission.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Queues/StallPrompt.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Queues/SubmissionRing.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Queues/WorkerAffinity.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Driver/Shaders/ShaderDiagnostics.cpp
@@ -417,6 +435,7 @@ set(agcDriverSources
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/AspectFit.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/PresentationScaler.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/PresentationPass.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/PresentationUpscaler.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/PerformanceOverlay.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/KeyboardOverlay.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/PadStatusOverlay.cpp
@@ -724,6 +743,11 @@ function(agc_add_draw_pipeline_test agcTestName)
if(WIN32)
set_tests_properties(${agcTestName}_draw_pipeline PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test(NAME ${agcTestName}_plan_verify COMMAND ${agcTestName}_tests)
set_tests_properties(${agcTestName}_plan_verify PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1;APS5_VERIFY_DRAW_PLAN=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
if(WIN32)
set_tests_properties(${agcTestName}_plan_verify PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endfunction()
function(agc_add_spirv_mode_tests agcTest)
@@ -862,6 +886,7 @@ if(BUILD_TESTING)
agc_driver_prepared_shaders_indirect agc_driver_prepared_shaders_uncached
agc_driver_prepared_shaders_debug agc_driver_prepared_shaders_debug_failure
PROPERTIES RESOURCE_LOCK shader_failure_capture)
set_property(TEST agc_driver_prepared_shaders APPEND PROPERTY ENVIRONMENT "APS5_NO_MASKED_RESULT_MEMO=1")
endif()
option(AGC_BUILD_VISUAL_TEST "Enable the standalone AGC SPIR-V visual test" OFF)
@@ -1066,7 +1091,7 @@ endif()
if(BUILD_TESTING)
get_directory_property(agcRegisteredTests TESTS)
list(FILTER agcRegisteredTests EXCLUDE REGEX "^(agc_pipeline_journal(_long_paths|_extended_paths)?|agc_driver_pipeline_journal|agc_pipeline_store_replay_growth)$")
list(FILTER agcRegisteredTests EXCLUDE REGEX "^(agc_pipeline_journal(_long_paths|_extended_paths)?|agc_driver_pipeline_journal(_undecodable_module)?|agc_pipeline_store_replay_growth)$")
set_property(TEST ${agcRegisteredTests} APPEND PROPERTY ENVIRONMENT "APS5_NO_PIPELINE_JOURNAL=1")
endif()
@@ -400,6 +400,254 @@ inline std::vector<std::string> DeviceFaultReport(VkDevice device, PFN_vkGetDevi
return lines;
}
inline constexpr std::uint32_t DeviceFaultMaxIndirectWords = 4;
inline const char* DeviceFaultStageName(std::uint32_t stage) noexcept {
try {
switch (static_cast<FaultStage>(stage)) {
case FaultStage::graphics: return "graphics";
case FaultStage::compute: return "compute";
case FaultStage::mesh: return "mesh";
case FaultStage::task: return "task";
case FaultStage::copy: return "copy";
case FaultStage::unknown:
default: return "unknown";
}
} catch (...) {
return "unknown";
}
}
struct DeviceFaultResidencyProbe {
bool boundNow = false;
bool importInFlight = false;
bool writeWatchRefused = false;
bool evicted = false;
std::uint64_t evictedAtSerial = 0;
};
inline std::string DeviceFaultIndirectLine(FaultToken token, const FaultTokenEntry& found) noexcept {
try {
const std::uint32_t words = found.argCount < DeviceFaultMaxIndirectWords ? found.argCount : DeviceFaultMaxIndirectWords;
char indirect[192];
int used = std::snprintf(indirect, sizeof(indirect), "[device-fault] indirect token %u args %u words from 0x%llx+%u stride %u:", static_cast<unsigned>(token), static_cast<unsigned>(words), static_cast<unsigned long long>(found.argBuffer), static_cast<unsigned>(found.argOffset), static_cast<unsigned>(found.argStride));
for (std::uint32_t i = 0; i < words && used > 0 && static_cast<std::size_t>(used) < sizeof(indirect) - 10; ++i) {
used += std::snprintf(indirect + used, sizeof(indirect) - static_cast<std::size_t>(used), " %08x", static_cast<unsigned>(found.argWords[i]));
}
if (used > 0 && static_cast<std::size_t>(used) < sizeof(indirect) - 15 && words != 0) std::snprintf(indirect + used, sizeof(indirect) - static_cast<std::size_t>(used), " (record-time)");
return indirect;
} catch (...) {
return {};
}
}
inline std::vector<std::string> DeviceFaultResidencyLines(std::uint64_t va, std::uint64_t submitSerial, const SubmissionSnapshots* snapshots, const DeviceFaultResidencyProbe& probe) noexcept {
std::vector<std::string> lines;
try {
char line[128];
if (probe.writeWatchRefused) {
std::snprintf(line, sizeof(line), "[device-fault] residency 0x%llx write-watch refused", static_cast<unsigned long long>(va));
lines.emplace_back(line);
return lines;
}
if (probe.importInFlight) {
std::snprintf(line, sizeof(line), "[device-fault] residency 0x%llx import in flight", static_cast<unsigned long long>(va));
lines.emplace_back(line);
return lines;
}
if (probe.evicted) {
if (probe.evictedAtSerial != 0) std::snprintf(line, sizeof(line), "[device-fault] residency 0x%llx evicted at serial %llu", static_cast<unsigned long long>(va), static_cast<unsigned long long>(probe.evictedAtSerial));
else std::snprintf(line, sizeof(line), "[device-fault] residency 0x%llx evicted", static_cast<unsigned long long>(va));
lines.emplace_back(line);
return lines;
}
bool snapshotFound = false;
bool covered = false;
if (snapshots != nullptr && submitSerial != 0) {
if (const auto found = snapshots->Find(submitSerial)) {
snapshotFound = true;
if (found->ranges != nullptr) {
for (const auto& range : *found->ranges) {
if (range.begin <= va && va < range.end) {
covered = true;
break;
}
}
}
}
}
if (snapshotFound && !covered && !probe.boundNow) {
std::snprintf(line, sizeof(line), "[device-fault] residency 0x%llx never bound", static_cast<unsigned long long>(va));
lines.emplace_back(line);
return lines;
}
std::snprintf(line, sizeof(line), "[device-fault] residency 0x%llx unknown", static_cast<unsigned long long>(va));
lines.emplace_back(line);
} catch (...) {
}
return lines;
}
struct DeviceFaultStageLinesTag {};
inline std::vector<std::string> DeviceFaultBracketLines(const SubmitBracket& bracket, const FaultTokenRing& ring, VkQueue queue, DeviceFaultStageLinesTag) noexcept {
std::vector<std::string> lines;
try {
if (bracket.submitSerial == 0) return lines;
char line[320];
if (queue == VK_NULL_HANDLE) std::snprintf(line, sizeof(line), "[device-fault] bracket: last completed %llu, in flight %llu, first not started %llu", static_cast<unsigned long long>(bracket.lastCompleted), static_cast<unsigned long long>(bracket.submitSerial), static_cast<unsigned long long>(bracket.submitSerial + 1));
else std::snprintf(line, sizeof(line), "[device-fault] bracket: last completed %llu, in flight %llu, first not started %llu, queue 0x%llx", static_cast<unsigned long long>(bracket.lastCompleted), static_cast<unsigned long long>(bracket.submitSerial), static_cast<unsigned long long>(bracket.submitSerial + 1), static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(queue)));
lines.emplace_back(line);
if (bracket.firstToken == 0) return lines;
if (bracket.lastToken < bracket.firstToken) return lines;
const std::uint64_t tokens = static_cast<std::uint64_t>(bracket.lastToken) - static_cast<std::uint64_t>(bracket.firstToken) + 1;
const std::uint64_t listed = tokens < DeviceFaultBracketTokensListed ? tokens : DeviceFaultBracketTokensListed;
const std::uint64_t start = static_cast<std::uint64_t>(bracket.firstToken) + (tokens > listed ? tokens - listed : 0);
for (std::uint64_t i = 0; i < listed; ++i) {
const FaultToken token = static_cast<FaultToken>(start + i);
const auto found = ring.Find(token);
if (!found.has_value()) {
if (queue == VK_NULL_HANDLE) std::snprintf(line, sizeof(line), "[device-fault] unknown token %u in batch %llu", static_cast<unsigned>(token), static_cast<unsigned long long>(bracket.submitSerial));
else std::snprintf(line, sizeof(line), "[device-fault] unknown token %u in batch %llu queue 0x%llx", static_cast<unsigned>(token), static_cast<unsigned long long>(bracket.submitSerial), static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(queue)));
lines.emplace_back(line);
continue;
}
const char* stage = DeviceFaultStageName(found->stage);
const std::size_t descLength = strnlen(found->desc, sizeof(found->desc));
if (queue == VK_NULL_HANDLE) {
if (descLength == 0) std::snprintf(line, sizeof(line), "[device-fault] token %u in batch %llu: program 0x%llx variant %llu stage %s", static_cast<unsigned>(token), static_cast<unsigned long long>(found->submitSerial), static_cast<unsigned long long>(found->programAddress), static_cast<unsigned long long>(found->variantId), stage);
else std::snprintf(line, sizeof(line), "[device-fault] token %u in batch %llu: program 0x%llx variant %llu stage %s %.*s", static_cast<unsigned>(token), static_cast<unsigned long long>(found->submitSerial), static_cast<unsigned long long>(found->programAddress), static_cast<unsigned long long>(found->variantId), stage, static_cast<int>(descLength), found->desc);
} else if (descLength == 0) std::snprintf(line, sizeof(line), "[device-fault] token %u in batch %llu queue 0x%llx: program 0x%llx variant %llu stage %s", static_cast<unsigned>(token), static_cast<unsigned long long>(found->submitSerial), static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(queue)), static_cast<unsigned long long>(found->programAddress), static_cast<unsigned long long>(found->variantId), stage);
else std::snprintf(line, sizeof(line), "[device-fault] token %u in batch %llu queue 0x%llx: program 0x%llx variant %llu stage %s %.*s", static_cast<unsigned>(token), static_cast<unsigned long long>(found->submitSerial), static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(queue)), static_cast<unsigned long long>(found->programAddress), static_cast<unsigned long long>(found->variantId), stage, static_cast<int>(descLength), found->desc);
lines.emplace_back(line);
if (found->argBuffer != 0) lines.emplace_back(DeviceFaultIndirectLine(token, *found));
}
if (tokens > listed) {
std::snprintf(line, sizeof(line), "[device-fault] %llu more bracket tokens", static_cast<unsigned long long>(tokens - listed));
lines.emplace_back(line);
}
} catch (...) {
}
return lines;
}
inline std::vector<std::string> DeviceFaultReport(VkDevice device, PFN_vkGetDeviceFaultInfoEXT faultInfo, VkQueue queue, PFN_vkGetQueueCheckpointDataNV checkpointData, std::uint64_t submitSerial, const SubmissionSnapshots* snapshots, const SubmitBracket& bracket, const FaultTokenRing& ring, DeviceFaultResidencyProbe (*residencyFor)(std::uint64_t va)) noexcept {
std::vector<std::string> lines;
try {
std::vector<VkCheckpointDataNV> points;
std::uint64_t tokenSerial = 0;
if (checkpointData != nullptr && queue != VK_NULL_HANDLE) {
std::uint32_t count = 0;
checkpointData(queue, &count, nullptr);
if (count > DeviceFaultMaxInfos) count = DeviceFaultMaxInfos;
points.assign(count, VkCheckpointDataNV{VK_STRUCTURE_TYPE_CHECKPOINT_DATA_NV});
if (count != 0) checkpointData(queue, &count, points.data());
points.resize(count);
for (const auto& point : points) {
const FaultToken token = static_cast<FaultToken>(reinterpret_cast<std::uintptr_t>(point.pCheckpointMarker));
const auto found = ring.Find(token);
if (found.has_value() && found->submitSerial != 0) tokenSerial = found->submitSerial;
}
}
const std::uint64_t effectiveSerial = submitSerial != 0 ? submitSerial : tokenSerial;
SubmitBracket effectiveBracket = bracket;
if (effectiveBracket.submitSerial == 0 && effectiveSerial != 0 && snapshots != nullptr) {
if (const auto found = snapshots->FindBracket(effectiveSerial)) effectiveBracket = *found;
}
const auto window = DeviceFaultBracketLines(effectiveBracket, ring, queue, DeviceFaultStageLinesTag{});
lines.insert(lines.end(), window.begin(), window.end());
if (effectiveSerial == 0 && device != VK_NULL_HANDLE) lines.emplace_back("[device-fault] no per-submit marker (submit serial unknown; markers need APS5_GPU_CHECKPOINTS on the main queue)");
if (checkpointData != nullptr && queue != VK_NULL_HANDLE) {
if (points.empty()) lines.emplace_back("[device-fault] no checkpoint reached");
char checkpoint[320];
for (const auto& point : points) {
const FaultToken token = static_cast<FaultToken>(reinterpret_cast<std::uintptr_t>(point.pCheckpointMarker));
const auto found = ring.Find(token);
if (!found.has_value()) {
std::snprintf(checkpoint, sizeof(checkpoint), "[device-fault] checkpoint: unknown token %u queue 0x%llx", static_cast<unsigned>(token), static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(queue)));
} else {
const char* stage = DeviceFaultStageName(found->stage);
const std::size_t descLength = strnlen(found->desc, sizeof(found->desc));
if (descLength == 0) std::snprintf(checkpoint, sizeof(checkpoint), "[device-fault] checkpoint: token %u batch %llu queue 0x%llx program 0x%llx variant %llu stage %s", static_cast<unsigned>(token), static_cast<unsigned long long>(found->submitSerial), static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(queue)), static_cast<unsigned long long>(found->programAddress), static_cast<unsigned long long>(found->variantId), stage);
else std::snprintf(checkpoint, sizeof(checkpoint), "[device-fault] checkpoint: token %u batch %llu queue 0x%llx program 0x%llx variant %llu stage %s %.*s", static_cast<unsigned>(token), static_cast<unsigned long long>(found->submitSerial), static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(queue)), static_cast<unsigned long long>(found->programAddress), static_cast<unsigned long long>(found->variantId), stage, static_cast<int>(descLength), found->desc);
if (found->argBuffer != 0) {
DeviceFaultAppendStage(checkpoint, sizeof(checkpoint), point.stage);
lines.emplace_back(checkpoint);
lines.emplace_back(DeviceFaultIndirectLine(token, *found));
continue;
}
}
DeviceFaultAppendStage(checkpoint, sizeof(checkpoint), point.stage);
lines.emplace_back(checkpoint);
}
}
if (faultInfo == nullptr || device == VK_NULL_HANDLE) {
if (points.empty() && effectiveBracket.submitSerial != 0) lines.emplace_back("[device-fault] no device-side fault data; CPU-side bracket only");
return lines;
}
char line[VK_MAX_DESCRIPTION_SIZE + 128];
VkDeviceFaultCountsEXT counts{VK_STRUCTURE_TYPE_DEVICE_FAULT_COUNTS_EXT};
if (faultInfo(device, &counts, nullptr) != VK_SUCCESS) {
lines.emplace_back("[device-fault] vkGetDeviceFaultInfoEXT reported nothing");
return lines;
}
if (counts.addressInfoCount > DeviceFaultMaxInfos) counts.addressInfoCount = DeviceFaultMaxInfos;
if (counts.vendorInfoCount > DeviceFaultMaxInfos) counts.vendorInfoCount = DeviceFaultMaxInfos;
std::vector<VkDeviceFaultAddressInfoEXT> addresses(counts.addressInfoCount);
std::vector<VkDeviceFaultVendorInfoEXT> vendors(counts.vendorInfoCount);
counts.vendorBinarySize = 0;
VkDeviceFaultInfoEXT info{VK_STRUCTURE_TYPE_DEVICE_FAULT_INFO_EXT};
info.pAddressInfos = addresses.empty() ? nullptr : addresses.data();
info.pVendorInfos = vendors.empty() ? nullptr : vendors.data();
const auto result = faultInfo(device, &counts, &info);
if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
lines.emplace_back("[device-fault] vkGetDeviceFaultInfoEXT reported nothing");
return lines;
}
addresses.resize(std::min<std::size_t>(addresses.size(), counts.addressInfoCount));
vendors.resize(std::min<std::size_t>(vendors.size(), counts.vendorInfoCount));
std::snprintf(line, sizeof(line), "[device-fault] result %d: %s", static_cast<int>(result), DeviceFaultText(info.description).c_str());
lines.emplace_back(line);
for (const auto& address : addresses) {
std::snprintf(line, sizeof(line), "[device-fault] %s at 0x%llx (precision 0x%llx)", DeviceFaultAddressKind(address.addressType), static_cast<unsigned long long>(address.reportedAddress), static_cast<unsigned long long>(address.addressPrecision));
lines.emplace_back(line);
if (snapshots != nullptr) {
const auto correlated = DeviceFaultBatchLines(address.addressType, address.reportedAddress, address.addressPrecision, effectiveSerial, *snapshots);
lines.insert(lines.end(), correlated.begin(), correlated.end());
}
const auto live = LiveResourceRing::Instance().LinesFor(address.reportedAddress);
lines.insert(lines.end(), live.begin(), live.end());
try {
DeviceFaultResidencyProbe probe{};
bool hasProbe = false;
if (residencyFor != nullptr) {
probe = residencyFor(address.reportedAddress);
hasProbe = true;
}
if (!hasProbe) {
char residency[128];
std::snprintf(residency, sizeof(residency), "[device-fault] residency 0x%llx unknown", static_cast<unsigned long long>(address.reportedAddress));
lines.emplace_back(residency);
} else {
const auto verdict = DeviceFaultResidencyLines(address.reportedAddress, effectiveSerial, snapshots, probe);
lines.insert(lines.end(), verdict.begin(), verdict.end());
}
} catch (...) {
char residency[128];
std::snprintf(residency, sizeof(residency), "[device-fault] residency 0x%llx unknown", static_cast<unsigned long long>(address.reportedAddress));
lines.emplace_back(residency);
}
}
for (const auto& vendor : vendors) {
std::snprintf(line, sizeof(line), "[device-fault] vendor: %s (code 0x%llx, data 0x%llx)", DeviceFaultText(vendor.description).c_str(), static_cast<unsigned long long>(vendor.vendorFaultCode), static_cast<unsigned long long>(vendor.vendorFaultData));
lines.emplace_back(line);
}
if (addresses.empty() && points.empty() && effectiveBracket.submitSerial != 0) lines.emplace_back("[device-fault] no device-side fault data; CPU-side bracket only");
} catch (...) {
}
return lines;
}
}
#endif
@@ -31,6 +31,7 @@ extern "C" void AgcDriverLockVulkanLoader_nid_postfix();
extern "C" void AgcDriverUnlockVulkanLoader_nid_postfix();
extern "C" void AgcDriverShutdown_nid_postfix();
extern "C" void AgcDriverRequestScreenshot_nid_postfix();
extern "C" void AgcDriverTracePresent_nid_postfix(std::uint32_t width, std::uint32_t height);
extern "C" void AgcDriverSuspendPoint_nid_postfix();
extern "C" void AgcDriverSerialProgress_nid_postfix(std::uint64_t* accepted, std::uint64_t* completed);
extern "C" std::size_t AgcDriverAwaitedWaits_nid_postfix(AgcDriver::AwaitedWait* waits, std::size_t capacity);
@@ -69,6 +69,7 @@ struct DispatchVariant {
std::vector<std::array<std::uint32_t, 3>> descriptorPatches;
std::uint64_t calleeWords = 0;
std::vector<std::pair<std::uint32_t, std::uint32_t>> calleeReads;
std::shared_ptr<DispatchVariant> donor;
std::vector<std::pair<std::uint32_t, std::uint32_t>> shaderDataPatches;
std::uint64_t userDataMask = ~std::uint64_t{0};
std::shared_ptr<const ShaderRecompiler::ShaderVertexStageInfo> vertexInfo;
@@ -88,7 +89,7 @@ struct DispatchEntry {
};
struct EntryCounters {
std::uint64_t lookups = 0, absent = 0, equal = 0, differing = 0, inaccessible = 0, queuedLabel = 0, flushingImage = 0, publishMoved = 0, pendingMoved = 0, forgetMoved = 0, imagesFlushed = 0, runsSynced = 0, forgetSinceInsert = 0, replaced = 0, inserts = 0, unstable = 0, touches = 0;
std::uint64_t lookups = 0, absent = 0, equal = 0, differing = 0, queuedStores = 0, inaccessible = 0, queuedLabel = 0, flushingImage = 0, publishMoved = 0, pendingMoved = 0, forgetMoved = 0, imagesFlushed = 0, runsSynced = 0, forgetSinceInsert = 0, replaced = 0, inserts = 0, unstable = 0, touches = 0;
std::uint64_t runsValidated = 0, runsInserted = 0, retriesEqual = 0, retriesMoved = 0;
double validateUs = 0;
@@ -112,7 +113,7 @@ struct DataMask {
std::vector<std::pair<std::uint32_t, std::uint32_t>>* live;
};
enum class EntryOutcome { Equal, EqualData, Differing, Inaccessible, QueuedLabel, FlushingImage, PublishMoved, PendingMoved, ForgetMoved };
enum class EntryOutcome { Equal, EqualData, Differing, QueuedStores, Inaccessible, QueuedLabel, FlushingImage, PublishMoved, PendingMoved, ForgetMoved };
bool CacheableResult(const ShaderRecompiler::RecompileResult& compiled);
@@ -79,6 +79,7 @@ struct DrawEntry {
std::uint64_t touched = 0;
std::list<std::uint64_t>::iterator order;
std::uint64_t shape = 0;
std::shared_ptr<DrawEntry> donor;
};
using DrawDataCandidates = std::vector<std::vector<std::pair<std::shared_ptr<DispatchVariant>, std::vector<ShaderRecompiler::MemoryRegion>>>>;
@@ -88,7 +89,7 @@ struct StageDataHit {
std::shared_ptr<const ShaderRecompiler::RecompileResult> compiled;
};
enum class DrawMiss : std::size_t { FrontDiffering, FragmentDiffering, OtherDiffering, Layout, Gate, Stages, Count };
enum class DrawMiss : std::size_t { FrontDiffering, FragmentDiffering, OtherDiffering, QueuedStores, Layout, Gate, Stages, Count };
struct DrawEntryCounters {
std::uint64_t lookups = 0, absent = 0, hits = 0, stageValidations = 0, stageEqual = 0, variantsCompared = 0, inserts = 0, shapeUpdates = 0, variantsInserted = 0, variantsEvicted = 0, present = 0, unstable = 0, touches = 0, verifyHits = 0, verifyMismatches = 0;
@@ -31,6 +31,7 @@ public:
};
enum class DrainReason : std::uint8_t { Packet, Flush, Labels, Capture, Indirect, Submission, Count };
enum class QueuedWrite : std::uint8_t { None, Stored, Unknown };
enum class CommitKind : std::uint8_t { Other, Draw, IndirectDraw, ColorMetadata, Dispatch, SampleDump, DmaFill, DmaWrite, DmaCopy, Store, EndOfPipe, Seal, SubmitEnd, Completion, BufferFill, Count };
static DrawPipeline& Queue0();
static std::size_t Depth();
@@ -41,7 +42,9 @@ public:
static unsigned Committers();
void Enqueue(Commit commit, std::vector<Range> writes, std::uint64_t labelAddress = 0, std::vector<std::byte> labelBytes = {}, std::vector<Range> reads = {}, bool draw = false);
void Enqueue(CommitKind kind, Commit commit, std::vector<Range> writes, std::uint64_t labelAddress = 0, std::vector<std::byte> labelBytes = {}, std::vector<Range> reads = {}, bool draw = false);
void EnqueueStore(Commit commit, std::uint64_t address, std::vector<std::byte> bytes);
static void NoteDrawKey(std::uint64_t key, std::uint64_t shape);
void Drain(DrainReason reason, std::uint32_t opcode = 0x100);
void Stop();
void ReleaseRetired();
@@ -74,6 +77,7 @@ private:
std::vector<Range> reads;
bool draw = false;
bool store = false;
CommitKind kind = CommitKind::Other;
};
DrawPipeline() = default;
void enqueue(Item item);
@@ -111,6 +115,8 @@ private:
std::array<std::uint64_t, 257> drainOpcodes{};
std::array<std::atomic<std::uint64_t>, 257> drainRequests{};
std::array<std::atomic<std::uint64_t>, static_cast<std::size_t>(DrainReason::Count)> reasonRequests{};
std::array<std::atomic<std::uint64_t>, static_cast<std::size_t>(CommitKind::Count)> kindCommits{};
std::array<std::atomic<std::uint64_t>, static_cast<std::size_t>(CommitKind::Count)> kindNs{};
std::uint64_t depthSum = 0;
std::chrono::steady_clock::time_point lastReport = std::chrono::steady_clock::now();
};
@@ -84,6 +84,7 @@ public:
void UnregisterVideoOutput(std::uint32_t handle, const std::shared_ptr<IVideoOutput>& output);
void AttachWindow(const PresentationWindow& window);
void Present(const PresentationWindow& window, const DisplayBuffer* buffer, const DisplayBuffer* plane, bool opaque, void (*gpuReady)(void*), void* context);
void TracePresent(std::uint32_t width, std::uint32_t height);
void ReleaseWindow(void* window);
void RegisterShader(const Shader* shader);
void ResolveShaderAbi(const Shader* shader, std::span<const ShaderRegister> context, std::span<const ShaderRegister> primitive);
@@ -199,8 +200,8 @@ private:
void insertDrawEntry(std::uint64_t key, std::vector<std::shared_ptr<DispatchVariant>>& fresh, std::shared_ptr<const DrawDecode> decode, std::uint64_t shape = 0, bool replaceShape = false);
bool admitDrawKey(std::uint64_t key, std::uint64_t shape);
void eraseDrawEntry(std::uint64_t key, const std::shared_ptr<DrawEntry>& expected);
std::shared_ptr<const DrawRecipe> findDrawRecipe(std::uint64_t key, const std::vector<std::shared_ptr<DispatchVariant>>& stages);
void attachDrawRecipe(std::uint64_t key, const std::vector<std::shared_ptr<DispatchVariant>>& stages, std::shared_ptr<const DrawRecipe> recipe);
std::shared_ptr<const DrawRecipe> findDrawRecipe(std::uint64_t key, const std::vector<std::shared_ptr<DispatchVariant>>& stages, const std::shared_ptr<DrawEntry>& donor = nullptr);
void attachDrawRecipe(std::uint64_t key, const std::vector<std::shared_ptr<DispatchVariant>>& stages, std::shared_ptr<const DrawRecipe> recipe, const std::shared_ptr<DrawEntry>& donor = nullptr);
static bool traceDrawCache();
static void traceInsert(std::unordered_set<std::uint64_t>& set, std::uint64_t key);
void maybeReportDrawCache(bool profile);
@@ -302,7 +303,7 @@ private:
void noteForeignWriter(std::uint64_t begin, std::uint64_t end, std::uint32_t queue);
void noteDrawWriters(std::span<const Graphics::CompiledShader> stages, std::uint32_t queue);
static std::vector<std::pair<std::uint64_t, std::uint64_t>> drawWriteRanges(const Graphics::State& graphics, std::span<const Graphics::CompiledShader> stages);
void commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, VulkanDevice::DrawTraceContext trace = {}, std::uint64_t shape = 0);
void commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, const std::shared_ptr<DrawEntry>& recipeDonor, VulkanDevice::DrawTraceContext trace = {}, std::uint64_t shape = 0);
bool labelPacketQueues(std::span<const std::uint32_t> packet, std::uint32_t opcode);
bool enqueueLabelPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue, std::optional<std::uint32_t> interrupt);
bool enqueueDmaPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue, const QueueState& state);
@@ -12,6 +12,7 @@
#include <map>
#include <memory>
#include <set>
#include <span>
#include <thread>
#include <unordered_map>
#include <unordered_set>
@@ -59,6 +60,13 @@ struct QueueWorker {
std::thread thread;
};
struct ReferencedProgramScan {
std::vector<std::uint64_t> addresses;
bool complete = true;
};
ReferencedProgramScan ReferencedPrograms(std::span<const std::uint32_t> commands, const std::map<std::size_t, std::vector<std::uint32_t>>& registerLists);
}
#endif
@@ -4,6 +4,7 @@
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <mutex>
#include <span>
#include <string_view>
@@ -16,6 +17,17 @@ std::size_t SubmissionRingCapacity();
std::chrono::seconds StallWatchdogPeriod();
using StallClock = std::chrono::steady_clock::time_point (*)();
void SetStallClock(StallClock clock);
enum class StallChoice { Wait, Quit, Unavailable };
using StallPresenter = StallChoice (*)(const char* message);
void SetStallPresenter(StallPresenter presenter);
StallChoice ShowStallPrompt(const char* message);
bool StallPromptEnabled();
bool ReadSubmissionRingSettings();
void PrepareSubmissionRing(std::uint32_t queue);
@@ -28,12 +40,14 @@ class StallWatch {
public:
explicit StallWatch(std::uint32_t queue) : queue(queue) {}
void Progressed() { since = {}; }
void Check(const char* waiter, std::uint64_t value);
void Check(const char* waiter, std::uint64_t value, std::unique_lock<std::mutex>* held = nullptr);
private:
std::uint32_t queue;
std::chrono::steady_clock::time_point since{};
bool dumped = false;
bool finished = false;
int prompts = 0;
};
}
@@ -332,6 +332,7 @@ void PublishRegisteredShader(std::shared_ptr<ShaderRegistry>& registry, const st
void SubmitRegistrationPreparation(std::function<void()> task, const PreparedShaders* prepared = nullptr);
void PrioritizeRegistrationPreparation(PreparedShaders& prepared);
void AwaitRegistrationPreparation();
void AwaitReferencedPreparations(const ShaderRegistry& registry, std::span<const std::uint64_t> addresses);
void SubmitLibraryPrebuild(std::function<void()> task, std::uint64_t program = 0);
bool LibraryPrebuildsWaiting();
void PrioritizeLibraryPrebuilds(std::span<const std::uint64_t> programs);
@@ -8,11 +8,13 @@ namespace AgcDriver {
struct Float32FlushControl {
bool probe = false;
bool declared = false;
bool computeOnly = false;
};
inline Float32FlushControl Float32FlushControlFor(VkDriverId driver, VkBool32 flushToZero, VkShaderFloatControlsIndependence independence) {
const bool declared = flushToZero == VK_TRUE && independence != VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE;
return {declared || driver == VK_DRIVER_ID_MOLTENVK || driver == VK_DRIVER_ID_NVIDIA_PROPRIETARY, declared};
const bool kosmicKrisp = driver == VK_DRIVER_ID_MESA_KOSMICKRISP;
return {declared || driver == VK_DRIVER_ID_MOLTENVK || kosmicKrisp || driver == VK_DRIVER_ID_NVIDIA_PROPRIETARY, declared, kosmicKrisp};
}
}
@@ -8,6 +8,7 @@
#include <functional>
#include <mutex>
#include <span>
#include <string>
#include <utility>
#include <vector>
@@ -94,6 +95,7 @@ bool UnchangedCommittedSince(std::span<const std::pair<std::uint64_t, std::uint6
// UnchangedSince(range, it) holds until the next store over the range.
std::uint64_t MarkWritten(std::uint64_t address, std::size_t bytes);
std::uint64_t MarkPossiblyWritten(std::uint64_t address, std::size_t bytes);
std::uint64_t MarkPossiblyWritten(std::uint64_t address, std::size_t bytes, std::uint64_t& order);
std::uint64_t StoreOwnBytes(std::uint64_t address, std::size_t bytes, const std::function<void()>& store);
std::uint64_t StoreOwnBytes(std::uint64_t address, std::span<const std::byte> source);
bool StoredOver(std::uint64_t address, std::size_t bytes, std::uint64_t generation);
@@ -216,9 +218,22 @@ unsigned long long CodeOffset(const void* address);
// every read and store through this interface calls first. Code that reads guest memory directly
// calls FlushGpuWrites itself.
void SetFlushHook(void (*hook)(std::uint64_t address, std::size_t bytes));
auto CurrentFlushHook() -> void (*)(std::uint64_t address, std::size_t bytes);
void SetReadGuard(void (*guard)(std::uint64_t address, std::size_t bytes));
void GuardRead(std::uint64_t address, std::size_t bytes);
void FlushGpuWrites(std::uint64_t address, std::size_t bytes);
void PrepareHostWrite(std::uintptr_t address, std::size_t bytes);
bool StopHostWrites(std::uint32_t boundMs);
std::uint64_t LockedHostWrites();
struct HostWriteCounts {
std::uint64_t calls = 0;
std::uint64_t waited = 0;
double waitedMs = 0;
double maxWaitedMs = 0;
};
HostWriteCounts HostWritesCounted();
void SetWaitedMsProvider(double (*provider)());
std::string HostWriteReport();
// Moves with every ForgetPages call (the libc invalidator: memory unmapped or re-registered): odd
// while the call stores its page states, moved past it after, so a reader that loads an even
// value before consulting the page states and reading directly, and the same value after, knows
@@ -8,16 +8,12 @@
#include <cstdint>
#include <cstdlib>
#include <thread>
#if defined(__x86_64__) || defined(_M_X64)
#include <immintrin.h>
#endif
#include "prx/libc/include/PreciseWait.hpp"
namespace AgcDriver {
inline void SpinPause() {
#if defined(__x86_64__) || defined(_M_X64)
_mm_pause();
#endif
PreciseSpinPause();
}
inline unsigned UsableProcessors() {
@@ -81,6 +81,7 @@ struct DrawArguments {
// path (which waits for recorded GPU work that writes them).
DrawArguments ReadDrawArguments(const DrawParameters::IndirectDraw& indirect, std::uint32_t record);
std::uint32_t ReadDrawCount(const DrawParameters::IndirectDraw& indirect);
DrawArguments ReadDrawArgumentsUnsynced(const DrawParameters::IndirectDraw& indirect, std::uint32_t record);
inline bool IndirectDrawOpcode(std::uint32_t opcode) { return opcode == 0x24 || opcode == 0x25 || opcode == 0x2c || opcode == 0x38; }
inline bool DrawOpcode(std::uint32_t opcode) { return opcode == 0x27 || opcode == 0x2d || opcode == 0x35 || IndirectDrawOpcode(opcode); }
@@ -155,7 +156,9 @@ inline constexpr std::uint32_t DmaSourceData = 2;
inline constexpr std::uint32_t DmaDestinationNowhere = 2;
inline std::size_t DmaBytes(std::span<const std::uint32_t> packet) { return packet[6] & 0x3ffffffu; }
inline constexpr std::uint32_t CopyDataGpuClockSource = 18;
inline constexpr std::uint32_t CopyDataSelectGds = 6;
inline std::uint32_t CopyDataSource(std::span<const std::uint32_t> packet) { return ((packet[1] & 0xfu) << 1u) | ((packet[1] >> 30u) & 1u); }
inline std::uint32_t CopyDataDestination(std::span<const std::uint32_t> packet) { return ((packet[1] >> 8u) & 0xfu) << 1u; }
inline bool CopyDataImmediate(std::uint32_t source) { return source >= 10 && source != CopyDataGpuClockSource; }
inline bool CopyDataToRegister(std::span<const std::uint32_t> packet) { return ((packet[1] >> 8u) & 0xfu) == 0; }
inline std::size_t CopyDataBytes(std::span<const std::uint32_t> packet) { return (packet[1] & 0x10000u) != 0 ? 8 : 4; }
@@ -3,6 +3,7 @@
#define VK_NO_PROTOTYPES
#include <vulkan/vulkan.h>
#include "prx/libSceAgcDriver/Execution/include/AspectFit.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Context.hpp"
#include <cstddef>
#include <cstdint>
@@ -29,6 +30,7 @@ public:
void Bind(std::size_t slot, VkImage image, std::uint32_t width, std::uint32_t height, std::uint64_t pixelFormat, float whiteNits, std::uint32_t layer = 0);
void BindTexels(std::size_t slot, VkCommandBuffer commands, std::span<const std::byte> texels, std::uint32_t width, std::uint32_t height, std::uint64_t pixelFormat, float whiteNits);
void RecordPresent(VkCommandBuffer commands, std::size_t slot, VkImage destination, VkFormat format, VkColorSpaceKHR colorSpace, VkExtent2D extent, VkImageLayout finalLayout);
void RecordStage(VkCommandBuffer commands, std::size_t slot, VkImage destination, VkFormat format, VkColorSpaceKHR colorSpace, VkExtent2D extent, VkImageLayout finalLayout);
void RecordOverlay(VkCommandBuffer commands, std::size_t slot, VkImage destination, VkFormat format, VkColorSpaceKHR colorSpace, VkExtent2D extent, VkImageLayout initialLayout, VkImageLayout finalLayout);
void RecordDump(VkCommandBuffer commands, std::size_t slot, std::uint32_t stride, VkBuffer destination);
void RecordDumpImage(VkCommandBuffer commands, std::size_t slot, std::uint32_t stride);
@@ -38,6 +40,7 @@ public:
void Release(std::size_t slot) noexcept;
static bool TenBitFormat(VkFormat format);
static VkExtent2D DumpExtent(std::uint32_t width, std::uint32_t height, std::uint32_t stride);
static VkSubpassDependency ExitDependency(VkImageLayout finalLayout);
private:
struct Target {
@@ -72,6 +75,7 @@ private:
void ensureUploadImage(Slot& slot, VkExtent2D extent);
void releaseUploadImage(Slot& slot) noexcept;
void draw(VkCommandBuffer commands, const Slot& slot, const Target& target, VkFramebuffer framebuffer, VkExtent2D extent, VkRect2D scissor, const std::int32_t (&parameters)[9]) const;
void recordInto(VkCommandBuffer commands, std::size_t slot, VkImage destination, VkFormat format, VkColorSpaceKHR colorSpace, VkExtent2D extent, VkImageLayout finalLayout, const AspectFitRect& rect);
void release() noexcept;
Graphics::Context context;
@@ -32,6 +32,8 @@ public:
// The aspect-fitting blit of RecordBlit from any image: presenting a resident render target needs
// no copy into the source image first.
static void RecordBlitFrom(const Graphics::Context& context, VkCommandBuffer commands, VkImage image, VkImageLayout layout, std::uint32_t width, std::uint32_t height, VkFilter filter, VkImage destinationImage, std::uint32_t destinationWidth, std::uint32_t destinationHeight, std::uint32_t layer = 0);
void RecordStretch(VkCommandBuffer commands, VkImage destinationImage, const AspectFitRect& destination);
static void RecordStretchFrom(const Graphics::Context& context, VkCommandBuffer commands, VkImage image, VkImageLayout layout, std::uint32_t width, std::uint32_t height, VkFilter filter, VkImage destinationImage, const AspectFitRect& destination, std::uint32_t layer = 0);
void RecordLetterbox(VkCommandBuffer commands, std::uint32_t width, std::uint32_t height, VkImage destinationImage, std::uint32_t destinationWidth, std::uint32_t destinationHeight);
static std::vector<AspectFitRect> LetterboxBands(std::uint32_t width, std::uint32_t height, std::uint32_t destinationWidth, std::uint32_t destinationHeight);
std::uint32_t SourceWidth() const { return sourceWidth; }
@@ -0,0 +1,77 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_PRESENTATIONUPSCALER_HPP
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_PRESENTATIONUPSCALER_HPP
#define VK_NO_PROTOTYPES
#include <vulkan/vulkan.h>
#include "prx/libSceAgcDriver/Graphics/include/Context.hpp"
#include <cstdint>
#include <map>
#include <tuple>
#include <utility>
#include <vector>
namespace AgcDriver {
class PresentationUpscaler {
public:
PresentationUpscaler(const Graphics::Context& context, std::size_t slots, float sharpness);
~PresentationUpscaler();
PresentationUpscaler(const PresentationUpscaler&) = delete;
PresentationUpscaler& operator=(const PresentationUpscaler&) = delete;
static bool Upscales(std::uint32_t width, std::uint32_t height, VkExtent2D extent);
static VkExtent2D StageExtent(std::uint32_t width, std::uint32_t height, VkExtent2D extent);
VkImage Stage(std::size_t slot, VkFormat format, VkExtent2D extent);
void RecordStageTransferDestination(VkCommandBuffer commands, std::size_t slot);
void RecordStageWritten(VkCommandBuffer commands, std::size_t slot, VkImageLayout layout, VkPipelineStageFlags stage, VkAccessFlags access);
void RecordUpscale(VkCommandBuffer commands, std::size_t slot, VkImage destination, VkExtent2D extent, VkImageLayout finalLayout);
void RecordPresent(VkCommandBuffer commands, std::size_t slot, std::uint32_t width, std::uint32_t height, VkImage destination, VkExtent2D extent, VkImageLayout finalLayout);
void Release(std::size_t slot) noexcept;
float Sharpness() const { return sharpness; }
private:
enum class Filter { Easu, Rcas };
struct Target {
VkRenderPass renderPass = VK_NULL_HANDLE;
VkPipeline pipeline = VK_NULL_HANDLE;
};
struct Surface {
VkImage image = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
VkImageView sampled = VK_NULL_HANDLE;
VkFormat format = VK_FORMAT_UNDEFINED;
VkExtent2D extent{};
};
struct Slot {
Surface stage;
Surface upscaled;
VkDescriptorSet easuSet = VK_NULL_HANDLE;
VkDescriptorSet rcasSet = VK_NULL_HANDLE;
std::vector<std::pair<VkImageView, VkFramebuffer>> transient;
};
const Target& target(VkFormat format, VkImageLayout finalLayout, Filter filter);
void ensureSurface(Surface& surface, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage);
void releaseSurface(Surface& surface) noexcept;
VkImageView createView(VkImage image, VkFormat format, VkImageUsageFlags usage) const;
VkFramebuffer transientFramebuffer(Slot& slot, VkRenderPass renderPass, VkImage image, VkFormat format, VkExtent2D extent, VkImageLayout finalLayout);
void bindSource(VkDescriptorSet set, VkImageView view) const;
void draw(VkCommandBuffer commands, const Target& target, VkFramebuffer framebuffer, VkExtent2D extent, VkDescriptorSet set, const void* parameters, std::uint32_t size) const;
void release() noexcept;
Graphics::Context context;
float sharpness;
VkSampler sampler = VK_NULL_HANDLE;
VkDescriptorSetLayout descriptorLayout = VK_NULL_HANDLE;
VkPipelineLayout pipelineLayout = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
VkShaderModule vertex = VK_NULL_HANDLE;
VkShaderModule easu = VK_NULL_HANDLE;
VkShaderModule rcas = VK_NULL_HANDLE;
std::map<std::tuple<VkFormat, VkImageLayout, Filter>, Target> targets;
std::vector<Slot> slots;
};
}
#endif
@@ -15,12 +15,20 @@ namespace AgcDriver {
using FaultToken = std::uint32_t;
enum class FaultStage : std::uint32_t { unknown = 0, graphics = 1, compute = 2, mesh = 3, task = 4, copy = 5 };
struct FaultTokenEntry {
alignas(std::atomic_ref<FaultToken>::required_alignment) mutable FaultToken token = 0;
std::uint64_t submitSerial = 0;
std::uint64_t programAddress = 0;
std::uint64_t variantId = 0;
char desc[48]{};
std::uint32_t stage = 0;
std::uint64_t argBuffer = 0;
std::uint32_t argOffset = 0;
std::uint32_t argStride = 0;
std::uint32_t argWords[4] = {};
std::uint32_t argCount = 0;
};
struct SubmitBracket {
@@ -62,6 +70,12 @@ public:
copy.programAddress = slot.programAddress;
copy.variantId = slot.variantId;
for (std::size_t i = 0; i < 48; ++i) copy.desc[i] = slot.desc[i];
copy.stage = slot.stage;
copy.argBuffer = slot.argBuffer;
copy.argOffset = slot.argOffset;
copy.argStride = slot.argStride;
for (std::size_t i = 0; i < 4; ++i) copy.argWords[i] = slot.argWords[i];
copy.argCount = slot.argCount;
if (std::atomic_ref<FaultToken>(slot.token).load(std::memory_order_acquire) != token) return std::nullopt;
copy.token = token;
return copy;
@@ -7,6 +7,8 @@
namespace AgcDriver {
inline constexpr std::uint64_t SwapchainAcquireTimeoutNs = 1000000;
inline std::uint32_t SwapchainImageCount(const VkSurfaceCapabilitiesKHR& surface) {
const std::uint32_t count = std::max(surface.minImageCount, 3u);
return surface.maxImageCount != 0 ? std::min(count, surface.maxImageCount) : count;
@@ -8,6 +8,7 @@ namespace AgcDriver {
class TraceFile {
public:
static std::filesystem::path Directory();
static void WriteGzip(const std::filesystem::path& path, std::string_view text);
static void ReplaceGzip(const std::filesystem::path& path, std::string_view text);
static void AppendLine(const std::filesystem::path& path, std::string_view line);
@@ -0,0 +1,34 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_UPSCALEMODE_HPP
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_UPSCALEMODE_HPP
#include <charconv>
#include <cmath>
#include <stdexcept>
#include <string_view>
namespace AgcDriver {
struct UpscaleMode {
bool fsr = false;
float sharpness = 0.2f;
};
inline UpscaleMode SelectUpscaleMode(const char* upscale, const char* sharpness) {
UpscaleMode mode;
if (upscale != nullptr && *upscale != '\0') {
if (std::string_view(upscale) != "fsr") throw std::runtime_error("Vulkan presentation: ANYPS5_UPSCALE must be fsr or unset");
mode.fsr = true;
}
if (sharpness != nullptr && *sharpness != '\0') {
const std::string_view text(sharpness);
float value = 0.0f;
const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
if (error != std::errc{} || end != text.data() + text.size() || !std::isfinite(value) || value < 0.0f || value > 2.0f) throw std::runtime_error("Vulkan presentation: ANYPS5_FSR_SHARPNESS must be a number from 0.0 to 2.0");
mode.sharpness = value;
}
return mode;
}
}
#endif
@@ -295,6 +295,7 @@ public:
std::uint64_t checked, presyncs, keyChecks, keyWaits;
};
static PresyncStatistics PresyncCounts();
static std::uint64_t UpscaledPresents();
// Stage A of a dispatch's resource build, run WITHOUT GuestMemory::GpuMutex before Dispatch or
// DispatchIndirect: the binding plan, data buffers, imports already serving the guest buffers,
// read-only copies and the descriptor set (see ShaderResources). The dispatch completes it
@@ -354,6 +355,7 @@ public:
enum class DrawRecipePrecheck : std::size_t { NoRecipe, Device };
static void NoteDrawRecipeMiss(DrawRecipePrecheck miss);
using DrawTraceContext = Graphics::DrawTraceContext;
static std::uint64_t DrawRecipeHits();
// `recipe`, when given, receives the DrawRecipe a recorded, cacheable, reusable, direct draw
// built for its draw-cache entry (design_cpu_final M8); null otherwise.
void Draw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders, std::span<const Graphics::GuestMemorySnapshot> snapshots = {}, std::shared_ptr<const DrawRecipe>* recipe = nullptr, const DrawTraceContext* trace = nullptr, std::uint64_t shape = 0);
@@ -239,7 +239,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
static const bool keyHygiene = std::getenv("APS5_NO_DISPATCH_KEY_HYGIENE") == nullptr;
if (keyHygiene) {
for (const auto offset : {0x207u, 0x208u, 0x209u, 0x212u, 0x213u}) {
for (const auto offset : {0x207u, 0x208u, 0x209u, 0x212u, 0x213u, 0x228u}) {
const auto found = queue.shader.find(offset);
mix(found == queue.shader.end() ? (1ull << 32u) : found->second);
@@ -517,7 +517,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
const auto epoch = DrawPipeline::EpochToken().load(std::memory_order_relaxed);
const auto queueId = submission.queue;
itemCommits.fetch_add(1, std::memory_order_relaxed);
DrawPipeline::Queue0().Enqueue([this, localDevice = std::move(localDevice), result = compiledResult, capture, registeredViews, snapshots = std::move(snapshots), liveWords = std::move(liveWords), groups, address, queueId, recipe, keepVariant, dataHit, epoch, htileClearCompletion, htileMask] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Dispatch, [this, localDevice = std::move(localDevice), result = compiledResult, capture, registeredViews, snapshots = std::move(snapshots), liveWords = std::move(liveWords), groups, address, queueId, recipe, keepVariant, dataHit, epoch, htileClearCompletion, htileMask] {
DrawPipeline::FollowEpoch(epoch);
GuestMemory::SetCurrentPacket(0x15, queueId);
const auto& compiledCommit = *result;
@@ -58,7 +58,7 @@ void Driver::classifyDiffering(std::uint64_t program, std::uint64_t key, const D
void Driver::reportDispatchCache(EntryCounters& counters) {
const auto count = [](std::uint64_t value) { return static_cast<unsigned long long>(value); };
const auto validated = counters.lookups - counters.absent;
AgcDriver::ProfilePrint_nid_no_patch("[dispatch-cache] %llu lookups (10 s): %llu no entry, %llu validated by value in %.1f us each: %llu equal, %llu differing, %llu page not mapped, %llu queued label, %llu image being stored, %llu publish generation moved, %llu pending serial moved, %llu forget serial moved (%llu pending images stored first, %llu pending runs synced first, %llu equal entries inserted before a forget; gate retried %llu: %llu equal, %llu moved again); runs per entry %.1f validated / %.1f inserted; %llu misses found the entry replaced meanwhile; %llu inserts (%llu captures not kept: unstable), %llu evictions in total, %zu entries, %llu LRU moves\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast<double>(validated) : 0.0, count(counters.equal), count(counters.differing), count(counters.inaccessible), count(counters.queuedLabel), count(counters.flushingImage), count(counters.publishMoved), count(counters.pendingMoved), count(counters.forgetMoved), count(counters.imagesFlushed), count(counters.runsSynced), count(counters.forgetSinceInsert), count(counters.retriesEqual + counters.retriesMoved), count(counters.retriesEqual), count(counters.retriesMoved), validated != 0 ? static_cast<double>(counters.runsValidated) / static_cast<double>(validated) : 0.0, counters.inserts != 0 ? static_cast<double>(counters.runsInserted) / static_cast<double>(counters.inserts) : 0.0, count(counters.replaced), count(counters.inserts), count(counters.unstable), count(dispatchCacheEvictions), dispatchCache.size(), count(counters.touches));
AgcDriver::ProfilePrint_nid_no_patch("[dispatch-cache] %llu lookups (10 s): %llu no entry, %llu validated by value in %.1f us each: %llu equal, %llu differing, %llu recaptured over queued stores, %llu page not mapped, %llu queued label, %llu image being stored, %llu publish generation moved, %llu pending serial moved, %llu forget serial moved (%llu pending images stored first, %llu pending runs synced first, %llu equal entries inserted before a forget; gate retried %llu: %llu equal, %llu moved again); runs per entry %.1f validated / %.1f inserted; %llu misses found the entry replaced meanwhile; %llu inserts (%llu captures not kept: unstable), %llu evictions in total, %zu entries, %llu LRU moves\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast<double>(validated) : 0.0, count(counters.equal), count(counters.differing), count(counters.queuedStores), count(counters.inaccessible), count(counters.queuedLabel), count(counters.flushingImage), count(counters.publishMoved), count(counters.pendingMoved), count(counters.forgetMoved), count(counters.imagesFlushed), count(counters.runsSynced), count(counters.forgetSinceInsert), count(counters.retriesEqual + counters.retriesMoved), count(counters.retriesEqual), count(counters.retriesMoved), validated != 0 ? static_cast<double>(counters.runsValidated) / static_cast<double>(validated) : 0.0, counters.inserts != 0 ? static_cast<double>(counters.runsInserted) / static_cast<double>(counters.inserts) : 0.0, count(counters.replaced), count(counters.inserts), count(counters.unstable), count(dispatchCacheEvictions), dispatchCache.size(), count(counters.touches));
std::vector<std::pair<std::uint64_t, std::uint64_t>> programs(counters.differingByProgram.begin(), counters.differingByProgram.end());
std::sort(programs.begin(), programs.end(), [](const auto& a, const auto& b) { return a.second > b.second; });
std::string top;
@@ -113,6 +113,7 @@ void Driver::lookupDispatch(std::uint64_t address, const Submission& submission,
case EntryOutcome::Equal: ++counters.equal; break;
case EntryOutcome::EqualData: ++counters.equal; break;
case EntryOutcome::Differing: ++counters.differing; break;
case EntryOutcome::QueuedStores: ++counters.queuedStores; break;
case EntryOutcome::Inaccessible: ++counters.inaccessible; break;
case EntryOutcome::QueuedLabel: ++counters.queuedLabel; break;
case EntryOutcome::FlushingImage: ++counters.flushingImage; break;
@@ -168,7 +169,7 @@ void Driver::lookupDispatch(std::uint64_t address, const Submission& submission,
}
}
} else {
if (traceCache) std::fprintf(stderr, "[dispatch-cache] 0x%llx captured memory changed\n", static_cast<unsigned long long>(address));
if (traceCache) std::fprintf(stderr, "[dispatch-cache] 0x%llx %s\n", static_cast<unsigned long long>(address), outcome == EntryOutcome::QueuedStores ? "queued stores over the captured memory" : "captured memory changed");
missedEntry = entry;
missedDiffering = outcome == EntryOutcome::Differing;
@@ -111,7 +111,7 @@ EntryOutcome Driver::validateVariant(std::uint64_t program, std::uint32_t queue,
if (DrawPipeline::Active()) {
auto& pipeline = DrawPipeline::Queue0();
if (pipeline.Busy() && pipeline.OverlapsAny(variant.runs)) {
if (!knownValueVerify() && QueuedWritesOver(pipeline, regions) == QueuedOverlap::Stored) return EntryOutcome::Differing;
if (!knownValueVerify() && QueuedWritesOver(pipeline, regions) == QueuedOverlap::Stored) return EntryOutcome::QueuedStores;
pipeline.Drain(DrawPipeline::DrainReason::Capture);
}
}
@@ -360,6 +360,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
using Stage = ShaderRecompiler::ShaderStage;
using Role = ShaderRecompiler::ProgramRole;
static const bool dumpGraphics = std::getenv("APS5_DUMP_GRAPHICS_SHADERS") != nullptr;
static const std::uint64_t dumpTarget = [] { const char* text = std::getenv("APS5_DUMP_DRAW_SHADERS"); return text ? std::strtoull(text, nullptr, 16) : 0ull; }();
static const std::uint64_t dumpSlot1 = [] { const char* text = std::getenv("APS5_DUMP_DRAW_SLOT1"); return text ? std::strtoull(text, nullptr, 16) : 0ull; }();
@@ -387,7 +388,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
timing.Mark("device_setup");
phaseTiming.Phase(DrawRowVectors);
const bool useDrawEntries = drawEntries() && !ShaderRecompiler::DebugProbeActive() && dumpTarget == 0 && dumpSlot1 == 0;
const bool useDrawEntries = drawEntries() && !ShaderRecompiler::DebugProbeActive() && !dumpGraphics && dumpTarget == 0 && dumpSlot1 == 0;
tail.registerKey = useDrawEntries && registerKeyEnabled();
const bool registerKey = tail.registerKey;
auto& drawKey = tail.drawKey;
@@ -416,6 +417,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
}
}
drawKey = drawRegisterKey(queue, *submission.shaders, localDevice->Serial(), &shapeKey, traceDrawCache() ? &drawKeyComponents : nullptr, aliasFirst ? relocation.get() : nullptr, aliasFirst ? &drawAlias : nullptr);
DrawPipeline::NoteDrawKey(drawKey, shapeKey);
if (DrawFinisher::Busy()) {
bool shapeMatters = false;
if (DrawFinisher::Overlap() && drawDataHits()) {
@@ -734,7 +736,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
tail.dumpTarget = dumpTarget;
tail.dumpSlot1 = dumpSlot1;
tail.packetOffset = packetOffset;
const bool handOff = pipelined && !drawParameters.indirect && !profile && !lockedPrepare && dumpTarget == 0 && dumpSlot1 == 0 && !tracePrograms && !verifyDrawDataHits() && deferredLabels().labels.empty() && DrawFinisher::Enabled();
const bool handOff = pipelined && !drawParameters.indirect && !profile && !lockedPrepare && !dumpGraphics && dumpTarget == 0 && dumpSlot1 == 0 && !tracePrograms && !verifyDrawDataHits() && deferredLabels().labels.empty() && DrawFinisher::Enabled();
if (handOff) {
tail.epoch = DrawPipeline::EpochToken().load(std::memory_order_relaxed);
tail.submissionSerial = submission.serial;
@@ -1204,10 +1206,10 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
auto commit = [this, localDevice = std::move(localDevice), decode = std::move(decode), direct, stages = std::move(stages), snapshots = std::move(snapshots), commitQueue, commitPacket, epoch, writablePrograms = std::move(writablePrograms), results = std::move(results), memory = std::move(memory), linked = std::move(linked), stageCaptures = std::move(stageCaptures), matched = std::move(matched), matchedRegions = std::move(matchedRegions), fresh = std::move(fresh), decodeReads = std::move(decodeReads), shaderMemory = std::move(shaderMemory), entry = std::move(entry), dataEntry = std::move(dataEntry), compiledStages = std::move(compiledStages), stageData = std::move(stageData)] {
DrawPipeline::FollowEpoch(epoch);
GuestMemory::SetCurrentPacket(commitPacket, commitQueue);
commitDraw(localDevice, commitQueue, decode->state, direct, stages, snapshots, nullptr, {}, 0);
commitDraw(localDevice, commitQueue, decode->state, direct, stages, snapshots, nullptr, {}, 0, nullptr);
};
auto held = std::make_shared<decltype(commit)>(std::move(commit));
DrawPipeline::Queue0().Enqueue([held] { (*held)(); }, std::move(writes));
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::IndirectDraw, [held] { (*held)(); }, std::move(writes));
phaseTiming.Phase(DrawRowLockWait);
timing.Mark("draw_enqueued");
return drawn();
@@ -1235,12 +1237,13 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
std::vector<std::shared_ptr<DispatchVariant>> recipeStages;
if (registerKey && !drawParameters.indirect && !patchedStages && !graphics.stages.tessellationGeometry && Graphics::DrawRecipes()) {
recipeStages.reserve(programs.size());
for (std::size_t i = 0; i < programs.size(); ++i) recipeStages.push_back(drawHit ? matched[i] : fresh[i]);
for (std::size_t i = 0; i < programs.size(); ++i) recipeStages.push_back(drawHit ? (matched[i] != nullptr && matched[i]->donor != nullptr ? matched[i]->donor : matched[i]) : fresh[i]);
if (std::all_of(recipeStages.begin(), recipeStages.end(), [](const std::shared_ptr<DispatchVariant>& variant) { return variant == nullptr; })) recipeStages.clear();
}
const auto recipeDonor = drawHit && entry != nullptr ? entry->donor : nullptr;
std::shared_ptr<const DrawRecipe> recipe;
if (drawHit && !recipeStages.empty()) {
recipe = findDrawRecipe(drawKey, recipeStages);
recipe = findDrawRecipe(drawKey, recipeStages, recipeDonor);
if (recipe == nullptr) VulkanDevice::NoteDrawRecipeMiss(VulkanDevice::DrawRecipePrecheck::NoRecipe);
}
if (recipe == nullptr) {
@@ -1270,13 +1273,13 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
const auto commitPacket = tail.packetOpcode;
const auto epoch = DrawFinisher::OnFinisherThread() ? tail.epoch : DrawPipeline::EpochToken().load(std::memory_order_relaxed);
auto reads = QueuedDrawReadRanges(drawParameters, stages);
auto commit = [this, localDevice = std::move(localDevice), decode = std::move(decode), drawParameters, stages = std::move(stages), snapshots = std::move(snapshots), recipe = std::move(recipe), recipeStages = std::move(recipeStages), drawKey, shape = tail.shapeKey, commitQueue, commitPacket, epoch, trace = trace, writablePrograms = std::move(writablePrograms), results = std::move(results), memory = std::move(memory), linked = std::move(linked), stageCaptures = std::move(stageCaptures), matched = std::move(matched), matchedRegions = std::move(matchedRegions), fresh = std::move(fresh), decodeReads = std::move(decodeReads), shaderMemory = std::move(shaderMemory), entry = std::move(entry), dataEntry = std::move(dataEntry), compiledStages = std::move(compiledStages), stageData = std::move(stageData)]() mutable {
auto commit = [this, localDevice = std::move(localDevice), decode = std::move(decode), drawParameters, stages = std::move(stages), snapshots = std::move(snapshots), recipe = std::move(recipe), recipeStages = std::move(recipeStages), drawKey, recipeDonor, shape = tail.shapeKey, commitQueue, commitPacket, epoch, trace = trace, writablePrograms = std::move(writablePrograms), results = std::move(results), memory = std::move(memory), linked = std::move(linked), stageCaptures = std::move(stageCaptures), matched = std::move(matched), matchedRegions = std::move(matchedRegions), fresh = std::move(fresh), decodeReads = std::move(decodeReads), shaderMemory = std::move(shaderMemory), entry = std::move(entry), dataEntry = std::move(dataEntry), compiledStages = std::move(compiledStages), stageData = std::move(stageData)]() mutable {
DrawPipeline::FollowEpoch(epoch);
GuestMemory::SetCurrentPacket(commitPacket, commitQueue);
commitDraw(localDevice, commitQueue, decode->state, drawParameters, stages, snapshots, recipe, recipeStages, drawKey, trace, shape);
commitDraw(localDevice, commitQueue, decode->state, drawParameters, stages, snapshots, recipe, recipeStages, drawKey, recipeDonor, trace, shape);
};
auto held = std::make_shared<decltype(commit)>(std::move(commit));
DrawPipeline::Queue0().Enqueue([held] { (*held)(); }, std::move(writes), 0, {}, std::move(reads), true);
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Draw, [held] { (*held)(); }, std::move(writes), 0, {}, std::move(reads), true);
phaseTiming.Phase(DrawRowLockWait);
timing.Mark("draw_enqueued");
return drawn();
@@ -1303,12 +1306,12 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
std::shared_ptr<const DrawRecipe> built;
localDevice->Draw(graphics, drawParameters, stages, snapshots, recipeStages.empty() ? nullptr : &built, tracePtr, tail.shapeKey);
phaseTiming.Phase(DrawRowGraphics);
if (built != nullptr) attachDrawRecipe(drawKey, recipeStages, std::move(built));
if (built != nullptr) attachDrawRecipe(drawKey, recipeStages, std::move(built), recipeDonor);
timing.Mark("draw_and_resource_release");
return drawn();
}
void Driver::commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, VulkanDevice::DrawTraceContext trace, std::uint64_t shape) {
void Driver::commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, const std::shared_ptr<DrawEntry>& recipeDonor, VulkanDevice::DrawTraceContext trace, std::uint64_t shape) {
const auto* tracePtr = trace.token != 0 ? &trace : nullptr;
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Draw);
std::lock_guard gpuLock(GuestMemory::GpuMutex());
@@ -1328,7 +1331,7 @@ void Driver::commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t
}
std::shared_ptr<const DrawRecipe> built;
localDevice->Draw(graphics, drawParameters, stages, snapshots, recipeStages.empty() ? nullptr : &built, tracePtr, shape);
if (built != nullptr) attachDrawRecipe(drawKey, recipeStages, std::move(built));
if (built != nullptr) attachDrawRecipe(drawKey, recipeStages, std::move(built), recipeDonor);
}
}
@@ -232,9 +232,11 @@ bool DecodeProgramsCurrent(const DrawDecode& decode, const ShaderRegistry&) {
});
}
std::shared_ptr<const DrawRecipe> Driver::findDrawRecipe(std::uint64_t key, const std::vector<std::shared_ptr<DispatchVariant>>& stages) {
std::shared_ptr<const DrawRecipe> Driver::findDrawRecipe(std::uint64_t key, const std::vector<std::shared_ptr<DispatchVariant>>& stages, const std::shared_ptr<DrawEntry>& donor) {
std::shared_ptr<const std::vector<DrawRecipeRecord>> records;
{
if (donor != nullptr) {
records = donor->recipes.load();
} else {
std::lock_guard cacheLock(drawCacheMutex);
const auto found = drawCache.find(key);
if (found == drawCache.end()) return nullptr;
@@ -247,24 +249,28 @@ std::shared_ptr<const DrawRecipe> Driver::findDrawRecipe(std::uint64_t key, cons
return nullptr;
}
void Driver::attachDrawRecipe(std::uint64_t key, const std::vector<std::shared_ptr<DispatchVariant>>& stages, std::shared_ptr<const DrawRecipe> recipe) {
std::shared_ptr<DrawEntry> entry;
{
void Driver::attachDrawRecipe(std::uint64_t key, const std::vector<std::shared_ptr<DispatchVariant>>& stages, std::shared_ptr<const DrawRecipe> recipe, const std::shared_ptr<DrawEntry>& donor) {
std::shared_ptr<DrawEntry> entry = donor;
if (entry == nullptr) {
std::lock_guard cacheLock(drawCacheMutex);
const auto found = drawCache.find(key);
if (found == drawCache.end()) return;
entry = found->second;
}
const auto old = entry->recipes.load();
auto records = std::make_shared<std::vector<DrawRecipeRecord>>();
records->push_back({std::vector<std::weak_ptr<const DispatchVariant>>(stages.begin(), stages.end()), std::move(recipe)});
if (old != nullptr) {
for (const auto& record : *old) {
if (record.Matches(stages) || record.Expired() || records->size() >= dispatchVariants()) continue;
records->push_back(record);
const DrawRecipeRecord attached{std::vector<std::weak_ptr<const DispatchVariant>>(stages.begin(), stages.end()), std::move(recipe)};
auto old = entry->recipes.load();
std::shared_ptr<const std::vector<DrawRecipeRecord>> records;
do {
auto next = std::make_shared<std::vector<DrawRecipeRecord>>();
next->push_back(attached);
if (old != nullptr) {
for (const auto& record : *old) {
if (record.Matches(stages) || record.Expired() || next->size() >= dispatchVariants()) continue;
next->push_back(record);
}
}
}
entry->recipes.store(std::move(records));
records = std::move(next);
} while (!entry->recipes.compare_exchange_strong(old, records));
VulkanDevice::NoteRecipe(VulkanDevice::RecipeEvent::Attach, VulkanDevice::RecipeKind::Draw);
}
@@ -32,7 +32,7 @@ void Driver::reportDrawCache(DrawEntryCounters& counters, bool profile) {
char line[1536];
std::uint64_t misses = 0;
for (const auto value : counters.misses) misses += value;
std::snprintf(line, sizeof(line), "[draw-cache] 10 s: %llu lookups, %llu hits (%.1f%%), %llu stage misses, %llu without an entry, %llu data-only hits (stages: %llu reused, %llu compiled; %llu verified); no entry: new registers %llu, user words/pointers only %llu, evicted %llu, seen but never inserted %llu; stage misses: front differing %llu, fragment differing %llu, other differing %llu, layout %llu, gate %llu, stage count %llu; differing captures: same runs %llu (%.1f words changed each), other runs %llu; %zu entries, %llu evicted (%llu over the byte budget)\n", count(counters.lookups), count(counters.hits), counters.lookups != 0 ? 100.0 * static_cast<double>(counters.hits) / static_cast<double>(counters.lookups) : 0.0, count(misses), count(counters.absent), count(counters.dataHits), count(counters.dataStagesReused), count(counters.dataStagesCompiled), count(counters.dataVerified), count(counters.absentNewRegisters), count(counters.absentUserWords), count(counters.absentEvicted), count(counters.absentNeverInserted), miss(DrawMiss::FrontDiffering), miss(DrawMiss::FragmentDiffering), miss(DrawMiss::OtherDiffering), miss(DrawMiss::Layout), miss(DrawMiss::Gate), miss(DrawMiss::Stages), count(counters.differingSameRuns), counters.differingSameRuns != 0 ? static_cast<double>(counters.differingWords) / static_cast<double>(counters.differingSameRuns) : 0.0, count(counters.differingRunsChanged), drawCache.size(), count(counters.evictions), count(counters.byteEvictions));
std::snprintf(line, sizeof(line), "[draw-cache] 10 s: %llu lookups, %llu hits (%.1f%%), %llu stage misses, %llu without an entry, %llu data-only hits (stages: %llu reused, %llu compiled; %llu verified); no entry: new registers %llu, user words/pointers only %llu, evicted %llu, seen but never inserted %llu; stage misses: front differing %llu, fragment differing %llu, other differing %llu, recaptured over queued stores %llu, layout %llu, gate %llu, stage count %llu; differing captures: same runs %llu (%.1f words changed each), other runs %llu; %zu entries, %llu evicted (%llu over the byte budget)\n", count(counters.lookups), count(counters.hits), counters.lookups != 0 ? 100.0 * static_cast<double>(counters.hits) / static_cast<double>(counters.lookups) : 0.0, count(misses), count(counters.absent), count(counters.dataHits), count(counters.dataStagesReused), count(counters.dataStagesCompiled), count(counters.dataVerified), count(counters.absentNewRegisters), count(counters.absentUserWords), count(counters.absentEvicted), count(counters.absentNeverInserted), miss(DrawMiss::FrontDiffering), miss(DrawMiss::FragmentDiffering), miss(DrawMiss::OtherDiffering), miss(DrawMiss::QueuedStores), miss(DrawMiss::Layout), miss(DrawMiss::Gate), miss(DrawMiss::Stages), count(counters.differingSameRuns), counters.differingSameRuns != 0 ? static_cast<double>(counters.differingWords) / static_cast<double>(counters.differingSameRuns) : 0.0, count(counters.differingRunsChanged), drawCache.size(), count(counters.evictions), count(counters.byteEvictions));
text += line;
std::snprintf(line, sizeof(line), "[draw-cache] register-key miss component changes (10 s): stable registers %llu, user data %llu, auxiliary registers %llu, device %llu, first shader set %llu, unchanged components %llu\n", count(counters.registerKeyMissChanges[0]), count(counters.registerKeyMissChanges[1]), count(counters.registerKeyMissChanges[2]), count(counters.registerKeyMissChanges[3]), count(counters.registerKeyMissChanges[4]), count(counters.registerKeyMissChanges[5]));
text += line;
@@ -75,7 +75,7 @@ std::string Driver::profileDrawCacheLines(const DrawEntryCounters& counters) {
std::snprintf(item, sizeof(item), "%s%llu", rank == 0 ? "" : " / ", count(counters.variantHitsByRank[rank]));
ranks += item;
}
append("[draw-cache] %llu lookups (10 s): %llu no entry, %llu validated in %.1f us each (key, lookup and every stage): %llu hits (every stage equal; stage hits by variant rank 1..k %s), misses by reason: front stage differing %llu, fragment differing %llu, other stage differing %llu, layout (push offset) %llu, gate %llu, stage count %llu; %llu stage validations (%llu equal, %.2f variants compared each); %llu inserts (%llu shape updates, %llu variants inserted, %llu evicted beyond k, %llu already present, %llu unstable), %zu entries (%llu variants, ~%.1f MiB of a %.1f MiB budget), %llu evictions in total (%llu over the byte budget), %llu LRU moves; verify: %llu hits captured again, %llu stages differed\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast<double>(validated) : 0.0, count(counters.hits), ranks.c_str(), miss(DrawMiss::FrontDiffering), miss(DrawMiss::FragmentDiffering), miss(DrawMiss::OtherDiffering), miss(DrawMiss::Layout), miss(DrawMiss::Gate), miss(DrawMiss::Stages), count(counters.stageValidations), count(counters.stageEqual), counters.stageValidations != 0 ? static_cast<double>(counters.variantsCompared) / static_cast<double>(counters.stageValidations) : 0.0, count(counters.inserts), count(counters.shapeUpdates), count(counters.variantsInserted), count(counters.variantsEvicted), count(counters.present), count(counters.unstable), drawCache.size(), count(drawCacheVariants), static_cast<double>(drawCacheVariantBytes) / (1024.0 * 1024.0), static_cast<double>(DrawCacheBytes()) / (1024.0 * 1024.0), count(drawCacheEvictions), count(drawCacheByteEvictions), count(counters.touches), count(counters.verifyHits), count(counters.verifyMismatches));
append("[draw-cache] %llu lookups (10 s): %llu no entry, %llu validated in %.1f us each (key, lookup and every stage): %llu hits (every stage equal; stage hits by variant rank 1..k %s), misses by reason: front stage differing %llu, fragment differing %llu, other stage differing %llu, recaptured over queued stores %llu, layout (push offset) %llu, gate %llu, stage count %llu; %llu stage validations (%llu equal, %.2f variants compared each); %llu inserts (%llu shape updates, %llu variants inserted, %llu evicted beyond k, %llu already present, %llu unstable), %zu entries (%llu variants, ~%.1f MiB of a %.1f MiB budget), %llu evictions in total (%llu over the byte budget), %llu LRU moves; verify: %llu hits captured again, %llu stages differed\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast<double>(validated) : 0.0, count(counters.hits), ranks.c_str(), miss(DrawMiss::FrontDiffering), miss(DrawMiss::FragmentDiffering), miss(DrawMiss::OtherDiffering), miss(DrawMiss::QueuedStores), miss(DrawMiss::Layout), miss(DrawMiss::Gate), miss(DrawMiss::Stages), count(counters.stageValidations), count(counters.stageEqual), counters.stageValidations != 0 ? static_cast<double>(counters.variantsCompared) / static_cast<double>(counters.stageValidations) : 0.0, count(counters.inserts), count(counters.shapeUpdates), count(counters.variantsInserted), count(counters.variantsEvicted), count(counters.present), count(counters.unstable), drawCache.size(), count(drawCacheVariants), static_cast<double>(drawCacheVariantBytes) / (1024.0 * 1024.0), static_cast<double>(DrawCacheBytes()) / (1024.0 * 1024.0), count(drawCacheEvictions), count(drawCacheByteEvictions), count(counters.touches), count(counters.verifyHits), count(counters.verifyMismatches));
append("[draw-cache] register key (10 s): %llu lookups, %llu hits, key build %.1f us each; decode skipped %llu, partial (state/pixel/programs from the entry) %llu; facade log != table %llu; verify: %llu decodes compared, %llu differed\n", count(counters.registerKeyLookups), count(counters.registerKeyHits), counters.registerKeyLookups != 0 ? counters.keyUs / static_cast<double>(counters.registerKeyLookups) : 0.0, count(counters.decodeSkipped), count(counters.decodePartial), count(counters.facadeMismatches), count(counters.verifyDecodes), count(counters.verifyDecodeMismatches));
append("[draw-cache] stage data hits (10 s): %llu stages (%llu words refreshed), verified %llu; stage inserts with data positions %llu (%.1f positions each)\n", count(counters.stageDataHits), count(counters.stageDataWords), count(counters.stageDataVerified), count(counters.stageDataInserts), counters.stageDataInserts != 0 ? static_cast<double>(counters.stageDataPositions) / static_cast<double>(counters.stageDataInserts) : 0.0);
return text;
@@ -125,6 +125,8 @@ std::shared_ptr<const ShaderRecompiler::RecompileResult> Driver::materializeDraw
if (matched[j] != nullptr && !recompiled[j] && (drawHit || j < i)) memory.insert(memory.end(), matchedRegions[j].begin(), matchedRegions[j].end());
}
request.context.memory = memory;
static const bool dumpGraphics = std::getenv("APS5_DUMP_GRAPHICS_SHADERS") != nullptr;
if (dumpGraphics) static_cast<void>(dumpRequest(program.binary.codeAddress, request));
if (traceCapSync()) traceCapture("draw-capture", program.binary.codeAddress, submission.queue, memory, Graphics::Recorder::ThreadWaitedMs() - waitedBefore);
if (profile) {
++captures;
@@ -126,6 +126,11 @@ void DecodeGraphicsPrograms(DrawDecode& decoded, const QueueState& queue, const
codeOffset
};
result.resourceRegister = rsrc2;
if (!nullPixel) {
Graphics::NoteRegisterRead(Graphics::RegisterBank::Shader, rsrc2);
const auto resources = queue.shader.find(rsrc2);
require(resources == queue.shader.end() || (resources->second >> 28u) == 0u, "wave-shared VGPRs of a graphics stage (SPI_SHADER_PGM_RSRC2.SHARED_VGPR_CNT) are not modeled");
}
result.nullPixel = nullPixel;
ReadUserWords(queue, result, staticAbi);
return result;
@@ -182,6 +182,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptr<Vulk
}
if (matched[i] != nullptr) continue;
if (!anyLayout) miss = DrawMiss::Layout;
else if (outcome == EntryOutcome::QueuedStores) miss = DrawMiss::QueuedStores;
else if (outcome != EntryOutcome::Differing) miss = DrawMiss::Gate;
else miss = roles[i] == Role::Fragment ? DrawMiss::FragmentDiffering : i == 0 ? DrawMiss::FrontDiffering : DrawMiss::OtherDiffering;
}
@@ -5,6 +5,7 @@
#include "prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp"
#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp"
#include "prx/libSceAgcDriver/Execution/include/WorkerSampler.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include <algorithm>
#include <array>
@@ -22,7 +23,14 @@ namespace {
constexpr std::array<const char*, static_cast<std::size_t>(DrawPipeline::DrainReason::Count)> DrainNames{"packet", "flush", "labels", "capture", "indirect", "submission"};
constexpr std::array<const char*, static_cast<std::size_t>(DrawPipeline::CommitKind::Count)> KindNames{"other", "draw", "indirect", "colormeta", "dispatch", "sampledump", "dmafill", "dmawrite", "dmacopy", "store", "endofpipe", "seal", "submitend", "completion", "bufferfill"};
std::atomic<unsigned> runningCommitters{0};
std::atomic<std::uint64_t> drawKeys{0};
std::atomic<std::uint64_t> drawKeysSameAsPrevious{0};
std::atomic<std::uint64_t> drawKeysSeenRecently{0};
std::atomic<std::uint64_t> drawShapesSameAsPrevious{0};
std::atomic<std::uint64_t> drawShapesSeenRecently{0};
std::uint64_t elapsedNs(std::chrono::steady_clock::time_point since) {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - since).count());
@@ -299,9 +307,32 @@ void DrawPipeline::Enqueue(Commit commit, std::vector<Range> writes, std::uint64
enqueue({std::move(commit), std::move(writes), labelAddress, std::move(labelBytes), std::move(reads), draw});
}
void DrawPipeline::Enqueue(CommitKind kind, Commit commit, std::vector<Range> writes, std::uint64_t labelAddress, std::vector<std::byte> labelBytes, std::vector<Range> reads, bool draw) {
enqueue({std::move(commit), std::move(writes), labelAddress, std::move(labelBytes), std::move(reads), draw, false, kind});
}
void DrawPipeline::NoteDrawKey(std::uint64_t key, std::uint64_t shape) {
constexpr std::size_t RecentSlots = 4096;
thread_local std::array<std::uint64_t, RecentSlots> recent{};
thread_local std::uint64_t previous = 0;
thread_local std::array<std::uint64_t, RecentSlots> recentShapes{};
thread_local std::uint64_t previousShape = 0;
const auto shapeSlot = static_cast<std::size_t>((shape ^ (shape >> 29u)) % RecentSlots);
const auto slot = static_cast<std::size_t>((key ^ (key >> 29u)) % RecentSlots);
drawKeys.fetch_add(1, std::memory_order_relaxed);
if (key == previous) drawKeysSameAsPrevious.fetch_add(1, std::memory_order_relaxed);
if (recent[slot] == key) drawKeysSeenRecently.fetch_add(1, std::memory_order_relaxed);
if (shape == previousShape) drawShapesSameAsPrevious.fetch_add(1, std::memory_order_relaxed);
if (recentShapes[shapeSlot] == shape) drawShapesSeenRecently.fetch_add(1, std::memory_order_relaxed);
recent[slot] = key;
previous = key;
recentShapes[shapeSlot] = shape;
previousShape = shape;
}
void DrawPipeline::EnqueueStore(Commit commit, std::uint64_t address, std::vector<std::byte> bytes) {
const auto end = address + bytes.size();
enqueue({std::move(commit), {{address, end}}, address, std::move(bytes), {}, false, true});
enqueue({std::move(commit), {{address, end}}, address, std::move(bytes), {}, false, true, CommitKind::Store});
}
void DrawPipeline::enqueue(Item item) {
@@ -380,6 +411,18 @@ void DrawPipeline::report(std::chrono::steady_clock::time_point now) {
std::snprintf(reads, sizeof(reads), " %llu read ranges, %llu stores held, %llu decode drains", static_cast<unsigned long long>(heldReadRanges.load(std::memory_order_relaxed)), static_cast<unsigned long long>(heldReadHits.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(decodeDrainCount - reportedDecodeDrains));
reportedDecodeDrains = decodeDrainCount;
AgcDriver::ProfilePrint_nid_no_patch("[draw] pipelined (10 s, depth %zu): %llu commits at %.1f us each on the committer, %llu failed; %llu enqueued behind %.2f on average, waiting %.1f us per draw for room, %.2f us for the lock; %llu committer wakes;%s; drains:%s\n", Depth(), static_cast<unsigned long long>(commits), perCommit, static_cast<unsigned long long>(commitErrors), static_cast<unsigned long long>(enqueued), queued, perDraw, enqueued == 0 ? 0.0 : static_cast<double>(lockWaitNs) / 1e3 / static_cast<double>(enqueued), static_cast<unsigned long long>(wakes), reads, drainText.c_str());
std::string kindText;
for (std::size_t i = 0; i < kindCommits.size(); ++i) {
const auto count = kindCommits[i].exchange(0, std::memory_order_relaxed);
const auto ns = kindNs[i].exchange(0, std::memory_order_relaxed);
if (count == 0) continue;
char item[64];
std::snprintf(item, sizeof(item), " %s %llu (%.1f us)", KindNames[i], static_cast<unsigned long long>(count), static_cast<double>(ns) / 1e3 / static_cast<double>(count));
kindText += item;
}
AgcDriver::ProfilePrint_nid_no_patch("[commits] by kind (10 s):%s\n", kindText.c_str());
const auto vk = Graphics::TakeVkDrawCounts();
AgcDriver::ProfilePrint_nid_no_patch("[vkdraw] (10 s): %llu vkCmdDraw, %llu vkCmdDrawIndexed, %llu vkCmdDrawIndirect calls, %llu mesh; draw keys %llu, same as the previous draw %llu, seen within the last 4096 draws %llu; draw shapes (state without per-draw user words) same as the previous %llu, seen within the last 4096 %llu\n", static_cast<unsigned long long>(vk.direct), static_cast<unsigned long long>(vk.indexed), static_cast<unsigned long long>(vk.indirect), static_cast<unsigned long long>(vk.mesh), static_cast<unsigned long long>(drawKeys.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(drawKeysSameAsPrevious.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(drawKeysSeenRecently.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(drawShapesSameAsPrevious.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(drawShapesSeenRecently.exchange(0, std::memory_order_relaxed)));
commits = commitNs = commitErrors = enqueued = fullWaitNs = depthSum = wakes = lockWaitNs = 0;
drains = {};
drainWaitNs = {};
@@ -425,6 +468,9 @@ void DrawPipeline::run() {
}
std::lock_guard lock(mutex);
countWrites(items.front().writes, false);
const auto kindIndex = static_cast<std::size_t>(items.front().kind);
kindCommits[kindIndex].fetch_add(1, std::memory_order_relaxed);
kindNs[kindIndex].fetch_add(spent, std::memory_order_relaxed);
retired.push_back(std::move(items.front()));
items.pop_front();
retiredItems.fetch_add(1, std::memory_order_release);
@@ -53,7 +53,7 @@ std::optional<DrawVerdict> Driver::precheckDraw(const QueueState& queue, const S
if (!writes.empty() && localDevice != nullptr) {
const auto queueId = submission.queue;
const auto opcode = (packet[0] >> 8u) & 0xffu;
DrawPipeline::Queue0().Enqueue([this, localDevice, queueId, opcode, pass = *pass] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::ColorMetadata, [this, localDevice, queueId, opcode, pass = *pass] {
GuestMemory::SetCurrentPacket(opcode, queueId);
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Draw);
std::lock_guard gpuLock(GuestMemory::GpuMutex());
@@ -80,7 +80,7 @@ std::optional<DrawVerdict> Driver::precheckDraw(const QueueState& queue, const S
auto copyDraw = DepthCopyDraw(queue, *copy);
return draw(copyDraw, packet, submission, packetOffset, rejected);
}
if (const auto control = Graphics::DecodeDepthRenderControl(queue); control && ((control->control & 0x60u) != 0u || Graphics::DepthSurfaceAt(control->address))) {
if (const auto control = Graphics::DecodeDepthRenderControl(queue); control && Graphics::DepthRenderControlDrains(*control)) {
if (DrawPipeline::Active()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, (packet[0] >> 8u) & 0xffu);
Graphics::NoteDepthRenderControl(*control);
}
@@ -292,6 +292,7 @@ void Driver::relocateDrawEntry(const QueueState& queue, std::uint64_t alias, std
++counters.donors;
auto relocated = std::make_shared<DrawEntry>();
relocated->decode = donor->decode;
relocated->donor = donor->donor != nullptr ? donor->donor : donor;
relocated->stages.resize(donor->stages.size());
for (std::size_t i = 0; i < donor->stages.size(); ++i) {
const bool moved = std::any_of(moves.begin(), moves.end(), [&](const Move& move) { return move.program == i; });
@@ -314,6 +315,7 @@ void Driver::relocateDrawEntry(const QueueState& queue, std::uint64_t alias, std
copy->valueSlots = variant->valueSlots;
copy->calleeWords = variant->calleeWords;
copy->calleeReads = variant->calleeReads;
copy->donor = variant->donor != nullptr ? variant->donor : variant;
copy->words = variant->words;
copy->forgetSerial = variant->forgetSerial;
copy->compiled = variant->compiled;
@@ -123,6 +123,10 @@ extern "C" void AgcDriverRequestScreenshot_nid_postfix() {
AgcDriver::Screenshot::Request();
}
extern "C" void AgcDriverTracePresent_nid_postfix(std::uint32_t width, std::uint32_t height) {
AgcDriver::DriverDetail::Driver::Get().TracePresent(width, height);
}
extern "C" void AgcDriverRegisterShader_nid_postfix(const Shader* shader) try {
AgcDriver::RegisterShader(shader);
} catch (const ProcessShutdown&) {
@@ -13,6 +13,7 @@
#include "prx/libSceAgcDriver/Graphics/include/ParallelCompare.hpp"
#include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "prx/libc/include/GuestArena.hpp"
#include "ShaderDiskCache.hpp"
#include "prx/libc/include/GuestArena.hpp"
#include "prx/libc/include/GuestWriteWatch.hpp"
@@ -156,6 +157,7 @@ Driver& Driver::Get() {
}
Driver::~Driver() {
GuestArena::GuestArenaSetHostWriteHook_nid_no_patch(nullptr);
GuestAllocations::GuestAllocationsSetGpuMapObserver_nid_postfix(nullptr);
stop();
}
@@ -170,6 +172,8 @@ void Driver::stop() {
require(!onWorkerThread(), "worker cannot stop itself");
std::lock_guard shutdownLock(shutdownMutex);
if (stopped) return;
GuestArena::GuestArenaSetHostWriteHook_nid_no_patch(nullptr);
if (!GuestMemory::StopHostWrites(1000)) std::fprintf(stderr, "[driver] a host write was still inside the driver's hook 1 s into the shutdown; stopping without waiting for it\n");
LibcRequestShutdown_nid_postfix();
{
std::lock_guard lock(mutex);
@@ -219,12 +223,14 @@ Driver::Driver() {
});
static_cast<void>(GuestMemory::TrackerGeneration());
ShaderMemory::SetWaitedMsProvider(&Graphics::Recorder::ThreadWaitedMs);
GuestMemory::SetWaitedMsProvider(&Graphics::Recorder::ThreadWaitedMs);
try {
LibcRegisterShutdown_nid_postfix([] { Driver::Get().Shutdown(); });
} catch (...) {
stop();
throw;
}
GuestArena::GuestArenaSetHostWriteHook_nid_no_patch(&GuestMemory::PrepareHostWrite);
GuestAllocations::GuestAllocationsSetGpuMapObserver_nid_postfix([](const GuestAllocations::Mapped& ranges, std::uint64_t generation) {
const auto import = [&] {
try {
@@ -462,7 +462,7 @@ void Driver::storeBufferFill(std::uint32_t queueId, std::uint64_t base, std::siz
};
static const bool orderedFills = std::getenv("APS5_PIPELINE_DRAIN_FILLS") == nullptr;
if (orderedFills && queueId == 0 && DrawPipeline::Active()) {
DrawPipeline::Queue0().Enqueue([store, queueId] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::BufferFill, [store, queueId] {
GuestMemory::SetCurrentPacket(0x15, queueId);
store();
}, {{base, base + bytes}});
@@ -1,6 +1,7 @@
#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
#include "ThreadOwned.hpp"
#include "prx/libSceAgcDriver/Execution/include/ThreadScratch.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp"
#include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp"
@@ -73,7 +74,7 @@ bool keepsDrawPipeline(std::span<const std::uint32_t> packet, std::uint32_t head
if (header == FlipPacketHeader || header == RenderingWaitPacketHeader) return false;
if (Pm4::DrawOpcode(opcode)) return true;
switch (opcode) {
case 0x11: case 0x12: case 0x13: case 0x20: case 0x26: case 0x2a: case 0x2f: case 0x42: case 0x58: case 0x59: case 0x69: case 0x76: case 0x79: case 0x7a: case 0x81: return true;
case 0x11: case 0x12: case 0x13: case 0x20: case 0x26: case 0x2a: case 0x2f: case 0x3f: case 0x42: case 0x58: case 0x59: case 0x69: case 0x76: case 0x79: case 0x7a: case 0x81: return true;
case 0x46: return packet.size() >= 2 && (packet[1] & 0x3fu) != 0x39u;
case 0x15: return orderedFills();
case 0x63: case 0x64: case 0x9f:
@@ -143,7 +144,8 @@ void Driver::timed(double WorkerProfile::*bucket, TWork&& work) {
work();
return;
}
static thread_local WorkerProfile profile;
struct Slot {};
auto& profile = ThreadScratch<WorkerProfile, Slot>();
const auto begin = std::chrono::steady_clock::now();
work();
const auto end = std::chrono::steady_clock::now();
@@ -562,7 +564,7 @@ void Driver::execute(const Submission& submission) {
std::lock_guard gpuLock(GuestMemory::GpuMutex());
if (const auto localDevice = device.Load()) localDevice->SealPassWriteOnly();
};
if (pipelined && DrawPipeline::Queue0().Busy()) DrawPipeline::Queue0().Enqueue(seal, {});
if (pipelined && DrawPipeline::Queue0().Busy()) DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Seal, seal, {});
else seal();
}
} else if (opcode != 0x42 && opcode != 0x46 && opcode != 0x58) {
@@ -617,7 +619,7 @@ void Driver::execute(const Submission& submission) {
}
if ((std::atomic_ref<std::uint32_t>(*const_cast<std::uint32_t*>(submission.rewindTail - 1)).load(std::memory_order_acquire) & 0x80000000u) != 0) {
const bool holdsFlip = std::exchange(flipHold.working, false);
DrawPipeline::Queue0().Enqueue([this, holdsFlip, progress = submission.progress] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::SubmitEnd, [this, holdsFlip, progress = submission.progress] {
if (holdsFlip) finishFlipWork(submitFlipWork(0));
else submitOpenWork(progress);
wakeQueueZeroForCompletions();
@@ -343,7 +343,7 @@ bool Driver::enqueueSampleDumpPacket(std::span<const std::uint32_t> packet, std:
if (!ordered || opcode != 0x46 || queue != 0 || packet.size() < 4 || !Pm4::SampleDump(packet) || !DrawPipeline::Active() || !deferredLabels().labels.empty()) return false;
const auto address = Pm4::SampleDumpAddress(packet);
if (address == 0 || !GuestMemory::Accessible(reinterpret_cast<const void*>(address), Pm4::SampleDumpBytes, true)) return false;
DrawPipeline::Queue0().Enqueue([this, queue, address] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::SampleDump, [this, queue, address] {
GuestMemory::SetCurrentPacket(0x46, queue);
bool wrote = false;
{
@@ -373,7 +373,7 @@ bool Driver::enqueueDmaPacket(std::span<const std::uint32_t> packet, std::uint32
const auto fillBytes = Pm4::DmaBytes(packet);
const auto pattern = packet[2];
if (fillAddress % 16 != 0 || fillBytes % 16 != 0 || !GuestMemory::Accessible(reinterpret_cast<const void*>(fillAddress), fillBytes, true) || !device.Load()) return false;
DrawPipeline::Queue0().Enqueue([this, queue, fillAddress, fillBytes, pattern] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::DmaFill, [this, queue, fillAddress, fillBytes, pattern] {
GuestMemory::SetCurrentPacket(0x50, queue);
if (const auto localDevice = device.Load()) {
storeBufferFill(queue, fillAddress, fillBytes, {pattern, pattern, pattern, pattern}, localDevice, false, true);
@@ -393,7 +393,7 @@ bool Driver::enqueueDmaPacket(std::span<const std::uint32_t> packet, std::uint32
const auto fillAddress = packet[4] | (static_cast<std::uint64_t>(packet[5]) << 32u);
const auto fillBytes = packet[6] & 0x3ffffffu;
const auto pattern = packet[2];
DrawPipeline::Queue0().Enqueue([this, queue, address, bytes = std::move(bytes), gds, metadataFill, fillAddress, fillBytes, pattern] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::DmaWrite, [this, queue, address, bytes = std::move(bytes), gds, metadataFill, fillAddress, fillBytes, pattern] {
GuestMemory::SetCurrentPacket(0x50, queue);
if (gds) {
GuestMemory::Write(address, bytes, 1);
@@ -410,7 +410,7 @@ bool Driver::enqueueDmaPacket(std::span<const std::uint32_t> packet, std::uint32
if (Pm4::DmaSource(packet) == 0 || Pm4::DmaSource(packet) == 3) Graphics::RequireNoMultisampleTarget(packet[2] | (static_cast<std::uint64_t>(packet[3]) << 32u), packet[6] & 0x3ffffffu, "a DMA copy");
const auto copy = Pm4::DecodeMemoryCopy(packet);
if (!copy.has_value() || copy->destination % 4 != 0 || copy->bytes % 4 != 0 || !GuestMemory::Accessible(reinterpret_cast<const void*>(copy->source), copy->bytes) || !GuestMemory::Accessible(reinterpret_cast<const void*>(copy->destination), copy->bytes, true)) return false;
DrawPipeline::Queue0().Enqueue([this, queue, copy = *copy] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::DmaCopy, [this, queue, copy = *copy] {
DrawPipeline::Queue0().ReleaseRunningReads();
GuestMemory::SetCurrentPacket(0x50, queue);
constexpr std::size_t gpuStoreLimit = 65536;
@@ -513,7 +513,7 @@ bool Driver::enqueueLabelPacket(std::span<const std::uint32_t> packet, std::uint
auto stored = bytes;
auto labelBytes = bytes;
auto enqueue =[this, queue, opcode, address, bytes = std::move(bytes), interrupt, writes, stored = std::move(stored)]() mutable {
DrawPipeline::Queue0().Enqueue([this, queue, opcode, address, bytes = std::move(bytes), interrupt] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::EndOfPipe, [this, queue, opcode, address, bytes = std::move(bytes), interrupt] {
GuestMemory::SetCurrentPacket(opcode, queue);
commitLabel(queue, address, bytes, interrupt);
}, std::move(writes), address, std::move(stored));
@@ -79,6 +79,10 @@ void Driver::AttachWindow(const PresentationWindow& window) {
timing.Mark("vulkan_device_create");
}
void Driver::TracePresent(std::uint32_t width, std::uint32_t height) {
if (PerformanceTrace::Configured()) PerformanceTrace::Present(width, height, device.Load().get());
}
void Driver::Present(const PresentationWindow& window, const DisplayBuffer* buffer, const DisplayBuffer* plane, bool opaque, void (*gpuReady)(void*), void* context) {
if (PerformanceTrace::Configured()) PerformanceTrace::Present(window.width, window.height, device.Load().get());
PerformanceContext timingContext(window.timing.get());
@@ -74,7 +74,7 @@ void Driver::deferCompletion(const Submission& submission) {
completionDeferred() = true;
static const bool traceGpu = std::getenv("APS5_TRACE_GPU") != nullptr;
if (traceGpu) std::fprintf(stderr, "[gpu] %.1f deferred completion serial=%llu to the draw pipeline\n", TraceMs(), static_cast<unsigned long long>(submission.serial));
DrawPipeline::Queue0().Enqueue([this, serial = submission.serial, received, labelWrites = submission.labelWrites, progress = submission.progress, holdsFlip = submission.holdsFlip] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Completion, [this, serial = submission.serial, received, labelWrites = submission.labelWrites, progress = submission.progress, holdsFlip = submission.holdsFlip] {
completeSubmission(serial, received, labelWrites, progress, holdsFlip);
}, {});
}
@@ -275,7 +275,7 @@ void Driver::run(std::uint32_t id) noexcept {
OrderHold hold{orderHolders};
const auto released = [&] { return failure || stopping || !waitFreeBefore(submission.received); };
StallWatch stall(id);
while (!released() && !poll(released)) stall.Check("order behind other queues for event", submission.received);
while (!released() && !poll(released)) stall.Check("order behind other queues for event", submission.received, &lock);
}
rethrowFailure();
}
@@ -288,7 +288,7 @@ void Driver::run(std::uint32_t id) noexcept {
OrderHold hold{orderHolders};
const auto released = [&] { return failure || stopping || orderReleased(id, submission.received); };
StallWatch stall(id);
while (!released() && !poll(released)) stall.Check("order behind queue 0 for event", submission.received);
while (!released() && !poll(released)) stall.Check("order behind queue 0 for event", submission.received, &lock);
}
rethrowFailure();
}
@@ -0,0 +1,23 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Queues/SubmissionRing.hpp"
#include "SDL.h"
namespace AgcDriver::DriverDetail {
StallChoice ShowStallPrompt(const char* message) {
SDL_MessageBoxButtonData buttons[]{
{SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT | SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, 0, "Wait"},
{0, 1, "Quit"},
};
SDL_MessageBoxData data{};
data.flags = SDL_MESSAGEBOX_WARNING;
data.title = "AnyPS5";
data.message = message;
data.numbuttons = 2;
data.buttons = buttons;
int button = -1;
if (SDL_ShowMessageBox(&data, &button) != 0) return StallChoice::Unavailable;
return button == 1 ? StallChoice::Quit : StallChoice::Wait;
}
}
@@ -14,6 +14,7 @@
#include "ThreadOwned.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include <algorithm>
#include <array>
#include <atomic>
#include <bit>
#include <cmath>
@@ -225,6 +226,60 @@ bool Driver::copySegment(Submission& submission, const std::uint32_t* guest, std
return false;
}
ReferencedProgramScan ReferencedPrograms(std::span<const std::uint32_t> commands, const std::map<std::size_t, std::vector<std::uint32_t>>& registerLists) {
constexpr std::array<std::uint32_t, 7> programRegisters{0x008u, 0x048u, 0x088u, 0x0c8u, 0x108u, 0x148u, 0x20cu};
std::array<std::uint32_t, programRegisters.size() * 2> values{};
std::array<bool, programRegisters.size() * 2> written{};
std::array<bool, programRegisters.size()> bound{};
ReferencedProgramScan scan;
const auto write = [&](std::uint32_t offset, std::uint32_t value, bool conditional) {
const auto base = std::ranges::find_if(programRegisters, [&](std::uint32_t program) { return offset - program < 2u; });
if (base == programRegisters.end()) return;
if (conditional) {
scan.complete = false;
return;
}
const auto slot = static_cast<std::size_t>(base - programRegisters.begin()) * 2u + (offset - *base);
values[slot] = value;
written[slot] = true;
const auto low = slot & ~std::size_t{1};
if (written[low] && written[low + 1]) {
bound[low / 2] = true;
scan.addresses.push_back((static_cast<std::uint64_t>(values[low]) << 8u) | (static_cast<std::uint64_t>(values[low + 1] & 0xffu) << 40u));
}
};
std::size_t guardedEnd = 0;
for (std::size_t cursor = 0; cursor < commands.size(); cursor += Pm4::PacketWords(commands[cursor])) {
const auto header = commands[cursor];
if ((header >> 30u) != 3u) continue;
const auto opcode = (header >> 8u) & 0xffu;
const auto words = std::min<std::size_t>(Pm4::PacketWords(header), commands.size() - cursor);
const bool conditional = (header & 1u) != 0 || cursor < guardedEnd;
if (opcode == 0x22u && words == 5) guardedEnd = std::max(guardedEnd, cursor + words + Pm4::ConditionalWords(commands.subspan(cursor, words)));
if (Pm4::DrawOpcode(opcode) && !std::any_of(bound.begin(), bound.end() - 1, [](bool pair) { return pair; })) scan.complete = false;
if ((opcode == 0x15u || opcode == 0x16u) && !bound.back()) scan.complete = false;
if (opcode == 0x76u && words >= 3) {
const auto packet = commands.subspan(cursor, words);
const auto offset = packet[1] & ~0x70000000u;
for (std::size_t i = 2; i < words; ++i) write(offset + static_cast<std::uint32_t>(i - 2), packet[i], conditional);
} else if (opcode == 0x63u) {
const auto list = registerLists.find(cursor);
if (list == registerLists.end()) continue;
if (!Pm4::IndirectRegistersValid(list->second)) {
scan.complete = false;
continue;
}
for (std::size_t i = 0; i + 1 < list->second.size(); i += 2) write(list->second[i] & ~0x70000000u, list->second[i + 1], conditional);
}
}
for (std::size_t slot = 0; slot < written.size(); slot += 2) {
if (written[slot] != written[slot + 1]) scan.complete = false;
}
std::ranges::sort(scan.addresses);
scan.addresses.erase(std::unique(scan.addresses.begin(), scan.addresses.end()), scan.addresses.end());
return scan;
}
void Driver::readRegisterLists(Submission& submission) {
submission.registerLists.clear();
for (std::size_t cursor = 0; cursor < submission.commands.size(); cursor += Pm4::PacketWords(submission.commands[cursor])) {
@@ -511,7 +566,17 @@ void Driver::Submit(const Packet* packet, std::uint32_t queue, bool cpuFlip) {
if (APS5_ENABLE_TIMING_LOG) submission.validatedAt = std::chrono::steady_clock::now();
waitForFlipRoom(submission);
holdFlipBehindWorker(submission, cpuFlip);
AwaitRegistrationPreparation();
const auto scan = ReferencedPrograms(submission.commands, submission.registerLists);
if (!scan.complete || submission.rewindTail != nullptr) {
AwaitRegistrationPreparation();
} else {
std::shared_ptr<const ShaderRegistry> registry;
{
std::lock_guard lock(mutex);
registry = shaders;
}
if (registry != nullptr) AwaitReferencedPreparations(*registry, scan.addresses);
}
if (LibraryPrebuildsWaiting()) PrioritizeLibraryPrebuilds(BoundGraphicsPrograms(submission));
if (APS5_ENABLE_TIMING_LOG) submission.roomReadyAt = std::chrono::steady_clock::now();
static const bool trace = std::getenv("APS5_TRACE_GPU") != nullptr;
@@ -2,6 +2,7 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp"
#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp"
#include "prx/libc/include/FailureReport.hpp"
#include "prx/libc/include/Shutdown.hpp"
#include <algorithm>
#include <array>
#include <atomic>
@@ -11,6 +12,7 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <memory>
#include <mutex>
#include <thread>
@@ -23,6 +25,10 @@
#include <unistd.h>
#endif
#ifdef __APPLE__
extern "C" void Aps5RunOnMainThread_nid_no_patch(void (*function)(void*), void* context);
#endif
namespace AgcDriver::DriverDetail {
namespace {
@@ -32,6 +38,37 @@ constexpr std::size_t MaximumCapacity = 4096;
constexpr std::size_t MaximumStallSeconds = 86400;
constexpr std::size_t PayloadWordsShown = 8;
std::chrono::steady_clock::time_point realStallClock() { return std::chrono::steady_clock::now(); }
std::atomic<StallClock> stallClock{realStallClock};
std::atomic<StallPresenter> stallPresenter{ShowStallPrompt};
std::atomic<bool> stallPromptOpen{false};
constexpr int StallQuitExitCode = 124;
constexpr int MaxStallPrompts = 3;
StallChoice askOnMainThread(StallPresenter presenter, const char* message) {
#ifdef __APPLE__
struct Call {
StallPresenter presenter;
const char* message;
StallChoice choice = StallChoice::Unavailable;
std::exception_ptr error;
} call{presenter, message};
Aps5RunOnMainThread_nid_no_patch([](void* context) {
auto& call = *static_cast<Call*>(context);
try {
call.choice = call.presenter(call.message);
} catch (...) {
call.error = std::current_exception();
}
}, &call);
if (call.error) std::rethrow_exception(call.error);
return call.choice;
#else
return presenter(message);
#endif
}
struct Entry {
std::uint64_t tenthsOfMs = 0;
std::uint64_t serial = 0;
@@ -224,8 +261,27 @@ std::chrono::seconds StallWatchdogPeriod() {
return value;
}
void SetStallClock(StallClock clock) {
stallClock.store(clock != nullptr ? clock : realStallClock);
}
void SetStallPresenter(StallPresenter presenter) {
stallPresenter.store(presenter != nullptr ? presenter : ShowStallPrompt);
}
bool StallPromptEnabled() {
static const bool value = [] {
const char* text = std::getenv("ANYPS5_STALL_PROMPT");
if (text == nullptr || std::strcmp(text, "0") == 0) return false;
require(std::strcmp(text, "1") == 0, "ANYPS5_STALL_PROMPT must be 0 or 1");
return true;
}();
return value;
}
bool ReadSubmissionRingSettings() {
StallWatchdogPeriod();
StallPromptEnabled();
return SubmissionRingCapacity() != 0;
}
@@ -262,20 +318,48 @@ void DumpSubmissionRings(std::string_view reason) {
require(dump(reason, false), "cannot write the PM4 ring dump to stderr");
}
void StallWatch::Check(const char* waiter, std::uint64_t value) {
if (dumped) return;
void StallWatch::Check(const char* waiter, std::uint64_t value, std::unique_lock<std::mutex>* held) {
if (finished) return;
const auto period = StallWatchdogPeriod();
if (period.count() == 0) return;
const auto now = std::chrono::steady_clock::now();
const auto now = stallClock.load()();
if (since == std::chrono::steady_clock::time_point{}) {
since = now;
return;
}
if (now - since < period) return;
dumped = true;
char reason[192];
std::snprintf(reason, sizeof(reason), "queue 0x%x %s 0x%llx has not progressed for %lld s (APS5_STALL_WATCHDOG_SECS)", queue, waiter, static_cast<unsigned long long>(value), static_cast<long long>(period.count()));
DumpSubmissionRings(reason);
if (!dumped) {
dumped = true;
DumpSubmissionRings(reason);
}
if (!StallPromptEnabled()) {
finished = true;
return;
}
char message[320];
std::snprintf(message, sizeof(message), "This title has not made progress for %lld seconds (queue 0x%x %s 0x%llx).\n\nWait keeps it running. Quit stops it; the submission rings are on stderr.", static_cast<long long>(period.count()), queue, waiter, static_cast<unsigned long long>(value));
if (stallPromptOpen.exchange(true)) return;
if (held != nullptr) held->unlock();
const auto choice = askOnMainThread(stallPresenter.load(), message);
stallPromptOpen.store(false);
switch (choice) {
case StallChoice::Wait:
if (held != nullptr) held->lock();
if (++prompts == MaxStallPrompts) finished = true;
since = stallClock.load()();
return;
case StallChoice::Quit:
std::fprintf(stderr, "[stall prompt] quit at a stalled wait; exit code %d (ANYPS5_STALL_PROMPT)\n", StallQuitExitCode);
std::fflush(stderr);
LibcTerminate_nid_no_patch(StallQuitExitCode);
case StallChoice::Unavailable:
if (held != nullptr) held->lock();
std::fputs("[stall prompt] no message box is available; the rings are printed only\n", stderr);
finished = true;
return;
}
}
}
@@ -52,6 +52,7 @@
#include <sstream>
#include <stdexcept>
#include <thread>
#include <unordered_map>
#include "Optimization/ShaderStageInputInfo.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/RegistrationPreparationBudget.hpp"
#include "prx/libSceAgcDriver/Execution/include/PerformanceOverlay.hpp"
@@ -1647,6 +1648,7 @@ public:
else tasks.push_back({std::move(task), prepared, sequence, budgeted, program});
if (program != 0) waitingPrograms.fetch_add(1, std::memory_order_relaxed);
unfinished.insert(sequence);
if (prepared != nullptr) owned.emplace(prepared, sequence);
lock.unlock();
ready.notify_one();
return;
@@ -1657,10 +1659,17 @@ public:
void Prioritize(const PreparedShaders& prepared) {
std::lock_guard lock(mutex);
const auto found = std::ranges::find_if(tasks, [&](const auto& task) { return task.prepared == &prepared; });
if (found == tasks.end()) return;
if (std::getenv("APS5_TRACE_PREPARATION_WAIT") != nullptr) std::fprintf(stderr, "[shader-prepare] demanded queued task at position %zu of %zu\n", static_cast<std::size_t>(std::distance(tasks.begin(), found)), tasks.size());
std::rotate(tasks.begin(), found, std::next(found));
moveToFront(prepared);
}
void AwaitOwned(const PreparedShaders& prepared) {
std::unique_lock lock(mutex);
const auto [first, last] = owned.equal_range(&prepared);
if (first == last) return;
std::vector<std::uint64_t> sequences;
for (auto entry = first; entry != last; ++entry) sequences.push_back(entry->second);
moveToFront(prepared);
idle.wait(lock, [&] { return std::ranges::none_of(sequences, [&](const auto sequence) { return unfinished.contains(sequence); }); });
}
void Prioritize(std::span<const std::uint64_t> programs) {
@@ -1688,7 +1697,10 @@ public:
if (dropQueued) {
dropped.swap(tasks);
waitingPrograms.store(0, std::memory_order_relaxed);
for (const auto& task : dropped) unfinished.erase(task.sequence);
for (const auto& task : dropped) {
unfinished.erase(task.sequence);
disown(task.prepared, task.sequence);
}
idle.notify_all();
}
idle.wait(lock, [&] { return tasks.empty() && running == 0; });
@@ -1701,6 +1713,20 @@ public:
private:
static constexpr std::size_t StackBytes = 64u << 20u;
void moveToFront(const PreparedShaders& prepared) {
const auto found = std::ranges::find_if(tasks, [&](const auto& task) { return task.prepared == &prepared; });
if (found == tasks.end()) return;
if (std::getenv("APS5_TRACE_PREPARATION_WAIT") != nullptr) std::fprintf(stderr, "[shader-prepare] demanded queued task at position %zu of %zu\n", static_cast<std::size_t>(std::distance(tasks.begin(), found)), tasks.size());
std::rotate(tasks.begin(), found, std::next(found));
}
void disown(const PreparedShaders* prepared, std::uint64_t sequence) {
if (prepared == nullptr) return;
const auto [first, last] = owned.equal_range(prepared);
const auto found = std::find_if(first, last, [&](const auto& entry) { return entry.second == sequence; });
if (found != last) owned.erase(found);
}
#ifdef _WIN32
struct Worker {
HANDLE handle;
@@ -1778,6 +1804,7 @@ private:
}
const auto sequence = task.sequence;
const bool budgeted = task.budgeted;
const auto* const prepared = task.prepared;
task.function();
task = {};
bool drained = false;
@@ -1786,6 +1813,7 @@ private:
--pool.running;
if (budgeted) --pool.budgetedRunning;
pool.unfinished.erase(sequence);
pool.disown(prepared, sequence);
drained = pool.tasks.empty() && pool.running == 0;
pool.idle.notify_all();
}
@@ -1818,6 +1846,7 @@ private:
unsigned budgetedLimit = 1;
std::uint64_t submitted = 0;
std::set<std::uint64_t> unfinished;
std::unordered_multimap<const PreparedShaders*, std::uint64_t> owned;
bool closed = false;
};
@@ -1894,6 +1923,24 @@ void AwaitRegistrationPreparation() {
if (auto* pool = RegistrationPreparePool::Existing()) pool->AwaitSubmitted();
}
void AwaitReferencedPreparations(const ShaderRegistry& registry, std::span<const std::uint64_t> addresses) {
for (const auto address : addresses) {
auto found = registry.upper_bound(address);
if (found == registry.begin()) continue;
--found;
for (const auto& snapshot : found->second) {
if (address - snapshot->codeAddress >= snapshot->code.size() * sizeof(std::uint32_t)) continue;
auto& prepared = *snapshot->prepared;
{
std::lock_guard lock(prepared.mutex);
if (!prepared.pending) continue;
}
prepared.demanded.store(true);
if (auto* pool = RegistrationPreparePool::Existing()) pool->AwaitOwned(prepared);
}
}
}
void SubmitLibraryPrebuild(std::function<void()> task, std::uint64_t program) {
RegistrationPreparePool::Prebuild().Submit(std::move(task), nullptr, false, program);
}
@@ -13,7 +13,7 @@
#ifdef _WIN32
#include <windows.h>
#endif
#include <immintrin.h>
#include "prx/libc/include/PreciseWait.hpp"
#include <algorithm>
#include <tuple>
#include <vector>
@@ -366,7 +366,7 @@ void Driver::waitMemory(std::span<const std::uint32_t> packet, std::uint32_t que
}
++polls;
if (spinning) {
_mm_pause();
PreciseSpinPause();
if ((polls & 63u) != 0) continue;
if (std::chrono::steady_clock::now() - spinStart > spinLimit) spinning = false;
} else if (pauseSpin || polls >= 4000) {
@@ -4,6 +4,7 @@
#include "prx/libSceAgcDriver/Execution/include/Mutex.hpp"
#include "prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp"
#include "prx/libSceAgcDriver/Execution/include/WriteWatchCoverage.hpp"
#include "prx/libSceAgcDriver/Execution/include/ThreadScratch.hpp"
#include "ThreadOwned.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "prx/libc/include/GuestArena.hpp"
@@ -16,12 +17,14 @@
#include <atomic>
#include <algorithm>
#include <bit>
#if defined(__x86_64__) || defined(_M_X64)
#include <emmintrin.h>
#if defined(_MSC_VER) && !defined(__clang__)
#include <intrin.h>
#else
#include <cpuid.h>
#endif
#endif
#include <functional>
#include <cstdio>
#include <cstdlib>
@@ -38,6 +41,7 @@
#include <thread>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
#ifdef _WIN32
#ifndef NOMINMAX
@@ -223,8 +227,8 @@ struct ThreadMemoryCounters {
MemoryCounter& CounterFor(MemoryCounterKind kind) {
if (SharedMemoryCounters()) return Profile().shared.counters[kind];
thread_local ThreadMemoryCounters* thread = nullptr;
return ShaderRecompiler::ThreadOwned(thread).counters.counters[kind];
struct Slot {};
return ThreadScratch<ThreadMemoryCounters, Slot>().counters.counters[kind];
}
// Every thread's counters, the retired and the shared ones summed: calls, bytes, nanoseconds per kind.
@@ -891,7 +895,8 @@ bool onOwnLiveStack(std::uintptr_t address, std::size_t bytes) {
#endif
}
};
thread_local const Bounds bounds;
struct Slot {};
const auto& bounds = ThreadScratch<Bounds, Slot>();
const auto frame = reinterpret_cast<std::uintptr_t>(__builtin_frame_address(0));
return bounds.high != 0 && frame >= bounds.low && frame < bounds.high && address >= frame && address < bounds.high && bytes <= bounds.high - address;
}
@@ -1611,8 +1616,8 @@ struct EpochCollectMap {
};
EpochCollectMap& epochCollectMap(std::uint64_t epoch) {
thread_local EpochCollectMap* slot = nullptr;
auto& map = ShaderRecompiler::ThreadOwned(slot);
struct Slot {};
auto& map = ThreadScratch<EpochCollectMap, Slot>();
if (map.epoch != epoch) {
map.ranges.clear();
map.epoch = epoch;
@@ -1753,12 +1758,18 @@ std::uint64_t collectWrites(std::uint64_t address, std::size_t bytes, bool memoi
const auto unwatched = unwatchSerial.load(std::memory_order_acquire);
const auto mapping = GuestAllocations::GuestAllocationsGeneration_nid_postfix();
const bool useMemo = memoized && collectMemoEnabled() && bytes != 0;
if (useMemo && !sharedCollectMemo()) {
const bool epochal = HostThreadSlot<std::uint64_t, CollectEpochSlot>::Get() != 0;
if (useMemo && epochal && !sharedCollectMemo()) {
// An entry exists only for a completed walk of an in-arena range, so the tracker is
// initialized and watched; nothing below the lock needs asking.
if (epochCollectMapEnabled()) {
const auto& map = epochCollectMap(epoch);
if (const auto found = map.ranges.find(first); found != map.ranges.end() && found->second.unwatched == unwatched && found->second.mapping == mapping && stop <= found->second.end) {
const auto blockFirst = first & ~(WriteBlockBytes - 1);
const auto reusable = [&](std::uintptr_t key) {
const auto found = map.ranges.find(key);
return found != map.ranges.end() && found->second.unwatched == unwatched && found->second.mapping == mapping && stop <= found->second.end;
};
if (reusable(first) || (blockFirst != first && reusable(blockFirst))) {
collectMemoHits.fetch_add(1, std::memory_order_relaxed);
return tracker.stable.load(std::memory_order_acquire);
}
@@ -1811,9 +1822,11 @@ std::uint64_t collectWrites(std::uint64_t address, std::size_t bytes, bool memoi
const auto serial = unwatchSerial.load(std::memory_order_relaxed);
if (sharedCollectMemo()) tracker.memo[tracker.nextMemo++ % tracker.memo.size()] = {first, stop, epoch, serial, mapping};
else {
auto& memo = threadCollectMemo();
memo.entries[memo.next++ % memo.entries.size()] = {first, stop, epoch, serial, mapping};
if (epochCollectMapEnabled()) {
if (useMemo && epochal) {
auto& memo = threadCollectMemo();
memo.entries[memo.next++ % memo.entries.size()] = {first, stop, epoch, serial, mapping};
}
if (epochal && epochCollectMapEnabled()) {
auto& entry = epochCollectMap(epoch).ranges[first];
if (entry.unwatched != serial || entry.mapping != mapping || entry.end < stop) entry = {first, stop, epoch, serial, mapping};
}
@@ -1989,6 +2002,29 @@ void unwatchLocked(WriteTracker& tracker, std::uint64_t address, std::size_t byt
#endif
}
thread_local bool ownHostWrite = false;
std::atomic<std::uint64_t> hostWritesInFlight{0};
std::atomic<bool> hostWritesStopped{false};
class HostWriteInFlight {
public:
HostWriteInFlight() { hostWritesInFlight.fetch_add(1, std::memory_order_seq_cst); }
~HostWriteInFlight() { hostWritesInFlight.fetch_sub(1, std::memory_order_seq_cst); }
HostWriteInFlight(const HostWriteInFlight&) = delete;
HostWriteInFlight& operator=(const HostWriteInFlight&) = delete;
};
class OwnHostWrite {
public:
OwnHostWrite() : outer(std::exchange(ownHostWrite, true)) {}
~OwnHostWrite() { ownHostWrite = outer; }
OwnHostWrite(const OwnHostWrite&) = delete;
OwnHostWrite& operator=(const OwnHostWrite&) = delete;
private:
bool outer;
};
}
void SetUnwatchHook(void (*hook)(std::uint64_t, std::size_t)) {
@@ -2066,6 +2102,7 @@ bool ImportWatched(std::uint64_t address, std::size_t bytes, const std::function
const bool covered = tracker.covers(first, static_cast<std::size_t>(stop - first));
const auto runImport = [&] {
#ifdef __APPLE__
const OwnHostWrite own;
std::optional<GuestArena::HostWrite> open;
if (importMayWriteGuest) open.emplace(reinterpret_cast<void*>(first), static_cast<std::size_t>(stop - first));
#endif
@@ -2258,16 +2295,18 @@ std::uint64_t StoreOwnBytes(std::uint64_t address, std::span<const std::byte> so
return StoreOwnBytes(address, source.size(), [&] { copyOwnBytes(address, source); });
}
static std::uint64_t markWritten(std::uint64_t address, std::size_t bytes, bool complete) {
static std::uint64_t markWritten(std::uint64_t address, std::size_t bytes, bool complete, std::uint64_t* order = nullptr) {
BreakProofs();
auto& tracker = Tracker();
auto lock = lockTracker(tracker);
if (order != nullptr) *order = 0;
tracker.initialize();
if (bytes == 0) return 0;
++tracker.generation;
if (!tracker.watched || !tracker.covers(address, bytes)) {
tracker.noteUnstampedStore(address, address + bytes);
if (tracker.watched) tracker.stampWatchedPart(address, address + bytes, tracker.generation, complete);
if (order != nullptr) *order = tracker.generation.load(std::memory_order_relaxed);
return 0;
}
{
@@ -2284,8 +2323,10 @@ static std::uint64_t markWritten(std::uint64_t address, std::size_t bytes, bool
const TrackerLock::Suspension suspended{lock};
beforeUnwatchUnproven(blockFirst, static_cast<std::size_t>(blockStop - blockFirst));
}
++tracker.generation;
unwatchLocked(tracker, blockFirst, static_cast<std::size_t>(blockStop - blockFirst));
tracker.noteUnstampedStore(address, address + bytes);
if (order != nullptr) *order = tracker.generation.load(std::memory_order_relaxed);
return 0;
}
if (runs.stamped != 0) ++tracker.generation;
@@ -2296,7 +2337,9 @@ static std::uint64_t markWritten(std::uint64_t address, std::size_t bytes, bool
tracker.stamp(block, tracker.generation, StampKind::Driver);
tracker.noteDriverStore(block, address, address + bytes, tracker.generation, complete);
}
return tracker.generation;
const auto generation = tracker.generation.load(std::memory_order_relaxed);
if (order != nullptr) *order = generation;
return generation;
}
std::uint64_t MarkWritten(std::uint64_t address, std::size_t bytes) {
@@ -2307,6 +2350,10 @@ std::uint64_t MarkPossiblyWritten(std::uint64_t address, std::size_t bytes) {
return markWritten(address, bytes, false);
}
std::uint64_t MarkPossiblyWritten(std::uint64_t address, std::size_t bytes, std::uint64_t& order) {
return markWritten(address, bytes, false, &order);
}
bool StoredOver(std::uint64_t address, std::size_t bytes, std::uint64_t generation) {
auto& tracker = Tracker();
const auto lock = lockTracker(tracker);
@@ -2861,6 +2908,10 @@ void SetFlushHook(void (*hook)(std::uint64_t, std::size_t)) {
GuestArena::GuestArenaSetHostReadHook_nid_no_patch(&PrepareHostRead);
}
auto CurrentFlushHook() -> void (*)(std::uint64_t, std::size_t) {
return flushHook.load(std::memory_order_acquire);
}
void SetReadGuard(void (*guard)(std::uint64_t address, std::size_t bytes)) {
readGuard.store(guard, std::memory_order_release);
GuestArena::GuestArenaSetHostReadHook_nid_no_patch(&PrepareHostRead);
@@ -2874,6 +2925,105 @@ void FlushGpuWrites(std::uint64_t address, std::size_t bytes) {
if (const auto hook = flushHook.load(std::memory_order_acquire)) hook(address, bytes);
}
namespace {
std::atomic<std::uint64_t> lockedHostWrites{0};
std::atomic<bool> lockedHostWriteLogged{false};
void noteLockedHostWrite(std::uintptr_t address, std::size_t bytes) {
static const bool assertLock = std::getenv("APS5_ASSERT_GPU_LOCK") != nullptr;
if (assertLock) {
std::fprintf(stderr, "[lock] ASSERT: a host write of 0x%zx bytes at 0x%llx was made under GuestMemory::GpuMutex on thread tagged 0x%x\n", bytes, static_cast<unsigned long long>(address), GpuLockThreadTag());
std::abort();
}
lockedHostWrites.fetch_add(1, std::memory_order_relaxed);
if (!lockedHostWriteLogged.exchange(true, std::memory_order_relaxed)) std::fprintf(stderr, "[lock] a host write of 0x%zx bytes at 0x%llx was made under GuestMemory::GpuMutex on thread tagged 0x%x; it waits for GPU work with the mutex held (counted, logged once)\n", bytes, static_cast<unsigned long long>(address), GpuLockThreadTag());
}
std::atomic<double (*)()> waitedMsProvider{nullptr};
double threadWaitedMs() {
const auto provider = waitedMsProvider.load(std::memory_order_acquire);
return provider != nullptr ? provider() : 0.0;
}
struct HostWriteTotals {
std::atomic<std::uint64_t> calls{0};
std::atomic<std::uint64_t> waited{0};
std::atomic<std::uint64_t> waitedNanoseconds{0};
std::atomic<std::uint64_t> maxWaitedNanoseconds{0};
std::atomic<std::int64_t> lastReport{0};
};
HostWriteTotals& HostWrites() {
static HostWriteTotals totals;
return totals;
}
void noteHostWriteWait(double waitedMs) {
auto& totals = HostWrites();
totals.calls.fetch_add(1, std::memory_order_relaxed);
if (waitedMs > 0) {
const auto nanoseconds = static_cast<std::uint64_t>(waitedMs * 1e6);
totals.waited.fetch_add(1, std::memory_order_relaxed);
totals.waitedNanoseconds.fetch_add(nanoseconds, std::memory_order_relaxed);
auto most = totals.maxWaitedNanoseconds.load(std::memory_order_relaxed);
while (nanoseconds > most && !totals.maxWaitedNanoseconds.compare_exchange_weak(most, nanoseconds, std::memory_order_relaxed)) {
}
}
const auto nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
auto last = totals.lastReport.load(std::memory_order_relaxed);
if (nowMs - last < 10000 || !totals.lastReport.compare_exchange_strong(last, nowMs)) return;
AgcDriver::ProfilePrint_nid_no_patch("%s", HostWriteReport().c_str());
}
}
std::uint64_t LockedHostWrites() {
return lockedHostWrites.load(std::memory_order_relaxed);
}
void SetWaitedMsProvider(double (*provider)()) {
waitedMsProvider.store(provider, std::memory_order_release);
}
HostWriteCounts HostWritesCounted() {
const auto& totals = HostWrites();
return {totals.calls.load(std::memory_order_relaxed), totals.waited.load(std::memory_order_relaxed), totals.waitedNanoseconds.load(std::memory_order_relaxed) / 1e6, totals.maxWaitedNanoseconds.load(std::memory_order_relaxed) / 1e6};
}
std::string HostWriteReport() {
const auto counts = HostWritesCounted();
char line[256];
std::snprintf(line, sizeof(line), "[hostwrite] %llu host writes, %llu waited for GPU work over their range: %.2f ms in total, %.2f ms at most\n", static_cast<unsigned long long>(counts.calls), static_cast<unsigned long long>(counts.waited), counts.waitedMs, counts.maxWaitedMs);
return line;
}
void PrepareHostWrite(std::uintptr_t address, std::size_t bytes) {
if (ownHostWrite || bytes == 0) return;
if (GpuMutex().HeldByThisThread()) noteLockedHostWrite(address, bytes);
const HostWriteInFlight inFlight;
if (hostWritesStopped.load(std::memory_order_seq_cst)) return;
const ReadSiteScope site(ReadSite::Store);
if (!MemoryProfiled()) {
FlushGpuWrites(address, bytes);
return;
}
const auto waitedBefore = threadWaitedMs();
FlushGpuWrites(address, bytes);
noteHostWriteWait(threadWaitedMs() - waitedBefore);
}
bool StopHostWrites(std::uint32_t boundMs) {
hostWritesStopped.store(true, std::memory_order_seq_cst);
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(boundMs);
while (hostWritesInFlight.load(std::memory_order_seq_cst) != 0) {
if (std::chrono::steady_clock::now() >= deadline) return false;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return true;
}
void Read(std::uint64_t address, std::span<std::byte> destination, std::size_t alignment) {
if (destination.empty()) return;
GuardRead(address, destination.size());
@@ -3057,12 +3207,15 @@ void WriteChangedCommitted(std::uint64_t address, std::span<const std::byte> cur
}
}
#if defined(__x86_64__) || defined(_M_X64)
static std::uint32_t changedByteCount(__m128i same) {
const auto sums = _mm_sad_epu8(_mm_and_si128(same, _mm_set1_epi8(1)), _mm_setzero_si128());
return 16u - static_cast<std::uint32_t>(_mm_cvtsi128_si32(_mm_add_epi32(sums, _mm_unpackhi_epi64(sums, sums))));
}
#endif
std::uint32_t ChangedByteStoreLimit() {
#if defined(__x86_64__) || defined(_M_X64)
static const auto limit = [] {
#if defined(_MSC_VER) && !defined(__clang__)
int registers[4]{};
@@ -3075,13 +3228,16 @@ std::uint32_t ChangedByteStoreLimit() {
return ebx == 0x68747541u && edx == 0x69746e65u && ecx == 0x444d4163u ? 16u : 4u;
}();
return limit;
#else
return 16u;
#endif
}
void WriteChanged(std::uint64_t address, std::span<const std::byte> current, std::span<const std::byte> original) {
WriteChanged(address, current, original, ChangedByteStoreLimit());
}
static void writeChanged(std::uint64_t address, std::span<const std::byte> current, std::span<const std::byte> original, std::uint32_t byteStoreLimit, bool keepGuest) {
static void writeChanged(std::uint64_t address, std::span<const std::byte> current, std::span<const std::byte> original, [[maybe_unused]] std::uint32_t byteStoreLimit, bool keepGuest) {
require(current.size() == original.size(), "write-back snapshot sizes differ");
BreakProofs();
if (current.empty()) return;
@@ -3097,8 +3253,9 @@ static void writeChanged(std::uint64_t address, std::span<const std::byte> curre
CheckRange(destination, size, 1, true);
std::size_t firstChanged = size;
std::size_t lastChanged = 0;
bool masked = false;
std::size_t at = 0;
#if defined(__x86_64__) || defined(_M_X64)
bool masked = false;
for (; at + 16 <= size; at += 16) {
const auto bytes = _mm_loadu_si128(reinterpret_cast<const __m128i*>(current.data() + at));
const auto uploaded = _mm_loadu_si128(reinterpret_cast<const __m128i*>(original.data() + at));
@@ -3121,6 +3278,7 @@ static void writeChanged(std::uint64_t address, std::span<const std::byte> curre
lastChanged = std::max(lastChanged, at + 32 - static_cast<std::size_t>(std::countl_zero(changed)));
}
if (masked) _mm_sfence();
#endif
for (; at < size; ++at) {
if (current[at] == original[at] || (keepGuest && destination[at] != original[at])) continue;
destination[at] = current[at];
@@ -81,8 +81,7 @@ std::unique_ptr<TraceBenchWriter>& benchWriter() {
}
std::filesystem::path traceDirectory() {
const char* directory = std::getenv("APS5_TRACE_DIR");
return std::filesystem::path(directory != nullptr ? directory : ".");
return TraceFile::Directory();
}
std::uint64_t processId() {
@@ -34,11 +34,13 @@ bool ImportableGdsRequested() {
}
bool GdsShared() {
if (!ImportableGdsRequested()) return false;
static_cast<void>(GdsAddress());
return gdsShared.load(std::memory_order_acquire);
}
bool GdsImportable() {
if (!ImportableGdsRequested()) return false;
static_cast<void>(GdsAddress());
return gdsImportable.load(std::memory_order_acquire);
}
@@ -211,6 +213,7 @@ std::vector<std::byte> copyDataSource(std::span<const std::uint32_t> packet, con
}
return data;
}
if (source == CopyDataSelectGds) return copySource(GdsAddress() + packet[2], bytes, false);
if (source != CopyDataGpuClockSource) return copySource(address(packet[2], packet[3]), bytes, CopyDataImmediate(source));
const auto value = gpuClockCount();
std::vector<std::byte> data(bytes);
@@ -559,7 +562,7 @@ void Validate(std::span<const std::uint32_t> packet, std::uint32_t queue) {
size(6);
require((packet[1] & ~(0x40110f0fu | CopyDataCachePolicy)) == 0, "COPY_DATA engine or reserved fields are not implemented");
const auto source = CopyDataSource(packet);
const auto destination = ((packet[1] >> 8u) & 0xfu) << 1u;
const auto destination = CopyDataDestination(packet);
if (CopyDataToRegister(packet)) {
require(source == 2 || source == 4, "COPY_DATA to a register from a register, GDS, immediate or clock source is not implemented");
require((packet[2] & 3u) == 0, "misaligned COPY_DATA source");
@@ -568,9 +571,11 @@ void Validate(std::span<const std::uint32_t> packet, std::uint32_t queue) {
break;
}
require(destination <= 10, "invalid COPY_DATA destination");
require(destination == 2 || destination == 4 || destination == 10, "COPY_DATA GDS or performance-counter destination is not implemented");
require(source == 2 || source == 4 || source == 5 || source == 10 || source == 11 || source == CopyDataGpuClockSource || source == CopyDataRegisterSource, "COPY_DATA GDS or reference-clock source is not implemented");
require(destination == 2 || destination == 4 || destination == 10 || destination == CopyDataSelectGds, "COPY_DATA performance-counter destination is not implemented");
require(source == 2 || source == 4 || source == 5 || source == 10 || source == 11 || source == CopyDataGpuClockSource || source == CopyDataRegisterSource || source == CopyDataSelectGds, "COPY_DATA reference-clock source is not implemented");
require(source != CopyDataRegisterSource || (packet[3] == 0 && registerBankBase(packet[2]) != 0 && registerBankBase(packet[2]) == registerBankBase(packet[2] + copyDataCount(packet) - 1)), "COPY_DATA from a register outside the shader, context and user config registers is not implemented");
require(source != CopyDataSelectGds || (packet[3] == 0 && gdsRange(packet[2], CopyDataBytes(packet))), "COPY_DATA GDS source range exceeds the GDS");
require(destination != CopyDataSelectGds || (packet[5] == 0 && gdsRange(packet[4], CopyDataBytes(packet))), "COPY_DATA GDS destination range exceeds the GDS");
require(source < 10 || source == CopyDataGpuClockSource || ((packet[1] & 0x10000u) == 0 && packet[3] == 0), "64-bit immediate COPY_DATA is not implemented");
break;
}
@@ -948,6 +953,15 @@ DrawArguments ReadDrawArguments(const DrawParameters::IndirectDraw& indirect, st
return {words[0], words[1], words[2], 0, words[3]};
}
DrawArguments ReadDrawArgumentsUnsynced(const DrawParameters::IndirectDraw& indirect, std::uint32_t record) {
require(record < indirect.count, "indirect draw record index exceeds the packet's count");
std::array<std::uint32_t, 5> words{};
const GuestMemory::ReadSiteScope site(GuestMemory::ReadSite::IndirectArguments);
GuestMemory::ReadCommittedUnsynced(indirect.arguments + static_cast<std::uint64_t>(record) * indirect.stride, std::as_writable_bytes(std::span(words)).first(indirect.recordBytes));
if (indirect.recordBytes == 20) return {words[0], words[1], words[2], words[3], words[4]};
return {words[0], words[1], words[2], 0, words[3]};
}
std::uint32_t ReadDrawCount(const DrawParameters::IndirectDraw& indirect) {
require(indirect.countIndirect && indirect.countAddress != 0, "indirect draw has no count address");
std::uint32_t count = 0;
@@ -1239,7 +1253,7 @@ void Execute(std::span<const std::uint32_t> packet, QueueState& queue) {
for (std::uint32_t i = 0; i < count; ++i) writeRegister(queue, 0x69, packet[4] - ContextRegisterBase + i, values[i]);
return;
}
const auto destination = address(packet[4], packet[5]);
const auto destination = CopyDataDestination(packet) == CopyDataSelectGds ? GdsAddress() + packet[4] : address(packet[4], packet[5]);
const auto data = copyDataSource(packet, queue, CopyDataBytes(packet));
GuestMemory::CheckRange(reinterpret_cast<void*>(destination), data.size(), 1, true);
GuestMemory::Write(destination, data);
@@ -117,6 +117,18 @@ VkExtent2D PresentationPass::DumpExtent(std::uint32_t width, std::uint32_t heigh
return {(width + stride - 1) / stride, (height + stride - 1) / stride};
}
VkSubpassDependency PresentationPass::ExitDependency(VkImageLayout finalLayout) {
VkSubpassDependency dependency{0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, 0, 0};
if (finalLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
dependency.dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
dependency.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
} else if (finalLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
dependency.dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
dependency.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
}
return dependency;
}
void PresentationPass::Release(std::size_t index) noexcept {
if (index >= slots.size()) return;
auto& slot = slots[index];
@@ -181,10 +193,9 @@ const PresentationPass::Target& PresentationPass::target(VkFormat format, VkImag
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &reference;
const bool transfer = finalLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
const VkSubpassDependency dependencies[2] = {
{VK_SUBPASS_EXTERNAL, 0, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, blended ? VkAccessFlags{VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT} : VkAccessFlags{0}, blended ? VkAccessFlags{VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT} : VkAccessFlags{VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT}, 0},
{0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, transfer ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, transfer ? VK_ACCESS_TRANSFER_READ_BIT : VkAccessFlags{0}, 0},
ExitDependency(finalLayout),
};
VkRenderPassCreateInfo renderPassInfo{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
renderPassInfo.attachmentCount = 1;
@@ -364,6 +375,7 @@ VkFramebuffer PresentationPass::destinationFramebuffer(Slot& slot, const Target&
for (const auto layout : {initialLayout, finalLayout}) {
if (layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
if (layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
if (layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
}
const auto view = createView(destination, format, usage);
VkFramebuffer framebuffer = VK_NULL_HANDLE;
@@ -380,10 +392,19 @@ VkFramebuffer PresentationPass::destinationFramebuffer(Slot& slot, const Target&
void PresentationPass::RecordPresent(VkCommandBuffer commands, std::size_t index, VkImage destination, VkFormat format, VkColorSpaceKHR colorSpace, VkExtent2D extent, VkImageLayout finalLayout) {
Graphics::Require(index < slots.size() && slots[index].source != VK_NULL_HANDLE, "presentation pass slot has no source");
Graphics::Require(destination != VK_NULL_HANDLE && extent.width != 0 && extent.height != 0, "presentation pass destination is unavailable");
recordInto(commands, index, destination, format, colorSpace, extent, finalLayout, ComputeContainRect_nid_postfix(slots[index].width, slots[index].height, extent.width, extent.height));
}
void PresentationPass::RecordStage(VkCommandBuffer commands, std::size_t index, VkImage destination, VkFormat format, VkColorSpaceKHR colorSpace, VkExtent2D extent, VkImageLayout finalLayout) {
Graphics::Require(index < slots.size() && slots[index].source != VK_NULL_HANDLE, "presentation pass slot has no source");
Graphics::Require(destination != VK_NULL_HANDLE && extent.width != 0 && extent.height != 0, "presentation pass destination is unavailable");
recordInto(commands, index, destination, format, colorSpace, extent, finalLayout, AspectFitRect{0, 0, extent.width, extent.height});
}
void PresentationPass::recordInto(VkCommandBuffer commands, std::size_t index, VkImage destination, VkFormat format, VkColorSpaceKHR colorSpace, VkExtent2D extent, VkImageLayout finalLayout, const AspectFitRect& rect) {
auto& slot = slots[index];
const auto& entry = target(format, finalLayout);
const auto framebuffer = destinationFramebuffer(slot, entry, destination, format, extent, VK_IMAGE_LAYOUT_UNDEFINED, finalLayout);
const auto rect = ComputeContainRect_nid_postfix(slot.width, slot.height, extent.width, extent.height);
const bool hdr10 = colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT;
Graphics::Require(colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR || (hdr10 && (slot.mode & ModePq) != 0 && TenBitFormat(format)), "presentation pass presents only PQ display buffers to a 10-bit HDR10 destination");
const std::uint32_t mode = (hdr10 ? slot.mode & ~ModePq : slot.mode) | (TenBitFormat(format) ? ModeKeepTenBit : 0u);
@@ -151,7 +151,17 @@ void PresentationScaler::RecordBlit(VkCommandBuffer commands, VkImage destinatio
void PresentationScaler::RecordBlitFrom(const Graphics::Context& context, VkCommandBuffer commands, VkImage image, VkImageLayout layout, std::uint32_t width, std::uint32_t height, VkFilter filter, VkImage destinationImage, std::uint32_t destinationWidth, std::uint32_t destinationHeight, std::uint32_t layer) {
Graphics::Require(image != VK_NULL_HANDLE && width != 0 && height != 0, "presentation blit source is unavailable");
const auto rect = ComputeContainRect_nid_postfix(width, height, destinationWidth, destinationHeight);
RecordStretchFrom(context, commands, image, layout, width, height, filter, destinationImage, ComputeContainRect_nid_postfix(width, height, destinationWidth, destinationHeight), layer);
}
void PresentationScaler::RecordStretch(VkCommandBuffer commands, VkImage destinationImage, const AspectFitRect& destination) {
Graphics::Require(sourceImage != VK_NULL_HANDLE, "presentation source image has not been created");
RecordStretchFrom(context, commands, sourceImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, sourceWidth, sourceHeight, VK_FILTER_LINEAR, destinationImage, destination);
}
void PresentationScaler::RecordStretchFrom(const Graphics::Context& context, VkCommandBuffer commands, VkImage image, VkImageLayout layout, std::uint32_t width, std::uint32_t height, VkFilter filter, VkImage destinationImage, const AspectFitRect& rect, std::uint32_t layer) {
Graphics::Require(image != VK_NULL_HANDLE && width != 0 && height != 0, "presentation blit source is unavailable");
Graphics::Require(destinationImage != VK_NULL_HANDLE && rect.width != 0 && rect.height != 0, "presentation blit destination is unavailable");
VkImageBlit blit{};
blit.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, layer, 1};
blit.srcOffsets[0] = {0, 0, 0};
@@ -0,0 +1,390 @@
#include "prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp"
#include "prx/libSceAgcDriver/Execution/include/AspectFit.hpp"
#include "prx/libSceAgcDriver/Execution/include/PresentationPass.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp"
#include "prx/libSceAgcDriver/Graphics/shaders/FsrEasuFrag_spv.h"
#include "prx/libSceAgcDriver/Graphics/shaders/FsrRcasFrag_spv.h"
#include "prx/libSceAgcDriver/Graphics/shaders/PresentationPassVert_spv.h"
#include <array>
#include <cmath>
namespace AgcDriver {
namespace {
struct EasuParameters {
float sourceWidth;
float sourceHeight;
float outputWidth;
float outputHeight;
};
struct RcasParameters {
std::int32_t x;
std::int32_t y;
std::int32_t width;
std::int32_t height;
float sharpness;
};
constexpr std::uint32_t ParameterBytes = sizeof(RcasParameters);
static_assert(sizeof(EasuParameters) <= ParameterBytes);
}
PresentationUpscaler::PresentationUpscaler(const Graphics::Context& context, std::size_t slotCount, float sharpness) : context(context), sharpness(sharpness), slots(slotCount) {
Graphics::Require(slotCount != 0, "presentation upscaler needs at least one slot");
Graphics::Require(std::isfinite(sharpness) && sharpness >= 0.0f && sharpness <= 2.0f, "FSR sharpness must be from 0.0 to 2.0 stops");
try {
VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
samplerInfo.magFilter = VK_FILTER_NEAREST;
samplerInfo.minFilter = VK_FILTER_NEAREST;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
Graphics::Check(context.Function<PFN_vkCreateSampler>("vkCreateSampler")(context.device, &samplerInfo, nullptr, &sampler), "vkCreateSampler presentation upscaler");
const VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, &sampler};
VkDescriptorSetLayoutCreateInfo descriptorInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};
descriptorInfo.bindingCount = 1;
descriptorInfo.pBindings = &binding;
Graphics::Check(context.Function<PFN_vkCreateDescriptorSetLayout>("vkCreateDescriptorSetLayout")(context.device, &descriptorInfo, nullptr, &descriptorLayout), "vkCreateDescriptorSetLayout presentation upscaler");
const VkPushConstantRange push{VK_SHADER_STAGE_FRAGMENT_BIT, 0, ParameterBytes};
VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
layoutInfo.setLayoutCount = 1;
layoutInfo.pSetLayouts = &descriptorLayout;
layoutInfo.pushConstantRangeCount = 1;
layoutInfo.pPushConstantRanges = &push;
Graphics::Check(context.Function<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &pipelineLayout), "vkCreatePipelineLayout presentation upscaler");
const auto sets = static_cast<std::uint32_t>(slotCount * 2);
const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, sets};
VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
poolInfo.maxSets = sets;
poolInfo.poolSizeCount = 1;
poolInfo.pPoolSizes = &size;
Graphics::Check(context.Function<PFN_vkCreateDescriptorPool>("vkCreateDescriptorPool")(context.device, &poolInfo, nullptr, &descriptorPool), "vkCreateDescriptorPool presentation upscaler");
for (auto& slot : slots) {
const std::array<VkDescriptorSetLayout, 2> layouts{descriptorLayout, descriptorLayout};
std::array<VkDescriptorSet, 2> allocated{};
VkDescriptorSetAllocateInfo allocation{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
allocation.descriptorPool = descriptorPool;
allocation.descriptorSetCount = static_cast<std::uint32_t>(layouts.size());
allocation.pSetLayouts = layouts.data();
Graphics::Check(context.Function<PFN_vkAllocateDescriptorSets>("vkAllocateDescriptorSets")(context.device, &allocation, allocated.data()), "vkAllocateDescriptorSets presentation upscaler");
slot.easuSet = allocated[0];
slot.rcasSet = allocated[1];
}
vertex = Graphics::CreateShaderModule(context, PRESENTATION_PASS_VERT_SPV, sizeof(PRESENTATION_PASS_VERT_SPV), "vkCreateShaderModule presentation upscaler vertex");
easu = Graphics::CreateShaderModule(context, FSR_EASU_FRAG_SPV, sizeof(FSR_EASU_FRAG_SPV), "vkCreateShaderModule FSR EASU");
rcas = Graphics::CreateShaderModule(context, FSR_RCAS_FRAG_SPV, sizeof(FSR_RCAS_FRAG_SPV), "vkCreateShaderModule FSR RCAS");
} catch (...) {
release();
throw;
}
}
PresentationUpscaler::~PresentationUpscaler() {
release();
}
void PresentationUpscaler::release() noexcept {
for (std::size_t i = 0; i < slots.size(); ++i) {
Release(i);
releaseSurface(slots[i].stage);
releaseSurface(slots[i].upscaled);
}
for (const auto& [key, entry] : targets) {
if (entry.pipeline) context.Function<PFN_vkDestroyPipeline>("vkDestroyPipeline")(context.device, entry.pipeline, nullptr);
if (entry.renderPass) context.Function<PFN_vkDestroyRenderPass>("vkDestroyRenderPass")(context.device, entry.renderPass, nullptr);
}
targets.clear();
for (auto* module : {&rcas, &easu, &vertex}) {
if (*module) context.Function<PFN_vkDestroyShaderModule>("vkDestroyShaderModule")(context.device, *module, nullptr);
*module = VK_NULL_HANDLE;
}
if (descriptorPool) context.Function<PFN_vkDestroyDescriptorPool>("vkDestroyDescriptorPool")(context.device, descriptorPool, nullptr);
if (pipelineLayout) context.Function<PFN_vkDestroyPipelineLayout>("vkDestroyPipelineLayout")(context.device, pipelineLayout, nullptr);
if (descriptorLayout) context.Function<PFN_vkDestroyDescriptorSetLayout>("vkDestroyDescriptorSetLayout")(context.device, descriptorLayout, nullptr);
if (sampler) context.Function<PFN_vkDestroySampler>("vkDestroySampler")(context.device, sampler, nullptr);
descriptorPool = VK_NULL_HANDLE;
pipelineLayout = VK_NULL_HANDLE;
descriptorLayout = VK_NULL_HANDLE;
sampler = VK_NULL_HANDLE;
}
bool PresentationUpscaler::Upscales(std::uint32_t width, std::uint32_t height, VkExtent2D extent) {
const auto rect = ComputeContainRect_nid_postfix(width, height, extent.width, extent.height);
return rect.width > width || rect.height > height;
}
VkExtent2D PresentationUpscaler::StageExtent(std::uint32_t width, std::uint32_t height, VkExtent2D extent) {
if (Upscales(width, height, extent)) return {width, height};
const auto rect = ComputeContainRect_nid_postfix(width, height, extent.width, extent.height);
return {rect.width, rect.height};
}
void PresentationUpscaler::Release(std::size_t index) noexcept {
if (index >= slots.size()) return;
for (const auto& [view, framebuffer] : slots[index].transient) {
if (framebuffer) context.Function<PFN_vkDestroyFramebuffer>("vkDestroyFramebuffer")(context.device, framebuffer, nullptr);
if (view) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, view, nullptr);
}
slots[index].transient.clear();
}
void PresentationUpscaler::releaseSurface(Surface& surface) noexcept {
if (surface.sampled) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, surface.sampled, nullptr);
if (surface.image) context.Function<PFN_vkDestroyImage>("vkDestroyImage")(context.device, surface.image, nullptr);
if (surface.memory) context.Function<PFN_vkFreeMemory>("vkFreeMemory")(context.device, surface.memory, nullptr);
surface = Surface{};
}
void PresentationUpscaler::ensureSurface(Surface& surface, VkFormat format, VkExtent2D extent, VkImageUsageFlags usage) {
if (surface.image != VK_NULL_HANDLE && surface.format == format && surface.extent.width == extent.width && surface.extent.height == extent.height) return;
releaseSurface(surface);
VkFormatProperties properties{};
context.formatProperties(context.physical, format, &properties);
VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT;
if ((usage & VK_IMAGE_USAGE_TRANSFER_DST_BIT) != 0) needed |= VK_FORMAT_FEATURE_BLIT_DST_BIT;
Graphics::Require((properties.optimalTilingFeatures & needed) == needed, "presentation upscaler format cannot be rendered, sampled and blitted to");
try {
VkImageCreateInfo imageInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.format = format;
imageInfo.extent = {extent.width, extent.height, 1u};
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
Graphics::Check(context.Function<PFN_vkCreateImage>("vkCreateImage")(context.device, &imageInfo, nullptr, &surface.image), "vkCreateImage presentation upscaler");
VkMemoryRequirements requirements{};
context.Function<PFN_vkGetImageMemoryRequirements>("vkGetImageMemoryRequirements")(context.device, surface.image, &requirements);
VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocation.allocationSize = requirements.size;
allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
Graphics::Check(context.Function<PFN_vkAllocateMemory>("vkAllocateMemory")(context.device, &allocation, nullptr, &surface.memory), "vkAllocateMemory presentation upscaler");
Graphics::Check(context.Function<PFN_vkBindImageMemory>("vkBindImageMemory")(context.device, surface.image, surface.memory, 0), "vkBindImageMemory presentation upscaler");
surface.sampled = createView(surface.image, format, VK_IMAGE_USAGE_SAMPLED_BIT);
surface.format = format;
surface.extent = extent;
} catch (...) {
releaseSurface(surface);
throw;
}
}
VkImageView PresentationUpscaler::createView(VkImage image, VkFormat format, VkImageUsageFlags usage) const {
VkImageViewUsageCreateInfo usageInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO};
usageInfo.usage = usage;
VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
viewInfo.pNext = &usageInfo;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY};
viewInfo.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageView view = VK_NULL_HANDLE;
Graphics::Check(context.Function<PFN_vkCreateImageView>("vkCreateImageView")(context.device, &viewInfo, nullptr, &view), "vkCreateImageView presentation upscaler");
return view;
}
VkImage PresentationUpscaler::Stage(std::size_t index, VkFormat format, VkExtent2D extent) {
Graphics::Require(index < slots.size(), "presentation upscaler slot is out of range");
Graphics::Require(extent.width != 0 && extent.height != 0, "presentation upscaler stage extent must be non-zero");
auto& slot = slots[index];
ensureSurface(slot.stage, format, extent, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
return slot.stage.image;
}
void PresentationUpscaler::RecordStageTransferDestination(VkCommandBuffer commands, std::size_t index) {
Graphics::Require(index < slots.size() && slots[index].stage.image != VK_NULL_HANDLE, "presentation upscaler slot has no stage");
VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = slots[index].stage.image;
barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
}
void PresentationUpscaler::RecordStageWritten(VkCommandBuffer commands, std::size_t index, VkImageLayout layout, VkPipelineStageFlags stage, VkAccessFlags access) {
Graphics::Require(index < slots.size() && slots[index].stage.image != VK_NULL_HANDLE, "presentation upscaler slot has no stage");
VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
barrier.srcAccessMask = access;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.oldLayout = layout;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = slots[index].stage.image;
barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, stage, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
}
const PresentationUpscaler::Target& PresentationUpscaler::target(VkFormat format, VkImageLayout finalLayout, Filter filter) {
const auto key = std::tuple{format, finalLayout, filter};
if (const auto found = targets.find(key); found != targets.end()) return found->second;
VkFormatProperties properties{};
context.formatProperties(context.physical, format, &properties);
Graphics::Require((properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0, "presentation upscaler format is not renderable");
Target created;
try {
VkAttachmentDescription attachment{};
attachment.format = format;
attachment.samples = VK_SAMPLE_COUNT_1_BIT;
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachment.finalLayout = finalLayout;
const VkAttachmentReference reference{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &reference;
const VkSubpassDependency dependencies[2] = {
{VK_SUBPASS_EXTERNAL, 0, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, 0},
PresentationPass::ExitDependency(finalLayout),
};
VkRenderPassCreateInfo renderPassInfo{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
renderPassInfo.attachmentCount = 1;
renderPassInfo.pAttachments = &attachment;
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 2;
renderPassInfo.pDependencies = dependencies;
Graphics::Check(context.Function<PFN_vkCreateRenderPass>("vkCreateRenderPass")(context.device, &renderPassInfo, nullptr, &created.renderPass), "vkCreateRenderPass presentation upscaler");
VkPipelineShaderStageCreateInfo stages[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}};
stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
stages[0].module = vertex;
stages[0].pName = "main";
stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
stages[1].module = filter == Filter::Easu ? easu : rcas;
stages[1].pName = "main";
VkPipelineVertexInputStateCreateInfo vertexInput{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO};
assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
viewport.viewportCount = 1;
viewport.scissorCount = 1;
VkPipelineRasterizationStateCreateInfo rasterization{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO};
rasterization.polygonMode = VK_POLYGON_MODE_FILL;
rasterization.cullMode = VK_CULL_MODE_NONE;
rasterization.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterization.lineWidth = 1.0f;
VkPipelineMultisampleStateCreateInfo multisample{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO};
multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineColorBlendAttachmentState blendAttachment{};
blendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO};
blend.attachmentCount = 1;
blend.pAttachments = &blendAttachment;
const VkDynamicState dynamicStates[2] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
dynamic.dynamicStateCount = 2;
dynamic.pDynamicStates = dynamicStates;
VkGraphicsPipelineCreateInfo pipelineInfo{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = stages;
pipelineInfo.pVertexInputState = &vertexInput;
pipelineInfo.pInputAssemblyState = &assembly;
pipelineInfo.pViewportState = &viewport;
pipelineInfo.pRasterizationState = &rasterization;
pipelineInfo.pMultisampleState = &multisample;
pipelineInfo.pColorBlendState = &blend;
pipelineInfo.pDynamicState = &dynamic;
pipelineInfo.layout = pipelineLayout;
pipelineInfo.renderPass = created.renderPass;
const auto lock = context.LockPipelineCacheForUse();
Graphics::Check(context.Function<PFN_vkCreateGraphicsPipelines>("vkCreateGraphicsPipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &created.pipeline), "vkCreateGraphicsPipelines presentation upscaler");
} catch (...) {
if (created.renderPass) context.Function<PFN_vkDestroyRenderPass>("vkDestroyRenderPass")(context.device, created.renderPass, nullptr);
throw;
}
return targets.emplace(key, created).first->second;
}
VkFramebuffer PresentationUpscaler::transientFramebuffer(Slot& slot, VkRenderPass renderPass, VkImage image, VkFormat format, VkExtent2D extent, VkImageLayout finalLayout) {
const auto view = createView(image, format, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | (finalLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ? VK_IMAGE_USAGE_TRANSFER_SRC_BIT : 0u) | (finalLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL ? VK_IMAGE_USAGE_SAMPLED_BIT : 0u));
VkFramebufferCreateInfo info{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
info.renderPass = renderPass;
info.attachmentCount = 1;
info.pAttachments = &view;
info.width = extent.width;
info.height = extent.height;
info.layers = 1;
VkFramebuffer framebuffer = VK_NULL_HANDLE;
const auto created = context.Function<PFN_vkCreateFramebuffer>("vkCreateFramebuffer")(context.device, &info, nullptr, &framebuffer);
if (created != VK_SUCCESS) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, view, nullptr);
Graphics::Check(created, "vkCreateFramebuffer presentation upscaler");
slot.transient.emplace_back(view, framebuffer);
return framebuffer;
}
void PresentationUpscaler::bindSource(VkDescriptorSet set, VkImageView view) const {
const VkDescriptorImageInfo imageInfo{sampler, view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
write.dstSet = set;
write.dstBinding = 0;
write.descriptorCount = 1;
write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write.pImageInfo = &imageInfo;
context.Function<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(context.device, 1, &write, 0, nullptr);
}
void PresentationUpscaler::draw(VkCommandBuffer commands, const Target& entry, VkFramebuffer framebuffer, VkExtent2D extent, VkDescriptorSet set, const void* parameters, std::uint32_t size) const {
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
begin.renderPass = entry.renderPass;
begin.framebuffer = framebuffer;
begin.renderArea = {{0, 0}, extent};
context.Function<PFN_vkCmdBeginRenderPass>("vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, entry.pipeline);
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(extent.width), static_cast<float>(extent.height), 0.0f, 1.0f};
const VkRect2D scissor{{0, 0}, extent};
context.Function<PFN_vkCmdSetViewport>("vkCmdSetViewport")(commands, 0, 1, &viewport);
context.Function<PFN_vkCmdSetScissor>("vkCmdSetScissor")(commands, 0, 1, &scissor);
context.Function<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, 0, nullptr);
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, size, parameters);
context.Function<PFN_vkCmdDraw>("vkCmdDraw")(commands, 3, 1, 0, 0);
context.Function<PFN_vkCmdEndRenderPass>("vkCmdEndRenderPass")(commands);
}
void PresentationUpscaler::RecordUpscale(VkCommandBuffer commands, std::size_t index, VkImage destination, VkExtent2D extent, VkImageLayout finalLayout) {
Graphics::Require(index < slots.size() && slots[index].stage.image != VK_NULL_HANDLE, "presentation upscaler slot has no stage");
Graphics::Require(destination != VK_NULL_HANDLE && extent.width != 0 && extent.height != 0, "presentation upscaler destination is unavailable");
auto& slot = slots[index];
const auto& entry = target(slot.stage.format, finalLayout, Filter::Easu);
const auto framebuffer = transientFramebuffer(slot, entry.renderPass, destination, slot.stage.format, extent, finalLayout);
bindSource(slot.easuSet, slot.stage.sampled);
const EasuParameters parameters{static_cast<float>(slot.stage.extent.width), static_cast<float>(slot.stage.extent.height), static_cast<float>(extent.width), static_cast<float>(extent.height)};
draw(commands, entry, framebuffer, extent, slot.easuSet, &parameters, sizeof(parameters));
}
void PresentationUpscaler::RecordPresent(VkCommandBuffer commands, std::size_t index, std::uint32_t width, std::uint32_t height, VkImage destination, VkExtent2D extent, VkImageLayout finalLayout) {
Graphics::Require(index < slots.size() && slots[index].stage.image != VK_NULL_HANDLE, "presentation upscaler slot has no stage");
Graphics::Require(destination != VK_NULL_HANDLE && extent.width != 0 && extent.height != 0, "presentation upscaler destination is unavailable");
auto& slot = slots[index];
const auto staged = StageExtent(width, height, extent);
Graphics::Require(slot.stage.extent.width == staged.width && slot.stage.extent.height == staged.height, "presentation upscaler stage does not match the source and destination");
const auto rect = ComputeContainRect_nid_postfix(width, height, extent.width, extent.height);
VkImageView sharpened = slot.stage.sampled;
if (Upscales(width, height, extent)) {
const VkExtent2D upscaled{rect.width, rect.height};
ensureSurface(slot.upscaled, slot.stage.format, upscaled, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
RecordUpscale(commands, index, slot.upscaled.image, upscaled, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
sharpened = slot.upscaled.sampled;
}
const auto& entry = target(slot.stage.format, finalLayout, Filter::Rcas);
const auto framebuffer = transientFramebuffer(slot, entry.renderPass, destination, slot.stage.format, extent, finalLayout);
bindSource(slot.rcasSet, sharpened);
const RcasParameters parameters{rect.x, rect.y, static_cast<std::int32_t>(rect.width), static_cast<std::int32_t>(rect.height), sharpness};
draw(commands, entry, framebuffer, extent, slot.rcasSet, &parameters, sizeof(parameters));
}
}
@@ -3,6 +3,7 @@
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdlib>
#include <fstream>
#include <stdexcept>
#include <string>
@@ -14,6 +15,16 @@
namespace AgcDriver {
std::filesystem::path TraceFile::Directory() {
#ifdef _WIN32
const wchar_t* directory = _wgetenv(L"APS5_TRACE_DIR");
return std::filesystem::path(directory != nullptr ? directory : L".");
#else
const char* directory = std::getenv("APS5_TRACE_DIR");
return std::filesystem::path(directory != nullptr ? directory : ".");
#endif
}
void TraceFile::WriteGzip(const std::filesystem::path& path, std::string_view text) {
z_stream stream{};
if (deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY) != Z_OK) throw std::runtime_error("deflateInit2 failed");
@@ -39,9 +39,11 @@
#include "prx/libSceAgcDriver/Execution/include/PadStatusOverlay.hpp"
#include "prx/libSceAgcDriver/Execution/include/PresentationPass.hpp"
#include "prx/libSceAgcDriver/Execution/include/PresentationScaler.hpp"
#include "prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp"
#include "prx/libSceAgcDriver/Execution/include/Screenshot.hpp"
#include "prx/libSceAgcDriver/Execution/include/SubmissionSnapshots.hpp"
#include "prx/libSceAgcDriver/TraceRevision.hpp"
#include "prx/libSceAgcDriver/Execution/include/UpscaleMode.hpp"
#include "prx/libkernel/AppMetadata/include/AppMetadata.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
@@ -409,6 +411,7 @@ private:
// The [present] line's counters (see the header); mutated under State::presentMutex.
VulkanDevice::PresentStatistics presentCounters{};
std::atomic<std::uint64_t> upscaledPresents{0};
}
@@ -573,6 +576,7 @@ struct VulkanDevice::State {
bool float16DenormPreserve = false;
bool float32FlushToZeroCandidate = false;
bool float32FlushToZero = false;
bool float32FlushComputeOnly = false;
bool float16WidenNans = false;
bool float16NarrowNans = false;
bool float32DenormPreserve = false;
@@ -725,6 +729,7 @@ struct VulkanDevice::State {
std::unique_ptr<PresentationPass> presentation;
std::unique_ptr<PresentationPass> planePass;
std::unique_ptr<PerformanceOverlay> overlay;
std::unique_ptr<PresentationUpscaler> upscaler;
std::unique_ptr<PerformanceOverlay> keyboard;
std::unique_ptr<PerformanceOverlay> padStatus;
VkFormat surfaceFormat = VK_FORMAT_B8G8R8A8_UNORM;
@@ -1013,6 +1018,7 @@ struct VulkanDevice::State {
void RetireSlot(PresentSlot& slot) {
slot.inFlight = false;
if (presentation) presentation->Release(static_cast<std::size_t>(&slot - presentSlots.data()));
if (upscaler) upscaler->Release(static_cast<std::size_t>(&slot - presentSlots.data()));
if (planePass) planePass->Release(static_cast<std::size_t>(&slot - presentSlots.data()));
slot.kept.reset();
slot.keptPlane.reset();
@@ -1197,6 +1203,7 @@ struct VulkanDevice::State {
detiler.reset();
colorTransfer.reset();
overlay.reset();
upscaler.reset();
planePass.reset();
keyboard.reset();
padStatus.reset();
@@ -1567,6 +1574,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
if ((state->subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT) != 0) state->capabilities.push_back(spv::CapabilityGroupNonUniformBallot);
if ((state->subgroup.supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_BIT) != 0) state->capabilities.push_back(spv::CapabilityGroupNonUniformShuffle);
if ((state->subgroup.supportedOperations & VK_SUBGROUP_FEATURE_ARITHMETIC_BIT) != 0) state->capabilities.push_back(spv::CapabilityGroupNonUniformArithmetic);
if ((state->subgroup.supportedOperations & VK_SUBGROUP_FEATURE_QUAD_BIT) != 0) state->capabilities.push_back(spv::CapabilityGroupNonUniformQuad);
}
APS5_LOG_OUT("Selected GPU name=%s vendor=0x%x device=0x%x subgroup=%u", state->properties.deviceName, state->properties.vendorID, state->properties.deviceID, state->subgroup.subgroupSize);
state->InstanceFunction<PFN_vkGetPhysicalDeviceMemoryProperties>("vkGetPhysicalDeviceMemoryProperties")(selected, &state->memoryProperties);
@@ -1782,6 +1790,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
floatControls.denormBehaviorIndependence == VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL;
const auto float32Flush = Float32FlushControlFor(driverId, floatControls.shaderDenormFlushToZeroFloat32, floatControls.denormBehaviorIndependence);
state->float32FlushToZeroCandidate = float32Flush.probe && std::getenv("APS5_NO_HW_F32_FLUSH") == nullptr;
state->float32FlushComputeOnly = float32Flush.computeOnly;
if (state->float32FlushToZeroCandidate && float32Flush.declared) state->capabilities.push_back(spv::CapabilityDenormFlushToZero);
state->float32DenormPreserve = floatControls.shaderDenormPreserveFloat32 == VK_TRUE && floatControls.denormBehaviorIndependence != VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE && std::getenv("APS5_NO_HW_F32_PRESERVE") == nullptr;
if ((state->float16DenormPreserve || state->float32DenormPreserve) && std::find(state->capabilities.begin(), state->capabilities.end(), static_cast<std::uint32_t>(spv::CapabilityDenormPreserve)) == state->capabilities.end()) state->capabilities.push_back(spv::CapabilityDenormPreserve);
@@ -2077,6 +2086,8 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
require(available.samplerAnisotropy && available.textureCompressionBC, "device lacks sampler anisotropy or BC texture compression support required for texture sampling");
enabled.samplerAnisotropy = VK_TRUE;
enabled.textureCompressionBC = VK_TRUE;
require(available.independentBlend, "device lacks independentBlend, required for color targets with different blend states");
enabled.independentBlend = VK_TRUE;
// Guest shaders routinely read past descriptor ranges; robust access turns that into zeros
// instead of a GPU fault that loses the device.
enabled.robustBufferAccess = available.robustBufferAccess;
@@ -2499,7 +2510,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
if (deviceFault || queueCheckpoints || bufferMarkers) {
const auto faultInfo = deviceFault ? state->DeviceFunction<PFN_vkGetDeviceFaultInfoEXT>("vkGetDeviceFaultInfoEXT") : nullptr;
const auto checkpointData = queueCheckpoints ? state->DeviceFunction<PFN_vkGetQueueCheckpointDataNV>("vkGetQueueCheckpointDataNV") : nullptr;
Graphics::DeviceLostHook() = [device = state->device, queue = state->queue, present = state->presentQueue, settle = state->settleQueue, sparse = state->sparseQueue, faultInfo, checkpointData, vendorDump = vendorBinary, owner = state.get()] noexcept {
Graphics::DeviceLostHook() = [device = state->device, queue = state->queue, present = state->presentQueue, settle = state->settleQueue, sparse = state->sparseQueue, faultInfo, checkpointData, vendorDump = vendorBinary, owner = state.get(), reportResidency = checkpointsRequested] noexcept {
owner->hookActive.fetch_add(1, std::memory_order_acq_rel);
try {
if (!owner->hookRetired.load(std::memory_order_acquire)) {
@@ -2567,7 +2578,24 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
}
}
std::fprintf(stderr, "[device-fault] queue main\n");
for (const auto& line : DeviceFaultReport(device, faultInfo, queue, checkpointData, submitSerial, &AgcDriver::SubmissionSnapshots::DeviceSnapshots(), bracket, AgcDriver::FaultTokenRing::Instance())) std::fprintf(stderr, "%s\n", line.c_str());
if (reportResidency) {
const std::uint64_t shadowRefused = Graphics::StagingShadowsRefused();
if (shadowRefused != 0) std::fprintf(stderr, "[device-fault] staging shadow copies refused: %llu (process-wide total)\n", static_cast<unsigned long long>(shadowRefused));
for (const auto& line : DeviceFaultReport(device, faultInfo, queue, checkpointData, submitSerial, &AgcDriver::SubmissionSnapshots::DeviceSnapshots(), bracket, AgcDriver::FaultTokenRing::Instance(), [](std::uint64_t va) noexcept {
AgcDriver::DeviceFaultResidencyProbe probe{};
try {
if (const auto space = Graphics::GuestBufferMemory::TrySnapshotAddressSpace(); space.has_value() && space->second != nullptr) {
for (const auto& range : *space->second) {
if (range.begin <= va && va < range.end) { probe.boundNow = true; break; }
}
}
} catch (...) {
}
return probe;
})) std::fprintf(stderr, "%s\n", line.c_str());
} else {
for (const auto& line : DeviceFaultReport(device, faultInfo, queue, checkpointData, submitSerial, &AgcDriver::SubmissionSnapshots::DeviceSnapshots(), bracket, AgcDriver::FaultTokenRing::Instance())) std::fprintf(stderr, "%s\n", line.c_str());
}
const VkQueue extraQueues[] = {present, settle, sparse};
for (VkQueue extra : extraQueues) {
if (extra == VK_NULL_HANDLE || extra == queue) continue;
@@ -2692,6 +2720,11 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
}
state->scaler = std::make_unique<PresentationScaler>(graphicsContext(), VK_FORMAT_B8G8R8A8_UNORM, state->surfaceFormat);
state->presentation = std::make_unique<PresentationPass>(graphicsContext(), state->presentSlots.size());
const auto upscale = SelectUpscaleMode(std::getenv("ANYPS5_UPSCALE"), std::getenv("ANYPS5_FSR_SHARPNESS"));
if (upscale.fsr) {
state->upscaler = std::make_unique<PresentationUpscaler>(graphicsContext(), state->presentSlots.size(), upscale.sharpness);
std::fprintf(stderr, "[present] ANYPS5_UPSCALE=fsr: FSR 1 EASU and RCAS when the window is larger than the display buffer, the normal scaler otherwise; RCAS sharpness %.2f\n", static_cast<double>(upscale.sharpness));
}
}
if (state->float32FlushToZeroCandidate) {
const auto probeStart = std::chrono::steady_clock::now();
@@ -4077,7 +4110,7 @@ bool VulkanDevice::AcquireImage() {
std::uint32_t index = 0;
timing.Mark("fence_reset");
// An out-of-date swapchain (the window changed) drops this frame; the next Resize recreates it.
const auto acquired = state->DeviceFunction<PFN_vkAcquireNextImageKHR>("vkAcquireNextImageKHR")(state->device, state->swapchain, 0, VK_NULL_HANDLE, state->acquireFence, &index);
const auto acquired = state->DeviceFunction<PFN_vkAcquireNextImageKHR>("vkAcquireNextImageKHR")(state->device, state->swapchain, AgcDriver::SwapchainAcquireTimeoutNs, VK_NULL_HANDLE, state->acquireFence, &index);
if (acquired == VK_ERROR_OUT_OF_DATE_KHR) {
state->extent = {0, 0};
return false;
@@ -4134,6 +4167,7 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu
// wait for every slot first. The game path did so before taking the mutex
// (PresentWaitsForSlots); this is the fallback.
const bool shared = !clearOnly && !direct && !drawn;
const bool upscaled = state->upscaler != nullptr && !clearOnly && PresentationUpscaler::Upscales(width, height, state->extent);
if (shared && state->SharedSlotInFlight()) RetirePresents(0);
// The next slot is the oldest; a caller that did not retire it first (PresentPixels) waits here.
if (state->presentSlots[state->presentCursor].inFlight) RetirePresents(state->presentSlots.size() - 1);
@@ -4223,7 +4257,7 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu
bindPlane();
state->planePass->RecordOverlay(commands, planeSlot, image, format, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, extent, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
};
if (!drawn) {
if (!drawn && !upscaled) {
pipelineBarrier(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
Graphics::Recorder::CountBarriers(CommandClass::PresentBlit);
}
@@ -4268,7 +4302,21 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu
if (uniform != nullptr) scaler->RecordClear(commands, *uniform);
else scaler->RecordUpload(commands, display != nullptr ? state->colorTransfer->LinearBuffer() : state->uploadBuffer);
}
if (drawn) {
if (upscaled) {
const auto stageExtent = PresentationUpscaler::StageExtent(width, height, state->extent);
const auto stage = state->upscaler->Stage(slotIndex, state->surfaceFormat, stageExtent);
if (drawn) {
state->presentation->Bind(slotIndex, resident->Image(), width, height, display->pixelFormat, whiteNits, residentLayer);
state->presentation->RecordStage(commands, slotIndex, stage, state->surfaceFormat, state->surfaceColorSpace, stageExtent, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
} else {
const AspectFitRect whole{0, 0, stageExtent.width, stageExtent.height};
state->upscaler->RecordStageTransferDestination(commands, slotIndex);
if (direct) PresentationScaler::RecordStretchFrom(graphicsContext(), commands, resident->Image(), VK_IMAGE_LAYOUT_GENERAL, width, height, residentFilter, stage, whole, residentLayer);
else scaler->RecordStretch(commands, stage, whole);
state->upscaler->RecordStageWritten(commands, slotIndex, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
}
state->upscaler->RecordPresent(commands, slotIndex, width, height, barrier.image, state->extent, drawsOver ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
} else if (drawn) {
state->presentation->Bind(slotIndex, resident->Image(), width, height, display->pixelFormat, whiteNits, residentLayer);
state->presentation->RecordPresent(commands, slotIndex, barrier.image, state->surfaceFormat, state->surfaceColorSpace, state->extent, drawsOver ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
} else {
@@ -4314,7 +4362,7 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu
}
if (plane != nullptr) {
bindPlane();
state->planePass->RecordOverlay(commands, planeSlot, barrier.image, state->surfaceFormat, state->surfaceColorSpace, state->extent, drawn ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, overlay || keyboard || padStatusShown ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
state->planePass->RecordOverlay(commands, planeSlot, barrier.image, state->surfaceFormat, state->surfaceColorSpace, state->extent, drawn || upscaled ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, overlay || keyboard || padStatusShown ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
if (planeSource.resident != nullptr) {
planeBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
planeBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
@@ -4324,17 +4372,17 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu
}
if (keyboard) {
if (!state->keyboard) state->keyboard = std::make_unique<PerformanceOverlay>(graphicsContext(), state->presentSlots.size());
state->keyboard->RecordRects(commands, static_cast<std::size_t>(&slot - state->presentSlots.data()), barrier.image, state->surfaceFormat, state->surfaceColorSpace, state->extent, drawn || plane != nullptr ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, overlay ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, *systemLayout);
state->keyboard->RecordRects(commands, static_cast<std::size_t>(&slot - state->presentSlots.data()), barrier.image, state->surfaceFormat, state->surfaceColorSpace, state->extent, drawn || upscaled || plane != nullptr ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, overlay ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, *systemLayout);
}
if (padStatusShown) {
if (!state->padStatus) state->padStatus = std::make_unique<PerformanceOverlay>(graphicsContext(), state->presentSlots.size());
state->padStatus->RecordRects(commands, static_cast<std::size_t>(&slot - state->presentSlots.data()), barrier.image, state->surfaceFormat, state->surfaceColorSpace, state->extent, drawn || plane != nullptr ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, overlay ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, LayOutPadStatus(*padStatusLines, state->extent, PerformanceOverlay::Corner()));
state->padStatus->RecordRects(commands, static_cast<std::size_t>(&slot - state->presentSlots.data()), barrier.image, state->surfaceFormat, state->surfaceColorSpace, state->extent, drawn || upscaled || plane != nullptr ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, overlay ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, LayOutPadStatus(*padStatusLines, state->extent, PerformanceOverlay::Corner()));
}
if (overlay) {
if (!state->overlay) state->overlay = std::make_unique<PerformanceOverlay>(graphicsContext(), state->presentSlots.size());
state->overlay->NotePresent(std::chrono::steady_clock::now(), clearOnly ? VkExtent2D{} : VkExtent2D{width, height}, OverlayPresentInfo{std::exchange(state->presentedAddress, 0), state->presentMode, presentCounters.acquireDrops, ConfiguredFrameLimit() ? ConfiguredFrameLimit()->FramesPerSecond() : 0.0});
state->overlay->Record(commands, static_cast<std::size_t>(&slot - state->presentSlots.data()), barrier.image, state->surfaceFormat, state->surfaceColorSpace, state->extent, drawn || plane != nullptr || keyboard || padStatusShown ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
} else if (!drawn && plane == nullptr && !keyboard && !padStatusShown) {
state->overlay->Record(commands, static_cast<std::size_t>(&slot - state->presentSlots.data()), barrier.image, state->surfaceFormat, state->surfaceColorSpace, state->extent, drawn || upscaled || plane != nullptr || keyboard || padStatusShown ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
} else if (!drawn && !upscaled && plane == nullptr && !keyboard && !padStatusShown) {
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = 0;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
@@ -4379,6 +4427,7 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu
state->queueGuestFrame = state->presentingGuestFrame;
state->queueIndex = index;
++presentCounters.presents;
if (upscaled) upscaledPresents.fetch_add(1, std::memory_order_relaxed);
if (plane != nullptr) ++presentCounters.planes;
if (auto* frame = PerformanceContext::Current()) {
frame->NoteBlit(batchesAtBlit, lastSubmittedAt, submittedAt);
@@ -4409,6 +4458,10 @@ std::size_t VulkanDevice::FlipInFlight() {
return count;
}
std::uint64_t VulkanDevice::UpscaledPresents() {
return upscaledPresents.load(std::memory_order_relaxed);
}
std::uint64_t VulkanDevice::FillCompletionSyncCount() { return fillCompletionSyncs; }
VulkanDevice::PresentStatistics VulkanDevice::PresentCounts() {
@@ -4500,6 +4553,7 @@ bool VulkanDevice::PresentsOnOwnQueue() const {
ShaderRecompiler::SpirvTarget VulkanDevice::ComputeTarget(std::uint32_t waveSize) const {
auto target = Target();
target.float32FlushToZero = state->float32FlushToZero;
if (waveSize == 32u && state->computeWave32) target.subgroupSize = 32u;
return target;
}
@@ -4561,7 +4615,7 @@ bool VulkanDevice::SupportsImageFormat(VkFormat format, VkImageUsageFlags usage)
ShaderRecompiler::SpirvTarget VulkanDevice::Target() const {
require(state->shaderProfile != nullptr, "shader device profile is unavailable");
auto target = state->shaderProfile->Target();
target.float32FlushToZero = state->float32FlushToZero;
target.float32FlushToZero = state->float32FlushToZero && !state->float32FlushComputeOnly;
target.fusedExactArithmetic = state->fusedExactArithmetic;
target.hostInterpolationFirst = state->hostInterpolationFirst;
target.float32DenormPreserve = state->float32DenormPreserve;
@@ -4734,6 +4788,7 @@ Graphics::Context VulkanDevice::buildContext() const {
context.pipelineLinkTimeOptimization = state->pipelineLinkTimeOptimization;
context.drawInputsInPlace = state->drawInputsInPlace;
context.discreteGpu = state->properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU;
context.integratedGpu = state->properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
context.provokingVertexModePerPipeline = state->provokingVertexModePerPipeline;
context.drawIndirectCount = state->drawIndirectCount;
context.occlusionQueryPrecise = state->occlusionQueryPrecise;
@@ -5402,6 +5457,10 @@ void VulkanDevice::NoteDrawRecipeMiss(DrawRecipePrecheck miss) {
counters.precheckMisses[miss == DrawRecipePrecheck::NoRecipe ? MissNoRecipe : MissDevice].fetch_add(1, std::memory_order_relaxed);
}
std::uint64_t VulkanDevice::DrawRecipeHits() {
return Recipes().kinds[static_cast<std::size_t>(RecipeKind::Draw)].hits.load(std::memory_order_relaxed);
}
RecipeOutcome VulkanDevice::DrawFromRecipe(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const DrawTraceContext* trace) {
PerformanceTimer timing("Vulkan.DrawFromRecipe");
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
@@ -5871,7 +5930,38 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) {
entry->submitSerial = recorder.OpenSerial();
entry->programAddress = record.programAddress;
entry->variantId = record.shader != nullptr && record.shader->program != nullptr ? record.shader->program->variantId : 0;
std::snprintf(entry->desc, sizeof(entry->desc), "dispatch %ux%ux%u", record.x, record.y, record.z);
entry->stage = static_cast<std::uint32_t>(AgcDriver::FaultStage::compute);
entry->argBuffer = 0;
entry->argOffset = 0;
entry->argStride = 0;
entry->argCount = 0;
for (auto& word : entry->argWords) word = 0;
if (record.arguments != 0) {
entry->argBuffer = record.arguments;
entry->argOffset = 0;
std::array<std::uint32_t, 3> groups{};
entry->argStride = static_cast<std::uint32_t>(sizeof(groups));
try {
GuestMemory::ReadCommittedUnsynced(record.arguments, std::as_writable_bytes(std::span(groups)));
entry->argWords[0] = groups[0];
entry->argWords[1] = groups[1];
entry->argWords[2] = groups[2];
entry->argCount = static_cast<std::uint32_t>(groups.size());
} catch (...) {
entry->argCount = 0;
}
} else if (record.cpuArguments != 0) {
constexpr std::uint32_t groupDwords = 3;
entry->argBuffer = record.cpuArguments;
entry->argOffset = 0;
entry->argStride = static_cast<std::uint32_t>(sizeof(std::uint32_t) * groupDwords);
entry->argWords[0] = record.x;
entry->argWords[1] = record.y;
entry->argWords[2] = record.z;
entry->argCount = groupDwords;
}
if (record.arguments != 0) std::snprintf(entry->desc, sizeof(entry->desc), "dispatch indirect");
else std::snprintf(entry->desc, sizeof(entry->desc), "dispatch %ux%ux%u", record.x, record.y, record.z);
recorder.NoteFaultToken(faultToken);
std::atomic_ref<AgcDriver::FaultToken>(entry->token).store(faultToken, std::memory_order_release);
}
+4 -4
View File
@@ -32,14 +32,14 @@ int APS5_VABI sceAgcDriverDestroyQueue(void) {
return 0;
}
int APS5_VABI sceAgcDriverGetRegShadowInfo(void) {
int APS5_VABI sceAgcDriverGetRegShadowInfo(void* info) {
if (info == nullptr) return static_cast<int>(0x8A6D0003u);
NotImplemented_nid_no_patch(__func__);
return 0;
}
int APS5_VABI sceAgcDriverGetRegShadowInfoAgr(void) {
int APS5_VABI sceAgcDriverGetRegShadowInfoAgr(void* info) {
if (info == nullptr) return static_cast<int>(0x8A6D0003u);
NotImplemented_nid_no_patch(__func__);
return 0;
}
int APS5_VABI sceAgcDriverGetReservedDmemForAgc(void) {
@@ -61,7 +61,7 @@ struct SlabSlot {
class BufferPool {
public:
explicit BufferPool(const Context& context);
static VkDeviceSize DeviceBudget(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported = nullptr);
static VkDeviceSize DeviceBudget(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported = nullptr, bool integratedGpu = false);
static VkDeviceSize ReclaimTarget(VkDeviceSize bytes);
~BufferPool();
BufferPool(const BufferPool&) = delete;
@@ -180,6 +180,7 @@ struct Context {
VkDeviceSize hostImportAlignment = 0;
bool drawInputsInPlace = true;
bool discreteGpu = false;
bool integratedGpu = false;
bool dmaBufImport = false;
bool sparseBinding = false;
bool sparseResidencyBuffer = false;
@@ -89,6 +89,7 @@ bool DepthSurfaceHolds(const Context& context, const GuestTextureResource& resou
void NoteDepthMetadataFill(std::uint64_t address, std::size_t bytes, std::uint32_t pattern);
std::size_t DiscardFilledDepthPlanes(std::uint64_t address, std::size_t bytes, std::uint32_t pattern);
void NoteDepthRenderControl(const DepthRenderControl& draw);
bool DepthRenderControlDrains(const DepthRenderControl& draw);
VkImageAspectFlags HtileFillClears(std::uint32_t pattern, bool stencilInHtile);
std::uint64_t HtileMetadataBytes(VkExtent2D extent);
bool HtileFillCovers(std::uint64_t htile, VkExtent2D extent, std::uint64_t address, std::size_t bytes);
@@ -14,6 +14,14 @@
namespace AgcDriver::Graphics {
struct VkDrawCounts {
std::uint64_t direct = 0;
std::uint64_t indexed = 0;
std::uint64_t indirect = 0;
std::uint64_t mesh = 0;
};
VkDrawCounts TakeVkDrawCounts();
struct HostImport;
struct DrawTraceContext {
@@ -267,6 +267,7 @@ struct AddressSpaceStats {
std::uint64_t dissolvedOverlap = 0;
std::uint64_t dissolvedImports = 0;
std::uint64_t waiterDrops = 0;
std::uint64_t patchedEpoch = 0;
};
AddressSpaceStats AddressSpaceCounters();
@@ -280,6 +281,7 @@ struct MirrorStats {
std::uint64_t heapChecks = 0;
std::uint64_t sparseBinds = 0;
std::uint64_t evictions = 0;
std::uint64_t rangeMirrors = 0;
};
MirrorStats MirrorCounters();
std::uint64_t SnapshotMismatches();
@@ -27,6 +27,7 @@ struct GuestSamplerResource {
VkBorderColor borderColor;
VkSamplerReductionMode reductionMode = VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT;
bool forceDegamma = false;
bool disableDegamma = false;
bool compareEnable = false;
VkCompareOp compareOp = VK_COMPARE_OP_NEVER;
bool unnormalizedCoordinates = false;
@@ -21,6 +21,7 @@ public:
Sampler& operator=(const Sampler&) = delete;
bool ForcesDegamma() const;
bool DisablesDegamma() const;
VkSampler Handle() const;
bool RequiresFilterMinmax() const;
bool ReadsOpaqueBlackBorder() const;
@@ -34,6 +35,7 @@ private:
Context context;
bool forcesDegamma = false;
bool disablesDegamma = false;
VkSampler sampler = VK_NULL_HANDLE;
bool requiresFilterMinmax = false;
bool opaqueBlackBorder = false;
@@ -73,6 +75,7 @@ void RequireFilterMinmax(const Context& context, VkFormat format, std::uint64_t
bool ForcesDegammaOn(std::uint32_t guestFormat, std::uint64_t samplerMask, std::span<const std::shared_ptr<Sampler>> samplers);
void RequireBorderSwizzle(std::uint32_t bcSwizzle, std::uint64_t samplerMask, std::span<const std::shared_ptr<Sampler>> samplers);
void RequireNonSeamlessCube(bool cube, std::uint64_t samplerMask, std::span<const std::shared_ptr<Sampler>> samplers);
void RequireDisablesDegammaOn(std::uint32_t guestFormat, std::uint64_t samplerMask, std::span<const std::shared_ptr<Sampler>> samplers);
}
@@ -461,6 +461,7 @@ private:
bool sampled = false;
bool storage = false;
std::vector<std::size_t> elementTextures;
std::vector<std::uint32_t> representatives;
std::vector<std::pair<std::uint32_t, std::uint32_t>> samplerRejections;
};
std::vector<TableStage> tableStages;
@@ -3,9 +3,7 @@
#include <atomic>
#include <thread>
#if defined(__x86_64__) || defined(_M_X64)
#include <immintrin.h>
#endif
#include "prx/libc/include/PreciseWait.hpp"
namespace AgcDriver::Graphics {
@@ -21,9 +19,7 @@ public:
while (locked.load(std::memory_order_relaxed)) {
if (spins < 128) {
++spins;
#if defined(__x86_64__) || defined(_M_X64)
_mm_pause();
#endif
PreciseSpinPause();
} else {
std::this_thread::yield();
}
@@ -49,7 +49,7 @@ namespace AgcDriver::Graphics {
// leaving the other elements of both buffers alone.
void Dispatch(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, bool thick = false, const DetileWindow& window = {});
void DispatchImage(VkCommandBuffer commands, TextureTileMode tileMode, std::uint32_t elementBytes, VkBuffer tiled, std::uint64_t tiledOffset, VkImageView view, const TileMipLayout& layout, bool retile = false, std::uint32_t slice = 0, const DetileWindow& window = {});
void DispatchRepack(VkCommandBuffer commands, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, std::uint64_t bytes);
void DispatchRepack(VkCommandBuffer commands, VkBuffer source, std::uint64_t sourceOffset, VkBuffer destination, std::uint64_t destinationOffset, std::uint64_t bytes, bool depthToFloat = false);
static VkFormat ImageElementFormat(std::uint32_t elementBytes);
// Recycles the descriptor sets of the previous batch; call before recording a new command batch.
void BeginBatch();
@@ -0,0 +1,36 @@
#version 450
#extension GL_GOOGLE_include_directive : require
#define A_GPU 1
#define A_GLSL 1
#include "ffx_a.h"
layout(set = 0, binding = 0) uniform sampler2D source;
layout(push_constant) uniform Parameters {
vec2 sourceSize;
vec2 outputSize;
} parameters;
layout(location = 0) out vec4 color;
AF4 FsrEasuRF(AF2 p) {
return textureGather(source, p, 0);
}
AF4 FsrEasuGF(AF2 p) {
return textureGather(source, p, 1);
}
AF4 FsrEasuBF(AF2 p) {
return textureGather(source, p, 2);
}
#define FSR_EASU_F 1
#include "ffx_fsr1.h"
void main() {
AU4 con0, con1, con2, con3;
FsrEasuCon(con0, con1, con2, con3, parameters.sourceSize.x, parameters.sourceSize.y, parameters.sourceSize.x, parameters.sourceSize.y, parameters.outputSize.x, parameters.outputSize.y);
AF3 upscaled;
FsrEasuF(upscaled, AU2(gl_FragCoord.xy), con0, con1, con2, con3);
color = vec4(upscaled, 1.0);
}
@@ -0,0 +1,37 @@
#version 450
#extension GL_GOOGLE_include_directive : require
#define A_GPU 1
#define A_GLSL 1
#include "ffx_a.h"
layout(set = 0, binding = 0) uniform sampler2D source;
layout(push_constant) uniform Parameters {
ivec2 origin;
ivec2 size;
float sharpness;
} parameters;
layout(location = 0) out vec4 color;
AF4 FsrRcasLoadF(ASU2 p) {
return texelFetch(source, clamp(p, ASU2(0), parameters.size - 1), 0);
}
void FsrRcasInputF(inout AF1 r, inout AF1 g, inout AF1 b) {
}
#define FSR_RCAS_F 1
#include "ffx_fsr1.h"
void main() {
ivec2 pixel = ivec2(gl_FragCoord.xy) - parameters.origin;
if (any(lessThan(pixel, ivec2(0))) || any(greaterThanEqual(pixel, parameters.size))) {
color = vec4(0.0, 0.0, 0.0, 1.0);
return;
}
AU4 con;
FsrRcasCon(con, parameters.sharpness);
AF3 sharpened;
FsrRcasF(sharpened.r, sharpened.g, sharpened.b, AU2(pixel), con);
color = vec4(clamp(sharpened, 0.0, 1.0), 1.0);
}
@@ -10,11 +10,19 @@ layout(push_constant) uniform Push {
uint destinationBase;
uint words;
uint rowWords;
uint depthToFloat;
} push;
void main() {
const uint index = gl_GlobalInvocationID.y * push.rowWords + gl_GlobalInvocationID.x;
if (gl_GlobalInvocationID.x >= push.rowWords || index >= push.words) return;
const uint word = source[push.sourceBase / 4u + index];
destination[push.destinationBase / 4u + index] = ((word >> 21u) & 0x7ffu) | (((word >> 10u) & 0x7ffu) << 11u) | ((word & 0x3ffu) << 22u);
if (push.depthToFloat == 0u) {
destination[push.destinationBase / 4u + index] = ((word >> 21u) & 0x7ffu) | (((word >> 10u) & 0x7ffu) << 11u) | ((word & 0x3ffu) << 22u);
} else {
precise float scaled = float(word & 0xffffffu) * 5.9604644775390625e-8;
precise float excess = scaled * 5.9604644775390625e-8;
precise float depth = scaled + excess;
destination[push.destinationBase / 4u + index] = floatBitsToUint(depth);
}
}
@@ -357,7 +357,7 @@ bool BufferPool::DeviceTierEnabled() {
return enabled;
}
VkDeviceSize BufferPool::DeviceBudget(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported) {
VkDeviceSize BufferPool::DeviceBudget(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported, bool integratedGpu) {
static const char* value = std::getenv("APS5_STAGING_POOL_MIB");
if (value != nullptr) return static_cast<VkDeviceSize>(std::strtoull(value, nullptr, 10)) << 20u;
std::optional<std::uint32_t> largest;
@@ -366,18 +366,18 @@ VkDeviceSize BufferPool::DeviceBudget(const VkPhysicalDeviceMemoryProperties& me
}
VkDeviceSize size = largest ? memory.memoryHeaps[*largest].size : 0;
if (largest && reported != nullptr && reported->heapBudget[*largest] != 0) size = std::min(size, reported->heapBudget[*largest]);
if (largest && systemMemoryHeap(memory, *largest)) return std::max<VkDeviceSize>(VkDeviceSize{128} << 20u, size / 64u);
if (largest && (integratedGpu || systemMemoryHeap(memory, *largest))) return std::max<VkDeviceSize>(VkDeviceSize{128} << 20u, size / 64u);
return std::max<VkDeviceSize>(VkDeviceSize{512} << 20u, size / 8u);
}
VkDeviceSize BufferPool::deviceBudget(const Context& context) {
if (!DeviceTierEnabled()) return 0;
if (context.memoryProperties2 == nullptr || context.physical == VK_NULL_HANDLE) return DeviceBudget(context.memory);
if (context.memoryProperties2 == nullptr || context.physical == VK_NULL_HANDLE) return DeviceBudget(context.memory, nullptr, context.integratedGpu);
VkPhysicalDeviceMemoryBudgetPropertiesEXT reported{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT};
VkPhysicalDeviceMemoryProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2};
properties.pNext = &reported;
context.memoryProperties2(context.physical, &properties);
return DeviceBudget(context.memory, &reported);
return DeviceBudget(context.memory, &reported, context.integratedGpu);
}
VkDeviceSize BufferPool::destroy(const BufferAllocation& allocation, bool retained) noexcept {
@@ -1,6 +1,7 @@
#include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libc/include/HostThreadSlot.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "prx/libc/include/PrimedSharedMutex.hpp"
#include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp"
@@ -225,6 +226,7 @@ struct DepthSamplingState {
std::optional<float> initialDepth;
std::optional<std::uint8_t> initialStencil;
std::string refusal;
std::optional<float> aliasDepth;
std::optional<std::uint8_t> aliasStencil;
std::optional<MultisampleColorAlias> unprovenStencil;
std::optional<MultisampleColorAlias> depthAlias;
@@ -259,6 +261,15 @@ std::optional<std::uint8_t> aliasedStencil(const MultisampleColorAlias& alias, c
return alias.byte;
}
std::optional<float> aliasedDepth(const MultisampleColorAlias& alias, const GuestMemory::UnchangedQuery& plane, std::uint32_t samples) {
const bool r32 = alias.format == VK_FORMAT_R32_SFLOAT;
const bool known = alias.newest == MultisampleColorContent::Fill || alias.newest == MultisampleColorContent::FastClear || alias.newest == MultisampleColorContent::Clear;
if (!r32 || !known || !alias.value || alias.samples != samples || alias.address != plane.address || alias.bytes != plane.bytes) return std::nullopt;
const auto value = alias.value->float32[0];
if (!(value >= 0.0f && value <= 1.0f)) return std::nullopt;
return value;
}
void reportAlias(const MultisampleColorAlias& alias, const GuestMemory::UnchangedQuery& range, const char* plane) {
static std::atomic<int> reports{0};
if (reports.fetch_add(1) >= 8) return;
@@ -331,6 +342,12 @@ DepthSamplingState prepareUniformPlaneSampling(const Context& context, const Dep
for (std::size_t index = 0u; index < state.initial.size(); ++index) {
const auto alias = MultisampleColorTargetOver(state.initial[index].address, state.initial[index].bytes);
if (!alias) continue;
if (index == 0u) {
if (const auto depthValue = aliasedDepth(*alias, state.initial[index], target.samples)) {
state.aliasDepth = *depthValue;
continue;
}
}
reportAlias(*alias, state.initial[index], index == 1u ? "stencil plane" : "depth");
return refuse(index == 1u ? stencilAliasRefusal : depthAliasRefusal);
}
@@ -342,14 +359,18 @@ DepthSamplingState prepareUniformPlaneSampling(const Context& context, const Dep
range.generation = GuestMemory::CollectWritesUncached(range.address, range.bytes);
if (range.generation == 0u) return refuse("native multisample depth import requires tracked generations");
}
const auto depthWord = uniformPlaneValue<std::uint32_t>(depth.address, depth.bytes);
const auto depthValue = depthWord ? std::bit_cast<float>(*depthWord) : 0.0f;
if (!depthWord || !(depthValue >= 0.0f && depthValue <= 1.0f)) return refuse("native multisample depth plane without HTILE does not hold one depth value in [0, 1]");
if (state.aliasDepth) {
state.initialDepth = *state.aliasDepth;
} else {
const auto depthWord = uniformPlaneValue<std::uint32_t>(depth.address, depth.bytes);
const auto depthValue = depthWord ? std::bit_cast<float>(*depthWord) : 0.0f;
if (!depthWord || !(depthValue >= 0.0f && depthValue <= 1.0f)) return refuse("native multisample depth plane without HTILE does not hold one depth value in [0, 1]");
state.initialDepth = depthValue;
}
const auto stencilByte = uniformPlaneValue<std::uint8_t>(stencil.address, stencil.bytes);
if (!stencilByte) return refuse("native multisample stencil plane without HTILE does not hold one stencil value");
for (const auto& range : state.initial) GuestMemory::CollectWritesUncached(range.address, range.bytes);
if (!GuestMemory::UnchangedSinceAll(state.initial)) return refuse("guest writes raced native multisample depth import");
state.initialDepth = depthValue;
state.initialStencil = *stencilByte;
return state;
}
@@ -390,15 +411,17 @@ DepthSamplingState prepareDepthSampling(const Context& context, const DepthTarge
const auto& range = state.initial[index];
const auto alias = MultisampleColorTargetOver(range.address, range.bytes);
if (!alias) continue;
std::optional<float> depthValue;
std::optional<std::uint8_t> stencilValue;
if (index == 0u) {
depthValue = aliasedDepth(*alias, range, target.samples);
if (const auto sole = soleDepthAlias(range, target.samples)) {
reportAlias(*sole, range, "depth");
state.depthAlias = sole;
continue;
if (!depthValue) continue;
}
}
const auto value = index == 2u && stencilPlane ? aliasedStencil(*alias, range, target.samples) : std::nullopt;
if (!value) {
} else if (index == 2u && stencilPlane) stencilValue = aliasedStencil(*alias, range, target.samples);
if (!depthValue && !stencilValue) {
reportAlias(*alias, range, index == 2u ? "stencil plane" : index == 1u ? "HTILE" : "depth");
if (index == 2u && stencilPlane) {
state.unprovenStencil = alias;
@@ -406,7 +429,8 @@ DepthSamplingState prepareDepthSampling(const Context& context, const DepthTarge
}
return refuse(index == 2u ? stencilAliasRefusal : depthAliasRefusal);
}
state.aliasStencil = value;
if (depthValue) state.aliasDepth = *depthValue;
else state.aliasStencil = *stencilValue;
}
const auto& htile = state.initial[1];
for (auto& range : state.initial) {
@@ -420,8 +444,10 @@ DepthSamplingState prepareDepthSampling(const Context& context, const DepthTarge
std::vector<std::uint32_t> metadata(htile.bytes / sizeof(std::uint32_t));
GuestMemory::Read(target.htileAddress, std::as_writable_bytes(std::span(metadata)), 256u);
if (!target.htilePipeAligned && std::adjacent_find(metadata.begin(), metadata.end(), [](std::uint32_t first, std::uint32_t second) { return first != second; }) != metadata.end()) return refuse("native multisample depth HTILE that is not pipe-aligned holds more than one word");
if (state.aliasDepth && state.depthAlias && !std::all_of(metadata.begin(), metadata.end(), [&](std::uint32_t word) { return htileProvesClear(word, target.htileDepthOnly, *state.aliasDepth); })) state.aliasDepth.reset();
const float depthClear = state.aliasDepth.value_or(target.clearDepth);
for (const auto word : metadata) {
if (!htileProvesClear(word, target.htileDepthOnly, target.clearDepth)) return refuse("native multisample depth initial HTILE does not prove its clear value");
if (!htileProvesClear(word, target.htileDepthOnly, depthClear)) return refuse("native multisample depth initial HTILE does not prove its clear value");
if (stencil && !stencilPlane && !htileProvesStencilClear(word)) return refuse("native multisample stencil initial HTILE does not prove its clear value");
}
if (stencilPlane && !state.aliasStencil && !state.unprovenStencil) {
@@ -431,6 +457,7 @@ DepthSamplingState prepareDepthSampling(const Context& context, const DepthTarge
}
for (const auto& range : state.initial) GuestMemory::CollectWritesUncached(range.address, range.bytes);
if (!GuestMemory::UnchangedSinceAll(state.initial)) return refuse("guest writes raced native multisample depth import");
if (state.aliasDepth) state.initialDepth = *state.aliasDepth;
return state;
}
@@ -578,7 +605,7 @@ public:
Require(context.imageFormatProperties != nullptr, "native multisample depth requires image format queries");
VkImageFormatProperties shadowProperties{};
VkImageFormatProperties directProperties{};
const auto sampledUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
const auto sampledUsage = sampleShadowUsage();
const auto shadowResult = context.imageFormatProperties(context.physical, hostFormat, info.imageType, info.tiling, sampledUsage, 0, &shadowProperties);
if (shadowResult != VK_ERROR_FORMAT_NOT_SUPPORTED) Check(shadowResult, "vkGetPhysicalDeviceImageFormatProperties sampled depth shadow");
const auto directResult = context.imageFormatProperties(context.physical, hostFormat, info.imageType, info.tiling, info.usage | VK_IMAGE_USAGE_SAMPLED_BIT, info.flags, &directProperties);
@@ -660,7 +687,7 @@ public:
const auto newestStencilNote = recorder != nullptr && sampling.initial.size() > 2u ? recorder->NewestWriteNote(sampling.initial[2].address, sampling.initial[2].bytes) : 0u;
const bool queuedStencilFill = stencilClearValue.has_value() && stencilFillNote != 0u && newestStencilNote == stencilFillNote;
const bool separatePlane = target.stencilAddress != 0u && !target.htileStencil && target.htileDepthOnly && sampling.initial.size() > 2u;
bool planeAliased = false;
bool stencilPlaneAliased = false;
for (std::size_t index = 0u; index < sampling.initial.size(); ++index) {
const auto& range = sampling.initial[index];
Require(GuestMemory::Accessible(reinterpret_cast<const void*>(range.address), range.bytes) && GuestMemory::Watched(range.address, range.bytes), "native multisample depth requires watched accessible guest memory");
@@ -669,20 +696,26 @@ public:
const auto alias = MultisampleColorTargetOver(range.address, range.bytes);
if (!alias || (index == 2u && sampling.unprovenStencil && stencilClearGeneration == 0u)) continue;
if (index == 0u && sampling.depthAlias && sameDepthAlias(*sampling.depthAlias, range)) continue;
const auto value = index == 2u && separatePlane ? aliasedStencil(*alias, range, target.samples) : std::nullopt;
const bool kept = value.has_value() && (stencilClearGeneration != 0u ? *value == *stencilClearValue : value == sampling.aliasStencil);
const bool stencilRange = index == 2u || (index == 1u && uniformPlaneTarget(target));
const bool uniform = uniformPlaneTarget(target);
std::optional<float> depthValue;
std::optional<std::uint8_t> stencilValue;
if (index == 0u) depthValue = aliasedDepth(*alias, range, target.samples);
else if (index == 2u && separatePlane) stencilValue = aliasedStencil(*alias, range, target.samples);
bool kept = false;
if (depthValue) kept = std::bit_cast<std::uint32_t>(*depthValue) == std::bit_cast<std::uint32_t>(sampling.initialDepth.value_or(target.clearDepth));
else if (stencilValue) kept = stencilClearGeneration != 0u ? *stencilValue == *stencilClearValue : *stencilValue == sampling.aliasStencil;
const bool stencilRange = index == 2u || (index == 1u && uniform);
if (!kept) reportAlias(*alias, range, stencilRange ? "stencil plane" : index == 1u ? "HTILE" : "depth");
Require(kept, stencilRange ? stencilAliasRefusal : depthAliasRefusal);
planeAliased = true;
if (stencilValue) stencilPlaneAliased = true;
}
if (stencilClearGeneration != 0u) {
auto& plane = sampling.initial[2];
const bool gpuFill = stencilFillNote != 0u && (queuedStencilFill || newestStencilNote == 0u);
Require(GuestMemory::UnchangedSinceCollected(plane.address, plane.bytes, stencilClearGeneration), "CPU writes raced native multisample stencil plane fill");
if (planeAliased) sampling.aliasStencil = *stencilClearValue;
if (stencilPlaneAliased) sampling.aliasStencil = *stencilClearValue;
else Require(gpuFill || stencilStored || GuestMemory::StoredAllSince_nid_no_patch(plane.address, plane.bytes, stencilClearGeneration), "native multisample stencil plane fill has no complete tracked store");
if (!queuedStencilFill && !planeAliased) {
if (!queuedStencilFill && !stencilPlaneAliased) {
const auto* bytes = reinterpret_cast<const std::uint8_t*>(plane.address);
Require(std::all_of(bytes, bytes + plane.bytes, [&](std::uint8_t value) { return value == *stencilClearValue; }), "native multisample stencil plane does not hold its fill value");
}
@@ -1353,25 +1386,29 @@ public:
}
std::vector<bool> WrittenUnits(const GuestTextureResource& resource, std::uint64_t& generation) {
const auto bytes = static_cast<std::size_t>(DescribeSurface(resource).guestBytes);
const auto bytes = static_cast<std::size_t>(MirrorBytes());
SizeUnits(bytes);
const auto collected = GuestMemory::CollectWrites(resource.baseAddress, bytes);
generation = GuestMemory::TrackerGeneration();
std::vector<bool> changed(unitGeneration.size(), false);
std::vector<bool> changed;
const auto mark = [&](std::size_t unit) {
if (changed.empty()) changed.assign(unitGeneration.size(), false);
changed[unit] = true;
};
if (collected == 0u) {
for (std::size_t unit = 0; unit < unitGeneration.size(); ++unit) {
const auto offset = unit * unitBytes;
const auto address = resource.baseAddress + offset;
const auto length = static_cast<std::size_t>(std::min<std::uint64_t>(unitBytes, bytes - offset));
if (GuestMemory::CollectWritesUncached(address, length) != 0u) {
changed[unit] = unitGeneration[unit] != 0u && GuestMemory::WrittenSince(address, length, unitGeneration[unit]);
if (unitGeneration[unit] != 0u && GuestMemory::WrittenSince(address, length, unitGeneration[unit])) mark(unit);
continue;
}
constexpr std::uint64_t pageBytes = 4096u;
for (std::size_t page = 0; page < length;) {
const auto pageAddress = address + page;
const auto pageLength = static_cast<std::size_t>(std::min<std::uint64_t>(length - page, pageBytes - pageAddress % pageBytes));
if (GuestMemory::CollectWritesUncached(pageAddress, pageLength) != 0u && unitGeneration[unit] != 0u && GuestMemory::WrittenSince(pageAddress, pageLength, unitGeneration[unit])) changed[unit] = true;
if (GuestMemory::CollectWritesUncached(pageAddress, pageLength) != 0u && unitGeneration[unit] != 0u && GuestMemory::WrittenSince(pageAddress, pageLength, unitGeneration[unit])) mark(unit);
page += pageLength;
}
}
@@ -1379,14 +1416,16 @@ public:
return changed;
}
if (unitGeneration.size() == 1u) {
changed[0] = GuestMemory::WrittenSince(resource.baseAddress, bytes, unitGeneration[0]);
if (GuestMemory::WrittenSince(resource.baseAddress, bytes, unitGeneration[0])) mark(0);
return changed;
}
const auto oldest = *std::min_element(unitGeneration.begin(), unitGeneration.end());
if (oldest != 0u && !GuestMemory::WrittenSince(resource.baseAddress, bytes, oldest)) return changed;
std::vector<std::uint8_t> stamped(unitGeneration.size(), GuestMemory::BlockUnchanged);
if (!GuestMemory::ChangedBlocks(resource.baseAddress, bytes, unitGeneration, stamped)) return changed;
for (std::size_t unit = 0; unit < changed.size(); ++unit) changed[unit] = unitGeneration[unit] != 0u && stamped[unit] == GuestMemory::BlockWritten;
for (std::size_t unit = 0; unit < stamped.size(); ++unit) {
if (unitGeneration[unit] != 0u && stamped[unit] == GuestMemory::BlockWritten) mark(unit);
}
return changed;
}
@@ -1432,7 +1471,7 @@ public:
}
void SyncStencilFromMemory(const GuestTextureResource& resource) {
const auto bytes = static_cast<std::size_t>(DescribeSurface(resource).guestBytes);
const auto bytes = static_cast<std::size_t>(StencilMirrorBytes());
GuestMemory::CollectWrites(resource.baseAddress, bytes);
const auto generation = GuestMemory::TrackerGeneration();
const bool changed = stencilGeneration != 0u && GuestMemory::WrittenSince(resource.baseAddress, bytes, stencilGeneration);
@@ -1476,6 +1515,11 @@ public:
std::uint64_t unitBytes = 0;
bool syncing = false;
std::uint64_t scannedEpoch = 0;
mutable std::uint64_t mirrorBytes = 0;
mutable std::uint64_t stencilMirrorBytes = 0;
std::uint64_t MirrorBytes() const;
std::uint64_t StencilMirrorBytes() const;
const Context context;
const DepthTarget target;
@@ -1598,6 +1642,10 @@ private:
StencilCopy stencilCopy;
VkImageView transferView = VK_NULL_HANDLE;
VkImageUsageFlags sampleShadowUsage() const {
return VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | (HasStencil(hostFormat) ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : 0u);
}
void createSampleShadow() {
VkImage image = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
@@ -1610,7 +1658,7 @@ private:
info.arrayLayers = 1;
info.samples = static_cast<VkSampleCountFlagBits>(target.samples);
info.tiling = VK_IMAGE_TILING_OPTIMAL;
info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
info.usage = sampleShadowUsage();
info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
Check(context.Function<PFN_vkCreateImage>("vkCreateImage")(context.device, &info, nullptr, &image), "vkCreateImage sampled depth shadow");
@@ -1932,7 +1980,7 @@ public:
const bool guestFill = std::any_of(slices.begin(), slices.end(), [](const auto& slice) { return slice.image == VK_NULL_HANDLE; });
if (guestFill && (geometry.layers != requested || geometry.sliceLinearBytes < sliceBytes() || geometry.mips.empty())) {
char text[320];
std::snprintf(text, sizeof(text), "AGC graphics: depth plane copy geometry does not match its layers (copy %ux%u, %u layers, %llu bytes a slice; texture %ux%u guest format %u, dimension %d, tile mode %u, %u layers, %llu bytes a slice, %zu mips)", extent.width, extent.height, layers, static_cast<unsigned long long>(sliceBytes()), resource.width, resource.height, resource.format, static_cast<int>(resource.dimension), resource.tileMode, geometry.layers, static_cast<unsigned long long>(geometry.sliceLinearBytes), geometry.mips.size());
std::snprintf(text, sizeof(text), "AGC graphics: depth plane copy geometry does not match its layers (copy %ux%u, %u layers, %llu bytes a slice; texture %ux%u guest format %u, dimension %d, tile mode %d, %u layers, %llu bytes a slice, %zu mips)", extent.width, extent.height, layers, static_cast<unsigned long long>(sliceBytes()), resource.width, resource.height, resource.format, static_cast<int>(resource.dimension), static_cast<int>(resource.tileMode), geometry.layers, static_cast<unsigned long long>(geometry.sliceLinearBytes), geometry.mips.size());
throw std::runtime_error(text);
}
const auto stagingBytes = std::max<std::size_t>(static_cast<std::size_t>(geometry.sliceLinearBytes), static_cast<std::size_t>(sliceBytes())) * requested;
@@ -2837,7 +2885,7 @@ GuestTextureResource mirrorResource(const DepthTarget& target) {
}
std::pair<std::uint64_t, std::uint64_t> stalePlaneRange(const DepthSurface& surface) {
return {surface.target.address, surface.target.address + DescribeSurface(mirrorResource(surface.target)).guestBytes};
return {surface.target.address, surface.target.address + surface.MirrorBytes()};
}
GuestTextureResource stencilResource(const DepthTarget& target) {
@@ -2847,8 +2895,18 @@ GuestTextureResource stencilResource(const DepthTarget& target) {
return resource;
}
std::uint64_t DepthSurface::MirrorBytes() const {
if (mirrorBytes == 0) mirrorBytes = DescribeSurface(mirrorResource(target)).guestBytes;
return mirrorBytes;
}
std::uint64_t DepthSurface::StencilMirrorBytes() const {
if (stencilMirrorBytes == 0) stencilMirrorBytes = DescribeSurface(stencilResource(target)).guestBytes;
return stencilMirrorBytes;
}
std::pair<std::uint64_t, std::uint64_t> staleStencilRange(const DepthSurface& surface) {
return {surface.target.stencilAddress, surface.target.stencilAddress + DescribeSurface(stencilResource(surface.target)).guestBytes};
return {surface.target.stencilAddress, surface.target.stencilAddress + surface.StencilMirrorBytes()};
}
void forgetStaleStencil(const DepthSurface& surface) {
@@ -2905,7 +2963,7 @@ void retireStoringStale(DepthSurface& surface) {
return;
}
const auto resource = mirrorResource(surface.target);
const auto planeBytes = DescribeSurface(resource).guestBytes;
const auto planeBytes = surface.MirrorBytes();
std::uint64_t generation = 0;
const auto written = surface.WrittenUnits(resource, generation);
const auto removed = unmappedUnits(surface.target.address, planeBytes, surface.unitBytes, surface.staleUnits.size(), surface.depthMark);
@@ -2960,8 +3018,9 @@ void RequireNoResidentDepthRead_nid_no_patch(std::uint64_t address, std::size_t
const bool accepted = std::ranges::all_of(depthGuards(), [&](const auto& range) {
if (!overlaps(range)) return true;
return std::ranges::any_of(surfaces(), [&](const auto& surface) {
if (surface->active != range.active || !surface->active->load(std::memory_order_acquire) || !surface->samplingActive || !surface->sampling.refusal.empty() || !surface->clearPending) return false;
const auto& metadata = surface->sampling.initial[1];
return surface->active == range.active && surface->active->load(std::memory_order_acquire) && surface->samplingActive && surface->sampling.refusal.empty() && surface->clearPending && metadata.address == range.address && metadata.bytes == range.bytes && metadata.address == htileClear->first && metadata.bytes <= htileClear->second;
return metadata.address == range.address && metadata.bytes == range.bytes && metadata.address == htileClear->first && metadata.bytes <= htileClear->second;
});
});
if (accepted) return;
@@ -3161,7 +3220,7 @@ VkImageView DepthSurfaceViewWithStencilWriteIntent(const Context& context, const
if (cleared || htileCleared != 0u) surface->expanded = false;
if (created && !inherits && target.htileAddress == 0) surface->TakeStorage();
if (cleared && (!created || inherits)) {
if (target.samples != 1u) surface->sampling.Refuse("native multisample depth fast-clear transition is not implemented");
if (target.samples != 1u && (!created || !surface->samplingActive)) surface->sampling.Refuse("native multisample depth fast-clear transition is not implemented");
if (!created) surface->NoteHtileClear(VK_IMAGE_ASPECT_DEPTH_BIT);
}
if (!created) surface->NoteHtileClear(htileCleared);
@@ -3186,7 +3245,7 @@ VkImageView DepthSurfaceViewWithStencilWriteIntent(const Context& context, const
}
if ((depthWritten || cleared) && mirrorable(target)) {
const auto plane = target.address;
const auto planeBytes = DescribeSurface(mirrorResource(target)).guestBytes;
const auto planeBytes = surface->MirrorBytes();
surface->NoteDepthWork();
surface->MarkAllStale(planeBytes);
noteStalePlane(plane, plane + planeBytes);
@@ -3228,7 +3287,8 @@ bool DepthPlanesStale() {
}
std::vector<std::pair<std::uint64_t, std::uint64_t>> FlushDepthPlanes(std::uint64_t address, std::size_t bytes, DepthPlaneScope scope) {
static thread_local bool flushing = false;
struct FlushingSlot {};
const bool flushing = HostThreadSlot<bool, FlushingSlot>::Get();
const auto end = bytes > std::numeric_limits<std::uint64_t>::max() - address ? std::numeric_limits<std::uint64_t>::max() : address + bytes;
if (flushing || !overlapsStalePlane(address, end)) return {};
if (scope == DepthPlaneScope::Overlapped) {
@@ -3239,13 +3299,13 @@ std::vector<std::pair<std::uint64_t, std::uint64_t>> FlushDepthPlanes(std::uint6
const auto [stencilBegin, stencilEnd] = staleStencilRange(*surface);
if (stencilBegin < end && address < stencilEnd) return true;
}
return surface->AnyStale() && ((surface->pendingClear & VK_IMAGE_ASPECT_DEPTH_BIT) != 0 || anyUnit(surface->StaleUnitsIn(DescribeSurface(mirrorResource(surface->target)).guestBytes, address, end)));
return surface->AnyStale() && ((surface->pendingClear & VK_IMAGE_ASPECT_DEPTH_BIT) != 0 || anyUnit(surface->StaleUnitsIn(surface->MirrorBytes(), address, end)));
};
if (std::none_of(surfaces().begin(), surfaces().end(), staleInRange)) return {};
}
flushing = true;
HostThreadSlot<bool, FlushingSlot>::Set(true);
struct Reset {
~Reset() { flushing = false; }
~Reset() { HostThreadSlot<bool, FlushingSlot>::Set(false); }
} reset;
struct Stored {
DepthSurface* surface;
@@ -3290,7 +3350,7 @@ std::vector<std::pair<std::uint64_t, std::uint64_t>> FlushDepthPlanes(std::uint6
if (!surface->AnyStale()) continue;
const auto resource = mirrorResource(surface->target);
const auto plane = surface->target.address;
const auto planeBytes = DescribeSurface(resource).guestBytes;
const auto planeBytes = surface->MirrorBytes();
const bool overlapped = !surface->syncing && plane < end && address < plane + planeBytes;
if (overlapped && (surface->pendingClear & VK_IMAGE_ASPECT_DEPTH_BIT) != 0) surface->MarkAllStale(planeBytes);
if (overlapped && (scope == DepthPlaneScope::Whole || anyUnit(surface->StaleUnitsIn(planeBytes, address, end)))) {
@@ -3894,6 +3954,13 @@ void NoteDepthRenderControl(const DepthRenderControl& draw) {
}
}
bool DepthRenderControlDrains(const DepthRenderControl& draw) {
if (draw.samples == 1u) return false;
if ((draw.control & 0x60u) != 0u) return true;
std::lock_guard lock(surfacesMutex());
return std::any_of(surfaces().begin(), surfaces().end(), [&](const auto& surface) { return surface->active->load(std::memory_order_acquire) && surface->target.samples == draw.samples && surface->target.address == draw.address; });
}
bool DepthSurfaceAt(const Context& context, std::span<const std::uint32_t> words, const GuestTextureResource& resource) {
std::lock_guard lock(surfacesMutex());
const auto* found = planeSurface(context.device, resource.baseAddress);
@@ -53,13 +53,19 @@ void WriteCheckpointMarker(const Context& context, VkCommandBuffer commands, std
void WriteNvCheckpointToken(const Context& context, VkCommandBuffer commands, std::uint64_t token, std::uint32_t queue);
namespace {
enum class VkDrawKind : std::size_t { Direct, Indexed, Indirect, Mesh, Count };
std::array<std::atomic<std::uint64_t>, static_cast<std::size_t>(VkDrawKind::Count)> vkDrawCounts{};
void CountVkDraw(VkDrawKind kind) {
vkDrawCounts[static_cast<std::size_t>(kind)].fetch_add(1, std::memory_order_relaxed);
}
bool DrawFaultTokens() {
static const bool enabled = std::getenv("APS5_GPU_CHECKPOINTS") != nullptr;
return enabled;
}
void noteDrawFaultToken(const Context& context, Recorder& recorder, VkCommandBuffer commands, std::span<const CompiledShader> shaders, const Pm4::DrawParameters& draw, bool indirect) {
void noteDrawFaultToken(const Context& context, Recorder& recorder, VkCommandBuffer commands, std::span<const CompiledShader> shaders, const Pm4::DrawParameters& draw, std::uint32_t stage, const Pm4::DrawParameters::IndirectDraw* args) {
try {
if (!DrawFaultTokens()) return;
const auto queue = GuestMemory::GpuLockThreadTag();
@@ -74,7 +80,29 @@ void noteDrawFaultToken(const Context& context, Recorder& recorder, VkCommandBuf
if (shader.program != nullptr && (variant == 0 || shader.stage == ShaderRecompiler::ShaderStage::Fragment)) variant = shader.program->variantId;
}
entry->variantId = variant;
std::snprintf(entry->desc, sizeof(entry->desc), "draw%s%s c=%u i=%u", draw.indexed ? " indexed" : "", indirect ? " indirect" : "", draw.indexCount, draw.instanceCount);
entry->stage = stage;
entry->argBuffer = 0;
entry->argOffset = 0;
entry->argStride = 0;
entry->argCount = 0;
for (auto& word : entry->argWords) word = 0;
if (args != nullptr) {
entry->argBuffer = args->arguments;
entry->argOffset = 0;
entry->argStride = args->stride;
try {
constexpr std::uint32_t argWordLimit = 4;
const auto first = Pm4::ReadDrawArgumentsUnsynced(*args, 0);
entry->argWords[0] = first.count;
entry->argWords[1] = first.instances;
entry->argWords[2] = first.firstVertexOrIndex;
entry->argWords[3] = draw.indexed ? first.vertexOffset : first.firstInstance;
entry->argCount = argWordLimit;
} catch (...) {
entry->argCount = 0;
}
}
std::snprintf(entry->desc, sizeof(entry->desc), "draw%s%s c=%u i=%u", draw.indexed ? " indexed" : "", args != nullptr ? " indirect" : "", draw.indexCount, draw.instanceCount);
recorder.NoteFaultToken(faultToken);
std::atomic_ref<AgcDriver::FaultToken>(entry->token).store(faultToken, std::memory_order_release);
}
@@ -1381,6 +1409,12 @@ struct DrawTimer {
us[which] += std::chrono::duration<double, std::micro>(now - phaseStart).count();
phaseStart = now;
}
void charge(DrawPhase which, std::chrono::steady_clock::time_point start) {
if (!profile) return;
const auto now = std::chrono::steady_clock::now();
us[which] += std::chrono::duration<double, std::micro>(now - start).count();
phaseStart += now - start;
}
};
// One line per draw with the phases that took time (APS5_TRACE_DRAWS), and the 10 s totals.
@@ -1425,13 +1459,13 @@ DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uin
DrawInputCopy CopyZeroPaddedDrawInput(const Context& context, std::uint64_t address, std::size_t bytes, std::size_t validBytes, std::size_t stride) {
Require(validBytes <= bytes, "the valid bytes of a vertex fetch exceed the fetch");
GuestMemory::FlushGpuWrites(address, bytes);
auto readable = validBytes;
if (stride != 0 && !GuestMemory::Accessible(reinterpret_cast<const void*>(address), validBytes)) {
const auto ranges = GuestMemory::CommittedRanges(address, validBytes);
const std::size_t prefix = !ranges.empty() && ranges.front().first == address ? static_cast<std::size_t>(ranges.front().second - address) : 0;
if (validBytes - prefix < stride) readable = prefix;
}
if (readable != 0) GuestMemory::FlushGpuWrites(address, readable);
DrawInputCopy copy;
auto* recorder = context.recorder;
const bool keep = recorder != nullptr && readable != 0 && readable <= std::numeric_limits<std::uint32_t>::max();
@@ -1546,15 +1580,28 @@ std::shared_ptr<Buffer> zeroVertexBuffer(const Context& context, std::size_t byt
// Draw's validation, index and vertex phases. With `recipe` the fragment outputs, the pipeline
// stages and the vertex input layout are the recipe's (derived from the same compiled stages)
// instead of computed.
DrawInputs prepareDrawInputs(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, DrawOutcome& outcome, DrawTimer& timer, PerformanceTimer& timing, const DrawRecipe* recipe) {
DrawInputs inputs;
struct DrawPlan {
bool nothing = false;
std::uint64_t indexBytes = 0;
std::uint32_t fragmentOutputs = 0;
VkPipelineStageFlags shaderStages = 0;
std::uint32_t meshGroups = 0;
std::uint32_t meshLayers = 1;
std::uint32_t meshLayerStride = 0;
VertexInputLayout vertexInput;
std::shared_ptr<const VertexInputLayout> retainedVertexInput;
bool candidate = false;
bool keyed = false;
ResourceCache::Key contentKey;
const VertexInputLayout& VertexLayout() const { return retainedVertexInput != nullptr ? *retainedVertexInput : vertexInput; }
};
DrawPlan planDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, const DrawRecipe* recipe, DrawOutcome& outcome, DrawTimer& timer) {
DrawPlan plan;
APS5_LOG_OUT_DEBUG("Draw indices=%u instances=%u indexSize=%u flags=%u indexAddress=0x%llx", draw.indexCount, draw.instanceCount, draw.indexSize, draw.flags, static_cast<unsigned long long>(draw.indexAddress));
APS5_LOG_OUT_DEBUG("State colorTarget=%u render=%ux%u colorAddress=0x%llx colorBytes=%llu colorExtent=%ux%u", state.hasColorTarget ? 1u : 0u, state.renderExtent.width, state.renderExtent.height, static_cast<unsigned long long>(state.color.address), static_cast<unsigned long long>(state.color.bytes), state.color.extent.width, state.color.extent.height);
APS5_LOG_OUT_DEBUG("Viewport x=%f y=%f w=%f h=%f minDepth=%f maxDepth=%f", state.viewport.x, state.viewport.y, state.viewport.width, state.viewport.height, state.viewport.minDepth, state.viewport.maxDepth);
APS5_LOG_OUT_DEBUG("Scissor x=%d y=%d w=%u h=%u topology=%u cullMode=0x%x frontFace=%u", state.scissor.offset.x, state.scissor.offset.y, state.scissor.extent.width, state.scissor.extent.height, static_cast<unsigned>(state.topology), static_cast<unsigned>(state.cullMode), static_cast<unsigned>(state.frontFace));
// An indirect draw: the counts live in guest memory records (Pm4::DrawParameters::IndirectDraw),
// read by the GPU from the host import or, when the GPU could not see their current bytes, by
// the CPU (Draw's `records`). The driver resolved every non-vertex-path draw before this.
const auto* args = draw.indirect ? &*draw.indirect : nullptr;
Require(draw.indexed ? draw.flags == 0 : (draw.flags & ~0x20u) == 0, "draw modifiers are unsupported");
if (draw.indexed) {
@@ -1563,8 +1610,8 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
Require(draw.indexAddress == 0 && draw.indexSize == 0, "auto draw must not reference an index buffer");
if (args == nullptr) {
if (draw.indexCount == 0 || draw.instanceCount == 0) {
inputs.nothing = true;
return inputs;
plan.nothing = true;
return plan;
}
Require(draw.firstVertex <= std::numeric_limits<std::uint32_t>::max() - (draw.indexCount - 1u), "auto draw vertex range overflow");
Require(draw.firstInstance <= std::numeric_limits<std::uint32_t>::max() - (draw.instanceCount - 1u), "auto draw instance range overflow");
@@ -1572,32 +1619,25 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
}
if (args == nullptr) {
if (draw.indexCount == 0 || draw.instanceCount == 0) {
inputs.nothing = true;
return inputs;
plan.nothing = true;
return plan;
}
} else Require((!state.stages.mesh || draw.indexed) && !state.stages.tessellation && !state.quadList, "indirect draw on a non-vertex path must be resolved by the driver");
inputs.indexBytes = static_cast<std::uint64_t>(draw.indexCount) * draw.indexSize;
const auto indexBytes = inputs.indexBytes;
plan.indexBytes = static_cast<std::uint64_t>(draw.indexCount) * draw.indexSize;
const auto indexBytes = plan.indexBytes;
APS5_LOG_OUT_DEBUG("Index buffer bytes=%llu", static_cast<unsigned long long>(indexBytes));
Require(indexBytes <= std::numeric_limits<std::size_t>::max(), "index buffer size overflow");
if (draw.indexed) GuestMemory::CheckRange(reinterpret_cast<const void*>(draw.indexAddress), static_cast<std::size_t>(indexBytes), draw.indexSize);
APS5_LOG_CHARS_OUT_DEBUG("Index buffer range OK");
Require(!draw.indexed || !state.hasColorTarget || draw.indexAddress + indexBytes <= state.color.MemoryAddress() || state.color.MemoryAddress() + state.color.bytes <= draw.indexAddress, "index buffer aliases the render target");
if (draw.indexed) RequireNoMultisampleTarget(draw.indexAddress, static_cast<std::size_t>(indexBytes), "an index buffer read");
if (state.pixelKill && !state.pixelEarlyZ && std::ranges::any_of(state.colors, [](const ColorTarget& color) { return color.partialWriteMask != 0; })) {
const auto* recorder = Recorder::Active();
Require(recorder == nullptr || !recorder->CountingSamples(), "a partial write of a packed color target merges inside the pixel shader after early depth and stencil tests, which a shader that kills pixels under late tests cannot use while occlusion queries count samples: the early tests would count the pixels it kills");
}
APS5_LOG_CHARS_OUT_DEBUG("ValidateShaders");
if (recipe != nullptr) {
inputs.fragmentOutputs = recipe->fragmentOutputs;
inputs.shaderStages = recipe->shaderStages;
plan.fragmentOutputs = recipe->fragmentOutputs;
plan.shaderStages = recipe->shaderStages;
} else {
inputs.fragmentOutputs = CachedFragmentOutputs(context, shaders, state, outcome.validateMemoized, outcome.validateHit);
inputs.shaderStages = PipelineStages(shaders);
plan.fragmentOutputs = CachedFragmentOutputs(context, shaders, state, outcome.validateMemoized, outcome.validateHit);
plan.shaderStages = PipelineStages(shaders);
}
APS5_LOG_CHARS_OUT_DEBUG("ValidateShaders OK");
APS5_LOG_OUT_DEBUG("PipelineStages=0x%x", static_cast<unsigned>(inputs.shaderStages));
APS5_LOG_OUT_DEBUG("PipelineStages=0x%x", static_cast<unsigned>(plan.shaderStages));
if (state.stages.mesh) {
APS5_LOG_CHARS_OUT_DEBUG("Mesh path");
Require(context.meshShader, "device does not support mesh shaders");
@@ -1606,8 +1646,8 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
Require(mesh.primitivesPerGroup != 0, "mesh pipeline groups no primitive (zero primitives per group)");
Require(((state.stages.registerValue >> 19u) & 3u) == 0 || !draw.indexed, "indexed fast-launch draws are unsupported");
if (args == nullptr && draw.indexCount < inputSize) {
inputs.nothing = true;
return inputs;
plan.nothing = true;
return plan;
}
if (args == nullptr) {
const auto step = mesh.inputPrimitive == 5 || mesh.inputPrimitive == 6 ? 1u : inputSize;
@@ -1616,17 +1656,74 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
const auto grid = MeshGridFor(context, groups, draw.instanceCount);
Require(grid.has_value(), "mesh draw exceeds workgroup count limits");
APS5_LOG_OUT_DEBUG("Mesh primitives=%u groups=%u as %u x %u", primitives, groups, grid->groups, grid->layers);
inputs.meshGroups = grid->groups;
inputs.meshLayers = grid->layers;
inputs.meshLayerStride = grid->layerStride;
plan.meshGroups = grid->groups;
plan.meshLayers = grid->layers;
plan.meshLayerStride = grid->layerStride;
}
}
if (state.stages.tessellation) Require(draw.indexCount % state.stages.tessellation->inputControlPoints == 0, "incomplete tessellation patch");
// Viewport and scissor are dynamic pipeline state, so their limits are checked here per draw.
ValidateViewport(context, state.viewport);
ValidateDepthBounds(context, state);
ValidateSampleMask(context, state, shaders);
timer.phase(PhaseValidate);
const auto layoutStart = timer.profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
const auto& attributes = shaders.front().program->vertexAttributes;
if (recipe != nullptr) {
plan.vertexInput = recipe->vertexInput;
} else if (!attributes.empty()) {
if (context.vertexInputs != nullptr) plan.retainedVertexInput = context.vertexInputs->TryGet(shaders.front().program->variantId, attributes);
if (plan.retainedVertexInput == nullptr) plan.vertexInput = BuildVertexInputLayout(context, attributes);
}
timer.charge(PhaseVertex, layoutStart);
static const bool noDrawResourceCache = std::getenv("APS5_NO_DRAW_RESOURCE_CACHE") != nullptr;
static const bool noTextureCache = std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr;
static const bool trimKey = std::getenv("APS5_NO_DRAW_KEY_TRIM") == nullptr;
plan.candidate = recipe == nullptr && !noDrawResourceCache && !noTextureCache && std::all_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->PipelineVariantId() != 0; });
plan.keyed = plan.candidate && !ShaderResources::NeverReusable(shaders);
if (plan.keyed) {
const auto keyStart = timer.profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
plan.contentKey = DrawResourceKey(context, shaders, state.color, static_cast<std::uint32_t>(state.colors.size()), draw.indexAddress, indexBytes, !trimKey);
timer.charge(PhaseLookup, keyStart);
}
return plan;
}
bool VerifyDrawPlan() {
static const bool verify = std::getenv("APS5_VERIFY_DRAW_PLAN") != nullptr;
return verify;
}
void requireDrawPlanRepeats(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, const DrawPlan& plan) {
DrawOutcome scratch;
DrawTimer scratchTimer(false);
const auto again = planDraw(context, state, draw, shaders, nullptr, scratch, scratchTimer);
const auto sameBinding = [](const VkVertexInputBindingDescription& a, const VkVertexInputBindingDescription& b) { return a.binding == b.binding && a.stride == b.stride && a.inputRate == b.inputRate; };
const auto sameAttribute = [](const VkVertexInputAttributeDescription& a, const VkVertexInputAttributeDescription& b) { return a.location == b.location && a.binding == b.binding && a.format == b.format && a.offset == b.offset; };
const auto& layout = plan.VertexLayout();
const auto& repeated = again.VertexLayout();
Require(again.nothing == plan.nothing && again.indexBytes == plan.indexBytes && again.fragmentOutputs == plan.fragmentOutputs && again.shaderStages == plan.shaderStages && again.meshGroups == plan.meshGroups && again.meshLayers == plan.meshLayers && again.meshLayerStride == plan.meshLayerStride && again.candidate == plan.candidate && again.keyed == plan.keyed && again.contentKey == plan.contentKey && std::ranges::equal(repeated.bindings, layout.bindings, sameBinding) && std::ranges::equal(repeated.attributes, layout.attributes, sameAttribute), "APS5_VERIFY_DRAW_PLAN: the plan built after the draw's record-time work differs from the plan the draw used");
}
DrawInputs prepareDrawInputs(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, const DrawPlan& drawPlan, DrawTimer& timer, PerformanceTimer& timing) {
DrawInputs inputs;
inputs.indexBytes = drawPlan.indexBytes;
inputs.fragmentOutputs = drawPlan.fragmentOutputs;
inputs.shaderStages = drawPlan.shaderStages;
inputs.meshGroups = drawPlan.meshGroups;
inputs.meshLayers = drawPlan.meshLayers;
inputs.meshLayerStride = drawPlan.meshLayerStride;
inputs.vertexInput = drawPlan.vertexInput;
inputs.retainedVertexInput = drawPlan.retainedVertexInput;
const auto* args = draw.indirect ? &*draw.indirect : nullptr;
const auto indexBytes = inputs.indexBytes;
if (draw.indexed) GuestMemory::CheckRange(reinterpret_cast<const void*>(draw.indexAddress), static_cast<std::size_t>(indexBytes), draw.indexSize);
APS5_LOG_CHARS_OUT_DEBUG("Index buffer range OK");
if (draw.indexed) RequireNoMultisampleTarget(draw.indexAddress, static_cast<std::size_t>(indexBytes), "an index buffer read");
if (state.pixelKill && !state.pixelEarlyZ && std::ranges::any_of(state.colors, [](const ColorTarget& color) { return color.partialWriteMask != 0; })) {
const auto* recorder = Recorder::Active();
Require(recorder == nullptr || !recorder->CountingSamples(), "a partial write of a packed color target merges inside the pixel shader after early depth and stencil tests, which a shader that kills pixels under late tests cannot use while occlusion queries count samples: the early tests would count the pixels it kills");
}
timer.phase(PhaseValidate);
timing.Mark("validate");
inputs.maxIndex = draw.indexed ? 0u : draw.firstVertex + draw.indexCount - 1u;
if (state.quadList || StripPatches(state, shaders)) {
@@ -1800,13 +1897,6 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
APS5_LOG_CHARS_OUT_DEBUG("Index validation OK");
timing.Mark("index_upload");
const auto& attributes = shaders.front().program->vertexAttributes;
// Validates the vertex descriptors; the layout also keys and builds the pipeline.
if (recipe != nullptr) {
inputs.vertexInput = recipe->vertexInput;
} else if (!attributes.empty()) {
if (context.vertexInputs != nullptr) inputs.retainedVertexInput = context.vertexInputs->TryGet(shaders.front().program->variantId, attributes);
if (inputs.retainedVertexInput == nullptr) inputs.vertexInput = BuildVertexInputLayout(context, attributes);
}
inputs.vertexOffsets.assign(attributes.size(), 0);
inputs.vertexHandles.reserve(attributes.size());
// An indexed draw's vertex offset moves every fetch: the copy must reach the last one.
@@ -2005,7 +2095,7 @@ bool drawStagingEnabled() {
return !disabled;
}
ResolvedResources resolveDrawResources(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots, std::uint64_t indexBytes, bool recordable, DrawOutcome& outcome, DrawTimer& timer) {
ResolvedResources resolveDrawResources(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots, std::uint64_t indexBytes, bool recordable, const DrawPlan& plan, DrawOutcome& outcome, DrawTimer& timer) {
ResolvedResources resolved;
APS5_LOG_CHARS_OUT_DEBUG("Creating ShaderResources");
// A recordable draw whose stages' compiled content repeats an earlier one binds that build's
@@ -2014,19 +2104,17 @@ ResolvedResources resolveDrawResources(const Context& context, const State& stat
// object must never do. Revalidate proves a hit by texture identity, which needs the texture
// caches. Push constants still come from this draw's stages. APS5_NO_DRAW_RESOURCE_CACHE=1
// builds every draw's resources as before.
static const bool noDrawResourceCache = std::getenv("APS5_NO_DRAW_RESOURCE_CACHE") != nullptr;
static const bool noTextureCache = std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr;
// The render target and index ranges stay out of the key (see DrawResourceKey); a hit repeats
// the alias checks instead. Debug aid: APS5_NO_DRAW_KEY_TRIM=1 keys them as before.
static const bool trimKey = std::getenv("APS5_NO_DRAW_KEY_TRIM") == nullptr;
const bool candidate = recordable && !noDrawResourceCache && !noTextureCache && std::all_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->PipelineVariantId() != 0; });
resolved.cacheable = candidate && !ShaderResources::NeverReusable(shaders);
const bool candidate = recordable && plan.candidate;
resolved.cacheable = recordable && plan.keyed;
const auto address = candidate && !ShaderResources::SpaceReuseDisabled() ? addressStages(shaders) : AddressStages::None;
std::optional<AddressDrawReuse> reuse;
if (address == AddressStages::Storing) reuse = AddressDrawReuse::NotReadOnly;
else if (address == AddressStages::ReadOnly && !resolved.cacheable) reuse = AddressDrawReuse::NotSpaceOnly;
if (resolved.cacheable) {
resolved.contentKey = DrawResourceKey(context, shaders, state.color, static_cast<std::uint32_t>(state.colors.size()), draw.indexAddress, indexBytes, !trimKey);
resolved.contentKey = plan.contentKey;
if (auto cached = SharedResourceCache().Find(resolved.contentKey)) {
const auto releaseSpace = [](ShaderResources* resources) { static_cast<void>(resources->ReleaseSpace()); };
std::unique_ptr<ShaderResources, decltype(releaseSpace)> heldSpace(nullptr, releaseSpace);
@@ -2156,6 +2244,7 @@ bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, co
};
const auto* args = indirect != nullptr ? indirect->args : nullptr;
if (state.stages.mesh && (args != nullptr || state.tessellationCapture != nullptr)) {
CountVkDraw(VkDrawKind::Mesh);
context.Function<PFN_vkCmdDrawMeshTasksIndirectEXT>("vkCmdDrawMeshTasksIndirectEXT")(commands, argumentBuffer, argumentOffset, 1, sizeof(VkDrawMeshTasksIndirectCommandEXT));
recorded(subdraw++);
emitted = true;
@@ -2163,6 +2252,7 @@ bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, co
}
if (state.stages.mesh) {
APS5_LOG_OUT_DEBUG("vkCmdDrawMeshTasksEXT groups=%u instances=%u layers=%u", inputs.meshGroups, draw.instanceCount, inputs.meshLayers);
CountVkDraw(VkDrawKind::Mesh);
context.Function<PFN_vkCmdDrawMeshTasksEXT>("vkCmdDrawMeshTasksEXT")(commands, inputs.meshGroups, draw.instanceCount, inputs.meshLayers);
recorded(subdraw++);
emitted = true;
@@ -2171,6 +2261,7 @@ bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, co
if (!inputs.vertexHandles.empty()) context.Resolved(&DeviceFunctions::cmdBindVertexBuffers, "vkCmdBindVertexBuffers")(commands, 0, static_cast<std::uint32_t>(inputs.vertexHandles.size()), inputs.vertexHandles.data(), inputs.vertexOffsets.data());
if (inputs.expandedIndexCount != 0u) {
context.Resolved(&DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer")(commands, inputs.indexHandle, inputs.indexOffset, VK_INDEX_TYPE_UINT32);
CountVkDraw(VkDrawKind::Indexed);
context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, inputs.expandedIndexCount, draw.instanceCount, 0, static_cast<std::int32_t>(draw.firstVertex), draw.firstInstance);
emitted = true;
return true;
@@ -2178,10 +2269,12 @@ bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, co
if (draw.indexed) context.Resolved(&DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer")(commands, inputs.indexHandle, inputs.indexOffset, draw.indexSize == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32);
if (args == nullptr) {
if (draw.indexed) {
CountVkDraw(VkDrawKind::Indexed);
context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, pieceFirstIndex ? draw.indexCount : inputs.indexCount.value_or(draw.indexCount), draw.instanceCount, pieceFirstIndex.value_or(0u), static_cast<std::int32_t>(draw.firstVertex), draw.firstInstance);
recorded(subdraw++);
emitted = true;
} else {
CountVkDraw(VkDrawKind::Direct);
context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, draw.indexCount, draw.instanceCount, draw.firstVertex, draw.firstInstance);
recorded(subdraw++);
emitted = true;
@@ -2189,14 +2282,17 @@ bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, co
} else if (indirect->path == IndirectDrawPath::Gpu) {
emitted = true;
if (args->countIndirect) {
CountVkDraw(VkDrawKind::Indirect);
if (draw.indexed) context.Function<PFN_vkCmdDrawIndexedIndirectCountKHR>("vkCmdDrawIndexedIndirectCountKHR")(commands, argumentBuffer, argumentOffset, indirect->countImport->buffer, HostImportOffset(*indirect->countImport, args->countAddress), args->count, args->stride);
else context.Function<PFN_vkCmdDrawIndirectCountKHR>("vkCmdDrawIndirectCountKHR")(commands, argumentBuffer, argumentOffset, indirect->countImport->buffer, HostImportOffset(*indirect->countImport, args->countAddress), args->count, args->stride);
} else if (args->count <= 1 || context.multiDrawIndirect) {
CountVkDraw(VkDrawKind::Indirect);
if (draw.indexed) context.Resolved(&DeviceFunctions::cmdDrawIndexedIndirect, "vkCmdDrawIndexedIndirect")(commands, argumentBuffer, argumentOffset, args->count, args->stride);
else context.Resolved(&DeviceFunctions::cmdDrawIndirect, "vkCmdDrawIndirect")(commands, argumentBuffer, argumentOffset, args->count, args->stride);
} else {
for (std::uint32_t record = 0; record < args->count; ++record) {
const auto offset = argumentOffset + static_cast<VkDeviceSize>(record) * args->stride;
CountVkDraw(VkDrawKind::Indirect);
if (draw.indexed) context.Resolved(&DeviceFunctions::cmdDrawIndexedIndirect, "vkCmdDrawIndexedIndirect")(commands, argumentBuffer, offset, 1, args->stride);
else context.Resolved(&DeviceFunctions::cmdDrawIndirect, "vkCmdDrawIndirect")(commands, argumentBuffer, offset, 1, args->stride);
}
@@ -2214,10 +2310,12 @@ bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, co
if (record.firstVertexOrIndex >= boundCount) continue;
const auto vertexOffset = args->vertexRule == Rule::InPlace ? record.vertexOffset : args->vertexConstant;
emitted = true;
CountVkDraw(VkDrawKind::Indexed);
context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, std::min(record.count, boundCount - record.firstVertexOrIndex), record.instances, record.firstVertexOrIndex, static_cast<std::int32_t>(vertexOffset), firstInstance);
} else {
const auto firstVertex = args->vertexRule == Rule::InPlace ? record.firstVertexOrIndex : args->vertexConstant;
emitted = true;
CountVkDraw(VkDrawKind::Direct);
context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, record.count, record.instances, firstVertex, firstInstance);
}
}
@@ -2824,7 +2922,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam
}
eachDrawTiming = recorder->BeginInPassGpuTiming(Recorder::DrawTimingKey(key));
}
noteDrawFaultToken(context, *recorder, commands, shaders, draw, record.indirect != nullptr);
noteDrawFaultToken(context, *recorder, commands, shaders, draw, static_cast<std::uint32_t>(state.stages.mesh.has_value() ? AgcDriver::FaultStage::mesh : AgcDriver::FaultStage::graphics), record.indirect != nullptr ? record.indirect->args : nullptr);
if (record.stencilReplay.empty()) recordDrawCommands(context, commands, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw);
else {
recordStencilReplay(context, commands, state, draw, inputs, record.stencilReplay, shaders, resources, record.pushBytes, record.pushStages);
@@ -3191,8 +3289,13 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
auto& ownWaitedMs = prepared.ownWaitedMs;
const auto report = [&](const char* suffix) { reportDrawEnd(state, timer, built, outcome, waitedBefore, ownWaitedMs, suffix); };
auto& inputs = prepared.inputs;
inputs = prepareDrawInputs(context, state, draw, shaders, outcome, timer, timing, nullptr);
if (inputs.nothing) return false;
const auto plan = planDraw(context, state, draw, shaders, nullptr, outcome, timer);
if (plan.nothing) return false;
inputs = prepareDrawInputs(context, state, draw, shaders, plan, timer, timing);
if (inputs.nothing) {
if (VerifyDrawPlan()) requireDrawPlanRepeats(context, state, draw, shaders, plan);
return false;
}
const auto* args = prepared.args = draw.indirect ? &*draw.indirect : nullptr;
const auto indexBytes = inputs.indexBytes;
const int dumpLimit = prepared.dumpLimit = DumpTargetLimit();
@@ -3334,7 +3437,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
auto* recorder = prepared.recorder = Recorder::Active();
bool recordable = recordDraws && recorder != nullptr && dumpLimit == 0 && std::all_of(targets.begin(), targets.end(), [](const TargetBinding& binding) { return binding.resident != nullptr || binding.multisampled; });
auto& resolved = prepared.resolved;
resolved = resolveDrawResources(context, state, draw, shaders, snapshots, indexBytes, recordable, outcome, timer);
resolved = resolveDrawResources(context, state, draw, shaders, snapshots, indexBytes, recordable, plan, outcome, timer);
if (stopAfterResolve.load(std::memory_order_relaxed) != 0) {
const auto stop = stopAfterResolve.exchange(0, std::memory_order_relaxed);
if (stop == 1) return false;
@@ -3575,6 +3678,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
prepared.depthLocations = passDepthLocations(context, pipelineState, *pipeline);
timer.phase(PhasePipeline);
APS5_LOG_CHARS_OUT_DEBUG("Pipeline created");
if (VerifyDrawPlan()) requireDrawPlanRepeats(context, state, draw, shaders, plan);
return true;
}
@@ -3806,7 +3910,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D
pushDrawConstants(*pipeline, commands, state, draw, shaders, *resources, nullptr, 0, meshArguments != nullptr ? meshArguments->DeviceAddress() : 0, !inputs.restartTable.empty(), inputs.meshLayerStride);
APS5_LOG_CHARS_OUT_DEBUG("Push constants recorded");
std::uint32_t subdraw = 0;
if (recorded) noteDrawFaultToken(context, *recorder, commands, shaders, draw, args != nullptr);
if (recorded) noteDrawFaultToken(context, *recorder, commands, shaders, draw, static_cast<std::uint32_t>(state.stages.mesh.has_value() ? AgcDriver::FaultStage::mesh : AgcDriver::FaultStage::graphics), args);
if (stencilReplay.empty()) recordDrawCommands(context, commands, state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw);
else {
recordStencilReplay(context, commands, state, draw, inputs, stencilReplay, shaders, *resources);
@@ -4110,7 +4214,10 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con
if (recipe.hasDepth != state.depth.has_value()) return miss(DrawRecipeMiss::TargetGone);
const std::size_t expectedViews = state.colors.size() + (recipe.hasDepth ? 1u : 0u);
Require(recipe.targets.size() == state.colors.size() && recipe.targetViews.size() == expectedViews, "draw recipe targets do not match the state");
auto inputs = prepareDrawInputs(context, state, draw, shaders, outcome, timer, timing, &recipe);
const auto plan = planDraw(context, state, draw, shaders, &recipe, outcome, timer);
DrawInputs inputs;
if (plan.nothing) inputs.nothing = true;
else inputs = prepareDrawInputs(context, state, draw, shaders, plan, timer, timing);
if (inputs.nothing) {
result.recorded = true;
return result;
@@ -4190,7 +4297,12 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con
record.targetViews = recipe.targetViews;
record.targets = std::move(targets);
for (const auto& color : state.colors) record.targetSlices.emplace_back(color.arraySlice, color.arrayLastSlice != 0 ? color.layers : 1u);
record.pushBytes = &recipe.pushBytes;
auto pushBytes = recipe.pushBytes;
if (recipe.pushStages != 0) {
pushBytes = AssemblePushConstants(shaders);
record.resources->PatchPushConstants(pushBytes);
}
record.pushBytes = &pushBytes;
record.pushStages = recipe.pushStages;
record.depthLocations = passDepthLocations(context, state, *record.pipeline);
recordDraw(context, state, draw, shaders, inputs, record, outcome, timer, ownWaitedMs, trace);
@@ -4312,4 +4424,14 @@ bool CommitTrims() {
return DrawPipelineEnabled();
}
VkDrawCounts TakeVkDrawCounts() {
VkDrawCounts counts;
counts.direct = vkDrawCounts[static_cast<std::size_t>(VkDrawKind::Direct)].exchange(0, std::memory_order_relaxed);
counts.indexed = vkDrawCounts[static_cast<std::size_t>(VkDrawKind::Indexed)].exchange(0, std::memory_order_relaxed);
counts.indirect = vkDrawCounts[static_cast<std::size_t>(VkDrawKind::Indirect)].exchange(0, std::memory_order_relaxed);
counts.mesh = vkDrawCounts[static_cast<std::size_t>(VkDrawKind::Mesh)].exchange(0, std::memory_order_relaxed);
return counts;
}
}
@@ -200,6 +200,7 @@ struct AddressSpaceCache {
std::atomic<std::uint64_t> dissolvedOverlap{0};
std::atomic<std::uint64_t> dissolvedImports{0};
std::atomic<std::uint64_t> waiterDrops{0};
std::atomic<std::uint64_t> patchedEpoch{0};
};
AddressSpaceCache& Spaces() {
@@ -765,7 +766,7 @@ const char* createDmaBufImport(const Context& context, HostImport& entry, int fi
#ifndef _WIN32
constexpr std::uint64_t ImportChunkBytes = std::uint64_t{64} << 20u;
constexpr VkBufferUsageFlags ChunkImportUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
constexpr VkBufferUsageFlags ChunkImportUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
constexpr std::uint64_t SparseBlockBytes = 65536;
struct ImportChunk {
@@ -1660,6 +1661,15 @@ std::pair<std::size_t, std::size_t> continuedRun(const GuestAllocations::Lease&
return entry.run;
}
bool joinedWithin(const HostImports& state, std::uint64_t begin, std::uint64_t end) {
auto it = state.imports.lower_bound(begin);
if (it != state.imports.begin() && std::prev(it)->second.joined && std::prev(it)->first + std::prev(it)->second.bytes > begin) return true;
for (; it != state.imports.end() && it->first < end; ++it) {
if (it->second.joined) return true;
}
return false;
}
RunBounds importRunBounds(const GuestAllocations::Lease& lease, std::uint64_t address, std::uint64_t largest = std::numeric_limits<std::uint64_t>::max(), std::uint64_t budget = 0) {
const auto index = leasedIndexContaining(lease, address);
if (index == lease.size()) return {};
@@ -1692,7 +1702,7 @@ RunBounds importRunBounds(const GuestAllocations::Lease& lease, std::uint64_t ad
const auto blockLast = bounding(index, last, blockHigh, false);
if (blockFirst == lease.size() || blockLast == lease.size()) continue;
if (blockFirst == blockLast) break;
if (skipped(blockFirst, blockLast)) continue;
if (skipped(blockFirst, blockLast) || joinedWithin(state, blockLow, blockHigh)) continue;
return {blockFirst, blockLast, true};
}
return single;
@@ -3523,6 +3533,15 @@ std::shared_ptr<ImageMirror> findMirror(const Context& context, std::uint64_t be
return mirror;
}
std::shared_ptr<const GuestAllocations::Range> fixedImageRange(std::uint64_t begin, std::uint64_t end) {
const auto lease = GuestAllocations::GuestAllocationsAcquire_nid_postfix();
auto found = std::upper_bound(lease.begin(), lease.end(), begin, [](std::uint64_t address, const auto& range) { return address < range->address; });
if (found == lease.begin()) return nullptr;
const auto& range = *--found;
if (!range->readable || range->writable || range->releasable || end > range->address + range->bytes) return nullptr;
return range;
}
void sweepMirrors(std::uint64_t neededBytes, std::uint64_t protectAddress) {
ReferenceStorage::Shared().ReleaseIdle();
const bool released = releaseExpiredJoinedHeaps();
@@ -3929,7 +3948,7 @@ LeaseStats LeaseCounters() {
AddressSpaceStats AddressSpaceCounters() {
const auto& cache = Spaces();
const auto load = [](const std::atomic<std::uint64_t>& counter) { return counter.load(std::memory_order_relaxed); };
return {addressSpaceCacheEnabled(), load(cache.hits), load(cache.rebuiltFirst), load(cache.rebuiltGeneration), load(cache.rebuiltEpoch), load(cache.rebuiltDevice), load(cache.rebuiltWaiterDrop), load(cache.unpublished), load(cache.dissolvedOverlap), load(cache.dissolvedImports), load(cache.waiterDrops)};
return {addressSpaceCacheEnabled(), load(cache.hits), load(cache.rebuiltFirst), load(cache.rebuiltGeneration), load(cache.rebuiltEpoch), load(cache.rebuiltDevice), load(cache.rebuiltWaiterDrop), load(cache.unpublished), load(cache.dissolvedOverlap), load(cache.dissolvedImports), load(cache.waiterDrops), load(cache.patchedEpoch)};
}
std::string AddressCopyOverflow(std::vector<AddressCopy> copies, std::uint64_t limit) {
@@ -3953,7 +3972,10 @@ MirrorStats MirrorCounters() {
auto& state = Mirrors();
std::lock_guard lock(state.mutex);
MirrorStats stats{0, state.heapBytes, state.rebuilds, state.blocksCopied, state.heapRefills, state.sweeps, state.heapChecks, state.sparseBinds, state.evictions};
for (const auto& [base, mirror] : state.entries) stats.heapMirrors += mirror->heap ? 1 : 0;
for (const auto& [base, mirror] : state.entries) {
stats.heapMirrors += mirror->heap ? 1 : 0;
stats.rangeMirrors += mirror->heap ? 0 : 1;
}
return stats;
}
@@ -4745,7 +4767,7 @@ void GuestBufferMemory::CountAddressBuild(double snapshotsUs) {
const auto delta = [](std::uint64_t now, std::uint64_t before) { return static_cast<unsigned long long>(now - before); };
const auto space = AddressSpaceCounters();
const auto& spaceSeen = totals.spaceSeen;
AgcDriver::ProfilePrint_nid_no_patch("[address] %llu address-based builds (10 s), us per build: lease %.0f, imports pass %.0f, mirror prepare %.0f, compare %.0f (%.0f blocks, %.1f copied), snapshots %.0f; space hits %llu / rebuilds: generation %llu, epoch %llu, device %llu, waiter drop %llu, first %llu; unpublished %llu, dissolved: overlap %llu, imports %llu%s; [bda-table] hits %llu / misses %llu (space tables %llu), first entry: expired %llu, hash differs low %llu / heap %llu, same hash %llu, none held %llu\n", static_cast<unsigned long long>(totals.builds), per(totals.sums.leaseUs), per(totals.sums.importsUs), per(totals.sums.mirrorsUs), per(totals.sums.compareUs), per(static_cast<double>(totals.sums.blocksCompared)), per(static_cast<double>(totals.sums.blocksCopied)), per(totals.snapshotsUs), delta(space.hits, spaceSeen.hits), delta(space.rebuiltGeneration, spaceSeen.rebuiltGeneration), delta(space.rebuiltEpoch, spaceSeen.rebuiltEpoch), delta(space.rebuiltDevice, spaceSeen.rebuiltDevice), delta(space.rebuiltWaiterDrop, spaceSeen.rebuiltWaiterDrop), delta(space.rebuiltFirst, spaceSeen.rebuiltFirst), delta(space.unpublished, spaceSeen.unpublished), delta(space.dissolvedOverlap, spaceSeen.dissolvedOverlap), delta(space.dissolvedImports, spaceSeen.dissolvedImports), space.enabled ? "" : " (cache off)", delta(table.hits, seen.hits), delta(table.misses, seen.misses), delta(table.spaceTables, seen.spaceTables), delta(table.firstExpired, seen.firstExpired), delta(table.firstDiffersLow, seen.firstDiffersLow), delta(table.firstDiffersHeap, seen.firstDiffersHeap), delta(table.firstSameHash, seen.firstSameHash), delta(table.firstEmpty, seen.firstEmpty));
AgcDriver::ProfilePrint_nid_no_patch("[address] %llu address-based builds (10 s), us per build: lease %.0f, imports pass %.0f, mirror prepare %.0f, compare %.0f (%.0f blocks, %.1f copied), snapshots %.0f; space hits %llu (patched after an import change %llu) / rebuilds: generation %llu, epoch %llu, device %llu, waiter drop %llu, first %llu; unpublished %llu, dissolved: overlap %llu, imports %llu%s; [bda-table] hits %llu / misses %llu (space tables %llu), first entry: expired %llu, hash differs low %llu / heap %llu, same hash %llu, none held %llu\n", static_cast<unsigned long long>(totals.builds), per(totals.sums.leaseUs), per(totals.sums.importsUs), per(totals.sums.mirrorsUs), per(totals.sums.compareUs), per(static_cast<double>(totals.sums.blocksCompared)), per(static_cast<double>(totals.sums.blocksCopied)), per(totals.snapshotsUs), delta(space.hits, spaceSeen.hits), delta(space.patchedEpoch, spaceSeen.patchedEpoch), delta(space.rebuiltGeneration, spaceSeen.rebuiltGeneration), delta(space.rebuiltEpoch, spaceSeen.rebuiltEpoch), delta(space.rebuiltDevice, spaceSeen.rebuiltDevice), delta(space.rebuiltWaiterDrop, spaceSeen.rebuiltWaiterDrop), delta(space.rebuiltFirst, spaceSeen.rebuiltFirst), delta(space.unpublished, spaceSeen.unpublished), delta(space.dissolvedOverlap, spaceSeen.dissolvedOverlap), delta(space.dissolvedImports, spaceSeen.dissolvedImports), space.enabled ? "" : " (cache off)", delta(table.hits, seen.hits), delta(table.misses, seen.misses), delta(table.spaceTables, seen.spaceTables), delta(table.firstExpired, seen.firstExpired), delta(table.firstDiffersLow, seen.firstDiffersLow), delta(table.firstDiffersHeap, seen.firstDiffersHeap), delta(table.firstSameHash, seen.firstSameHash), delta(table.firstEmpty, seen.firstEmpty));
totals.tableSeen = table;
totals.spaceSeen = space;
totals.builds = 0;
@@ -4822,7 +4844,36 @@ void GuestBufferMemory::AcquireRegistered() {
const auto generation = GuestAllocations::GuestAllocationsGeneration_nid_postfix();
if (addressSpaceCacheEnabled()) {
auto current = spaces.current.load();
const auto published = current;
bool hit = false;
static const bool patchSpaces = std::getenv("APS5_NO_SPACE_PATCH") == nullptr;
const auto patchedSpace = [&](HostImports& state, std::shared_ptr<const AddressSpace> old) -> std::shared_ptr<const AddressSpace> {
if (!patchSpaces) return nullptr;
if (importable) refreshImports(context, state, old->lease);
if (old->generation != GuestAllocations::GuestAllocationsGeneration_nid_postfix()) return nullptr;
auto built = std::make_shared<AddressSpace>();
built->base = old->base;
for (auto& region : built->base) {
if (region.direct == nullptr) continue;
const auto* entry = peekImport(state, region.begin, region.end);
if (entry == nullptr) return nullptr;
region.direct = entry;
}
built->generation = old->generation;
built->importsEpoch = state.epoch;
built->device = old->device;
built->serial = spaces.serials.fetch_add(1, std::memory_order_relaxed) + 1;
built->lease = old->lease;
built->copied = old->copied;
built->directReads = old->directReads;
built->ranges.reserve(built->base.size());
for (const auto& region : built->base) built->ranges.push_back(addressRange(region));
planSpaceMirrors(*built);
const auto imported = [&](ImageMirror* mirror) { return importsNow(context, state, old->lease, mirror->base); };
if (std::any_of(built->heapMirrors.begin(), built->heapMirrors.end(), imported) || std::any_of(built->sparseMirrors.begin(), built->sparseMirrors.end(), imported)) return nullptr;
for (std::size_t index = 0; index < built->heapRuns.size() && index < old->heapRuns.size(); ++index) built->verified[index].store(old->verified[index].load(std::memory_order_relaxed), std::memory_order_relaxed);
return built;
};
{
auto& state = Imports();
std::lock_guard lock(state.mutex);
@@ -4830,8 +4881,13 @@ void GuestBufferMemory::AcquireRegistered() {
if (current == nullptr) (spaces.droppedByWaiter.exchange(false, std::memory_order_relaxed) ? spaces.rebuiltWaiterDrop : spaces.rebuiltFirst).fetch_add(1, std::memory_order_relaxed);
else if (current->device != context.device) spaces.rebuiltDevice.fetch_add(1, std::memory_order_relaxed);
else if (current->generation != generation) spaces.rebuiltGeneration.fetch_add(1, std::memory_order_relaxed);
else if (current->importsEpoch != state.epoch) spaces.rebuiltEpoch.fetch_add(1, std::memory_order_relaxed);
else if (current->importsEpoch != state.epoch && (current = patchedSpace(state, std::move(current))) == nullptr) spaces.rebuiltEpoch.fetch_add(1, std::memory_order_relaxed);
else hit = std::all_of(current->heapMirrors.begin(), current->heapMirrors.end(), keeps) && std::all_of(current->sparseMirrors.begin(), current->sparseMirrors.end(), keeps);
if (hit && current != published) {
spaces.patchedEpoch.fetch_add(1, std::memory_order_relaxed);
auto expected = published;
spaces.current.compare_exchange_strong(expected, current);
}
importFloor = state.useCounter + 1;
if (hit) {
const auto stamp = ++state.useCounter;
@@ -6034,6 +6090,14 @@ void GuestBufferMemory::UploadPrepare(bool addressable) {
// before the imports: the image can never be imported, and the import fallback would acquire
// a registry lease for it on nearly every descriptor upload.
auto mirror = findMirror(context, region.begin, region.end);
if (mirror == nullptr) {
const auto range = fixedImageRange(region.begin, region.end);
if (range != nullptr && (region.begin - range->address) % context.limits.minStorageBufferOffsetAlignment == 0) {
std::vector<RefreshBlock> unused;
mirror = acquireMirror(context, range, unused, false);
if (mirror != nullptr) sweepMirrors();
}
}
if (mirror == nullptr || (region.begin - mirror->base) % context.limits.minStorageBufferOffsetAlignment != 0) continue;
// A read-only mirror's bytes never change while its Range exists; a writable one is
// refreshed by UploadFinish (the refresh may wait for recorded work). Either is confirmed
@@ -6999,8 +7063,9 @@ void GuestBufferMemory::MarkDirectWrites() const {
if (found == nullptr) continue;
const auto& region = *found;
if (region.direct != nullptr || (region.gpuCopy && region.copiedBack)) {
const auto generation = GuestMemory::MarkPossiblyWritten(begin, static_cast<std::size_t>(end - begin));
if (generation != 0) directWritesGeneration = std::max(directWritesGeneration, generation);
std::uint64_t order = 0;
static_cast<void>(GuestMemory::MarkPossiblyWritten(begin, static_cast<std::size_t>(end - begin), order));
directWritesGeneration = std::max(directWritesGeneration, order);
}
}
}
@@ -104,7 +104,7 @@ GuestSamplerResource DecodeSamplerResource(std::span<const std::uint32_t> words,
static_cast<void>(anisoThreshold);
static_cast<void>(anisoBias);
const auto reductionMode = toVkReductionMode(filterMode);
Require(!disableDegamma, "guest sampler descriptor disables degamma which is not implemented");
static_cast<void>(disableDegamma);
static_cast<void>(lodBiasSec);
Require(!pointPreclamp, "guest sampler descriptor uses point preclamping which is not implemented");
static_cast<void>(anisoOverride);
@@ -156,6 +156,7 @@ GuestSamplerResource DecodeSamplerResource(std::span<const std::uint32_t> words,
const std::array compareOps{VK_COMPARE_OP_NEVER, VK_COMPARE_OP_LESS, VK_COMPARE_OP_EQUAL, VK_COMPARE_OP_LESS_OR_EQUAL, VK_COMPARE_OP_GREATER, VK_COMPARE_OP_NOT_EQUAL, VK_COMPARE_OP_GREATER_OR_EQUAL, VK_COMPARE_OP_ALWAYS};
result.compareOp = compareOps.at(depthCompareFunc);
result.forceDegamma = forceSrgb;
result.disableDegamma = disableDegamma;
result.nonSeamlessCube = disableCubeWrap;
if (forceUnormCoords) {
result.unnormalizedCoordinates = true;
@@ -287,7 +287,7 @@ void ValidateViewport(const Context& context, const VkViewport& viewport) {
}
bool ShadersWriteMemory(std::span<const CompiledShader> shaders) {
const auto any = [](const std::vector<bool>& written, std::uint32_t count) { return written.size() < count || std::ranges::any_of(written, [](bool element) { return element; }); };
const auto any = [](const ShaderRecompiler::ElementFlags& written, std::uint32_t count) { return written.size() < count || std::ranges::any_of(written, [](bool element) { return element; }); };
for (const auto& shader : shaders) {
if (shader.program == nullptr) continue;
for (const auto& binding : shader.program->bindings) {
@@ -704,8 +704,8 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput
}
if (alternateAlpha) {
const auto keepsStencil = [](const VkStencilOpState& face) { return face.writeMask == 0 || (face.failOp == VK_STENCIL_OP_KEEP && face.passOp == VK_STENCIL_OP_KEEP && face.depthFailOp == VK_STENCIL_OP_KEEP); };
Require(!(state.depth && (state.depthWrite || (state.stencilTest && (!keepsStencil(state.stencilFront) || !keepsStencil(state.stencilBack))))) && !state.depthBiasPerFace, "blending into an 8_8 color target with the alternate component order and a separate alpha blend from a draw that writes depth or stencil is not implemented");
Require(!ShadersWriteMemory(shaders), "blending into an 8_8 color target with the alternate component order and a separate alpha blend from a draw whose shaders write memory is not implemented");
Require(!(state.depth && (state.depthWrite || (state.stencilTest && (!keepsStencil(state.stencilFront) || !keepsStencil(state.stencilBack))))) && !state.depthBiasPerFace, "blending into a two-channel color target with the alternate component order and a separate alpha blend from a draw that writes depth or stencil is not implemented");
Require(!ShadersWriteMemory(shaders), "blending into a two-channel color target with the alternate component order and a separate alpha blend from a draw whose shaders write memory is not implemented");
for (std::size_t index = 0; index < secondChannels.size(); ++index) {
const bool split = index < state.colors.size() && state.colors[index].componentMapping == 0xecu && state.blends[index].blendEnable;
if (!split) {
@@ -551,8 +551,9 @@ bool expandModule(std::span<const std::byte> payload, std::vector<std::byte>& mo
if (payload.size() < ModuleHeaderBytes) return false;
std::uint32_t bytes = 0;
std::memcpy(&bytes, payload.data() + 20, sizeof(bytes));
module.resize(bytes);
const auto frame = payload.subspan(ModuleHeaderBytes);
if (ZSTD_getFrameContentSize(frame.data(), frame.size()) != bytes) return false;
module.resize(bytes);
const auto expanded = ZSTD_decompress(module.data(), module.size(), frame.data(), frame.size());
return !ZSTD_isError(expanded) && expanded == bytes;
}
@@ -3,6 +3,7 @@
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
#include "prx/libSceAgcDriver/Execution/include/Mutex.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include "prx/libc/include/HostThreadSlot.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ReferenceStorage.hpp"
@@ -144,10 +145,10 @@ AgcDriver::Mutex threadSyncsMutex;
// This thread's fence and timeline waits in total (Recorder::ThreadWaitedMs): a caller times a span
// of its own work and reads the difference to learn how much of it was waiting for the GPU.
thread_local double threadWaitedMs = 0;
struct ThreadWaitedSlot {};
void CountThreadSync(int source, double ms) {
threadWaitedMs += ms;
HostThreadSlot<double, ThreadWaitedSlot>::Set(HostThreadSlot<double, ThreadWaitedSlot>::Get() + ms);
const auto tag = GuestMemory::GpuLockThreadTag();
std::lock_guard lock(threadSyncsMutex);
auto it = std::find_if(threadSyncs.begin(), threadSyncs.end(), [&](const ThreadSyncs& thread) { return thread.tag == tag; });
@@ -249,7 +250,11 @@ bool RecorderAlive(std::uint64_t id) {
// Completion actions in progress on this thread (finish()): a pending-write sync the flush hook
// makes from inside one (a copied buffer's write-back store) is skipped, see SyncThrough.
thread_local int completionDepth = 0;
struct CompletionDepthSlot {};
int completionDepth() {
return HostThreadSlot<int, CompletionDepthSlot>::Get();
}
// This thread's hook syncs that waited for an unsignaled target (Recorder::ThreadHookWaits).
thread_local std::uint64_t hookRealWaits = 0;
@@ -260,7 +265,7 @@ bool Recorder::Alive(std::uint64_t id) {
}
bool Recorder::InCompletion() {
return completionDepth != 0;
return completionDepth() != 0;
}
namespace {
@@ -1041,7 +1046,7 @@ void FlushForAccess(std::uint64_t address, std::size_t bytes) {
// rest of this one's, and this queue's queued label follows every batch of its own in flight
// anyway, so the write-back landing first is the order the hardware gives.
if (!QueuedLabelRanges().empty() && QueuedLabelOverlaps(address, bytes)) {
if (completionDepth != 0 && HookCompletionGuard()) {
if (completionDepth() != 0 && HookCompletionGuard()) {
queuedLabelHookInCompletion.fetch_add(1, std::memory_order_relaxed);
} else if (auto* record = queuedLabelRecorder.load(std::memory_order_acquire); record != nullptr) {
queuedLabelHookRecords.fetch_add(1, std::memory_order_relaxed);
@@ -1062,7 +1067,7 @@ void FlushForAccess(std::uint64_t address, std::size_t bytes) {
}
const auto site = GuestMemory::CurrentReadSite();
const auto scope = site != GuestMemory::ReadSite::Store ? PublishScope::Whole : PublishScope::PartialUnits;
const bool waited = completionDepth != 0;
const bool waited = completionDepth() != 0;
bool published = false;
// The classification is made before the store (the store changes what it measures); profile only.
StorageTexture::AccessClassification classification{};
@@ -1082,7 +1087,7 @@ void FlushForAccess(std::uint64_t address, std::size_t bytes) {
} else {
stored = StorageTexture::FlushPending(address, bytes, nullptr, "memory access", scope, &published, waited);
}
if (stored || published || (completionDepth == 0 && SnapshotOverlaps(address, bytes))) {
if (stored || published || (completionDepth() == 0 && SnapshotOverlaps(address, bytes))) {
// Stores into imported memory were only recorded; the CPU is about to read them. The wait
// targets the batch holding them (the open one: SyncThrough submits it) and runs with the
// mutex released when this acquisition is the outermost; a nested hook waits locked through
@@ -1094,7 +1099,7 @@ void FlushForAccess(std::uint64_t address, std::size_t bytes) {
if (auto* recorder = Recorder::Active(); recorder != nullptr) {
const RecordedStoreSyncScope attribution(*recorder, address, bytes, classification, stored, HookSyncProfiled() ? RecordedStoreKey() : HookSyncKey{});
Recorder::CountSync(2);
if (HookFullSync() || completionDepth != 0) recorder->Sync();
if (HookFullSync() || completionDepth() != 0) recorder->Sync();
else recorder->SyncThrough(address, bytes, true);
}
}
@@ -1286,10 +1291,9 @@ void TeardownCheckpointMarkers() noexcept {
}
struct Recorder::ProgressWatcher {
std::mutex mutex;
std::condition_variable wake;
std::uint64_t submitted = 0;
bool stop = false;
std::atomic<std::uint64_t> submitted{0};
std::atomic<bool> stop{false};
std::atomic<std::uint32_t> wakes{0};
std::thread thread;
ProgressWatcher(VkDevice device, VkSemaphore timeline, PFN_vkWaitSemaphoresKHR waitSemaphores, PFN_vkGetSemaphoreCounterValueKHR counterValue) {
@@ -1297,10 +1301,11 @@ struct Recorder::ProgressWatcher {
CpuTopology::PinHelperThread("GPU progress watcher");
std::uint64_t seen = 0;
for (;;) {
{
std::unique_lock lock(mutex);
wake.wait(lock, [&] { return stop || submitted > seen; });
if (stop) return;
const auto token = wakes.load(std::memory_order_acquire);
if (stop.load(std::memory_order_acquire)) return;
if (submitted.load(std::memory_order_acquire) <= seen) {
wakes.wait(token, std::memory_order_acquire);
continue;
}
const std::uint64_t target = seen + 1;
VkSemaphoreWaitInfoKHR info{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO_KHR};
@@ -1322,19 +1327,15 @@ struct Recorder::ProgressWatcher {
}
void Submitted(std::uint64_t serial) {
{
std::lock_guard lock(mutex);
submitted = serial;
}
wake.notify_one();
submitted.store(serial, std::memory_order_release);
wakes.fetch_add(1, std::memory_order_release);
wakes.notify_one();
}
~ProgressWatcher() {
{
std::lock_guard lock(mutex);
stop = true;
}
wake.notify_one();
stop.store(true, std::memory_order_release);
wakes.fetch_add(1, std::memory_order_release);
wakes.notify_one();
thread.join();
}
};
@@ -1807,7 +1808,7 @@ void Recorder::AnnounceSyncSite(const void* site) {
}
double Recorder::ThreadWaitedMs() {
return threadWaitedMs;
return HostThreadSlot<double, ThreadWaitedSlot>::Get();
}
std::uint64_t Recorder::ReapsWithWork() {
@@ -4355,7 +4356,7 @@ void Recorder::FlushDeferredReleases() {
void Recorder::SyncThrough(std::uint64_t address, std::size_t bytes, bool waitUnlocked) {
if (bytes == 0) return;
const auto end = address + bytes;
if (completionDepth != 0 && !CompletionStoreSyncs()) {
if (completionDepth() != 0 && !CompletionStoreSyncs()) {
// A store made by a completion action (a copied buffer's write-back, GuestBufferMemory::
// WriteBack) reached the flush hook, and a batch still in flight notes the range. Every
// batch in flight now was recorded after the completing one (finish runs front to back),
@@ -4371,8 +4372,8 @@ void Recorder::SyncThrough(std::uint64_t address, std::size_t bytes, bool waitUn
++holdCounters.completionSyncsSkipped;
return;
}
if (completionDepth != 0) ++holdCounters.completionSyncsWaited;
const auto completionWaitStart = completionDepth != 0 && DrawProfiled() ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
if (completionDepth() != 0) ++holdCounters.completionSyncsWaited;
const auto completionWaitStart = completionDepth() != 0 && DrawProfiled() ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
struct CompletionWait {
std::chrono::steady_clock::time_point start;
~CompletionWait() {
@@ -4385,7 +4386,7 @@ void Recorder::SyncThrough(std::uint64_t address, std::size_t bytes, bool waitUn
const void* site = announcedSite != nullptr ? announcedSite : __builtin_return_address(0);
if (syncThroughUnlocked(address, end, source, site)) return;
// A completion-store wait (kill switch above) is already counted as 'waited'.
if (completionDepth == 0) ++holdCounters.hookLockedWaits;
if (completionDepth() == 0) ++holdCounters.hookLockedWaits;
}
if (!SyncThroughEnabled() || (open != nullptr && overlaps(*open, address, end))) {
// The announced site (or this call's caller) names the sync, not this function.
@@ -4731,8 +4732,8 @@ void Recorder::finish(std::unique_ptr<Batch> batch, bool wait, int source, bool
const auto completionStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
{
struct InCompletion {
InCompletion() { ++completionDepth; }
~InCompletion() { --completionDepth; }
InCompletion() { HostThreadSlot<int, CompletionDepthSlot>::Set(completionDepth() + 1); }
~InCompletion() { HostThreadSlot<int, CompletionDepthSlot>::Set(completionDepth() - 1); }
} inCompletion;
for (auto& action : batch->completions) {
try {
@@ -28,6 +28,7 @@ namespace AgcDriver::Graphics {
Sampler::Sampler(const Context& context, const GuestSamplerResource& descriptor) : context(context) {
Validate(context, descriptor);
forcesDegamma = descriptor.forceDegamma;
disablesDegamma = descriptor.disableDegamma;
VkSamplerCreateInfo info{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
VkSamplerReductionModeCreateInfoEXT reduction{VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT, nullptr, descriptor.reductionMode};
@@ -126,6 +127,10 @@ namespace AgcDriver::Graphics {
bool Sampler::ForcesDegamma() const {
return forcesDegamma;
}
bool Sampler::DisablesDegamma() const {
return disablesDegamma;
}
bool Sampler::RequiresNonSeamlessCube() const {
return requiresNonSeamlessCube;
@@ -158,5 +163,14 @@ namespace AgcDriver::Graphics {
if (element < samplers.size() && samplers[element]->RequiresNonSeamlessCube()) Require(false, "a cube texture is sampled through a sampler that disables seamless cube filtering, which needs VK_EXT_non_seamless_cube_map");
}
}
void RequireDisablesDegammaOn(std::uint32_t guestFormat, std::uint64_t samplerMask, std::span<const std::shared_ptr<Sampler>> samplers) {
if (!IsSrgbTextureFormat(guestFormat)) return;
for (auto mask = samplerMask; mask != 0u; mask &= mask - 1u) {
const auto element = static_cast<std::uint32_t>(std::countr_zero(mask));
if (element < samplers.size() && samplers[element]->DisablesDegamma()) {
Require(false, "guest sampler descriptor disables degamma with an sRGB texture, which is not implemented");
}
}
}
}
@@ -22,7 +22,9 @@ namespace {
constexpr std::uint32_t computeNumThreadX = 0x207;
constexpr std::uint32_t computeNumThreadY = 0x208;
constexpr std::uint32_t computeNumThreadZ = 0x209;
constexpr std::uint32_t computePgmRsrc1 = 0x212;
constexpr std::uint32_t computePgmRsrc2 = 0x213;
constexpr std::uint32_t computePgmRsrc3 = 0x228;
constexpr std::uint32_t spiPsInputCntl0 = 0x191;
constexpr std::uint32_t spiPsInputEna = 0x1B3;
@@ -87,6 +89,10 @@ ShaderRecompiler::ShaderComputeStageInfo DecodeComputeStageInfo(const Registers&
scratchDwords = agcShader.scratch_size_dw_per_thread;
if (scratchDwords == 0) throw std::runtime_error("AGC graphics: COMPUTE_PGM_RSRC2.SCRATCH_EN with a zero scratch size");
}
NoteRegisterRead(RegisterBank::Shader, computePgmRsrc3);
const auto rsrc3 = shader.find(computePgmRsrc3);
const std::uint32_t sharedVgprBlocks = rsrc3 == shader.end() ? 0u : rsrc3->second & 0xfu;
const std::uint32_t granulatedVgprCount = sharedVgprBlocks == 0u ? 0u : read(shader, computePgmRsrc1, RegisterBank::Shader) & 0x3fu;
// Debug aid: APS5_LDS_SLACK=<dwords> grows every dispatch's LDS allocation by that much, to tell
// whether a program depends on addresses past its declared allocation.
static const std::uint32_t ldsSlack = [] { const char* text = std::getenv("APS5_LDS_SLACK"); return text ? static_cast<std::uint32_t>(std::strtoul(text, nullptr, 0)) : 0u; }();
@@ -97,7 +103,9 @@ ShaderRecompiler::ShaderComputeStageInfo DecodeComputeStageInfo(const Registers&
((rsrc2 >> 10u) & 0x1u) != 0,
((rsrc2 >> 11u) & 0x3u) + 1u,
{},
scratchDwords
scratchDwords,
granulatedVgprCount,
sharedVgprBlocks
};
}
@@ -2024,6 +2024,10 @@ TableState CurrentTableState() {
return {GuestMemory::ThreadCollectEpoch(), GuestMemory::UnwatchSerial(), GuestAllocations::GuestAllocationsGeneration_nid_postfix(), DepthSurfacesSerial()};
}
constexpr auto NoRepresentative = std::numeric_limits<std::uint32_t>::max();
std::vector<std::uint32_t> variantRepresentatives(VkDevice device, const ShaderRecompiler::DescriptorBinding& binding, std::uint64_t elementBase, std::uint64_t capacity);
struct ReusedTableElement {
TextureKey key{};
std::weak_ptr<Texture> texture;
@@ -2040,7 +2044,7 @@ struct ReusedTable {
std::uint64_t pendingSerial = 0;
std::vector<std::uint32_t> words;
std::vector<ShaderRecompiler::DescriptorImageShape> shapes;
std::vector<bool> depthCompare;
ShaderRecompiler::ElementFlags depthCompare;
std::vector<ReusedTableElement> elements;
std::vector<GuestMemory::UnchangedQuery> queries;
std::vector<std::pair<std::uint64_t, std::uint64_t>> ranges;
@@ -2901,7 +2905,7 @@ void VisitContentKey(const CompiledShader& shader, bool dataWords, bool movableB
visit(static_cast<std::uint32_t>(program.PipelineVariantId()));
visit(static_cast<std::uint32_t>(program.PipelineVariantId() >> 32u));
visit(static_cast<std::uint32_t>(program.bindings.size()));
const auto packBits = [&](const std::vector<bool>& bits) {
const auto packBits = [&](const ShaderRecompiler::ElementFlags& bits) {
visit(static_cast<std::uint32_t>(bits.size()));
std::uint32_t word = 0;
for (std::size_t i = 0; i < bits.size(); ++i) {
@@ -3723,6 +3727,7 @@ ShaderResources::OwnRefreshFallback ShaderResources::refreshOwnObjects(std::span
for (std::size_t element = 0; element < table.elementTextures.size(); ++element) {
const auto index = table.elementTextures[element];
if (index == std::numeric_limits<std::size_t>::max()) continue;
if (!table.representatives.empty() && table.representatives[element] != NoRepresentative) continue;
if (index != textureIndex++ || index >= textures.size()) return OwnRefreshFallback::Uncached;
const auto overlap = listed(index, false);
if (overlap == overlapping.end()) continue;
@@ -3914,8 +3919,10 @@ bool ShaderResources::revalidateFull(std::span<const CompiledShader> shaders, Pr
TextureCounts().tablesReused.fetch_add(1, std::memory_order_relaxed);
continue;
}
if (!table.representatives.empty() && table.representatives != variantRepresentatives(context.device, *images, table.elementBase, context.imageTableCapacity)) return false;
for (std::uint32_t element = 0; element < images->count; ++element) {
if (table.elementTextures[element] == std::numeric_limits<std::size_t>::max()) continue;
if (!table.representatives.empty() && table.representatives[element] != NoRepresentative) continue;
const auto raw = std::span<const std::uint32_t>(images->guestDescriptor).subspan(static_cast<std::size_t>(element) * 8u, 8u);
std::array<std::uint32_t, 8> narrowed{};
const auto words = firstLayerWords(raw, images->imageShapes.at(element), narrowed, false);
@@ -5249,6 +5256,7 @@ void ShaderResources::resolveImageBinding(const ShaderRecompiler::DescriptorBind
}
const bool forcedSrgb = ForcesDegammaOn(resource.format, binding.imageSamplers[element], shaderSamplers);
RequireNonSeamlessCube(resource.dimension == TextureDimension::kCube, binding.imageSamplers[element], shaderSamplers);
RequireDisablesDegammaOn(resource.format, binding.imageSamplers[element], shaderSamplers);
const bool depthCompare = !binding.imageDepthCompare.empty() && binding.imageDepthCompare.at(element);
const bool firstLayer = binding.imageShape == ShaderRecompiler::DescriptorImageShape::Image2D && (resource.dimension == TextureDimension::k2DArray || (depthCompare && resource.dimension == TextureDimension::k1DArray));
const bool depth1D = depthCompare && ((binding.imageShape == ShaderRecompiler::DescriptorImageShape::Image2D && resource.dimension == TextureDimension::k1D) || (binding.imageShape == ShaderRecompiler::DescriptorImageShape::Image2DArray && resource.dimension == TextureDimension::k1DArray));
@@ -5511,14 +5519,6 @@ void ShaderResources::addSamplerTable(const ShaderRecompiler::DescriptorBinding&
namespace {
constexpr auto NoRepresentative = std::numeric_limits<std::uint32_t>::max();
struct VariantSource {
GuestTextureResource resource;
std::uint64_t guestBytes;
bool firstLayer;
};
void noteVariantSurface(std::uint64_t address, std::size_t members, const GuestTextureResource& chosen, const char* rule) {
static std::mutex mutex;
static std::unordered_set<std::uint64_t> seen;
@@ -5550,7 +5550,7 @@ std::vector<std::uint32_t> variantRepresentatives(VkDevice device, const ShaderR
const FamilyKey key{resource.baseAddress, resource.pipeBankXor, resource.format, static_cast<std::uint32_t>(resource.tileMode), static_cast<std::uint32_t>(resource.dimension), resource.mipCount, resource.baseLevel, resource.lastLevel, resource.depthOrLastArray, resource.baseArray};
families[key].push_back({element, resource});
}
std::vector<std::uint32_t> representatives(binding.count, NoRepresentative);
std::vector<std::uint32_t> representatives;
for (const auto& [key, members] : families) {
const auto& first = members.front().resource;
const auto otherExtent = [&](const Member& member) { return member.resource.width != first.width || member.resource.height != first.height; };
@@ -5568,12 +5568,15 @@ std::vector<std::uint32_t> variantRepresentatives(VkDevice device, const ShaderR
if (chosen == members.end()) {
rule = "largest accessible";
std::uint64_t chosenBytes = 0;
std::uint64_t chosenExtent = 0;
for (auto member = members.begin(); member != members.end(); ++member) {
try {
const auto bytes = DescribeSurface(member->resource).guestBytes;
if (bytes <= chosenBytes || !GuestMemory::Accessible(reinterpret_cast<const void*>(member->resource.baseAddress), static_cast<std::size_t>(bytes))) continue;
const auto extent = static_cast<std::uint64_t>(member->resource.width) * member->resource.height;
if (bytes < chosenBytes || (bytes == chosenBytes && extent <= chosenExtent) || !GuestMemory::Accessible(reinterpret_cast<const void*>(member->resource.baseAddress), static_cast<std::size_t>(bytes))) continue;
chosen = member;
chosenBytes = bytes;
chosenExtent = extent;
} catch (const std::runtime_error&) {
}
}
@@ -5582,6 +5585,7 @@ std::vector<std::uint32_t> variantRepresentatives(VkDevice device, const ShaderR
for (const auto& member : members) {
if (member.resource.width == chosen->resource.width && member.resource.height == chosen->resource.height) continue;
if (binding.imageShapes.at(member.element) != binding.imageShapes.at(chosen->element) || binding.imageDepthCompare.at(member.element) != binding.imageDepthCompare.at(chosen->element)) continue;
if (representatives.empty()) representatives.assign(binding.count, NoRepresentative);
representatives[member.element] = chosen->element;
}
noteVariantSurface(first.baseAddress, members.size(), chosen->resource, rule);
@@ -5620,11 +5624,12 @@ void ShaderResources::resolveImageTables() {
table.elementTextures[element] = textures.size() - 1u;
item->imageAllocations[static_cast<std::size_t>(table.elementBase) + element] = textures.size() - 1u;
};
const auto bind = [&](std::uint32_t element, std::span<const std::uint32_t> words, std::shared_ptr<Texture> texture, const GuestTextureResource& resource, std::uint64_t guestBytes, bool firstLayer) -> std::string {
const auto refusal = [&](std::uint32_t element, std::span<const std::uint32_t> words, const std::shared_ptr<Texture>& texture, const GuestTextureResource& resource) -> std::string {
try {
RequireFilterMinmax(context, texture->ViewFormat(), binding.imageSamplers.at(element), stageSamplers);
RequireBorderSwizzle(resource.bcSwizzle, binding.imageSamplers.at(element), stageSamplers);
RequireNonSeamlessCube(resource.dimension == TextureDimension::kCube, binding.imageSamplers.at(element), stageSamplers);
RequireDisablesDegammaOn(resource.format, binding.imageSamplers.at(element), stageSamplers);
const auto numeric = ShaderRecompiler::DepthBitsTextureWidth(words[1], words[3]) != 0u ? ShaderRecompiler::IrTextureNumericClass::Float : ShaderRecompiler::SampledTextureNumericClass(static_cast<ShaderRecompiler::IrBufferFormat>(resource.format));
const bool integerImage = numeric == ShaderRecompiler::IrTextureNumericClass::Uint || numeric == ShaderRecompiler::IrTextureNumericClass::Sint;
for (auto mask = binding.imageSamplers.at(element); mask != 0u; mask &= mask - 1u) {
@@ -5637,9 +5642,16 @@ void ShaderResources::resolveImageTables() {
Require(!SingleLevelSamplerWords(source.words, true, false).has_value(), "an image table entry paired with anisotropic ANISO_OVERRIDE needs dynamic texture mip-level pairing, which is not implemented");
}
} catch (const std::runtime_error& error) {
table.map[faults + element] = rejectTableElement(table, words, error.what());
return error.what();
}
return {};
};
const auto bind = [&](std::uint32_t element, std::span<const std::uint32_t> words, std::shared_ptr<Texture> texture, const GuestTextureResource& resource, std::uint64_t guestBytes, bool firstLayer) -> std::string {
auto message = refusal(element, words, texture, resource);
if (!message.empty()) {
table.map[faults + element] = rejectTableElement(table, words, message);
return message;
}
place(element, std::move(texture), resource, guestBytes, firstLayer);
return {};
};
@@ -5688,12 +5700,13 @@ void ShaderResources::resolveImageTables() {
ReusedTable fresh;
fresh.bound.assign(binding.count, {});
bool reusable = state.epoch != 0;
const auto representatives = binding.count > 1 ? variantRepresentatives(context.device, binding, table.elementBase, context.imageTableCapacity) : std::vector<std::uint32_t>{};
if (binding.count > 1) table.representatives = variantRepresentatives(context.device, binding, table.elementBase, context.imageTableCapacity);
const auto& representatives = table.representatives;
std::vector<bool> representativeNeeded(representatives.size(), false);
for (const auto representative : representatives) {
if (representative != NoRepresentative) representativeNeeded[representative] = true;
}
std::unordered_map<std::uint32_t, VariantSource> representativeSources;
std::unordered_map<std::uint32_t, GuestTextureResource> representativeSources;
std::vector<std::uint32_t> substitutes;
for (std::uint32_t element = 0; element < binding.count; ++element) {
const auto words = std::span<const std::uint32_t>(binding.guestDescriptor).subspan(static_cast<std::size_t>(element) * 8u, 8u);
@@ -5796,7 +5809,7 @@ void ShaderResources::resolveImageTables() {
fresh.ranges.emplace_back(resource.baseAddress, resource.baseAddress + guestBytes);
}
}
if (!representativeNeeded.empty() && representativeNeeded[element]) representativeSources.emplace(element, VariantSource{resource, guestBytes, firstLayer});
if (!representativeNeeded.empty() && representativeNeeded[element]) representativeSources.emplace(element, resource);
fresh.bound[element] = bind(element, sampledWords, std::move(texture), resource, guestBytes, firstLayer);
}
for (const auto element : substitutes) {
@@ -5804,13 +5817,15 @@ void ShaderResources::resolveImageTables() {
const auto words = std::span<const std::uint32_t>(binding.guestDescriptor).subspan(static_cast<std::size_t>(representative) * 8u, 8u);
const auto index = table.elementTextures[representative];
const auto source = representativeSources.find(representative);
if (index == std::numeric_limits<std::size_t>::max() || source == representativeSources.end()) {
table.map[faults + element] = rejectTableElement(table, words, "the dynamic-resolution variant this entry borrows from was rejected");
const auto message = index == std::numeric_limits<std::size_t>::max() || source == representativeSources.end() ? std::string("the dynamic-resolution variant this entry borrows from was rejected") : refusal(element, words, textures[index], source->second);
if (!message.empty()) {
table.map[faults + element] = rejectTableElement(table, words, message);
counters.variantRejected.fetch_add(1, std::memory_order_relaxed);
continue;
}
if (bind(element, words, textures[index], source->second.resource, source->second.guestBytes, source->second.firstLayer).empty()) counters.variantSubstituted.fetch_add(1, std::memory_order_relaxed);
else counters.variantRejected.fetch_add(1, std::memory_order_relaxed);
table.elementTextures[element] = index;
item->imageAllocations[static_cast<std::size_t>(table.elementBase) + element] = index;
counters.variantSubstituted.fetch_add(1, std::memory_order_relaxed);
}
counters.tablesResolved.fetch_add(1, std::memory_order_relaxed);
if (reusable && CurrentTableState() == state) {
Loaded 100 of 974 files, more files were not shown because too many files have changed in this diff. Show more