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

Keeps this branch's FormatVersion above main's 45 (#7831's barycentric bump).
This commit is contained in:
Yunus Shaikh committed 2026-10-22 23:12:25 -07:00
commit 4661f4bab5
578 files changed
+26151 -3269

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
name: Bug report
description: A title, homebrew or test stops, crashes or renders wrongly.
labels: [bug]
body:
- type: markdown
attributes:
value: |
Search open and closed issues and pull requests for the error text first, and comment there if it is already reported.
Game bring-up progress belongs in [Discussions](https://github.com/boykopovar/AnyPS5/discussions/categories/game-bring-up), one thread per title.
A slow scene or a change in speed goes into the [Performance report](https://github.com/boykopovar/AnyPS5/issues/new?template=performance.yml) form, which asks for a [performance trace](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/BUILD.md#performance-trace) and its `tools/trace_digest.py` digest.
- type: input
id: summary
attributes:
label: What happens
description: One sentence, with the exact error text if there is one.
validations:
required: true
- type: input
id: title
attributes:
label: Title, test or build step
description: Title ID and content version (for example PPSAxxxxx 01.000.000), a homebrew with its source, the ctest name, or the build step that fails.
validations:
required: true
- type: input
id: commit
attributes:
label: AnyPS5 commit
description: The `main` commit that was built, or the release that was used, and any pull requests merged on top.
validations:
required: true
- type: input
id: system
attributes:
label: System
description: OS, GPU and driver version, and the compiler if you built it yourself.
placeholder: Arch Linux, GCC 16.2.1, RTX 5080 (NVIDIA 615.78.08)
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: The commands that were run, environment variables included, and how long it takes to stop.
validations:
required: true
- type: textarea
id: log
attributes:
label: Log
description: The lines around the stop.
render: text
validations:
required: true
- type: textarea
id: notes
attributes:
label: What was checked
description: Other devices or commits tried, and whether it is the same every run. Attach the full log and screenshots here.
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: Game bring-up
url: https://github.com/boykopovar/AnyPS5/discussions/categories/game-bring-up
about: Progress of one title, one thread per title ID
- name: Question
url: https://github.com/boykopovar/AnyPS5/discussions/categories/q-a
about: Building, converting and running
+117
View File
@@ -0,0 +1,117 @@
name: Windows MSYS2
on:
schedule:
- cron: '23 8 * * *'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: windows-msys2-${{ github.ref }}
cancel-in-progress: true
env:
CONFIGURE: >-
-G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON
-DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++
-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
jobs:
windows-msys2:
runs-on: windows-latest
timeout-minutes: 45
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.sha }}
persist-credentials: false
- id: submodules
name: Key the submodules on their commits
run: |
echo "key=$(git ls-files -s | awk '$1 == "160000" { print $2, $4 }' | cat - .gitmodules | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT"
echo "ffmpeg=$(git rev-parse HEAD:3rdparty/ffmpeg-core)" >> "$GITHUB_OUTPUT"
- id: submodule-cache
uses: actions/cache/restore@v6
with:
path: ${{ runner.temp }}/submodule-gitdirs.tar
key: submodule-gitdirs-${{ runner.os }}-${{ steps.submodules.outputs.key }}
- name: Check out the submodules
run: |
if [ -f "$RUNNER_TEMP/submodule-gitdirs.tar" ]; then tar --force-local -xf "$RUNNER_TEMP/submodule-gitdirs.tar"; fi
git submodule update --init --recursive --depth 1 --jobs 8
- if: steps.submodule-cache.outputs.cache-hit != 'true'
run: tar --force-local -cf "$RUNNER_TEMP/submodule-gitdirs.tar" .git/modules
- if: steps.submodule-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v6
continue-on-error: true
with:
path: ${{ runner.temp }}/submodule-gitdirs.tar
key: submodule-gitdirs-${{ runner.os }}-${{ steps.submodules.outputs.key }}
- name: Use the CA bundle of Git for Windows
run: |
for prefix in ucrt64 mingw64; do
bundle="C:/Program Files/Git/$prefix/etc/ssl/certs/ca-bundle.crt"
if [ -f "$bundle" ]; then echo "SSL_CERT_FILE=$bundle" >> "$GITHUB_ENV"; exit 0; fi
done
echo "::error::No CA bundle found in Git for Windows"; exit 1
- id: msys2
uses: msys2/setup-msys2@v2
with:
msystem: UCRT64
update: true
install: >-
mingw-w64-ucrt-x86_64-gcc
mingw-w64-ucrt-x86_64-cmake
mingw-w64-ucrt-x86_64-ninja
- shell: pwsh
env:
MSYS2_LOCATION: ${{ steps.msys2.outputs.msys2-location }}
run: Add-Content -LiteralPath $env:GITHUB_PATH -Value "$env:MSYS2_LOCATION\ucrt64\bin"
- uses: hendrikmuhs/ccache-action@v1.2.24
with:
key: windows-msys2
save: ${{ github.ref == 'refs/heads/main' }}
evict-old-files: job
- id: ffmpeg-cache
uses: actions/cache/restore@v6
with:
path: build/externals
key: ffmpeg-${{ runner.os }}-${{ steps.submodules.outputs.ffmpeg }}
- shell: cmd
run: cmake -S . -B build %CONFIGURE% "-DANYPS5_AGC_EXECUTION_TESTS=F16ToF32Unpack;F64FmaSubnormals;RegistrationPrepareShutdown"
- if: steps.ffmpeg-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v6
continue-on-error: true
with:
path: build/externals
key: ${{ steps.ffmpeg-cache.outputs.cache-primary-key }}
- name: Check that every test executable is registered with ctest
shell: cmd
run: python tools/check_test_registration.py build
- shell: cmd
run: cmake --build build
- shell: cmd
run: cmake --build build --target libs
- shell: cmd
working-directory: build
run: ctest --output-on-failure --timeout 120 --parallel 4 --output-log ctest.log --output-junit ctest.xml
- run: python tools/check_skips.py build/ctest.xml --job windows
- name: Report tests slower than 30 s
if: ${{ !cancelled() }}
run: |
[ -f build/ctest.log ] || exit 0
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"] }' build/ctest.log
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with:
name: windows-msys2-tests
path: |
build/ctest.log
build/ctest.xml
if-no-files-found: ignore
+6
View File
@@ -52,3 +52,9 @@
[submodule "3rdparty/vgmstream"]
path = 3rdparty/vgmstream
url = https://github.com/vgmstream/vgmstream.git
[submodule "3rdparty/ogg"]
path = 3rdparty/ogg
url = https://github.com/xiph/ogg.git
[submodule "3rdparty/vorbis"]
path = 3rdparty/vorbis
url = https://github.com/xiph/vorbis.git
Vendored Submodule
+1
Submodule 3rdparty/ogg added at be05b13e98.
Vendored Submodule
+1
Submodule 3rdparty/vorbis added at 0657aee69d.
+1
View File
@@ -107,6 +107,7 @@ if(BUILD_TESTING)
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/tests/RequestSerializerTests.cpp
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp)
target_include_directories(request_serializer_tests PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/core/libs
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ControlFlow/include)
add_test(NAME request_serializer COMMAND request_serializer_tests)
+84 -6
View File
@@ -39,9 +39,16 @@ if(MINGW)
check_cxx_source_compiles("#ifdef __USING_SJLJ_EXCEPTIONS__\n#error\n#endif\nint main() { return 0; }" ANYPS5_MINGW_DWARF_EXCEPTIONS)
unset(CMAKE_REQUIRED_FLAGS)
if(NOT ANYPS5_MINGW_DWARF_EXCEPTIONS)
message(FATAL_ERROR "${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION} selects SjLj exceptions with -fno-asynchronous-unwind-tables; the libraries need DWARF unwinding. Use the MinGW-w64 toolchain listed in docs/dev/BUILD.md.")
check_cxx_source_compiles("#if !defined(__SEH__) || defined(__USING_SJLJ_EXCEPTIONS__)\n#error\n#endif\n[[gnu::sysv_abi, gnu::noinline]] void Throw() { throw 1; }\n[[gnu::sysv_abi, gnu::noinline]] int Catch() { try { Throw(); } catch (int value) { return value; } return 0; }\nint main() { return Catch() != 1; }" ANYPS5_MINGW_SYSV_SEH_EXCEPTIONS)
if(NOT ANYPS5_MINGW_SYSV_SEH_EXCEPTIONS)
message(FATAL_ERROR "The Windows libraries require DWARF exceptions or GCC with System V ABI SEH support. Use the toolchains listed in docs/dev/BUILD.md.")
endif()
add_library(windows_seh_personalities OBJECT ${CMAKE_CURRENT_SOURCE_DIR}/prx/libc/src/specifics/windows/SehPersonalities.cpp)
target_link_options(windows_seh_personalities INTERFACE LINKER:--undefined=LibcSehPersonalities_nid_no_patch)
link_libraries(windows_seh_personalities)
else()
add_compile_options(-fno-asynchronous-unwind-tables)
endif()
add_compile_options(-fno-asynchronous-unwind-tables)
endif()
function(configure_windows_unwind target)
@@ -50,7 +57,7 @@ function(configure_windows_unwind target)
message(FATAL_ERROR "Windows DWARF unwinding requires objcopy")
endif()
add_custom_command(TARGET ${target} POST_BUILD
COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram "$<TARGET_FILE:${target}>"
COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:${target}>"
VERBATIM
)
endif()
@@ -211,7 +218,7 @@ if(TARGET mimalloc)
target_compile_features(pe_import_first PRIVATE cxx_std_20)
if(MINGW)
target_compile_options(pe_import_first PRIVATE -fasynchronous-unwind-tables)
target_link_options(pe_import_first PRIVATE -static -static-libgcc -static-libstdc++)
target_link_options(pe_import_first PRIVATE -municode -static -static-libgcc -static-libstdc++)
endif()
add_custom_command(
OUTPUT ${PATCHED_DIR}/mimalloc.dll
@@ -241,6 +248,15 @@ if(BUILD_TESTING)
set_tests_properties(guest_posix_scalar_io PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel>")
endif()
add_test_executable(guest_kernel_sys_sdk_version_tests tests/GuestKernelSysSdkVersion.cpp)
target_include_directories(guest_kernel_sys_sdk_version_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_kernel_sys_sdk_version_tests PRIVATE libkernel_sys libkernel libc)
configure_windows_unwind(guest_kernel_sys_sdk_version_tests)
add_test(NAME guest_kernel_sys_sdk_version COMMAND guest_kernel_sys_sdk_version_tests)
if(WIN32)
set_tests_properties(guest_kernel_sys_sdk_version PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
endif()
add_test_executable(nid_buffer_validation_tests nid/tests/BufferValidation.cpp)
target_include_directories(nid_buffer_validation_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/nid/include)
target_compile_features(nid_buffer_validation_tests PRIVATE cxx_std_20)
@@ -302,18 +318,34 @@ if(BUILD_TESTING)
target_link_libraries(guest_kernel_sys_tests PRIVATE libkernel_sys libkernel libc)
configure_windows_unwind(guest_kernel_sys_tests)
add_test(NAME guest_kernel_sys COMMAND guest_kernel_sys_tests)
add_test_executable(guest_kernel_sys_thread_defaults_tests tests/GuestKernelSysThreadDefaults.cpp)
target_include_directories(guest_kernel_sys_thread_defaults_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_kernel_sys_thread_defaults_tests PRIVATE libkernel_sys libkernel libc)
configure_windows_unwind(guest_kernel_sys_thread_defaults_tests)
add_test(NAME guest_kernel_sys_thread_defaults COMMAND guest_kernel_sys_thread_defaults_tests)
set_tests_properties(guest_kernel_sys_thread_defaults PROPERTIES TIMEOUT 20)
if(Python3_Interpreter_FOUND)
add_test(NAME nid_verneed COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_verneed.py $<TARGET_FILE:nid_patcher>)
endif()
if(WIN32)
set_tests_properties(guest_kernel_sys PROPERTIES ENVIRONMENT_MODIFICATION
set_tests_properties(guest_kernel_sys guest_kernel_sys_thread_defaults PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
endif()
if(APPLE)
add_subdirectory(tests/write_watch)
add_subdirectory(tests/guest_arena)
endif()
add_test_executable(guest_kernel_sys_module_internal_tests tests/GuestKernelSysModuleInternal.cpp)
target_include_directories(guest_kernel_sys_module_internal_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_kernel_sys_module_internal_tests PRIVATE libkernel_sys libkernel libc)
configure_windows_unwind(guest_kernel_sys_module_internal_tests)
add_test(NAME guest_kernel_sys_module_internal COMMAND guest_kernel_sys_module_internal_tests)
set_tests_properties(guest_kernel_sys_module_internal PROPERTIES TIMEOUT 20)
if(WIN32)
set_tests_properties(guest_kernel_sys_module_internal PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
endif()
if(WIN32)
add_test_executable(windows_write_watch_tests tests/WindowsWriteWatch.cpp)
target_include_directories(windows_write_watch_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
@@ -327,6 +359,9 @@ if(BUILD_TESTING)
if(WIN32)
add_test_executable(undeliverable_host_exception_tests tests/UndeliverableHostException.cpp)
if(MINGW)
target_compile_options(undeliverable_host_exception_tests PRIVATE -fno-asynchronous-unwind-tables -fno-exceptions)
endif()
add_dependencies(undeliverable_host_exception_tests libc)
add_test(NAME undeliverable_host_exception COMMAND undeliverable_host_exception_tests $<TARGET_FILE:libc>)
set_tests_properties(undeliverable_host_exception PROPERTIES
@@ -362,6 +397,26 @@ if(BUILD_TESTING)
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceVoice>")
endif()
add_test_executable(guest_gnm_neo_retail_tests tests/GuestGnmNeoRetail.cpp)
target_include_directories(guest_gnm_neo_retail_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_gnm_neo_retail_tests PRIVATE libSceGnmDriverForNeoMode libc)
configure_windows_unwind(guest_gnm_neo_retail_tests)
add_test(NAME guest_gnm_neo_retail COMMAND guest_gnm_neo_retail_tests)
if(WIN32)
set_tests_properties(guest_gnm_neo_retail PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceGnmDriverForNeoMode>")
endif()
add_test_executable(guest_vr_tracker_devices_tests tests/GuestVrTrackerDevices.cpp)
target_include_directories(guest_vr_tracker_devices_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_vr_tracker_devices_tests PRIVATE libSceVrTracker libc)
configure_windows_unwind(guest_vr_tracker_devices_tests)
add_test(NAME guest_vr_tracker_devices COMMAND guest_vr_tracker_devices_tests)
if(WIN32)
set_tests_properties(guest_vr_tracker_devices PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceVrTracker>")
endif()
add_test_executable(guest_move_tests tests/GuestMove.cpp)
target_include_directories(guest_move_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_move_tests PRIVATE libSceMove libc)
@@ -396,6 +451,17 @@ if(BUILD_TESTING)
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceHttp>")
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)
configure_windows_unwind(guest_entitlements_tests)
add_test(NAME guest_entitlements COMMAND guest_entitlements_tests)
add_test(NAME guest_entitlements_missing COMMAND guest_entitlements_tests missing)
if(WIN32)
set_tests_properties(guest_entitlements guest_entitlements_missing PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceNpEntitlementAccess>")
endif()
add_test_executable(guest_signin_dialog_tests tests/GuestSigninDialog.cpp)
target_include_directories(guest_signin_dialog_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_signin_dialog_tests PRIVATE libSceSigninDialog libc)
@@ -595,6 +661,16 @@ if(BUILD_TESTING)
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceNpCppWebApi>")
endif()
add_test_executable(guest_np_cpp_web_api_signed_out_tests tests/GuestNpCppWebApiSignedOut.cpp)
target_include_directories(guest_np_cpp_web_api_signed_out_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_np_cpp_web_api_signed_out_tests PRIVATE libSceNpCppWebApi libc)
configure_windows_unwind(guest_np_cpp_web_api_signed_out_tests)
add_test(NAME guest_np_cpp_web_api_signed_out COMMAND guest_np_cpp_web_api_signed_out_tests)
if(WIN32)
set_tests_properties(guest_np_cpp_web_api_signed_out PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceNpCppWebApi>")
endif()
add_test_executable(savedata_core_write_replacement_tests tests/SaveDataWriteReplacement.cpp)
target_include_directories(savedata_core_write_replacement_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(savedata_core_write_replacement_tests PRIVATE libSceSaveData)
@@ -687,9 +763,11 @@ if(BUILD_TESTING)
add_test_executable(guest_vorbis_dec_tests tests/GuestVorbisDec.cpp)
target_include_directories(guest_vorbis_dec_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_vorbis_dec_tests PRIVATE libSceVorbisDec libc)
target_compile_definitions(guest_vorbis_dec_tests PRIVATE OV_EXCLUDE_STATIC_CALLBACKS)
target_link_libraries(guest_vorbis_dec_tests PRIVATE libSceVorbisDec vorbisenc vorbisfile vorbis ogg libc)
configure_windows_unwind(guest_vorbis_dec_tests)
add_test(NAME guest_vorbis_dec COMMAND guest_vorbis_dec_tests)
set_tests_properties(guest_vorbis_dec PROPERTIES TIMEOUT 30)
if(WIN32)
set_tests_properties(guest_vorbis_dec PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceVorbisDec>")
+4 -3
View File
@@ -5,6 +5,7 @@
#include <cctype>
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <stdexcept>
@@ -78,16 +79,16 @@ void MoveImportFirst(std::vector<unsigned char>& bytes, const std::string& dll)
for (std::size_t index = 0; index < descriptors.size(); ++index) std::memcpy(bytes.data() + directory + index * DescriptorBytes, descriptors[index].data(), DescriptorBytes);
}
void MoveImportFirstInFile(const std::string& path, const std::string& dll) {
void MoveImportFirstInFile(const std::filesystem::path& path, const std::string& dll) {
std::vector<unsigned char> bytes;
{
std::ifstream input(path, std::ios::binary);
if (!input) throw std::runtime_error("cannot open " + path);
if (!input) throw std::runtime_error("cannot open " + path.string());
bytes.assign(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>());
}
MoveImportFirst(bytes, dll);
std::ofstream output(path, std::ios::binary | std::ios::trunc);
if (!output || !output.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()))) throw std::runtime_error("cannot write " + path);
if (!output || !output.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()))) throw std::runtime_error("cannot write " + path.string());
}
}
+2 -1
View File
@@ -1,13 +1,14 @@
#ifndef CORE_LIBS_ALLOCATOR_PEIMPORTFIRST_HPP
#define CORE_LIBS_ALLOCATOR_PEIMPORTFIRST_HPP
#include <filesystem>
#include <string>
#include <vector>
namespace Allocator {
void MoveImportFirst(std::vector<unsigned char>& image, const std::string& dll);
void MoveImportFirstInFile(const std::string& path, const std::string& dll);
void MoveImportFirstInFile(const std::filesystem::path& path, const std::string& dll);
}
+27 -7
View File
@@ -2,17 +2,37 @@
#include <cstdio>
#include <exception>
#include <filesystem>
#include <string>
int main(int argc, char** argv) {
if (argc != 3) {
std::fprintf(stderr, "usage: pe_import_first <file> <dll>\n");
return 2;
}
namespace {
int Usage() {
std::fprintf(stderr, "usage: pe_import_first <file> <dll>\n");
return 2;
}
int Run(const std::filesystem::path& file, const std::string& dll) {
try {
Allocator::MoveImportFirstInFile(argv[1], argv[2]);
Allocator::MoveImportFirstInFile(file, dll);
} catch (const std::exception& error) {
std::fprintf(stderr, "pe_import_first: %s: %s\n", argv[1], error.what());
std::fprintf(stderr, "pe_import_first: %s: %s\n", file.string().c_str(), error.what());
return 1;
}
return 0;
}
}
#ifdef _WIN32
int wmain(int argc, wchar_t** argv) {
if (argc != 3) return Usage();
const auto dll = std::filesystem::path(argv[2]).u8string();
return Run(argv[1], std::string(dll.begin(), dll.end()));
}
#else
int main(int argc, char** argv) {
if (argc != 3) return Usage();
return Run(argv[1], argv[2]);
}
#endif
@@ -113,7 +113,7 @@ void movesTheNamedImportFirst() {
void movesTheImportInAFile(const std::filesystem::path& directory) {
const auto path = directory / "moved.dll";
writeFile(path, image({"kernel32.dll", "mimalloc-redirect.dll"}));
Allocator::MoveImportFirstInFile(path.string(), "mimalloc-redirect.dll");
Allocator::MoveImportFirstInFile(path, "mimalloc-redirect.dll");
const auto moved = readFile(path);
require(importName(moved, 0) == "mimalloc-redirect.dll" && importName(moved, 1) == "kernel32.dll", "the file's import did not move first");
}
@@ -122,7 +122,7 @@ void failsWithoutTouchingTheFile(const std::filesystem::path& directory, const s
const auto path = directory / (what + ".dll");
writeFile(path, bytes);
try {
Allocator::MoveImportFirstInFile(path.string(), "mimalloc-redirect.dll");
Allocator::MoveImportFirstInFile(path, "mimalloc-redirect.dll");
} catch (const std::exception& error) {
require(std::string(error.what()).find(expected) != std::string::npos, what + ": failed with another error: " + error.what());
require(readFile(path) == bytes, what + ": the file changed although the move failed");
@@ -134,7 +134,8 @@ void failsWithoutTouchingTheFile(const std::filesystem::path& directory, const s
}
int main() {
const auto directory = std::filesystem::temp_directory_path() / ("aps5-pe-import-first-" + std::to_string(std::random_device{}()));
auto directory = std::filesystem::temp_directory_path() / std::filesystem::path(u8"aps5-pe-import-first-a\u00e7\u00e3o-\u65e5\u672c-");
directory += std::to_string(std::random_device{}());
try {
std::filesystem::create_directories(directory);
movesTheNamedImportFirst();
+13
View File
@@ -267,6 +267,19 @@ if(BUILD_TESTING)
endif()
endif()
add_test_executable(agc_instrumentation_query_size_tests EXCLUDE_FROM_ALL tests/InstrumentationQuerySize.cpp)
target_include_directories(agc_instrumentation_query_size_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_instrumentation_query_size_tests PRIVATE libSceAgc libc)
configure_windows_unwind(agc_instrumentation_query_size_tests)
if(BUILD_TESTING)
set_target_properties(agc_instrumentation_query_size_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_instrumentation_query_size_tests COMMAND agc_instrumentation_query_size_tests)
if(WIN32)
set_tests_properties(agc_instrumentation_query_size_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_context_state_size_tests EXCLUDE_FROM_ALL tests/ContextStateSize.cpp)
target_include_directories(agc_context_state_size_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_context_state_size_tests PRIVATE libSceAgc libc)
@@ -22,13 +22,12 @@ std::uint32_t* APS5_VABI sceAgcDcbGetLodStats(CommandBuffer* buf, std::uint8_t c
}
std::uint32_t APS5_VABI sceAgcDcbBeginOcclusionQueryGetSize(std::int32_t queryType) {
NotImplemented_nid_no_patch(__func__);
return 0;
if (queryType == 1) return 0x120u;
return queryType == 0 ? 0x10u : 0u;
}
std::uint32_t APS5_VABI sceAgcDcbEndOcclusionQueryGetSize() {
NotImplemented_nid_no_patch(__func__);
return 0;
return 0x10u;
}
}
@@ -1,9 +1,16 @@
#include "prx/libSceAgc/Misc/include/Debug.hpp"
#include <atomic>
#include <cstdint>
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
namespace {
std::atomic<std::uint32_t> shaderInstrumentation{0};
}
extern "C" {
int APS5_VABI sceAgcDebugRaiseException(std::uint32_t exceptionId) {
@@ -11,4 +18,13 @@ int APS5_VABI sceAgcDebugRaiseException(std::uint32_t exceptionId) {
return 0;
}
int APS5_VABI sceAgcSetShaderInstrumentation(std::uint32_t flags) {
shaderInstrumentation.store(flags, std::memory_order_relaxed);
return 0;
}
std::uint32_t APS5_VABI sceAgcGetShaderInstrumentation() {
return shaderInstrumentation.load(std::memory_order_relaxed);
}
}
@@ -53,12 +53,9 @@ std::uint32_t CreateInterpolantValueSplitF16(std::uint32_t psWord, const ShaderS
: CreateInterpolantValue(psWord, gsSemantic);
}
std::uint32_t UpdateInterpolantValue(std::uint32_t psWord, const ShaderSemantic* gsSemantic) {
const std::uint32_t f16 = (psWord >> 20u) & 0x3u;
if (f16 != 0 && f16 != InterpolantF16HiOnly && ((psWord >> 28u) & 0x3u) != ((psWord >> 30u) & 0x3u)) {
throw std::runtime_error(std::string(__func__) + ": DEFAULT_VAL of an f16 input with different low and high defaults is unknown");
}
return CreateInterpolantValueSplitF16(psWord, gsSemantic);
std::uint32_t CreateInterpolantValueFlatDefault(std::uint32_t psWord, const ShaderSemantic* gsSemantic) {
const std::uint32_t value = CreateInterpolantValue(psWord, gsSemantic);
return ((psWord & 0x00700000u) == 0x00400000u) ? (value | 0x00000020u) : value;
}
int CreateInterpolantMapping(const char* fn, ShaderRegister* regs, const Shader* gs, const Shader* ps, CreateInterpolantValueFn createValue, bool fillIdentityTail) {
@@ -132,7 +129,15 @@ int APS5_VABI sceAgcCreateInterpolantMapping_10000(ShaderRegister* regs, const S
}
int APS5_VABI sceAgcUpdateInterpolantMapping_10000(ShaderRegister* regs, const Shader* gs, const Shader* ps) {
return CreateInterpolantMapping(__func__, regs, gs, ps, UpdateInterpolantValue, false);
return CreateInterpolantMapping(__func__, regs, gs, ps, CreateInterpolantValueSplitF16, false);
}
int APS5_VABI sceAgcCreateInterpolantMapping_nid_postfix(ShaderRegister* regs, const Shader* gs, const Shader* ps) {
return CreateInterpolantMapping(__func__, regs, gs, ps, CreateInterpolantValueFlatDefault, true);
}
int APS5_VABI sceAgcUpdateInterpolantMapping_nid_postfix(ShaderRegister* regs, const Shader* gs, const Shader* ps) {
return CreateInterpolantMapping(__func__, regs, gs, ps, CreateInterpolantValueFlatDefault, false);
}
}
-10
View File
@@ -40,14 +40,4 @@ std::uint32_t* APS5_VABI sceAgcCbMemsetExclusive(CommandBuffer* buffer, void* de
return 0;
}
int APS5_VABI sceAgcSetShaderInstrumentation(std::uint32_t flags) {
NotImplemented_nid_no_patch(__func__);
return 0;
}
int APS5_VABI sceAgcGetShaderInstrumentation() {
NotImplemented_nid_no_patch(__func__);
return 0;
}
}
@@ -0,0 +1,48 @@
#include "prx/libc/include/general/VabiMacros.hpp"
#include "prx/libc/include/Shutdown.hpp"
#include <cstdint>
#include <cstdio>
#include <stdexcept>
extern "C" {
int APS5_VABI sceAgcSetShaderInstrumentation(std::uint32_t);
std::uint32_t APS5_VABI sceAgcGetShaderInstrumentation();
std::uint32_t APS5_VABI sceAgcDcbBeginOcclusionQueryGetSize(std::int32_t);
std::uint32_t APS5_VABI sceAgcDcbEndOcclusionQueryGetSize();
}
namespace {
void check(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
}
void testShaderInstrumentation() {
check(sceAgcGetShaderInstrumentation() == 0, "shader instrumentation starts cleared");
check(sceAgcSetShaderInstrumentation(0x80000005u) == 0, "setting shader instrumentation failed");
check(sceAgcGetShaderInstrumentation() == 0x80000005u, "shader instrumentation flags were not kept");
check(sceAgcSetShaderInstrumentation(0) == 0 && sceAgcGetShaderInstrumentation() == 0, "shader instrumentation was not cleared");
}
void testOcclusionQuerySizes() {
check(sceAgcDcbBeginOcclusionQueryGetSize(0) == 0x10u, "begin occlusion query size for type 0");
check(sceAgcDcbBeginOcclusionQueryGetSize(1) == 0x120u, "begin occlusion query size for type 1");
check(sceAgcDcbBeginOcclusionQueryGetSize(2) == 0, "begin occlusion query size for an unknown type");
check(sceAgcDcbEndOcclusionQueryGetSize() == 0x10u, "end occlusion query size");
}
}
int main() {
try {
testShaderInstrumentation();
testOcclusionQuerySizes();
LibcRunShutdown_nid_postfix();
std::puts("AGC shader instrumentation and occlusion query size tests passed");
return 0;
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
}
@@ -14,6 +14,8 @@
extern "C" int APS5_VABI sceAgcCreateInterpolantMapping_0100(ShaderRegister* regs, const Shader* gs, const Shader* ps);
extern "C" int APS5_VABI sceAgcCreateInterpolantMapping_10000(ShaderRegister* regs, const Shader* gs, const Shader* ps);
extern "C" int APS5_VABI sceAgcUpdateInterpolantMapping_10000(ShaderRegister* regs, const Shader* gs, const Shader* ps);
extern "C" int APS5_VABI sceAgcCreateInterpolantMapping_nid_postfix(ShaderRegister* regs, const Shader* gs, const Shader* ps);
extern "C" int APS5_VABI sceAgcUpdateInterpolantMapping_nid_postfix(ShaderRegister* regs, const Shader* gs, const Shader* ps);
namespace {
@@ -158,13 +160,46 @@ void testUpdateMapping() {
check(std::memcmp(create.data(), update.data(), written) == 0, "update differs from the split f16 mapping");
checkIdentity(create, static_cast<std::uint32_t>(inputs.size()), "unused interpolants are not the identity");
for (const std::uint32_t index : {1u, 3u}) {
inputs[index].default_value = 0;
update = filled();
expectFailure([&] { sceAgcUpdateInterpolantMapping_10000(update.data(), &gs, &ps); });
check(std::memcmp(update.data(), untouched.data(), sizeof(update)) == 0, "rejected update wrote registers");
inputs[index].default_value = inputs[index].default_value_hi;
inputs[1].default_value = 0;
inputs[3].default_value = 0;
update = filled();
check(sceAgcUpdateInterpolantMapping_10000(update.data(), &gs, &ps) == 0, "update with split f16 defaults failed");
check(update[1].value == 0x01380007u && update[3].value == 0x03680409u, "f16 DEFAULT_VAL does not come from the low default");
}
void testUnversionedMapping() {
std::array<ShaderSemantic, 5> inputs{
semantic(1, 0, 2), semantic(2, 0, 2), semantic(5, 0, 2), semantic(3, 0, 0), semantic(4, 0, 3)};
inputs[0].is_flat_shaded = 1;
inputs[0].default_value = 1;
inputs[0].default_value_hi = 3;
inputs[1].default_value_hi = 1;
inputs[2].is_flat_shaded = 1;
inputs[2].default_value_hi = 2;
inputs[3].is_flat_shaded = 1;
inputs[3].default_value = 2;
std::array<ShaderSemantic, 4> outputs{semantic(1, 7, 3), semantic(2, 4, 1), semantic(3, 9, 0), semantic(4, 2, 1)};
Shader gs{};
gs.output_semantics = outputs.data();
gs.num_output_semantics = static_cast<std::uint16_t>(outputs.size());
Shader ps{};
ps.input_semantics = inputs.data();
ps.num_input_semantics = static_cast<std::uint32_t>(inputs.size());
const std::array<std::uint32_t, 5> flatDefault{0x02680527u, 0x02380024u, 0x02580020u, 0x00000629u, 0x03180002u};
const std::size_t written = inputs.size() * sizeof(ShaderRegister);
const auto untouched = filled();
auto create = filled();
check(sceAgcCreateInterpolantMapping_nid_postfix(create.data(), &gs, &ps) == 0, "unversioned mapping failed");
for (std::uint32_t i = 0; i < inputs.size(); ++i) {
check(create[i].offset == ShaderRegs::SPI_PS_INPUT_CNTL_0 + i && create[i].value == flatDefault[i], "unversioned mapping changed");
}
checkIdentity(create, static_cast<std::uint32_t>(inputs.size()), "unused interpolants are not the identity");
auto update = filled();
check(sceAgcUpdateInterpolantMapping_nid_postfix(update.data(), &gs, &ps) == 0, "unversioned update failed");
check(std::memcmp(update.data(), create.data(), written) == 0, "unversioned update differs from its mapping");
check(std::memcmp(update.data() + inputs.size(), untouched.data(), sizeof(update) - written) == 0, "unversioned update wrote past its inputs");
}
void testRejections() {
@@ -208,8 +243,9 @@ int main() {
testIdentity();
testMapping();
testUpdateMapping();
testUnversionedMapping();
testRejections();
check(mappings == 7u && links == 5u, "mapping preparation call count changed");
check(mappings == 10u && links == 8u, "mapping preparation call count changed");
LibcRunShutdown_nid_postfix();
std::puts("AGC interpolant mapping tests passed");
return 0;
+76 -4
View File
@@ -433,6 +433,16 @@ if(MINGW OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
endif()
if(BUILD_TESTING)
add_test_executable(agc_driver_unsupported_diagnostics_tests tests/UnsupportedDiagnostics.cpp)
target_include_directories(agc_driver_unsupported_diagnostics_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_driver_unsupported_diagnostics_tests PRIVATE libSceAgcDriver)
configure_windows_unwind(agc_driver_unsupported_diagnostics_tests)
add_test(NAME agc_driver_unsupported_diagnostics COMMAND agc_driver_unsupported_diagnostics_tests)
if(WIN32)
set_tests_properties(agc_driver_unsupported_diagnostics PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceAgcDriver>")
endif()
add_test_executable(agc_driver_draw_program_trace_tests
tests/DrawProgramTrace.cpp
Execution/src/Driver/Draw/DrawProgramTrace.cpp
@@ -459,6 +469,16 @@ if(WIN32)
endif()
if(BUILD_TESTING)
add_test_executable(agc_driver_nop_data_packet_tests tests/NopDataWritePacket.cpp)
target_include_directories(agc_driver_nop_data_packet_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_driver_nop_data_packet_tests PRIVATE libSceAgcDriver)
configure_windows_unwind(agc_driver_nop_data_packet_tests)
add_test(NAME agc_driver_nop_data_packet COMMAND agc_driver_nop_data_packet_tests)
if(WIN32)
set_tests_properties(agc_driver_nop_data_packet PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test_executable(agc_frame_dump_io_tests tests/FrameDumpIo.cpp)
target_include_directories(agc_frame_dump_io_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_frame_dump_io_tests PRIVATE libc)
@@ -1653,9 +1673,17 @@ if(BUILD_TESTING)
ENVIRONMENT "APS5_PIN_WAIT_MS=2000" SKIP_RETURN_CODE 77 TIMEOUT 30)
set_tests_properties(agc_driver_unit_shadow_budget PROPERTIES
ENVIRONMENT "APS5_PIN_WAIT_MS=2000;APS5_UNIT_SHADOW_MIB=8" SKIP_RETURN_CODE 77 TIMEOUT 30)
add_test(NAME agc_recorder_completion_labels COMMAND agc_driver_recorder_tests --completion-labels-only)
set_tests_properties(agc_recorder_completion_labels PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30)
add_test(NAME agc_recorder_cmask COMMAND agc_driver_recorder_tests --cmask-only)
set_tests_properties(agc_recorder_cmask PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30)
add_test(NAME agc_recorder_cube COMMAND agc_driver_recorder_tests --cube-only)
set_tests_properties(agc_recorder_cube PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30)
if(WIN32)
set_tests_properties(agc_driver_host_import_lifetime agc_driver_host_import_mutation_race agc_driver_unit_shadow agc_driver_unit_shadow_budget PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
set_tests_properties(agc_recorder_completion_labels agc_recorder_cmask agc_recorder_cube PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
set_property(TEST agc_driver_host_import_lifetime APPEND PROPERTY ENVIRONMENT_MODIFICATION
"APS5_RELEASE_UNDER_LOCK=unset:" "APS5_RELEASE_ON_UNLOCK=unset:")
@@ -1982,6 +2010,7 @@ foreach(agcExecutionTestSource IN LISTS agcExecutionTestSources)
add_test_executable(${agcExecutionTest} EXCLUDE_FROM_ALL ${agcExecutionTestSource})
target_include_directories(${agcExecutionTest} PRIVATE
${LIBS_INCLUDE_DIR}
$<TARGET_PROPERTY:shader_recompiler_agc_driver,INTERFACE_INCLUDE_DIRECTORIES>
${CMAKE_SOURCE_DIR}/core/shader/recompiler
${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR}
${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR}
@@ -2043,13 +2072,23 @@ if(BUILD_TESTING)
add_test(NAME agc_driver_store_pending_identity COMMAND agc_driver_store_over_untracked_tests --pending-identity)
set_tests_properties(agc_driver_store_pending_identity PROPERTIES
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
add_test(NAME agc_driver_store_idle_results_wake COMMAND agc_driver_store_idle_results_tests --idle-epoch-wake)
set_tests_properties(agc_driver_store_idle_results_wake PROPERTIES
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
if(WIN32)
set_tests_properties(agc_driver_store_pending_identity PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
set_tests_properties(agc_driver_store_idle_results_wake PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
if(BUILD_TESTING)
add_test(NAME agc_driver_native_fmask COMMAND agc_driver_sample_multisample_target_tests --native-fmask)
set_tests_properties(agc_driver_native_fmask PROPERTIES TIMEOUT 30 ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
if(WIN32)
set_tests_properties(agc_driver_native_fmask PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test(NAME agc_driver_native_msaa_vertex_input COMMAND agc_driver_sample_multisample_target_tests --native-vertex-input)
set_tests_properties(agc_driver_native_msaa_vertex_input PROPERTIES
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
@@ -2321,11 +2360,28 @@ if(BUILD_TESTING)
--unset=APS5_TRACE_FRAMES --unset=APS5_TRACE_SECONDS --unset=APS5_TRACE_SUMMARY_EVERY
$<TARGET_FILE:agc_driver_draw_pipeline_trace_tests> disabled)
set_tests_properties(agc_driver_draw_pipeline_trace_disabled PROPERTIES ENVIRONMENT "APS5_PIPELINED_DRAWS=8" SKIP_RETURN_CODE 77 TIMEOUT 30)
add_test(NAME agc_driver_draw_finisher_trace COMMAND agc_driver_draw_pipeline_trace_tests finisher)
set_tests_properties(agc_driver_draw_finisher_trace PROPERTIES
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=8;APS5_TRACE_FRAMES=0:1;APS5_TRACE_EVENTS=64" SKIP_RETURN_CODE 77 TIMEOUT 30)
set_property(TEST agc_driver_draw_finisher_trace APPEND PROPERTY ENVIRONMENT_MODIFICATION
"APS5_TRACE_SECONDS=unset:" "APS5_TRACE_SUMMARY_EVERY=unset:")
add_test(NAME agc_driver_draw_finisher_trace_disabled COMMAND ${CMAKE_COMMAND} -E env
--unset=APS5_TRACE_FRAMES --unset=APS5_TRACE_SECONDS --unset=APS5_TRACE_SUMMARY_EVERY
$<TARGET_FILE:agc_driver_draw_pipeline_trace_tests> finisher-disabled)
set_tests_properties(agc_driver_draw_finisher_trace_disabled PROPERTIES ENVIRONMENT "APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=8" SKIP_RETURN_CODE 77 TIMEOUT 30)
if(WIN32)
set_tests_properties(agc_driver_draw_pipeline_trace_disabled PROPERTIES ENVIRONMENT_MODIFICATION
set_tests_properties(agc_driver_draw_pipeline_trace_disabled agc_driver_draw_finisher_trace agc_driver_draw_finisher_trace_disabled PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
set_tests_properties(agc_driver_queued_raw_shader PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_PIPELINED_DRAWS=8" TIMEOUT 30)
set(agcDrawPipelineTests agc_driver_draw_write_ranges agc_driver_draw_unsupported_buffer_type agc_driver_bda_span_reads agc_driver_copied_writer_copy agc_driver_image_table_reuse agc_driver_depth_storage_reuse agc_driver_staged_clear_sampled_read agc_driver_storage_write_back_overhang agc_driver_write_data_written_ahead agc_driver_gated_dispatch_capture agc_driver_buffer_load_store agc_driver_pipelined_dma agc_driver_pipelined_fill agc_driver_pipelined_predication_read agc_driver_pipelined_predicated_label_order agc_driver_pipelined_metadata_pass agc_driver_draw_cache_reuse agc_driver_draw_cache_relocation agc_driver_draw_data_hit_user_words agc_driver_finisher_label_order agc_driver_same_queue_label_wait agc_driver_unimported_label_order)
foreach(agcTestName IN LISTS agcDrawPipelineTests)
add_test(NAME ${agcTestName}_draw_pipeline COMMAND ${agcTestName}_tests)
set_tests_properties(${agcTestName}_draw_pipeline PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_DRAW_PIPELINE=1;APS5_PIPELINED_DRAWS=32;APS5_PIPELINE_DISPATCH=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
if(WIN32)
set_tests_properties(${agcTestName}_draw_pipeline PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endforeach()
add_test(NAME agc_driver_partially_resident_pending_stores COMMAND agc_driver_partially_resident_snapshot_tests --pending-stores)
set_tests_properties(agc_driver_multisample_readback PROPERTIES TIMEOUT 20)
foreach(agcReadbackCase IN ITEMS uint8 uint16 uint64 uint128 depth upload retile depth_retile)
@@ -2741,8 +2797,10 @@ if(BUILD_TESTING)
set_property(TEST agc_driver_draw_cache_reuse agc_driver_draw_cache_reuse_off APPEND PROPERTY ENVIRONMENT "APS5_VERIFY_DRAW_RECIPE=1" "APS5_VERIFY_REGISTER_KEYS=1")
add_test(NAME agc_driver_draw_data_hit_user_words_verify COMMAND agc_driver_draw_data_hit_user_words_tests)
set_tests_properties(agc_driver_draw_data_hit_user_words_verify PROPERTIES ENVIRONMENT "APS5_VERIFY_DRAW_DATA_HITS=1" SKIP_RETURN_CODE 77)
add_test(NAME agc_driver_draw_data_hit_user_words_refresh COMMAND agc_driver_draw_data_hit_user_words_tests)
set_tests_properties(agc_driver_draw_data_hit_user_words_refresh PROPERTIES ENVIRONMENT "APS5_DRAW_PIPELINE=1" SKIP_RETURN_CODE 77)
if(WIN32)
set_tests_properties(agc_driver_draw_cache_reuse_off agc_driver_draw_cache_reuse_verify agc_driver_draw_cache_reuse_inline agc_driver_draw_data_hit_user_words_verify PROPERTIES ENVIRONMENT_MODIFICATION
set_tests_properties(agc_driver_draw_cache_reuse_off agc_driver_draw_cache_reuse_verify agc_driver_draw_cache_reuse_inline agc_driver_draw_data_hit_user_words_verify agc_driver_draw_data_hit_user_words_refresh PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
@@ -2838,15 +2896,16 @@ if(BUILD_TESTING)
endif()
endforeach()
add_test(NAME agc_driver_shutdown_threads_joined COMMAND agc_driver_shutdown_threads_tests --joined)
add_test(NAME agc_driver_shutdown_threads_queued_prebuilds COMMAND agc_driver_shutdown_threads_tests --queued-prebuilds)
add_test(NAME agc_driver_shutdown_threads_compare_helpers COMMAND agc_driver_shutdown_threads_tests --compare-helpers)
add_test(NAME agc_driver_shutdown_threads_draw_committer COMMAND agc_driver_shutdown_threads_tests --draw-committer)
add_test(NAME agc_driver_shutdown_threads_shader_cache_writer COMMAND agc_driver_shutdown_threads_tests --shader-cache-writer)
add_test(NAME agc_driver_shutdown_threads_late_shader_cache COMMAND agc_driver_shutdown_threads_tests --late-shader-cache)
add_test(NAME agc_driver_shutdown_threads_async_log_held COMMAND agc_driver_shutdown_threads_tests --async-log-held)
add_test(NAME agc_driver_shutdown_threads_exit_after_start COMMAND agc_driver_shutdown_threads_tests --exit-after-start)
set_tests_properties(agc_driver_shutdown_threads_joined agc_driver_shutdown_threads_compare_helpers agc_driver_shutdown_threads_draw_committer agc_driver_shutdown_threads_shader_cache_writer agc_driver_shutdown_threads_late_shader_cache agc_driver_shutdown_threads_async_log_held agc_driver_shutdown_threads_exit_after_start PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30)
set_tests_properties(agc_driver_shutdown_threads_joined agc_driver_shutdown_threads_queued_prebuilds agc_driver_shutdown_threads_compare_helpers agc_driver_shutdown_threads_draw_committer agc_driver_shutdown_threads_shader_cache_writer agc_driver_shutdown_threads_late_shader_cache agc_driver_shutdown_threads_async_log_held agc_driver_shutdown_threads_exit_after_start PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30)
if(WIN32)
set_tests_properties(agc_driver_shutdown_threads_joined agc_driver_shutdown_threads_compare_helpers agc_driver_shutdown_threads_draw_committer agc_driver_shutdown_threads_shader_cache_writer agc_driver_shutdown_threads_late_shader_cache agc_driver_shutdown_threads_async_log_held agc_driver_shutdown_threads_exit_after_start PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
set_tests_properties(agc_driver_shutdown_threads_joined agc_driver_shutdown_threads_queued_prebuilds agc_driver_shutdown_threads_compare_helpers agc_driver_shutdown_threads_draw_committer agc_driver_shutdown_threads_shader_cache_writer agc_driver_shutdown_threads_late_shader_cache agc_driver_shutdown_threads_async_log_held agc_driver_shutdown_threads_exit_after_start PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test(NAME agc_driver_compute_user_data_calls_registered COMMAND agc_driver_compute_user_data_calls_tests --registered)
set_tests_properties(agc_driver_compute_user_data_calls_registered PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
@@ -3376,6 +3435,19 @@ if(BUILD_TESTING)
endif()
endif()
add_test_executable(agc_gcn_decode_tests EXCLUDE_FROM_ALL tests/GcnDecode.cpp)
target_link_libraries(agc_gcn_decode_tests PRIVATE shader_recompiler_agc_driver libc)
set_target_properties(agc_gcn_decode_tests PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(agc_gcn_decode_tests)
if(BUILD_TESTING)
set_target_properties(agc_gcn_decode_tests PROPERTIES EXCLUDE_FROM_ALL OFF)
add_test(NAME agc_gcn_decode COMMAND agc_gcn_decode_tests)
if(WIN32)
set_tests_properties(agc_gcn_decode PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_pixel_position_export_tests EXCLUDE_FROM_ALL tests/PixelPositionExport.cpp)
target_link_libraries(agc_pixel_position_export_tests PRIVATE shader_recompiler_agc_driver libc)
set_target_properties(agc_pixel_position_export_tests PROPERTIES CXX_EXTENSIONS OFF)
@@ -88,7 +88,7 @@ struct StageDataHit {
enum class DrawMiss : std::size_t { FrontDiffering, FragmentDiffering, OtherDiffering, Layout, Gate, Stages, Count };
struct DrawEntryCounters {
std::uint64_t lookups = 0, absent = 0, hits = 0, stageValidations = 0, stageEqual = 0, variantsCompared = 0, inserts = 0, variantsInserted = 0, variantsEvicted = 0, present = 0, unstable = 0, touches = 0, verifyHits = 0, verifyMismatches = 0;
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;
std::array<std::uint64_t, static_cast<std::size_t>(DrawMiss::Count)> misses{};
std::array<std::uint64_t, MaxDispatchVariants> variantHitsByRank{};
double validateUs = 0;
@@ -13,6 +13,8 @@
#include <mutex>
#include <optional>
#include <thread>
#include <span>
#include <string>
#include <utility>
#include <vector>
@@ -32,17 +34,22 @@ public:
static void FollowEpoch(std::uint64_t token);
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 = {});
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 Drain(DrainReason reason, std::uint32_t opcode = 0x100);
void Stop();
void ReleaseRetired();
static std::uint64_t DrainRequestsByOpcode(std::uint32_t opcode);
bool Busy() const { return outstanding.load(std::memory_order_acquire) != 0; }
bool Busy() const;
std::size_t Outstanding() const { return outstanding.load(std::memory_order_acquire); }
bool Overlaps(std::uint64_t address, std::size_t bytes);
bool OverlapsAny(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges);
std::optional<std::uint64_t> PendingLabel(std::uint64_t address, std::size_t bytes);
static bool HeldReads(std::uint64_t address, std::size_t bytes);
void ReleaseRunningReads();
static bool MetadataPassesPipelined();
static void CountPipelinedMetadataPass();
static std::uint64_t PipelinedMetadataPasses();
private:
struct Item {
Commit commit;
@@ -50,22 +57,29 @@ private:
std::uint64_t labelAddress = 0;
std::vector<std::byte> labelBytes;
std::vector<Range> reads;
bool draw = false;
};
DrawPipeline() = default;
void run();
void rethrowFailure();
void report(std::chrono::steady_clock::time_point now);
void countWrites(const std::vector<Range>& writes, bool added);
std::mutex mutex;
std::condition_variable wake;
std::condition_variable idle;
std::deque<Item> items;
std::vector<std::pair<Range, std::uint32_t>> queuedWrites;
std::vector<Item> retired;
std::exception_ptr failure;
std::atomic<std::size_t> outstanding{0};
std::uint32_t idleWaiters = 0;
std::size_t resumeAt = 0;
bool committerWaiting = false;
bool stopped = false;
bool closing = false;
std::uint64_t wakes = 0;
std::uint64_t lockWaitNs = 0;
std::thread thread;
std::uint64_t commits = 0;
std::uint64_t commitNs = 0;
@@ -80,6 +94,54 @@ private:
std::chrono::steady_clock::time_point lastReport = std::chrono::steady_clock::now();
};
class DrawFinisher {
public:
using Job = std::function<void()>;
using Range = std::pair<std::uint64_t, std::uint64_t>;
struct Pending {
std::uint64_t key = 0;
std::uint64_t shape = 0;
bool unknown = true;
std::vector<Range> writes;
std::uint64_t labelAddress = 0;
std::vector<std::byte> labelBytes;
};
enum class LabelLookup : std::uint8_t { NotHeld, Value, Unknown };
static bool Overlap();
bool PendingOverlaps(std::uint64_t begin, std::uint64_t end);
LabelLookup PendingLabel(std::uint64_t address, std::size_t bytes, std::uint64_t& value);
bool PendingOverlapsAny(std::span<const Range> ranges);
bool PendingKey(std::uint64_t key, std::uint64_t shape);
enum class DrainSite : std::uint32_t { Lookup, Reads, Packet, Kept, Count };
static void NoteDrain(DrainSite site, bool drained);
static std::string DrainText();
static void NoteDrainedOpcode(std::uint32_t opcode, bool besideCommits);
static DrawFinisher& Get();
static bool Enabled();
static bool OnFinisherThread();
static bool Busy() { return outstanding.load(std::memory_order_acquire) != 0; }
void Enqueue(Job job);
void Enqueue(Job job, Pending held);
void Drain();
void Settle();
void ReleaseRan();
private:
DrawFinisher() = default;
void run();
inline static std::atomic<std::size_t> outstanding{0};
std::mutex mutex;
std::condition_variable wake;
std::condition_variable idle;
std::deque<Job> jobs;
std::deque<Pending> pending;
std::vector<Job> ran;
std::exception_ptr failure;
bool running = false;
bool sleeping = false;
std::thread thread;
};
}
#endif
@@ -41,8 +41,14 @@
#include <utility>
#include <vector>
namespace AgcDriver {
class PerformanceTimer;
}
namespace AgcDriver::DriverDetail {
struct DrawTail;
class Driver {
public:
static Driver& Get();
@@ -86,6 +92,7 @@ private:
friend class SampledReadScope;
friend struct PendingView;
friend struct PacketTimer;
friend struct DriverTestAccess;
void stop();
Driver();
void rethrowFailure() const;
@@ -140,7 +147,7 @@ private:
static bool verifyDrawRecipe();
static std::size_t drawCacheEntries();
void accountDrawVariant(const DispatchVariant& variant, bool added);
void insertDrawEntry(std::uint64_t key, std::vector<std::shared_ptr<DispatchVariant>>& fresh, std::shared_ptr<const DrawDecode> decode, std::uint64_t shape = 0);
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);
@@ -166,11 +173,12 @@ private:
void lookupDraw(const Submission& submission, const std::shared_ptr<VulkanDevice>& localDevice, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector<DrawProgram>& programs, const std::vector<ShaderRecompiler::ProgramRole>& roles, const std::vector<std::optional<ShaderRecompiler::ShaderVertexStageInfo>>& vertexInfos, bool useDrawEntries, bool registerKey, bool profile, std::uint64_t& drawKey, std::shared_ptr<DrawEntry>& entry, std::vector<std::shared_ptr<DispatchVariant>>& matched, std::vector<std::vector<ShaderRecompiler::MemoryRegion>>& matchedRegions, bool& drawHit, bool& verifyHit, DrawPhaseTiming& phaseTiming, std::array<double, DrawDriverPhaseCount>& phaseMs, const std::shared_ptr<DrawEntry>& dataEntry, DrawDataCandidates& dataCandidates, std::vector<StageDataHit>& stageData);
std::shared_ptr<const ShaderRecompiler::RecompileResult> materializeDrawStage(std::size_t i, std::uint32_t pushOffset, const QueueState& queue, const Submission& submission, const std::vector<DrawProgram>& programs, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector<std::optional<ShaderRecompiler::ShaderVertexStageInfo>>& vertexInfos, std::vector<ShaderRecompiler::MemoryRegion>& memory, const std::vector<ShaderRecompiler::LinkedProgram>& linked, const Pm4::DrawParameters& drawParameters, const std::shared_ptr<VulkanDevice>& localDevice, ShaderMemory& shaderMemory, std::vector<StageCapture>& stageCaptures, std::vector<bool>& recompiled, bool drawHit, const std::vector<std::shared_ptr<DispatchVariant>>& matched, const std::vector<std::vector<ShaderRecompiler::MemoryRegion>>& matchedRegions, bool profile, std::uint64_t dumpTarget, std::uint64_t dumpSlot1, std::uint64_t& captures, DrawPhaseTiming& phaseTiming, std::array<double, DrawDriverPhaseCount>& phaseMs, std::string& rejected, const std::optional<ShaderRecompiler::MeshBarycentricLayout>& meshBarycentrics);
static void recordStageDataPositions(DispatchVariant& variant, const ShaderRecompiler::ResourceCapture& capture, const std::vector<Graphics::DecodeRead>& decodeReads);
void cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawParameters& drawParameters, const std::optional<Graphics::IndirectDrawPath>& indirectCpu, const std::vector<DrawProgram>& programs, const std::vector<StageCapture>& stageCaptures, const std::vector<std::optional<ShaderRecompiler::ShaderVertexStageInfo>>& vertexInfos, const std::vector<std::vector<Graphics::DecodeRead>>& decodeReads, bool verifyHit, const std::vector<std::shared_ptr<DispatchVariant>>& matched, std::vector<std::shared_ptr<DispatchVariant>>& fresh, std::uint64_t drawKey, bool registerKey, const std::shared_ptr<const DrawDecode>& decode, DrawPhaseTiming& phaseTiming, const std::vector<bool>& reused, const std::shared_ptr<DrawEntry>& entry, std::uint64_t shapeKey);
void cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawParameters& drawParameters, const std::optional<Graphics::IndirectDrawPath>& indirectCpu, const std::vector<DrawProgram>& programs, const std::vector<StageCapture>& stageCaptures, const std::vector<std::optional<ShaderRecompiler::ShaderVertexStageInfo>>& vertexInfos, const std::vector<std::vector<Graphics::DecodeRead>>& decodeReads, bool verifyHit, const std::vector<std::shared_ptr<DispatchVariant>>& matched, std::vector<std::shared_ptr<DispatchVariant>>& fresh, std::uint64_t drawKey, bool registerKey, const std::shared_ptr<const DrawDecode>& decode, DrawPhaseTiming& phaseTiming, const std::vector<bool>& reused, const std::shared_ptr<DrawEntry>& entry, std::uint64_t shapeKey, bool shapeNeedsEntry = false);
static bool drawPrecheck();
std::optional<DrawVerdict> precheckDraw(const QueueState& queue, const Submission& submission, std::span<const std::uint32_t> packet, const Pm4::DrawParameters& drawParameters, std::string& rejected, bool& traceIndirect);
static std::uint32_t drawUserWord(const DrawProgram& program, std::int32_t sgpr);
DrawVerdict draw(QueueState& queue, std::span<const std::uint32_t> packet, const Submission& submission, std::string& rejected);
DrawVerdict finishDraw(DrawTail& tail, PerformanceTimer& timing);
void addDriverPhases(DispatchClass which, const std::array<double, DriverPhaseCount>& ms, bool hit, bool validated);
static PendingDispatchPhases& pendingDispatchPhases();
static std::chrono::steady_clock::time_point& packetStartedAt();
@@ -243,6 +251,7 @@ private:
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);
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);
bool enqueueDmaPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue, const QueueState& state);
void commitDmaStore(std::uint32_t queue, std::uint64_t address, std::span<const std::byte> bytes);
@@ -177,6 +177,7 @@ struct ShaderSnapshot {
std::shared_ptr<const RegisteredShaderState> registeredState;
std::shared_ptr<std::atomic<std::uint8_t>> workgroupUse = std::make_shared<std::atomic<std::uint8_t>>(0u);
std::shared_ptr<std::atomic<std::uint8_t>> positionVectorUse = std::make_shared<std::atomic<std::uint8_t>>(0u);
std::shared_ptr<std::atomic<std::uint8_t>> memoryWrites = std::make_shared<std::atomic<std::uint8_t>>(0u);
std::shared_ptr<std::atomic<bool>> rawGraphicsNoted = std::make_shared<std::atomic<bool>>(false);
std::optional<std::uint32_t> userDataTailRegister;
};
@@ -189,6 +190,7 @@ void NoteRawGraphicsDraw(const ShaderSnapshot& snapshot);
bool RawGraphicsDrawn();
bool RawGraphicsDrawnIn(std::uint64_t begin, std::uint64_t end);
bool ProgramUsesWorkgroup(const ShaderSnapshot& snapshot, std::size_t codeOffset);
bool ProgramWritesMemory(const ShaderSnapshot& snapshot, std::size_t codeOffset);
// The PA_CL_VS_OUT_CNTL position export bits a vertex program is compiled with: none for a program
// without pos1..pos3 exports, so its artifact does not depend on them.
std::uint32_t PositionExportLayout(const ShaderSnapshot* snapshot, std::size_t codeOffset, std::span<const std::uint32_t> code, std::uint32_t paClVsOutCntl, const ShaderSnapshot* continuation = nullptr);
@@ -84,6 +84,7 @@ bool UnchangedCommittedSince(std::span<const std::pair<std::uint64_t, std::uint6
// Returns the generation the blocks were stamped with (0 when the arena is not write-watched):
// 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 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);
@@ -105,6 +106,9 @@ bool StoredAllSince_nid_no_patch(std::uint64_t address, std::size_t bytes, std::
// workers bump before every packet as before. CollectEpochBumps counts the bumps ([guestmem] line).
void BumpCollectEpoch();
void AdoptLatestCollectEpoch();
std::uint64_t ProofSerial();
void BreakProofs();
void MarkProofThread();
std::uint64_t CollectEpoch();
std::uint64_t CollectEpochBumps();
std::uint64_t ThreadCollectEpoch();
@@ -17,6 +17,7 @@
#include <memory>
#include <optional>
#include <string>
#include <utility>
namespace AgcDriver {
@@ -273,7 +274,7 @@ public:
// `recipe`, when given, receives the Recipe a successful call built for its dispatch-cache
// variant (design_cpu_final M4): only when the resource cache served or took the object
// (reusable, cacheable) and recipes are on (APS5_NO_DISPATCH_RECIPE=1 builds none); else null.
void Dispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::span<const Graphics::GuestMemorySnapshot> snapshots = {}, std::uint64_t programAddress = 0, std::shared_ptr<PreparedDispatch> prepared = nullptr, std::shared_ptr<const Recipe>* recipe = nullptr);
void Dispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::span<const Graphics::GuestMemorySnapshot> snapshots = {}, std::uint64_t programAddress = 0, std::shared_ptr<PreparedDispatch> prepared = nullptr, std::shared_ptr<const Recipe>* recipe = nullptr, std::optional<std::pair<std::uint64_t, std::size_t>> htileClear = std::nullopt);
struct IndirectOutcome {
int cpuReason;
double argumentReadMs;
@@ -357,7 +358,7 @@ private:
ShaderRecompiler::SpirvTarget buildTarget() const;
Graphics::Context buildContext() const;
// Body of Dispatch and DispatchIndirect: `arguments` 0 dispatches x, y, z groups.
IndirectOutcome dispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t arguments, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::uint64_t programAddress, std::shared_ptr<PreparedDispatch> prepared, std::shared_ptr<const Recipe>* recipe, const std::array<std::uint32_t, 3>& threadGroup = {});
IndirectOutcome dispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t arguments, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::uint64_t programAddress, std::shared_ptr<PreparedDispatch> prepared, std::shared_ptr<const Recipe>* recipe, const std::array<std::uint32_t, 3>& threadGroup = {}, std::optional<std::pair<std::uint64_t, std::size_t>> htileClear = std::nullopt);
// The stage-A pre-sync over `surfaces` (see PrepareDispatch): the serial waited for, 0 none.
std::uint64_t presync(std::span<const Graphics::PresyncSurface> surfaces);
std::shared_ptr<ComputePipelineObjects> computePipeline(const Graphics::Context& context, const ShaderRecompiler::RecompileResult& shader, VkDescriptorSetLayout setLayout, std::span<const std::uint32_t> layoutKey, VkShaderStageFlags pushStages, std::uint64_t programAddress);
@@ -16,7 +16,9 @@
#include "Optimization/ResourceProgram.hpp"
#include <algorithm>
#include <cstdlib>
#include <optional>
#include <stdexcept>
#include <utility>
namespace AgcDriver::DriverDetail {
@@ -119,6 +121,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
}
const bool pipelineCandidate = !resolving && !fromAhead && DispatchItemsEnabled() && DrawPipeline::Active() && indirectArguments == 0 && deferredLabels().labels.empty() && !matchesCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesStreamCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute);
const bool partialLastGroup = partialGroups != std::array<std::uint32_t, 3>{};
std::optional<std::pair<std::uint64_t, std::size_t>> htileClearCompletion;
if (resolving) {
if (indirectArguments == 0 && Graphics::MatchMultisampledSingleClear(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads)) return;
if (!partialLastGroup && matchesFillKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute)) return;
@@ -139,7 +142,8 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
if (const auto htile = Graphics::HtileDepthClearAddress(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads); htile != 0) {
const auto threads = (packet[4] & 0x20u) != 0 ? static_cast<std::uint64_t>(packet[1]) : static_cast<std::uint64_t>(packet[1]) * compute.numThreads[0];
const auto nativeBytes = Graphics::HtileDepthClearBytes_nid_no_patch(std::span(snapshot.code).subspan(codeOffset), userData, compute, packet, indirectArguments);
Graphics::NoteHtileDepthClear(htile, static_cast<std::size_t>(threads * 16u), nativeBytes);
const auto bytes = static_cast<std::size_t>(threads * 16u);
if (Graphics::NoteHtileDepthClear(htile, bytes, nativeBytes)) htileClearCompletion = std::pair{htile, bytes};
}
if (!partialLastGroup && indirectArguments == 0 && copyBuffer(queue, submission.queue, packet, std::span(snapshot.code).subspan(codeOffset), userData, compute, localDevice, address)) {
pendingDispatchPhases().outcome = DispatchOutcome::CopyHle;
@@ -462,18 +466,18 @@ 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, snapshots = std::move(snapshots), liveWords = std::move(liveWords), groups, address, queueId, recipe, keepVariant, dataHit, epoch] {
DrawPipeline::Queue0().Enqueue([this, localDevice = std::move(localDevice), result = compiledResult, snapshots = std::move(snapshots), liveWords = std::move(liveWords), groups, address, queueId, recipe, keepVariant, dataHit, epoch, htileClearCompletion] {
DrawPipeline::FollowEpoch(epoch);
GuestMemory::SetCurrentPacket(0x15, queueId);
const auto& compiledCommit = *result;
const bool noteWrites = writeEvidenceEnabled() || traceCapSync();
try {
std::shared_ptr<RecipeHit> recipeHit = localDevice->PrepareRecipe(recipe, false);
std::shared_ptr<RecipeHit> recipeHit = htileClearCompletion.has_value() ? nullptr : localDevice->PrepareRecipe(recipe, false);
std::shared_ptr<const Recipe> builtRecipe;
bool writersNoted = false;
for (;;) {
std::shared_ptr<PreparedDispatch> prepared;
if (recipeHit == nullptr || VulkanDevice::VerifyRecipes()) prepared = localDevice->PrepareDispatch(compiledCommit, snapshots);
if (recipeHit == nullptr || VulkanDevice::VerifyRecipes() || htileClearCompletion.has_value()) prepared = localDevice->PrepareDispatch(compiledCommit, snapshots);
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Dispatch);
std::lock_guard gpuLock(GuestMemory::GpuMutex());
recordLabelsForPacket(localDevice.get(), queueId);
@@ -491,7 +495,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
continue;
}
} else {
localDevice->Dispatch(compiledCommit, groups[0], groups[1], groups[2], snapshots, address, std::move(prepared), &builtRecipe);
localDevice->Dispatch(compiledCommit, groups[0], groups[1], groups[2], snapshots, address, std::move(prepared), htileClearCompletion.has_value() ? nullptr : &builtRecipe, htileClearCompletion);
}
break;
}
@@ -517,7 +521,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
std::shared_ptr<RecipeHit> recipeHit;
if (cached && keepVariant != nullptr && !stampValidate()) {
recipeHit = localDevice->PrepareRecipe(keepVariant->recipe.load(std::memory_order_acquire), indirectArguments != 0);
recipeHit = htileClearCompletion.has_value() ? nullptr : localDevice->PrepareRecipe(keepVariant->recipe.load(std::memory_order_acquire), indirectArguments != 0);
phaseTiming.Phase(PhaseRecipePrecheck);
}
@@ -595,7 +599,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
const auto outcome = localDevice->DispatchIndirect(compiled, indirectArguments, snapshots, address, std::move(prepared), attachTo != nullptr ? &builtRecipe : nullptr, threadGroup);
countIndirect(outcome.cpuReason, outcome.argumentReadMs);
} else {
localDevice->Dispatch(compiled, groups[0], groups[1], groups[2], snapshots, address, std::move(prepared), attachTo != nullptr ? &builtRecipe : nullptr);
localDevice->Dispatch(compiled, groups[0], groups[1], groups[2], snapshots, address, std::move(prepared), htileClearCompletion.has_value() ? nullptr : (attachTo != nullptr ? &builtRecipe : nullptr), htileClearCompletion);
}
} catch (const std::exception& error) {
if (rethrow(error)) return;
@@ -1,6 +1,7 @@
#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp"
#include "ThreadOwned.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp"
#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp"
#include "prx/libSceAgcDriver/Execution/include/VideoOutput.hpp"
@@ -107,6 +108,7 @@ void Driver::resolveGroupAhead(const Submission& submission, const QueueState& l
if (!allQueues && submission.queue == 0) return;
auto& resolved = resolvedAhead();
if (resolved.contains(from) || device.Load() == nullptr) return;
if (submission.queue == 0 && DrawPipeline::Depth() != 0 && DrawPipeline::Queue0().Busy()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, (submission.commands[from] >> 8u) & 0xffu);
auto& stats = groupCaptureStats();
const auto begin = std::chrono::steady_clock::now();
++stats.runs;
@@ -93,7 +93,7 @@ EntryOutcome Driver::validateVariant(std::uint64_t program, std::uint32_t queue,
if (live != nullptr) live->clear();
if (DrawPipeline::Active()) {
auto& pipeline = DrawPipeline::Queue0();
if (pipeline.Busy() && std::any_of(variant.runs.begin(), variant.runs.end(), [&](const auto& run) { return pipeline.Overlaps(run.first, static_cast<std::size_t>(run.second - run.first)); })) pipeline.Drain(DrawPipeline::DrainReason::Capture);
if (pipeline.Busy() && pipeline.OverlapsAny(variant.runs)) pipeline.Drain(DrawPipeline::DrainReason::Capture);
}
const bool masked = live != nullptr && !variant.dataPositions.empty();
const DataMask mask{variant.dataPositions, live};
@@ -1,6 +1,8 @@
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawProgramTrace.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DrawWriteRanges.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp"
@@ -8,21 +10,201 @@
#include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp"
#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp"
#include "Optimization/ResourceProgram.hpp"
#include <atomic>
#include <array>
#include <algorithm>
#include <bit>
#include <chrono>
#include <cstdio>
#include <unordered_set>
#include <cstdlib>
#include <cstdio>
#include <cstring>
namespace AgcDriver::DriverDetail {
struct DrawTail {
using GpuLock = std::unique_lock<std::remove_reference_t<decltype(GuestMemory::GpuMutex())>>;
bool profile = false;
std::array<double, DrawDriverPhaseCount> phaseMs{};
std::uint64_t captures = 0;
std::chrono::steady_clock::time_point phaseLap{};
DrawPhaseTiming phaseTiming{false, phaseMs, phaseLap};
Pm4::DrawParameters drawParameters{};
bool pipelined = false;
bool traceIndirect = false;
std::uint64_t dumpTarget = 0;
std::uint64_t dumpSlot1 = 0;
std::shared_ptr<VulkanDevice> localDevice;
bool registerKey = false;
std::uint64_t drawKey = 0;
std::shared_ptr<DrawEntry> entry;
std::shared_ptr<const DrawDecode> decode;
std::shared_ptr<const DrawDecode> relocatedDecode;
std::shared_ptr<DrawEntry> dataEntry;
std::uint64_t shapeKey = 0;
ShaderRecompiler::ShaderPixelStageInfo pixel{};
std::vector<DrawProgram> programs;
std::vector<ShaderRecompiler::MemoryRegion> memory;
std::vector<ShaderRecompiler::LinkedProgram> linked;
std::vector<std::optional<ShaderRecompiler::ShaderVertexStageInfo>> vertexInfos;
std::vector<std::vector<Graphics::DecodeRead>> decodeReads;
std::unique_ptr<ShaderMemory> shaderMemory;
std::vector<ShaderRecompiler::RecompileResult> results;
std::vector<std::shared_ptr<const ShaderRecompiler::RecompileResult>> compiledStages;
std::vector<Graphics::CompiledShader> stages;
std::uint32_t pushCursorBytes = 0;
std::vector<const ShaderRecompiler::RecompileResult*> programResults;
std::vector<StageCapture> stageCaptures;
std::vector<std::shared_ptr<DispatchVariant>> matched;
std::vector<std::vector<ShaderRecompiler::MemoryRegion>> matchedRegions;
std::vector<std::shared_ptr<DispatchVariant>> fresh;
std::vector<bool> recompiled;
DrawDataCandidates dataCandidates;
std::vector<bool> reused;
std::vector<StageDataHit> stageData;
bool drawHit = false;
bool verifyHit = false;
bool stageEntries = false;
bool patchedStages = false;
const Submission* submission = nullptr;
std::uint32_t submissionQueue = 0;
std::uint64_t submissionSerial = 0;
std::size_t packetOffset = 0;
std::uint32_t packetOpcode = 0;
std::uint32_t reg207 = 0;
std::uint64_t epoch = 0;
QueueState* queue = nullptr;
std::span<const std::uint32_t> packet;
std::string* rejected = nullptr;
std::string ownRejected;
GpuLock* gpuLock = nullptr;
GpuLock ownLock{GuestMemory::GpuMutex(), std::defer_lock};
};
namespace {
void noteFinisherHandOff(bool handed) {
static std::atomic<std::uint64_t> handedOff{0}, kept{0};
static std::atomic<std::int64_t> reportedAt{0};
(handed ? handedOff : kept).fetch_add(1, std::memory_order_relaxed);
static const bool stats = std::getenv("APS5_PIPELINE_STATS") != nullptr || std::getenv("APS5_PROFILE_DRAW") != nullptr;
if (!stats) return;
const auto tenSeconds = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()).count() / 10;
if (reportedAt.exchange(tenSeconds, std::memory_order_relaxed) == tenSeconds) return;
std::fprintf(stderr, "[finisher] draws (10 s): %llu handed to the draw finisher, %llu finished on the worker%s\n", static_cast<unsigned long long>(handedOff.exchange(0)), static_cast<unsigned long long>(kept.exchange(0)), DrawFinisher::DrainText().c_str());
}
}
namespace {
enum class HeldReason : std::size_t { Known, NoDecode, Size, NullVertex, NullFragment, NullOther, Bda, Buffer, Storage, Count };
std::array<std::atomic<std::uint64_t>, static_cast<std::size_t>(HeldReason::Count)> heldReasons{};
void noteHeld(HeldReason reason) {
heldReasons[static_cast<std::size_t>(reason)].fetch_add(1, std::memory_order_relaxed);
static const bool profile = std::getenv("APS5_PIPELINE_STATS") != nullptr || std::getenv("APS5_PROFILE_DRAW") != nullptr;
if (!profile) return;
static std::atomic<std::uint64_t> total{0};
const auto count = ++total;
if (count % 262144u != 0u && (count > 262144u || (count & (count - 1u)) != 0u)) return;
constexpr std::array<const char*, static_cast<std::size_t>(HeldReason::Count)> names{"targets only", "no decode", "stage count", "no variant (vertex)", "no variant (fragment)", "no variant (other)", "BDA stores", "written buffer", "storage image"};
std::string text;
for (std::size_t i = 0; i < names.size(); ++i) {
char item[64];
std::snprintf(item, sizeof(item), "%s %s %llu", i == 0 ? "" : ",", names[i], static_cast<unsigned long long>(count >= 262144u ? heldReasons[i].exchange(0) : heldReasons[i].load()));
text += item;
}
std::fprintf(stderr, "[finisher-held] held draws' writes:%s\n", text.c_str());
}
std::optional<HeldReason> writesBeyondTargets(const ShaderRecompiler::RecompileResult& compiled) {
using Role = ShaderRecompiler::DescriptorRole;
for (const auto& binding : compiled.bindings) {
if (binding.role == Role::BdaPagetable && Graphics::ShaderStoresThroughAddresses(compiled.spirv)) return HeldReason::Bda;
if (binding.role == Role::GuestBuffers) {
for (std::uint32_t element = 0; element < binding.count; ++element) {
if (element >= binding.bufferWritten.size() || binding.bufferWritten[element]) return HeldReason::Buffer;
}
}
if (binding.role == Role::GuestImages && binding.kind == ShaderRecompiler::DescriptorKind::StorageImage) {
for (std::uint32_t element = 0; element < binding.count; ++element) {
if (element >= binding.imageWritten.size() || binding.imageWritten[element]) return HeldReason::Storage;
}
}
}
return std::nullopt;
}
DrawFinisher::Pending heldWrites(const DrawTail& tail) {
DrawFinisher::Pending held;
held.key = tail.drawKey;
held.shape = tail.shapeKey;
if (tail.decode == nullptr) {
noteHeld(HeldReason::NoDecode);
return held;
}
if (tail.matched.size() != tail.programs.size()) {
noteHeld(HeldReason::Size);
return held;
}
const auto& roles = tail.decode->roles;
for (std::size_t i = 0; i < tail.matched.size(); ++i) {
if (i < roles.size() && roles[i] == ShaderRecompiler::ProgramRole::GeometryBack) continue;
const auto& variant = tail.matched[i];
if (variant == nullptr || variant->compiled == nullptr) {
const bool candidates = !tail.drawHit && i < tail.dataCandidates.size() && !tail.dataCandidates[i].empty();
const auto& program = tail.programs[i];
if (!candidates && program.snapshot != nullptr && !ProgramWritesMemory(*program.snapshot, program.codeOffset) && (program.tailContinuation == nullptr || !ProgramWritesMemory(*program.tailContinuation, 0))) continue;
if (!candidates) {
const auto stage = tail.programs[i].binary.stage;
noteHeld(stage == ShaderRecompiler::ShaderStage::Fragment ? HeldReason::NullFragment : stage == ShaderRecompiler::ShaderStage::Vertex ? HeldReason::NullVertex : HeldReason::NullOther);
return held;
}
for (const auto& [candidate, regions] : tail.dataCandidates[i]) {
if (candidate == nullptr || candidate->compiled == nullptr) {
noteHeld(HeldReason::NullOther);
return held;
}
if (const auto reason = writesBeyondTargets(*candidate->compiled)) {
noteHeld(*reason);
return held;
}
}
continue;
}
if (const auto reason = writesBeyondTargets(*variant->compiled)) {
noteHeld(*reason);
return held;
}
if (i < tail.stageData.size() && tail.stageData[i].compiled != nullptr) {
if (const auto reason = writesBeyondTargets(*tail.stageData[i].compiled)) {
noteHeld(*reason);
return held;
}
}
}
noteHeld(HeldReason::Known);
held.writes = DrawWriteRanges(tail.decode->state, {}, ExactDrawWrites());
held.unknown = false;
return held;
}
}
DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packet, const Submission& submission, std::string& rejected) {
PerformanceTimer timing("Driver.Draw");
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
std::array<double, DrawDriverPhaseCount> phaseMs{};
std::uint64_t captures = 0;
auto phaseLap = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
DrawPhaseTiming phaseTiming{profile, phaseMs, phaseLap};
auto tailHolder = std::make_shared<DrawTail>();
auto& tail = *tailHolder;
auto& phaseMs = tail.phaseMs;
auto& captures = tail.captures;
auto& phaseLap = tail.phaseLap;
phaseLap = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
tail.profile = profile;
tail.phaseTiming.profile = profile;
auto& phaseTiming = tail.phaseTiming;
if (profile && packetStartedAt() != std::chrono::steady_clock::time_point{}) phaseMs[DrawRowPrologue] = std::chrono::duration<double, std::milli>(phaseLap - packetStartedAt()).count();
const auto drawn = [&] {
@@ -35,8 +217,10 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
pending.tailAt = phaseLap;
return DrawVerdict::Drawn;
};
auto drawParameters = Pm4::ResolveDraw(packet, queue);
const bool pipelined = DrawPipeline::Active();
auto& drawParameters = tail.drawParameters;
drawParameters = Pm4::ResolveDraw(packet, queue);
tail.pipelined = DrawPipeline::Active();
const bool pipelined = tail.pipelined;
static const bool pipelinedIndirect = std::getenv("APS5_NO_PIPELINED_INDIRECT") == nullptr;
if (pipelined && drawParameters.indirect) {
const auto& indirect = *drawParameters.indirect;
@@ -44,10 +228,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
const bool overlaps = pipeline.Busy() && (pipeline.Overlaps(indirect.arguments, static_cast<std::size_t>(std::max<std::uint64_t>(indirect.RangeBytes(), indirect.recordBytes))) || (indirect.countIndirect && pipeline.Overlaps(indirect.countAddress, 4)));
if (!pipelinedIndirect || overlaps) pipeline.Drain(DrawPipeline::DrainReason::Indirect);
}
const auto drainBeforeInline = [&] {
if (pipelined && DrawPipeline::Queue0().Busy()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Indirect);
};
bool traceIndirect = false;
auto& traceIndirect = tail.traceIndirect;
if (const auto verdict = precheckDraw(queue, submission, packet, drawParameters, rejected, traceIndirect)) return *verdict;
phaseTiming.Phase(DrawRowPrecheck);
using Stage = ShaderRecompiler::ShaderStage;
@@ -59,7 +240,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
static const bool lockedPrepare = std::getenv("APS5_LOCKED_DRAW_PREPARE") != nullptr;
std::unique_lock gpuLock(GuestMemory::GpuMutex(), std::defer_lock);
std::shared_ptr<VulkanDevice> localDevice;
auto& localDevice = tail.localDevice;
if (lockedPrepare) {
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Draw);
@@ -81,13 +262,14 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
phaseTiming.Phase(DrawRowVectors);
const bool useDrawEntries = drawEntries() && !ShaderRecompiler::DebugProbeActive() && dumpTarget == 0 && dumpSlot1 == 0;
const bool registerKey = useDrawEntries && registerKeyEnabled();
std::uint64_t drawKey = 0;
tail.registerKey = useDrawEntries && registerKeyEnabled();
const bool registerKey = tail.registerKey;
auto& drawKey = tail.drawKey;
std::array<std::uint64_t, 5> drawKeyComponents{};
std::shared_ptr<DrawEntry> entry;
std::shared_ptr<const DrawDecode> decode;
std::shared_ptr<DrawEntry> dataEntry;
std::uint64_t shapeKey = 0;
auto& entry = tail.entry;
auto& decode = tail.decode;
auto& dataEntry = tail.dataEntry;
auto& shapeKey = tail.shapeKey;
std::uint64_t drawIdentity = 0, drawAlias = 0;
std::vector<DrawUserPatch> userPatches;
if (registerKey) {
@@ -95,6 +277,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
std::shared_ptr<const DrawRelocation> relocation;
bool aliasFirst = false;
if (drawRelocationEnabled()) {
if (DrawFinisher::Busy() && drawRelocationPending.key != 0) DrawFinisher::Get().Drain();
drawIdentity = drawIdentityKey(queue, *submission.shaders);
std::lock_guard cacheLock(drawCacheMutex);
learnPendingRelocation();
@@ -107,6 +290,17 @@ 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);
if (DrawFinisher::Busy()) {
bool shapeMatters = false;
if (DrawFinisher::Overlap() && drawDataHits()) {
std::lock_guard peekLock(drawCacheMutex);
const auto shape = drawShapes.find(shapeKey);
shapeMatters = !drawCache.contains(drawKey) && (shape == drawShapes.end() || !drawCache.contains(shape->second));
}
const bool drain = !DrawFinisher::Overlap() || DrawFinisher::Get().PendingKey(drawKey, shapeMatters ? shapeKey : 0);
if (drain) DrawFinisher::Get().Drain();
if (DrawFinisher::Overlap()) DrawFinisher::NoteDrain(DrawFinisher::DrainSite::Lookup, drain);
}
std::unique_lock cacheLock(drawCacheMutex);
++drawEntryCounters.lookups;
++drawEntryCounters.registerKeyLookups;
@@ -186,16 +380,15 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
}
resolveDrawDecode(queue, submission, localDevice->graphicsContext(), decode, registerKey, drawKey, profile);
const auto& graphics = decode->state;
auto pixel = decode->pixel;
const bool writesPrograms = graphics.stages.mesh || drawParameters.indirect || !userPatches.empty();
std::vector<DrawProgram> writablePrograms;
if (writesPrograms) writablePrograms = decode->programs;
for (const auto& patch : userPatches) writablePrograms[patch.program].userData[patch.index] = patch.value;
const std::vector<DrawProgram>& programs = writesPrograms ? writablePrograms : decode->programs;
auto& pixel = tail.pixel;
pixel = decode->pixel;
auto& programs = tail.programs;
programs = decode->programs;
for (const auto& patch : userPatches) programs[patch.program].userData[patch.index] = patch.value;
if (const auto skipped = SkippedShader(); skipped != 0 && std::any_of(programs.begin(), programs.end(), [skipped](const DrawProgram& program) { return program.binary.codeAddress == skipped; })) return drawn();
const auto setMeshIndexBuffer = [&](const Pm4::DrawParameters& parameters) {
if (!graphics.stages.mesh) return;
auto& words = writablePrograms.front().userData;
auto& words = programs.front().userData;
require(programs.front().firstUserSgpr == 0 && words.size() >= ShaderRecompiler::MeshIndexBufferUserWord + 4, "mesh program lacks the hidden user words");
const auto descriptor = Graphics::MeshIndexBufferDescriptor(parameters);
std::copy(descriptor.begin(), descriptor.end(), words.begin() + ShaderRecompiler::MeshIndexBufferUserWord);
@@ -231,10 +424,15 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
indirect.startInstanceSgpr = sgprOf(indirect.startInstanceLocation);
indirect.drawIndexSgpr = sgprOf(indirect.drawIndexLocation);
}
std::vector<ShaderRecompiler::MemoryRegion> memory;
if (DrawFinisher::Busy()) {
const bool drain = !DrawFinisher::Overlap();
if (drain) DrawFinisher::Get().Drain();
else DrawFinisher::NoteDrain(DrawFinisher::DrainSite::Reads, false);
}
auto& memory = tail.memory;
auto& linked = tail.linked;
memory.reserve(2 * programs.size() + 32);
AppendProgramMemory(memory, programs);
std::vector<ShaderRecompiler::LinkedProgram> linked;
linked.reserve(programs.size());
for (std::size_t i = 0; i < programs.size(); ++i) {
const auto& program = programs[i];
@@ -243,47 +441,60 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
timing.Mark("prepare");
phaseTiming.Phase(DrawRowProgramPrepare);
std::vector<std::optional<ShaderRecompiler::ShaderVertexStageInfo>> vertexInfos(programs.size());
std::vector<std::vector<Graphics::DecodeRead>> decodeReads(programs.size());
auto& vertexInfos = tail.vertexInfos;
vertexInfos.resize(programs.size());
auto& decodeReads = tail.decodeReads;
decodeReads.resize(programs.size());
const auto decodeVertexInfo = [&](std::size_t i) {
const auto& program = programs[i];
if (program.binary.stage == Stage::Fragment || roles[i] == Role::GeometryBack) return;
decodeReads[i].clear();
vertexInfos[i] = Graphics::DecodeVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, &decodeReads[i], false, 8u - program.firstUserSgpr);
if (vertexInfos[i]) vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, readRegister(queue.context, 0x207), program.tailContinuation.get()) | graphics.layerExports;
if (vertexInfos[i]) {
vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, readRegister(queue.context, 0x207), program.tailContinuation.get()) | graphics.layerExports;
vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode;
Graphics::ApplyPointSize(graphics, *vertexInfos[i]);
}
};
if (!registerKey) {
for (std::size_t i = 0; i < programs.size(); ++i) decodeVertexInfo(i);
phaseTiming.Phase(DrawRowDecode);
}
auto shaderMemory = std::make_unique<ShaderMemory>(memory, &queryPendingWrite, &observePendingWrite, hookWaitCounter(), &QueryPendingSpan);
std::vector<ShaderRecompiler::RecompileResult> results;
std::vector<std::shared_ptr<const ShaderRecompiler::RecompileResult>> compiledStages;
auto& shaderMemory = tail.shaderMemory;
shaderMemory = std::make_unique<ShaderMemory>(memory, &queryPendingWrite, &observePendingWrite, hookWaitCounter(), &QueryPendingSpan);
auto& results = tail.results;
auto& compiledStages = tail.compiledStages;
compiledStages.reserve(programs.size());
std::vector<Graphics::CompiledShader> stages;
auto& stages = tail.stages;
results.reserve(programs.size() + 2u);
stages.reserve(programs.size());
std::uint32_t pushCursorBytes = 0;
auto& pushCursorBytes = tail.pushCursorBytes;
std::vector<const ShaderRecompiler::RecompileResult*> programResults(programs.size(), nullptr);
auto& programResults = tail.programResults;
programResults.assign(programs.size(), nullptr);
std::vector<StageCapture> stageCaptures(programs.size());
std::vector<std::shared_ptr<DispatchVariant>> matched(programs.size());
std::vector<std::vector<ShaderRecompiler::MemoryRegion>> matchedRegions(programs.size());
auto& stageCaptures = tail.stageCaptures;
stageCaptures.resize(programs.size());
auto& matched = tail.matched;
matched.resize(programs.size());
auto& matchedRegions = tail.matchedRegions;
matchedRegions.resize(programs.size());
std::vector<std::shared_ptr<DispatchVariant>> fresh(programs.size());
auto& fresh = tail.fresh;
fresh.resize(programs.size());
std::vector<bool> recompiled(programs.size(), false);
std::vector<std::vector<std::pair<std::shared_ptr<DispatchVariant>, std::vector<ShaderRecompiler::MemoryRegion>>>> dataCandidates(programs.size());
std::vector<bool> reused(programs.size(), false);
std::vector<StageDataHit> stageData(programs.size());
std::uint64_t dataStagesReused = 0, dataStagesCompiled = 0, dataVerified = 0;
bool drawHit = false;
bool verifyHit = false;
const bool stageEntries = useDrawEntries && !(graphics.stages.tessellation && !drawParameters.indirect && drawParameters.instanceCount > 1u);
auto& recompiled = tail.recompiled;
recompiled.assign(programs.size(), false);
auto& dataCandidates = tail.dataCandidates;
dataCandidates.resize(programs.size());
auto& reused = tail.reused;
reused.assign(programs.size(), false);
auto& stageData = tail.stageData;
stageData.resize(programs.size());
auto& drawHit = tail.drawHit;
auto& verifyHit = tail.verifyHit;
tail.stageEntries = useDrawEntries && !(graphics.stages.tessellation && !drawParameters.indirect && drawParameters.instanceCount > 1u);
const bool stageEntries = tail.stageEntries;
lookupDraw(submission, localDevice, graphics, pixel, programs, roles, vertexInfos, stageEntries, registerKey, profile, drawKey, entry, matched, matchedRegions, drawHit, verifyHit, phaseTiming, phaseMs, dataEntry, dataCandidates, stageData);
for (std::size_t i = 0; i < matched.size(); ++i) {
if (matched[i] == nullptr || matched[i]->shaderDataPatches.empty()) continue;
@@ -304,8 +515,8 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
for (const auto& patch : userPatches) current->programs[patch.program].userData[patch.index] = patch.value;
decode = std::move(current);
}
const bool patchedStages = std::any_of(stageData.begin(), stageData.end(), [](const StageDataHit& hit) { return hit.compiled != nullptr; });
std::uint64_t stageDataVerified = 0;
tail.patchedStages = std::any_of(stageData.begin(), stageData.end(), [](const StageDataHit& hit) { return hit.compiled != nullptr; });
tail.relocatedDecode = relocatedDecode;
if (registerKey) {
@@ -330,6 +541,137 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
phaseTiming.Phase(DrawRowDecode);
}
tail.submission = &submission;
tail.submissionQueue = submission.queue;
tail.packetOpcode = (packet[0] >> 8u) & 0xffu;
tail.reg207 = readRegister(queue.context, 0x207);
tail.dumpTarget = dumpTarget;
tail.dumpSlot1 = dumpSlot1;
const bool handOff = pipelined && !drawParameters.indirect && !profile && !lockedPrepare && 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;
tail.packetOffset = static_cast<std::size_t>(packet.data() - submission.commands.data());
noteFinisherHandOff(true);
DrawFinisher::Pending held;
if (DrawFinisher::Overlap()) held = heldWrites(tail);
DrawFinisher::Get().Enqueue([this, tailHolder] {
auto& job = *tailHolder;
DrawPipeline::FollowEpoch(job.epoch);
GuestMemory::SetCurrentPacket(job.packetOpcode, job.submissionQueue);
PerformanceTimer finishTiming("Driver.DrawFinish");
try {
if (finishDraw(job, finishTiming) == DrawVerdict::Rejected) throw std::runtime_error(job.ownRejected);
} catch (const std::exception& error) {
CaptureTrace::Log("draw-error submission=%llu offset=%zu finisher=1 reason=%.256s", static_cast<unsigned long long>(job.submissionSerial), job.packetOffset, error.what());
throw std::runtime_error("draw at submission " + std::to_string(job.submissionSerial) + " offset " + std::to_string(job.packetOffset) + " (finished on the draw finisher): " + error.what());
}
}, std::move(held));
timing.Mark("draw_handed_off");
return drawn();
}
noteFinisherHandOff(false);
if (DrawFinisher::Busy()) {
DrawFinisher::Get().Drain();
if (DrawFinisher::Overlap()) DrawFinisher::NoteDrain(DrawFinisher::DrainSite::Kept, true);
}
tail.queue = &queue;
tail.packet = packet;
tail.rejected = &rejected;
tail.gpuLock = &gpuLock;
return finishDraw(tail, timing);
}
DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
using Stage = ShaderRecompiler::ShaderStage;
using Role = ShaderRecompiler::ProgramRole;
const bool profile = tail.profile;
auto& phaseMs = tail.phaseMs;
auto& phaseLap = tail.phaseLap;
auto& captures = tail.captures;
auto& phaseTiming = tail.phaseTiming;
auto& drawParameters = tail.drawParameters;
const bool pipelined = tail.pipelined;
static const bool pipelinedIndirect = std::getenv("APS5_NO_PIPELINED_INDIRECT") == nullptr;
const auto drainBeforeInline = [&] {
if (pipelined && DrawPipeline::Queue0().Busy()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Indirect);
};
auto& traceIndirect = tail.traceIndirect;
const auto dumpTarget = tail.dumpTarget;
const auto dumpSlot1 = tail.dumpSlot1;
auto& gpuLock = tail.gpuLock != nullptr ? *tail.gpuLock : tail.ownLock;
auto& localDevice = tail.localDevice;
const bool registerKey = tail.registerKey;
auto& drawKey = tail.drawKey;
auto& entry = tail.entry;
auto& decode = tail.decode;
auto& dataEntry = tail.dataEntry;
auto& shapeKey = tail.shapeKey;
const auto& graphics = decode->state;
auto& pixel = tail.pixel;
auto& programs = tail.programs;
const std::vector<Role>& roles = decode->roles;
auto& memory = tail.memory;
auto& linked = tail.linked;
auto& vertexInfos = tail.vertexInfos;
auto& decodeReads = tail.decodeReads;
auto& shaderMemory = tail.shaderMemory;
auto& results = tail.results;
auto& compiledStages = tail.compiledStages;
auto& stages = tail.stages;
auto& pushCursorBytes = tail.pushCursorBytes;
auto& programResults = tail.programResults;
auto& stageCaptures = tail.stageCaptures;
auto& matched = tail.matched;
auto& matchedRegions = tail.matchedRegions;
auto& fresh = tail.fresh;
auto& recompiled = tail.recompiled;
auto& dataCandidates = tail.dataCandidates;
auto& reused = tail.reused;
auto& stageData = tail.stageData;
std::uint64_t dataStagesReused = 0, dataStagesCompiled = 0, dataVerified = 0;
auto& drawHit = tail.drawHit;
auto& verifyHit = tail.verifyHit;
const bool stageEntries = tail.stageEntries;
const bool patchedStages = tail.patchedStages;
std::uint64_t stageDataVerified = 0;
const Submission& submission = *tail.submission;
std::string& rejected = tail.rejected != nullptr ? *tail.rejected : tail.ownRejected;
static const QueueState noQueue{};
const QueueState& queue = tail.queue != nullptr ? *tail.queue : noQueue;
const auto drawn = [&] {
phaseTiming.Phase(DrawRowVectors);
if (!profile) return DrawVerdict::Drawn;
auto& pending = pendingDrawPhases();
pending.phases = true;
pending.captures = captures;
pending.ms = phaseMs;
pending.tailAt = phaseLap;
return DrawVerdict::Drawn;
};
const auto setMeshIndexBuffer = [&](const Pm4::DrawParameters& parameters) {
if (!graphics.stages.mesh) return;
auto& words = programs.front().userData;
require(programs.front().firstUserSgpr == 0 && words.size() >= ShaderRecompiler::MeshIndexBufferUserWord + 4, "mesh program lacks the hidden user words");
const auto descriptor = Graphics::MeshIndexBufferDescriptor(parameters);
std::copy(descriptor.begin(), descriptor.end(), words.begin() + ShaderRecompiler::MeshIndexBufferUserWord);
};
const auto locate = [&](std::uint32_t location) -> std::optional<std::pair<std::size_t, std::size_t>> {
if (location == 0x280u) return std::nullopt;
for (std::size_t i = 0; i < programs.size(); ++i) {
if (roles[i] == Role::Fragment || roles[i] == Role::GeometryBack || location < programs[i].userDataBase) continue;
const auto word = location - programs[i].userDataBase + (8u - programs[i].firstUserSgpr);
if (word < programs[i].userData.size()) return std::make_pair(i, static_cast<std::size_t>(word));
}
return std::nullopt;
};
const auto decodeVertexInfo = [&](std::size_t i) {
const auto& program = programs[i];
if (program.binary.stage == Stage::Fragment || roles[i] == Role::GeometryBack) return;
decodeReads[i].clear();
vertexInfos[i] = Graphics::DecodeVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, &decodeReads[i], false, 8u - program.firstUserSgpr);
if (vertexInfos[i]) vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, tail.reg207, program.tailContinuation.get()) | graphics.layerExports;
};
const auto fold = [&](const ShaderRecompiler::RecompileResult& main, Pm4::DrawParameters& parameters) { FoldDrawOffsets(main, programs.front(), parameters); };
const auto freshRuns = [&](std::size_t i, std::vector<std::pair<std::uint64_t, std::uint64_t>>& runs, std::vector<std::uint32_t>& words) {
@@ -433,15 +775,36 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
drawEntryCounters.dataStagesCompiled += dataStagesCompiled;
drawEntryCounters.dataVerified += dataVerified;
}
cacheDrawStages(stageEntries, drawHit, drawParameters, indirectCpu, programs, stageCaptures, vertexInfos, decodeReads, verifyHit, matched, fresh, drawKey, registerKey, decode, phaseTiming, reused, entry, shapeKey);
const bool shapeRefresh = Graphics::DrawPipelineEnabled();
const auto refreshSeenTwice = [&] {
std::uint64_t data = shapeKey;
bool stored = false;
const auto mix = [&data](std::uint64_t value) {
data ^= value + 0x9e3779b97f4a7c15ull + (data << 6u) + (data >> 2u);
};
for (std::size_t i = 0; i < programs.size(); ++i) {
const auto& capture = stageCaptures[i];
if (reused[i] || capture.compiled == nullptr || !CacheableResult(*capture.compiled)) continue;
stored = true;
const auto& words = programs[i].userData;
for (std::size_t w = 0; w < words.size(); ++w) {
if (w >= 64u || (capture.userDataMask >> w & 1u) != 0) mix((static_cast<std::uint64_t>(i) << 40u) ^ (static_cast<std::uint64_t>(w) << 32u) ^ words[w]);
}
}
if (!stored) return false;
static std::array<std::atomic<std::uint64_t>, 4096> lastData{};
return lastData[shapeKey % lastData.size()].exchange(data, std::memory_order_relaxed) == data;
};
const bool shapeNeedsEntry = shapeRefresh && registerKey && shapeKey != 0 && drawDataHits() && !drawParameters.indirect && dataEntry != nullptr && dataStagesCompiled != 0 && refreshSeenTwice();
cacheDrawStages(stageEntries, drawHit, drawParameters, indirectCpu, programs, stageCaptures, vertexInfos, decodeReads, verifyHit, matched, fresh, drawKey, registerKey, decode, phaseTiming, reused, entry, shapeKey, shapeNeedsEntry);
timing.Mark("shader_compile_and_link");
for (const auto& reads : decodeReads) {
for (const auto& read : reads) memory.push_back({read.address, read.Bytes()});
}
if (pipelined && !deferredLabels().labels.empty()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Labels);
if (recordQueuedLabelsAfterCapture(submission.queue, memory)) return draw(queue, packet, submission, rejected);
if (tail.queue != nullptr && pipelined && !deferredLabels().labels.empty()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Labels);
if (tail.queue != nullptr && recordQueuedLabelsAfterCapture(submission.queue, memory)) return draw(*tail.queue, tail.packet, submission, rejected);
bool rectListBuilt = false;
@@ -487,7 +850,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
results.push_back(ShaderRecompiler::BuildBarycentricGeometryShader(*programResults[0], *programResults[1], localDevice->Target(), geometryLimits));
stages.insert(stages.begin() + 1, Graphics::CompiledShader{Stage::Geometry, &results.back(), 0});
} else {
require(graphics.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST && !graphics.primitiveRestart, "a pixel shader that reads barycentrics without VK_KHR_fragment_shader_barycentric or geometry shaders needs a triangle list without primitive restart");
require((graphics.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || graphics.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP) && !graphics.primitiveRestart, "a pixel shader that reads barycentrics without VK_KHR_fragment_shader_barycentric or geometry shaders needs a triangle list or strip without primitive restart");
auto patches = ShaderRecompiler::BuildBarycentricTessellationShaders(*programResults[0], *programResults[1], localDevice->Target(), localDevice->MaxFragmentInputComponents(), graphics.provokingVertexMode == VK_PROVOKING_VERTEX_MODE_LAST_VERTEX_EXT ? 2u : 0u);
const auto first = results.size();
results.push_back(std::move(patches.control));
@@ -504,6 +867,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
snapshot();
timing.Mark("post_compile_prepare");
const auto lockForDraw = [&] {
require(tail.queue != nullptr, "the draw finisher reached a draw it cannot commit through the pipeline");
if (gpuLock.owns_lock()) return;
phaseTiming.Phase(DrawRowVectors);
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Draw);
@@ -553,7 +917,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
std::set<std::size_t> patched;
const auto patch = [&](const std::vector<std::pair<std::size_t, std::size_t>>& words, std::uint32_t value) {
for (const auto& [program, word] : words) {
writablePrograms[program].userData[word] = value;
programs[program].userData[word] = value;
patched.insert(program);
}
};
@@ -598,7 +962,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
phaseTiming.Phase(DrawRowVectors);
auto writes = drawWriteRanges(graphics, stages);
const auto commitQueue = submission.queue;
const auto commitPacket = (packet[0] >> 8u) & 0xffu;
const auto commitPacket = tail.packetOpcode;
const auto epoch = DrawPipeline::EpochToken().load(std::memory_order_relaxed);
auto commit = [this, localDevice = std::move(localDevice), decode = std::move(decode), direct, stages = std::move(stages), snapshots = std::move(snapshots), commitQueue, commitPacket, epoch, programs = std::move(programs), 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);
@@ -639,20 +1003,20 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
return DrawVerdict::Rejected;
}
}
if (pipelined && !drawParameters.indirect && deferredLabels().labels.empty()) {
if (pipelined && !drawParameters.indirect && (tail.queue == nullptr || deferredLabels().labels.empty())) {
phaseTiming.Phase(DrawRowVectors);
auto writes = drawWriteRanges(graphics, stages);
const auto commitQueue = submission.queue;
const auto commitPacket = (packet[0] >> 8u) & 0xffu;
const auto epoch = DrawPipeline::EpochToken().load(std::memory_order_relaxed);
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, commitQueue, commitPacket, epoch, programs = std::move(programs), 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)] {
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, commitQueue, commitPacket, epoch, programs = std::move(programs), 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);
};
auto held = std::make_shared<decltype(commit)>(std::move(commit));
DrawPipeline::Queue0().Enqueue([held] { (*held)(); }, std::move(writes), 0, {}, std::move(reads));
DrawPipeline::Queue0().Enqueue([held] { (*held)(); }, std::move(writes), 0, {}, std::move(reads), true);
phaseTiming.Phase(DrawRowLockWait);
timing.Mark("draw_enqueued");
return drawn();
@@ -123,10 +123,24 @@ bool Driver::admitDrawKey(std::uint64_t key, std::uint64_t shape) {
return drawShapeSightings->SeenBefore(shape);
}
void Driver::insertDrawEntry(std::uint64_t key, std::vector<std::shared_ptr<DispatchVariant>>& fresh, std::shared_ptr<const DrawDecode> decode, std::uint64_t shape) {
void Driver::insertDrawEntry(std::uint64_t key, std::vector<std::shared_ptr<DispatchVariant>>& fresh, std::shared_ptr<const DrawDecode> decode, std::uint64_t shape, bool replaceShape) {
std::lock_guard cacheLock(drawCacheMutex);
auto& counters = drawEntryCounters;
++counters.inserts;
if (replaceShape && shape != 0) {
++counters.shapeUpdates;
if (const auto shapeOf = drawShapes.find(shape); shapeOf != drawShapes.end() && shapeOf->second != key) {
if (const auto previous = drawCache.find(shapeOf->second); previous != drawCache.end()) {
for (const auto& variants : previous->second->stages) {
for (const auto& variant : variants) accountDrawVariant(*variant, false);
}
drawOrder.erase(previous->second->order);
drawCache.erase(previous);
}
drawShapes.erase(shapeOf);
}
} else {
++counters.inserts;
}
const auto found = drawCache.find(key);
auto replacement = std::make_shared<DrawEntry>();
replacement->stages.resize(fresh.size());
@@ -62,7 +62,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 variants inserted, %llu evicted beyond k, %llu already present, %llu unstable), %zu entries (%llu variants, ~%.1f MiB), %llu evictions in total, %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.variantsInserted), count(counters.variantsEvicted), count(counters.present), count(counters.unstable), drawCache.size(), count(drawCacheVariants), static_cast<double>(drawCacheVariantBytes) / (1024.0 * 1024.0), count(drawCacheEvictions), 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, 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), %llu evictions in total, %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), count(drawCacheEvictions), 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;
@@ -152,8 +152,11 @@ void Driver::recordStageDataPositions(DispatchVariant& variant, const ShaderReco
variant.dataSlots.resize(kept);
}
void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawParameters& drawParameters, const std::optional<Graphics::IndirectDrawPath>& indirectCpu, const std::vector<DrawProgram>& programs, const std::vector<StageCapture>& stageCaptures, const std::vector<std::optional<ShaderRecompiler::ShaderVertexStageInfo>>& vertexInfos, const std::vector<std::vector<Graphics::DecodeRead>>& decodeReads, bool verifyHit, const std::vector<std::shared_ptr<DispatchVariant>>& matched, std::vector<std::shared_ptr<DispatchVariant>>& fresh, std::uint64_t drawKey, bool registerKey, const std::shared_ptr<const DrawDecode>& decode, DrawPhaseTiming& phaseTiming, const std::vector<bool>& reused, const std::shared_ptr<DrawEntry>& entry, std::uint64_t shapeKey) {
if (useDrawEntries && !drawHit && !(drawParameters.indirect && indirectCpu) && (verifyHit || admitDrawKey(drawKey, registerKey && drawDataHits() ? shapeKey : 0))) {
void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawParameters& drawParameters, const std::optional<Graphics::IndirectDrawPath>& indirectCpu, const std::vector<DrawProgram>& programs, const std::vector<StageCapture>& stageCaptures, const std::vector<std::optional<ShaderRecompiler::ShaderVertexStageInfo>>& vertexInfos, const std::vector<std::vector<Graphics::DecodeRead>>& decodeReads, bool verifyHit, const std::vector<std::shared_ptr<DispatchVariant>>& matched, std::vector<std::shared_ptr<DispatchVariant>>& fresh, std::uint64_t drawKey, bool registerKey, const std::shared_ptr<const DrawDecode>& decode, DrawPhaseTiming& phaseTiming, const std::vector<bool>& reused, const std::shared_ptr<DrawEntry>& entry, std::uint64_t shapeKey, bool shapeNeedsEntry) {
const bool cacheable = useDrawEntries && !drawHit && !(drawParameters.indirect && indirectCpu);
const bool admitted = cacheable && (verifyHit || admitDrawKey(drawKey, registerKey && drawDataHits() ? shapeKey : 0));
const bool replaceShape = cacheable && !admitted && shapeNeedsEntry;
if (admitted || replaceShape) {
phaseTiming.Phase(DrawRowVectors);
std::uint64_t unstable = 0, mismatches = 0, differingSameRuns = 0, differingWords = 0, differingRunsChanged = 0;
for (std::size_t i = 0; i < programs.size(); ++i) {
@@ -222,7 +225,7 @@ void Driver::cacheDrawStages(bool useDrawEntries, bool drawHit, const Pm4::DrawP
}
fresh[i] = std::move(variant);
}
insertDrawEntry(drawKey, fresh, registerKey ? decode : nullptr, registerKey && drawDataHits() ? shapeKey : 0);
insertDrawEntry(drawKey, fresh, registerKey ? decode : nullptr, registerKey && drawDataHits() ? shapeKey : 0, replaceShape);
std::uint64_t dataInserts = 0, dataPositions = 0;
for (std::size_t i = 0; i < programs.size(); ++i) {
if (fresh[i] == nullptr || reused[i] || fresh[i]->dataPositions.empty()) continue;
@@ -2,6 +2,7 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include <algorithm>
#include <bit>
namespace AgcDriver::DriverDetail {
@@ -51,6 +52,10 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptr<Vulk
mix(vertex.fetchBufferReg);
mix(vertex.fetchEmbedded);
mix(vertex.paClVsOutCntl);
mix(vertex.pointList);
mix(std::bit_cast<std::uint32_t>(vertex.pointSize));
mix(std::bit_cast<std::uint32_t>(vertex.pointSizeMin));
mix(std::bit_cast<std::uint32_t>(vertex.pointSizeMax));
for (std::uint32_t r = 0; r < vertex.resourcesNum; ++r) {
for (const auto field : vertex.resources[r].fields) mix(field);
const auto& destination = vertex.resourcesDst[r];
@@ -4,7 +4,11 @@
#include "prx/libSceAgcDriver/Execution/include/HandoffSpin.hpp"
#include "prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp"
#include "prx/libSceAgcDriver/Execution/include/WorkerSampler.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include <algorithm>
#include <array>
#include <limits>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -29,6 +33,212 @@ std::atomic<std::uint64_t> heldReadHits{0};
}
namespace {
thread_local bool finisherThread = false;
thread_local bool finisherProducer = false;
}
DrawFinisher& DrawFinisher::Get() {
static DrawFinisher* finisher = new DrawFinisher();
return *finisher;
}
bool DrawFinisher::Enabled() {
return Graphics::DrawPipelineEnabled();
}
bool DrawPipeline::MetadataPassesPipelined() {
return Graphics::DrawPipelineEnabled();
}
namespace {
std::atomic<std::uint64_t> pipelinedMetadataPasses{0};
}
std::uint64_t DrawPipeline::PipelinedMetadataPasses() {
return pipelinedMetadataPasses.load(std::memory_order_relaxed);
}
void DrawPipeline::CountPipelinedMetadataPass() {
pipelinedMetadataPasses.fetch_add(1, std::memory_order_relaxed);
}
bool DrawFinisher::Overlap() {
return Graphics::DrawPipelineEnabled();
}
bool DrawFinisher::PendingOverlaps(std::uint64_t begin, std::uint64_t end) {
if (!Busy() || !finisherProducer) return false;
std::lock_guard lock(mutex);
for (const auto& held : pending) {
if (held.unknown) return true;
for (const auto& [first, last] : held.writes) {
if (begin < last && first < end) return true;
}
}
return false;
}
DrawFinisher::LabelLookup DrawFinisher::PendingLabel(std::uint64_t address, std::size_t bytes, std::uint64_t& value) {
if (!Busy() || !finisherProducer) return LabelLookup::NotHeld;
const auto end = address + bytes;
std::lock_guard lock(mutex);
for (auto held = pending.rbegin(); held != pending.rend(); ++held) {
if (held->unknown) return LabelLookup::Unknown;
const bool overlaps = std::any_of(held->writes.begin(), held->writes.end(), [&](const Range& range) { return address < range.second && range.first < end; });
if (!overlaps) continue;
if (held->labelBytes.empty() || address < held->labelAddress || end > held->labelAddress + held->labelBytes.size()) return LabelLookup::Unknown;
value = 0;
std::memcpy(&value, held->labelBytes.data() + (address - held->labelAddress), bytes);
return LabelLookup::Value;
}
return LabelLookup::NotHeld;
}
bool DrawFinisher::PendingOverlapsAny(std::span<const Range> ranges) {
if (!Busy() || !finisherProducer) return false;
std::lock_guard lock(mutex);
for (const auto& held : pending) {
if (held.unknown) return true;
for (const auto& [first, last] : held.writes) {
for (const auto& [begin, end] : ranges) {
if (begin < last && first < end) return true;
}
}
}
return false;
}
bool DrawFinisher::PendingKey(std::uint64_t key, std::uint64_t shape) {
if (!Busy() || !finisherProducer) return false;
std::lock_guard lock(mutex);
return std::any_of(pending.begin(), pending.end(), [&](const Pending& held) { return held.key == key || (shape != 0 && held.shape == shape); });
}
namespace {
std::array<std::atomic<std::uint64_t>, static_cast<std::size_t>(DrawFinisher::DrainSite::Count)> finisherDrains{}, finisherSkips{};
}
void DrawFinisher::NoteDrain(DrainSite site, bool drained) {
(drained ? finisherDrains : finisherSkips)[static_cast<std::size_t>(site)].fetch_add(1, std::memory_order_relaxed);
}
namespace {
std::array<std::atomic<std::uint64_t>, 257> drainedOpcodes{}, drainedBeside{};
}
void DrawFinisher::NoteDrainedOpcode(std::uint32_t opcode, bool besideCommits) {
drainedOpcodes[std::min<std::uint32_t>(opcode, 256u)].fetch_add(1, std::memory_order_relaxed);
if (besideCommits) drainedBeside[std::min<std::uint32_t>(opcode, 256u)].fetch_add(1, std::memory_order_relaxed);
}
std::string DrawFinisher::DrainText() {
constexpr std::array<const char*, static_cast<std::size_t>(DrainSite::Count)> names{"lookup", "reads", "packet", "kept draw"};
std::string text = "; worker drains of the finisher (drained/skipped):";
for (std::size_t i = 0; i < names.size(); ++i) {
char item[64];
std::snprintf(item, sizeof(item), " %s %llu/%llu", names[i], static_cast<unsigned long long>(finisherDrains[i].exchange(0)), static_cast<unsigned long long>(finisherSkips[i].exchange(0)));
text += item;
}
text += "; drained by opcode (of them beside commits):";
for (int shown = 0; shown < 6; ++shown) {
std::size_t top = 0;
for (std::size_t i = 1; i < drainedOpcodes.size(); ++i) {
if (drainedOpcodes[i].load() > drainedOpcodes[top].load()) top = i;
}
const auto count = drainedOpcodes[top].exchange(0);
if (count == 0) break;
char item[48];
std::snprintf(item, sizeof(item), " 0x%02zx x%llu (%llu)", top, static_cast<unsigned long long>(count), static_cast<unsigned long long>(drainedBeside[top].exchange(0)));
text += item;
}
return text;
}
bool DrawFinisher::OnFinisherThread() {
return finisherThread;
}
void DrawFinisher::Enqueue(Job job) {
Enqueue(std::move(job), Pending{});
}
void DrawFinisher::Enqueue(Job job, Pending held) {
finisherProducer = true;
constexpr std::size_t depth = 16;
struct ReclaimStorage {};
auto& reclaim = HostThreadLocal<std::vector<Job>, ReclaimStorage>();
reclaim.clear();
std::unique_lock lock(mutex);
if (!ran.empty()) std::swap(ran, reclaim);
if (failure != nullptr) std::rethrow_exception(std::exchange(failure, nullptr));
if (jobs.size() >= depth && GuestMemory::GpuMutex().HeldByThisThread()) throw std::runtime_error("draw finisher full while the enqueuing thread holds the GPU lock");
idle.wait(lock, [&] { return jobs.size() < depth; });
jobs.push_back(std::move(job));
pending.push_back(std::move(held));
outstanding.fetch_add(1, std::memory_order_release);
if (!running) {
running = true;
thread = std::thread([this] {
finisherThread = true;
run();
});
}
if (sleeping) wake.notify_one();
}
void DrawFinisher::run() {
PerformanceTrace::BindThread("draw finisher");
for (;;) {
Job* job = nullptr;
bool failed = false;
SpinUntil(HandoffSpinWindow(), [&] { return outstanding.load(std::memory_order_acquire) != 0; });
{
std::unique_lock lock(mutex);
sleeping = true;
wake.wait(lock, [&] { return !jobs.empty(); });
sleeping = false;
job = &jobs.front();
failed = failure != nullptr;
}
std::exception_ptr error;
try {
if (!failed) (*job)();
} catch (...) {
error = std::current_exception();
}
std::lock_guard lock(mutex);
if (error != nullptr && failure == nullptr) failure = error;
ran.push_back(std::move(jobs.front()));
jobs.pop_front();
pending.pop_front();
outstanding.fetch_sub(1, std::memory_order_release);
idle.notify_all();
}
}
void DrawFinisher::Settle() {
if (!Busy() || OnFinisherThread()) return;
if (GuestMemory::GpuMutex().HeldByThisThread()) throw std::runtime_error("draw finisher settle under the GPU lock");
std::unique_lock lock(mutex);
idle.wait(lock, [&] { return jobs.empty(); });
}
void DrawFinisher::Drain() {
if (OnFinisherThread()) return;
if (Busy() && GuestMemory::GpuMutex().HeldByThisThread()) throw std::runtime_error("draw finisher drain under the GPU lock");
SpinUntil(HandoffSpinWindow() * 2, [&] { return outstanding.load(std::memory_order_acquire) == 0; });
std::unique_lock lock(mutex);
if (!jobs.empty()) idle.wait(lock, [&] { return jobs.empty(); });
if (failure != nullptr) std::rethrow_exception(std::exchange(failure, nullptr));
}
void DrawFinisher::ReleaseRan() {
std::vector<Job> done;
std::lock_guard lock(mutex);
std::swap(done, ran);
}
DrawPipeline& DrawPipeline::Queue0() {
static DrawPipeline* pipeline = new DrawPipeline();
return *pipeline;
@@ -78,9 +288,16 @@ void DrawPipeline::rethrowFailure() {
std::rethrow_exception(error);
}
void DrawPipeline::Enqueue(Commit commit, std::vector<Range> writes, std::uint64_t labelAddress, std::vector<std::byte> labelBytes, std::vector<Range> reads) {
void DrawPipeline::Enqueue(Commit commit, std::vector<Range> writes, std::uint64_t labelAddress, std::vector<std::byte> labelBytes, std::vector<Range> reads, bool draw) {
if (DrawFinisher::Busy() && !DrawFinisher::OnFinisherThread()) DrawFinisher::Get().Drain();
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
struct ReclaimStorage {};
auto& reclaim = HostThreadLocal<std::vector<Item>, ReclaimStorage>();
reclaim.clear();
const auto lockStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
std::unique_lock lock(mutex);
if (!retired.empty()) std::swap(retired, reclaim);
if (profile) lockWaitNs += elapsedNs(lockStart);
rethrowFailure();
if (closing) {
lock.unlock();
@@ -90,23 +307,33 @@ void DrawPipeline::Enqueue(Commit commit, std::vector<Range> writes, std::uint64
if (items.size() >= Depth()) {
if (GuestMemory::GpuMutex().HeldByThisThread()) throw std::runtime_error("draw pipeline full while the enqueuing thread holds the GPU lock");
const auto start = std::chrono::steady_clock::now();
resumeAt = Depth() - 1;
++idleWaiters;
idle.wait(lock, [&] { return items.size() < Depth(); });
idle.wait(lock, [&] { return items.size() <= resumeAt; });
--idleWaiters;
resumeAt = 0;
fullWaitNs += elapsedNs(start);
rethrowFailure();
}
depthSum += items.size();
++enqueued;
heldReadRanges.fetch_add(reads.size(), std::memory_order_relaxed);
items.push_back({std::move(commit), std::move(writes), labelAddress, std::move(labelBytes), std::move(reads)});
countWrites(writes, true);
items.push_back({std::move(commit), std::move(writes), labelAddress, std::move(labelBytes), std::move(reads), draw});
outstanding.fetch_add(1, std::memory_order_release);
if (!thread.joinable()) {
thread = std::thread([this] { run(); });
thread = std::thread([this] {
GuestMemory::MarkProofThread();
run();
});
runningCommitters.fetch_add(1, std::memory_order_acq_rel);
}
if (committerWaiting) wake.notify_one();
if (!profile) return;
if (committerWaiting) {
++wakes;
wake.notify_one();
}
static const bool stats = std::getenv("APS5_PIPELINE_STATS") != nullptr;
if (!profile && !stats) return;
const auto now = std::chrono::steady_clock::now();
if (now - lastReport >= std::chrono::seconds(10)) report(now);
}
@@ -135,17 +362,19 @@ void DrawPipeline::report(std::chrono::steady_clock::time_point now) {
char reads[64];
std::snprintf(reads, sizeof(reads), " %llu read ranges, %llu stores held", static_cast<unsigned long long>(heldReadRanges.load(std::memory_order_relaxed)), static_cast<unsigned long long>(heldReadHits.exchange(0, std::memory_order_relaxed)));
drainText += reads;
std::fprintf(stderr, "[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;%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, reads, drainText.c_str());
commits = commitNs = commitErrors = enqueued = fullWaitNs = depthSum = 0;
std::fprintf(stderr, "[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());
commits = commitNs = commitErrors = enqueued = fullWaitNs = depthSum = wakes = lockWaitNs = 0;
drains = {};
drainWaitNs = {};
}
void DrawPipeline::run() {
PerformanceTrace::BindThread("draw committer");
StartCommitterSampler();
for (;;) {
Commit* commit = nullptr;
bool isDraw = false;
SpinUntil(HandoffSpinWindow(), [&] { return outstanding.load(std::memory_order_acquire) != 0; });
{
std::unique_lock lock(mutex);
@@ -154,6 +383,7 @@ void DrawPipeline::run() {
committerWaiting = false;
if (items.empty()) break;
commit = stopped ? nullptr : &items.front().commit;
isDraw = items.front().draw;
}
const auto start = std::chrono::steady_clock::now();
std::exception_ptr fatal;
@@ -161,6 +391,7 @@ void DrawPipeline::run() {
bool shutdown = false;
try {
if (commit != nullptr) (*commit)();
if (!isDraw) GuestMemory::BreakProofs();
} catch (const std::exception&) {
failed = true;
fatal = std::current_exception();
@@ -176,13 +407,15 @@ void DrawPipeline::run() {
if (!shutdown) Driver::Get().ReportFailure(fatal);
}
std::lock_guard lock(mutex);
countWrites(items.front().writes, false);
retired.push_back(std::move(items.front()));
items.pop_front();
++commits;
commitNs += spent;
if (failed) ++commitErrors;
if (fatal != nullptr && failure == nullptr) failure = fatal;
outstanding.fetch_sub(1, std::memory_order_release);
if (idleWaiters != 0) idle.notify_all();
if (idleWaiters != 0 && (items.empty() || items.size() <= resumeAt)) idle.notify_all();
}
runningCommitters.fetch_sub(1, std::memory_order_acq_rel);
}
@@ -200,10 +433,18 @@ void DrawPipeline::Stop() {
else committer.join();
}
void DrawPipeline::ReleaseRetired() {
std::vector<Item> done;
std::lock_guard lock(mutex);
std::swap(done, retired);
}
void DrawPipeline::Drain(DrainReason reason, std::uint32_t opcode) {
drainRequests[std::min<std::uint32_t>(opcode, 0x100)].fetch_add(1, std::memory_order_relaxed);
const bool finisherBusy = DrawFinisher::Busy() && !DrawFinisher::OnFinisherThread();
if ((finisherBusy || Busy()) && GuestMemory::GpuMutex().HeldByThisThread()) throw std::runtime_error("draw pipeline drain under the GPU lock (reason " + std::to_string(static_cast<unsigned>(reason)) + ", opcode " + std::to_string(opcode) + ")");
if (finisherBusy) DrawFinisher::Get().Drain();
if (!Busy()) return;
if (GuestMemory::GpuMutex().HeldByThisThread()) throw std::runtime_error("draw pipeline drain under the GPU lock (reason " + std::to_string(static_cast<unsigned>(reason)) + ", opcode " + std::to_string(opcode) + ")");
const auto start = std::chrono::steady_clock::now();
SpinUntil(HandoffSpinWindow() * 2, [&] { return !Busy(); });
std::unique_lock lock(mutex);
@@ -244,6 +485,12 @@ void DrawPipeline::ReleaseRunningReads() {
std::optional<std::uint64_t> DrawPipeline::PendingLabel(std::uint64_t address, std::size_t bytes) {
if (bytes == 0 || bytes > 8) return std::nullopt;
if (DrawFinisher::Overlap()) {
std::uint64_t held = 0;
const auto lookup = DrawFinisher::Get().PendingLabel(address, bytes, held);
if (lookup == DrawFinisher::LabelLookup::Value) return held;
if (lookup == DrawFinisher::LabelLookup::Unknown) return std::nullopt;
}
const auto end = address + bytes;
std::lock_guard lock(mutex);
for (auto item = items.rbegin(); item != items.rend(); ++item) {
@@ -257,15 +504,42 @@ std::optional<std::uint64_t> DrawPipeline::PendingLabel(std::uint64_t address, s
return std::nullopt;
}
bool DrawPipeline::Overlaps(std::uint64_t address, std::size_t bytes) {
const auto end = address + bytes;
void DrawPipeline::countWrites(const std::vector<Range>& writes, bool added) {
for (const auto& range : writes) {
const auto found = std::find_if(queuedWrites.begin(), queuedWrites.end(), [&](const auto& entry) { return entry.first == range; });
if (added) {
if (found != queuedWrites.end()) ++found->second;
else queuedWrites.emplace_back(range, 1u);
} else if (found != queuedWrites.end() && --found->second == 0) {
*found = queuedWrites.back();
queuedWrites.pop_back();
}
}
}
bool DrawPipeline::Busy() const {
return outstanding.load(std::memory_order_acquire) != 0 || (finisherProducer && DrawFinisher::Busy() && DrawFinisher::Overlap());
}
bool DrawPipeline::OverlapsAny(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges) {
if (DrawFinisher::Overlap() && DrawFinisher::Get().PendingOverlapsAny(ranges)) return true;
std::lock_guard lock(mutex);
for (const auto& item : items) {
for (const auto& [begin, limit] : item.writes) {
if (address < limit && begin < end) return true;
for (const auto& [range, count] : queuedWrites) {
for (const auto& [address, end] : ranges) {
if (address < range.second && range.first < end) return true;
}
}
return false;
}
bool DrawPipeline::Overlaps(std::uint64_t address, std::size_t bytes) {
const auto end = address + bytes;
if (DrawFinisher::Overlap() && DrawFinisher::Get().PendingOverlaps(address, end)) return true;
std::lock_guard lock(mutex);
for (const auto& [range, count] : queuedWrites) {
if (address < range.second && range.first < end) return true;
}
return false;
}
}
@@ -3,6 +3,7 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp"
#include <cstdlib>
namespace AgcDriver::DriverDetail {
@@ -16,6 +17,25 @@ std::optional<DrawVerdict> Driver::precheckDraw(const QueueState& queue, const S
if (!drawParameters.indirect && !drawParameters.indexed && (drawParameters.indexCount == 0 || drawParameters.instanceCount == 0)) return DrawVerdict::Nothing;
if (const auto pass = Graphics::DecodeColorMetadataPass(queue)) {
require(!drawParameters.indirect, "indirect CB metadata passes are unsupported");
if (DrawPipeline::Active() && DrawPipeline::MetadataPassesPipelined() && deferredLabels().labels.empty()) {
auto writes = Graphics::PipelinedColorMetadataPassWrites(*pass);
const auto localDevice = device.Load();
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] {
GuestMemory::SetCurrentPacket(opcode, queueId);
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Draw);
std::lock_guard gpuLock(GuestMemory::GpuMutex());
auto current = device.Load();
const auto& target = current != nullptr ? current : localDevice;
recordLabelsForPacket(target.get(), queueId);
target->ColorMetadataPass(pass);
}, std::move(writes));
DrawPipeline::CountPipelinedMetadataPass();
return DrawVerdict::Drawn;
}
}
if (DrawPipeline::Active()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, (packet[0] >> 8u) & 0xffu);
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Draw);
std::lock_guard gpuLock(GuestMemory::GpuMutex());
@@ -213,7 +213,7 @@ void Driver::traceDrawKeyLookup(const std::array<std::uint64_t, 5>& components,
}
bool Driver::sameVertexInfo(const ShaderRecompiler::ShaderVertexStageInfo& a, const ShaderRecompiler::ShaderVertexStageInfo& b) {
if (a.resourcesNum != b.resourcesNum || a.fetchAttribReg != b.fetchAttribReg || a.fetchBufferReg != b.fetchBufferReg || a.fetchEmbedded != b.fetchEmbedded || a.paClVsOutCntl != b.paClVsOutCntl) return false;
if (a.resourcesNum != b.resourcesNum || a.fetchAttribReg != b.fetchAttribReg || a.fetchBufferReg != b.fetchBufferReg || a.fetchEmbedded != b.fetchEmbedded || a.paClVsOutCntl != b.paClVsOutCntl || a.pointList != b.pointList || a.pointSize != b.pointSize || a.pointSizeMin != b.pointSizeMin || a.pointSizeMax != b.pointSizeMax) return false;
if (a.depthRemapMode != b.depthRemapMode) return false;
for (std::uint32_t i = 0; i < a.resourcesNum && i < a.resources.size(); ++i) {
if (a.resources[i].fields != b.resources[i].fields) return false;
@@ -263,7 +263,7 @@ bool Driver::sameDecode(const DrawDecode& a, const DrawDecode& b) {
if (x.binary.stage != y.binary.stage || x.binary.codeAddress != y.binary.codeAddress || x.userDataBase != y.userDataBase || x.firstUserSgpr != y.firstUserSgpr || x.userData != y.userData || x.snapshot != y.snapshot || x.codeOffset != y.codeOffset || x.tailContinuation != y.tailContinuation) return false;
}
if (p.targetExportPacking != q.targetExportPacking || p.dualSourceBlend != q.dualSourceBlend || p.reversedBlend != q.reversedBlend || p.alphaToCoverage != q.alphaToCoverage || p.rasterPrimitive != q.rasterPrimitive || p.ditheredAlphaToCoverage != q.ditheredAlphaToCoverage || p.quadPixelMask != q.quadPixelMask || p.quadSampleMask != q.quadSampleMask || p.iteratesSamples != q.iteratesSamples || p.positionLocation != q.positionLocation || p.sampleLocations != q.sampleLocations || p.sampleOrder != q.sampleOrder) return false;
if (s.samples != t.samples || s.mergedCoverage != t.mergedCoverage || s.quadSampleMask != t.quadSampleMask || s.pixelEarlyZ != t.pixelEarlyZ) return false;
if (s.samples != t.samples || s.mergedCoverage != t.mergedCoverage || s.truncatedCoverage != t.truncatedCoverage || s.quadSampleMask != t.quadSampleMask || s.pixelEarlyZ != t.pixelEarlyZ) return false;
return true;
}
@@ -161,7 +161,13 @@ void Driver::stop() {
for (auto& [queue, worker] : workers) {
if (worker.thread.joinable()) worker.thread.join();
}
try {
DrawFinisher::Get().Drain();
} catch (...) {
}
DrawPipeline::Queue0().Stop();
DrawPipeline::Queue0().ReleaseRetired();
DrawFinisher::Get().ReleaseRan();
StopWorkerSampler();
CloseRegistrationPreparation();
Graphics::StopPipelineLibraryWorker();
@@ -224,13 +230,17 @@ Driver::Driver() {
void Driver::WaitIdle() {
require(!onWorkerThread(), "worker cannot wait for itself");
std::unique_lock lock(mutex);
const auto target = accepted;
++idleWaiters;
changed.wait(lock, [&] { return failure != nullptr || stopping || completed >= target; });
--idleWaiters;
rethrowFailure();
checkStopping();
{
std::unique_lock lock(mutex);
const auto target = accepted;
++idleWaiters;
changed.wait(lock, [&] { return failure != nullptr || stopping || completed >= target; });
--idleWaiters;
rethrowFailure();
checkStopping();
}
std::lock_guard gpuLock(GuestMemory::GpuMutex());
if (const auto localDevice = device.Load()) localDevice->WaitIdle();
}
void Driver::CheckFailure() {
@@ -34,6 +34,24 @@ bool pipelineDma() {
return enabled;
}
bool keepsDrawFinisher(std::uint32_t header, std::uint32_t opcode) {
if (header == FlipPacketHeader || header == RenderingWaitPacketHeader) return false;
if (Pm4::DrawOpcode(opcode)) return true;
switch (opcode) {
case 0x13: case 0x26: case 0x2a: case 0x2f: case 0x69: case 0x76: case 0x79: return true;
case 0x10: return ((header >> 2u) & 0x3fu) == 0;
default: return false;
}
}
bool waitTakesPendingLabel(std::span<const std::uint32_t> packet) {
if (packet.size() < 5) return false;
const auto awaitedBytes = Pm4::WaitAwaitedBytes(packet);
const std::uint64_t awaited = (packet[2] & (awaitedBytes == 8 ? ~7u : ~3u)) | (static_cast<std::uint64_t>(packet[3]) << 32u);
const auto value = DrawPipeline::Queue0().PendingLabel(awaited, awaitedBytes);
return value.has_value() && Pm4::WaitComparesValue(packet, *value);
}
bool keepsDrawPipeline(std::span<const std::uint32_t> packet, std::uint32_t header, std::uint32_t opcode) {
if (header == FlipPacketHeader || header == RenderingWaitPacketHeader) return false;
if (Pm4::DrawOpcode(opcode)) return true;
@@ -108,13 +126,17 @@ void Driver::deliverFlipEopInterrupt(std::uint32_t queue) {
template <typename TWork>
void Driver::timed(double WorkerProfile::*bucket, TWork&& work) {
static const bool report = std::getenv("APS5_PROFILE_DRAW") != nullptr;
if (!report) {
work();
return;
}
static thread_local WorkerProfile profile;
const auto begin = std::chrono::steady_clock::now();
work();
const auto end = std::chrono::steady_clock::now();
profile.*bucket += std::chrono::duration<double, std::milli>(end - begin).count();
static const bool report = std::getenv("APS5_PROFILE_DRAW") != nullptr;
if (report && end - profile.reported > std::chrono::seconds(10)) {
if (end - profile.reported > std::chrono::seconds(10)) {
profile.reported = end;
AgcDriver::ProfilePrint_nid_no_patch( "[gpu] worker at %.0f s: dispatch %.1f s, draw %.1f s, wait %.1f s\n", std::chrono::duration<double>(end - profile.start).count(), profile.dispatchMs / 1000, profile.drawMs / 1000, profile.waitMs / 1000);
}
@@ -226,6 +248,12 @@ void Driver::execute(const Submission& submission) {
struct ClearAhead {
~ClearAhead() { clearResolvedAhead(); }
} clearAhead;
struct SettleFinisher {
bool queue0;
~SettleFinisher() {
if (queue0) DrawFinisher::Get().Settle();
}
} settleFinisher{submission.queue == 0};
for (std::size_t cursor = 0; cursor < submission.commands.size();) {
if (packetEpoch()) bumpEpoch(&EpochBumps::packets);
CheckFailure();
@@ -235,10 +263,20 @@ void Driver::execute(const Submission& submission) {
const auto packet = std::span(submission.commands).subspan(cursor, count);
const auto opcode = (header >> 8u) & 0xffu;
auto nextCursor = cursor + count;
const bool predicated = Pm4::Predicated(header) && queue.predication.operation != 0;
if (submission.queue == 0 && DrawFinisher::Busy() && !keepsDrawFinisher(header, opcode)) {
const bool queuesLabel = pipelined && !predicated && header != FlipPacketHeader && header != RenderingWaitPacketHeader && !submission.flips.contains(cursor) && labelPacketQueues(packet, opcode);
const bool heldLabelWait = pipelined && !predicated && orderedWaits && (opcode == 0x3c || opcode == 0x93) && header != RenderingWaitPacketHeader && waitTakesPendingLabel(packet);
const bool beside = DrawFinisher::Overlap() && opcode != 0x15 && (queuesLabel || heldLabelWait || keepsDrawPipeline(packet, header, opcode));
if (!beside) DrawFinisher::Get().Drain();
if (DrawFinisher::Overlap()) {
DrawFinisher::NoteDrain(DrawFinisher::DrainSite::Packet, !beside);
if (!beside) DrawFinisher::NoteDrainedOpcode(header == FlipPacketHeader ? 0xffu : opcode, keepsDrawPipeline(packet, header, opcode));
}
}
if (APS5_ENABLE_TIMING_LOG && submission.queue == 0 && pendingFrameTiming == nullptr) includeTimingSubmission(submission, false);
PerformanceContext timingContext(submission.queue == 0 ? pendingFrameTiming.get() : FrameTiming::Async());
PerformanceTimer timing("Driver.Packet");
const bool predicated = Pm4::Predicated(header) && queue.predication.operation != 0;
if (pipelined && !predicated && header != FlipPacketHeader && header != RenderingWaitPacketHeader && !submission.flips.contains(cursor) && (enqueueLabelPacket(packet, opcode, submission.queue) || enqueueDmaPacket(packet, opcode, submission.queue, queue))) {
traceLabel(packet, submission.queue);
recent.Record(cursor);
@@ -289,7 +327,7 @@ void Driver::execute(const Submission& submission) {
const auto flushStart = profilePackets ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
flushBetweenPackets(submission.queue, header, opcode == 0x49 || opcode == 0x37);
timing.Mark("flush_between_packets");
PacketTimer packetTimer{profilePackets, header == FlipPacketHeader ? 0xffffu : opcode, submission.queue, packetProfile, std::chrono::steady_clock::now()};
PacketTimer packetTimer{profilePackets, header == FlipPacketHeader ? 0xffffu : opcode, submission.queue, packetProfile, profilePackets ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}};
if (profilePackets) {
packetStartedAt() = packetTimer.start;
@@ -519,6 +557,7 @@ void Driver::execute(const Submission& submission) {
cursor = nextCursor;
}
if (submission.queue == 0) DrawFinisher::Get().Drain();
PerformanceContext endContext(submission.queue == 0 ? frameTiming() : FrameTiming::Async());
PerformanceTimer endTiming("Driver.EndSubmission");
static const bool submitAtEnd = std::getenv("APS5_SUBMIT_AT_END") != nullptr;
@@ -380,9 +380,15 @@ void Driver::commitDmaStore(std::uint32_t queue, std::uint64_t address, std::spa
Graphics::Recorder::CloseLabelGroup(GuestMemory::TrackerGeneration());
}
bool Driver::enqueueLabelPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue) {
bool Driver::labelPacketQueues(std::span<const std::uint32_t> packet, std::uint32_t opcode) {
static const bool ordered = std::getenv("APS5_PIPELINE_DRAIN_LABELS") == nullptr;
if (!ordered || !DeferLabels() || (opcode != 0x49 && opcode != 0x37) || !deferredLabels().labels.empty()) return false;
if (Pm4::DecodeLabelWrite(packet).has_value()) return true;
return opcode == 0x49 && ((packet[2] >> 29u) == 0 || (packet[3] | (static_cast<std::uint64_t>(packet[4]) << 32u)) == 0);
}
bool Driver::enqueueLabelPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue) {
if (!labelPacketQueues(packet, opcode)) return false;
const auto interruptSelect = opcode == 0x49 ? (packet[2] >> 24u) & 7u : 0u;
const bool endOfPipeInterrupt = interruptSelect != 0 && interruptSelect != 3;
const auto label = Pm4::DecodeLabelWrite(packet);
@@ -406,10 +412,23 @@ bool Driver::enqueueLabelPacket(std::span<const std::uint32_t> packet, std::uint
}
if (endOfPipeInterrupt) bumpEpoch(&EpochBumps::drains);
auto stored = bytes;
DrawPipeline::Queue0().Enqueue([this, queue, opcode, address, bytes = std::move(bytes), endOfPipeInterrupt] {
GuestMemory::SetCurrentPacket(opcode, queue);
commitLabel(queue, address, bytes, endOfPipeInterrupt);
}, std::move(writes), address, std::move(stored));
auto labelBytes = bytes;
auto enqueue =[this, queue, opcode, address, bytes = std::move(bytes), endOfPipeInterrupt, writes, stored = std::move(stored)]() mutable {
DrawPipeline::Queue0().Enqueue([this, queue, opcode, address, bytes = std::move(bytes), endOfPipeInterrupt] {
GuestMemory::SetCurrentPacket(opcode, queue);
commitLabel(queue, address, bytes, endOfPipeInterrupt);
}, std::move(writes), address, std::move(stored));
};
if (queue == 0 && DrawFinisher::Overlap() && DrawFinisher::Busy()) {
DrawFinisher::Pending held;
held.unknown = false;
held.writes = std::move(writes);
held.labelAddress = address;
held.labelBytes = std::move(labelBytes);
DrawFinisher::Get().Enqueue(std::move(enqueue), std::move(held));
return true;
}
enqueue();
return true;
}
@@ -236,6 +236,216 @@ bool ProgramUsesWorkgroup(const ShaderSnapshot& snapshot, std::size_t codeOffset
return used;
}
namespace {
bool readOnlyMemoryOp(ShaderRecompiler::RdnaOpcode op) {
using Op = ShaderRecompiler::RdnaOpcode;
switch (op) {
case Op::SLoadDword:
case Op::SLoadDwordx2:
case Op::SLoadDwordx4:
case Op::SLoadDwordx8:
case Op::SLoadDwordx16:
case Op::BufferLoadFormatX:
case Op::BufferLoadFormatXy:
case Op::BufferLoadFormatXyz:
case Op::BufferLoadFormatXyzw:
case Op::BufferLoadDword:
case Op::BufferLoadDwordx2:
case Op::BufferLoadDwordx4:
case Op::ImageSample:
case Op::ImageSampleLz:
case Op::ImageSampleBCl:
case Op::ImageSampleBClO:
case Op::ImageSampleBO:
case Op::ImageSampleC:
case Op::ImageSampleCB:
case Op::ImageSampleCBCl:
case Op::ImageSampleCBClO:
case Op::ImageSampleCBO:
case Op::ImageSampleCCl:
case Op::ImageSampleCClO:
case Op::ImageSampleCD:
case Op::ImageSampleCDCl:
case Op::ImageSampleCDClO:
case Op::ImageSampleCDO:
case Op::ImageSampleCL:
case Op::ImageSampleCLzO:
case Op::ImageSampleCLO:
case Op::ImageSampleCO:
case Op::ImageSampleCl:
case Op::ImageSampleClO:
case Op::ImageSampleD:
case Op::ImageSampleDCl:
case Op::ImageSampleDO:
case Op::ImageSampleLzO:
case Op::ImageSampleO:
case Op::ImageSampleCd:
case Op::ImageSampleCdCl:
case Op::ImageSampleCCd:
case Op::ImageSampleCCdCl:
case Op::ImageSampleCdO:
case Op::ImageSampleCdClO:
case Op::ImageSampleCCdO:
case Op::ImageSampleCCdClO:
case Op::ImageSampleDG16:
case Op::ImageSampleDClG16:
case Op::ImageSampleCDG16:
case Op::ImageSampleCDClG16:
case Op::ImageSampleDOG16:
case Op::ImageSampleDClOG16:
case Op::ImageSampleCDOG16:
case Op::ImageSampleCDClOG16:
case Op::ImageSampleCdG16:
case Op::ImageSampleCdClG16:
case Op::ImageSampleCCdG16:
case Op::ImageSampleCCdClG16:
case Op::ImageSampleCdOG16:
case Op::ImageSampleCdClOG16:
case Op::ImageSampleCCdOG16:
case Op::ImageSampleCCdClOG16:
case Op::ImageLoad:
case Op::ImageGetResinfo:
case Op::SBufferLoadDword:
case Op::SBufferLoadDwordx2:
case Op::SBufferLoadDwordx4:
case Op::SBufferLoadDwordx8:
case Op::SBufferLoadDwordx16:
case Op::SScratchLoadDword:
case Op::SScratchLoadDwordx2:
case Op::SScratchLoadDwordx4:
case Op::BufferLoadUbyte:
case Op::BufferLoadSbyte:
case Op::BufferLoadUshort:
case Op::BufferLoadSshort:
case Op::BufferLoadDwordx3:
case Op::BufferLoadUbyteD16:
case Op::BufferLoadUbyteD16Hi:
case Op::BufferLoadSbyteD16:
case Op::BufferLoadSbyteD16Hi:
case Op::BufferLoadShortD16:
case Op::BufferLoadShortD16Hi:
case Op::TbufferLoadFormatX:
case Op::TbufferLoadFormatXy:
case Op::TbufferLoadFormatXyz:
case Op::TbufferLoadFormatXyzw:
case Op::TbufferLoadFormatD16X:
case Op::TbufferLoadFormatD16Xy:
case Op::TbufferLoadFormatD16Xyz:
case Op::TbufferLoadFormatD16Xyzw:
case Op::BufferLoadFormatD16X:
case Op::BufferLoadFormatD16Xy:
case Op::BufferLoadFormatD16Xyz:
case Op::BufferLoadFormatD16Xyzw:
case Op::BufferLoadFormatD16HiX:
case Op::FlatLoadUbyte:
case Op::FlatLoadSbyte:
case Op::FlatLoadUshort:
case Op::FlatLoadSshort:
case Op::FlatLoadDword:
case Op::FlatLoadDwordx2:
case Op::FlatLoadDwordx3:
case Op::FlatLoadDwordx4:
case Op::GlobalLoadDwordAddtid:
case Op::FlatLoadUbyteD16:
case Op::FlatLoadUbyteD16Hi:
case Op::FlatLoadSbyteD16:
case Op::FlatLoadSbyteD16Hi:
case Op::FlatLoadShortD16:
case Op::FlatLoadShortD16Hi:
case Op::ImageGetLod:
case Op::ImageLoadMip:
case Op::ImageLoadPck:
case Op::ImageLoadPckSgn:
case Op::ImageLoadMipPck:
case Op::ImageLoadMipPckSgn:
case Op::ImageLoadBy2:
case Op::ImageLoadBy4:
case Op::ImageLoadMipBy2:
case Op::ImageLoadMipBy4:
case Op::ImageLoadPck2:
case Op::ImageLoadPck4:
case Op::ImageLoadMipPck2:
case Op::ImageLoadMipPck4:
case Op::ImageMsaaLoad:
case Op::ImageGather4Lz:
case Op::ImageGather4C:
case Op::ImageGather4CLz:
case Op::ImageGather4LzO:
case Op::ImageGather4CO:
case Op::ImageGather4CLzO:
case Op::ImageGather4h:
case Op::ImageGather4hPck:
case Op::ImageGather4:
case Op::ImageGather4B:
case Op::ImageGather4BCl:
case Op::ImageGather4BClO:
case Op::ImageGather4BO:
case Op::ImageGather4Cl:
case Op::ImageGather4ClO:
case Op::ImageGather4CB:
case Op::ImageGather4CBCl:
case Op::ImageGather4CBClO:
case Op::ImageGather4CBO:
case Op::ImageGather4CCl:
case Op::ImageGather4CClO:
case Op::ImageGather4CL:
case Op::ImageGather4CLO:
case Op::ImageGather4L:
case Op::ImageGather4LO:
case Op::ImageGather4O:
case Op::ImageBvhIntersectRay:
case Op::SGl1Inv:
case Op::SDcacheInv:
case Op::SDcacheWb:
case Op::SMemtime:
case Op::SMemrealtime:
case Op::SDcacheDiscard:
case Op::SDcacheDiscardX2:
case Op::BufferGl0Inv:
case Op::BufferGl1Inv:
return true;
default:
return false;
}
}
bool decodedWritesMemory(std::span<const std::uint32_t> code) {
using Family = ShaderRecompiler::RdnaInstructionFamily;
using Op = ShaderRecompiler::RdnaOpcode;
try {
const auto decoded = ShaderRecompiler::RdnaInstructionDecoder{}.Decode(code);
return std::any_of(decoded.instructions.begin(), decoded.instructions.end(), [](const auto& instruction) {
switch (instruction.family) {
case Family::MUBUF: case Family::MTBUF: case Family::FLAT: case Family::MIMG: case Family::SMEM:
return !readOnlyMemoryOp(instruction.op);
case Family::DS:
return instruction.gds || instruction.op == Op::DsGwsInit || instruction.op == Op::DsGwsBarrier || instruction.op == Op::DsGwsSemaV || instruction.op == Op::DsGwsSemaP || instruction.op == Op::DsGwsSemaBr || instruction.op == Op::DsGwsSemaReleaseAll || instruction.op == Op::DsOrderedCount || instruction.op == Op::DsAppend || instruction.op == Op::DsConsume;
case Family::Unknown:
return true;
default:
return instruction.op == Op::SSetpcB64 || instruction.op == Op::SSwappcB64 || instruction.op == Op::SRfeB64;
}
});
} catch (const std::exception&) {
return true;
}
}
}
bool ProgramWritesMemory(const ShaderSnapshot& snapshot, std::size_t codeOffset) {
constexpr std::uint8_t Unknown = 0, Reads = 1, Writes = 2;
if (codeOffset == 0) {
const auto cached = snapshot.memoryWrites->load(std::memory_order_acquire);
if (cached != Unknown) return cached == Writes;
}
if (codeOffset > snapshot.code.size()) return true;
const bool writes = decodedWritesMemory(std::span(snapshot.code).subspan(codeOffset));
if (codeOffset == 0) snapshot.memoryWrites->store(writes ? Writes : Reads, std::memory_order_release);
return writes;
}
std::uint32_t PositionExportLayout(const ShaderSnapshot* snapshot, std::size_t codeOffset, std::span<const std::uint32_t> code, std::uint32_t paClVsOutCntl, const ShaderSnapshot* continuation) {
constexpr std::uint8_t Unknown = 0, Unused = 1, Used = 2;
const auto bits = paClVsOutCntl & Graphics::PositionExportLayoutBits;
@@ -1146,9 +1356,8 @@ public:
Closing() = true;
pools = {Existing(), ExistingPrebuild()};
}
for (auto* pool : pools) {
if (pool != nullptr) pool->Close();
}
if (pools[0] != nullptr) pools[0]->Close(false);
if (pools[1] != nullptr) pools[1]->Close(true);
}
private:
@@ -1204,11 +1413,17 @@ public:
idle.wait(lock, [&] { return unfinished.empty() || *unfinished.begin() > ticket; });
}
void Close() {
void Close(bool dropQueued) {
std::vector<Worker> joined;
std::deque<Task> dropped;
{
std::unique_lock lock(mutex);
closed = true;
if (dropQueued) {
dropped.swap(tasks);
for (const auto& task : dropped) unfinished.erase(task.sequence);
idle.notify_all();
}
idle.wait(lock, [&] { return tasks.empty() && running == 0; });
joined.swap(workers);
}
@@ -1435,7 +1650,10 @@ std::vector<PreparedGraphicsStage> PrepareGraphicsStages(const DrawDecode& decod
prepared.push_back({program.snapshot, {program.codeOffset, nullptr}, program.binary.stage, offset, nullptr});
continue;
}
if (vertex) vertex->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, decoded.state.paClVsOutCntl, program.tailContinuation.get()) | decoded.state.layerExports;
if (vertex) {
vertex->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, decoded.state.paClVsOutCntl, program.tailContinuation.get()) | decoded.state.layerExports;
Graphics::ApplyPointSize(decoded.state, *vertex);
}
ShaderRecompiler::RecompileRequest request{program.binary, {wave, program.firstUserSgpr, program.userData, {}, fragment ? std::optional(decoded.pixel) : std::nullopt, vertex, memory, RegisteredFloatMode(*program.snapshot)}, target, {0, 0, offset, room}, ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, decoded.state.stages.mesh, decoded.state.stages.tessellation, {}}};
std::vector<std::uint64_t> key;
ShaderRecompiler::BuildPreparedShaderKey(request, key);
@@ -971,8 +971,10 @@ struct WriteTracker {
struct DriverPieces {
std::uint32_t whole = 0;
std::uint32_t dropped = 0;
std::uint32_t next = 0;
std::array<DriverPiece, 4> pieces{};
std::uint32_t possibleWhole = 0;
std::uint32_t possibleDropped = 0;
std::array<DriverPiece, 4> possiblePieces{};
bool covers(std::uint32_t begin, std::uint32_t end, std::uint64_t generation) const {
if (generation == 0 || begin >= end || dropped > generation) return false;
@@ -1025,7 +1027,7 @@ struct WriteTracker {
#endif
}
void stampWatchedPart(std::uint64_t address, std::uint64_t end, std::uint32_t stampGeneration) {
void stampWatchedPart(std::uint64_t address, std::uint64_t end, std::uint32_t stampGeneration, bool complete) {
#ifdef _WIN32
address = std::max<std::uint64_t>(address, base);
end = std::min<std::uint64_t>(end, base + size);
@@ -1039,24 +1041,45 @@ struct WriteTracker {
const auto stop = std::min<std::uint64_t>(end, blockBegin(block) + WriteBlockBytes);
if (!blockPartWatched(first, stop)) continue;
stamp(block, stampGeneration, StampKind::Driver);
noteDriverStore(block, address, end, stampGeneration);
noteDriverStore(block, address, end, stampGeneration, complete);
}
}
void noteDriverStore(std::uint64_t block, std::uint64_t address, std::uint64_t end, std::uint32_t stampGeneration) {
void noteDriverStore(std::uint64_t block, std::uint64_t address, std::uint64_t end, std::uint32_t stampGeneration, bool complete) {
const auto begin = blockBegin(block);
const auto from = static_cast<std::uint32_t>(std::max(address, begin) - begin);
const auto to = static_cast<std::uint32_t>(std::min<std::uint64_t>(end, begin + WriteBlockBytes) - begin);
if (from == 0 && to == WriteBlockBytes) {
auto& entry = driverPieces[block];
entry = DriverPieces{};
entry.whole = stampGeneration;
if (complete) {
entry = DriverPieces{};
entry.whole = stampGeneration;
} else {
entry.possibleWhole = stampGeneration;
entry.possibleDropped = 0;
entry.possiblePieces = {};
}
return;
}
auto& entry = driverPieces[block];
auto& slot = entry.pieces[entry.next++ % entry.pieces.size()];
entry.dropped = std::max(entry.dropped, slot.generation);
slot = {stampGeneration, from, to};
auto& pieces = complete ? entry.pieces : entry.possiblePieces;
auto& dropped = complete ? entry.dropped : entry.possibleDropped;
DriverPiece* contained = nullptr;
for (auto& piece : pieces) {
if (piece.generation == 0 || piece.begin < from || piece.end > to) continue;
if (contained == nullptr) contained = &piece;
else piece = {};
}
if (contained != nullptr) {
*contained = {stampGeneration, from, to};
return;
}
auto* oldest = &pieces.front();
for (auto& piece : pieces) {
if (piece.generation < oldest->generation) oldest = &piece;
}
dropped = std::max(dropped, oldest->generation);
*oldest = {stampGeneration, from, to};
}
Leaf& leafFor(std::uint64_t block) {
@@ -1167,10 +1190,13 @@ struct WriteTracker {
continue;
}
const auto& entry = found->second;
if (entry.whole > generation || entry.dropped > generation) return true;
if (entry.whole > generation || entry.dropped > generation || entry.possibleWhole > generation || entry.possibleDropped > generation) return true;
for (const auto& piece : entry.pieces) {
if (piece.generation > generation && piece.begin < to && from < piece.end) return true;
}
for (const auto& piece : entry.possiblePieces) {
if (piece.generation > generation && piece.begin < to && from < piece.end) return true;
}
}
return false;
}
@@ -1459,6 +1485,23 @@ std::uint64_t CollectEpochBumps() {
return collectEpochBumps.load(std::memory_order_relaxed);
}
namespace {
std::atomic<std::uint64_t> proofSerial{1};
thread_local bool proofThread = false;
}
std::uint64_t ProofSerial() {
return proofSerial.load(std::memory_order_acquire);
}
void BreakProofs() {
proofSerial.fetch_add(1, std::memory_order_acq_rel);
}
void MarkProofThread() {
proofThread = true;
}
std::uint64_t CollectEpoch() {
return collectMemoEnabled() ? threadCollectEpoch : 0;
}
@@ -1666,17 +1709,18 @@ bool UnchangedCommittedSince(std::span<const std::pair<std::uint64_t, std::uint6
std::uint64_t storeOwn(std::uint64_t address, std::size_t bytes, const std::function<std::pair<std::uint64_t, std::uint64_t>()>& store) {
if (bytes == 0) return 0;
BreakProofs();
const auto stampStored = [](WriteTracker& tracker, std::pair<std::uint64_t, std::uint64_t> stored) -> std::uint64_t {
if (stored.second <= stored.first) return 0;
++tracker.generation;
if (!tracker.watched || !tracker.covers(stored.first, static_cast<std::size_t>(stored.second - stored.first))) {
tracker.noteUnstampedStore(stored.first, stored.second);
if (tracker.watched) tracker.stampWatchedPart(stored.first, stored.second, tracker.generation);
if (tracker.watched) tracker.stampWatchedPart(stored.first, stored.second, tracker.generation, true);
return 0;
}
for (auto block = tracker.blockOf(stored.first); block <= tracker.blockOf(stored.second - 1); ++block) {
tracker.stamp(block, tracker.generation, StampKind::Driver);
tracker.noteDriverStore(block, stored.first, stored.second, tracker.generation);
tracker.noteDriverStore(block, stored.first, stored.second, tracker.generation, true);
}
return tracker.generation;
};
@@ -1709,7 +1753,8 @@ std::uint64_t StoreOwnBytes(std::uint64_t address, std::span<const std::byte> so
});
}
std::uint64_t MarkWritten(std::uint64_t address, std::size_t bytes) {
static std::uint64_t markWritten(std::uint64_t address, std::size_t bytes, bool complete) {
BreakProofs();
auto& tracker = Tracker();
auto lock = lockTracker(tracker);
tracker.initialize();
@@ -1717,7 +1762,7 @@ std::uint64_t MarkWritten(std::uint64_t address, std::size_t bytes) {
++tracker.generation;
if (!tracker.watched || !tracker.covers(address, bytes)) {
tracker.noteUnstampedStore(address, address + bytes);
if (tracker.watched) tracker.stampWatchedPart(address, address + bytes, tracker.generation);
if (tracker.watched) tracker.stampWatchedPart(address, address + bytes, tracker.generation, complete);
return 0;
}
{
@@ -1725,11 +1770,11 @@ std::uint64_t MarkWritten(std::uint64_t address, std::size_t bytes) {
const auto blockStop = (address + bytes + WriteBlockBytes - 1) & ~(std::uint64_t{WriteBlockBytes} - 1);
StampRuns runs{tracker, StampKind::Fresh};
#ifdef _WIN32
const bool complete = collectWindowsWrites(runs, blockFirst, blockStop, false);
const bool collected = collectWindowsWrites(runs, blockFirst, blockStop, false);
#else
const bool complete = GuestWriteWatch::GuestWriteWatchCollectFresh_nid_postfix(static_cast<std::uintptr_t>(blockFirst), static_cast<std::size_t>(blockStop - blockFirst), &stampWrittenRun, &runs);
const bool collected = GuestWriteWatch::GuestWriteWatchCollectFresh_nid_postfix(static_cast<std::uintptr_t>(blockFirst), static_cast<std::size_t>(blockStop - blockFirst), &stampWrittenRun, &runs);
#endif
if (!complete) {
if (!collected) {
lock.unlock();
beforeUnwatch(blockFirst, static_cast<std::size_t>(blockStop - blockFirst));
lock.lock();
@@ -1743,11 +1788,19 @@ std::uint64_t MarkWritten(std::uint64_t address, std::size_t bytes) {
const auto last = tracker.blockOf(address + bytes - 1);
for (auto block = first; block <= last; ++block) {
tracker.stamp(block, tracker.generation, StampKind::Driver);
tracker.noteDriverStore(block, address, address + bytes, tracker.generation);
tracker.noteDriverStore(block, address, address + bytes, tracker.generation, complete);
}
return tracker.generation;
}
std::uint64_t MarkWritten(std::uint64_t address, std::size_t bytes) {
return markWritten(address, bytes, true);
}
std::uint64_t MarkPossiblyWritten(std::uint64_t address, std::size_t bytes) {
return markWritten(address, bytes, false);
}
bool StoredOver(std::uint64_t address, std::size_t bytes, std::uint64_t generation) {
auto& tracker = Tracker();
const auto lock = lockTracker(tracker);
@@ -2065,7 +2118,10 @@ std::atomic<std::uint64_t> gpuHoldSerial{0};
void GpuMutexType::acquired() {
owner.store(ThreadToken(), std::memory_order_relaxed);
if (++depth == 1) gpuHoldSerial.fetch_add(1, std::memory_order_relaxed);
if (++depth == 1) {
gpuHoldSerial.fetch_add(1, std::memory_order_relaxed);
if (!proofThread) BreakProofs();
}
}
bool GpuMutexType::try_lock() {
@@ -2420,6 +2476,7 @@ void WriteChangedCommitted(std::uint64_t address, std::span<const std::byte> cur
void WriteChanged(std::uint64_t address, std::span<const std::byte> current, std::span<const std::byte> original) {
require(current.size() == original.size(), "write-back snapshot sizes differ");
BreakProofs();
if (current.empty()) return;
// A store: the hook sync it makes orders this write after a pending GPU write, whatever a read
// site above it was doing (the [hooksync] line counts stores apart).
@@ -16,8 +16,12 @@ namespace {
std::atomic<bool> requested{false};
std::filesystem::path directory() {
#ifdef _WIN32
const wchar_t* configured = _wgetenv(L"ANYPS5_SCREENSHOTS");
#else
const char* configured = std::getenv("ANYPS5_SCREENSHOTS");
if (configured != nullptr && configured[0] != '\0') return configured;
#endif
if (configured != nullptr && configured[0] != 0) return configured;
const std::unique_ptr<char, decltype(&SDL_free)> basePath(SDL_GetBasePath(), SDL_free);
if (!basePath) throw std::runtime_error(std::string("Screenshot: cannot locate the executable: ") + SDL_GetError());
return std::filesystem::path(reinterpret_cast<const char8_t*>(basePath.get())) / "anyps5-screenshots";
@@ -18,6 +18,8 @@
#include <memory>
#include <stdexcept>
#include <vector>
#include <mutex>
#include <unordered_map>
namespace AgcDriver {
namespace {
@@ -130,6 +132,23 @@ std::vector<std::unique_ptr<TPage>>& pagePool() {
constexpr std::size_t PagePoolLimit = 64;
bool sharedPagePools() {
static const bool enabled = std::getenv("APS5_DRAW_PIPELINE") != nullptr;
return enabled;
}
template<typename TPage>
struct SharedPagePool {
std::mutex mutex;
std::vector<std::unique_ptr<TPage>> pages;
};
template<typename TPage>
SharedPagePool<TPage>& sharedPagePool() {
static auto* pool = new SharedPagePool<TPage>();
return *pool;
}
}
void ShaderMemory::SetWaitedMsProvider(WaitedMsProvider provider) {
@@ -144,6 +163,15 @@ ShaderMemory::ShaderMemory(std::span<const ShaderRecompiler::MemoryRegion> regio
}
ShaderMemory::~ShaderMemory() {
if (sharedPagePools() && !pages.empty()) {
auto& shared = sharedPagePool<Page>();
std::lock_guard lock(shared.mutex);
for (const auto& [base, page] : pages) {
if (shared.pages.size() < 1024) shared.pages.emplace_back(page);
else delete page;
}
return;
}
auto& pool = pagePool<Page>();
for (const auto& [base, page] : pages) {
if (pool.size() < PagePoolLimit) pool.emplace_back(page);
@@ -191,6 +219,14 @@ std::size_t ShaderMemory::pageAtOrAfter(std::uint64_t base) const {
ShaderMemory::Page& ShaderMemory::addPage(std::size_t position, std::uint64_t base) {
auto& pool = pagePool<Page>();
if (pool.empty() && sharedPagePools()) {
auto& shared = sharedPagePool<Page>();
std::lock_guard lock(shared.mutex);
for (std::size_t i = 0; i < 32 && !shared.pages.empty(); ++i) {
pool.push_back(std::move(shared.pages.back()));
shared.pages.pop_back();
}
}
std::unique_ptr<Page> owned;
if (pool.empty()) {
owned = std::make_unique<Page>();
@@ -156,20 +156,22 @@ public:
std::lock_guard lock(mutex);
stopping = true;
}
changed.notify_one();
changed.notify_all();
if (worker.joinable()) worker.join();
}
void Enqueue(int index, std::uint32_t width, std::uint32_t height, std::uint32_t scale, bool screenshot, std::vector<std::byte> pixels) {
std::lock_guard lock(mutex);
std::unique_lock lock(mutex);
require(!stopping, "frame dump writer has stopped");
require(pixels.size() <= maxBytes - queuedBytes, "frame dump queue exceeded 64 MiB");
if (!screenshot && !frameDumpOutput.Enabled_nid_no_patch()) return;
require(pixels.size() <= maxBytes, "a frame dump exceeds the 64 MiB queue");
changed.wait(lock, [&] { return stopping || pixels.size() <= maxBytes - queuedBytes; });
require(!stopping, "frame dump writer has stopped");
if (!worker.joinable()) worker = std::thread([this] { run(); });
const auto bytes = pixels.size();
pending.push_back({index, width, height, scale, screenshot, std::move(pixels)});
queuedBytes += bytes;
changed.notify_one();
changed.notify_all();
}
bool Idle() {
@@ -202,6 +204,7 @@ private:
else WriteFrameBmp(frame.index, frame.width, frame.height, frame.pixels, frame.scale);
std::lock_guard lock(mutex);
queuedBytes -= frame.pixels.size();
changed.notify_all();
}
}
} catch (const std::exception& error) {
@@ -313,6 +316,7 @@ struct VulkanDevice::State {
bool fragmentShaderBarycentric = false;
bool shaderTerminateInvocation = false;
bool geometryShader = false;
bool largePoints = false;
bool sampleRateShading = false;
bool storageImageMultisample = false;
bool storageImageWriteWithoutFormat = false;
@@ -342,6 +346,7 @@ struct VulkanDevice::State {
bool imageInt64Atomics = false;
bool bufferInt64Atomics = false;
bool viewportIndexLayer = false;
bool imageFormatList = false;
bool primitiveListRestart = false;
bool depthClipControl = false;
bool graphicsPipelineLibrary = false;
@@ -382,6 +387,8 @@ struct VulkanDevice::State {
bool samplerFilterMinmax = false;
bool nonSeamlessCubeMap = false;
VkSampleCountFlags mergedCoverageSampleCounts = 0;
VkSampleCountFlags truncatedCoverageSampleCounts = 0;
bool mixedAttachmentSamples = false;
bool fragmentShaderPixelInterlock = false;
bool conservativeRasterization = false;
bool provokingVertexLast = false;
@@ -1313,6 +1320,10 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
state->spirvExtensions.push_back("SPV_EXT_shader_viewport_index_layer");
state->viewportIndexLayer = true;
}
if (hasExtension(VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME)) {
deviceExtensions.push_back(VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME);
state->imageFormatList = true;
}
if (state->demoteToHelperInvocation) {
deviceExtensions.push_back(VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME);
state->capabilities.push_back(spv::CapabilityDemoteToHelperInvocation);
@@ -1507,12 +1518,17 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
check(combinations(selected, &count, supported.data()), "vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV");
for (const auto& combination : supported) {
if (combination.coverageReductionMode == VK_COVERAGE_REDUCTION_MODE_MERGE_NV && combination.colorSamples == VK_SAMPLE_COUNT_1_BIT && combination.depthStencilSamples == 0) state->mergedCoverageSampleCounts |= combination.rasterizationSamples;
if (combination.coverageReductionMode == VK_COVERAGE_REDUCTION_MODE_TRUNCATE_NV && combination.colorSamples == VK_SAMPLE_COUNT_1_BIT && combination.depthStencilSamples == combination.rasterizationSamples) state->truncatedCoverageSampleCounts |= combination.rasterizationSamples;
}
}
if (state->mergedCoverageSampleCounts != 0) {
if (state->mergedCoverageSampleCounts != 0 || state->truncatedCoverageSampleCounts != 0) {
deviceExtensions.push_back(VK_NV_FRAMEBUFFER_MIXED_SAMPLES_EXTENSION_NAME);
deviceExtensions.push_back(VK_NV_COVERAGE_REDUCTION_MODE_EXTENSION_NAME);
}
} else if (hasExtension(VK_AMD_MIXED_ATTACHMENT_SAMPLES_EXTENSION_NAME)) {
state->mixedAttachmentSamples = true;
state->truncatedCoverageSampleCounts = state->properties.limits.framebufferDepthSampleCounts & state->properties.limits.framebufferColorSampleCounts & ~static_cast<VkSampleCountFlags>(VK_SAMPLE_COUNT_1_BIT);
deviceExtensions.push_back(VK_AMD_MIXED_ATTACHMENT_SAMPLES_EXTENSION_NAME);
}
coverageReductionFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COVERAGE_REDUCTION_MODE_FEATURES_NV};
coverageReductionFeatures.coverageReductionMode = VK_TRUE;
@@ -1703,6 +1719,8 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
enabled.sampleRateShading = available.sampleRateShading;
enabled.geometryShader = available.geometryShader;
state->geometryShader = enabled.geometryShader == VK_TRUE;
enabled.largePoints = available.largePoints;
state->largePoints = enabled.largePoints == VK_TRUE;
state->sampleRateShading = enabled.sampleRateShading == VK_TRUE;
if (enabled.sampleRateShading) state->capabilities.push_back(spv::CapabilityInterpolationFunction);
if (enabled.geometryShader) state->capabilities.push_back(spv::CapabilityGeometry);
@@ -1803,7 +1821,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
nonSeamlessCubeFeatures.pNext = const_cast<void*>(deviceInfo.pNext);
deviceInfo.pNext = &nonSeamlessCubeFeatures;
}
if (state->mergedCoverageSampleCounts != 0) {
if (!state->mixedAttachmentSamples && (state->mergedCoverageSampleCounts != 0 || state->truncatedCoverageSampleCounts != 0)) {
coverageReductionFeatures.pNext = const_cast<void*>(deviceInfo.pNext);
deviceInfo.pNext = &coverageReductionFeatures;
}
@@ -3806,6 +3824,8 @@ Graphics::Context VulkanDevice::buildContext() const {
context.samplerFilterMinmax = state->samplerFilterMinmax;
context.nonSeamlessCubeMap = state->nonSeamlessCubeMap;
context.mergedCoverageSampleCounts = state->mergedCoverageSampleCounts;
context.truncatedCoverageSampleCounts = state->truncatedCoverageSampleCounts;
context.mixedAttachmentSamples = state->mixedAttachmentSamples;
context.conservativeRasterization = state->conservativeRasterization;
context.meshWave32 = state->meshWave32;
context.provokingVertexLast = state->provokingVertexLast;
@@ -3830,6 +3850,7 @@ Graphics::Context VulkanDevice::buildContext() const {
context.imageTableUpdateAfterBind = ImageTableUpdateAfterBind(context);
context.samplerTableUpdateAfterBind = SamplerTableUpdateAfterBind(context);
context.geometryShader = state->geometryShader;
context.largePoints = state->largePoints;
context.sampleRateShading = state->sampleRateShading;
context.fillModeNonSolid = state->fillModeNonSolid;
context.maintenance5 = state->maintenance5;
@@ -3842,6 +3863,7 @@ Graphics::Context VulkanDevice::buildContext() const {
context.bufferInt64Atomics = state->bufferInt64Atomics;
context.placeholderImages = state->placeholderImages.get();
context.viewportIndexLayer = state->viewportIndexLayer;
context.imageFormatList = state->imageFormatList;
context.demoteToHelperInvocation = state->demoteToHelperInvocation;
context.earlyFragmentSampleMaskTestBeforeSampleCounting = state->earlyFragmentSampleMaskTestBeforeSampleCounting;
context.primitiveListRestart = state->primitiveListRestart;
@@ -4403,6 +4425,7 @@ struct RecordedDispatch {
// A template hit's revalidate time, charged to the [rescache] refresh accounting.
double revalidateMs;
DispatchTimer* timer;
std::optional<std::pair<std::uint64_t, std::size_t>> htileClear;
// Whether the data refresh recorded anything.
bool refreshed = false;
bool resourceKeyMatched = false;
@@ -4663,8 +4686,8 @@ std::shared_ptr<RecipeHit> VulkanDevice::PrepareRecipe(const std::shared_ptr<con
return hit;
}
void VulkanDevice::Dispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::uint64_t programAddress, std::shared_ptr<PreparedDispatch> prepared, std::shared_ptr<const Recipe>* recipe) {
static_cast<void>(dispatch(shader, x, y, z, 0, snapshots, programAddress, std::move(prepared), recipe));
void VulkanDevice::Dispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::uint64_t programAddress, std::shared_ptr<PreparedDispatch> prepared, std::shared_ptr<const Recipe>* recipe, std::optional<std::pair<std::uint64_t, std::size_t>> htileClear) {
static_cast<void>(dispatch(shader, x, y, z, 0, snapshots, programAddress, std::move(prepared), recipe, {}, htileClear));
}
VulkanDevice::IndirectOutcome VulkanDevice::DispatchIndirect(const ShaderRecompiler::RecompileResult& shader, std::uint64_t arguments, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::uint64_t programAddress, std::shared_ptr<PreparedDispatch> prepared, std::shared_ptr<const Recipe>* recipe, const std::array<std::uint32_t, 3>& threadGroup) {
@@ -4925,21 +4948,31 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) {
recorder.EndGpuTiming(trailingTiming);
recorder.MarkCovered(dispatchedAccess);
recordStep(PhaseRecordBind);
if (record.htileClear.has_value()) Graphics::ArmHtileDepthClear(record.htileClear->first, record.htileClear->second);
resources.MarkGpuWrites(recorder);
if (record.htileClear.has_value()) {
Graphics::QueueHtileDepthClear(record.htileClear->first, record.htileClear->second);
recorder.NotePendingWrite(record.htileClear->first, record.htileClear->second);
}
recordStep(PhaseRecordMarks);
// Only copied written buffers (and BDA fault checks) need work once the GPU is done; without them
// the batch can signal its labels from the GPU.
if (resources.NeedsCompletion() && resources.Reusable()) {
const bool completionNeeded = resources.NeedsCompletion() || record.htileClear.has_value();
if (completionNeeded && resources.Reusable()) {
auto kept = record.resources;
recorder.OnComplete([kept] { kept->CheckFaults(); });
} else if (resources.NeedsCompletion()) {
recorder.OnComplete([kept, htileClear = record.htileClear] {
kept->CheckFaults();
if (htileClear.has_value()) Graphics::CompleteHtileDepthClear(htileClear->first, htileClear->second);
});
} else if (completionNeeded) {
// Listed for DispatchIndirect until the write-back ran (a non-reusable object, so once).
auto writers = state->copiedWriters;
auto kept = record.resources;
recorder.OnComplete([kept, writers] {
recorder.OnComplete([kept, writers, htileClear = record.htileClear] {
// Delisted before the write-back: one that fails must not keep indirect dispatches on the CPU.
writers->erase(std::remove(writers->begin(), writers->end(), kept), writers->end());
kept->WriteBackBuffers();
if (htileClear.has_value()) Graphics::CompleteHtileDepthClear(htileClear->first, htileClear->second);
});
// Listed after the registration: a throw there leaves nothing that would pin the CPU path forever.
if (resources.HasCopiedWrites()) writers->push_back(kept);
@@ -5070,7 +5103,7 @@ std::shared_ptr<ComputePipelineObjects> VulkanDevice::computePipeline(const Grap
return finish(std::move(objects), nullptr);
}
VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t arguments, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::uint64_t programAddress, std::shared_ptr<PreparedDispatch> prepared, std::shared_ptr<const Recipe>* recipeOut, const std::array<std::uint32_t, 3>& threadGroup) {
VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::RecompileResult& shader, std::uint32_t x, std::uint32_t y, std::uint32_t z, std::uint64_t arguments, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::uint64_t programAddress, std::shared_ptr<PreparedDispatch> prepared, std::shared_ptr<const Recipe>* recipeOut, const std::array<std::uint32_t, 3>& threadGroup, std::optional<std::pair<std::uint64_t, std::size_t>> htileClear) {
startJournalReplay();
for (const auto& binding : shader.bindings) {
if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue;
@@ -5322,7 +5355,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec
// works; the batch is waited for where the guest expects results (labels, flips, CPU reads).
auto& recorder = *state->recorder;
IndirectOutcome outcome{0, 0};
RecordedDispatch record{&context, &shaders[0], resources, objects, pushStages, &pushBytes, x, y, z, arguments, nullptr, programAddress, fromCache && TemplateDataRefresh() ? RecordedDispatch::DataRefresh::Words : RecordedDispatch::DataRefresh::None, 0, revalidateMs, &timer};
RecordedDispatch record{&context, &shaders[0], resources, objects, pushStages, &pushBytes, x, y, z, arguments, nullptr, programAddress, fromCache && TemplateDataRefresh() ? RecordedDispatch::DataRefresh::Words : RecordedDispatch::DataRefresh::None, 0, revalidateMs, &timer, htileClear};
record.resourceKeyMatched = fromCache;
record.bindings = overlay;
record.threadGroup = threadGroup;
@@ -213,6 +213,8 @@ struct Context {
bool samplerFilterMinmax = false;
bool nonSeamlessCubeMap = false;
VkSampleCountFlags mergedCoverageSampleCounts = 0;
VkSampleCountFlags truncatedCoverageSampleCounts = 0;
bool mixedAttachmentSamples = false;
bool conservativeRasterization = false;
bool meshWave32 = false;
VkBuffer emptyBuffer = VK_NULL_HANDLE;
@@ -237,11 +239,13 @@ struct Context {
bool imageTableUpdateAfterBind = false;
bool samplerTableUpdateAfterBind = false;
bool geometryShader = false;
bool largePoints = false;
bool sampleRateShading = false;
bool fillModeNonSolid = false;
bool maintenance5 = false;
bool storageImageMultisample = false;
bool storageImageWriteWithoutFormat = false;
bool imageFormatList = false;
bool shaderClipDistance = false;
bool shaderCullDistance = false;
bool nullDescriptors = false;
@@ -29,6 +29,7 @@ struct DepthPlaneStoreStatistics {
std::uint64_t bytes = 0;
};
DepthPlaneStoreStatistics DepthPlaneStoreCounts();
void NoteDepthSurfaceWrite(const Context& context, const DepthTarget& target);
bool SampleLocationsCompatibleDepth(const Context& context, VkFormat format, std::uint32_t samples);
std::uint64_t DepthSurfacesSerial();
std::uint64_t DepthSurfacesReleased();
@@ -54,7 +55,10 @@ bool DepthSurfaceOverlaps(VkDevice device, std::uint64_t address, std::uint64_t
bool DepthSurfaceAt(const Context& context, std::span<const std::uint32_t> words, const GuestTextureResource& resource);
std::uint64_t HtileDepthClearAddress(std::span<const std::uint32_t> code, std::span<const std::uint32_t> userData, const std::array<std::uint32_t, 3>& numThreads);
std::size_t HtileDepthClearBytes_nid_no_patch(std::span<const std::uint32_t> code, std::span<const std::uint32_t> userData, const ShaderRecompiler::ShaderComputeStageInfo& compute, std::span<const std::uint32_t> packet, std::uint64_t indirectArguments);
void NoteHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes, std::size_t nativeBytes = 0u);
bool NoteHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes, std::size_t nativeBytes = 0u);
void ArmHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes);
void QueueHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes);
void CompleteHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes);
struct MemoryValueFill {
std::uint64_t address;
std::size_t bytes;
@@ -128,6 +128,9 @@ std::shared_ptr<std::vector<std::shared_ptr<ShaderResources>>> DrawCopiedWriters
void RunColorMetadataPass(const Context& context, const ColorMetadataPass& pass);
void RunDepthCopyPass(const Context& context, const DepthCopyPass& pass);
std::vector<std::pair<std::uint64_t, std::uint64_t>> PipelinedColorMetadataPassWrites(const ColorMetadataPass& pass);
bool DrawPipelineEnabled();
bool CommitTrims();
}
@@ -90,6 +90,7 @@ struct GuestTextureResource {
std::uint32_t minLod = 0;
std::uint32_t allocatedMipCount = 0;
std::uint32_t samples = 1;
std::uint64_t fmaskCmaskAddress = 0;
};
float EffectiveMinLod(const GuestTextureResource& resource);
@@ -76,6 +76,7 @@ bool MultisampleTargetStorable(const Context& context, const ColorTarget& target
void ResolveMultisampleTarget(const Context& context, const ColorTarget& source, StorageTexture& destination, VkImageView destinationView);
bool MultisampledColorFillAbsorbs(std::uint64_t address, std::size_t bytes, std::uint32_t pattern);
void NoteColorMetadataFill(std::uint64_t address, std::size_t bytes, std::uint32_t pattern);
std::shared_ptr<Texture> MultisampleTargetFmaskTexture_nid_no_patch(const Context& context, const GuestTextureResource& resource, VkComponentMapping components);
void ClearMultisampleTargets(VkDevice device);
void InstallResidentImageReadGuard_nid_no_patch();
void UpdateResidentImageUnmapObserver_nid_no_patch();
@@ -48,6 +48,7 @@ std::shared_ptr<Texture> CachedSampledTexture(const Context& context, std::span<
bool SampledTexturesShareEntry(std::span<const std::uint32_t> first, std::span<const std::uint32_t> second);
bool CompletePendingCpuWrites(const Context& context, std::uint64_t address, std::size_t bytes);
bool SpirvStoresThroughAddresses(std::span<const std::uint32_t> words);
bool ShaderStoresThroughAddresses(const ShaderRecompiler::SharedSpirv& spirv);
// The cached storage image of a surface (render targets use it as their resident image); brought up
// to date with guest memory before it is returned.
@@ -292,6 +293,7 @@ public:
ProofFailure failure = ProofFailure::None;
};
bool Revalidate(std::span<const CompiledShader> shaders, ProofReport* report = nullptr);
static bool EpochProofs();
bool Revalidate(const CompiledShader& shader, ProofReport* report = nullptr) { return Revalidate(std::span<const CompiledShader>(&shader, 1), report); }
// The proof a recipe hit runs on its template (design_cpu_final M4): Revalidate by that name.
bool ProveCurrent(std::span<const CompiledShader> shaders, ProofReport* report = nullptr) { return Revalidate(shaders, report); }
@@ -632,6 +634,10 @@ private:
// no image other than the object's own sources has results pending over its surfaces and
// regions, so those checks are skipped (see fastRevalidate).
std::uint64_t pendingSerialSeen = 0;
std::uint64_t provedEpoch = 0;
std::uint64_t provedProof = 0;
std::uint64_t provedPending = 0;
bool revalidateFull(std::span<const CompiledShader> shaders, ProofReport* report);
// The import table's identity when the direct regions' serials were last proved.
HostImportsProof importsProof;
// FNV-1a offset basis: the hash of no data buffers (DataWordsHash).
@@ -721,8 +727,25 @@ private:
void noteUse(const Key& key);
struct KeyHash {
std::size_t operator()(const Key& key) const noexcept {
std::uint64_t hash = 14695981039346656037ull;
for (const auto word : key) hash = (hash ^ word) * 1099511628211ull;
constexpr std::uint64_t Prime = 0x9e3779b97f4a7c15ull;
std::uint64_t lanes[4] = {0x243f6a8885a308d3ull, 0x13198a2e03707344ull, 0xa4093822299f31d0ull, 0x082efa98ec4e6c89ull};
const auto* words = key.data();
const auto count = key.size();
std::size_t at = 0;
for (; at + 8u <= count; at += 8u) {
for (std::size_t lane = 0; lane < 4u; ++lane) {
const auto value = static_cast<std::uint64_t>(words[at + lane * 2u]) | static_cast<std::uint64_t>(words[at + lane * 2u + 1u]) << 32u;
lanes[lane] = (lanes[lane] ^ value) * Prime;
lanes[lane] ^= lanes[lane] >> 29u;
}
}
std::uint64_t hash = lanes[0] ^ (lanes[1] << 17u | lanes[1] >> 47u) ^ (lanes[2] << 31u | lanes[2] >> 33u) ^ (lanes[3] << 47u | lanes[3] >> 17u) ^ count;
for (; at < count; ++at) hash = (hash ^ words[at]) * Prime;
hash ^= hash >> 33u;
hash *= 0xff51afd7ed558ccdull;
hash ^= hash >> 33u;
hash *= 0xc4ceb9fe1a85ec53ull;
hash ^= hash >> 33u;
return static_cast<std::size_t>(hash);
}
};
@@ -68,6 +68,8 @@ struct ColorTarget {
std::uint32_t pipeBankXor = 0;
std::uint32_t samples = 1;
std::uint32_t dccControl = 0;
std::uint64_t fmaskAddress = 0;
std::uint32_t fmaskPipeBankXor = 0;
};
struct DepthTarget {
@@ -140,6 +142,7 @@ struct State {
bool ditheredAlphaToCoverage = false;
bool perSampleShading = false;
bool mergedCoverage = false;
bool truncatedCoverage = false;
VkConservativeRasterizationModeEXT conservativeRasterization = VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT;
VkRect2D scissor;
VkCullModeFlags cullMode;
@@ -153,6 +156,10 @@ struct State {
bool customSampleLocations = false;
bool sampleLocationGrid = false;
std::uint32_t paClVsOutCntl = 0;
bool vertexPoints = false;
float pointSize = 1.0f;
float pointSizeMin = 0.0f;
float pointSizeMax = 0.0f;
std::array<std::uint16_t, 4> quadSampleMask{0xffffu, 0xffffu, 0xffffu, 0xffffu};
bool pixelEarlyZ = false;
};
@@ -162,6 +169,7 @@ struct State {
inline constexpr std::uint32_t PositionExportLayoutBits = 0xffffu | (1u << 21u) | (1u << 22u) | (1u << 23u);
ShaderStages DecodeShaderStages(const QueueState& queue, bool vertexWorkgroup = false);
void ApplyPointSize(const State& state, ShaderRecompiler::ShaderVertexStageInfo& vertex);
State DecodeState(const QueueState& queue, bool vertexWorkgroup = false);
void ApplyDepthRemap(const Context& context, State& state);
void NormalizeUnusedViewportDepth(State& state, const ShaderRecompiler::ShaderPixelStageInfo& pixel);
@@ -370,6 +370,7 @@ public:
// Keeps the image current with guest memory (see GuestMemory::CollectWrites).
bool Refresh();
bool RefreshLayers(std::uint32_t first, std::uint32_t count);
inline static std::atomic<std::uint64_t> epochRefreshes{0};
static std::uint64_t SinglePassMoves();
static std::uint64_t SlabRetiles();
static std::uint64_t RefreshesProved();
@@ -383,6 +384,9 @@ public:
VkDeviceSize AllocationBytes() const { return memoryBytes; }
private:
std::atomic<std::uint64_t> provedEpoch{0};
std::atomic<std::uint64_t> provedProof{0};
std::atomic<std::uint64_t> provedPending{0};
StorageTexture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, std::uint32_t mipLevel);
// The regions of every array layer, or of the tracked layers `layers` selects.
std::vector<VkBufferImageCopy> CopyRegions(const std::vector<bool>* layers = nullptr) const;
@@ -347,7 +347,7 @@ void BdaResources::markWrittenPages() const {
Require(false, message.str());
}
}
GuestMemory::MarkWritten(begin, bytes);
GuestMemory::MarkPossiblyWritten(begin, bytes);
}), "invalid BDA written-page record");
for (std::uint32_t claim = 0; claim < count; ++claim) {
const auto slot = words[Abi::WrittenListWord + claim];
@@ -58,6 +58,7 @@ struct DepthGuard {
std::size_t bytes;
std::shared_ptr<std::atomic<bool>> active;
std::vector<GuestMemory::UnchangedQuery> live;
std::shared_ptr<std::atomic<bool>> hostWritten;
};
std::shared_mutex& depthGuardMutex() {
@@ -338,6 +339,7 @@ public:
const auto clearLease = clearGeneration == 0u ? GuestAllocations::Lease{} : GuestAllocations::GuestAllocationsAcquireAll_nid_postfix();
Require(active->load(std::memory_order_acquire), "the native multisample depth owner was released");
Require(sampling.refusal.empty(), sampling.refusal);
Require(!clearPending, "native multisample depth clear has not been recorded");
for (const auto& range : sampling.initial) {
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");
if (const auto* recorder = RecorderFor(context)) Require(!recorder->PendingWriteOverlaps(range.address, range.bytes), "external GPU writes over native multisample depth are not implemented");
@@ -491,6 +493,7 @@ public:
void CopyAspectFrom(const DepthSurface& source, VkImageAspectFlagBits aspect) {
ForgetClear(aspect);
NoteHostWrite();
auto* recorder = RecorderFor(context);
std::unique_ptr<CommandBatch> batch;
if (recorder == nullptr) batch = std::make_unique<CommandBatch>(context);
@@ -540,7 +543,12 @@ public:
return std::any_of(textures.begin(), textures.end(), [](const auto& entry) { return entry.second.use_count() > 1; });
}
void NoteHostWrite() {
hostWritten->store(true, std::memory_order_release);
}
std::uint64_t written = ++depthWrites;
std::shared_ptr<std::atomic<bool>> hostWritten = std::make_shared<std::atomic<bool>>(false);
bool retired = false;
bool Overlaps(std::uint64_t address, std::uint64_t bytes) const {
@@ -690,6 +698,7 @@ public:
if (plane.storage.get() == &candidate) {
if (stencil || !StoreOverwrite(candidate)) copyPlane(plane, plane.storage, stencil, false);
written = ++depthWrites;
NoteHostWrite();
return true;
}
if (std::none_of(plane.replaced.begin(), plane.replaced.end(), [&](const auto& old) { return old.lock().get() == &candidate; })) continue;
@@ -707,6 +716,7 @@ public:
const auto source = std::const_pointer_cast<StorageTexture>(candidate.shared_from_this());
copyPlane(plane, source, stencil, false);
written = ++depthWrites;
NoteHostWrite();
return true;
}
return false;
@@ -910,7 +920,9 @@ public:
bool sampleable = true;
bool samplingActive = false;
DepthSamplingState sampling;
bool clearPending = false;
std::uint64_t clearGeneration = 0u;
bool clearCompletionQueued = false;
std::shared_ptr<OwnedImage> owned;
std::shared_ptr<OwnedImage> sampleShadow;
bool useSampleShadow = false;
@@ -1527,6 +1539,21 @@ DepthSurface* planeSurface(VkDevice device, std::uint64_t address) {
return found == list.rend() ? nullptr : found->get();
}
void settlePendingHtileClear(const Context& context, std::uint64_t address) {
if (Recorder::InCompletion()) return;
auto* recorder = RecorderFor(context);
if (recorder == nullptr) return;
std::pair<std::uint64_t, std::size_t> metadata;
{
std::lock_guard lock(surfacesMutex());
const auto* surface = planeSurface(context.device, address);
if (surface == nullptr || !surface->samplingActive || surface->clearGeneration == 0u || !surface->clearCompletionQueued || !surface->sampling.refusal.empty()) return;
const auto& range = surface->sampling.initial[1];
metadata = {range.address, range.bytes};
}
if (recorder->PendingWriteOverlaps(metadata.first, metadata.second)) recorder->SyncThrough(metadata.first, metadata.second);
}
std::map<std::uint64_t, std::size_t>& clearedHtiles() {
static auto* cleared = new std::map<std::uint64_t, std::size_t>();
return *cleared;
@@ -1826,8 +1853,28 @@ std::uint64_t MultisampledDepthBytes_nid_no_patch(VkExtent2D extent, std::uint32
void RequireNoResidentDepthRead_nid_no_patch(std::uint64_t address, std::size_t bytes) {
if (bytes == 0u || !anyDepthGuard().load(std::memory_order_acquire)) return;
Require(address <= std::numeric_limits<std::uint64_t>::max() - bytes, "native depth read range overflows");
std::shared_lock lock(depthGuardMutex());
for (const auto& range : depthGuards()) Require(address >= range.address + range.bytes || range.address >= address + bytes, "sample-preserving guest publication of native multisample depth is not implemented");
const auto overlaps = [&](const DepthGuard& range) { return address < range.address + range.bytes && range.address < address + bytes; };
{
std::shared_lock lock(depthGuardMutex());
if (std::ranges::none_of(depthGuards(), overlaps)) return;
}
std::unique_lock lock(depthGuardMutex());
for (const auto& range : depthGuards()) {
if (overlaps(range)) Require(!range.hostWritten->load(std::memory_order_acquire), "sample-preserving guest publication of native multisample depth is not implemented");
}
for (const auto& range : depthGuards()) {
if (overlaps(range)) range.active->store(false, std::memory_order_release);
}
std::erase_if(depthGuards(), [](const auto& range) { return !range.active->load(std::memory_order_acquire); });
anyDepthGuard().store(!depthGuards().empty(), std::memory_order_release);
}
void NoteDepthSurfaceWrite(const Context& context, const DepthTarget& target) {
if (target.samples == 1u || !anyDepthGuard().load(std::memory_order_acquire)) return;
std::lock_guard lock(surfacesMutex());
for (const auto& surface : surfaces()) {
if (surface->active->load(std::memory_order_acquire) && surface->context.device == context.device && sameSurface(surface->target, target)) surface->NoteHostWrite();
}
}
bool HasResidentDepthGuards_nid_no_patch() {
@@ -1900,6 +1947,7 @@ float HostDepthBiasConstant(const Context& context, VkFormat format, float const
VkImageView DepthSurfaceView(const Context& context, const DepthTarget& target, bool depthWritten) {
const auto htileCleared = RoutesToNativeDepthOwner(target) ? VkImageAspectFlags{0} : storeBackClearedHtile(context, target);
std::lock_guard gpu(GuestMemory::GpuMutex());
settlePendingHtileClear(context, target.address);
std::unique_lock lock(surfacesMutex());
const bool cleared = takeClearedHtile(target);
DepthSurface* surface = nullptr;
@@ -1936,7 +1984,7 @@ VkImageView DepthSurfaceView(const Context& context, const DepthTarget& target,
auto& fresh = *surfaces().back();
if (target.samples != 1u && fresh.sampleable && fresh.sampling.refusal.empty()) {
std::unique_lock guardLock(depthGuardMutex());
for (const auto& range : fresh.sampling.initial) depthGuards().push_back({context.device, range.address, range.bytes, fresh.active, {{range.address, range.bytes, 0u}}});
for (const auto& range : fresh.sampling.initial) depthGuards().push_back({context.device, range.address, range.bytes, fresh.active, {{range.address, range.bytes, 0u}}, fresh.hostWritten});
anyDepthGuard().store(true, std::memory_order_release);
InstallResidentImageReadGuard_nid_no_patch();
fresh.samplingActive = true;
@@ -2184,17 +2232,22 @@ std::size_t HtileDepthClearBytes_nid_no_patch(std::span<const std::uint32_t> cod
return address <= std::numeric_limits<std::uint64_t>::max() - bytes ? static_cast<std::size_t>(bytes) : 0u;
}
void NoteHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes, std::size_t nativeBytes) {
bool NoteHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes, std::size_t nativeBytes) {
std::lock_guard lock(surfacesMutex());
forgetHtileReads(htileAddress, bytes);
bool existing = false;
bool completionCandidate = false;
for (const auto& surface : surfaces()) {
if (!surface->active->load(std::memory_order_acquire)) continue;
if (surface->samplingActive && surface->target.htileAddress == htileAddress) {
const auto& metadata = surface->sampling.initial[1];
if (nativeBytes != bytes || nativeBytes < metadata.bytes || !GuestMemory::Accessible(reinterpret_cast<const void*>(metadata.address), metadata.bytes) || !GuestMemory::Watched(metadata.address, metadata.bytes)) surface->sampling.Refuse("native multisample depth incomplete or unproven fast-clear transition is not implemented");
else if (surface->clearGeneration != 0u) surface->sampling.Refuse("overlapping native multisample depth clear transitions are not implemented");
else surface->clearGeneration = GuestMemory::CollectWritesUncached(metadata.address, metadata.bytes);
else if (surface->clearPending || surface->clearGeneration != 0u) surface->sampling.Refuse("overlapping native multisample depth clear transitions are not implemented");
else {
surface->clearPending = true;
surface->clearCompletionQueued = false;
completionCandidate = true;
}
existing = true;
continue;
}
@@ -2204,6 +2257,39 @@ void NoteHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes, std::siz
existing = true;
}
if (!existing) clearedHtiles()[htileAddress] = bytes;
return completionCandidate;
}
void ArmHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes) {
std::lock_guard lock(surfacesMutex());
for (const auto& surface : surfaces()) {
if (!surface->active->load(std::memory_order_acquire) || !surface->samplingActive || surface->target.htileAddress != htileAddress || !surface->clearPending) continue;
const auto& metadata = surface->sampling.initial[1];
if (bytes < metadata.bytes) continue;
surface->clearGeneration = GuestMemory::CollectWritesUncached(metadata.address, metadata.bytes);
surface->clearPending = false;
if (surface->clearGeneration == 0u) surface->sampling.Refuse("native multisample depth clear requires tracked HTILE generations");
}
}
void QueueHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes) {
std::lock_guard lock(surfacesMutex());
for (const auto& surface : surfaces()) {
if (!surface->active->load(std::memory_order_acquire) || !surface->samplingActive || surface->target.htileAddress != htileAddress || surface->clearGeneration == 0u || !surface->sampling.refusal.empty()) continue;
if (bytes >= surface->sampling.initial[1].bytes) surface->clearCompletionQueued = true;
}
}
void CompleteHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes) {
std::lock_guard lock(surfacesMutex());
for (const auto& surface : surfaces()) {
if (!surface->active->load(std::memory_order_acquire) || !surface->samplingActive || surface->target.htileAddress != htileAddress || surface->clearGeneration == 0u) continue;
const auto& metadata = surface->sampling.initial[1];
if (bytes < metadata.bytes) continue;
Require(GuestMemory::UnchangedSinceCollected(metadata.address, metadata.bytes, surface->clearGeneration), "CPU writes raced native multisample depth clear");
GuestMemory::MarkWritten(metadata.address, metadata.bytes);
surface->clearCompletionQueued = false;
}
}
void ClearDepthSurfaces(VkDevice device) {
@@ -2231,6 +2317,7 @@ std::shared_ptr<Texture> DepthSurfaceTexture(const Context& context, std::span<c
if (std::none_of(surfaces().begin(), surfaces().end(), held)) return nullptr;
}
std::lock_guard gpu(GuestMemory::GpuMutex());
settlePendingHtileClear(context, resource.baseAddress);
std::lock_guard lock(surfacesMutex());
auto* found = planeSurface(context.device, resource.baseAddress);
if (found == nullptr) return nullptr;
@@ -2293,6 +2380,7 @@ bool DepthSurfaceHolds(const Context& context, const GuestTextureResource& resou
if ((resource.dimension != TextureDimension::k2D && resource.dimension != TextureDimension::k2DMsaa) || resource.baseArray != 0) return false;
std::lock_guard gpu(GuestMemory::GpuMutex());
const auto address = resource.baseAddress;
settlePendingHtileClear(context, address);
std::lock_guard lock(surfacesMutex());
auto* found = planeSurface(context.device, address);
if (found == nullptr || !found->Holds(texture)) return false;
@@ -2454,7 +2542,10 @@ bool DepthSurfaceStoreBack(const Context& context, const StorageTexture& storage
if (std::get<0>(key) != context.device || entry->storage.get() != &storage) continue;
const auto slices = layeredSlices(context, *entry);
entry->Copy(slices, false);
for (const auto& slice : slices) slice.surface->written = ++depthWrites;
for (const auto& slice : slices) {
slice.surface->written = ++depthWrites;
slice.surface->NoteHostWrite();
}
return true;
}
for (const auto& surface : surfaces()) {
@@ -20,6 +20,7 @@
#include "prx/libc/include/GuestAllocations.hpp"
#include "Optimization/include/Optimization/ShaderStageInputInfo.hpp"
#include "ThreadOwned.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include <algorithm>
#include <array>
#include <atomic>
@@ -55,6 +56,7 @@ std::uint64_t DrawRenderPassKey(const Context& context, const State& state, std:
mix(state.renderExtent.height);
mix(state.samples);
mix(state.mergedCoverage);
mix(state.truncatedCoverage);
mix(state.customSampleLocations);
if (state.customSampleLocations) {
mix(state.sampleLocationGrid);
@@ -81,6 +83,10 @@ GuestTextureResource ArraySurfaceForTarget(const ColorTarget& color) {
namespace {
bool writesDepthTarget(const State& state) {
return state.depthWrite || (state.stencilTest && (state.stencilFront.writeMask != 0u || state.stencilBack.writeMask != 0u));
}
std::size_t colorKeyCount(const ColorTarget& color, std::size_t bytes) {
if (color.mipCount != 1 || color.depth != 1 || !color.dccPipeAligned) return DccKeyBytes(bytes);
return DccKeyCount(ColorTextureTileMode(color.tileMode), color.elementBytes, color.extent.width, color.extent.height, bytes);
@@ -666,6 +672,7 @@ bool ValidationKey(const Context& context, std::span<const CompiledShader> shade
add(context.viewportIndexLayer);
add(context.shaderTerminateInvocation);
add(state.paClVsOutCntl);
add(state.vertexPoints);
add(state.stages.mesh.has_value());
if (state.stages.mesh) {
const auto& mesh = *state.stages.mesh;
@@ -718,11 +725,26 @@ std::uint32_t CachedFragmentOutputs(const Context& context, std::span<const Comp
auto& key = validationKeyScratch();
const bool keyed = ValidationKey(context, shaders, state, key);
static std::map<std::vector<std::uint64_t>, std::uint32_t> memo;
struct LastKeyStorage {};
auto& lastKey = HostThreadLocal<std::vector<std::uint64_t>, LastKeyStorage>();
thread_local std::uint32_t lastOutputs = 0;
thread_local bool lastValid = false;
const bool trims = keyed && CommitTrims();
if (trims && lastValid && key == lastKey) {
memoized = true;
hit = true;
return lastOutputs;
}
if (keyed) {
memoized = true;
std::lock_guard lock(validationMutex());
if (const auto found = memo.find(key); found != memo.end()) {
hit = true;
if (trims) {
lastKey = key;
lastOutputs = found->second;
lastValid = true;
}
return found->second;
}
}
@@ -777,10 +799,16 @@ ResourceCache::Key DrawResourceKey(const Context& context, std::span<const Compi
append64(reinterpret_cast<std::uint64_t>(context.device));
key.push_back(static_cast<std::uint32_t>(shaders.size()));
for (const auto& shader : shaders) {
const auto at = key.size();
key.push_back(0);
ShaderResources::AppendContentKey(shader, true, MovableBuffers(), key);
key[at] = static_cast<std::uint32_t>(key.size() - at - 1);
const auto sizeAt = key.size();
key.push_back(0u);
auto& memo = shader.program->drawKeyMemo.words;
if (auto words = memo.load(std::memory_order_acquire); words != nullptr) {
key.insert(key.end(), words->begin(), words->end());
} else {
ShaderResources::AppendContentKey(shader, true, MovableBuffers(), key);
memo.store(std::make_shared<const std::vector<std::uint32_t>>(key.begin() + static_cast<std::ptrdiff_t>(sizeAt + 1u), key.end()), std::memory_order_release);
}
key[sizeAt] = static_cast<std::uint32_t>(key.size() - sizeAt - 1u);
}
key.push_back(colorAttachments);
if (ranges) {
@@ -1043,9 +1071,14 @@ struct DrawInputs {
VkPipelineStageFlags shaderStages = 0;
std::uint32_t meshGroups = 0;
std::vector<std::uint32_t> restartTable;
std::uint32_t expandedIndexCount = 0;
const VertexInputLayout& VertexLayout() const { return retainedVertexInput != nullptr ? *retainedVertexInput : vertexInput; }
};
bool StripPatches(const State& state, std::span<const CompiledShader> shaders) {
return state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP && BarycentricPatches(state, shaders);
}
std::shared_ptr<Buffer> zeroVertexBuffer(const Context& context, const ShaderRecompiler::VertexAttribute& attribute) {
auto zero = std::make_shared<Buffer>(context, DecodeVertexFormat(attribute).bytes, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
std::fill(zero->Bytes().begin(), zero->Bytes().end(), std::byte{0});
@@ -1129,19 +1162,58 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
ValidateSampleMask(context, state, shaders);
timer.phase(PhaseValidate);
inputs.maxIndex = draw.indexed ? 0u : draw.firstVertex + draw.indexCount - 1u;
if (state.quadList) {
Require(!draw.indirect, "indirect quad-list draw is unsupported");
const std::uint32_t quadCount = draw.indexCount / 4u;
if (quadCount == 0u || draw.instanceCount == 0u) {
if (state.quadList || StripPatches(state, shaders)) {
Require(!draw.indirect, state.quadList ? "indirect quad-list draw is unsupported" : "an indirect triangle strip through emulated barycentric patches is unsupported");
const std::uint32_t primitives = state.quadList ? draw.indexCount / 4u : draw.indexCount >= 3u ? draw.indexCount - 2u : 0u;
if (primitives == 0u || draw.instanceCount == 0u) {
inputs.nothing = true;
return inputs;
}
const std::uint32_t outputIndexCount = quadCount * 6u;
const std::size_t quadIndexBytes = static_cast<std::size_t>(outputIndexCount) * sizeof(std::uint32_t);
auto indexCopy = std::make_shared<Buffer>(context, quadIndexBytes, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
const std::uint32_t corners = state.quadList ? 6u : 3u;
const std::uint32_t outputIndexCount = primitives * corners;
const std::size_t expandedIndexBytes = static_cast<std::size_t>(outputIndexCount) * sizeof(std::uint32_t);
auto indexCopy = std::make_shared<Buffer>(context, expandedIndexBytes, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
auto* outIndices = reinterpret_cast<std::uint32_t*>(indexCopy->Bytes().data());
std::uint32_t maxIdx = 0;
const bool lastProvoking = state.provokingVertexMode == VK_PROVOKING_VERTEX_MODE_LAST_VERTEX_EXT;
const auto expand = [&](const auto& source) {
for (std::uint32_t primitive = 0; primitive < primitives; ++primitive) {
auto* out = outIndices + static_cast<std::size_t>(primitive) * corners;
if (state.quadList) {
const auto i0 = source(primitive * 4u + 0u);
const auto i1 = source(primitive * 4u + 1u);
const auto i2 = source(primitive * 4u + 2u);
const auto i3 = source(primitive * 4u + 3u);
if (lastProvoking) {
out[0] = i0;
out[1] = i1;
out[2] = i3;
out[3] = i1;
out[4] = i2;
out[5] = i3;
} else {
out[0] = i0;
out[1] = i1;
out[2] = i2;
out[3] = i0;
out[4] = i2;
out[5] = i3;
}
} else {
const std::uint32_t odd = primitive & 1u;
if (lastProvoking) {
out[0] = source(primitive + odd);
out[1] = source(primitive + 1u - odd);
out[2] = source(primitive + 2u);
} else {
out[0] = source(primitive);
out[1] = source(primitive + 1u + odd);
out[2] = source(primitive + 2u - odd);
}
}
for (std::uint32_t corner = 0; corner < corners; ++corner) maxIdx = std::max(maxIdx, out[corner]);
}
};
if (draw.indexed) {
GuestMemory::FlushGpuWrites(draw.indexAddress, static_cast<std::size_t>(indexBytes));
GuestMemory::CheckRange(reinterpret_cast<const void*>(draw.indexAddress), static_cast<std::size_t>(indexBytes), draw.indexSize);
@@ -1156,59 +1228,18 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
return v;
}
};
for (std::uint32_t q = 0; q < quadCount; ++q) {
const auto i0 = readIndex(q * 4u + 0u);
const auto i1 = readIndex(q * 4u + 1u);
const auto i2 = readIndex(q * 4u + 2u);
const auto i3 = readIndex(q * 4u + 3u);
maxIdx = std::max({maxIdx, i0, i1, i2, i3});
if (lastProvoking) {
outIndices[q * 6u + 0u] = i0;
outIndices[q * 6u + 1u] = i1;
outIndices[q * 6u + 2u] = i3;
outIndices[q * 6u + 3u] = i1;
outIndices[q * 6u + 4u] = i2;
outIndices[q * 6u + 5u] = i3;
} else {
outIndices[q * 6u + 0u] = i0;
outIndices[q * 6u + 1u] = i1;
outIndices[q * 6u + 2u] = i2;
outIndices[q * 6u + 3u] = i0;
outIndices[q * 6u + 4u] = i2;
outIndices[q * 6u + 5u] = i3;
}
}
expand(readIndex);
Require(draw.firstVertex <= std::numeric_limits<std::uint32_t>::max() - maxIdx, "indexed draw vertex range overflow");
inputs.maxIndex = maxIdx + draw.firstVertex;
} else {
maxIdx = quadCount * 4u - 1u;
Require(draw.firstVertex <= std::numeric_limits<std::uint32_t>::max() - maxIdx, "auto draw vertex range overflow");
for (std::uint32_t q = 0; q < quadCount; ++q) {
const auto i0 = q * 4u + 0u;
const auto i1 = q * 4u + 1u;
const auto i2 = q * 4u + 2u;
const auto i3 = q * 4u + 3u;
if (lastProvoking) {
outIndices[q * 6u + 0u] = i0;
outIndices[q * 6u + 1u] = i1;
outIndices[q * 6u + 2u] = i3;
outIndices[q * 6u + 3u] = i1;
outIndices[q * 6u + 4u] = i2;
outIndices[q * 6u + 5u] = i3;
} else {
outIndices[q * 6u + 0u] = i0;
outIndices[q * 6u + 1u] = i1;
outIndices[q * 6u + 2u] = i2;
outIndices[q * 6u + 3u] = i0;
outIndices[q * 6u + 4u] = i2;
outIndices[q * 6u + 5u] = i3;
}
}
inputs.maxIndex = maxIdx + draw.firstVertex;
const std::uint32_t lastVertex = state.quadList ? primitives * 4u - 1u : primitives + 1u;
Require(draw.firstVertex <= std::numeric_limits<std::uint32_t>::max() - lastVertex, "auto draw vertex range overflow");
expand([](std::uint32_t idx) { return idx; });
}
inputs.maxIndex = maxIdx + draw.firstVertex;
Require(inputs.maxIndex <= context.limits.maxDrawIndexedIndexValue, "index exceeds the device's indexed draw limit");
inputs.indexHandle = indexCopy->Handle();
inputs.indexOffset = 0;
inputs.expandedIndexCount = outputIndexCount;
inputs.indices = std::move(indexCopy);
} else if (draw.indexed) {
const bool listTopology = state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
@@ -1491,9 +1522,9 @@ void recordDrawCommands(const Context& context, VkCommandBuffer commands, const
return;
}
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 (state.quadList) {
if (inputs.expandedIndexCount != 0u) {
context.Resolved(&DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer")(commands, inputs.indexHandle, inputs.indexOffset, VK_INDEX_TYPE_UINT32);
context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, (draw.indexCount / 4u) * 6u, draw.instanceCount, 0, static_cast<std::int32_t>(draw.firstVertex), draw.firstInstance);
context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, inputs.expandedIndexCount, draw.instanceCount, 0, static_cast<std::int32_t>(draw.firstVertex), draw.firstInstance);
return;
}
if (draw.indexed) context.Resolved(&DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer")(commands, inputs.indexHandle, inputs.indexOffset, draw.indexSize == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32);
@@ -1686,6 +1717,7 @@ void keepRecordedDraw(Recorder& recorder, const std::shared_ptr<ShaderResources>
resources->WriteBackBuffers();
});
writers->push_back(resources);
GuestMemory::BreakProofs();
} else if (completion) {
if (resources->Reusable()) recorder.OnComplete([resources] { resources->CheckFaults(); });
else recorder.OnComplete([resources] { resources->WriteBackBuffers(); });
@@ -2148,8 +2180,66 @@ std::optional<std::string> KnownValidationFailure(const Context& context, std::s
return std::nullopt;
}
void Draw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots, std::shared_ptr<const DrawRecipe>* recipeOut) {
namespace {
struct TargetBinding {
ColorTarget color;
bool gpuTiling = false;
std::shared_ptr<StorageTexture> resident;
bool proxied = false;
std::unique_ptr<Buffer> transfer;
std::unique_ptr<Buffer> tiled;
std::unique_ptr<DeviceBuffer> tiledDevice;
std::unique_ptr<DeviceBuffer> linearDevice;
std::vector<std::byte> original;
TileMipLayout mip{};
std::unique_ptr<RenderTarget> target;
bool multisampled = false;
VkImage multisampleImage = VK_NULL_HANDLE;
std::shared_ptr<void> multisampleOwner;
std::unique_ptr<Buffer> dump;
};
struct PreparedDraw {
explicit PreparedDraw(bool profile) : timer(profile) {}
PreparedDraw(const PreparedDraw&) = delete;
PreparedDraw& operator=(const PreparedDraw&) = delete;
std::shared_ptr<const DrawRecipe>* recipeOut = nullptr;
std::vector<std::uint32_t> stencilReferences;
std::optional<PerformanceTimer> timing;
DrawTimer timer;
DrawOutcome outcome;
const ShaderResources::BuildTiming* built = nullptr;
double waitedBefore = 0;
double ownWaitedMs = 0;
DrawInputs inputs;
const Pm4::DrawParameters::IndirectDraw* args = nullptr;
int dumpLimit = 0;
std::vector<TargetBinding> targets;
std::vector<VkImageView> targetViews;
Recorder* recorder = nullptr;
ResolvedResources resolved;
IndirectRecord indirect;
std::vector<Pm4::DrawArguments> records;
bool completion = false;
bool listed = false;
bool recorded = false;
bool lean = false;
bool multisampled = false;
std::optional<State> masked;
std::vector<std::pair<std::uint32_t, std::shared_ptr<Pipeline>>> stencilReplay;
std::shared_ptr<Pipeline> pipeline;
std::vector<std::shared_ptr<StorageTexture>> owners;
std::vector<std::shared_ptr<void>> framebufferOwners;
std::shared_ptr<Framebuffer> framebuffer;
std::vector<SampleOrderTarget> reordered;
SampleOrderPass reorderPass;
std::optional<DepthSampleLocations> depthLocations;
};
bool prepareDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots, PreparedDraw& prepared) {
auto*& recipeOut = prepared.recipeOut;
auto& stencilReferences = prepared.stencilReferences;
for (const auto& shader : shaders) {
if (shader.program != nullptr && !shader.program->stencilReferences.empty()) {
Require(shader.stage == ShaderRecompiler::ShaderStage::Fragment && stencilReferences.empty(), "stencil replay requires exactly one fragment stage");
@@ -2172,60 +2262,37 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
Require(state.samples == 1u && (!state.depth || HasStencil(state.depth->format)), "stencil replay requires single-sample rendering and an eight-bit stencil format");
recipeOut = nullptr;
}
if (state.quadList) recipeOut = nullptr;
if (state.quadList || StripPatches(state, shaders)) recipeOut = nullptr;
if (context.recorder != nullptr) context.recorder->BoundKeptBytes();
PerformanceTimer timing("Graphics.Draw");
auto& timing = prepared.timing.emplace("Graphics.Draw");
// APS5_PROFILE_DRAW prints the time of each phase of the draw (microseconds) and the [draws] totals.
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
DrawTimer timer(profile);
auto& timer = prepared.timer;
timer = DrawTimer(profile);
// APS5_TRACE_DRAWS (together with APS5_PROFILE_DRAW; alone it only enables Driver.cpp's own
// [draw] lines) additionally prints one line per draw with its phases and, for synchronous
// draws, their inputs: per-draw string building at ~1400 draws per 10 s is itself a cost the
// totals must not carry.
static const bool traceDraws = std::getenv("APS5_TRACE_DRAWS") != nullptr;
DrawOutcome outcome;
const ShaderResources::BuildTiming* built = nullptr;
auto& outcome = prepared.outcome;
auto& built = prepared.built;
// The thread's GPU waits so far: the difference at the report, less the draw's own syncs
// (`ownWaitedMs`, sampled around them), is what this draw waited for through the flush hook
// (nested in the draw's hold, see DrawOutcome::hookWaitUs).
const auto waitedBefore = profile ? Recorder::ThreadWaitedMs() : 0.0;
double ownWaitedMs = 0;
const auto waitedBefore = prepared.waitedBefore = profile ? Recorder::ThreadWaitedMs() : 0.0;
auto& ownWaitedMs = prepared.ownWaitedMs;
const auto report = [&](const char* suffix) { reportDrawEnd(state, timer, built, outcome, waitedBefore, ownWaitedMs, suffix); };
auto inputs = prepareDrawInputs(context, state, draw, shaders, outcome, timer, nullptr);
if (inputs.nothing) return;
const auto* args = draw.indirect ? &*draw.indirect : nullptr;
auto& inputs = prepared.inputs;
inputs = prepareDrawInputs(context, state, draw, shaders, outcome, timer, nullptr);
if (inputs.nothing) return false;
const auto* args = prepared.args = draw.indirect ? &*draw.indirect : nullptr;
const auto indexBytes = inputs.indexBytes;
timing.Mark("validate");
timing.Mark("index_upload");
// One binding per color attachment. Tiled targets are detiled and retiled on the GPU in video memory;
// only changed guest blocks are stored back.
struct TargetBinding {
ColorTarget color;
bool gpuTiling = false;
// Resident target: the surface's cached storage image is attached directly and marked dirty
// afterwards, so nothing is copied in or out per draw.
std::shared_ptr<StorageTexture> resident;
bool proxied = false;
// Linear pixels converted on the CPU, for targets the GPU detiler does not handle.
std::unique_ptr<Buffer> transfer;
// Guest bytes in host memory, and their device-local copies for the detiler.
std::unique_ptr<Buffer> tiled;
std::unique_ptr<DeviceBuffer> tiledDevice;
std::unique_ptr<DeviceBuffer> linearDevice;
std::vector<std::byte> original;
TileMipLayout mip{};
std::unique_ptr<RenderTarget> target;
bool multisampled = false;
VkImage multisampleImage = VK_NULL_HANDLE;
std::shared_ptr<void> multisampleOwner;
// APS5_DUMP_TARGETS: the rendered linear pixels, read back for target_<address>_<n>.raw.
std::unique_ptr<Buffer> dump;
};
const int dumpLimit = DumpTargetLimit();
static std::mutex dumpMutex;
static std::map<std::uint64_t, int> dumped;
std::vector<TargetBinding> targets(state.colors.size());
std::vector<VkImageView> targetViews;
const int dumpLimit = prepared.dumpLimit = DumpTargetLimit();
auto& targets = prepared.targets;
targets.resize(state.colors.size());
auto& targetViews = prepared.targetViews;
for (std::size_t index = 0; index < state.colors.size(); ++index) {
auto& binding = targets[index];
binding.color = state.colors[index];
@@ -2317,12 +2384,16 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
binding.target = std::make_unique<RenderTarget>(context, color, state.blends.at(color.exportIndex).blendEnable != 0);
targetViews.push_back(binding.target->View());
}
if (state.depth) targetViews.push_back(DepthSurfaceView(context, *state.depth, state.depthWrite));
if (state.depth) {
targetViews.push_back(DepthSurfaceView(context, *state.depth, state.depthWrite));
if (writesDepthTarget(state)) NoteDepthSurfaceWrite(context, *state.depth);
}
timer.phase(PhasePrepare);
const bool recordDraws = RecordDraws();
auto* recorder = Recorder::Active();
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 = resolveDrawResources(context, state, draw, shaders, snapshots, indexBytes, recordable, outcome, timer);
auto& resolved = prepared.resolved;
resolved = resolveDrawResources(context, state, draw, shaders, snapshots, indexBytes, recordable, outcome, timer);
auto& resources = resolved.resources;
if (!stencilReferences.empty() && resources->ChecksFaults()) recordable = false;
if (!stencilReferences.empty()) {
@@ -2362,9 +2433,9 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
// and records plain draws with the same per-dimension rules. The import pointer stays valid:
// refreshImports runs only under GuestMemory::GpuMutex, held here, and a retired import's
// buffer is kept while the recorder is busy.
IndirectRecord indirect;
auto& indirect = prepared.indirect;
indirect.args = args;
std::vector<Pm4::DrawArguments> records;
auto& records = prepared.records;
if (args != nullptr) {
static const bool gpuIndirectDraws = std::getenv("APS5_NO_GPU_INDIRECT_DRAW") == nullptr;
const auto decide = [&](std::uint64_t address, std::size_t bytes, const HostImport*& import) {
@@ -2385,7 +2456,7 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
const auto rangeBytes = args->RangeBytes();
if (rangeBytes == 0) {
report(" indirect draw without records");
return;
return false;
}
Require(rangeBytes <= std::numeric_limits<std::size_t>::max(), "indirect draw record range overflow");
if (!gpuIndirectDraws) indirect.path = IndirectDrawPath::Disabled;
@@ -2406,7 +2477,7 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
if (std::none_of(records.begin(), records.end(), [](const Pm4::DrawArguments& record) { return record.count != 0 && record.instances != 0; })) {
CountIndirectDraw(indirect.path, indirect.readMs);
report(" indirect draw with empty records");
return;
return false;
}
}
}
@@ -2431,14 +2502,14 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
static const bool syncCompletionDraws = std::getenv("APS5_SYNC_COMPLETION_DRAWS") != nullptr;
static const bool recorderSyncDraws = std::getenv("APS5_NO_RECORDER_SYNC_DRAWS") == nullptr;
static const bool recordCopiedDraws = std::getenv("APS5_NO_RECORD_COPIED_DRAWS") == nullptr;
const bool completion = resources->NeedsCompletion();
const bool completion = prepared.completion = resources->NeedsCompletion();
const bool copiedWrites = completion && resources->HasCopiedWrites();
// A lease only forces the wait when deferred release is off.
const bool lease = resources->HoldsLease() && SyncLeaseWork();
outcome.completion = completion;
outcome.recorded = recordable;
// Whether the copied write-back is listed in DrawCopiedWriters instead of waited for.
bool listed = false;
auto& listed = prepared.listed;
if (!recordable) {
outcome.reason = !recordDraws || dumpLimit != 0 ? SyncDisabled : recorder == nullptr ? SyncNoRecorder : SyncNotResident;
} else if (completion && (syncCompletionDraws || copiedWrites || lease)) {
@@ -2448,7 +2519,7 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
else if (recorderSyncDraws) outcome.waited = true;
else outcome.recorded = false;
}
const bool recorded = outcome.recorded;
const bool recorded = prepared.recorded = outcome.recorded;
// A build this recorded draw can share with later identical ones goes into the cache (a cache
// hit is reusable by construction, so `recorded` holds for it; one with completion work is
// never reusable).
@@ -2457,8 +2528,8 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
// aid: APS5_DRAW_TRANSITIONS=1 keeps the per-draw upload and download barriers, the layout
// transitions of every target and one pass per draw, as before.
static const bool drawTransitions = std::getenv("APS5_DRAW_TRANSITIONS") != nullptr;
const bool lean = recorded && !drawTransitions;
const bool multisampled = std::any_of(targets.begin(), targets.end(), [](const TargetBinding& binding) { return binding.multisampled; });
const bool lean = prepared.lean = recorded && !drawTransitions;
const bool multisampled = prepared.multisampled = std::any_of(targets.begin(), targets.end(), [](const TargetBinding& binding) { return binding.multisampled; });
Require(lean || !multisampled, "multisampled draws are only rendered as recorded draws");
for (const auto& binding : targets) {
if (binding.multisampled) Require(std::find(resources->MultisampleSources().begin(), resources->MultisampleSources().end(), binding.color.surfaceAddress) == resources->MultisampleSources().end(), "sampling a multisampled color target the draw renders to is not implemented");
@@ -2470,7 +2541,8 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
if (state.depth) RequireNoNativeDepthFeedback_nid_no_patch(context, *state.depth, resources->SampledTextures());
APS5_LOG_CHARS_OUT_DEBUG("Creating Pipeline");
// The state is copied only when a mask must change.
auto masked = maskedState(state, inputs.fragmentOutputs);
auto& masked = prepared.masked;
masked = maskedState(state, inputs.fragmentOutputs);
if (std::any_of(targets.begin(), targets.end(), [](const TargetBinding& binding) { return binding.proxied; })) recipeOut = nullptr;
for (std::size_t index = 0; index < targets.size(); ++index) {
if (!targets[index].proxied) continue;
@@ -2485,7 +2557,7 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
const auto built = resources->SetLayouts();
Require(described.layouts.main == built.main && described.layouts.fragment == built.fragment && described.layouts.split == built.split && std::ranges::equal(described.mainKey, built.mainKey) && std::ranges::equal(described.fragmentKey, built.fragmentKey), "set layouts described from the shaders differ from the draw's");
}
std::vector<std::pair<std::uint32_t, std::shared_ptr<Pipeline>>> stencilReplay;
auto& stencilReplay = prepared.stencilReplay;
for (const auto reference : stencilReferences) {
auto selected = pipelineState;
selected.stencilReplayReference = reference;
@@ -2495,20 +2567,22 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
Require(!selectedPipeline->SplitsFaces() && !selectedPipeline->SplitsSecondChannel(), "stencil replay refuses pipeline face or channel splits");
stencilReplay.emplace_back(reference, std::move(selectedPipeline));
}
auto pipeline = stencilReplay.empty() ? CachedPipeline(context, pipelineState, inputs.VertexLayout(), *resources, shaders, lean ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) : stencilReplay.front().second;
auto& pipeline = prepared.pipeline;
pipeline = stencilReplay.empty() ? CachedPipeline(context, pipelineState, inputs.VertexLayout(), *resources, shaders, lean ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) : stencilReplay.front().second;
// Resident targets' views are stable while their storage image lives, so the framebuffer is
// reused with the pipeline; a per-draw RenderTarget gets a framebuffer of its own.
std::vector<std::shared_ptr<StorageTexture>> owners;
auto& owners = prepared.owners;
owners.reserve(targets.size());
std::vector<std::shared_ptr<void>> framebufferOwners;
auto& framebufferOwners = prepared.framebufferOwners;
framebufferOwners.reserve(targets.size());
for (const auto& binding : targets) {
owners.push_back(binding.resident);
framebufferOwners.push_back(binding.multisampled ? binding.multisampleOwner : binding.resident);
}
auto framebuffer = pipeline->AcquireFramebuffer(targetViews, framebufferOwners, state.renderExtent, state.renderLayers);
std::vector<SampleOrderTarget> reordered;
SampleOrderPass reorderPass;
auto& framebuffer = prepared.framebuffer;
framebuffer = pipeline->AcquireFramebuffer(targetViews, framebufferOwners, state.renderExtent, state.renderLayers);
auto& reordered = prepared.reordered;
auto& reorderPass = prepared.reorderPass;
if (pipeline->ReordersSamples()) {
reorderPass = SampleOrderPassFor(context, pipelineState, pipeline->HostSampleOrder());
for (const auto& step : PlanSampleOrder(context, state, pipeline->HostSampleOrder())) {
@@ -2517,9 +2591,50 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
Require(reordered.back().method == step.method, "a reordered attachment's surface disagrees with the planned way of putting its samples in order");
}
}
const auto depthLocations = passDepthLocations(context, pipelineState, *pipeline);
prepared.depthLocations = passDepthLocations(context, pipelineState, *pipeline);
timer.phase(PhasePipeline);
APS5_LOG_CHARS_OUT_DEBUG("Pipeline created");
return true;
}
void recordPreparedDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, PreparedDraw& prepared) {
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
static const bool traceDraws = std::getenv("APS5_TRACE_DRAWS") != nullptr;
static std::mutex dumpMutex;
static std::map<std::uint64_t, int> dumped;
auto& timing = *prepared.timing;
auto& timer = prepared.timer;
auto& outcome = prepared.outcome;
const auto* built = prepared.built;
const auto waitedBefore = prepared.waitedBefore;
auto& ownWaitedMs = prepared.ownWaitedMs;
const auto report = [&](const char* suffix) { reportDrawEnd(state, timer, built, outcome, waitedBefore, ownWaitedMs, suffix); };
auto* recipeOut = prepared.recipeOut;
const auto& stencilReferences = prepared.stencilReferences;
auto& inputs = prepared.inputs;
const auto* args = prepared.args;
const int dumpLimit = prepared.dumpLimit;
auto& targets = prepared.targets;
const auto& targetViews = prepared.targetViews;
auto* recorder = prepared.recorder;
auto& resolved = prepared.resolved;
auto& resources = resolved.resources;
const auto& contentKey = resolved.contentKey;
const bool cacheable = resolved.cacheable;
auto& indirect = prepared.indirect;
const bool completion = prepared.completion;
const bool listed = prepared.listed;
const bool recorded = prepared.recorded;
const bool lean = prepared.lean;
const bool multisampled = prepared.multisampled;
const auto& masked = prepared.masked;
const auto& stencilReplay = prepared.stencilReplay;
const auto& pipeline = prepared.pipeline;
const auto& owners = prepared.owners;
const auto& framebuffer = prepared.framebuffer;
const auto& reordered = prepared.reordered;
const auto& reorderPass = prepared.reorderPass;
const auto& depthLocations = prepared.depthLocations;
if (lean) {
RecordedDraw record;
record.recorder = recorder;
@@ -2844,6 +2959,15 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
APS5_LOG_CHARS_OUT_DEBUG("Draw finished");
}
}
void Draw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots, std::shared_ptr<const DrawRecipe>* recipeOut) {
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
PreparedDraw prepared(profile);
prepared.recipeOut = recipeOut;
if (prepareDraw(context, state, draw, shaders, snapshots, prepared)) recordPreparedDraw(context, state, draw, shaders, prepared);
}
DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots, const DrawRecipe& recipe) {
if (context.recorder != nullptr) context.recorder->BoundKeptBytes();
static_cast<void>(snapshots);
@@ -2866,7 +2990,7 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con
};
Require(!draw.indirect, "a draw recipe covers direct draws only");
auto* recorder = Recorder::Active();
if (state.quadList || !RecordDraws() || recorder == nullptr || DumpTargetLimit() != 0) return miss(DrawRecipeMiss::NotRecordable);
if (state.quadList || StripPatches(state, shaders) || !RecordDraws() || recorder == nullptr || DumpTargetLimit() != 0) return miss(DrawRecipeMiss::NotRecordable);
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");
@@ -2899,6 +3023,7 @@ DrawRecipeOutcome DrawWithRecipe(const Context& context, const State& state, con
if (recipe.hasDepth) {
timer.phase(PhaseSetup);
const auto depthView = DepthSurfaceView(context, *state.depth, state.depthWrite);
if (writesDepthTarget(state)) NoteDepthSurfaceWrite(context, *state.depth);
timer.phase(PhaseReadTarget);
if (recipe.targetViews.back() != depthView) return miss(DrawRecipeMiss::TargetGone);
}
@@ -2980,6 +3105,26 @@ void RunDepthCopyPass(const Context& context, const DepthCopyPass& pass) {
CopyDepthSample(context, pass.depthAddress, pass.samples, pass.sample, *resident, resident->StorageView(0, false), pass.extent);
}
std::vector<std::pair<std::uint64_t, std::uint64_t>> PipelinedColorMetadataPassWrites(const ColorMetadataPass& pass) {
std::vector<std::pair<std::uint64_t, std::uint64_t>> writes;
if (pass.mode == ColorMetadataPass::Mode::Resolve) {
if (!pass.source.has_value() || pass.targets.size() != 1) return writes;
const auto& destination = pass.targets.front();
if (destination.samples != 1u || destination.bytes == 0 || destination.cmaskAddress != 0) return writes;
writes.emplace_back(destination.address, destination.address + destination.bytes);
if (destination.dccAddress != 0) writes.emplace_back(destination.dccAddress, destination.dccAddress + std::max<std::size_t>(colorKeyCount(destination, destination.bytes), 1u));
return writes;
}
if (pass.mode != ColorMetadataPass::Mode::EliminateFastClear && pass.mode != ColorMetadataPass::Mode::DccDecompress) return writes;
for (const auto& color : pass.targets) {
if (color.samples != 1u || color.bytes == 0) return {};
writes.emplace_back(color.address, color.address + color.bytes);
if (color.cmaskAddress != 0) writes.emplace_back(color.cmaskAddress, color.cmaskAddress + std::max<std::size_t>(color.cmaskBytes, 1u));
if (color.dccAddress != 0) writes.emplace_back(color.dccAddress, color.dccAddress + std::max<std::size_t>(colorKeyCount(color, color.bytes), 1u));
}
return writes;
}
void RunColorMetadataPass(const Context& context, const ColorMetadataPass& pass) {
if (pass.mode == ColorMetadataPass::Mode::Resolve) {
Require(pass.source.has_value() && pass.targets.size() == 1, "CB resolve without its source and destination");
@@ -3024,4 +3169,13 @@ void RunColorMetadataPass(const Context& context, const ColorMetadataPass& pass)
}
}
bool DrawPipelineEnabled() {
static const bool enabled = std::getenv("APS5_DRAW_PIPELINE") != nullptr;
return enabled;
}
bool CommitTrims() {
return DrawPipelineEnabled();
}
}
@@ -4679,7 +4679,7 @@ void GuestBufferMemory::UploadFinish(bool addressable) {
void GuestBufferMemory::copyRegion(Region& region, bool addressable) {
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
const auto bytes = region.end - region.begin;
const auto usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (addressable ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u);
const auto usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | (addressable ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u);
std::uint64_t readBytes = 0;
bool inImport = false;
if (profile && context.hostImportAlignment != 0) {
@@ -5173,7 +5173,7 @@ void GuestBufferMemory::MarkDirectWrites() const {
const auto* found = owner(begin, end);
if (found == nullptr) continue;
const auto& region = *found;
if (region.direct != nullptr || (region.gpuCopy && region.copiedBack)) GuestMemory::MarkWritten(begin, static_cast<std::size_t>(end - begin));
if (region.direct != nullptr || (region.gpuCopy && region.copiedBack)) GuestMemory::MarkPossiblyWritten(begin, static_cast<std::size_t>(end - begin));
}
}
@@ -5261,7 +5261,7 @@ void GuestBufferMemory::WriteBack() {
if (region.direct == nullptr && !(region.gpuCopy && (region.copiedBack || region.deviceLocal)) && !(region.mirror != nullptr && !region.mirror->writable)) Recorder::NoteWrittenBack(begin, static_cast<std::size_t>(end - begin));
if (region.direct != nullptr) {
// The GPU wrote imported guest memory directly; page write watching did not see it.
GuestMemory::MarkWritten(begin, static_cast<std::size_t>(end - begin));
GuestMemory::MarkPossiblyWritten(begin, static_cast<std::size_t>(end - begin));
continue;
}
if (region.mirror != nullptr) {
@@ -5291,7 +5291,7 @@ void GuestBufferMemory::WriteBack() {
if (region.copiedBack) {
// The GPU copied the written sub-range back into the import; page write watching
// did not see it.
GuestMemory::MarkWritten(begin, static_cast<std::size_t>(end - begin));
GuestMemory::MarkPossiblyWritten(begin, static_cast<std::size_t>(end - begin));
continue;
}
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
@@ -5,6 +5,8 @@
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
#include "RdnaDecoder/RdnaDescriptorFormat.hpp"
#include <algorithm>
#include <array>
#include <optional>
#include <stdexcept>
#include <string>
@@ -50,6 +52,45 @@ TextureDimension resolveDimension(std::uint32_t raw) {
}
}
bool ZeroTail(std::span<const std::uint32_t> words) {
return words[4] == 0u && words[5] == 0u && words[6] == 0u && words[7] == 0u;
}
bool SameLevels(const TileMipLayout& a, const TileMipLayout& b) {
return a.tiledOffset == b.tiledOffset && a.tiledSize == b.tiledSize && a.width == b.width && a.height == b.height && a.blocksPerRow == b.blocksPerRow && a.pitchBytes == b.pitchBytes && a.tail == b.tail && a.tailX == b.tailX && a.tailY == b.tailY;
}
std::optional<std::array<std::uint32_t, 8>> R128ResidentLevelWords(std::span<const std::uint32_t> words) {
const auto baseLevel = (words[3] >> 12u) & 0xfu;
const auto lastLevel = (words[3] >> 16u) & 0xfu;
const auto typeRaw = (words[3] >> 28u) & 0xfu;
if (baseLevel == 0u || baseLevel > lastLevel || (typeRaw != 8u && typeRaw != 9u)) return std::nullopt;
const std::array<std::uint32_t, 8> chainWords{words[0], words[1], words[2], words[3], 0u, lastLevel << 4u, 0u, 0u};
const auto width = (((words[1] >> 30u) & 0x3u) | ((words[2] & 0xfffu) << 2u)) + 1u;
const auto height = ((words[2] >> 14u) & 0x3fffu) + 1u;
const auto minLod = (words[1] >> 8u) & 0xfffu;
const auto widthMinus1 = std::max(width >> baseLevel, 1u) - 1u;
const auto heightMinus1 = std::max(height >> baseLevel, 1u) - 1u;
const auto rebasedMinLod = minLod > baseLevel * 256u ? minLod - baseLevel * 256u : 0u;
const auto levels = lastLevel - baseLevel;
auto rebased = chainWords;
rebased[1] = (words[1] & ~((0xfffu << 8u) | (0x3u << 30u))) | (rebasedMinLod << 8u) | ((widthMinus1 & 0x3u) << 30u);
rebased[2] = (words[2] & ~(0xfffu | (0x3fffu << 14u))) | ((widthMinus1 >> 2u) & 0xfffu) | ((heightMinus1 & 0x3fffu) << 14u);
rebased[3] = (words[3] & ~(0xffu << 12u)) | (levels << 16u);
rebased[5] = levels << 4u;
try {
const auto chain = DescribeSurface(DecodeTextureResource(chainWords));
const auto view = DescribeSurface(DecodeTextureResource(rebased));
if (chain.mips.size() != lastLevel + 1u || view.mips.size() != levels + 1u || chain.layers != view.layers) return std::nullopt;
for (std::uint32_t level = baseLevel; level <= lastLevel; ++level) {
if (!SameLevels(chain.mips[level], view.mips[level - baseLevel])) return std::nullopt;
}
} catch (const std::exception&) {
return std::nullopt;
}
return rebased;
}
}
bool IsNullTextureResource(std::span<const std::uint32_t> words) {
@@ -140,7 +181,8 @@ GuestTextureResource DecodeTextureResource(std::span<const std::uint32_t> words)
const bool fmask = ShaderRecompiler::IsFmaskTextureFormat(static_cast<ShaderRecompiler::IrBufferFormat>(format));
if (fmask) {
Require(format == static_cast<std::uint32_t>(ShaderRecompiler::IrBufferFormat::Fmask32_S8_F8), "guest FMASK format is not implemented");
Require(!metaCompress && !writeCompress, "FMASK CMASK compression is not implemented");
Require(!writeCompress && (!metaCompress || metaAddr != 0u), "FMASK CMASK compression is not implemented without readable metadata");
Require(!metaCompress || metaPipeAligned, "FMASK CMASK metadata must be pipe aligned");
Require((typeRaw == 9u || typeRaw == 13u) && tileModeRaw == 24u && baseLevel == 0u && lastLevel == 0u && maxMip == 0u, "FMASK reads require a single-mip 2D or 2D-array Z_64KB_X surface");
for (const auto selector : {dstSelX, dstSelY, dstSelZ, dstSelW}) Require(selector == 0u || selector == 1u || selector == 4u, "FMASK destination channel selector is not implemented");
}
@@ -229,14 +271,19 @@ GuestTextureResource DecodeTextureResource(std::span<const std::uint32_t> words)
result.dstSelZ = static_cast<std::uint8_t>(dstSelZ);
result.dstSelW = static_cast<std::uint8_t>(dstSelW);
result.bcSwizzle = static_cast<std::uint8_t>(bcSwizzle);
result.dccAddress = metaCompress ? metaAddr << 8u : 0u;
result.dccAddress = metaCompress && !fmask ? metaAddr << 8u : 0u;
result.fmaskCmaskAddress = metaCompress && fmask ? metaAddr << 8u : 0u;
result.dccAlphaOnMsb = dccAlphaPos;
result.dccPipeAligned = metaPipeAligned;
result.iterate256 = iterate256;
result.minLod = minLod;
result.samples = samples;
if (baseLevel > maxMip) {
Require(LevelsFitAllocation(result, lastLevel + 1u), "guest texture descriptor starts past the surface's last mip level at levels that would move the surface's own" + describe());
const bool fits = LevelsFitAllocation(result, lastLevel + 1u);
if (!fits && ZeroTail(words)) {
if (const auto resident = R128ResidentLevelWords(words)) return DecodeTextureResource(*resident);
}
Require(fits, "guest texture descriptor starts past the surface's last mip level at levels that would move the surface's own" + describe());
result.mipCount = lastLevel + 1u;
}
return result;
@@ -9,6 +9,8 @@
#include "prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp"
#include "IntermediateRepresentation/IrMetadata/BufferFormat.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include <algorithm>
@@ -45,10 +47,57 @@ std::uint64_t collectBlocks(std::uint64_t address, std::size_t bytes) {
return generation != 0 ? generation : GuestMemory::CollectWritesUncached(address, bytes);
}
GuestTextureResource fmaskSnapshotResource(const GuestTextureResource& resource) {
Require(resource.format == static_cast<std::uint32_t>(ShaderRecompiler::IrBufferFormat::Format32UInt) && resource.fmaskCmaskAddress != 0u, "FMASK image format read semantics are not implemented");
Require(resource.dimension == TextureDimension::k2D || resource.dimension == TextureDimension::k2DArray, "FMASK image dimension is not implemented");
Require(resource.tileMode == TextureTileMode::kZ64KBX && (resource.pipeBankXor & ~0xcf00u) == 0u, "FMASK image swizzle or pipe/bank XOR is not implemented");
Require(resource.width != 0u && resource.width <= 16384u && resource.height != 0u && resource.height <= 16384u && resource.depthOrLastArray < 8192u && resource.baseArray <= resource.depthOrLastArray, "invalid FMASK image extent or layer range");
Require(resource.dimension == TextureDimension::k2DArray || (resource.depthOrLastArray == 0u && resource.baseArray == 0u), "FMASK 2D image has an array range");
Require(resource.mipCount == 1u && resource.allocatedMipCount == 1u && resource.baseLevel == 0u && resource.lastLevel == 0u && resource.minLod == 0u, "FMASK image mip fields are not implemented");
Require(resource.fmaskCmaskAddress == 0u || resource.dccPipeAligned, "FMASK image CMASK must be pipe aligned");
for (const auto selector : {resource.dstSelX, resource.dstSelY, resource.dstSelZ, resource.dstSelW}) Require(selector == 0u || selector == 1u || selector == 4u, "FMASK image selects an unverified channel");
auto snapshot = resource;
snapshot.format = static_cast<std::uint32_t>(ShaderRecompiler::IrBufferFormat::Format32UInt);
snapshot.tileMode = TextureTileMode::kLinear;
snapshot.pipeBankXor = 0u;
snapshot.dccAddress = 0u;
snapshot.fmaskCmaskAddress = 0u;
snapshot.dccAlphaOnMsb = false;
snapshot.dccPipeAligned = false;
return snapshot;
}
GuestTextureResource fmaskResource(const ColorTarget& target) {
GuestTextureResource resource{};
resource.baseAddress = target.fmaskAddress;
resource.width = target.extent.width;
resource.height = target.extent.height;
resource.mipCount = 1u;
resource.allocatedMipCount = 1u;
resource.tileMode = TextureTileMode::kZ64KBX;
resource.dimension = TextureDimension::k2D;
resource.format = static_cast<std::uint32_t>(ShaderRecompiler::IrBufferFormat::Format32UInt);
resource.dstSelX = 4u;
resource.pipeBankXor = target.fmaskPipeBankXor;
resource.fmaskCmaskAddress = target.cmaskAddress;
resource.dccPipeAligned = true;
return resource;
}
bool sameTarget(const ColorTarget& a, const ColorTarget& b) {
return a.surfaceAddress == b.surfaceAddress && a.format == b.format && a.extent.width == b.extent.width && a.extent.height == b.extent.height && a.samples == b.samples;
}
constexpr VkImageUsageFlags twinViewUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
VkFormat colorTwinFormat(const Context& context, VkFormat format) {
if (const auto srgb = SrgbTwinFormat(context, format); srgb != VK_FORMAT_UNDEFINED) return srgb;
for (const auto unorm : {VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_A8B8G8R8_UNORM_PACK32}) {
if (SrgbTwinFormat(context, unorm) == format) return unorm;
}
return VK_FORMAT_UNDEFINED;
}
bool recreated(const ColorTarget& resident, const ColorTarget& use) {
return use.dccAddress != 0 && use.pipeBankXor != resident.pipeBankXor && use.address == resident.address && use.dccAddress == resident.dccAddress && use.dccControl == resident.dccControl && use.dccAlphaOnMsb == resident.dccAlphaOnMsb && use.dccPipeAligned == resident.dccPipeAligned && use.cmaskAddress == resident.cmaskAddress && use.cmaskBytes == resident.cmaskBytes && use.tileMode == resident.tileMode && use.elementBytes == resident.elementBytes;
}
@@ -101,6 +150,13 @@ public:
return context.imageFormatProperties(context.physical, format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, formatUsage, flags, &properties) == VK_SUCCESS && (properties.sampleCounts & samples) != 0;
};
if (storageFormat != VK_FORMAT_UNDEFINED && (!context.storageImageMultisample || !storageSupports(storageFormat, VK_IMAGE_USAGE_STORAGE_BIT, 0u) || !storageSupports(target.format, usage | VK_IMAGE_USAGE_STORAGE_BIT, storageFlags))) storageFormat = VK_FORMAT_UNDEFINED;
twinFormat = colorTwinFormat(context, target.format);
if (twinFormat != VK_FORMAT_UNDEFINED) {
VkFormatProperties twinProperties{};
context.formatProperties(context.physical, twinFormat, &twinProperties);
const VkImageCreateFlags twinFlags = orderFlags | VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
if ((twinProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) == 0 || !storageSupports(target.format, usage, twinFlags) || !storageSupports(twinFormat, twinViewUsage, twinFlags)) twinFormat = VK_FORMAT_UNDEFINED;
}
try {
const auto created = allocate(usage, orderFlags);
image = created.image;
@@ -135,6 +191,16 @@ public:
try {
VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
info.flags = flags;
const std::array<VkFormat, 2> viewFormats{target.format, twinFormat};
VkImageFormatListCreateInfo formatList{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO};
if (twinFormat != VK_FORMAT_UNDEFINED) {
if ((flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) == 0 && context.imageFormatList) {
formatList.viewFormatCount = static_cast<std::uint32_t>(viewFormats.size());
formatList.pViewFormats = viewFormats.data();
info.pNext = &formatList;
}
info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT;
}
info.imageType = VK_IMAGE_TYPE_2D;
info.format = target.format;
info.extent = {target.extent.width, target.extent.height, 1};
@@ -203,6 +269,7 @@ public:
Recorder::CountBarriers(Recorder::CommandClass::Draw, 3);
for (auto& [key, texture] : textures) retiredTextures.push_back(std::move(texture));
textures.clear();
retired.push_back({VK_NULL_HANDLE, VK_NULL_HANDLE, std::exchange(twinView, VK_NULL_HANDLE)});
retired.push_back({image, memory, view});
image = storable.image;
memory = storable.memory;
@@ -212,6 +279,28 @@ public:
recorder.Keep(shared_from_this(), static_cast<std::size_t>(storable.bytes));
}
std::shared_ptr<Texture> FmaskSampled(const GuestTextureResource& resource, VkComponentMapping components) {
const auto snapshot = fmaskSnapshotResource(resource);
Require(target.samples == 8u && target.dccAddress != 0u && fmaskRange.has_value(), "native FMASK sampling requires a tracked eight-fragment DCC target");
Require(target.tileMode == ColorTileMode::RenderTarget && target.depth == 1u && target.depthSlice == 0u && target.layers == 1u && target.arrayLastSlice == 0u && target.arraySlice == 0u && target.mip == 0u && target.mipCount == 1u, "native FMASK target layout is not implemented");
Require(target.fmaskAddress == resource.baseAddress && target.fmaskPipeBankXor == resource.pipeBankXor && target.cmaskAddress == resource.fmaskCmaskAddress, "native FMASK descriptor does not match its resident target");
Require(target.extent.width == resource.width && target.extent.height == resource.height && resource.baseArray == 0u && resource.depthOrLastArray == 0u, "native FMASK extent or subresource does not match its resident target");
auto* recorder = Recorder::Active();
Require(recorder != nullptr && recorder->Device() == context.device && !Recorder::InCompletion(), "native FMASK sampling requires its device's active recorder outside completion");
ApplyFastClear(target);
Keep();
const std::array<std::uint32_t, 5> key{static_cast<std::uint32_t>(components.r), static_cast<std::uint32_t>(components.g), static_cast<std::uint32_t>(components.b), static_cast<std::uint32_t>(components.a), static_cast<std::uint32_t>(resource.dimension)};
auto& texture = fmaskTextures[key];
if (texture == nullptr) {
const auto geometry = DescribeSurface(snapshot);
std::vector<std::byte> bytes(geometry.guestBytes);
constexpr std::uint32_t expanded = 0x76543210u;
for (std::size_t offset = 0; offset < bytes.size(); offset += sizeof(expanded)) std::memcpy(bytes.data() + offset, &expanded, sizeof(expanded));
texture = std::make_unique<Texture>(context, *context.detiler, snapshot, components, bytes);
}
return {shared_from_this(), texture.get()};
}
void Keep() {
if (auto* recorder = Recorder::Active(); recorder != nullptr && recorder->Device() == context.device) {
recorder->Keep(shared_from_this());
@@ -241,6 +330,7 @@ public:
colorFill = MultisampledColorFill(use);
fromTexture = false;
dccRanges.clear();
fmaskRange.reset();
metadataValid = std::make_shared<std::atomic<bool>>(true);
const auto initial = initialDccClear(use);
recordCommands(context, [&](VkCommandBuffer commands, Recorder* recorder) {
@@ -336,14 +426,39 @@ public:
return {shared_from_this(), texture.get()};
}
VkRenderPass ResolvePass() {
VkImageView View(VkFormat format) {
if (format == target.format) return view;
Require(twinFormat != VK_FORMAT_UNDEFINED && format == twinFormat, "a multisampled color target is only viewed in its own format or its sRGB twin");
if (twinView == VK_NULL_HANDLE) {
VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = twinFormat;
viewInfo.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageViewUsageCreateInfo viewUsage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO};
viewUsage.usage = twinViewUsage;
viewInfo.pNext = &viewUsage;
Check(context.Function<PFN_vkCreateImageView>("vkCreateImageView")(context.device, &viewInfo, nullptr, &twinView), "vkCreateImageView multisampled target twin");
}
return twinView;
}
bool Serves(const ColorTarget& use) const {
if (use.format == target.format) return sameTarget(target, use);
auto twin = use;
twin.format = target.format;
return twinFormat != VK_FORMAT_UNDEFINED && use.format == twinFormat && sameTarget(target, twin);
}
VkRenderPass ResolvePass(VkFormat format) {
auto& resolvePass = resolvePasses[format];
if (resolvePass != VK_NULL_HANDLE) return resolvePass;
std::array<VkAttachmentDescription, 2> attachments{};
attachments[0].format = target.format;
attachments[0].format = format;
attachments[0].samples = static_cast<VkSampleCountFlagBits>(target.samples);
attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[1].format = target.format;
attachments[1].format = format;
attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
@@ -376,7 +491,7 @@ public:
VkImage image = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
VkImageView view = VK_NULL_HANDLE;
VkRenderPass resolvePass = VK_NULL_HANDLE;
std::map<VkFormat, VkRenderPass> resolvePasses;
MultisampledCmask cmask;
MultisampledColorFill colorFill;
bool fromTexture = false;
@@ -391,10 +506,14 @@ private:
VkImageUsageFlags usage = 0;
VkFormat storageFormat = VK_FORMAT_UNDEFINED;
VkImageCreateFlags storageFlags = 0;
VkFormat twinFormat = VK_FORMAT_UNDEFINED;
VkImageView twinView = VK_NULL_HANDLE;
std::vector<Allocation> retired;
VkImageView storageView = VK_NULL_HANDLE;
bool storageWritten = false;
VkDeviceSize allocationBytes = 0;
std::optional<GuestMemory::UnchangedQuery> fmaskRange;
std::map<std::array<std::uint32_t, 5>, std::unique_ptr<Texture>> fmaskTextures;
std::map<std::array<std::uint32_t, 5>, std::shared_ptr<Texture>> textures;
std::vector<std::shared_ptr<Texture>> retiredTextures;
std::vector<GuestMemory::UnchangedQuery> dccRanges;
@@ -450,18 +569,29 @@ private:
Require(a.address >= b.address + b.bytes || b.address >= a.address + a.bytes, "overlapping multisampled DCC color or metadata ranges are not implemented");
}
}
if (use.samples == 8u && use.fmaskAddress != 0u && use.cmaskAddress != 0u) {
const auto resource = fmaskResource(use);
static_cast<void>(fmaskSnapshotResource(resource));
fmaskRange = GuestMemory::UnchangedQuery{use.fmaskAddress, static_cast<std::size_t>(DescribeSurface(resource).guestBytes), 0};
auto& range = *fmaskRange;
GuestMemory::CheckRange(reinterpret_cast<const void*>(range.address), range.bytes, 65536u);
Require(GuestMemory::Watched(range.address, range.bytes), "native FMASK contents require watched guest memory");
range.generation = GuestMemory::CollectWritesUncached(range.address, range.bytes);
Require(range.generation != 0, "native FMASK contents have no write generation");
for (const auto& other : dccRanges) Require(range.address >= other.address + other.bytes || other.address >= range.address + range.bytes, "native FMASK overlaps its color or metadata planes");
}
std::vector<std::byte> dcc(dccRanges[1].bytes);
GuestMemory::Read(use.dccAddress, dcc);
std::vector<std::byte> cmask(use.cmaskBytes);
if (!cmask.empty()) GuestMemory::Read(use.cmaskAddress, cmask);
const auto clear = MultisampledDccClear(use, dcc, cmask);
Require(GuestMemory::UnchangedSinceAll(dccRanges), "initial multisampled DCC contents changed during import");
Require(GuestMemory::UnchangedSinceAll(dccRanges) && (!fmaskRange || GuestMemory::UnchangedSinceAll(std::span(&*fmaskRange, 1u))), "initial multisampled DCC contents changed during import");
return clear;
}
void requireDccRange(bool valid, const GuestMemory::UnchangedQuery& range, const char* reason) const {
if (valid) return;
const auto* plane = range.address == target.address ? "color" : range.address == target.dccAddress ? "DCC" : "CMASK";
const auto* plane = range.address == target.address ? "color" : range.address == target.dccAddress ? "DCC" : range.address == target.fmaskAddress ? "FMASK" : "CMASK";
char text[384];
std::snprintf(text, sizeof(text), "%s (%s range 0x%llx+0x%zx, %u samples)", reason, plane, static_cast<unsigned long long>(range.address), range.bytes, target.samples);
Require(false, text);
@@ -482,13 +612,23 @@ private:
requireDccRange(GuestMemory::UnchangedSince(range.address, range.bytes, range.generation) || !GuestMemory::StoredOver(range.address, range.bytes, range.generation), range, "writes to a resident multisampled DCC target or its metadata are not implemented");
if (auto* recorder = Recorder::Active(); recorder != nullptr) requireDccRange(!recorder->PendingWriteOverlaps(range.address, range.bytes), range, "pending writes to a resident multisampled DCC target or its metadata are not implemented");
}
if (fmaskRange) {
Require(use.fmaskAddress == target.fmaskAddress && use.fmaskPipeBankXor == target.fmaskPipeBankXor, "native FMASK target layout changed");
const auto& range = *fmaskRange;
requireDccRange(GuestMemory::Watched(range.address, range.bytes), range, "native FMASK sampling requires watched guest memory");
GuestMemory::CollectWritesUncached(range.address, range.bytes);
requireDccRange(GuestMemory::UnchangedSince(range.address, range.bytes, range.generation) || !GuestMemory::StoredOver(range.address, range.bytes, range.generation), range, "writes to a resident native FMASK are not implemented");
if (auto* recorder = Recorder::Active(); recorder != nullptr) requireDccRange(!recorder->PendingWriteOverlaps(range.address, range.bytes), range, "pending writes to a resident native FMASK are not implemented");
}
}
void release() noexcept {
fmaskTextures.clear();
textures.clear();
retiredTextures.clear();
if (resolvePass) context.Function<PFN_vkDestroyRenderPass>("vkDestroyRenderPass")(context.device, resolvePass, nullptr);
for (const auto& [format, resolvePass] : resolvePasses) context.Function<PFN_vkDestroyRenderPass>("vkDestroyRenderPass")(context.device, resolvePass, nullptr);
if (orderView) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, orderView, nullptr);
if (twinView) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, twinView, nullptr);
if (storageView) context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, storageView, nullptr);
destroy({image, memory, view});
for (const auto& allocation : retired) destroy(allocation);
@@ -591,6 +731,7 @@ void guard(const Context& context, const ColorTarget& target, const std::shared_
if (target.dccAddress != 0) {
guarded().push_back({context.device, target.dccAddress, MultisampledDccBytes(target), target.samples, active, metadataValid});
if (target.cmaskAddress != 0) guarded().push_back({context.device, target.cmaskAddress, target.cmaskBytes, target.samples, active, metadataValid});
if (target.samples == 8u && target.fmaskAddress != 0u && target.cmaskAddress != 0u) guarded().push_back({context.device, target.fmaskAddress, DescribeSurface(fmaskResource(target)).guestBytes, target.samples, active, metadataValid});
}
anyGuarded().store(true, std::memory_order_release);
InstallResidentImageReadGuard_nid_no_patch();
@@ -610,11 +751,13 @@ void discardRetiredTargets() {
std::erase_if(targets(), [](const auto& target) { return !target->active->load(std::memory_order_acquire); });
}
MultisampleTarget& acquire(const Context& context, const ColorTarget& use) {
MultisampleTarget& acquire(const Context& context, const ColorTarget& requested) {
discardRetiredTargets();
for (const auto& target : targets()) {
if (!target->active->load(std::memory_order_acquire)) continue;
if (target->context.device != context.device || !sameTarget(target->target, use)) continue;
if (target->context.device != context.device || !target->Serves(requested)) continue;
auto use = requested;
use.format = target->target.format;
if (recreated(target->target, use)) {
{
std::unique_lock lock(guardedMutex());
@@ -636,6 +779,7 @@ MultisampleTarget& acquire(const Context& context, const ColorTarget& use) {
target->ApplyFastClear(use);
return *target;
}
const auto& use = requested;
auto target = std::make_shared<MultisampleTarget>(context, use);
target->Keep();
targets().push_back(std::move(target));
@@ -956,9 +1100,9 @@ SampleOrderTarget MultisampleTargetOrderTarget(const Context& context, const Col
VkImageView MultisampleTargetView(const Context& context, const ColorTarget& target, VkImage* image) {
std::lock_guard lock(targetsMutex());
const auto& acquired = acquire(context, target);
auto& acquired = acquire(context, target);
if (image != nullptr) *image = acquired.image;
return acquired.view;
return acquired.View(target.format);
}
VkImageView MultisampleTargetView(const Context& context, const ColorTarget& target, std::shared_ptr<void>& owner, VkImage* image) {
@@ -966,7 +1110,7 @@ VkImageView MultisampleTargetView(const Context& context, const ColorTarget& tar
auto& acquired = acquire(context, target);
owner = acquired.shared_from_this();
if (image != nullptr) *image = acquired.image;
return acquired.view;
return acquired.View(target.format);
}
void KeepMultisampleTarget_nid_no_patch(const std::shared_ptr<void>& owner) {
@@ -1052,12 +1196,12 @@ void ResolveMultisampleTarget(const Context& context, const ColorTarget& source,
std::lock_guard lock(targetsMutex());
auto& target = acquire(context, source);
target.Keep();
const std::array<VkImageView, 2> views{target.view, destinationView};
auto framebuffer = std::make_shared<Framebuffer>(context, target.ResolvePass(), views, source.extent);
const std::array<VkImageView, 2> views{target.View(source.format), destinationView};
auto framebuffer = std::make_shared<Framebuffer>(context, target.ResolvePass(source.format), views, source.extent);
recordCommands(context, [&](VkCommandBuffer commands, Recorder* recorder) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
begin.renderPass = target.ResolvePass();
begin.renderPass = target.ResolvePass(source.format);
begin.framebuffer = framebuffer->Handle();
begin.renderArea = {{0, 0}, source.extent};
context.Resolved(&DeviceFunctions::cmdBeginRenderPass, "vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
@@ -1107,6 +1251,20 @@ void NoteColorMetadataFill(std::uint64_t address, std::size_t bytes, std::uint32
}
}
std::shared_ptr<Texture> MultisampleTargetFmaskTexture_nid_no_patch(const Context& context, const GuestTextureResource& resource, VkComponentMapping components) {
std::lock_guard lock(targetsMutex());
discardRetiredTargets();
std::shared_ptr<MultisampleTarget> owner;
for (const auto& candidate : targets()) {
if (!candidate->active->load(std::memory_order_acquire) || candidate->context.device != context.device) continue;
const auto& target = candidate->target;
if (target.fmaskAddress != resource.baseAddress && (resource.fmaskCmaskAddress == 0u || target.cmaskAddress != resource.fmaskCmaskAddress)) continue;
Require(owner == nullptr, "FMASK descriptor refers to more than one resident target");
owner = candidate;
}
return owner != nullptr ? owner->FmaskSampled(resource, components) : nullptr;
}
void ClearMultisampleTargets(VkDevice device) {
std::lock_guard lock(targetsMutex());
std::erase_if(targets(), [&](const auto& target) { return target->context.device == device; });
@@ -112,6 +112,10 @@ void ValidateProvokingVertex(const Context& context, const State& state, std::sp
}
return;
}
for (const auto& shader : shaders) {
if (shader.stage != ShaderRecompiler::ShaderStage::Fragment || shader.program == nullptr) continue;
Require(std::none_of(shader.program->fragmentParameters.begin(), shader.program->fragmentParameters.end(), [](const ShaderRecompiler::FragmentParameter& parameter) { return parameter.flatP20; }), "v_interp_mov p20 of a flat input with the last provoking vertex is not measured");
}
if (BarycentricPatches(state, shaders)) {
for (const auto& shader : shaders) {
if (shader.stage != ShaderRecompiler::ShaderStage::Fragment || shader.program == nullptr) continue;
@@ -259,6 +263,8 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State&
appendKey(keys.fragmentOutput, state.perSampleShading);
appendKey(keys.fragmentShader, state.mergedCoverage);
appendKey(keys.fragmentOutput, state.mergedCoverage);
appendKey(keys.fragmentShader, state.truncatedCoverage);
appendKey(keys.fragmentOutput, state.truncatedCoverage);
const auto sampleLocationsEnabled = ValidateSampleLocations(context, state);
appendKey(keys.fragmentShader, sampleLocationsEnabled);
appendKey(keys.fragmentOutput, sampleLocationsEnabled);
@@ -341,11 +347,13 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput
Require(!state.negativeOneToOne || context.depthClipControl, "negative-one-to-one depth clipping requires VK_EXT_depth_clip_control with depthClipControl enabled");
Require(!state.perSampleShading || context.sampleRateShading, "per-sample pixel shading requires the sampleRateShading device feature");
Require(!state.mergedCoverage || (context.mergedCoverageSampleCounts & state.samples) != 0, "an overrasterized draw (a multisampled rasterizer into one-sample color targets) requires VK_NV_framebuffer_mixed_samples with merged coverage reduction");
Require(!(state.vertexPoints || (state.stages.mesh.has_value() && state.stages.mesh->outputPrimitiveSize == 1u)) || context.largePoints || (state.pointSize == 1.0f && ((state.paClVsOutCntl & (1u << 16u)) == 0 || (state.pointSizeMin == 1.0f && state.pointSizeMax == 1.0f))), "points of a size other than one pixel require the largePoints device feature");
Require(!state.truncatedCoverage || (context.truncatedCoverageSampleCounts & state.samples) != 0, "one-sample color targets beside a multisampled depth target require VK_AMD_mixed_attachment_samples or VK_NV_framebuffer_mixed_samples with truncated coverage reduction");
Require(state.conservativeRasterization == VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT || context.conservativeRasterization, "conservative rasterization requires VK_EXT_conservative_rasterization with at most 1/256 pixel of overestimation and degenerate triangles rasterized");
ValidateProvokingVertex(context, state, shaders);
if (state.rectList) Require(context.tessellationShader && context.limits.maxTessellationPatchSize >= 4, "rect-list requires tessellation with four output control points");
const bool barycentricPatches = BarycentricPatches(state, shaders);
if (barycentricPatches) Require(context.tessellationShader && state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST && !state.primitiveRestart, "emulated barycentrics through tessellation require a triangle list without primitive restart");
if (barycentricPatches) Require(context.tessellationShader && (state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP) && !state.primitiveRestart, "emulated barycentrics through tessellation require a triangle list or strip without primitive restart");
if (std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.stage == ShaderRecompiler::ShaderStage::Geometry; })) Require(context.geometryShader, "device does not support geometry shaders");
if (state.stages.tessellation) {
Require(context.tessellationShader, "device does not support tessellation shaders");
@@ -403,7 +411,7 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput
for (std::uint32_t index = 0; index < state.colors.size(); ++index) {
VkAttachmentDescription color{};
color.format = state.colors[index].format;
color.samples = state.mergedCoverage ? VK_SAMPLE_COUNT_1_BIT : static_cast<VkSampleCountFlagBits>(state.samples);
color.samples = state.mergedCoverage || state.truncatedCoverage ? VK_SAMPLE_COUNT_1_BIT : static_cast<VkSampleCountFlagBits>(state.samples);
color.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
color.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
color.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
@@ -440,7 +448,8 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput
VkAttachmentSampleCountInfoNV attachmentSamples{VK_STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV};
attachmentSamples.colorAttachmentCount = static_cast<std::uint32_t>(mergedColorSamples.size());
attachmentSamples.pColorAttachmentSamples = mergedColorSamples.empty() ? nullptr : mergedColorSamples.data();
if (state.mergedCoverage) rendering.pNext = &attachmentSamples;
if (state.truncatedCoverage) attachmentSamples.depthStencilAttachmentSamples = static_cast<VkSampleCountFlagBits>(state.samples);
if (state.mergedCoverage || state.truncatedCoverage) rendering.pNext = &attachmentSamples;
if (state.depth) {
rendering.depthAttachmentFormat = HostDepthFormat(context, state.depth->format);
if (HasStencil(state.depth->format)) rendering.stencilAttachmentFormat = rendering.depthAttachmentFormat;
@@ -514,8 +523,8 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput
sampleLocations.sampleLocationsInfo = {VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT, nullptr, samples.rasterizationSamples, grid, state.samples * grid.width * grid.height, locations.data()};
if (sampleLocationsEnabled) samples.pNext = &sampleLocations;
VkPipelineCoverageReductionStateCreateInfoNV coverageReduction{VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_REDUCTION_STATE_CREATE_INFO_NV};
coverageReduction.coverageReductionMode = VK_COVERAGE_REDUCTION_MODE_MERGE_NV;
if (state.mergedCoverage) {
coverageReduction.coverageReductionMode = state.truncatedCoverage ? VK_COVERAGE_REDUCTION_MODE_TRUNCATE_NV : VK_COVERAGE_REDUCTION_MODE_MERGE_NV;
if (state.mergedCoverage || (state.truncatedCoverage && !context.mixedAttachmentSamples)) {
coverageReduction.pNext = samples.pNext;
samples.pNext = &coverageReduction;
}
@@ -893,6 +902,7 @@ void pipelineKey(std::vector<std::byte>& key, const Context& context, const Stat
append(key, state.samples);
append(key, state.perSampleShading);
append(key, state.mergedCoverage);
append(key, state.truncatedCoverage);
append(key, state.customSampleLocations);
if (state.customSampleLocations) {
append(key, state.sampleLocationGrid);
@@ -35,7 +35,7 @@ static_assert(sizeof(VkStencilOpState) == 28, "VkStencilOpState changed: update
static_assert(sizeof(VkVertexInputBindingDescription) == 12, "VkVertexInputBindingDescription changed: update the recipe codec");
static_assert(sizeof(VkVertexInputAttributeDescription) == 16, "VkVertexInputAttributeDescription changed: update the recipe codec");
#if defined(__linux__) && defined(__x86_64__) && defined(__GLIBCXX__)
static_assert(sizeof(State) == 784, "State changed: update CanonicalPipelineState and the recipe codec");
static_assert(sizeof(State) == 824, "State changed: update CanonicalPipelineState and the recipe codec");
static_assert(sizeof(ShaderStages) == 112, "ShaderStages changed: update the recipe codec");
static_assert(sizeof(ShaderRecompiler::MeshConfiguration) == 40, "MeshConfiguration changed: update the recipe codec");
static_assert(sizeof(ShaderRecompiler::TessellationConfiguration) == 40, "TessellationConfiguration changed: update the recipe codec");
@@ -44,7 +44,7 @@ static_assert(sizeof(ShaderRecompiler::TessellationConfiguration) == 40, "Tessel
constexpr std::uint32_t FileMagic = 0x4c4a5041u;
// Bumped when the recipe codec, CanonicalPipelineState or the store key change in a way the
// layout guards above do not catch (a field renumbered or reinterpreted at the same size).
constexpr std::uint32_t FileFormat = 6u;
constexpr std::uint32_t FileFormat = 8u;
constexpr std::uint32_t ModuleRecord = 1u;
constexpr std::uint32_t GraphicsRecord = 2u;
constexpr std::uint32_t ComputeRecord = 3u;
@@ -217,8 +217,13 @@ void encodeState(Writer& writer, const State& state) {
writer.Bool(state.sampleLocationGrid);
writer.Bool(state.perSampleShading);
writer.Bool(state.mergedCoverage);
writer.Bool(state.truncatedCoverage);
for (const auto mask : state.quadSampleMask) writer.Raw(mask);
writer.U32(state.depthRemap.mode);
writer.Bool(state.vertexPoints);
writer.Raw(state.pointSize);
writer.Raw(state.pointSizeMin);
writer.Raw(state.pointSizeMax);
}
void decodeState(Reader& reader, State& state) {
@@ -278,8 +283,13 @@ void decodeState(Reader& reader, State& state) {
state.sampleLocationGrid = reader.Bool();
state.perSampleShading = reader.Bool();
state.mergedCoverage = reader.Bool();
state.truncatedCoverage = reader.Bool();
for (auto& mask : state.quadSampleMask) mask = reader.Raw<std::uint16_t>();
state.depthRemap.mode = reader.U32();
state.vertexPoints = reader.Bool();
state.pointSize = reader.Raw<float>();
state.pointSizeMin = reader.Raw<float>();
state.pointSizeMax = reader.Raw<float>();
}
void encodeRecipe(Writer& writer, const GraphicsPipelineRecipe& recipe) {
@@ -1051,8 +1061,13 @@ State CanonicalPipelineState(const State& state) {
canonical.sampleLocationGrid = state.sampleLocationGrid;
canonical.perSampleShading = state.perSampleShading;
canonical.mergedCoverage = state.mergedCoverage;
canonical.truncatedCoverage = state.truncatedCoverage;
canonical.quadSampleMask = state.quadSampleMask;
canonical.depthRemap.mode = state.depthRemap.mode;
canonical.vertexPoints = state.vertexPoints;
canonical.pointSize = state.pointSize;
canonical.pointSizeMin = state.pointSizeMin;
canonical.pointSizeMax = state.pointSizeMax;
return canonical;
}
@@ -255,10 +255,24 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip
}
if (partsOnly) return VK_NULL_HANDLE;
PerformanceTimer timing("Vulkan.GraphicsPipelineLink");
std::optional<std::pair<std::vector<VkSampleCountFlagBits>, VkSampleCountFlagBits>> sampleCounts;
for (auto* next = static_cast<const VkBaseInStructure*>(rendering.pNext); next != nullptr; next = next->pNext) {
if (next->sType != VK_STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV) continue;
const auto& counts = *reinterpret_cast<const VkAttachmentSampleCountInfoNV*>(next);
sampleCounts.emplace(std::vector<VkSampleCountFlagBits>(counts.pColorAttachmentSamples, counts.pColorAttachmentSamples + counts.colorAttachmentCount), counts.depthStencilAttachmentSamples);
}
const auto attachmentSamples = [](const std::pair<std::vector<VkSampleCountFlagBits>, VkSampleCountFlagBits>& counts) {
return VkAttachmentSampleCountInfoNV{VK_STRUCTURE_TYPE_ATTACHMENT_SAMPLE_COUNT_INFO_NV, nullptr, static_cast<std::uint32_t>(counts.first.size()), counts.first.empty() ? nullptr : counts.first.data(), counts.second};
};
auto linkedSamples = sampleCounts ? attachmentSamples(*sampleCounts) : VkAttachmentSampleCountInfoNV{};
VkPipelineLibraryCreateInfoKHR linked{VK_STRUCTURE_TYPE_PIPELINE_LIBRARY_CREATE_INFO_KHR};
linked.libraryCount = static_cast<std::uint32_t>(libraries.size());
linked.pLibraries = libraries.data();
VkGraphicsPipelineCreateInfo create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &linked};
if (sampleCounts) {
linkedSamples.pNext = create.pNext;
create.pNext = &linkedSamples;
}
create.layout = info.layout;
VkPipeline pipeline = VK_NULL_HANDLE;
lock.unlock();
@@ -277,12 +291,17 @@ VkPipeline LinkPipelineFromLibraries(const Context& context, const VkGraphicsPip
const auto cache = context.pipelineCache;
const auto cacheSynchronization = context.pipelineCacheSynchronization;
const auto libraryLayout = fullLayout;
std::function<void()> relink = [slot, createPipelines, cache, cacheSynchronization, libraryLayout, libraries, &store, devicePointer = &device] {
std::function<void()> relink = [slot, createPipelines, cache, cacheSynchronization, libraryLayout, libraries, sampleCounts, attachmentSamples, &store, devicePointer = &device] {
if (slot->released.load()) return;
auto linkedSamples = sampleCounts ? attachmentSamples(*sampleCounts) : VkAttachmentSampleCountInfoNV{};
VkPipelineLibraryCreateInfoKHR linked{VK_STRUCTURE_TYPE_PIPELINE_LIBRARY_CREATE_INFO_KHR};
linked.libraryCount = static_cast<std::uint32_t>(libraries.size());
linked.pLibraries = libraries.data();
VkGraphicsPipelineCreateInfo create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &linked};
if (sampleCounts) {
linkedSamples.pNext = create.pNext;
create.pNext = &linkedSamples;
}
create.flags = VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT;
create.layout = libraryLayout;
VkPipeline result = VK_NULL_HANDLE;
@@ -3451,6 +3451,7 @@ void Recorder::AfterCompletions(std::uint64_t address, std::span<const std::byte
} else {
++batch.completionLabelCount;
completionLabels.fetch_add(1, std::memory_order_acq_rel);
GuestMemory::BreakProofs();
}
// The table entry before the write note: the note bumps the generation a poller watches, and a
// poller that sees the bump then finds the label without the GPU mutex.
@@ -3467,6 +3468,7 @@ bool Recorder::AfterRecordedWork(std::function<void()> action) {
batch.completions.push_back(std::move(action));
++batch.completionLabelCount;
completionLabels.fetch_add(1, std::memory_order_acq_rel);
GuestMemory::BreakProofs();
if (&batch == open.get() && activeRecorder == this && pendingLabelSince.load(std::memory_order_relaxed) == NoPendingLabel) {
pendingLabelSince.store(std::chrono::steady_clock::now().time_since_epoch().count(), std::memory_order_release);
}
@@ -3494,6 +3496,7 @@ void Recorder::NoteWrittenBack(std::uint64_t address, std::size_t bytes) {
label.counted = true;
++batch.completionLabelCount;
completionLabels.fetch_add(1, std::memory_order_acq_rel);
GuestMemory::BreakProofs();
completionLabelsCountedLate.fetch_add(1, std::memory_order_relaxed);
recorder->markBehindCompletion(batch, label.begin, label.end);
}
@@ -93,6 +93,10 @@ bool storesThroughAddressesCached(const ShaderRecompiler::SharedSpirv& spirv) {
}
bool ShaderStoresThroughAddresses(const ShaderRecompiler::SharedSpirv& spirv) {
return storesThroughAddressesCached(spirv);
}
bool SpirvStoresThroughAddresses(std::span<const std::uint32_t> words) {
if (words.size() < 5 || words[0] != spv::MagicNumber) return true;
std::unordered_set<std::uint32_t> pointerTypes;
@@ -3,6 +3,7 @@
#include "prx/libSceAgc/Shader/include/ShaderConstants.hpp"
#include "prx/libSceAgcDriver/Graphics/include/State.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include <algorithm>
#include <array>
#include <cstddef>
@@ -244,6 +245,48 @@ ShaderRecompiler::ShaderVertexStageInfo DecodeVertexStageInfo(std::span<const st
read.size = static_cast<std::uint32_t>(bytes.size());
};
if (reads != nullptr) reads->reserve(reads->size() + 2u * shader.num_input_semantics);
std::array<std::uint32_t, ShaderRecompiler::ShaderVertexStageInfo::MaxResources> attribWords{};
std::array<std::array<std::uint32_t, 4>, ShaderRecompiler::ShaderVertexStageInfo::MaxResources> sharpWords{};
if (!staticAbi) {
std::uint32_t firstSemantic = ~0u, lastSemantic = 0;
for (std::uint32_t i = 0; i < shader.num_input_semantics; ++i) {
firstSemantic = std::min<std::uint32_t>(firstSemantic, semantics[i].semantic);
lastSemantic = std::max<std::uint32_t>(lastSemantic, semantics[i].semantic);
}
const auto readWords = [](std::uint64_t base, std::uint32_t stride, std::uint32_t first, std::uint32_t last, std::vector<std::uint32_t>& words, auto&& wanted) {
const auto wordsPer = stride / 4u;
words.assign(static_cast<std::size_t>(last - first + 1u) * wordsPer, 0u);
const auto begin = base + static_cast<std::uint64_t>(first) * stride;
if (AgcDriver::GuestMemory::Accessible(reinterpret_cast<const void*>(begin), words.size() * 4u)) {
AgcDriver::GuestMemory::Read(begin, std::as_writable_bytes(std::span(words)), 4);
return;
}
for (std::uint32_t entry = first; entry <= last; ++entry) {
if (!wanted(entry)) continue;
AgcDriver::GuestMemory::Read(base + static_cast<std::uint64_t>(entry) * stride, std::as_writable_bytes(std::span(words).subspan(static_cast<std::size_t>(entry - first) * wordsPer, wordsPer)), 4);
}
};
struct TableStorage {};
auto& table = HostThreadLocal<std::vector<std::uint32_t>, TableStorage>();
readWords(attribTableAddr, 4u, firstSemantic, lastSemantic, table, [&](std::uint32_t semantic) { return std::any_of(semantics.begin(), semantics.begin() + shader.num_input_semantics, [&](const ShaderSemantic& candidate) { return candidate.semantic == semantic; }); });
std::uint32_t firstIndex = ~0u, lastIndex = 0;
for (std::uint32_t i = 0; i < shader.num_input_semantics; ++i) {
attribWords[i] = table[semantics[i].semantic - firstSemantic];
const auto index = attribWords[i] & 0x1fu;
if (index >= ShaderRecompiler::ShaderVertexStageInfo::MaxResources) throw std::runtime_error("AGC graphics: vertex buffer index exceeds the supported domain");
firstIndex = std::min(firstIndex, index);
lastIndex = std::max(lastIndex, index);
}
if (shader.num_input_semantics != 0) {
struct SharpsStorage {};
auto& sharps = HostThreadLocal<std::vector<std::uint32_t>, SharpsStorage>();
readWords(bufferTableAddr, 16u, firstIndex, lastIndex, sharps, [&](std::uint32_t index) { return std::any_of(attribWords.begin(), attribWords.begin() + shader.num_input_semantics, [&](std::uint32_t word) { return (word & 0x1fu) == index; }); });
for (std::uint32_t i = 0; i < shader.num_input_semantics; ++i) {
const auto index = attribWords[i] & 0x1fu;
std::copy_n(sharps.begin() + static_cast<std::ptrdiff_t>((index - firstIndex) * 4u), 4, sharpWords[i].begin());
}
}
}
for (std::uint32_t i = 0; i < shader.num_input_semantics; ++i) {
const auto& semantic = semantics[i];
if (semantic.static_vb_index == 1 || semantic.static_attribute == 1) throw std::runtime_error("AGC graphics: statically bound vertex attributes are not implemented");
@@ -256,10 +299,9 @@ ShaderRecompiler::ShaderVertexStageInfo DecodeVertexStageInfo(std::span<const st
}
std::array<std::byte, 4> attribWordBytes{};
const auto attribWordAddress = attribTableAddr + static_cast<std::uint64_t>(semantic.semantic) * 4u;
AgcDriver::GuestMemory::Read(attribWordAddress, attribWordBytes, 4);
std::memcpy(attribWordBytes.data(), &attribWords[i], 4);
record(attribWordAddress, attribWordBytes);
std::uint32_t attribWord;
std::memcpy(&attribWord, attribWordBytes.data(), 4);
const std::uint32_t attribWord = attribWords[i];
const auto index = attribWord & 0x1fu;
const auto format = (attribWord >> 5u) & 0x1ffu;
const auto offset = (attribWord >> 14u) & 0xfffu;
@@ -267,7 +309,7 @@ ShaderRecompiler::ShaderVertexStageInfo DecodeVertexStageInfo(std::span<const st
if (index >= ShaderRecompiler::ShaderVertexStageInfo::MaxResources) throw std::runtime_error("AGC graphics: vertex buffer index exceeds the supported domain");
std::array<std::byte, 16> sharpBytes{};
const auto sharpAddress = bufferTableAddr + static_cast<std::uint64_t>(index) * 16u;
AgcDriver::GuestMemory::Read(sharpAddress, sharpBytes, 4);
std::memcpy(sharpBytes.data(), sharpWords[i].data(), 16);
record(sharpAddress, sharpBytes);
std::array<std::uint32_t, 4> sharp{};
std::memcpy(sharp.data(), sharpBytes.data(), 16);
@@ -4,6 +4,7 @@
#include "ThreadOwned.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/PlaceholderImages.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp"
@@ -682,6 +683,14 @@ std::shared_ptr<Texture> cachedTexture(const Context& context, std::span<const s
logLookup({target.get(), resource, 0, DccKeys::Uncompressed, 0, nullptr, true});
return target;
}
if (resource.fmaskCmaskAddress != 0u) {
Require(!depthCompare, "FMASK depth comparison sampling is not implemented");
Require(resource.baseArray == 0u && resource.depthOrLastArray == 0u, "native FMASK array sampling is not implemented");
CompletePendingCpuWrites(context, resource.fmaskCmaskAddress, CmaskBytes(resource.width, resource.height));
auto native = MultisampleTargetFmaskTexture_nid_no_patch(context, resource, components);
Require(native != nullptr, "compressed FMASK sampling without a matching resident native target is not implemented");
return native;
}
CaptureTrace::Log("sampled-lookup address=%llx width=%u height=%u dcc=%llx", static_cast<unsigned long long>(resource.baseAddress), resource.width, resource.height, static_cast<unsigned long long>(resource.dccAddress));
RequireNoMultisampleTarget(resource.baseAddress, guestBytes != 0 ? static_cast<std::size_t>(guestBytes) : 1u, "a texture read");
if (auto* recorder = Recorder::Active(); recorder != nullptr) recorder->BoundKeptBytes();
@@ -3272,7 +3281,54 @@ const ShaderRecompiler::DescriptorBinding* ShaderResources::tableImages(std::spa
return nullptr;
}
bool ShaderResources::EpochProofs() {
return DrawPipelineEnabled();
}
namespace {
void noteEpochProof(bool reused, bool verified, bool failed) {
static std::atomic<std::uint64_t> reuses{0}, proofs{0}, checks{0}, failures{0};
if (verified) checks.fetch_add(1, std::memory_order_relaxed);
if (failed) failures.fetch_add(1, std::memory_order_relaxed);
const auto count = (reused ? reuses : proofs).fetch_add(1, std::memory_order_relaxed) + 1u;
static const bool report = std::getenv("APS5_PROFILE_DRAW") != nullptr || std::getenv("APS5_VERIFY_DRAW_PIPELINE") != nullptr;
if (!report) return;
if (count % 262144u == 0u || (count & (count - 1u)) == 0u) std::fprintf(stderr, "[epoch-proofs] resource proofs: %llu reused the epoch's, %llu proved; verify: %llu checked, %llu failed; storage refreshes reused %llu\n", static_cast<unsigned long long>(reuses.load()), static_cast<unsigned long long>(proofs.load()), static_cast<unsigned long long>(checks.load()), static_cast<unsigned long long>(failures.load()), static_cast<unsigned long long>(StorageTexture::epochRefreshes.load()));
}
}
bool ShaderResources::Revalidate(std::span<const CompiledShader> shaders, ProofReport* report) {
if (EpochProofs()) {
const auto epoch = GuestMemory::CollectEpoch();
const auto proof = GuestMemory::ProofSerial();
const auto pending = StorageTexture::PendingSerial();
if (epoch != 0 && provedEpoch == epoch && provedProof == proof && provedPending == pending) {
static const bool verify = std::getenv("APS5_VERIFY_DRAW_PIPELINE") != nullptr;
thread_local std::uint64_t reuses = 0;
if (verify && ++reuses % 64u == 0u) {
const bool ok = revalidateFull(shaders, report);
noteEpochProof(true, true, !ok);
return ok;
}
if (report != nullptr) *report = {ProofPath::Full, ProofFailure::None};
noteEpochProof(true, false, false);
return true;
}
const bool ok = revalidateFull(shaders, report);
noteEpochProof(false, false, false);
if (ok) {
provedEpoch = epoch;
provedProof = proof;
provedPending = pending;
} else {
provedEpoch = 0;
}
return ok;
}
return revalidateFull(shaders, report);
}
bool ShaderResources::revalidateFull(std::span<const CompiledShader> shaders, ProofReport* report) {
if (report != nullptr) *report = {ProofPath::Full, ProofFailure::Other};
if (!reusable || shaders.empty()) return false;
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
@@ -5586,6 +5642,7 @@ void ShaderResources::WriteBack() {
} catch (const BdaUnalignedAccess&) {
unaligned = std::current_exception();
}
if (!guestMemory.Writes().empty() || std::find(storageWritten.begin(), storageWritten.end(), true) != storageWritten.end() || (usesBda && !bdaReadOnly)) GuestMemory::BreakProofs();
if (!SkipWriteBack()) {
for (std::size_t index = 0; index < storageTextures.size(); ++index) {
if (!storageWritten[index] || storageTextures[index] == nullptr) continue;
@@ -53,6 +53,8 @@ struct Module {
bool layerOutput = false;
bool meshCapability = false;
std::uint32_t primitiveInputs = 0;
bool pointSizeOutput = false;
bool pointSize = false;
std::map<std::uint32_t, std::vector<std::uint32_t>> modes;
const std::vector<std::uint32_t>& Type(std::uint32_t id) const {
@@ -138,6 +140,10 @@ struct Module {
Require(input && (clipInput || (value == spv::BuiltInPosition && signature == "f32x4") || (value == spv::BuiltInTessCoord && stage == Stage::TessellationEvaluation && signature == "f32x3") || ((value == spv::BuiltInInvocationId || value == spv::BuiltInPrimitiveId || value == spv::BuiltInPatchVertices) && (signature == "i32" || signature == "u32"))), "unsupported tessellation built-in");
return;
}
if (!input && value == spv::BuiltInPointSize && pointSizeOutput && signature == "f32" && !pointSize) {
pointSize = true;
return;
}
if (!input && value == spv::BuiltInPrimitivePointIndicesEXT) primitiveIndices = 1u;
if (!input && value == spv::BuiltInPrimitiveLineIndicesEXT) primitiveIndices = 2u;
if (!input && value == spv::BuiltInPrimitiveTriangleIndicesEXT) primitiveIndices = 3u;
@@ -149,6 +155,10 @@ struct Module {
Require((value == spv::BuiltInVertexIndex || value == spv::BuiltInInstanceIndex || value == spv::BuiltInBaseInstance) && signature == "i32", "unsupported vertex built-in input");
} else if (vertex && storage == spv::StorageClassOutput) {
if (value == spv::BuiltInLayer && layerOutput && (signature == "u32" || signature == "i32")) return;
if (value == spv::BuiltInPointSize && pointSizeOutput && signature == "f32" && !pointSize) {
pointSize = true;
return;
}
Require(value == spv::BuiltInPosition && signature == "f32x4" && !position, "unsupported or duplicate vertex built-in output");
position = true;
} else {
@@ -186,6 +196,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi
Require(words[4] == 0, "unsupported SPIR-V schema: " + std::to_string(words[4]));
Module module;
module.pointSizeOutput = (state.vertexPoints && stage == Stage::Vertex) || (mesh && state.stages.mesh.has_value() && state.stages.mesh->outputPrimitiveSize == 1u);
std::uint32_t entries = 0;
std::uint32_t memoryModels = 0;
std::uint32_t entryPoint = 0;
@@ -659,7 +670,7 @@ std::set<std::uint32_t> ValidateShaders(std::span<const CompiledShader> shaders,
const bool geometry = state.stages.path == ShaderPath::Vertex && !state.rectList && shaders.size() == 3u;
const bool patches = BarycentricPatches(state, shaders) && shaders.back().program != nullptr && shaders.back().program->barycentricEmulation.active;
Require(geometry || shaders.size() == (tessellation || state.rectList || patches ? 4u : 2u), "incorrect graphics stage count");
if (patches) Require(state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, "emulated barycentrics through tessellation require a triangle list");
if (patches) Require(state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, "emulated barycentrics through tessellation require a triangle list or strip");
if (geometry) {
Require(shaders.back().program != nullptr && shaders.back().program->barycentricEmulation.active, "a geometry stage is generated only for emulated barycentrics");
Require(state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, "emulated barycentrics require triangle primitives");
@@ -190,6 +190,37 @@ std::uint32_t inactiveVertexPointSize(const QueueState& queue) {
}
}
bool pointOutput(const QueueState& queue) {
const auto stages = find(queue.context, 0x2d5);
const auto primitive = find(queue.userConfig, 0x242, RegisterBank::UserConfig);
if (stages == queue.context.end()) return false;
if ((stages->second & 0x24u) == 0) return primitive != queue.userConfig.end() && primitive->second == 1u;
const auto output = find(queue.context, 0x29b);
return (stages->second & 0x24u) == 0x20u && output != queue.context.end() && output->second == 0u;
}
void decodePointSize(const QueueState& queue, State& result) {
const auto& cx = queue.context;
const auto size = read(cx, 0x280);
const auto limits = read(cx, 0x281);
const bool fromVertex = (result.paClVsOutCntl & (1u << 16u)) != 0;
Require(!fromVertex || (result.paClVsOutCntl & (1u << 21u)) != 0, "USE_VTX_POINT_SIZE without VS_OUT_MISC_VEC_ENA is unsupported");
Require(fromVertex || (size & 0xffffu) == size >> 16u, "points whose PA_SU_POINT_SIZE width and height differ are unsupported");
Require(fromVertex || (size & 0xffffu) != 0, "points of size 0 (PA_SU_POINT_SIZE 0) are unsupported");
Require((limits & 0xffffu) <= limits >> 16u, "PA_SU_POINT_MINMAX with a minimum above its maximum is unsupported");
Require(!fromVertex || (limits >> 16u) != 0, "a vertex point size clamped to 0 (PA_SU_POINT_MINMAX maximum 0) is unsupported");
result.pointSize = static_cast<float>(size & 0xffffu) / 8.0f;
result.pointSizeMin = static_cast<float>(limits & 0xffffu) / 8.0f;
result.pointSizeMax = static_cast<float>(limits >> 16u) / 8.0f;
const auto interpolation = find(cx, 0x1b5);
const auto inputs = find(cx, 0x1b6);
if (interpolation == cx.end() || (interpolation->second & 2u) == 0 || inputs == cx.end()) return;
for (std::uint32_t input = 0; input < (inputs->second & 0x3fu); ++input) {
const auto control = find(cx, 0x191 + input);
Require(control == cx.end() || (control->second & 0x820000u) == 0, "point sprite texture coordinates (SPI_PS_INPUT_CNTL PT_SPRITE_TEX) are not implemented");
}
}
constexpr std::uint32_t DepthControlMask = ~0x007007f0u;
// EXEC_ON_HIER_FAIL / EXEC_ON_NOOP / EXEC_IF_OVERLAPPED (bits 9, 10, 17) only force the pixel shader
// to run, which it always does here.
@@ -355,13 +386,14 @@ void decodeDepth(const Registers& cx, std::uint32_t depthControl, bool testValEx
const bool opValReference = opValExport && StencilOperationValueReplaces(cx);
zero(cx, 0x000, 0x0000101cu, "depth copy, resummarize or decompress draws (DB_RENDER_CONTROL)");
const bool depthClear = (read(cx, 0x000) & 1u) != 0;
const bool stencilClear = (read(cx, 0x000) & 2u) != 0;
const auto view = read(cx, 0x002);
zero(cx, 0x002, 0x3c000000u, "depth mips (DB_DEPTH_VIEW MIP_LEVEL)");
zero(cx, 0x010, 0x000f1000u, "partially resident or mipmapped depth (DB_Z_INFO)");
zero(cx, 0x010, 0x00001000u, "partially resident depth (DB_Z_INFO)");
const auto viewMip = (view >> 26u) & 0xfu;
const auto maxMip = (read(cx, 0x010) >> 16u) & 0xfu;
zero(cx, 0x011, 0x00001000u, "partially resident stencil (DB_STENCIL_INFO)");
const auto zFormat = read(cx, 0x010) & 3u;
const bool stencil = (read(cx, 0x011) & 1u) != 0;
const bool stencilClear = stencil && (read(cx, 0x000) & 2u) != 0;
Require(zFormat != 2, "Z_24 depth is unsupported");
if (zFormat == 0) depthControl &= ~6u;
if (!stencil) depthControl &= ~1u;
@@ -371,7 +403,7 @@ void decodeDepth(const Registers& cx, std::uint32_t depthControl, bool testValEx
};
const bool depthReadOnly = (view & 0x01000000u) != 0;
const bool stencilReadOnly = (view & 0x02000000u) != 0;
Require(!stencilClear || (stencil && !stencilReadOnly), "stencil clear requires a writable stencil plane");
Require(!stencilClear || !stencilReadOnly, "stencil clear requires a writable stencil plane");
Require(!stencilClear || !testValExport, "stencil clear with a pixel shader that exports the stencil test value is unsupported");
Require(!depthClear || (zFormat != 0 && !depthReadOnly), "depth clear requires a writable depth plane");
DepthTarget depth{};
@@ -396,7 +428,27 @@ void decodeDepth(const Registers& cx, std::uint32_t depthControl, bool testValEx
}
const auto size = read(cx, 0x007);
depth.extent = {(size & 0x3fffu) + 1u, ((size >> 16u) & 0x3fffu) + 1u};
if (const auto slice = view & 0x1fffu; slice != 0) {
if (maxMip == 0 && viewMip != 0) Require(false, "depth view mip " + std::to_string(viewMip) + " on a surface without mips");
if (maxMip != 0) {
char message[320];
std::snprintf(message, sizeof(message), "depth view mip %u of %u at %ux%u (DB_Z_INFO 0x%08x, DB_DEPTH_VIEW 0x%08x)", viewMip, maxMip + 1u, depth.extent.width, depth.extent.height, read(cx, 0x010), view);
const std::string where(message);
Require(viewMip <= maxMip, "the " + where + " is beyond the surface's mips");
Require(depth.samples == 1u, "multisampled " + where + " is unsupported");
Require(depth.depthSwizzle == XorSwizzleMode(TextureTileMode::kZ64KBX), "the " + where + " uses a swizzle other than 64 KiB Z_X");
const auto depthMips = ComputeElementMipLayout(TextureTileMode::kZ64KBX, zFormat == 1 ? 2u : 4u, depth.extent.width, depth.extent.height, maxMip + 1u);
const auto stencilMips = ComputeElementMipLayout(TextureTileMode::kZ64KBX, 1u, depth.extent.width, depth.extent.height, maxMip + 1u);
Require(zFormat == 0 || !depthMips.at(viewMip).tail, "rendering the " + where + " into the packed mip tail is unsupported");
Require(!stencil || !stencilMips.at(viewMip).tail, "rendering the stencil of the " + where + " into the packed mip tail is unsupported");
Require((read(cx, 0x010) & (1u << 29u)) == 0, "HTILE for the " + where + " is unsupported");
if (const auto slice = view & 0x1fffu; slice != 0) {
if (depth.address != 0) depth.address += static_cast<std::uint64_t>(slice) * ComputeSurfaceSize(depthMips, 1u);
if (depth.stencilAddress != 0) depth.stencilAddress += static_cast<std::uint64_t>(slice) * ComputeSurfaceSize(stencilMips, 1u);
}
if (depth.address != 0) depth.address += depthMips.at(viewMip).tiledOffset;
if (depth.stencilAddress != 0) depth.stencilAddress += stencilMips.at(viewMip).tiledOffset;
depth.extent = {depthMips.at(viewMip).width, depthMips.at(viewMip).height};
} else if (const auto slice = view & 0x1fffu; slice != 0) {
if (depth.address != 0) depth.address += static_cast<std::uint64_t>(slice) * DepthSliceBytes(depth.extent, zFormat == 1 ? 2u : 4u);
if (depth.stencilAddress != 0) depth.stencilAddress += static_cast<std::uint64_t>(slice) * DepthSliceBytes(depth.extent, 1u);
}
@@ -908,8 +960,8 @@ DecodedColorFormat DecodeColorFormat(std::uint32_t format, std::uint32_t number,
if (number == unorm) return {VK_FORMAT_R32_UINT, 4, 0xe4u, ShaderRecompiler::ColorExportPacking::Unorm10_11_11};
return {VK_FORMAT_B10G11R11_UFLOAT_PACK32, 4};
case 7:
if (swap != 2 || number != floating) return fail();
return {VK_FORMAT_R32_UINT, 4, 0xc6u, ShaderRecompiler::ColorExportPacking::Float11_11_10};
if ((swap != 0 && swap != 2) || number != floating) return fail();
return {VK_FORMAT_R32_UINT, 4, static_cast<std::uint8_t>(swap == 2 ? 0xc6u : 0xe4u), ShaderRecompiler::ColorExportPacking::Float11_11_10};
case 9:
// COLOR_2_10_10_10 keeps red in the low bits, the Vulkan A2B10G10R10 packing.
if (number != unorm) return fail();
@@ -1061,6 +1113,15 @@ std::array<std::uint8_t, 32> PixelSampleLocations(const State& state, const Shad
return locations;
}
void ApplyPointSize(const State& state, ShaderRecompiler::ShaderVertexStageInfo& vertex) {
if (!state.vertexPoints && !(state.stages.mesh.has_value() && state.stages.mesh->outputPrimitiveSize == 1u)) return;
vertex.paClVsOutCntl |= state.paClVsOutCntl & (1u << 16u);
vertex.pointList = true;
vertex.pointSize = state.pointSize;
vertex.pointSizeMin = state.pointSizeMin;
vertex.pointSizeMax = state.pointSizeMax;
}
ShaderStages DecodeShaderStages(const QueueState& queue, bool vertexWorkgroup) {
const auto value = read(queue.context, 0x2d5);
const auto validate = [&](bool condition, const char* reason) {
@@ -1235,7 +1296,11 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) {
const auto primitive = read(queue.userConfig, 0x242, RegisterBank::UserConfig);
APS5_LOG_OUT_DEBUG("DecodeState primitive=%u path=%u vertexWave=%u", primitive, static_cast<unsigned>(result.stages.path), result.stages.vertexWaveSize);
switch (primitive) {
case 1: Require(result.stages.mesh.has_value(), "point-list vertex rendering requires point-size output support"); result.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break;
case 1:
Require(result.stages.mesh.has_value() || result.stages.path == ShaderPath::Vertex, "point lists are only drawn through the vertex and geometry paths");
result.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
result.vertexPoints = result.stages.path == ShaderPath::Vertex;
break;
case 2: result.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break;
case 3: result.topology = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; break;
case 7:
@@ -1260,9 +1325,10 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) {
}
APS5_LOG_OUT_DEBUG("Topology=%u", static_cast<unsigned>(result.topology));
result.primitiveRestart = read(queue.userConfig, 0x24b, RegisterBank::UserConfig) != 0 && !result.rectList && !result.quadList && result.topology != VK_PRIMITIVE_TOPOLOGY_PATCH_LIST;
zero(cx, 0x207, ~(LayerExports | ClipCullExports | inactiveVertexPointSize(queue)), "layer, viewport or auxiliary vertex exports");
zero(cx, 0x207, ~(LayerExports | ClipCullExports | ((result.vertexPoints || (result.stages.mesh.has_value() && result.stages.mesh->outputPrimitiveSize == 1u)) ? 1u << 16u : inactiveVertexPointSize(queue))), "layer, viewport or auxiliary vertex exports");
Require(std::popcount(read(cx, 0x207) & 0xffffu) <= 8, "more than eight clip and cull distances are unsupported");
result.paClVsOutCntl = read(cx, 0x207);
if (result.vertexPoints || (result.stages.mesh.has_value() && result.stages.mesh->outputPrimitiveSize == 1u)) decodePointSize(queue, result);
result.samples = decodeSamples(cx);
Require(coveredCentroidSupported(queue), "COVERED_CENTROID_IS_CENTER with active or unspecified centroid inputs is not implemented");
decodeSampleLocations(cx, result);
@@ -1313,8 +1379,7 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) {
result.sampleLocationGrid = false;
}
if (result.samples > 1 && (read(cx, 0x292) & 1u) == 0) {
const bool filled = result.topology != VK_PRIMITIVE_TOPOLOGY_POINT_LIST && result.topology != VK_PRIMITIVE_TOPOLOGY_LINE_LIST && result.topology != VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
Require(filled && !result.alphaToCoverage, "multisampled targets rasterized without MSAA_ENABLE are unsupported for points, lines or alpha-to-coverage");
Require(RasterPrimitiveOf(result) != ShaderRecompiler::RasterPrimitive::Point && !result.alphaToCoverage, "multisampled targets rasterized without MSAA_ENABLE are unsupported for points or alpha-to-coverage");
if (const auto eqaa = find(cx, 0x201); result.depth && eqaa != cx.end() && (eqaa->second & 0x0f0c0000u) != 0) throw std::runtime_error(zeroMessage(0x201, eqaa->second, "a multisampled depth target rasterized without MSAA_ENABLE with Z interpolation or overrasterization (DB_EQAA)"));
if (const auto control = find(cx, 0x203); result.depth && control != cx.end() && (control->second & 0x100u) != 0) throw std::runtime_error(zeroMessage(0x203, control->second, "a multisampled depth target rasterized without MSAA_ENABLE with a sample-mask export"));
result.customSampleLocations = true;
@@ -1415,8 +1480,10 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) {
}
const bool merged = color.samples == 1u && !result.depth && !result.perSampleShading && (result.colors.empty() || result.mergedCoverage) && overrasterized(cx, result.samples);
if (!merged && color.samples == 1 && result.colors.empty() && !result.depth && rasterizesSampleZeroOnly(cx, result)) rasterizeSampleZero(result);
Require((color.samples == result.samples && !result.mergedCoverage) || merged, "a color target's sample count differs from the rasterizer's");
const bool truncated = color.samples == 1u && result.samples > 1u && result.depth && result.depth->samples == result.samples && (result.colors.empty() || result.truncatedCoverage) && !overrasterized(cx, result.samples);
Require((color.samples == result.samples && !result.mergedCoverage && !result.truncatedCoverage) || merged || truncated, "a color target's sample count differs from the rasterizer's");
result.mergedCoverage = merged;
result.truncatedCoverage = truncated;
APS5_LOG_OUT_DEBUG("Color %u address=0x%llx extent=%ux%u bytes=%llu VkFormat=%u", slot, static_cast<unsigned long long>(color.address), color.extent.width, color.extent.height, static_cast<unsigned long long>(color.bytes), static_cast<unsigned>(color.format));
if (result.colors.empty()) {
result.renderExtent = color.extent;
@@ -1856,6 +1923,14 @@ ColorTarget DecodeColorBuffer(const Registers& cx, std::uint32_t slot, bool allo
if (color.samples == 1) GuestMemory::CheckRange(reinterpret_cast<const void*>(cmask), totalCmaskBytes, CmaskLayout::Alignment, true);
}
color.cmaskFastClear = (info & 0x2000u) != 0;
if (const auto fmask = find(cx, 0x321 + stride); color.samples > 1u && fmask != cx.end()) {
const auto high = find(cx, 0x3a0 + slot);
const auto fmaskHigh = high == cx.end() ? 0u : high->second;
Require((fmaskHigh & ~0xffu) == 0u, "invalid FMASK address extension");
const auto address = (static_cast<std::uint64_t>(fmaskHigh) << 40u) | (static_cast<std::uint64_t>(fmask->second) << 8u);
color.fmaskPipeBankXor = static_cast<std::uint32_t>(address & 0xffffu);
color.fmaskAddress = address - color.fmaskPipeBankXor;
}
}
if ((info & 0x10000000u) != 0) {
if (maxMip == 0) {
@@ -2023,15 +2098,16 @@ std::string DrawRejection(const QueueState& queue, bool indexed) {
if (value(queue.userConfig, 0x242, primitive) && (primitive & 0x3fu) != 1 && (primitive & 0x3fu) != 2 && (primitive & 0x3fu) != 3 && (primitive & 0x3fu) != 4 && (primitive & 0x3fu) != 5 && (primitive & 0x3fu) != 6 && (primitive & 0x3fu) != 21) return "AGC graphics: primitive restart is only supported for point, line and triangle topologies";
if (value(cx, 0x103, resetIndex) && (resetIndex & 0xffffu) != 0xffffu) return "AGC graphics: primitive restart index other than all ones is unsupported";
}
if (auto reason = nonzero(cx, 0x207, ~(LayerExports | ClipCullExports | inactiveVertexPointSize(queue)), "layer, viewport or auxiliary vertex exports"); !reason.empty()) return reason;
if (auto reason = nonzero(cx, 0x207, ~(LayerExports | ClipCullExports | (pointOutput(queue) ? 1u << 16u : inactiveVertexPointSize(queue))), "layer, viewport or auxiliary vertex exports"); !reason.empty()) return reason;
if (value(cx, 0x207, word) && std::popcount(word & 0xffffu) > 8) return require(false, "more than eight clip and cull distances are unsupported");
if (value(cx, 0x200, word)) {
const auto renderControl = find(cx, 0x000);
const bool depthClear = renderControl != cx.end() && (renderControl->second & 1u) != 0;
const bool stencilClear = renderControl != cx.end() && (renderControl->second & 2u) != 0;
std::uint32_t stencilInfo = 0;
const bool stencilClear = renderControl != cx.end() && (renderControl->second & 2u) != 0 && !(value(cx, 0x011, stencilInfo) && (stencilInfo & 1u) == 0);
if (stencilClear && !depthPlanesAbsent(cx)) {
std::uint32_t stencil = 0, view = 0;
if ((value(cx, 0x011, stencil) && (stencil & 1u) == 0) || (value(cx, 0x002, view) && (view & 0x02000000u) != 0)) return require(false, "stencil clear requires a writable stencil plane");
std::uint32_t view = 0;
if (value(cx, 0x002, view) && (view & 0x02000000u) != 0) return require(false, "stencil clear requires a writable stencil plane");
}
if (depthClear && !depthPlanesAbsent(cx)) {
std::uint32_t z = 0, view = 0;
@@ -9,6 +9,7 @@
#include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp"
// For the declaration of PendingStorageOverlaps, defined below.
#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp"
@@ -2057,10 +2058,25 @@ bool StorageTexture::refresh(std::uint32_t firstLayer, std::uint32_t lastLayer)
const bool profile = LookupOutcomes::Profiled();
auto start = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
const bool scoped = firstLayer != 0 || lastLayer != trackedLayers;
const bool epochProofs = ShaderResources::EpochProofs();
const auto epoch = epochProofs ? GuestMemory::CollectEpoch() : 0;
if (epoch != 0 && provedEpoch.load(std::memory_order_relaxed) == epoch && provedProof.load(std::memory_order_relaxed) == GuestMemory::ProofSerial() && provedPending.load(std::memory_order_relaxed) == PendingSerial()) {
NoteProved();
refreshesProved.fetch_add(1, std::memory_order_relaxed);
epochRefreshes.fetch_add(1, std::memory_order_relaxed);
return true;
}
const auto proofBefore = GuestMemory::ProofSerial();
const auto pendingBefore = PendingSerial();
CompletePendingCpuWrites(context, descriptor.baseAddress, static_cast<std::size_t>(guestBytes));
if (descriptor.dccAddress != 0) CompletePendingCpuWrites(context, descriptor.dccAddress, DccKeyBytes(guestBytes));
if (refreshProved()) {
layerBehind.clear();
if (epoch != 0) {
provedEpoch.store(epoch, std::memory_order_relaxed);
provedProof.store(proofBefore, std::memory_order_relaxed);
provedPending.store(pendingBefore, std::memory_order_relaxed);
}
NoteProved();
refreshesProved.fetch_add(1, std::memory_order_relaxed);
if (profile) LookupOutcomes::Add(LookupOutcomes::RefreshProved, start);
@@ -3730,11 +3746,19 @@ void StorageTexture::markLayersPending(std::uint32_t first, std::uint32_t count)
CaptureTrace::Log("image-write image=%llx first=%u count=%u generation=%llu", static_cast<unsigned long long>(descriptor.baseAddress), first, count, static_cast<unsigned long long>(generation));
++writes;
static const bool eager = std::getenv("APS5_EAGER_WRITEBACK") != nullptr || std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr;
std::vector<bool> unsaved(trackedLayers, false);
std::vector<bool> unsaved;
bool anyUnsaved = false;
for (std::uint32_t layer = first; layer < first + count; ++layer) {
unsaved[layer] = !layerPending[layer] && !layerOriginal[layer] && layerGeneration[layer] == 0;
anyUnsaved = anyUnsaved || unsaved[layer];
const bool trims = CommitTrims();
if (trims) {
for (std::uint32_t layer = first; layer < first + count && !anyUnsaved; ++layer) anyUnsaved = !layerPending[layer] && !layerOriginal[layer] && layerGeneration[layer] == 0;
}
if (!trims || anyUnsaved) {
unsaved.assign(trackedLayers, false);
anyUnsaved = false;
for (std::uint32_t layer = first; layer < first + count; ++layer) {
unsaved[layer] = !layerPending[layer] && !layerOriginal[layer] && layerGeneration[layer] == 0;
anyUnsaved = anyUnsaved || unsaved[layer];
}
}
if (anyUnsaved && !GuestMemory::Watched(descriptor.baseAddress, static_cast<std::size_t>(guestBytes))) captureGuestBytes(&unsaved);
for (std::uint32_t layer = first; layer < first + count; ++layer) layerPending[layer] = true;
@@ -4252,8 +4276,10 @@ bool StorageTexture::AnyPendingOverlaps(std::span<const std::pair<std::uint64_t,
}
return false;
};
for (const auto* texture : pending.textures) {
if (overlapsAny(texture)) return true;
if (std::any_of(ranges.begin(), ranges.end(), [&](const auto& range) { return range.second > range.first && pending.textures.MayOverlap(range.first, static_cast<std::size_t>(range.second - range.first)); })) {
for (const auto* texture : pending.textures) {
if (overlapsAny(texture)) return true;
}
}
for (const auto* texture : pending.flushing) {
if (overlapsAny(texture)) return true;
@@ -492,11 +492,11 @@ std::size_t PublishShadow(std::uint64_t address, std::size_t bytes, PublishScope
return units;
}
bool AnyShadowedOverlaps(std::uint64_t address, std::size_t bytes) {
if (!UnitShadowEnabled() || bytes == 0) return false;
namespace {
bool anyShadowedLocked(const Shadows& registry, std::uint64_t address, std::size_t bytes) {
if (bytes == 0) return false;
const auto end = bytes > std::numeric_limits<std::uint64_t>::max() - address ? std::numeric_limits<std::uint64_t>::max() : address + bytes;
auto& registry = Registry();
std::lock_guard lock(registry.mutex);
return anyOverlapping(registry, address, end, [&](const std::shared_ptr<UnitShadow>& shadow) {
if (shadow->liveUnits == 0) return false;
const auto begin = std::max(address, shadow->importBase);
@@ -508,10 +508,21 @@ bool AnyShadowedOverlaps(std::uint64_t address, std::size_t bytes) {
});
}
}
bool AnyShadowedOverlaps(std::uint64_t address, std::size_t bytes) {
if (!UnitShadowEnabled() || bytes == 0) return false;
auto& registry = Registry();
std::lock_guard lock(registry.mutex);
return anyShadowedLocked(registry, address, bytes);
}
bool AnyShadowedOverlaps(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges) {
if (!UnitShadowEnabled()) return false;
if (!UnitShadowEnabled() || ranges.empty()) return false;
auto& registry = Registry();
std::lock_guard lock(registry.mutex);
for (const auto& [begin, end] : ranges) {
if (end > begin && AnyShadowedOverlaps(begin, static_cast<std::size_t>(end - begin))) return true;
if (end > begin && anyShadowedLocked(registry, begin, static_cast<std::size_t>(end - begin))) return true;
}
return false;
}
@@ -5,6 +5,12 @@
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
namespace {
constexpr int CAPTURE_UNAVAILABLE = static_cast<int>(0x8A6C1000);
}
extern "C" {
bool APS5_VABI sceAgcDriverIsCaptureInProgress(void) {
@@ -21,18 +27,15 @@ bool APS5_VABI sceAgcDriverIsSubmitValidationEnabled(void) {
int APS5_VABI sceAgcDriverRequestCaptureStart(const char* path) {
(void)path;
NotImplemented_nid_no_patch(__func__);
return 0;
return CAPTURE_UNAVAILABLE;
}
int APS5_VABI sceAgcDriverRequestCaptureStop() {
NotImplemented_nid_no_patch(__func__);
return 0;
return CAPTURE_UNAVAILABLE;
}
int APS5_VABI sceAgcDriverTriggerCapture() {
NotImplemented_nid_no_patch(__func__);
return 0;
return CAPTURE_UNAVAILABLE;
}
}
+14 -10
View File
@@ -57,6 +57,17 @@ int APS5_VABI sceAgcDriverGetHsOffchipParam(uint16_t* first, uint16_t* second) {
return 0;
}
int APS5_VABI sceAgcDriverNopDataWritePacket(void* destination, uint32_t address, const void* data, uint32_t bytes) {
const auto alignedBytes = (static_cast<std::uint64_t>(bytes) + 3) & ~std::uint64_t{3};
const auto totalBytes = alignedBytes + 8;
std::memset(destination, 0, static_cast<std::size_t>(totalBytes));
const auto header = (static_cast<std::uint32_t>(totalBytes) << 14) + 0x3ffe0000U | 0xc0001000U;
std::memcpy(destination, &header, sizeof(header));
std::memcpy(static_cast<std::byte*>(destination) + 4, &address, sizeof(address));
if (data != nullptr && bytes != 0) std::memcpy(static_cast<std::byte*>(destination) + 8, data, bytes);
return data == nullptr || bytes == 0 ? 2 : static_cast<int>(totalBytes / 4);
}
int APS5_VABI sceAgcDriverSetValidationDisabled() {
return DEBUG_UNAVAILABLE;
@@ -154,9 +165,8 @@ int APS5_VABI sceAgcDriverAcquireHDRScopesACQ() {
return 0;
}
int APS5_VABI sceAgcDriverGetCoredumpAddress() {
NotImplemented_nid_no_patch(__func__);
return 0;
void* APS5_VABI sceAgcDriverGetCoredumpAddress() {
return nullptr;
}
int APS5_VABI sceAgcDriverHp3dLockEnd() {
@@ -174,19 +184,13 @@ int APS5_VABI sceAgcDriverIsEsvmProcess() {
return 0;
}
int APS5_VABI sceAgcDriverNopDataWritePacket() {
NotImplemented_nid_no_patch(__func__);
return 0;
}
int APS5_VABI sceAgcDriverReleaseHDRScopesACQ() {
NotImplemented_nid_no_patch(__func__);
return 0;
}
int APS5_VABI sceAgcDriverSetTargetRingForDiag() {
NotImplemented_nid_no_patch(__func__);
return 0;
return DRIVER_FEATURE_UNAVAILABLE;
}
int APS5_VABI sceAgcDriverSetValueToSharedGds() {
@@ -2813,7 +2813,7 @@ bool RunSparseBufferHoleTests(const Context& context, const BdaTestAccess& acces
std::memset(reservation.data + 2 * unit, 0x72, unit);
VkBuffer seeded = VK_NULL_HANDLE;
{
Buffer seed(context, copied, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
Buffer seed(context, copied, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
std::fill(seed.Bytes().begin(), seed.Bytes().end(), std::byte{0xa5});
seeded = seed.Handle();
}
@@ -0,0 +1,45 @@
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
#include <array>
#include <cstdint>
#include <cstdio>
#include <exception>
#include <span>
using namespace ShaderRecompiler;
namespace {
int failures = 0;
void Check(bool condition, const char* what) {
if (condition) return;
std::fprintf(stderr, "%s\n", what);
++failures;
}
RdnaInstruction Decode(std::span<const std::uint32_t> words) {
return DecodeGcnInstruction(0u, words, 0u);
}
void SetregImmKeepsItsLiteral() {
const std::array<std::uint32_t, 3> setreg{0xba80f801u, 0x12345678u, 0xbf810000u};
const auto instruction = Decode(setreg);
Check(instruction.op == RdnaOpcode::SSetregImm32B32, "s_setreg_imm32_b32 did not decode as its RDNA opcode");
Check(instruction.wordCount == 2u, "a GCN s_setreg_imm32_b32 is not two words");
Check(instruction.source0.value == 0x12345678u, "s_setreg_imm32_b32 lost its literal");
const std::array<std::uint32_t, 2> movk{0xb0001234u, 0xbf810000u};
Check(Decode(movk).wordCount == 1u, "s_movk_i32 took a literal word");
}
}
int main() {
try {
SetregImmKeepsItsLiteral();
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
if (failures == 0) std::puts("GCN decode tests passed");
return failures == 0 ? 0 : 1;
}
+278 -17
View File
@@ -19,6 +19,7 @@
#include "prx/libSceAgcDriver/Graphics/include/ParallelCompare.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
#include "SceShaders.hpp"
#include "prx/libSceAgc/Shader/include/ShaderConstants.hpp"
#include "ControlFlow/RequestSerializer.hpp"
@@ -162,9 +163,15 @@ void inactiveVertexPointSizeTests() {
}
throw std::runtime_error("potentially active point size passed the state decoder");
};
for (const auto primitive : {1u, 9u}) {
{
auto queue = pointSizeState();
queue.userConfig[0x242] = primitive;
queue.userConfig[0x242] = 9;
rejected(queue);
}
{
auto queue = pointSizeState();
queue.userConfig[0x242] = 1;
queue.context[0x2d5] = 0x2020;
rejected(queue);
}
for (const auto stages : {0x2004u, 0x2020u}) {
@@ -221,6 +228,73 @@ void PolygonPrimitiveTests() {
Require(indexedState.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN && indexedState.primitiveRestart, "indexed polygon decoding did not keep primitive restart");
}
void vertexPointListTests() {
const auto pointState = [](std::uint32_t control, std::uint32_t size, std::uint32_t limits) {
auto queue = makeState();
queue.userConfig[0x242] = 1;
queue.context[0x1b3] = queue.context[0x1b4] = 2;
queue.context[0x207] = control;
queue.context[0x280] = size;
queue.context[0x281] = limits;
return queue;
};
{
const auto queue = pointState(0x01210000u, 0x00080008u, 0x00080008u);
const auto rejection = AgcDriver::Graphics::DrawRejection(queue, false);
Require(rejection.empty(), "a vertex-path point list with a vertex point size failed the draw precheck: " + rejection);
const auto state = AgcDriver::Graphics::DecodeState(queue);
Require(state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST && state.paClVsOutCntl == 0x01210000u, "a vertex-path point list with a vertex point size did not decode as a point list");
Require(AgcDriver::Graphics::RasterPrimitiveOf(state) == ShaderRecompiler::RasterPrimitive::Point, "a vertex-path point list is not rasterized as points");
Require(state.vertexPoints && state.pointSize == 1.0f && state.pointSizeMin == 1.0f && state.pointSizeMax == 1.0f, "PA_SU_POINT_SIZE and PA_SU_POINT_MINMAX of 8 did not decode as one-pixel points");
ShaderRecompiler::ShaderVertexStageInfo vertex{};
vertex.paClVsOutCntl = 1u << 21u;
AgcDriver::Graphics::ApplyPointSize(state, vertex);
Require(vertex.pointList && vertex.paClVsOutCntl == ((1u << 16u) | (1u << 21u)) && vertex.pointSize == 1.0f && vertex.pointSizeMin == 1.0f && vertex.pointSizeMax == 1.0f, "the vertex stage did not receive the vertex point size");
}
{
const auto state = AgcDriver::Graphics::DecodeState(pointState(0, 0x00200020u, 0x00100004u));
Require(state.vertexPoints && state.pointSize == 4.0f && state.pointSizeMin == 0.5f && state.pointSizeMax == 2.0f, "a register point size did not decode as diameters");
ShaderRecompiler::ShaderVertexStageInfo vertex{};
vertex.paClVsOutCntl = 1u << 21u;
AgcDriver::Graphics::ApplyPointSize(state, vertex);
Require(vertex.pointList && vertex.paClVsOutCntl == (1u << 21u) && vertex.pointSize == 4.0f, "a register point size turned on the vertex point size");
}
{
const auto state = AgcDriver::Graphics::DecodeState(pointState(0x01210000u, 0x00200010u, 0x00400000u));
Require(state.pointSizeMin == 0.0f && state.pointSizeMax == 8.0f, "a vertex point size refused a register size whose width and height differ");
}
{
auto queue = makeState();
queue.context[0x1b3] = queue.context[0x1b4] = 2;
queue.context[0x207] = 0x01210000u;
const auto state = AgcDriver::Graphics::DecodeState(queue);
Require(!state.vertexPoints, "a triangle draw decoded as vertex points");
ShaderRecompiler::ShaderVertexStageInfo vertex{};
AgcDriver::Graphics::ApplyPointSize(state, vertex);
Require(!vertex.pointList && vertex.paClVsOutCntl == 0, "a triangle draw received a point size");
}
expectFailure([&] { AgcDriver::Graphics::DecodeState(pointState(0, 0x00200010u, 0x00080008u)); }, "points whose PA_SU_POINT_SIZE width and height differ are unsupported");
expectFailure([&] { AgcDriver::Graphics::DecodeState(pointState(0, 0x00080008u, 0x00080010u)); }, "PA_SU_POINT_MINMAX with a minimum above its maximum is unsupported");
expectFailure([&] { AgcDriver::Graphics::DecodeState(pointState(1u << 16u, 0x00080008u, 0x00080008u)); }, "USE_VTX_POINT_SIZE without VS_OUT_MISC_VEC_ENA is unsupported");
expectFailure([&] { AgcDriver::Graphics::DecodeState(pointState(0, 0, 0x00080008u)); }, "points of size 0 (PA_SU_POINT_SIZE 0) are unsupported");
expectFailure([&] { AgcDriver::Graphics::DecodeState(pointState(0x01210000u, 0x00080008u, 0)); }, "a vertex point size clamped to 0 (PA_SU_POINT_MINMAX maximum 0) is unsupported");
{
const auto state = AgcDriver::Graphics::DecodeState(pointState(0x01210000u, 0, 0x00200000u));
Require(state.pointSize == 0.0f && state.pointSizeMin == 0.0f && state.pointSizeMax == 4.0f, "a vertex point size refused a zero register size or a zero clamp minimum");
static_cast<void>(AgcDriver::Graphics::DecodeState(pointState(0, 0x00080008u, 0)));
}
for (const auto sprite : {1u << 17u, 1u << 23u}) {
auto queue = pointState(0x01210000u, 0x00080008u, 0x00080008u);
queue.context[0x1b5] = 0x486bu;
queue.context[0x1b6] = 2;
queue.context[0x191] = 0;
queue.context[0x192] = sprite;
expectFailure([&] { AgcDriver::Graphics::DecodeState(queue); }, "point sprite texture coordinates (SPI_PS_INPUT_CNTL PT_SPRITE_TEX) are not implemented");
queue.context[0x1b5] = 0x4869u;
Require(AgcDriver::Graphics::DecodeState(queue).vertexPoints, "PT_SPRITE_TEX was refused with point sprites off");
}
}
void retainedPixelStageTests() {
using namespace AgcDriver::Graphics;
auto queue = makeState();
@@ -765,10 +839,12 @@ void msaaEnableClearOneSampleTargetTests() {
expectFailure([&] { DecodeState(queue); }, refused);
queue = drawC();
queue.context[0x2dc] = 0x0000aa01u;
expectFailure([&] { DecodeState(queue); }, "without MSAA_ENABLE are unsupported for points, lines");
queue = drawC();
queue.userConfig[0x242] = 2;
expectFailure([&] { DecodeState(queue); }, "without MSAA_ENABLE are unsupported for points, lines");
expectFailure([&] { DecodeState(queue); }, "without MSAA_ENABLE are unsupported for points or alpha-to-coverage");
for (const auto primitive : {2u, 3u}) {
queue = drawC();
queue.userConfig[0x242] = primitive;
requireOneSample(queue, "a line list or strip into PPSA18216's draw C target");
}
const auto twoTargets = [&](std::uint32_t first, std::uint32_t second) {
auto pair = drawC();
for (const auto offset : {0x318u, 0x31bu, 0x31cu}) pair.context[offset + 0xfu] = pair.context.at(offset);
@@ -853,9 +929,11 @@ void msaaEnableClearOneSampleTargetTests() {
queue = depthTarget(color);
queue.context[0x2dc] = 0x0000aa01u;
expectFailure([&] { DecodeState(queue); }, depthRefused);
queue = depthTarget(color);
queue.userConfig[0x242] = 2;
expectFailure([&] { DecodeState(queue); }, depthRefused);
for (const auto primitive : {2u, 3u}) {
queue = depthTarget(color);
queue.userConfig[0x242] = primitive;
expectFailure([&] { DecodeState(queue); }, depthRefused);
}
for (const auto eqaa : {0x00050002u, 0x00090002u, 0x01010002u, 0x08010002u}) {
queue = depthTarget(color);
queue.context[0x201] = eqaa;
@@ -1075,11 +1153,30 @@ void ShaderStageTests() {
lines.context[0x29b] = 1;
Require(AgcDriver::Graphics::DecodeState(lines).stages.mesh->provokingVertex == 1, "a last-vertex geometry draw does not take its flat inputs and layer from the second vertex of each output line");
lines.context[0x29b] = 0;
expectFailure([&] { AgcDriver::Graphics::DecodeState(lines); }, "missing register in context bank at DWORD 0x280");
lines.context[0x280] = 0x00080008u;
expectFailure([&] { AgcDriver::Graphics::DecodeState(lines); }, "missing register in context bank at DWORD 0x281");
lines.context[0x281] = 0xffff0000u;
state = AgcDriver::Graphics::DecodeState(lines);
mesh = *state.stages.mesh;
Require(mesh.outputPrimitiveSize == 1 && mesh.maxPrimitives == 255 && AgcDriver::Graphics::RasterPrimitiveOf(state) == ShaderRecompiler::RasterPrimitive::Point, "a point-list subgroup did not decode as points");
Require(mesh.provokingVertex == 0, "a point draw has provoking vertex 0");
Require(state.pointSize == 1.0f && state.pointSizeMin == 0.0f && state.pointSizeMax == 8191.875f, "geometry points did not decode the queue's default point size and limits");
lines.context[0x205] = raster;
auto points = lines;
points.userConfig[0x242] = 6;
points.userConfig[0x25b] = 0x5c2e;
points.context[0x1ff] = 0x8a;
points.context[0x2ce] = 3;
points.context[0x29b] = 0;
points.context[0x280] = 0x00180018u;
points.context[0x281] = 0x00400008u;
const auto pointState = AgcDriver::Graphics::DecodeState(points);
const auto& pointMesh = *pointState.stages.mesh;
ShaderRecompiler::ShaderVertexStageInfo pointInfo{};
AgcDriver::Graphics::ApplyPointSize(pointState, pointInfo);
Require(pointInfo.pointList && pointInfo.pointSize == 3.0f && pointInfo.pointSizeMin == 1.0f && pointInfo.pointSizeMax == 8.0f, "geometry points lost their register sizes");
Require(pointMesh.outputPrimitiveSize == 1u && pointMesh.primitivesPerGroup == 44u && pointMesh.verticesPerGroup == 46u && pointMesh.maxVertices == 138u && pointMesh.maxPrimitives == 138u && pointMesh.threadsPerGroup == 192u && AgcDriver::Graphics::RasterPrimitiveOf(pointState) == ShaderRecompiler::RasterPrimitive::Point, "triangle-strip input with point output did not decode the reported subgroup");
lines.context[0x29b] = 1;
lines.context[0x2ce] = 1;
expectFailure([&] { AgcDriver::Graphics::DecodeState(lines); }, "unsupported geometry input or output assembly");
@@ -1729,7 +1826,39 @@ void DisabledColorTests() {
queue.context[0x002] = 3;
const auto thirdSlice = AgcDriver::Graphics::DecodeState(queue);
Require(thirdSlice.depth && thirdSlice.depth->firstSlice == 3 && thirdSlice.depth->address == depthOnly.depth->address + 3u * AgcDriver::Graphics::DepthSliceBytes(depthOnly.depth->extent, 4u), "a depth view of slice 3 lost its slice or its Z offset");
queue.context[0x002] = 1u << 26u;
expectFailure([&] { AgcDriver::Graphics::DecodeState(queue); }, "on a surface without mips");
queue.context[0x002] = 0;
{
using AgcDriver::Graphics::ComputeElementMipLayout;
using AgcDriver::Graphics::TextureTileMode;
auto mipped = queue;
mipped.context[0x007] = 0x03ff03ff;
mipped.context[0x010] = 0x80000181u | (2u << 16u);
const auto mips = ComputeElementMipLayout(TextureTileMode::kZ64KBX, 2u, 1024u, 1024u, 3u);
Require(!mips.at(1).tail && mips.at(1).width == 512u && mips.at(1).height == 512u, "the 1024x1024 Z_X layout does not give a 512x512 second mip outside the tail");
const auto first = AgcDriver::Graphics::DecodeState(mipped);
Require(first.depth && first.depth->address == depthOnly.depth->address + mips.at(0).tiledOffset && first.depth->extent.width == 1024u && first.depth->extent.height == 1024u, "view mip 0 of a mip chain is not its first level");
mipped.context[0x002] = 1u << 26u;
const auto second = AgcDriver::Graphics::DecodeState(mipped);
Require(second.depth && second.depth->address == depthOnly.depth->address + mips.at(1).tiledOffset, "view mip 1 is not at the second level's offset in the Z_X mip chain");
Require(second.depth->extent.width == 512u && second.depth->extent.height == 512u, "view mip 1 does not render at the second level's extent");
mipped.context[0x002] = (1u << 26u) | 1u | (1u << 13u);
const auto sliced = AgcDriver::Graphics::DecodeState(mipped);
Require(sliced.depth && sliced.depth->address == second.depth->address + AgcDriver::Graphics::ComputeSurfaceSize(mips, 1u), "slice 1 of a mip chain does not step by the whole chain");
mipped.context[0x002] = 3u << 26u;
expectFailure([&] { AgcDriver::Graphics::DecodeState(mipped); }, "is beyond the surface's mips");
mipped.context[0x002] = 2u << 26u;
mipped.context[0x007] = 0x003f003f;
expectFailure([&] { AgcDriver::Graphics::DecodeState(mipped); }, "into the packed mip tail is unsupported");
mipped.context[0x007] = 0x03ff03ff;
mipped.context[0x002] = 1u << 26u;
mipped.context[0x010] |= 1u << 29u;
mipped.context[0x005] = 0x300;
expectFailure([&] { AgcDriver::Graphics::DecodeState(mipped); }, "HTILE for the depth view mip");
mipped.context[0x010] = (0x80000181u | (2u << 16u)) & ~(31u << 4u);
expectFailure([&] { AgcDriver::Graphics::DecodeState(mipped); }, "uses a swizzle other than 64 KiB Z_X");
}
for (const auto colorControl : {0x0u, 0xcc0000u}) {
queue = makeState();
queue.context[0x202] = colorControl;
@@ -2363,10 +2492,12 @@ void DepthStencilTests() {
queue.context[0x000] = 0x22u | control;
expectFailure([&] { AgcDriver::Graphics::DecodeState(queue); }, "DB_RENDER_CONTROL");
}
queue.context[0x000] = 0x22;
queue.context[0x000] = 0x23;
queue.context[0x011] = 0;
expectFailure([&] { AgcDriver::Graphics::DecodeState(queue); }, "writable stencil plane");
Require(AgcDriver::Graphics::DrawRejection(queue, false).find("writable stencil plane") != std::string::npos, "precheck accepted clear without a stencil plane");
state = AgcDriver::Graphics::DecodeState(queue);
Require(state.depthWrite && state.depthCompare == VK_COMPARE_OP_ALWAYS && !state.stencilTest && state.colors.size() == 2, "a depth and stencil clear without a stencil plane does not clear depth alone");
Require(AgcDriver::Graphics::DrawRejection(queue, false).empty(), "precheck rejected a stencil clear without a stencil plane");
queue.context[0x000] = 0x22;
queue.context[0x010] = 0;
state = AgcDriver::Graphics::DecodeState(queue);
Require(!state.depth && !state.depthTest && !state.depthWrite && !state.stencilTest && state.colors.size() == 2, "clear flags without depth/stencil planes changed color-only rendering");
@@ -3316,6 +3447,43 @@ void msaaEnableClearDepthTests() {
state = DecodeState(queue);
Require(state.colors.empty(), "a depth-only 4x draw without MSAA_ENABLE decoded a color target");
requireCentered(state, "a 4x depth target rasterized without MSAA_ENABLE");
for (const auto primitive : {2u, 3u}) {
queue = drawB();
queue.userConfig[0x242] = primitive;
state = DecodeState(queue);
Require(state.topology == (primitive == 2u ? VK_PRIMITIVE_TOPOLOGY_LINE_LIST : VK_PRIMITIVE_TOPOLOGY_LINE_STRIP) && state.colors.size() == 1 && state.colors[0].samples == 4, "PPSA18216's line list or strip into its 4x depth and color pair lost its topology or color target");
requireCentered(state, "a line list or strip into PPSA18216's 4x depth and color pair without MSAA_ENABLE");
Require(!state.sampleLocationGrid && !state.perSampleShading, "a line list or strip without MSAA_ENABLE kept a sample location grid or sample shading");
Require(AgcDriver::Graphics::DrawRejection(queue, false).empty(), "the precheck refused a line list or strip into PPSA18216's 4x depth and color pair");
}
queue = drawB();
queue.userConfig[0x242] = 1;
queue.context[0x2d5] = 0x2030;
queue.userConfig[0x25b] = 0x6633;
queue.context[0x1ff] = 255;
queue.context[0x2ce] = 5;
queue.context[0x29b] = 2;
queue.context[0x2ab] = 4;
queue.shader[0x8a] = 3u << 29u;
queue.shader[0x8b] = 3u << 16u;
state = DecodeState(queue);
Require(state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST && state.stages.mesh && state.stages.mesh->outputPrimitiveSize == 3u && AgcDriver::Graphics::RasterPrimitiveOf(state) == ShaderRecompiler::RasterPrimitive::Triangle && state.colors.size() == 1 && state.colors[0].samples == 4, "a point list into a geometry program that outputs triangle strips into PPSA18216's 4x depth and color pair did not decode as triangles");
requireCentered(state, "triangles a geometry program makes from a point list into PPSA18216's 4x depth and color pair without MSAA_ENABLE");
for (const auto primitive : {4u, 2u, 1u}) {
queue = drawB();
queue.userConfig[0x242] = primitive;
queue.context[0x2d5] = 0x2030;
queue.userConfig[0x25b] = 0x6633;
queue.context[0x1ff] = 255;
queue.context[0x2ce] = 5;
queue.context[0x29b] = 0;
queue.context[0x2ab] = 4;
queue.context[0x280] = 0x00080008u; // point-output geometry programs decode PA_SU_POINT_SIZE / PA_SU_POINT_MINMAX before this rejection
queue.context[0x281] = 0x00080008u;
queue.shader[0x8a] = 3u << 29u;
queue.shader[0x8b] = 3u << 16u;
expectFailure([&] { DecodeState(queue); }, "multisampled targets rasterized without MSAA_ENABLE are unsupported for points or alpha-to-coverage");
}
for (const auto eqaa : {0x00050002u, 0x00090002u, 0x01010002u, 0x08010002u}) {
queue = drawB();
queue.context[0x201] = eqaa;
@@ -3327,7 +3495,7 @@ void msaaEnableClearDepthTests() {
expectFailure([&] { DecodeState(queue); }, "a multisampled depth target rasterized without MSAA_ENABLE with a sample-mask export");
queue = drawB();
queue.context[0x2dc] = 0x0000aa01u;
expectFailure([&] { DecodeState(queue); }, "multisampled targets rasterized without MSAA_ENABLE are unsupported for points, lines or alpha-to-coverage");
expectFailure([&] { DecodeState(queue); }, "multisampled targets rasterized without MSAA_ENABLE are unsupported for points or alpha-to-coverage");
queue = drawB();
queue.context[0x010] = 0xa2900987;
expectFailure([&] { DecodeState(queue); }, "the depth target's sample count differs from the rasterizer's");
@@ -3634,7 +3802,7 @@ void multisampleTests() {
const auto aliased = AgcDriver::Graphics::SampleLocations(state);
for (std::uint32_t sample = 0; sample < state.samples; ++sample) Require(aliased[sample].x == 0.5f && aliased[sample].y == 0.5f, "a 2x target rasterized without MSAA_ENABLE did not place every sample at the pixel center");
queue.context[0x2dc] = 0x0000aa01u;
expectFailure([&] { DecodeState(queue); }, "without MSAA_ENABLE are unsupported for points, lines or alpha-to-coverage");
expectFailure([&] { DecodeState(queue); }, "without MSAA_ENABLE are unsupported for points or alpha-to-coverage");
queue = multisampled();
queue.context[0x292] = 2;
queue.context[0x302] = 0x44cc;
@@ -4077,6 +4245,29 @@ void multisampledDepthTests() {
Require(!DecodeState(queue).perSampleShading, "PS_ITER_SAMPLE requested sample shading for a single-sample scan");
queue = singleSampleScan();
queue.context[0x31d] = 0;
state = DecodeState(queue);
Require(state.truncatedCoverage && !state.mergedCoverage && state.colors.size() == 1 && state.colors[0].samples == 1, "a single-sample scan into a 4x depth target and a one-sample color target did not take the color from sample 0");
requireCentered(state, "a single-sample scan into a 4x depth target and a one-sample color target");
const auto truncatedTwoSample = [&] {
auto queue = singleSampleScan();
queue.context[0x2f8] = 0x00100001;
queue.context[0x292] = 3;
for (std::uint32_t pixel = 0; pixel < 4; ++pixel) queue.context[0x2fe + pixel * 4u] = 0xcc44;
queue.context[0x010] = 0x22900987;
queue.context[0x31d] = 0;
return queue;
};
queue = truncatedTwoSample();
state = DecodeState(queue);
Require(state.samples == 2 && state.depth && state.depth->samples == 2 && state.colors.size() == 1 && state.colors[0].samples == 1 && state.truncatedCoverage && !state.mergedCoverage && !state.perSampleShading, "a one-sample color target beside a 2x depth target under a 2x rasterizer with MSAA_ENABLE (PPSA02225's registers) did not take the color from sample 0");
Require(AgcDriver::Graphics::DrawRejection(queue, false).empty(), "the precheck refused a one-sample color target beside a 2x depth target");
queue = truncatedTwoSample();
queue.context[0x293] = 0x10000u;
queue.context[0x1b3] = queue.context[0x1b4] = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PerspectiveSample) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::FrontFace);
state = DecodeState(queue);
Require(state.truncatedCoverage && state.perSampleShading && state.samples == 2 && state.colors[0].samples == 1, "PS_ITER_SAMPLE into a one-sample color target beside a 2x depth target (PPSA02225's registers) did not run per sample with sample 0's color");
queue = truncatedTwoSample();
queue.context[0x31d] = 0x12000;
expectFailure([&] { DecodeState(queue); }, "a color target's sample count differs from the rasterizer's");
queue = singleSampleScan();
queue.context[0x010] = 0x22900983;
@@ -7778,6 +7969,9 @@ void barycentricEmulationTests() {
const std::array<FragmentParameter, 3> parameters{{{0u, 0u, false, false}, {1u, 1u, false, true}, {2u, 2u, true, false}}};
const auto layout = LayoutBarycentricEmulation(parameters, {true, true, true});
Require(layout.smoothLocation == 1u && layout.linearLocation == 3u && layout.perVertexLocations == std::vector<std::pair<std::uint32_t, std::uint32_t>>{{1u, 4u}}, "emulated barycentrics did not take the free locations in order");
const auto offsetLayout = LayoutBarycentricEmulation(parameters, {true, true, false, true});
Require(offsetLayout.smoothLocation == 1u && offsetLayout.reciprocalWLocation == 3u && offsetLayout.perVertexLocations == std::vector<std::pair<std::uint32_t, std::uint32_t>>{{1u, 4u}}, "perspective offset emulation did not reserve reciprocal-w inputs");
Require(LayoutBarycentricEmulation(parameters, {true, true, false}).reciprocalWLocation == BarycentricEmulationLayout::NoLocation, "non-offset perspective barycentrics reserved reciprocal-w inputs");
Require(LayoutBarycentricEmulation(parameters, {}).perVertexLocations.empty() && LayoutBarycentricEmulation(parameters, {}).smoothLocation == BarycentricEmulationLayout::NoLocation, "an inactive emulation was given locations");
std::vector<FragmentParameter> crowded;
for (std::uint32_t location = 0; location < 11u; ++location) crowded.push_back({location, location, false, true});
@@ -7894,9 +8088,11 @@ void barycentricEmulationTests() {
Require(BarycentricPatches(state, patchShaders) && !BarycentricPatches(state, shaders), "generated tessellation stages were not recognised as barycentric patches");
state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
ValidateShaders(patchShaders, state, subgroup, false);
for (const auto topology : {VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, VK_PRIMITIVE_TOPOLOGY_POINT_LIST}) {
state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
ValidateShaders(patchShaders, state, subgroup, false);
for (const auto topology : {VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, VK_PRIMITIVE_TOPOLOGY_POINT_LIST}) {
state.topology = topology;
expectFailure([&] { ValidateShaders(patchShaders, state, subgroup, false); }, "require a triangle list");
expectFailure([&] { ValidateShaders(patchShaders, state, subgroup, false); }, "require a triangle list or strip");
}
state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
const std::array<CompiledShader, 4> plainPatchShaders{{{ShaderStage::Vertex, &vertex, 0}, {ShaderStage::TessellationControl, &patches.control, 0}, {ShaderStage::TessellationEvaluation, &patches.evaluation, 0}, {ShaderStage::Fragment, &plain, 0}}};
@@ -9136,6 +9332,14 @@ void ProvokingVertexTests() {
const std::array<CompiledShader, 1> flatP10Shaders{{{ShaderRecompiler::ShaderStage::Fragment, &flatP10Pixel, 0}}};
ValidateProvokingVertex(supported, last, flatP10Shaders);
expectFailure([&] { ValidateProvokingVertex(supported, first, flatP10Shaders); }, "v_interp_mov p10 of a flat input with the first provoking vertex is not measured");
const std::array<std::uint32_t, 7> flatP20Color{0xc8120001u, 0xc8160101u, 0xc81a0201u, 0xc81e0301u, 0xf800180fu, 0x07060504u, 0xbf810000u};
const auto flatP20Pixel = recompilePixel({0x400u}, flatP20Color);
const auto p20Inputs = locatedInputs(flatP20Pixel.spirv.Words());
Require(p20Inputs.size() == 1 && p20Inputs[0].location == 0 && p20Inputs[0].flat && !p20Inputs[0].perVertex, "flat v_interp_mov P20 did not compile to a flat input");
Require(flatP20Pixel.fragmentParameters.size() == 1 && flatP20Pixel.fragmentParameters[0].flatP20 && !flatP20Pixel.fragmentParameters[0].flatP10 && !flatP20Pixel.fragmentParameters[0].perVertex && !flatP10Pixel.fragmentParameters[0].flatP20, "flat v_interp_mov P20 was not recorded apart from P10");
const std::array<CompiledShader, 1> flatP20Shaders{{{ShaderRecompiler::ShaderStage::Fragment, &flatP20Pixel, 0}}};
ValidateProvokingVertex(supported, first, flatP20Shaders);
expectFailure([&] { ValidateProvokingVertex(supported, last, flatP20Shaders); }, "v_interp_mov p20 of a flat input with the last provoking vertex is not measured");
auto lastStrip = last;
lastStrip.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
auto lastList = last;
@@ -9280,6 +9484,8 @@ void ConservativeRasterizationTests() {
geometry.context[0x2ce] = 3;
geometry.context[0x29b] = 2;
geometry.context[0x2ab] = 4;
geometry.context[0x280] = 0x00080008u; // PA_SU_POINT_SIZE and PA_SU_POINT_MINMAX: a point-output geometry program decodes them
geometry.context[0x281] = 0x00080008u;
geometry.shader[0x8a] = 3u << 29u;
geometry.shader[0x8b] = 3u << 16u;
for (const auto input : {1u, 2u, 4u}) {
@@ -9500,7 +9706,12 @@ void float11_11_10TargetTests() {
auto changed = queue;
changed.context[0x31c] &= ~0x40000u;
expectFailure([&] { AgcDriver::Graphics::DecodeState(changed); }, "rounding (ROUND_MODE 0) 11_11_10 float color targets");
for (const auto swap : {0u, 1u, 3u}) {
changed = queue;
changed.context[0x31c] &= ~0x1800u;
const auto standard = AgcDriver::Graphics::DecodeState(changed);
Require(standard.color.format == VK_FORMAT_R32_UINT && standard.color.componentMapping == 0xe4u && standard.color.packing == ColorExportPacking::Float11_11_10, "an 11_11_10 float target with the standard component order did not decode");
Require(AgcDriver::Graphics::ExportMappings(standard)[0] == 0xe4u, "export 0 reordered its components into the standard-order 11_11_10 float target");
for (const auto swap : {1u, 3u}) {
changed = queue;
changed.context[0x31c] = (changed.context[0x31c] & ~0x1800u) | (swap << 11u);
expectFailure([&] { AgcDriver::Graphics::DecodeState(changed); }, "unsupported color format 7 number type 7 component swap " + std::to_string(swap));
@@ -10686,6 +10897,39 @@ void pipelineJournalTests(bool longPath = false, bool extended = false) {
const PipelineSetLayouts decodedLayouts{layouts.layouts.main, layouts.layouts.fragment, decoded.splitSets, decoded.mainLayoutKey, decoded.fragmentLayoutKey};
BuildPipelineStoreKey(replayed, context, decoded.state, decoded.vertexInput, decodedLayouts, shaders, decoded.attachmentLayout);
Require(!original.empty() && original == canonical && original == replayed, "the canonical or the decoded state keys another pipeline");
auto fmaskState = state;
fmaskState.samples = 8;
fmaskState.color.samples = 8;
fmaskState.color.fmaskAddress = 0x30000;
fmaskState.color.fmaskPipeBankXor = 0x1200;
for (auto& target : fmaskState.colors) {
target.samples = 8;
target.fmaskAddress = 0x40000;
target.fmaskPipeBankXor = 0x2300;
}
const auto fmaskRecipe = MakeGraphicsPipelineRecipe(fmaskState, input, layouts.View(), shaders, VK_IMAGE_LAYOUT_GENERAL);
Require(fmaskRecipe.state.color.fmaskAddress == 0 && fmaskRecipe.state.color.fmaskPipeBankXor == 0, "the canonical state kept the primary target's FMASK location");
for (const auto& canonicalColor : fmaskRecipe.state.colors) {
Require(canonicalColor.fmaskAddress == 0 && canonicalColor.fmaskPipeBankXor == 0, "the canonical state kept an attachment's FMASK location");
}
const auto fmaskBytes = EncodeGraphicsPipelineRecipe(fmaskRecipe);
GraphicsPipelineRecipe fmaskDecoded;
Require(DecodeGraphicsPipelineRecipe(fmaskBytes, fmaskDecoded) && EncodeGraphicsPipelineRecipe(fmaskDecoded) == fmaskBytes, "the FMASK pipeline recipe did not round-trip byte for byte");
std::vector<std::byte> fmaskKey, fmaskReplayedKey;
BuildPipelineStoreKey(fmaskKey, context, fmaskState, input, layouts.View(), shaders, VK_IMAGE_LAYOUT_GENERAL);
BuildPipelineStoreKey(fmaskReplayedKey, context, fmaskDecoded.state, fmaskDecoded.vertexInput, layouts.View(), shaders, fmaskDecoded.attachmentLayout);
Require(fmaskKey != original && fmaskKey == fmaskReplayedKey, "the decoded FMASK state keys another pipeline");
auto relocatedFmask = fmaskState;
relocatedFmask.color.fmaskAddress += 0x10000;
relocatedFmask.color.fmaskPipeBankXor ^= 0x100;
for (auto& target : relocatedFmask.colors) {
target.fmaskAddress += 0x20000;
target.fmaskPipeBankXor ^= 0x200;
}
std::vector<std::byte> relocatedFmaskKey;
BuildPipelineStoreKey(relocatedFmaskKey, context, relocatedFmask, input, layouts.View(), shaders, VK_IMAGE_LAYOUT_GENERAL);
Require(relocatedFmaskKey == fmaskKey, "the FMASK resource location changed the pipeline key");
Require(EncodeGraphicsPipelineRecipe(MakeGraphicsPipelineRecipe(relocatedFmask, input, layouts.View(), shaders, VK_IMAGE_LAYOUT_GENERAL)) == fmaskBytes, "the FMASK resource location changed the journal recipe");
auto gridState = state;
gridState.samples = 2;
gridState.customSampleLocations = true;
@@ -10704,6 +10948,22 @@ void pipelineJournalTests(bool longPath = false, bool extended = false) {
GraphicsPipelineRecipe lineDecoded;
Require(DecodeGraphicsPipelineRecipe(EncodeGraphicsPipelineRecipe(MakeGraphicsPipelineRecipe(lineState, input, layouts.View(), shaders, VK_IMAGE_LAYOUT_GENERAL)), lineDecoded), "the line strip mesh recipe does not decode");
Require(lineDecoded.state.stages.mesh && lineDecoded.state.stages.mesh->outputPrimitiveSize == 2u && lineDecoded.state.stages.mesh->esgsItemSize == 4u, "the recipe dropped the mesh output primitive size");
auto pointState = state;
pointState.vertexPoints = true;
pointState.pointSize = 4.0f;
pointState.pointSizeMin = 0.5f;
pointState.pointSizeMax = 8.0f;
GraphicsPipelineRecipe pointDecoded;
Require(DecodeGraphicsPipelineRecipe(EncodeGraphicsPipelineRecipe(MakeGraphicsPipelineRecipe(pointState, input, layouts.View(), shaders, VK_IMAGE_LAYOUT_GENERAL)), pointDecoded), "the point list recipe does not decode");
Require(pointDecoded.state.vertexPoints && pointDecoded.state.pointSize == 4.0f && pointDecoded.state.pointSizeMin == 0.5f && pointDecoded.state.pointSizeMax == 8.0f, "the recipe dropped the vertex point list or its point sizes");
auto meshPointState = pointState;
meshPointState.vertexPoints = false;
meshPointState.stages.mesh = *lineState.stages.mesh;
meshPointState.stages.mesh->outputPrimitiveSize = 1u;
meshPointState.stages.mesh->provokingVertex = 0u;
GraphicsPipelineRecipe meshPointDecoded;
Require(DecodeGraphicsPipelineRecipe(EncodeGraphicsPipelineRecipe(MakeGraphicsPipelineRecipe(meshPointState, input, layouts.View(), shaders, VK_IMAGE_LAYOUT_GENERAL)), meshPointDecoded), "the mesh point recipe does not decode");
Require(!meshPointDecoded.state.vertexPoints && meshPointDecoded.state.stages.mesh && meshPointDecoded.state.stages.mesh->outputPrimitiveSize == 1u && meshPointDecoded.state.pointSize == 4.0f && meshPointDecoded.state.pointSizeMin == 0.5f && meshPointDecoded.state.pointSizeMax == 8.0f, "the recipe dropped mesh points or their sizes without the vertex point flag");
auto fourSampleState = state;
fourSampleState.samples = 4;
auto maskState = fourSampleState;
@@ -11185,6 +11445,7 @@ int main(int argc, char** argv) {
NggVertexWorkgroupTests();
inactiveVertexPointSizeTests();
PolygonPrimitiveTests();
vertexPointListTests();
TuningFieldTests();
PixelInputLayoutTests();
UnexportedPixelInputTests();
@@ -95,6 +95,52 @@ void rejectFields(const Fields& f, std::string_view reason) {
}
static void RunR128TextureTests() {
constexpr std::array<std::uint32_t, 8> streamed{0xa0c18800u, 0xcad00000u, 0x01ffc1ffu, 0x905b2facu, 0u, 0u, 0u, 0u};
const auto view = DecodeTextureResource(streamed);
Require(view.baseAddress == 0xa0c1880000ull && view.format == 173u && view.tileMode == TextureTileMode::kStandard4KB && view.width == 512u && view.height == 512u && view.baseLevel == 0u && view.lastLevel == 9u && view.mipCount == 10u && view.allocatedMipCount == 10u && view.minLod == 0u,
"a 128-bit BC3 T# (2048x2048, levels 2..11, words 4-7 zero) must read as the 512x512 chain of its 10 resident levels, got " + std::to_string(view.width) + "x" + std::to_string(view.height) + " levels " + std::to_string(view.baseLevel) + ".." + std::to_string(view.lastLevel) + " of " + std::to_string(view.mipCount));
auto chainWords = streamed;
chainWords[3] &= ~(0xfu << 12u);
chainWords[5] = 11u << 4u;
const auto full = DecodeTextureResource(chainWords);
Require(full.width == 2048u && full.mipCount == 12u, "the same surface with MAX_MIP 11 must be the 12-level 2048x2048 chain");
const auto chain = DescribeSurface(full);
const auto resident = DescribeSurface(view);
Require(chain.mips.size() == 12u && resident.mips.size() == 10u, "the chain and the resident levels must have 12 and 10 levels");
for (std::uint32_t level = 0; level < 10u; ++level) {
const auto& a = chain.mips[level + 2u];
const auto& b = resident.mips[level];
Require(a.tiledOffset == b.tiledOffset && a.tiledSize == b.tiledSize && a.width == b.width && a.height == b.height && a.blocksPerRow == b.blocksPerRow && a.tail == b.tail && a.tailX == b.tailX && a.tailY == b.tailY, "resident level " + std::to_string(level) + " must be level " + std::to_string(level + 2u) + " of the 12-level chain");
}
Require(resident.guestBytes <= chain.mips[1].tiledOffset && chain.mips[0].tiledOffset > chain.mips[1].tiledOffset, "the resident levels must end before the chain's levels 1 and 0, which come last in a GFX10 swizzled chain");
auto levelZero = streamed;
levelZero[3] &= ~(0xfu << 12u);
const auto single = DecodeTextureResource(levelZero);
Require(single.mipCount == 1u && single.lastLevel == 0u, "a T# with words 4-7 zero that starts at level 0 must stay one level");
auto tailed = streamed;
tailed[5] = 4u << 20u;
reject([&] { DecodeTextureResource(tailed); }, "would move the surface's own");
constexpr std::array<std::uint32_t, 8> tall{0xa0c1de00u, 0xcad00000u, 0x01ffc0ffu, 0x905b4facu, 0u, 0u, 0u, 0u};
const auto tallView = DecodeTextureResource(tall);
Require(tallView.width == 64u && tallView.height == 128u && tallView.lastLevel == 7u && tallView.mipCount == 8u, "a 128-bit 1024x2048 T# of levels 4..11 must read as its 64x128 chain of 8 levels");
Fields clamped;
clamped.base40 = 0x55ea000ull;
clamped.format = 20;
clamped.width = 1024;
clamped.height = 1024;
clamped.tileModeRaw = 0x1b;
clamped.baseLevel = 2;
clamped.lastLevel = 10;
clamped.minLod = 2u * 256u + 64u;
const auto clampedView = DecodeTextureResource(pack(clamped));
Require(clampedView.width == 256u && clampedView.mipCount == 9u && clampedView.minLod == 64u, "reading a 128-bit T# from its resident levels must move its MIN_LOD clamp with the base level");
clamped.minLod = 256u;
Require(DecodeTextureResource(pack(clamped)).minLod == 0u, "a MIN_LOD clamp below the base level must vanish when read from the resident levels");
}
void RunGuestTextureResourceTests() {
Fields base;
const auto baseWords = pack(base);
@@ -123,6 +169,15 @@ void RunGuestTextureResourceTests() {
fmask.dstSelY = fmask.dstSelZ = fmask.dstSelW = 0u;
const auto fmaskResource = DecodeTextureResource(pack(fmask));
Require(fmaskResource.format == 20u && fmaskResource.dimension == TextureDimension::k2D && fmaskResource.tileMode == TextureTileMode::kZ64KBX, "uncompressed 32-bit FMASK did not use an integer Z surface");
auto compressedFmask = fmask;
compressedFmask.metaCompress = compressedFmask.metaPipeAligned = true;
compressedFmask.metaAddr = 0x123456789aull;
const auto compressedResource = DecodeTextureResource(pack(compressedFmask));
Require(compressedResource.fmaskCmaskAddress == compressedFmask.metaAddr << 8u && compressedResource.dccAddress == 0u && compressedResource.dccPipeAligned, "compressed FMASK CMASK was interpreted as color DCC");
compressedFmask.metaPipeAligned = false;
rejectFields(compressedFmask, "FMASK CMASK metadata must be pipe aligned");
compressedFmask.metaPipeAligned = compressedFmask.writeCompress = true;
rejectFields(compressedFmask, "FMASK CMASK compression is not implemented");
Fields fmaskArray = fmask;
fmaskArray.typeRaw = 13u;
fmaskArray.depth = 2u;
@@ -620,6 +675,7 @@ void RunGuestTextureResourceTests() {
pastUntailed.maxMip = 0;
pastUntailed.baseLevel = 1;
pastUntailed.lastLevel = 1;
pastUntailed.perfMod = 4;
rejectFields(pastUntailed, "would move the surface's own");
auto untailedChain = tailView;
untailedChain.mipCount = 1;
@@ -627,6 +683,8 @@ void RunGuestTextureResourceTests() {
untailedChain.mipCount = 2;
Require(untailedAllocated == 0xff0000u && DescribeSurface(untailedChain).guestBytes == 0x1470000u, "a second level must grow a 1920x1080 64 bpp SW_64KB_R_X surface from addrlib's 0xff0000 to 0x1470000 bytes");
RunR128TextureTests();
std::array<std::uint32_t, 4> shortWords{};
reject([&] { DecodeTextureResource(shortWords); }, "8 dwords");
+64 -1
View File
@@ -5,6 +5,7 @@
#include "prx/libc/include/GuestAllocations.hpp"
#include <algorithm>
#include <array>
#include <bit>
#include <cmath>
#include <cstdio>
#include <cstdlib>
@@ -144,6 +145,7 @@ struct MeshDraw {
VkCullModeFlags cull = VK_CULL_MODE_NONE;
std::span<const std::uint32_t> code = {};
std::uint32_t stagesRegister = 0x20u;
ShaderRecompiler::ShaderVertexStageInfo vertex{};
};
bool ReadsNumWorkgroups(std::span<const std::uint32_t> words) {
@@ -176,7 +178,7 @@ void DrawMesh(AgcDriver::VulkanDevice& device, const MeshDraw& setup) {
const std::array<ShaderRecompiler::MemoryRegion, 1> geometryMemory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(std::span(code))}}};
ShaderRecompiler::RecompileRequest geometry{
{ShaderStage::Mesh, reinterpret_cast<std::uintptr_t>(code.data()), code, 0, {}},
{setup.waveSize, 0, userData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, geometryMemory},
{setup.waveSize, 0, userData, std::nullopt, std::nullopt, setup.vertex, geometryMemory},
target,
{0, 0, 0, setup.geometryPushBytes},
ShaderRecompiler::GraphicsCompileContext{0, {}, setup.mesh, std::nullopt, {setup.draw.indexAddress, setup.draw.indexCount, setup.draw.indexSize, setup.draw.instanceCount}}
@@ -207,6 +209,10 @@ void DrawMesh(AgcDriver::VulkanDevice& device, const MeshDraw& setup) {
AgcDriver::Graphics::State state{};
state.stages = {AgcDriver::Graphics::ShaderPath::Geometry, setup.stagesRegister, setup.waveSize, 64, setup.mesh, std::nullopt};
state.pointSize = setup.vertex.pointSize;
state.pointSizeMin = setup.vertex.pointSizeMin;
state.pointSizeMax = setup.vertex.pointSizeMax;
state.paClVsOutCntl = setup.vertex.paClVsOutCntl;
state.color = {reinterpret_cast<std::uintptr_t>(Pixels.data()), {Width, Height}, VK_FORMAT_R8G8B8A8_UNORM, Pixels.size(), 0xe4u};
state.colors = {state.color};
state.hasColorTarget = true;
@@ -394,6 +400,63 @@ int main() {
}
}
ClearPixels();
auto pointSubgroup = SmallSubgroup;
pointSubgroup.outputPrimitiveSize = 1u;
for (const auto pointWave : {32u, 64u}) {
ClearPixels();
DrawMesh(device, {pointSubgroup, {0, static_cast<std::uint32_t>(Ordered.size()), 0, 1, 0, false}, VertexBufferDescriptor(Ordered.data(), static_cast<std::uint32_t>(Ordered.size())), ShaderRecompiler::MeshDrawPushOffsetBytes, false, pointWave});
for (std::uint32_t triangle = 0; triangle < Triangles; ++triangle) {
const auto& position = Ordered[3u * triangle].position;
const auto x = static_cast<std::uint32_t>((position[0] + 1.0f) * 0.5f * Width);
const auto y = static_cast<std::uint32_t>((1.0f - position[1]) * 0.5f * Height);
const auto offset = (static_cast<std::size_t>(y) * Width + x) * 4u;
Require(PixelIs(offset, TriangleColor(triangle)), "mesh point missing at first exported index for primitive " + std::to_string(triangle));
Require(PixelIs(CellPixel(triangle), Background), "mesh point output filled the interior of its packed triangle");
}
}
for (const auto pointWave : {32u, 64u}) {
for (const auto size : {3.0f, 4.0f}) {
ClearPixels();
MeshDraw points{pointSubgroup, {0, static_cast<std::uint32_t>(Ordered.size()), 0, 1, 0, false}, VertexBufferDescriptor(Ordered.data(), static_cast<std::uint32_t>(Ordered.size()))};
points.waveSize = pointWave;
points.vertex.pointSize = size;
DrawMesh(device, points);
for (std::uint32_t primitive = 0; primitive < Triangles; ++primitive) {
std::uint32_t covered = 0;
for (std::size_t pixel = 0; pixel < Pixels.size(); pixel += 4u) covered += PixelIs(pixel, TriangleColor(primitive));
Require(covered == static_cast<std::uint32_t>(size * size), "mesh point did not cover its register-sized square");
}
}
for (const auto exportedSize : {6.0f, -3.0f}) {
ClearPixels();
const auto& baseCode = pointWave == 32u ? Wave32GeometryCode : GeometryCode;
std::array<std::uint32_t, GeometryCode.size() + 4u> sizedCode{};
std::copy_n(baseCode.begin(), 101u, sizedCode.begin());
sizedCode[92] = 0xbf88000eu;
sizedCode[99] = 0xf80000cfu;
sizedCode[101] = 0x7e6802ffu;
sizedCode[102] = std::bit_cast<std::uint32_t>(exportedSize);
sizedCode[103] = 0xf80008d1u;
sizedCode[104] = 0x00000034u;
std::copy(baseCode.begin() + 101u, baseCode.end(), sizedCode.begin() + 105u);
MeshDraw exported{pointSubgroup, {0, static_cast<std::uint32_t>(Ordered.size()), 0, 1, 0, false}, VertexBufferDescriptor(Ordered.data(), static_cast<std::uint32_t>(Ordered.size()))};
exported.waveSize = pointWave;
exported.code = sizedCode;
exported.vertex.paClVsOutCntl = (1u << 16u) | (1u << 21u);
exported.vertex.pointSizeMin = 3.0f;
exported.vertex.pointSizeMax = 4.0f;
DrawMesh(device, exported);
for (std::uint32_t primitive = 0; primitive < Triangles; ++primitive) {
std::uint32_t covered = 0;
for (std::size_t pixel = 0; pixel < Pixels.size(); pixel += 4u) covered += PixelIs(pixel, TriangleColor(primitive));
const auto side = exportedSize < 3.0f ? 3u : 4u;
Require(covered == side * side, "mesh point ignored its exported size or clamp");
}
}
}
ClearPixels();
auto lineSubgroup = FastLaunchSubgroup;
lineSubgroup.maxPrimitives = 2u;
@@ -0,0 +1,38 @@
#include "SceTypes.hpp"
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
extern "C" int APS5_VABI sceAgcDriverNopDataWritePacket(void* destination, uint32_t address, const void* data, uint32_t bytes);
int main() {
std::array<std::byte, 24> storage;
storage.fill(std::byte{0xaa});
const std::array<std::byte, 5> data{std::byte{0x11}, std::byte{0x22}, std::byte{0x33}, std::byte{0x44}, std::byte{0x55}};
const auto words = sceAgcDriverNopDataWritePacket(storage.data() + 4, 0x12345678, data.data(), static_cast<std::uint32_t>(data.size()));
std::uint32_t header = 0;
std::uint32_t address = 0;
std::memcpy(&header, storage.data() + 4, sizeof(header));
std::memcpy(&address, storage.data() + 8, sizeof(address));
if (words != 4 || header != 0xc0021000U || address != 0x12345678U) return 1;
if (!std::equal(data.begin(), data.end(), storage.begin() + 12)) return 2;
if (storage[17] != std::byte{0} || storage[18] != std::byte{0} || storage[19] != std::byte{0}) return 3;
if (storage[3] != std::byte{0xaa} || storage[20] != std::byte{0xaa}) return 4;
storage.fill(std::byte{0xaa});
const auto emptyWords = sceAgcDriverNopDataWritePacket(storage.data() + 4, 0x87654321, nullptr, 5);
std::memcpy(&header, storage.data() + 4, sizeof(header));
std::memcpy(&address, storage.data() + 8, sizeof(address));
if (emptyWords != 2 || header != 0xc0021000U || address != 0x87654321U) return 5;
if (storage[12] != std::byte{0} || storage[19] != std::byte{0} || storage[20] != std::byte{0xaa}) return 6;
storage.fill(std::byte{0xaa});
const auto zeroBytesWords = sceAgcDriverNopDataWritePacket(storage.data() + 4, 0x01020304, data.data(), 0);
std::memcpy(&header, storage.data() + 4, sizeof(header));
std::memcpy(&address, storage.data() + 8, sizeof(address));
if (zeroBytesWords != 2 || header != 0xc0001000U || address != 0x01020304U) return 7;
if (storage[12] != std::byte{0xaa}) return 8;
return 0;
}
@@ -4642,6 +4642,9 @@ bool unitShadowTests(const Device& device, Recorder& recorder) {
retile(*half, unit3, unit / 2, 0x22, true);
Require(AnyShadowedOverlaps(unit3, 1) && AnyShadowedOverlaps(unit4 - 1, 1) && AnyShadowedOverlaps(unit3 + 1000, 64), "a fresh unit is not seen as shadowed");
Require(!AnyShadowedOverlaps(unit3 - 1, 1) && !AnyShadowedOverlaps(unit4, unit) && !AnyShadowedOverlaps(address, 3 * unit), "a range outside the unit is seen as shadowed");
const std::array<std::pair<std::uint64_t, std::uint64_t>, 2> outside{{{unit3 - 8, unit3}, {unit4, unit4 + unit}}};
const std::array<std::pair<std::uint64_t, std::uint64_t>, 2> reaching{{{unit3 - 8, unit3}, {unit4 - 4, unit4}}};
Require(!AnyShadowedOverlaps(outside) && AnyShadowedOverlaps(reaching), "a set of ranges around the fresh unit was answered wrongly");
{
// An upload's runs over units 2..4 split at unit 3's freshness; the fresh piece reads the slab.
const std::pair<std::uint64_t, std::uint64_t> run{2 * unit, 5 * unit};
@@ -4804,11 +4807,14 @@ void idlePublishWaitTests(const Device& device, Recorder& recorder) {
recorder.Sync();
Require(words[2 * unit] == 0x44 && words[4 * unit - 1] == 0x45, "a CPU store made after the idle flush returned was overwritten by its publish");
Require(words[2 * unit + 1] == 0x22 && words[3 * unit - 1] == 0x22 && words[3 * unit] == 0x33 && words[1 * unit] == 0x11 && words[4 * unit] == 0x11, "the idle publish's bytes are wrong");
words[5 * unit] = 0x11;
CollectWritesUncached(address, bytes);
retile(address + 5 * unit, 0x55);
StorageTexture::FlushAllPending("label");
Require(recorder.PendingWriteOverlaps(address + 5 * unit, unit), "a publish of a flush other than the idle one was waited");
const bool pending = recorder.PendingWriteOverlaps(address + 5 * unit, unit);
recorder.Sync();
Require(words[5 * unit] == 0x55 && words[6 * unit - 1] == 0x55, "the label flush's publish did not land");
Require(words[5 * unit] == 0x55 && words[6 * unit - 1] == 0x55, "the label flush's publish did not land: the unit read as written after its retile, so the publish dropped it as stale");
Require(pending, "a publish of a flush other than the idle one was waited");
std::cout << "idle publish wait verified\n";
}
@@ -6417,6 +6423,9 @@ void unchangedCpuStampTests(const Device& device, Recorder& recorder) {
context.Function<PFN_vkCmdClearColorImage>("vkCmdClearColorImage")(commands, image->Image(), VK_IMAGE_LAYOUT_GENERAL, &value, 1, &range);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT);
image->MarkDirty();
const std::array<std::pair<std::uint64_t, std::uint64_t>, 2> beside{{{address - 64, address - 16}, {address + surfaceBytes, address + surfaceBytes + 64}}};
const std::array<std::pair<std::uint64_t, std::uint64_t>, 2> touching{{{address - 64, address - 16}, {address + surfaceBytes - 4, address + surfaceBytes}}};
Require(!StorageTexture::AnyPendingOverlaps(beside) && StorageTexture::AnyPendingOverlaps(touching), "(c) " + what + ": a set of ranges beside the pending image or touching its last word was answered wrongly");
for (std::size_t i = 0; i < 4096; ++i) memory[offset + i] = pattern(offset + i);
if (changed) memory[offset + 16] = static_cast<std::uint8_t>(~pattern(offset + 16));
AgcDriver::GuestMemory::CollectWritesUncached(blockAddress, bytes);
@@ -0,0 +1,19 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_TESTS_SAVEDEXECMASKLOOP_HPP
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_TESTS_SAVEDEXECMASKLOOP_HPP
#include <cstdint>
#include <vector>
namespace AgcTest {
inline std::vector<std::uint32_t> SavedExecMaskLoop(std::uint32_t rounds) {
std::vector<std::uint32_t> code{0xbea2047eu, 0xbea40380u};
for (std::uint32_t step = 0; step < rounds; ++step) code.insert(code.end(), {0xbefe0422u, 0x7c080080u, 0x8aa26a7eu});
const auto branch = 0xbf850000u | static_cast<std::uint16_t>(2 - static_cast<int>(code.size() + 3));
code.insert(code.end(), {0x80248124u, 0xbf0a8424u, branch, 0xbefe0422u});
return code;
}
}
#endif
@@ -21,9 +21,9 @@ void require(bool condition, const char* message) {
void setScreenshotDirectory(const std::filesystem::path& directory) {
#ifdef _WIN32
require(_putenv_s("ANYPS5_SCREENSHOTS", directory.string().c_str()) == 0, "set ANYPS5_SCREENSHOTS");
require(_wputenv_s(L"ANYPS5_SCREENSHOTS", directory.wstring().c_str()) == 0, "set ANYPS5_SCREENSHOTS");
#else
require(::setenv("ANYPS5_SCREENSHOTS", directory.string().c_str(), 1) == 0, "set ANYPS5_SCREENSHOTS");
require(::setenv("ANYPS5_SCREENSHOTS", directory.c_str(), 1) == 0, "set ANYPS5_SCREENSHOTS");
#endif
}
@@ -73,7 +73,7 @@ void rejectsInvalidFrames() {
int main() try {
const auto root = std::filesystem::temp_directory_path() / ("anyps5_screenshot-" + std::to_string(std::random_device{}()));
const auto directory = root / "nested";
const auto directory = root / std::filesystem::path(u8"nested-a\u00e7\u00e3o-\u65e5\u672c");
std::filesystem::remove_all(root);
setScreenshotDirectory(directory);
requestsMerge();
@@ -20,6 +20,7 @@
#include "IntermediateRepresentation/IrBuilder.hpp"
#include "IntermediateRepresentation/IrProgram.hpp"
#include "SpirvBackend/SpirvAnalysis.hpp"
#include "SavedExecMaskLoop.hpp"
#if ANYPS5_ENABLE_SPIRV_TOOLS
#include "SpirvBackend/SpirvOptimizer.hpp"
#endif
@@ -4088,6 +4089,18 @@ void verifyHalfWaveReduction() {
{0u, 0x38000000u, 0x88000000u, spv::OpGroupNonUniformBitwiseOr, "half-wave reduction: the wave64 OR scan did not read lane 31 as a subgroup OR on 32 lanes"},
}};
for (const auto& reduction : scans) require(reductions(pixel(scan(reduction.identity, reduction.vector, reduction.scalar), 32u, true), reduction.reduce) == 1u, reduction.message);
auto loopScan = scan(0xffffffffu, 0x26000000u, 0x83800000u);
const auto savedMaskLoop = AgcTest::SavedExecMaskLoop(8u);
loopScan.insert(loopScan.begin(), savedMaskLoop.begin(), savedMaskLoop.end());
auto helperLoop = loopScan;
helperLoop[0] = 0xbea204c1u;
expectFailure([&] { static_cast<void>(pixel(helperLoop, 32u, true)); }, "v_readlane_b32 of lane 63 is outside the 32-lane host subgroup", "half-wave reduction: a loop initialized with helper lanes was proven to exclude them");
auto upperHelperLoop = loopScan;
upperHelperLoop[0] = 0xbea2037eu;
upperHelperLoop.insert(upperHelperLoop.begin() + 1, 0xbea303c1u);
expectFailure([&] { static_cast<void>(pixel(upperHelperLoop, 32u, true)); }, "v_readlane_b32 of lane 63 is outside the 32-lane host subgroup", "half-wave reduction: the low-word loop proof was reused for helper-inclusive upper lanes");
require(reductions(pixel(loopScan, 32u, true), spv::OpGroupNonUniformUMin) == 1u, "half-wave reduction: a loop-carried saved EXEC mask exhausted the entry-lane proof on 32 lanes");
require(halves(pixel(loopScan, 64u, true), spv::OpGroupNonUniformUMin, 0xffffffffu), "half-wave reduction: a loop-carried saved EXEC mask did not preserve the two half-wave UMin reductions");
auto comparedScan = scan(0u, 0x38000000u, 0x88000000u);
*std::find(comparedScan.begin(), comparedScan.end(), 0xbe98047eu) = 0x8a986a7eu;
comparedScan.insert(comparedScan.begin(), 0x7c080080u);
@@ -4500,13 +4513,15 @@ void verifyMeshConfiguration() {
RecompileCacheKey::Build(other, key);
require(key != first && RecompileCacheKey::ContextHash(request) != RecompileCacheKey::ContextHash(other), "the cache keys ignore the mesh configuration");
require(mesh.outputPrimitiveSize == 3u && replay.request.graphics->mesh->outputPrimitiveSize == 3u, "a mesh configuration does not output triangles by default");
otherMesh = mesh;
otherMesh.outputPrimitiveSize = 2u;
other.graphics = GraphicsCompileContext{0u, {}, otherMesh, std::nullopt, {}};
const auto lineReplay = RequestSerializer{}.Deserialize(RequestSerializer{}.Serialize(other));
require(lineReplay.request.graphics.has_value() && lineReplay.request.graphics->mesh.has_value() && lineReplay.request.graphics->mesh->outputPrimitiveSize == 2u, "the mesh output primitive size was lost in serialization");
RecompileCacheKey::Build(other, key);
require(key != first && RecompileCacheKey::ContextHash(request) != RecompileCacheKey::ContextHash(other), "the cache keys ignore the mesh output primitive size");
for (const auto primitiveSize : {1u, 2u}) {
otherMesh = mesh;
otherMesh.outputPrimitiveSize = primitiveSize;
other.graphics = GraphicsCompileContext{0u, {}, otherMesh, std::nullopt, {}};
const auto primitiveReplay = RequestSerializer{}.Deserialize(RequestSerializer{}.Serialize(other));
require(primitiveReplay.request.graphics.has_value() && primitiveReplay.request.graphics->mesh.has_value() && primitiveReplay.request.graphics->mesh->outputPrimitiveSize == primitiveSize, "the mesh output primitive size was lost in serialization");
RecompileCacheKey::Build(other, key);
require(key != first && RecompileCacheKey::ContextHash(request) != RecompileCacheKey::ContextHash(other), "the cache keys ignore the mesh output primitive size");
}
RecompileRequest hull{};
hull.shader = {ShaderStage::TessellationControl, 0x10000u, code, 0, {}};
hull.context.waveSize = 64;
@@ -4883,7 +4898,7 @@ void verifyPixelRequestSerialization() {
minimal.context.pixel->layerExported = true;
minimal.context.pixel->ditheredAlphaToCoverage = true;
const auto encoded = serializer.Serialize(minimal);
require(requestPrefix(encoded, 8u) == "NVNQQSoAAAA=", "new requests did not use serialization version 42");
require(requestPrefix(encoded, 8u) == "NVNQQSsAAAA=", "new requests did not use serialization version 43");
const std::array<std::uint32_t, 2> fallbacks{0x40u, 0x1ac4u};
auto withFallbacks = minimal;
withFallbacks.context.linkedCallFallbacks = fallbacks;
@@ -5001,7 +5016,7 @@ void verifyPixelRequestSerialization() {
for (std::size_t bytes = 0; bytes < 45u; ++bytes) {
expectFailure([&] { static_cast<void>(serializer.Deserialize(requestPrefix(encoded, mappingOffset + bytes))); }, "truncated data", "a truncated pixel mapping, packing, dual-source, alpha-to-coverage, stencil reference export flag, primitive class, layer export, dither or front-face flag, quad pixel mask or quad sample mask was accepted");
}
for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQSsAAAA="}) {
for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQSwAAAA="}) {
expectFailure([&] { static_cast<void>(serializer.Deserialize(unsupported)); }, "serialization version", "an unsupported request version was accepted");
}
static constexpr std::string_view version18Request{
@@ -5290,15 +5305,16 @@ void verifyDepthRemapRequests() {
const auto replay = serializer.Deserialize(remapped);
require(replay.request.target.depthRangeRemap && replay.request.context.vertex.has_value() && replay.request.context.vertex->paClVsOutCntl == 0x89abcdefu, "the depth remap target flag or the vertex info did not round-trip");
require(replay.request.context.vertex->depthRemapMode == 2u, "the depth remap mode did not round-trip");
require(serializer.Serialize(replay.request) == remapped, "a version 35 depth remap request changed on re-serialization");
require(serializer.Serialize(replay.request) == remapped, "the depth remap request changed on re-serialization");
const auto plainBytes = decodeBase64(plain);
const auto remappedBytes = decodeBase64(remapped);
require(plainBytes.size() == remappedBytes.size() && plainBytes.size() > 5u && std::equal(plainBytes.begin(), plainBytes.end() - 7, remappedBytes.begin()), "the depth remap flag and mode are not the 6 bytes before the f32 flush and denormal preserve flags of a vertex request");
constexpr std::size_t pointTailBytes = 13u;
require(plainBytes.size() == remappedBytes.size() && plainBytes.size() > 7u + pointTailBytes && std::equal(plainBytes.begin(), plainBytes.end() - 7 - pointTailBytes, remappedBytes.begin()) && std::equal(plainBytes.end() - pointTailBytes, plainBytes.end(), remappedBytes.end() - pointTailBytes), "the depth remap flag and mode are not the 6 bytes before the f32 flush and denormal preserve flags and the point tail of a vertex request");
for (const std::uint8_t legacyVersion : {32u, 34u}) {
auto legacyBytes = remappedBytes;
legacyBytes.pop_back();
legacyBytes[4] = legacyVersion;
legacyBytes.resize(legacyBytes.size() - 6u);
legacyBytes.resize(legacyBytes.size() - 6u - pointTailBytes);
const auto legacy = serializer.Deserialize(encodeBase64(legacyBytes));
require(!legacy.request.target.depthRangeRemap && legacy.request.context.vertex.has_value() && legacy.request.context.vertex->depthRemapMode == 0u, ("a version " + std::to_string(legacyVersion) + " vertex request read depth remap fields").c_str());
require(serializer.Serialize(legacy.request) == plain, ("a version " + std::to_string(legacyVersion) + " vertex request misread the fields before the depth remap").c_str());
@@ -5306,10 +5322,10 @@ void verifyDepthRemapRequests() {
auto version35 = remappedBytes;
version35.pop_back();
version35[4] = 35u;
version35.pop_back();
version35.resize(version35.size() - 1u - pointTailBytes);
const auto replay35 = serializer.Deserialize(encodeBase64(version35));
require(replay35.request.target.depthRangeRemap && replay35.request.context.vertex->depthRemapMode == 2u && !replay35.request.target.float32FlushToZero && serializer.Serialize(replay35.request) == remapped, "a version 35 request misread the depth remap fields or read an f32 flush flag");
auto truncated = remappedBytes;
auto truncated = version35;
truncated.resize(truncated.size() - 2u);
expectFailure([&] { static_cast<void>(serializer.Deserialize(encodeBase64(truncated))); }, "truncated data", "a truncated depth remap mode was accepted");
auto trailing = remappedBytes;
@@ -5350,9 +5366,12 @@ void verifyMergedHullConfiguration() {
const auto replay = serializer.Deserialize(merged);
require(replay.request.graphics.has_value() && replay.request.graphics->tessellation.has_value() && replay.request.graphics->tessellation->mergedHull, "a merged hull configuration was lost in serialization");
require(!serializer.Deserialize(separate).request.graphics->tessellation->mergedHull, "a separate hull configuration was read as merged");
constexpr std::size_t pointTailBytes = 13u;
auto legacy = decodeBase64(merged);
require(legacy.size() > 53u + pointTailBytes && legacy[4] == 43u, "a merged hull request did not use serialization version 43");
legacy.resize(legacy.size() - pointTailBytes);
legacy.pop_back();
require(legacy.size() > 52u && legacy[legacy.size() - 52u] == 1u, "the merged hull flag is not the last byte of the tessellation configuration");
require(legacy[legacy.size() - 52u] == 1u, "the merged hull flag is not the last byte of the tessellation configuration");
legacy.erase(legacy.end() - 52);
for (const auto version : {30u, 31u, 32u, 34u, 35u, 36u, 37u, 38u}) {
auto older = legacy;
@@ -7587,6 +7606,24 @@ void verifyDynamicStorageMipChain() {
require(ResourceMaterializer::TryRuntimeImageMode(image, allLevels, modes).mode.has_value(), "a dynamic-mip storage image with sixteen levels was rejected");
}
void verifyArrayVolumeStoreMode() {
using namespace ShaderRecompiler;
const DescriptorValue descriptor{{0x11800100u, 0xc3800000u, 0x0003c003u, 0xd0900facu, 0u, 0x00700000u, 0u, 0u}, 8u};
ImageResource store{};
store.resourceClass = ImageResourceClass::Storage;
store.dimension = RdnaImageDimension::Dim3D;
store.written = true;
store.fmaskCompatible = false;
const auto modes = ResourceMaterializer::RuntimeImageModes(store);
require(modes[ResourceMaterializer::RuntimeImageMode(store, descriptor, modes)].dimension == RdnaImageDimension::Dim2DArray, "3D image store on a 2D-array T# did not select an array runtime mode");
store.read = true;
expectFailure([&] { static_cast<void>(ResourceMaterializer::RuntimeImageMode(store, descriptor, ResourceMaterializer::RuntimeImageModes(store))); }, "incompatible with the static runtime image interface", "3D image load and store on a 2D-array T# was accepted");
store.read = false;
store.atomic = true;
const DescriptorValue uintDescriptor{{0x11800100u, 0xc1400000u, 0x0003c003u, 0xd0900facu, 0u, 0x00700000u, 0u, 0u}, 8u};
expectFailure([&] { static_cast<void>(ResourceMaterializer::RuntimeImageMode(store, uintDescriptor, ResourceMaterializer::RuntimeImageModes(store))); }, "incompatible with the static runtime image interface", "3D image atomic on a 2D-array T# was accepted");
}
void verifySrgbDepthCompareModes() {
using namespace ShaderRecompiler;
for (const auto decodeFormats : {0u, 1u, 2u, 3u}) {
@@ -7761,6 +7798,7 @@ int main(int argc, char** argv) {
verifyFmaskImageMode();
verifyCubeDepthCompareMode();
verifyVolumeArrayLoadMode();
verifyArrayVolumeStoreMode();
verifyVolumeBiasTableRejection();
verifyDynamicStorageMipChain();
verifySrgbDepthCompareModes();
@@ -1,11 +1,16 @@
#include "IntermediateRepresentation/IrBuilder.hpp"
#include "IntermediateRepresentation/IrProgram.hpp"
#include "Optimization/ShaderStageInputInfo.hpp"
#include "Optimization/TessellationLowering.hpp"
#include "SpirvBackend/SpirvEmitter.hpp"
#include <spirv/unified1/spirv.hpp>
#include <cstdint>
#include <cstdio>
#include <exception>
#include <functional>
#include <stdexcept>
#include <string>
#include <unordered_map>
using namespace ShaderRecompiler;
@@ -135,6 +140,52 @@ bool RefusedBecause(IrProgram& program, const char* reason) {
return !outcome.lowered && outcome.reason.find(reason) != std::string::npos;
}
std::uint32_t EmittedEvaluationControlPoint(std::uint32_t address) {
constexpr std::uint32_t ControlStride = 16u;
IrProgram program;
IrBuilder builder{program};
program.SetWaveSize(64);
program.Resources().stage = IrShaderStage::TessellationEvaluation;
program.Resources().srtPlanComplete = true;
program.Resources().resourceTrackingComplete = true;
program.Metadata().shaderInfoComplete = true;
program.Metadata().bindingLayoutComplete = true;
program.Metadata().tessellationControlStride = ControlStride;
auto& block = program.CreateBlock();
program.SetEntryBlock(block);
program.BlockOrder().push_back(&block);
BlockInfo info;
info.id = block.Id();
program.Metadata().blockInfo.push_back(info);
builder.SetInsertionPoint(block);
auto& read = builder.Emit(IrOpcode::GetTessellationAttribute, IrType::U32, {&builder.Constant(static_cast<std::uint32_t>(TessellationAttribute::EvaluationInput)), &builder.Constant(address), &builder.ConstantBool(true)});
static_cast<void>(builder.Emit(IrOpcode::ReferenceU32, IrType::Void, {&read}));
ShaderVertexInputInfo vertex;
vertex.tess.inputControlPoints = InputControlPoints;
vertex.tess.outputControlPoints = InputControlPoints;
vertex.tess.domain = 1u;
vertex.tess.partitioning = 2u;
vertex.tess.outputTopology = 2u;
ShaderStageInputInfo inputs;
inputs.vertex = &vertex;
CompiledBindingLayout bindings;
bindings.layout = program.Metadata().bindings;
SpirvTargetOptions target{};
target.vulkanVersion = 0x00401000;
target.spirvVersion = 0x00010300;
target.subgroupSize = 64;
const auto words = SpirvEmitter().Emit(program, inputs, bindings, target);
std::unordered_map<std::uint32_t, std::uint32_t> constants;
for (std::size_t at = 5; at < words.size(); at += words[at] >> 16u) {
const auto count = words[at] >> 16u;
if (count == 0u || at + count > words.size()) throw std::runtime_error("the domain program compiled to a malformed SPIR-V instruction");
const auto opcode = words[at] & 0xffffu;
if (opcode == spv::OpConstant && count == 4u) constants[words[at + 2u]] = words[at + 3u];
if (opcode == spv::OpAccessChain && count == 7u) return constants.at(words[at + 4u]);
}
throw std::runtime_error("the domain program reads no control point attribute");
}
bool run(const char* name, const std::function<bool()>& body) {
bool passed = false;
try {
@@ -206,5 +257,9 @@ int main() {
return patch->Opcode() == IrOpcode::IMul32 && patch->Argument(1)->Resolve()->ImmediateU32() == PatchStride;
});
passed &= run("a domain read at an immediate address past the last control point reads the last control point", [] {
return EmittedEvaluationControlPoint(InputControlPoints * 16u) == InputControlPoints - 1u;
});
return passed ? 0 : 1;
}
@@ -143,6 +143,25 @@ void repackedFormatTests() {
Require(TextureComponentChannel(guest, VK_COMPONENT_SWIZZLE_A) == VK_COMPONENT_SWIZZLE_A && TextureComponentChannel(guest, VK_COMPONENT_SWIZZLE_ZERO) == VK_COMPONENT_SWIZZLE_ZERO, "format 43 keeps alpha and constant selectors");
}
void gcnBufferFormatTests() {
using ShaderRecompiler::IrBufferFormat;
const auto& formats = ShaderRecompiler::GcnBufferFormats();
const auto gcn = [&](std::uint32_t data, std::uint32_t number) { return static_cast<IrBufferFormat>(formats[(data << 3u) | number]); };
std::array<std::uint32_t, 78> seen{};
for (const auto format : formats) ++seen[format];
for (std::uint32_t format = 1; format < seen.size(); ++format) Require(seen[format] == 1u, "unified buffer format " + std::to_string(format) + " must come from exactly one GCN format pair");
Require(gcn(0u, 4u) == IrBufferFormat::Invalid && gcn(15u, 7u) == IrBufferFormat::Invalid, "GCN DATA_FORMAT 0 and 15 have no buffer form");
Require(gcn(1u, 7u) == IrBufferFormat::Invalid && gcn(4u, 0u) == IrBufferFormat::Invalid, "8-bit float and 32-bit UNORM have no buffer form");
Require(gcn(1u, 0u) == IrBufferFormat::Format8UNorm && gcn(2u, 7u) == IrBufferFormat::Format16Float, "8 and 16-bit pairs must map");
Require(gcn(4u, 4u) == IrBufferFormat::Format32UInt && gcn(4u, 7u) == IrBufferFormat::Format32Float, "32-bit pairs must map");
Require(gcn(6u, 7u) == IrBufferFormat::Format11_11_10Float && gcn(7u, 7u) == IrBufferFormat::Format10_11_11Float, "GCN 10_11_11 and 11_11_10 must map by bit layout");
Require(gcn(8u, 0u) == IrBufferFormat::Format2_10_10_10UNorm && gcn(9u, 0u) == IrBufferFormat::Format10_10_10_2UNorm, "GCN 10_10_10_2 and 2_10_10_10 must map by bit layout");
Require(gcn(10u, 0u) == IrBufferFormat::Format8_8_8_8UNorm && gcn(14u, 7u) == IrBufferFormat::Format32_32_32_32Float, "four-channel pairs must map");
const std::uint32_t word3 = 0x00000facu | (7u << 12u) | (14u << 15u) | (7u << 27u);
Require(ShaderRecompiler::GcnBufferWord3(16u << 16u, word3) == (0x00000facu | (77u << 12u) | (1u << 28u)), "a strided GCN V# must check its index range");
Require(ShaderRecompiler::GcnBufferWord3(0u, word3) == (0x00000facu | (77u << 12u) | (3u << 28u)), "a GCN V# without a stride must check its byte range");
}
void convertedDccClearTests() {
alignas(64) std::array<std::uint8_t, 16> keys{};
GuestTextureResource resource{};
@@ -268,4 +287,5 @@ void RunTextureFormatTests() {
convertedDccClearTests();
singleDccKeysTests();
packedFloatDccClearTests();
gcnBufferFormatTests();
}
@@ -0,0 +1,10 @@
#include "SceTypes.hpp"
extern "C" void* APS5_VABI sceAgcDriverGetCoredumpAddress();
extern "C" int APS5_VABI sceAgcDriverSetTargetRingForDiag();
int main() {
if (sceAgcDriverGetCoredumpAddress() != nullptr) return 1;
if (sceAgcDriverSetTargetRingForDiag() != static_cast<int>(0x8A6D0001)) return 2;
return 0;
}
@@ -174,6 +174,21 @@ void CheckSharedBlock() {
if (!Watched(outside, unwatched.size())) Require(StoredOver(outside, unwatched.size(), TrackerGeneration()), "an unwatched range reads as not stored over");
}
void CheckStoredOverUsesPageEvidence() {
constexpr std::size_t Page = 4096;
auto* memory = static_cast<std::uint8_t*>(AllocateWatched(2 * Block));
const auto base = reinterpret_cast<std::uint64_t>(memory);
std::memset(memory, 0x11, 2 * Block);
const auto before = CollectWritesUncached(base, 2 * Block);
Require(before != 0, "the stored-over page fixture was not collected");
static_cast<volatile std::uint8_t*>(memory)[0] = 0x22;
const auto after = CollectWritesUncached(base, Block);
Require(after > before, "the page-local CPU write was not collected");
Require(StoredOver(base, Page, before), "a collected CPU write on a page was not reported as stored over");
Require(!StoredOver(base + Page, Page, before), "a page-local CPU write made an untouched page in the same block count as stored over");
}
void CheckStoredAllSince() {
constexpr std::size_t bytes = 4 * Block;
auto* memory = static_cast<std::uint8_t*>(AllocateWatched(bytes));
@@ -217,6 +232,39 @@ void CheckStoredAllSince() {
MarkWritten(base, 64);
Require(StoredAllSince_nid_no_patch(base, 64, before), "a complete non-block-aligned range store is absent");
before = TrackerGeneration();
MarkPossiblyWritten(base + 2048, 16);
Require(StoredOver(base + 2048, 16, before), "a possible driver write did not invalidate its exact range");
Require(!StoredOver(base + 2064, 16, before), "a possible driver write invalidated an adjacent range");
Require(!UnchangedSince(base + 2048, 16, before), "a possible driver write left its exact range unchanged");
Require(UnchangedSince(base + 2064, 16, before), "a possible driver write changed an adjacent range");
Require(!StoredAllSince_nid_no_patch(base + 2048, 16, before), "a possible driver write proved complete byte coverage");
for (unsigned repeat = 0; repeat < 6; ++repeat) MarkPossiblyWritten(base + 2048, 16);
Require(StoredOver(base + 2048, 16, before), "repeated possible writes lost their overlap evidence");
Require(!StoredOver(base + 2064, 16, before), "repeated possible writes invalidated an adjacent range");
Require(!StoredAllSince_nid_no_patch(base + 2048, 16, before), "repeated possible writes proved complete byte coverage");
before = TrackerGeneration();
constexpr unsigned PossibleIntervals = 8;
auto beforeNewest = before;
for (unsigned interval = 0; interval < PossibleIntervals; ++interval) {
beforeNewest = TrackerGeneration();
MarkPossiblyWritten(base + 4096 + static_cast<std::uint64_t>(interval) * 32, 16);
}
Require(StoredOver(base + 4096, 16, before), "an evicted possible-write interval was forgotten instead of marking its block");
Require(StoredOver(base + 4096 + 16, 16, before), "an evicted possible write did not mark the rest of its block");
Require(StoredOver(base + 4096 + (PossibleIntervals - 1) * 32, 16, beforeNewest), "the newest possible-write interval was evicted");
const auto beforeRecord = TrackerGeneration();
MarkPossiblyWritten(base + 4096, 16);
Require(StoredOver(base + 4096, 16, beforeRecord), "a possible-write interval was not retained after being re-recorded");
Require(!StoredAllSince_nid_no_patch(base + 4096, 16, before), "possible-write eviction or re-recording proved complete byte coverage");
before = TrackerGeneration();
MarkWritten(base + 2560, 16);
MarkPossiblyWritten(base, Block);
Require(StoredAllSince_nid_no_patch(base + 2560, 16, before), "a possible whole-block range erased an exact partial-store proof");
Require(!StoredAllSince_nid_no_patch(base, Block, before), "a possible whole-block range proved complete block coverage");
before = TrackerGeneration();
MarkWritten(base + 512, 16);
MarkWritten(base + 544, 16);
@@ -348,6 +396,42 @@ void CheckSharedBlockProofs() {
Require(!UnchangedSince(base + Block + 14 * page + 0x800, 16, beforeNeighbour), "a range in the page an own store dirtied reads as unchanged");
}
void CheckRepeatedPossibleStores() {
void* memory = AllocateWatched(3 * Block);
const auto base = reinterpret_cast<std::uint64_t>(memory);
const auto boundary = base + 2 * Block - 0x9000;
std::memset(memory, 0x11, 3 * Block);
const auto synced = CollectWrites(base, 3 * Block);
Require(synced != 0, "the test block is not collected");
const auto exact = TrackerGeneration();
MarkWritten(base + Block, 0x100);
for (std::uint64_t store = 0; store < 5; ++store) MarkPossiblyWritten(boundary + store * 0x1000, 0x100);
Require(StoredAllSince_nid_no_patch(base + Block, 0x100, exact), "possible writes beyond the ring forgot an exact store's coverage");
void* fresh = AllocateWatched(2 * Block);
const auto freshBase = reinterpret_cast<std::uint64_t>(fresh);
std::memset(fresh, 0x11, 2 * Block);
const auto freshSynced = CollectWrites(freshBase, 2 * Block);
const auto neighbour = freshBase + Block - 0x9000;
MarkPossiblyWritten(neighbour, 0x100);
const auto secondStored = MarkPossiblyWritten(neighbour + 0x1000, 0x100);
const auto thirdStored = MarkPossiblyWritten(neighbour + 0x2000, 0x100);
MarkPossiblyWritten(neighbour + 0x3000, 0x100);
const auto settled = TrackerGeneration();
MarkPossiblyWritten(neighbour, 0x100);
MarkPossiblyWritten(neighbour, 0x100);
MarkPossiblyWritten(neighbour + 0x5000, 0x100);
Require(!StoredOver(freshBase, static_cast<std::size_t>(neighbour - freshBase), secondStored), "a full possible ring evicted a newer piece instead of its oldest");
Require(StoredOver(freshBase, static_cast<std::size_t>(neighbour - freshBase), freshSynced), "an evicted possible write is not taken as a store over the rest of the block");
const auto partial = TrackerGeneration();
MarkPossiblyWritten(neighbour + 0x5080, 0x100);
Require(StoredOver(neighbour + 0x5000, 0x10, settled) && StoredOver(neighbour + 0x5100, 0x10, partial), "a possible write that overlaps an earlier piece without containing it replaced it");
Require(!StoredOver(freshBase, static_cast<std::size_t>(neighbour - freshBase), thirdStored), "a possible write that overlaps without containing evicted a newer piece instead of the oldest");
}
void CheckOwnStore() {
void* memory = AllocateWatched(2 * Block);
const auto base = reinterpret_cast<std::uint64_t>(memory);
@@ -1450,8 +1534,10 @@ int main() {
}
#endif
CheckSharedBlock();
CheckStoredOverUsesPageEvidence();
CheckStoredAllSince();
CheckSharedBlockProofs();
CheckRepeatedPossibleStores();
CheckOwnStore();
CheckUnwatch();
CheckNewestStamp();
@@ -177,6 +177,21 @@ void UnreadUserWordsKeepTheStage(bool verify) {
Require(counters.dataHits == moved.dataHits + 1, "a draw that pointed the pixel stage at another buffer descriptor was not a data-only hit: " + Counts(counters));
Require(counters.dataStagesCompiled - moved.dataStagesCompiled >= 1, "a draw that pointed the pixel stage at another buffer descriptor reused the pixel stage: " + Counts(counters));
if (!verify) Require(counters.dataStagesReused - moved.dataStagesReused == 1, "a draw that changed only the pixel stage's descriptor pointer did not reuse the vertex stage: " + Counts(counters));
const bool refresh = std::getenv("APS5_DRAW_PIPELINE") != nullptr;
for (const std::uint32_t unread : {0x33u, 0x44u}) {
commands.clear();
PixelUserData(commands, second, unread);
Append(commands, 0x2d, {3, 2});
const auto last = counters;
counters = Submit(std::move(commands));
Require(counters.dataHits == last.dataHits + 1 && counters.inserts == last.inserts, "a draw at the moved pointer with a new unread word: " + Counts(counters));
if (verify) continue;
const auto compiled = counters.dataStagesCompiled - last.dataStagesCompiled;
const bool expectReuse = refresh && unread == 0x44u;
Require(compiled == (expectReuse ? 0u : 1u), std::string(expectReuse ? "after a refresh, the draw at the moved pointer compiled its pixel stage again: " : "the draw at the moved pointer did not compile its pixel stage: ") + Counts(counters));
Require(counters.shapeUpdates - last.shapeUpdates == (refresh && unread == 0x33u ? 1u : 0u), "shape refreshes: " + std::to_string(counters.shapeUpdates - last.shapeUpdates) + " (" + Counts(counters) + ")");
}
}
unsigned BrightestColorByte() {
@@ -11,35 +11,46 @@ int main(int argc, char** argv) {
try {
using namespace AgcDriver;
using DriverDetail::DrawPipeline;
using DriverDetail::DrawFinisher;
if (DrawPipeline::Depth() == 0) return 77;
const bool disabled = argc > 1 && std::string_view(argv[1]) == "disabled";
const auto mode = argc > 1 ? std::string_view(argv[1]) : std::string_view{};
const bool disabled = mode == "disabled" || mode == "finisher-disabled";
const bool finisher = mode.starts_with("finisher");
const char* worker = finisher ? "draw finisher" : "draw committer";
if (finisher && !DrawFinisher::Enabled()) throw std::runtime_error("draw finisher is disabled");
if (PerformanceTrace::Configured() == disabled) throw std::runtime_error("unexpected trace configuration");
if (!disabled) PerformanceTrace::Present(1, 1, nullptr);
bool checked = false;
const char* failure = nullptr;
DrawPipeline::Queue0().Enqueue([&] {
const auto checkWorker = [&] {
auto* trace = PerformanceTrace::Thread();
if (disabled) {
if (trace != nullptr) { failure = "unconfigured draw committer allocated a trace buffer"; return; }
if (trace != nullptr) { failure = "unconfigured draw worker allocated a trace buffer"; return; }
checked = true;
return;
}
if (trace == nullptr) { failure = "draw committer CPU spans are absent from the trace"; return; }
if (trace == nullptr) { failure = "draw worker CPU spans are absent from the trace"; return; }
{
PerformanceTimer timer("DrawPipeline.TraceRegression");
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
const auto snapshot = trace->Collect();
if (snapshot.name != "draw committer" || snapshot.dropped) { failure = "draw committer trace identity or capacity is incorrect"; return; }
if (snapshot.name != worker || snapshot.dropped) { failure = "draw worker trace identity or capacity is incorrect"; return; }
const auto found = [](const auto& event) { return event.scope != nullptr && std::string_view(event.scope) == "DrawPipeline.TraceRegression" && event.stage == nullptr && event.length > std::chrono::steady_clock::duration::zero(); };
if (std::none_of(snapshot.slices.begin(), snapshot.slices.end(), found) || std::none_of(snapshot.totals.begin(), snapshot.totals.end(), found))
{ failure = "committed work was missing from trace slices or totals"; return; }
{ failure = "draw work was missing from trace slices or totals"; return; }
checked = true;
}, {});
DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Submission);
};
if (finisher) {
DrawFinisher::Get().Enqueue(checkWorker);
DrawFinisher::Get().Drain();
} else {
DrawPipeline::Queue0().Enqueue(checkWorker, {});
DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Submission);
}
if (failure != nullptr) throw std::runtime_error(failure);
if (!checked) throw std::runtime_error("draw committer did not run the trace check");
std::cout << "Draw committer tracing checked\n";
if (!checked) throw std::runtime_error("draw worker did not run the trace check");
std::cout << worker << " tracing checked\n";
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
@@ -6,6 +6,7 @@
#include <bit>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <initializer_list>
#include <iostream>
@@ -92,6 +93,7 @@ void NamesShaderAndDescriptor() {
Require(message.find("buffer descriptor uses an unsupported type") != std::string::npos, "draw failed for another reason: " + message);
Require(message.find(shader) != std::string::npos, std::string("draw error does not name ") + shader + ": " + message);
Require(message.find(words) != std::string::npos, std::string("draw error does not name ") + words + ": " + message);
if (std::getenv("APS5_DRAW_PIPELINE") != nullptr) Require(message.find("draw at submission ") != std::string::npos && message.find("(finished on the draw finisher)") != std::string::npos, "a draw finished on the draw finisher does not name its submission and offset: " + message);
return;
}
throw std::runtime_error("a pixel shader read a buffer through a descriptor of type 2");
@@ -0,0 +1,153 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp"
#include "VulkanTestDevice.hpp"
#include <algorithm>
#include <array>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <initializer_list>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
namespace {
using AgcDriver::Graphics::Require;
alignas(256) constexpr std::array<std::uint32_t, 16> VertexCode{
0x7e000d05u, 0x080200f4u, 0x10020300u, 0x100202f4u, 0x060202f3u, 0x060400f3u, 0x10040500u, 0x060404f3u,
0x7e060280u, 0x7e0802f2u, 0xf80008cfu, 0x04030201u, 0xbf810000u,
};
alignas(256) constexpr std::array<std::uint32_t, 10> PixelCode{0xf4000100u, 0xfa000000u, 0xbf8cc07fu, 0x7e000204u, 0x06000002u, 0x7e020280u, 0xf800180fu, 0x00010100u, 0xbf810000u, 0xbf810000u};
alignas(256) std::array<float, 4> PixelConstant{};
alignas(256) std::array<std::byte, 1024> ColorMemory{};
constexpr std::uint32_t Labels = 8;
alignas(256) std::array<std::uint32_t, Labels> LabelMemory{};
struct Header {
Shader shader{};
ShaderUserData userData{};
};
alignas(8) Header VertexHeader{};
alignas(8) Header PixelHeader{};
void Registered(Header& header, const std::uint32_t* code, std::size_t bytes, std::uint8_t type) {
header.shader.file_header = 0x34333231u;
header.shader.version = 0x18u;
header.shader.header_size = sizeof(Header);
header.shader.shader_size = static_cast<std::uint32_t>(bytes);
header.shader.code = code;
header.shader.type = type;
header.shader.user_data = &header.userData;
AgcDriverRegisterShader_nid_postfix(&header.shader);
}
void Append(std::vector<std::uint32_t>& commands, std::uint32_t opcode, std::initializer_list<std::uint32_t> payload) {
commands.push_back(0xc0000000u | (static_cast<std::uint32_t>(payload.size() - 1) << 16u) | (opcode << 8u));
commands.insert(commands.end(), payload);
}
std::vector<std::uint32_t> Setup() {
const auto color = reinterpret_cast<std::uintptr_t>(ColorMemory.data());
const auto vertex = reinterpret_cast<std::uintptr_t>(VertexCode.data());
const auto pixel = reinterpret_cast<std::uintptr_t>(PixelCode.data());
const std::vector<std::pair<std::uint32_t, std::uint32_t>> context{
{0x2d5, 0x2000},
{0x1b6, 0}, {0x207, 0}, {0x200, 0}, {0x203, 0x800},
{0x2dc, 0xaa00}, {0x2f8, 0}, {0x292, 2}, {0x293, 0},
{0x80, 0}, {0x8d, 0}, {0x83, 0xffff}, {0x8c, 0xa},
{0x2f9, 0x2d}, {0x313, 0x6000}, {0x30e, 0xffffffff}, {0x30f, 0xffffffff},
{0x206, 0x43f}, {0x204, 0x80000}, {0x205, 0x240},
{0x8e, 0xf}, {0x8f, 0xf}, {0x202, 0xcc0010},
{0x1c4, 0}, {0x1c5, 9}, {0x1c3, 4}, {0x31c, 0x28028},
{0x31b, 0}, {0x31d, 0}, {0x3b0, (63u << 14u) | 3u},
{0x3b8, 0x9000000}, {0x1e0, 0},
{0xc, 0}, {0xd, 0x40040},
{0x81, 0x80000000}, {0x82, 0x40040},
{0x90, 0x80000000}, {0x91, 0x40040},
{0x94, 0x80000000}, {0x95, 0x40040},
{0x318, static_cast<std::uint32_t>(color >> 8u)}, {0x390, static_cast<std::uint32_t>(color >> 40u)},
{0x10f, std::bit_cast<std::uint32_t>(32.0f)}, {0x110, std::bit_cast<std::uint32_t>(32.0f)},
{0x111, std::bit_cast<std::uint32_t>(-2.0f)}, {0x112, std::bit_cast<std::uint32_t>(2.0f)},
{0x113, std::bit_cast<std::uint32_t>(1.0f)}, {0x114, 0},
{0xb4, 0}, {0xb5, std::bit_cast<std::uint32_t>(1.0f)},
{0x2fe, 0}, {0x302, 0}, {0x306, 0}, {0x30a, 0},
};
const std::vector<std::pair<std::uint32_t, std::uint32_t>> shader{
{0xc8, static_cast<std::uint32_t>(vertex >> 8u)}, {0xc9, static_cast<std::uint32_t>(vertex >> 40u)}, {0x8b, 0}, {0x8c, 0},
{0x008, static_cast<std::uint32_t>(pixel >> 8u)}, {0x009, static_cast<std::uint32_t>(pixel >> 40u)}, {0x00b, 3u << 1u},
};
std::vector<std::uint32_t> commands;
Append(commands, 0x79, {0x242, 4});
for (const auto& [offset, value] : context) Append(commands, 0x69, {offset, value});
for (const auto& [offset, value] : shader) Append(commands, 0x76, {offset, value});
const auto table = reinterpret_cast<std::uintptr_t>(PixelConstant.data());
Append(commands, 0x76, {0x00c, static_cast<std::uint32_t>(table)});
Append(commands, 0x76, {0x00d, static_cast<std::uint32_t>(table >> 32u)});
Append(commands, 0x76, {0x00e, std::bit_cast<std::uint32_t>(0.25f)});
return commands;
}
void WriteLabel(std::vector<std::uint32_t>& commands, std::uint32_t index, std::uint32_t value) {
const auto address = reinterpret_cast<std::uintptr_t>(&LabelMemory[index]);
commands.insert(commands.end(), {0xc0033700u, 0x00100200u, static_cast<std::uint32_t>(address), static_cast<std::uint32_t>(address >> 32u), value});
}
void WaitLabel(std::vector<std::uint32_t>& commands, std::uint32_t index, std::uint32_t value) {
const auto address = reinterpret_cast<std::uintptr_t>(&LabelMemory[index]);
commands.insert(commands.end(), {0xc0053c00u, 0x13u, static_cast<std::uint32_t>(address), static_cast<std::uint32_t>(address >> 32u), value, 0xffffffffu, 0x19u});
}
}
int main() {
try {
bool libraries = false;
{
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
libraries = device->GraphicsPipelineLibraries();
}
if (!libraries && std::getenv("APS5_NO_GPL") == nullptr) return VulkanTestSkipped;
using AgcDriver::DriverDetail::DrawFinisher;
const bool finisher = DrawFinisher::Enabled() && DrawFinisher::Overlap();
Registered(VertexHeader, VertexCode.data(), sizeof(VertexCode), 2);
Registered(PixelHeader, PixelCode.data(), sizeof(PixelCode), 1);
PixelConstant[0] = 0.25f;
static_cast<void>(DrawFinisher::DrainText());
auto commands = Setup();
for (std::uint32_t index = 0; index < Labels; ++index) {
Append(commands, 0x2d, {3, 2});
WriteLabel(commands, index, 0x100u + index);
WaitLabel(commands, index, 0x100u + index);
}
Packet packet{commands.data(), static_cast<std::uint32_t>(commands.size()), 0, {}};
Require(sceAgcDriverSubmitDcb(&packet) == 0, "the draw submission failed");
AgcDriverWaitIdle_nid_postfix();
const auto drains = DrawFinisher::DrainText();
AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast<std::uintptr_t>(LabelMemory.data()), sizeof(LabelMemory));
AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast<std::uintptr_t>(ColorMemory.data()), ColorMemory.size());
for (std::uint32_t index = 0; index < Labels; ++index) {
Require(LabelMemory[index] == 0x100u + index, "label " + std::to_string(index) + " is " + std::to_string(LabelMemory[index]) + " after the draws before it, expected " + std::to_string(0x100u + index));
}
unsigned brightest = 0;
for (const auto value : ColorMemory) brightest = std::max(brightest, static_cast<unsigned>(std::to_integer<std::uint8_t>(value)));
Require(brightest + 2 >= 128 && brightest <= 130, "the draws before the labels wrote " + std::to_string(brightest) + ", expected 128");
if (finisher) Require(drains.find(" 0x37 x") == std::string::npos, "a WRITE_DATA label after a draw handed to the finisher drained the finisher:" + drains);
if (finisher) Require(drains.find(" 0x3c x") == std::string::npos, "a WAIT_REG_MEM on a label the finisher holds drained the finisher:" + drains);
AgcDriverShutdown_nid_postfix();
std::cout << "labels after finisher draws " << (finisher ? "queued through the finisher" : "written in order") << "\n";
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
AgcDriverShutdown_nid_postfix();
return 1;
}
}
@@ -30,7 +30,10 @@ constexpr std::uint32_t ClampEdge = 2;
alignas(256) std::array<std::uint32_t, Threads * 4> Input{};
alignas(256) std::array<float, Threads * 8> Output{};
alignas(65536) std::array<std::uint8_t, 4u << 20u> Texels{};
constexpr std::size_t TexelBytes = 4u << 20u;
constexpr std::size_t TexelAlignment = 65536;
std::array<std::uint8_t, TexelBytes + TexelAlignment - 1> TexelStorage{};
const std::span<std::uint8_t, TexelBytes> Texels{reinterpret_cast<std::uint8_t*>((reinterpret_cast<std::uintptr_t>(TexelStorage.data()) + TexelAlignment - 1) & ~(TexelAlignment - 1)), TexelBytes};
alignas(256) constexpr std::array<std::uint32_t, 15> Code{
0x34020084, 0xe0381000, 0x80000201, 0xbf8c3f70, 0xf09c0f20, 0x00820602, 0xf0001f20, 0x00020a04,
@@ -62,7 +65,7 @@ std::array<std::uint8_t, 4> Texel(std::uint32_t x, std::uint32_t guestLayer) {
}
void FillTexels() {
Texels.fill(0);
std::ranges::fill(Texels, std::uint8_t{0});
const auto surface = AgcDriver::Graphics::DescribeSurface(AgcDriver::Graphics::DecodeTextureResource(TextureDescriptor()));
const auto& mip = surface.mips.at(0);
Require(surface.layers == LastArray + 1u && surface.guestBytes <= Texels.size(), "the test array does not fit its storage");
@@ -117,7 +120,7 @@ void Run(AgcDriver::VulkanDevice& device, std::uint32_t baseArray = BaseArray) {
device.WaitIdle();
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
const float u = std::bit_cast<float>(Input[tid * 4u + 0u]);
const float layer = std::clamp(std::nearbyint(std::bit_cast<float>(Input[tid * 4u + 1u])), 0.0f, static_cast<float>(Layers - 1u));
const float layer = std::clamp(std::nearbyint(std::bit_cast<float>(Input[tid * 4u + 1u])), 0.0f, static_cast<float>(LastArray - baseArray));
const auto x = static_cast<std::uint32_t>(std::clamp(static_cast<int>(std::floor(u * static_cast<float>(Width))), 0, static_cast<int>(Width) - 1));
Expect(tid, "image_sample_lz on a window of a 1D array past maxImageArrayLayers", &Output[tid * 8u], Texel(x, baseArray + static_cast<std::uint32_t>(layer)));
Expect(tid, "image_load on a window of a 1D array past maxImageArrayLayers", &Output[tid * 8u + 4u], Texel(Input[tid * 4u + 2u], baseArray + Input[tid * 4u + 3u]));
@@ -128,6 +131,7 @@ void Run(AgcDriver::VulkanDevice& device, std::uint32_t baseArray = BaseArray) {
int main() {
try {
Require(reinterpret_cast<std::uintptr_t>(Texels.data()) % TexelAlignment == 0, "the test array is not 64 KiB aligned");
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
FillTexels();
@@ -0,0 +1,173 @@
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "Recompiler.hpp"
#include "VulkanTestDevice.hpp"
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <span>
#include <string>
#include <vector>
namespace {
using AgcDriver::Graphics::Require;
using ShaderRecompiler::ShaderStage;
constexpr std::uint32_t Threads = 32;
constexpr std::uint32_t Size = 4;
constexpr std::uint32_t Depth = 2;
constexpr std::uint32_t Format32UInt = 20;
constexpr std::uint32_t Type2DArray = 13;
constexpr std::uint32_t IdentitySwizzle = 0xfacu;
constexpr std::size_t TexelBytes = 16384;
constexpr std::size_t BlockBytes = 65536;
alignas(256) std::array<std::uint32_t, Threads * 4> Input{};
alignas(256) constexpr std::array<std::uint32_t, 10> StoreCode{
0x34020084, 0xe0381000, 0x80001401, 0xbf8c3f70, 0xf0201110, 0x00011714, 0x7e2c0282, 0xf0201110,
0x00011714, 0xbf810000,
};
class GuestBlock {
public:
GuestBlock() {
#ifdef _WIN32
block = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, BlockBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
#else
block = static_cast<std::uint8_t*>(std::aligned_alloc(BlockBytes, BlockBytes));
#endif
Require(block != nullptr, "image store volume through array: cannot allocate the guest block");
GuestAllocations::Mutation().Add(block, BlockBytes, true, true, true);
}
~GuestBlock() {
GuestAllocations::Mutation().Remove(block);
#ifdef _WIN32
VirtualFree(block, 0, MEM_RELEASE);
#else
std::free(block);
#endif
}
GuestBlock(const GuestBlock&) = delete;
GuestBlock& operator=(const GuestBlock&) = delete;
std::uint8_t* Data() { return block; }
private:
std::uint8_t* block = nullptr;
};
std::string Hex(std::uint32_t value) {
char text[16];
std::snprintf(text, sizeof(text), "0x%08x", value);
return text;
}
std::uint32_t Value(std::uint32_t tid) {
return (tid + 1u) * 0x9e3779b1u;
}
std::vector<std::uint8_t> Initial() {
std::vector<std::uint8_t> bytes(TexelBytes);
for (std::size_t index = 0; index < bytes.size(); ++index) bytes[index] = static_cast<std::uint8_t>(0x80u + 37u * index + 11u * (index >> 4u));
return bytes;
}
std::array<std::uint32_t, 4> BufferDescriptor(const void* data, std::uint32_t bytes) {
const auto address = reinterpret_cast<std::uintptr_t>(data);
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu), bytes, 0x31016facu};
}
std::array<std::uint32_t, 8> ArrayDescriptor(const void* data) {
const auto address = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(data));
return {
static_cast<std::uint32_t>(address >> 8u),
static_cast<std::uint32_t>((address >> 40u) & 0xffu) | (Format32UInt << 20u) | (((Size - 1u) & 3u) << 30u),
((Size - 1u) >> 2u) | ((Size - 1u) << 14u),
IdentitySwizzle | (Type2DArray << 28u),
Depth - 1u,
0u,
0u,
0u,
};
}
void Dispatch(AgcDriver::VulkanDevice& device, std::uint8_t* texels, std::size_t bytes) {
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
const std::array<std::uint32_t, 4> words{tid % Size, (tid / Size) % Size, tid / (Size * Size), Value(tid)};
std::copy(words.begin(), words.end(), Input.begin() + tid * 4u);
}
const auto initial = Initial();
std::copy(initial.begin(), initial.end(), texels);
std::vector<std::uint32_t> userData(16, 0u);
const auto buffer = BufferDescriptor(Input.data(), static_cast<std::uint32_t>(Input.size() * 4u));
const auto texture = ArrayDescriptor(texels);
std::copy(buffer.begin(), buffer.end(), userData.begin());
std::copy(texture.begin(), texture.end(), userData.begin() + 4);
const std::span<const std::uint32_t> code(StoreCode);
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(code)}}};
const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {false, false, false}, false, 1};
ShaderRecompiler::RecompileRequest request{
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(code.data()), code, 0, {}},
{32, 0, userData, compute, std::nullopt, std::nullopt, memory},
device.Target(),
{0, 0, 0, 128}
};
request.useCache = false;
const auto result = ShaderRecompiler::Recompile(request);
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(code.data()));
device.WaitIdle();
AgcDriver::Graphics::StorageTexture::FlushPending(reinterpret_cast<std::uintptr_t>(texels), bytes, nullptr, "test");
device.WaitIdle();
}
void Check(const std::uint8_t* texels) {
const auto geometry = AgcDriver::Graphics::DescribeSurface(AgcDriver::Graphics::DecodeTextureResource(ArrayDescriptor(texels)));
const auto& mip = geometry.mips.at(0);
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
const auto x = tid % Size;
const auto y = (tid / Size) % Size;
const auto z = tid / (Size * Size);
std::uint32_t actual = 0;
std::memcpy(&actual, texels + geometry.GuestLayerOffset(z) + mip.tiledOffset + static_cast<std::uint64_t>(y) * mip.pitchBytes + x * 4u, 4u);
Require(actual == Value(tid), "image_store 3d through a 2D-array T#: texel (" + std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z) + ") is " + Hex(actual) + ", expected " + Hex(Value(tid)));
}
const auto initial = Initial();
Require(std::equal(texels + geometry.guestBytes, texels + TexelBytes, initial.begin() + static_cast<std::ptrdiff_t>(geometry.guestBytes)), "image_store 3d through a 2D-array T#: a slice past the array changed bytes after it");
}
}
int main() {
try {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
GuestBlock block;
auto* texels = block.Data();
const auto geometry = AgcDriver::Graphics::DescribeSurface(AgcDriver::Graphics::DecodeTextureResource(ArrayDescriptor(texels)));
Require(geometry.guestBytes <= TexelBytes, "image store volume through array: the array does not fit the texel storage");
Dispatch(*device, texels, geometry.guestBytes);
Check(texels);
std::puts("image store volume through array tests passed");
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -0,0 +1,330 @@
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libSceAgcDriver/Graphics/include/State.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "Recompiler.hpp"
#include "VulkanTestDevice.hpp"
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
#include <algorithm>
#include <array>
#include <bit>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <iostream>
#include <memory>
#include <span>
#include <string>
#include <vector>
namespace AgcDriver {
struct VulkanDeviceTestAccess {
static Graphics::Context ContextOf(const VulkanDevice& device) { return device.graphicsContext(); }
};
}
namespace {
using AgcDriver::Graphics::Require;
using ShaderRecompiler::ShaderStage;
constexpr std::uint32_t Side = 16;
constexpr std::uint32_t Samples = 4;
constexpr std::uint32_t SampleShift = 2;
constexpr std::size_t BlockBytes = 65536;
constexpr std::uint32_t WaveSize = 64;
constexpr std::uint32_t Float16x4Info = 0x0730u;
constexpr std::uint32_t MultisampledAttrib = (SampleShift << 12u) | (SampleShift << 15u);
constexpr std::uint32_t TiledAttrib3 = 0x4dc6c000u;
constexpr std::uint32_t AaConfig4x = 0x0020c002u;
constexpr std::uint32_t MsaaEnableClear = 2;
constexpr std::uint32_t StandardLocations4x = 0x622ae6aeu;
constexpr std::uint32_t Format16161616Float = 71;
constexpr std::uint32_t Type2DMsaa = 14;
constexpr std::uint32_t TileRenderTarget = 0x1b;
constexpr std::uint32_t Threads = 32;
constexpr std::uint32_t Words = 32;
constexpr std::uint32_t LoadResult = 12;
constexpr std::array<std::uint32_t, 2> Primitives{2u, 3u};
constexpr std::array<float, 4> Drawn{0.25f, 0.5f, 0.125f, 1.0f};
constexpr std::array<std::byte, 4> DrawnBytes{std::byte{64}, std::byte{128}, std::byte{32}, std::byte{255}};
alignas(256) constexpr std::array<std::uint32_t, 6> VertexCode{
0xe0382000, 0x80000005, 0xbf8c3f70, 0xf80008cf, 0x03020100, 0xbf810000,
};
alignas(256) constexpr std::array<std::uint32_t, 11> PixelCode{
0x7e0802ff, 0x3e800000, 0x7e0a02ff, 0x3f000000, 0x7e0c02ff, 0x3e000000, 0x7e0e02ff, 0x3f800000, 0xf800180f, 0x07060504, 0xbf810000,
};
alignas(256) constexpr std::array<std::uint32_t, 11> Unorm8PixelCode{
0x7e0802ff, std::bit_cast<std::uint32_t>(64.0f / 255.0f), 0x7e0a02ff, std::bit_cast<std::uint32_t>(128.0f / 255.0f), 0x7e0c02ff, std::bit_cast<std::uint32_t>(32.0f / 255.0f), 0x7e0e02ff, std::bit_cast<std::uint32_t>(1.0f), 0xf800180f, 0x07060504, 0xbf810000,
};
alignas(256) constexpr std::array<std::uint32_t, 26> LoadCode{
0x34020087, 0xe0301000, 0x80000201, 0xe0301004, 0x80000301, 0xe0301008, 0x80000401, 0xe030100c,
0x80000501, 0xe0301010, 0x80000601, 0xe0301014, 0x80000701, 0xbf8c3f70, 0xf0001f30, 0x00011005,
0xbf8c3f70, 0xe0701030, 0x80001001, 0xe0701034, 0x80001101, 0xe0701038, 0x80001201, 0xe070103c,
0x80001301, 0xbf810000,
};
alignas(256) constexpr std::array<std::array<float, 4>, 4> Lines{{
{-0.828125f, -0.4375f, 0.5f, 1.0f}, {0.90625f, 0.140625f, 0.5f, 1.0f},
{-0.265625f, 0.90625f, 0.5f, 1.0f}, {0.34375f, -0.921875f, 0.5f, 1.0f},
}};
alignas(256) std::array<std::uint32_t, Threads * Words> Buffer{};
alignas(256) std::array<std::array<std::byte, 4096>, Primitives.size()> LinePixels{};
struct Block {
explicit Block(std::size_t bytes) : bytes(bytes) {
#ifdef _WIN32
data = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
#else
data = static_cast<std::uint8_t*>(std::aligned_alloc(BlockBytes, bytes));
#endif
Require(data != nullptr, "cannot allocate the multisampled color target");
std::memset(data, 0, bytes);
GuestAllocations::Mutation mutation;
mutation.Add(data, bytes, true, true, true);
}
~Block() {
{
GuestAllocations::Mutation mutation;
mutation.Remove(data);
}
#ifdef _WIN32
VirtualFree(data, 0, MEM_RELEASE);
#else
std::free(data);
#endif
}
Block(const Block&) = delete;
Block& operator=(const Block&) = delete;
std::uint64_t Address() const { return reinterpret_cast<std::uintptr_t>(data); }
std::size_t bytes;
std::uint8_t* data = nullptr;
};
AgcDriver::QueueState LineQueue(const Block& block, std::uint32_t primitive) {
const auto half = std::bit_cast<std::uint32_t>(static_cast<float>(Side) / 2.0f);
const auto extent = (Side << 16u) | Side;
AgcDriver::QueueState queue;
queue.userConfig[0x242] = primitive;
queue.context = {
{0x2d5, 0x2000}, {0x1b6, 0}, {0x207, 0}, {0x200, 0}, {0x203, 0x800},
{0x2dc, 0xaa00}, {0x2f8, AaConfig4x}, {0x292, MsaaEnableClear}, {0x293, 0},
{0x80, 0}, {0x8d, 0}, {0x83, 0xffff}, {0x8c, 0xa},
{0x2f9, 0x2d}, {0x313, 0x6000}, {0x30e, 0xffffffff}, {0x30f, 0xffffffff},
{0x206, 0x43f}, {0x204, 0x80000}, {0x205, 0x240},
{0x8e, 0xf}, {0x8f, 0xf}, {0x202, 0xcc0010},
{0x1c4, 0}, {0x1c5, 9}, {0x1c3, 4},
{0x318, static_cast<std::uint32_t>(block.Address() >> 8u)}, {0x390, static_cast<std::uint32_t>(block.Address() >> 40u)},
{0x31b, 0}, {0x31c, Float16x4Info}, {0x31d, MultisampledAttrib},
{0x3b0, ((Side - 1u) << 14u) | (Side - 1u)}, {0x3b8, TiledAttrib3}, {0x1e0, 0},
{0xc, 0}, {0xd, extent}, {0x81, 0x80000000}, {0x82, extent},
{0x90, 0x80000000}, {0x91, extent}, {0x94, 0x80000000}, {0x95, extent},
{0x10f, half}, {0x110, half}, {0x111, std::bit_cast<std::uint32_t>(-static_cast<float>(Side) / 2.0f)}, {0x112, half},
{0x113, std::bit_cast<std::uint32_t>(1.0f)}, {0x114, 0}, {0xb4, 0}, {0xb5, std::bit_cast<std::uint32_t>(1.0f)}
};
for (std::uint32_t offset = 0x2fe; offset <= 0x30d; ++offset) queue.context[offset] = (offset - 0x2feu) % 4u == 0 ? StandardLocations4x : 0u;
queue.shader[0x008] = 0x100;
queue.shader[0x009] = 0;
return queue;
}
AgcDriver::Graphics::State DecodeLines(const Block& block, std::uint32_t primitive) {
const auto state = AgcDriver::Graphics::DecodeState(LineQueue(block, primitive));
const auto& color = state.color;
Require(state.topology == (primitive == 2u ? VK_PRIMITIVE_TOPOLOGY_LINE_LIST : VK_PRIMITIVE_TOPOLOGY_LINE_STRIP), "VGT_PRIMITIVE_TYPE " + std::to_string(primitive) + " did not decode as a line list or strip");
Require(state.colors.size() == 1 && color.address == block.Address() && color.format == VK_FORMAT_R16G16B16A16_SFLOAT && color.samples == Samples && color.extent.width == Side && color.extent.height == Side, "the target did not decode as a 16x16 RGBA16F surface of 4 samples");
Require(state.samples == Samples && !state.depth && !state.perSampleShading && !state.alphaToCoverage, "the lines did not decode as a 4x draw without depth, sample shading or alpha-to-coverage");
const auto locations = AgcDriver::Graphics::SampleLocations(state);
for (std::uint32_t sample = 0; sample < Samples; ++sample) Require(locations[sample].x == 0.5f && locations[sample].y == 0.5f, "the decoded 4x line state does not put every sample at the pixel center");
Require(state.viewport.x == 0.0f && state.viewport.y == static_cast<float>(Side) && state.viewport.width == static_cast<float>(Side) && state.viewport.height == -static_cast<float>(Side) && state.scissor.offset.x == 0 && state.scissor.offset.y == 0 && state.scissor.extent.width == Side && state.scissor.extent.height == Side, "the decoded viewport or scissor does not cover the 16x16 target");
return state;
}
AgcDriver::Graphics::State OneSample(AgcDriver::Graphics::State state, std::span<std::byte> pixels, const AgcDriver::Graphics::ColorTargetLayout& linear) {
state.color = {reinterpret_cast<std::uintptr_t>(pixels.data()), {Side, Side}, VK_FORMAT_R8G8B8A8_UNORM, linear.Bytes(), 0xe4u};
state.colors = {state.color};
state.samples = 1;
state.customSampleLocations = false;
state.sampleLocations.fill(0);
state.sampleLocationGrid = false;
return state;
}
void DrawLines(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::State& state, std::span<const std::uint32_t> pixelCode) {
const auto target = device.Target();
std::vector<std::uint32_t> vertexUserData(4, 0u);
const auto address = reinterpret_cast<std::uintptr_t>(Lines.data());
const std::array<std::uint32_t, 4> vertexBuffer{static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu) | (16u << 16u), static_cast<std::uint32_t>(Lines.size()), 0x01016facu};
std::copy(vertexBuffer.begin(), vertexBuffer.end(), vertexUserData.begin());
const std::array<ShaderRecompiler::MemoryRegion, 1> vertexMemory{{{reinterpret_cast<std::uintptr_t>(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}};
ShaderRecompiler::RecompileRequest vertex{
{ShaderStage::Vertex, reinterpret_cast<std::uintptr_t>(VertexCode.data()), VertexCode, 0, {}},
{WaveSize, 0, vertexUserData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, vertexMemory},
target,
{0, 0, 0, 64}
};
vertex.useCache = false;
const auto vertexResult = ShaderRecompiler::Recompile(vertex);
const auto vertexPush = static_cast<std::uint32_t>(vertexResult.pushConstants.size());
ShaderRecompiler::ShaderPixelStageInfo pixel{};
pixel.inputAddr = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionX) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionY);
pixel.posX = true;
pixel.posY = true;
pixel.targetOutputMode[0] = 9;
pixel.targetExportMapping.fill(0xe4u);
const std::vector<std::uint32_t> pixelUserData(8, 0u);
const auto codeAddress = reinterpret_cast<std::uintptr_t>(pixelCode.data());
const std::array<ShaderRecompiler::MemoryRegion, 1> pixelMemory{{{codeAddress, std::as_bytes(pixelCode)}}};
ShaderRecompiler::RecompileRequest fragment{
{ShaderStage::Fragment, codeAddress, pixelCode, 0, {}},
{WaveSize, 0, pixelUserData, std::nullopt, pixel, std::nullopt, pixelMemory},
target,
PixelPushLayout(vertexPush, target)
};
fragment.useCache = false;
const auto pixelResult = ShaderRecompiler::Recompile(fragment);
const std::array<AgcDriver::Graphics::CompiledShader, 2> shaders{{
{ShaderStage::Vertex, &vertexResult, 0},
{ShaderStage::Fragment, &pixelResult, PixelPushOffset(vertexPush, target)}
}};
const AgcDriver::Pm4::DrawParameters draw{0, static_cast<std::uint32_t>(Lines.size()), 0, 1, 0, false};
device.Draw(state, draw, shaders);
device.WaitIdle();
}
std::vector<std::array<float, 4>> LoadSamples(AgcDriver::VulkanDevice& device, const Block& block) {
const auto address = block.Address();
const std::array<std::uint32_t, 8> texture{
static_cast<std::uint32_t>(address >> 8u),
static_cast<std::uint32_t>((address >> 40u) & 0xffu) | (Format16161616Float << 20u) | (((Side - 1u) & 3u) << 30u),
((Side - 1u) >> 2u) | ((Side - 1u) << 14u),
0xfacu | (SampleShift << 16u) | (TileRenderTarget << 20u) | (Type2DMsaa << 28u),
0u,
SampleShift << 4u,
0u,
0u,
};
const auto bufferAddress = reinterpret_cast<std::uintptr_t>(Buffer.data());
const std::array<std::uint32_t, 4> buffer{static_cast<std::uint32_t>(bufferAddress), static_cast<std::uint32_t>((bufferAddress >> 32u) & 0xffffu), static_cast<std::uint32_t>(Buffer.size() * 4u), 0x31016facu};
std::vector<std::uint32_t> userData(16, 0u);
std::copy(buffer.begin(), buffer.end(), userData.begin());
std::copy(texture.begin(), texture.end(), userData.begin() + 4);
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(LoadCode.data()), std::as_bytes(std::span(LoadCode))}}};
const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {false, false, false}, false, 1};
ShaderRecompiler::RecompileRequest request{
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(LoadCode.data()), LoadCode, 0, {}},
{32, 0, userData, compute, std::nullopt, std::nullopt, memory},
device.Target(),
{0, 0, 0, 128}
};
request.useCache = false;
const auto program = ShaderRecompiler::Recompile(request);
std::vector<std::array<float, 4>> loaded(Side * Side * Samples);
for (std::uint32_t first = 0; first < loaded.size(); first += Threads) {
Buffer.fill(0xdeadbeefu);
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
const auto index = first + tid;
const auto pixel = index / Samples;
const std::array<std::uint32_t, 6> words{0u, 0u, 0u, pixel % Side, pixel / Side, index % Samples};
std::copy(words.begin(), words.end(), &Buffer[tid * Words]);
}
device.Dispatch(program, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(LoadCode.data()));
device.WaitIdle();
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
for (std::uint32_t component = 0; component < 4u; ++component) loaded[first + tid][component] = std::bit_cast<float>(Buffer[tid * Words + LoadResult + component]);
}
}
return loaded;
}
bool NearEndpoint(std::uint32_t x, std::uint32_t y) {
return std::any_of(Lines.begin(), Lines.end(), [&](const std::array<float, 4>& vertex) {
const double px = (static_cast<double>(vertex[0]) + 1.0) * 0.5 * Side;
const double py = Side - (static_cast<double>(vertex[1]) + 1.0) * 0.5 * Side;
return std::fabs(x + 0.5 - px) < 1.5 && std::fabs(y + 0.5 - py) < 1.5;
});
}
void CompareLines(AgcDriver::VulkanDevice& device, const Block& block, std::uint32_t primitive, std::span<std::byte> pixels) {
const auto decoded = DecodeLines(block, primitive);
DrawLines(device, decoded, PixelCode);
const auto loaded = LoadSamples(device, block);
const AgcDriver::Graphics::ColorTargetLayout linear(Side, Side, AgcDriver::Graphics::ColorTileMode::Linear, 4u);
Require(linear.Bytes() <= pixels.size(), "the one-sample line target does not fit its memory");
std::fill(pixels.begin(), pixels.end(), std::byte{0});
DrawLines(device, OneSample(decoded, pixels, linear), Unorm8PixelCode);
std::uint32_t covered = 0;
std::uint32_t single = 0;
std::uint32_t compared = 0;
std::uint32_t differing = 0;
for (std::uint32_t y = 0; y < Side; ++y) {
for (std::uint32_t x = 0; x < Side; ++x) {
char where[80];
std::snprintf(where, sizeof(where), "VGT_PRIMITIVE_TYPE %u: pixel (%u, %u)", primitive, x, y);
std::uint32_t drawn = 0;
for (std::uint32_t sample = 0; sample < Samples; ++sample) {
const auto& texel = loaded[(y * Side + x) * Samples + sample];
Require(texel == Drawn || texel == std::array<float, 4>{}, std::string(where) + " of the 4x target holds neither the line color nor the cleared value");
drawn += texel == Drawn ? 1u : 0u;
}
Require(drawn == 0u || drawn == Samples, std::string(where) + " has " + std::to_string(drawn) + " of its 4 samples covered by a line with every sample at the pixel center");
const auto bytes = pixels.begin() + static_cast<std::ptrdiff_t>(linear.Offset(x, y));
const bool oneSample = std::equal(DrawnBytes.begin(), DrawnBytes.end(), bytes);
Require(oneSample || std::all_of(bytes, bytes + 4, [](std::byte value) { return value == std::byte{0}; }), std::string(where) + " of the one-sample target holds neither the line color nor zero");
covered += drawn == Samples ? 1u : 0u;
single += oneSample ? 1u : 0u;
if (NearEndpoint(x, y)) continue;
++compared;
differing += (drawn == Samples) != oneSample ? 1u : 0u;
Require(!oneSample || drawn == Samples, std::string(where) + " is drawn by the one-sample line but not covered in the 4x target");
}
}
Require(covered >= 20u && covered <= 2u * single && compared >= 200u, "VGT_PRIMITIVE_TYPE " + std::to_string(primitive) + ": the 4x lines covered " + std::to_string(covered) + " pixels and the one-sample lines " + std::to_string(single) + ", with " + std::to_string(compared) + " pixels compared");
std::printf("VGT_PRIMITIVE_TYPE %u: 4x lines with every sample at the pixel center covered %u pixels in full and none in part; the one-sample lines drew %u; %u of the %u pixels away from the endpoints differ\n", primitive, covered, single, differing, compared);
}
}
int main() {
try {
auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
if (!AgcDriver::VulkanDeviceTestAccess::ContextOf(*device).storageImageMultisample) {
std::puts("skipped, the device has no shaderStorageImageMultisample to load the samples of a 4x target");
return VulkanTestSkipped;
}
if ((AgcDriver::VulkanDeviceTestAccess::ContextOf(*device).sampleLocationSampleCounts & Samples) == 0u) {
std::puts("skipped, the device has no VK_EXT_sample_locations at 4 samples to put every sample at the pixel center");
return VulkanTestSkipped;
}
Block listTarget(4u * BlockBytes);
Block stripTarget(4u * BlockBytes);
struct ReleaseDevice {
std::unique_ptr<AgcDriver::VulkanDevice>& value;
~ReleaseDevice() { value.reset(); }
} releaseDevice{device};
const std::array<const Block*, Primitives.size()> targets{&listTarget, &stripTarget};
for (std::size_t index = 0; index < Primitives.size(); ++index) CompareLines(*device, *targets[index], Primitives[index], LinePixels[index]);
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -14,6 +14,7 @@
#else
#include <sys/mman.h>
#endif
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <cstdint>
@@ -66,6 +67,15 @@ PFN_vkDestroyImageView realDestroyImageView = nullptr;
PFN_vkCmdClearColorImage realClearColorImage = nullptr;
PFN_vkCmdCopyImage realCopyImage = nullptr;
[[noreturn]] void FailViewOutlivesImage() {
std::fputs("an MSAA image would be destroyed before one of its views; stopping\n", stderr);
std::fflush(stderr);
#ifdef _WIN32
TerminateProcess(GetCurrentProcess(), 1);
#endif
std::_Exit(1);
}
[[noreturn]] void FailPendingImage() {
std::fputs("an unsubmitted MSAA image would be destroyed; stopping without submitting it\n", stderr);
std::fflush(stderr);
@@ -104,6 +114,7 @@ VKAPI_ATTR void VKAPI_CALL CountDestroyImage(VkDevice device, VkImage image, con
for (const auto& [pending, generation] : pendingImages) {
if (pending == image && images.at(image).generation == generation) FailPendingImage();
}
if (std::any_of(views.begin(), views.end(), [&](const auto& entry) { return entry.second == image; })) FailViewOutlivesImage();
realDestroyImage(device, image, callbacks);
images.erase(image);
++destroyed;
@@ -514,6 +525,37 @@ public:
AwaitImages(0, "promoted MSAA targets were not fully released");
}
void StorageTwin() {
GuestBlock block;
const auto target = Target(block);
auto twin = target;
twin.format = VK_FORMAT_R8G8B8A8_SRGB;
const auto resource = Resource(block);
VkImage renderedImage = VK_NULL_HANDLE, twinImage = VK_NULL_HANDLE, promotedImage = VK_NULL_HANDLE, promotedTwinImage = VK_NULL_HANDLE;
Image rendered{}, promoted{};
VkImageView twinView = VK_NULL_HANDLE;
{
std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex());
rendered = ImageFor(MultisampleTargetView(context, target), &renderedImage);
twinView = MultisampleTargetView(context, twin);
ImageFor(twinView, &twinImage);
Require(twinImage == renderedImage, "an sRGB use of an MSAA surface rendered as UNORM does not reach its samples");
}
Sync();
{
std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex());
promoted = ImageFor(MultisampleTargetStorageView(context, resource), &promotedImage);
Require(promoted.generation != rendered.generation, "MSAA storage promotion kept the rendered image");
const auto promotedTwin = MultisampleTargetView(context, twin);
ImageFor(promotedTwin, &promotedTwinImage);
Require(promotedTwinImage == promotedImage, "after storage promotion an sRGB use of the MSAA surface still views the retired image");
}
Sync();
block.Unmap();
Clear();
AwaitImages(0, "MSAA targets with twin views were not fully released");
}
private:
AgcDriver::VulkanDevice& device;
Context context;
@@ -533,6 +575,7 @@ int main() {
run.SampledRemap();
run.StorageRemap();
run.OrderRemap();
if (context.storageImageMultisample) run.StorageTwin();
std::puts("retired MSAA allocations stay bounded, recorded clears and storage promotions retain their images, sampled aliases release their parents after the last batch, and sample-order targets keep their retired images until their batch completes");
return 0;
} catch (const std::exception& error) {
@@ -0,0 +1,247 @@
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp"
#include "prx/libSceAgcDriver/Graphics/include/State.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "prx/libc/include/Shutdown.hpp"
#include "VulkanTestDevice.hpp"
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <initializer_list>
#include <iostream>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <utility>
namespace AgcDriver {
struct VulkanDeviceTestAccess {
static Graphics::Context ContextOf(const VulkanDevice& device) { return device.graphicsContext(); }
};
}
namespace {
using AgcDriver::Graphics::ColorTarget;
using AgcDriver::Graphics::Require;
constexpr std::size_t BlockBytes = 65536;
constexpr std::uint32_t Side = 64;
class GuestBlock {
public:
GuestBlock() {
#ifdef _WIN32
block = static_cast<std::byte*>(VirtualAlloc(nullptr, BlockBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
#else
block = static_cast<std::byte*>(std::aligned_alloc(BlockBytes, BlockBytes));
#endif
Require(block != nullptr, "multisampled sRGB twin: cannot allocate a guest block");
std::memset(block, 0, BlockBytes);
GuestAllocations::Mutation().Add(block, BlockBytes, true, true, true);
}
GuestBlock(const GuestBlock&) = delete;
GuestBlock& operator=(const GuestBlock&) = delete;
std::uint64_t Address() const { return static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(block)); }
private:
std::byte* block = nullptr;
};
GuestBlock& NewBlock() {
static auto* blocks = new std::deque<GuestBlock>();
return blocks->emplace_back();
}
ColorTarget MultisampledTarget(const GuestBlock& color, VkFormat format) {
ColorTarget target{};
target.address = color.Address();
target.surfaceAddress = target.address;
target.extent = {Side, Side};
target.surfaceExtent = target.extent;
target.format = format;
target.tileMode = AgcDriver::Graphics::ColorTileMode::RenderTarget;
target.elementBytes = 4;
target.bytes = BlockBytes / 4;
target.samples = 4;
return target;
}
struct Acquired {
VkImageView view = VK_NULL_HANDLE;
VkImage image = VK_NULL_HANDLE;
std::shared_ptr<void> owner;
};
Acquired Acquire(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::Context& context, const ColorTarget& target) {
std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex());
Acquired acquired;
acquired.view = AgcDriver::Graphics::MultisampleTargetView(context, target, acquired.owner, &acquired.image);
Require(acquired.view != VK_NULL_HANDLE && acquired.image != VK_NULL_HANDLE && acquired.owner != nullptr, "the multisampled target has no view");
device.SubmitRecorded(true);
device.WaitIdle();
return acquired;
}
std::array<std::byte, 4> UniformTexel(const AgcDriver::Graphics::Context& context, VkImage multisampled, VkFormat format) {
VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
info.imageType = VK_IMAGE_TYPE_2D;
info.format = format;
info.extent = {Side, Side, 1};
info.mipLevels = 1;
info.arrayLayers = 1;
info.samples = VK_SAMPLE_COUNT_1_BIT;
info.tiling = VK_IMAGE_TILING_OPTIMAL;
info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VkImage resolved = VK_NULL_HANDLE;
AgcDriver::Graphics::Check(context.Function<PFN_vkCreateImage>("vkCreateImage")(context.device, &info, nullptr, &resolved), "vkCreateImage resolved texels");
VkMemoryRequirements requirements{};
context.Function<PFN_vkGetImageMemoryRequirements>("vkGetImageMemoryRequirements")(context.device, resolved, &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);
VkDeviceMemory memory = VK_NULL_HANDLE;
AgcDriver::Graphics::Check(context.Function<PFN_vkAllocateMemory>("vkAllocateMemory")(context.device, &allocation, nullptr, &memory), "vkAllocateMemory resolved texels");
AgcDriver::Graphics::Check(context.Function<PFN_vkBindImageMemory>("vkBindImageMemory")(context.device, resolved, memory, 0), "vkBindImageMemory resolved texels");
AgcDriver::Graphics::Buffer readback(context, static_cast<std::size_t>(Side) * Side * 4u, VK_BUFFER_USAGE_TRANSFER_DST_BIT);
{
AgcDriver::Graphics::CommandBatch batch(context);
const auto commands = batch.Handle();
std::array<VkImageMemoryBarrier, 2> barriers{};
for (auto& barrier : barriers) {
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
}
barriers[0].image = multisampled;
barriers[0].srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT;
barriers[0].dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
barriers[0].oldLayout = barriers[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
barriers[1].image = resolved;
barriers[1].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barriers[1].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barriers[1].newLayout = VK_IMAGE_LAYOUT_GENERAL;
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, static_cast<std::uint32_t>(barriers.size()), barriers.data());
VkImageResolve region{};
region.srcSubresource = region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
region.extent = {Side, Side, 1};
context.Function<PFN_vkCmdResolveImage>("vkCmdResolveImage")(commands, multisampled, VK_IMAGE_LAYOUT_GENERAL, resolved, VK_IMAGE_LAYOUT_GENERAL, 1, &region);
VkMemoryBarrier toCopy{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
toCopy.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
toCopy.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &toCopy, 0, nullptr, 0, nullptr);
VkBufferImageCopy copy{};
copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
copy.imageExtent = {Side, Side, 1};
context.Function<PFN_vkCmdCopyImageToBuffer>("vkCmdCopyImageToBuffer")(commands, resolved, VK_IMAGE_LAYOUT_GENERAL, readback.Handle(), 1, &copy);
VkMemoryBarrier toHost{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
toHost.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
toHost.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &toHost, 0, nullptr, 0, nullptr);
batch.SubmitAndWait();
}
readback.Invalidate();
const auto bytes = readback.Bytes();
std::array<std::byte, 4> texel{};
std::copy_n(bytes.begin(), texel.size(), texel.begin());
for (std::size_t offset = 0; offset < bytes.size(); offset += texel.size()) Require(std::equal(texel.begin(), texel.end(), bytes.begin() + static_cast<std::ptrdiff_t>(offset)), "a cleared multisampled target holds different texels");
context.Function<PFN_vkDestroyImage>("vkDestroyImage")(context.device, resolved, nullptr);
context.Function<PFN_vkFreeMemory>("vkFreeMemory")(context.device, memory, nullptr);
return texel;
}
std::array<std::byte, 4> Bytes(std::uint32_t pattern) {
std::array<std::byte, 4> bytes{};
std::memcpy(bytes.data(), &pattern, bytes.size());
return bytes;
}
void FillTakenThroughTwin(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::Context& context, VkFormat created, VkFormat used, std::uint32_t pattern) {
auto& color = NewBlock();
const auto target = MultisampledTarget(color, created);
const auto rendered = Acquire(device, context, target);
const auto bytes = static_cast<std::size_t>(AgcDriver::Graphics::MultisampledColorBytes(target));
Require(AgcDriver::Graphics::MultisampledColorFillAbsorbs(color.Address(), bytes, pattern), "the color fill is not taken as the target's clear in its creation format");
AgcDriver::Graphics::NoteColorMetadataFill(color.Address(), bytes, pattern);
const auto twin = Acquire(device, context, MultisampledTarget(color, used));
Require(twin.image == rendered.image, "the twin use of the filled target does not reach its samples");
std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex());
Require(UniformTexel(context, twin.image, created) == Bytes(pattern), "a fill taken as a clear through the twin format does not store the guest's bytes");
}
bool TwinFormatsShareTheirSamples(AgcDriver::VulkanDevice& device) {
const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device);
if ((context.limits.framebufferColorSampleCounts & VK_SAMPLE_COUNT_4_BIT) == 0) {
std::cout << "skipped, the device has no 4x color targets\n";
return false;
}
struct ClearTargets {
AgcDriver::VulkanDevice& device;
VkDevice handle;
~ClearTargets() {
std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex());
device.SubmitRecorded(true);
device.WaitIdle();
AgcDriver::Graphics::ClearMultisampleTargets(handle);
}
} clearTargets{device, context.device};
for (const auto [first, second] : {std::pair{VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM}, std::pair{VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_SRGB}}) {
if (AgcDriver::Graphics::SrgbTwinFormat(context, first) != second && AgcDriver::Graphics::SrgbTwinFormat(context, second) != first) continue;
auto& color = NewBlock();
const auto rendered = Acquire(device, context, MultisampledTarget(color, first));
const auto twin = Acquire(device, context, MultisampledTarget(color, second));
Require(twin.image == rendered.image && twin.owner == rendered.owner, "a use of a multisampled surface in its sRGB twin format does not reach the samples rendered in the other format");
Require(twin.view != rendered.view, "a use of a multisampled surface in its sRGB twin format is given the view of the other format");
const auto again = Acquire(device, context, MultisampledTarget(color, first));
Require(again.image == rendered.image && again.view == rendered.view, "returning to the first format does not give back the first format's view");
}
if (AgcDriver::Graphics::SrgbTwinFormat(context, VK_FORMAT_R8G8B8A8_UNORM) == VK_FORMAT_R8G8B8A8_SRGB) {
FillTakenThroughTwin(device, context, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_SRGB, 0x80808080u);
FillTakenThroughTwin(device, context, VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_R8G8B8A8_UNORM, 0xff0000ffu);
}
auto& other = NewBlock();
const auto unorm = Acquire(device, context, MultisampledTarget(other, VK_FORMAT_R8G8B8A8_UNORM));
const auto floating = Acquire(device, context, MultisampledTarget(other, VK_FORMAT_R16G16_SFLOAT));
Require(floating.image != unorm.image, "a multisampled surface used in an unrelated format of the same size shares the other format's samples");
return true;
}
}
int main() {
try {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
const bool tested = TwinFormatsShareTheirSamples(*device);
LibcRunShutdown_nid_postfix();
if (!tested) return VulkanTestSkipped;
std::cout << "multisampled sRGB twin tests passed\n";
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
try {
LibcRunShutdown_nid_postfix();
} catch (...) {
}
return 1;
}
}
@@ -25,7 +25,9 @@
#include <cstring>
#include <exception>
#include <mutex>
#include <optional>
#include <span>
#include <utility>
namespace AgcDriver {
@@ -93,7 +95,9 @@ private:
#endif
};
int RunNativeClear(AgcDriver::VulkanDevice& device) {
enum class ClearConsumer { Owner, Texture, Attachment };
int RunNativeClear(AgcDriver::VulkanDevice& device, ClearConsumer consumer) {
using namespace ShaderRecompiler;
using namespace AgcDriver::Graphics;
const std::lock_guard lock(Memory::GpuMutex());
@@ -153,10 +157,28 @@ int RunNativeClear(AgcDriver::VulkanDevice& device) {
device.WaitIdle();
target.clearDepth = 1.0f;
Require(DepthSurfaceView(context, target) == view, "changing the native clear value replaced its attachment");
NoteHtileDepthClear(target.htileAddress, metadataBytes, metadataBytes);
std::optional<std::pair<std::uint64_t, std::size_t>> htileClear;
if (NoteHtileDepthClear(target.htileAddress, metadataBytes, metadataBytes)) htileClear.emplace(target.htileAddress, metadataBytes);
Require(htileClear.has_value(), "the full BDA clear was not registered for completion");
const auto generation = Memory::TrackerGeneration();
userData[4] = 0xfffffff0u;
device.Dispatch(compile(), groups, 1u, 1u, {}, reinterpret_cast<std::uintptr_t>(code.data()));
device.Dispatch(compile(), groups, 1u, 1u, {}, reinterpret_cast<std::uintptr_t>(code.data()), nullptr, nullptr, htileClear);
std::puts("Native full BDA clear: checking sampled owner before explicit WaitIdle");
Require(context.recorder->PendingWriteOverlaps(target.htileAddress, metadataBytes), "the recognized HTILE clear is missing its pending write range");
switch (consumer) {
case ClearConsumer::Owner:
Require(DepthSurfaceHolds(context, DecodeTextureResource(words), sampled.get()), "a pending full BDA clear lost its native sampled owner");
break;
case ClearConsumer::Texture:
Require(CachedSampledTexture(context, words) == sampled, "a pending full BDA clear lost its native sampled view");
break;
case ClearConsumer::Attachment:
Require(DepthSurfaceView(context, target) == view, "a pending full BDA clear lost its native attachment");
break;
}
std::printf("Native full BDA clear: consumer=%u settled the recognized clear before WaitIdle\n", static_cast<unsigned>(consumer));
Require(!context.recorder->PendingWriteOverlaps(target.htileAddress, metadataBytes), "the native HTILE consumer did not settle its clear's pending write");
Require(Memory::StoredAllSince_nid_no_patch(target.htileAddress, metadataBytes, generation), "the native HTILE consumer did not complete its recognized clear");
device.WaitIdle();
for (std::size_t offset = 0; offset < BlockBytes; offset += 4u) {
std::uint32_t value = 0;
@@ -164,6 +186,7 @@ int RunNativeClear(AgcDriver::VulkanDevice& device) {
Require(value == (offset < metadataBytes ? 0xfffffff0u : 0u), "the native GPU clear did not write its exact metadata range");
}
std::printf("Native full BDA clear: exact %zu-byte metadata readback passed; complete=%d\n", metadataBytes, Memory::StoredAllSince_nid_no_patch(target.htileAddress, metadataBytes, generation));
Require(Memory::StoredAllSince_nid_no_patch(target.htileAddress, metadataBytes, generation), "the completed recognized native clear did not record exact coverage");
Require(CachedSampledTexture(context, words) == sampled, "a completed full BDA clear lost its native sampled view");
Require(DepthSurfaceView(context, target) == view, "a completed full BDA clear replaced its native attachment");
device.WaitIdle();
@@ -178,7 +201,11 @@ int main() {
try {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
return RunNativeClear(*device);
for (const auto consumer : {ClearConsumer::Owner, ClearConsumer::Texture, ClearConsumer::Attachment}) {
const auto result = RunNativeClear(*device, consumer);
if (result != 0) return result;
}
return 0;
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
@@ -7,6 +7,9 @@
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp"
#include "prx/libc/include/GuestArena.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "prx/libc/include/GuestWriteWatch.hpp"
@@ -21,6 +24,7 @@
#include <cstdlib>
#include <cstring>
#include <memory>
#include <mutex>
#include <optional>
#include <span>
#include <string>
@@ -35,6 +39,12 @@
#include <sys/mman.h>
#endif
namespace AgcDriver::DriverDetail {
struct DriverTestAccess {
static std::shared_ptr<VulkanDevice> GetDevice() { return Driver::Get().device.Load(); }
};
}
namespace {
using namespace AgcDriver::Graphics;
@@ -137,7 +147,7 @@ private:
class TargetMemory {
public:
explicit TargetMemory(std::size_t bytes) : bytes(bytes) {
explicit TargetMemory(std::size_t bytes, bool registerAllocation = false) : bytes(bytes), registered(registerAllocation) {
#ifdef _WIN32
pointer = GuestArena::GuestArenaAllocate_nid_postfix(bytes, 65536u);
GuestArena::GuestArenaCommit_nid_postfix(pointer, bytes, PAGE_READWRITE, bytes);
@@ -153,8 +163,10 @@ public:
#endif
Require(pointer != nullptr, "multisample target fixture allocation failed");
std::memset(pointer, 0xa5, bytes);
if (registered) GuestAllocations::Mutation().Add(pointer, bytes, true, true, true);
}
~TargetMemory() {
if (registered) GuestAllocations::Mutation().Remove(pointer);
#ifdef _WIN32
GuestArena::GuestArenaReset_nid_postfix(pointer, bytes);
GuestArena::GuestArenaRelease_nid_postfix(pointer, bytes);
@@ -168,8 +180,49 @@ public:
private:
void* pointer = nullptr;
std::size_t bytes;
bool registered = false;
};
alignas(256) constexpr std::array<std::uint32_t, 17> HtileMaskKernel{
0xd7460000u, 0x04010c06u, 0x34000084u, 0xdc388000u, 0x04020000u, 0xbf8c3f70u, 0xd7710008u, 0x00120805u,
0xd7710009u, 0x00120a05u, 0xd771000au, 0x00120c05u, 0xd771000bu, 0x00120e05u, 0xdc788000u, 0x00020800u,
0xbf810000u,
};
std::vector<std::uint32_t> DriverPm4Packet(std::uint32_t opcode, std::initializer_list<std::uint32_t> body) {
std::vector<std::uint32_t> words{0xc0000000u | (static_cast<std::uint32_t>(body.size() - 1u) << 16u) | (opcode << 8u)};
words.insert(words.end(), body);
return words;
}
Context SubmitDriverHtileClear(std::uint64_t address, std::unique_lock<AgcDriver::GuestMemory::GpuMutexType>& gpuLock) {
const auto shader = reinterpret_cast<std::uintptr_t>(HtileMaskKernel.data());
std::vector<std::uint32_t> commands;
const auto append = [&commands](std::vector<std::uint32_t> packet) { commands.insert(commands.end(), packet.begin(), packet.end()); };
append(DriverPm4Packet(0x76u, {0x20cu, static_cast<std::uint32_t>(shader >> 8u)}));
append(DriverPm4Packet(0x76u, {0x20du, static_cast<std::uint32_t>(shader >> 40u) & 0xffu}));
append(DriverPm4Packet(0x76u, {0x207u, 64u}));
append(DriverPm4Packet(0x76u, {0x208u, 1u}));
append(DriverPm4Packet(0x76u, {0x209u, 1u}));
append(DriverPm4Packet(0x76u, {0x213u, (6u << 1u) | 0x80u}));
append(DriverPm4Packet(0x76u, {0x240u, 0u}));
append(DriverPm4Packet(0x76u, {0x241u, 0u}));
append(DriverPm4Packet(0x76u, {0x242u, static_cast<std::uint32_t>(address)}));
append(DriverPm4Packet(0x76u, {0x243u, static_cast<std::uint32_t>(address >> 32u)}));
append(DriverPm4Packet(0x76u, {0x244u, 0xfffc00f0u}));
append(DriverPm4Packet(0x76u, {0x245u, 0u}));
append(DriverPm4Packet(0x15u, {32u, 1u, 1u, 0x41u}));
Packet packet{commands.data(), static_cast<std::uint32_t>(commands.size()), 0u, {}};
Require(sceAgcDriverSubmitDcb(&packet) == 0, "native depth HTILE clear: PM4 submission failed");
gpuLock.unlock();
try { AgcDriverWaitIdle_nid_postfix(); }
catch (...) { gpuLock.lock(); throw; }
gpuLock.lock();
const auto driverDevice = AgcDriver::DriverDetail::DriverTestAccess::GetDevice();
Require(driverDevice != nullptr, "HTILE clear driver device is missing");
return driverDevice->graphicsContext();
}
template<typename Action>
void TargetRefuses(Action action, std::string_view expected) {
std::string message;
@@ -548,7 +601,8 @@ void CheckDrawFeedback() {
Require(device != nullptr, "native depth draw feedback requires Vulkan");
constexpr VkExtent2D extent{5u, 3u};
constexpr std::uint32_t samples = 4u;
TargetMemory memory(static_cast<std::size_t>(MultisampledDepthBytes_nid_no_patch(extent, 4u, samples))), metadata(65536u);
const auto depthBytes = static_cast<std::size_t>(MultisampledDepthBytes_nid_no_patch(extent, 4u, samples));
TargetMemory memory(depthBytes), metadata(65536u);
std::memset(metadata.Data(), 0, 65536u);
DepthTarget depth{memory.Address(), 0u, extent, VK_FORMAT_D32_SFLOAT, 0.0f, 0u, metadata.Address(), false, samples};
depth.depthSwizzle = 24u;
@@ -581,6 +635,9 @@ void CheckDrawFeedback() {
const std::array<CompiledShader, 2> initial{{{ShaderRecompiler::ShaderStage::Vertex, &vertex, 0u}, {ShaderRecompiler::ShaderStage::Fragment, &producer, pixelOffset}}};
device->Draw(state, draw, initial);
device->WaitIdle();
std::array<std::byte, 1> probe{};
TargetRefuses([&] { AgcDriver::GuestMemory::Read(depth.address, probe); }, "sample-preserving guest publication");
Require(DepthSurfaceAt(depth.address), "a refused guest read retired a native depth surface a draw wrote");
reader.spirv = DepthFeedbackFragmentShader(binding, true);
reader.variantId = 3u;
const auto words = DepthSampleWords(depth);
@@ -597,10 +654,25 @@ void CheckDrawFeedback() {
const std::array<CompiledShader, 2> shaders{{{ShaderRecompiler::ShaderStage::Vertex, &vertex, 0u}, {ShaderRecompiler::ShaderStage::Fragment, &reader, pixelOffset}}};
TargetRefuses([&] { device->Draw(state, draw, shaders); }, "sampling a native multisampled depth target the draw attaches");
device->WaitIdle();
std::puts("Native depth feedback refused through the draw resource path");
TargetMemory testedMemory(depthBytes), testedMetadata(65536u);
std::memset(testedMetadata.Data(), 0, 65536u);
const auto guestByte = [](std::size_t offset) { return static_cast<std::byte>(offset * 7u + 3u); };
for (std::size_t offset = 0u; offset < depthBytes; ++offset) testedMemory.Data()[offset] = guestByte(offset);
auto tested = depth;
tested.address = testedMemory.Address();
tested.htileAddress = testedMetadata.Address();
state.depth = tested;
state.depthWrite = false;
device->Draw(state, draw, initial);
device->WaitIdle();
Require(DepthSurfaceAt(tested.address), "a depth-test-only draw left no resident native depth surface");
AgcDriver::GuestMemory::Read(tested.address + depthBytes - 1u, probe);
Require(probe[0] == guestByte(depthBytes - 1u), "a guest read after a depth-test-only draw did not return its guest bytes");
Require(!DepthSurfaceAt(tested.address), "a guest read left a native depth surface only depth-tested resident");
std::puts("Native depth feedback refused through the draw resource path; a written surface refused and a depth-tested one retired on guest read");
}
enum class ClearFault { None, PartialStore, CpuWrite, DepthWrite, BadMetadata, UnprovenDispatch, PendingWrite, Overlap };
enum class ClearFault { None, PartialStore, CpuWrite, DepthWrite, BadMetadata, UnprovenDispatch, PendingWrite, Overlap, PossibleStore, CompletedPossibleStore, DriverDispatch, ImportWindowWrite };
void CheckClearDispatch() {
const std::array<std::uint32_t, 17> code{
@@ -609,7 +681,7 @@ void CheckClearDispatch() {
0xd771000a, 0x00120c05, 0xd771000b, 0x00120e05,
0xdc788000, 0x00020800, 0xbf810000,
};
const std::array<std::uint32_t, 6> userData{0u, 0u, 65536u, 0u, 0xf0u, 0xf0u};
const std::array<std::uint32_t, 6> userData{0u, 0u, 65536u, 0u, 0xfffc00f0u, 0u};
const ShaderRecompiler::ShaderComputeStageInfo compute{{64u, 1u, 1u}, 0u, {true, false, false}, false, 1u};
const std::array<std::uint32_t, 5> packet{0u, 32u, 1u, 1u, 1u};
Require(HtileDepthClearBytes_nid_no_patch(code, userData, compute, packet, 0u) == 32768u, "complete HTILE mask dispatch was not recognized");
@@ -649,10 +721,10 @@ void CheckClearDispatch() {
}
}
void CheckDepthTarget(Context context, VkFormat format, std::uint32_t fragments, bool one, bool clearing = false, std::optional<bool> depthOnlyOverride = std::nullopt, ClearFault fault = ClearFault::None, bool iterate256 = true) {
void CheckDepthTarget(Context context, VkFormat format, std::uint32_t fragments, bool one, bool clearing, std::optional<bool> depthOnlyOverride, ClearFault fault, std::unique_lock<AgcDriver::GuestMemory::GpuMutexType>& gpuLock, bool iterate256 = true) {
const VkExtent2D extent{5u, 3u};
const auto bytes = static_cast<std::size_t>(MultisampledDepthBytes_nid_no_patch(extent, format == VK_FORMAT_D16_UNORM ? 2u : 4u, fragments));
TargetMemory memory(bytes), metadata(65536u);
TargetMemory memory(bytes), metadata(65536u, fault == ClearFault::DriverDispatch);
const auto metadataBytes = HtileMetadataBytes(extent);
const bool depthOnly = depthOnlyOverride.value_or(one);
const std::uint32_t pattern = one ? (depthOnly ? 0xfffffff0u : 0xfffc00f0u) : 0u;
@@ -679,6 +751,7 @@ void CheckDepthTarget(Context context, VkFormat format, std::uint32_t fragments,
}
const auto view = DepthSurfaceView(context, target);
Require(DepthSurfaceView(context, target) == view, "native depth attachment did not reuse its image");
NoteDepthSurfaceWrite(context, target);
std::array<std::byte, 1> beforeSampling{};
TargetRefuses([&] { AgcDriver::GuestMemory::Read(target.address + bytes - 1u, beforeSampling); }, "sample-preserving guest publication");
TargetRefuses([&] { RequireNoMultisampleTarget(target.htileAddress + metadataBytes - 1u, 1u, "a DMA copy"); }, "sample-preserving guest publication");
@@ -770,17 +843,65 @@ void CheckDepthTarget(Context context, VkFormat format, std::uint32_t fragments,
target.clearDepth = clearOne ? 1.0f : 0.0f;
Require(DepthSurfaceView(context, target) == view, "updating the native clear value replaced its attachment");
const std::uint32_t clearPattern = clearOne ? (depthOnly ? 0xfffffff0u : 0xfffc00f0u) : 0u;
const auto nativeBytes = fault == ClearFault::UnprovenDispatch ? 0u : static_cast<std::size_t>(metadataBytes);
NoteHtileDepthClear(target.htileAddress, static_cast<std::size_t>(metadataBytes), nativeBytes);
if (fault == ClearFault::Overlap) NoteHtileDepthClear(target.htileAddress, static_cast<std::size_t>(metadataBytes), nativeBytes);
const auto storedBytes = fault == ClearFault::PartialStore ? 4u : static_cast<std::size_t>(metadataBytes);
AgcDriver::GuestMemory::StoreOwnBytes(target.htileAddress, storedBytes, [&] {
for (std::size_t i = 0u; i < storedBytes / 4u; ++i) std::memcpy(metadata.Data() + i * 4u, &clearPattern, 4u);
if (fault == ClearFault::BadMetadata) metadata.Data()[0] = std::byte{0x0f};
});
if (fault == ClearFault::CpuWrite) metadata.Data()[metadataBytes - 1u] ^= std::byte{0x01};
if (fault == ClearFault::DepthWrite) memory.Data()[bytes - 1u] ^= std::byte{0x01};
if (fault == ClearFault::PendingWrite) QueueTargetByteWrite(context, recorder, target.htileAddress, std::byte{0});
if (fault == ClearFault::DriverDispatch && clearOne) {
struct ShutdownDriver {
~ShutdownDriver() {
try { AgcDriverShutdown_nid_postfix(); } catch (...) {}
}
} shutdownDriver;
const auto generation = AgcDriver::GuestMemory::TrackerGeneration();
const auto driverContext = SubmitDriverHtileClear(target.htileAddress, gpuLock);
recorder.Activate();
Require(Recorder::Active() == &recorder, "driver idle did not restore the native depth fixture recorder");
if (!AgcDriver::GuestMemory::Watched(target.htileAddress, metadataBytes)) {
Require(PrepareImportWatch(driverContext) == ImportWatch::Unwatch,
"the HTILE metadata range lost write-watch coverage on a device whose host imports stay watched");
std::puts("skipped native HTILE write-coverage assertion: the write tracker does not cover the imported metadata range; the production depth-sampling path may still decline this clear");
TargetRefuses([&] { Require(DepthSurfaceHolds(context, DecodeTextureResource(words), texture.get()), "native depth owner was not retained"); },
"native multisample depth clear requires tracked HTILE generations");
return;
} else {
const bool storedAll = AgcDriver::GuestMemory::StoredAllSince_nid_no_patch(target.htileAddress, metadataBytes, generation);
Require(storedAll, "driver idle returned before recording the completed HTILE dispatch");
}
} else {
const auto nativeBytes = fault == ClearFault::UnprovenDispatch ? 0u : static_cast<std::size_t>(metadataBytes);
if (fault == ClearFault::PartialStore || fault == ClearFault::PossibleStore || fault == ClearFault::CompletedPossibleStore) {
for (std::size_t i = 0u; i < metadataBytes / 4u; ++i) std::memcpy(metadata.Data() + i * 4u, &clearPattern, 4u);
}
const bool completionCandidate = NoteHtileDepthClear(target.htileAddress, static_cast<std::size_t>(metadataBytes), nativeBytes);
if (fault == ClearFault::ImportWindowWrite) {
const auto beforeImport = AgcDriver::GuestMemory::TrackerGeneration();
Require(AgcDriver::GuestMemory::ImportWatched(target.htileAddress, static_cast<std::size_t>(metadataBytes), [&] {
metadata.Data()[0] ^= std::byte{0x01};
return true;
}), "HTILE host import simulation failed");
Require(AgcDriver::GuestMemory::CollectWritesUncached(target.htileAddress, static_cast<std::size_t>(metadataBytes)) > beforeImport, "HTILE import window did not stamp its changed page");
}
if (completionCandidate) ArmHtileDepthClear(target.htileAddress, static_cast<std::size_t>(metadataBytes));
if (fault == ClearFault::Overlap) NoteHtileDepthClear(target.htileAddress, static_cast<std::size_t>(metadataBytes), nativeBytes);
const auto storedBytes = fault == ClearFault::PartialStore ? 4u : static_cast<std::size_t>(metadataBytes);
if (fault == ClearFault::PossibleStore || fault == ClearFault::CompletedPossibleStore) {
const auto generation = AgcDriver::GuestMemory::TrackerGeneration();
AgcDriver::GuestMemory::MarkPossiblyWritten(target.htileAddress, metadataBytes);
Require(!AgcDriver::GuestMemory::StoredAllSince_nid_no_patch(target.htileAddress, metadataBytes, generation), "a possible HTILE range proved complete coverage");
if (fault == ClearFault::CompletedPossibleStore) CompleteHtileDepthClear(target.htileAddress, static_cast<std::size_t>(metadataBytes));
} else AgcDriver::GuestMemory::StoreOwnBytes(target.htileAddress, storedBytes, [&] {
for (std::size_t i = 0u; i < storedBytes / 4u; ++i) std::memcpy(metadata.Data() + i * 4u, &clearPattern, 4u);
if (fault == ClearFault::BadMetadata) metadata.Data()[0] = std::byte{0x0f};
});
if (fault == ClearFault::CpuWrite) metadata.Data()[metadataBytes - 1u] ^= std::byte{0x01};
if (fault == ClearFault::DepthWrite) memory.Data()[bytes - 1u] ^= std::byte{0x01};
if (fault == ClearFault::PendingWrite) {
QueueTargetByteWrite(context, recorder, target.htileAddress, std::byte{0});
std::string pendingRefusal;
try { CachedSampledTexture(context, words); }
catch (const std::exception& error) { pendingRefusal = error.what(); }
const bool refused = pendingRefusal.find("external GPU writes") != std::string::npos;
if (!refused) std::fprintf(stderr, "Pending HTILE texture refusal: %s\n", pendingRefusal.c_str());
Require(refused, "an unrecognized pending HTILE write was accepted or refused for another reason");
}
}
Require(DepthSurfaceHolds(context, DecodeTextureResource(words), texture.get()), "completed native depth clear lost its sampled view");
recorder.Sync();
Require(DepthSurfaceView(context, target) == view && CachedSampledTexture(context, words) == texture, "completed native depth clear replaced an attachment or cached view");
@@ -843,6 +964,59 @@ void CheckDepthTarget(Context context, VkFormat format, std::uint32_t fragments,
std::printf("Native depth format=%u samples=%u clear=%u iterate256=%u: imported, rasterized twice, sampled and refused conflicts\n", static_cast<std::uint32_t>(format), fragments, one, iterate256);
}
void CheckUnwrittenGuestAccess(Context context, VkFormat format, std::uint32_t fragments) {
const VkExtent2D extent{5u, 3u};
const auto bytes = static_cast<std::size_t>(MultisampledDepthBytes_nid_no_patch(extent, format == VK_FORMAT_D16_UNORM ? 2u : 4u, fragments));
const auto metadataBytes = static_cast<std::size_t>(HtileMetadataBytes(extent));
TargetMemory memory(bytes), metadata(65536u), unrelated(65536u);
const auto guestByte = [](std::size_t offset) { return static_cast<std::byte>(offset * 7u + 3u); };
for (std::size_t offset = 0u; offset < bytes; ++offset) memory.Data()[offset] = guestByte(offset);
std::memset(metadata.Data(), 0, metadataBytes);
DepthTarget target{memory.Address(), 0u, extent, format, 0.0f, 0u, metadata.Address(), false, fragments};
target.depthSwizzle = 24u;
target.iterate256 = target.htilePipeAligned = target.htileDepthOnly = true;
Recorder recorder(context);
recorder.Activate();
struct Cleanup {
Recorder& recorder;
Context context;
~Cleanup() { recorder.Sync(); ClearCachedTextures(context.device); ClearDepthSurfaces(context.device); }
} cleanup{recorder, context};
const auto resident = [&] { return HasResidentDepthGuards_nid_no_patch() && DepthSurfaceAt(target.address); };
auto view = DepthSurfaceView(context, target);
Require(view != VK_NULL_HANDLE && resident(), "unwritten native depth fixture has no resident owner");
auto otherDevice = context;
otherDevice.device = VK_NULL_HANDLE;
NoteDepthSurfaceWrite(otherDevice, target);
auto unattached = target;
unattached.address += 65536u;
NoteDepthSurfaceWrite(context, unattached);
std::array<std::byte, 1> probe{};
AgcDriver::GuestMemory::Read(unrelated.Address(), probe);
Require(resident(), "an unrelated guest read retired a native depth surface");
for (const bool readMetadata : {false, true}) {
if (readMetadata) RequireNoMultisampleTarget(target.htileAddress + metadataBytes - 1u, 1u, "a DMA copy");
else {
AgcDriver::GuestMemory::Read(target.address + bytes - 1u, probe);
Require(probe[0] == guestByte(bytes - 1u), "a guest read over an unwritten native depth surface did not return its guest bytes");
}
Require(!resident(), "a guest access left an unwritten native depth surface resident");
RequireNoResidentDepthRead_nid_no_patch(target.address, bytes);
RequireNoResidentDepthRead_nid_no_patch(target.htileAddress, metadataBytes);
recorder.Sync();
const auto rebound = DepthSurfaceView(context, target);
Require(rebound != VK_NULL_HANDLE && rebound != view && resident(), "rebinding after a guest access did not import a new native depth surface");
view = rebound;
}
NoteDepthSurfaceWrite(context, target);
TargetRefuses([&] { AgcDriver::GuestMemory::Read(target.address, probe); }, "sample-preserving guest publication");
TargetRefuses([&] { RequireNoMultisampleTarget(target.htileAddress, 1u, "a DMA copy"); }, "sample-preserving guest publication");
Require(resident(), "a refused guest access retired a written native depth surface");
for (std::size_t offset = 0u; offset < bytes; ++offset) Require(memory.Data()[offset] == guestByte(offset), "retiring an unwritten native depth surface changed its guest bytes");
Require(std::all_of(metadata.Data(), metadata.Data() + metadataBytes, [](std::byte value) { return value == std::byte{0}; }), "retiring an unwritten native depth surface changed its HTILE");
std::printf("Native depth format=%u samples=%u: guest access retired the unwritten surface and refused the written one\n", static_cast<std::uint32_t>(format), fragments);
}
void CheckHtileRouting(Context context, VkFormat format, std::uint32_t fragments) {
const VkExtent2D extent{5u, 3u};
const auto bytes = static_cast<std::size_t>(MultisampledDepthBytes_nid_no_patch(extent, format == VK_FORMAT_D16_UNORM ? 2u : 4u, fragments));
@@ -1031,6 +1205,7 @@ void CheckRetirement(Context context, VkFormat format, std::uint32_t samples, st
const auto words = DepthSampleWords(target);
const auto resource = DecodeTextureResource(words);
const auto firstView = DepthSurfaceView(context, target);
NoteDepthSurfaceWrite(context, target);
auto firstTexture = DepthSurfaceTexture(context, words, resource, VkComponentMapping{});
Require(firstTexture != nullptr, "retirement fixture has no native sampled view");
ColorTarget color{colorMemory.Address(), extent, VK_FORMAT_R8G8B8A8_UNORM, extent.width * extent.height * 4u, 0u};
@@ -1129,7 +1304,7 @@ int main(int argc, char** argv) {
}
CheckDrawFeedback();
const auto context = device->GetContext();
const std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex());
std::unique_lock lock(AgcDriver::GuestMemory::GpuMutex());
Require(DepthSupported(context, VK_FORMAT_D32_SFLOAT, 4u), "the native depth regression requires sampled D32 with four samples");
if (argc == 2 && std::string_view(argv[1]) == "--clear-refusals") {
for (const auto& [fault, expected] : std::array{
@@ -1137,10 +1312,11 @@ int main(int argc, char** argv) {
std::pair{ClearFault::CpuWrite, "CPU writes raced"},
std::pair{ClearFault::DepthWrite, "guest writes"},
std::pair{ClearFault::BadMetadata, "does not prove its clear value"},
std::pair{ClearFault::PossibleStore, "no complete tracked HTILE store"},
std::pair{ClearFault::UnprovenDispatch, "incomplete or unproven"},
std::pair{ClearFault::PendingWrite, "external GPU writes"},
std::pair{ClearFault::Overlap, "overlapping native multisample depth"}}) {
TargetRefuses([&] { CheckDepthTarget(context, VK_FORMAT_D32_SFLOAT, 4u, false, true, false, fault); }, expected);
TargetRefuses([&] { CheckDepthTarget(context, VK_FORMAT_D32_SFLOAT, 4u, false, true, false, fault, lock); }, expected);
std::printf("Native depth clear fault=%u refused: %s\n", static_cast<std::uint32_t>(fault), expected);
}
return 0;
@@ -1152,10 +1328,16 @@ int main(int argc, char** argv) {
for (const auto samples : {2u, 4u, 8u}) {
if (!DepthSupported(context, format, samples)) { unavailable += 4u; continue; }
for (const bool depthOnly : {false, true}) {
for (const bool one : {false, true}) { CheckDepthTarget(context, format, samples, one, true, depthOnly); ++checked; }
for (const bool one : {false, true}) { CheckDepthTarget(context, format, samples, one, true, depthOnly, ClearFault::None, lock); ++checked; }
}
}
}
CheckDepthTarget(context, VK_FORMAT_D32_SFLOAT, 4u, false, true, false, ClearFault::CompletedPossibleStore, lock);
++checked;
CheckDepthTarget(context, VK_FORMAT_D32_SFLOAT, 4u, false, true, false, ClearFault::ImportWindowWrite, lock);
++checked;
CheckDepthTarget(context, VK_FORMAT_D32_SFLOAT, 4u, false, true, false, ClearFault::DriverDispatch, lock);
++checked;
std::printf("Native depth completed clear cases checked=%u unavailable=%u\n", checked, unavailable);
return 0;
}
@@ -1176,9 +1358,10 @@ int main(int argc, char** argv) {
for (const auto samples : {2u, 4u, 8u}) {
if (!DepthSupported(context, format, samples)) { unavailable += 4u; continue; }
for (const bool one : {false, true}) {
for (const bool iterate256 : {true, false}) { CheckDepthTarget(context, format, samples, one, false, std::nullopt, ClearFault::None, iterate256); ++checked; }
for (const bool iterate256 : {true, false}) { CheckDepthTarget(context, format, samples, one, false, std::nullopt, ClearFault::None, lock, iterate256); ++checked; }
}
CheckHtileRouting(context, format, samples);
CheckUnwrittenGuestAccess(context, format, samples);
}
}
CheckEligibility(context);
@@ -45,6 +45,7 @@ constexpr std::uint32_t Height = 128;
constexpr std::uint32_t ScissorWidth = 128;
constexpr std::size_t BlockBytes = 65536;
constexpr std::uint32_t Float11_11_10Info = 0x4171cu;
constexpr std::uint32_t StandardOrderInfo = Float11_11_10Info & ~0x1800u;
constexpr std::uint32_t TiledAttrib3 = 0x4dc6c000u;
constexpr std::uint32_t LinearAttrib3 = 0x09000000u;
constexpr std::uint32_t Float32Export = 9;
@@ -58,7 +59,7 @@ constexpr std::array<std::array<float, 4>, 3> Triangle{{
{-1.0f, -1.0f, 0.5f, 1.0f}, {3.0f, -1.0f, 0.5f, 1.0f}, {-1.0f, 3.0f, 0.5f, 1.0f}
}};
alignas(256) std::array<std::array<std::uint32_t, 64>, 32> Programs{};
alignas(256) std::array<std::array<std::uint32_t, 64>, 64> Programs{};
std::size_t programCount = 0;
std::uint32_t SmallFloat(float value, std::uint32_t mantissaBits) {
@@ -78,7 +79,8 @@ std::uint32_t SmallFloat(float value, std::uint32_t mantissaBits) {
return (static_cast<std::uint32_t>(exponent - 1 + 15) << mantissaBits) | static_cast<std::uint32_t>(std::floor((fraction * 2.0 - 1.0) * scale));
}
std::uint32_t Packed(std::array<float, 3> rgb) {
std::uint32_t Packed(std::array<float, 3> rgb, bool standardOrder) {
if (standardOrder) return SmallFloat(rgb[0], 5) | (SmallFloat(rgb[1], 6) << 10u) | (SmallFloat(rgb[2], 6) << 21u);
return SmallFloat(rgb[2], 5) | (SmallFloat(rgb[1], 6) << 10u) | (SmallFloat(rgb[0], 6) << 21u);
}
@@ -170,17 +172,17 @@ struct Block {
std::uint8_t* data = nullptr;
};
AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, std::uint32_t attrib3) {
AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, std::uint32_t attrib3, bool standardOrder) {
AgcDriver::Registers cx;
cx[0x318] = static_cast<std::uint32_t>(block.Address() >> 8u);
cx[0x31b] = 0;
cx[0x31c] = Float11_11_10Info;
cx[0x31c] = standardOrder ? StandardOrderInfo : Float11_11_10Info;
cx[0x31d] = 0;
cx[0x3b0] = ((Width - 1u) << 14u) | (Height - 1u);
cx[0x3b8] = attrib3;
cx[0x390] = static_cast<std::uint32_t>(block.Address() >> 40u);
auto color = AgcDriver::Graphics::DecodeColorBuffer(cx, 0);
Require(color.format == VK_FORMAT_R32_UINT && color.elementBytes == 4 && color.componentMapping == 0xc6u && color.packing == ShaderRecompiler::ColorExportPacking::Float11_11_10 && color.bytes == block.bytes, "the 11_11_10 float target did not decode as a packed R32_UINT surface");
Require(color.format == VK_FORMAT_R32_UINT && color.elementBytes == 4 && color.componentMapping == (standardOrder ? 0xe4u : 0xc6u) && color.packing == ShaderRecompiler::ColorExportPacking::Float11_11_10 && color.bytes == block.bytes, "the 11_11_10 float target did not decode as a packed R32_UINT surface");
return color;
}
@@ -290,10 +292,10 @@ std::string Describe(std::array<float, 3> rgb) {
return text;
}
void TargetTests(AgcDriver::VulkanDevice& device, Block& block, std::uint32_t attrib3, ColorTileMode mode, const char* kind) {
void TargetTests(AgcDriver::VulkanDevice& device, Block& block, std::uint32_t attrib3, ColorTileMode mode, const char* kind, bool standardOrder) {
const ColorTargetLayout layout(Width, Height, mode, 4);
Require(layout.Bytes() == block.bytes, "the test surface size disagrees with its layout");
const auto color = DecodeTarget(block, attrib3);
const auto color = DecodeTarget(block, attrib3, standardOrder);
auto before = Fill(block);
const float nan = std::numeric_limits<float>::quiet_NaN();
const float infinity = std::numeric_limits<float>::infinity();
@@ -311,12 +313,12 @@ void TargetTests(AgcDriver::VulkanDevice& device, Block& block, std::uint32_t at
}};
for (const auto& rgb : cases) {
Draw(device, color, Float32Export, Float32Program(rgb));
ExpectSurface(device, block, layout, before, Packed(rgb), std::string("a 32_ABGR export of ") + Describe(rgb) + " into a " + kind + " 11_11_10 float target");
ExpectSurface(device, block, layout, before, Packed(rgb, standardOrder), std::string("a 32_ABGR export of ") + Describe(rgb) + " into a " + kind + " 11_11_10 float target");
before = ReadBack(device, block);
}
const std::array<float, 3> halves{0.5f, 0.75f, 0.125f};
Draw(device, color, Float16Export, Float16Program(halves));
ExpectSurface(device, block, layout, before, Packed(halves), std::string("an FP16_ABGR export of ") + Describe(halves) + " into a " + kind + " 11_11_10 float target");
ExpectSurface(device, block, layout, before, Packed(halves, standardOrder), std::string("an FP16_ABGR export of ") + Describe(halves) + " into a " + kind + " 11_11_10 float target");
}
}
@@ -327,8 +329,10 @@ int main() {
if (!device) return VulkanTestSkipped;
Block tiled(ColorTargetLayout(Width, Height, ColorTileMode::RenderTarget, 4).Bytes());
Block linear(ColorTargetLayout(Width, Height, ColorTileMode::Linear, 4).Bytes());
TargetTests(*device, tiled, TiledAttrib3, ColorTileMode::RenderTarget, "tiled");
TargetTests(*device, linear, LinearAttrib3, ColorTileMode::Linear, "linear");
for (const bool standardOrder : {false, true}) {
TargetTests(*device, tiled, TiledAttrib3, ColorTileMode::RenderTarget, standardOrder ? "tiled standard-order" : "tiled", standardOrder);
TargetTests(*device, linear, LinearAttrib3, ColorTileMode::Linear, standardOrder ? "linear standard-order" : "linear", standardOrder);
}
std::puts("11_11_10 float color target tests passed");
return 0;
} catch (const std::exception& error) {
@@ -11,6 +11,7 @@
#include <cstdlib>
#include <future>
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
@@ -75,16 +76,29 @@ void AppendLabel(std::vector<std::uint32_t>& words, std::uint32_t* target, std::
}
struct Blocker {
std::atomic<bool> release{false};
struct State {
std::atomic<bool> release{false};
std::atomic<bool> done{false};
};
std::shared_ptr<State> state = std::make_shared<State>();
std::uint32_t* target = nullptr;
~Blocker() { release = true; }
~Blocker() { Release(); }
void Release() { state->release = true; }
void Enqueue(std::vector<DrawPipeline::Range> writes = {}) {
DrawPipeline::Queue0().Enqueue([this] {
while (!release.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1));
DrawPipeline::Queue0().Enqueue([state = state, target = target] {
while (!state->release.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1));
if (target != nullptr) std::atomic_ref<std::uint32_t>(*target).store(1);
std::lock_guard gpuLock(AgcDriver::GuestMemory::GpuMutex());
{ std::lock_guard gpuLock(AgcDriver::GuestMemory::GpuMutex()); }
state->done = true;
}, std::move(writes));
}
void Join() const {
const auto start = std::chrono::steady_clock::now();
while (!state->done.load()) {
Require(std::chrono::steady_clock::now() - start < std::chrono::seconds(20), "the blocker never ran");
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
};
void SubmitBehind(Blocker& blocker, std::vector<std::uint32_t>& words) {
@@ -107,7 +121,7 @@ void ReleaseWhen(Blocker& blocker, std::size_t reached, std::size_t passed) {
Require(now - start < std::chrono::seconds(20), "the queue worker never reached the fill");
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
blocker.release = true;
blocker.Release();
}
void Finish() {
@@ -118,6 +132,11 @@ void Finish() {
std::_Exit(1);
}
idle.get();
const auto start = std::chrono::steady_clock::now();
while (DrawPipeline::Queue0().Outstanding() != 0) {
Require(std::chrono::steady_clock::now() - start < std::chrono::seconds(20), "the draw pipeline kept an item after the queue went idle");
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast<std::uintptr_t>(Output.data()), sizeof(Output));
AgcDriver::GuestMemory::FlushGpuWrites(reinterpret_cast<std::uintptr_t>(Scratch.data()), sizeof(Scratch));
}
@@ -135,6 +154,7 @@ void InputsAfterQueuedLabels() {
SubmitBehind(blocker, words);
ReleaseWhen(blocker, 4, 5);
Finish();
blocker.Join();
for (std::size_t i = 0; i < Output.size(); ++i) {
const auto expected = i < 128 ? 0xababababu : 0xcafebabeu;
Require(Output[i] == expected, "a fill read its control or pattern before the queued labels that write them, at " + std::to_string(i));
@@ -156,6 +176,7 @@ void FillIntoFullPipeline() {
SubmitBehind(blocker, words);
ReleaseWhen(blocker, depth, depth + 1);
Finish();
blocker.Join();
for (std::size_t i = 0; i + 2 < depth; ++i) Require(Labels[i] == i + 1, "a queued label was not stored");
for (std::size_t i = 0; i < Output.size(); ++i) Require(Output[i] == (i < 256 ? 0x5a5a5a5au : 0xcafebabeu), "a fill behind a full draw pipeline did not land at " + std::to_string(i));
}
@@ -180,8 +201,9 @@ void SatisfiedWaitKeepsUnrelatedQueuedWork() {
while (DrawPipeline::Queue0().Outstanding() < 2 && std::chrono::steady_clock::now() < deadline)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
const bool keptQueued = DrawPipeline::Queue0().Outstanding() >= 2;
blocker.release = true;
blocker.Release();
Finish();
blocker.Join();
Require(keptQueued, "a satisfied WAIT_REG_MEM drained unrelated queued work");
Require(marker == 1, "a label after a satisfied WAIT_REG_MEM did not execute");
}
@@ -211,11 +233,12 @@ void SatisfiedWaitDrainsOverlappingQueuedWork() {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
const bool drained = DrawPipeline::DrainRequestsByOpcode(0x3c) > drainsBefore;
const bool labelQueuedEarly = DrawPipeline::Queue0().Outstanding() >= 2;
blocker.release = true;
blocker.Release();
Require(submitted.wait_for(std::chrono::seconds(20)) == std::future_status::ready,
"WAIT_REG_MEM submission did not finish after the overlapping write");
submitted.get();
Finish();
blocker.Join();
Require(drained && !labelQueuedEarly, "a satisfied WAIT_REG_MEM skipped an overlapping queued write");
Require(marker == 1, "a label after an overlapping WAIT_REG_MEM did not execute");
}
@@ -17,6 +17,7 @@
#include <future>
#include <initializer_list>
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
@@ -138,20 +139,34 @@ void Flush(const std::array<std::byte, 1024>& memory) {
}
struct Blocker {
std::atomic<bool> release{false};
struct State {
std::atomic<bool> release{false};
std::atomic<bool> done{false};
};
std::shared_ptr<State> state = std::make_shared<State>();
void Release() { state->release = true; }
void Enqueue() {
DrawPipeline::Queue0().Enqueue([this] {
while (!release.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1));
std::lock_guard gpuLock(AgcDriver::GuestMemory::GpuMutex());
DrawPipeline::Queue0().Enqueue([state = state] {
while (!state->release.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1));
{ std::lock_guard gpuLock(AgcDriver::GuestMemory::GpuMutex()); }
state->done = true;
}, {});
}
void Join() const {
const auto start = std::chrono::steady_clock::now();
while (!state->done.load()) {
Require(std::chrono::steady_clock::now() - start < std::chrono::seconds(20), "the blocker never ran");
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
};
void SubmitBehind(Blocker& blocker, std::vector<std::uint32_t>& commands) {
void SubmitBehind(Blocker& blocker, std::vector<std::uint32_t>& commands, std::size_t queuedBefore) {
std::unique_lock gpuLock(AgcDriver::GuestMemory::GpuMutex());
Packet packet{commands.data(), static_cast<std::uint32_t>(commands.size()), 0, {}};
AgcDriver::Submit(&packet, 0);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
const auto start = std::chrono::steady_clock::now();
while (DrawPipeline::Queue0().Outstanding() < queuedBefore && std::chrono::steady_clock::now() - start < std::chrono::seconds(60)) std::this_thread::sleep_for(std::chrono::milliseconds(1));
blocker.Enqueue();
}
@@ -190,19 +205,20 @@ void IndirectDrawsQueueBehindTheCommitter() {
AppendTarget(commands, SecondMemory, Clipped);
AppendIndirect(commands);
Blocker blocker;
SubmitBehind(blocker, commands);
SubmitBehind(blocker, commands, 3);
const auto start = std::chrono::steady_clock::now();
while (DrawPipeline::Queue0().Outstanding() < 3) {
if (std::chrono::steady_clock::now() - start > std::chrono::seconds(10)) {
const auto outstanding = DrawPipeline::Queue0().Outstanding();
blocker.release = true;
blocker.Release();
Finish();
Require(false, "the indirect draws drained the pipeline instead of queuing behind it (" + std::to_string(outstanding) + " items outstanding, expected the blocker and two draws)");
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
blocker.release = true;
blocker.Release();
Finish();
blocker.Join();
Flush(FirstMemory);
Flush(SecondMemory);
SameAsDirect(FirstMemory, "the first queued indirect draw");
@@ -219,12 +235,13 @@ void IndirectDrawWaitsForItsQueuedRecordWrite() {
AppendTarget(commands, WrittenMemory, Clipped);
AppendIndirect(commands);
Blocker blocker;
SubmitBehind(blocker, commands);
const auto drainsBefore = DrawPipeline::DrainRequestsByOpcode(0x100);
SubmitBehind(blocker, commands, 1);
const auto start = std::chrono::steady_clock::now();
while (DrawPipeline::Queue0().Outstanding() < 2 && std::chrono::steady_clock::now() - start < std::chrono::seconds(10)) std::this_thread::sleep_for(std::chrono::milliseconds(1));
std::this_thread::sleep_for(std::chrono::milliseconds(500));
blocker.release = true;
while (DrawPipeline::DrainRequestsByOpcode(0x100) == drainsBefore && std::chrono::steady_clock::now() - start < std::chrono::seconds(10)) std::this_thread::sleep_for(std::chrono::milliseconds(1));
blocker.Release();
Finish();
blocker.Join();
Flush(WrittenMemory);
Require(LateRecords[0] == 3, "the queued label did not store the record's vertex count");
SameAsDirect(WrittenMemory, "the indirect draw whose record a queued label wrote");
Loaded 100 of 578 files, more files were not shown because too many files have changed in this diff. Show more