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

Keeps this branch's FormatVersion at 93, above main's 91 (#21758).
This commit is contained in:
Yunus Shaikh committed 2026-11-19 17:59:19 -08:00
commit 5b21241399
947 files changed
+51849 -4521

No files matched your search

+10 -6
View File
@@ -293,7 +293,7 @@ jobs:
needs: eligibility
if: ${{ needs.eligibility.outputs.relinker == 'true' }}
runs-on: ${{ matrix.os }}
timeout-minutes: 15
timeout-minutes: ${{ matrix.os == 'windows-latest' && 20 || 15 }}
strategy:
fail-fast: false
matrix:
@@ -645,14 +645,11 @@ jobs:
mem_mb=$(awk '/^MemTotal:/ { print int($2 / 1024) }' /proc/meminfo)
slots=$(( (mem_mb - 2048) / 1024 ))
slots=$(( slots < 1 ? 1 : slots ))
tests=$(( cpus - busy ))
tests=$(( tests < 1 ? 1 : tests ))
slot_dir=$CCACHE_DIR/compile-slots
mkdir -p -m 1777 "$slot_dir"
test -w "$slot_dir"
echo "cpus=$cpus load=$busy mem_total_mb=$mem_mb -> build jobs $cpus, cold compiles $slots per host, tests $tests"
echo "cpus=$cpus load=$busy mem_total_mb=$mem_mb -> build jobs $cpus, cold compiles $slots per host"
echo "CMAKE_BUILD_PARALLEL_LEVEL=$cpus" >> "$GITHUB_ENV"
echo "CTEST_PARALLEL_LEVEL=$tests" >> "$GITHUB_ENV"
echo "CCACHE_PREFIX=$GITHUB_WORKSPACE/tools/compile_slot.sh" >> "$GITHUB_ENV"
echo "ANYPS5_COMPILE_SLOT_DIR=$slot_dir" >> "$GITHUB_ENV"
echo "ANYPS5_COMPILE_SLOTS=$slots" >> "$GITHUB_ENV"
@@ -702,7 +699,14 @@ jobs:
if [ -f build/select.ninja ]; then ninja -C build -f select.ninja -j "$CMAKE_BUILD_PARALLEL_LEVEL" -l "$(nproc)" selected; else cmake --build build -- -l "$(nproc)"; fi
- id: libs
run: cmake --build build --target libs -- -l "$(nproc)"
- run: python3 tools/select_tests.py ctest build --test-load "$(nproc)" --output-on-failure --timeout 120 --output-log ctest.log --output-junit ctest.xml
- name: Run the tests
run: |
cpus=$(nproc)
busy=$(awk '{ printf "%d", $1 + 0.5 }' /proc/loadavg)
tests=$(( cpus - busy ))
tests=$(( tests < 4 ? 4 : tests ))
echo "cpus=$cpus load=$busy -> tests $tests"
CTEST_PARALLEL_LEVEL=$tests python3 tools/select_tests.py ctest build --test-load "$(nproc)" --output-on-failure --timeout 120 --output-log ctest.log --output-junit ctest.xml
env:
ANYPS5_REQUIRE_VULKAN: 1
GALLIUM_OVERRIDE_CPU_CAPS: avx
+7
View File
@@ -116,3 +116,10 @@ cookies.txt
.env
.env.local
.env.*
*.pem
*.key
*.p12
*.pfx
id_rsa*
id_ed25519*
+19 -2
View File
@@ -320,15 +320,22 @@ if(BUILD_TESTING)
target_include_directories(pad_input_script_tests PRIVATE core/libs)
add_test(NAME pad_input_script COMMAND pad_input_script_tests)
set_tests_properties(pad_input_script PROPERTIES TIMEOUT 20)
set(anyps5HostTestTemp ${CMAKE_BINARY_DIR}/test-temp)
file(MAKE_DIRECTORY ${anyps5HostTestTemp})
set_property(TEST shader_cache_file_read pad_command_file pad_recording pad_input_script APPEND PROPERTY
ENVIRONMENT_MODIFICATION
"TMPDIR=set:${anyps5HostTestTemp};TEMP=set:${anyps5HostTestTemp};TMP=set:${anyps5HostTestTemp}")
if(Python3_Interpreter_FOUND)
get_property(windows_tooling_before DIRECTORY PROPERTY TESTS)
add_test(NAME mingw_host_only_test_targets COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_mingw_host_only_test_targets.py)
set_tests_properties(mingw_host_only_test_targets PROPERTIES TIMEOUT 30)
add_test(NAME patch_lib_atrac9 COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_patch_lib_atrac9.py ${CMAKE_COMMAND})
set_tests_properties(patch_lib_atrac9 PROPERTIES TIMEOUT 60)
add_test(NAME build_changed_guest_tests COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_build_changed_guest_tests.py)
set_tests_properties(build_changed_guest_tests PROPERTIES TIMEOUT 30)
add_test(NAME shader_cache_native_paths COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/tests/test_shader_cache_native_paths.py
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ShaderCacheVersion.cmake ${CMAKE_COMMAND})
@@ -354,11 +361,13 @@ if(BUILD_TESTING)
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap.py)
add_test(NAME pr_labels COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_labels.py)
set_tests_properties(pr_labels PROPERTIES TIMEOUT 30)
add_test(NAME progress_history_date_window COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_history.py HistoryDateWindowTests)
set_tests_properties(progress_history_date_window PROPERTIES TIMEOUT 20)
add_test(NAME pr_ready COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_ready.py)
set_tests_properties(pr_ready PROPERTIES TIMEOUT 30)
add_test(NAME pr_unchanged COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_unchanged.py)
add_test(NAME progress_history COMMAND ${Python3_EXECUTABLE}
@@ -410,6 +419,7 @@ if(BUILD_TESTING)
set_tests_properties(tools_catalog_json PROPERTIES TIMEOUT 20)
add_test(NAME validate_patch_catalog COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_validate_patch_catalog.py)
set_tests_properties(validate_patch_catalog PROPERTIES TIMEOUT 30)
endif()
add_test(NAME annotation_symbols_ghidra COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_annotation_symbols_ghidra.py)
@@ -443,6 +453,7 @@ if(BUILD_TESTING)
set_tests_properties(build_mingw_host_only_tests_script PROPERTIES TIMEOUT 60)
add_test(NAME export_gap COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_export_gap.py)
set_tests_properties(export_gap PROPERTIES TIMEOUT 30)
add_test(NAME unwrap_self COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_unwrap_self.py)
add_test(NAME tools_compile_plan COMMAND ${Python3_EXECUTABLE}
@@ -450,6 +461,7 @@ if(BUILD_TESTING)
set_tests_properties(tools_compile_plan PROPERTIES TIMEOUT 20)
add_test(NAME audit_dump COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_audit_dump.py)
set_tests_properties(audit_dump PROPERTIES TIMEOUT 30)
add_test(NAME forced_include_paths COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_forced_include_paths.py
--cmake "${CMAKE_COMMAND}" --compiler "${CMAKE_CXX_COMPILER}"
@@ -457,10 +469,13 @@ if(BUILD_TESTING)
set_tests_properties(forced_include_paths PROPERTIES TIMEOUT 30)
add_test(NAME ffmpeg_cache_keys COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_ffmpeg_cache_keys.py)
set_tests_properties(ffmpeg_cache_keys PROPERTIES TIMEOUT 30)
add_test(NAME winlibs_digest COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_winlibs_digest.py)
set_tests_properties(winlibs_digest PROPERTIES TIMEOUT 30)
add_test(NAME progress_comment_concurrency COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_comment_concurrency.py)
set_tests_properties(progress_comment_concurrency PROPERTIES TIMEOUT 30)
add_test(NAME eligibility_paths COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_eligibility_paths.py)
add_test(NAME release_workflow COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_release_workflow.py)
@@ -556,6 +571,8 @@ if(BUILD_TESTING)
add_test(NAME tools_release_notes_check COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_release_notes_check.py)
set_tests_properties(tools_release_notes_check PROPERTIES TIMEOUT 20)
add_test(NAME tools_prepare_release_notes COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_prepare_release_notes.py)
add_test(NAME check_skips_ctest COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips_ctest.py)
set_tests_properties(check_skips_ctest PROPERTIES TIMEOUT 30)
@@ -574,11 +591,11 @@ if(BUILD_TESTING)
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py
SkipJsonTests RequiredTestsTests SkipReportTests NotRunTests)
add_test(NAME check_skips_privilege COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py CheckSkipsTests)
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py CheckSkipsTests SymlinkPrivilegeLimitationTests)
add_test(NAME check_skips_ctest_policy COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py CtestSkipPolicyTests)
add_test(NAME check_skips_device_policy COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py DeviceSkipPolicyTests)
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py DeviceSkipPolicyTests DeviceLimitationsTests EnvironmentLoaderRetentionTests)
add_test(NAME check_skips_cli_output COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py SkipCliOutputTests)
set_tests_properties(check_skips check_skips_privilege check_skips_ctest_policy
+3 -1
View File
@@ -22,7 +22,9 @@
Toolchains are listed in the [build instructions](docs/dev/BUILD.md).
For relinker changes, use the [relinker-only build](docs/dev/BUILD.md#relinker-only) to build and test without third-party submodules, system libraries or a GPU. It also works on macOS. Changes to system libraries or shaders still need the full build and relevant runtime tests.
For relinker changes, use the [relinker-only build](docs/dev/BUILD.md#relinker-only) to build and test without third-party submodules, system libraries or a GPU; it adds `-DANYPS5_RELINKER_ONLY=ON` to the first command below. It also works on macOS. Changes to system libraries or shaders still need the full build and relevant runtime tests.
The full build needs the submodules (`git submodule update --init --recursive`):
```
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON
+1 -1
View File
@@ -1,4 +1,4 @@
**English** | [Português (Brasil)](docs/user/README.pt-BR.md) | [Español](docs/user/README.es.md) | [Català](docs/user/README.ca.md) | [Italiano](docs/user/README.it.md) | [简体中文](docs/user/README.zh-CN.md) | [Русский](docs/user/README.ru.md) | [Bahasa Indonesia](docs/user/README.id.md) | [Polski](docs/user/README.pl.md) | [日本語](docs/user/README.ja.md)
**English** | [Português (Brasil)](docs/user/README.pt-BR.md) | [Español](docs/user/README.es.md) | [Català](docs/user/README.ca.md) | [Italiano](docs/user/README.it.md) | [简体中文](docs/user/README.zh-CN.md) | [Русский](docs/user/README.ru.md) | [Bahasa Indonesia](docs/user/README.id.md) | [Polski](docs/user/README.pl.md) | [日本語](docs/user/README.ja.md) | [العربية](docs/user/README.ar.md)
# About
+9 -1
View File
@@ -34,7 +34,9 @@ add_library(icu_common STATIC EXCLUDE_FROM_ALL
${ICU_SOURCE_DIR}/common/emojiprops.cpp
${ICU_SOURCE_DIR}/common/filterednormalizer2.cpp
${ICU_SOURCE_DIR}/common/loadednormalizer2impl.cpp
${ICU_SOURCE_DIR}/common/locmap.cpp
${ICU_SOURCE_DIR}/common/errorcode.cpp
${ICU_SOURCE_DIR}/common/locavailable.cpp
${ICU_SOURCE_DIR}/common/locmap.cpp
${ICU_SOURCE_DIR}/common/normalizer2.cpp
${ICU_SOURCE_DIR}/common/normalizer2impl.cpp
${ICU_SOURCE_DIR}/common/parsepos.cpp
@@ -157,3 +159,9 @@ set_target_properties(icu_i18n PROPERTIES POSITION_INDEPENDENT_CODE ON CXX_VISIB
if(MINGW OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_link_options(icu_i18n INTERFACE LINKER:--exclude-libs,libicu_i18n.a)
endif()
target_sources(icu_i18n PRIVATE
${ICU_SOURCE_DIR}/i18n/ufieldpositer.cpp
${ICU_SOURCE_DIR}/i18n/fpositer.cpp
${CMAKE_SOURCE_DIR}/core/libs/prx/libSceIcu/FieldPositionBackend.cpp
${ICU_SOURCE_DIR}/i18n/fphdlimp.cpp)
@@ -35,6 +35,9 @@ std::vector<std::uint8_t> Encode(std::span<const std::uint8_t> pixels, std::uint
std::uint32_t channels, int quality, Sampling sampling = Sampling::Yuv444,
std::uint32_t restartBlocks = 0, std::uint32_t restartRows = 0);
std::vector<std::uint8_t> EncodePlanarYuv(std::span<const std::uint8_t> pixels, std::uint32_t width, std::uint32_t height,
int quality, Sampling sampling, std::uint32_t restartBlocks, std::uint32_t restartRows);
std::optional<Header> ParseHeader(std::span<const std::uint8_t> jpeg);
std::optional<Image> Decode(std::span<const std::uint8_t> jpeg);
+39 -14
View File
@@ -47,31 +47,38 @@ int toSubsampling(Sampling sampling) {
throw std::invalid_argument("Jpeg::Encode: invalid sampling");
}
void validateEncodeOptions(std::uint32_t width, std::uint32_t height, int quality,
std::uint32_t restartBlocks, std::uint32_t restartRows) {
if (width == 0 || height == 0 || width > MAX_DIMENSION || height > MAX_DIMENSION) {
throw std::invalid_argument("Jpeg::Encode: unsupported image size");
}
if (quality < 1 || quality > 100) throw std::invalid_argument("Jpeg::Encode: quality must be 1-100");
if (restartBlocks > MAX_DIMENSION || restartRows > MAX_DIMENSION || (restartBlocks != 0 && restartRows != 0)) {
throw std::invalid_argument("Jpeg::Encode: invalid restart interval");
}
}
void configureEncoder(tjhandle handle, int quality, int subsampling, std::uint32_t restartBlocks, std::uint32_t restartRows) {
if (tj3Set(handle, TJPARAM_QUALITY, quality) < 0 || tj3Set(handle, TJPARAM_SUBSAMP, subsampling) < 0 ||
(restartBlocks != 0 && tj3Set(handle, TJPARAM_RESTARTBLOCKS, static_cast<int>(restartBlocks)) < 0) ||
(restartRows != 0 && tj3Set(handle, TJPARAM_RESTARTROWS, static_cast<int>(restartRows)) < 0)) {
throw std::runtime_error("Jpeg::Encode: encoder configuration failed");
}
}
} // namespace
std::vector<std::uint8_t> Encode(std::span<const std::uint8_t> pixels, std::uint32_t width, std::uint32_t height,
std::uint32_t channels, int quality, Sampling sampling, std::uint32_t restartBlocks,
std::uint32_t restartRows) {
if (width == 0 || height == 0 || width > MAX_DIMENSION || height > MAX_DIMENSION) {
throw std::invalid_argument("Jpeg::Encode: unsupported image size");
}
validateEncodeOptions(width, height, quality, restartBlocks, restartRows);
if (channels != 1 && channels != 3) throw std::invalid_argument("Jpeg::Encode: channels must be 1 or 3");
if (quality < 1 || quality > 100) throw std::invalid_argument("Jpeg::Encode: quality must be 1-100");
if (pixels.size() < static_cast<std::size_t>(width) * height * channels) {
throw std::invalid_argument("Jpeg::Encode: pixel buffer is too small");
}
if (restartBlocks > MAX_DIMENSION || restartRows > MAX_DIMENSION || (restartBlocks != 0 && restartRows != 0)) {
throw std::invalid_argument("Jpeg::Encode: invalid restart interval");
}
const int subsampling = toSubsampling(sampling);
Handle handle(TJINIT_COMPRESS);
if (tj3Set(handle, TJPARAM_QUALITY, quality) < 0 || tj3Set(handle, TJPARAM_SUBSAMP, channels == 1 ? TJSAMP_GRAY : subsampling) < 0) {
throw std::runtime_error("Jpeg::Encode: encoder configuration failed");
}
if ((restartBlocks != 0 && tj3Set(handle, TJPARAM_RESTARTBLOCKS, static_cast<int>(restartBlocks)) < 0) ||
(restartRows != 0 && tj3Set(handle, TJPARAM_RESTARTROWS, static_cast<int>(restartRows)) < 0)) {
throw std::runtime_error("Jpeg::Encode: encoder configuration failed");
}
configureEncoder(handle, quality, channels == 1 ? TJSAMP_GRAY : subsampling, restartBlocks, restartRows);
Buffer buffer;
std::size_t size = 0;
const int pixelFormat = channels == 1 ? TJPF_GRAY : TJPF_RGB;
@@ -81,6 +88,24 @@ std::vector<std::uint8_t> Encode(std::span<const std::uint8_t> pixels, std::uint
return {buffer.data, buffer.data + size};
}
std::vector<std::uint8_t> EncodePlanarYuv(std::span<const std::uint8_t> pixels, std::uint32_t width, std::uint32_t height,
int quality, Sampling sampling, std::uint32_t restartBlocks, std::uint32_t restartRows) {
validateEncodeOptions(width, height, quality, restartBlocks, restartRows);
const int subsampling = toSubsampling(sampling);
const int cols = static_cast<int>(width);
const int rows = static_cast<int>(height);
const auto required = tj3YUVBufSize(cols, 1, rows, subsampling);
if (required == 0 || pixels.size() < required) throw std::invalid_argument("Jpeg::EncodePlanarYuv: pixel buffer is too small");
Handle handle(TJINIT_COMPRESS);
configureEncoder(handle, quality, subsampling, restartBlocks, restartRows);
Buffer buffer;
std::size_t size = 0;
if (tj3CompressFromYUV8(handle, pixels.data(), cols, 1, rows, &buffer.data, &size) < 0) {
throw std::runtime_error("Jpeg::EncodePlanarYuv: encoding failed");
}
return {buffer.data, buffer.data + size};
}
std::uint32_t ScaledDimension(std::uint32_t dimension, std::uint32_t denominator) {
if (denominator != 1 && denominator != 2 && denominator != 4 && denominator != 8) {
throw std::invalid_argument("Jpeg::ScaledDimension: the scale must be 1/1, 1/2, 1/4 or 1/8");
+11
View File
@@ -905,6 +905,17 @@ if(BUILD_TESTING)
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
endif()
add_test_executable(guest_kernel_sys_lwfs_tests tests/GuestKernelSysLwfs.cpp)
target_include_directories(guest_kernel_sys_lwfs_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_kernel_sys_lwfs_tests PRIVATE libkernel_sys libkernel libc)
configure_windows_unwind(guest_kernel_sys_lwfs_tests)
add_test(NAME guest_kernel_sys_lwfs COMMAND guest_kernel_sys_lwfs_tests)
set_tests_properties(guest_kernel_sys_lwfs PROPERTIES TIMEOUT 20)
if(WIN32)
set_tests_properties(guest_kernel_sys_lwfs PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
endif()
add_test_executable(guest_kernel_sys_thread_name_tests tests/GuestKernelSysThreadName.cpp)
target_include_directories(guest_kernel_sys_thread_name_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_kernel_sys_thread_name_tests PRIVATE libkernel_sys libkernel libc)
@@ -0,0 +1,15 @@
add_library(libSceAbstractStorage SHARED EXCLUDE_FROM_ALL Export.cpp)
target_include_directories(libSceAbstractStorage PRIVATE ${LIBS_INCLUDE_DIR})
configure_windows_unwind(libSceAbstractStorage)
if(BUILD_TESTING)
add_test_executable(guest_abstract_storage_consts_tests ${LIBS_INCLUDE_DIR}/tests/GuestAbstractStorageConsts.cpp)
target_include_directories(guest_abstract_storage_consts_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_abstract_storage_consts_tests PRIVATE libSceAbstractStorage libc)
configure_windows_unwind(guest_abstract_storage_consts_tests)
add_test(NAME guest_abstract_storage_consts COMMAND guest_abstract_storage_consts_tests)
if(WIN32)
set_tests_properties(guest_abstract_storage_consts PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceAbstractStorage>")
endif()
endif()
@@ -11,11 +11,11 @@ extern "C" {
int APS5_VABI _ZN15AbstractStorage12Serializable12readExternalESt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
return static_cast<int>(0x809e0005u);
}
int APS5_VABI _ZN15AbstractStorage12Serializable13writeExternalESt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
return static_cast<int>(0x809e0005u);
}
int APS5_VABI _ZN15AbstractStorage12SerializableC1Ev() {
@@ -31,11 +31,11 @@ void APS5_VABI _ZN15AbstractStorage12SerializableD1Ev(void*) {}
void APS5_VABI _ZN15AbstractStorage12SerializableD2Ev(void*) {}
int APS5_VABI _ZN15AbstractStorage14MemfileContent12readExternalESt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
return static_cast<int>(0x809e0002u);
}
int APS5_VABI _ZN15AbstractStorage14MemfileContent13writeExternalESt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
return static_cast<int>(0x809e0002u);
}
int APS5_VABI _ZN15AbstractStorage14MemfileContent14CreateInstanceESbIcSt11char_traitsIcENS_8StlAllocIcEEEN3paf6common9SharedPtrINS6_6BufferEEE() {
@@ -259,7 +259,7 @@ int APS5_VABI _ZN15AbstractStorage4Item14GetStorageNameEv() {
}
int APS5_VABI _ZN15AbstractStorage4Item6RenameERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
return static_cast<int>(0x809e0005u);
}
int APS5_VABI _ZN15AbstractStorage4Item7GetNameERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
@@ -427,11 +427,11 @@ int APS5_VABI _ZNK15AbstractStorage14MemfileContent7GetStatEPNS_4StatE(const voi
}
int APS5_VABI _ZNK15AbstractStorage4Item12GetThumbnailEPSt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
return static_cast<int>(0x809e0005u);
}
int APS5_VABI _ZNK15AbstractStorage4Item15CreateThumbnailEPvPSt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
return static_cast<int>(0x809e0005u);
}
int APS5_VABI _ZNK15AbstractStorage6Folder7GetTypeEv(const void*) {
+12 -12
View File
@@ -30,11 +30,11 @@ int APS5_VABI _ZN15AbstractStorage13TwitterFolder10NewContentERKSbIcSt11char_tra
}
int APS5_VABI _ZN15AbstractStorage13TwitterFolder12RemoveFolderERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb() {
NotImplemented_nid_no_patch(__func__);
return SCE_ABSTRACT_STORAGE_ERROR_NOT_SUPPORTED;
}
int APS5_VABI _ZN15AbstractStorage13TwitterFolder13RemoveContentERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
return SCE_ABSTRACT_STORAGE_ERROR_NOT_SUPPORTED;
}
int APS5_VABI _ZN15AbstractStorage13TwitterFolder4OpenENS_8ItemTypeE() {
@@ -50,11 +50,11 @@ int APS5_VABI _ZN15AbstractStorage13TwitterFolder6RemoveEb() {
}
int APS5_VABI _ZN15AbstractStorage13TwitterFolder8NextItemEPSt10shared_ptrINS_4ItemEE() {
NotImplemented_nid_no_patch(__func__);
return SCE_ABSTRACT_STORAGE_ERROR_NOT_SUPPORTED;
}
int APS5_VABI _ZN15AbstractStorage13TwitterFolder9NewFolderERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_6FolderEE() {
NotImplemented_nid_no_patch(__func__);
return SCE_ABSTRACT_STORAGE_ERROR_NOT_SUPPORTED;
}
int APS5_VABI _ZN15AbstractStorage13TwitterFolderC1ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEb() {
@@ -118,7 +118,7 @@ int APS5_VABI _ZN15AbstractStorage14TwitterContent6RemoveEv() {
}
int APS5_VABI _ZN15AbstractStorage14TwitterContent6RenameERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
return SCE_ABSTRACT_STORAGE_ERROR_NOT_SUPPORTED;
}
int APS5_VABI _ZN15AbstractStorage14TwitterContent8SeekByteEliPl() {
@@ -186,15 +186,15 @@ int APS5_VABI _ZN15AbstractStorage14TwitterServiceD2Ev() {
}
int APS5_VABI _ZN15AbstractStorage14TwitterStorage10GetContentERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_7ContentEE() {
NotImplemented_nid_no_patch(__func__);
return SCE_ABSTRACT_STORAGE_ERROR_NOT_SUPPORTED;
}
int APS5_VABI _ZN15AbstractStorage14TwitterStorage11DeserializeESt10shared_ptrINS_7ContentEEPS1_INS_4ItemEE() {
NotImplemented_nid_no_patch(__func__);
return SCE_ABSTRACT_STORAGE_ERROR_NOT_SUPPORTED;
}
int APS5_VABI _ZN15AbstractStorage14TwitterStorage13GetRootFolderEPSt10shared_ptrINS_6FolderEE() {
NotImplemented_nid_no_patch(__func__);
return SCE_ABSTRACT_STORAGE_ERROR_NOT_SUPPORTED;
}
int APS5_VABI _ZN15AbstractStorage14TwitterStorage14GetStorageSizeEPlS1_S1_() {
@@ -202,11 +202,11 @@ int APS5_VABI _ZN15AbstractStorage14TwitterStorage14GetStorageSizeEPlS1_S1_() {
}
int APS5_VABI _ZN15AbstractStorage14TwitterStorage15CreateRecursiveERKSbIcSt11char_traitsIcENS_8StlAllocIcEEENS_8ItemTypeEPSt10shared_ptrINS_4ItemEE() {
NotImplemented_nid_no_patch(__func__);
return SCE_ABSTRACT_STORAGE_ERROR_NOT_SUPPORTED;
}
int APS5_VABI _ZN15AbstractStorage14TwitterStorage15RemoveRecursiveERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
return SCE_ABSTRACT_STORAGE_ERROR_NOT_SUPPORTED;
}
int APS5_VABI _ZN15AbstractStorage14TwitterStorage7GetItemERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_4ItemEE() {
@@ -214,7 +214,7 @@ int APS5_VABI _ZN15AbstractStorage14TwitterStorage7GetItemERKSbIcSt11char_traits
}
int APS5_VABI _ZN15AbstractStorage14TwitterStorage7IsExistERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
NotImplemented_nid_no_patch(__func__);
return 0;
}
int APS5_VABI _ZN15AbstractStorage14TwitterStorage9GetForderERKSbIcSt11char_traitsIcENS_8StlAllocIcEEEPSt10shared_ptrINS_6FolderEE() {
@@ -222,7 +222,7 @@ int APS5_VABI _ZN15AbstractStorage14TwitterStorage9GetForderERKSbIcSt11char_trai
}
int APS5_VABI _ZN15AbstractStorage14TwitterStorage9SerializeESt10shared_ptrINS_7ContentEES1_INS_4ItemEE() {
NotImplemented_nid_no_patch(__func__);
return SCE_ABSTRACT_STORAGE_ERROR_NOT_SUPPORTED;
}
int APS5_VABI _ZN15AbstractStorage14TwitterStorageC1ERKSbIcSt11char_traitsIcENS_8StlAllocIcEEE() {
+1 -2
View File
@@ -252,8 +252,7 @@ int APS5_VABI sceAcmBatchStartBuffer(AcmContextId context, const void* batch_com
int APS5_VABI sceAcmBatchStartBuffers(AcmContextId context, uint32_t batch_info_count, const AcmBatchInfo* const batch_info[], AcmBatchError* batch_error, AcmBatchId* batch) {
(void)batch_info_count;
(void)batch_info;
if (!batch || batch_error) return SCE_ACM_ERROR_BAD_POINTER;
if (!batch_info || !batch || batch_error) return SCE_ACM_ERROR_BAD_POINTER;
if (context == 0) return SCE_ACM_ERROR_BAD_CONTEXT;
std::lock_guard<std::mutex> lock(g_mutex);
if (!g_contexts.contains(context)) return SCE_ACM_ERROR_BAD_CONTEXT;
+17 -1
View File
@@ -306,7 +306,7 @@ foreach(agcSampleOrderVariant IN ITEMS "R8;comp;-DTEXEL_FORMAT=r8ui" "R16;comp;-
)
list(APPEND agcSampleOrderShaderHeaders ${agcSampleOrderShaderHeader})
endforeach()
foreach(agcFirstSampleClass IN ITEMS Float Uint Sint)
foreach(agcFirstSampleClass IN ITEMS Float Uint Sint Packed)
string(TOUPPER "${agcFirstSampleClass}" agcFirstSampleSymbol)
set(agcFirstSampleShaderSource ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/shaders/FirstSample.frag)
set(agcFirstSampleShaderSpv ${agcTextureDetileGeneratedDir}/FirstSample${agcFirstSampleClass}.spv)
@@ -576,6 +576,18 @@ target_link_libraries(libSceAgcDriver PRIVATE
if(WIN32)
target_link_libraries(libSceAgcDriver PRIVATE pdh)
endif()
set(APS5_AGC_PROFILE "" CACHE STRING "Profile-guided build of the AGC driver: generate or use")
if(APS5_AGC_PROFILE STREQUAL "generate")
foreach(agcProfileTarget libSceAgcDriver shader_recompiler_agc_driver)
target_compile_options(${agcProfileTarget} PRIVATE -fprofile-generate -fprofile-update=atomic)
endforeach()
target_compile_definitions(libSceAgcDriver PRIVATE APS5_PROFILE_GENERATE)
target_link_options(libSceAgcDriver PRIVATE -fprofile-generate)
elseif(APS5_AGC_PROFILE STREQUAL "use")
foreach(agcProfileTarget libSceAgcDriver shader_recompiler_agc_driver)
target_compile_options(${agcProfileTarget} PRIVATE -fprofile-use -fprofile-correction -Wno-missing-profile -Wno-coverage-mismatch)
endforeach()
endif()
target_include_directories(libSceAgcDriver SYSTEM PRIVATE ${CMAKE_SOURCE_DIR}/3rdparty/zstd/lib)
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_link_options(libSceAgcDriver PRIVATE LINKER:--exclude-libs,libzstd.a)
@@ -722,6 +734,10 @@ foreach(agcExecutionTestSource IN LISTS agcExecutionTestSources)
set_target_properties(${agcExecutionTest} PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(${agcExecutionTest})
target_compile_definitions(${agcExecutionTest} PRIVATE VK_ENABLE_BETA_EXTENSIONS)
if(WIN32 AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
target_compile_options(${agcExecutionTest} PRIVATE
-include ${CMAKE_CURRENT_SOURCE_DIR}/tests/execution/TestEnvironment.hpp)
endif()
if(agcExecutionTests)
list(GET agcExecutionTests 0 agcExecutionPchTarget)
target_precompile_headers(${agcExecutionTest} REUSE_FROM ${agcExecutionPchTarget})
@@ -44,6 +44,7 @@ public:
static DrawPipeline& Queue0();
static std::size_t Depth();
static std::size_t ResumeDepth();
static std::size_t QueuedItems();
static bool& Active();
static std::atomic<std::uint64_t>& EpochToken();
@@ -69,6 +70,8 @@ public:
Watch WatchWrites();
bool WrittenSince(Watch& watch, const std::vector<Range>& reads);
std::uint64_t Retired() const { return retiredItems.load(std::memory_order_acquire); }
std::uint64_t ProducerWaits() const { return producerWaits.load(std::memory_order_acquire); }
std::uint64_t DrainWaits() const { return drainWaits.load(std::memory_order_acquire); }
void NoteDecodeDrain() { decodeDrains.fetch_add(1, std::memory_order_relaxed); }
std::uint64_t DecodeDrains() const { return decodeDrains.load(std::memory_order_relaxed); }
std::optional<std::uint64_t> PendingLabel(std::uint64_t address, std::size_t bytes);
@@ -112,10 +115,12 @@ private:
std::exception_ptr failure;
std::atomic<std::size_t> outstanding{0};
std::atomic<std::uint64_t> retiredItems{0};
std::atomic<std::uint64_t> producerWaits{0};
std::atomic<std::uint64_t> drainWaits{0};
std::atomic<std::uint64_t> decodeDrains{0};
std::uint64_t reportedDecodeDrains = 0;
std::uint32_t idleWaiters = 0;
std::size_t resumeAt = 0;
std::uint32_t producersWaiting = 0;
std::uint32_t drainersWaiting = 0;
bool committerWaiting = false;
bool stopped = false;
bool closing = false;
@@ -331,7 +331,7 @@ private:
bool labelPacketQueues(std::span<const std::uint32_t> packet, std::uint32_t opcode);
bool enqueueLabelPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue, std::optional<std::uint32_t> interrupt);
bool enqueueDmaPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue, const QueueState& state);
bool enqueueSampleDumpPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue);
bool enqueueSampleDumpPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue, std::uint32_t blocks);
bool enqueueConstantRamDump(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue, const QueueState& state);
void commitStore(std::uint32_t queue, std::uint64_t address, std::span<const std::byte> bytes);
void commitLabel(std::uint32_t queue, std::uint64_t address, std::span<const std::byte> bytes, std::optional<std::uint32_t> interrupt);
@@ -424,7 +424,7 @@ private:
static void recordQueuedLabelsFromHook();
void flushBetweenPackets(std::uint32_t queue, std::uint32_t header, bool labelPacket);
bool preparePacketMemory(const Submission& submission, QueueState& queue, std::span<const std::uint32_t> packet, std::uint32_t header, std::uint32_t opcode, std::optional<std::uint32_t> interrupt, bool& wroteOnGpu, bool& endOfPipeInterrupt, bool& interruptDeferred, bool& drawPacket, bool& sampleDump);
void dumpSampleCounters(std::uint64_t address);
void dumpSampleCounters(std::uint64_t address, std::uint32_t blocks);
template <typename TWork>
static void timed(double WorkerProfile::*bucket, TWork&& work);
FrameTiming* frameTiming();
@@ -125,6 +125,7 @@ std::uint64_t MarkWritten(std::uint64_t address, std::size_t bytes);
std::uint64_t MarkPossiblyWritten(std::uint64_t address, std::size_t bytes);
std::uint64_t MarkPossiblyWritten(std::uint64_t address, std::size_t bytes, std::uint64_t& order);
void ForgetKnownZero(std::uint64_t address, std::size_t bytes);
std::uint64_t KnownZeroMarks();
void MaterializeKnownZero(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::size_t bytes, const std::function<void(std::span<std::byte>)>& store);
@@ -172,6 +173,15 @@ std::uint64_t CollectEpochBumps();
std::uint64_t ThreadCollectEpoch();
std::uint64_t UnwatchSerial();
std::uint64_t CollectWritesUncached(std::uint64_t address, std::size_t bytes);
struct GpuUseObservation {
std::uint64_t address = 0;
std::size_t bytes = 0;
std::uint64_t generation = 0;
std::uint64_t epoch = 0;
std::uint64_t unwatched = 0;
std::uint64_t mapping = 0;
};
void CollectWritesForGpuUse(const UnchangedQuery& range, GpuUseObservation& observation);
struct Observation {
enum class Status { Complete, Refused, Uncovered, Failed };
Status status = Status::Failed;
@@ -194,6 +194,10 @@ inline constexpr std::uint64_t SampleDumpBlockBytes = 8;
inline constexpr std::uint64_t SampleDumpBytes = (SampleDumpBlocks - 1) * SampleDumpStride + SampleDumpBlockBytes;
inline bool SampleDump(std::span<const std::uint32_t> packet) { return ((packet[0] >> 8u) & 0xffu) == 0x46u && packet.size() >= 2 && (packet[1] & 0x3fu) == SampleDumpEvent; }
inline std::uint64_t SampleDumpAddress(std::span<const std::uint32_t> packet) { return packet[2] | (static_cast<std::uint64_t>(packet[3]) << 32u); }
inline constexpr std::uint32_t SampleControlEvent = 0x38;
static_assert(AllSampleDumpBlocks == (1u << SampleDumpBlocks) - 1u);
inline bool SampleControl(std::span<const std::uint32_t> packet) { return ((packet[0] >> 8u) & 0xffu) == 0x46u && packet.size() >= 3 && (packet[1] & 0x3fu) == SampleControlEvent; }
inline std::uint32_t SampleControlBlocks(std::span<const std::uint32_t> packet) { return (packet[2] >> 11u) & AllSampleDumpBlocks; }
struct PacketStore {
enum class Value : std::uint8_t { Bytes, Pattern, RunTime };
std::uint64_t address = 0;
@@ -220,9 +220,9 @@ private:
inline Registers BuildInitialContextRegisters() {
Registers result{
{0x200, 0}, {0x201, 0}, {0x202, 0xcc0010}, {0x203, 0},
{0x204, 0}, {0x205, 0}, {0x206, 0}, {0x207, 0},
{0x204, 0}, {0x205, 0}, {0x206, 1087}, {0x207, 0},
{0x0, 0}, {0x2, 0}, {0x3, 0}, {0x4, 0}, {0x8, 0}, {0x9, 0x3f800000}, {0xa, 0}, {0xb, 0}, {0x10, 0}, {0x11, 0},
{0x80, 0}, {0x83, 0xffff}, {0x8c, 0xaa99aaaa}, {0x8d, 0}, {0x8e, 0xffffffffu}, {0x8f, 0xffffffffu},
{0x80, 0}, {0x83, 0xffff}, {0x8c, 0xaa99aaaa}, {0x8d, 0}, {0x8e, 0}, {0x8f, 0},
{0xc, 0}, {0xd, 0x40004000}, {0x81, 0x80000000}, {0x82, 0x40004000},
{0x90, 0x80000000}, {0x91, 0x40004000},
{0x105, 0}, {0x106, 0}, {0x107, 0}, {0x108, 0},
@@ -278,6 +278,8 @@ inline Registers ClearStateContextRegisters() {
return cleared;
}
inline constexpr std::uint32_t AllSampleDumpBlocks = 0xffffu;
struct Predication {
std::uint64_t address = 0;
std::uint32_t operation = 0;
@@ -301,6 +303,7 @@ struct QueueState {
std::uint32_t instanceCount = 1;
std::vector<std::string> markers;
Predication predication;
std::uint32_t sampleDumpBlocks = AllSampleDumpBlocks;
void ClearContext() {
context = ClearStateContextRegisters();
@@ -154,7 +154,7 @@ public:
// CPU (a copied buffer's write-back, a deferred label). Debug aid: APS5_FILL_SYNC=1 waits for
// every recorded store over the range.
bool FillBuffer(std::uint64_t address, std::size_t bytes, std::span<const std::uint32_t, 4> pattern);
bool DumpSamplesOnGpu(std::uint64_t address);
bool DumpSamplesOnGpu(std::uint64_t address, std::uint32_t blocks);
void NoteHtileMask(const Graphics::HtileMaskClear& clear) const;
// Copies `bytes` of guest memory from `source` to `destination` (disjoint ranges) in place of the
// engine's memcpy kernel (Driver.cpp copyBuffer). `path` 0: copied on the CPU at once, when
@@ -231,7 +231,7 @@ public:
};
static ComputePipelineCreation ComputePipelineCounts();
struct DispatchMoveCount {
std::uint64_t checked, exact, moved, refused, filtered, rebuilt, kept, served;
std::uint64_t checked, exact, moved, refused, filtered, rebuilt, kept, served, inPlace;
};
static DispatchMoveCount DispatchMoveCounts();
void ResolveMemory(std::uint64_t address, std::size_t bytes, bool writable);
@@ -275,6 +275,10 @@ std::size_t DrawPipeline::Depth() {
return depth;
}
std::size_t DrawPipeline::ResumeDepth() {
return Depth() / 2;
}
std::size_t DrawPipeline::QueuedItems() {
auto& pipeline = Queue0();
std::lock_guard lock(pipeline.mutex);
@@ -383,14 +387,14 @@ void DrawPipeline::enqueue(Item item) {
item.commit();
return;
}
if (items.size() >= Depth()) {
if (Depth() != 0 && 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() <= resumeAt; });
--idleWaiters;
resumeAt = 0;
while (items.size() >= Depth()) {
++producersWaiting;
producerWaits.fetch_add(1, std::memory_order_release);
idle.wait(lock);
}
fullWaitNs += elapsedNs(start);
rethrowFailure();
}
@@ -513,7 +517,11 @@ void DrawPipeline::run() {
if (failed) ++commitErrors;
if (fatal != nullptr && failure == nullptr) failure = fatal;
outstanding.fetch_sub(1, std::memory_order_release);
if (idleWaiters != 0 && (items.empty() || items.size() <= resumeAt)) idle.notify_all();
if ((producersWaiting != 0 && items.size() <= ResumeDepth()) || (drainersWaiting != 0 && items.empty())) {
producersWaiting = 0;
drainersWaiting = 0;
idle.notify_all();
}
}
runningCommitters.fetch_sub(1, std::memory_order_acq_rel);
}
@@ -548,9 +556,11 @@ void DrawPipeline::Drain(DrainReason reason, std::uint32_t opcode) {
const auto start = std::chrono::steady_clock::now();
SpinUntil(HandoffSpinWindow() * 2, [&] { return !Busy(); });
std::unique_lock lock(mutex);
++idleWaiters;
idle.wait(lock, [&] { return items.empty(); });
--idleWaiters;
while (!items.empty()) {
++drainersWaiting;
drainWaits.fetch_add(1, std::memory_order_release);
idle.wait(lock);
}
const auto index = static_cast<std::size_t>(reason);
++drains[index];
++drainOpcodes[std::min<std::uint32_t>(opcode, 0x100)];
@@ -20,6 +20,7 @@
#include "prx/libc/include/GuestArena.hpp"
#include "prx/libc/include/GuestWriteWatch.hpp"
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cerrno>
@@ -216,7 +217,21 @@ void Driver::stop() {
stopped = true;
}
#ifdef APS5_PROFILE_GENERATE
extern "C" void __gcov_dump(void);
extern "C" void __gcov_reset(void);
#endif
Driver::Driver() {
#ifdef APS5_PROFILE_GENERATE
std::thread([] {
for (;;) {
std::this_thread::sleep_for(std::chrono::seconds(20));
__gcov_dump();
__gcov_reset();
}
}).detach();
#endif
InstallAsyncLog_nid_no_patch();
static const bool driverMemory = (MapDriverMemory(), true);
static_cast<void>(driverMemory);
@@ -323,7 +323,7 @@ void Driver::execute(Submission& submission) {
if (submission.queue != 0 && Graphics::Recorder::DispatchOverlapEnabled()) noteRingPacket(submission.queue, submission.serial, opcode, header);
PerformanceTimer timing("Driver.Packet");
if (!predicated) noteLabelIssue(packet, submission.queue);
if (pipelined && !predicated && header != FlipPacketHeader && header != RenderingWaitPacketHeader && !submission.flips.contains(cursor) && (enqueueLabelPacket(packet, opcode, submission.queue, releaseInterrupt(packet, opcode, false)) || enqueueDmaPacket(packet, opcode, submission.queue, queue) || enqueueConstantRamDump(packet, opcode, submission.queue, queue) || enqueueSampleDumpPacket(packet, opcode, submission.queue))) {
if (pipelined && !predicated && header != FlipPacketHeader && header != RenderingWaitPacketHeader && !submission.flips.contains(cursor) && (enqueueLabelPacket(packet, opcode, submission.queue, releaseInterrupt(packet, opcode, false)) || enqueueDmaPacket(packet, opcode, submission.queue, queue) || enqueueConstantRamDump(packet, opcode, submission.queue, queue) || enqueueSampleDumpPacket(packet, opcode, submission.queue, queue.sampleDumpBlocks))) {
traceLabel(packet, submission.queue);
recent.Record(cursor);
cursor = nextCursor;
@@ -582,7 +582,7 @@ void Driver::execute(Submission& submission) {
recordQueuedLabelsBeforeRead(submission.queue);
Pm4::Execute(packet, queue);
} else if (sampleDump && !wroteOnGpu) {
dumpSampleCounters(Pm4::SampleDumpAddress(packet));
dumpSampleCounters(Pm4::SampleDumpAddress(packet), queue.sampleDumpBlocks);
} else if (submission.queue == 0 && sealsWriteOnly(packet, opcode)) {
if (std::exchange(drawnSinceSeal(), false)) {
const auto seal = [this] {
@@ -593,7 +593,7 @@ void Driver::execute(Submission& submission) {
if (pipelined && DrawPipeline::Queue0().Busy()) DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Seal, seal, {});
else seal();
}
} else if (opcode != 0x42 && opcode != 0x46 && opcode != 0x58) {
} else if (opcode != 0x42 && (opcode != 0x46 || Pm4::SampleControl(packet)) && opcode != 0x58) {
if (!wroteOnGpu) {
if (Pm4::IndirectRegisterOpcode(opcode)) {
const auto& listed = submission.registerLists.at(cursor);
@@ -13,6 +13,7 @@
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
#include "prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp"
#include <algorithm>
#include <bit>
#include <cstdlib>
#include <cstring>
#include <limits>
@@ -261,7 +262,7 @@ bool Driver::preparePacketMemory(const Submission& submission, QueueState& queue
std::lock_guard gpuLock(GuestMemory::GpuMutex());
if (const auto localDevice = device.Load()) {
recordDeferredLabels(localDevice.get(), submission.queue);
wroteOnGpu = localDevice->DumpSamplesOnGpu(Pm4::SampleDumpAddress(packet));
wroteOnGpu = localDevice->DumpSamplesOnGpu(Pm4::SampleDumpAddress(packet), queue.sampleDumpBlocks);
}
}
@@ -323,7 +324,7 @@ bool Driver::preparePacketMemory(const Submission& submission, QueueState& queue
return drains;
}
void Driver::dumpSampleCounters(std::uint64_t address) {
void Driver::dumpSampleCounters(std::uint64_t address, std::uint32_t blocks) {
std::uint64_t samples = 0;
{
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Flush);
@@ -334,18 +335,20 @@ void Driver::dumpSampleCounters(std::uint64_t address) {
samples = recorder->SamplesTotal();
}
constexpr std::uint64_t ready = 1ull << 63u;
const auto first = static_cast<std::uint64_t>(std::countr_zero(blocks));
for (std::uint64_t db = 0; db < Pm4::SampleDumpBlocks; ++db) {
const std::uint64_t value = ready | (db == 0 ? samples : 0u);
if (((blocks >> db) & 1u) == 0) continue;
const std::uint64_t value = ready | (db == first ? samples : 0u);
GuestMemory::Write(address + db * Pm4::SampleDumpStride, std::as_bytes(std::span(&value, 1)).first(Pm4::SampleDumpBlockBytes), 8);
}
}
bool Driver::enqueueSampleDumpPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue) {
bool Driver::enqueueSampleDumpPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue, std::uint32_t blocks) {
static const bool ordered = std::getenv("APS5_PIPELINE_DRAIN_SAMPLE_DUMPS") == nullptr;
if (!ordered || opcode != 0x46 || queue != 0 || packet.size() < 4 || !Pm4::SampleDump(packet) || !DrawPipeline::Active() || !deferredLabels().labels.empty()) return false;
const auto address = Pm4::SampleDumpAddress(packet);
if (address == 0 || !GuestMemory::Accessible(reinterpret_cast<const void*>(address), Pm4::SampleDumpBytes, true)) return false;
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::SampleDump, [this, queue, address] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::SampleDump, [this, queue, address, blocks] {
GuestMemory::SetCurrentPacket(0x46, queue);
bool wrote = false;
{
@@ -353,11 +356,11 @@ bool Driver::enqueueSampleDumpPacket(std::span<const std::uint32_t> packet, std:
std::lock_guard gpuLock(GuestMemory::GpuMutex());
if (const auto localDevice = device.Load()) {
recordDeferredLabels(localDevice.get(), queue);
wrote = localDevice->DumpSamplesOnGpu(address);
wrote = localDevice->DumpSamplesOnGpu(address, blocks);
if (!wrote) localDevice->WaitIdle();
}
}
if (!wrote) dumpSampleCounters(address);
if (!wrote) dumpSampleCounters(address, blocks);
}, {{address, address + Pm4::SampleDumpBytes}});
++sampleDumpsQueued;
Graphics::Recorder::CountRecordedWork();
@@ -65,7 +65,7 @@ bool Driver::labelTryEachPacket() {
std::chrono::microseconds Driver::labelFlushDeadline() {
static const std::chrono::microseconds value = [] {
const char* text = std::getenv("APS5_LABEL_FLUSH_US");
return std::chrono::microseconds(text ? std::atoi(text) : (LabelBatchSubmit() ? 1000 : 250));
return std::chrono::microseconds(text ? std::atoi(text) : (LabelBatchSubmit() ? 100 : 250));
}();
return value;
}
@@ -2372,6 +2372,19 @@ void MarkProofThread() {
proofThread = true;
}
void CollectWritesForGpuUse(const UnchangedQuery& range, GpuUseObservation& observation) {
const auto epoch = CollectEpoch();
const auto unwatched = UnwatchSerial();
const auto mapping = GuestAllocations::GuestAllocationsGeneration_nid_postfix();
if (proofThread && epoch != 0 && observation.address == range.address && observation.bytes == range.bytes && observation.generation == range.generation && observation.epoch == epoch && observation.unwatched == unwatched && observation.mapping == mapping) return;
const auto collected = CollectWritesUncached(range.address, range.bytes);
if (!proofThread || epoch == 0 || collected == 0) {
observation = {};
return;
}
observation = {range.address, range.bytes, range.generation, epoch, unwatched, mapping};
}
std::uint64_t CollectEpoch() {
return collectMemoEnabled() ? HostThreadSlot<std::uint64_t, CollectEpochSlot>::Get() : 0;
}
@@ -3527,6 +3540,14 @@ void ForgetKnownZero(std::uint64_t address, std::size_t bytes) {
#endif
}
std::uint64_t KnownZeroMarks() {
#ifdef _WIN32
return GuestArena::GuestArenaKnownZeroMarks_nid_no_patch();
#else
return 0;
#endif
}
void MaterializeKnownZero(std::uint64_t address, std::size_t bytes) {
#ifdef _WIN32
GuestArena::GuestArenaKnownZero_nid_no_patch(static_cast<std::uintptr_t>(address), bytes, [](void*, std::uintptr_t first, std::uintptr_t last) {
@@ -1,5 +1,6 @@
#ifdef _WIN32
#include <algorithm>
#include <atomic>
#include <cstddef>
#include <cstdint>
@@ -8,19 +9,34 @@
#include <malloc.h>
#include <new>
#include <windows.h>
#include <xmmintrin.h>
namespace {
constexpr std::size_t Granule = 16;
constexpr std::size_t LargestCached = 1024;
constexpr std::size_t Classes = LargestCached / Granule;
constexpr std::size_t SmallestKept = sizeof(void*);
constexpr std::uintptr_t HeldBits = Granule - 1;
constexpr std::uint16_t Depth(std::size_t sizeClass) {
return sizeClass < 256 / Granule ? 64 : 16;
}
struct FreeBlock {
std::uintptr_t link;
};
FreeBlock* Next(const FreeBlock* block) noexcept {
return reinterpret_cast<FreeBlock*>(block->link & ~HeldBits);
}
std::size_t Held(const FreeBlock* block, std::size_t sizeClass) noexcept {
return sizeClass * Granule + (block->link & HeldBits) + 1;
}
struct Cache {
void* heads[Classes];
FreeBlock* heads[Classes];
std::uint16_t counts[Classes];
};
@@ -28,33 +44,25 @@ constexpr std::uint16_t KeptLists = 8;
struct Depot {
SRWLOCK lock = SRWLOCK_INIT;
void* lists = nullptr;
FreeBlock* lists[KeptLists] = {};
std::uint16_t count = 0;
};
Depot depots[Classes];
bool KeepList(std::size_t sizeClass, void* list) noexcept {
bool KeepList(std::size_t sizeClass, FreeBlock* list) noexcept {
auto& depot = depots[sizeClass];
AcquireSRWLockExclusive(&depot.lock);
const bool kept = depot.count < KeptLists;
if (kept) {
static_cast<void**>(list)[1] = depot.lists;
depot.lists = list;
++depot.count;
}
if (kept) depot.lists[depot.count++] = list;
ReleaseSRWLockExclusive(&depot.lock);
return kept;
}
void* TakeList(std::size_t sizeClass) noexcept {
FreeBlock* TakeList(std::size_t sizeClass) noexcept {
auto& depot = depots[sizeClass];
AcquireSRWLockExclusive(&depot.lock);
void* list = depot.lists;
if (list != nullptr) {
depot.lists = static_cast<void**>(list)[1];
--depot.count;
}
FreeBlock* list = depot.count != 0 ? depot.lists[--depot.count] : nullptr;
ReleaseSRWLockExclusive(&depot.lock);
return list;
}
@@ -71,8 +79,8 @@ std::atomic<DWORD> flsSlot{FLS_OUT_OF_INDEXES};
void Drain(Cache* cache) noexcept {
for (std::size_t sizeClass = 0; sizeClass < Classes; ++sizeClass) {
while (void* block = cache->heads[sizeClass]) {
cache->heads[sizeClass] = *static_cast<void**>(block);
while (FreeBlock* block = cache->heads[sizeClass]) {
cache->heads[sizeClass] = Next(block);
std::free(block);
}
cache->counts[sizeClass] = 0;
@@ -144,21 +152,37 @@ Cache* CurrentCache() noexcept {
return cache != nullptr ? cache : CreateCache(slot);
}
bool Keep(Cache* cache, FreeBlock* block, std::size_t held) noexcept {
const auto sizeClass = (held - 1) / Granule;
if (cache->counts[sizeClass] == Depth(sizeClass) && KeepList(sizeClass, cache->heads[sizeClass])) {
cache->heads[sizeClass] = nullptr;
cache->counts[sizeClass] = 0;
}
if (cache->counts[sizeClass] == Depth(sizeClass)) return false;
block->link = reinterpret_cast<std::uintptr_t>(cache->heads[sizeClass]) | ((held - 1) & HeldBits);
cache->heads[sizeClass] = block;
++cache->counts[sizeClass];
return true;
}
void* TryAllocate(std::size_t bytes) noexcept {
if (bytes == 0) bytes = 1;
if (bytes <= LargestCached) {
const auto sizeClass = (bytes - 1) / Granule;
if (auto* cache = CurrentCache()) {
if (cache->heads[sizeClass] == nullptr) {
if (void* list = TakeList(sizeClass)) {
if (FreeBlock* list = TakeList(sizeClass)) {
cache->heads[sizeClass] = list;
cache->counts[sizeClass] = Depth(sizeClass);
}
}
if (void* block = cache->heads[sizeClass]) {
cache->heads[sizeClass] = *static_cast<void**>(block);
if (FreeBlock* block = cache->heads[sizeClass]) {
FreeBlock* next = Next(block);
cache->heads[sizeClass] = next;
--cache->counts[sizeClass];
return block;
if (next != nullptr) _mm_prefetch(reinterpret_cast<const char*>(next), _MM_HINT_T0);
if (Held(block, sizeClass) >= bytes || _msize(block) >= bytes) return block;
if (sizeClass == 0 || !Keep(cache, block, sizeClass * Granule)) std::free(block);
}
}
return std::malloc((sizeClass + 1) * Granule);
@@ -177,20 +201,12 @@ void* Allocate(std::size_t bytes) {
void Release(void* block, std::size_t bytes = 0) noexcept {
if (block == nullptr) return;
if (auto* cache = CurrentCache()) {
const auto usable = bytes != 0 && bytes % Granule == 0 ? bytes : _msize(block);
if (usable >= Granule && usable < LargestCached + Granule) {
const auto sizeClass = usable / Granule - 1;
if (cache->counts[sizeClass] == Depth(sizeClass) && KeepList(sizeClass, cache->heads[sizeClass])) {
cache->heads[sizeClass] = nullptr;
cache->counts[sizeClass] = 0;
}
if (cache->counts[sizeClass] < Depth(sizeClass)) {
*static_cast<void**>(block) = cache->heads[sizeClass];
cache->heads[sizeClass] = block;
++cache->counts[sizeClass];
if ((reinterpret_cast<std::uintptr_t>(block) & HeldBits) == 0) {
if (auto* cache = CurrentCache()) {
const auto held = bytes >= SmallestKept ? bytes : _msize(block);
if (held >= SmallestKept && held < LargestCached + Granule
&& Keep(cache, static_cast<FreeBlock*>(block), std::min(held, LargestCached)))
return;
}
}
}
std::free(block);
@@ -492,6 +492,14 @@ void Validate(std::span<const std::uint32_t> packet, std::uint32_t queue) {
size(2);
require(eventIndex == 0, "invalid stream-out statistics event index");
break;
case 0x38:
graphics();
size(4);
require(eventIndex == 1, "invalid pixel pipe statistics control event index");
require((packet[2] & ~0x07fffff8u) == 0 && packet[3] == 0, "unsupported PIXEL_PIPE_STAT_CONTROL reserved bits");
require(((packet[2] >> 3u) & 0x3fu) == 0, "PIXEL_PIPE_STAT_CONTROL counters other than occlusion count 0 are not implemented");
require(((packet[2] >> 9u) & 3u) == 2, "PIXEL_PIPE_STAT_CONTROL dump strides other than 128 bits are not implemented");
break;
case 0x39:
graphics();
size(4);
@@ -704,12 +712,14 @@ bool PredicationPasses(const QueueState& queue) {
const GuestMemory::ReadSiteScope site(GuestMemory::ReadSite::Wait);
if (predication.operation == 1) {
constexpr std::uint64_t ready = 1ull << 63u;
std::array<std::uint64_t, SampleDumpBlocks * SampleDumpStride / sizeof(std::uint64_t)> words{};
GuestMemory::Read(predication.address, std::as_writable_bytes(std::span(words)).first(PredicationBytes(predication)), 8);
require(queue.sampleDumpBlocks != 0, "Z-pass predication with no counter block enabled by PIXEL_PIPE_STAT_CONTROL is not implemented");
std::uint64_t samples = 0;
for (std::uint64_t db = 0; db < SampleDumpBlocks; ++db) {
const auto begin = words[db * SampleDumpStride / sizeof(std::uint64_t)];
const auto end = words[db * SampleDumpStride / sizeof(std::uint64_t) + 1];
if (((queue.sampleDumpBlocks >> db) & 1u) == 0) continue;
std::array<std::uint64_t, 2> pair{};
GuestMemory::Read(predication.address + db * SampleDumpStride, std::as_writable_bytes(std::span(pair)), 8);
const auto begin = pair[0];
const auto end = pair[1];
if ((begin & ready) == 0 || (end & ready) == 0) {
require(predication.runWhenUnwritten, "Z-pass predication waits for a counter pair that was never written");
return true;
@@ -1199,6 +1209,10 @@ void Execute(std::span<const std::uint32_t> packet, QueueState& queue) {
case 0x2a: queue.indexType = packet[1]; return;
case 0x91: executeIndexAttributes(readIndexAttributes(packet), queue); return;
case 0x2f: queue.instanceCount = packet[1]; return;
case 0x46:
if (!SampleControl(packet)) throw std::runtime_error("packet requires driver execution");
queue.sampleDumpBlocks = SampleControlBlocks(packet);
return;
case 0x63: case 0x64: case 0x9f:
ExecuteIndirectRegisters(packet, ReadIndirectRegisters(packet), queue);
return;
@@ -411,8 +411,15 @@ bool ShaderMemory::read(void* context, std::uint64_t address, std::uint32_t* val
if (self.descriptorSpanBytes > sizeof(word) &&
(self.forceSync != 0u ? self.pendingSpan(address, self.descriptorSpanBytes, {}) != PendingWrite::None
: spanNeedsSync(self.pendingSpan(address, self.descriptorSpanBytes, {})))) {
policy = PendingWrite::Sync;
forcedRaw = self.forceSync != 0u && !spanNeedsSync(self.pendingSpan(address, self.descriptorSpanBytes, {}));
std::vector<std::byte> span(self.descriptorSpanBytes);
const auto spanPolicy = self.forceSync == 0u && self.pendingWrite != nullptr ? self.pendingWrite(address, span.size(), span) : PendingWrite::Sync;
if ((spanPolicy == PendingWrite::KnownValue || spanPolicy == PendingWrite::VerifyKnownValue) && GuestMemory::Accessible(reinterpret_cast<const void*>(address), sizeof(word))) {
policy = spanPolicy;
std::memcpy(&word, span.data(), sizeof(word));
} else {
policy = PendingWrite::Sync;
forcedRaw = self.forceSync != 0u && !spanNeedsSync(self.pendingSpan(address, self.descriptorSpanBytes, {}));
}
} else {
policy = self.pendingWrite(address, sizeof(word), std::as_writable_bytes(std::span(&word, 1)));
if (self.forceSync != 0u && policy != PendingWrite::None) {
@@ -1704,7 +1704,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
if (hasExtension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &barycentricFeatures};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
state->fragmentShaderBarycentric = barycentricFeatures.fragmentShaderBarycentric == VK_TRUE;
state->fragmentShaderBarycentric = barycentricFeatures.fragmentShaderBarycentric == VK_TRUE && std::getenv("APS5_NO_FRAGMENT_SHADER_BARYCENTRIC") == nullptr;
state->fragmentBarycentricBuiltins = state->fragmentShaderBarycentric;
if (state->fragmentShaderBarycentric && hasExtension(VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME)) {
state->fragmentShaderBarycentric = FragmentShaderBarycentricUsable(driverId, state->fragmentShaderBarycentric);
@@ -3207,7 +3207,7 @@ void VulkanDevice::NoteHtileMask(const Graphics::HtileMaskClear& clear) const {
Graphics::NoteHtileMaskOnGpu(graphicsContext(), clear);
}
bool VulkanDevice::DumpSamplesOnGpu(std::uint64_t address) {
bool VulkanDevice::DumpSamplesOnGpu(std::uint64_t address, std::uint32_t blocks) {
static const bool syncDumps = std::getenv("APS5_SYNC_SAMPLE_DUMPS") != nullptr || std::getenv("APS5_NO_GPU_SAMPLE_DUMPS") != nullptr;
if (syncDumps) return false;
if (!state->recorder) return false;
@@ -3222,7 +3222,7 @@ bool VulkanDevice::DumpSamplesOnGpu(std::uint64_t address) {
if (Graphics::AnyShadowedOverlaps(address, bytes)) Graphics::PublishShadow(address, bytes, Graphics::PublishScope::PartialUnits, Graphics::PublishReason::Label);
if (!recorder.QueuesSampleDumps()) recorder.FlushStoresOverlapping(address, bytes);
recorder.FlushKeyStoresOverlapping(address, bytes);
if (!recorder.DumpSamples(import->address + (address - import->base), address)) return false;
if (!recorder.DumpSamples(import->address + (address - import->base), address, blocks)) return false;
recorder.NotePendingWrite(address, bytes);
GuestMemory::MarkWritten(address, bytes);
return true;
@@ -5311,7 +5311,7 @@ constexpr std::size_t MoveRefusals = static_cast<std::size_t>(Graphics::ShaderRe
struct DispatchMoveCounters {
std::atomic<std::uint64_t> checked{0}, exact{0}, moved{0}, buffers{0}, bytes{0};
std::atomic<std::uint64_t> rebuilt{0}, kept{0}, served{0};
std::atomic<std::uint64_t> rebuilt{0}, kept{0}, served{0}, inPlace{0};
std::array<std::atomic<std::uint64_t>, 5> sizes{};
std::array<std::atomic<std::uint64_t>, MoveRefusals> refused{};
std::array<std::atomic<std::uint64_t>, MoveRefusals> filtered{};
@@ -5348,6 +5348,7 @@ void reportDispatchMove() {
const auto moved = take(moves.moved);
const auto buffers = take(moves.buffers);
const auto bytes = take(moves.bytes);
const auto inPlace = take(moves.inPlace);
const auto rebuilt = take(moves.rebuilt);
const auto kept = take(moves.kept);
const auto served = take(moves.served);
@@ -5355,7 +5356,7 @@ void reportDispatchMove() {
for (std::size_t i = 0; i < 5; ++i) sizes[i] = take(moves.sizes[i]);
const auto refused = list(moves.refused);
const auto filtered = list(moves.filtered);
AgcDriver::ProfilePrint_nid_no_patch("[dispmove] (10 s) %llu template hits checked: %llu with every read-only buffer where it was built, %llu with %llu moved ones (%.2f MiB snapshotted; per dispatch up to 1 KiB %llu, 16 KiB %llu, 256 KiB %llu, 4 MiB %llu, more %llu); refused %s at stage A (the hit was dropped before the record), %s at record; after a refusal: %llu rebuilt, %llu inserted beside the movable template (kept), %llu served by an exact entry\n", checked, exact, moved, buffers, static_cast<double>(bytes) / 1048576.0, sizes[0], sizes[1], sizes[2], sizes[3], sizes[4], filtered.c_str(), refused.c_str(), rebuilt, kept, served);
AgcDriver::ProfilePrint_nid_no_patch("[dispmove] (10 s) %llu template hits checked: %llu with every read-only buffer where it was built, %llu with %llu moved ones (%llu bound in place, %.2f MiB snapshotted; per dispatch up to 1 KiB %llu, 16 KiB %llu, 256 KiB %llu, 4 MiB %llu, more %llu); refused %s at stage A (the hit was dropped before the record), %s at record; after a refusal: %llu rebuilt, %llu inserted beside the movable template (kept), %llu served by an exact entry\n", checked, exact, moved, buffers, inPlace, static_cast<double>(bytes) / 1048576.0, sizes[0], sizes[1], sizes[2], sizes[3], sizes[4], filtered.c_str(), refused.c_str(), rebuilt, kept, served);
}
void noteDispatchMoveSize(std::size_t bytes) {
@@ -5550,7 +5551,7 @@ bool VulkanDevice::DmaBufImportSelected() const {
VulkanDevice::DispatchMoveCount VulkanDevice::DispatchMoveCounts() {
auto& moves = DispatchMoves();
DispatchMoveCount count{moves.checked.load(), moves.exact.load(), moves.moved.load(), 0, 0, moves.rebuilt.load(), moves.kept.load(), moves.served.load()};
DispatchMoveCount count{moves.checked.load(), moves.exact.load(), moves.moved.load(), 0, 0, moves.rebuilt.load(), moves.kept.load(), moves.served.load(), moves.inPlace.load()};
for (std::size_t i = 1; i < MoveRefusals; ++i) {
count.refused += moves.refused[i].load();
count.filtered += moves.filtered[i].load();
@@ -5986,7 +5987,8 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) {
const std::pair<std::uint64_t, std::uint64_t> argumentRange{arguments, arguments + 12};
recorder.NoteAccess(CommandClass::IndirectArguments, Graphics::Recorder::Access{std::span(&argumentRange, 1), {}, {}, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT});
}
const auto reads = resources.InPlaceReads();
auto reads = resources.InPlaceReads();
if (record.bindings != nullptr) reads.insert(reads.end(), record.bindings->inPlaceReads.begin(), record.bindings->inPlaceReads.end());
const auto images = resources.StorageImages();
recorder.NoteAccess(CommandClass::DispatchLeading, Graphics::Recorder::Access{reads, resources.GpuWrites(), images, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, resources.HoldsLease()});
}
@@ -6143,7 +6145,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) {
}
recordStep(PhaseRecordBind);
if (record.htileClear.has_value()) Graphics::ArmHtileDepthClear(record.htileClear->first, record.htileClear->second);
resources.MarkGpuWrites(recorder);
resources.MarkGpuWrites(recorder, record.bindings.get());
if (record.htileClear.has_value()) {
Graphics::QueueHtileDepthClear(record.htileClear->first, record.htileClear->second);
recorder.NotePendingWrite(record.htileClear->first, record.htileClear->second);
@@ -6469,6 +6471,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec
moves.moved.fetch_add(1, std::memory_order_relaxed);
moves.buffers.fetch_add(proof.buffers, std::memory_order_relaxed);
moves.bytes.fetch_add(proof.bytes, std::memory_order_relaxed);
moves.inPlace.fetch_add(proof.inPlace, std::memory_order_relaxed);
noteDispatchMoveSize(proof.bytes);
}
}
@@ -48,7 +48,8 @@ std::uint64_t DirectDepthCopyCount();
void SetDepthTransferPasses(bool enabled);
std::uint64_t DepthTransferPassCount();
std::uint64_t MultisampledDepthBytes_nid_no_patch(VkExtent2D extent, std::uint32_t bytesPerTexel, std::uint32_t samples);
void RequireNoResidentDepthRead_nid_no_patch(std::uint64_t address, std::size_t bytes, std::optional<std::pair<std::uint64_t, std::size_t>> htileClear = std::nullopt, bool allowPublication = true);
enum class DepthReadCause { Access, Reuse };
void RequireNoResidentDepthRead_nid_no_patch(std::uint64_t address, std::size_t bytes, std::optional<std::pair<std::uint64_t, std::size_t>> htileClear = std::nullopt, bool allowPublication = true, DepthReadCause cause = DepthReadCause::Access);
void AppendHostWrittenDepthRanges(std::uint64_t address, std::size_t bytes, std::vector<std::pair<std::uint64_t, std::uint64_t>>& ranges);
enum class DepthPublicationStage { ReadCaptured, GuestCopied, BeforeCommit, PlaneCommitted, StencilPlaneRead };
void SetDepthPublicationHookForTest(void (*hook)(DepthPublicationStage));
@@ -74,6 +74,9 @@ DrawInputCopy CopyZeroPaddedDrawInput(const Context& context, std::uint64_t addr
void KeepDrawInput(Recorder* recorder, std::uint64_t address, const DrawInputCopy& copy, Recorder::SnapshotUse use, std::uint32_t derived, std::uint32_t lowest = 0);
inline constexpr std::uint64_t InPlaceDrawInputMaxReads = 512;
const HostImport* InPlaceDrawInput(const Context& context, std::uint64_t address, std::size_t bytes, std::size_t alignment, bool* behindGpuWrite = nullptr, std::size_t fetched = std::numeric_limits<std::size_t>::max(), std::uint64_t reads = std::numeric_limits<std::uint64_t>::max());
enum class IndexBehindWriter : std::uint8_t { Taken, Off, NoWriter, VertexAttributes, IndexLimit, MeshStage, PrimitiveRestart, VertexOffset, UnitShadow, PendingStorage, LabelOrStore, CopiedWriter, NoImport, Refused, Count };
std::array<std::uint64_t, static_cast<std::size_t>(IndexBehindWriter::Count)> IndexBehindWriterCounts();
const HostImport* InPlaceIndexBehindWriter(const Context& context, std::uint64_t address, std::size_t bytes, std::uint32_t indexSize, bool vertexAttributes, bool meshStage, bool primitiveRestart, std::uint32_t firstVertex, IndexBehindWriter* outcome = nullptr);
struct InPlaceIndices {
std::optional<std::uint32_t> highest;
std::uint32_t lowest = 0;
@@ -2,6 +2,7 @@
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_FIRSTSAMPLECOPY_HPP
#include "prx/libSceAgcDriver/Graphics/include/Context.hpp"
#include <memory>
namespace AgcDriver::Graphics {
@@ -9,16 +10,18 @@ class Recorder;
class FirstSampleCopy {
public:
FirstSampleCopy(const Context& context, VkFormat format, VkExtent2D extent);
FirstSampleCopy(const Context& context, VkFormat format, VkExtent2D extent, bool averagePacked = false);
~FirstSampleCopy();
FirstSampleCopy(const FirstSampleCopy&) = delete;
FirstSampleCopy& operator=(const FirstSampleCopy&) = delete;
void Record(Recorder& recorder, VkImageView source, VkImageLayout layout);
std::shared_ptr<void> RecordInto(VkCommandBuffer commands, Recorder* recorder, VkImageView source, VkImageLayout layout, VkImageView destination);
VkImage Image() const { return image; }
private:
void release() noexcept;
std::shared_ptr<void> record(Recorder* recorder, VkCommandBuffer commands, VkImageView source, VkImageLayout layout, VkFramebuffer target);
Context context;
VkExtent2D extent;
@@ -125,6 +125,12 @@ void ReportHostImports();
const HostImport* HostImportFor(const Context& context, std::uint64_t address, std::size_t bytes, ImportRequester requester = ImportRequester::Access);
bool HostImportUsesDmaBuf(const Context& context, std::uint64_t address, std::size_t bytes);
const HostImport* ExistingHostImportFor(const Context& context, std::uint64_t address, std::size_t bytes);
struct HostImportCopy {
VkBuffer buffer;
VkDeviceSize offset;
VkDeviceSize bytes;
};
std::vector<HostImportCopy> ExistingHostImportCopies(const Context& context, std::uint64_t address, std::size_t bytes);
void RequireGpuLockBeforeImports(const char* where);
bool ImportsHeldByThisThread();
bool WatchedAfterSettle(const Context& context, std::uint64_t address, std::size_t bytes);
@@ -184,6 +190,14 @@ std::uint64_t RegisteredReadableEnd(std::uint64_t address);
// imported); see GuestBufferMemory.cpp.
struct ImageMirror;
class Recorder;
class StorageTexture;
struct MirrorPublishEntry {
std::shared_ptr<StorageTexture> image;
std::uint64_t base = 0;
std::uint64_t serial = 0;
std::uint64_t since = 0;
};
template<typename TRange>
void OverlappedRanges(std::span<const TRange> sorted, std::size_t first, std::span<const std::pair<std::uint64_t, std::uint64_t>> writes, std::vector<std::size_t>& indices) {
@@ -204,6 +218,9 @@ void OverlappedRanges(std::span<const TRange> sorted, std::size_t first, std::sp
// work using the import is recorded) the imports are left as they are.
std::uint64_t HostImportSerial(const Context& context, std::uint64_t address, std::size_t bytes, bool reconcile);
bool HostImportView(const Context& context, std::uint64_t address, std::size_t bytes, VkDescriptorBufferInfo& view, std::uint64_t& serial);
// The import table's identity (the fast Revalidate): serials proved under one identity stand
// while the table still has it, i.e. the same device, the same epoch (bumped by every retire)
// and the registry generation it was reconciled with, which must still be the live one.
@@ -589,6 +606,7 @@ private:
// instead of the CPU (see Region::gpuCopy): live guest bytes, not sparse, at most the size
// APS5_GPU_COPY_MAX_KIB allows, and APS5_CPU_COPIES unset.
bool gpuCopyEligible(const Region& region) const;
bool copyBehindGpuWork(const Region& region, bool locked) const;
// Whether a region inside a host import is staged in device memory instead of bound in place
// (see GuestBufferMemory.cpp): staging allowed, not address-based unless an overlay region, a
// written element inside, and an atomic element or a size within the written-shadow window.
@@ -604,6 +622,8 @@ private:
void recordGpuCopies(std::span<Region* const> copies, bool addressable);
void takeHeapReferences();
void releaseHeapReferences() noexcept;
void publishIntoMirrors();
std::vector<MirrorPublishEntry> mirrorPublishes;
Context context;
bool stagingAllowed = false;
bool addressStaging = true;
@@ -3,9 +3,12 @@
#include "Recompiler.hpp"
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <span>
#include <string>
namespace AgcDriver::Graphics {
@@ -150,6 +153,16 @@ bool IsNullTextureResource(std::span<const std::uint32_t> words);
std::optional<std::uint64_t> TextureResourceAllocationAddress(std::span<const std::uint32_t> words);
bool IsNullSampledTextureResource(std::span<const std::uint32_t> words);
GuestTextureResource DecodeTextureResource(std::span<const std::uint32_t> words);
struct TextureResourceDecode {
GuestTextureResource resource{};
std::shared_ptr<const std::string> rejection;
};
inline constexpr std::size_t RememberedTextureRejections = 4096;
TextureResourceDecode TryDecodeTextureResource(std::span<const std::uint32_t> words);
std::size_t RememberedTextureRejectionCount();
std::array<std::uint32_t, 8> EncodeTextureResource(const GuestTextureResource& resource);
bool DescriptorSingleLevel(std::span<const std::uint32_t> words);
bool FirstLayerDescriptor(std::span<const std::uint32_t> words, std::array<std::uint32_t, 8>& narrowed);
@@ -3,6 +3,7 @@
#include "prx/libSceAgcDriver/Graphics/include/Context.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp"
#include "BdaAbi.hpp"
#include "prx/libSceAgcDriver/Graphics/include/State.hpp"
@@ -134,7 +135,7 @@ bool MultisampleColorTargetOverlaps(std::uint64_t address, std::uint64_t bytes);
void ClaimMultisampleTargetStore(std::uint64_t address, std::uint64_t bytes);
void GuardOneFragmentFmask(const Context& context, const ColorTarget& target);
bool HoldsMultisampleTargetsLock();
void RequireNoMultisampleTarget(std::uint64_t address, std::size_t bytes, const char* access);
void RequireNoMultisampleTarget(std::uint64_t address, std::size_t bytes, const char* access, DepthReadCause cause = DepthReadCause::Access);
void RequireNoMultisampleColorTarget(std::uint64_t address, std::size_t bytes, const char* access);
void RetireMultisampleColorTarget(const std::shared_ptr<std::atomic<bool>>& active);
void RetireMultisampleColorTargetsOnFmaskWrite(std::uint64_t address, std::size_t bytes);
@@ -95,6 +95,7 @@ private:
bool depthBounds = false;
bool depthBias = false;
bool libraries = false;
bool dynamicColorWriteMask = false;
std::uint32_t dynamicSlots = 0;
std::shared_ptr<OptimizedPipeline> optimized;
bool dynamicRendering = false;
@@ -373,7 +373,7 @@ public:
};
bool RecordBoundChangedCopy(VkCommandBuffer commands, BoundWords result, BoundWords snapshot, BoundWords target, std::uint32_t dwords, VkBuffer counter = VK_NULL_HANDLE);
std::uint64_t SamplesTotal();
bool DumpSamples(VkDeviceAddress target, std::uint64_t address = 0);
bool DumpSamples(VkDeviceAddress target, std::uint64_t address = 0, std::uint32_t blocks = 0xffffu);
void NoteSampledDraw(VkCommandBuffer commands);
void NoteDrawTraceToken(std::uint64_t token) noexcept;
void NoteFaultToken(AgcDriver::FaultToken token) noexcept;
@@ -661,7 +661,7 @@ public:
// or APS5_PROFILE_GPU). A class range covers the command with its own barriers (a dispatch's
// barriers are classes of their own, its program range stays keyed by the program), so the
// union of every range of a batch and the batch span differ by what no class times ('untimed').
enum class CommandClass : std::uint8_t { DispatchLeading = 0, DispatchTrailing, IndirectArguments, LabelRun, Fill, FillClear, Copy, StagingIn, StagingOut, Draw, StorageUpload, StorageWriteBack, DccClear, DccKeyStore, PresentBlit, ShadowPublish, TemplateDataRefresh, InputMirror, Count };
enum class CommandClass : std::uint8_t { DispatchLeading = 0, DispatchTrailing, IndirectArguments, LabelRun, Fill, FillClear, Copy, StagingIn, StagingOut, Draw, StorageUpload, StorageWriteBack, DccClear, DccKeyStore, PresentBlit, ShadowPublish, TemplateDataRefresh, InputMirror, MirrorPublish, Count };
static constexpr std::uint64_t ClassKey(CommandClass which) { return 0x10 + static_cast<std::uint64_t>(which); }
std::uint32_t BeginGpuTiming(CommandClass which) { return BeginGpuTiming(ClassKey(which)); }
static void CountBarriers(CommandClass which, std::uint32_t count = 1);
@@ -834,6 +834,7 @@ private:
std::uint64_t address;
VkDeviceAddress dumpTarget = 0;
std::uint32_t dumpSegments = 0;
std::uint32_t dumpBlocks = 0;
std::uint64_t End() const;
};
std::vector<Queued> queued;
@@ -903,7 +904,7 @@ private:
void readSamples(Batch& batch);
bool gpuSampleCounter();
void endSamples(Batch& batch);
void foldSamples(Batch& batch, VkDeviceAddress target);
void foldSamples(Batch& batch, VkDeviceAddress target, std::uint32_t blocks = 0xffffu);
bool segmentMode() const;
bool segmentSlotReady(const Batch& batch) const;
void takeSegmentPool(Batch& batch);
@@ -952,6 +953,7 @@ private:
// them null and resolves per call as before; vkWaitSemaphoresKHR stays a lazy lookup (timeline
// semaphores are optional).
PFN_vkGetFenceStatus getFenceStatus = nullptr;
PFN_vkGetSemaphoreCounterValueKHR getSemaphoreCounterValue = nullptr;
PFN_vkResetFences resetFences = nullptr;
PFN_vkWaitForFences waitForFences = nullptr;
PFN_vkCmdUpdateBuffer cmdUpdateBuffer = nullptr;
@@ -970,6 +972,8 @@ private:
return resolved != nullptr ? resolved : context.Function<TFunction>(name);
}
VkResult fenceStatus(VkFence fence) const { return function(getFenceStatus, "vkGetFenceStatus")(context.device, fence); }
bool gpuDone(const Batch& batch) const;
std::uint64_t readTimeline() const;
void recordBarrier(VkCommandBuffer commands, VkPipelineStageFlags sourceStage, VkPipelineStageFlags destinationStage, VkAccessFlags sourceAccess, VkAccessFlags destinationAccess) const;
// Opens a batch when none is open, without closing a store run (Commands() does both).
void ensureOpen();
@@ -1033,6 +1037,8 @@ private:
Context context;
VkSemaphore timeline = VK_NULL_HANDLE;
bool fenceless = false;
mutable std::uint64_t reachedSerial = 0;
VkSemaphore submitHold = VK_NULL_HANDLE;
std::uint64_t submitHoldValue = 0;
struct ProgressWatcher;
@@ -45,6 +45,7 @@ public:
void Store(std::uint64_t guest, std::span<const std::byte> bytes);
std::shared_ptr<Buffer> RecordReadback(VkCommandBuffer commands, std::uint64_t guest, std::uint64_t bytes) const;
void ReadDevice(std::uint64_t guest, std::span<std::byte> out);
std::uint64_t UploadSerial(std::uint64_t begin, std::uint64_t end) const;
static void FlushChanged(const Context& context);
private:
@@ -70,6 +71,8 @@ private:
std::uint64_t size = 0;
std::uint64_t bound = 0;
std::vector<Slot> slots;
std::vector<std::uint64_t> uploads;
std::uint64_t uploadCounter = 0;
std::mutex changedMutex;
GuestRuns changed;
};
@@ -23,8 +23,10 @@ enum class RuntimeSwitch : std::size_t {
NoSharedCollectWalks,
NoExtendedFastProofs,
TableSnapshot,
NoAliasViews,
NoTargetMemo,
NoTargetMemoOverlapCache,
IndexInPlaceBehindWriter,
Count,
};
@@ -241,6 +241,14 @@ public:
DescriptorCache::SetAllocation fragmentAllocation;
DescriptorCache::SetAllocation allocation;
std::vector<Snapshot> snapshots;
struct InPlace {
std::size_t allocation;
VkBuffer buffer;
VkDeviceSize offset;
std::size_t bytes;
};
std::vector<InPlace> inPlace;
std::vector<std::pair<std::uint64_t, std::uint64_t>> inPlaceReads;
~DrawBindings();
};
struct MovedBuffer {
@@ -251,6 +259,7 @@ public:
VkBuffer inPlace = VK_NULL_HANDLE;
VkDeviceSize inPlaceOffset = 0;
std::uint32_t adjustment = 0;
bool dispatchInPlace = false;
};
struct DrawUse {
DrawUse() = default;
@@ -272,6 +281,7 @@ public:
MoveRefusal refusal = MoveRefusal::None;
std::size_t buffers = 0;
std::size_t bytes = 0;
std::size_t inPlace = 0;
};
static const char* MoveRefusalName(MoveRefusal refusal);
std::optional<std::vector<MovedBuffer>> MovedDispatchBuffers(const CompiledShader& shader, Recorder* recorder, std::size_t maxBytes, MoveProof& proof) const;
@@ -281,7 +291,7 @@ public:
// Deferred completion: MarkGpuWrites registers the results the recorded work leaves on the GPU
// (storage images stay there; buffer ranges are noted so CPU reads wait); WriteBackBuffers runs
// once the work completed.
void MarkGpuWrites(Recorder& recorder);
void MarkGpuWrites(Recorder& recorder, const DrawBindings* bindings = nullptr);
void WriteBackBuffers();
// Whether WriteBackBuffers has anything the CPU must see (copied written buffers, BDA faults).
bool NeedsCompletion() const { return (bda != nullptr && faultChecks) || guestMemory.HasCopiedWrites(); }
@@ -646,6 +656,7 @@ private:
bool sourceEligible = false;
bool depthCompare = false;
bool sourceRefreshed = false;
const StorageTexture* alias = nullptr;
};
// `serialBefore` is StorageTexture::PendingSerial() loaded before any check of this Revalidate;
// `refreshed` the surfaces refreshOwnObjects resolved earlier in the same Revalidate (empty on
@@ -30,7 +30,7 @@ class Buffer;
class ResidentColor;
class CommandBatch;
class StorageTexture;
struct HostImport;
struct HostImportCopy;
// The Vulkan format storage images of a guest format use (sRGB formats store as their UNORM form).
// Throws when the format has no storage form; the query is cached per format (a lookup cost a
@@ -70,7 +70,7 @@ struct OwnedImage {
class Texture {
public:
Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, bool depthCompare = false, bool layerRows = false, const VkClearColorValue* clear = nullptr, std::optional<std::span<const std::uint32_t>> packedSlabs = std::nullopt, const HostImport* source = nullptr);
Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, bool depthCompare = false, bool layerRows = false, const VkClearColorValue* clear = nullptr, std::optional<std::span<const std::uint32_t>> packedSlabs = std::nullopt, std::span<const HostImportCopy> sources = {});
Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::shared_ptr<Buffer> staging, bool depthCompare = false, bool layerRows = false, std::optional<std::span<const std::uint32_t>> packedSlabs = std::nullopt);
Texture(const Context& context, const std::shared_ptr<ResidentColor>& source, const GuestTextureResource& descriptor, VkComponentMapping components);
// A view of a storage image's own VkImage: the sampled texture follows the image's content, so a
@@ -144,7 +144,7 @@ public:
void MarkReleased() { released.store(true, std::memory_order_release); }
private:
Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, std::shared_ptr<Buffer> staging, bool depthCompare, bool layerRows, const VkClearColorValue* clear, std::optional<std::span<const std::uint32_t>> packedSlabs, const HostImport* source);
Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, std::shared_ptr<Buffer> staging, bool depthCompare, bool layerRows, const VkClearColorValue* clear, std::optional<std::span<const std::uint32_t>> packedSlabs, std::span<const HostImportCopy> sources);
void release() noexcept;
bool refreshBlockCopy();
bool refreshSrgbExpand();
@@ -418,6 +418,47 @@ public:
// does when it lists no image, and all an access AccessKeptByCpu approved needs): whether any
// unit was published.
static bool PublishShadowsOnly(std::uint64_t address, std::size_t bytes, PublishScope scope, const char* reason = "memory access", bool waited = false);
class MirrorPublishScope {
public:
MirrorPublishScope(std::vector<std::shared_ptr<StorageTexture>>& deferred, std::uint64_t address, std::size_t bytes);
~MirrorPublishScope();
MirrorPublishScope(const MirrorPublishScope&) = delete;
MirrorPublishScope& operator=(const MirrorPublishScope&) = delete;
private:
MirrorPublishScope* previous;
std::vector<std::shared_ptr<StorageTexture>>& deferred;
std::uint64_t address;
std::size_t bytes;
friend class StorageTexture;
};
static bool MirrorPublishEnabled();
static bool DeferToMirror(std::uint64_t address, std::size_t bytes);
std::optional<std::vector<std::pair<std::uint64_t, std::uint64_t>>> MirrorPublishRanges(std::uint64_t begin, std::uint64_t end) const;
struct MirrorTarget {
VkBuffer buffer = VK_NULL_HANDLE;
std::uint64_t origin = 0;
std::uint64_t serial = 0;
std::uint64_t uploads = 0;
std::shared_ptr<void> keep;
};
bool MirrorPublishCurrent(const MirrorTarget& target, std::uint64_t begin, std::uint64_t end) const;
std::uint64_t PublishIntoMirror(const MirrorTarget& target, std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges, std::uint64_t begin, std::uint64_t end);
enum class MirrorFallback : std::uint8_t { ReadTrap, DccKeys, DrawnRect, Unwatched, NoGeneration, Copied, Written, Untracked, NoRecorder, Count };
static constexpr std::size_t MirrorFallbackReasons = static_cast<std::size_t>(MirrorFallback::Count);
static const char* MirrorFallbackName(MirrorFallback reason);
struct MirrorPublishCounts {
std::uint64_t published = 0;
std::uint64_t bytes = 0;
std::uint64_t skipped = 0;
std::uint64_t fallbacks = 0;
std::uint64_t refreshed = 0;
std::array<std::uint64_t, MirrorFallbackReasons> reasons{};
std::array<std::uint64_t, MirrorFallbackReasons> reasonBytes{};
};
static MirrorPublishCounts MirrorPublishTotals();
static void NoteMirrorPublishFallback(MirrorFallback reason, std::uint64_t bytes);
static void NoteMirrorPublishRefresh();
// For the [hooksync] recorded-store line: images a FlushPending stored after a hook skip of
// theirs (AccessKeptByCpu), of which by the hook for the same read site as the last skip; 10 s deltas.
struct HookSkipCounts {
@@ -447,6 +488,7 @@ public:
// contains a descriptor of its first mips), if any; the caller decides whether the geometry fits
// (Texture::CanCopyFrom, ResidentPresentable).
static std::shared_ptr<StorageTexture> FindPending(std::uint64_t address, std::uint64_t bytes);
bool IsPendingAlias(const StorageTexture& pending) const;
VkDevice Device() const;
static std::uint64_t EightBitWrites();
static std::shared_ptr<StorageTexture> FindPendingSlice(std::uint64_t address, std::uint64_t bytes);
@@ -788,6 +830,7 @@ private:
void forgetBorrowed(std::uint32_t first, std::uint32_t count);
bool clearByKeysFill(DccKeys keys, std::uint8_t key);
bool overlaps(std::uint64_t address, std::size_t bytes) const;
static bool trapReadsAtLabel(const StorageTexture* texture);
// Whether the image is live (not released) and overlaps the fill: the test that gives ClassifyFill
// its overlapping images, and that NoteKeysFill and ClearByKeysFill use to bound the key match.
bool overlapsLive(std::uint64_t address, std::size_t bytes) const;
@@ -796,6 +839,16 @@ private:
// saying whether any live image overlaps the fill (see Texture.cpp).
bool keysFillMatches(std::uint64_t address, std::size_t bytes, bool overlapped) const;
bool pendingUnitInside(std::uint64_t address, std::size_t bytes) const;
std::optional<MirrorFallback> mirrorPublishRefusal() const;
struct MirrorPublishMemo {
std::uint64_t mirror = 0;
std::uint64_t begin = 0;
std::uint64_t end = 0;
std::uint64_t version = 0;
std::uint64_t uploads = 0;
std::uint64_t tracker = 0;
};
std::vector<MirrorPublishMemo> mirrorMemos;
bool storesWhole() const;
void appendStoredLayers(std::uint64_t address, std::size_t bytes, std::vector<std::pair<std::uint64_t, std::uint64_t>>& ranges) const;
VkImageView createView(std::uint32_t mip, bool firstLayer, VkFormat format) const;
@@ -909,6 +962,9 @@ private:
std::atomic<bool> writtenOccasionally{false};
std::uint64_t version = 0;
std::uint64_t writes = 0;
std::uint64_t zeroForgetMarks = 0;
std::uint64_t zeroForgetBegin = 0;
std::uint64_t zeroForgetEnd = 0;
// `original` holds the guest bytes; false after a GPU-side clear, which never read them.
std::vector<bool> layerOriginal;
std::map<std::uint64_t, std::uint64_t> keptAtUnwatch;
@@ -87,7 +87,8 @@ struct SurfaceGeometry {
SurfaceGeometry DescribeSurface(const GuestTextureResource& descriptor);
std::uint64_t DescribeSurfaceGuestBytes(const GuestTextureResource& descriptor);
std::uint64_t SurfaceGuestBytes(const GuestTextureResource& descriptor);
std::vector<TileMipLayout> ComputeGcnMipLayout(TextureTileMode tileMode, std::uint32_t format, std::uint32_t width, std::uint32_t height, std::uint32_t pitch, bool pow2Pad, std::uint32_t mipCount, bool linearGeneral = false, std::uint32_t layers = 1, bool volume = false);
std::vector<TileMipLayout> ComputeGcnMipLayout(TextureTileMode tileMode, std::uint32_t format, std::uint32_t width, std::uint32_t height, std::uint32_t pitch, bool pow2Pad, std::uint32_t mipCount, bool linearGeneral = false, std::uint32_t layers = 1, bool volume = false, std::uint32_t samples = 1);
inline constexpr std::uint32_t GcnSampleShift = 28u;
struct GcnTileGeometry {
std::uint32_t blockBytes;
std::uint32_t blockWidth;
@@ -99,7 +100,7 @@ struct GcnTileGeometry {
std::uint32_t bankMask = 0;
std::uint32_t bankShift = 0;
};
GcnTileGeometry GcnTiling(TextureTileMode tileMode, std::uint32_t bytesPerElement);
GcnTileGeometry GcnTiling(TextureTileMode tileMode, std::uint32_t bytesPerElement, std::uint32_t samples = 1);
inline std::uint32_t GcnLayerBankXor(const GcnTileGeometry& geometry, std::uint32_t layer) { return ((geometry.layerBankStep * layer) & geometry.bankMask) << geometry.bankShift; }
inline TextureTileMode MipTileMode(TextureTileMode tileMode, const TileMipLayout& mip) { return mip.gcnMicroTiled ? (IsGcnThick(tileMode) ? TextureTileMode::kGcnThin1D : GcnMicroTileMode(tileMode)) : tileMode; }
bool LevelsFitAllocation(const GuestTextureResource& surface, std::uint32_t levels);
@@ -6,11 +6,53 @@ layout(location = 0) out uvec4 color;
#elif defined(SINT_SAMPLES)
layout(set = 0, binding = 0) uniform isampler2DMS source;
layout(location = 0) out ivec4 color;
#elif defined(PACKED_SAMPLES)
layout(set = 0, binding = 0) uniform usampler2DMS source;
layout(location = 0) out uvec4 color;
#else
layout(set = 0, binding = 0) uniform sampler2DMS source;
layout(location = 0) out vec4 color;
#endif
#if defined(PACKED_SAMPLES)
uint averageField(ivec2 texel, int samples, uint offset, uint mantissaBits) {
uint mask = (1u << mantissaBits) - 1u;
uvec2 sum = uvec2(0u);
bool nan = false;
bool infinity = false;
for (int sampleIndex = 0; sampleIndex < samples; ++sampleIndex) {
uint raw = bitfieldExtract(texelFetch(source, texel, sampleIndex).x, int(offset), int(mantissaBits + 5u));
uint exponent = raw >> mantissaBits;
uint mantissa = raw & mask;
if (exponent == 31u) {
nan = nan || mantissa != 0u;
infinity = infinity || mantissa == 0u;
continue;
}
uint significand = exponent == 0u ? mantissa : mantissa | (1u << mantissaBits);
uint shift = exponent == 0u ? 0u : exponent - 1u;
uint carry;
sum.x = uaddCarry(sum.x, significand << shift, carry);
sum.y += carry + (shift == 0u ? 0u : significand >> (32u - shift));
}
if (nan) return (31u << mantissaBits) | (1u << (mantissaBits - 1u));
if (infinity) return 31u << mantissaBits;
uint divide = uint(findLSB(uint(samples)));
uvec2 units = divide == 0u ? sum : uvec2((sum.x >> divide) | (sum.y << (32u - divide)), sum.y >> divide);
if (units.y == 0u && units.x <= mask) return units.x;
int top = units.y != 0u ? 32 + findMSB(units.y) : findMSB(units.x);
uint drop = uint(top) - mantissaBits;
uint kept = drop == 0u ? units.x : drop >= 32u ? units.y >> (drop - 32u) : (units.x >> drop) | (units.y << (32u - drop));
return ((drop + 1u) << mantissaBits) | (kept & mask);
}
#endif
void main() {
#if defined(PACKED_SAMPLES)
ivec2 texel = ivec2(gl_FragCoord.xy);
int samples = textureSamples(source);
color = uvec4(averageField(texel, samples, 0u, 5u) | (averageField(texel, samples, 10u, 6u) << 10u) | (averageField(texel, samples, 21u, 6u) << 21u), 0u, 0u, 0u);
#else
color = texelFetch(source, ivec2(gl_FragCoord.xy), 0);
#endif
}
@@ -8,11 +8,15 @@ layout(push_constant) uniform Parameters {
Words target;
uint count;
uint store;
uint blocks;
} parameters;
void main() {
uint first = uint(findLSB(parameters.blocks));
if (parameters.store == 2u) {
for (uint db = 0u; db < 16u; ++db) parameters.target.words[db * 4u + 1u] |= 0x80000000u;
for (uint db = 0u; db < 16u; ++db) {
if ((parameters.blocks & (1u << db)) != 0u) parameters.target.words[db * 4u + 1u] |= 0x80000000u;
}
return;
}
uint low = parameters.counter.words[0];
@@ -23,11 +27,15 @@ void main() {
high = high + parameters.counter.words[5u + 2u * i] + carry;
}
if (parameters.store == 1u) {
for (uint db = 0u; db < 16u; ++db) parameters.target.words[db * 4u + 1u] = db == 0u ? (high & 0x7fffffffu) : 0u;
for (uint db = 0u; db < 16u; ++db) {
if ((parameters.blocks & (1u << db)) != 0u) parameters.target.words[db * 4u + 1u] = db == first ? (high & 0x7fffffffu) : 0u;
}
return;
}
if (parameters.store == 3u) {
for (uint db = 0u; db < 16u; ++db) parameters.target.words[db * 4u] = db == 0u ? low : 0u;
for (uint db = 0u; db < 16u; ++db) {
if ((parameters.blocks & (1u << db)) != 0u) parameters.target.words[db * 4u] = db == first ? low : 0u;
}
}
parameters.counter.words[0] = low;
parameters.counter.words[1] = high;
@@ -26,10 +26,13 @@ void main() {
high = high + parameters.counter.words[5u + 2u * segment] + carry;
}
Words target = Words(uvec2(parameters.dumps.words[dump * 4u], parameters.dumps.words[dump * 4u + 1u]));
uint blocks = parameters.dumps.words[dump * 4u + 3u];
uint first = uint(findLSB(blocks));
for (uint db = 0u; db < 16u; ++db) {
if (parameters.phase == 0u) target.words[db * 4u + 1u] = db == 0u ? (high & 0x7fffffffu) : 0u;
else if (parameters.phase == 1u) target.words[db * 4u] = db == 0u ? low : 0u;
else target.words[db * 4u + 1u] = (db == 0u ? high : 0u) | 0x80000000u;
if ((blocks & (1u << db)) == 0u) continue;
if (parameters.phase == 0u) target.words[db * 4u + 1u] = db == first ? (high & 0x7fffffffu) : 0u;
else if (parameters.phase == 1u) target.words[db * 4u] = db == first ? low : 0u;
else target.words[db * 4u + 1u] = (db == first ? high : 0u) | 0x80000000u;
}
}
if (parameters.phase != 2u && parameters.dumpCount != 0u) return;
@@ -933,6 +933,7 @@ class DepthSurface {
public:
DepthSurface(const Context& context, const DepthTarget& target, DepthSamplingState sampling = {}) : context(context), target(target), hostFormat(HostDepthFormat(context, target.format)), sampling(std::move(sampling)) {
this->context.bufferPool.reset();
samplingObservations.resize(this->sampling.initial.size());
VkFormatProperties properties{};
context.formatProperties(context.physical, hostFormat, &properties);
Require((properties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) != 0, "depth/stencil format " + std::to_string(hostFormat) + " cannot be an attachment on this device");
@@ -1061,7 +1062,7 @@ public:
RecorderFor(context)->SyncThrough(range.address, range.bytes);
Require(!GuestMemory::WrittenSince(range.address, range.bytes, settled), "external GPU writes over native multisample depth are not implemented");
}
GuestMemory::CollectWritesUncached(range.address, range.bytes);
GuestMemory::CollectWritesForGpuUse(range, samplingObservations[index]);
const auto alias = MultisampleColorTargetOver(range.address, range.bytes);
if (!alias || (index == 2u && sampling.unprovenStencil && stencilClearGeneration == 0u)) continue;
if (index == 0u && sampling.depthAlias && sameDepthAlias(*sampling.depthAlias, range)) continue;
@@ -1441,7 +1442,7 @@ public:
});
}
void PublishToGuest();
bool PublishToGuest(DepthReadCause cause);
std::uint64_t written = ++depthWrites;
std::shared_ptr<std::atomic<bool>> hostWritten = std::make_shared<std::atomic<bool>>(false);
@@ -2028,6 +2029,7 @@ public:
bool sampleable = true;
bool samplingActive = false;
DepthSamplingState sampling;
mutable std::vector<GuestMemory::GpuUseObservation> samplingObservations;
bool clearPending = false;
std::uint64_t clearGeneration = 0u;
bool clearCompletionQueued = false;
@@ -3161,7 +3163,7 @@ std::uint32_t expandedHtileWord(std::uint32_t word, bool stencilInHtile, VkImage
return word;
}
void DepthSurface::PublishToGuest() {
bool DepthSurface::PublishToGuest(DepthReadCause cause) {
Require(!Recorder::InCompletion(), "native multisample depth publication inside a GPU completion is not implemented");
Require(!publicationInProgress, "recursive native multisample depth publication is not implemented");
Require(!publicationFailed, "a previous native multisample depth publication store did not complete");
@@ -3254,7 +3256,11 @@ void DepthSurface::PublishToGuest() {
if (current[index][offset] != plane.Byte(offset) || current[index][offset] == result[index][offset] || GuestMemory::StoredAllSince_nid_no_patch(plane.range.address + offset, 1u, plane.range.generation)) {
if (current[index][offset] != result[index][offset]) tookGuest[index] = true;
result[index][offset] = current[index][offset];
} else Require(GuestMemory::UnchangedSinceLastCollect(plane.range.address + offset, 1u, plane.range.generation), "native multisample depth publication cannot distinguish an unwritten byte from a same-value guest store");
} else if (!GuestMemory::UnchangedSinceLastCollect(plane.range.address + offset, 1u, plane.range.generation)) {
Require(cause == DepthReadCause::Reuse, "native multisample depth publication cannot distinguish an unwritten byte from a same-value guest store");
tookGuest[index] = true;
result[index][offset] = current[index][offset];
}
}
}
first += bytes;
@@ -3292,17 +3298,20 @@ void DepthSurface::PublishToGuest() {
publication.clear();
if (superseded[0]) RetireMultisampleColorTarget(sampling.depthAlias->active);
if (superseded[2]) RetireMultisampleColorTarget(sampling.stencilAlias->active);
return std::ranges::find(tookGuest, true) != tookGuest.end();
}
void publishWrittenDepth(std::span<const std::shared_ptr<std::atomic<bool>>> written) {
std::vector<std::shared_ptr<std::atomic<bool>>> publishWrittenDepth(std::span<const std::shared_ptr<std::atomic<bool>>> written, DepthReadCause cause) {
std::lock_guard gpu(GuestMemory::GpuMutex());
std::lock_guard lock(surfacesMutex());
std::vector<std::shared_ptr<std::atomic<bool>>> tookGuest;
for (const auto& flag : written) {
if (!flag->load(std::memory_order_acquire)) continue;
const auto found = std::ranges::find_if(surfaces(), [&](const auto& surface) { return surface->hostWritten == flag && surface->active->load(std::memory_order_acquire); });
if (found == surfaces().end()) continue;
(*found)->PublishToGuest();
if ((*found)->PublishToGuest(cause)) tookGuest.push_back((*found)->active);
}
return tookGuest;
}
std::mutex& htileReadsMutex() {
@@ -3789,7 +3798,7 @@ void proveOverwrittenPlanes(std::uint64_t address, std::size_t bytes) {
}
}
void RequireNoResidentDepthRead_nid_no_patch(std::uint64_t address, std::size_t bytes, std::optional<std::pair<std::uint64_t, std::size_t>> htileClear, bool allowPublication) {
void RequireNoResidentDepthRead_nid_no_patch(std::uint64_t address, std::size_t bytes, std::optional<std::pair<std::uint64_t, std::size_t>> htileClear, bool allowPublication, DepthReadCause cause) {
if (bytes != 0u && pendingOverwriteProofs().load(std::memory_order_acquire) != 0u && allowPublication && !HoldsMultisampleTargetsLock()) proveOverwrittenPlanes(address, 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");
@@ -3816,17 +3825,20 @@ void RequireNoResidentDepthRead_nid_no_patch(std::uint64_t address, std::size_t
if (overlaps(range) && range.hostWritten->load(std::memory_order_acquire) && std::ranges::find(written, range.hostWritten) == written.end()) written.push_back(range.hostWritten);
}
}
std::vector<std::shared_ptr<std::atomic<bool>>> tookGuest;
if (!written.empty()) {
Require(allowPublication && !HoldsMultisampleTargetsLock(), "sample-preserving guest publication of native multisample depth is not implemented while a multisampled colour target is being acquired");
if (const auto hook = depthPublicationHook.load(std::memory_order_acquire)) hook(DepthPublicationStage::ReadCaptured);
publishWrittenDepth(written);
tookGuest = publishWrittenDepth(written, cause);
}
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.hostEverWritten->load(std::memory_order_acquire)) range.active->store(false, std::memory_order_release);
if (!overlaps(range) || !range.active->load(std::memory_order_acquire)) continue;
const bool replaced = cause == DepthReadCause::Reuse && std::ranges::find(tookGuest, range.active) != tookGuest.end();
if (replaced || !range.hostEverWritten->load(std::memory_order_acquire)) range.active->store(false, std::memory_order_release);
}
const auto removed = std::erase_if(depthGuards(), [](const auto& range) { return !range.active->load(std::memory_order_acquire); });
publishDepthGuards(removed != 0);
@@ -4071,9 +4083,9 @@ VkImageView DepthSurfaceViewWithStencilWriteIntent(const Context& context, const
const auto metadataBytes = target.htileAddress == 0u ? 0u : HtileMetadataBytes(target.extent);
Require(target.address <= std::numeric_limits<std::uint64_t>::max() - depthBytes && target.stencilAddress <= std::numeric_limits<std::uint64_t>::max() - stencilBytes && target.htileAddress <= std::numeric_limits<std::uint64_t>::max() - metadataBytes, "native depth attachment range overflows");
lock.unlock();
RequireNoResidentDepthRead_nid_no_patch(target.address, static_cast<std::size_t>(depthBytes));
if (stencilBytes != 0u) RequireNoResidentDepthRead_nid_no_patch(target.stencilAddress, static_cast<std::size_t>(stencilBytes));
if (metadataBytes != 0u) RequireNoResidentDepthRead_nid_no_patch(target.htileAddress, static_cast<std::size_t>(metadataBytes));
RequireNoResidentDepthRead_nid_no_patch(target.address, static_cast<std::size_t>(depthBytes), std::nullopt, true, DepthReadCause::Reuse);
if (stencilBytes != 0u) RequireNoResidentDepthRead_nid_no_patch(target.stencilAddress, static_cast<std::size_t>(stencilBytes), std::nullopt, true, DepthReadCause::Reuse);
if (metadataBytes != 0u) RequireNoResidentDepthRead_nid_no_patch(target.htileAddress, static_cast<std::size_t>(metadataBytes), std::nullopt, true, DepthReadCause::Reuse);
{
std::shared_lock guardLock(depthGuardMutex());
for (const auto& range : depthGuards()) {
@@ -1579,6 +1579,80 @@ const HostImport* InPlaceDrawInput(const Context& context, std::uint64_t address
return import;
}
namespace {
constexpr std::array<const char*, static_cast<std::size_t>(IndexBehindWriter::Count)> IndexBehindWriterNames{
"taken", "off", "no writer", "vertex attributes", "index limit", "mesh stage", "primitive restart", "vertex offset",
"unit shadow", "pending storage", "label or store", "copied writer", "no import", "refused"
};
std::array<ProfileCounter, static_cast<std::size_t>(IndexBehindWriter::Count)>& indexBehindWriterEvents() {
static std::array<ProfileCounter, static_cast<std::size_t>(IndexBehindWriter::Count)> events;
return events;
}
const bool indexBehindWriterProfiled = std::getenv("APS5_PROFILE_DRAW") != nullptr;
void reportIndexBehindWriter() {
using Clock = std::chrono::steady_clock;
static std::atomic<std::int64_t> reported{Clock::now().time_since_epoch().count()};
static std::array<std::uint64_t, static_cast<std::size_t>(IndexBehindWriter::Count)> previous{};
const auto now = Clock::now().time_since_epoch().count();
auto last = reported.load(std::memory_order_relaxed);
if (Clock::duration(now - last) < std::chrono::seconds(10) || !reported.compare_exchange_strong(last, now, std::memory_order_relaxed)) return;
std::string line;
for (std::size_t index = 0; index < previous.size(); ++index) {
const auto total = indexBehindWriterEvents()[index].Sum();
const auto count = total - previous[index];
previous[index] = total;
if (count == 0) continue;
line += (line.empty() ? " " : ", ") + std::string(IndexBehindWriterNames[index]) + " " + std::to_string(count);
}
AgcDriver::ProfilePrint_nid_no_patch("[index-behind-writer] (10 s, all threads, index ranges behind a pending GPU writer):%s\n", line.empty() ? " none" : line.c_str());
}
}
std::array<std::uint64_t, static_cast<std::size_t>(IndexBehindWriter::Count)> IndexBehindWriterCounts() {
std::array<std::uint64_t, static_cast<std::size_t>(IndexBehindWriter::Count)> counts{};
for (std::size_t index = 0; index < counts.size(); ++index) counts[index] = indexBehindWriterEvents()[index].Sum();
return counts;
}
const HostImport* InPlaceIndexBehindWriter(const Context& context, std::uint64_t address, std::size_t bytes, std::uint32_t indexSize, bool vertexAttributes, bool meshStage, bool primitiveRestart, std::uint32_t firstVertex, IndexBehindWriter* outcome) {
const bool enabled = RuntimeSwitches::Set(RuntimeSwitch::IndexInPlaceBehindWriter);
const auto leave = [&](IndexBehindWriter result, const HostImport* import) {
if (outcome != nullptr) *outcome = result;
if (enabled) {
indexBehindWriterEvents()[static_cast<std::size_t>(result)].Add(1);
if (indexBehindWriterProfiled) reportIndexBehindWriter();
}
return import;
};
auto* recorder = context.recorder;
if (!enabled || recorder == nullptr || (indexSize != 2 && indexSize != 4) || bytes < indexSize) return leave(IndexBehindWriter::Off, nullptr);
if (!recorder->PendingWriteOverlaps(address, bytes)) return leave(IndexBehindWriter::NoWriter, nullptr);
if (vertexAttributes) return leave(IndexBehindWriter::VertexAttributes, nullptr);
if (context.limits.maxDrawIndexedIndexValue != std::numeric_limits<std::uint32_t>::max()) return leave(IndexBehindWriter::IndexLimit, nullptr);
if (meshStage) return leave(IndexBehindWriter::MeshStage, nullptr);
if (primitiveRestart) return leave(IndexBehindWriter::PrimitiveRestart, nullptr);
const std::uint32_t largestIndex = indexSize == 2 ? 0xffffu : std::numeric_limits<std::uint32_t>::max();
if (firstVertex > std::numeric_limits<std::uint32_t>::max() - largestIndex) return leave(IndexBehindWriter::VertexOffset, nullptr);
if (AnyShadowedOverlaps(address, bytes)) return leave(IndexBehindWriter::UnitShadow, nullptr);
if (PendingStorageOverlaps(address, bytes, nullptr)) return leave(IndexBehindWriter::PendingStorage, nullptr);
if (recorder->PendingLabelIn(address, bytes) || recorder->CompletionLabelIn(address, bytes) || recorder->QueuedStoreOverlaps(address, bytes)) return leave(IndexBehindWriter::LabelOrStore, nullptr);
const auto overlaps = [&](const auto& writer) { return writer->WritesOverlap(address, bytes); };
const auto drawWriters = DrawCopiedWriters();
if ((context.copiedWriters != nullptr && std::any_of(context.copiedWriters->begin(), context.copiedWriters->end(), overlaps)) || std::any_of(drawWriters->begin(), drawWriters->end(), overlaps)) return leave(IndexBehindWriter::CopiedWriter, nullptr);
const auto* existing = ExistingHostImportFor(context, address, bytes);
if (existing == nullptr || HostImportOffset(*existing, address) % indexSize != 0) return leave(IndexBehindWriter::NoImport, nullptr);
auto inPlace = context;
inPlace.drawInputsInPlace = true;
bool behind = false;
const auto* import = InPlaceDrawInput(inPlace, address, bytes, indexSize, &behind);
return leave(import != nullptr ? IndexBehindWriter::Taken : IndexBehindWriter::Refused, import);
}
InPlaceIndices InPlaceIndexRange(Recorder& recorder, std::uint64_t address, std::size_t bytes, std::uint32_t indexSize, bool skipRestart) {
const std::span<const std::byte> range(reinterpret_cast<const std::byte*>(address), bytes);
InPlaceIndices indices;
@@ -1627,6 +1701,7 @@ struct DrawInputs {
std::vector<VkDeviceSize> vertexOffsets;
std::vector<std::pair<std::uint64_t, std::uint64_t>> inPlaceReads;
bool vertexInputBehindGpuWrite = false;
bool indexInputBehindGpuWrite = false;
std::uint32_t fragmentOutputs = 0;
VkPipelineStageFlags shaderStages = 0;
std::uint32_t meshGroups = 0;
@@ -1806,7 +1881,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
const auto indexBytes = inputs.indexBytes;
if (draw.indexed) GuestMemory::CheckRange(reinterpret_cast<const void*>(draw.indexAddress), static_cast<std::size_t>(indexBytes), draw.indexSize);
APS5_LOG_CHARS_OUT_DEBUG("Index buffer range OK");
if (draw.indexed) RequireNoMultisampleTarget(draw.indexAddress, static_cast<std::size_t>(indexBytes), "an index buffer read");
if (draw.indexed) RequireNoMultisampleTarget(draw.indexAddress, static_cast<std::size_t>(indexBytes), "an index buffer read", DepthReadCause::Reuse);
if (state.pixelKill && !state.pixelEarlyZ && std::ranges::any_of(state.colors, [](const ColorTarget& color) { return color.partialWriteMask != 0; })) {
const auto* recorder = Recorder::Active();
Require(recorder == nullptr || !recorder->CountingSamples(), "a partial write of a packed color target merges inside the pixel shader after early depth and stencil tests, which a shader that kills pixels under late tests cannot use while occlusion queries count samples: the early tests would count the pixels it kills");
@@ -1932,13 +2007,17 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
const bool skipRestart = state.primitiveRestart && (!listTopology || context.primitiveListRestart || state.stages.mesh);
const auto use = draw.indexSize == 2 ? (skipRestart ? Recorder::SnapshotUse::Index16Restart : Recorder::SnapshotUse::Index16) : (skipRestart ? Recorder::SnapshotUse::Index32Restart : Recorder::SnapshotUse::Index32);
const bool restartTable = skipRestart && state.stages.mesh && (state.stages.mesh->inputPrimitive == 5 || state.stages.mesh->inputPrimitive == 6);
const auto* import = InPlaceDrawInput(context, draw.indexAddress, static_cast<std::size_t>(indexBytes), draw.indexSize, nullptr, static_cast<std::size_t>(indexBytes), reads);
const auto* behindWriter = InPlaceIndexBehindWriter(context, draw.indexAddress, static_cast<std::size_t>(indexBytes), draw.indexSize, !shaders.front().program->vertexAttributes.empty(), static_cast<bool>(state.stages.mesh), skipRestart, draw.firstVertex);
const auto* import = behindWriter != nullptr ? behindWriter : InPlaceDrawInput(context, draw.indexAddress, static_cast<std::size_t>(indexBytes), draw.indexSize, nullptr, static_cast<std::size_t>(indexBytes), reads);
DrawInputCopy copy;
if (import == nullptr) copy = CopyDrawInput(context, context.recorder, draw.indexAddress, static_cast<std::size_t>(indexBytes), draw.indexSize, use, 0, !BindsIndexCopy(state));
else GuestMemory::CheckRange(reinterpret_cast<const void*>(draw.indexAddress), static_cast<std::size_t>(indexBytes), draw.indexSize);
std::optional<std::uint32_t> highest;
std::uint32_t lowest = 0;
if (import != nullptr) {
if (behindWriter != nullptr) {
highest = draw.indexSize == 2 ? 0xffffu : std::numeric_limits<std::uint32_t>::max();
inputs.indexInputBehindGpuWrite = true;
} else if (import != nullptr) {
const auto range = InPlaceIndexRange(*context.recorder, draw.indexAddress, static_cast<std::size_t>(indexBytes), draw.indexSize, skipRestart);
highest = range.highest;
lowest = range.lowest;
@@ -2059,7 +2138,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
const auto [begin, end] = plan.copies[range];
const auto bytes = static_cast<std::size_t>(end - begin);
GuestMemory::CheckRange(reinterpret_cast<const void*>(begin), bytes, 1);
RequireNoMultisampleTarget(begin, bytes, "a vertex buffer read");
RequireNoMultisampleTarget(begin, bytes, "a vertex buffer read", DepthReadCause::Reuse);
if (const auto* import = InPlaceDrawInput(context, begin, bytes, plan.alignments[range], &inputs.vertexInputBehindGpuWrite, bytes - std::min(rangeFrom[range], bytes), reads)) {
rangeHandles.push_back(import->buffer);
rangeOffsets.push_back(HostImportOffset(*import, begin));
@@ -2952,7 +3031,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam
const bool fenced = state.depth.has_value() || !record.proxies.empty();
resources.RequireGuestBuffers();
if (UsesMeshWindow(shaders)) PrepareMeshWindow(context);
const auto start = recorder->StartDrawPass(passKey, capture || readsTarget || gpuIndirect || meshIndirect || captured || !record.staged.empty() || PixelFunctionLdsSubgroup(shaders) != 0u, fenced, passAccess);
const auto start = recorder->StartDrawPass(passKey, inputs.indexInputBehindGpuWrite || capture || readsTarget || gpuIndirect || meshIndirect || captured || !record.staged.empty() || PixelFunctionLdsSubgroup(shaders) != 0u, fenced, passAccess);
if (record.spaceKeep != nullptr) *record.spaceKeep = reserveSpaceKeep(*recorder, resources);
for (const auto& target : record.multisampleTargets) KeepMultisampleTarget_nid_no_patch(target);
const bool continued = start.continued;
@@ -3002,8 +3081,8 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam
countBarrier(1);
}
APS5_LOG_CHARS_OUT_DEBUG("Upload barrier recorded");
if (inputs.vertexInputBehindGpuWrite) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT);
if (inputs.vertexInputBehindGpuWrite || inputs.indexInputBehindGpuWrite) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, (inputs.vertexInputBehindGpuWrite ? VkAccessFlags{VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT} : VkAccessFlags{0}) | (inputs.indexInputBehindGpuWrite ? VkAccessFlags{VK_ACCESS_INDEX_READ_BIT} : VkAccessFlags{0}));
countBarrier(1);
}
const auto pixelLdsSubgroup = PixelFunctionLdsSubgroup(shaders);
@@ -3828,7 +3907,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
Require((shader.program->hostSubgroupSize == 1u || shader.program->hostSubgroupSize == context.subgroup.subgroupSize) && shader.program->spirv.size() >= 5u && shader.program->spirv[1] >= 0x00010000u && shader.program->spirv[1] < 0x00010600u, "stencil replay vertex subgroup contract differs from the physical device");
}
Require(static_cast<std::uint64_t>(draw.firstInstance) + draw.instanceCount <= 0x100000000ull && (draw.indexed || static_cast<std::uint64_t>(draw.firstVertex) + draw.indexCount <= 0x100000000ull), "stencil replay draw indices overflow");
Require(state.samples == 1u && (!state.depth || HasStencil(state.depth->format)), "stencil replay requires single-sample rendering and an eight-bit stencil format");
Require(!state.depth || HasStencil(state.depth->format), "stencil replay requires an eight-bit stencil format");
recipeOut = nullptr;
}
if (state.quadList || StripPatches(state, shaders)) recipeOut = nullptr;
@@ -4115,8 +4194,12 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
Require(!imageRead && !resources->ReadsImage(target.resident.get()) && !resources->ReadsOverlap(target.color.MemoryAddress(), static_cast<std::size_t>(target.color.bytes)) && !inputOverlaps(target.color.MemoryAddress(), target.color.bytes), "stencil replay refuses attachment feedback reads");
}
if (state.depth) {
const auto bytes = static_cast<std::size_t>(state.depth->extent.width) * state.depth->extent.height * 4u;
const auto bytes = static_cast<std::size_t>(state.depth->extent.width) * state.depth->extent.height * 4u * std::max(state.depth->samples, 1u);
Require(!resources->ReadsOverlap(state.depth->address, bytes) && !resources->ReadsOverlap(state.depth->stencilAddress, bytes) && !inputOverlaps(state.depth->address, bytes) && !inputOverlaps(state.depth->stencilAddress, bytes), "stencil replay refuses depth or stencil feedback reads");
const auto boundPlane = [&](std::uint64_t address, std::uint64_t length) {
const auto overlaps = [&](std::uint64_t plane) { return plane != 0u && address < plane + bytes && plane < address + length; };
return overlaps(state.depth->address) || overlaps(state.depth->stencilAddress);
};
for (const auto& shader : shaders) {
for (const auto& binding : shader.program->bindings) {
if (binding.role != ShaderRecompiler::DescriptorRole::GuestImages && binding.role != ShaderRecompiler::DescriptorRole::ImageTable) continue;
@@ -4124,7 +4207,9 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
const auto words = std::span<const std::uint32_t>(binding.guestDescriptor).subspan(offset, 8u);
if (words[0] == 0u && (words[1] & 0xffu) == 0u) continue;
const auto texture = DecodeTextureResource(words);
Require(!DepthSurfaceAt(context, words, texture), "stencil replay refuses sampled depth-surface feedback");
if (!DepthSurfaceAt(context, words, texture)) continue;
const auto sampledBytes = static_cast<std::uint64_t>(texture.width) * texture.height * 4u * std::max(texture.samples, 1u) * (static_cast<std::uint64_t>(texture.depthOrLastArray) + 1u);
Require(!boundPlane(texture.baseAddress, sampledBytes), "stencil replay refuses sampled depth-surface feedback");
}
}
}
@@ -4516,8 +4601,8 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D
countBarrier();
}
APS5_LOG_CHARS_OUT_DEBUG("Upload barrier recorded");
if (inputs.vertexInputBehindGpuWrite) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT);
if (inputs.vertexInputBehindGpuWrite || inputs.indexInputBehindGpuWrite) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, (inputs.vertexInputBehindGpuWrite ? VkAccessFlags{VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT} : VkAccessFlags{0}) | (inputs.indexInputBehindGpuWrite ? VkAccessFlags{VK_ACCESS_INDEX_READ_BIT} : VkAccessFlags{0}));
countBarrier();
}
const auto pixelLdsSubgroup = PixelFunctionLdsSubgroup(shaders);
@@ -1,11 +1,14 @@
#include "prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp"
#include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp"
#include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/shaders/FirstSampleFloat_spv.h"
#include "prx/libSceAgcDriver/Graphics/shaders/FirstSamplePacked_spv.h"
#include "prx/libSceAgcDriver/Graphics/shaders/FirstSampleSint_spv.h"
#include "prx/libSceAgcDriver/Graphics/shaders/FirstSampleUint_spv.h"
#include "prx/libSceAgcDriver/Graphics/shaders/PresentationPassVert_spv.h"
#include <array>
#include <memory>
#include <span>
@@ -32,7 +35,8 @@ bool uintFormat(VkFormat format) {
}
}
std::span<const std::uint32_t> fragmentCode(VkFormat format) {
std::span<const std::uint32_t> fragmentCode(VkFormat format, bool averagePacked) {
if (averagePacked) return FIRST_SAMPLE_PACKED_SPV;
if (sintFormat(format)) return FIRST_SAMPLE_SINT_SPV;
if (uintFormat(format)) return FIRST_SAMPLE_UINT_SPV;
return FIRST_SAMPLE_FLOAT_SPV;
@@ -49,7 +53,7 @@ struct DescriptorPool {
}
FirstSampleCopy::FirstSampleCopy(const Context& context, VkFormat format, VkExtent2D extent) : context(context), extent(extent) {
FirstSampleCopy::FirstSampleCopy(const Context& context, VkFormat format, VkExtent2D extent, bool averagePacked) : context(context), extent(extent) {
try {
VkImageCreateInfo imageInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
imageInfo.imageType = VK_IMAGE_TYPE_2D;
@@ -136,7 +140,7 @@ FirstSampleCopy::FirstSampleCopy(const Context& context, VkFormat format, VkExte
Check(context.Function<PFN_vkCreateFramebuffer>("vkCreateFramebuffer")(context.device, &framebufferInfo, nullptr, &framebuffer), "vkCreateFramebuffer first sample");
vertex = CreateShaderModule(context, PRESENTATION_PASS_VERT_SPV, sizeof(PRESENTATION_PASS_VERT_SPV), "vkCreateShaderModule first sample vertex");
const auto code = fragmentCode(format);
const auto code = fragmentCode(format, averagePacked);
fragment = CreateShaderModule(context, code.data(), code.size_bytes(), "vkCreateShaderModule first sample fragment");
VkPipelineShaderStageCreateInfo stages[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}};
stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
@@ -214,6 +218,19 @@ void FirstSampleCopy::release() noexcept {
}
void FirstSampleCopy::Record(Recorder& recorder, VkImageView source, VkImageLayout layout) {
record(&recorder, VK_NULL_HANDLE, source, layout, framebuffer);
}
std::shared_ptr<void> FirstSampleCopy::RecordInto(VkCommandBuffer commands, Recorder* recorder, VkImageView source, VkImageLayout layout, VkImageView destination) {
const std::array<VkImageView, 1> views{destination};
auto target = std::make_shared<Framebuffer>(context, renderPass, views, extent);
auto pool = record(recorder, commands, source, layout, target->Handle());
auto kept = std::make_shared<std::pair<std::shared_ptr<void>, std::shared_ptr<Framebuffer>>>(std::move(pool), std::move(target));
if (recorder != nullptr) recorder->Keep(kept);
return kept;
}
std::shared_ptr<void> FirstSampleCopy::record(Recorder* recorder, VkCommandBuffer batchCommands, VkImageView source, VkImageLayout layout, VkFramebuffer target) {
const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1};
VkDescriptorPoolCreateInfo poolInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO};
poolInfo.maxSets = 1;
@@ -236,19 +253,27 @@ void FirstSampleCopy::Record(Recorder& recorder, VkImageView source, VkImageLayo
write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write.pImageInfo = &imageInfo;
context.Function<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(context.device, 1, &write, 0, nullptr);
recorder.Keep(pool);
recorder.RecordUncounted([&](CommandState& recording) {
const auto draw = [&](CommandState& recording) {
const auto commands = recording.Commands();
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
begin.renderPass = renderPass;
begin.framebuffer = framebuffer;
begin.framebuffer = target;
begin.renderArea = {{0, 0}, extent};
context.Resolved(&DeviceFunctions::cmdBeginRenderPass, "vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
recording.BindPipeline(context, pipeline, 0);
context.Function<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, 0, nullptr);
context.Function<PFN_vkCmdDraw>("vkCmdDraw")(commands, 3, 1, 0, 0);
context.Resolved(&DeviceFunctions::cmdEndRenderPass, "vkCmdEndRenderPass")(commands);
});
};
if (recorder != nullptr) {
recorder->Keep(pool);
recorder->RecordUncounted(draw);
} else {
CommandState recording;
recording.Begin(batchCommands, false);
draw(recording);
}
return pool;
}
}
@@ -183,6 +183,7 @@ void clearCarriedShadows(VkDevice device);
struct RefreshBlock;
static thread_local GuestBufferMemory* buildingBufferMemory = nullptr;
static thread_local std::vector<RefreshBlock>* buildingBlocks = nullptr;
static thread_local std::vector<MirrorPublishEntry>* publishing = nullptr;
std::atomic<std::uint64_t> importSetGeneration{1};
@@ -1018,7 +1019,7 @@ bool createSparseDmaBufImport(const Context& context, HostImport& entry, int fil
if (runs.empty()) return false;
const auto lead = runs[0].offset % SparseBlockBytes;
const bool ownQueue = context.sparseQueue != VK_NULL_HANDLE && context.sparseQueueMutex != nullptr;
if (!context.sparseBinding || entry.bytes <= ImportChunkBytes || (!ownQueue && !GuestMemory::GpuMutex().HeldByThisThread()) || udmabufDevice() < 0) return false;
if (!context.sparseBinding || (!ownQueue && !GuestMemory::GpuMutex().HeldByThisThread()) || udmabufDevice() < 0) return false;
struct stat backing {};
if (fstat(file, &backing) != 0) throwSparseImport(entry, "fstat of the shared backing", VK_ERROR_INVALID_EXTERNAL_HANDLE);
const auto chunkTypes = dmaBufBufferRequirements(context, entry, 0, ChunkImportUsage, ImportChunkBytes, nullptr).memoryTypeBits;
@@ -1061,8 +1062,13 @@ bool createSparseDmaBufImport(const Context& context, HostImport& entry, int fil
const char* step = nullptr;
VkResult failure = VK_SUCCESS;
auto chunk = importChunk(context, file, index, requirements.memoryTypeBits, step, failure);
const bool usable = chunk != nullptr && ((requirements.memoryTypeBits >> chunk->memoryType) & 1u) != 0;
if (!usable && entry.bytes <= ImportChunkBytes) {
context.Function<PFN_vkDestroyBuffer>("vkDestroyBuffer")(context.device, buffer, nullptr);
return false;
}
if (chunk == nullptr) fail(step, failure);
if (((requirements.memoryTypeBits >> chunk->memoryType) & 1u) == 0) fail("the memory type of a chunk import", VK_ERROR_FORMAT_NOT_SUPPORTED);
if (!usable) fail("the memory type of a chunk import", VK_ERROR_FORMAT_NOT_SUPPORTED);
binds.push_back({piece.resource + done, size, chunk->memory, within, 0});
chunks->push_back(std::move(chunk));
done += size;
@@ -3457,6 +3463,33 @@ void prepareRange(std::uint64_t address, std::uint64_t bytes) {
syncRange(address, bytes);
}
void syncHeapRange(std::uint64_t address, std::uint64_t bytes, std::span<ImageMirror* const> mirrors) {
const bool resident = !mirrors.empty() && std::all_of(mirrors.begin(), mirrors.end(), [](const ImageMirror* mirror) { return mirror->resident != nullptr; });
if (publishing == nullptr || !resident || !StorageTexture::MirrorPublishEnabled()) {
if (publishing != nullptr && !resident && StorageTexture::MirrorPublishEnabled() && StorageTexture::AnyPendingOverlaps(std::array<std::pair<std::uint64_t, std::uint64_t>, 1>{{{address, address + bytes}}})) StorageTexture::NoteMirrorPublishFallback(StorageTexture::MirrorFallback::Copied, bytes);
syncRange(address, bytes);
return;
}
std::vector<std::shared_ptr<StorageTexture>> deferred;
const auto since = GuestMemory::TrackerGeneration();
{
const StorageTexture::MirrorPublishScope scope(deferred, address, static_cast<std::size_t>(bytes));
syncRange(address, bytes);
}
for (auto& image : deferred) {
const auto imageBegin = image->Descriptor().baseAddress;
const auto imageEnd = imageBegin + image->GuestBytes();
for (auto* mirror : mirrors) {
if (imageBegin < mirror->base + mirror->bytes && mirror->base < imageEnd) publishing->push_back({image, mirror->base, mirror->serial, since});
}
}
}
void prepareHeapRange(std::uint64_t address, std::uint64_t bytes, std::span<ImageMirror* const> mirrors) {
Require(GuestMemory::Accessible(reinterpret_cast<const void*>(address), static_cast<std::size_t>(bytes)), "image mirror range became inaccessible");
syncHeapRange(address, bytes, mirrors);
}
bool prepareRefresh(ImageMirror& mirror, std::uint64_t address, std::uint64_t bytes) {
if ((!mirror.writable && !mirror.heap) || bytes == 0) return false;
prepareRange(address, bytes);
@@ -3561,7 +3594,7 @@ void refreshHeapMirrors(std::vector<ImageMirror*>& mirrors, std::vector<RefreshB
while (last < mirrors.size() && mirrors[last]->base == mirrors[last - 1]->base + mirrors[last - 1]->bytes) ++last;
const auto begin = mirrors[first]->base;
const auto bytes = mirrors[last - 1]->base + mirrors[last - 1]->bytes - begin;
prepareRange(begin, bytes);
prepareHeapRange(begin, bytes, std::span<ImageMirror* const>(mirrors).subspan(first, last - first));
const auto generation = GuestMemory::CollectWrites(begin, static_cast<std::size_t>(bytes));
appendHeapRun(std::span<ImageMirror* const>(mirrors).subspan(first, last - first), generation, blocks);
first = last;
@@ -3662,7 +3695,8 @@ Pieces clipPieces(const Pieces& pieces, std::uint64_t begin, std::uint64_t end)
bool refreshSparseMirror(ImageMirror& mirror, std::vector<RefreshBlock>& blocks) {
auto pieces = GuestMemory::DescribeCommitted(mirror.base, static_cast<std::size_t>(mirror.reserved)).ranges;
if (!pieces.empty() && pieces.back().second > mirror.base + mirror.bytes) return false;
syncRange(mirror.base, mirror.bytes);
ImageMirror* const heap[1]{&mirror};
syncHeapRange(mirror.base, mirror.bytes, heap);
const auto generation = collectPieces(pieces);
if (generation == 0) markUnwatched(mirror);
appendSparseBlocks(mirror, std::move(pieces), generation, blocks);
@@ -3697,7 +3731,7 @@ std::vector<std::pair<std::size_t, std::uint64_t>> refreshHeapRuns(const GuestBu
checked.reserve(space.heapRuns.size());
for (std::size_t index = 0; index < space.heapRuns.size(); ++index) {
const auto& run = space.heapRuns[index];
prepareRange(run.begin, run.bytes);
prepareHeapRange(run.begin, run.bytes, std::span<ImageMirror* const>(space.heapMirrors).subspan(run.first, run.last - run.first));
const auto generation = GuestMemory::CollectWrites(run.begin, static_cast<std::size_t>(run.bytes));
const auto since = space.verified[index].load(std::memory_order_relaxed);
if (since == 0 || !GuestMemory::UnchangedSince(run.begin, static_cast<std::size_t>(run.bytes), since)) appendHeapRun(std::span<ImageMirror* const>(space.heapMirrors).subspan(run.first, run.last - run.first), generation, blocks);
@@ -4984,6 +5018,28 @@ const HostImport* ExistingHostImportFor(const Context& context, std::uint64_t ad
return findImport(state, address, address + bytes);
}
std::vector<HostImportCopy> ExistingHostImportCopies(const Context& context, std::uint64_t address, std::size_t bytes) {
if (context.hostImportAlignment == 0 || bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address) return {};
auto& state = Imports();
std::lock_guard lock(state.mutex);
if (importsStale(context, state)) return {};
std::vector<HostImportCopy> copies;
const auto end = address + bytes;
for (auto cursor = address; cursor < end;) {
const auto* entry = peekImport(state, cursor, cursor + 1);
if (entry == nullptr) return {};
const auto next = std::min(end, entry->base + entry->bytes);
copies.push_back({entry->buffer, HostImportOffset(*entry, cursor), next - cursor});
cursor = next;
}
auto cursor = address;
for (const auto& copy : copies) {
static_cast<void>(findImport(state, cursor, cursor + copy.bytes));
cursor += copy.bytes;
}
return copies;
}
bool WatchedAfterSettle(const Context& context, std::uint64_t address, std::size_t bytes) {
#ifdef _WIN32
if (context.hostImportAlignment != 0 && bytes != 0 && bytes <= std::numeric_limits<std::uint64_t>::max() - address && GuestMemory::GpuMutex().HeldByThisThread()) {
@@ -5214,6 +5270,18 @@ void GuestBufferMemory::CountAddressBuild(double snapshotsUs) {
const auto space = AddressSpaceCounters();
const auto& spaceSeen = totals.spaceSeen;
AgcDriver::ProfilePrint_nid_no_patch("[address] %llu address-based builds (10 s), us per build: lease %.0f, imports pass %.0f, mirror prepare %.0f, compare %.0f (%.0f blocks, %.1f copied), snapshots %.0f; space hits %llu (patched after an import change %llu) / rebuilds: generation %llu, epoch %llu, growth %llu, device %llu, waiter drop %llu, first %llu; unpublished %llu, dissolved: overlap %llu, imports %llu%s; [bda-table] hits %llu / misses %llu (space tables %llu), first entry: expired %llu, hash differs low %llu / heap %llu, same hash %llu, none held %llu\n", static_cast<unsigned long long>(totals.builds), per(totals.sums.leaseUs), per(totals.sums.importsUs), per(totals.sums.mirrorsUs), per(totals.sums.compareUs), per(static_cast<double>(totals.sums.blocksCompared)), per(static_cast<double>(totals.sums.blocksCopied)), per(totals.snapshotsUs), delta(space.hits, spaceSeen.hits), delta(space.patchedEpoch, spaceSeen.patchedEpoch), delta(space.rebuiltGeneration, spaceSeen.rebuiltGeneration), delta(space.rebuiltEpoch, spaceSeen.rebuiltEpoch), delta(space.rebuiltGrowth, spaceSeen.rebuiltGrowth), delta(space.rebuiltDevice, spaceSeen.rebuiltDevice), delta(space.rebuiltWaiterDrop, spaceSeen.rebuiltWaiterDrop), delta(space.rebuiltFirst, spaceSeen.rebuiltFirst), delta(space.unpublished, spaceSeen.unpublished), delta(space.dissolvedOverlap, spaceSeen.dissolvedOverlap), delta(space.dissolvedImports, spaceSeen.dissolvedImports), space.enabled ? "" : " (cache off)", delta(table.hits, seen.hits), delta(table.misses, seen.misses), delta(table.spaceTables, seen.spaceTables), delta(table.firstExpired, seen.firstExpired), delta(table.firstDiffersLow, seen.firstDiffersLow), delta(table.firstDiffersHeap, seen.firstDiffersHeap), delta(table.firstSameHash, seen.firstSameHash), delta(table.firstEmpty, seen.firstEmpty));
static StorageTexture::MirrorPublishCounts publishSeen{};
const auto publish = StorageTexture::MirrorPublishTotals();
std::string fallbackReasons;
for (std::size_t reason = 0; reason < StorageTexture::MirrorFallbackReasons; ++reason) {
const auto count = publish.reasons[reason] - publishSeen.reasons[reason];
if (count == 0) continue;
char text[96];
std::snprintf(text, sizeof(text), "%s%s %llu/%.1f MiB", fallbackReasons.empty() ? "" : ", ", StorageTexture::MirrorFallbackName(static_cast<StorageTexture::MirrorFallback>(reason)), static_cast<unsigned long long>(count), static_cast<double>(publish.reasonBytes[reason] - publishSeen.reasonBytes[reason]) / 1048576.0);
fallbackReasons += text;
}
AgcDriver::ProfilePrint_nid_no_patch("[address] mirror publish (10 s): published %llu (%.1f MiB), skipped unchanged %llu, fallbacks %llu (%s), refreshes %llu%s\n", delta(publish.published, publishSeen.published), static_cast<double>(publish.bytes - publishSeen.bytes) / 1048576.0, delta(publish.skipped, publishSeen.skipped), delta(publish.fallbacks, publishSeen.fallbacks), fallbackReasons.empty() ? "none" : fallbackReasons.c_str(), delta(publish.refreshed, publishSeen.refreshed), StorageTexture::MirrorPublishEnabled() ? "" : " (off)");
publishSeen = publish;
totals.tableSeen = table;
totals.spaceSeen = space;
totals.builds = 0;
@@ -5285,10 +5353,15 @@ void stampSpaceUse(HostImports& state, const GuestBufferMemory::AddressSpace& sp
void GuestBufferMemory::AcquireRegistered() {
struct BuildingScope {
explicit BuildingScope(GuestBufferMemory* self) { buildingBufferMemory = self; }
explicit BuildingScope(GuestBufferMemory* self) {
buildingBufferMemory = self;
self->mirrorPublishes.clear();
publishing = &self->mirrorPublishes;
}
~BuildingScope() {
buildingBufferMemory = nullptr;
buildingBlocks = nullptr;
publishing = nullptr;
}
};
const BuildingScope buildingScope(this);
@@ -5906,6 +5979,7 @@ bool GuestBufferMemory::ReleaseCompletedSpace(std::uint64_t recorder, std::uint6
std::shared_ptr<const void> GuestBufferMemory::ReleaseSpace() {
GuestMemory::AssertGpuLockHeld("GuestBufferMemory::ReleaseSpace");
mirrorPublishes.clear();
if (space == nullptr) return {};
spaceHeldThrough = 0;
spaceHeldBy = 0;
@@ -6010,6 +6084,12 @@ bool GuestBufferMemory::RetakeSpace() {
}
if (epochMirrors()) noteEpochMirrors(false, *space);
}
mirrorPublishes.clear();
struct PublishingScope {
explicit PublishingScope(std::vector<MirrorPublishEntry>& entries) { publishing = &entries; }
~PublishingScope() { publishing = nullptr; }
};
const PublishingScope publishingScope(mirrorPublishes);
const auto checked = refreshHeapRuns(*space, blocks);
compareBlocks(blocks);
for (const auto& [run, collected] : checked) space->verified[run].store(collected, std::memory_order_relaxed);
@@ -6023,6 +6103,7 @@ bool GuestBufferMemory::RetakeSpace() {
if (space->importsEpoch != state.epoch) {
releasedSpace = space;
space.reset();
mirrorPublishes.clear();
return false;
}
}
@@ -6417,6 +6498,16 @@ bool GuestBufferMemory::gpuCopyEligible(const Region& region) const {
return region.end - region.begin <= gpuCopyLimit();
}
bool GuestBufferMemory::copyBehindGpuWork(const Region& region, bool locked) const {
if (!gpuCopiesEnabled() || region.sparse || !(region.hostBacked || region.writable)) return false;
const auto* recorder = Recorder::Active();
if (recorder == nullptr) return false;
const auto bytes = static_cast<std::size_t>(region.end - region.begin);
const std::array<std::pair<std::uint64_t, std::uint64_t>, 1> range{{{region.begin, region.end}}};
const bool written = locked ? recorder->PendingWriteOverlaps(region.begin, bytes) : Recorder::SnapshotWriteOverlaps(region.begin, bytes);
return written || StorageTexture::AnyPendingOverlaps(range) || AnyShadowedOverlaps(region.begin, bytes);
}
bool GuestBufferMemory::bindableInPlace(std::uint64_t offset, bool addressable) const {
if (adjustedRegions && !addressable) return offset % 4 == 0;
return offset % context.limits.minStorageBufferOffsetAlignment == 0;
@@ -6638,7 +6729,7 @@ void GuestBufferMemory::UploadPrepare(bool addressable) {
}
if (misaligned || staged) {
if (!staged) {
if (!gpuCopyEligible(region)) continue;
if (!gpuCopyEligible(region) && !copyBehindGpuWork(region, false)) continue;
const auto allocateStart = std::chrono::steady_clock::now();
region.buffer = std::make_shared<Buffer>(context, static_cast<std::size_t>(region.end - region.begin), gpuCopyUsage(context, addressable), copyBufferProperties(false));
if (profile) allocateUs.fetch_add(microsecondsSince(allocateStart), std::memory_order_relaxed);
@@ -6789,6 +6880,7 @@ void GuestBufferMemory::UploadFinish(bool addressable, std::optional<std::pair<s
heapsBegin = space->base.front().begin;
heapsEnd = space->base.back().end;
}
static std::atomic<int> sparseImports{0};
for (auto& region : regions) {
if (!region.pending) continue;
region.pending = false;
@@ -6821,12 +6913,13 @@ void GuestBufferMemory::UploadFinish(bool addressable, std::optional<std::pair<s
entry = importAccess(context, state, region.begin, region.end, importRanges(), ImportRequester::Build);
}
bool runImport = false;
if (entry == nullptr && sparseRun && !region.backed.empty() && region.backed.front().first == region.begin && !WritesOverlap(region.begin, static_cast<std::size_t>(bytes))) {
static const bool sparseImport = std::getenv("APS5_NO_SPARSE_HEAP_IMPORT") == nullptr;
if (sparseImport && entry == nullptr && sparseRun && !region.backed.empty() && region.backed.front().first == region.begin) {
const auto committedEnd = region.backed.back().second;
const auto neededEnd = std::min(region.end, std::max(committedEnd, std::max(region.lastView, region.begin) + 4u));
const auto covers = [&](const HostImport* candidate) { return candidate != nullptr && candidate->base <= region.begin && candidate->base + candidate->bytes >= neededEnd; };
entry = findImport(state, region.begin, neededEnd);
if (entry == nullptr && runCovers(importRanges(), region.begin, neededEnd)) entry = importAllocation(context, state, region.begin, importRanges(), ImportRequester::Build);
if (entry == nullptr && runCovers(importRanges(), region.begin, neededEnd)) entry = importAllocation(context, state, region.begin, importRanges(), ImportRequester::Build, neededEnd);
if (!covers(entry)) entry = nullptr;
const auto& lease = importRanges();
const auto index = leasedIndexContaining(lease, region.begin);
@@ -6851,12 +6944,16 @@ void GuestBufferMemory::UploadFinish(bool addressable, std::optional<std::pair<s
if (entry != nullptr && !staged && bindableInPlace(HostImportOffset(*entry, region.begin), addressable)) {
region.direct = entry;
region.runCut = runImport;
if (runImport && profile) {
const auto count = sparseImports.fetch_add(1, std::memory_order_relaxed) + 1;
if (count <= 8 || count % 1000 == 0) AgcDriver::ProfilePrint_nid_no_patch("[buffers] sparse heap imported in place: 0x%llx+0x%llx, %d times\n", static_cast<unsigned long long>(region.begin), static_cast<unsigned long long>(entry->bytes), count);
}
region.snapshot.clear();
// A buffer UploadPrepare made for a GPU copy is not needed: the import serves the
// region in place (Descriptor prefers `direct`), and a kept buffer would count as copied.
region.buffer.reset();
region.deviceLocal = false;
} else if (entry != nullptr && recorder != nullptr && (staged || gpuCopyEligible(region))) {
} else if (entry != nullptr && recorder != nullptr && (staged || gpuCopyEligible(region) || copyBehindGpuWork(region, true))) {
// Misaligned in the import (or staged): the GPU copies the sub-range out of it. The
// handle and base are taken now, under the import lock: a reconcile by the flush
// below could retire the entry (the batch opened below keeps a retired import's
@@ -6914,6 +7011,7 @@ void GuestBufferMemory::UploadFinish(bool addressable, std::optional<std::pair<s
if (addressable) StoreDepthExpandWrites(context);
if (heapsEnd > heapsBegin) StorageTexture::PublishShadowsOnly(heapsBegin, static_cast<std::size_t>(heapsEnd - heapsBegin), PublishScope::Whole, "address-based heaps");
if (!gpuCopies.empty()) recordGpuCopies(gpuCopies, addressable);
publishIntoMirrors();
takeHeapReferences();
ResidentBuffer::FlushChanged(context);
if (!profile) return;
@@ -7779,6 +7877,98 @@ void GuestBufferMemory::releaseHeapReferences() noexcept {
heapReadbacks.clear();
}
namespace {
void refreshResidentRange(ImageMirror& mirror, std::uint64_t begin, std::uint64_t end) {
constexpr std::uint64_t block = 65536;
const auto from = std::max(mirror.base, begin / block * block);
const auto to = std::min(mirror.base + mirror.bytes, (end + block - 1) / block * block);
if (from >= to) return;
std::vector<RefreshBlock> blocks;
appendBlocks(blocks, mirror, from, to - from);
const auto generation = GuestMemory::CollectWrites(from, static_cast<std::size_t>(to - from));
for (auto& entry : blocks) entry.generation = generation;
compareBlocks(blocks);
StorageTexture::NoteMirrorPublishRefresh();
}
}
void GuestBufferMemory::publishIntoMirrors() {
if (mirrorPublishes.empty()) return;
GuestMemory::AssertGpuLockHeld("GuestBufferMemory::publishIntoMirrors");
auto entries = std::move(mirrorPublishes);
mirrorPublishes.clear();
struct Work {
StorageTexture* image;
std::shared_ptr<ImageMirror> mirror;
std::uint64_t begin;
std::uint64_t end;
std::vector<std::pair<std::uint64_t, std::uint64_t>> ranges;
};
auto& state = Mirrors();
const auto store = [](std::uint64_t begin, std::size_t bytes) {
StorageTexture::NoteMirrorPublishFallback(StorageTexture::MirrorFallback::Copied, bytes);
StorageTexture::FlushPending(begin, bytes, nullptr, "memory access");
};
std::vector<std::shared_ptr<ImageMirror>> held(entries.size());
{
std::lock_guard lock(state.mutex);
for (std::size_t index = 0; index < entries.size(); ++index) {
const auto found = state.entries.find(entries[index].base);
if (found != state.entries.end() && found->second->serial == entries[index].serial && found->second->listed && found->second->resident != nullptr) held[index] = found->second;
}
}
std::vector<Work> work;
const auto* active = Recorder::Active();
const bool recording = active != nullptr && active->Device() == context.device;
for (std::size_t index = 0; index < entries.size(); ++index) {
const auto& entry = entries[index];
if (held[index] == nullptr) {
store(entry.image->Descriptor().baseAddress, static_cast<std::size_t>(entry.image->GuestBytes()));
continue;
}
auto& mirror = *held[index];
const auto begin = std::max(entry.image->Descriptor().baseAddress, mirror.base);
const auto end = std::min(entry.image->Descriptor().baseAddress + entry.image->GuestBytes(), mirror.base + mirror.bytes);
if (begin >= end) continue;
const auto bytes = static_cast<std::size_t>(end - begin);
std::optional<std::vector<std::pair<std::uint64_t, std::uint64_t>>> ranges;
const bool written = mirror.writable && WritesOverlap(begin, bytes);
if (!recording) StorageTexture::NoteMirrorPublishFallback(StorageTexture::MirrorFallback::NoRecorder, bytes);
else if (written) StorageTexture::NoteMirrorPublishFallback(StorageTexture::MirrorFallback::Written, bytes);
else ranges = entry.image->MirrorPublishRanges(begin, end);
if (!ranges.has_value() || ranges->empty()) {
if (!ranges.has_value()) StorageTexture::FlushPending(begin, bytes, nullptr, "memory access");
if (auto* recorder = Recorder::Active(); recorder != nullptr && recorder->PendingWriteOverlaps(begin, bytes)) {
Recorder::CountSync(4);
++state.syncs;
recorder->Sync();
}
refreshResidentRange(mirror, begin, end);
continue;
}
if (!GuestMemory::UnchangedSince(begin, bytes, entry.since)) refreshResidentRange(mirror, begin, end);
growResident(mirror, *ranges);
work.push_back({entry.image.get(), held[index], begin, end, std::move(*ranges)});
}
ResidentBuffer::FlushChanged(context);
for (auto& item : work) {
std::shared_ptr<ResidentBuffer> resident;
{
std::lock_guard lock(state.mutex);
if (item.mirror->listed) resident = item.mirror->resident;
}
if (resident == nullptr) {
store(item.begin, static_cast<std::size_t>(item.end - item.begin));
continue;
}
const StorageTexture::MirrorTarget target{resident->Handle(), resident->Origin(), item.mirror->serial, resident->UploadSerial(item.begin, item.end), resident};
if (item.image->MirrorPublishCurrent(target, item.begin, item.end)) continue;
static_cast<void>(item.image->PublishIntoMirror(target, item.ranges, item.begin, item.end));
}
}
void GuestBufferMemory::takeHeapReferences() {
releaseHeapReferences();
for (const auto& [begin, end] : mergeWrites(writes)) {
@@ -8023,6 +8213,7 @@ void GuestBufferMemory::AddressStores(std::vector<std::pair<std::uint64_t, std::
void GuestBufferMemory::RecordStagingCopies(Recorder& recorder) {
ResidentBuffer::FlushChanged(context);
publishIntoMirrors();
if (!uploaded || committed) return;
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
std::vector<Region*> copies;
@@ -8050,6 +8241,11 @@ std::uint64_t ImageMirrorSerial(const Context& context, std::uint64_t address, s
return mirror != nullptr && !mirror->writable ? mirror->serial : 0;
}
static std::uint64_t NextHostImportSerial() {
static std::uint64_t serials = 0;
return ++serials;
}
std::uint64_t HostImportSerial(const Context& context, std::uint64_t address, std::size_t bytes, bool reconcile) {
if (context.hostImportAlignment == 0 || bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address) return 0;
auto& state = Imports();
@@ -8064,11 +8260,28 @@ std::uint64_t HostImportSerial(const Context& context, std::uint64_t address, st
if (address < entry.base || address + bytes > entry.base + entry.bytes) return 0;
// Serials are handed out on first use: a fresh import starts at 0, so one made after an earlier
// import of the same range was dropped can never repeat that import's serial.
static std::uint64_t serials = 0;
if (entry.serial == 0) entry.serial = ++serials;
if (entry.serial == 0) entry.serial = NextHostImportSerial();
return entry.serial;
}
bool HostImportView(const Context& context, std::uint64_t address, std::size_t bytes, VkDescriptorBufferInfo& view, std::uint64_t& serial) {
if (context.hostImportAlignment == 0 || bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address) return false;
auto& state = Imports();
std::lock_guard lock(state.mutex);
auto found = state.imports.upper_bound(address);
if (found == state.imports.begin()) return false;
--found;
auto& entry = found->second;
if (entry.buffer == VK_NULL_HANDLE || address < entry.base || address + bytes > entry.base + entry.bytes) return false;
const auto offset = address - (entry.base - entry.lead);
const auto alignment = std::max<VkDeviceSize>(context.limits.minStorageBufferOffsetAlignment, 4);
if (offset % alignment != 0) return false;
if (entry.serial == 0) entry.serial = NextHostImportSerial();
serial = entry.serial;
view = {entry.buffer, static_cast<VkDeviceSize>(offset), static_cast<VkDeviceSize>(bytes)};
return true;
}
bool HostImportsUnchanged(const Context& context, const HostImportsProof& proof) {
if (proof.device == VK_NULL_HANDLE || proof.device != context.device) return false;
auto& state = Imports();
@@ -9,7 +9,11 @@
#include <algorithm>
#include <array>
#include <bit>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <shared_mutex>
#include <stdexcept>
#include <string>
@@ -321,7 +325,7 @@ GuestTextureResource DecodeTextureResource(std::span<const std::uint32_t> descri
case TextureDimension::k1DArray:
Require(height == 1, "guest 1D array texture descriptor has a nonzero height");
Require(baseArray <= depth, "guest 1D array texture descriptor has a base array past its last array slice");
Require(tileMode == TextureTileMode::kLinear || tileMode == TextureTileMode::kZ64KBX || tileMode == TextureTileMode::kR64KBX, "guest 1D array texture descriptor uses a tile mode other than linear, Z or R, which 1D resources cannot use");
Require(gcn || tileMode == TextureTileMode::kLinear || tileMode == TextureTileMode::kZ64KBX || tileMode == TextureTileMode::kR64KBX, "guest 1D array texture descriptor uses a tile mode other than linear, Z or R, which 1D resources cannot use" + describe());
break;
case TextureDimension::kCube:
Require(width == height, "guest cube texture descriptor is not square");
@@ -374,6 +378,60 @@ GuestTextureResource DecodeTextureResource(std::span<const std::uint32_t> descri
return result;
}
namespace {
using RejectionKey = std::array<std::uint32_t, 9>;
struct RememberedRejections {
std::shared_mutex mutex;
std::map<RejectionKey, std::shared_ptr<const std::string>> entries;
};
RememberedRejections& rememberedRejections() {
static RememberedRejections remembered;
return remembered;
}
}
TextureResourceDecode TryDecodeTextureResource(std::span<const std::uint32_t> words) {
TextureResourceDecode decoded;
if (words.size() != 8) {
try {
decoded.resource = DecodeTextureResource(words);
} catch (const std::runtime_error& error) {
decoded.rejection = std::make_shared<const std::string>(error.what());
}
return decoded;
}
RejectionKey key{};
std::copy(words.begin(), words.end(), key.begin());
key[8] = ShaderRecompiler::GcnGuestShaders() ? 1u : 0u;
auto& remembered = rememberedRejections();
{
std::shared_lock lock(remembered.mutex);
if (const auto found = remembered.entries.find(key); found != remembered.entries.end()) {
decoded.rejection = found->second;
return decoded;
}
}
try {
decoded.resource = DecodeTextureResource(words);
} catch (const std::runtime_error& error) {
decoded.rejection = std::make_shared<const std::string>(error.what());
std::unique_lock lock(remembered.mutex);
if (remembered.entries.size() >= RememberedTextureRejections) remembered.entries.clear();
remembered.entries.emplace(key, decoded.rejection);
}
return decoded;
}
std::size_t RememberedTextureRejectionCount() {
auto& remembered = rememberedRejections();
std::shared_lock lock(remembered.mutex);
return remembered.entries.size();
}
std::array<std::uint32_t, 8> EncodeTextureResource(const GuestTextureResource& resource) {
const bool multisampled = resource.dimension == TextureDimension::k2DMsaa;
const bool array = resource.dimension == TextureDimension::k2DArray;
@@ -794,6 +794,12 @@ public:
return {shared_from_this(), texture.get()};
}
FirstSampleCopy& PackedResolve() {
Require(sampleable, "the device cannot sample the multisampled 11_11_10 float color target a CB resolve averages");
if (packedResolve == nullptr) packedResolve = std::make_unique<FirstSampleCopy>(context, target.format, target.extent, true);
return *packedResolve;
}
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");
@@ -948,6 +954,7 @@ private:
std::map<std::array<std::uint32_t, 5>, std::shared_ptr<Texture>> textures;
std::vector<std::shared_ptr<Texture>> retiredTextures;
std::unique_ptr<FirstSampleCopy> firstSampleCopy;
std::unique_ptr<FirstSampleCopy> packedResolve;
std::map<std::array<std::uint32_t, 4>, std::shared_ptr<Texture>> firstSampleTextures;
struct ReinterpretCopy {
Allocation allocation;
@@ -964,6 +971,8 @@ private:
};
mutable std::vector<DccCopy> dccCopies;
mutable DccCopy fmaskCopy;
mutable std::vector<GuestMemory::GpuUseObservation> dccObservations;
mutable GuestMemory::GpuUseObservation fmaskObservation;
std::optional<std::uint32_t> dccFill;
std::optional<std::uint32_t> cmaskFill;
@@ -1071,6 +1080,7 @@ private:
dccRanges.push_back({use.dccAddress, dccBytes, 0});
if (use.cmaskAddress != 0) dccRanges.push_back({use.cmaskAddress, use.cmaskBytes, 0});
dccCopies.assign(dccRanges.size(), {});
dccObservations.resize(dccRanges.size());
std::vector<GuestMemory::UnchangedQuery> watched;
for (std::size_t index = 0; index < dccRanges.size(); ++index) {
auto& range = dccRanges[index];
@@ -1145,7 +1155,7 @@ private:
if (compared(index)) {
requireDccRange(copyCurrent(range, dccCopies[index]), range, "writes to a resident multisampled DCC target or its metadata are not implemented");
} else {
GuestMemory::CollectWritesUncached(range.address, range.bytes);
GuestMemory::CollectWritesForGpuUse(range, dccObservations[index]);
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");
@@ -1157,7 +1167,7 @@ private:
if (fmaskCopy.compared) {
requireDccRange(copyCurrent(range, fmaskCopy), range, "writes to a resident native FMASK are not implemented");
} else {
GuestMemory::CollectWritesUncached(range.address, range.bytes);
GuestMemory::CollectWritesForGpuUse(range, fmaskObservation);
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");
@@ -1170,6 +1180,7 @@ private:
retiredTextures.clear();
firstSampleTextures.clear();
firstSampleCopy.reset();
packedResolve.reset();
for (auto& [format, copy] : reinterpretCopies) {
copy.textures.clear();
destroy(copy.allocation);
@@ -1973,19 +1984,25 @@ void ResolveMultisampleTarget(const Context& context, const ColorTarget& source,
auto& target = acquire(context, source);
target.Keep();
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);
auto* averaging = source.packing == ShaderRecompiler::ColorExportPacking::Float11_11_10 ? &target.PackedResolve() : nullptr;
auto framebuffer = averaging != nullptr ? nullptr : std::make_shared<Framebuffer>(context, target.ResolvePass(source.format), views, source.extent);
std::shared_ptr<void> averaged;
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(source.format);
begin.framebuffer = framebuffer->Handle();
begin.renderArea = {{0, 0}, source.extent};
context.Resolved(&DeviceFunctions::cmdBeginRenderPass, "vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
context.Resolved(&DeviceFunctions::cmdEndRenderPass, "vkCmdEndRenderPass")(commands);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_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 | VK_ACCESS_SHADER_READ_BIT);
if (averaging != nullptr) {
averaged = averaging->RecordInto(commands, recorder, views[0], VK_IMAGE_LAYOUT_GENERAL, destinationView);
} else {
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
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);
context.Resolved(&DeviceFunctions::cmdEndRenderPass, "vkCmdEndRenderPass")(commands);
}
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT);
if (recorder != nullptr) {
Recorder::CountBarriers(Recorder::CommandClass::Draw, 2);
recorder->Keep(framebuffer);
if (framebuffer != nullptr) recorder->Keep(framebuffer);
}
});
destination.MarkDirty();
@@ -2203,8 +2220,8 @@ std::optional<std::vector<ShaderRecompiler::BdaAbi::Range>> ExcludeMultisampleTa
return changed ? std::optional(std::move(filtered)) : std::nullopt;
}
void RequireNoMultisampleTarget(std::uint64_t address, std::size_t bytes, const char* access) {
RequireNoResidentDepthRead_nid_no_patch(address, bytes);
void RequireNoMultisampleTarget(std::uint64_t address, std::size_t bytes, const char* access, DepthReadCause cause) {
RequireNoResidentDepthRead_nid_no_patch(address, bytes, std::nullopt, true, cause);
RequireNoMultisampleColorTarget(address, bytes, access);
}
@@ -381,8 +381,8 @@ ColorWriteMasks channelWriteMasks(const State& state, std::span<const VkPipeline
return masks;
}
VkPipelineColorBlendAttachmentState keyedBlend(const Context& context, VkPipelineColorBlendAttachmentState blend) {
if (context.dynamicColorWriteMask) blend.colorWriteMask = 0;
VkPipelineColorBlendAttachmentState keyedBlend(bool dynamicColorWriteMask, VkPipelineColorBlendAttachmentState blend) {
if (dynamicColorWriteMask) blend.colorWriteMask = 0;
return blend;
}
@@ -468,7 +468,7 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State&
}
}
}
for (const auto& blend : state.blends) appendKey(keys.fragmentOutput, keyedBlend(context, blend));
for (const auto& blend : state.blends) appendKey(keys.fragmentOutput, keyedBlend(context.dynamicColorWriteMask, blend));
appendKey(keys.fragmentOutput, state.colorRop);
for (const auto value : state.blendConstants) appendKey(keys.fragmentOutput, value);
appendKey(keys.renderPass, state.blends.size());
@@ -516,7 +516,7 @@ bool libraryKeys(PipelineLibraryKeys& keys, const Context& context, const State&
Pipeline::Pipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const ShaderResources& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout) : Pipeline(context, state, vertexInput, resources.SetLayouts(), shaders, attachmentLayout) {}
Pipeline::Pipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout) : context(context), _modules(shaders.size()), attachments(state.colors.size() + (state.depth ? 1u : 0u)), colorAttachments(state.colors.size()), depthBounds(state.depth.has_value() && state.depthBoundsTest), depthBias(state.depth.has_value() && state.depthBias), dynamicRendering(context.graphicsPipelineLibrary) {
Pipeline::Pipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout) : context(context), _modules(shaders.size()), attachments(state.colors.size() + (state.depth ? 1u : 0u)), colorAttachments(state.colors.size()), depthBounds(state.depth.has_value() && state.depthBoundsTest), depthBias(state.depth.has_value() && state.depthBias), dynamicColorWriteMask(context.dynamicColorWriteMask && !FragmentInterlock(shaders)), dynamicRendering(context.graphicsPipelineLibrary) {
PerformanceTimer timing("Vulkan.GraphicsPipeline");
for (const auto& color : state.colors) boundAttachments.push_back(color.partialWriteMask == 0u);
if (state.depth) boundAttachments.push_back(true);
@@ -696,7 +696,7 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput
if (depthBounds) dynamicStates.push_back(VK_DYNAMIC_STATE_DEPTH_BOUNDS);
if (depthBias) dynamicStates.push_back(VK_DYNAMIC_STATE_DEPTH_BIAS);
if (libraries) dynamicStates.assign(PipelineLibraryDynamicStates().begin(), PipelineLibraryDynamicStates().end());
if (context.dynamicColorWriteMask) dynamicStates.push_back(VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT);
if (dynamicColorWriteMask) dynamicStates.push_back(VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT);
dynamicSlots = CommandState::DynamicSlots(dynamicStates);
VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
dynamic.dynamicStateCount = static_cast<std::uint32_t>(dynamicStates.size());
@@ -771,8 +771,8 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput
const auto firstMasks = channelWriteMasks(state, state.blends, false);
const auto secondMasks = channelWriteMasks(state, state.blends, true);
for (std::size_t index = 0; index < firstChannels.size(); ++index) {
firstChannels[index].colorWriteMask = context.dynamicColorWriteMask ? 0u : firstMasks[index];
secondChannels[index].colorWriteMask = context.dynamicColorWriteMask ? 0u : secondMasks[index];
firstChannels[index].colorWriteMask = dynamicColorWriteMask ? 0u : firstMasks[index];
secondChannels[index].colorWriteMask = dynamicColorWriteMask ? 0u : secondMasks[index];
}
if (const auto logicOp = LogicOpFromRop(state.colorRop); logicOp != VK_LOGIC_OP_COPY) {
blend.logicOpEnable = VK_TRUE;
@@ -1062,7 +1062,7 @@ void Pipeline::ContinueSecondChannel(CommandState& recording, const State& state
}
void Pipeline::setColorWriteMasks(CommandState& recording, const State& state, const State* masked, bool secondChannel) const {
if (!context.dynamicColorWriteMask || state.blends.empty()) return;
if (!dynamicColorWriteMask || state.blends.empty()) return;
const auto masks = channelWriteMasks(state, masked != nullptr ? std::span(masked->blends) : std::span(state.blends), secondChannel);
recording.SetColorWriteMasks(context, std::span(masks).first(state.blends.size()));
}
@@ -1177,7 +1177,8 @@ std::size_t pipelineKey(std::vector<std::byte>& storage, const Context& context,
append(key, state.depthClamp && context.depthClamp);
append(key, state.conservativeRasterization);
append(key, state.blends.size());
for (const auto& blend : state.blends) append(key, keyedBlend(context, blend));
const bool dynamicColorWriteMask = context.dynamicColorWriteMask && !FragmentInterlock(shaders);
for (const auto& blend : state.blends) append(key, keyedBlend(dynamicColorWriteMask, blend));
key.Put(state.colorRop);
key.PutBytes(state.blendConstants.data(), sizeof(state.blendConstants));
append(key, state.samples);
@@ -40,6 +40,7 @@
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -202,7 +203,7 @@ std::vector<std::uint64_t> liveRecorders;
std::atomic<std::uint64_t> nextRecorderId{1};
std::atomic<std::uint64_t> samplesPassed{0};
constexpr std::uint32_t SampleFoldCapacity = 64;
constexpr std::uint32_t SampleCounterPushBytes = 24;
constexpr std::uint32_t SampleCounterPushBytes = 28;
constexpr std::uint32_t SegmentSlots = 128;
constexpr std::uint32_t SegmentFoldCapacity = 1024;
constexpr std::uint32_t DumpFoldCapacity = 1024;
@@ -1091,7 +1092,7 @@ void FlushForAccess(std::uint64_t address, std::size_t bytes) {
record();
}
}
if (HookClearAccess() && HookSnapshotEnabled() && !HookFlushCpuBlocks() && ClearAccess(address, bytes)) {
if (HookClearAccess() && HookSnapshotEnabled() && !HookFlushCpuBlocks() && ClearAccess(address, bytes) && !(GuestMemory::CurrentReadSite() == GuestMemory::ReadSite::HostWrite && AnyPublishInProgress())) {
ClearAccesses::Set(ClearAccesses::Get() + 1);
return;
}
@@ -1121,8 +1122,9 @@ void FlushForAccess(std::uint64_t address, std::size_t bytes) {
// publish is all FlushPending would do (one registry scan, not two).
bool stored = false;
std::size_t images = 0, evicted = 0;
const bool kept = !HookFlushCpuBlocks() && StorageTexture::AccessKeptByCpu(address, bytes, &images, &evicted);
if (kept || (images == 0 && !HookFlushCpuBlocks())) {
const bool deferred = StorageTexture::DeferToMirror(address, bytes);
const bool kept = !deferred && !HookFlushCpuBlocks() && StorageTexture::AccessKeptByCpu(address, bytes, &images, &evicted);
if (deferred || kept || (images == 0 && !HookFlushCpuBlocks())) {
stored = StorageTexture::WaitForFlushing(address, bytes);
published = StorageTexture::PublishShadowsOnly(address, bytes, scope, "memory access", waited);
if (kept && HookSyncProfiled()) CountRecordedStoreSkip(RecordedStoreKey(), evicted);
@@ -1419,6 +1421,11 @@ Recorder::Recorder(const Context& context, bool timelineSemaphores) : context(co
if (result != VK_SUCCESS) {
std::fprintf(stderr, "[gpu] timeline semaphore creation failed (Vulkan result %d); drains wait under the GPU mutex\n", static_cast<int>(result));
timeline = VK_NULL_HANDLE;
return;
}
fenceless = std::getenv("APS5_BATCH_FENCES") == nullptr;
if (ProcTable() && context.deviceProc != nullptr) {
getSemaphoreCounterValue = context.Function<PFN_vkGetSemaphoreCounterValueKHR>("vkGetSemaphoreCounterValueKHR");
}
}
@@ -2220,12 +2227,14 @@ void Recorder::ensureOpen() {
allocation.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocation.commandBufferCount = 1;
Check(context.Function<PFN_vkAllocateCommandBuffers>("vkAllocateCommandBuffers")(context.device, &allocation, &batch->commands), "vkAllocateCommandBuffers recorder");
if (!spare.empty()) {
batch->fence = spare.back();
spare.pop_back();
} else {
VkFenceCreateInfo info{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
Check(context.Function<PFN_vkCreateFence>("vkCreateFence")(context.device, &info, nullptr, &batch->fence), "vkCreateFence recorder");
if (!fenceless) {
if (!spare.empty()) {
batch->fence = spare.back();
spare.pop_back();
} else {
VkFenceCreateInfo info{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
Check(context.Function<PFN_vkCreateFence>("vkCreateFence")(context.device, &info, nullptr, &batch->fence), "vkCreateFence recorder");
}
}
VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
@@ -2484,9 +2493,9 @@ namespace {
constexpr std::uint32_t MaxTimedRanges = 512;
constexpr std::size_t CommandClasses = static_cast<std::size_t>(Recorder::CommandClass::Count);
constexpr const char* CommandClassNames[CommandClasses] = {"dispatch-lead", "dispatch-trail", "indirect-args", "label-run", "fill", "fill-clear", "copy", "staging-in", "staging-out", "draw", "storage-upload", "storage-writeback", "dcc-clear", "dcc-keys", "present-blit", "shadow-publish", "template-refresh", "input-mirror"};
constexpr const char* BarrierScopes[CommandClasses] = {"Graphics.Barrier.dispatch-lead", "Graphics.Barrier.dispatch-trail", "Graphics.Barrier.indirect-args", "Graphics.Barrier.label-run", "Graphics.Barrier.fill", "Graphics.Barrier.fill-clear", "Graphics.Barrier.copy", "Graphics.Barrier.staging-in", "Graphics.Barrier.staging-out", "Graphics.Barrier.draw", "Graphics.Barrier.storage-upload", "Graphics.Barrier.storage-writeback", "Graphics.Barrier.dcc-clear", "Graphics.Barrier.dcc-keys", "Graphics.Barrier.present-blit", "Graphics.Barrier.shadow-publish", "Graphics.Barrier.template-refresh", "Graphics.Barrier.input-mirror"};
constexpr const char* BarrierMergedScopes[CommandClasses] = {"Graphics.BarrierMerged.dispatch-lead", "Graphics.BarrierMerged.dispatch-trail", "Graphics.BarrierMerged.indirect-args", "Graphics.BarrierMerged.label-run", "Graphics.BarrierMerged.fill", "Graphics.BarrierMerged.fill-clear", "Graphics.BarrierMerged.copy", "Graphics.BarrierMerged.staging-in", "Graphics.BarrierMerged.staging-out", "Graphics.BarrierMerged.draw", "Graphics.BarrierMerged.storage-upload", "Graphics.BarrierMerged.storage-writeback", "Graphics.BarrierMerged.dcc-clear", "Graphics.BarrierMerged.dcc-keys", "Graphics.BarrierMerged.present-blit", "Graphics.BarrierMerged.shadow-publish", "Graphics.BarrierMerged.template-refresh", "Graphics.BarrierMerged.input-mirror"};
constexpr const char* CommandClassNames[CommandClasses] = {"dispatch-lead", "dispatch-trail", "indirect-args", "label-run", "fill", "fill-clear", "copy", "staging-in", "staging-out", "draw", "storage-upload", "storage-writeback", "dcc-clear", "dcc-keys", "present-blit", "shadow-publish", "template-refresh", "input-mirror", "mirror-publish"};
constexpr const char* BarrierScopes[CommandClasses] = {"Graphics.Barrier.dispatch-lead", "Graphics.Barrier.dispatch-trail", "Graphics.Barrier.indirect-args", "Graphics.Barrier.label-run", "Graphics.Barrier.fill", "Graphics.Barrier.fill-clear", "Graphics.Barrier.copy", "Graphics.Barrier.staging-in", "Graphics.Barrier.staging-out", "Graphics.Barrier.draw", "Graphics.Barrier.storage-upload", "Graphics.Barrier.storage-writeback", "Graphics.Barrier.dcc-clear", "Graphics.Barrier.dcc-keys", "Graphics.Barrier.present-blit", "Graphics.Barrier.shadow-publish", "Graphics.Barrier.template-refresh", "Graphics.Barrier.input-mirror", "Graphics.Barrier.mirror-publish"};
constexpr const char* BarrierMergedScopes[CommandClasses] = {"Graphics.BarrierMerged.dispatch-lead", "Graphics.BarrierMerged.dispatch-trail", "Graphics.BarrierMerged.indirect-args", "Graphics.BarrierMerged.label-run", "Graphics.BarrierMerged.fill", "Graphics.BarrierMerged.fill-clear", "Graphics.BarrierMerged.copy", "Graphics.BarrierMerged.staging-in", "Graphics.BarrierMerged.staging-out", "Graphics.BarrierMerged.draw", "Graphics.BarrierMerged.storage-upload", "Graphics.BarrierMerged.storage-writeback", "Graphics.BarrierMerged.dcc-clear", "Graphics.BarrierMerged.dcc-keys", "Graphics.BarrierMerged.present-blit", "Graphics.BarrierMerged.shadow-publish", "Graphics.BarrierMerged.template-refresh", "Graphics.BarrierMerged.input-mirror", "Graphics.BarrierMerged.mirror-publish"};
// [barriers] counters by class (relaxed: only reported) and the [gputime] totals, which the
// presenter's thread adds to without the GPU mutex (AddGpuTiming).
std::atomic<std::uint64_t> classBarriers[CommandClasses]{};
@@ -3078,7 +3087,7 @@ void Recorder::recordQueuedDumps(VkCommandBuffer commands, std::span<const Batch
for (const auto& write : writes) {
if (write.dumpTarget == 0) continue;
segments = write.dumpSegments;
list.insert(list.end(), {static_cast<std::uint32_t>(write.dumpTarget), static_cast<std::uint32_t>(write.dumpTarget >> 32u), write.dumpSegments, 0u});
list.insert(list.end(), {static_cast<std::uint32_t>(write.dumpTarget), static_cast<std::uint32_t>(write.dumpTarget >> 32u), write.dumpSegments, write.dumpBlocks});
}
Require(list.size() <= 4u * DumpFoldCapacity, "queued occlusion dumps exceed the fold capacity");
copySegments(commands, segments);
@@ -3145,7 +3154,7 @@ void Recorder::endSamples(Batch& batch) {
batch.samplesDrawn = false;
}
void Recorder::foldSamples(Batch& batch, VkDeviceAddress target) {
void Recorder::foldSamples(Batch& batch, VkDeviceAddress target, std::uint32_t blocks) {
const auto commands = batch.commands;
const auto copy = function(cmdCopyQueryPoolResults, "vkCmdCopyQueryPoolResults");
const auto push = function(cmdPushConstants, "vkCmdPushConstants");
@@ -3169,8 +3178,9 @@ void Recorder::foldSamples(Batch& batch, VkDeviceAddress target) {
VkDeviceAddress target;
std::uint32_t count;
std::uint32_t store;
} parameters{sampleCounter->DeviceAddress(), target, count, last && target != 0 ? 1u : 0u};
static_assert(sizeof(parameters) == SampleCounterPushBytes);
std::uint32_t blocks;
} parameters{sampleCounter->DeviceAddress(), target, count, last && target != 0 ? 1u : 0u, blocks};
static_assert(offsetof(decltype(parameters), blocks) + sizeof(parameters.blocks) == SampleCounterPushBytes);
push(commands, sampleLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes, &parameters);
dispatch(commands, 1, 1, 1);
if (parameters.store == 1u) {
@@ -3189,7 +3199,7 @@ void Recorder::foldSamples(Batch& batch, VkDeviceAddress target) {
pendingSamples.clear();
}
bool Recorder::DumpSamples(VkDeviceAddress target, std::uint64_t address) {
bool Recorder::DumpSamples(VkDeviceAddress target, std::uint64_t address, std::uint32_t blocks) {
GuestMemory::AssertGpuLockHeld("Recorder::DumpSamples");
if (target == 0 || !gpuSampleCounter()) return false;
countingSamples = true;
@@ -3204,19 +3214,20 @@ bool Recorder::DumpSamples(VkDeviceAddress target, std::uint64_t address) {
queued.address = address;
queued.dumpTarget = target;
queued.dumpSegments = static_cast<std::uint32_t>(pendingSamples.size());
queued.dumpBlocks = blocks;
++open->queuedDumps;
dumpsQueued.fetch_add(1, std::memory_order_relaxed);
return true;
}
FlushStores();
Commands();
foldSamples(*open, target);
foldSamples(*open, target, blocks);
dumpsAtOnce.fetch_add(1, std::memory_order_relaxed);
return true;
}
Commands();
endSamples(*open);
foldSamples(*open, target);
foldSamples(*open, target, blocks);
if (open->samplePool != nullptr) open->kept.push_back(std::move(open->samplePool));
open->samplePool.reset();
open->samples = VK_NULL_HANDLE;
@@ -4205,7 +4216,18 @@ std::uint64_t Recorder::PendingLeaseSerial(std::uint64_t address, std::size_t by
}
bool Recorder::signaled(const Batch& batch) const {
return batch.submitted && fenceStatus(batch.fence) == VK_SUCCESS;
return batch.submitted && gpuDone(batch);
}
std::uint64_t Recorder::readTimeline() const {
std::uint64_t value = 0;
if (function(getSemaphoreCounterValue, "vkGetSemaphoreCounterValueKHR")(context.device, timeline, &value) == VK_SUCCESS && value > reachedSerial) reachedSerial = value;
return reachedSerial;
}
bool Recorder::gpuDone(const Batch& batch) const {
if (!fenceless) return fenceStatus(batch.fence) == VK_SUCCESS;
return batch.serial != 0 && (batch.serial <= reachedSerial || batch.serial <= readTimeline());
}
bool Recorder::PendingWriteSettled(std::uint64_t address, std::size_t bytes) const {
@@ -4423,7 +4445,7 @@ std::optional<Recorder::PendingWriteInfo> Recorder::DescribePendingWrite(std::ui
const auto* range = firstOverlap(**it);
if (range == nullptr) continue;
// In flight means submitted, so the fence is live; signaled = the GPU already ran it.
const bool signaled = fenceStatus((*it)->fence) == VK_SUCCESS;
const bool signaled = gpuDone(**it);
if (syncAll) return PendingWriteInfo{submissions + (open != nullptr ? 1 : 0), open != nullptr, signaled, range->first, range->second, allBatches};
return PendingWriteInfo{(*it)->serial, false, signaled, range->first, range->second, finished};
}
@@ -4568,7 +4590,7 @@ std::optional<Recorder::LabelHit> Recorder::lookupLabel(std::uint64_t address, s
bool Recorder::unsignaled(std::uint64_t serial) const {
for (const auto& batch : inFlight) {
if (batch->serial == serial) return fenceStatus(batch->fence) != VK_SUCCESS;
if (batch->serial == serial) return !gpuDone(*batch);
}
return false;
}
@@ -5083,12 +5105,11 @@ bool Recorder::syncThroughUnlocked(std::uint64_t address, std::uint64_t end, int
std::chrono::steady_clock::time_point targetSubmittedAt{};
std::map<std::uint32_t, std::uint64_t> aheadByQueue;
if (profile || trace) {
const auto status = context.Function<PFN_vkGetFenceStatus>("vkGetFenceStatus");
for (const auto& batch : inFlight) {
if (batch->serial > targetSerial) break;
++batchesToTarget;
++aheadByQueue[batch->queue];
if (status(context.device, batch->fence) != VK_SUCCESS) ++unsignaledAtStart;
if (!gpuDone(*batch)) ++unsignaledAtStart;
if (batch->serial != targetSerial) continue;
targetSubmittedAt = batch->submittedAt;
targetRanges = batch->writes.size();
@@ -5174,8 +5195,9 @@ bool Recorder::Reap() {
const bool profile = DrawProfiled();
const auto start = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
std::uint64_t retired = 0;
if (fenceless && !inFlight.empty() && inFlight.back()->serial > reachedSerial) readTimeline();
while (!inFlight.empty()) {
if (fenceStatus(inFlight.front()->fence) != VK_SUCCESS) break;
if (fenceless ? inFlight.front()->serial > reachedSerial : fenceStatus(inFlight.front()->fence) != VK_SUCCESS) break;
auto batch = std::move(inFlight.front());
inFlight.pop_front();
finish(std::move(batch), false, 4);
@@ -5226,7 +5248,7 @@ void Recorder::finish(std::unique_ptr<Batch> batch, bool wait, int source, bool
const auto waitStart = std::chrono::steady_clock::now();
// A fence still unsignaled here makes this a real GPU wait under the mutex (finish runs
// under it): the [lock] line's 'locked GPU waits'.
const bool signaledAtStart = !profile || context.Function<PFN_vkGetFenceStatus>("vkGetFenceStatus")(context.device, batch->fence) == VK_SUCCESS;
const bool signaledAtStart = !profile || gpuDone(*batch);
struct Report {
bool enabled;
int source;
@@ -5254,8 +5276,14 @@ void Recorder::finish(std::unique_ptr<Batch> batch, bool wait, int source, bool
}
}
} report{profile, source, waitStart, *this, signaledAtStart};
const auto waitTimeline = [&] {
VkResult reached = VK_SUCCESS;
if (batch->serial > reachedSerial && batch->serial > readTimeline()) reached = WaitTimeline(context.device, timeline, context.Function<PFN_vkWaitSemaphoresKHR>("vkWaitSemaphoresKHR"), batch->serial);
if (reached == VK_SUCCESS) reachedSerial = std::max(reachedSerial, batch->serial);
return reached;
};
const auto waitFences = function(waitForFences, "vkWaitForFences");
auto result = waitFences(context.device, 1, &batch->fence, VK_TRUE, 5'000'000'000ull);
auto result = fenceless ? waitTimeline() : waitFences(context.device, 1, &batch->fence, VK_TRUE, 5'000'000'000ull);
for (int waited = 5; result == VK_TIMEOUT; waited += 5) {
// A batch still running after 5 s is reported (every 5 s) so a GPU-side hang is visible.
std::fprintf(stderr, "[gpu] recorded batch still running on the GPU after %d s\n", waited);
@@ -5267,7 +5295,7 @@ void Recorder::finish(std::unique_ptr<Batch> batch, bool wait, int source, bool
}
if (result != VK_SUCCESS) {
release(*batch);
Check(result, "vkWaitForFences recorder");
Check(result, fenceless ? "vkWaitSemaphoresKHR recorder" : "vkWaitForFences recorder");
}
}
readGpuTiming(*batch);
@@ -391,6 +391,7 @@ ResidentBuffer::ResidentBuffer(const Context& context, std::uint64_t base, std::
type = context.DeviceMemoryType(requirements.memoryTypeBits, SlabBytes, "a resident heap mirror slab");
memory = residentMemory(context, type);
slots.resize(static_cast<std::size_t>(size / BlockSize));
uploads.assign(slots.size(), 0);
std::vector<bool> wanted(slots.size(), false);
for (const auto& [first, last] : backed) {
if (first >= last) continue;
@@ -517,6 +518,13 @@ void ResidentBuffer::Read(std::uint64_t guest, std::span<std::byte> out) const {
}
}
std::uint64_t ResidentBuffer::UploadSerial(std::uint64_t begin, std::uint64_t end) const {
std::uint64_t serial = 0;
if (begin >= end) return serial;
for (auto index = blockIndex(begin); index <= blockIndex(end - 1); ++index) serial = std::max(serial, uploads[index]);
return serial;
}
void ResidentBuffer::Store(std::uint64_t guest, std::span<const std::byte> bytes) {
std::size_t done = 0;
while (done < bytes.size()) {
@@ -568,6 +576,7 @@ void ResidentBuffer::flush() {
for (auto at = std::max(first, cursor); at < last;) {
const auto next = std::min(last, (at / BlockSize + 1) * BlockSize);
if (slots[blockIndex(at)].host != nullptr) {
uploads[blockIndex(at)] = ++uploadCounter;
if (!regions.empty() && regions.back().dstOffset + regions.back().size == at - origin) regions.back().size += next - at;
else regions.push_back({total, at - origin, next - at});
total += next - at;
@@ -29,8 +29,10 @@ constexpr std::array<const char*, SwitchCount> SwitchNames{
"APS5_NO_SHARED_COLLECT_WALKS",
"APS5_NO_EXTENDED_FAST_PROOFS",
"APS5_DRAW_TABLE_SNAPSHOT",
"APS5_NO_ALIAS_VIEWS",
"APS5_NO_TARGET_MEMO",
"APS5_NO_TARGET_MEMO_OVERLAP_CACHE",
"APS5_INDEX_IN_PLACE_BEHIND_WRITER",
};
struct SwitchValues {
@@ -49,8 +51,10 @@ struct SwitchValues {
std::getenv("APS5_NO_SHARED_COLLECT_WALKS") != nullptr,
std::getenv("APS5_NO_EXTENDED_FAST_PROOFS") != nullptr,
std::getenv("APS5_DRAW_TABLE_SNAPSHOT") != nullptr,
std::getenv("APS5_NO_ALIAS_VIEWS") != nullptr,
std::getenv("APS5_NO_TARGET_MEMO") != nullptr,
std::getenv("APS5_NO_TARGET_MEMO_OVERLAP_CACHE") != nullptr,
std::getenv("APS5_INDEX_IN_PLACE_BEHIND_WRITER") != nullptr,
};
for (std::size_t index = 0; index < SwitchCount; ++index) set[index].store(environment[index], std::memory_order_relaxed);
}
@@ -535,6 +535,8 @@ struct TextureCounters {
// by a byte compare.
std::atomic<std::uint64_t> untrackedKept{0};
std::atomic<std::uint64_t> untrackedCompared{0};
std::atomic<std::uint64_t> aliasViews{0};
std::atomic<std::uint64_t> aliasRefreshes{0};
std::atomic<std::int64_t> lastReport{0};
};
@@ -558,7 +560,7 @@ void reportTextureCounters() {
auto last = counters.lastReport.load();
if (nowMs - last < 10000 || !counters.lastReport.compare_exchange_strong(last, nowMs)) return;
const auto count = [](const std::atomic<std::uint64_t>& value) { return static_cast<unsigned long long>(value.load(std::memory_order_relaxed)); };
AgcDriver::ProfilePrint_nid_no_patch("[textures] sampled created: %llu from storage images, %llu cleared on the GPU, %llu uploaded on the GPU from host imports, %llu snapshots (%llu snapshot reads over recorded writes inside cachedTexture, %llu storage-path fallbacks); stage-A records %llu: %llu fast hits, %llu full lookups; storage images %llu hits, %llu created, %llu own-object refreshes; image tables %llu reused, %llu resolved; dynamic-resolution variants: %llu surfaces, %llu entries substituted, %llu entries rejected; %llu one-layer 2D array entries bound to the 2D texture of their surface; untracked snapshots %llu kept by the write-watch hint, %llu compared\n", count(counters.fromStorage), count(counters.cleared), count(counters.imported), count(counters.snapshots), count(counters.pendingReads), count(counters.storageFallbacks), count(counters.records), count(counters.fastHits), count(counters.fastMisses), count(counters.storageHits), count(counters.storageCreated), count(counters.ownRefreshes), count(counters.tablesReused), count(counters.tablesResolved), count(counters.variantSurfaces), count(counters.variantSubstituted), count(counters.variantRejected), count(counters.arrayViewsShared), count(counters.untrackedKept), count(counters.untrackedCompared));
AgcDriver::ProfilePrint_nid_no_patch("[textures] sampled created: %llu from storage images, %llu cleared on the GPU, %llu uploaded on the GPU from host imports, %llu snapshots (%llu snapshot reads over recorded writes inside cachedTexture, %llu storage-path fallbacks); stage-A records %llu: %llu fast hits, %llu full lookups; storage images %llu hits, %llu created, %llu own-object refreshes; image tables %llu reused, %llu resolved; dynamic-resolution variants: %llu surfaces, %llu entries substituted, %llu entries rejected; %llu one-layer 2D array entries bound to the 2D texture of their surface; untracked snapshots %llu kept by the write-watch hint, %llu compared; views kept through a pending alias: %llu lookups, %llu revalidations\n", count(counters.fromStorage), count(counters.cleared), count(counters.imported), count(counters.snapshots), count(counters.pendingReads), count(counters.storageFallbacks), count(counters.records), count(counters.fastHits), count(counters.fastMisses), count(counters.storageHits), count(counters.storageCreated), count(counters.ownRefreshes), count(counters.tablesReused), count(counters.tablesResolved), count(counters.variantSurfaces), count(counters.variantSubstituted), count(counters.variantRejected), count(counters.arrayViewsShared), count(counters.untrackedKept), count(counters.untrackedCompared), count(counters.aliasViews), count(counters.aliasRefreshes));
}
// What the sampled-texture lookups on this thread proved their returned objects current against,
@@ -1228,8 +1230,10 @@ std::shared_ptr<Texture> cachedTexture(const Context& context, std::span<const s
// The view follows the storage image, whatever the GPU wrote to it since; guest memory
// written meanwhile is taken in by refreshing the image. A fast clear the image cannot
// see (keys, and no pending results to prefer) ends the view: a snapshot holds the clear.
if (!stagedFlushed && (source == nullptr || source == it->source) && (source != nullptr || *keys == DccKeys::Uncompressed) && StorageImageServesKeys(*it->source, resource.dccAddress)) {
if (!GuestMemory::UnchangedSince(address, bytes, it->source->GenerationFor(address, bytes))) refreshForView(*it->source, resource);
const bool aliasServed = !stagedFlushed && source != nullptr && source != it->source && *keys == DccKeys::Uncompressed && !RuntimeSwitches::Set(RuntimeSwitch::NoAliasViews) && it->source->IsPendingAlias(*source);
if (!stagedFlushed && (source == nullptr || source == it->source || aliasServed) && (source != nullptr || *keys == DccKeys::Uncompressed) && StorageImageServesKeys(*it->source, resource.dccAddress)) {
if (aliasServed || !GuestMemory::UnchangedSince(address, bytes, it->source->GenerationFor(address, bytes))) refreshForView(*it->source, resource);
if (aliasServed) counters.aliasViews.fetch_add(1, std::memory_order_relaxed);
if (it->texture->IsDepthCopy()) it->texture->RefreshDepthCopy();
it->keys = *keys;
touchTexture(cache, it);
@@ -1282,8 +1286,8 @@ std::shared_ptr<Texture> cachedTexture(const Context& context, std::span<const s
const auto clear = source == nullptr ? SampledClearColor(context, resource, *keys, depthCompare) : std::nullopt;
static const bool sampledImport = std::getenv("APS5_NO_SAMPLED_IMPORT") == nullptr;
const bool gpuWritten = sampledImport && source == nullptr && !clear && !depthCompare && !layerRows && !slabs.has_value() && *keys == DccKeys::Uncompressed && Recorder::SnapshotWriteOverlaps(address, bytes);
const HostImport* gpuSource = gpuWritten ? ExistingHostImportFor(context, address, bytes) : nullptr;
if (source != nullptr || clear.has_value() || gpuSource != nullptr) parkSnapshot(cache, recycled);
const auto gpuSources = gpuWritten ? ExistingHostImportCopies(context, address, bytes) : std::vector<HostImportCopy>{};
if (source != nullptr || clear.has_value() || !gpuSources.empty()) parkSnapshot(cache, recycled);
CachedTexture entry{key, address, std::vector<std::byte>{}, nullptr, *keys, snapshotGeneration};
entry.committed = std::move(committed);
entry.surfaceBytes = bytes;
@@ -1316,8 +1320,8 @@ std::shared_ptr<Texture> cachedTexture(const Context& context, std::span<const s
entry.texture = createTexture(*context.detiler, resource, components, std::span<const std::byte>{}, false, layerRows, &*clear);
entry.accounted = entry.texture->AllocationBytes();
counters.cleared.fetch_add(1, std::memory_order_relaxed);
} else if (gpuSource != nullptr) {
entry.texture = createTexture(*context.detiler, resource, components, std::span<const std::byte>{}, false, false, nullptr, std::nullopt, gpuSource);
} else if (!gpuSources.empty()) {
entry.texture = createTexture(*context.detiler, resource, components, std::span<const std::byte>{}, false, false, nullptr, std::nullopt, std::span<const HostImportCopy>(gpuSources));
entry.accounted = entry.texture->AllocationBytes();
counters.imported.fetch_add(1, std::memory_order_relaxed);
} else {
@@ -1537,7 +1541,7 @@ std::shared_ptr<StorageTexture> cachedStorageTexture(const Context& context, std
if (viewed.baseAddress != requested.baseAddress) guestBytes = 0;
Require(viewed.dimension != TextureDimension::k2DMsaa, "storage image access to a multisampled texture is not implemented");
const auto viewedBytes = guestBytes != 0 ? guestBytes : SurfaceGuestBytes(viewed);
RequireNoMultisampleTarget(viewed.baseAddress, static_cast<std::size_t>(viewedBytes), "a storage image access");
RequireNoMultisampleTarget(viewed.baseAddress, static_cast<std::size_t>(viewedBytes), "a storage image access", DepthReadCause::Reuse);
if (auto depth = DepthSurfaceStorage(context, words, viewed, mip)) return depth;
if (viewedBytes >= (1ull << 30u)) {
static std::atomic<std::uint64_t> large{0};
@@ -1944,7 +1948,7 @@ std::shared_ptr<StorageTexture> RepeatStorageSurface(const Context& context, con
const auto viewed = ArrayLayerWindow(requested, context.limits.maxImageArrayLayers);
Require(viewed.dimension != TextureDimension::k2DMsaa, "storage image access to a multisampled texture is not implemented");
const auto viewedBytes = SurfaceGuestBytes(viewed);
RequireNoMultisampleTarget(viewed.baseAddress, static_cast<std::size_t>(viewedBytes), "a storage image access");
RequireNoMultisampleTarget(viewed.baseAddress, static_cast<std::size_t>(viewedBytes), "a storage image access", DepthReadCause::Reuse);
if (DepthSurfaceStorage(context, {}, viewed, 0) != nullptr) return nullptr;
if (DepthPlanesStale()) static_cast<void>(FlushDepthPlanes(viewed.baseAddress, static_cast<std::size_t>(viewedBytes), DepthPlaneScope::Overlapped));
if (auto* recorder = Recorder::Active(); recorder != nullptr) recorder->BoundKeptBytes();
@@ -3933,7 +3937,7 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::span<const
const auto viewed = pendingLookupSource(context, surface.resource, surface.bytes, entry.depthCompare).source;
return viewed.get() == pending[k].except || (viewed == nullptr && entry.sourceEligible && entry.sourceRefreshed);
};
if (const auto entry = refreshedOwner(owners[k]); entry != refreshed.end() && (entry->storage || pending[k].found == pending[k].except || (pending[k].found == nullptr && entry->sourceEligible) || lookupAccepts(*entry))) {
if (const auto entry = refreshedOwner(owners[k]); entry != refreshed.end() && (entry->storage || pending[k].found == pending[k].except || (pending[k].found == nullptr && entry->sourceEligible) || (entry->alias != nullptr && pending[k].found == entry->alias) || lookupAccepts(*entry))) {
if (BuildProfiled()) Revalidations().refreshedOverlaps.fetch_add(1, std::memory_order_relaxed);
accepted = true;
continue;
@@ -4050,7 +4054,14 @@ ShaderResources::OwnRefreshFallback ShaderResources::refreshOwnObjects(std::span
overlap.sourceRefreshed = false;
const auto found = pendingLookupSource(context, surface.resource, surface.bytes, depthCompare).source;
if (found != nullptr) {
if (found != source) return OwnRefreshFallback::ForeignView;
if (found != source) {
if (!overlap.viewUncompressed || RuntimeSwitches::Set(RuntimeSwitch::NoAliasViews) || !source->IsPendingAlias(*found)) return OwnRefreshFallback::ForeignView;
countOwnRefresh(false);
refreshForView(*source, surface.resource);
TextureCounts().aliasRefreshes.fetch_add(1, std::memory_order_relaxed);
overlap.alias = found.get();
return OwnRefreshFallback::Count;
}
if (!GuestMemory::UnchangedSince(address, bytes, source->GenerationFor(address, bytes))) {
countOwnRefresh(false);
refreshForView(*source, surface.resource);
@@ -5268,8 +5279,8 @@ std::size_t ResourceCache::Capacity() const {
std::uint64_t ResourceCache::TableElementBudget() {
static const std::uint64_t elements = [] {
const char* value = std::getenv("APS5_RESOURCE_CACHE_TABLE_ELEMENTS");
const auto parsed = value ? std::strtoull(value, nullptr, 10) : 65536ull;
return static_cast<std::uint64_t>(parsed != 0 ? parsed : 65536ull);
const auto parsed = value ? std::strtoull(value, nullptr, 10) : 262144ull;
return static_cast<std::uint64_t>(parsed != 0 ? parsed : 262144ull);
}();
return elements;
}
@@ -6301,13 +6312,10 @@ std::vector<std::uint32_t> variantRepresentatives(VkDevice device, const ShaderR
for (std::uint32_t element = 0; element < binding.count && elementBase + element < capacity; ++element) {
if (element < binding.imageWritten.size() && binding.imageWritten[element]) continue;
const auto words = std::span<const std::uint32_t>(binding.guestDescriptor).subspan(static_cast<std::size_t>(element) * 8u, 8u);
GuestTextureResource resource{};
try {
if (IsNullTextureResource(words)) continue;
resource = DecodeTextureResource(words);
} catch (const std::runtime_error&) {
continue;
}
if (IsNullTextureResource(words)) continue;
const auto decoded = TryDecodeTextureResource(words);
if (decoded.rejection) continue;
const auto& resource = decoded.resource;
const FamilyKey key{resource.baseAddress, resource.pipeBankXor, resource.format, static_cast<std::uint32_t>(resource.tileMode), static_cast<std::uint32_t>(resource.dimension), resource.mipCount, resource.baseLevel, resource.lastLevel, resource.depthOrLastArray, resource.baseArray};
families[key].push_back({element, resource});
}
@@ -6364,13 +6372,10 @@ std::vector<std::uint32_t> arrayPartners(const ShaderRecompiler::DescriptorBindi
for (std::uint32_t element = 0; element < binding.count && elementBase + element < capacity; ++element) {
if (element < binding.imageWritten.size() && binding.imageWritten[element]) continue;
const auto words = std::span<const std::uint32_t>(binding.guestDescriptor).subspan(static_cast<std::size_t>(element) * 8u, 8u);
GuestTextureResource resource{};
try {
if (IsNullSampledTextureResource(words)) continue;
resource = DecodeTextureResource(words);
} catch (const std::runtime_error&) {
continue;
}
if (IsNullSampledTextureResource(words)) continue;
const auto decoded = TryDecodeTextureResource(words);
if (decoded.rejection) continue;
const auto& resource = decoded.resource;
std::array<std::uint32_t, 8> key{};
std::copy(words.begin(), words.end(), key.begin());
key[3] &= ~(0xfu << 28u);
@@ -6458,7 +6463,12 @@ void ShaderResources::resolveImageTables() {
};
const auto decodeEntry = [&](std::uint32_t element, std::span<const std::uint32_t> words) {
DecodedEntry decoded;
decoded.resource = DecodeTextureResource(words);
const auto texture = TryDecodeTextureResource(words);
if (texture.rejection) {
decoded.rejected = *texture.rejection;
return decoded;
}
decoded.resource = texture.resource;
const auto& resource = decoded.resource;
const auto shape = binding.imageShapes.at(element);
const bool depthCompare = element < binding.imageDepthCompare.size() && binding.imageDepthCompare[element];
@@ -7114,16 +7124,22 @@ std::optional<std::vector<ShaderResources::MovedBuffer>> ShaderResources::MovedD
const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element];
if (written || empty || item.written) return refuse(MoveRefusal::Written);
if (size > context.limits.maxStorageBufferRange) return refuse(MoveRefusal::Limit);
VkDescriptorBufferInfo view{};
std::uint64_t serial = 0;
const bool inPlace = item.adjustment == 0 && HostImportView(context, address, static_cast<std::size_t>(size), view, serial);
const auto begin = address - item.adjustment;
const auto bytes = static_cast<std::size_t>(GuestBufferMemory::ViewBytes(size, item.adjustment));
if (maxBytes != 0 && proof.bytes + bytes > maxBytes) return refuse(MoveRefusal::Limit);
if (!inPlace && maxBytes != 0 && proof.bytes + bytes > maxBytes) return refuse(MoveRefusal::Limit);
if (!GuestMemory::Accessible(reinterpret_cast<const void*>(begin), bytes)) return refuse(MoveRefusal::Inaccessible);
const bool pending = recorder != nullptr ? recorder->PendingWriteOverlaps(begin, bytes) : Recorder::SnapshotWriteOverlaps(begin, bytes);
const std::array<std::pair<std::uint64_t, std::uint64_t>, 1> range{{{begin, begin + bytes}}};
if (guestMemory.WritesOverlap(begin, bytes) || pending || StorageTexture::AnyPendingOverlaps(range) || AnyShadowedOverlaps(begin, bytes)) return refuse(MoveRefusal::Overlap);
moved.push_back({kept->allocations[element], address, static_cast<std::size_t>(size)});
MovedBuffer entry{kept->allocations[element], address, static_cast<std::size_t>(size)};
entry.dispatchInPlace = inPlace;
moved.push_back(entry);
++proof.buffers;
proof.bytes += bytes;
if (inPlace) ++proof.inPlace;
else proof.bytes += bytes;
}
}
return moved;
@@ -7201,6 +7217,15 @@ std::shared_ptr<ShaderResources::DrawBindings> ShaderResources::PrepareDrawBindi
keep({begin, nullptr, override->inPlaceOffset, bytes, override->inPlace});
continue;
}
if (override != moved.end() && override->dispatchInPlace) {
VkDescriptorBufferInfo view{};
std::uint64_t serial = 0;
if (!HostImportView(context, override->address, override->size, view, serial)) return {};
const auto begin = override->address - item.adjustment;
result->inPlace.push_back({index, view.buffer, view.offset, static_cast<std::size_t>(view.range)});
result->inPlaceReads.push_back({begin, begin + GuestBufferMemory::ViewBytes(override->size, item.adjustment)});
continue;
}
std::uint64_t address = item.address;
std::size_t size = item.size;
if (override != moved.end()) {
@@ -7262,7 +7287,7 @@ std::shared_ptr<ShaderResources::DrawBindings> ShaderResources::PrepareDrawBindi
totalSnapshotBytes += bytes;
CaptureTrace::Log("draw-snapshot batch=%llu address=%llx bytes=%zu", static_cast<unsigned long long>(recorder.Submissions() + 1), static_cast<unsigned long long>(begin), bytes);
}
if (selected.empty() && !rebound) return {};
if (selected.empty() && result->inPlace.empty() && !rebound) return {};
writeDrawSets(*result, selected, faultRecord);
recorder.Keep(result);
for (const auto& snapshot : result->snapshots) {
@@ -7314,6 +7339,10 @@ void ShaderResources::writeDrawSets(DrawBindings& result, std::span<const std::s
auto& snapshotIndices = ShaderRecompiler::ThreadOwned(indicesSlot);
snapshotIndices.assign(allocations.size(), selected.size());
for (std::size_t index = 0; index < selected.size(); ++index) snapshotIndices[selected[index]] = index;
thread_local std::vector<std::size_t>* inPlaceSlot = nullptr;
auto& inPlaceIndices = ShaderRecompiler::ThreadOwned(inPlaceSlot);
inPlaceIndices.assign(allocations.size(), result.inPlace.size());
for (std::size_t index = 0; index < result.inPlace.size(); ++index) inPlaceIndices[result.inPlace[index].allocation] = index;
auto nextWrite = writes.begin();
for (const auto& binding : bindings) {
const auto original = setOf(binding) == 0 ? _set : fragment.set;
@@ -7324,6 +7353,12 @@ void ShaderResources::writeDrawSets(DrawBindings& result, std::span<const std::s
const auto offset = static_cast<std::size_t>(write.pBufferInfo - descriptorBuffers.data());
write.pBufferInfo = buffers.data() + offset;
for (std::size_t element = 0; element < binding.allocations.size(); ++element) {
const auto boundIndex = inPlaceIndices[binding.allocations[element]];
if (boundIndex != result.inPlace.size()) {
const auto& bound = result.inPlace[boundIndex];
buffers[offset + element] = wholeDwordRange({bound.buffer, bound.offset, bound.bytes});
continue;
}
const auto snapshotIndex = snapshotIndices[binding.allocations[element]];
if (snapshotIndex == selected.size()) continue;
const auto& snapshot = result.snapshots[snapshotIndex];
@@ -7433,14 +7468,18 @@ void ShaderResources::WriteBack() {
if (unaligned) std::rethrow_exception(unaligned);
}
void ShaderResources::MarkGpuWrites(Recorder& recorder) {
void ShaderResources::MarkGpuWrites(Recorder& recorder, const DrawBindings* bindings) {
if (bda != nullptr && recorder.Device() == context.device) bda->NoteUse(recorder.OpenSerial());
// The ranges this use reads in place through their host imports (read-only and written elements
// alike, and an address-based build's whole leased heaps), before the writes: a CPU store into
// one of them (the copy HLE) must not land before the recorded work read it.
static const bool readOnlyLeaseSkip = std::getenv("APS5_NO_READ_ONLY_LEASE_SKIP") == nullptr;
const auto kind = !guestMemory.HoldsLease() ? Recorder::ReadKind::DispatchElement : readOnlyLeaseSkip && usesBda && bdaReadOnly ? Recorder::ReadKind::AddressBasedReadOnly : Recorder::ReadKind::AddressBased;
if (auto split = guestMemory.SplitInPlaceReads()) {
if (bindings != nullptr && !bindings->inPlaceReads.empty()) {
auto reads = guestMemory.InPlaceReads();
reads.insert(reads.end(), bindings->inPlaceReads.begin(), bindings->inPlaceReads.end());
recorder.NotePendingReads(reads, kind);
} else if (auto split = guestMemory.SplitInPlaceReads()) {
recorder.NotePendingReadList(std::move(split->space), kind);
recorder.NotePendingReads(split->own, kind);
} else {
@@ -310,6 +310,12 @@ constexpr std::uint32_t PixelShaderIteratesSamples = 0x10000u;
constexpr std::uint32_t PixelSampleCoverageInput = 0x4000u;
constexpr std::uint32_t PixelSampleRateInputs = 0x2011u;
constexpr std::uint32_t ScreenOffsetMask = ~0x01ff01ffu;
constexpr std::uint32_t VertexRoundModeMask = 0x6u;
constexpr std::uint32_t HalfPixelCenterSubpixel256 = 0x29u;
bool vertexControlSupported(std::uint32_t word) {
return (word & ~VertexRoundModeMask) == HalfPixelCenterSubpixel256;
}
// Bits 26/27 (ZCLIP_NEAR/FAR_DISABLE) become depth clamping; bit 19 selects the [0, 1] clip space;
// bit 16 disables clipping.
constexpr std::uint32_t ClipControlMask = ~(0x10000u | 0x80000u | 0x01000000u | 0x0c000000u);
@@ -1469,7 +1475,10 @@ std::optional<DepthRenderControl> DecodeDepthRenderControl(const QueueState& que
return DepthRenderControl{address & ~std::uint64_t{65535u}, 1u << ((zInfo->second >> 2u) & 3u), control->second};
}
ReversedBlend TranslateReversedBlend(std::uint32_t blendControl, std::uint8_t componentMapping, VkFormat format, bool forceDestinationAlphaOne, const std::array<float, 4>& constants) {
namespace {
template <typename TReadConstant>
ReversedBlend translateReversedBlendWith(std::uint32_t blendControl, std::uint8_t componentMapping, VkFormat format, bool forceDestinationAlphaOne, TReadConstant&& readConstant) {
const auto refuse = [&](const char* reason) {
char text[320];
std::snprintf(text, sizeof(text), "AGC graphics: blending into a color target with a reversed component order %s (CB_BLEND_CONTROL 0x%08x, component mapping 0x%02x, VkFormat %d)", reason, blendControl, componentMapping, static_cast<int>(format));
@@ -1504,7 +1513,10 @@ ReversedBlend TranslateReversedBlend(std::uint32_t blendControl, std::uint8_t co
for (const auto factor : color) {
if (factor == VK_BLEND_FACTOR_DST_ALPHA || factor == VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA || factor == VK_BLEND_FACTOR_SRC_ALPHA_SATURATE) refuse("with a factor of the destination alpha in the color equation, which the target keeps in its first channel, is not implemented");
}
const auto guestConstant = [&](std::uint32_t component) { return format == VK_FORMAT_R16G16B16A16_SFLOAT ? constants[component] : std::clamp(constants[component], 0.0f, 1.0f); };
const auto guestConstant = [&](std::uint32_t component) {
const float value = readConstant(component);
return format == VK_FORMAT_R16G16B16A16_SFLOAT ? value : std::clamp(value, 0.0f, 1.0f);
};
const auto fixedValue = [&](VkBlendFactor factor, std::uint32_t component) -> std::optional<float> {
switch (factor) {
case VK_BLEND_FACTOR_ZERO: return 0.0f;
@@ -1567,6 +1579,12 @@ ReversedBlend TranslateReversedBlend(std::uint32_t blendControl, std::uint8_t co
return result;
}
}
ReversedBlend TranslateReversedBlend(std::uint32_t blendControl, std::uint8_t componentMapping, VkFormat format, bool forceDestinationAlphaOne, const std::array<float, 4>& constants) {
return translateReversedBlendWith(blendControl, componentMapping, format, forceDestinationAlphaOne, [&](std::uint32_t component) { return constants[component]; });
}
void ApplyReadOnlyDepthBoundsComparison(State& state, const ShaderRecompiler::ShaderPixelStageInfo& pixel, bool enabled) {
if (!enabled || !state.depthBoundsTest || !state.depth || state.depth->format != VK_FORMAT_D32_SFLOAT_S8_UINT) return;
if (state.depthTest || state.depthWrite || state.stencilTest || state.depthBias || state.depthBiasPerFace || state.depthRemap.mode != 0) return;
@@ -1802,7 +1820,7 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) {
zero(cx, 0x8d, ScreenOffsetMask, "reserved PA_SU_HARDWARE_SCREEN_OFFSET bits");
Require(read(cx, 0x83) == 0xffffu, "clip rectangles are unsupported");
Require((read(cx, 0x8c) & 0xfu) == 0xau, "nonstandard triangle edge rules are unsupported");
Require(read(cx, 0x2f9) == 0x2du, "nonstandard pixel center or vertex quantization is unsupported");
Require(vertexControlSupported(read(cx, 0x2f9)), "nonstandard pixel center or vertex quantization is unsupported");
if (auto reason = sampleMaskRejection(queue, read(cx, 0x2f8), read(cx, 0x30e), read(cx, 0x30f)); !reason.empty()) throw std::runtime_error(reason);
const auto viewportControl = read(cx, 0x206);
if (viewportControl != 0x43fu && viewportControl != 0u) throw std::runtime_error(vteMessage(viewportControl));
@@ -2022,9 +2040,13 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) {
const bool reversed = mapping == 0x1bu || mapping == 0x93u;
if (state.blendEnable) {
const bool opaqueDestination = (read(cx, 0x31d + slot * 0xfu) & 0x20000u) != 0;
for (std::uint32_t i = 0; i < 4; ++i) result.blendConstants[i] = readFloat(cx, 0x105 + i);
const auto recordBlendConstant = [&](std::uint32_t channel, float value) {
Require((requiredBlendMask & (1u << channel)) == 0 || requiredBlendConstants[channel] == value, "color targets require conflicting blend constants after component swap");
requiredBlendConstants[channel] = value;
requiredBlendMask |= 1u << channel;
};
if (reversed) {
const auto translated = TranslateReversedBlend(blend, mapping, color.format, opaqueDestination, result.blendConstants);
const auto translated = translateReversedBlendWith(blend, mapping, color.format, opaqueDestination, [&](std::uint32_t component) { return readFloat(cx, 0x105 + component); });
state.srcColorBlendFactor = translated.blend.srcColorBlendFactor;
state.dstColorBlendFactor = translated.blend.dstColorBlendFactor;
state.colorBlendOp = translated.blend.colorBlendOp;
@@ -2034,9 +2056,7 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) {
if (translated.shaderCode != 0u) result.reversedBlend = translated.shaderCode;
for (std::uint32_t i = 0; i < 4; ++i) {
if ((translated.constantMask & (1u << i)) == 0u || (state.colorWriteMask & (1u << i)) == 0u) continue;
Require((requiredBlendMask & (1u << i)) == 0 || requiredBlendConstants[i] == translated.constants[i], "color targets require conflicting blend constants after component swap");
requiredBlendConstants[i] = translated.constants[i];
requiredBlendMask |= 1u << i;
recordBlendConstant(i, translated.constants[i]);
}
} else {
state.srcColorBlendFactor = blendFactor(blend & 0x1fu);
@@ -2062,21 +2082,14 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) {
const auto factorsCount = [](VkBlendOp op) { return op != VK_BLEND_OP_MIN && op != VK_BLEND_OP_MAX; };
const bool colorReadsAlpha = (state.colorWriteMask & 7u) != 0 && factorsCount(state.colorBlendOp) && (constantAlpha(state.srcColorBlendFactor) || constantAlpha(state.dstColorBlendFactor));
const bool alphaReadsAlpha = (state.colorWriteMask & 8u) != 0 && factorsCount(state.alphaBlendOp) && (anyConstant(state.srcAlphaBlendFactor) || anyConstant(state.dstAlphaBlendFactor));
if (colorReadsAlpha || alphaReadsAlpha) {
const auto value = result.blendConstants[3];
Require((requiredBlendMask & 8u) == 0 || requiredBlendConstants[3] == value, "color targets require conflicting blend constants after component swap");
requiredBlendConstants[3] = value;
requiredBlendMask |= 8u;
}
if (colorReadsAlpha || alphaReadsAlpha) recordBlendConstant(3u, readFloat(cx, 0x105 + 3u));
}
const auto constantColor = [](VkBlendFactor factor) { return factor == VK_BLEND_FACTOR_CONSTANT_COLOR || factor == VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR; };
if ((mapping == 0xe4u || mapping == 0xc6u) && state.colorBlendOp != VK_BLEND_OP_MIN && state.colorBlendOp != VK_BLEND_OP_MAX && (constantColor(state.srcColorBlendFactor) || constantColor(state.dstColorBlendFactor))) {
if (!reversed && mapping != 0xecu && state.colorBlendOp != VK_BLEND_OP_MIN && state.colorBlendOp != VK_BLEND_OP_MAX && (constantColor(state.srcColorBlendFactor) || constantColor(state.dstColorBlendFactor))) {
for (std::uint32_t i = 0; i < 3; ++i) {
if ((state.colorWriteMask & (1u << i)) == 0) continue;
const auto value = result.blendConstants[(mapping >> (2u * i)) & 3u];
Require((requiredBlendMask & (1u << i)) == 0 || requiredBlendConstants[i] == value, "color targets require conflicting blend constants after component swap");
requiredBlendConstants[i] = value;
requiredBlendMask |= 1u << i;
const std::uint32_t sourceChannel = (mapping == 0xe4u || mapping == 0xc6u) ? ((mapping >> (2u * i)) & 3u) : i;
recordBlendConstant(i, readFloat(cx, 0x105 + sourceChannel));
}
}
if (mapping == 0xecu) {
@@ -2786,7 +2799,8 @@ std::optional<ColorMetadataPass> DecodeColorMetadataPass(const QueueState& queue
Require(destination.samples == 1, "CB resolve into a multisampled target is unsupported");
Require(destination.cmaskAddress == 0, "CB resolve into a fast-clear color target is unsupported (the resolve does not update its CMASK)");
Require(source.format == destination.format && source.extent.width == destination.extent.width && source.extent.height == destination.extent.height, "CB resolve between different formats or extents is unsupported");
if (WordPacked(source.packing)) throw std::runtime_error("AGC graphics: CB resolves of " + std::string(PackedColorTargetName(source.packing)) + " color targets are unsupported");
if (source.packing == ShaderRecompiler::ColorExportPacking::Float11_11_10 || destination.packing == ShaderRecompiler::ColorExportPacking::Float11_11_10) Require(source.packing == destination.packing && source.componentMapping == destination.componentMapping, "CB resolve between 11_11_10 float color targets of different layouts is unsupported");
if (WordPacked(source.packing) && source.packing != ShaderRecompiler::ColorExportPacking::Float11_11_10) throw std::runtime_error("AGC graphics: CB resolves of " + std::string(PackedColorTargetName(source.packing)) + " color targets are unsupported");
requireCovered(destination);
pass.source = source;
pass.targets.push_back(destination);
@@ -2931,7 +2945,7 @@ std::string DrawRejection(const QueueState& queue, bool indexed) {
if (auto reason = nonzero(cx, 0x8d, ScreenOffsetMask, "reserved PA_SU_HARDWARE_SCREEN_OFFSET bits"); !reason.empty()) return reason;
if (value(cx, 0x83, word) && word != 0xffffu) return require(false, "clip rectangles are unsupported");
if (value(cx, 0x8c, word) && (word & 0xfu) != 0xau) return require(false, "nonstandard triangle edge rules are unsupported");
if (value(cx, 0x2f9, word) && word != 0x2du) return require(false, "nonstandard pixel center or vertex quantization is unsupported");
if (value(cx, 0x2f9, word) && !vertexControlSupported(word)) return require(false, "nonstandard pixel center or vertex quantization is unsupported");
if (value(cx, 0x313, word) && (word & ~0x001f6000u) != 0 && word != 0x6001u) return conservativeMessage(word);
std::uint32_t config = 0, other = 0;
if (value(cx, 0x2f8, config) && value(cx, 0x30e, word) && value(cx, 0x30f, other)) {
@@ -2966,7 +2980,7 @@ bool PixelProgramSkipped(const QueueState& queue) {
if (targetMask == cx.end() || shaderMask == cx.end() || shaderControl == cx.end()) return false;
const auto alphaToMask = find(cx, 0x2dc);
if (alphaToMask != cx.end() && (alphaToMask->second & 1u) != 0) return false;
return (targetMask->second & shaderMask->second) == 0 && (shaderControl->second & PixelStageRunsMask) == 0;
return ColorWriteMask(cx) == 0 && (shaderControl->second & PixelStageRunsMask) == 0;
}
std::string NullPixelProgramRejection(const QueueState& queue) {
@@ -139,6 +139,17 @@ thread_local const char* uploadReason = "first";
// (DiscardPendingInside) and units an alias's own results superseded (markLayersPending); relaxed,
// reported only.
std::atomic<std::uint64_t> singlePassMoves{0}, slabRetiles{0}, paddingSeedCopies{0}, linearImportRetiles{0};
std::atomic<std::uint64_t> importRouteDirect{0}, importRouteHostBlocked{0}, importRouteOther{0};
static void noteImportRoute(std::atomic<std::uint64_t>& route) {
route.fetch_add(1, std::memory_order_relaxed);
static const bool stats = std::getenv("APS5_PIPELINE_STATS") != nullptr;
if (!stats) return;
static std::atomic<std::int64_t> reportedAt{0};
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, "[import-writeback] (10 s): %llu retiled into the import, %llu eligible but copied (host-memory import), %llu other\n", static_cast<unsigned long long>(importRouteDirect.exchange(0)), static_cast<unsigned long long>(importRouteHostBlocked.exchange(0)), static_cast<unsigned long long>(importRouteOther.exchange(0)));
}
std::atomic<std::uint64_t> partialUploads{0}, partialUploadBytes{0}, partialWriteBacks{0}, partialWriteBackBytes{0}, emptyWriteBacks{0}, coalescedWriteBacks{0}, unitsDropped{0}, unitsSuperseded{0}, clearHandOvers{0}, creationHandOvers{0}, handedOverSuperseded{0};
// FlushPending listings skipped because no pending unit of the image lay inside the range, images
// whose selected pending units were dropped because their memory is no longer registered (see
@@ -514,11 +525,11 @@ static VkDeviceSize BindSparseLevels(const Context& context, OwnedImage& owned,
return bytes;
}
Texture::Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, bool depthCompare, bool layerRows, const VkClearColorValue* clear, std::optional<std::span<const std::uint32_t>> packedSlabs, const HostImport* source) : Texture(context, detiler, descriptor, components, snapshot, nullptr, depthCompare, layerRows, clear, packedSlabs, source) {}
Texture::Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, bool depthCompare, bool layerRows, const VkClearColorValue* clear, std::optional<std::span<const std::uint32_t>> packedSlabs, std::span<const HostImportCopy> sources) : Texture(context, detiler, descriptor, components, snapshot, nullptr, depthCompare, layerRows, clear, packedSlabs, sources) {}
Texture::Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::shared_ptr<Buffer> staging, bool depthCompare, bool layerRows, std::optional<std::span<const std::uint32_t>> packedSlabs) : Texture(context, detiler, descriptor, components, {}, std::move(staging), depthCompare, layerRows, nullptr, packedSlabs, nullptr) {}
Texture::Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::shared_ptr<Buffer> staging, bool depthCompare, bool layerRows, std::optional<std::span<const std::uint32_t>> packedSlabs) : Texture(context, detiler, descriptor, components, {}, std::move(staging), depthCompare, layerRows, nullptr, packedSlabs, {}) {}
Texture::Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, std::shared_ptr<Buffer> staging, bool depthCompare, bool layerRows, const VkClearColorValue* clear, std::optional<std::span<const std::uint32_t>> packedSlabs, const HostImport* source) : context(context) {
Texture::Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, std::shared_ptr<Buffer> staging, bool depthCompare, bool layerRows, const VkClearColorValue* clear, std::optional<std::span<const std::uint32_t>> packedSlabs, std::span<const HostImportCopy> sources) : context(context) {
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
PhaseTimer timer;
@@ -556,11 +567,17 @@ Texture::Texture(const Context& context, TextureDetiler& detiler, const GuestTex
const auto guestBytes = geometry.guestBytes;
AgcDriver::LiveResourceRing::Instance().Note(descriptor.baseAddress, guestBytes, "texture");
const auto slabBytes = geometry.layerBytes;
const auto snapshotSize = source != nullptr ? guestBytes : staging != nullptr ? staging->Bytes().size() : snapshot.size();
const auto snapshotSize = !sources.empty() ? guestBytes : staging != nullptr ? staging->Bytes().size() : snapshot.size();
Require(clear == nullptr || !packedSlabs.has_value(), "a cleared texture takes no snapshot, so it has no committed slabs");
Require(clear != nullptr || source != nullptr ? snapshot.empty() && staging == nullptr : packedSlabs.has_value() ? slabBytes != 0 && snapshotSize == packedSlabs->size() * slabBytes : snapshotSize == guestBytes, "texture snapshot size mismatch");
Require(source == nullptr || !packedSlabs.has_value(), "a texture uploaded from a host import covers the whole surface, so it has no committed slabs");
Require(source == nullptr || (descriptor.baseAddress >= source->base && descriptor.baseAddress - source->base + guestBytes <= source->bytes), "texture import source does not cover the surface");
Require(clear != nullptr || !sources.empty() ? snapshot.empty() && staging == nullptr : packedSlabs.has_value() ? slabBytes != 0 && snapshotSize == packedSlabs->size() * slabBytes : snapshotSize == guestBytes, "texture snapshot size mismatch");
Require(sources.empty() || !packedSlabs.has_value(), "a texture uploaded from a host import covers the whole surface, so it has no committed slabs");
Require(clear == nullptr || sources.empty(), "a cleared texture cannot have import sources");
std::uint64_t importedBytes = 0;
for (const auto& copy : sources) {
Require(copy.buffer != VK_NULL_HANDLE && copy.bytes != 0 && copy.bytes <= guestBytes - importedBytes && copy.offset <= UINT64_MAX - copy.bytes, "texture import source does not cover the surface");
importedBytes += copy.bytes;
}
Require(sources.empty() || importedBytes == guestBytes, "texture import source does not cover the surface");
Require(clear == nullptr || (!depthCompare && !srgbExpand && !IsRepackedTextureFormat(descriptor.format) && !IsBlockCompressed(descriptor.format)), "a cleared texture needs a plain color format");
Require(!packedSlabs.has_value() || (std::ranges::adjacent_find(*packedSlabs, std::greater_equal<>{}) == packedSlabs->end() && (packedSlabs->empty() || packedSlabs->back() < guestBytes / slabBytes)), "texture snapshot slabs are not ascending slabs of the surface");
Require(!packedSlabs.has_value() || !geometry.levelMajor, "a partially committed snapshot of a PS4 layered surface with several mip levels (stored level by level) is not implemented");
@@ -699,7 +716,7 @@ Texture::Texture(const Context& context, TextureDetiler& detiler, const GuestTex
}
static const bool syncUploads = std::getenv("APS5_SYNC_TEXTURE_UPLOAD") != nullptr;
auto* recorder = dumpWanted || syncUploads ? nullptr : Recorder::Active();
if (staging == nullptr && source == nullptr && !uploaded.empty()) {
if (staging == nullptr && sources.empty() && !uploaded.empty()) {
staging = std::make_shared<Buffer>(context, snapshot.size(), VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
std::memcpy(staging->Bytes().data(), snapshot.data(), snapshot.size());
}
@@ -720,7 +737,7 @@ Texture::Texture(const Context& context, TextureDetiler& detiler, const GuestTex
std::shared_ptr<DeviceBuffer> linear;
if (recorder != nullptr) {
commands = recorder->Commands();
if (staging != nullptr || source != nullptr) {
if (staging != nullptr || !sources.empty()) {
tiled = recorder->UploadScratchBuffer(Recorder::UploadScratch::Tiled, snapshotSize);
linear = recorder->UploadScratchBuffer(Recorder::UploadScratch::Linear, static_cast<std::size_t>(linearBytes));
if (staging != nullptr) recorder->Keep(staging, snapshotSize);
@@ -731,15 +748,19 @@ Texture::Texture(const Context& context, TextureDetiler& detiler, const GuestTex
} else {
batch = std::make_unique<CommandBatch>(context);
commands = batch->Handle();
if (staging != nullptr || source != nullptr) {
if (staging != nullptr || !sources.empty()) {
tiled = std::make_shared<DeviceBuffer>(context, snapshotSize, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
linear = std::make_shared<DeviceBuffer>(context, static_cast<std::size_t>(linearBytes), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
}
}
if (source != nullptr) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT);
CopyBuffer(context, commands, source->buffer, HostImportOffset(*source, descriptor.baseAddress), tiled->Handle(), 0, guestBytes);
if (!sources.empty()) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT);
VkDeviceSize destination = 0;
for (const auto& copy : sources) {
CopyBuffer(context, commands, copy.buffer, copy.offset, tiled->Handle(), destination, copy.bytes);
destination += copy.bytes;
}
} else {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_HOST_BIT | Recorder::UploadScratchReuseStages, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT);
if (staging != nullptr) CopyBuffer(context, commands, staging->Handle(), 0, tiled->Handle(), 0, snapshotSize);
@@ -4770,7 +4791,22 @@ std::uint64_t StorageTexture::OccasionalLabelStores() {
}
void StorageTexture::markLayersPending(std::uint32_t first, std::uint32_t count) {
if (count != 0) GuestMemory::ForgetKnownZero(layerBegin(first), static_cast<std::size_t>(layerBegin(first + count - 1) + layerBytes(first + count - 1) - layerBegin(first)));
if (count != 0) {
const auto begin = layerBegin(first);
const auto end = layerBegin(first + count - 1) + layerBytes(first + count - 1);
const auto marks = GuestMemory::KnownZeroMarks();
if (marks != zeroForgetMarks || begin < zeroForgetBegin || end > zeroForgetEnd) {
GuestMemory::ForgetKnownZero(begin, static_cast<std::size_t>(end - begin));
if (marks == zeroForgetMarks && begin <= zeroForgetEnd && end >= zeroForgetBegin) {
zeroForgetBegin = std::min(zeroForgetBegin, begin);
zeroForgetEnd = std::max(zeroForgetEnd, end);
} else {
zeroForgetBegin = begin;
zeroForgetEnd = end;
}
zeroForgetMarks = marks;
}
}
{
auto& records = LayoutWrites();
std::lock_guard lock(records.mutex);
@@ -5840,6 +5876,24 @@ std::size_t StorageTexture::StoreSmallPending(const char* reason) {
return stored;
}
#if defined(__APPLE__)
bool StorageTexture::trapReadsAtLabel(const StorageTexture* texture) {
auto& pending = Pending();
const auto page = TrapPage();
const auto first = texture->descriptor.baseAddress & ~(page - 1);
const auto span = static_cast<std::size_t>(((texture->descriptor.baseAddress + texture->guestBytes + page - 1) & ~(page - 1)) - first);
const auto shares = [&](const StorageTexture* other) { return other != texture && other->overlaps(first, span); };
const auto sharesStored = [&](const StorageTexture* other) { return shares(other) && (other->descriptor.tileMode == TextureTileMode::kLinear || other->guestBytes <= SmallStoreBytes); };
if (std::any_of(pending.textures.begin(), pending.textures.end(), sharesStored) || std::any_of(pending.flushing.begin(), pending.flushing.end(), shares)) return false;
const auto address = static_cast<std::uintptr_t>(texture->descriptor.baseAddress);
const auto bytes = static_cast<std::size_t>(texture->guestBytes);
if (!texture->readTrapped.load(std::memory_order_acquire) && DirectMemoryAliased_nid_postfix(address, bytes)) return false;
if (!GuestWriteWatch::GuestWriteWatchTrapReads_nid_postfix(address, bytes)) return false;
texture->readTrapped.store(true, std::memory_order_release);
return true;
}
#endif
void StorageTexture::StoreReadbackBeforeLabel(const char* reason, VkDevice device) {
static const bool disabled = std::getenv("APS5_NO_LABEL_READBACK_STORE") != nullptr;
if (disabled) return;
@@ -5857,22 +5911,11 @@ void StorageTexture::StoreReadbackBeforeLabel(const char* reason, VkDevice devic
#if defined(__APPLE__)
const bool trap = LabelTrapsEnabled();
if (trap) labelTrapsSet.store(true, std::memory_order_relaxed);
const auto page = TrapPage();
const auto sharesPage = [&](const StorageTexture* texture) {
const auto first = texture->descriptor.baseAddress & ~(page - 1);
const auto bytes = static_cast<std::size_t>(((texture->descriptor.baseAddress + texture->guestBytes + page - 1) & ~(page - 1)) - first);
const auto shares = [&](const StorageTexture* other) { return other != texture && other->overlaps(first, bytes); };
const auto sharesStored = [&](const StorageTexture* other) { return shares(other) && (other->descriptor.tileMode == TextureTileMode::kLinear || other->guestBytes <= SmallStoreBytes); };
return std::any_of(pending.textures.begin(), pending.textures.end(), sharesStored) || std::any_of(pending.flushing.begin(), pending.flushing.end(), shares);
};
#endif
for (const auto* texture : pending.textures) {
if (texture->descriptor.tileMode != TextureTileMode::kLinear && texture->guestBytes > SmallStoreBytes) continue;
#if defined(__APPLE__)
if (trap && !sharesPage(texture) && (texture->readTrapped.load(std::memory_order_acquire) || !DirectMemoryAliased_nid_postfix(static_cast<std::uintptr_t>(texture->descriptor.baseAddress), static_cast<std::size_t>(texture->guestBytes))) && GuestWriteWatch::GuestWriteWatchTrapReads_nid_postfix(static_cast<std::uintptr_t>(texture->descriptor.baseAddress), static_cast<std::size_t>(texture->guestBytes))) {
texture->readTrapped.store(true, std::memory_order_release);
continue;
}
if (trap && trapReadsAtLabel(texture)) continue;
#endif
ranges.emplace_back(texture->descriptor.baseAddress, static_cast<std::size_t>(texture->guestBytes));
}
@@ -5896,8 +5939,17 @@ std::size_t StorageTexture::StoreDrawnLinear(const char* reason) {
std::vector<std::pair<std::uint64_t, std::size_t>> ranges;
{
std::lock_guard lock(pending.mutex);
#if defined(__APPLE__)
const bool trap = (std::strcmp(reason, "label") == 0 || std::strcmp(reason, "interrupt") == 0) && LabelTrapsEnabled();
if (trap) labelTrapsSet.store(true, std::memory_order_relaxed);
#endif
for (const auto& entry : pending.drawn) {
if (entry.texture->dirty) ranges.emplace_back(entry.texture->descriptor.baseAddress, static_cast<std::size_t>(entry.texture->guestBytes));
const auto* texture = entry.texture;
if (!texture->dirty) continue;
#if defined(__APPLE__)
if (trap && texture->descriptor.tileMode == TextureTileMode::kLinear && HostImportCovers(texture->context, texture->descriptor.baseAddress, static_cast<std::size_t>(texture->guestBytes)) && trapReadsAtLabel(texture)) continue;
#endif
ranges.emplace_back(texture->descriptor.baseAddress, static_cast<std::size_t>(texture->guestBytes));
}
}
std::size_t stored = 0;
@@ -5967,6 +6019,10 @@ std::shared_ptr<StorageTexture> StorageTexture::FindPending(std::uint64_t addres
return containing != nullptr ? containing->weak_from_this().lock() : nullptr;
}
bool StorageTexture::IsPendingAlias(const StorageTexture& pending) const {
return &pending != this && pendingAlias().get() == &pending;
}
VkDevice StorageTexture::Device() const {
return context.device;
}
@@ -6256,6 +6312,227 @@ bool StorageTexture::AccessKeptByCpu(std::uint64_t address, std::size_t bytes, s
return true;
}
namespace {
thread_local StorageTexture::MirrorPublishScope* mirrorPublishScope = nullptr;
std::atomic<std::uint64_t> mirrorPublished{0};
std::atomic<std::uint64_t> mirrorPublishedBytes{0};
std::atomic<std::uint64_t> mirrorPublishSkipped{0};
std::atomic<std::uint64_t> mirrorPublishFallbacks{0};
std::atomic<std::uint64_t> mirrorPublishRefreshes{0};
std::array<std::atomic<std::uint64_t>, StorageTexture::MirrorFallbackReasons> mirrorFallbackReasons{};
std::array<std::atomic<std::uint64_t>, StorageTexture::MirrorFallbackReasons> mirrorFallbackBytes{};
}
StorageTexture::MirrorPublishScope::MirrorPublishScope(std::vector<std::shared_ptr<StorageTexture>>& deferred, std::uint64_t address, std::size_t bytes) : previous(std::exchange(mirrorPublishScope, this)), deferred(deferred), address(address), bytes(bytes) {}
StorageTexture::MirrorPublishScope::~MirrorPublishScope() {
mirrorPublishScope = previous;
}
bool StorageTexture::MirrorPublishEnabled() {
static const bool enabled = std::getenv("APS5_NO_MIRROR_PUBLISH") == nullptr;
return enabled;
}
const char* StorageTexture::MirrorFallbackName(MirrorFallback reason) {
constexpr std::array<const char*, MirrorFallbackReasons> names{"read trap", "dcc keys", "drawn rect", "unwatched", "no generation", "copied mirror", "written by the build", "untracked", "no recorder"};
return names[static_cast<std::size_t>(reason)];
}
std::optional<StorageTexture::MirrorFallback> StorageTexture::mirrorPublishRefusal() const {
if (readTrapped.load(std::memory_order_acquire)) return MirrorFallback::ReadTrap;
if (descriptor.dccAddress != 0 && uploadedKeys != DccKeys::Uncompressed) return MirrorFallback::DccKeys;
if (drawnArea().rect) return MirrorFallback::DrawnRect;
if (!GuestMemory::Watched(descriptor.baseAddress, static_cast<std::size_t>(guestBytes))) return MirrorFallback::Unwatched;
for (std::uint32_t layer = 0; layer < trackedLayers; ++layer) {
if (layerPending[layer] && layerGeneration[layer] == 0) return MirrorFallback::NoGeneration;
}
return std::nullopt;
}
bool StorageTexture::DeferToMirror(std::uint64_t address, std::size_t bytes) {
auto* scope = mirrorPublishScope;
if (scope == nullptr || scope->address != address || scope->bytes != bytes || !MirrorPublishEnabled() || Recorder::Active() == nullptr) return false;
const auto overlapping = overlappingPending(address, bytes);
if (overlapping.empty()) return false;
{
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Hook);
std::lock_guard gpu(GuestMemory::GpuMutex());
bool refused = false;
for (const auto& texture : overlapping) {
if (const auto reason = texture->mirrorPublishRefusal()) {
NoteMirrorPublishFallback(*reason, texture->guestBytes);
refused = true;
}
}
if (refused) return false;
}
static_cast<void>(FlushDepthPlanes(address, bytes));
for (const auto& texture : overlapping) {
if (std::find(scope->deferred.begin(), scope->deferred.end(), texture) == scope->deferred.end()) scope->deferred.push_back(texture);
}
return true;
}
std::optional<std::vector<std::pair<std::uint64_t, std::uint64_t>>> StorageTexture::MirrorPublishRanges(std::uint64_t begin, std::uint64_t end) const {
GuestMemory::AssertGpuLockHeld("StorageTexture::MirrorPublishRanges");
std::vector<std::pair<std::uint64_t, std::uint64_t>> ranges;
const auto first = std::max(begin, descriptor.baseAddress);
const auto last = std::min(end, descriptor.baseAddress + guestBytes);
if (first >= last || !anyLayerPending()) return ranges;
if (const auto reason = mirrorPublishRefusal()) {
NoteMirrorPublishFallback(*reason, last - first);
return std::nullopt;
}
constexpr std::uint64_t block = 65536;
const auto spanBegin = first & ~(block - 1);
const auto spanBlocks = static_cast<std::size_t>((last - spanBegin + block - 1) / block);
GuestMemory::CollectWritesUncached(first, static_cast<std::size_t>(last - first));
std::vector<std::uint64_t> generations(spanBlocks, 0);
for (std::uint32_t layer = 0; layer < trackedLayers; ++layer) {
if (!layerPending[layer]) continue;
const auto from = std::max(first, layerBegin(layer));
const auto to = std::min(last, layerBegin(layer) + layerBytes(layer));
for (auto at = from & ~(block - 1); at < to; at += block) generations[static_cast<std::size_t>((at - spanBegin) / block)] = unitBlockGeneration(layer, at);
}
std::vector<std::uint8_t> changed(spanBlocks);
if (!GuestMemory::ChangedBlocks(first, static_cast<std::size_t>(last - first), generations, changed)) {
NoteMirrorPublishFallback(MirrorFallback::Untracked, last - first);
return std::nullopt;
}
for (std::uint32_t layer = 0; layer < trackedLayers; ++layer) {
if (!layerPending[layer]) continue;
const auto unitBegin = layerBegin(layer);
const auto unitEnd = unitBegin + layerBytes(layer);
if (unitEnd <= first || last <= unitBegin) continue;
for (auto at = std::max(first, unitBegin) & ~(block - 1); at < std::min(last, unitEnd); at += block) {
const auto from = std::max(at, unitBegin);
const auto to = std::min(at + block, unitEnd);
if (from >= to) continue;
const bool edge = from != at || to != at + block;
const auto index = static_cast<std::size_t>((at - spanBegin) / block);
const bool written = keptAtUnwatchHolds(from, layer) || (changed[index] == GuestMemory::BlockWritten && (!edge || GuestMemory::StoredOver(from, static_cast<std::size_t>(to - from), unitBlockGeneration(layer, at))) && !cpuLeftUnchanged(layer, from, to, edge));
if (written) continue;
const auto keepBegin = std::max(from, first);
const auto keepEnd = std::min(to, last);
if (keepBegin >= keepEnd) continue;
if (!ranges.empty() && ranges.back().second == keepBegin) ranges.back().second = keepEnd;
else ranges.emplace_back(keepBegin, keepEnd);
}
}
return ranges;
}
bool StorageTexture::MirrorPublishCurrent(const MirrorTarget& target, std::uint64_t begin, std::uint64_t end) const {
const bool current = std::any_of(mirrorMemos.begin(), mirrorMemos.end(), [&](const MirrorPublishMemo& memo) { return memo.mirror == target.serial && memo.begin == begin && memo.end == end && memo.version == version && memo.uploads == target.uploads && GuestMemory::UnchangedSince(begin, static_cast<std::size_t>(end - begin), memo.tracker); });
if (current) mirrorPublishSkipped.fetch_add(1, std::memory_order_relaxed);
return current;
}
std::uint64_t StorageTexture::PublishIntoMirror(const MirrorTarget& target, std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges, std::uint64_t begin, std::uint64_t end) {
GuestMemory::AssertGpuLockHeld("StorageTexture::PublishIntoMirror");
auto* recorder = recorderFor(context);
Require(recorder != nullptr, "a storage image publish into a heap mirror needs the active recorder");
const auto tracker = GuestMemory::TrackerGeneration();
const auto remember = [&] {
const MirrorPublishMemo memo{target.serial, begin, end, version, target.uploads, tracker};
const auto found = std::find_if(mirrorMemos.begin(), mirrorMemos.end(), [&](const MirrorPublishMemo& entry) { return entry.mirror == target.serial && entry.begin == begin && entry.end == end; });
if (found != mirrorMemos.end()) *found = memo;
else if (mirrorMemos.size() < 8) mirrorMemos.push_back(memo);
else mirrorMemos[static_cast<std::size_t>(version % mirrorMemos.size())] = memo;
};
if (ranges.empty()) {
remember();
return 0;
}
const auto elementBytes = BytesPerElement(descriptor.format);
std::vector<bool> layers(trackedLayers, false);
for (std::uint32_t layer = 0; layer < trackedLayers; ++layer) {
const auto unitBegin = layerBegin(layer);
const auto unitEnd = unitBegin + layerBytes(layer);
layers[layer] = std::any_of(ranges.begin(), ranges.end(), [&](const auto& range) { return range.first < unitEnd && unitBegin < range.second; });
}
const auto* storedLayers = trackedLayers == arrayLayers && trackedLayers > 1 ? &layers : nullptr;
const auto hullBegin = ranges.front().first;
const auto hullEnd = ranges.back().second;
std::uint64_t publishedBytes = 0;
for (const auto& [from, to] : ranges) publishedBytes += to - from;
auto linear = std::make_shared<DeviceBuffer>(context, static_cast<std::size_t>(sliceLinearBytes * arrayLayers), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
auto scratch = std::make_shared<DeviceBuffer>(context, static_cast<std::size_t>(guestBytes), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
detiler.BeginBatch();
const auto commands = recorder->Commands();
const auto timing = recorder->BeginGpuTiming(Recorder::CommandClass::MirrorPublish);
recorder->Keep(linear, linear->Size());
recorder->Keep(scratch, scratch->Size());
if (target.keep != nullptr) recorder->Keep(target.keep);
if (auto self = weak_from_this().lock()) keepStorageTexture(*recorder, std::move(self));
Recorder::CountBarriers(Recorder::CommandClass::MirrorPublish, 5);
VkImageMemoryBarrier toSource{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
toSource.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
toSource.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
toSource.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
toSource.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
toSource.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
toSource.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
toSource.image = image;
toSource.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, descriptor.mipCount, 0, VK_REMAINING_ARRAY_LAYERS};
const VkMemoryBarrier seedReady{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT};
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &seedReady, 0, nullptr, 1, &toSource);
const VkBufferCopy seed{hullBegin - target.origin, hullBegin - descriptor.baseAddress, hullEnd - hullBegin};
context.Function<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer")(commands, target.buffer, scratch->Handle(), 1, &seed);
const auto regions = CopyRegions(storedLayers);
context.Function<PFN_vkCmdCopyImageToBuffer>("vkCmdCopyImageToBuffer")(commands, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, linear->Handle(), static_cast<std::uint32_t>(regions.size()), regions.data());
const VkMemoryBarrier retileReady{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT};
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &retileReady, 0, nullptr, 0, nullptr);
for (std::uint32_t layer = 0; layer < arrayLayers; ++layer) {
if (storedLayers != nullptr && !(*storedLayers)[layer]) continue;
for (std::uint32_t level = 0; level < mips.size(); ++level) {
if (!geometry.HasLayer(level, layer)) continue;
const auto& mip = mips[level];
detiler.Dispatch(commands, descriptor.tileMode, elementBytes, linear->Handle(), geometry.LinearLayerOffset(layer) + mip.linearOffset, scratch->Handle(), geometry.GuestOffset(layer, mip), mip, true, layer, geometry.thick, {.pipeBankXor = descriptor.pipeBankXor});
}
}
const auto scratchDone = WholeBufferBarrier(scratch->Handle(), VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT);
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, &scratchDone, 0, nullptr);
std::vector<VkBufferCopy> copies;
copies.reserve(ranges.size());
for (const auto& [from, to] : ranges) copies.push_back({from - descriptor.baseAddress, from - target.origin, to - from});
context.Function<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer")(commands, scratch->Handle(), target.buffer, static_cast<std::uint32_t>(copies.size()), copies.data());
VkImageMemoryBarrier backToGeneral = toSource;
backToGeneral.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
backToGeneral.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
backToGeneral.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
backToGeneral.newLayout = VK_IMAGE_LAYOUT_GENERAL;
const VkMemoryBarrier published{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT};
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &published, 0, nullptr, 1, &backToGeneral);
recorder->EndGpuTiming(timing, publishedBytes);
mirrorPublished.fetch_add(1, std::memory_order_relaxed);
mirrorPublishedBytes.fetch_add(publishedBytes, std::memory_order_relaxed);
remember();
return publishedBytes;
}
StorageTexture::MirrorPublishCounts StorageTexture::MirrorPublishTotals() {
MirrorPublishCounts counts{mirrorPublished.load(std::memory_order_relaxed), mirrorPublishedBytes.load(std::memory_order_relaxed), mirrorPublishSkipped.load(std::memory_order_relaxed), mirrorPublishFallbacks.load(std::memory_order_relaxed), mirrorPublishRefreshes.load(std::memory_order_relaxed)};
for (std::size_t reason = 0; reason < MirrorFallbackReasons; ++reason) {
counts.reasons[reason] = mirrorFallbackReasons[reason].load(std::memory_order_relaxed);
counts.reasonBytes[reason] = mirrorFallbackBytes[reason].load(std::memory_order_relaxed);
}
return counts;
}
void StorageTexture::NoteMirrorPublishFallback(MirrorFallback reason, std::uint64_t bytes) {
mirrorPublishFallbacks.fetch_add(1, std::memory_order_relaxed);
mirrorFallbackReasons[static_cast<std::size_t>(reason)].fetch_add(1, std::memory_order_relaxed);
mirrorFallbackBytes[static_cast<std::size_t>(reason)].fetch_add(bytes, std::memory_order_relaxed);
}
void StorageTexture::NoteMirrorPublishRefresh() {
mirrorPublishRefreshes.fetch_add(1, std::memory_order_relaxed);
}
bool StorageTexture::evictStale(std::uint64_t address, std::size_t bytes, std::size_t& dropped) {
static const bool staleEvict = std::getenv("APS5_STALE_EVICT") != nullptr;
constexpr std::uint64_t block = 65536;
@@ -7682,6 +7959,7 @@ void StorageTexture::writeBackLayers(const std::vector<bool>& layers) {
std::vector<std::pair<std::uint64_t, std::uint64_t>> importStores(keep.begin(), keep.end());
const bool linearRows = descriptor.tileMode == TextureTileMode::kLinear && !geometry.thick && std::none_of(mips.begin(), mips.end(), [](const TileMipLayout& mip) { return mip.tail; });
const HostImport* directImport = nullptr;
bool routed = false;
if (linearRows && !padding.copies.empty() && padding.slabs.empty() && saveUnits.empty()) {
std::vector<std::pair<std::uint64_t, std::uint64_t>> runs;
for (const auto& range : copied) runs.emplace_back(range.begin, range.end);
@@ -7698,9 +7976,15 @@ void StorageTexture::writeBackLayers(const std::vector<bool>& layers) {
if (!wholeLayers.empty() && wholeLayers.back().second == begin) wholeLayers.back().second = end;
else wholeLayers.emplace_back(begin, end);
}
if (wholeLayers == keep && HostImportDeviceLocal(context, *segments.front().import)) directImport = segments.front().import;
static const bool hostRetile = std::getenv("APS5_LINEAR_IMPORT_RETILE_HOST") != nullptr;
if (wholeLayers == keep) {
if (HostImportDeviceLocal(context, *segments.front().import) || hostRetile) directImport = segments.front().import;
noteImportRoute(directImport != nullptr ? importRouteDirect : importRouteHostBlocked);
routed = true;
}
}
}
if (!routed) noteImportRoute(importRouteOther);
const auto tiledScratch = directImport == nullptr ? std::make_shared<DeviceBuffer>(context, static_cast<std::size_t>(guestBytes), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT) : nullptr;
detiler.BeginBatch();
auto* recorder = recorderFor(context);
@@ -460,8 +460,9 @@ std::uint32_t GcnLevelSlices(std::uint32_t slices, std::uint32_t level, bool pow
}
std::vector<TileMipLayout> ComputeGcnMipLayout(TextureTileMode tileMode, std::uint32_t format, std::uint32_t width, std::uint32_t height, std::uint32_t pitch, bool pow2Pad, std::uint32_t mipCount, bool linearGeneral, std::uint32_t layers, bool volume) {
std::vector<TileMipLayout> ComputeGcnMipLayout(TextureTileMode tileMode, std::uint32_t format, std::uint32_t width, std::uint32_t height, std::uint32_t pitch, bool pow2Pad, std::uint32_t mipCount, bool linearGeneral, std::uint32_t layers, bool volume, std::uint32_t samples) {
Require(layers != 0, "a PS4 surface has at least one slice");
Require(samples == 1u || (IsGcnDepthTiled(tileMode) && mipCount == 1u && layers == 1u && !volume), "a PS4 multisampled surface is modeled only as one level and one slice in a depth tile mode");
Require(!linearGeneral || tileMode == TextureTileMode::kLinear, "LINEAR_GENERAL is a linear layout");
Require(width != 0 && height != 0 && pitch >= width, "cannot compute the mip layout of an empty PS4 texture");
Require(mipCount != 0 && mipCount <= 16u, "texture mip count is out of range");
@@ -482,7 +483,7 @@ std::vector<TileMipLayout> ComputeGcnMipLayout(TextureTileMode tileMode, std::ui
std::uint32_t macroWidth = 0;
std::uint32_t splitSlices = 1;
if (IsGcnMacroTiled(tileMode)) {
const auto geometry = GcnTiling(tileMode, bytes);
const auto geometry = GcnTiling(tileMode, bytes, samples);
macro = level == 0 || (rowElements >= geometry.blockWidth && rows >= geometry.blockHeight);
if (macro) {
macroWidth = geometry.blockWidth;
@@ -508,9 +509,9 @@ std::vector<TileMipLayout> ComputeGcnMipLayout(TextureTileMode tileMode, std::ui
mip.height = TexelLevelDimension(height, level, texelHeight);
mip.blocksPerRow = macro ? rowElements / macroWidth : micro ? rowElements / 8u : rowElements;
mip.gcnMicroTiled = micro && IsGcnMacroTiled(tileMode);
mip.gcnSplitStride = splitSlices > 1u ? static_cast<std::uint32_t>(static_cast<std::uint64_t>(rowElements) * rows * bytes / splitSlices) : 0u;
mip.pitchBytes = rowElements * bytes;
mip.tiledSize = static_cast<std::uint64_t>(rowElements) * rows * bytes;
mip.gcnSplitStride = splitSlices > 1u ? static_cast<std::uint32_t>(static_cast<std::uint64_t>(rowElements) * rows * bytes * samples / splitSlices) : 0u;
mip.pitchBytes = rowElements * bytes * samples;
mip.tiledSize = static_cast<std::uint64_t>(rowElements) * rows * bytes * samples;
mip.linearSize = static_cast<std::uint64_t>(mip.pitchBytes) * mip.height;
mip.tiledOffset = offset;
mip.linearOffset = linearOffset;
@@ -523,11 +524,13 @@ std::vector<TileMipLayout> ComputeGcnMipLayout(TextureTileMode tileMode, std::ui
return mips;
}
GcnTileGeometry GcnTiling(TextureTileMode tileMode, std::uint32_t bytesPerElement) {
GcnTileGeometry GcnTiling(TextureTileMode tileMode, std::uint32_t bytesPerElement, std::uint32_t samples) {
Require(IsGcnTiled(tileMode), "PS4 tile geometry needs a PS4 tiled mode");
Require(std::has_single_bit(bytesPerElement) && bytesPerElement <= 16u, "unsupported bytes per element for PS4 tiling");
Require(samples == 1u || ((samples == 2u || samples == 4u || samples == 8u) && IsGcnDepthTiled(tileMode)), "PS4 multisampled tiling is only modeled for 2, 4 or 8 samples in a depth tile mode");
const auto x = [](std::uint32_t bit) { return 1u << bit; };
const auto y = [](std::uint32_t bit) { return 1u << (12u + bit); };
const auto s = [](std::uint32_t bit) { return 1u << (GcnSampleShift + bit); };
const std::array<std::uint32_t, 6> thin{x(0), y(0), x(1), y(1), x(2), y(2)};
const std::array<std::array<std::uint32_t, 6>, 5> display{{
{x(0), x(1), x(2), y(1), y(0), y(2)}, {x(0), x(1), x(2), y(0), y(1), y(2)}, {x(0), x(1), y(0), x(2), y(1), y(2)},
@@ -535,8 +538,12 @@ GcnTileGeometry GcnTiling(TextureTileMode tileMode, std::uint32_t bytesPerElemen
}};
const auto log2Bytes = static_cast<std::uint32_t>(std::countr_zero(bytesPerElement));
const bool displayOrder = tileMode == TextureTileMode::kGcnDisplay1D || tileMode == TextureTileMode::kGcnDisplay2D || tileMode == TextureTileMode::kGcnDisplayPrt || tileMode == TextureTileMode::kGcnDisplay2DPrt;
const auto& order = displayOrder ? display[log2Bytes] : thin;
const auto microBytes = 64u * bytesPerElement;
const auto log2Samples = static_cast<std::uint32_t>(std::countr_zero(samples));
std::array<std::uint32_t, 9> order{};
for (std::uint32_t bit = 0; bit < log2Samples; ++bit) order[bit] = s(bit);
std::ranges::copy(displayOrder ? display[log2Bytes] : thin, order.begin() + log2Samples);
const auto orderBits = log2Samples + 6u;
const auto microBytes = 64u * bytesPerElement * samples;
GcnTileGeometry geometry{};
if (tileMode == TextureTileMode::kGcnThick1D) {
const auto z = [](std::uint32_t bit) { return 1u << (24u + bit); };
@@ -547,7 +554,7 @@ GcnTileGeometry GcnTiling(TextureTileMode tileMode, std::uint32_t bytesPerElemen
}
if (IsGcnMicroTiled(tileMode)) {
geometry = {microBytes, 8u, 8u, {}};
for (std::uint32_t bit = 0; bit < order.size(); ++bit) geometry.equation[log2Bytes + bit] = order[bit];
for (std::uint32_t bit = 0; bit < orderBits; ++bit) geometry.equation[log2Bytes + bit] = order[bit];
return geometry;
}
struct MacroMode { std::uint32_t bankHeight; std::uint32_t banks; std::uint32_t aspect; };
@@ -581,7 +588,8 @@ GcnTileGeometry GcnTiling(TextureTileMode tileMode, std::uint32_t bytesPerElemen
geometry.blockBytes = macroBytes * pipes * mode.banks;
const auto elementBits = log2TileBytes - log2Bytes;
geometry.splitSlices = microBytes / tileBytes;
for (auto bit = elementBits; bit < order.size(); ++bit) geometry.splitMasks[bit - elementBits] = order[bit];
Require(orderBits - elementBits <= geometry.splitMasks.size(), "a PS4 depth micro tile split into more than 16 slices is not implemented");
for (auto bit = elementBits; bit < orderBits; ++bit) geometry.splitMasks[bit - elementBits] = order[bit];
std::array<std::uint32_t, 16> inner{};
for (std::uint32_t bit = 0; bit < elementBits; ++bit) inner[log2Bytes + bit] = order[bit];
auto innerBits = log2TileBytes;
@@ -665,10 +673,23 @@ SurfaceGeometry describeGcnVolume(const GuestTextureResource& descriptor) {
return geometry;
}
SurfaceGeometry describeGcnMultisampled(const GuestTextureResource& descriptor) {
Require(IsGcnDepthTiled(descriptor.tileMode), "PS4 multisampled textures outside the depth tile modes are not implemented");
Require(descriptor.samples == 2u || descriptor.samples == 4u || descriptor.samples == 8u, "a PS4 multisampled texture of " + std::to_string(descriptor.samples) + " samples is not implemented");
Require(descriptor.mipCount == 1u && descriptor.baseArray == 0u && descriptor.depthOrLastArray == 0u, "PS4 multisampled texture mip levels or array layers are not implemented");
Require(!IsBlockCompressed(descriptor.format), "a PS4 multisampled block-compressed texture is not implemented");
SurfaceGeometry geometry;
geometry.mips = ComputeGcnMipLayout(descriptor.tileMode, descriptor.format, descriptor.width, descriptor.height, descriptor.gcnPitch, descriptor.gcnPow2Pad, 1u, false, 1u, false, descriptor.samples);
geometry.guestBytes = geometry.mips[0].tiledSize;
geometry.layerBytes = geometry.guestBytes;
geometry.sliceLinearBytes = geometry.mips[0].linearSize;
return geometry;
}
SurfaceGeometry describeGcnSurface(const GuestTextureResource& descriptor) {
Require(!IsGcnThick(descriptor.tileMode) || descriptor.dimension == TextureDimension::k3D, "PS4 thick tile modes are only implemented for 3D textures");
if (IsGcnThick(descriptor.tileMode)) return describeGcnVolume(descriptor);
Require(descriptor.dimension != TextureDimension::k2DMsaa, "PS4 multisampled textures are not implemented");
if (descriptor.dimension == TextureDimension::k2DMsaa) return describeGcnMultisampled(descriptor);
const bool volume = descriptor.dimension == TextureDimension::k3D;
const bool layered = volume || descriptor.dimension == TextureDimension::k2DArray || descriptor.dimension == TextureDimension::k1DArray || descriptor.dimension == TextureDimension::kCube;
SurfaceGeometry geometry;
@@ -94,6 +94,7 @@ struct UnitShadow {
// whether a slab -> import copy was recorded at that generation.
std::vector<std::uint64_t> generation;
std::vector<std::uint8_t> published;
std::vector<std::vector<std::pair<std::uint32_t, std::uint32_t>>> produced;
// Slab k covers units [k * SlabUnits(), (k + 1) * SlabUnits()), made on demand; a failed
// allocation is not retried before the noted present.
std::vector<std::shared_ptr<ShadowSlab>> slabs;
@@ -114,6 +115,17 @@ struct UnitShadow {
}
};
void AddProducedSpan(std::vector<std::pair<std::uint32_t, std::uint32_t>>& spans, std::uint32_t from, std::uint32_t to) {
auto at = std::lower_bound(spans.begin(), spans.end(), std::pair{from, to});
if (at != spans.begin() && std::prev(at)->second >= from) --at;
while (at != spans.end() && at->first <= to) {
from = std::min(from, at->first);
to = std::max(to, at->second);
at = spans.erase(at);
}
spans.insert(at, {from, to});
}
struct Shadows {
SlimMutex mutex;
std::map<std::uint64_t, std::shared_ptr<UnitShadow>> byBase;
@@ -197,6 +209,7 @@ std::shared_ptr<UnitShadow> findOrCreate(Shadows& registry, const Context& conte
const auto units = (import.base + import.bytes - shadow->base + UnitBytes - 1) / UnitBytes;
shadow->generation.assign(static_cast<std::size_t>(units), 0);
shadow->published.assign(static_cast<std::size_t>(units), 0);
shadow->produced.assign(static_cast<std::size_t>(units), {});
const auto slabs = (units + SlabUnits() - 1) / SlabUnits();
shadow->slabs.assign(static_cast<std::size_t>(slabs), nullptr);
shadow->slabFailedUntil.assign(static_cast<std::size_t>(slabs), 0);
@@ -435,21 +448,28 @@ std::size_t publishUnits(const std::shared_ptr<UnitShadow>& shadow, std::uint64_
++ended;
continue;
}
const auto [begin, end] = shadow->UnitRange(unit);
if (end <= begin) continue;
const VkBufferCopy region{(unit - slab->firstUnit) * UnitBytes + (begin - shadow->UnitBegin(unit)), begin - shadow->importBase + shadow->importLead, end - begin};
if (!copies.empty() && copies.back().slab == slab && copies.back().regions.back().dstOffset + copies.back().regions.back().size == region.dstOffset) {
copies.back().regions.back().size += region.size;
ranges.back().second = end;
} else {
if (copies.empty() || copies.back().slab != slab) copies.push_back({slab, {}});
copies.back().regions.push_back(region);
ranges.emplace_back(begin, end);
const auto [unitBegin, unitEnd] = shadow->UnitRange(unit);
bool copied = false;
for (const auto& [from, to] : shadow->produced[unit]) {
const auto begin = std::max(unitBegin, shadow->UnitBegin(unit) + from);
const auto end = std::min(unitEnd, shadow->UnitBegin(unit) + to);
if (end <= begin) continue;
const VkBufferCopy region{(unit - slab->firstUnit) * UnitBytes + (begin - shadow->UnitBegin(unit)), begin - shadow->importBase + shadow->importLead, end - begin};
if (!copies.empty() && copies.back().slab == slab && copies.back().regions.back().dstOffset + copies.back().regions.back().size == region.dstOffset) {
copies.back().regions.back().size += region.size;
ranges.back().second = end;
} else {
if (copies.empty() || copies.back().slab != slab) copies.push_back({slab, {}});
copies.back().regions.push_back(region);
ranges.emplace_back(begin, end);
}
bytes += end - begin;
copied = true;
}
shadow->published[unit] = 1;
++ended;
if (!copied) continue;
slab->lastUse = Recorder::Presents();
bytes += end - begin;
++units;
}
shadow->liveUnits -= ended;
@@ -917,10 +937,15 @@ void MarkShadowed(const HostImport& import, std::span<const ShadowedRange> range
++lost;
continue;
}
const auto from = static_cast<std::uint32_t>(std::max(begin, shadow->UnitBegin(unit)) - shadow->UnitBegin(unit));
const auto to = static_cast<std::uint32_t>(std::min(end, shadow->UnitBegin(unit + 1)) - shadow->UnitBegin(unit));
auto& produced = shadow->produced[unit];
if (!shadow->Live(unit)) {
++shadow->liveUnits;
turnedLive = true;
produced.clear();
}
AddProducedSpan(produced, from, to);
shadow->generation[unit] = generation;
shadow->published[unit] = 0;
current->lastUse = present;
@@ -3599,7 +3599,7 @@ void importWatchTests() {
#endif
}
void sparseImportedHeapTests(const Context& context, const BdaTestAccess& access) {
void sparseImportedHeapTests(const Context& context, const BdaTestAccess& access, bool allowWritableImports) {
#ifndef _WIN32
if (!GuestWriteWatch::GuestWriteWatchAvailable_nid_postfix()) {
std::cout << "write watch unavailable: sparse imported heaps not tested\n";
@@ -3657,16 +3657,29 @@ void sparseImportedHeapTests(const Context& context, const BdaTestAccess& access
memory.WriteBack();
}
{
GuestBufferMemory written(importing);
auto writing = importing;
if (!allowWritableImports) writing.hostImportAlignment = 0;
const auto beforeWrite = MirrorCounters();
GuestBufferMemory written(writing);
written.AddWritable(base, 2 * bytes);
written.Upload(false);
std::uint32_t adjustment = 0;
const auto view = written.Descriptor(base, 2 * bytes, adjustment);
Require(view.buffer != imported->buffer && view.range == bytes && MirrorCounters().rebuilds == before.rebuilds + 1, "a sparse writable descriptor bound a shortened import");
access.bytes(view.buffer)[view.offset] = std::byte{0x68};
Require(view.range == bytes && adjustment == 0, "a sparse writable descriptor did not end at the committed prefix");
const bool direct = view.buffer == imported->buffer;
if (direct) {
Require(allowWritableImports && written.CopiedBytes() == 0 && MirrorCounters().rebuilds == beforeWrite.rebuilds, "a sparse writable import copied or rebuilt its heap mirror");
} else {
Require(MirrorCounters().rebuilds == before.rebuilds + 1, "a sparse writable fallback changed its heap-mirror rebuild count");
}
auto gpuBytes = direct ? std::span<std::byte>(reinterpret_cast<std::byte*>(imported->base), static_cast<std::size_t>(imported->bytes)) : access.bytes(view.buffer);
Require(view.offset <= gpuBytes.size() && view.range <= gpuBytes.size() - view.offset, "a sparse writable view extends past its bound fixture memory");
if (direct) Require(imported->base + view.offset == base, "a sparse writable import does not address its guest prefix");
gpuBytes[view.offset] = std::byte{0x68};
guest[8] = 0x79;
written.WriteBack();
Require(guest[0] == 0x68 && guest[8] == 0x79, "the sparse writable fallback lost a GPU store or rolled back a CPU store");
Require(guest[0] == 0x68 && guest[8] == 0x79, "the sparse writable binding lost a GPU store or rolled back a CPU store");
std::cout << "Sparse writable heap " << (direct ? "direct import" : "mirror fallback") << " preserved interleaved writes\n";
}
mutation = GuestAllocations::GuestAllocationsBegin_nid_postfix();
GuestAllocations::GuestAllocationsRemove_nid_postfix(mutation, guest);
@@ -3685,6 +3698,7 @@ void sparseImportedHeapTests(const Context& context, const BdaTestAccess& access
#else
static_cast<void>(context);
static_cast<void>(access);
static_cast<void>(allowWritableImports);
#endif
}
@@ -5652,7 +5666,8 @@ void RunBdaResourceTests(const Context& context, const BdaTestAccess& access) {
importReportFloorTests(context, false, failure);
}
importReportRefusalMemoryTests(context, access);
sparseImportedHeapTests(context, access);
sparseImportedHeapTests(context, access, true);
sparseImportedHeapTests(context, access, false);
importEvictionFramesTests(context);
heapMirrorTests(context, access);
partialHeapImportBudgetTests(context, access);
+123 -16
View File
@@ -241,6 +241,27 @@ void PolygonPrimitiveTests() {
Require(indexedState.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN && indexedState.primitiveRestart, "indexed polygon decoding did not keep primitive restart");
}
void VertexControlTests() {
const auto vertexControl = [](std::uint32_t word) {
auto queue = makeState();
queue.context[0x1b3] = 2;
queue.context[0x1b4] = 2;
queue.context[0x2f9] = word;
return queue;
};
for (const auto word : {0x29u, 0x2bu, 0x2du, 0x2fu}) {
const auto queue = vertexControl(word);
const auto rejection = AgcDriver::Graphics::DrawRejection(queue, false);
Require(rejection.empty(), "a PA_SU_VTX_CNTL rounding mode failed the draw precheck: " + rejection);
static_cast<void>(AgcDriver::Graphics::DecodeState(queue));
}
for (const auto word : {0x28u, 0x2cu, 0x21u, 0x25u, 0x31u, 0x39u, 0x69u}) {
const auto queue = vertexControl(word);
Require(AgcDriver::Graphics::DrawRejection(queue, false).find("nonstandard pixel center or vertex quantization") != std::string::npos, "the draw precheck accepted an unsupported PA_SU_VTX_CNTL");
expectFailure([&] { AgcDriver::Graphics::DecodeState(queue); }, "nonstandard pixel center or vertex quantization");
}
}
void vertexPointListTests() {
const auto pointState = [](std::uint32_t control, std::uint32_t size, std::uint32_t limits) {
auto queue = makeState();
@@ -328,6 +349,25 @@ void retainedPixelStageTests() {
Require(!PixelProgramSkipped(queue), "an enabled high render target lost its pixel program");
queue.context[0x8e] = queue.context[0x8f] = 0;
}
queue.context[0x8e] = queue.context[0x8f] = 0xffffffffu;
Require(!PixelProgramSkipped(queue), "a pixel program writing a bound color target was skipped");
const std::uint32_t boundInfo = queue.context.at(0x31c);
for (std::uint32_t slot = 0; slot < 8; ++slot) queue.context[0x31c + 0xfu * slot] = 0;
Require(PixelProgramSkipped(queue), "reset-value color masks ran an unused pixel program with no color target bound");
Require(DrawRejection(queue, true).empty(), "an unused pixel program under reset-value color masks with no color target bound was rejected");
queue.context[0x203] = 0x400;
Require(!PixelProgramSkipped(queue), "EXEC_ON_NOOP was skipped with no color target bound");
queue.context[0x203] = 0;
queue.context[0x31c + 0xfu * 7u] = boundInfo;
Require(!PixelProgramSkipped(queue), "a pixel program writing a bound high color target was skipped");
queue.context[0x31c + 0xfu * 7u] = 0;
queue.context[0x31c] = boundInfo;
queue.context[0x8e] = queue.context[0x8f] = 0xf0u;
Require(PixelProgramSkipped(queue), "color masks enabling only a target without a format ran an unused pixel program beside a bound target");
queue.context[0x31c + 0xfu] = boundInfo;
Require(!PixelProgramSkipped(queue), "a pixel program writing the second bound color target was skipped");
queue.context[0x31c + 0xfu] = 0;
queue.context[0x8e] = queue.context[0x8f] = 0;
queue.context[0x3] = 0;
queue.context[0xb4] = std::bit_cast<std::uint32_t>(0.0f);
queue.context[0xb5] = std::bit_cast<std::uint32_t>(1.0f);
@@ -2327,6 +2367,12 @@ void ReversedComponentOrderBlendTests() {
const auto separate = DecodeState(constantQueue(0x60130001u));
Require(separate.reversedBlend == 0u && separate.blends.at(0).srcColorBlendFactor == VK_BLEND_FACTOR_CONSTANT_COLOR && separate.blends.at(0).dstColorBlendFactor == VK_BLEND_FACTOR_ZERO && separate.blends.at(0).srcAlphaBlendFactor == VK_BLEND_FACTOR_ONE && separate.blends.at(0).dstAlphaBlendFactor == VK_BLEND_FACTOR_ZERO, "a constant alpha factor of the alpha equation did not reach the host color equation of the reversed target");
Require(separate.blendConstants[0] == constants[3] && separate.blendConstants[1] == 1.0f && separate.blendConstants[2] == 1.0f, "the host blend constants of a constant alpha factor do not weigh the alpha channel alone");
auto nanRgb = constantQueue(0x60130001u);
for (std::uint32_t i = 0; i < 3; ++i) nanRgb.context[0x105 + i] = 0x7fc00000u;
Require(DecodeState(nanRgb).blendConstants[0] == constants[3], "a reversed target's constant alpha factor read unused RGB CB_BLEND registers");
nanRgb.context[0x1e0] = 0x40000504u;
nanRgb.context[0x108] = 0x7fc00000u;
Require(DecodeState(nanRgb).blendConstants == std::array<float, 4>{}, "a non-constant reversed target blend read CB_BLEND registers");
const auto colored = DecodeState(constantQueue(0x40000e0du));
Require(colored.blends.at(0).srcColorBlendFactor == VK_BLEND_FACTOR_CONSTANT_COLOR && colored.blends.at(0).dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR && colored.blends.at(0).srcAlphaBlendFactor == VK_BLEND_FACTOR_CONSTANT_ALPHA && colored.blends.at(0).dstAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA, "a constant color factor and its complement did not share the host blend constants");
for (std::uint32_t component = 0; component < 4; ++component) Require(colored.blendConstants[component] == constantOf(component), "the blend constants of a reversed target did not follow its component mapping");
@@ -2500,7 +2546,25 @@ void Color565TargetTests() {
Require(AgcDriver::Graphics::DecodeState(queue).blendConstants == std::array<float, 4>{0.375f, 0.25f, 0.125f, 0.5f}, "a 5_6_5 target with the standard component order did not exchange the constants of a ONE_MINUS_CONSTANT_COLOR destination factor");
queue.context[0x8e] = 0x3u;
const auto partial = AgcDriver::Graphics::DecodeState(queue).blendConstants;
Require(partial[1] == 0.25f && partial[2] == 0.125f && partial[3] == 0.5f, "a 5_6_5 target with the standard component order writing only X and Y did not take the constants of its written channels from their exports");
Require(partial == std::array<float, 4>{0.0f, 0.25f, 0.125f, 0.0f}, "a 5_6_5 target with the standard component order writing only X and Y did not take the constants of its written channels from their exports");
for (std::uint32_t i = 0; i < 4; ++i) queue.context[0x105 + i] = 0x7fc00000u;
queue.context[0x1e0] = 0x40000504u;
Require(AgcDriver::Graphics::DecodeState(queue).blendConstants == std::array<float, 4>{}, "non-constant blending read unused CB_BLEND registers");
queue.context[0x1e0] = 0x40000d4du;
Require(AgcDriver::Graphics::DecodeState(queue).blendConstants == std::array<float, 4>{}, "MIN blending read unused CB_BLEND registers");
queue.context[0x8e] = 0x2u;
queue.context[0x1e0] = (1u << 30u) | 13u;
queue.context[0x106] = std::bit_cast<std::uint32_t>(0.25f);
Require(AgcDriver::Graphics::DecodeState(queue).blendConstants == std::array<float, 4>{0.0f, 0.25f, 0.0f, 0.0f}, "masked constant blending read masked-off CB_BLEND registers");
queue.context[0x8e] = 0x7u;
queue.context[0x107] = 0;
expectFailure([&] { AgcDriver::Graphics::DecodeState(queue); }, "non-finite register at DWORD 261");
queue.context[0x8e] = 0xfu;
queue.context[0x1e0] = 0x40001413u;
queue.context[0x108] = std::bit_cast<std::uint32_t>(0.5f);
Require(AgcDriver::Graphics::DecodeState(queue).blendConstants == std::array<float, 4>{0.0f, 0.0f, 0.0f, 0.5f}, "constant alpha blending read unused RGB CB_BLEND registers");
queue.context[0x108] = 0x7f800000u;
expectFailure([&] { AgcDriver::Graphics::DecodeState(queue); }, "non-finite register at DWORD 264");
queue.context[0x8e] = 0xfu;
queue.context[0x1e0] = 0;
for (const auto& [number, swap] : {std::pair{1u, 2u}, std::pair{4u, 0u}, std::pair{0u, 1u}, std::pair{0u, 3u}}) {
@@ -2509,6 +2573,25 @@ void Color565TargetTests() {
}
}
void SingleChannelSwapBlendTests() {
auto queue = makeState();
for (const auto swap : {1u, 2u}) {
queue.context[0x31c] = (queue.context[0x31c] & ~((0x1fu << 2u) | (7u << 8u) | (3u << 11u))) | (1u << 2u) | (swap << 11u);
queue.context[0x8e] = 0xfu;
for (std::uint32_t i = 0; i < 4; ++i) queue.context[0x105 + i] = std::bit_cast<std::uint32_t>(float(i + 1) / 8.0f);
queue.context[0x1e0] = (1u << 30u) | 13u;
Require(AgcDriver::Graphics::DecodeState(queue).blendConstants == std::array<float, 4>{0.125f, 0.25f, 0.375f, 0.5f}, "a one-channel target with component swap did not keep the constant-colour blend registers");
queue.context[0x1e0] = (1u << 30u) | (14u << 8u);
Require(AgcDriver::Graphics::DecodeState(queue).blendConstants == std::array<float, 4>{0.125f, 0.25f, 0.375f, 0.5f}, "a one-channel target with component swap did not keep the destination constant-colour blend registers");
queue.context[0x1e0] = 0x6001000du;
queue.context[0x105] = 0x7fc00000u;
expectFailure([&] { AgcDriver::Graphics::DecodeState(queue); }, "non-finite register at DWORD 261");
for (std::uint32_t i = 0; i < 4; ++i) queue.context[0x105 + i] = 0x7fc00000u;
queue.context[0x1e0] = 0x40000504u;
Require(AgcDriver::Graphics::DecodeState(queue).blendConstants == std::array<float, 4>{}, "non-constant blending on a swapped one-channel target read unused CB_BLEND registers");
}
}
void Color1555TargetTests() {
auto queue = makeState();
queue.context[0x31c] = (queue.context[0x31c] & ~((0x1fu << 2u) | (7u << 8u) | (3u << 11u))) | (17u << 2u);
@@ -4619,11 +4702,21 @@ void multisampleTests() {
}
queue.context[0x32b] = queue.context[0x31c] ^ (1u << 8u);
expectFailure([&] { DecodeColorMetadataPass(queue); }, "different formats or extents");
for (const auto [packedInfo, name] : {std::pair{6u << 2u, "10_11_11 unorm"}, std::pair{(7u << 2u) | (7u << 8u) | (2u << 11u) | 0x40000u, "11_11_10 float"}}) {
auto packed = rasterizedResolve;
for (const auto offset : {0x31cu, 0x32bu}) packed.context[offset] = (packed.context[offset] & ~0x41f7cu) | packedInfo;
expectFailure([&] { DecodeColorMetadataPass(packed); }, std::string("CB resolves of ") + name + " color targets");
}
auto packed = rasterizedResolve;
for (const auto offset : {0x31cu, 0x32bu}) packed.context[offset] = (packed.context[offset] & ~0x41f7cu) | (6u << 2u);
expectFailure([&] { DecodeColorMetadataPass(packed); }, "CB resolves of 10_11_11 unorm color targets");
for (const auto offset : {0x31cu, 0x32bu}) packed.context[offset] = (packed.context[offset] & ~0x41f7cu) | (7u << 2u) | (7u << 8u) | (2u << 11u) | 0x40000u;
const auto floatPass = DecodeColorMetadataPass(packed);
Require(floatPass.has_value() && floatPass->mode == ColorMetadataPass::Mode::Resolve && floatPass->source.has_value() && floatPass->source->packing == ShaderRecompiler::ColorExportPacking::Float11_11_10 && floatPass->source->samples == 2 && floatPass->targets.size() == 1, "a CB resolve of an 11_11_10 float target was refused");
auto swapped = packed;
swapped.context[0x32b] &= ~(3u << 11u);
expectFailure([&] { DecodeColorMetadataPass(swapped); }, "11_11_10 float color targets of different layouts");
auto unormDestination = packed;
unormDestination.context[0x32b] = (unormDestination.context[0x32b] & ~0x41f7cu) | (6u << 2u);
expectFailure([&] { DecodeColorMetadataPass(unormDestination); }, "11_11_10 float color targets of different layouts");
auto unormSource = packed;
unormSource.context[0x31c] = (unormSource.context[0x31c] & ~0x41f7cu) | (6u << 2u);
expectFailure([&] { DecodeColorMetadataPass(unormSource); }, "11_11_10 float color targets of different layouts");
auto uintSource = rasterizedResolve;
for (const auto offset : {0x31cu, 0x32bu}) uintSource.context[offset] = (uintSource.context[offset] & ~0x700u) | (4u << 8u);
const auto uintPass = DecodeColorMetadataPass(uintSource);
@@ -5888,8 +5981,8 @@ void InitialContextTests() {
Require(queue.context.at(0x3) == 0 && queue.context.at(0x8) == 0 && queue.context.at(0x9) == 0x3f800000, "depth bounds overlap render override");
Require(queue.context.at(0x2dc) == 0xaa00 && queue.context.at(0x313) == 0x6000 && queue.context.at(0x2f9) == 0x2d, "initial raster controls are incomplete");
Require(queue.context.at(0x30e) == 0xffffffff && queue.context.at(0x30f) == 0xffffffff, "initial sample mask excludes samples");
Require(queue.context.at(0x206) == 0, "the initial viewport control is not its reset value");
Require(queue.context.at(0x8e) == 0xffffffffu && queue.context.at(0x8f) == 0xffffffffu, "the initial color masks are not their reset values");
Require(queue.context.at(0x206) == 0x43f, "the initial viewport control does not apply the viewport transform");
Require(queue.context.at(0x8e) == 0 && queue.context.at(0x8f) == 0, "the initial color masks write color");
queue.userConfig[0x242] = 4;
for (const auto offset : {0x2d5u, 0x204u, 0x8eu, 0x8fu, 0x1c3u, 0x1c5u, 0x31cu, 0x3b0u, 0x3b8u, 0x318u, 0x390u, 0x10fu, 0x110u, 0x111u, 0x112u, 0x113u, 0x114u, 0xb4u, 0xb5u}) queue.context.at(offset) = configured.context.at(offset);
const auto state = AgcDriver::Graphics::DecodeState(queue);
@@ -5898,21 +5991,27 @@ void InitialContextTests() {
const auto offsetX = std::bit_cast<float>(static_cast<std::uint32_t>(queue.context.at(0x110)));
const auto scaleY = std::bit_cast<float>(static_cast<std::uint32_t>(queue.context.at(0x111)));
const auto offsetY = std::bit_cast<float>(static_cast<std::uint32_t>(queue.context.at(0x112)));
Require(state.viewport.x == offsetX - scaleX && state.viewport.y == offsetY - scaleY && state.viewport.width == 2 * scaleX && state.viewport.height == 2 * scaleY, "a draw that programmed its viewport transform but never wrote the viewport control lost the transform");
Require(AgcDriver::Graphics::DrawRejection(queue, false).find("PA_CL_VTE_CNTL") == std::string::npos, "a draw with the reset viewport control was rejected for its viewport control");
Require(state.viewport.x == offsetX - scaleX && state.viewport.y == offsetY - scaleY && state.viewport.width == 2 * scaleX && state.viewport.height == 2 * scaleY, "a draw with the initial viewport control lost its viewport transform");
{
queue.context[0x111] = std::bit_cast<std::uint32_t>(-scaleY);
const auto flipped = AgcDriver::Graphics::DecodeState(queue);
Require(flipped.viewport.y == offsetY + scaleY && flipped.viewport.height == -2 * scaleY, "a negative Y scale was dropped for a draw that never wrote the viewport control");
Require(flipped.viewport.y == offsetY + scaleY && flipped.viewport.height == -2 * scaleY, "a negative Y scale was dropped for a draw with the initial viewport control");
queue.context[0x111] = std::bit_cast<std::uint32_t>(scaleY);
}
Require(queue.context.at(0x206) == 0x43f, "initial homogeneous viewport mode changed");
queue.context[0x206] = 0;
{
const auto programmed = AgcDriver::Graphics::DecodeState(queue);
Require(programmed.viewport.x == offsetX - scaleX && programmed.viewport.y == offsetY - scaleY && programmed.viewport.width == 2 * scaleX && programmed.viewport.height == 2 * scaleY, "a draw that wrote a zero viewport control lost its programmed viewport transform");
std::array<std::uint32_t, 6> words{};
for (std::uint32_t word = 0; word < 6; ++word) {
words[word] = queue.context.at(0x10f + word);
queue.context[0x10f + word] = word % 2 == 0 ? 0x3f800000u : 0u;
}
const auto untouched = AgcDriver::Graphics::DecodeState(queue);
Require(untouched.viewport.x == 0.0f && untouched.viewport.y == 0.0f && untouched.viewport.width == static_cast<float>(untouched.renderExtent.width) && untouched.viewport.height == static_cast<float>(untouched.renderExtent.height), "a draw that never programmed a viewport did not get a viewport covering its render target");
const auto untransformed = AgcDriver::Graphics::DecodeState(queue);
Require(untransformed.viewport.x == 0.0f && untransformed.viewport.y == 0.0f && untransformed.viewport.width == static_cast<float>(untransformed.renderExtent.width) && untransformed.viewport.height == static_cast<float>(untransformed.renderExtent.height), "a draw without a viewport transform did not get a viewport covering its render target");
Require(AgcDriver::Graphics::DrawRejection(queue, false).find("PA_CL_VTE_CNTL") == std::string::npos, "a draw with the viewport transform disabled was rejected for its viewport control");
for (std::uint32_t word = 0; word < 6; ++word) queue.context[0x10f + word] = words[word];
queue.context[0x111] = std::bit_cast<std::uint32_t>(scaleY);
}
for (const auto control : {0x3fu, 0x43eu, 0x53fu, 0x63fu, 0x8000043fu}) {
queue.context[0x206] = control;
@@ -5925,7 +6024,7 @@ void InitialContextTests() {
queue.context.erase(0x2dc);
expectFailure([&] { AgcDriver::Graphics::DecodeState(queue); }, "missing register");
queue.ClearContext();
Require(queue.context.at(0x2dc) == 0xaa00 && queue.context.at(0x318) == 0 && queue.context.at(0x8e) == 0xffffffffu && queue.context.at(0x206) == 0, "clear did not restore controls, color masks and viewport control");
Require(queue.context.at(0x2dc) == 0xaa00 && queue.context.at(0x318) == 0 && queue.context.at(0x8e) == 0 && queue.context.at(0x206) == 0x43f, "clear did not restore controls, color masks and viewport control");
Require(!queue.context.contains(0xdead), "unknown context register acquired a default");
}
@@ -10501,7 +10600,8 @@ void rectListTests() {
auto explicitInterpolation = BuildRectListShaders(vertex, fragment, target);
Require(!explicitInterpolation.control.spirv.empty() && !explicitInterpolation.evaluation.spirv.empty(), "rect-list shaders for an explicitly interpolated parameter are empty");
fragment.fragmentParameters[0].custom = true;
expectFailure([&] { static_cast<void>(BuildRectListShaders(vertex, fragment, target)); }, "per-vertex interpolation");
const auto passThrough = BuildRectListShaders(vertex, fragment, target);
Require(std::ranges::equal(passThrough.control.spirv.Words(), explicitInterpolation.control.spirv.Words()) && std::ranges::equal(passThrough.evaluation.spirv.Words(), explicitInterpolation.evaluation.spirv.Words()), "a pass-through parameter read per vertex does not pass the rectangle's corners like an explicitly interpolated one");
fragment.fragmentParameters[0].perVertex = false;
fragment.fragmentParameters[0].custom = false;
vertex.parameterExports.clear();
@@ -15426,6 +15526,11 @@ int main(int argc, char** argv) {
DualSourceBlendTests();
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--vertex-control-state") {
VertexControlTests();
std::cout << "Vertex control state checks passed\n";
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--depth-bounds-state") {
DepthBoundsBiasTests();
ReadOnlyDepthBoundsComparisonTests();
@@ -15511,6 +15616,7 @@ int main(int argc, char** argv) {
DisabledColorTests();
OpaqueDestinationAlphaTests();
Color565TargetTests();
SingleChannelSwapBlendTests();
Color1555TargetTests();
BlendBypassTests();
UnclampedNormalizedColorTests();
@@ -15547,6 +15653,7 @@ int main(int argc, char** argv) {
NggVertexWorkgroupTests();
inactiveVertexPointSizeTests();
PolygonPrimitiveTests();
VertexControlTests();
vertexPointListTests();
TuningFieldTests();
ShaderDeclaredPixelInputTests();
@@ -97,6 +97,46 @@ void rejectFields(const Fields& f, std::string_view reason) {
}
static void RunRememberedRejectionTests() {
Fields invalid;
invalid.cornerSample = true;
const auto invalidWords = pack(invalid);
std::string thrown;
try {
DecodeTextureResource(invalidWords);
} catch (const std::runtime_error& error) {
thrown = error.what();
}
Require(!thrown.empty(), "a corner-sampled T# must be rejected");
const auto before = RememberedTextureRejectionCount();
const auto first = TryDecodeTextureResource(invalidWords);
Require(first.rejection != nullptr && *first.rejection == thrown, "TryDecodeTextureResource must report the decoder's own rejection message");
const auto remembered = RememberedTextureRejectionCount();
Require(remembered == (before >= RememberedTextureRejections ? 1u : before + 1u), "a rejected T# must be remembered once");
const auto repeat = TryDecodeTextureResource(invalidWords);
Require(repeat.rejection == first.rejection, "a repeated rejected T# must return the remembered rejection");
Require(RememberedTextureRejectionCount() == remembered, "a repeated rejected T# must not be remembered twice");
const auto valid = TryDecodeTextureResource(pack(Fields{}));
Require(valid.rejection == nullptr && valid.resource.baseAddress == DecodeTextureResource(pack(Fields{})).baseAddress, "a valid T# must decode as DecodeTextureResource does");
Require(RememberedTextureRejectionCount() == remembered, "a valid T# must not be remembered");
ShaderRecompiler::SetGcnGuestShaders(true);
const auto gcn = TryDecodeTextureResource(invalidWords);
ShaderRecompiler::SetGcnGuestShaders(false);
Require(gcn.rejection != nullptr && gcn.rejection != first.rejection, "the remembered rejection of an RDNA T# must not answer for the same words decoded as a PS4 T#");
for (std::uint64_t base = 1; base <= RememberedTextureRejections + 1u; ++base) {
Fields distinct = invalid;
distinct.base40 = base;
Require(TryDecodeTextureResource(pack(distinct)).rejection != nullptr, "a corner-sampled T# must be rejected at every base address");
Require(RememberedTextureRejectionCount() <= RememberedTextureRejections, "remembered T# rejections must stay within their bound");
}
const auto again = TryDecodeTextureResource(invalidWords);
Require(again.rejection != nullptr && *again.rejection == thrown, "a T# rejected again after the remembered rejections were dropped must report the same message");
}
static void RunR128TextureTests() {
constexpr std::array<std::uint32_t, 8> streamed{0xa0c18800u, 0xcad00000u, 0x01ffc1ffu, 0x905b2facu, 0u, 0u, 0u, 0u};
const auto view = DecodeTextureResource(streamed);
@@ -810,4 +850,21 @@ void RunGuestTextureResourceTests() {
Require(gcnResult.baseAddress == 0x100000u, "a PS4 T# took MTYPE_L2 above its 38-bit base as address bits");
Require(gcnNull, "a PS4 T# with a zero base and MTYPE_L2 set was not classified as null");
Require(gcnAllocation && *gcnAllocation == gcnResult.baseAddress, "a PS4 T# with MTYPE_L2 set looked up its allocation at an address other than its 38-bit base");
const std::array<std::pair<std::uint32_t, TextureTileMode>, 4> gcnOneDArrayModes{{{5u, TextureTileMode::kGcnThin1D}, {9u, TextureTileMode::kGcnDisplay1D}, {13u, TextureTileMode::kGcnThin1D}, {14u, TextureTileMode::kGcnThin2D}}};
for (const auto& [tilingIndex, expectedMode] : gcnOneDArrayModes) {
const std::array<std::uint32_t, 8> gcnOneDArray{0x00001000u, 0x00a000c0u, 0x0000003fu, 0xc0000facu | (tilingIndex << 20u), 0x000fe000u, 3u << 13u, 0u, 0u};
auto gcnTwoDArray = gcnOneDArray;
gcnTwoDArray[3] = (gcnOneDArray[3] & 0x0fffffffu) | 0xd0000000u;
ShaderRecompiler::SetGcnGuestShaders(true);
const auto oneD = DecodeTextureResource(ShaderRecompiler::GcnImageWords(std::span<const std::uint32_t, 8>(gcnOneDArray)));
const auto twoD = DecodeTextureResource(ShaderRecompiler::GcnImageWords(std::span<const std::uint32_t, 8>(gcnTwoDArray)));
ShaderRecompiler::SetGcnGuestShaders(false);
Require(oneD.dimension == TextureDimension::k1DArray && oneD.tileMode == expectedMode && oneD.width == 64u && oneD.height == 1u && oneD.depthOrLastArray == 3u && oneD.gcnPitch == 128u, "a PS4 1D array T# with a tiled PS4 tile mode index decoded incorrectly");
const auto oneDGeometry = DescribeSurface(oneD);
const auto twoDGeometry = DescribeSurface(twoD);
Require(oneDGeometry.layers == 4u && oneDGeometry.layers == twoDGeometry.layers && oneDGeometry.layerBytes == twoDGeometry.layerBytes && oneDGeometry.guestBytes == twoDGeometry.guestBytes && oneDGeometry.mips.size() == twoDGeometry.mips.size() && oneDGeometry.mips[0].tiledSize == twoDGeometry.mips[0].tiledSize && oneDGeometry.mips[0].pitchBytes == twoDGeometry.mips[0].pitchBytes, "a PS4 1D array was not laid out like the height-1 2D array the PS4 tile mode table describes");
}
RunRememberedRejectionTests();
}
@@ -81,6 +81,86 @@ void BlocksCrossIntoLibstdcxx() {
}
}
#ifdef _WIN32
void* (*volatile OperatorNew)(std::size_t) = &::operator new;
void (*volatile SizedDelete)(void*, std::size_t) noexcept = &::operator delete;
void SizedDeletesBetweenGranulesComeBack() {
for (std::size_t size = 8; size <= 1024; ++size) {
if (size % 16 == 0) continue;
auto* first = static_cast<unsigned char*>(OperatorNew(size));
FillAndVerify(first, size, 5);
SizedDelete(first, size);
auto* again = static_cast<unsigned char*>(OperatorNew(size));
Check(again == first, "a block freed with its size comes back for that size");
Check(_msize(again) >= size, "a reused block holds the bytes asked for");
FillAndVerify(again, size, 6);
SizedDelete(again, size);
}
for (std::size_t size = 1025; size < 1040; ++size) {
void* room = OperatorNew(1024);
auto* big = static_cast<unsigned char*>(OperatorNew(size));
SizedDelete(big, size);
auto* reused = static_cast<unsigned char*>(OperatorNew(1024));
Check(reused == big, "a block less than a granule over the largest class serves that class");
Check(_msize(reused) >= 1024, "a block kept in the largest class holds it");
FillAndVerify(reused, 1024, 10);
SizedDelete(reused, 1024);
SizedDelete(room, 1024);
}
}
void OwnBlocksServeTheirWholeGranule() {
for (std::size_t size = 8; size <= 1024; ++size) {
if (size % 16 == 0) continue;
const auto whole = (size + 15) / 16 * 16;
auto* block = static_cast<unsigned char*>(OperatorNew(size));
SizedDelete(block, size);
auto* larger = static_cast<unsigned char*>(OperatorNew(whole));
Check(larger == block, "a block freed with fewer bytes than its granule still serves the whole granule");
Check(_msize(larger) >= whole, "a block reused for its whole granule holds it");
FillAndVerify(larger, whole, 7);
SizedDelete(larger, whole);
}
}
void LibstdcxxBlocksServeOnlyTheirBytes() {
using Allocation = void* (*)(std::size_t);
const auto runtime = GetModuleHandleW(L"libstdc++-6.dll");
const auto allocate = runtime != nullptr ? reinterpret_cast<Allocation>(reinterpret_cast<void*>(GetProcAddress(runtime, "_Znwy"))) : nullptr;
Check(allocate != nullptr, "libstdc++-6.dll exports operator new");
if (allocate == nullptr) return;
std::size_t exact = 0;
for (std::size_t bytes = 8; bytes <= 1024; ++bytes) {
if (bytes % 16 == 0) continue;
const auto whole = (bytes + 15) / 16 * 16;
void* roomInClass = OperatorNew(whole);
void* roomBelow = whole > 16 ? OperatorNew(whole - 16) : nullptr;
void* made = allocate(bytes);
if (_msize(made) == bytes) ++exact;
SizedDelete(made, bytes);
void* same = OperatorNew(bytes);
Check(same == made, "a block libstdc++ made comes back for the bytes it holds");
SizedDelete(same, bytes);
auto* larger = static_cast<unsigned char*>(OperatorNew(whole));
const bool fits = _msize(larger) >= whole;
Check(fits, "a block libstdc++ made is never handed out for more bytes than it holds");
if (fits) FillAndVerify(larger, whole, 8);
if (roomBelow != nullptr) {
auto* lower = static_cast<unsigned char*>(OperatorNew(whole - 16));
Check(lower == made, "a block too small for its class serves the class below");
Check(_msize(lower) >= whole - 16, "the class below fits in the block");
FillAndVerify(lower, whole - 16, 9);
SizedDelete(lower, whole - 16);
SizedDelete(roomBelow, whole - 16);
}
SizedDelete(larger, whole);
SizedDelete(roomInClass, whole);
}
Check(exact > 0, "the C runtime heap reports the exact size libstdc++ asked for");
}
#endif
void BlocksMoveBetweenThreads() {
constexpr int perThread = 20000;
std::vector<std::unique_ptr<std::uint64_t[]>> made(perThread);
@@ -188,6 +268,11 @@ int main() {
EverySizeRoundTrips();
SizedDeletesKeepTheirClass();
BlocksCrossIntoLibstdcxx();
#ifdef _WIN32
SizedDeletesBetweenGranulesComeBack();
OwnBlocksServeTheirWholeGranule();
LibstdcxxBlocksServeOnlyTheirBytes();
#endif
BlocksMoveBetweenThreads();
BlocksFlowToAnotherThread();
ThreadsEndWithCachedBlocks();
+50 -1
View File
@@ -1103,7 +1103,35 @@ void testEventWrite() {
expectFailure([] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x139, 0x1004, 0x2}), 0); }, "misaligned occlusion counter");
expectFailure([] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x139, 0, 0}), 0); }, "null or misaligned occlusion counter");
expectFailure([] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x139, 0x1000}), 0); }, "packet size");
expectFailure([] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x138, 0x1000, 0x2}), 0); }, "event type 56");
const auto sampleControl = [](std::uint32_t blocks) { return (blocks << 11u) | (2u << 9u); };
AgcDriver::Pm4::Validate(makePacket(0x46, {0x138, sampleControl(0xffu), 0}), 0);
AgcDriver::Pm4::Validate(makePacket(0x46, {0x138, sampleControl(0xffffu), 0}), 0);
AgcDriver::Pm4::Validate(makePacket(0x46, {0x138, sampleControl(0u), 0}), 0);
expectFailure([&] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x138, sampleControl(0xffu), 0}), 0x20); }, "compute queue");
expectFailure([&] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x038, sampleControl(0xffu), 0}), 0); }, "pixel pipe statistics control event index");
expectFailure([&] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x138, sampleControl(0xffu)}), 0); }, "packet size");
for (const auto bits : {1u, 4u, 1u << 27u, 1u << 31u}) {
expectFailure([&] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x138, sampleControl(0xffu) | bits, 0}), 0); }, "PIXEL_PIPE_STAT_CONTROL reserved bits");
}
expectFailure([&] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x138, sampleControl(0xffu), 1}), 0); }, "PIXEL_PIPE_STAT_CONTROL reserved bits");
for (const auto counter : {1u, 3u, 4u, 7u}) {
expectFailure([&] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x138, sampleControl(0xffu) | (counter << 3u), 0}), 0); }, "occlusion count 0");
}
for (const auto stride : {0u, 1u, 3u}) {
expectFailure([&] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x138, (0xffu << 11u) | (stride << 9u), 0}), 0); }, "strides other than 128 bits");
}
AgcDriver::QueueState controlled;
check(controlled.sampleDumpBlocks == AgcDriver::AllSampleDumpBlocks, "a queue must dump every counter block before any PIXEL_PIPE_STAT_CONTROL");
execute(controlled, makePacket(0x46, {0x138, sampleControl(0xffu), 0}));
check(controlled.sampleDumpBlocks == 0xffu, "PIXEL_PIPE_STAT_CONTROL must select the counter blocks a dump writes");
execute(controlled, makePacket(0x46, {0x138, sampleControl(0x8001u), 0}));
check(controlled.sampleDumpBlocks == 0x8001u, "PIXEL_PIPE_STAT_CONTROL must replace the previous block selection");
execute(controlled, makePacket(0x12, {0}));
check(controlled.sampleDumpBlocks == 0x8001u, "CLEAR_STATE must keep the PIXEL_PIPE_STAT_CONTROL block selection");
execute(controlled, makePacket(0x10, {0, 0}, 0x68));
check(controlled.sampleDumpBlocks == 0x8001u, "a CONTEXT_STATE clear must keep the PIXEL_PIPE_STAT_CONTROL block selection");
execute(controlled, makePacket(0x10, {0}, 0x24));
check(controlled.sampleDumpBlocks == AgcDriver::AllSampleDumpBlocks, "a dispatch reset must restore every counter block");
for (const auto bit : {0x40u, 0x80u, 0x800u, 0x80000000u}) {
expectFailure([&] { AgcDriver::Pm4::Validate(makePacket(0x46, {0x410u | bit}), 0); }, "reserved bits");
}
@@ -1227,6 +1255,27 @@ void testPredication() {
check(AgcDriver::Pm4::PredicationPasses(state), "samples in the last block must run draw-visible packets");
counters[3] &= ~ready;
expectFailure([&] { static_cast<void>(AgcDriver::Pm4::PredicationPasses(state)); }, "never written");
std::fill(std::begin(counters), std::end(counters), 0u);
for (std::size_t db = 0; db < 8; ++db) counters[db * 2] = counters[db * 2 + 1] = ready | (40u + db);
execute(state, makePacket(0x46, {0x138, (0xffu << 11u) | (2u << 9u), 0}));
check(!AgcDriver::Pm4::PredicationPasses(state), "Z-pass predication must read only the counter blocks PIXEL_PIPE_STAT_CONTROL enables");
counters[15] += 5;
check(AgcDriver::Pm4::PredicationPasses(state), "samples in the last enabled block must run draw-visible packets");
counters[15] &= ~ready;
expectFailure([&] { static_cast<void>(AgcDriver::Pm4::PredicationPasses(state)); }, "never written");
std::fill(std::begin(counters), std::end(counters), 0u);
counters[0] = counters[1] = counters[30] = counters[31] = ready | 60u;
execute(state, makePacket(0x46, {0x138, (0x8001u << 11u) | (2u << 9u), 0}));
check(!AgcDriver::Pm4::PredicationPasses(state), "Z-pass predication must skip the unwritten blocks between enabled ones");
counters[3] = ready | 9u;
check(!AgcDriver::Pm4::PredicationPasses(state), "samples in a disabled block must not count");
counters[31] += 7;
check(AgcDriver::Pm4::PredicationPasses(state), "samples in the highest enabled block must run draw-visible packets");
counters[30] &= ~ready;
expectFailure([&] { static_cast<void>(AgcDriver::Pm4::PredicationPasses(state)); }, "never written");
execute(state, makePacket(0x46, {0x138, 2u << 9u, 0}));
expectFailure([&] { static_cast<void>(AgcDriver::Pm4::PredicationPasses(state)); }, "no counter block enabled");
execute(state, makePacket(0x46, {0x138, (AgcDriver::AllSampleDumpBlocks << 11u) | (2u << 9u), 0}));
execute(state, setPredication(0, false, nullptr));
expectFailure([&] { AgcDriver::Pm4::Validate(setPredication(2, true, &flag[0]), 0); }, "primitive-count predication");
expectFailure([&] { AgcDriver::Pm4::Validate(setPredication(5, true, &flag[0]), 0); }, "invalid predication operation");
@@ -2,6 +2,7 @@
#include "prx/libkernel/include/Api.hpp"
#include "prx/libSceAgc/Command/include/Packet.hpp"
#include "prx/libSceAgcDriver/Execution/include/PipelineLinkOptimization.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp"
#include "Triangle_frag_spv.h"
#include "Triangle_vert_spv.h"
#include "prx/libSceAgcDriver/Graphics/include/VertexInput.hpp"
@@ -49,6 +50,7 @@
#include "SampleLod_spv.h"
#include "BufferUpdate_spv.h"
#include "SampleArray_spv.h"
#include "SampleImportOrigin_spv.h"
#include "Cover_vert_spv.h"
#include "Cover_frag_spv.h"
#include "VertexRange_vert_spv.h"
@@ -2635,6 +2637,8 @@ void storeRunTests(const Device& device, Recorder& recorder) {
HostImportFor(context, address, bytes);
}
std::atomic<std::uint64_t> multisampleUseWalks{0};
#ifdef _WIN32
bool deferredSettleTests(const Device& device) {
using namespace AgcDriver::GuestMemory;
@@ -3402,8 +3406,16 @@ bool rewatchUnderImageTests(const Device& device) {
return true;
}
bool settleInitialDccTests(const Device& device) {
bool settleInitialDccTests(const Device& device, bool ordered = false) {
using namespace AgcDriver::GuestMemory;
struct ResetObservationHook {
~ResetObservationHook() { SetObservationHookForTest(nullptr); }
} resetObservationHook;
if (ordered) {
SetObservationHookForTest(+[](int point) {
if (point == 1) multisampleUseWalks.fetch_add(1, std::memory_order_relaxed);
});
}
const auto& base = device.GetContext();
constexpr std::size_t unit = 65536;
constexpr std::size_t tail = 0x4000;
@@ -3615,12 +3627,14 @@ bool settleInitialDccTests(const Device& device) {
}
const auto before = HostImportSettles();
Require(!fmaskAlone || before.submitted == quiet.submitted, "(m) a settle read was submitted between the FMASK's import and the target's first use");
if (ordered) multisampleUseWalks.store(0, std::memory_order_relaxed);
std::string refusal;
try {
Require(MultisampleTargetView(context, target) != VK_NULL_HANDLE, "(m) the multisampled DCC target has no view");
} catch (const std::exception& error) {
refusal = error.what();
}
const auto firstUseWalks = ordered ? multisampleUseWalks.load(std::memory_order_relaxed) : 0;
const auto after = HostImportSettles();
const auto* settled = ExistingHostImportFor(context, address, importBytes);
const char* name = kind == Case::Pending ? "a pending settle" : kind == Case::PartialBlock ? "an import of whole and partial 64 KiB blocks" : kind == Case::ComparedNeighbour ? "a compared import in its last 64 KiB block" : kind == Case::DeferredOff ? "deferred settles off" : kind == Case::UnwatchedKeys ? "explicitly unwatched DCC keys" : kind == Case::PendingFmask ? "an eight-sample target whose color and FMASK imports both have pending settles" : "an eight-sample target whose FMASK alone has a pending settle";
@@ -3632,6 +3646,12 @@ bool settleInitialDccTests(const Device& device) {
return;
}
Require(refusal.empty(), std::string("(m) an initial multisampled DCC import over ") + name + " was refused: " + refusal);
Require(!ordered || firstUseWalks != 0, std::string("(m) the first ordered use over ") + name + " reused another caller's observation");
if (ordered) {
multisampleUseWalks.store(0, std::memory_order_relaxed);
Require(MultisampleTargetView(context, target) != VK_NULL_HANDLE, std::string("(m) the repeated multisampled DCC target over ") + name + " has no view");
Require(multisampleUseWalks.load(std::memory_order_relaxed) == 0, std::string("(m) the repeated ordered use over ") + name + " walked its own unchanged observations again");
}
Require(!fmaskAlone || (after.submitted - before.submitted == 1 && after.rewatched - before.rewatched == 1), "(m) the first use over a pending FMASK settle alone submitted " + std::to_string(after.submitted - before.submitted) + " settle reads, not the FMASK's alone");
const bool settledBefore = kind == Case::PartialBlock;
Require((settledBefore ? after.submitted == before.submitted : after.submitted > before.submitted && after.rewatched > before.rewatched) && Watched(address, importBytes) && settled != nullptr && !settled->unwatched, std::string("(m) the initial DCC import over ") + name + " did not settle the import and return it to the write watch");
@@ -3694,8 +3714,147 @@ bool settleInitialDccTests(const Device& device) {
std::cout << "initial multisampled DCC over a pending settle tests passed\n";
return true;
}
bool settleInitialDccCommitterTests(const Device& device) {
bool passed = false;
std::exception_ptr failure;
auto& committer = AgcDriver::DriverDetail::DrawPipeline::Queue0();
committer.Enqueue(AgcDriver::DriverDetail::DrawPipeline::CommitKind::Draw, [&] {
try {
AgcDriver::GuestMemory::BumpCollectEpoch();
Require(AgcDriver::GuestMemory::CollectEpoch() != 0, "the initial DCC committer fixture has no collect epoch");
passed = settleInitialDccTests(device, true);
} catch (...) {
failure = std::current_exception();
}
}, {}, 0, {}, {}, true);
committer.Drain(AgcDriver::DriverDetail::DrawPipeline::DrainReason::Submission);
committer.Stop();
if (failure) std::rethrow_exception(failure);
return passed;
}
#endif
bool multisampleUseCollectTests(const Device& device) {
using namespace AgcDriver::GuestMemory;
const auto& base = device.GetContext();
if (!device.Graphics() || (base.limits.framebufferColorSampleCounts & VK_SAMPLE_COUNT_4_BIT) == 0 || !WriteWatched()) {
std::cout << "skipped, watched memory or four-sample colour targets unavailable\n";
return false;
}
const auto run = [&](bool ordered, std::uint32_t samples) {
auto context = base;
Recorder recorder(context);
recorder.Activate();
constexpr std::size_t unit = 65536;
constexpr std::size_t bytes = 4 * unit;
auto* block = static_cast<std::uint8_t*>(AllocateWatched(bytes, unit));
Require(block != nullptr, "cannot allocate the multisample-use collect fixture");
struct Release {
const Context& context;
Recorder& recorder;
void* block;
~Release() {
SetObservationHookForTest(nullptr);
{
std::lock_guard gpu(GpuMutex());
recorder.Sync();
ClearMultisampleTargets(context.device);
recorder.FlushDeferredReleases();
}
{
GuestAllocations::Mutation mutation;
mutation.Remove(block);
}
ReleaseWatched(block, bytes);
}
} release{context, recorder, block};
std::memset(block, 0, bytes);
{
GuestAllocations::Mutation mutation;
mutation.Add(block, bytes, true, true, true);
}
std::unique_lock gpu(GpuMutex());
ColorTarget target{};
target.address = reinterpret_cast<std::uint64_t>(block);
target.surfaceAddress = target.address;
target.extent = {32, 32};
target.surfaceExtent = target.extent;
target.format = VK_FORMAT_R8G8B8A8_UNORM;
target.elementBytes = 4;
target.samples = samples;
target.tileMode = ColorTileMode::RenderTarget;
target.dccPipeAligned = true;
target.bytes = MultisampledColorBytes(target);
Require(target.bytes <= unit, "multisample-use colour plane exceeds the fixture");
target.dccAddress = target.address + unit;
const auto dccBytes = MultisampledDccBytes(target);
Require(dccBytes <= unit, "multisample-use DCC plane exceeds the fixture");
std::memset(block + unit, 0xc0, dccBytes);
if (samples == 8) {
target.cmaskAddress = target.address + 2 * unit;
target.cmaskBytes = CmaskBytes(target.extent.width, target.extent.height);
target.cmaskFastClear = true;
target.fmaskAddress = target.address + 3 * unit;
std::memset(block + 2 * unit, 0xcc, static_cast<std::size_t>(target.cmaskBytes));
std::memset(block + 3 * unit, 0x11, unit);
}
Require(MultisampleTargetView(context, target) != VK_NULL_HANDLE, "the multisample-use fixture has no view");
SetObservationHookForTest(+[](int point) {
if (point == 1) multisampleUseWalks.fetch_add(1, std::memory_order_relaxed);
});
if (ordered && CollectEpoch() == 0) {
std::uint64_t zeroEpochWalks = 0;
for (int use = 0; use != 2; ++use) {
multisampleUseWalks.store(0, std::memory_order_relaxed);
MultisampleTargetView(context, target);
const auto walked = multisampleUseWalks.load(std::memory_order_relaxed);
Require(walked != 0, "a GPU use without a collect epoch reused an observation");
zeroEpochWalks += walked;
}
std::cout << "multisample-use samples=" << samples << " zero-epoch walks=" << zeroEpochWalks << '\n';
}
BumpCollectEpoch();
multisampleUseWalks.store(0, std::memory_order_relaxed);
MultisampleTargetView(context, target);
Require(multisampleUseWalks.load(std::memory_order_relaxed) != 0, "the first ordered use did not observe memory");
multisampleUseWalks.store(0, std::memory_order_relaxed);
MultisampleTargetView(context, target);
const auto repeated = multisampleUseWalks.load(std::memory_order_relaxed);
const bool memoized = ordered && CollectEpoch() != 0;
Require(memoized ? repeated == 0 : repeated != 0, memoized ? "a repeated GPU use walked unchanged multisample planes again" : "a use without GPU epoch reuse skipped a fresh observation");
auto* changed = reinterpret_cast<volatile std::uint8_t*>(samples == 8 ? target.fmaskAddress : target.dccAddress);
*changed = samples == 8 ? 0x11 : 0xc0;
if (ordered) BumpCollectEpoch();
std::string refusal;
try {
MultisampleTargetView(context, target);
} catch (const std::exception& error) {
refusal = error.what();
}
const auto expected = samples == 8 ? "writes to a resident native FMASK" : "writes to a resident multisampled DCC target";
Require(refusal.find(expected) != std::string::npos, "a same-value CPU store over a multisample plane was missed: " + refusal);
std::cout << "multisample-use samples=" << samples << " ordered=" << ordered << " repeat walks=" << repeated << ", same-value CPU store refused\n";
};
std::vector<std::uint32_t> sampleCounts{4};
if (base.storageImageMultisample && (base.limits.framebufferColorSampleCounts & VK_SAMPLE_COUNT_8_BIT) != 0) sampleCounts.push_back(8);
std::exception_ptr failure;
auto& committer = AgcDriver::DriverDetail::DrawPipeline::Queue0();
committer.Enqueue(AgcDriver::DriverDetail::DrawPipeline::CommitKind::Draw, [&] {
try {
Require(CollectEpoch() == 0, "the draw-committer fixture did not start at collect epoch zero");
for (const auto samples : sampleCounts) run(true, samples);
} catch (...) {
failure = std::current_exception();
}
}, {}, 0, {}, {}, true);
committer.Drain(AgcDriver::DriverDetail::DrawPipeline::DrainReason::Submission);
committer.Stop();
if (failure) std::rethrow_exception(failure);
for (const auto samples : sampleCounts) run(false, samples);
return true;
}
void remappedImportTests(const Device& device) {
const auto& context = device.GetContext();
if (context.hostImportAlignment == 0) {
@@ -4789,7 +4948,7 @@ bool bdaStagingTests(const Device& device, Recorder& recorder) {
bool carriedShadowTests(const Device& device, Recorder& recorder) {
const auto& context = device.GetContext();
if (context.hostImportAlignment == 0) {
std::cout << "host imports unavailable: carried shadows not tested\n";
std::cout << "skipped, host imports unavailable: carried shadows not tested\n";
return false;
}
constexpr std::size_t bytes = 4u << 20u;
@@ -4815,11 +4974,11 @@ bool carriedShadowTests(const Device& device, Recorder& recorder) {
}
const Cleanup cleanup{context, block};
if (HostImportFor(context, address, bytes) == nullptr) {
std::cout << "host import of the test block refused: carried shadows not tested\n";
std::cout << "skipped, host import of the test block refused: carried shadows not tested\n";
return false;
}
if (!AgcDriver::GuestMemory::Watched(address, bytes)) {
std::cout << "host imports are compared, not watched: carried shadows not tested\n";
std::cout << "skipped, host imports are compared, not watched: carried shadows not tested\n";
return false;
}
const auto element = address + 4096;
@@ -5108,7 +5267,13 @@ bool sparseRunImportTests(const Device& device, bool copied) {
Require(std::memcmp(readback.Bytes().data(), guest, committed) == 0, "the GPU does not read a sparse run heap's bytes through its in-place view");
});
upload(true, 0, [&](GuestBufferMemory& memory) {
Require(!bound(memory, address, heap), "a written sparse run heap is bound in place");
if (const auto* import = run(); import != nullptr) {
std::uint32_t adjustment = 0;
const auto view = memory.Descriptor(address, heap, adjustment);
Require(view.buffer == import->buffer && view.range == committed && adjustment == 0, "a written sparse run heap with an import is not bound in place from its run's import");
} else {
Require(!bound(memory, address, heap), "a written sparse run heap without an import is bound in place");
}
});
upload(false, 5 * unit, [&](GuestBufferMemory& memory) {
Require(!bound(memory, address, heap), "a sparse run heap with a view past its run is bound in place");
@@ -5158,6 +5323,123 @@ bool sparseRunImportTests(const Device& device, bool copied) {
return true;
}
bool pendingUploadGpuCopy(const Device& device, Recorder& recorder, std::size_t producedOffset, std::size_t producedBytes) {
const auto& context = device.GetContext();
const auto alignment = context.limits.minStorageBufferOffsetAlignment;
if (alignment < 8 || alignment > 256) {
std::cout << "storage buffer offset alignment " << alignment << ": uploads behind a pending GPU write not tested\n";
return false;
}
constexpr std::size_t bytes = 4u << 20u;
void* block = context.hostImportAlignment != 0 ? AllocateWatched(bytes, 65536) : nullptr;
if (block == nullptr) {
std::cout << "host imports or write watching unavailable: uploads behind a pending GPU write not tested\n";
return false;
}
struct Release {
void* block;
~Release() { ReleaseWatched(block, bytes); }
} release{block};
auto* guest = static_cast<std::uint8_t*>(block);
for (std::size_t at = 0; at < bytes; ++at) guest[at] = static_cast<std::uint8_t>(at * 5u + 1u);
const auto address = reinterpret_cast<std::uint64_t>(block);
{
GuestAllocations::Mutation mutation;
mutation.Add(block, bytes, true, true, true);
}
struct Unregister {
const Context& context;
void* block;
~Unregister() {
{
GuestAllocations::Mutation mutation;
mutation.Remove(block);
}
HostImportFor(context, reinterpret_cast<std::uint64_t>(block), bytes);
}
} unregister{context, block};
const auto* import = HostImportFor(context, address, bytes);
if (import == nullptr) {
std::cout << "host import of the watched block refused: uploads behind a pending GPU write not tested\n";
return false;
}
constexpr std::size_t viewOffset = 4096 + 4;
constexpr std::size_t viewBytes = 3u << 20u;
Require(producedOffset >= viewOffset && producedOffset + producedBytes <= viewOffset + viewBytes, "the producer's write is not inside the test view");
const auto view = address + viewOffset;
const auto produced = address + producedOffset;
Require((view - import->base) % alignment != 0 && (view - import->base) % 4 == 0, "the test view is not a DWORD-aligned view off the storage buffer offset alignment");
std::vector<std::uint8_t> expected(guest + viewOffset, guest + viewOffset + viewBytes);
auto source = std::make_shared<Buffer>(context, producedBytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
auto* pattern = reinterpret_cast<std::uint8_t*>(source->Bytes().data());
for (std::size_t at = 0; at < producedBytes; ++at) {
pattern[at] = static_cast<std::uint8_t>((at * 7u + 3u) ^ 0xa5u);
expected[producedOffset - viewOffset + at] = pattern[at];
}
{
std::lock_guard lock(GpuMutex());
recorder.Sync();
const auto commands = recorder.Commands();
CopyBuffer(context, commands, source->Handle(), 0, import->buffer, HostImportOffset(*import, produced), producedBytes);
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_TRANSFER_READ_BIT);
recorder.Keep(source);
recorder.NotePendingWrite(produced, producedBytes);
}
Require(recorder.OpenWriteOverlaps(produced, producedBytes), "the producer's GPU write is not pending in the open batch");
{
GuestBufferMemory memory(context);
memory.AddReadable(view, viewBytes);
const auto waitsBefore = Recorder::ThreadHookWaits();
const auto submissionsBefore = recorder.Submissions();
const auto notedBefore = Recorder::ReadCounts().noted;
{
std::lock_guard lock(GpuMutex());
memory.Upload(false);
}
const auto waits = Recorder::ThreadHookWaits() - waitsBefore;
const auto submissions = recorder.Submissions() - submissionsBefore;
const auto shape = "a misaligned " + std::to_string(viewBytes >> 20u) + " MiB region over a pending " + std::to_string(producedBytes >> 10u) + " KiB GPU write";
Require(waits == 0 && submissions == 0 && recorder.OpenWriteOverlaps(produced, producedBytes), "the upload of " + shape + " waited for it on the CPU (" + std::to_string(waits) + " flush-hook waits, " + std::to_string(submissions) + " submissions)");
Require(memory.CopiedBytes() == viewBytes, "the upload of " + shape + " copied " + std::to_string(memory.CopiedBytes()) + " bytes, not the region's " + std::to_string(viewBytes));
const auto noted = Recorder::ReadCounts().noted - notedBefore;
const auto copy = recorder.DescribePendingRead(view, viewBytes);
const bool copiedOnGpu = noted == 1 && copy.has_value() && copy->open && copy->kind == Recorder::ReadKind::GpuCopy;
const bool wholeRegion = recorder.PendingReadOverlaps(view, 4) && recorder.PendingReadOverlaps(view + viewBytes - 4, 4) && !recorder.PendingReadOverlaps(view - 4, 4) && !recorder.PendingReadOverlaps(view + viewBytes, 4);
Require(copiedOnGpu && wholeRegion, "the upload of " + shape + " did not copy the region once on the GPU (" + std::to_string(noted) + " reads noted)");
auto readback = std::make_shared<Buffer>(context, viewBytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT);
{
std::lock_guard lock(GpuMutex());
std::uint32_t adjustment = 0;
const auto info = memory.Descriptor(view, viewBytes, adjustment);
const auto commands = recorder.Commands();
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT);
CopyBuffer(context, commands, info.buffer, info.offset + adjustment, readback->Handle(), 0, viewBytes);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT);
recorder.Keep(readback);
recorder.Submit();
}
device.WaitQueue();
{
std::lock_guard lock(GpuMutex());
recorder.Sync();
}
const auto* read = reinterpret_cast<const std::uint8_t*>(readback->Bytes().data());
const auto mismatch = std::mismatch(expected.begin(), expected.end(), read);
Require(mismatch.first == expected.end(), "the region uploaded behind the pending GPU write misses the producer's bytes at byte " + std::to_string(mismatch.first - expected.begin()) + " of the view");
Require(std::memcmp(guest + producedOffset, pattern, producedBytes) == 0, "the producer's GPU write did not reach guest memory");
}
std::cout << "uploads behind a pending " << (producedBytes >> 10u) << " KiB GPU write tests passed\n";
return true;
}
bool pendingUploadGpuCopyTests(const Device& device, Recorder& recorder) {
return pendingUploadGpuCopy(device, recorder, 1u << 20u, 1u << 20u);
}
bool pendingUploadGpuCopyBytesTests(const Device& device, Recorder& recorder) {
return pendingUploadGpuCopy(device, recorder, 2u << 20u, 4096);
}
void misalignedRegionTests(const Device& device, Recorder& recorder) {
const auto& context = device.GetContext();
const auto alignment = context.limits.minStorageBufferOffsetAlignment;
@@ -5575,7 +5857,14 @@ void imageTableFirstLayerRevalidateTests(const Device& device, Recorder& recorde
}
}
bool SkipOnCpuVulkan(const Device& device, const char* what) {
if (device.Properties().deviceType != VK_PHYSICAL_DEVICE_TYPE_CPU) return false;
std::cout << "skipped, unproven on CPU Vulkan (llvmpipe): " << what << "\n";
return true;
}
void drawSnapshotReuseTests(const Device& device, Recorder& recorder) {
if (SkipOnCpuVulkan(device, "an unchanged draw input was copied again (draw snapshot reuse)")) return;
const auto& context = device.GetContext();
constexpr std::size_t bytes = 65536;
void* block = context.hostImportAlignment != 0 ? AllocateWatched(bytes, 65536) : nullptr;
@@ -6519,6 +6808,7 @@ void vertexWindowMirrorTests(const Device& device) {
using namespace AgcDriver::GuestMemory;
using Use = Recorder::SnapshotUse;
if (!Recorder::DrawInputMirrors() || !WriteWatched()) return;
if (SkipOnCpuVulkan(device, "a kept vertex window was not mirrored in device memory")) return;
constexpr std::size_t bytes = 65536;
void* block = AllocateWatched(bytes, 65536);
struct Release {
@@ -6559,6 +6849,7 @@ VKAPI_ATTR void VKAPI_CALL tightMemoryBudget(VkPhysicalDevice, VkPhysicalDeviceM
}
void drawInputMirrorTests(const Device& device) {
if (Recorder::DrawInputMirrors() && SkipOnCpuVulkan(device, "a reused draw input came back without its device-local mirror")) return;
if (!DmaBufDeviceOpens()) {
std::cout << "skipped, host imports are unavailable: /dev/udmabuf cannot be opened; draw input mirrors not tested\n";
return;
@@ -6655,6 +6946,7 @@ void drawInputMirrorTests(const Device& device) {
}
void drawInputReuseTests(const Device& device, Recorder& recorder) {
if (SkipOnCpuVulkan(device, "an unchanged draw input was copied again (draw input reuse)")) return;
if (!DmaBufDeviceOpens()) {
std::cout << "skipped, host imports are unavailable: /dev/udmabuf cannot be opened; draw input reuse not tested\n";
return;
@@ -6921,6 +7213,111 @@ void drawInputInPlaceTests(const Device& device, Recorder& recorder, bool copied
Require(range.reused && !range.highest.has_value(), "an empty in-place index range was scanned again");
}
bool indexBehindWriterTests(const Device& device, Recorder& recorder) {
auto context = device.GetContext();
constexpr std::size_t bytes = 65536;
void* block = context.hostImportAlignment != 0 ? AllocateWatched(bytes, 65536) : nullptr;
if (block == nullptr) {
std::cout << "host imports or write watching unavailable: index ranges behind a pending GPU writer not tested\n";
return false;
}
struct Release {
void* block;
~Release() { ReleaseWatched(block, bytes); }
} release{block};
const auto address = reinterpret_cast<std::uint64_t>(block);
{
GuestAllocations::Mutation mutation;
mutation.Add(block, bytes, true, true, true);
}
struct Unregister {
const Context& context;
void* block;
~Unregister() {
{
GuestAllocations::Mutation mutation;
mutation.Remove(block);
}
HostImportFor(context, reinterpret_cast<std::uint64_t>(block), bytes);
}
} unregister{context, block};
const auto* whole = HostImportFor(context, address, bytes);
if (whole == nullptr) {
std::cout << "host import of the watched block refused: index ranges behind a pending GPU writer not tested\n";
return false;
}
context.recorder = &recorder;
context.drawInputsInPlace = false;
context.limits.maxDrawIndexedIndexValue = 0xffffffffu;
recorder.Sync();
const bool configured = RuntimeSwitches::Set(RuntimeSwitch::IndexInPlaceBehindWriter);
struct Restore {
bool configured;
~Restore() { RuntimeSwitches::Assign(RuntimeSwitch::IndexInPlaceBehindWriter, configured); }
} restore{configured};
const auto attempt = [&](const Context& with, std::uint64_t at, std::uint32_t indexSize, bool vertexAttributes, bool meshStage, std::uint32_t firstVertex) {
IndexBehindWriter outcome = IndexBehindWriter::Count;
const auto* import = InPlaceIndexBehindWriter(with, at, 256, indexSize, vertexAttributes, meshStage, false, firstVertex, &outcome);
return std::pair<const HostImport*, IndexBehindWriter>(import, outcome);
};
const auto indices = address + 4096;
recorder.NotePendingWrite(indices, 16);
Require(recorder.PendingWriteOverlaps(indices, 256), "the pending GPU write over the index range was not noted");
RuntimeSwitches::Assign(RuntimeSwitch::IndexInPlaceBehindWriter, false);
const auto switchedOff = IndexBehindWriterCounts();
const auto off = attempt(context, indices, 4, false, false, 0);
Require(IndexBehindWriterCounts() == switchedOff, "an attempt without APS5_INDEX_IN_PLACE_BEHIND_WRITER was counted");
Require(off.first == nullptr && off.second == IndexBehindWriter::Off, "an index range behind a pending GPU writer was bound in place without APS5_INDEX_IN_PLACE_BEHIND_WRITER");
Require(!recorder.PendingReadOverlaps(indices, 256), "an index range left on the copy path was noted as an in-place read");
RuntimeSwitches::Assign(RuntimeSwitch::IndexInPlaceBehindWriter, true);
const auto countsBefore = IndexBehindWriterCounts();
const auto taken = attempt(context, indices, 4, false, false, 0);
Require(taken.first != nullptr && taken.second == IndexBehindWriter::Taken && taken.first->base <= indices && indices + 256 <= taken.first->base + taken.first->bytes, "an index range behind a pending GPU writer was not bound in place with APS5_INDEX_IN_PLACE_BEHIND_WRITER");
Require(recorder.PendingWriteOverlaps(indices, 256), "binding an index range behind a pending GPU writer waited for the writer");
const auto read = recorder.DescribePendingRead(indices, 256);
Require(read.has_value() && read->kind == Recorder::ReadKind::DrawInput && read->open, "the read of an index range bound behind a pending GPU writer was not noted on the open batch");
Require(attempt(context, address + 16384, 4, false, false, 0).second == IndexBehindWriter::NoWriter, "an index range without a pending GPU writer left the copy path");
Require(attempt(context, indices, 4, true, false, 0).second == IndexBehindWriter::VertexAttributes, "an index range of a draw with vertex attributes, which needs its highest index on the CPU, was bound behind a pending GPU writer");
Require(attempt(context, indices, 4, false, true, 0).second == IndexBehindWriter::MeshStage, "an index range of a mesh draw was bound behind a pending GPU writer");
IndexBehindWriter restartOutcome = IndexBehindWriter::Count;
Require(InPlaceIndexBehindWriter(context, indices, 256, 4, false, false, true, 0, &restartOutcome) == nullptr && restartOutcome == IndexBehindWriter::PrimitiveRestart, "an index range of a draw with primitive restart, which is skipped when it holds restart indices only, was bound behind a pending GPU writer");
IndexBehindWriter shortOutcome = IndexBehindWriter::Count;
Require(InPlaceIndexBehindWriter(context, indices, 2, 4, false, false, false, 0, &shortOutcome) == nullptr && shortOutcome == IndexBehindWriter::Off, "an index range shorter than one index, which is skipped on the copy path, was bound behind a pending GPU writer");
Require(attempt(context, indices, 4, false, false, 1).second == IndexBehindWriter::VertexOffset, "a 32-bit index range whose vertex offset can overflow was bound behind a pending GPU writer");
Require(attempt(context, indices, 2, false, false, 0xffff0000u).second == IndexBehindWriter::Taken, "a 16-bit index range whose vertex offset cannot overflow was not bound behind a pending GPU writer");
Require(attempt(context, indices, 2, false, false, 0xffff0001u).second == IndexBehindWriter::VertexOffset, "a 16-bit index range whose vertex offset can overflow was bound behind a pending GPU writer");
Require(attempt(context, indices + 2, 4, false, false, 0).second == IndexBehindWriter::NoImport, "an index range misaligned for its format was bound behind a pending GPU writer");
auto limited = context;
limited.limits.maxDrawIndexedIndexValue = 0xffffffu;
Require(attempt(limited, indices, 4, false, false, 0).second == IndexBehindWriter::IndexLimit, "an index range was bound behind a pending GPU writer on a device whose index limit needs the highest index");
auto unrecorded = context;
unrecorded.recorder = nullptr;
Require(attempt(unrecorded, indices, 4, false, false, 0).second == IndexBehindWriter::Off, "an index range was bound behind a pending GPU writer without a recorder");
const std::array<std::byte, 4> label{std::byte{1}, std::byte{2}, std::byte{3}, std::byte{4}};
recorder.NotePendingWrite(address + 12288, 16);
recorder.RecordStore(whole->buffer, address + 12288 - whole->base, label, address + 12288);
Require(recorder.QueuedStoreOverlaps(address + 12288, 4), "the label store was not queued");
Require(attempt(context, address + 12288, 4, false, false, 0).second == IndexBehindWriter::LabelOrStore, "an index range under a queued label store was bound behind a pending GPU writer");
recorder.Sync();
Require(!recorder.PendingReadOverlaps(indices, 256), "the read of an index range bound behind a pending GPU writer outlived its batch");
Require(attempt(context, indices, 4, false, false, 0).second == IndexBehindWriter::NoWriter, "an index range whose GPU writer completed left the copy path");
const auto countsAfter = IndexBehindWriterCounts();
std::array<std::uint64_t, static_cast<std::size_t>(IndexBehindWriter::Count)> expectedCounts{};
const auto expect = [&](IndexBehindWriter outcome, std::uint64_t count) { expectedCounts[static_cast<std::size_t>(outcome)] = count; };
expect(IndexBehindWriter::Taken, 2);
expect(IndexBehindWriter::Off, 2);
expect(IndexBehindWriter::NoWriter, 2);
expect(IndexBehindWriter::VertexAttributes, 1);
expect(IndexBehindWriter::IndexLimit, 1);
expect(IndexBehindWriter::MeshStage, 1);
expect(IndexBehindWriter::PrimitiveRestart, 1);
expect(IndexBehindWriter::VertexOffset, 2);
expect(IndexBehindWriter::LabelOrStore, 1);
expect(IndexBehindWriter::NoImport, 1);
for (std::size_t index = 0; index < expectedCounts.size(); ++index) Require(countsAfter[index] - countsBefore[index] == expectedCounts[index], "the outcome counter " + std::to_string(index) + " of the index ranges behind a pending GPU writer counted " + std::to_string(countsAfter[index] - countsBefore[index]) + " instead of " + std::to_string(expectedCounts[index]));
return true;
}
// Unit shadows (UnitShadow.hpp) over a host import of write-watched arena memory: a retile piece's
// slab destination and its seeds, freshness from the tracker (a publish never stamps, a CPU write
// makes the unit stale), the scopes, the slab boundary, and the retire publish. With
@@ -9768,10 +10165,11 @@ void writeBackPaddingTests(const Device& device, Recorder& recorder, bool watche
static const bool importRetile = std::getenv("APS5_NO_LINEAR_IMPORT_RETILE") == nullptr;
const auto* surfaceImport = watched ? HostImportFor(context, address, surfaceBytes) : nullptr;
const bool deviceLocalImport = surfaceImport != nullptr && HostImportDeviceLocal(context, *surfaceImport);
const bool expectImportRetile = importRetile && deviceLocalImport && test.tileMode == TextureTileMode::kLinear && watched && AgcDriver::GuestMemory::Watched(address, surfaceBytes);
static const bool hostRetile = std::getenv("APS5_LINEAR_IMPORT_RETILE_HOST") != nullptr;
const bool expectImportRetile = importRetile && (deviceLocalImport || hostRetile) && test.tileMode == TextureTileMode::kLinear && watched && AgcDriver::GuestMemory::Watched(address, surfaceBytes);
if (expectImportRetile && importRetiled == 0) failures += what + ": the linear write-back went through its scratch instead of retiling into the import\n";
if (!importRetile && importRetiled != 0) failures += what + ": the linear write-back retiled into the import with APS5_NO_LINEAR_IMPORT_RETILE set\n";
if (watched && !deviceLocalImport && importRetiled != 0) failures += what + ": the linear write-back retiled into an import outside a device-local heap\n";
if (watched && !deviceLocalImport && !hostRetile && importRetiled != 0) failures += what + ": the linear write-back retiled into an import outside a device-local heap\n";
std::vector<std::byte> read(bytes);
if (watched) AgcDriver::GuestMemory::Read(blockAddress, read);
else std::memcpy(read.data(), memory, bytes);
@@ -14483,6 +14881,136 @@ void expectRed(float got, float want, const char* what) {
if (std::abs(got - want) > 1.5f / 255.0f) throw std::runtime_error(std::string(what) + ": read " + std::to_string(got) + ", expected " + std::to_string(want));
}
bool sampledImportPiecesTests(const Device& device, Recorder& recorder) {
auto context = device.GetContext();
context.nullDescriptors = device.NullDescriptors();
if (context.hostImportAlignment == 0 || !context.nullDescriptors || !AgcDriver::GuestMemory::WriteWatched()) return false;
recorder.Sync();
const auto unit = static_cast<std::size_t>(std::max<VkDeviceSize>(65536u, context.hostImportAlignment));
const auto bytes = 4u * unit;
auto* block = static_cast<std::byte*>(AllocateWatched(bytes, unit));
Require(block != nullptr, "cannot allocate sampled import pieces memory");
struct Release {
const Context& context;
Recorder& recorder;
std::byte* block;
std::size_t bytes;
~Release() {
recorder.Sync();
ClearCachedTextures(context.device);
SampledFromStorageForTest(true);
SetHostImportRangeWindow(64ull << 20u);
GuestAllocations::Mutation().Remove(block);
ClearHostImports(context.device);
recorder.Sync();
ReleaseWatched(block, bytes);
}
} release{context, recorder, block, bytes};
const auto address = reinterpret_cast<std::uint64_t>(block);
GuestAllocations::Mutation().Add(block, bytes, true, true, true);
SetHostImportRangeWindow(unit);
ClearHostImports(context.device);
recorder.Sync();
for (std::size_t half = 0; half < 8; ++half) std::memset(block + half * unit / 2, static_cast<int>(16 + half * 16), unit / 2);
for (const auto window : {0u, 2u}) Require(HostImportFor(context, address + window * unit, 1) != nullptr, "cannot import a sampled texture window");
TextureDetiler detiler(context);
context.detiler = &detiler;
TextureCache cache(context);
context.textureCache = &cache;
SampledFromStorageForTest(false);
SampleProgram center(context, recorder, SAMPLE_ARRAY_SPV);
SampleProgram origin(context, recorder, SAMPLE_IMPORT_ORIGIN_SPV);
struct Drain { Recorder& recorder; ~Drain() { recorder.Sync(); } } drain{recorder};
constexpr std::uint32_t width = 128;
const auto height = static_cast<std::uint32_t>(unit / (width * 4u));
const auto request = [&](std::uint64_t begin) {
ShaderRecompiler::RecompileResult program;
ShaderRecompiler::DescriptorBinding binding;
binding.kind = ShaderRecompiler::DescriptorKind::SampledImage;
binding.role = ShaderRecompiler::DescriptorRole::GuestImages;
binding.descriptorSet = 0;
binding.binding = ShaderRecompiler::RuntimeAbi::FirstImageBinding;
binding.count = 1;
binding.imageSamplers = {0};
binding.imageShape = ShaderRecompiler::DescriptorImageShape::Image2DArray;
binding.guestDescriptor = {static_cast<std::uint32_t>(begin >> 8u), static_cast<std::uint32_t>(begin >> 40u) | (56u << 20u) | (((width - 1u) & 3u) << 30u), ((width - 1u) >> 2u) | ((height - 1u) << 14u), 0xd0000facu, 2u, 0u, 0u, 0u};
Require(DescribeSurface(DecodeTextureResource(binding.guestDescriptor)).guestBytes == 3u * unit, "sampled import pieces fixture has the wrong array size");
program.bindings.push_back(std::move(binding));
return program;
};
const auto check = [&](const std::shared_ptr<ShaderResources>& resources, std::size_t offset, std::uint32_t phase) {
Require(resources->SampledTextures().size() == 1, "sampled import pieces produced no texture");
const auto& texture = resources->SampledTextures().front();
recorder.Keep(resources);
for (std::size_t layer = 0; layer < 3; ++layer) {
const auto firstHalf = (offset + layer * unit) / (unit / 2u);
const auto centerHalf = (offset + layer * unit + (height / 2u * width + width / 2u) * 4u) / (unit / 2u);
expectRed(origin.Red(texture->View(), texture->Layout(), 0, static_cast<float>(layer)), (16u + firstHalf * 16u + phase * 4u) / 255.0f, "an imported array layer starts with another source's texel");
expectRed(center.Red(texture->View(), texture->Layout(), 0, static_cast<float>(layer)), (16u + centerHalf * 16u + phase * 4u) / 255.0f, "an imported array layer sampled across an import boundary incorrectly");
}
};
const auto partialProgram = request(address);
const CompiledShader partialShader{ShaderRecompiler::ShaderStage::Compute, &partialProgram, 0};
Require(ExistingHostImportCopies(context, address, 3u * unit).empty(), "a gapped import set produced a partial copy plan");
Require(ExistingHostImportCopies(context, address, 0).empty(), "an empty texture range produced import copies");
Require(ExistingHostImportCopies(context, UINT64_MAX - 7u, 16u).empty(), "an overflowing texture range produced import copies");
const auto partialCommands = recorder.Commands();
RecordMemoryBarrier(context, partialCommands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
for (const auto half : {0u, 1u, 4u, 5u}) {
const auto begin = address + half * unit / 2u;
const auto* imported = ExistingHostImportFor(context, begin, unit / 2u);
Require(imported != nullptr, "a gapped sampled texture lost an imported window");
const auto value = static_cast<std::uint32_t>(16u + half * 16u) * 0x01010101u;
context.Function<PFN_vkCmdFillBuffer>("vkCmdFillBuffer")(partialCommands, imported->buffer, HostImportOffset(*imported, begin), unit / 2u, value);
}
recorder.NotePendingWrite(address, 3u * unit);
static_cast<void>(AgcDriver::GuestMemory::MarkPossiblyWritten(address, 3u * unit));
const auto beforePartial = SampledTexturesImported();
auto partial = std::make_shared<ShaderResources>(context, partialShader);
Require(SampledTexturesImported() == beforePartial, "a gapped import set was accepted for a sampled texture");
check(partial, 0, 0);
partial.reset();
ClearCachedTextures(context.device);
ClearHostImports(context.device);
recorder.Sync();
for (std::size_t window = 0; window < 4; ++window) {
const auto* imported = HostImportFor(context, address + window * unit, 1);
Require(imported != nullptr && imported->base == address + window * unit && imported->bytes == unit, "the sampled texture windows were not imported separately");
}
for (std::uint32_t phase = 0; phase < 2; ++phase) {
const auto commands = recorder.Commands();
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
for (std::size_t half = 0; half < 8; ++half) {
const auto begin = address + half * unit / 2u;
const auto* imported = ExistingHostImportFor(context, begin, unit / 2u);
Require(imported != nullptr, "a sampled texture half lost its existing import");
const auto value = static_cast<std::uint32_t>(16u + half * 16u + phase * 4u) * 0x01010101u;
context.Function<PFN_vkCmdFillBuffer>("vkCmdFillBuffer")(commands, imported->buffer, HostImportOffset(*imported, begin), unit / 2u, value);
}
recorder.NotePendingWrite(address, bytes);
static_cast<void>(AgcDriver::GuestMemory::MarkPossiblyWritten(address, bytes));
const auto submissions = recorder.Submissions();
std::vector<std::shared_ptr<ShaderResources>> uploaded;
std::shared_ptr<DeviceBuffer> scratch;
for (const auto offset : {std::size_t{0}, unit / 2u}) {
Require(ExistingHostImportFor(context, address + offset, 3u * unit) == nullptr, "the sampled array unexpectedly fits one import");
const auto program = request(address + offset);
const CompiledShader shader{ShaderRecompiler::ShaderStage::Compute, &program, 0};
const auto before = SampledTexturesImported();
auto resources = std::make_shared<ShaderResources>(context, shader);
Require(SampledTexturesImported() == before + 1, "a sampled array spanning existing imports was not uploaded on the GPU");
Require(recorder.Submissions() == submissions, "a sampled array waited for its imported GPU writes");
const auto reused = recorder.UploadScratchBuffer(Recorder::UploadScratch::Tiled, 3u * unit);
Require(scratch == nullptr || scratch == reused, "consecutive imported uploads did not reuse tiled scratch");
scratch = reused;
uploaded.push_back(std::move(resources));
}
for (std::size_t index = 0; index < uploaded.size(); ++index) check(uploaded[index], index * unit / 2u, phase);
}
std::cout << "sampled import pieces: gapped fallback, consecutive scratch reuse, boundary texels and repeated writes passed\n";
return true;
}
void minLodTests(const Device& device, Recorder& recorder) {
const auto& context = device.GetContext();
if (!context.imageViewMinLod) {
@@ -17226,6 +17754,7 @@ int main(int argc, char** argv) {
return 77;
}
Device& device = *created;
if (argc == 2 && std::string_view(argv[1]) == "--multisample-use-collect-only") return multisampleUseCollectTests(device) ? 0 : 77;
if (argc == 2 && std::string_view(argv[1]) == "--host-import-lifetime-only") return RunHostImportLifetimeTests(device.GetContext());
if (argc == 2 && std::string_view(argv[1]) == "--host-import-mutation-race-only") return RunHostImportMutationRaceTests(device.GetContext());
if (argc == 2 && (std::string_view(argv[1]) == "--gpu-timing-complete-only" || std::string_view(argv[1]) == "--gpu-timing-incomplete-only")) {
@@ -17243,9 +17772,9 @@ int main(int argc, char** argv) {
importWatchTests(device);
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--settle-initial-dcc-only") {
if (argc == 2 && (std::string_view(argv[1]) == "--settle-initial-dcc-only" || std::string_view(argv[1]) == "--settle-initial-dcc-committer-only")) {
#ifdef _WIN32
return settleInitialDccTests(device) ? 0 : 77;
return (std::string_view(argv[1]) == "--settle-initial-dcc-committer-only" ? settleInitialDccCommitterTests(device) : settleInitialDccTests(device)) ? 0 : 77;
#else
std::cout << "skipped, the device has no deferred settle of host imports: imports under 1 MiB wait for one only on Windows\n";
return 77;
@@ -17368,6 +17897,9 @@ int main(int argc, char** argv) {
storeRunTests(device, recorder);
return Recorder::StoreCounts().stores != before ? 0 : 77;
}
if (argc == 2 && std::string_view(argv[1]) == "--sampled-import-pieces") {
return sampledImportPiecesTests(device, recorder) ? 0 : 77;
}
if (argc == 2 && std::string_view(argv[1]) == "--copied-direct-only") {
copiedDirectOrderingTests(device, recorder);
return 0;
@@ -17455,6 +17987,12 @@ int main(int argc, char** argv) {
if (argc == 2 && std::string_view(argv[1]) == "--typed-fill-clear-only") {
return denormalClearTests(device, recorder) ? 0 : 77;
}
if (argc == 2 && std::string_view(argv[1]) == "--pending-upload-gpu-copy-only") {
return pendingUploadGpuCopyTests(device, recorder) ? 0 : 77;
}
if (argc == 2 && std::string_view(argv[1]) == "--pending-upload-gpu-copy-bytes-only") {
return pendingUploadGpuCopyBytesTests(device, recorder) ? 0 : 77;
}
if (argc == 2 && std::string_view(argv[1]) == "--integer-clear-only") {
integerClearTests(device);
return 0;
@@ -17756,6 +18294,11 @@ int main(int argc, char** argv) {
std::cout << "Draw input reuse tests passed\n";
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--index-behind-writer-only") {
if (!indexBehindWriterTests(device, recorder)) return 77;
std::cout << "Index ranges behind a pending GPU writer tests passed\n";
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--draw-inputs-copied-only") {
drawInputInPlaceTests(device, recorder, true);
std::cout << "Copied draw input tests passed\n";
@@ -17853,6 +18396,8 @@ int main(int argc, char** argv) {
fmaskDecompressMsaaTests(device, recorder);
misalignedSnapshotTests(device, recorder);
misalignedRegionTests(device, recorder);
pendingUploadGpuCopyTests(device, recorder);
pendingUploadGpuCopyBytesTests(device, recorder);
drawSnapshotReuseTests(device, recorder);
drawDescriptorWriteTests(device, recorder);
drawSnapshotTableSetTests(device, recorder);
@@ -0,0 +1,638 @@
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include <algorithm>
#include <array>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
using namespace AgcDriver::Graphics;
namespace {
enum class Mode { Fenceless, Fenced, NoTimeline };
constexpr std::array<Mode, 3> Modes{Mode::Fenceless, Mode::Fenced, Mode::NoTimeline};
const char* Name(Mode mode) {
return mode == Mode::Fenceless ? "fenceless" : mode == Mode::Fenced ? "fenced timeline" : "no timeline";
}
int failures = 0;
void Expect(Mode mode, bool condition, const std::string& what) {
if (condition) return;
std::fprintf(stderr, "FAIL (%s): %s\n", Name(mode), what.c_str());
++failures;
}
struct Entry {
VkFence fence = VK_NULL_HANDLE;
std::uint64_t signal = 0;
bool held = false;
bool done = false;
};
struct MockDevice {
std::uintptr_t next = 1;
std::thread::id owner;
std::map<VkFence, bool> signaled;
std::vector<Entry> queue;
std::uint64_t timelineValue = 0;
std::uint64_t fenceCreates = 0;
std::uint64_t fenceStatusCalls = 0;
std::uint64_t fenceWaits = 0;
std::uint64_t counterReads = 0;
std::uint64_t semaphoreWaits = 0;
std::uint64_t submits = 0;
std::uint64_t submitsWithFence = 0;
std::uint64_t semaphoresCreated = 0;
std::uint64_t semaphoresDestroyed = 0;
std::uint64_t allocatedCommands = 0;
std::uint64_t freedCommands = 0;
std::uint64_t idleWaits = 0;
VkResult submitResult = VK_SUCCESS;
VkResult createSemaphoreResult = VK_SUCCESS;
VkResult waitResult = VK_SUCCESS;
VkResult pollResult = VK_SUCCESS;
VkResult idleResult = VK_SUCCESS;
};
MockDevice mock;
std::mutex mockLock;
bool Owner() {
return std::this_thread::get_id() == mock.owner;
}
void Finish(Entry& entry) {
entry.done = true;
if (entry.fence != VK_NULL_HANDLE) mock.signaled.at(entry.fence) = true;
if (entry.signal != 0) mock.timelineValue = std::max(mock.timelineValue, entry.signal);
}
void CompleteUntil(const std::function<bool(const Entry&)>& reached) {
for (auto& entry : mock.queue) {
if (entry.done) continue;
if (entry.held) return;
Finish(entry);
if (reached(entry)) return;
}
}
void Complete(std::size_t count) {
std::lock_guard lock(mockLock);
std::size_t remaining = count;
CompleteUntil([&](const Entry&) { return --remaining == 0; });
}
void CompleteAll() {
Complete(std::numeric_limits<std::size_t>::max());
}
void ReleaseHeld() {
std::lock_guard lock(mockLock);
for (auto& entry : mock.queue) entry.held = false;
}
VKAPI_ATTR VkResult VKAPI_CALL mockAllocateCommandBuffers(VkDevice, const VkCommandBufferAllocateInfo*, VkCommandBuffer* commands) {
*commands = reinterpret_cast<VkCommandBuffer>(mock.next++);
++mock.allocatedCommands;
return VK_SUCCESS;
}
VKAPI_ATTR void VKAPI_CALL mockFreeCommandBuffers(VkDevice, VkCommandPool, std::uint32_t count, const VkCommandBuffer*) {
mock.freedCommands += count;
}
VKAPI_ATTR VkResult VKAPI_CALL mockCreateFence(VkDevice, const VkFenceCreateInfo*, const VkAllocationCallbacks*, VkFence* fence) {
std::lock_guard lock(mockLock);
*fence = reinterpret_cast<VkFence>(mock.next++);
mock.signaled[*fence] = false;
++mock.fenceCreates;
return VK_SUCCESS;
}
VKAPI_ATTR void VKAPI_CALL mockDestroyFence(VkDevice, VkFence fence, const VkAllocationCallbacks*) {
std::lock_guard lock(mockLock);
mock.signaled.erase(fence);
}
VKAPI_ATTR VkResult VKAPI_CALL mockGetFenceStatus(VkDevice, VkFence fence) {
std::lock_guard lock(mockLock);
++mock.fenceStatusCalls;
if (mock.pollResult != VK_SUCCESS) return mock.pollResult;
return mock.signaled.at(fence) ? VK_SUCCESS : VK_NOT_READY;
}
VKAPI_ATTR VkResult VKAPI_CALL mockWaitForFences(VkDevice, std::uint32_t, const VkFence* fences, VkBool32, std::uint64_t) {
std::lock_guard lock(mockLock);
++mock.fenceWaits;
if (mock.waitResult != VK_SUCCESS) return mock.waitResult;
const auto fence = fences[0];
if (!mock.signaled.at(fence)) CompleteUntil([&](const Entry& entry) { return entry.fence == fence; });
return mock.signaled.at(fence) ? VK_SUCCESS : VK_TIMEOUT;
}
VKAPI_ATTR VkResult VKAPI_CALL mockResetFences(VkDevice, std::uint32_t count, const VkFence* fences) {
std::lock_guard lock(mockLock);
for (std::uint32_t index = 0; index < count; ++index) mock.signaled.at(fences[index]) = false;
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL mockCreateSemaphore(VkDevice, const VkSemaphoreCreateInfo*, const VkAllocationCallbacks*, VkSemaphore* semaphore) {
std::lock_guard lock(mockLock);
if (mock.createSemaphoreResult != VK_SUCCESS) return mock.createSemaphoreResult;
*semaphore = reinterpret_cast<VkSemaphore>(mock.next++);
++mock.semaphoresCreated;
return VK_SUCCESS;
}
VKAPI_ATTR void VKAPI_CALL mockDestroySemaphore(VkDevice, VkSemaphore, const VkAllocationCallbacks*) {
std::lock_guard lock(mockLock);
++mock.semaphoresDestroyed;
}
VKAPI_ATTR VkResult VKAPI_CALL mockGetSemaphoreCounterValue(VkDevice, VkSemaphore, std::uint64_t* value) {
std::lock_guard lock(mockLock);
if (!Owner()) {
*value = mock.timelineValue;
return VK_SUCCESS;
}
++mock.counterReads;
if (mock.pollResult != VK_SUCCESS) return mock.pollResult;
*value = mock.timelineValue;
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL mockWaitSemaphores(VkDevice, const VkSemaphoreWaitInfo* info, std::uint64_t) {
if (!Owner()) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
return VK_TIMEOUT;
}
std::lock_guard lock(mockLock);
++mock.semaphoreWaits;
if (mock.waitResult != VK_SUCCESS) return mock.waitResult;
const auto target = info->pValues[0];
if (mock.timelineValue < target) CompleteUntil([&](const Entry& entry) { return entry.signal >= target; });
return mock.timelineValue >= target ? VK_SUCCESS : VK_TIMEOUT;
}
VKAPI_ATTR VkResult VKAPI_CALL mockBeginCommandBuffer(VkCommandBuffer, const VkCommandBufferBeginInfo*) {
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL mockEndCommandBuffer(VkCommandBuffer) {
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL mockQueueSubmit(VkQueue, std::uint32_t, const VkSubmitInfo* submissions, VkFence fence) {
std::lock_guard lock(mockLock);
if (mock.submitResult != VK_SUCCESS) return mock.submitResult;
Entry entry;
entry.fence = fence;
entry.held = submissions[0].waitSemaphoreCount != 0;
if (submissions[0].signalSemaphoreCount != 0) {
const auto* timeline = static_cast<const VkTimelineSemaphoreSubmitInfoKHR*>(submissions[0].pNext);
entry.signal = timeline->pSignalSemaphoreValues[0];
}
++mock.submits;
if (fence != VK_NULL_HANDLE) ++mock.submitsWithFence;
mock.queue.push_back(entry);
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL mockDeviceWaitIdle(VkDevice) {
++mock.idleWaits;
return mock.idleResult;
}
VKAPI_ATTR void VKAPI_CALL mockCmdUpdateBuffer(VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, const void*) {}
VKAPI_ATTR void VKAPI_CALL mockCmdPipelineBarrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, std::uint32_t, const VkImageMemoryBarrier*) {}
VKAPI_ATTR void VKAPI_CALL mockCmdBeginQuery(VkCommandBuffer, VkQueryPool, std::uint32_t, VkQueryControlFlags) {}
VKAPI_ATTR void VKAPI_CALL mockCmdEndQuery(VkCommandBuffer, VkQueryPool, std::uint32_t) {}
VKAPI_ATTR void VKAPI_CALL mockCmdResetQueryPool(VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t) {}
VKAPI_ATTR void VKAPI_CALL mockCmdCopyQueryPoolResults(VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, VkDeviceSize, VkDeviceSize, VkQueryResultFlags) {}
VKAPI_ATTR void VKAPI_CALL mockCmdBindPipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}
VKAPI_ATTR void VKAPI_CALL mockCmdPushConstants(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, std::uint32_t, const void*) {}
VKAPI_ATTR void VKAPI_CALL mockCmdDispatch(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t) {}
PFN_vkVoidFunction VKAPI_CALL mockProc(VkDevice, const char* name) {
static const std::map<std::string_view, PFN_vkVoidFunction> table{
{"vkAllocateCommandBuffers", reinterpret_cast<PFN_vkVoidFunction>(mockAllocateCommandBuffers)},
{"vkFreeCommandBuffers", reinterpret_cast<PFN_vkVoidFunction>(mockFreeCommandBuffers)},
{"vkCreateFence", reinterpret_cast<PFN_vkVoidFunction>(mockCreateFence)},
{"vkDestroyFence", reinterpret_cast<PFN_vkVoidFunction>(mockDestroyFence)},
{"vkGetFenceStatus", reinterpret_cast<PFN_vkVoidFunction>(mockGetFenceStatus)},
{"vkWaitForFences", reinterpret_cast<PFN_vkVoidFunction>(mockWaitForFences)},
{"vkResetFences", reinterpret_cast<PFN_vkVoidFunction>(mockResetFences)},
{"vkCreateSemaphore", reinterpret_cast<PFN_vkVoidFunction>(mockCreateSemaphore)},
{"vkDestroySemaphore", reinterpret_cast<PFN_vkVoidFunction>(mockDestroySemaphore)},
{"vkGetSemaphoreCounterValueKHR", reinterpret_cast<PFN_vkVoidFunction>(mockGetSemaphoreCounterValue)},
{"vkWaitSemaphoresKHR", reinterpret_cast<PFN_vkVoidFunction>(mockWaitSemaphores)},
{"vkBeginCommandBuffer", reinterpret_cast<PFN_vkVoidFunction>(mockBeginCommandBuffer)},
{"vkEndCommandBuffer", reinterpret_cast<PFN_vkVoidFunction>(mockEndCommandBuffer)},
{"vkQueueSubmit", reinterpret_cast<PFN_vkVoidFunction>(mockQueueSubmit)},
{"vkDeviceWaitIdle", reinterpret_cast<PFN_vkVoidFunction>(mockDeviceWaitIdle)},
{"vkCmdUpdateBuffer", reinterpret_cast<PFN_vkVoidFunction>(mockCmdUpdateBuffer)},
{"vkCmdPipelineBarrier", reinterpret_cast<PFN_vkVoidFunction>(mockCmdPipelineBarrier)},
{"vkCmdBeginQuery", reinterpret_cast<PFN_vkVoidFunction>(mockCmdBeginQuery)},
{"vkCmdEndQuery", reinterpret_cast<PFN_vkVoidFunction>(mockCmdEndQuery)},
{"vkCmdResetQueryPool", reinterpret_cast<PFN_vkVoidFunction>(mockCmdResetQueryPool)},
{"vkCmdCopyQueryPoolResults", reinterpret_cast<PFN_vkVoidFunction>(mockCmdCopyQueryPoolResults)},
{"vkCmdBindPipeline", reinterpret_cast<PFN_vkVoidFunction>(mockCmdBindPipeline)},
{"vkCmdPushConstants", reinterpret_cast<PFN_vkVoidFunction>(mockCmdPushConstants)},
{"vkCmdDispatch", reinterpret_cast<PFN_vkVoidFunction>(mockCmdDispatch)},
};
const auto it = table.find(name);
return it == table.end() ? nullptr : it->second;
}
Context mockContext() {
Context context{};
context.device = reinterpret_cast<VkDevice>(mock.next++);
context.queue = reinterpret_cast<VkQueue>(mock.next++);
context.deviceProc = mockProc;
return context;
}
void SetBatchFences(bool enabled) {
#ifdef _WIN32
_putenv_s("APS5_BATCH_FENCES", enabled ? "1" : "");
#else
if (enabled) setenv("APS5_BATCH_FENCES", "1", 1);
else unsetenv("APS5_BATCH_FENCES");
#endif
}
std::array<std::byte, 0x20000> memory{};
std::uint64_t Address(int index) {
return reinterpret_cast<std::uint64_t>(memory.data()) + 0x100u * static_cast<std::uint64_t>(index);
}
constexpr std::size_t Length = 0x100;
void Batch(Recorder& recorder, int index, bool hold = false) {
recorder.NotePendingWrite(Address(index), Length);
if (hold) recorder.HoldNextSubmit(reinterpret_cast<VkSemaphore>(std::uintptr_t{0xfeed}), 1);
recorder.Submit();
}
bool Settled(const Recorder& recorder, int index) {
return recorder.PendingWriteSettled(Address(index), Length);
}
void Begin(Mode mode) {
mock = MockDevice{};
mock.owner = std::this_thread::get_id();
SetBatchFences(mode == Mode::Fenced);
}
std::unique_ptr<Recorder> Make(Mode mode) {
auto recorder = std::make_unique<Recorder>(mockContext(), mode != Mode::NoTimeline);
SetBatchFences(false);
Expect(mode, recorder->HasTimeline() == (mode != Mode::NoTimeline), "the recorder's timeline does not match its configuration");
return recorder;
}
void ExpectNoLeaks(Mode mode) {
Expect(mode, mock.signaled.empty(), "a batch fence outlived the recorder");
Expect(mode, mock.allocatedCommands == mock.freedCommands, "a command buffer outlived the recorder");
Expect(mode, mock.semaphoresCreated == mock.semaphoresDestroyed, "the timeline outlived the recorder");
}
std::string Count(std::uint64_t value) {
return std::to_string(value);
}
void Configuration(Mode mode) {
Begin(mode);
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
{
const auto recorder = Make(mode);
for (int index = 0; index < 20; ++index) {
Batch(*recorder, index);
if (index % 3 == 2) CompleteAll();
recorder->Reap();
}
recorder->Sync();
Expect(mode, recorder->Idle() && recorder->Submissions() == 20 && mock.submits == 20, "twenty batches were not all submitted and completed");
if (mode == Mode::Fenceless) {
Expect(mode, mock.fenceCreates == 0 && mock.submitsWithFence == 0, "fenceless batches made " + Count(mock.fenceCreates) + " fences and submitted " + Count(mock.submitsWithFence) + " with one");
Expect(mode, mock.fenceStatusCalls == 0 && mock.fenceWaits == 0, "fenceless batches polled or waited on a fence");
} else {
Expect(mode, mock.fenceCreates != 0 && mock.submitsWithFence == mock.submits, "fenced batches were submitted without a fence of their own");
}
}
ExpectNoLeaks(mode);
}
void ReapCost(Mode mode) {
Begin(mode);
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
{
const auto recorder = Make(mode);
for (int index = 0; index < 8; ++index) Batch(*recorder, index);
Complete(4);
mock.counterReads = mock.fenceStatusCalls = 0;
Expect(mode, !recorder->Reap() && recorder->InFlightBatches() == 4, "a reap with four of eight batches complete did not retire exactly four");
if (mode == Mode::Fenceless) Expect(mode, mock.counterReads == 1 && mock.fenceStatusCalls == 0, "a fenceless reap made " + Count(mock.counterReads) + " timeline reads and " + Count(mock.fenceStatusCalls) + " fence queries, not one read");
else Expect(mode, mock.counterReads == 0 && mock.fenceStatusCalls == 5, "a fenced reap made " + Count(mock.counterReads) + " timeline reads and " + Count(mock.fenceStatusCalls) + " fence queries, not five");
CompleteAll();
mock.counterReads = mock.fenceStatusCalls = 0;
Expect(mode, Settled(*recorder, 7) && Settled(*recorder, 4) && Settled(*recorder, 5) && Settled(*recorder, 7), "completed batches are not settled");
if (mode == Mode::Fenceless) Expect(mode, mock.counterReads == 1, "the settled queries made " + Count(mock.counterReads) + " timeline reads, not one for all four");
else Expect(mode, mock.fenceStatusCalls == 4, "the settled queries made " + Count(mock.fenceStatusCalls) + " fence queries, not four");
mock.counterReads = mock.fenceStatusCalls = 0;
Expect(mode, recorder->Reap() && recorder->Idle(), "a reap with every batch complete did not retire them all");
if (mode == Mode::Fenceless) Expect(mode, mock.counterReads == 0 && mock.fenceStatusCalls == 0, "a reap after a read that covered every batch read the timeline again");
else Expect(mode, mock.fenceStatusCalls == 4, "a fenced reap made " + Count(mock.fenceStatusCalls) + " fence queries, not four");
mock.counterReads = mock.fenceStatusCalls = 0;
Expect(mode, recorder->Reap() && mock.counterReads == 0 && mock.fenceStatusCalls == 0, "a reap with nothing in flight queried the GPU");
}
ExpectNoLeaks(mode);
}
void HeldFirstBatch(Mode mode) {
Begin(mode);
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
{
const auto recorder = Make(mode);
Batch(*recorder, 0, true);
Batch(*recorder, 1);
Batch(*recorder, 2);
CompleteAll();
Expect(mode, !recorder->Reap() && recorder->InFlightBatches() == 3, "a reap retired a batch behind a submission still waiting on its semaphore");
Expect(mode, !Settled(*recorder, 0) && !Settled(*recorder, 1) && !Settled(*recorder, 2), "a batch behind a waiting submission counted as settled");
Expect(mode, recorder->UnsignaledBatches() == 3, "batches behind a waiting submission were not all unsignaled");
const auto info = recorder->DescribePendingWrite(Address(2), Length);
Expect(mode, info.has_value() && !info->signaled && info->serial == 3, "the newest batch behind a waiting submission described as signaled");
ReleaseHeld();
CompleteAll();
Expect(mode, Settled(*recorder, 0) && Settled(*recorder, 2) && recorder->UnsignaledBatches() == 0, "released batches are not settled");
const auto done = recorder->DescribePendingWrite(Address(1), Length);
Expect(mode, done.has_value() && done->signaled, "a completed batch described as unsignaled");
Expect(mode, recorder->Reap() && recorder->Idle(), "a reap did not retire the released batches");
Expect(mode, !recorder->DescribePendingWrite(Address(1), Length).has_value(), "a retired batch still describes a pending write");
}
ExpectNoLeaks(mode);
}
void PartialPrefix(Mode mode) {
Begin(mode);
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
{
const auto recorder = Make(mode);
Batch(*recorder, 0);
Batch(*recorder, 1);
Batch(*recorder, 2, true);
Batch(*recorder, 3);
CompleteAll();
Expect(mode, Settled(*recorder, 0) && Settled(*recorder, 1), "the batches ahead of a waiting submission are not settled");
Expect(mode, !Settled(*recorder, 2) && !Settled(*recorder, 3), "the waiting submission or the batch behind it counted as settled");
const auto ahead = recorder->DescribePendingWrite(Address(1), Length);
Expect(mode, ahead.has_value() && ahead->signaled && ahead->serial == 2, "the newest batch ahead of a waiting submission did not describe as signaled");
const auto held = recorder->DescribePendingWrite(Address(2), Length);
Expect(mode, held.has_value() && !held->signaled && held->serial == 3, "the waiting submission described as signaled");
Expect(mode, !recorder->Reap() && recorder->InFlightBatches() == 2, "a reap did not stop at the waiting submission");
Expect(mode, !Settled(*recorder, 2) && !Settled(*recorder, 3) && recorder->UnsignaledBatches() == 2, "the batches from the waiting submission on are not unsignaled");
ReleaseHeld();
CompleteAll();
Expect(mode, recorder->Reap() && recorder->Idle(), "a reap did not retire the rest once the submission was released");
}
ExpectNoLeaks(mode);
}
void TimelineWaits(Mode mode) {
if (mode == Mode::NoTimeline) return;
Begin(mode);
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
{
const auto recorder = Make(mode);
for (int index = 0; index < 5; ++index) Batch(*recorder, index, index == 3);
recorder->WaitSerial(2);
recorder->FinishUpTo(2);
Expect(mode, recorder->InFlightBatches() == 3 && mock.semaphoreWaits == 1, "a wait for serial 2 and the completions up to it left " + Count(recorder->InFlightBatches()) + " batches in flight after " + Count(mock.semaphoreWaits) + " timeline waits");
Expect(mode, mock.fenceWaits == (mode == Mode::Fenceless ? 0u : 2u), "the completions up to serial 2 made " + Count(mock.fenceWaits) + " fence waits");
Expect(mode, Settled(*recorder, 0) && Settled(*recorder, 1) && !Settled(*recorder, 3), "the completions up to serial 2 changed what is settled beyond it");
mock.semaphoreWaits = mock.fenceWaits = 0;
recorder->SyncThrough(Address(2), Length, true);
Expect(mode, recorder->InFlightBatches() == 2 && mock.semaphoreWaits == 1, "a sync through serial 3 left " + Count(recorder->InFlightBatches()) + " batches in flight after " + Count(mock.semaphoreWaits) + " timeline waits");
Expect(mode, mock.fenceWaits == (mode == Mode::Fenceless ? 0u : 1u), "the sync through serial 3 made " + Count(mock.fenceWaits) + " fence waits");
ReleaseHeld();
recorder->Sync();
Expect(mode, recorder->Idle(), "a sync left batches in flight");
}
ExpectNoLeaks(mode);
}
void LockedSyncThrough(Mode mode) {
Begin(mode);
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
{
const auto recorder = Make(mode);
for (int index = 0; index < 4; ++index) Batch(*recorder, index, index == 3);
recorder->SyncThrough(Address(1), Length, false);
Expect(mode, recorder->InFlightBatches() == 2, "a sync through serial 2 left " + Count(recorder->InFlightBatches()) + " batches in flight");
Expect(mode, !Settled(*recorder, 2) && !Settled(*recorder, 3), "a sync through serial 2 completed the batches beyond it");
CompleteAll();
Expect(mode, Settled(*recorder, 2) && !Settled(*recorder, 3), "the batch ahead of a waiting submission is not settled after the sync");
ReleaseHeld();
recorder->Sync();
Expect(mode, recorder->Idle(), "a sync left batches in flight");
}
ExpectNoLeaks(mode);
}
void SubmitFailure(Mode mode) {
Begin(mode);
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
{
const auto recorder = Make(mode);
Batch(*recorder, 0);
mock.submitResult = VK_ERROR_OUT_OF_HOST_MEMORY;
bool failed = false;
try {
Batch(*recorder, 1);
} catch (const std::exception& error) {
failed = std::string_view(error.what()).find("vkQueueSubmit recorder") != std::string_view::npos;
}
Expect(mode, failed, "a failed submission did not report its Vulkan failure");
Expect(mode, !recorder->Recording() && recorder->Submissions() == 1 && recorder->InFlightBatches() == 1 && mock.submits == 1, "a failed submission changed the batches in flight");
mock.submitResult = VK_SUCCESS;
Batch(*recorder, 2);
if (mode != Mode::NoTimeline) Expect(mode, mock.queue.size() == 2 && mock.queue.back().signal == 2, "the submission after a failed one did not take the next serial");
CompleteAll();
Expect(mode, Settled(*recorder, 0) && Settled(*recorder, 2) && recorder->Reap() && recorder->Idle(), "the batches around a failed submission did not complete");
if (mode == Mode::Fenceless) Expect(mode, mock.fenceCreates == 0, "a failed submission made a fence");
}
ExpectNoLeaks(mode);
}
void FailedWait(Mode mode, VkResult result) {
Begin(mode);
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
{
const auto recorder = Make(mode);
Batch(*recorder, 0);
Batch(*recorder, 1);
mock.waitResult = result;
bool failed = false;
try {
recorder->Sync();
} catch (const std::exception& error) {
const auto operation = mode == Mode::Fenceless ? "vkWaitSemaphoresKHR recorder" : "vkWaitForFences recorder";
failed = std::string_view(error.what()).find(operation) != std::string_view::npos;
}
Expect(mode, failed, "a failed wait did not report its Vulkan failure");
Expect(mode, recorder->InFlightBatches() == 1 && !recorder->Recording(), "a failed wait left " + Count(recorder->InFlightBatches()) + " batches in flight, not the one it did not reach");
Expect(mode, mock.idleWaits == (result == VK_ERROR_DEVICE_LOST ? 0u : 1u), "a failed wait settled the device " + Count(mock.idleWaits) + " times");
Expect(mode, !Settled(*recorder, 1), "a batch the GPU never completed counted as settled after a failed wait");
mock.waitResult = VK_SUCCESS;
recorder->Sync();
Expect(mode, recorder->Idle(), "a sync after a failed wait left batches in flight");
}
ExpectNoLeaks(mode);
}
void FailedPoll(Mode mode) {
Begin(mode);
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
{
const auto recorder = Make(mode);
Batch(*recorder, 0);
Batch(*recorder, 1);
CompleteAll();
mock.pollResult = VK_ERROR_DEVICE_LOST;
Expect(mode, !recorder->Reap() && recorder->InFlightBatches() == 2, "a reap retired batches whose completion could not be read");
Expect(mode, !Settled(*recorder, 0) && !Settled(*recorder, 1) && recorder->UnsignaledBatches() == 2, "batches whose completion could not be read counted as settled");
mock.pollResult = VK_SUCCESS;
Expect(mode, Settled(*recorder, 1) && recorder->Reap() && recorder->Idle(), "the batches were not retired once their completion could be read");
}
ExpectNoLeaks(mode);
}
void TimelineCreationFails() {
const auto mode = Mode::NoTimeline;
Begin(mode);
mock.createSemaphoreResult = VK_ERROR_OUT_OF_HOST_MEMORY;
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
{
Recorder recorder(mockContext(), true);
Expect(mode, !recorder.HasTimeline(), "a recorder whose timeline failed to create still reports one");
for (int index = 0; index < 3; ++index) Batch(recorder, index);
Expect(mode, mock.fenceCreates != 0 && mock.submitsWithFence == mock.submits, "batches without a timeline were submitted without a fence");
Complete(2);
Expect(mode, !recorder.Reap() && recorder.InFlightBatches() == 1, "a reap without a timeline did not retire the two completed batches");
recorder.Sync();
Expect(mode, recorder.Idle(), "a sync without a timeline left batches in flight");
}
ExpectNoLeaks(mode);
}
std::vector<std::string> Walk(Mode mode) {
std::vector<std::string> trace;
Begin(mode);
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
{
const auto recorder = Make(mode);
std::uint32_t state = 20260101;
const auto next = [&](std::uint32_t bound) {
state = state * 1664525u + 1013904223u;
return (state >> 16) % bound;
};
int submitted = 0;
for (int step = 0; step < 400; ++step) {
std::string line;
switch (next(8)) {
case 0:
case 1:
case 2:
if (submitted < 120) Batch(*recorder, submitted++, next(5) == 0);
line = "submit";
break;
case 3:
case 4:
Complete(1 + next(3));
line = "complete";
break;
case 5:
ReleaseHeld();
line = "release";
break;
case 6:
line = std::string("reap ") + (recorder->Reap() ? "idle" : "busy");
break;
default:
if (next(4) == 0) {
ReleaseHeld();
recorder->Sync();
line = "sync";
} else {
line = "skip";
}
break;
}
line += " flight=" + std::to_string(recorder->InFlightBatches()) + " unsignaled=" + std::to_string(recorder->UnsignaledBatches()) + " settled=";
for (int index = std::max(0, submitted - 12); index < submitted; ++index) line += Settled(*recorder, index) ? '1' : '0';
trace.push_back(line);
}
ReleaseHeld();
recorder->Sync();
Expect(mode, recorder->Idle(), "the walk left batches in flight");
}
ExpectNoLeaks(mode);
return trace;
}
void WalksAgree() {
const auto reference = Walk(Mode::NoTimeline);
for (const auto mode : {Mode::Fenceless, Mode::Fenced}) {
const auto trace = Walk(mode);
std::size_t step = 0;
while (step < trace.size() && step < reference.size() && trace[step] == reference[step]) ++step;
Expect(mode, step == reference.size() && trace.size() == reference.size(), "the walk of random submissions and completions diverged from the fence-only recorder at step " + std::to_string(step) + (step < trace.size() ? ": " + trace[step] + " against " + (step < reference.size() ? reference[step] : std::string("nothing")) : std::string()));
}
}
}
int main() {
try {
for (const auto mode : Modes) {
Configuration(mode);
ReapCost(mode);
HeldFirstBatch(mode);
PartialPrefix(mode);
TimelineWaits(mode);
LockedSyncThrough(mode);
SubmitFailure(mode);
FailedWait(mode, VK_ERROR_DEVICE_LOST);
FailedWait(mode, VK_ERROR_OUT_OF_HOST_MEMORY);
FailedPoll(mode);
}
TimelineCreationFails();
WalksAgree();
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
if (failures != 0) {
std::fprintf(stderr, "%d recorder batch fence checks failed\n", failures);
return 1;
}
std::printf("recorder batch fence tests passed\n");
return 0;
}
@@ -1197,6 +1197,14 @@ void verifyWaterfallRuntimeValues() {
std::uint32_t result = 0;
require(evaluator.Evaluate(Detail::IrNode(&nestedFirst), result) && result == (word == 4u ? word : word + 1u), "waterfall: a nested select ignored its uniform condition");
}
auto& copiedCondition = make(IrOpcode::IEqual32, IrType::Bool, {&input, &lane});
auto& copiedMask = make(IrOpcode::LogicalAnd, IrType::Bool, {&copiedCondition, &uniform});
auto& copiedFirst = make(IrOpcode::ReadFirstLane, IrType::U32, {&selected, &copiedMask});
require(SrtWalker().ValidateRuntimeValue(plan, &copiedFirst), "waterfall: a mask whose conjunct is a structural copy of the select condition was rejected");
auto& negatedCondition = make(IrOpcode::INotEqual32, IrType::Bool, {&input, &lane});
auto& negatedMask = make(IrOpcode::LogicalAnd, IrType::Bool, {&negatedCondition, &uniform});
auto& negatedFirst = make(IrOpcode::ReadFirstLane, IrType::U32, {&selected, &negatedMask});
require(!SrtWalker().ValidateRuntimeValue(plan, &negatedFirst), "waterfall: a mask whose conjunct is the negation of the select condition was accepted");
}
void verifyUniformVectorComponents() {
@@ -1875,6 +1883,24 @@ void verifyTypeZeroImageMaterialization() {
}), "raw-to-known descriptor transition: cached Raw descriptor was not invalidated and replaced by KnownValue");
}
phase = 4u;
waits = 0u;
flushed = false;
record0Addr = srtAddress;
record1Addr = 0u;
pendingT0 = thirdT;
{
AgcDriver::ShaderMemory forcedSpanMemory({}, multiPending, nullptr, hookWaits);
static_cast<void>(AgcDriver::ShaderMemory::descriptorScope(&forcedSpanMemory, SrtDescriptorForceSync));
const auto forcedCapture = forcedSpanMemory.Capture(request);
static_cast<void>(AgcDriver::ShaderMemory::descriptorScope(&forcedSpanMemory, SrtDescriptorEndForceSync));
require(std::ranges::any_of(forcedCapture->snapshot.images, [&](const DescriptorValue& value) {
return std::equal(oldT.begin(), oldT.end(), value.dwords.begin());
}) && std::ranges::none_of(forcedCapture->snapshot.images, [&](const DescriptorValue& value) {
return std::equal(thirdT.begin(), thirdT.end(), value.dwords.begin());
}), "force-sync descriptor span: a T# span read under SrtDescriptorForceSync took the KnownValue bytes instead of reading through the flush hook");
}
for (std::uint32_t record = 0; record < 128u; ++record) {
std::copy(oldT.begin(), oldT.end(), srt.begin() + record * 8u);
}
@@ -1,7 +1,11 @@
#include "Recompiler.hpp"
#include "IntermediateRepresentation/IrBuilder.hpp"
#include "SpirvBackend/SpirvEmitter.hpp"
#if ANYPS5_ENABLE_SPIRV_TOOLS
#include <spirv-tools/libspirv.hpp>
#endif
#include "IntermediateRepresentation/IrProgram.hpp"
#include "Optimization/ShaderStageInputInfo.hpp"
#include "SpirvBackend/SpirvEmitter.hpp"
#include "SpirvBackend/SpirvOptimizer.hpp"
#include <spirv/unified1/spirv.hpp>
#include <array>
@@ -51,6 +55,153 @@ std::vector<std::uint32_t> recompile(std::span<const std::uint32_t> code) {
return result.spirv.Copy();
}
enum class SampleSelection { Plain, Entry, Arithmetic, EntryLoop, Loop };
void requireUniformSampleSelection(SampleSelection shape) {
const bool selected = shape != SampleSelection::Plain;
const bool arithmetic = shape == SampleSelection::Arithmetic;
const bool loop = shape == SampleSelection::EntryLoop || shape == SampleSelection::Loop;
IrProgram program;
program.SetWaveSize(32u);
program.Resources().stage = IrShaderStage::Pixel;
program.Resources().srtPlanComplete = true;
program.Resources().resourceTrackingComplete = true;
program.Metadata().shaderInfoComplete = true;
program.Metadata().bindingLayoutComplete = true;
auto& entry = program.CreateBlock();
program.SetEntryBlock(entry);
program.BlockOrder().push_back(&entry);
program.Metadata().blockInfo.emplace_back();
IrBlock* headerBlock = &entry;
if (shape == SampleSelection::Loop) {
headerBlock = &program.CreateBlock();
program.BlockOrder().push_back(headerBlock);
program.Metadata().blockInfo.emplace_back().id = headerBlock->Id();
program.Metadata().blockInfo.front().terminator.kind = TerminatorKind::Branch;
program.Metadata().blockInfo.front().terminator.trueBlock = headerBlock->Id();
entry.AddBranch(headerBlock);
}
IrBuilder builder(program);
builder.SetInsertionPoint(*headerBlock);
auto& zero = builder.Constant(0u);
auto& flag = builder.GetUserData(static_cast<ScalarReg>(0u));
auto& condition = builder.INotEqual(flag, zero);
auto& imageHandle = builder.Emit(IrOpcode::GetImageResource, IrType::ImageResource, {&zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero});
auto& samplerHandle = builder.Emit(IrOpcode::GetSamplerResource, IrType::SamplerResource, {&zero, &zero, &zero, &zero});
auto& address = builder.Emit(IrOpcode::MakeImageAddress, IrType::ImageAddress, {&zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero});
auto& sample = builder.Emit(IrOpcode::ImageSampleRaw, IrType::U32x4, {&imageHandle, &samplerHandle, &address, &builder.ConstantBool(true)});
auto& channel = builder.CompositeExtract(sample, 0u);
const auto repair = [&](IrValue& bits) -> IrValue& {
auto& magnitude = builder.Emit(IrOpcode::BitwiseAnd32, IrType::U32, {&bits, &builder.Constant(0x7fffffffu)});
auto& isNan = builder.Emit(IrOpcode::UGreaterThan32, IrType::Bool, {&magnitude, &builder.Constant(0x7f800000u)});
return builder.Select(isNan, builder.Constant(0x7fc12345u), bits);
};
auto& value = arithmetic ? repair(repair(channel)) : channel;
if (selected) {
auto& output = builder.Select(condition, value, zero);
if (arithmetic) static_cast<void>(repair(repair(output)));
}
MemoryInfo memory{};
memory.kind = ResourceKind::Image;
memory.imageDimension = RdnaImageDimension::Dim2D;
memory.imageAddressComponents = 3u;
memory.imageSampleFlags = RdnaImageSampleFlagCompare;
memory.dmask = 0xfu;
memory.dataDwords = 4u;
memory.componentCount = 4u;
program.Resources().memoryInfo.push_back(memory);
ImageResource image{};
image.resourceClass = ImageResourceClass::Sampled;
image.numericClass = IrTextureNumericClass::Float;
image.dimension = memory.imageDimension;
image.read = true;
image.depthCompare = true;
image.emulatedCompare = EmulatedCompare::Unsupported;
image.fmaskCompatible = false;
image.cubeFaceCompatible = false;
image.flatLineCompatible = false;
program.Info().images.push_back(image);
program.Info().samplers.emplace_back().depthCompare = true;
auto& layout = program.Metadata().bindings;
layout.userDataRegisters = {0u};
layout.memoryOffsetDword = 1u;
layout.pushDataStartDword = 0u;
layout.descriptors = {{DescriptorBindingForImage(image), {0u}}, {DescriptorBindingKind::Samplers, {0u}}};
if (loop) {
auto& continuation = program.CreateBlock();
auto& exit = program.CreateBlock();
program.BlockOrder().push_back(&continuation);
program.BlockOrder().push_back(&exit);
program.Metadata().blockInfo.resize(program.BlockOrder().size());
auto& header = program.Metadata().blockInfo[headerBlock->Id()];
header.condition = &condition;
header.terminator.kind = TerminatorKind::ConditionalBranch;
header.terminator.trueBlock = continuation.Id();
header.terminator.falseBlock = exit.Id();
header.terminator.mergeBlock = exit.Id();
header.terminator.continueBlock = continuation.Id();
header.terminator.loopHeader = true;
auto& backedge = program.Metadata().blockInfo[continuation.Id()];
backedge.id = continuation.Id();
backedge.terminator.kind = TerminatorKind::Branch;
backedge.terminator.trueBlock = headerBlock->Id();
program.Metadata().blockInfo[exit.Id()].id = exit.Id();
headerBlock->AddBranch(&continuation);
headerBlock->AddBranch(&exit);
continuation.AddBranch(headerBlock);
}
ShaderPixelInputInfo pixel{};
ShaderStageInputInfo inputs{};
inputs.pixel = &pixel;
CompiledBindingLayout bindings{};
bindings.layout = layout;
bindings.pushConstantSizeBytes = 4u;
SpirvTargetOptions target{};
target.vulkanVersion = 0x00401000u;
target.spirvVersion = 0x00010300u;
target.subgroupSize = 32u;
std::vector<std::uint32_t> words;
try {
words = SpirvEmitter().Emit(program, inputs, bindings, target);
} catch (const std::runtime_error& error) {
if (shape == SampleSelection::EntryLoop && std::string_view(error.what()) == "value IR entry block has a predecessor") return;
throw;
}
require(shape != SampleSelection::EntryLoop, "uniform sample selection: accepted a backedge to the entry block");
std::uint32_t label = 0u;
std::uint32_t loopLabel = 0u;
std::uint32_t continueLabel = 0u;
bool backedgeFound = false;
std::uint32_t selections = 0u;
for (std::size_t cursor = 5u; cursor < words.size();) {
const auto count = words[cursor] >> 16u;
require(count != 0u && count <= words.size() - cursor, "uniform sample selection: truncated SPIR-V instruction");
const auto opcode = words[cursor] & 0xffffu;
if (opcode == spv::OpLabel) label = words[cursor + 1u];
if (opcode == spv::OpLoopMerge) {
loopLabel = label;
continueLabel = words[cursor + 2u];
}
if (opcode == spv::OpBranch && label == continueLabel) {
require(words[cursor + 1u] == loopLabel, "uniform sample selection: backedge does not target the loop header");
backedgeFound = true;
}
if (opcode == spv::OpSelectionMerge && words[cursor + 2u] == spv::SelectionControlDontFlattenMask) ++selections;
cursor += count;
}
require(loop ? loopLabel != 0u && backedgeFound : loopLabel == 0u, "uniform sample selection: unexpected loop structure");
require(selections == (selected && !loop ? 1u : 0u) + (arithmetic ? 1u : 0u), "uniform sample selection: unexpected guarded sample region count");
#if ANYPS5_ENABLE_SPIRV_TOOLS
std::string diagnostics;
spvtools::SpirvTools validator(SPV_ENV_VULKAN_1_1);
validator.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&, const char* message) {
if (message != nullptr) diagnostics += std::string(message) + '\n';
});
const bool valid = validator.Validate(words.data(), words.size());
require(valid, "uniform sample selection: invalid SPIR-V:\n" + diagnostics);
#endif
}
void requireDistinctTargets(const char* name, std::span<const std::uint32_t> code) {
const auto words = recompile(code);
for (std::size_t cursor = 5; cursor < words.size();) {
@@ -170,6 +321,11 @@ void requireCrossRegionNan(bool conjunct, bool certified = false, bool unproved
int main() {
try {
requireUniformSampleSelection(SampleSelection::Plain);
requireUniformSampleSelection(SampleSelection::Entry);
requireUniformSampleSelection(SampleSelection::Arithmetic);
requireUniformSampleSelection(SampleSelection::EntryLoop);
requireUniformSampleSelection(SampleSelection::Loop);
constexpr std::array<std::uint32_t, 2> zeroOffsetBranch{0xbf840000u, 0xbf810000u};
requireDistinctTargets("s_cbranch_scc0 to the next instruction", zeroOffsetBranch);
constexpr std::array<std::uint32_t, 4> unalignedStore{0x7e020281u, 0xe0700000u, 0x80020100u, 0xbf810000u};
@@ -187,6 +343,6 @@ int main() {
std::fprintf(stderr, "SpirvBranchTargets: %s\n", error.what());
return 1;
}
std::puts("SpirvBranchTargets: no conditional branch names one label twice");
std::puts("SpirvBranchTargets: branch targets and uniform sample selections preserve structure");
return 0;
}
@@ -170,6 +170,66 @@ void testIdsStayUniqueBeyondCacheCapacity() {
check(first > typeU32, "a constant was numbered before the type it uses");
}
void testSelectTreeOverSpecializedFormatFolds() {
constexpr std::uint32_t Entries = 78u;
const auto entry = [](std::uint32_t index) { return index < Entries ? 0x100u + (index / 2u) * 7u : 0u; };
for (std::uint32_t format = 0; format < 128u; ++format) {
SpirvModule module;
module.EmitCapability(spv::CapabilityShader);
const auto typeVoid = module.Type(spv::OpTypeVoid);
const auto typeBool = module.Type(spv::OpTypeBool);
const auto typeU32 = module.Type(spv::OpTypeInt, 32u, 0u);
const auto zero = module.Constant(spv::OpConstant, typeU32, 0u);
const auto word3 = module.Constant(spv::OpConstant, typeU32, (format << 12u) | 0xfacu);
const auto typePrivatePtr = module.Type(spv::OpTypePointer, spv::StorageClassPrivate, typeU32);
const auto typeFunction = module.Type(spv::OpTypeFunction, typeVoid);
const auto output = module.DefineGlobalVariable(typePrivatePtr, spv::StorageClassPrivate);
const auto mainId = module.AllocateId();
module.AddFunction(spv::OpFunction, typeVoid, mainId, spv::FunctionControlMaskNone, typeFunction);
module.AddFunction(spv::OpLabel, module.AllocateId());
const auto field = module.AllocateId();
module.AddFunction(spv::OpBitFieldUExtract, typeU32, field, word3, module.Constant(spv::OpConstant, typeU32, 12u), module.Constant(spv::OpConstant, typeU32, 7u));
std::vector<std::uint32_t> odd;
for (std::uint32_t span = 1u; span < Entries; span <<= 1u) {
const auto masked = module.AllocateId();
module.AddFunction(spv::OpBitwiseAnd, typeU32, masked, field, module.Constant(spv::OpConstant, typeU32, span));
const auto set = module.AllocateId();
module.AddFunction(spv::OpINotEqual, typeBool, set, masked, zero);
odd.push_back(set);
}
std::vector<std::uint32_t> values;
for (std::uint32_t index = 0; index < (1u << odd.size()); ++index) values.push_back(module.Constant(spv::OpConstant, typeU32, entry(index)));
for (const auto condition : odd) {
std::vector<std::uint32_t> halves;
for (std::size_t pair = 0; pair < values.size(); pair += 2u) {
if (values[pair] == values[pair + 1u]) {
halves.push_back(values[pair]);
continue;
}
const auto chosen = module.AllocateId();
module.AddFunction(spv::OpSelect, typeU32, chosen, condition, values[pair + 1u], values[pair]);
halves.push_back(chosen);
}
values = std::move(halves);
}
module.AddFunction(spv::OpStore, output, values.front());
module.AddFunction(spv::OpReturn);
module.AddFunction(spv::OpFunctionEnd);
const auto folded = ShaderRecompiler::SpecializeSpirv(module.Finalize());
const auto counts = opcodeCounts(folded);
check(!counts.contains(spv::OpSelect), "a select tree over a specialized buffer format kept an OpSelect");
check(!counts.contains(spv::OpBitFieldUExtract), "a specialized buffer format field was not folded");
std::map<std::uint32_t, std::uint32_t> constants;
std::uint32_t stored = 0;
for (std::size_t cursor = 5; cursor < folded.size(); cursor += folded[cursor] >> 16u) {
if ((folded[cursor] >> 16u) == 0u) break;
if ((folded[cursor] & 0xffffu) == spv::OpConstant && (folded[cursor] >> 16u) == 4u) constants[folded[cursor + 2u]] = folded[cursor + 3u];
if ((folded[cursor] & 0xffffu) == spv::OpStore && folded[cursor + 1u] == output) stored = folded[cursor + 2u];
}
check(constants.contains(stored) && constants.at(stored) == entry(format), "a select tree over a specialized buffer format folded to the wrong entry");
}
}
void testEmittedWordsAreStable() {
SpirvModule module;
const auto typeU32 = module.Type(spv::OpTypeInt, 32u, 0u);
@@ -632,6 +692,7 @@ int main() {
testIdsBeyondTheBoundAreRejected();
testStructExtractsAreNotShuffled();
testPrivateCompositeTableLoadFolding();
testSelectTreeOverSpecializedFormatFolds();
testRepeatedTypesShareOneId();
testOperandShapesDoNotCollide();
testOperandKindsAgree();
@@ -140,6 +140,31 @@ struct Hull {
static_cast<void>(builder.Emit(IrOpcode::ReferenceU32, IrType::Void, {&loaded}));
}
IrValue& addWithCarry(IrValue& lhs, IrValue& rhs) {
return builder.Emit(IrOpcode::IAddCarry32, IrType::U32x2, {&lhs, &rhs});
}
IrValue& sum(IrValue& pair) {
return builder.Emit(IrOpcode::CompositeExtractU32x2, IrType::U32, {&pair, &builder.Constant(0u)});
}
IrValue& carry(IrValue& pair) {
return builder.Emit(IrOpcode::INotEqual32, IrType::Bool, {&builder.Emit(IrOpcode::CompositeExtractU32x2, IrType::U32, {&pair, &builder.Constant(1u)}), &builder.Constant(0u)});
}
IrValue& carryIn(IrValue& set) {
return builder.Emit(IrOpcode::SelectU32, IrType::U32, {&set, &builder.Constant(1u), &builder.Constant(0u)});
}
void writeFactor(IrValue& offset) {
auto& base = builder.Emit(IrOpcode::TessellationBase, IrType::U32, {&builder.Constant(static_cast<std::uint32_t>(TessellationBaseKind::Factor))});
static_cast<void>(builder.Emit(IrOpcode::StoreBufferU32, IrType::Void, {&ringResource(), &builder.Constant(0u), &offset, &base, &builder.Constant(1u), &builder.ConstantBool(true)}, MemoryFlags{RingMemory, RingWritePc}));
}
IrValue& field(IrValue& source, std::uint32_t offset, std::uint32_t count, bool sign = false) {
return builder.Emit(sign ? IrOpcode::BitFieldSExtract : IrOpcode::BitFieldUExtract, IrType::U32, {&source, &builder.Constant(offset), &builder.Constant(count)});
}
IrValue& packed() {
return builder.BitwiseOr(builder.ShiftLeftLogical(invocation(), builder.Constant(8u)), relativePatch());
}
@@ -253,6 +278,24 @@ std::size_t Barriers(const IrProgram& program) {
return count;
}
std::vector<std::uint32_t> WrittenAddresses(const IrBlock& block) {
std::vector<std::uint32_t> addresses;
for (const IrValue* inst : block.Instructions()) {
if (!IsControlOutputWrite(inst)) continue;
const IrValue* address = inst->Argument(1)->Resolve();
addresses.push_back(address->HasImmediate() ? address->ImmediateU32() : ~0u);
}
return addresses;
}
bool WritesOwnFields(Hull& hull, std::uint32_t second) {
if (!LowersRing(hull.program)) return false;
const auto written = WrittenAddresses(*hull.block);
if (written.size() == 2u && written[0] != ~0u && written[1] == written[0] + second) return true;
for (const auto address : written) std::fprintf(stderr, "written at 0x%x\n", address);
return false;
}
std::uint32_t ReadAddress(const IrBlock& block) {
for (const IrValue* inst : block.Instructions()) {
if (!IsControlOutputRead(inst)) continue;
@@ -1059,6 +1102,135 @@ int main() {
return RingRefusedBecause(hull.program, "writes no control point there");
});
passed &= run("a ring address summed by an add with carry-out lowers like a plain add", [] {
Hull hull;
hull.writeRing(hull.ownControlPoint(0u));
auto& pair = hull.addWithCarry(hull.builder.IMul(hull.relativePatch(), hull.builder.Constant(ControlPatchStride)), hull.builder.IAdd(hull.builder.IMul(hull.invocation(), hull.builder.Constant(ControlStride)), hull.builder.Constant(16u)));
hull.writeRing(hull.sum(pair));
return WritesOwnFields(hull, 16u);
});
passed &= run("the carry of an address add that cannot wrap is zero when it feeds a high-word add of zero", [] {
Hull hull;
hull.writeRing(hull.ownControlPoint(0u));
auto& pair = hull.addWithCarry(hull.ring(hull.builder.IMul(hull.invocation(), hull.builder.Constant(ControlStride))), hull.builder.Constant(16u));
hull.writeRing(hull.sum(pair));
auto& high = hull.sum(hull.addWithCarry(hull.builder.Constant(0u), hull.carryIn(hull.carry(pair))));
static_cast<void>(hull.builder.Emit(IrOpcode::ReferenceU32, IrType::Void, {&high}));
return WritesOwnFields(hull, 16u);
});
passed &= run("an add with carry-in from an address add that cannot wrap lowers like a plain add", [] {
Hull hull;
hull.writeRing(hull.ownControlPoint(0u));
auto& first = hull.addWithCarry(hull.ring(hull.builder.IMul(hull.invocation(), hull.builder.Constant(ControlStride))), hull.builder.Constant(8u));
auto& second = hull.addWithCarry(hull.sum(first), hull.carryIn(hull.carry(first)));
hull.writeRing(hull.builder.IAdd(hull.sum(second), hull.builder.Constant(4u)));
return WritesOwnFields(hull, 12u);
});
passed &= run("a subtract whose borrow-in cannot be set lowers like a plain subtract", [] {
Hull hull;
hull.writeRing(hull.ownControlPoint(0u));
auto& field = hull.ownControlPoint(24u);
auto& partial = hull.builder.ISub(field, hull.builder.Constant(4u));
auto& borrow = hull.builder.Emit(IrOpcode::ULessThan32, IrType::Bool, {&field, &hull.builder.Constant(4u)});
hull.writeRing(hull.builder.ISub(partial, hull.carryIn(borrow)));
return WritesOwnFields(hull, 20u);
});
passed &= run("an add with carry-in that can be set stays refused", [] {
Hull hull;
hull.writeRing(hull.ownControlPoint(0u));
auto& wraps = hull.addWithCarry(hull.ownControlPoint(32u), hull.builder.Constant(0xfffffff0u));
auto& pair = hull.addWithCarry(hull.ownControlPoint(16u), hull.carryIn(hull.carry(wraps)));
hull.writeRing(hull.sum(pair));
return RingRefusedBecause(hull.program, "not affine in the control point and relative patch");
});
passed &= run("a ring address whose add with carry-out can wrap is refused", [] {
Hull hull;
hull.writeRing(hull.ownControlPoint(0u));
hull.writeRing(hull.sum(hull.addWithCarry(hull.ownControlPoint(16u), hull.builder.Constant(0xfffffff0u))));
return RingRefusedBecause(hull.program, "not affine in the control point and relative patch");
});
passed &= run("a hull program with one output control point writes quad factors at an address that adds its invocation", [] {
Hull hull;
auto& packed = hull.packed();
auto& point = hull.field(packed, 8u, 5u);
auto& patch = hull.field(packed, 0u, 8u);
for (std::uint32_t factor = 0; factor < 6u; ++factor) {
auto& scaled = hull.builder.ShiftRightLogical(hull.builder.IAdd(hull.builder.ShiftLeftLogical(point, hull.builder.Constant(4u)), hull.builder.Constant(16u * factor)), hull.builder.Constant(2u));
hull.writeFactor(hull.builder.IAdd(hull.builder.IMul(hull.field(patch, 0u, 24u), hull.field(hull.builder.Constant(24u), 0u, 24u)), scaled));
}
auto tessellation = Tessellation;
tessellation.domain = 2u;
tessellation.outputControlPoints = 1u;
const auto outcome = Lower(hull.program, tessellation);
if (!outcome.lowered) std::fprintf(stderr, "refused: %s\n", outcome.reason.c_str());
return outcome.lowered;
});
passed &= run("a merged hull program with one control point writes its LDS record at an address that adds its invocation", [] {
Hull hull;
auto& record = hull.builder.IMul(hull.relativePatch(), hull.builder.Constant(16u));
auto& own = hull.builder.IAdd(record, hull.builder.IMul(hull.invocation(), hull.builder.Constant(16u)));
static_cast<void>(hull.builder.Emit(IrOpcode::WriteSharedU32, IrType::Void, {&own, &hull.builder.Constant(7u), &hull.builder.ConstantBool(true)}, MemoryFlags{0u, RingWritePc}));
static_cast<void>(hull.read(hull.builder.IAdd(hull.builder.IMul(hull.relativePatch(), hull.builder.Constant(16u)), hull.builder.Constant(4u))));
const ShaderTessellationInputInfo merged{.inputControlPoints = 1u, .outputControlPoints = 1u, .patchesPerGroup = 1u, .mergedHull = true};
const TessellationTargetLimits limits{32u, 128u, 128u, 120u, 4096u, 128u, 128u};
try {
TessellationLowering{}.Lower(hull.program, merged, &limits);
} catch (const std::exception& error) {
std::fprintf(stderr, "refused: %s\n", error.what());
return false;
}
return true;
});
passed &= run("quad factors at an address that adds the invocation are refused when the hull program has several control points", [] {
Hull hull;
hull.writeFactor(hull.builder.IAdd(hull.builder.IMul(hull.relativePatch(), hull.builder.Constant(24u)), hull.builder.IMul(hull.invocation(), hull.builder.Constant(4u))));
auto tessellation = Tessellation;
tessellation.domain = 2u;
const auto outcome = Lower(hull.program, tessellation);
return !outcome.lowered && outcome.reason.find("outside its patch's quad factors") != std::string::npos;
});
passed &= run("a ring address from a signed 24-bit multiply-add of non-negative operands lowers like an unsigned one", [] {
Hull hull;
hull.writeRing(hull.ownControlPoint(0u));
auto& product = hull.builder.IMul(hull.field(hull.invocation(), 0u, 24u, true), hull.field(hull.builder.Constant(ControlStride), 0u, 24u, true));
hull.writeRing(hull.builder.IAdd(product, hull.ring(hull.builder.Constant(8u))));
return WritesOwnFields(hull, 8u);
});
passed &= run("a ring address from an arithmetic shift of a value below the sign bit lowers like a logical shift", [] {
Hull hull;
hull.writeRing(hull.ownControlPoint(0u));
auto& shifted = hull.builder.Emit(IrOpcode::ShiftRightArithmetic32, IrType::U32, {&hull.builder.ShiftLeftLogical(hull.ownControlPoint(8u), hull.builder.Constant(4u)), &hull.builder.Constant(4u)});
auto& field = hull.builder.Emit(IrOpcode::ShiftRightArithmetic32, IrType::U32, {&hull.builder.Constant(0x40u), &hull.builder.Constant(4u)});
hull.writeRing(hull.builder.IAdd(shifted, field));
return WritesOwnFields(hull, 12u);
});
passed &= run("an arithmetic shift of a value that can reach the sign bit is refused", [] {
Hull hull;
hull.writeRing(hull.ownControlPoint(0u));
auto& wide = hull.builder.Emit(IrOpcode::ShiftRightArithmetic32, IrType::U32, {&hull.builder.IMul(hull.invocation(), hull.builder.Constant(0x30000000u)), &hull.builder.Constant(4u)});
hull.writeRing(hull.builder.IAdd(wide, hull.ring(hull.builder.Constant(8u))));
return RingRefusedBecause(hull.program, "not affine in the control point and relative patch");
});
passed &= run("a signed 24-bit field that can reach its sign bit is refused", [] {
Hull hull;
hull.writeRing(hull.ownControlPoint(0u));
auto& wide = hull.field(hull.builder.IMul(hull.invocation(), hull.builder.Constant(0x300000u)), 0u, 24u, true);
hull.writeRing(hull.builder.IAdd(wide, hull.ring(hull.builder.Constant(8u))));
return RingRefusedBecause(hull.program, "not affine in the control point and relative patch");
});
passed &= run("a hull read past its patch's off-chip control points is refused", [] {
Hull hull;
hull.writeRing(hull.ownControlPoint(0u));
@@ -146,7 +146,7 @@ void requireSliceAddresses(const GuestTextureResource& resource, std::uint32_t b
}
}
std::uint64_t referenceGcnAddress(TextureTileMode mode, std::uint32_t bytes, std::uint32_t pitch, std::uint32_t height, std::uint32_t x, std::uint32_t y, std::uint32_t slice = 0u) {
std::uint64_t referenceGcnAddress(TextureTileMode mode, std::uint32_t bytes, std::uint32_t pitch, std::uint32_t height, std::uint32_t x, std::uint32_t y, std::uint32_t slice = 0u, std::uint32_t samples = 1u, std::uint32_t sample = 0u) {
const auto bit = [](std::uint32_t value, std::uint32_t index) { return (value >> index) & 1u; };
const std::uint32_t x0 = bit(x, 0), x1 = bit(x, 1), x2 = bit(x, 2), y0 = bit(y, 0), y1 = bit(y, 1), y2 = bit(y, 2);
std::array<std::uint32_t, 6> pixel{x0, y0, x1, y1, x2, y2};
@@ -161,8 +161,8 @@ std::uint64_t referenceGcnAddress(TextureTileMode mode, std::uint32_t bytes, std
}
std::uint32_t pixelIndex = 0;
for (std::uint32_t index = 0; index < 6u; ++index) pixelIndex |= pixel[index] << index;
std::uint64_t microBytes = 64u * bytes;
std::uint64_t elementOffset = static_cast<std::uint64_t>(pixelIndex) * bytes;
std::uint64_t microBytes = 64u * bytes * samples;
std::uint64_t elementOffset = (static_cast<std::uint64_t>(pixelIndex) * samples + sample) * bytes;
if (mode == TextureTileMode::kGcnThin1D || mode == TextureTileMode::kGcnDisplay1D) {
return (static_cast<std::uint64_t>(y / 8u) * (pitch / 8u) + x / 8u) * microBytes + elementOffset;
}
@@ -615,11 +615,84 @@ void sizeOnlySurfaceTests() {
reject([&] { DescribeSurfaceGuestBytes(array); }, "texture mip count is out of range");
}
void gcnMultisampleTilingTests() {
using enum TextureTileMode;
std::uint32_t compared = 0;
for (const auto mode : {kGcnDepth2D64, kGcnDepth2D128, kGcnDepth2D256, kGcnDepth2D512, kGcnDepth2D1K, kGcnDepthPrt256, kGcnDepthPrt1K}) {
for (std::uint32_t bytes = 1u; bytes <= 8u; bytes <<= 1u) {
for (std::uint32_t samples = 2u; samples <= 8u; samples <<= 1u) {
const auto what = "PS4 depth tile mode " + std::to_string(static_cast<int>(mode)) + " at " + std::to_string(bytes) + " bytes and " + std::to_string(samples) + " samples";
const auto split = mode == kGcnDepthPrt256 ? 256u : mode == kGcnDepthPrt1K ? 1024u : 64u << (static_cast<std::uint32_t>(mode) - static_cast<std::uint32_t>(kGcnDepth2D64));
const auto microBytes = 64u * bytes * samples;
if (microBytes / std::min(split, microBytes) > 16u) {
reject([&] { GcnTiling(mode, bytes, samples); }, "split into more than 16 slices");
continue;
}
const auto geometry = GcnTiling(mode, bytes, samples);
Require(geometry.splitSlices == microBytes / std::min(split, microBytes), what + ": split slice count differs from addrlib");
Require(geometry.blockBytes * geometry.splitSlices == geometry.blockWidth * geometry.blockHeight * bytes * samples, what + ": a block holds its samples exactly");
const auto splitStride = 16u * geometry.blockBytes;
const auto pitch = geometry.blockWidth * 4u;
const auto height = geometry.blockHeight * 4u;
const auto parity = [](std::uint32_t x, std::uint32_t y, std::uint32_t sample, std::uint32_t mask) { return static_cast<std::uint32_t>(std::popcount((x & mask & 0xfffu) ^ ((y << 12u) & mask & 0xfff000u) ^ ((sample << GcnSampleShift) & mask)) & 1); };
std::vector<std::uint8_t> seen(static_cast<std::size_t>(pitch) * height * samples, 0u);
for (std::uint32_t y = 0; y < height; ++y) {
for (std::uint32_t x = 0; x < pitch; ++x) {
for (std::uint32_t sample = 0; sample < samples; ++sample) {
std::uint32_t inBlock = 0, slice = 0;
for (std::uint32_t bit = 0; bit < 16u; ++bit) inBlock |= parity(x, y, sample, geometry.equation[bit]) << bit;
for (std::uint32_t bit = 0; bit < geometry.splitMasks.size(); ++bit) slice |= parity(x, y, sample, geometry.splitMasks[bit]) << bit;
const auto block = static_cast<std::uint64_t>(y / geometry.blockHeight) * (pitch / geometry.blockWidth) + x / geometry.blockWidth;
const auto address = block * geometry.blockBytes + inBlock + static_cast<std::uint64_t>(slice) * splitStride;
const auto expected = referenceGcnAddress(mode, bytes, pitch, height, x, y, 0u, samples, sample);
if (address != expected) Require(false, what + ": sample " + std::to_string(sample) + " of element " + std::to_string(x) + "," + std::to_string(y) + " is at " + std::to_string(address) + ", addrlib places it at " + std::to_string(expected));
Require(address % bytes == 0 && address / bytes < seen.size() && seen[address / bytes]++ == 0, what + ": two samples share an address or one leaves the surface");
}
}
}
++compared;
}
}
}
Require(compared == 80u, "the PS4 multisampled depth tiling sweep compared " + std::to_string(compared) + " layouts, not 80");
GuestTextureResource depth{};
depth.width = 1600u;
depth.height = 1800u;
depth.gcnPitch = 1792u;
depth.mipCount = 1u;
depth.allocatedMipCount = 1u;
depth.samples = 2u;
depth.tileMode = kGcnDepth2D64;
depth.dimension = TextureDimension::k2DMsaa;
depth.format = 20u;
const auto described = DescribeSurface(depth);
Require(described.guestBytes == 1792u * 1920u * 4u * 2u && DescribeSurfaceGuestBytes(depth) == described.guestBytes && described.layerBytes == described.guestBytes, "a 2-sample 32-bit PS4 depth texture of pitch 1792 and height 1800 holds 1792 x 1920 x 4 bytes x 2 samples");
Require(described.mips.size() == 1u && described.mips[0].gcnSplitStride == 1792u * 1920u * 4u * 2u / 8u && described.sliceLinearBytes == 1792u * 1800u * 4u * 2u, "a 2-sample 32-bit PS4 depth texture splits into eight 64-byte slices");
Require(described.mips[0].pitchBytes == 1792u * 2u * 4u && described.mips[0].linearSize == static_cast<std::uint64_t>(described.mips[0].pitchBytes) * 1800u, "a 2-sample 32-bit PS4 depth row holds both samples of its 1792 elements, as a PS5 multisampled row does");
auto splitBy128 = depth;
splitBy128.tileMode = kGcnDepth2D128;
const auto described128 = DescribeSurface(splitBy128);
Require(described128.guestBytes == 1792u * 1920u * 4u * 2u && described128.mips[0].gcnSplitStride == 1792u * 1920u * 4u * 2u / 4u && GcnTiling(kGcnDepth2D128, 4u, 2u).blockWidth == 128u && GcnTiling(kGcnDepth2D128, 4u, 2u).blockHeight == 128u, "a 2-sample 32-bit PS4 depth texture in the 128-byte split mode pads 1800 rows to 1920 in 128x128 macro tiles and splits into four slices");
auto stencil = depth;
stencil.format = 1u;
Require(DescribeSurface(stencil).guestBytes == 1792u * 1920u * 2u, "a 2-sample 8-bit PS4 depth texture of pitch 1792 and height 1800 holds 1792 x 1920 x 2 bytes");
auto color = depth;
color.tileMode = kGcnThin2D;
reject([&] { DescribeSurface(color); }, "PS4 multisampled textures outside the depth tile modes are not implemented");
reject([&] { GcnTiling(kGcnThin2D, 4u, 2u); }, "only modeled for 2, 4 or 8 samples in a depth tile mode");
auto mipped = depth;
mipped.mipCount = 2u;
reject([&] { DescribeSurface(mipped); }, "mip levels or array layers are not implemented");
reject([&] { ComputeGcnMipLayout(kGcnDepth2D64, 20u, 1792u, 1800u, 1792u, false, 2u, false, 1u, false, 2u); }, "one level and one slice in a depth tile mode");
}
}
void RunTextureTilingTests() {
gcnTilingTests();
gcnThickTilingTests();
gcnMultisampleTilingTests();
sizeOnlySurfaceTests();
{
const auto mips = ComputeMipLayout(TextureTileMode::kLinear, 1, 4, 4, 2);
@@ -0,0 +1,3 @@
if(BUILD_TESTING)
agc_add_draw_pipeline_test(agc_driver_draw_pipeline_producer_wake)
endif()
@@ -76,6 +76,7 @@ configure_windows_unwind(agc_driver_graphics_tests)
if(BUILD_TESTING)
add_test(NAME agc_driver_undithered_alpha_to_coverage_state COMMAND agc_driver_graphics_tests --undithered-alpha-to-coverage-state)
add_test(NAME agc_driver_depth_bounds_state COMMAND agc_driver_graphics_tests --depth-bounds-state)
add_test(NAME agc_driver_vertex_control_state COMMAND agc_driver_graphics_tests --vertex-control-state)
add_test(NAME agc_driver_linear_volume_nonresident COMMAND agc_driver_graphics_tests --linear-volume-nonresident)
set_tests_properties(agc_driver_linear_volume_nonresident PROPERTIES ENVIRONMENT "APS5_NO_RESIDENT_LINEAR=1" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
if(WIN32)
@@ -85,13 +86,13 @@ if(BUILD_TESTING)
add_test(NAME agc_driver_msaa_dcc_state COMMAND agc_driver_graphics_tests --multisample-dcc-state)
add_test(NAME agc_driver_unused_viewport_depth COMMAND agc_driver_graphics_tests --unused-viewport-depth)
set_tests_properties(agc_driver_unused_viewport_depth PROPERTIES TIMEOUT 30)
set_tests_properties(agc_driver_undithered_alpha_to_coverage_state agc_driver_depth_bounds_state PROPERTIES
set_tests_properties(agc_driver_undithered_alpha_to_coverage_state agc_driver_depth_bounds_state agc_driver_vertex_control_state PROPERTIES
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
add_test(NAME agc_driver_alpha_to_coverage_state COMMAND agc_driver_graphics_tests --alpha-to-coverage-state)
set_tests_properties(agc_driver_alpha_to_coverage_state PROPERTIES
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
if(WIN32)
set_tests_properties(agc_driver_alpha_to_coverage_state agc_driver_undithered_alpha_to_coverage_state agc_driver_depth_bounds_state agc_driver_msaa_dcc_state agc_driver_unused_viewport_depth PROPERTIES ENVIRONMENT_MODIFICATION
set_tests_properties(agc_driver_alpha_to_coverage_state agc_driver_undithered_alpha_to_coverage_state agc_driver_depth_bounds_state agc_driver_vertex_control_state agc_driver_msaa_dcc_state agc_driver_unused_viewport_depth PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
@@ -3,8 +3,12 @@ if(BUILD_TESTING)
set_tests_properties(agc_driver_pipelined_sample_dump_drained PROPERTIES
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_PIPELINE_DRAIN_SAMPLE_DUMPS=1"
SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
add_test(NAME agc_driver_pipelined_sample_dump_cpu COMMAND agc_driver_pipelined_sample_dump_tests)
set_tests_properties(agc_driver_pipelined_sample_dump_cpu PROPERTIES
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_GPU_SAMPLE_DUMPS=1"
SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
if(WIN32)
set_tests_properties(agc_driver_pipelined_sample_dump_drained PROPERTIES ENVIRONMENT_MODIFICATION
set_tests_properties(agc_driver_pipelined_sample_dump_drained agc_driver_pipelined_sample_dump_cpu PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
@@ -27,6 +27,13 @@ target_link_libraries(agc_driver_recorder_tests PRIVATE
)
if(BUILD_TESTING)
add_test(NAME agc_multisample_use_collect COMMAND agc_driver_recorder_tests --multisample-use-collect-only)
add_test(NAME agc_multisample_use_collect_no_memo COMMAND agc_driver_recorder_tests --multisample-use-collect-only)
set_tests_properties(agc_multisample_use_collect agc_multisample_use_collect_no_memo PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30 ENVIRONMENT "APS5_DRAW_PIPELINE=8")
set_property(TEST agc_multisample_use_collect_no_memo APPEND PROPERTY ENVIRONMENT "APS5_NO_COLLECT_MEMO=1")
if(WIN32)
set_tests_properties(agc_multisample_use_collect agc_multisample_use_collect_no_memo PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test(NAME agc_completion_label_wait COMMAND agc_driver_recorder_tests --completion-wait-only)
set_tests_properties(agc_completion_label_wait PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30)
if(WIN32)
@@ -36,6 +43,28 @@ endif()
set_target_properties(agc_driver_recorder_tests PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(agc_driver_recorder_tests)
set(agcSampleImportOriginHeader ${agcTestShaderGeneratedRoot}/SampleImportOrigin_spv.h)
set(agcSampleImportOriginSpv ${agcTestShaderGeneratedRoot}/SampleImportOrigin.spv)
add_custom_command(
OUTPUT "${agcSampleImportOriginHeader}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${agcTestShaderGeneratedRoot}"
COMMAND "$<TARGET_FILE:glslang-standalone>" -V --target-env vulkan1.1 -o "${agcSampleImportOriginSpv}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/shaders/SampleImportOrigin.comp"
COMMAND ${CMAKE_COMMAND} -DINPUT=${agcSampleImportOriginSpv} -DOUTPUT=${agcSampleImportOriginHeader}
-DSYMBOL=SAMPLE_IMPORT_ORIGIN_SPV -P "${CMAKE_CURRENT_SOURCE_DIR}/embed_spirv.cmake"
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/tests/shaders/SampleImportOrigin.comp" glslang-standalone
VERBATIM
)
target_sources(agc_driver_recorder_tests PRIVATE "${agcSampleImportOriginHeader}")
if(BUILD_TESTING)
add_test(NAME agc_sampled_import_pieces COMMAND agc_driver_recorder_tests --sampled-import-pieces)
set_tests_properties(agc_sampled_import_pieces PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30
FAIL_REGULAR_EXPRESSION "SYNC-HAZARD|VUID-"
ENVIRONMENT "VK_LAYER_ENABLES=VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT")
if(WIN32)
set_tests_properties(agc_sampled_import_pieces PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
if(BUILD_TESTING)
set_target_properties(agc_driver_recorder_tests PROPERTIES EXCLUDE_FROM_ALL OFF)
add_test(NAME agc_recorder_device_selection COMMAND agc_driver_recorder_tests --device-selection-only)
@@ -90,7 +119,8 @@ if(BUILD_TESTING)
add_test(NAME agc_import_watch COMMAND agc_driver_recorder_tests --import-watch-only)
set_tests_properties(agc_import_watch PROPERTIES SKIP_RETURN_CODE 77)
add_test(NAME agc_import_settle_initial_dcc COMMAND agc_driver_recorder_tests --settle-initial-dcc-only)
set_tests_properties(agc_import_settle_initial_dcc PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30)
add_test(NAME agc_import_settle_initial_dcc_committer COMMAND agc_driver_recorder_tests --settle-initial-dcc-committer-only)
set_tests_properties(agc_import_settle_initial_dcc agc_import_settle_initial_dcc_committer PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30)
if(WIN32)
add_test(NAME agc_import_watch_other_family COMMAND agc_driver_recorder_tests --import-watch-other-family-only)
set_tests_properties(agc_import_watch_other_family PROPERTIES SKIP_RETURN_CODE 77)
@@ -109,7 +139,7 @@ if(BUILD_TESTING)
add_test(NAME agc_import_settle_storage_image COMMAND agc_driver_recorder_tests --settle-storage-image-only)
add_test(NAME agc_import_rewatch_under_image COMMAND agc_driver_recorder_tests --rewatch-under-image-only)
set_tests_properties(agc_import_settle_deferred agc_import_settle_deferred_other_family agc_import_settle_first_use agc_import_settle_earlier_import agc_import_settle_retire agc_import_settle_storage_image agc_import_rewatch_under_image PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
set_tests_properties(agc_import_watch agc_import_watch_other_family agc_import_settle_deferred agc_import_settle_deferred_other_family agc_import_settle_first_use agc_import_settle_earlier_import agc_import_settle_retire agc_import_settle_storage_image agc_import_rewatch_under_image agc_import_settle_initial_dcc PROPERTIES ENVIRONMENT_MODIFICATION
set_tests_properties(agc_import_watch agc_import_watch_other_family agc_import_settle_deferred agc_import_settle_deferred_other_family agc_import_settle_first_use agc_import_settle_earlier_import agc_import_settle_retire agc_import_settle_storage_image agc_import_rewatch_under_image agc_import_settle_initial_dcc agc_import_settle_initial_dcc_committer PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
if(WIN32)
@@ -256,6 +286,18 @@ if(BUILD_TESTING)
endif()
add_test(NAME agc_storage_typed_fill_clear COMMAND agc_driver_recorder_tests --typed-fill-clear-only)
set_tests_properties(agc_storage_typed_fill_clear PROPERTIES ENVIRONMENT "APS5_NO_PIPELINE_JOURNAL=1" SKIP_RETURN_CODE 77)
add_test(NAME agc_buffer_upload_pending_gpu_copy COMMAND agc_driver_recorder_tests --pending-upload-gpu-copy-only)
set_tests_properties(agc_buffer_upload_pending_gpu_copy PROPERTIES SKIP_RETURN_CODE 77)
if(WIN32)
set_tests_properties(agc_buffer_upload_pending_gpu_copy PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test(NAME agc_buffer_upload_pending_gpu_copy_bytes COMMAND agc_driver_recorder_tests --pending-upload-gpu-copy-bytes-only)
set_tests_properties(agc_buffer_upload_pending_gpu_copy_bytes PROPERTIES SKIP_RETURN_CODE 77)
if(WIN32)
set_tests_properties(agc_buffer_upload_pending_gpu_copy_bytes PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test(NAME agc_storage_integer_clear COMMAND agc_driver_recorder_tests --integer-clear-only)
set_tests_properties(agc_storage_integer_clear PROPERTIES SKIP_RETURN_CODE 77)
if(WIN32)
@@ -328,6 +370,12 @@ if(BUILD_TESTING)
set_tests_properties(agc_storage_write_back_scratch PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test(NAME agc_storage_write_back_host_retile COMMAND agc_driver_recorder_tests --storage-write-back-only)
set_tests_properties(agc_storage_write_back_host_retile PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120 ENVIRONMENT "APS5_PIN_WAIT_MS=3000;APS5_LINEAR_IMPORT_RETILE_HOST=1")
if(WIN32)
set_tests_properties(agc_storage_write_back_host_retile PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
add_test(NAME agc_copied_direct_ordering COMMAND agc_driver_recorder_tests --copied-direct-only)
set_tests_properties(agc_copied_direct_ordering PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30)
if(WIN32)
@@ -490,6 +538,8 @@ if(BUILD_TESTING)
set_tests_properties(agc_draw_inputs_copied PROPERTIES SKIP_RETURN_CODE 77)
add_test(NAME agc_draw_input_reuse COMMAND agc_driver_recorder_tests --draw-input-reuse-only)
set_tests_properties(agc_draw_input_reuse PROPERTIES SKIP_RETURN_CODE 77)
add_test(NAME agc_index_in_place_behind_writer COMMAND agc_driver_recorder_tests --index-behind-writer-only)
set_tests_properties(agc_index_in_place_behind_writer PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30)
add_test(NAME agc_resident_present COMMAND agc_driver_recorder_tests --resident-present-only)
set_tests_properties(agc_resident_present PROPERTIES SKIP_RETURN_CODE 77)
add_test(NAME agc_queued_write_groups COMMAND agc_driver_recorder_tests --queued-write-groups-only)
@@ -500,7 +550,7 @@ if(BUILD_TESTING)
add_test(NAME agc_metadata_pass COMMAND agc_driver_recorder_tests --metadata-pass-only)
set_tests_properties(agc_metadata_pass PROPERTIES SKIP_RETURN_CODE 77)
if(WIN32)
set_tests_properties(agc_recorder_read_list agc_recorder_stored_bytes agc_host_import_unmap agc_parked_import_unmap agc_window_import_unmap agc_host_import_retirement agc_sparse_run_import agc_sparse_run_import_copied agc_unit_shadow agc_driver_recorder agc_idle_publish_wait agc_recorder_command_buffer_release agc_descriptor_pool_recycling agc_draw_snapshot_cap agc_untracked_forget agc_draw_snapshot_epoch agc_multisample_guest_access agc_repeat_storage_guard agc_owned_draw_inputs agc_owned_draw_inputs_verify agc_owned_draw_inputs_trace agc_owned_draw_inputs_trace_unbound agc_owned_draw_inputs_trace_eviction agc_draw_inputs_in_place agc_draw_inputs_copied agc_draw_input_reuse agc_resident_present agc_slice_dirty agc_queued_write_groups agc_metadata_pass agc_tiled_resolve agc_changed_copy agc_bound_changed_copy agc_draw_input_mirrors agc_draw_input_mirrors_off PROPERTIES ENVIRONMENT_MODIFICATION
set_tests_properties(agc_recorder_read_list agc_recorder_stored_bytes agc_host_import_unmap agc_parked_import_unmap agc_window_import_unmap agc_host_import_retirement agc_sparse_run_import agc_sparse_run_import_copied agc_unit_shadow agc_driver_recorder agc_idle_publish_wait agc_recorder_command_buffer_release agc_descriptor_pool_recycling agc_draw_snapshot_cap agc_untracked_forget agc_draw_snapshot_epoch agc_multisample_guest_access agc_repeat_storage_guard agc_owned_draw_inputs agc_owned_draw_inputs_verify agc_owned_draw_inputs_trace agc_owned_draw_inputs_trace_unbound agc_owned_draw_inputs_trace_eviction agc_draw_inputs_in_place agc_draw_inputs_copied agc_draw_input_reuse agc_index_in_place_behind_writer agc_resident_present agc_slice_dirty agc_queued_write_groups agc_metadata_pass agc_tiled_resolve agc_changed_copy agc_bound_changed_copy agc_draw_input_mirrors agc_draw_input_mirrors_off PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
add_test(NAME agc_host_import_second_mapping COMMAND agc_driver_recorder_tests --host-import-second-mapping-only)
set_tests_properties(agc_host_import_second_mapping PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT_MODIFICATION
@@ -0,0 +1,8 @@
if(BUILD_TESTING)
add_test(NAME agc_driver_resident_heap_mirror_no_publish COMMAND agc_driver_resident_heap_mirror_tests)
set_tests_properties(agc_driver_resident_heap_mirror_no_publish PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_MIRROR_PUBLISH=1;ANYPS5_TEST_EXPECT_MIRROR_PUBLISH=1" SKIP_RETURN_CODE 77 PASS_REGULAR_EXPRESSION "instead of publishing it into the heap mirror" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 60)
if(WIN32)
set_tests_properties(agc_driver_resident_heap_mirror_no_publish PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
@@ -0,0 +1,8 @@
if(BUILD_TESTING)
add_test(NAME agc_driver_sparse_heap_import_mirror COMMAND agc_driver_sparse_heap_import_tests)
set_tests_properties(agc_driver_sparse_heap_import_mirror PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_SPARSE_HEAP_IMPORT=1" SKIP_RETURN_CODE 77 TIMEOUT 60 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
if(WIN32)
set_tests_properties(agc_driver_sparse_heap_import_mirror PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
@@ -0,0 +1,14 @@
add_test_executable(agc_recorder_batch_fences_tests EXCLUDE_FROM_ALL tests/RecorderBatchFences.cpp)
target_include_directories(agc_recorder_batch_fences_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/core/shader/recompiler ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR})
target_link_libraries(agc_recorder_batch_fences_tests PRIVATE libSceAgcDriver libc)
set_target_properties(agc_recorder_batch_fences_tests PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(agc_recorder_batch_fences_tests)
if(BUILD_TESTING)
set_target_properties(agc_recorder_batch_fences_tests PROPERTIES EXCLUDE_FROM_ALL OFF)
add_test(NAME agc_recorder_batch_fences COMMAND agc_recorder_batch_fences_tests)
if(WIN32)
set_tests_properties(agc_recorder_batch_fences PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
@@ -3,6 +3,10 @@ target_link_libraries(agc_spirv_branch_targets_tests PRIVATE shader_recompiler_a
set_target_properties(agc_spirv_branch_targets_tests PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(agc_spirv_branch_targets_tests)
if(ANYPS5_ENABLE_SPIRV_TOOLS)
target_link_libraries(agc_spirv_branch_targets_tests PRIVATE SPIRV-Tools-static)
endif()
if(BUILD_TESTING)
set_target_properties(agc_spirv_branch_targets_tests PROPERTIES EXCLUDE_FROM_ALL OFF)
add_test(NAME agc_spirv_branch_targets COMMAND agc_spirv_branch_targets_tests)
@@ -100,6 +100,7 @@ void DepthCopyProgramsAreNotCaptured() {
for (std::uint32_t i = 0; i < words; ++i) queue.shader[0x00cu + i] = 0u;
queue.context[0x1b3u] = queue.context[0x1b4u] = 0x8002u;
queue.context[0x1c5u] = 1u;
queue.context[0x31cu] = 10u << 2u;
queue.context[0x08eu] = 0xfu;
queue.context[0x08fu] = 1u;
queue.context[0x203u] = 0u;
@@ -125,6 +126,7 @@ void StencilCopyProgramsAreNotCaptured() {
for (std::uint32_t i = 0; i < words; ++i) queue.shader[0x00cu + i] = 0u;
queue.context[0x1b3u] = queue.context[0x1b4u] = 0x8002u;
queue.context[0x1c5u] = 2u;
queue.context[0x31cu] = 10u << 2u;
queue.context[0x08eu] = 0xfu;
queue.context[0x08fu] = 3u;
queue.context[0x203u] = 0u;
@@ -91,6 +91,7 @@ int main() {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
if (SkipWithoutSharedMemoryStores()) return VulkanTestSkipped;
if (atomic && SkipOnLlvmpipe(*device, "the waiting dispatch with coherent atomic loads never finishes (recorded batch still running on the GPU after 10 s)")) return VulkanTestSkipped;
CheckLoads(*device, atomic);
}
if (!atomic) {
@@ -0,0 +1,246 @@
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "prx/libc/include/GuestArena.hpp"
#include "prx/libc/include/GuestWriteWatch.hpp"
#include "Recompiler.hpp"
#include "VulkanTestDevice.hpp"
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <sys/mman.h>
#endif
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#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 Words = 64;
constexpr std::size_t Moved = 2u * 1024u * 1024u;
constexpr std::size_t Bytes = Moved;
constexpr std::uint32_t Constant = 0x00010000u;
constexpr std::uint32_t Sentinel = 0xdeadbeefu;
alignas(256) std::array<std::uint32_t, 8> Table{};
constexpr std::uint32_t Vop2(std::uint32_t opcode, std::uint32_t destination, std::uint32_t source0, std::uint32_t source1) {
return (opcode << 25u) | (destination << 17u) | (source1 << 9u) | source0;
}
constexpr std::uint32_t BufferOperands = (0x80u << 24u) | (1u << 16u) | (2u << 8u) | 1u;
alignas(256) constexpr std::array<std::uint32_t, 15> Code{
Vop2(0x1au, 1u, 0x82u, 0u),
0xf4080100u, 0xfa000000u,
0xbf8cc07fu,
0xe0301000u, BufferOperands,
0xbf8c3f70u,
0xf4080100u, 0xfa000010u,
0xbf8cc07fu,
Vop2(0x25u, 2u, 0xffu, 2u), Constant,
0xe0701000u, BufferOperands,
0xbf810000u,
};
class GuestBuffer {
public:
GuestBuffer() = default;
void Create() {
#ifdef _WIN32
block = static_cast<std::uint8_t*>(GuestArena::GuestArenaAllocate_nid_postfix(Moved, Moved));
if (block != nullptr) GuestArena::GuestArenaCommit_nid_postfix(block, Moved, PAGE_READWRITE, Moved);
#else
void* mapped = mmap(nullptr, Moved + Moved, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (mapped != MAP_FAILED) {
const auto begin = reinterpret_cast<std::uintptr_t>(mapped);
const auto aligned = (begin + Moved - 1) & ~(static_cast<std::uintptr_t>(Moved) - 1);
if (aligned != begin) munmap(mapped, aligned - begin);
if (aligned + Moved != begin + Moved + Moved) munmap(reinterpret_cast<void*>(aligned + Moved), begin + Moved + Moved - aligned - Moved);
block = reinterpret_cast<std::uint8_t*>(aligned);
GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, Moved);
}
#endif
Require(block != nullptr, "dispatch rebind: cannot allocate the guest buffer");
GuestAllocations::Mutation().Add(block, Moved, true, true, true);
}
~GuestBuffer() {
if (block == nullptr) return;
GuestAllocations::Mutation().Remove(block);
#ifdef _WIN32
GuestArena::GuestArenaReset_nid_postfix(block, Moved);
GuestArena::GuestArenaRelease_nid_postfix(block, Moved);
#else
munmap(block, Moved);
GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(block, Moved);
#endif
}
GuestBuffer(const GuestBuffer&) = delete;
GuestBuffer& operator=(const GuestBuffer&) = delete;
std::uint32_t* Words() const { return reinterpret_cast<std::uint32_t*>(block); }
void Reregister() {
GuestAllocations::Mutation().Remove(block);
GuestAllocations::Mutation().Add(block, Moved, true, true, true);
}
private:
std::uint8_t* block = nullptr;
};
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::string Hex(std::uint32_t value) {
char text[16];
std::snprintf(text, sizeof(text), "0x%08x", value);
return text;
}
void Fill(std::uint32_t* where, std::uint32_t first) {
for (std::uint32_t index = 0; index < Words; ++index) where[index] = first + index;
}
void Reset(std::uint32_t* output) {
std::fill(output, output + Words, Sentinel);
}
ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const std::uint32_t* input, std::uint32_t inputBytes, const std::uint32_t* output) {
const auto in = BufferDescriptor(input, inputBytes);
const auto out = BufferDescriptor(output, Bytes);
std::copy(in.begin(), in.end(), Table.begin());
std::copy(out.begin(), out.end(), Table.begin() + 4);
const auto table = reinterpret_cast<std::uintptr_t>(Table.data());
const std::vector<std::uint32_t> userData{static_cast<std::uint32_t>(table), static_cast<std::uint32_t>(table >> 32u)};
const std::span<const std::uint32_t> code(Code);
const std::span<const std::uint32_t> tableWords(Table);
const std::array<ShaderRecompiler::MemoryRegion, 2> memory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(code)}, {table, std::as_bytes(tableWords)}}};
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;
return ShaderRecompiler::Recompile(request);
}
void Run(AgcDriver::VulkanDevice& device, const ShaderRecompiler::RecompileResult& compiled, const std::uint32_t* input, std::uint32_t inputBytes, const std::uint32_t* output) {
auto result = compiled;
std::size_t elements = 0;
for (auto& binding : result.bindings) {
if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue;
Require(binding.guestDescriptor.size() == static_cast<std::size_t>(binding.count) * 4u && binding.bufferWritten.size() == binding.count, "dispatch rebind: the program's buffer bindings have another shape");
for (std::uint32_t element = 0; element < binding.count; ++element, ++elements) {
const auto words = binding.bufferWritten[element] ? BufferDescriptor(output, Bytes) : BufferDescriptor(input, inputBytes);
std::copy(words.begin(), words.end(), binding.guestDescriptor.begin() + static_cast<std::ptrdiff_t>(element) * 4);
}
}
Require(elements == 2, "dispatch rebind: the program does not bind an input and an output");
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(Code.data()));
device.WaitIdle();
}
void Expect(const std::uint32_t* input, const std::uint32_t* output, const std::string& what) {
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
const auto expected = input[tid] + Constant;
Require(output[tid] == expected, "dispatch rebind: " + what + ": lane " + std::to_string(tid) + " is " + Hex(output[tid]) + ", expected " + Hex(expected));
}
}
struct Step {
std::uint64_t checked, exact, moved, refused, rebuilt, kept, served, inPlace;
};
Step Since(const AgcDriver::VulkanDevice::DispatchMoveCount& before) {
const auto now = AgcDriver::VulkanDevice::DispatchMoveCounts();
return {now.checked - before.checked, now.exact - before.exact, now.moved - before.moved, now.refused - before.refused, now.rebuilt - before.rebuilt, now.kept - before.kept, now.served - before.served, now.inPlace - before.inPlace};
}
bool RunTests(AgcDriver::VulkanDevice& device, GuestBuffer& first, GuestBuffer& second, GuestBuffer& output) {
Fill(first.Words(), 0xa000u);
Fill(second.Words(), 0xb000u);
const auto compiled = Compile(device, first.Words(), Bytes, output.Words());
Reset(output.Words());
Run(device, compiled, first.Words(), Bytes, output.Words());
Expect(first.Words(), output.Words(), "the first dispatch");
Reset(output.Words());
Run(device, compiled, second.Words(), Bytes, output.Words());
Expect(second.Words(), output.Words(), "the input moved to a second block");
Reset(output.Words());
Run(device, compiled, first.Words(), Bytes, output.Words());
Expect(first.Words(), output.Words(), "the input back where the template was built");
const auto before = AgcDriver::VulkanDevice::DispatchMoveCounts();
Reset(output.Words());
Run(device, compiled, second.Words(), Bytes, output.Words());
Expect(second.Words(), output.Words(), "the input moved to the imported block");
const auto moved = Since(before);
std::printf("dispatch rebind: a moved read-only buffer of %zu bytes: checked %llu, moved %llu, in place %llu, rebuilt %llu\n", Moved, static_cast<unsigned long long>(moved.checked), static_cast<unsigned long long>(moved.moved), static_cast<unsigned long long>(moved.inPlace), static_cast<unsigned long long>(moved.rebuilt));
if (moved.checked == 0) {
std::puts("dispatch rebind: the device kept no template (no host imports); the in-place path is not exercised");
return false;
}
Require(moved.moved != 0 && moved.inPlace != 0, "dispatch rebind: the moved read-only buffer was not rebound in place");
Require(moved.rebuilt == 0 && moved.kept == 0, "dispatch rebind: the in-place move rebuilt the template");
const auto written = AgcDriver::VulkanDevice::DispatchMoveCounts();
for (std::uint32_t index = 0; index < Words; ++index) second.Words()[index] = 0xe000u + index;
Reset(output.Words());
Run(device, compiled, second.Words(), Bytes, output.Words());
Expect(second.Words(), output.Words(), "the input written between two dispatches");
const auto afterWrite = Since(written);
Require(afterWrite.inPlace != 0, "dispatch rebind: a guest write to the moved range left the in-place path");
second.Reregister();
for (std::uint32_t index = 0; index < Words; ++index) second.Words()[index] = 0xf000u + index;
Reset(output.Words());
Run(device, compiled, second.Words(), Bytes, output.Words());
Expect(second.Words(), output.Words(), "the input whose import changed");
return true;
}
}
int main() {
try {
GuestBuffer first;
GuestBuffer second;
GuestBuffer output;
first.Create();
second.Create();
output.Create();
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
if (!RunTests(*device, first, second, output)) return VulkanTestSkipped;
std::puts("dispatch rebind tests passed");
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -0,0 +1,158 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
namespace {
using AgcDriver::DriverDetail::DrawPipeline;
using namespace std::chrono_literals;
void Require(bool condition, const char* message) {
if (condition) return;
std::cerr << message << '\n';
std::_Exit(1);
}
bool WaitFor(const std::function<bool()>& done, std::chrono::milliseconds limit) {
const auto end = std::chrono::steady_clock::now() + limit;
while (!done()) {
if (std::chrono::steady_clock::now() >= end) return false;
std::this_thread::sleep_for(1ms);
}
return true;
}
struct Gates {
std::mutex mutex;
std::condition_variable changed;
std::size_t open = 0;
void Pass(std::size_t index) {
std::unique_lock lock(mutex);
changed.wait(lock, [&] { return open > index; });
}
void OpenThrough(std::size_t count) {
{
std::lock_guard lock(mutex);
open = count;
}
changed.notify_all();
}
};
std::shared_ptr<Gates> FillWithGatedCommits(DrawPipeline& pipeline) {
auto gates = std::make_shared<Gates>();
for (std::size_t i = 0; i < DrawPipeline::Depth(); ++i) pipeline.Enqueue([gates, i] { gates->Pass(i); }, {});
return gates;
}
void RetireThrough(DrawPipeline& pipeline, Gates& gates, std::uint64_t base, std::size_t count) {
gates.OpenThrough(count);
Require(WaitFor([&] { return pipeline.Retired() >= base + count; }, 10s), "a released commit did not retire");
}
void ProducerResumesAtTheLowWatermark() {
auto& pipeline = DrawPipeline::Queue0();
pipeline.Drain(DrawPipeline::DrainReason::Submission);
const auto depth = DrawPipeline::Depth();
const auto resume = DrawPipeline::ResumeDepth();
const auto base = pipeline.Retired();
const auto waits = pipeline.ProducerWaits();
auto gates = FillWithGatedCommits(pipeline);
std::atomic<bool> returned{false};
std::thread producer([&] {
pipeline.Enqueue([] {}, {});
returned.store(true, std::memory_order_release);
});
Require(WaitFor([&] { return pipeline.ProducerWaits() > waits; }, 10s), "the producer did not wait on a full pipeline");
if (depth - resume > 1) {
RetireThrough(pipeline, *gates, base, 1);
std::this_thread::sleep_for(200ms);
Require(!returned.load(std::memory_order_acquire), "the producer resumed after one retire instead of at the low watermark");
}
for (std::size_t retired = 2; retired < depth - resume; ++retired) {
RetireThrough(pipeline, *gates, base, retired);
Require(!returned.load(std::memory_order_acquire), "the producer resumed above the low watermark");
}
RetireThrough(pipeline, *gates, base, depth - resume);
Require(WaitFor([&] { return returned.load(std::memory_order_acquire); }, 10s), "the producer did not resume at the low watermark");
producer.join();
gates->OpenThrough(depth);
pipeline.Drain(DrawPipeline::DrainReason::Submission);
Require(pipeline.Retired() == base + depth + 1, "the pipeline did not retire every item");
}
void EveryProducerResumes() {
auto& pipeline = DrawPipeline::Queue0();
pipeline.Drain(DrawPipeline::DrainReason::Submission);
const auto depth = DrawPipeline::Depth();
const auto resume = DrawPipeline::ResumeDepth();
const auto base = pipeline.Retired();
const auto waits = pipeline.ProducerWaits();
auto gates = FillWithGatedCommits(pipeline);
std::atomic<unsigned> returned{0};
std::vector<std::thread> producers;
for (int i = 0; i < 2; ++i) producers.emplace_back([&] {
pipeline.Enqueue([] {}, {});
returned.fetch_add(1, std::memory_order_acq_rel);
});
Require(WaitFor([&] { return pipeline.ProducerWaits() >= waits + 2; }, 10s), "both producers did not wait on a full pipeline");
RetireThrough(pipeline, *gates, base, depth - resume);
Require(WaitFor([&] { return returned.load(std::memory_order_acquire) == 2; }, 10s), "a producer did not resume at the low watermark");
for (auto& producer : producers) producer.join();
gates->OpenThrough(depth);
pipeline.Drain(DrawPipeline::DrainReason::Submission);
Require(pipeline.Retired() == base + depth + 2, "the pipeline did not retire every item");
}
void DrainReturnsAtEmptyBehindAWaitingProducer() {
auto& pipeline = DrawPipeline::Queue0();
pipeline.Drain(DrawPipeline::DrainReason::Submission);
const auto depth = DrawPipeline::Depth();
const auto resume = DrawPipeline::ResumeDepth();
const auto base = pipeline.Retired();
const auto producerWaits = pipeline.ProducerWaits();
const auto drainWaits = pipeline.DrainWaits();
auto gates = FillWithGatedCommits(pipeline);
std::atomic<bool> produced{false};
std::atomic<bool> drained{false};
std::thread producer([&] {
pipeline.Enqueue([] {}, {});
produced.store(true, std::memory_order_release);
});
Require(WaitFor([&] { return pipeline.ProducerWaits() > producerWaits; }, 10s), "the producer did not wait on a full pipeline");
std::thread drainer([&] {
pipeline.Drain(DrawPipeline::DrainReason::Submission);
drained.store(true, std::memory_order_release);
});
Require(WaitFor([&] { return pipeline.DrainWaits() > drainWaits; }, 10s), "the drain did not wait on a busy pipeline");
RetireThrough(pipeline, *gates, base, depth - resume);
Require(WaitFor([&] { return produced.load(std::memory_order_acquire); }, 10s), "the producer did not resume at the low watermark");
producer.join();
Require(!drained.load(std::memory_order_acquire), "the drain returned while items were queued");
RetireThrough(pipeline, *gates, base, depth - 1);
Require(!drained.load(std::memory_order_acquire), "the drain returned while items were queued");
gates->OpenThrough(depth);
Require(WaitFor([&] { return drained.load(std::memory_order_acquire); }, 10s), "the drain did not return when the pipeline emptied");
drainer.join();
Require(pipeline.Retired() == base + depth + 1, "the pipeline did not retire every item");
}
}
int main() {
if (DrawPipeline::Depth() == 0) return 77;
ProducerResumesAtTheLowWatermark();
if (DrawPipeline::Depth() >= DrawPipeline::ResumeDepth() + 2) EveryProducerResumes();
DrainReturnsAtEmptyBehindAWaitingProducer();
std::cout << "draw pipeline producer wake tests passed\n";
return 0;
}
@@ -162,6 +162,48 @@ void Run(AgcDriver::VulkanDevice& device) {
device.WaitIdle();
}
void RunSaturatedMaximum(AgcDriver::VulkanDevice& device) {
alignas(256) constexpr std::array<std::uint32_t, 10> code{
0x34020084u, 0x34060086u, 0xe0381000u, 0x80000401u, 0xbf8c3f70u,
0xd510800au, 0x00020880u, 0xe0701000u, 0x80010a03u, 0xbf810000u,
};
constexpr std::array<std::uint32_t, 16> inputs{
0u, 0x80000000u, 1u, 0x80000001u, 0x007fffffu, 0x807fffffu, 0x00800000u, 0x80800000u,
0x3f000000u, 0x3f800001u, 0x7f800000u, 0xff800000u, 0x7f800001u, 0xff800001u, 0x7fc12345u, 0xffc12345u,
};
for (std::uint32_t tid = 0; tid < Threads; ++tid) Input[tid * Inputs] = inputs[tid % inputs.size()];
Output.fill(0xdeadbeefu);
std::vector<std::uint32_t> userData(8, 0u);
const auto input = BufferDescriptor(Input.data(), static_cast<std::uint32_t>(Input.size() * 4u));
const auto output = BufferDescriptor(Output.data(), static_cast<std::uint32_t>(Output.size() * 4u));
std::copy(input.begin(), input.end(), userData.begin());
std::copy(output.begin(), output.end(), userData.begin() + 4);
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(std::span(code))}}};
ShaderRecompiler::RecompileRequest request{
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(code.data()), code, 0, {}},
{32, 0, userData, ShaderRecompiler::ShaderComputeStageInfo{{Threads, 1, 1}, 0u, {false, false, false}, false, 1}, std::nullopt, std::nullopt, memory},
device.Target(), {0, 0, 0, 128}
};
request.useCache = false;
request.target.float32FlushToZero = false;
for (const auto mode : {0xc0u, 0xf0u}) {
if (mode == 0xf0u && !request.target.float32DenormPreserve) {
std::puts("saturated maximum FLOAT_MODE 0xf0 not run: device lacks DenormPreserve 32");
continue;
}
request.context.floatMode = ShaderRecompiler::ShaderFloatMode{mode, true, false, false};
const auto result = ShaderRecompiler::Recompile(request);
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(code.data()));
device.WaitIdle();
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
auto bits = Input[tid * Inputs];
if (mode == 0xc0u && (bits & 0x7f800000u) == 0u) bits &= 0x80000000u;
const auto expected = bits - 1u < 0x7f800000u ? std::min(bits, 0x3f800000u) : 0u;
Expect(tid, Output[tid * Results], expected, "saturated maximum with zero");
}
}
}
void Check() {
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
const std::uint32_t* in = &Input[tid * Inputs];
@@ -180,6 +222,7 @@ int main() {
if (!device) return VulkanTestSkipped;
Run(*device);
Check();
RunSaturatedMaximum(*device);
std::puts("f32 result clamp tests passed");
return 0;
} catch (const std::exception& error) {
@@ -0,0 +1,137 @@
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libc/include/GuestArena.hpp"
#include "Recompiler.hpp"
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
#include "VulkanTestDevice.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <span>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using AgcDriver::Graphics::Require;
using ShaderRecompiler::ShaderStage;
constexpr std::size_t BlockBytes = 65536;
constexpr std::uintptr_t GcnAddressLimit = std::uintptr_t{1} << 44u;
constexpr std::uint32_t Threads = 64;
constexpr std::uint32_t OutputOffset = 0;
constexpr std::uint32_t TexelOffset = 4096;
constexpr std::uint32_t Fill = 0xdeadbeefu;
alignas(256) constexpr std::array<std::uint32_t, 9> Code{
0x7e020280u, 0x7e040280u, 0x340e0084u, 0xf09c0f00u, 0x00400301u, 0xbf8c0f70u, 0xe0781000u, 0x80030307u, 0xbf810000u,
};
class LowBlock {
public:
LowBlock() : block(static_cast<std::uint32_t*>(GuestArena::GuestArenaAllocate_nid_postfix(BlockBytes, BlockBytes))) {
Require(block != nullptr, "GCN invalid format image: cannot allocate the block in the guest arena");
GuestArena::GuestArenaCommit_nid_postfix(block, BlockBytes, 0x04u, BlockBytes);
}
~LowBlock() {
GuestArena::GuestArenaReset_nid_postfix(block, BlockBytes);
GuestArena::GuestArenaRelease_nid_postfix(block, BlockBytes);
}
LowBlock(const LowBlock&) = delete;
LowBlock& operator=(const LowBlock&) = delete;
std::uintptr_t Address() const { return reinterpret_cast<std::uintptr_t>(block); }
bool Addressable() const { return Address() + BlockBytes <= GcnAddressLimit; }
std::uint32_t* Words(std::uint32_t offset) const { return block + offset / 4u; }
private:
std::uint32_t* block = nullptr;
};
std::array<std::uint32_t, 4> BufferDescriptor(std::uintptr_t address, std::uint32_t bytes) {
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu), bytes, 0x00027facu};
}
std::array<std::uint32_t, 8> ImageWords(std::uintptr_t address, std::uint32_t dataFormat, std::uint32_t dstSel, std::uint32_t type) {
const auto base = static_cast<std::uint32_t>(address >> 8u);
const auto high = static_cast<std::uint32_t>((address >> 40u) & 0xffu);
const auto word1 = high | 0x000c0000u | (dataFormat << 20u);
return {base, word1, 0x00000008u, dstSel | 0x00050000u | (type << 28u), base + 1u, word1, 0x00000008u, 0x2005f22cu};
}
void Dispatch(AgcDriver::VulkanDevice& device, const LowBlock& block, const std::array<std::uint32_t, 8>& image) {
std::fill(block.Words(OutputOffset), block.Words(OutputOffset) + Threads * 4u, Fill);
std::fill(block.Words(TexelOffset), block.Words(TexelOffset) + 1024u, 0x3f800000u);
std::vector<std::uint32_t> userData(16, 0u);
std::copy(image.begin(), image.end(), userData.begin());
const auto output = BufferDescriptor(reinterpret_cast<std::uintptr_t>(block.Words(OutputOffset)), Threads * 16u);
std::copy(output.begin(), output.end(), userData.begin() + 12);
const std::span<const std::uint32_t> code(Code);
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, {}},
{64, 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();
}
void ExpectZeros(AgcDriver::VulkanDevice& device, const LowBlock& block, const std::array<std::uint32_t, 8>& image, const std::string& what) {
Dispatch(device, block, image);
std::array<std::uint32_t, Threads * 4u> stored{};
AgcDriver::GuestMemory::Read(reinterpret_cast<std::uintptr_t>(block.Words(OutputOffset)), std::as_writable_bytes(std::span(stored)), 4);
for (std::uint32_t word = 0; word < stored.size(); ++word) {
char text[192];
std::snprintf(text, sizeof(text), "GCN invalid format image: %s, thread %u component %u read 0x%08x, an unbound resource reads 0", what.c_str(), word / 4u, word % 4u, stored[word]);
Require(stored[word] == 0u, text);
}
}
void ExpectRefused(AgcDriver::VulkanDevice& device, const LowBlock& block, const std::array<std::uint32_t, 8>& image, const std::string& what) {
try {
Dispatch(device, block, image);
} catch (const std::exception& error) {
Require(std::string(error.what()).find("runtime image descriptor is invalid") != std::string::npos, "GCN invalid format image: " + what + " failed with another error: " + error.what());
return;
}
throw std::runtime_error("GCN invalid format image: " + what + " was accepted");
}
}
int main() {
try {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
ShaderRecompiler::SetGcnGuestShaders(true);
const LowBlock block;
if (!block.Addressable()) {
std::printf("skipped, the guest arena block at 0x%llx lies above the 44-bit GCN address range\n", static_cast<unsigned long long>(block.Address()));
return VulkanTestSkipped;
}
const auto texels = reinterpret_cast<std::uintptr_t>(block.Words(TexelOffset));
constexpr std::uint32_t Xyzw = 0xfacu;
constexpr std::uint32_t XyzOne = 0x3acu;
ExpectZeros(*device, block, ImageWords(texels, 0u, Xyzw, 2u), "a reserved TYPE 2 T# whose words are two V#s");
ExpectZeros(*device, block, ImageWords(texels, 0u, Xyzw, 7u), "a reserved TYPE 7 T#");
ExpectZeros(*device, block, ImageWords(texels, 0u, Xyzw, 15u), "a 2D MSAA array T#");
ExpectRefused(*device, block, ImageWords(texels, 0u, XyzOne, 2u), "a reserved TYPE 2 T# with DST_SEL_W 1");
ExpectRefused(*device, block, ImageWords(texels, 10u, Xyzw, 2u), "a reserved TYPE 2 T# with DATA_FORMAT 8_8_8_8");
std::puts("GCN invalid format image tests passed");
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -0,0 +1,121 @@
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libc/include/GuestArena.hpp"
#include "Recompiler.hpp"
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
#include "VulkanTestDevice.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <exception>
#include <iostream>
#include <optional>
#include <span>
#include <string>
namespace {
using AgcDriver::Graphics::Require;
using ShaderRecompiler::ShaderStage;
constexpr std::size_t BlockBytes = 65536;
constexpr std::uintptr_t GcnAddressLimit = std::uintptr_t{1} << 44u;
constexpr std::array<std::uint32_t, 4> Resident{0x12345678u, 0x5ca1ab1eu, 0x3f800000u, 0x600dcafeu};
alignas(256) constexpr std::array<std::uint32_t, 11> Code{
0x7e0202ffu, 0x11111111u,
0xc2040501u, 0xbf8c007fu,
0xbf008008u, 0xbf850001u,
0x7e020208u,
0xe0700000u, 0x80000100u,
0xbf8c0f70u, 0xbf810000u,
};
class LowBlock {
public:
LowBlock() : block(static_cast<std::uint32_t*>(GuestArena::GuestArenaAllocate_nid_postfix(BlockBytes, BlockBytes))) {
Require(block != nullptr, "GCN scalar buffer base: cannot allocate the buffer block in the guest arena");
GuestArena::GuestArenaCommit_nid_postfix(block, BlockBytes, 0x04u, BlockBytes);
}
~LowBlock() {
GuestArena::GuestArenaReset_nid_postfix(block, BlockBytes);
GuestArena::GuestArenaRelease_nid_postfix(block, BlockBytes);
}
LowBlock(const LowBlock&) = delete;
LowBlock& operator=(const LowBlock&) = delete;
std::uint32_t* Output() const { return block; }
std::uint32_t* Source() const { return block + 64; }
bool Addressable() const { return reinterpret_cast<std::uintptr_t>(block) + BlockBytes <= GcnAddressLimit; }
private:
std::uint32_t* block = nullptr;
};
std::array<std::uint32_t, 4> Descriptor(const std::uint32_t* data, std::uint32_t highBits) {
const auto address = reinterpret_cast<std::uintptr_t>(data);
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu) | highBits, 64u, 0x00027facu};
}
std::uint32_t Read(const std::uint32_t* data) {
std::uint32_t word = 0;
AgcDriver::GuestMemory::Read(reinterpret_cast<std::uintptr_t>(data), std::as_writable_bytes(std::span(&word, 1)), 4);
return word;
}
void Run(AgcDriver::VulkanDevice& device, const LowBlock& block, std::uint32_t highBits) {
std::fill_n(block.Output(), 4, 0xdeadbeefu);
std::copy(Resident.begin(), Resident.end(), block.Source());
const auto output = Descriptor(block.Output(), 0u);
const auto source = Descriptor(block.Source(), highBits);
std::array<std::uint32_t, 8> userData{};
std::copy(output.begin(), output.end(), userData.begin());
std::copy(source.begin(), source.end(), userData.begin() + 4);
const ShaderRecompiler::ShaderComputeStageInfo compute{{64u, 1u, 1u}, 0u, {false, false, false}, false, 1u};
ShaderRecompiler::RecompileRequest request{
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(Code.data()), Code, 0, {}},
{64u, 0, userData, compute, std::nullopt, std::nullopt, {}},
device.Target(),
{0, 0, 0, 128}
};
request.useCache = false;
char what[96];
std::snprintf(what, sizeof(what), "GCN scalar buffer base, V# word 1 bits 0x%04x", highBits);
AgcDriver::ShaderMemory memory({});
const auto capture = memory.Capture(request);
const auto regions = memory.Regions();
request.context.memory = regions;
const auto result = ShaderRecompiler::Recompile(request, *capture);
device.Dispatch(*result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(Code.data()));
device.WaitIdle();
const auto loaded = Read(block.Output());
char got[64];
std::snprintf(got, sizeof(got), ": s_buffer_load_dword returned 0x%08x, expected 0x%08x", loaded, Resident[1]);
Require(loaded == Resident[1], std::string(what) + got);
}
}
int main() {
try {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
ShaderRecompiler::SetGcnGuestShaders(true);
const LowBlock block;
if (!block.Addressable()) {
Require(GuestArena::GuestAddressOffset != 0, "GCN scalar buffer base: the guest arena block lies above the 44-bit GCN V# address range");
std::puts("skipped, the ASan guest arena offset places the block above the 44-bit GCN V# address range");
return VulkanTestSkipped;
}
for (const auto highBits : {0x0000u, 0x1000u, 0x8000u, 0xf000u}) Run(*device, block, highBits);
std::puts("GCN scalar buffer base tests passed");
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -0,0 +1,195 @@
#include "prx/libSceAgcDriver/Execution/include/Driver.hpp"
#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp"
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "Recompiler.hpp"
#include "VulkanTestDevice.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <span>
#include <string>
#include <vector>
namespace {
using AgcDriver::Graphics::Require;
using ShaderRecompiler::ShaderStage;
constexpr std::uint32_t MaxThreads = 64;
constexpr std::uint32_t Base = 0x100;
constexpr std::uint32_t Size = 0x100;
constexpr std::uint32_t Words = 4;
constexpr std::array<std::uint32_t, Words> Starts{1000, 2000, 3000, 4000};
constexpr std::array<std::uint32_t, Words> Canaries{7, 8, 9, 10};
constexpr std::uint32_t Untouched = 0x5eed0004u;
alignas(256) std::array<std::uint32_t, MaxThreads> Output{};
alignas(16) std::array<std::uint32_t, Words> Readback{};
alignas(256) auto AddCode = std::to_array<std::uint32_t>({
0x7e020280,
0x7e040281,
0xbefc03ff, (Base << 16u) | Size,
0xd8820004, 0x03000201,
0xbf8cc07f,
0xe0702000, 0x80000300,
0xbf810000,
});
alignas(256) auto ReadCode = std::to_array<std::uint32_t>({
0x7e020280,
0x7e0602ff, Untouched,
0xbefc03ff, (Base << 16u) | Size,
0xd8da0008, 0x03000001,
0xbf8cc07f,
0xe0702000, 0x80000300,
0xbf810000,
});
alignas(256) auto Add64Code = std::to_array<std::uint32_t>({
0x7e020280,
0x7e040281,
0x7e060280,
0xbefc03ff, (Base << 16u) | Size,
0xd9820008, 0x04000201,
0xbf8cc07f,
0xe0702000, 0x80000400,
0xbf810000,
});
struct Workgroup {
std::uint32_t threads;
std::uint32_t waveSize;
std::string Name() const {
return "wave" + std::to_string(waveSize) + " " + std::to_string(threads) + " threads";
}
};
constexpr std::array<Workgroup, 3> Workgroups{{{32, 32}, {64, 32}, {64, 64}}};
std::array<std::uint32_t, 4> BufferDescriptor(const void* data, std::uint32_t count) {
const auto address = reinterpret_cast<std::uintptr_t>(data);
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu) | (4u << 16u), count, 0x11016facu};
}
std::vector<std::uint32_t> Packet(std::uint32_t opcode, std::initializer_list<std::uint32_t> payload) {
std::vector<std::uint32_t> result{0xc0000000u | (static_cast<std::uint32_t>(payload.size() - 1) << 16u) | (opcode << 8u)};
result.insert(result.end(), payload);
return result;
}
void Execute(AgcDriver::QueueState& queue, const std::vector<std::uint32_t>& packet) {
AgcDriver::Pm4::Validate(packet, 0);
AgcDriver::Pm4::Execute(packet, queue);
}
void SetWords(AgcDriver::QueueState& queue, std::uint32_t offset, const std::array<std::uint32_t, Words>& values) {
for (std::uint32_t word = 0; word < Words; ++word) Execute(queue, Packet(0x50, {0x40100000u, values[word], 0, offset + word * 4u, 0, 4}));
}
std::array<std::uint32_t, Words> ReadWords(AgcDriver::QueueState& queue, std::uint32_t offset) {
Readback.fill(0xdeadbeefu);
const auto address = reinterpret_cast<std::uintptr_t>(Readback.data());
Execute(queue, Packet(0x50, {0x20000000u, offset, 0, static_cast<std::uint32_t>(address), static_cast<std::uint32_t>(address >> 32u), Words * 4u}));
return Readback;
}
void Run(AgcDriver::VulkanDevice& device, const Workgroup& workgroup, std::span<const std::uint32_t> code) {
Output.fill(Untouched);
std::vector<std::uint32_t> userData(4, 0u);
const auto output = BufferDescriptor(Output.data(), static_cast<std::uint32_t>(Output.size()));
std::copy(output.begin(), output.end(), userData.begin());
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(code)}}};
const ShaderRecompiler::ShaderComputeStageInfo compute{{workgroup.threads, 1, 1}, 0, {false, false, false}, false, 1};
ShaderRecompiler::RecompileRequest request{
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(code.data()), code, 0, {}},
{workgroup.waveSize, 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();
}
std::string Words4(const std::array<std::uint32_t, Words>& values) {
std::string text;
for (const auto value : values) text += (text.empty() ? "" : " ") + std::to_string(value);
return text;
}
void CheckAdd(AgcDriver::QueueState& queue, const Workgroup& workgroup) {
const auto what = workgroup.Name() + " ds_add_rtn_u32 gds with M0 base " + std::to_string(Base);
std::vector<std::uint32_t> old(Output.begin(), Output.begin() + workgroup.threads);
std::sort(old.begin(), old.end());
for (std::uint32_t lane = 0; lane < workgroup.threads; ++lane) {
Require(old[lane] == Starts[1] + lane, what + ": the returned values are not each of " + std::to_string(Starts[1]) + " to " + std::to_string(Starts[1] + workgroup.threads - 1) + " once (sorted value " + std::to_string(lane) + " is " + std::to_string(old[lane]) + ")");
}
auto expected = Starts;
expected[1] += workgroup.threads;
const auto atBase = ReadWords(queue, Base);
Require(atBase == expected, what + ": GDS at M0 base + offset holds " + Words4(atBase) + ", expected " + Words4(expected));
const auto atZero = ReadWords(queue, 0);
Require(atZero == Canaries, what + ": GDS at address 0 + offset holds " + Words4(atZero) + ", expected the untouched " + Words4(Canaries));
}
void CheckAdd64(AgcDriver::QueueState& queue, const Workgroup& workgroup) {
const auto what = workgroup.Name() + " ds_add_rtn_u64 gds with M0 base " + std::to_string(Base);
std::vector<std::uint32_t> old(Output.begin(), Output.begin() + workgroup.threads);
std::sort(old.begin(), old.end());
for (std::uint32_t lane = 0; lane < workgroup.threads; ++lane) {
Require(old[lane] == Starts[2] + lane, what + ": sorted returned low dword " + std::to_string(lane) + " is " + std::to_string(old[lane]) + ", expected " + std::to_string(Starts[2] + lane));
}
auto expected = Starts;
expected[2] += workgroup.threads;
const auto atBase = ReadWords(queue, Base);
Require(atBase == expected, what + ": GDS at M0 base + offset holds " + Words4(atBase) + ", expected " + Words4(expected));
const auto atZero = ReadWords(queue, 0);
Require(atZero == Canaries, what + ": GDS at address 0 + offset holds " + Words4(atZero) + ", expected the untouched " + Words4(Canaries));
}
void CheckRead(const Workgroup& workgroup) {
const auto what = workgroup.Name() + " ds_read_b32 gds with M0 base " + std::to_string(Base);
for (std::uint32_t lane = 0; lane < workgroup.threads; ++lane) {
Require(Output[lane] == Starts[2], what + ": lane " + std::to_string(lane) + " read " + std::to_string(Output[lane]) + ", expected " + std::to_string(Starts[2]) + " from M0 base + offset 8");
}
}
}
int main() {
try {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
if (device->Target().subgroupSize < 32) {
std::printf("skipped, the device's subgroups are narrower than a wave32 (%u lanes)\n", device->Target().subgroupSize);
return VulkanTestSkipped;
}
AgcDriver::QueueState queue;
for (const auto& workgroup : Workgroups) {
SetWords(queue, Base, Starts);
SetWords(queue, 0, Canaries);
Require(ReadWords(queue, Base) == Starts && ReadWords(queue, 0) == Canaries, workgroup.Name() + ": the GDS words did not read back as set");
Run(*device, workgroup, AddCode);
CheckAdd(queue, workgroup);
SetWords(queue, Base, Starts);
SetWords(queue, 0, Canaries);
Run(*device, workgroup, ReadCode);
CheckRead(workgroup);
SetWords(queue, Base, Starts);
SetWords(queue, 0, Canaries);
Run(*device, workgroup, Add64Code);
CheckAdd64(queue, workgroup);
}
std::puts("gds m0 base tests passed");
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -284,6 +284,7 @@ int main() {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
if (SkipWithoutSharedMemoryStores()) return VulkanTestSkipped;
if (SkipOnLlvmpipe(*device, "global atomic csub without glc: wave64 byte 644 is 146, expected 0 on subgroup size 8")) return VulkanTestSkipped;
GuestBlock guest;
Run(*device, guest, 32);
Run(*device, guest, 64);
@@ -17,6 +17,8 @@
#include <iostream>
#include <span>
#include <string>
#include <unordered_set>
#include <spirv/unified1/spirv.hpp>
namespace {
@@ -635,6 +637,22 @@ ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, Guest
return ShaderRecompiler::Recompile(request);
}
std::size_t PrivateArrays(std::span<const std::uint32_t> words) {
std::unordered_set<std::uint32_t> arrays;
std::unordered_set<std::uint32_t> pointers;
std::size_t variables = 0;
for (std::size_t cursor = 5; cursor < words.size();) {
const auto count = words[cursor] >> 16u;
Require(count != 0u && count <= words.size() - cursor, "gpu buffer format: malformed SPIR-V");
const auto op = words[cursor] & 0xffffu;
if (op == spv::OpTypeArray && count >= 4u) arrays.insert(words[cursor + 1]);
if (op == spv::OpTypePointer && count >= 4u && words[cursor + 2] == spv::StorageClassPrivate && arrays.contains(words[cursor + 3])) pointers.insert(words[cursor + 1]);
if (op == spv::OpVariable && count >= 4u && words[cursor + 3] == spv::StorageClassPrivate && pointers.contains(words[cursor + 1])) ++variables;
cursor += count;
}
return variables;
}
void Run(AgcDriver::VulkanDevice& device, const ShaderRecompiler::RecompileResult& shader, GuestBlock& guest, std::uint32_t records, std::uint32_t word3) {
auto descriptor = guest.Descriptor();
descriptor[0] = records;
@@ -654,6 +672,9 @@ int main() {
if (!device) return VulkanTestSkipped;
GuestBlock guest;
const auto shader = Compile(*device, guest);
const auto privateArrays = PrivateArrays(shader.spirv);
if (std::getenv("APS5_PRIVATE_BUFFER_FORMAT_TABLE") == nullptr) Require(privateArrays == 0u, "gpu buffer format: a run-time buffer format is looked up through a Private array, which drivers keep in per-invocation local memory");
else Require(privateArrays == 1u, "gpu buffer format: APS5_PRIVATE_BUFFER_FORMAT_TABLE did not bring the Private format table back");
for (const auto& test : Cases) {
Run(*device, shader, guest, test.records, test.word3);
for (std::uint32_t lane = 0; lane < Lanes; ++lane) {
@@ -219,6 +219,7 @@ int main() {
auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
if (!UnitShadowEnabled()) return Skip("unit shadows are off");
if (SkipOnLlvmpipe(*device, "host write over a shadowed unit: the import made without the GPU lock was refused")) return VulkanTestSkipped;
backing = memfd_create("anyps5-host-write-shadowed-unit", MFD_CLOEXEC | MFD_ALLOW_SEALING);
Require(backing >= 0 && ftruncate(backing, static_cast<off_t>(MappingBytes)) == 0, "host write over a shadowed unit: cannot make the backing file");
@@ -0,0 +1,253 @@
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
#include "Recompiler.hpp"
#include "VulkanTestDevice.hpp"
#include <algorithm>
#include <array>
#include <bit>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <limits>
#include <span>
#include <string>
#include <vector>
namespace AgcDriver {
struct VulkanDeviceTestAccess {
static bool ImageViewMinLod(const VulkanDevice& device) { return device.graphicsContext().imageViewMinLod; }
};
}
namespace {
using AgcDriver::Graphics::Require;
using ShaderRecompiler::ShaderStage;
constexpr std::uint32_t Threads = 32;
constexpr std::uint32_t Size = 16;
constexpr std::uint32_t Levels = 5;
constexpr std::uint32_t Format8888UNorm = 56;
constexpr std::uint32_t Format8888UInt = 60;
constexpr std::uint32_t Type2D = 9;
constexpr std::uint32_t ClampWrap = 0;
constexpr std::uint32_t ClampMirror = 1;
constexpr std::uint32_t ClampEdge = 2;
constexpr std::uint32_t ClampHalfBorder = 4;
constexpr std::uint32_t ClampBorder = 6;
constexpr std::uint32_t FilterPoint = 0;
constexpr std::uint32_t FilterBilinear = 1;
constexpr std::uint32_t MipNone = 0;
constexpr std::uint32_t MipPoint = 1;
alignas(256) std::array<std::uint32_t, Threads * 4> Input{};
alignas(256) std::array<std::uint32_t, Threads * 4> Output{};
alignas(4096) std::array<std::uint8_t, 65536> Texels{};
alignas(256) constexpr std::array<std::uint32_t, 10> Gather2DLod{
0x34020084, 0xe0381000, 0x80000201, 0xbf8c3f70, 0xf1100108, 0x00820602, 0xbf8c3f70, 0xe0781000,
0x80010601, 0xbf810000,
};
constexpr std::array<float, Threads> Lods{
0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 6.0f, 0.49f, 0.5f,
0.51f, 1.49f, 1.5f, 2.5f, -0.7f, -3.0f, 4294967296.0f, std::numeric_limits<float>::infinity(),
std::numeric_limits<float>::quiet_NaN(), 1.25f, 2.75f, 3.2f, 0.25f, 1.75f, -0.4f, 2.0f,
3.5f, 0.75f, 1.0f, 2.25f, 0.0f, 3.0f, 1.5f, 2.6f,
};
struct Variant {
std::uint32_t format;
std::uint32_t clampX;
std::uint32_t clampY;
std::uint32_t xyFilter;
std::uint32_t mipFilter;
std::uint32_t minLodRaw;
std::uint32_t maxLodRaw;
std::int32_t biasRaw;
std::uint32_t textureMinLodRaw;
const char* name;
};
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> TextureDescriptor(std::uint32_t format, std::uint32_t minLodRaw = 0u) {
const auto address = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(Texels.data()));
return {
static_cast<std::uint32_t>(address >> 8u),
static_cast<std::uint32_t>((address >> 40u) & 0xffu) | (minLodRaw << 8u) | (format << 20u) | (((Size - 1u) & 3u) << 30u),
((Size - 1u) >> 2u) | ((Size - 1u) << 14u),
0xfacu | ((Levels - 1u) << 16u) | (Type2D << 28u),
0u,
(Levels - 1u) << 4u,
0u,
0u,
};
}
std::array<std::uint32_t, 4> SamplerDescriptor(const Variant& variant) {
return {
variant.clampX | (variant.clampY << 3u) | (ClampEdge << 6u),
variant.minLodRaw | (variant.maxLodRaw << 12u),
(static_cast<std::uint32_t>(variant.biasRaw) & 0x3fffu) | (variant.xyFilter << 20u) | (variant.xyFilter << 22u) | (variant.mipFilter << 26u),
0u,
};
}
std::uint8_t Red(std::uint32_t level, std::uint32_t x, std::uint32_t y) {
return static_cast<std::uint8_t>(level * 61u + x * 13u + y * 7u + 3u);
}
void FillTexels() {
Texels.fill(0);
const auto surface = AgcDriver::Graphics::DescribeSurface(AgcDriver::Graphics::DecodeTextureResource(TextureDescriptor(Format8888UNorm)));
Require(surface.mips.size() == Levels, "the test surface has " + std::to_string(surface.mips.size()) + " mips, expected " + std::to_string(Levels));
for (std::uint32_t level = 0; level < Levels; ++level) {
const auto& mip = surface.mips.at(level);
const auto extent = Size >> level;
for (std::uint32_t y = 0; y < extent; ++y) {
for (std::uint32_t x = 0; x < extent; ++x) {
const auto offset = mip.tiledOffset + static_cast<std::uint64_t>(y) * mip.pitchBytes + x * 4u;
Require(offset + 4u <= Texels.size(), "the test surface does not fit its buffer");
auto* texel = Texels.data() + offset;
texel[0] = Red(level, x, y);
texel[1] = 0x11;
texel[2] = 0x22;
texel[3] = 0xff;
}
}
}
}
void FillInput() {
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
Input[tid * 4u + 0u] = std::bit_cast<std::uint32_t>(-0.37f + 0.077f * static_cast<float>(tid));
Input[tid * 4u + 1u] = std::bit_cast<std::uint32_t>(1.31f - 0.053f * static_cast<float>(tid));
Input[tid * 4u + 2u] = std::bit_cast<std::uint32_t>(Lods[tid]);
Input[tid * 4u + 3u] = 0u;
}
}
int Address(int coordinate, int extent, std::uint32_t clamp) {
switch (clamp) {
case ClampWrap: return ((coordinate % extent) + extent) % extent;
case ClampMirror: {
const int folded = ((coordinate % (2 * extent)) + 2 * extent) % (2 * extent);
return folded < extent ? folded : 2 * extent - 1 - folded;
}
case ClampEdge: return std::clamp(coordinate, 0, extent - 1);
default: return std::min(coordinate < 0 ? -1 - coordinate : coordinate, extent - 1);
}
}
bool Fallback(const Variant& variant) {
const auto border = [](std::uint32_t clamp) { return clamp == ClampHalfBorder || clamp == ClampBorder; };
return border(variant.clampX) || border(variant.clampY);
}
std::uint32_t Level(float lod, const Variant& variant) {
if (Fallback(variant)) return 0u;
if (variant.mipFilter == MipNone) return std::min(variant.textureMinLodRaw / 256u, Levels - 1u);
const auto clamp = [](float value, float low, float high) { return std::isnan(value) ? low : std::min(std::max(value, low), high); };
const float biased = lod + static_cast<float>(variant.biasRaw) / 256.0f;
const float sampled = std::min(std::isnan(biased) ? static_cast<float>(variant.minLodRaw) / 256.0f : std::max(biased, static_cast<float>(variant.minLodRaw) / 256.0f), static_cast<float>(variant.maxLodRaw) / 256.0f);
const float limited = clamp(std::max(sampled, static_cast<float>(variant.textureMinLodRaw) / 256.0f), 0.0f, static_cast<float>(Levels - 1u));
return static_cast<std::uint32_t>(std::clamp(std::ceil(limited + 0.5f) - 1.0f, 0.0f, static_cast<float>(Levels - 1u)));
}
std::array<std::uint32_t, 4> Expected(std::uint32_t tid, const Variant& variant) {
const float u = std::bit_cast<float>(Input[tid * 4u + 0u]);
const float v = std::bit_cast<float>(Input[tid * 4u + 1u]);
const auto level = Level(std::bit_cast<float>(Input[tid * 4u + 2u]), variant);
const int extent = static_cast<int>(Size >> level);
const int left = static_cast<int>(std::floor(u * static_cast<float>(extent) - 0.5f));
const int top = static_cast<int>(std::floor(v * static_cast<float>(extent) - 0.5f));
const auto texel = [&](int x, int y) {
if (Fallback(variant) && (x < 0 || y < 0 || x >= extent || y >= extent)) return 0u;
return static_cast<std::uint32_t>(Red(level, static_cast<std::uint32_t>(Address(x, extent, variant.clampX)), static_cast<std::uint32_t>(Address(y, extent, variant.clampY))));
};
return {texel(left, top + 1), texel(left + 1, top + 1), texel(left + 1, top), texel(left, top)};
}
ShaderRecompiler::RecompileResult Compile(AgcDriver::VulkanDevice& device, const Variant& variant) {
std::vector<std::uint32_t> userData(20, 0u);
const auto input = BufferDescriptor(Input.data(), static_cast<std::uint32_t>(sizeof(Input)));
const auto output = BufferDescriptor(Output.data(), static_cast<std::uint32_t>(sizeof(Output)));
const auto texture = TextureDescriptor(variant.format, variant.textureMinLodRaw);
const auto sampler = SamplerDescriptor(variant);
std::copy(input.begin(), input.end(), userData.begin());
std::copy(output.begin(), output.end(), userData.begin() + 4);
std::copy(texture.begin(), texture.end(), userData.begin() + 8);
std::copy(sampler.begin(), sampler.end(), userData.begin() + 16);
const std::span<const std::uint32_t> code(Gather2DLod);
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;
return ShaderRecompiler::Recompile(request);
}
void Run(AgcDriver::VulkanDevice& device, const Variant& variant) {
Output.fill(0xdeadbeefu);
const auto result = Compile(device, variant);
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(Gather2DLod.data()));
device.WaitIdle();
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
const auto expected = Expected(tid, variant);
for (std::uint32_t component = 0; component < 4u; ++component) {
const auto word = Output[tid * 4u + component];
std::uint32_t actual = word;
if (variant.format == Format8888UNorm) {
const float scaled = std::bit_cast<float>(word) * 255.0f;
Require(std::fabs(scaled - std::round(scaled)) < 1e-3f, std::string(variant.name) + ": thread " + std::to_string(tid) + " component " + std::to_string(component) + " is " + std::to_string(scaled) + "/255, not a whole step");
actual = static_cast<std::uint32_t>(std::lround(scaled));
}
Require(actual == expected[component], std::string(variant.name) + ": thread " + std::to_string(tid) + " (LOD " + std::to_string(Lods[tid]) + ", level " + std::to_string(Level(Lods[tid], variant)) + ") component " + std::to_string(component) + " is " + std::to_string(actual) + ", expected " + std::to_string(expected[component]));
}
}
}
}
int main() {
try {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
FillTexels();
FillInput();
constexpr std::uint32_t AllLevels = 15u << 8u;
Run(*device, {Format8888UNorm, ClampEdge, ClampEdge, FilterPoint, MipPoint, 0u, AllLevels, 0, 0u, "clamp to edge, point"});
Run(*device, {Format8888UNorm, ClampWrap, ClampWrap, FilterPoint, MipPoint, 0u, AllLevels, 0, 0u, "wrap, point"});
Run(*device, {Format8888UNorm, ClampMirror, ClampMirror, FilterPoint, MipPoint, 0u, AllLevels, 0, 0u, "mirror, point"});
Run(*device, {Format8888UNorm, ClampEdge, ClampWrap, FilterBilinear, MipPoint, 0u, AllLevels, 0, 0u, "bilinear x/y"});
Run(*device, {Format8888UNorm, ClampEdge, ClampEdge, FilterPoint, MipPoint, 320u, 704u, 0, 0u, "MIN_LOD 1.25, MAX_LOD 2.75"});
Run(*device, {Format8888UNorm, ClampEdge, ClampEdge, FilterPoint, MipPoint, 512u, 512u, 0, 0u, "MIN_LOD = MAX_LOD = 2"});
Run(*device, {Format8888UNorm, ClampEdge, ClampEdge, FilterPoint, MipPoint, 0u, AllLevels, -192, 0u, "LOD_BIAS -0.75"});
Run(*device, {Format8888UNorm, ClampEdge, ClampEdge, FilterPoint, MipNone, 0u, AllLevels, 0, 0u, "MIP_FILTER none"});
Run(*device, {Format8888UInt, ClampEdge, ClampWrap, FilterBilinear, MipPoint, 0u, AllLevels, 0, 0u, "8_8_8_8 UINT with a bilinear sampler"});
if (AgcDriver::VulkanDeviceTestAccess::ImageViewMinLod(*device)) {
Run(*device, {Format8888UNorm, ClampEdge, ClampEdge, FilterPoint, MipPoint, 0u, AllLevels, 0, 640u, "T# MIN_LOD 2.5"});
Run(*device, {Format8888UNorm, ClampEdge, ClampEdge, FilterPoint, MipNone, 0u, AllLevels, 0, 640u, "MIP_FILTER none, T# MIN_LOD 2.5"});
} else {
std::puts("T# MIN_LOD cases skipped, the device has no VK_EXT_image_view_min_lod");
}
Run(*device, {Format8888UNorm, ClampBorder, ClampHalfBorder, FilterPoint, MipPoint, 0u, AllLevels, 0, 0u, "border modes 6 and 4: base-level gather"});
std::puts("image 2D explicit-LOD gather tests passed");
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -222,13 +222,24 @@ std::array<float, 4> Texel(const std::uint8_t* target, std::uint32_t x, std::uin
return texel;
}
void Label(AgcDriver::VulkanDevice& device, const Block& block, std::uint32_t value, std::uint64_t submissions, bool watched, const char* what) {
bool Label(AgcDriver::VulkanDevice& device, const Block& block, std::uint32_t value, std::uint64_t& submissions, bool watched, const char* what) {
const auto bytes = std::as_bytes(std::span(&value, 1));
const auto reason = device.WriteLabelOnGpu(block.Address() + LabelOffset, bytes, value, 0);
Require(reason == 0, std::string(what) + ": the label was not recorded on the GPU (outcome " + std::to_string(reason) + ")");
Require(StorageTexture::FindPending(block.Address(), TargetBytes) == nullptr, std::string(what) + ": the drawn linear target was still pending after a label the GPU writes");
const auto* recorder = AgcDriver::Graphics::Recorder::Active();
Require(!watched || (recorder != nullptr && recorder->Submissions() == submissions), std::string(what) + ": storing the drawn linear target before the label waited for recorded work (" + std::to_string(recorder != nullptr ? recorder->Submissions() - submissions : 0) + " submissions)");
bool trapped = false;
#if defined(__APPLE__)
if (std::getenv("APS5_NO_LABEL_READ_TRAP") == nullptr && StorageTexture::FindPending(block.Address(), TargetBytes) != nullptr) {
trapped = true;
Require(watched, std::string(what) + ": the drawn linear target outside the write watch was left pending after a label the GPU writes");
const volatile std::uint8_t touched = block.data[0];
static_cast<void>(touched);
if (recorder != nullptr) submissions = recorder->Submissions();
}
#endif
Require(StorageTexture::FindPending(block.Address(), TargetBytes) == nullptr, std::string(what) + ": the drawn linear target was still pending after a label the GPU writes and the first CPU read of its memory");
return trapped;
}
bool Expect(AgcDriver::VulkanDevice& device) {
@@ -249,17 +260,26 @@ bool Expect(AgcDriver::VulkanDevice& device) {
};
Draw(device, color, red, {{0, 0}, {Width, Height}});
pending("after the first draw");
const auto submissions = recorder->Submissions();
auto submissions = recorder->Submissions();
Draw(device, color, blue, {{0, 0}, {Width / 2u, Height}});
pending("after the second draw");
Require(!watched || recorder->Submissions() == submissions, "the second draw into the linear target submitted recorded work");
Draw(device, color, red, {{Width / 4u, Height / 4u}, {Width / 4u, Height / 2u}});
pending("after the third draw");
Require(!watched || recorder->Submissions() == submissions, "the third draw into the linear target submitted recorded work");
Label(device, block, 1u, submissions, watched, "the first label");
const bool trapped = Label(device, block, 1u, submissions, watched, "the first label");
for (std::uint32_t y = 0; trapped && y < Height; ++y) {
for (std::uint32_t x = 0; x < Width; ++x) {
const bool thirdRed = x >= Width / 4u && x < Width / 2u && y >= Height / 4u && y < Height * 3u / 4u;
const float z = thirdRed || x >= Width / 2u ? 0.0f : 1.0f;
const std::array<float, 4> expected{static_cast<float>(x), static_cast<float>(y), z, 1.0f};
const auto texel = Texel(block.data, x, y);
Require(texel == expected, "after the first label, CPU read: pixel (" + std::to_string(x) + ", " + std::to_string(y) + ") holds (" + std::to_string(texel[0]) + ", " + std::to_string(texel[1]) + ", " + std::to_string(texel[2]) + ", " + std::to_string(texel[3]) + ")");
}
}
Draw(device, color, blue, {{Width / 2u, 0}, {Width / 2u, Height}});
pending("after the fourth draw");
Label(device, block, 2u, submissions, watched, "the second label");
static_cast<void>(Label(device, block, 2u, submissions, watched, "the second label"));
Draw(device, color, red, {{0, Height / 2u}, {Width, Height / 2u}});
pending("after the fifth draw");
Require(!watched || recorder->Submissions() == submissions, "the fifth draw into the linear target submitted recorded work");
@@ -4622,6 +4622,118 @@ void CheckElidedFillOverArmedClear(Context context, std::uint32_t samples) {
std::printf("Native D32 with HTILE, samples=%u: a recorded fill superseded an armed clear dispatch while an elided fill kept its pending-write refusal\n", samples);
}
enum class ReuseCase { VertexRead, IndexRead, StorageTexture, NewDepthTarget, CpuRead, DmaCopy, Rebind, ShaderBufferRead, TextureRead, DecidedVertexRead };
void CheckReusePublication(Context context, ReuseCase use) {
constexpr std::uint32_t samples = 4u;
constexpr VkExtent2D extent{256u, 64u};
const auto depthBytes = static_cast<std::size_t>(MultisampledDepthBytes_nid_no_patch(extent, 4u, samples));
const auto stencilBytes = static_cast<std::size_t>(MultisampledDepthBytes_nid_no_patch(extent, 1u, samples));
const auto metadataBytes = static_cast<std::size_t>(HtileMetadataBytes(extent));
TargetMemory memory(depthBytes, true), stencil(stencilBytes, true), metadata(65536u, true);
std::memset(stencil.Data(), 0x5a, stencilBytes);
std::memset(metadata.Data(), 0, metadataBytes);
DepthTarget target{memory.Address(), stencil.Address(), extent, VK_FORMAT_D32_SFLOAT_S8_UINT, 0.0f, 0x5au, metadata.Address(), false, samples};
target.depthSwizzle = 24u;
target.pipeBankXor = 0x8c00u;
target.iterate256 = true;
target.htilePipeAligned = true;
target.htileDepthOnly = true;
const MultisampleTextureLayout depthLayout(TextureTileMode::kZ64KBX, 4u, samples, extent.width, extent.height, 1u, target.pipeBankXor);
const MultisampleTextureLayout stencilLayout(TextureTileMode::kZ64KBX, 1u, samples, extent.width, extent.height, 1u, target.pipeBankXor);
std::vector<std::byte> host(stencilBytes, std::byte{0x5a});
for (std::uint32_t y = 0u; y < extent.height; ++y) {
for (std::uint32_t x = 0u; x < extent.width; ++x) {
for (std::uint32_t sample = 0u; sample < samples; ++sample) host[stencilLayout.Offset(x, y, 0u, sample)] = static_cast<std::byte>(0x20u + sample);
}
}
Require(std::none_of(host.begin(), host.begin() + 4096, [](std::byte value) { return value == std::byte{0x5a}; }), "the reuse publication fixture does not draw its first stencil page whole");
Recorder recorder(context);
recorder.Activate();
std::unique_ptr<DepthRaster> raster;
struct Cleanup {
Recorder& recorder;
Context context;
~Cleanup() { recorder.Sync(); ClearCachedTextures(context.device); ClearDepthSurfaces(context.device); ClearMultisampleTargets(context.device); }
} cleanup{recorder, context};
const auto view = DepthSurfaceView(context, target);
NoteDepthSurfaceWrite(context, target);
raster = std::make_unique<DepthRaster>(context, target, view, StencilUse{VK_COMPARE_OP_ALWAYS, VK_STENCIL_OP_REPLACE, 0x20u}, false, true);
raster->Run(recorder.Commands(), 0.25f);
constexpr std::size_t stored = 0x64u;
const auto guestStencil = [&] { return std::vector<std::byte>(reinterpret_cast<const std::byte*>(target.stencilAddress), reinterpret_cast<const std::byte*>(target.stencilAddress) + stencilBytes); };
const auto drawn = guestStencil();
const auto serial = DepthSurfacesSerial();
if (use == ReuseCase::Rebind) Require(DepthSurfaceView(context, target) == view && DepthSurfacesSerial() == serial && guestStencil() == drawn, "rebinding the same native depth identity imported or published it");
if (use == ReuseCase::ShaderBufferRead || use == ReuseCase::TextureRead || use == ReuseCase::DecidedVertexRead) {
if (use == ReuseCase::ShaderBufferRead) {
RequireNoResidentDepthRead_nid_no_patch(target.address, depthBytes, std::nullopt);
RequireNoMultisampleColorTarget(target.address, depthBytes, "a shader buffer access");
} else if (use == ReuseCase::TextureRead) RequireNoMultisampleTarget(target.address, depthBytes, "a texture read");
else RequireNoMultisampleTarget(target.stencilAddress, 4096u, "a vertex buffer read", DepthReadCause::Reuse);
Require(guestStencil() == host, "a depth read of a host-written native owner did not publish the host's stencil bytes");
for (std::uint32_t y = 0u; y < extent.height; ++y) {
for (std::uint32_t x = 0u; x < extent.width; ++x) {
for (std::uint32_t sample = 0u; sample < samples; ++sample) {
const float value = 0.25f + static_cast<float>(sample + 1u) / 16.0f;
Require(std::memcmp(reinterpret_cast<const void*>(target.address + depthLayout.Offset(x, y, 0u, sample)), &value, 4u) == 0, "a depth read of a host-written native owner did not publish the host's depth samples");
}
}
}
Require(DepthSurfaceAt(target.address) && DepthSurfaceView(context, target) == view && DepthSurfacesSerial() == serial, "a depth read of a host-written native owner retired or re-imported it");
if (use == ReuseCase::DecidedVertexRead) Require(CachedSampledTexture(context, DepthSampleWords(target)) != nullptr, "a native depth owner kept by a reuse that took no guest byte could not be sampled");
return;
}
*reinterpret_cast<volatile std::byte*>(target.stencilAddress + stored) = std::byte{0x77};
const auto held = guestStencil();
constexpr std::string_view refusal = "native multisample depth publication cannot distinguish an unwritten byte from a same-value guest store";
std::vector<std::byte> page(4096u);
if (use == ReuseCase::CpuRead || use == ReuseCase::DmaCopy || use == ReuseCase::Rebind) {
if (use != ReuseCase::DmaCopy) TargetRefuses([&] { AgcDriver::GuestMemory::Read(target.stencilAddress, page); }, refusal);
else TargetRefuses([&] { RequireNoMultisampleTarget(target.stencilAddress, page.size(), "a DMA copy"); }, refusal);
Require(guestStencil() == held, "a refused native depth publication committed guest bytes");
Require(DepthSurfaceAt(target.address), "a refused native depth publication retired its owner");
return;
}
if (use == ReuseCase::VertexRead) RequireNoMultisampleTarget(target.stencilAddress, page.size(), "a vertex buffer read", DepthReadCause::Reuse);
if (use == ReuseCase::IndexRead) RequireNoMultisampleTarget(target.stencilAddress, page.size(), "an index buffer read", DepthReadCause::Reuse);
if (use == ReuseCase::StorageTexture) {
GuestTextureResource alias{};
alias.baseAddress = target.stencilAddress;
alias.width = 256u;
alias.height = 4u;
alias.mipCount = alias.allocatedMipCount = 1u;
alias.dimension = TextureDimension::k2D;
alias.tileMode = TextureTileMode::kLinear;
alias.format = 22u;
alias.dstSelX = 0u;
alias.dstSelY = alias.dstSelZ = 4u;
alias.dstSelW = 5u;
Require(CachedStorageSurface(context, alias) != nullptr, "a storage texture over a reused native depth owner's stencil page was not created");
}
if (use == ReuseCase::NewDepthTarget) {
auto other = target;
other.extent = {128u, 64u};
const auto otherView = DepthSurfaceView(context, other);
Require(otherView != VK_NULL_HANDLE && otherView != view && DepthSurfacesSerial() == serial + 1u, "a new native depth attachment over a reused owner's planes did not import");
Require(DepthSurfaceAt(other.address), "a new native depth attachment over a reused owner's planes is not resident");
}
const auto published = guestStencil();
for (std::size_t offset = 0u; offset < stencilBytes; ++offset) {
Require(published[offset] == (offset < 4096u ? held[offset] : host[offset]), "a reuse publication did not keep the guest's undecided stencil bytes and the host's decided ones");
}
for (std::uint32_t y = 0u; y < extent.height; ++y) {
for (std::uint32_t x = 0u; x < extent.width; ++x) {
for (std::uint32_t sample = 0u; sample < samples; ++sample) {
const float value = 0.25f + static_cast<float>(sample + 1u) / 16.0f;
Require(std::memcmp(reinterpret_cast<const void*>(target.address + depthLayout.Offset(x, y, 0u, sample)), &value, 4u) == 0, "a reuse publication did not publish the host's depth samples");
}
}
}
if (use != ReuseCase::NewDepthTarget) {
const auto before = DepthSurfacesSerial();
Require(DepthSurfaceView(context, target) != VK_NULL_HANDLE && DepthSurfacesSerial() == before + 1u, "a reuse publication left its native depth owner resident");
}
}
int main(int argc, char** argv) {
try {
@@ -4691,6 +4803,7 @@ int main(int argc, char** argv) {
if (!supported(samples) || (context.limits.framebufferColorSampleCounts & samples) == 0u) continue;
for (const auto write : {PublicationWrite::AliasImported, PublicationWrite::AliasDrawnAfterImport, PublicationWrite::StencilAliasImported, PublicationWrite::StencilAliasRefilled, PublicationWrite::StencilAliasDrawnAfterImport}) CheckDepthPublication(publishing, samples, write, true);
}
for (const auto use : {ReuseCase::VertexRead, ReuseCase::IndexRead, ReuseCase::StorageTexture, ReuseCase::NewDepthTarget, ReuseCase::CpuRead, ReuseCase::DmaCopy, ReuseCase::Rebind, ReuseCase::ShaderBufferRead, ReuseCase::TextureRead, ReuseCase::DecidedVertexRead}) CheckReusePublication(publishing, use);
return 0;
}
CheckDrawFeedback();
@@ -0,0 +1,271 @@
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp"
#include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "prx/libc/include/GuestArena.hpp"
#include "prx/libc/include/GuestWriteWatch.hpp"
#include "Recompiler.hpp"
#include "VulkanTestDevice.hpp"
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <sys/mman.h>
#endif
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <memory>
#include <mutex>
#include <span>
#include <string>
#include <vector>
namespace AgcDriver {
struct VulkanDeviceTestAccess {
static Graphics::Context ContextOf(const VulkanDevice& device) { return device.graphicsContext(); }
};
}
namespace {
using AgcDriver::Graphics::CompiledShader;
using AgcDriver::Graphics::Require;
using AgcDriver::Graphics::RuntimeSwitch;
using AgcDriver::Graphics::ShaderResources;
using AgcDriver::Graphics::StorageTexture;
using ShaderRecompiler::ShaderStage;
namespace RuntimeSwitches = AgcDriver::Graphics::RuntimeSwitches;
constexpr std::uint32_t Threads = 32;
constexpr std::uint32_t Side = 128;
constexpr std::uint32_t Format8888UNorm = 56;
constexpr std::uint32_t Format32Float = 22;
constexpr std::uint32_t TileR64KBX = 0x1b;
constexpr std::uint32_t Type2D = 9;
constexpr std::uint32_t ClampEdge = 2;
constexpr std::size_t BlockBytes = 2u << 20u;
alignas(256) constexpr std::array<std::uint32_t, 5> StoreCode{
0x7e020280, 0x7e04020c, 0xf0201108, 0x00010200, 0xbf810000,
};
alignas(256) constexpr std::array<std::uint32_t, 12> SampleCode{
0x1614008c, 0xe03c1000, 0x8000010a, 0xbf8c3f70, 0xf09c0f08, 0x00820402, 0xbf8c3f70,
0x34160084, 0xe0781000, 0x8001040b, 0xbf810000, 0xbf810000,
};
std::uint64_t AddressOf(const void* data) {
return static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(data));
}
class GuestBlock {
public:
GuestBlock() {
#ifdef _WIN32
block = static_cast<std::uint8_t*>(GuestArena::GuestArenaAllocate_nid_postfix(BlockBytes, 65536));
if (block != nullptr) GuestArena::GuestArenaCommit_nid_postfix(block, BlockBytes, PAGE_READWRITE, BlockBytes);
#else
constexpr std::uintptr_t alignment = 65536;
void* mapped = mmap(nullptr, BlockBytes + alignment, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (mapped != MAP_FAILED) {
const auto begin = reinterpret_cast<std::uintptr_t>(mapped);
const auto aligned = (begin + alignment - 1) & ~(alignment - 1);
if (aligned != begin) munmap(mapped, aligned - begin);
if (aligned + BlockBytes != begin + BlockBytes + alignment) munmap(reinterpret_cast<void*>(aligned + BlockBytes), begin + alignment - aligned);
block = reinterpret_cast<std::uint8_t*>(aligned);
GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, BlockBytes);
}
#endif
Require(block != nullptr, "own refresh view alias: cannot allocate a guest block");
std::memset(block, 0, BlockBytes);
GuestAllocations::Mutation().Add(block, BlockBytes, true, true, true);
AgcDriver::GuestMemory::CollectWritesUncached(AddressOf(block), BlockBytes);
}
~GuestBlock() {
GuestAllocations::Mutation().Remove(block);
#ifdef _WIN32
GuestArena::GuestArenaReset_nid_postfix(block, BlockBytes);
GuestArena::GuestArenaRelease_nid_postfix(block, BlockBytes);
#else
munmap(block, BlockBytes);
GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(block, BlockBytes);
#endif
}
GuestBlock(const GuestBlock&) = delete;
GuestBlock& operator=(const GuestBlock&) = delete;
std::uint8_t* Data() { return block; }
private:
std::uint8_t* block = nullptr;
};
std::array<std::uint32_t, 8> TextureDescriptor(const std::uint8_t* texels, std::uint32_t format) {
const auto address = AddressOf(texels);
return {
static_cast<std::uint32_t>(address >> 8u),
static_cast<std::uint32_t>((address >> 40u) & 0xffu) | (format << 20u) | (((Side - 1u) & 3u) << 30u),
((Side - 1u) >> 2u) | ((Side - 1u) << 14u),
0xfacu | (TileR64KBX << 20u) | (Type2D << 28u),
0u,
0u,
0u,
0u,
};
}
std::array<std::uint32_t, 4> BufferDescriptor(const void* data, std::uint32_t bytes) {
const auto address = AddressOf(data);
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu), bytes, 0x31016facu};
}
ShaderRecompiler::RecompileResult Compile(const AgcDriver::VulkanDevice& device, std::span<const std::uint32_t> code, std::span<const std::uint32_t> userData) {
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;
return ShaderRecompiler::Recompile(request);
}
void Store(AgcDriver::VulkanDevice& device, const std::uint8_t* texels, std::uint32_t value) {
std::vector<std::uint32_t> userData(16, 0u);
const auto texture = TextureDescriptor(texels, Format32Float);
std::copy(texture.begin(), texture.end(), userData.begin() + 4);
userData[12] = value;
const auto result = Compile(device, StoreCode, userData);
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(StoreCode.data()));
device.WaitIdle();
}
std::vector<std::uint32_t> SampleUserData(const std::uint8_t* texels, std::uint8_t* buffers) {
std::vector<std::uint32_t> userData(24, 0u);
const auto input = BufferDescriptor(buffers, Threads * 12u);
const auto output = BufferDescriptor(buffers + 4096u, Threads * 16u);
const auto texture = TextureDescriptor(texels, Format8888UNorm);
const std::array<std::uint32_t, 4> sampler{ClampEdge | (ClampEdge << 3u) | (ClampEdge << 6u), 0u, 0u, 0u};
std::copy(input.begin(), input.end(), userData.begin());
std::copy(output.begin(), output.end(), userData.begin() + 4);
std::copy(texture.begin(), texture.end(), userData.begin() + 8);
std::copy(sampler.begin(), sampler.end(), userData.begin() + 16);
return userData;
}
std::string Path(const ShaderResources::ProofReport& report) {
switch (report.path) {
case ShaderResources::ProofPath::Fast: return "fast path";
case ShaderResources::ProofPath::OwnRefreshed: return "own-object refresh";
default: return "full walk";
}
}
std::string Hex(std::uint32_t value) {
char text[16];
std::snprintf(text, sizeof(text), "0x%08x", value);
return text;
}
void RequireSampled(const std::uint8_t* buffers, std::uint32_t stored, const std::string& what) {
std::array<float, 4> sampled{};
std::memcpy(sampled.data(), buffers + 4096u, sizeof(sampled));
for (std::uint32_t channel = 0; channel < 4; ++channel) {
const auto expected = static_cast<float>((stored >> (channel * 8u)) & 0xffu) / 255.0f;
Require(std::fabs(sampled[channel] - expected) < 1e-4f, what + ": channel " + std::to_string(channel) + " reads " + std::to_string(sampled[channel]) + ", expected " + std::to_string(expected) + " from the R32 float store of " + Hex(stored));
}
}
bool Run(AgcDriver::VulkanDevice& device) {
GuestBlock block;
GuestBlock buffers;
auto* texels = block.Data();
const auto surface = AddressOf(texels);
const auto bytes = static_cast<std::size_t>(AgcDriver::Graphics::DescribeSurface(AgcDriver::Graphics::DecodeTextureResource(TextureDescriptor(texels, Format8888UNorm))).guestBytes);
std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex());
const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device);
Store(device, texels, 0x11223344u);
StorageTexture::FlushPending(surface, bytes, nullptr, "test");
device.WaitIdle();
AgcDriver::GuestMemory::CollectWritesUncached(surface, bytes);
if (!AgcDriver::Graphics::HostImportCovers(context, surface, bytes)) {
std::puts("skipped, the device does not import guest memory");
return false;
}
const bool compared = !AgcDriver::GuestMemory::Watched(surface, bytes);
std::printf("the surface is %s\n", compared ? "compared, not write-watched" : "write-watched");
Require(StorageTexture::FindPending(surface, bytes) == nullptr, "the first R32 float store stayed pending after its flush");
const auto userData = SampleUserData(texels, buffers.Data());
const auto program = Compile(device, SampleCode, userData);
const CompiledShader shader{ShaderStage::Compute, &program, 0};
auto resources = std::make_shared<ShaderResources>(context, shader);
Require(resources->Reusable() && resources->SampledTextures().size() == 1, "the set is not reusable over one texture");
const auto view = resources->SampledTextures().front();
const auto source = view->SharedStorageSource();
Require(source != nullptr && source->Descriptor().format == Format8888UNorm, "the 8888 unorm view is not a view of its own storage image");
for (const std::uint32_t value : {0x3c003c00u, 0x41804180u}) {
Store(device, texels, value);
const auto alias = StorageTexture::FindPending(surface, bytes);
Require(alias != nullptr && alias != source && alias->Descriptor().format == Format32Float, "the R32 float store left no pending image of its own over the surface");
Require(source->IsPendingAlias(*alias), "the pending R32 float image is not the 8888 unorm image's alias");
ShaderResources::ProofReport report;
Require(resources->Revalidate(shader, &report), "the set over the view was not proved current over the pending alias");
if (!compared) Require(report.path == ShaderResources::ProofPath::OwnRefreshed, "a set whose view refreshed its own image through a pending R32 float alias took the " + Path(report) + ", not the own-object refresh");
Require(resources->SampledTextures().front() == view, "the proof replaced the view");
const auto rebuilt = std::make_shared<ShaderResources>(context, shader);
Require(rebuilt->SampledTextures().size() == 1 && rebuilt->SampledTextures().front() == view, "a build over the pending alias replaced the cached view");
std::memset(buffers.Data() + 4096u, 0xff, Threads * 16u);
device.Dispatch(program, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(SampleCode.data()));
device.WaitIdle();
RequireSampled(buffers.Data(), value, "the dispatch through the kept view");
if (!compared) Require(StorageTexture::FindPending(surface, bytes) == alias, "the view's refresh wrote the alias's results back instead of taking them on the device");
}
RuntimeSwitches::Assign(RuntimeSwitch::NoAliasViews, true);
Store(device, texels, 0x7f107f10u);
const auto replaced = std::make_shared<ShaderResources>(context, shader);
RuntimeSwitches::Assign(RuntimeSwitch::NoAliasViews, false);
Require(replaced->SampledTextures().size() == 1 && replaced->SampledTextures().front() != view, "APS5_NO_ALIAS_VIEWS kept the view over the pending alias");
StorageTexture::FlushPending(surface, bytes, nullptr, "test");
device.WaitIdle();
AgcDriver::Graphics::ClearCachedTextures(device.Device());
return true;
}
}
int main() {
#ifdef _WIN32
if (std::getenv("APS5_TEMPLATE_AUDIT_MS") == nullptr) _putenv_s("APS5_TEMPLATE_AUDIT_MS", "0");
if (std::getenv("APS5_VERIFY_PROOFS") == nullptr) _putenv_s("APS5_VERIFY_PROOFS", "1");
#else
setenv("APS5_TEMPLATE_AUDIT_MS", "0", 0);
setenv("APS5_VERIFY_PROOFS", "1", 0);
#endif
try {
const auto device = OpenVulkanTestDevice();
if (!device) return VulkanTestSkipped;
if (!Run(*device)) return VulkanTestSkipped;
std::puts("own refresh view alias tests passed");
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
@@ -3,6 +3,7 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ShaderInputState.hpp"
#include "prx/libSceAgcDriver/Graphics/include/State.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
@@ -31,6 +32,7 @@
#include <limits>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace {
@@ -172,21 +174,21 @@ struct Block {
std::uint8_t* data = nullptr;
};
AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, std::uint32_t attrib3, bool standardOrder) {
AgcDriver::Graphics::ColorTarget DecodeTarget(const Block& block, std::uint32_t attrib3, bool standardOrder, std::uint32_t sampleShift = 0) {
AgcDriver::Registers cx;
cx[0x318] = static_cast<std::uint32_t>(block.Address() >> 8u);
cx[0x31b] = 0;
cx[0x31c] = standardOrder ? StandardOrderInfo : Float11_11_10Info;
cx[0x31d] = 0;
cx[0x31d] = (sampleShift << 12u) | (sampleShift << 15u);
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 == (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");
Require(color.format == VK_FORMAT_R32_UINT && color.elementBytes == 4 && color.componentMapping == (standardOrder ? 0xe4u : 0xc6u) && color.packing == ShaderRecompiler::ColorExportPacking::Float11_11_10 && color.samples == 1u << sampleShift && (color.bytes << sampleShift) == block.bytes, "the 11_11_10 float target did not decode as a packed R32_UINT surface");
return color;
}
void Draw(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarget& color, std::uint32_t exportFormat, std::span<const std::uint32_t> pixelCode) {
void Draw(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarget& color, std::uint32_t exportFormat, std::span<const std::uint32_t> pixelCode, std::uint16_t sampleMask = 0xffffu) {
const auto target = device.Target();
constexpr std::uint32_t waveSize = 64;
std::vector<std::uint32_t> vertexUserData(4, 0u);
@@ -221,6 +223,8 @@ void Draw(AgcDriver::VulkanDevice& device, const AgcDriver::Graphics::ColorTarge
state.blends = {blend};
state.blend = blend;
state.blendConstants = {};
state.samples = color.samples;
state.quadSampleMask.fill(sampleMask);
const auto codeAddress = reinterpret_cast<std::uintptr_t>(pixelCode.data());
const AgcDriver::Registers context{{0x1b6, 0x8000}, {0x1b3, 0}, {0x1b4, 0}, {0x203, 0}, {0x1c5, exportFormat}};
@@ -279,6 +283,39 @@ void ExpectSurface(AgcDriver::VulkanDevice& device, const Block& block, const Co
}
}
void ResolveCase(AgcDriver::VulkanDevice& device, std::uint32_t sampleShift, const std::vector<std::array<float, 3>>& samples, std::uint32_t word, const std::string& what) {
const ColorTargetLayout layout(Width, Height, ColorTileMode::RenderTarget, 4);
Block source(layout.Bytes() << sampleShift);
Block resolved(layout.Bytes());
std::memset(source.data, 0, source.bytes);
std::memset(resolved.data, 0x5a, resolved.bytes);
const auto multisampled = DecodeTarget(source, TiledAttrib3, true, sampleShift);
for (std::uint32_t sample = 0; sample < (1u << sampleShift); ++sample) Draw(device, multisampled, Float32Export, Float32Program(samples[sample % samples.size()]), static_cast<std::uint16_t>(1u << sample));
AgcDriver::Graphics::ColorMetadataPass pass{};
pass.mode = AgcDriver::Graphics::ColorMetadataPass::Mode::Resolve;
pass.source = multisampled;
pass.targets = {DecodeTarget(resolved, TiledAttrib3, true)};
device.ColorMetadataPass(pass);
ExpectSurface(device, resolved, layout, std::vector<std::uint32_t>(resolved.bytes / 4u, 0u), word, what);
AgcDriver::Graphics::ClearMultisampleTargets(device.Device());
}
void ResolveTests(AgcDriver::VulkanDevice& device) {
const float infinity = std::numeric_limits<float>::infinity();
const float nan = std::bit_cast<float>(0x7fa00000u);
ResolveCase(device, 2u, {{1.0f + 1.0f / 32.0f, 3.0f, std::ldexp(1.0f, -15)}, {1.0f + 1.0f / 16.0f, 0.5f, std::ldexp(1.0f, -16)}},
(SmallFloat(1.0f, 5) + 1u) | (SmallFloat(1.75f, 6) << 10u) | (24u << 21u), "a CB resolve of a four-sample 11_11_10 float target");
ResolveCase(device, 2u, {{infinity, infinity, nan}, {1.0f, 1.0f, 2.0f}, {nan, 1.0f, 2.0f}, {1.0f, 1.0f, 2.0f}},
0x3f0u | (0x7c0u << 10u) | (0x7e0u << 21u), "a CB resolve of a four-sample 11_11_10 float target with NaN and infinite samples");
try {
ResolveCase(device, 3u, {{1.0f, 7.4375f, 7.4375f}, {1.0f, 49152.0f, 49152.0f}, {1.0f, 24.5f, 24.5f}, {1.0f, 10240.0f, 10240.0f}, {1.0f, 3424.0f, 3424.0f}, {1.0f, 13440.0f, 13440.0f}, {1.0f, 0.06201171875f, 0.06201171875f}, {1.0f, 38400.0f, 38400.0f}},
SmallFloat(1.0f, 5) | (0x72fu << 10u) | (0x72fu << 21u), "a CB resolve of an eight-sample 11_11_10 float target whose float32 sum rounds up");
} catch (const std::runtime_error& error) {
if (std::string_view(error.what()) != "AGC graphics: the device cannot render color with the target's sample count") throw;
std::puts("eight-sample 11_11_10 float resolve skipped, the device lacks eight-sample color attachments");
}
}
std::vector<std::uint32_t> Fill(Block& block) {
std::vector<std::uint32_t> words(block.bytes / 4u);
for (std::size_t index = 0; index < words.size(); ++index) words[index] = static_cast<std::uint32_t>(index * 0x9e3779b9u);
@@ -333,6 +370,7 @@ int main() {
TargetTests(*device, tiled, TiledAttrib3, ColorTileMode::RenderTarget, standardOrder ? "tiled standard-order" : "tiled", standardOrder);
TargetTests(*device, linear, LinearAttrib3, ColorTileMode::Linear, standardOrder ? "linear standard-order" : "linear", standardOrder);
}
ResolveTests(*device);
std::puts("11_11_10 float color target tests passed");
return 0;
} catch (const std::exception& error) {
@@ -144,6 +144,10 @@ void Dump(std::vector<std::uint32_t>& commands, const void* destination) {
Append(commands, 0x46, {0x139u, static_cast<std::uint32_t>(address), static_cast<std::uint32_t>(address >> 32u)});
}
void Control(std::vector<std::uint32_t>& commands, std::uint32_t blocks) {
Append(commands, 0x46, {0x138u, (blocks << 11u) | (2u << 9u), 0u});
}
void Submit(std::vector<std::uint32_t>& commands) {
const auto done = reinterpret_cast<std::uintptr_t>(&Done);
Done = 0;
@@ -190,6 +194,34 @@ void DumpsCountTheDrawsBeforeThem(const GuestBlock& guest) {
Require(dumps == (queued ? 4u : 0u), std::to_string(dumps) + " of 4 dumps were queued behind the draws");
}
void ControlledDumpsWriteOnlyTheirBlocks(const GuestBlock& guest) {
constexpr std::uint64_t untouched = (static_cast<std::uint64_t>(FirstFill) << 32u) | FirstFill;
auto* slots = guest.Slots();
std::vector<std::uint32_t> commands;
Fill(commands, FirstFill, slots, SlotCount * sizeof(std::uint64_t));
Control(commands, 0xffu);
Dump(commands, &slots[0]);
Draw(commands, guest.Target());
Dump(commands, reinterpret_cast<const std::byte*>(slots) + 8);
Control(commands, 0xf0u);
Dump(commands, &slots[32]);
Control(commands, 0u);
Dump(commands, reinterpret_cast<const std::byte*>(&slots[32]) + 8);
Control(commands, 0xffffu);
Submit(commands);
const auto begin = Count(slots, 0);
const auto end = Count(slots, 1);
Require(end > begin, "the end dump under eight enabled blocks counted " + std::to_string(end - begin) + " samples for the draw before it");
for (std::size_t slot = 2; slot < 16; ++slot) Require(slots[slot] == SampleReady, "slot " + std::to_string(slot) + " of an enabled block is not an empty ready block");
for (std::size_t slot = 16; slot < 32; ++slot) Require(slots[slot] == untouched, "slot " + std::to_string(slot) + " belongs to a block PIXEL_PIPE_STAT_CONTROL disabled, but a dump wrote it");
Require(Count(slots, 40) == end, "the dump whose first enabled block is block 4 counted " + std::to_string(Count(slots, 40)) + " samples there, expected " + std::to_string(end));
for (std::size_t slot = 32; slot < SlotCount; ++slot) {
if (slot == 40) continue;
const bool written = slot % 2 == 0 && slot >= 42 && slot <= 46;
Require(slots[slot] == (written ? SampleReady : untouched), "slot " + std::to_string(slot) + (written ? " of an enabled block is not an empty ready block" : " belongs to a disabled block, but a dump wrote it"));
}
}
}
int main() {
@@ -208,6 +240,7 @@ int main() {
{
const GuestBlock guest;
DumpsCountTheDrawsBeforeThem(guest);
ControlledDumpsWriteOnlyTheirBlocks(guest);
}
AgcDriverShutdown_nid_postfix();
std::puts("pipelined sample dump tests passed");
@@ -38,6 +38,14 @@ alignas(256) constexpr std::array<std::uint32_t, 6> VertexValuePixelCode{
0xc80a0000, 0xc80e0001, 0xc8120002, 0xf800180f, 0x04040302, 0xbf810000,
};
alignas(256) constexpr std::array<std::uint32_t, 6> VertexValueYPixelCode{
0xc80a0100, 0xc80e0101, 0xc8120102, 0xf800180f, 0x04040302, 0xbf810000,
};
alignas(256) constexpr std::array<std::uint32_t, 10> AffineVertexValuePixelCode{
0xc80a0000, 0xc80e0001, 0xc8120002, 0x080a0902, 0x080c0903, 0x56080b00, 0x56080d01, 0xf800180f, 0x04040404, 0xbf810000,
};
alignas(256) constexpr std::array<std::uint32_t, 4> FlatBarycentricPixelCode{
0xc8120002, 0xf800180f, 0x04040100, 0xbf810000,
};
@@ -259,10 +267,10 @@ std::uint32_t CheckBarycentrics(Emulation emulation, const std::string& what, bo
return checked;
}
void CheckVertexValues(Emulation emulation) {
void CheckVertexValues(Emulation emulation, bool raw = false, std::size_t component = 0) {
const auto positions = ClipPositions(emulation);
const auto p0 = positions[0][0];
const std::array<float, 3> expected{positions[1][0] - p0, positions[2][0] - p0, p0};
const auto p0 = positions[0][component];
const std::array<float, 3> expected = raw ? std::array<float, 3>{positions[1][component], positions[2][component], p0} : std::array<float, 3>{positions[1][component] - p0, positions[2][component] - p0, p0};
std::uint32_t checked = 0;
for (std::uint32_t y = 0; y < Height; ++y) {
for (std::uint32_t x = 0; x < Width; ++x) {
@@ -425,6 +433,40 @@ void CheckFirstVertex(AgcDriver::VulkanDevice& device) {
std::printf("a pass-through input read only at P0 is a flat input of the first vertex: %u pixels, %u and %u of a strip's even and odd triangle\n", checked, stripChecked[0], stripChecked[1]);
}
void CheckRectListPassThrough(AgcDriver::VulkanDevice& device) {
const auto perspective = PixelInputBit(PixelInput::PerspectiveCenter);
PassThrough = true;
for (const std::size_t component : {0u, 1u}) {
const auto result = Draw(device, Emulation::RectList, component == 0u ? std::span<const std::uint32_t>(VertexValuePixelCode) : std::span<const std::uint32_t>(VertexValueYPixelCode), perspective);
Require(result.barycentricEmulation.active && result.fragmentParameters.size() == 1 && result.fragmentParameters[0].custom && result.fragmentParameters[0].perVertex, "a rect-list pass-through input read at P10, P20 and P0 was not read per vertex");
CheckVertexValues(Emulation::RectList, true, component);
}
const auto first = Draw(device, Emulation::RectList, FirstVertexXYPixelCode, perspective);
Require(first.fragmentParameters.size() == 1 && first.fragmentParameters[0].custom && first.fragmentParameters[0].flat && !first.fragmentParameters[0].perVertex, "a rect-list pass-through input read only at P0 was not passed as a flat input");
const auto positions = ClipPositions(Emulation::RectList);
std::uint32_t checked = 0;
for (std::uint32_t y = 0; y < Height; ++y) {
for (std::uint32_t x = 0; x < Width; ++x) {
if (!BarycentricsUnsnapped(Emulation::RectList, x, y).inside) continue;
for (std::uint32_t channel = 0; channel < 4; ++channel) {
Require(Pixel(x, y, channel) == positions[0][channel & 1u], "rect-list pass-through P0: pixel (" + std::to_string(x) + ", " + std::to_string(y) + ") channel " + std::to_string(channel) + " is " + std::to_string(Pixel(x, y, channel)) + ", not the first vertex's " + std::to_string(positions[0][channel & 1u]));
}
++checked;
}
}
Require(checked > 200u, "rect-list pass-through P0: too few interior pixels were checked");
const bool native = device.Target().fragmentShaderBarycentricEnabled;
if (native) {
NativePerVertex = true;
const auto affine = Draw(device, Emulation::RectList, AffineVertexValuePixelCode, perspective, VK_CULL_MODE_NONE, false, VK_PROVOKING_VERTEX_MODE_FIRST_VERTEX_EXT, false, device.Target().fragmentBarycentricBuiltins);
NativePerVertex = false;
Require(!affine.barycentricEmulation.active && affine.fragmentParameters.size() == 1 && affine.fragmentParameters[0].custom && affine.fragmentParameters[0].perVertex, "a rect-list pass-through input read natively at P10, P20 and P0 was not read per vertex");
CheckInterpolated(Emulation::RectList);
}
PassThrough = false;
std::printf("rect-list pass-through inputs passed: the three vertices' raw values and the first vertex's value across the whole rectangle, %u pixels%s\n", checked, native ? ", and P0 + I(P1 - P0) + J(P2 - P0) from native per-vertex inputs" : "");
}
void CheckStrip(AgcDriver::VulkanDevice& device, Emulation emulation, const std::string& name, bool restart = false) {
const std::string strip = restart ? " triangle strip with primitive restart" : " triangle strip";
Draw(device, emulation, BarycentricPixelCode, PixelInputBit(PixelInput::LinearCenter), VK_CULL_MODE_NONE, false, VK_PROVOKING_VERTEX_MODE_FIRST_VERTEX_EXT, true, false, restart);
@@ -554,6 +596,7 @@ int main() {
if (tessellation) {
RunEmulation(*device, Emulation::Tessellation);
RunEmulation(*device, Emulation::RectList);
CheckRectListPassThrough(*device);
} else {
std::puts("tessellation and rect-list stages skipped, the device lacks tessellationShader");
}
@@ -27,9 +27,12 @@ alignas(256) constexpr std::array<std::uint32_t, 8> VertexCode{
0xe0382000, 0x80000005, 0xbf8c3f70, 0xf800020f, 0x03020100, 0xf80008cf, 0x03020100, 0xbf810000,
};
alignas(256) constexpr std::array<std::uint32_t, 18> PixelCode{
0xbefe0a7e, 0xbe80047e, 0xbefe0400, 0xc8080000, 0xc8090001, 0xc80c0100, 0xc80d0101, 0x101000ff, 0x358637bd, 0x06041102, 0x10040410, 0x10060611,
0xf0800f08, 0x00610402, 0xbf8c3f70, 0xf800180f, 0x07060504, 0xbf810000,
alignas(256) constexpr std::array<std::uint32_t, 35> PixelCode{
0xf4200480, 0xfa000000, 0xbf8cc07f, 0xbefe0a7e, 0xbe80047e, 0xbefe0400, 0xc8080000, 0xc8090001,
0xc80c0100, 0xc80d0101, 0x101000ff, 0x358637bd, 0x06041102, 0x10040410, 0x10060611, 0xf0800f08,
0x00610402, 0x101004f4, 0x101206f4, 0xf0800f08, 0x00610a08, 0xbf8c3f70, 0xd40d0014, 0x00002480,
0xd5010004, 0x00521504, 0xd5010005, 0x00521705, 0xd5010006, 0x00521906, 0xd5010007, 0x00521b07,
0xf800180f, 0x07060504, 0xbf810000,
};
std::vector<std::array<float, 4>> Triangles() {
@@ -72,7 +75,7 @@ void FillTexture() {
}
}
void Draw(AgcDriver::VulkanDevice& device, std::uint32_t wave, std::uint32_t level, bool emulate) {
void Draw(AgcDriver::VulkanDevice& device, std::uint32_t wave, std::uint32_t level, bool emulate, std::uint32_t flag) {
auto target = device.Target();
if (emulate) target.fragmentShaderBarycentricEnabled = false;
static const auto triangles = Triangles();
@@ -95,7 +98,10 @@ void Draw(AgcDriver::VulkanDevice& device, std::uint32_t wave, std::uint32_t lev
pixel.hasPerspectiveCenterVgpr = true;
pixel.targetOutputMode[0] = 9;
pixel.targetExportMapping.fill(0xe4u);
const std::array<std::uint32_t, 4> flagWords{flag, 0u, 0u, 0u};
const auto flagBuffer = BufferDescriptor(flagWords.data(), 1u);
std::vector<std::uint32_t> pixelUserData(18);
std::copy(flagBuffer.begin(), flagBuffer.end(), pixelUserData.begin());
const auto texture = TextureDescriptor();
std::copy(texture.begin(), texture.end(), pixelUserData.begin() + 4);
const std::array<std::uint32_t, 4> sampler{0u, 0xfffu << 12, 1u << 26, 0u};
@@ -132,14 +138,15 @@ void Draw(AgcDriver::VulkanDevice& device, std::uint32_t wave, std::uint32_t lev
state.blends = {state.blend};
device.Draw(state, {0, static_cast<std::uint32_t>(triangles.size()), 0, 1, 0, false}, shaders);
device.WaitIdle();
const auto expectedLevel = level + ((flag & 0x7fffffffu) >= 0x00800000u ? 1u : 0u);
std::uint32_t covered = 0;
std::uint32_t bad = 0;
for (std::uint32_t index = 0; index < Width * Height; ++index) {
if (Pixels[index * 4 + 3] == std::byte{0}) continue;
++covered;
bad += std::to_integer<unsigned>(Pixels[index * 4]) != 10u + 40u * level;
bad += std::to_integer<unsigned>(Pixels[index * 4]) != 10u + 40u * expectedLevel;
}
std::printf("emulate%u wave%u mip%u covered=%u incorrect=%u\n", emulate, wave, level, covered, bad);
std::printf("emulate%u wave%u mip%u flag%08x covered=%u incorrect=%u\n", emulate, wave, expectedLevel, flag, covered, bad);
Require(covered > 1000, "implicit derivative triangles covered too few pixels");
Require(bad == 0, "implicit derivatives selected the wrong mip at " + std::to_string(bad) + " pixels");
}
@@ -155,7 +162,8 @@ int main() {
return VulkanTestSkipped;
}
FillTexture();
for (const auto emulate : {false, true}) for (const auto wave : {64u, 32u}) for (const auto level : {0u, 1u, 2u}) Draw(*device, wave, level, emulate);
for (const auto emulate : {false, true}) for (const auto wave : {64u, 32u}) for (const auto level : {0u, 1u, 2u}) for (const auto flag : {0u, 0x3f800000u}) Draw(*device, wave, level, emulate, flag);
for (const auto flag : {0x80000000u, 0x00000001u, 0x7fc00001u}) Draw(*device, 64u, 1u, false, flag);
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
Loaded 100 of 947 files, more files were not shown because too many files have changed in this diff. Show more