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

Keeps this branch's FormatVersion at 93, above main's 90 (#6416).
This commit is contained in:
Yunus Shaikh committed 2026-11-18 16:43:47 -08:00
commit ef102a3a52
2301 files changed
+132514 -10434

No files matched your search

+1
View File
@@ -1,2 +1,3 @@
agc_driver_graphics address Stops on its check that guest heap memory lies below 1 << 40 (libSceAgcDriver/tests/Graphics.cpp, 'guest heap memory is beyond the 40-bit PS4 GPU address space'), because the ASan build maps the guest arena above 1 TiB; tracked in #16813.
agc_driver_graphics_maps_fallback address Stops on its check that guest heap memory lies below 1 << 40 (libSceAgcDriver/tests/Graphics.cpp, 'guest heap memory is beyond the 40-bit PS4 GPU address space'), because the ASan build maps the guest arena above 1 TiB; tracked in #16813.
agc_graphics_profile_draw address Stops on its check that guest heap memory lies below 1 << 40 (libSceAgcDriver/tests/Graphics.cpp, 'guest heap memory is beyond the 40-bit PS4 GPU address space'), because the ASan build maps the guest arena above 1 TiB; tracked in #16813.
+44 -1
View File
@@ -526,7 +526,50 @@ jobs:
- name: Remove git locks left by an interrupted checkout
shell: bash
run: if [ -d .git ]; then find .git -name '*.lock' -type f -print -delete; fi
- uses: actions/checkout@v7
- id: checkout
uses: actions/checkout@v7
continue-on-error: true
with:
ref: ${{ needs.eligibility.outputs.sha }}
persist-credentials: false
submodules: recursive
- id: broken
name: Remove the submodules a failed checkout left without a current revision
if: ${{ steps.checkout.outcome == 'failure' }}
continue-on-error: true
shell: bash
run: |
broken() {
git -C "$1" ls-tree -r HEAD | while IFS=$'\t' read -r entry path; do
case $entry in "160000 commit "*) ;; *) continue ;; esac
[ -e "$1/$path/.git" ] || continue
if git -C "$1/$path" rev-parse -q --verify 'HEAD^{commit}' > /dev/null 2>&1; then broken "$1/$path"; else echo "$1/$path"; fi
done
}
ws=$(realpath -m "${GITHUB_WORKSPACE:?}")
remove=()
while IFS= read -r path; do
gitdir=$(sed -n 's/^gitdir: //p' "$path/.git" 2> /dev/null || true)
case $gitdir in /*) gitdir=$(realpath -m "$gitdir") ;; ?*) gitdir=$(realpath -m "$path/$gitdir") ;; esac
case $(realpath -m "$path")/ in "$ws"/?*) ;; *) echo "outside the workspace: $path"; remove=(); break ;; esac
[ -z "$gitdir" ] || case $gitdir/ in "$ws"/.git/modules/?*) ;; *) echo "not a module directory of the workspace: $gitdir"; remove=(); break ;; esac
remove+=("$path" "$gitdir")
done < <(broken "$ws")
found=false
for ((i = 0; i < ${#remove[@]}; i += 2)); do
[ -z "${remove[i+1]}" ] || rm -rf "${remove[i+1]}"
rm -rf "${remove[i]}" && mkdir -p "${remove[i]}"
echo "removed ${remove[i]}${remove[i+1]:+ and ${remove[i+1]}}"
found=true
done
echo "found=$found" >> "$GITHUB_OUTPUT"
- name: Empty the workspace after a failed checkout
if: ${{ steps.checkout.outcome == 'failure' && steps.broken.outputs.found != 'true' }}
shell: bash
run: find "${GITHUB_WORKSPACE:?}" -mindepth 1 -maxdepth 1 -exec rm -rf {} +
- name: Check out again after a failed checkout
if: ${{ steps.checkout.outcome == 'failure' }}
uses: actions/checkout@v7
with:
ref: ${{ needs.eligibility.outputs.sha }}
persist-credentials: false
+98 -4
View File
@@ -137,6 +137,55 @@ if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fmacro-prefix-map=${CMAKE_SOURCE_DIR}/=>)
endif()
function(anyps5_zero_init_padding_bits directory)
file(RELATIVE_PATH relativeDirectory "${CMAKE_SOURCE_DIR}" "${directory}")
if(relativeDirectory MATCHES "^3rdparty(/|$)")
return()
endif()
get_property(targets DIRECTORY "${directory}" PROPERTY BUILDSYSTEM_TARGETS)
foreach(target IN LISTS targets)
get_target_property(sourceDirectory ${target} SOURCE_DIR)
get_target_property(sources ${target} SOURCES)
foreach(source IN LISTS sources)
if(source MATCHES "^\\$<" OR NOT source MATCHES "\\.(c|cc|cpp|cxx)$")
continue()
endif()
cmake_path(ABSOLUTE_PATH source BASE_DIRECTORY "${sourceDirectory}" NORMALIZE)
file(RELATIVE_PATH relativeSource "${CMAKE_SOURCE_DIR}" "${source}")
file(RELATIVE_PATH relativeBinarySource "${CMAKE_BINARY_DIR}" "${source}")
if(relativeSource MATCHES "^(3rdparty/|\\.\\./)" OR NOT relativeBinarySource MATCHES "^\\.\\./")
continue()
endif()
if(source MATCHES "\\.c$")
set(language C)
else()
set(language CXX)
endif()
if(ANYPS5_${language}_ZERO_INIT_PADDING_BITS)
set_property(SOURCE "${source}" TARGET_DIRECTORY ${target} APPEND PROPERTY COMPILE_OPTIONS -fzero-init-padding-bits=all)
endif()
endforeach()
endforeach()
get_property(children DIRECTORY "${directory}" PROPERTY SUBDIRECTORIES)
foreach(child IN LISTS children)
anyps5_zero_init_padding_bits("${child}")
endforeach()
endfunction()
function(anyps5_add_zero_init_padding_bits)
if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
include(CheckCCompilerFlag)
check_c_compiler_flag(-fzero-init-padding-bits=all ANYPS5_C_ZERO_INIT_PADDING_BITS)
endif()
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-fzero-init-padding-bits=all ANYPS5_CXX_ZERO_INIT_PADDING_BITS)
endif()
if(ANYPS5_C_ZERO_INIT_PADDING_BITS OR ANYPS5_CXX_ZERO_INIT_PADDING_BITS)
anyps5_zero_init_padding_bits("${CMAKE_CURRENT_SOURCE_DIR}")
endif()
endfunction()
cmake_language(DEFER CALL anyps5_add_zero_init_padding_bits)
include(CheckCXXSourceCompiles)
function(anyps5_check_cxx_links_standard_library)
set(CMAKE_TRY_COMPILE_TARGET_TYPE EXECUTABLE)
@@ -267,6 +316,10 @@ if(BUILD_TESTING)
target_include_directories(pad_recording_tests PRIVATE core/libs)
add_test(NAME pad_recording COMMAND pad_recording_tests)
set_tests_properties(pad_recording PROPERTIES TIMEOUT 20)
add_test_executable(pad_input_script_tests core/libs/prx/libScePad/tests/InputScript.cpp)
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)
if(Python3_Interpreter_FOUND)
get_property(windows_tooling_before DIRECTORY PROPERTY TESTS)
add_test(NAME mingw_host_only_test_targets COMMAND ${Python3_EXECUTABLE}
@@ -324,6 +377,7 @@ if(BUILD_TESTING)
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_prs.py)
add_test(NAME shader_scan COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_shader_scan.py)
add_test(NAME isa_profiles COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_isa_profiles.py)
add_test(NAME progress_report_inputs COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_report_inputs.py)
add_test(NAME tools_compdb_inventory COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_compile_database_inventory.py)
@@ -384,6 +438,9 @@ if(BUILD_TESTING)
endif()
endforeach()
endif()
add_test(NAME build_mingw_host_only_tests_script COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_build_mingw_host_only_tests.py)
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)
add_test(NAME unwrap_self COMMAND ${Python3_EXECUTABLE}
@@ -466,6 +523,9 @@ if(BUILD_TESTING)
add_test(NAME conventions_doc_links COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_doc_links.py)
set_tests_properties(conventions_doc_links PROPERTIES TIMEOUT 20)
add_test(NAME conventions_doc_anchors COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_doc_anchors.py)
set_tests_properties(conventions_doc_anchors PROPERTIES TIMEOUT 20)
add_test(NAME conventions_unknown_nids COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_unknown_nids.py)
set_tests_properties(conventions_unknown_nids PROPERTIES TIMEOUT 20)
@@ -507,6 +567,9 @@ if(BUILD_TESTING)
add_test(NAME rebase_verify COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_rebase_verify.py)
set_tests_properties(rebase_verify PROPERTIES TIMEOUT 60)
add_test(NAME check_test_registration_script COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_test_registration.py)
set_tests_properties(check_test_registration_script PROPERTIES TIMEOUT 60)
add_test(NAME check_skips COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py
SkipJsonTests RequiredTestsTests SkipReportTests NotRunTests)
@@ -850,16 +913,41 @@ if(BUILD_TESTING)
add_test(NAME title_run_paths COMMAND ${Python3_EXECUTABLE} -u
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_title_run_paths.py -v)
set_tests_properties(title_run_paths PROPERTIES TIMEOUT 30)
set_tests_properties(title_run_paths PROPERTIES TIMEOUT 300)
add_test(NAME title_run_identity COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_title_run_identity.py)
set_tests_properties(title_run_identity PROPERTIES TIMEOUT 30)
add_test(NAME performance_compare COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_performance_compare.py)
set_tests_properties(performance_compare PROPERTIES TIMEOUT 20)
add_test(NAME presentmon_compare COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_presentmon_compare.py)
set_tests_properties(presentmon_compare PROPERTIES TIMEOUT 30)
add_test(NAME benchmark_compare COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_benchmark_compare.py)
set_tests_properties(benchmark_compare PROPERTIES TIMEOUT 30)
add_test(NAME frame_replay_report COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_frame_replay_report.py)
set_tests_properties(frame_replay_report PROPERTIES TIMEOUT 30)
add_test(NAME frame_replay_compare COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_frame_replay_compare.py)
set_tests_properties(frame_replay_compare PROPERTIES TIMEOUT 30)
add_test(NAME title_run COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_title_run.py)
set_tests_properties(title_run PROPERTIES TIMEOUT 60)
foreach(performance_capture_class WindowParsing CaptureEnvironment CompletedCapture InvalidSummaries InvalidTraces BoundsAndLinks LossEvidence)
add_test(NAME performance_capture_${performance_capture_class} COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_performance_capture.py ${performance_capture_class})
set_tests_properties(performance_capture_${performance_capture_class} PROPERTIES TIMEOUT 30)
endforeach()
add_test(NAME performance_console COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_performance_console.py)
set_tests_properties(performance_console PROPERTIES TIMEOUT 30)
foreach(performance_runner_class PerformancePhaseTests PerformanceRunTests PerformanceArgumentTests PerformanceMainTests)
add_test(NAME performance_runner_${performance_runner_class} COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_title_run_performance.py ${performance_runner_class})
set_tests_properties(performance_runner_${performance_runner_class} PROPERTIES TIMEOUT 30)
endforeach()
add_test(NAME relinker_fuzz_seeds COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_relinker_fuzz_seeds.py)
set_tests_properties(relinker_fuzz_seeds PROPERTIES TIMEOUT 20)
@@ -910,11 +998,16 @@ set(SDL_HAPTIC OFF CACHE BOOL "" FORCE)
set(SDL_HIDAPI ON CACHE BOOL "" FORCE)
set(SDL_SENSOR OFF CACHE BOOL "" FORCE)
set(SDL_STATIC_PIC ON CACHE BOOL "" FORCE)
if(NOT ANYPS5_USE_SYSTEM_DEPS)
set(ANYPS5_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}")
function(anyps5_add_bundled_sdl2)
set(CMAKE_EXE_LINKER_FLAGS "")
set(HAVE_DLOPEN OFF)
set(HAVE_CLOCK_GETTIME OFF)
add_subdirectory(3rdparty/SDL2)
set(CMAKE_EXE_LINKER_FLAGS "${ANYPS5_EXE_LINKER_FLAGS}")
endfunction()
if(NOT ANYPS5_USE_SYSTEM_DEPS)
anyps5_add_bundled_sdl2()
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
get_directory_property(ANYPS5_SDL_X11_XRANDR DIRECTORY 3rdparty/SDL2 DEFINITION HAVE_X11_XRANDR)
if(NOT ANYPS5_SDL_X11_XRANDR)
@@ -950,6 +1043,7 @@ set(FT_DISABLE_PNG ON CACHE BOOL "" FORCE)
set(FT_DISABLE_HARFBUZZ ON CACHE BOOL "" FORCE)
set(FT_DISABLE_BROTLI ON CACHE BOOL "" FORCE)
set(FT_DISABLE_HVF ON CACHE BOOL "" FORCE)
set(FT_ENABLE_ERROR_STRINGS ON CACHE BOOL "" FORCE)
set(SKIP_INSTALL_ALL ON CACHE BOOL "" FORCE)
if(NOT ANYPS5_USE_SYSTEM_DEPS)
add_subdirectory(3rdparty/freetype EXCLUDE_FROM_ALL)
+2
View File
@@ -82,6 +82,8 @@ The [pull request template](.github/pull_request_template.md) is the checklist f
Text in the repository is dry, strict and concise. Record known gaps, unknown NIDs and signatures in [technical debt](docs/dev/TechnicalDebt.md) instead of new files. An entry states the gap first (what differs from the console, what is unverified, what throws) and describes the implemented behaviour only as far as the gap needs it. A pull request that closes a gap removes its entry, or cuts it to what is still open, instead of rewriting it to describe the corrected behaviour. An entry goes in `docs/dev/debt/<name>.md`, named after the first `core/` path it links (`<name>` for `core/libs/prx/<name>/...`, otherwise for `core/<name>/...`), under the same `###` sections as the index; entries that link neither stay in the index. A pull request whose `TechnicalDebt.md` change conflicts after the split rebases and runs `python3 tools/debt_split.py resolve` during the stopped rebase, which moves its added, edited and removed entries to their files; `python3 tools/debt_split.py split` moves entries left in the index.
A link to a Markdown file with a `#fragment` must name a heading of that file, as GitHub writes its anchor: the text of the heading in lowercase, with punctuation removed and spaces turned into hyphens. The check reports a fragment that matches no heading (`doc-anchor`) in the lines a pull request adds; it does not check fragments that were already there.
## Maintainer scripts
- `tools/rebase_verify.py <old> <new> [--onto BRANCH] [--repo REPO]` checks that a rebased branch kept its added and deleted lines, file modes, authors and commits. `--onto` names the branch the new commits sit on; by default it is `upstream/main`, then `origin/main`.
+21 -1
View File
@@ -1,5 +1,25 @@
set(ICU_SOURCE_DIR ${CMAKE_SOURCE_DIR}/3rdparty/icu/icu4c/source)
set(ICU_NORMALIZATION_DIR ${CMAKE_CURRENT_BINARY_DIR}/icu-normalization)
set(ICU_NORMALIZATION_SOURCE ${ICU_NORMALIZATION_DIR}/CommonData.cpp)
file(MAKE_DIRECTORY ${ICU_NORMALIZATION_DIR})
set(ICU_NORMALIZATION_DECLARATIONS "")
set(ICU_NORMALIZATION_ENTRIES "")
set(ICU_NORMALIZATION_FILES nfkc.nrm nfkc_cf.nrm uemoji.icu ulayout.icu)
list(LENGTH ICU_NORMALIZATION_FILES ICU_NORMALIZATION_COUNT)
foreach(ICU_NORMALIZATION_FILE IN LISTS ICU_NORMALIZATION_FILES)
string(MAKE_C_IDENTIFIER ${ICU_NORMALIZATION_FILE} ICU_NORMALIZATION_NAME)
set(ICU_NORMALIZATION_INPUT ${ICU_SOURCE_DIR}/data/in/${ICU_NORMALIZATION_FILE})
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${ICU_NORMALIZATION_INPUT})
file(READ ${ICU_NORMALIZATION_INPUT} ICU_NORMALIZATION_HEX HEX)
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," ICU_NORMALIZATION_BYTES "${ICU_NORMALIZATION_HEX}")
string(APPEND ICU_NORMALIZATION_DECLARATIONS
"alignas(16) constexpr unsigned char ${ICU_NORMALIZATION_NAME}[]{${ICU_NORMALIZATION_BYTES}};\n")
string(APPEND ICU_NORMALIZATION_ENTRIES
" {U_ICUDATA_NAME \"/${ICU_NORMALIZATION_FILE}\", ${ICU_NORMALIZATION_NAME}},\n")
endforeach()
configure_file(${CMAKE_CURRENT_LIST_DIR}/IcuNormalizationData.cpp.in ${ICU_NORMALIZATION_SOURCE} @ONLY)
add_library(icu_common STATIC EXCLUDE_FROM_ALL
${ICU_SOURCE_DIR}/common/appendable.cpp
${ICU_SOURCE_DIR}/common/bmpset.cpp
@@ -90,7 +110,7 @@ add_library(icu_common STATIC EXCLUDE_FROM_ALL
${ICU_SOURCE_DIR}/common/utrie_swap.cpp
${ICU_SOURCE_DIR}/common/uvector.cpp
${ICU_SOURCE_DIR}/common/uvectr32.cpp
${ICU_SOURCE_DIR}/stubdata/stubdata.cpp)
${ICU_NORMALIZATION_SOURCE})
target_sources(icu_common PRIVATE
${ICU_SOURCE_DIR}/common/fixedstring.cpp
${ICU_SOURCE_DIR}/common/localebuilder.cpp
+40
View File
@@ -0,0 +1,40 @@
#include "unicode/udata.h"
#include "unicode/utypes.h"
#include <cstddef>
#include <cstdint>
namespace {
@ICU_NORMALIZATION_DECLARATIONS@
struct Entry {
const char* name;
const void* data;
};
struct CommonData {
std::uint16_t headerSize;
std::uint8_t magic1;
std::uint8_t magic2;
UDataInfo info;
char padding[8];
std::uint32_t count;
std::uint32_t reserved;
Entry entries[@ICU_NORMALIZATION_COUNT@];
};
static_assert(offsetof(CommonData, count) == 32);
static_assert(offsetof(CommonData, entries) == 40);
static_assert(!U_IS_BIG_ENDIAN);
}
extern "C" U_EXPORT alignas(16) const CommonData U_ICUDATA_ENTRY_POINT = {
32, 0xda, 0x27,
{sizeof(UDataInfo), 0, U_IS_BIG_ENDIAN, U_CHARSET_FAMILY, sizeof(char16_t), 0,
{0x54, 0x6f, 0x43, 0x50}, {1, 0, 0, 0}, {}},
{}, @ICU_NORMALIZATION_COUNT@, 0,
{
@ICU_NORMALIZATION_ENTRIES@
}
};
+3
View File
@@ -62,6 +62,9 @@ function(add_jpeg_decoder target runtimeTarget)
IMPORTED_LOCATION "${jpeg_turbo_library}"
INTERFACE_INCLUDE_DIRECTORIES "${PROJECT_SOURCE_DIR}/3rdparty/libjpeg-turbo/src;${jpeg_turbo_prefix}/include"
)
if(MINGW OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_link_options(jpeg_turbo INTERFACE "LINKER:--exclude-libs,$<TARGET_FILE_NAME:jpeg_turbo>")
endif()
add_dependencies(jpeg_turbo jpeg_turbo_external)
endif()
+2
View File
@@ -1,3 +1,5 @@
include(${CMAKE_SOURCE_DIR}/cmake/Zlib.cmake)
function(add_png_decoder target runtimeTarget)
if(NOT TARGET "${runtimeTarget}")
message(FATAL_ERROR "PNG decoder requires an existing runtime target: ${runtimeTarget}")
+42 -1
View File
@@ -265,6 +265,19 @@ if(BUILD_TESTING)
set_tests_properties(guest_webrtc_vad PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libwebrtc>")
endif()
add_test_executable(guest_wtf_data_log_tests ${CMAKE_CURRENT_SOURCE_DIR}/tests/GuestWtfDataLog.cpp)
target_include_directories(guest_wtf_data_log_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_wtf_data_log_tests PRIVATE libSceNKWebKit libSceJsc libc)
configure_windows_unwind(guest_wtf_data_log_tests)
add_test(NAME guest_wtf_data_log COMMAND guest_wtf_data_log_tests)
add_test(NAME guest_wtf_data_log_install_first COMMAND guest_wtf_data_log_tests install-first)
add_test(NAME guest_wtf_data_log_install_null COMMAND guest_wtf_data_log_tests install-null)
set_tests_properties(guest_wtf_data_log guest_wtf_data_log_install_first guest_wtf_data_log_install_null PROPERTIES TIMEOUT 20)
if(WIN32)
set_tests_properties(guest_wtf_data_log guest_wtf_data_log_install_first guest_wtf_data_log_install_null PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceNKWebKit>;PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceJsc>")
endif()
endif()
if(BUILD_TESTING)
@@ -510,6 +523,14 @@ if(BUILD_TESTING)
add_test(NAME pe_import_first COMMAND pe_import_first_tests)
set_tests_properties(pe_import_first PROPERTIES TIMEOUT 10)
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
add_test_executable(patched_self_imports_tests ${CMAKE_CURRENT_SOURCE_DIR}/tests/PatchedSelfImports.cpp)
target_compile_features(patched_self_imports_tests PRIVATE cxx_std_20)
add_dependencies(patched_self_imports_tests libs)
add_test(NAME patched_self_imports COMMAND patched_self_imports_tests ${PATCHED_DIR})
set_tests_properties(patched_self_imports PROPERTIES TIMEOUT 30)
endif()
find_package(Python3 QUIET COMPONENTS Interpreter)
if(Python3_Interpreter_FOUND)
set(public_header_compiler_args)
@@ -647,6 +668,16 @@ if(BUILD_TESTING)
configure_windows_unwind(guest_kernel_sys_thread_defaults_tests)
add_test(NAME guest_kernel_sys_thread_defaults COMMAND guest_kernel_sys_thread_defaults_tests)
set_tests_properties(guest_kernel_sys_thread_defaults PROPERTIES TIMEOUT 20)
add_test_executable(guest_kernel_sys_kld_tests tests/GuestKernelSysKld.cpp)
target_include_directories(guest_kernel_sys_kld_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_kernel_sys_kld_tests PRIVATE libkernel_sys libkernel libc)
configure_windows_unwind(guest_kernel_sys_kld_tests)
add_test(NAME guest_kernel_sys_kld COMMAND guest_kernel_sys_kld_tests)
set_tests_properties(guest_kernel_sys_kld PROPERTIES TIMEOUT 20)
if(WIN32)
set_tests_properties(guest_kernel_sys_kld PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
endif()
add_test_executable(guest_kernel_sys_barrier_tests tests/GuestKernelSysBarrier.cpp)
target_include_directories(guest_kernel_sys_barrier_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_kernel_sys_barrier_tests PRIVATE libkernel_sys libkernel libc)
@@ -804,7 +835,7 @@ if(BUILD_TESTING)
target_include_directories(guest_kernel_sys_pthread_np_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_kernel_sys_pthread_np_tests PRIVATE libkernel_sys libkernel libc)
configure_windows_unwind(guest_kernel_sys_pthread_np_tests)
foreach(pthreadNpMode IN ITEMS rwlockattr kind attr)
foreach(pthreadNpMode IN ITEMS rwlockattr kind stack attr)
add_test(NAME guest_kernel_sys_pthread_np_${pthreadNpMode} COMMAND guest_kernel_sys_pthread_np_tests ${pthreadNpMode})
set_tests_properties(guest_kernel_sys_pthread_np_${pthreadNpMode} PROPERTIES TIMEOUT 20)
if(WIN32)
@@ -1359,6 +1390,16 @@ if(BUILD_TESTING)
ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSaveData.native>")
endif()
add_test_executable(guest_savedata_required_blocks_tests tests/GuestSaveDataRequiredBlocks.cpp)
target_include_directories(guest_savedata_required_blocks_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_savedata_required_blocks_tests PRIVATE libSceSaveData libc)
configure_windows_unwind(guest_savedata_required_blocks_tests)
add_test(NAME guest_savedata_required_blocks COMMAND guest_savedata_required_blocks_tests)
if(WIN32)
set_tests_properties(guest_savedata_required_blocks PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>;PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSaveData>")
endif()
add_test_executable(guest_kernel_sys_mqueue_tests tests/GuestKernelSysMqueue.cpp)
target_include_directories(guest_kernel_sys_mqueue_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_kernel_sys_mqueue_tests PRIVATE libkernel_sys libkernel libc)
+2
View File
@@ -1461,6 +1461,7 @@ struct HttpNBEvent { std::uint8_t opaque[64]; };
struct SceHttpUriElement {
int opaque = 0;
std::uint32_t pad0 = 0;
char* scheme = nullptr;
char* username = nullptr;
char* password = nullptr;
@@ -1470,6 +1471,7 @@ struct SceHttpUriElement {
char* fragment = nullptr;
std::uint16_t port = 0;
std::uint8_t reserved[10]{};
std::uint32_t pad1 = 0;
};
struct Http2AsyncResult {
+7
View File
@@ -381,9 +381,11 @@ void ElfNidPatcher::PatchNids(std::vector<std::uint8_t>& elf, const std::string&
std::size_t dynSymOffset = 0u, dynSymSize = 0u;
std::size_t gnuHashOffset = 0u, gnuHashSize = 0u;
std::uint32_t gnuHashLink = 0u;
std::size_t sysvHashOffset = 0u, sysvHashSize = 0u;
std::uint32_t sysvHashLink = 0u;
std::size_t versymOffset = 0u, versymSize = 0u;
std::uint32_t versymLink = 0u;
bool hasDynamic = false;
std::uint32_t dynSymSectionIndex = 0u;
std::uint32_t dynSymSectionLink = 0u;
@@ -407,6 +409,7 @@ void ElfNidPatcher::PatchNids(std::vector<std::uint8_t>& elf, const std::string&
if (shdr.sh_type == kShtGnuHash) {
gnuHashOffset = static_cast<std::size_t>(shdr.sh_offset);
gnuHashSize = static_cast<std::size_t>(shdr.sh_size);
gnuHashLink = shdr.sh_link;
}
if (shdr.sh_type == kShtHash) {
sysvHashOffset = static_cast<std::size_t>(shdr.sh_offset);
@@ -416,6 +419,7 @@ void ElfNidPatcher::PatchNids(std::vector<std::uint8_t>& elf, const std::string&
if (shdr.sh_type == kShtGnuVersym) {
versymOffset = static_cast<std::size_t>(shdr.sh_offset);
versymSize = static_cast<std::size_t>(shdr.sh_size);
versymLink = shdr.sh_link;
}
if (shdr.sh_type == kShtGnuVerdef)
throw std::runtime_error("unsupported .gnu.version_d section: symbol version definitions cannot be preserved");
@@ -439,6 +443,8 @@ void ElfNidPatcher::PatchNids(std::vector<std::uint8_t>& elf, const std::string&
const std::size_t symCount = dynSymSize / sizeof(Elf64_Sym);
if (symCount == 0u) throw std::runtime_error(".dynsym is empty");
if (versymOffset != 0u) {
if (versymLink != dynSymSectionIndex)
throw std::runtime_error("invalid ELF version symbol table link");
RequireElfRange(elf, versymOffset, versymSize, "versym");
if (versymSize < symCount * sizeof(std::uint16_t))
throw std::runtime_error("invalid ELF version symbol table size");
@@ -448,6 +454,7 @@ void ElfNidPatcher::PatchNids(std::vector<std::uint8_t>& elf, const std::string&
ValidateSysvHash(elf, sysvHashOffset, sysvHashSize, symCount);
}
if (gnuHashOffset != 0u) {
if (gnuHashLink != dynSymSectionIndex) throw std::runtime_error("invalid gnu.hash symbol table link");
ValidateGnuHash(elf, gnuHashOffset, gnuHashSize, symCount);
gnuHashSymOffset = Read<std::uint32_t>(elf, gnuHashOffset + 4u);
}
+2
View File
@@ -184,6 +184,8 @@ std::unordered_set<std::string> ReadExportList(const std::string& path) {
const auto end = text.find('\n', start);
if (end == start) throw std::runtime_error("empty name in export list: " + path);
auto name = text.substr(start, end - start);
if (!name.empty() && name.back() == '\r') name.pop_back();
if (name.empty()) throw std::runtime_error("empty name in export list: " + path);
if (!result.insert(name).second) throw std::runtime_error("duplicate name in export list: " + name);
start = end + 1;
}
+1
View File
@@ -21,6 +21,7 @@ bool IsMangledSceImport(const std::string& name) {
if (!name.starts_with("_ZN")) return false;
std::size_t index = 3u;
while (index < name.size() && (name[index] == 'r' || name[index] == 'V' || name[index] == 'K')) ++index;
if (index < name.size() && (name[index] == 'R' || name[index] == 'O')) ++index;
return name.size() >= index + 4u && name[index] == '3' &&
std::tolower(static_cast<unsigned char>(name[index + 1u])) == 's' &&
std::tolower(static_cast<unsigned char>(name[index + 2u])) == 'c' &&
@@ -1,6 +1,8 @@
import base64
import hashlib
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
@@ -55,6 +57,18 @@ class ElfDuplicateTests(unittest.TestCase):
self.assertIn(b"duplicate patched export name: sceAlphaComputeLength", result.stderr)
self.assertEqual(after, before)
def test_crlf_preserve_export_list_keeps_named_export(self):
with tempfile.TemporaryDirectory(prefix="anyps5-nid-crlf-") as directory:
path = Path(directory) / "exports.so"
listing = Path(directory) / "preserve.txt"
path.write_bytes(image(["sceAlphaComputeLength", "sceBetaCopyString"]))
listing.write_bytes(b"sceAlphaComputeLength\r\n")
result = subprocess.run([PATCHER, "libTest", "--preserve-export-list", str(listing), str(path)], capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
patched = [entry[0] for entry in read_dynsym(path.read_bytes()) if entry[1] == 9]
self.assertIn("sceAlphaComputeLength", patched)
self.assertIn(nid("sceBetaCopyString"), patched)
def test_distinct_exports_are_still_patched(self):
names = ["sceAlphaComputeLength_nid_disambig1", "sceBetaCopyString_nid_postfix", "sceGammaKeep_nid_no_patch_cut"]
result, after = patch(PATCHER, image(names), "distinct.so")
+5
View File
@@ -59,6 +59,11 @@ class GnuHashTests(unittest.TestCase):
struct.pack_into("<Q", image, SHOFF + 3 * 64 + 32, size)
self.reject(image)
def test_symbol_table_link_is_checked(self):
image = self.image()
struct.pack_into("<I", image, SHOFF + 3 * 64 + 40, 2)
self.reject(image)
def reject(self, image):
result, after = patch(PATCHER, bytes(image), "geometry.so")
self.assertEqual(result.returncode, 2, (result.returncode, result.stderr))
+1 -1
View File
@@ -6,7 +6,7 @@ import unittest
import test_symbol_versions as symbols_module
from test_symbol_versions import build_image, patch, read_dynsym, DEFINITIONS, SHN_UNDEF, STT_FUNC, PATCHER
SCE_IMPORTS = ["_ZN3sce4Json5Value3setEl", "_ZNK3sce4Json5Value3getEv", "_ZN3Sce4Json6StringC1EPKc"]
SCE_IMPORTS = ["_ZN3sce4Json5Value3setEl", "_ZNK3sce4Json5Value3getEv", "_ZN3Sce4Json6StringC1EPKc", "_ZNR3sce3Foo6lvalueEv", "_ZNO3sce3Foo6rvalueEv", "_ZNKR3sce3Foo11constLvalueEv", "_ZNKO3sce3Foo11constRvalueEv"]
OTHER_IMPORTS = ["_ZN4demo3FooEv", "_ZN5scene3BarEv", "_ZNSt6vectorIiE4sizeEv", "_ZN3scx3BazEv", "_Z3sce"]
PLAIN_IMPORT = "sceKernelPlainImportName"
+19 -1
View File
@@ -205,6 +205,23 @@ def sysv_only_image(entries):
return image
def test_version_table_must_link_to_dynsym(patcher):
entries = symbols(False)
image = sysv_only_image(entries)
for index in range(len(entries)):
struct.pack_into("<H", image, VERSYM_OFFSET + index * 2, 2)
struct.pack_into("<IIQQQQIIQQ", image, SHOFF + 4 * 64, 0, SHT_GNU_VERSYM, 2, 0,
VERSYM_OFFSET, len(entries) * 2, 2, 0, 2, 2)
struct.pack_into("<H", image, 0x3c, 5)
image = bytes(image)
result, on_disk = patch(patcher, image, "invalid-version-symbol-link.so")
assert result.returncode == 2, (result.returncode, result.stderr)
message = result.stderr.decode("utf-8", errors="replace")
assert "version symbol table link" in message, message
assert on_disk == image, "the rejected library was written back modified"
def test_version_table_smaller_than_symbols_is_rejected(patcher):
image = sysv_only_image(symbols(False))
for index in range(len(symbols(False))):
@@ -217,7 +234,7 @@ def test_version_table_smaller_than_symbols_is_rejected(patcher):
result, on_disk = patch(patcher, image, SONAME)
assert result.returncode != 0, result.stdout
message = result.stderr.decode("utf-8", errors="replace")
assert "version symbol table" in message, message
assert "version symbol table size" in message, message
assert on_disk == image, "the rejected library was written back modified"
@@ -269,6 +286,7 @@ def main():
sys.exit(0)
test_versioned_library_is_rejected(patcher)
test_unversioned_library_is_still_patched(patcher)
test_version_table_must_link_to_dynsym(patcher)
test_version_table_smaller_than_symbols_is_rejected(patcher)
test_two_dynsym_sections_are_rejected(patcher)
print("NID patcher symbol version tests passed")
+26 -52
View File
@@ -5,134 +5,108 @@
extern "C" {
int APS5_VABI PartyUnknown_0iEKNAvT600_nid_no_patch() {
int APS5_VABI PartySetMemoryCallbacks() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("0iEKNAvT600", PartyUnknown_0iEKNAvT600_nid_no_patch);
int APS5_VABI PartyUnknown_2cELEBPdYQ0_nid_no_patch() {
int APS5_VABI PartyFinishProcessingStateChanges() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("2cELEBPdYQ0", PartyUnknown_2cELEBPdYQ0_nid_no_patch);
int APS5_VABI PartyUnknown_5xYxiOtOccA_nid_no_patch() {
int APS5_VABI PartyNetworkGetNetworkDescriptor() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("5xYxiOtOccA", PartyUnknown_5xYxiOtOccA_nid_no_patch);
int APS5_VABI PartyUnknown_6W_plus_shIH315Q_nid_no_patch() {
int APS5_VABI PartyCleanup() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("6W+shIH315Q", PartyUnknown_6W_plus_shIH315Q_nid_no_patch);
int APS5_VABI PartyUnknown_7ilObq815O4_nid_no_patch() {
int APS5_VABI PartyCreateLocalUser() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("7ilObq815O4", PartyUnknown_7ilObq815O4_nid_no_patch);
int APS5_VABI PartyUnknown_7iq7Hfs8HBk_nid_no_patch() {
int APS5_VABI PartySerializeNetworkDescriptor() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("7iq7Hfs8HBk", PartyUnknown_7iq7Hfs8HBk_nid_no_patch);
int APS5_VABI PartyUnknown_7kwSdZNDyP0_nid_no_patch() {
int APS5_VABI PartyGetNetworks() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("7kwSdZNDyP0", PartyUnknown_7kwSdZNDyP0_nid_no_patch);
int APS5_VABI PartyUnknown_AC1FtjqMCL0_nid_no_patch() {
int APS5_VABI PartyNetworkCreateEndpoint() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("AC1FtjqMCL0", PartyUnknown_AC1FtjqMCL0_nid_no_patch);
int APS5_VABI PartyUnknown_AJ3I035AjIM_nid_no_patch() {
int APS5_VABI PartyLocalUserGetEntityId() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("AJ3I035AjIM", PartyUnknown_AJ3I035AjIM_nid_no_patch);
int APS5_VABI PartyUnknown_AMJZhpC_plus_siY_nid_no_patch() {
int APS5_VABI PartyDeserializeNetworkDescriptor() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("AMJZhpC+siY", PartyUnknown_AMJZhpC_plus_siY_nid_no_patch);
int APS5_VABI PartyUnknown_aq13EdrGdVw_nid_no_patch() {
int APS5_VABI PartyEndpointGetDevice() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("aq13EdrGdVw", PartyUnknown_aq13EdrGdVw_nid_no_patch);
int APS5_VABI PartyUnknown_BOW_minus_t_minus_9qJNI_nid_no_patch() {
int APS5_VABI PartyEndpointSetCustomContext() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("BOW-t-9qJNI", PartyUnknown_BOW_minus_t_minus_9qJNI_nid_no_patch);
int APS5_VABI PartyUnknown_E9XkHowt_plus_dY_nid_no_patch() {
int APS5_VABI PartyStartProcessingStateChanges() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("E9XkHowt+dY", PartyUnknown_E9XkHowt_plus_dY_nid_no_patch);
int APS5_VABI PartyUnknown_f3d6tchKw94_nid_no_patch() {
int APS5_VABI PartyNetworkGetDeviceConnectionType() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("f3d6tchKw94", PartyUnknown_f3d6tchKw94_nid_no_patch);
int APS5_VABI PartyUnknown_GADjreszOgM_nid_no_patch() {
int APS5_VABI PartyNetworkAuthenticateLocalUser() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("GADjreszOgM", PartyUnknown_GADjreszOgM_nid_no_patch);
int APS5_VABI PartyUnknown_Giyg2xGrXDU_nid_no_patch() {
int APS5_VABI PartyInitialize() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("Giyg2xGrXDU", PartyUnknown_Giyg2xGrXDU_nid_no_patch);
int APS5_VABI PartyUnknown_JrVwjbBmqLQ_nid_no_patch() {
int APS5_VABI PartyEndpointIsLocal() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("JrVwjbBmqLQ", PartyUnknown_JrVwjbBmqLQ_nid_no_patch);
int APS5_VABI PartyUnknown_KC3y21wrqzc_nid_no_patch() {
int APS5_VABI PartyNetworkLeaveNetwork() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("KC3y21wrqzc", PartyUnknown_KC3y21wrqzc_nid_no_patch);
int APS5_VABI PartyUnknown_nVzRzo3Yr_plus_s_nid_no_patch() {
int APS5_VABI PartyLocalUserUpdateEntityToken() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("nVzRzo3Yr+s", PartyUnknown_nVzRzo3Yr_plus_s_nid_no_patch);
int APS5_VABI PartyUnknown_pnz21I6VjDs_nid_no_patch() {
int APS5_VABI PartyConnectToNetwork() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("pnz21I6VjDs", PartyUnknown_pnz21I6VjDs_nid_no_patch);
int APS5_VABI PartyUnknown_Qb8wS4GZUsw_nid_no_patch() {
int APS5_VABI PartyCreateNewNetwork() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("Qb8wS4GZUsw", PartyUnknown_Qb8wS4GZUsw_nid_no_patch);
int APS5_VABI PartyUnknown_qk043QPsrZU_nid_no_patch() {
int APS5_VABI PartyEndpointSendMessage() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("qk043QPsrZU", PartyUnknown_qk043QPsrZU_nid_no_patch);
int APS5_VABI PartyUnknown_QVQ_minus_lvlaJZw_nid_no_patch() {
int APS5_VABI PartyNetworkGetEndpoints() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("QVQ-lvlaJZw", PartyUnknown_QVQ_minus_lvlaJZw_nid_no_patch);
int APS5_VABI PartyUnknown_SjQdzD78RpM_nid_no_patch() {
int APS5_VABI PartyGetLocalUsers() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("SjQdzD78RpM", PartyUnknown_SjQdzD78RpM_nid_no_patch);
int APS5_VABI PartyUnknown_uDGXwUKqi8s_nid_no_patch() {
int APS5_VABI PartyEndpointGetEntityId() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("uDGXwUKqi8s", PartyUnknown_uDGXwUKqi8s_nid_no_patch);
int APS5_VABI PartyUnknown_YdBvG5Myxzg_nid_no_patch() {
int APS5_VABI PartyEndpointGetCustomContext() {
NotImplemented_nid_no_patch(__func__);
}
APS5_EXPORT("YdBvG5Myxzg", PartyUnknown_YdBvG5Myxzg_nid_no_patch);
}
@@ -4,31 +4,31 @@
extern "C" {
int APS5_VABI PartyUnknown_0iEKNAvT600_nid_no_patch();
int APS5_VABI PartyUnknown_2cELEBPdYQ0_nid_no_patch();
int APS5_VABI PartyUnknown_5xYxiOtOccA_nid_no_patch();
int APS5_VABI PartyUnknown_6W_plus_shIH315Q_nid_no_patch();
int APS5_VABI PartyUnknown_7ilObq815O4_nid_no_patch();
int APS5_VABI PartyUnknown_7iq7Hfs8HBk_nid_no_patch();
int APS5_VABI PartyUnknown_7kwSdZNDyP0_nid_no_patch();
int APS5_VABI PartyUnknown_AC1FtjqMCL0_nid_no_patch();
int APS5_VABI PartyUnknown_AJ3I035AjIM_nid_no_patch();
int APS5_VABI PartyUnknown_AMJZhpC_plus_siY_nid_no_patch();
int APS5_VABI PartyUnknown_aq13EdrGdVw_nid_no_patch();
int APS5_VABI PartyUnknown_BOW_minus_t_minus_9qJNI_nid_no_patch();
int APS5_VABI PartyUnknown_E9XkHowt_plus_dY_nid_no_patch();
int APS5_VABI PartyUnknown_f3d6tchKw94_nid_no_patch();
int APS5_VABI PartyUnknown_GADjreszOgM_nid_no_patch();
int APS5_VABI PartyUnknown_Giyg2xGrXDU_nid_no_patch();
int APS5_VABI PartyUnknown_JrVwjbBmqLQ_nid_no_patch();
int APS5_VABI PartyUnknown_KC3y21wrqzc_nid_no_patch();
int APS5_VABI PartyUnknown_nVzRzo3Yr_plus_s_nid_no_patch();
int APS5_VABI PartyUnknown_pnz21I6VjDs_nid_no_patch();
int APS5_VABI PartyUnknown_Qb8wS4GZUsw_nid_no_patch();
int APS5_VABI PartyUnknown_qk043QPsrZU_nid_no_patch();
int APS5_VABI PartyUnknown_QVQ_minus_lvlaJZw_nid_no_patch();
int APS5_VABI PartyUnknown_SjQdzD78RpM_nid_no_patch();
int APS5_VABI PartyUnknown_uDGXwUKqi8s_nid_no_patch();
int APS5_VABI PartyUnknown_YdBvG5Myxzg_nid_no_patch();
int APS5_VABI PartySetMemoryCallbacks();
int APS5_VABI PartyFinishProcessingStateChanges();
int APS5_VABI PartyNetworkGetNetworkDescriptor();
int APS5_VABI PartyCleanup();
int APS5_VABI PartyCreateLocalUser();
int APS5_VABI PartySerializeNetworkDescriptor();
int APS5_VABI PartyGetNetworks();
int APS5_VABI PartyNetworkCreateEndpoint();
int APS5_VABI PartyLocalUserGetEntityId();
int APS5_VABI PartyDeserializeNetworkDescriptor();
int APS5_VABI PartyEndpointGetDevice();
int APS5_VABI PartyEndpointSetCustomContext();
int APS5_VABI PartyStartProcessingStateChanges();
int APS5_VABI PartyNetworkGetDeviceConnectionType();
int APS5_VABI PartyNetworkAuthenticateLocalUser();
int APS5_VABI PartyInitialize();
int APS5_VABI PartyEndpointIsLocal();
int APS5_VABI PartyNetworkLeaveNetwork();
int APS5_VABI PartyLocalUserUpdateEntityToken();
int APS5_VABI PartyConnectToNetwork();
int APS5_VABI PartyCreateNewNetwork();
int APS5_VABI PartyEndpointSendMessage();
int APS5_VABI PartyNetworkGetEndpoints();
int APS5_VABI PartyGetLocalUsers();
int APS5_VABI PartyEndpointGetEntityId();
int APS5_VABI PartyEndpointGetCustomContext();
}
+1 -1
View File
@@ -44,7 +44,7 @@ std::uint32_t* APS5_VABI sceAgcAcbAtomicGds_0900(CommandBuffer* buf, std::uint32
}
std::uint32_t* APS5_VABI sceAgcAcbJump(CommandBuffer* buf, std::uint8_t cachePolicy, const std::uint32_t* target, std::uint32_t sizeInDwords) {
return Agc::Command::WriteJump(buf, 1, cachePolicy, target, sizeInDwords, __func__);
return Agc::Command::WriteJump(buf, true, 1, cachePolicy, target, sizeInDwords, __func__);
}
uint32_t APS5_VABI sceAgcAcbJumpGetSize(void) {
+1 -1
View File
@@ -31,7 +31,7 @@ std::uint64_t APS5_VABI sceAgcAcbWaitOnAddressGetSize(std::uint32_t size) {
std::uint32_t* APS5_VABI sceAgcAcbEventWrite(CommandBuffer* buf, std::uint8_t eventType, const volatile void* address) {
Agc::Command::CheckBits(eventType, 0x3fu, __func__);
Agc::Command::Require(address == nullptr, __func__, "ACB event address is not supported");
Agc::Command::Require(address == nullptr || (eventType & 0xfeu) != 0x38u, __func__, "ACB event address is not supported");
return Agc::Command::Emit(buf, 0x46u, {eventType | (eventType == 7 ? 0x400u : 0u)}, __func__);
}
+16 -1
View File
@@ -10,6 +10,7 @@ add_library(libSceAgc SHARED EXCLUDE_FROM_ALL
${CMAKE_CURRENT_SOURCE_DIR}/Cb/src/Registers.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Cb/src/Sync.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Command/src/Memory.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Command/src/Memset.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Command/src/Control.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Command/src/Draw.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Command/src/RegisterDefaults.cpp
@@ -58,7 +59,7 @@ add_library(libSceAgc SHARED EXCLUDE_FROM_ALL
)
target_include_directories(libSceAgc PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(libSceAgc PRIVATE libSceAgcDriver libc)
target_link_libraries(libSceAgc PRIVATE libSceAgcDriver libkernel libc)
foreach(runtimeLinkFlag IN ITEMS -static-libgcc -static-libstdc++ -static)
string(REPLACE "${runtimeLinkFlag}" "" CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}")
@@ -209,6 +210,20 @@ if(BUILD_TESTING)
endif()
endif()
add_test_executable(agc_concurrent_allocation_tests EXCLUDE_FROM_ALL tests/ConcurrentAllocation.cpp)
target_include_directories(agc_concurrent_allocation_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_concurrent_allocation_tests PRIVATE libSceAgc libc)
configure_windows_unwind(agc_concurrent_allocation_tests)
if(BUILD_TESTING)
set_target_properties(agc_concurrent_allocation_tests PROPERTIES EXCLUDE_FROM_ALL OFF)
add_test(NAME agc_concurrent_allocation COMMAND agc_concurrent_allocation_tests)
set_tests_properties(agc_concurrent_allocation PROPERTIES TIMEOUT 60)
if(WIN32)
set_tests_properties(agc_concurrent_allocation PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_packet_info_tests EXCLUDE_FROM_ALL tests/PacketInfo.cpp)
target_include_directories(agc_packet_info_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_packet_info_tests PRIVATE libSceAgc libc)
+1 -2
View File
@@ -9,8 +9,7 @@
extern "C" {
std::uint32_t* APS5_VABI sceAgcCbDispatch(CommandBuffer* buf, std::uint32_t threadGroupX, std::uint32_t threadGroupY, std::uint32_t threadGroupZ, std::uint32_t modifier) {
Agc::Command::CheckBits(modifier, 0xa038u | 0x41u, __func__);
return Agc::Command::Emit(buf, 0x15u, {threadGroupX, threadGroupY, threadGroupZ, modifier | 0x41u}, __func__);
return Agc::Command::Emit(buf, 0x15u, {threadGroupX, threadGroupY, threadGroupZ, (modifier & 0xa038u) | 0x41u}, __func__);
}
uint32_t APS5_VABI sceAgcCbDispatchGetSize(void) {
@@ -5,7 +5,7 @@
namespace Agc::Command {
std::uint32_t* WriteJump(CommandBuffer* buffer, std::uint8_t chain, std::uint8_t cachePolicy, const std::uint32_t* target, std::uint32_t sizeInDwords, const char* function);
std::uint32_t* WriteJump(CommandBuffer* buffer, bool compute, std::uint8_t chain, std::uint8_t cachePolicy, const std::uint32_t* target, std::uint32_t sizeInDwords, const char* function);
std::uint32_t* WriteRewind(CommandBuffer* buffer, std::uint32_t initialState, const char* function);
std::uint32_t* WritePredication(CommandBuffer* buffer, std::uint8_t condition, std::uint8_t operation, std::uint8_t waitOperation, const volatile void* address, const char* function);
std::uint32_t* WriteMemSemaphore(CommandBuffer* buffer, const volatile void* address, std::uint8_t waitForMailbox, std::uint8_t signalType, std::uint8_t operation, const char* function);
@@ -2,13 +2,10 @@
namespace Agc::Command {
std::uint32_t* WriteJump(CommandBuffer* buffer, std::uint8_t chain, std::uint8_t cachePolicy, const std::uint32_t* target, std::uint32_t sizeInDwords, const char* function) {
std::uint32_t* WriteJump(CommandBuffer* buffer, bool compute, std::uint8_t chain, std::uint8_t cachePolicy, const std::uint32_t* target, std::uint32_t sizeInDwords, const char* function) {
const auto guestAddress = reinterpret_cast<std::uintptr_t>(target);
CheckBits(chain, 1, function);
CheckBits(cachePolicy, 3, function);
CheckBits(sizeInDwords, 0xfffffu, function);
Require((guestAddress & 3u) == 0, function, "misaligned jump target");
return Emit(buffer, 0x3fu, {static_cast<std::uint32_t>(guestAddress) & ~3u, static_cast<std::uint32_t>(guestAddress >> 32u), 0x0f200000u | (static_cast<std::uint32_t>(cachePolicy) << 28u) | (static_cast<std::uint32_t>(chain) << 20u) | sizeInDwords}, function);
const auto control = (compute ? 0x0f800000u : 0x0f200000u) | ((static_cast<std::uint32_t>(cachePolicy) & 3u) << 28u) | ((static_cast<std::uint32_t>(chain) & 1u) << 20u) | (sizeInDwords & 0xfffffu);
return Emit(buffer, 0x3fu, {static_cast<std::uint32_t>(guestAddress) & ~3u, static_cast<std::uint32_t>(guestAddress >> 32u), control}, function);
}
std::uint32_t* WriteRewind(CommandBuffer* buffer, std::uint32_t initialState, const char* function) {
@@ -16,14 +13,9 @@ std::uint32_t* WriteRewind(CommandBuffer* buffer, std::uint32_t initialState, co
}
std::uint32_t* WritePredication(CommandBuffer* buffer, std::uint8_t condition, std::uint8_t operation, std::uint8_t waitOperation, const volatile void* address, const char* function) {
CheckBits(condition, 1, function);
CheckBits(operation, 7, function);
CheckBits(waitOperation, 1, function);
const auto guestAddress = reinterpret_cast<std::uintptr_t>(address);
if (operation != 0) {
CheckAddress(guestAddress, 8, function);
}
return Emit(buffer, 0x20u, {(static_cast<std::uint32_t>(condition) << 8u) | (static_cast<std::uint32_t>(waitOperation) << 12u) | (static_cast<std::uint32_t>(operation) << 16u), static_cast<std::uint32_t>(guestAddress) & ~0xfu, static_cast<std::uint32_t>(guestAddress >> 32u)}, function);
const auto control = ((static_cast<std::uint32_t>(condition) & 1u) << 8u) | ((static_cast<std::uint32_t>(waitOperation) & 1u) << 12u) | ((static_cast<std::uint32_t>(operation) & 7u) << 16u);
return Emit(buffer, 0x20u, {control, static_cast<std::uint32_t>(guestAddress) & ~0xfu, static_cast<std::uint32_t>(guestAddress >> 32u)}, function);
}
std::uint32_t* WriteMemSemaphore(CommandBuffer* buffer, const volatile void* address, std::uint8_t waitForMailbox, std::uint8_t signalType, std::uint8_t operation, const char* function) {
@@ -84,10 +84,9 @@ std::uint32_t* WriteData(CommandBuffer* buffer, bool compute, std::uint8_t dst,
}
std::uint32_t* WriteWait(CommandBuffer* buffer, bool compute, std::uint8_t size, std::uint8_t compareFunction, std::uint8_t operation, std::uint8_t cachePolicy, const volatile void* address, std::uint64_t reference, std::uint64_t mask, std::uint32_t pollCycles, const char* function) {
CheckBits(size, 1, function);
if (size > 1u) return nullptr;
Require(compareFunction <= 6, function, "invalid wait comparison");
CheckBits(operation, size == 0 ? 0xfu : 7u, function);
CheckBits(cachePolicy, 3, function);
Require((pollCycles >> 4u) <= 0xffffu, function, "wait poll interval overflow");
if (size == 0) {
// 32-bit waits only use the low halves; guests commonly pass a full 64-bit mask.
@@ -96,7 +95,7 @@ std::uint32_t* WriteWait(CommandBuffer* buffer, bool compute, std::uint8_t size,
}
const auto guestAddress = reinterpret_cast<std::uintptr_t>(address);
// The address may be left null and filled in later with sceAgcWaitRegMemPatchAddress.
if (guestAddress != 0) CheckAddress(guestAddress, size == 0 ? 4 : 8, function);
if (guestAddress != 0 && size == 0) CheckAddress(guestAddress, 4, function);
CheckBits(guestAddress, 0xffffffffffffull, function);
const auto waitSize = size == 0 ? 7u : 9u;
const auto tagFlags = compute ? 0u : 4u;
@@ -108,8 +107,8 @@ std::uint32_t* WriteWait(CommandBuffer* buffer, bool compute, std::uint8_t size,
auto* wait = packet + 4;
wait[0] = Header(size == 0 ? 0x3cu : 0x93u, waitSize);
const auto opBits = size == 0 ? ((operation & 3u) << 8u) | ((operation & 0xcu) << 4u) : ((operation & 1u) << 8u) | ((operation & 6u) << 5u);
wait[1] = 0x10u | compareFunction | opBits | (static_cast<std::uint32_t>(cachePolicy) << 25u);
wait[2] = static_cast<std::uint32_t>(guestAddress);
wait[1] = 0x10u | compareFunction | opBits | ((static_cast<std::uint32_t>(cachePolicy) & 3u) << 25u);
wait[2] = static_cast<std::uint32_t>(guestAddress) & (size == 0 ? ~0u : ~7u);
wait[3] = static_cast<std::uint32_t>(guestAddress >> 32u);
wait[4] = static_cast<std::uint32_t>(reference);
if (size == 0) {
@@ -0,0 +1,88 @@
#include "prx/libSceAgc/include/Agc.hpp"
#include "prx/libSceAgc/Cb/include/Registers.hpp"
#include "prx/libSceAgc/Command/include/Packet.hpp"
#include "prx/libSceAgc/Shader/include/CreateShader.hpp"
#include "prx/libSceAgc/Shader/include/ShaderConstants.hpp"
#include "prx/libSceAgcDriver/include/AgcDriver.hpp"
#include "prx/libkernel/include/Api.hpp"
#include <array>
#include <cstdint>
#include <cstring>
namespace {
alignas(256) constexpr std::array<std::uint32_t, 21> FillCode{
0xbf068008u, 0xbf850012u, 0x7e0a0209u, 0x340a0a88u, 0x4a000105u, 0x7e020204u, 0x7e040205u,
0x7e060206u, 0x7e080207u, 0xbe8a0308u, 0x7d880002u, 0xbe8c246au, 0xe0782000u, 0x80000100u,
0xbefe040cu, 0x4a0000ffu, 0x00001000u, 0x808a810au, 0xbf07800au, 0xbf85fff6u, 0xbf810000u
};
constexpr std::uint32_t FillChecksum = [] {
std::uint32_t hash = 2166136261u;
for (const auto word : FillCode) {
for (unsigned shift = 0; shift < 32; shift += 8) hash = (hash ^ ((word >> shift) & 0xffu)) * 16777619u;
}
return hash;
}();
template <typename T>
T* Relative(T* target, const void* field) {
return reinterpret_cast<T*>(reinterpret_cast<std::uintptr_t>(target) - reinterpret_cast<std::uintptr_t>(field));
}
struct FillProgram {
Shader header{};
std::array<ShaderRegister, 9> registers{{
{0x20cu, 0u}, {0x20du, 0u}, {0x22au, FillChecksum}, {0x212u, 0x602c0041u}, {0x213u, 0x92u},
{0x228u, 0u}, {0x207u, 256u}, {0x208u, 1u}, {0x209u, 1u}
}};
ShaderUserData userData{};
ShaderSpecialRegs specials{};
FillProgram() {
header.file_header = ShaderRegs::SHADER_FILE_HEADER_MAGIC;
header.version = ShaderRegs::SHADER_VERSION;
header.header_size = sizeof(FillProgram);
header.shader_size = sizeof(FillCode);
header.type = static_cast<std::uint8_t>(ShaderRegs::ShaderBinaryType::Cs);
header.num_sh_registers = static_cast<std::uint8_t>(registers.size());
header.sh_registers = Relative(registers.data(), &header.sh_registers);
header.user_data = Relative(&userData, &header.user_data);
header.specials = Relative(&specials, &header.specials);
userData.srt_size_dw = 9;
specials.dispatch_modifier = 1;
Shader* created = nullptr;
Agc::Command::Require(sceAgcCreateShader(&created, &header, FillCode.data()) == 0 && created == &header, "sceAgcCbMemsetExclusive", "cannot create the fill shader");
}
};
FillProgram& Program() {
static FillProgram program;
return program;
}
} // namespace
extern "C" std::uint32_t* APS5_VABI sceAgcCbMemsetExclusive(CommandBuffer* buffer, void* destination, const void* pattern, std::uint64_t size) {
constexpr auto function = __func__;
Agc::Command::Require(buffer != nullptr, function, "null command buffer");
Agc::Command::CheckAddress(reinterpret_cast<std::uintptr_t>(pattern), 1, function);
auto& program = Program();
auto* first = sceAgcCbSetShRegistersDirect(buffer, program.header.sh_registers, program.header.num_sh_registers);
const auto address = reinterpret_cast<std::uint64_t>(destination);
std::array<std::uint32_t, 9> data{
static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu) | 0x100000u,
static_cast<std::uint32_t>(size >> 4u), 0x4bfacu, 0u, 0u, 0u, 0u,
static_cast<std::uint32_t>((size + 0xffffu) >> 16u)
};
std::memcpy(data.data() + 4, pattern, 16);
sceAgcCbSetShRegisterRangeDirect(buffer, 0x240u, data.data(), static_cast<std::uint32_t>(data.size()));
const auto mask = (static_cast<std::uint32_t>(sceKernelGetMainSocId()) & ~0x1fu) == 0x840fc0u ? 0x00ff00ffu : 0x0003fcffu;
Agc::Command::Emit(buffer, 0x76u, {0x216u, mask}, function);
Agc::Command::Emit(buffer, 0x76u, {0x217u, mask}, function);
const auto initiator = (program.specials.dispatch_modifier & 0xa038u) | static_cast<std::uint32_t>(sceAgcDriverGetTraceInitiator()) | 0x41u;
Agc::Command::Emit(buffer, 0x15u, {16u, 1u, 1u, initiator}, function);
Agc::Command::Emit(buffer, 0x76u, {0x216u, 0xffffffffu}, function);
Agc::Command::Emit(buffer, 0x76u, {0x217u, 0xffffffffu}, function);
return first;
}
+73 -1
View File
@@ -2,12 +2,17 @@
#include "prx/libSceAgc/Command/include/Packet.hpp"
#include <algorithm>
#include <array>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <limits>
#include <mutex>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
namespace Agc::Command {
@@ -53,6 +58,56 @@ std::uint32_t available(const CommandBuffer& buffer, const char* function) {
return static_cast<std::uint32_t>(count - buffer.reserved_dw);
}
struct Growing {
const CommandBuffer* buffer;
std::thread::id thread;
std::uint32_t depth;
};
struct AllocationStripe {
std::mutex mutex;
std::condition_variable grown;
std::vector<Growing> growing;
std::vector<Growing>::iterator find(const CommandBuffer* buffer) {
return std::find_if(growing.begin(), growing.end(), [buffer](const Growing& entry) { return entry.buffer == buffer; });
}
};
AllocationStripe& allocationStripe(const CommandBuffer* buffer) {
static std::array<AllocationStripe, 64> stripes;
return stripes[(reinterpret_cast<std::uintptr_t>(buffer) >> 4u) % stripes.size()];
}
class GrowScope {
public:
GrowScope(AllocationStripe& stripe, std::unique_lock<std::mutex>& lock, const CommandBuffer* buffer) : stripe(stripe), lock(lock), buffer(buffer) {
if (const auto entry = stripe.find(buffer); entry != stripe.growing.end()) {
++entry->depth;
} else {
stripe.growing.push_back({buffer, std::this_thread::get_id(), 1});
}
lock.unlock();
}
~GrowScope() {
lock.lock();
const auto entry = stripe.find(buffer);
if (--entry->depth == 0) {
stripe.growing.erase(entry);
stripe.grown.notify_all();
}
}
GrowScope(const GrowScope&) = delete;
GrowScope& operator=(const GrowScope&) = delete;
private:
AllocationStripe& stripe;
std::unique_lock<std::mutex>& lock;
const CommandBuffer* buffer;
};
}
void Reserve(CommandBuffer* buffer, std::uint32_t count, const char* function) {
@@ -66,7 +121,24 @@ void Reserve(CommandBuffer* buffer, std::uint32_t count, const char* function) {
}
std::uint32_t* Allocate(CommandBuffer* buffer, std::uint32_t count, const char* function) {
Reserve(buffer, count, function);
Require(buffer != nullptr && count != 0, function, "null command buffer or empty allocation");
auto& stripe = allocationStripe(buffer);
std::unique_lock serialized(stripe.mutex);
stripe.grown.wait(serialized, [&] {
const auto entry = stripe.find(buffer);
return entry == stripe.growing.end() || entry->thread == std::this_thread::get_id();
});
if (available(*buffer, function) < count) {
Require(buffer->callback != nullptr, function, "command buffer exhausted");
Require(count <= std::numeric_limits<std::uint32_t>::max() - buffer->reserved_dw, function, "command buffer allocation overflow");
bool grew = false;
{
const GrowScope growing(stripe, serialized, buffer);
grew = buffer->callback(buffer, count + buffer->reserved_dw, buffer->user_data);
}
Require(grew, function, "command buffer allocation callback failed");
Require(available(*buffer, function) >= count, function, "command buffer allocation callback returned insufficient space");
}
auto* result = buffer->cursor_up;
AgcDriverPrepareCommandWrite_nid_no_patch(reinterpret_cast<std::uint64_t>(result), static_cast<std::size_t>(count) * sizeof(std::uint32_t));
buffer->cursor_up += count;
@@ -77,7 +77,7 @@ std::uint32_t APS5_VABI sceAgcDcbDrawIndexIndirectMultiGetSize() {
return 64;
}
uint32_t* APS5_VABI sceAgcDcbDrawIndexMultiInstanced(CommandBuffer* buf, uint32_t index_count, const volatile void* index_addr, const volatile void* object_ids, uint32_t instance_count, uint64_t) {
uint32_t* APS5_VABI sceAgcDcbDrawIndexMultiInstanced(CommandBuffer* buf, uint32_t index_count, const volatile void* index_addr, const volatile void* object_ids, uint32_t instance_count, uint64_t modifier) {
const auto geometry = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(index_addr));
const auto objects = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(object_ids));
auto* packet = Agc::Command::Allocate(buf, 15, __func__);
@@ -92,7 +92,7 @@ uint32_t* APS5_VABI sceAgcDcbDrawIndexMultiInstanced(CommandBuffer* buf, uint32_
packet[8] = static_cast<std::uint32_t>(objects);
packet[9] = static_cast<std::uint32_t>(objects >> 32u);
packet[10] = instance_count;
packet[11] = 0x80u;
packet[11] = 0x80u | Agc::Command::DrawInitiator(modifier, true, __func__);
packet[12] = Agc::Command::Header(0x79u, 3, 4);
packet[13] = 0x342u;
packet[14] = 0xc6000000u;
@@ -29,7 +29,7 @@ std::uint32_t* APS5_VABI sceAgcDcbAtomicGds(CommandBuffer* buf, std::uint32_t en
uint32_t* APS5_VABI sceAgcDcbJump(CommandBuffer* buf, uint8_t mode, uint8_t cache_policy, const uint32_t* target, uint32_t size_in_dwords) {
return Agc::Command::WriteJump(buf, mode, cache_policy, target, size_in_dwords, __func__);
return Agc::Command::WriteJump(buf, false, mode, cache_policy, target, size_in_dwords, __func__);
}
std::uint32_t APS5_VABI sceAgcDcbJumpGetSize() {
@@ -10,11 +10,13 @@ extern "C" {
uint32_t APS5_VABI sceAgcGetPacketSize(uint32_t* packet) {
Agc::Command::CheckAddress(reinterpret_cast<std::uintptr_t>(packet), alignof(uint32_t), __func__);
Agc::Command::Require((packet[0] & 0xc0000000u) == 0xc0000000u, __func__, "source pointer is not a PM4 packet");
if ((packet[0] & 0x3fffff00u) == 0x3fff1000u) {
uint32_t header = 0;
Agc::Command::Require(GuestCopyIn_nid_no_patch(&header, packet, sizeof(header)), __func__, "source pointer is not readable");
Agc::Command::Require((header & 0xc0000000u) == 0xc0000000u, __func__, "source pointer is not a PM4 packet");
if ((header & 0x3fffff00u) == 0x3fff1000u) {
return 1;
}
return ((packet[0] >> 16u) & 0x3fffu) + 2u;
return ((header >> 16u) & 0x3fffu) + 2u;
}
int APS5_VABI sceAgcGetDataPacketPayloadAddress_0090(uint32_t** addr, uint32_t* cmd, int type) {
@@ -24,7 +26,9 @@ int APS5_VABI sceAgcGetDataPacketPayloadAddress_0090(uint32_t** addr, uint32_t*
if (type != 0) {
payload = cmd + 2;
} else {
payload = (~cmd[0] & 0x3fff0000u) != 0 ? cmd + 1 : nullptr;
uint32_t header = 0;
Agc::Command::Require(GuestCopyIn_nid_no_patch(&header, cmd, sizeof(header)), __func__, "source pointer is not readable");
payload = (~header & 0x3fff0000u) != 0 ? cmd + 1 : nullptr;
}
Agc::Command::Require(GuestCopyOut_nid_no_patch(addr, &payload, sizeof(payload)), __func__, "destination pointer is not writable");
return 0;
@@ -37,12 +41,14 @@ int APS5_VABI sceAgcGetDataPacketPayloadAddress(uint32_t** addr, uint32_t* cmd,
int APS5_VABI sceAgcGetDataPacketPayloadRange(SceAgcMemoryRange* range, uint32_t* cmd, int type) {
Agc::Command::CheckAddress(reinterpret_cast<std::uintptr_t>(range), alignof(SceAgcMemoryRange), __func__);
Agc::Command::CheckAddress(reinterpret_cast<std::uintptr_t>(cmd), alignof(uint32_t), __func__);
const uint64_t count_bytes = (cmd[0] >> 14u) & 0xfffcu;
uint32_t header = 0;
Agc::Command::Require(GuestCopyIn_nid_no_patch(&header, cmd, sizeof(header)), __func__, "source pointer is not readable");
const uint64_t count_bytes = (header >> 14u) & 0xfffcu;
SceAgcMemoryRange result{};
if (type != 0) {
result.base = cmd + 2;
result.size = count_bytes;
} else if ((~cmd[0] & 0x3fff0000u) == 0) {
} else if ((~header & 0x3fff0000u) == 0) {
result.base = nullptr;
result.size = 0;
} else {
@@ -56,10 +62,13 @@ int APS5_VABI sceAgcGetDataPacketPayloadRange(SceAgcMemoryRange* range, uint32_t
int APS5_VABI sceAgcDcbGetSystemSoftwareVersion(uint32_t* destination, const uint32_t* packet) {
Agc::Command::CheckAddress(reinterpret_cast<std::uintptr_t>(destination), alignof(uint32_t), __func__);
Agc::Command::CheckAddress(reinterpret_cast<std::uintptr_t>(packet), alignof(uint32_t), __func__);
Agc::Command::Require((packet[0] & 0xc0000000u) == 0xc0000000u, __func__, "source pointer is not a PM4 packet");
const auto size = ((packet[0] >> 16u) & 0x3fffu) + 2u;
uint32_t header = 0;
Agc::Command::Require(GuestCopyIn_nid_no_patch(&header, packet, sizeof(header)), __func__, "source pointer is not readable");
Agc::Command::Require((header & 0xc0000000u) == 0xc0000000u, __func__, "source pointer is not a PM4 packet");
const auto size = ((header >> 16u) & 0x3fffu) + 2u;
Agc::Command::Require(size >= 3u, __func__, "PM4 packet is too short to carry a software version");
const auto version = packet[1];
uint32_t version = 0;
Agc::Command::Require(GuestCopyIn_nid_no_patch(&version, packet + 1, sizeof(version)), __func__, "source pointer is not readable");
Agc::Command::Require(GuestCopyOut_nid_no_patch(destination, &version, sizeof(version)), __func__, "destination pointer is not writable");
return 0;
}
@@ -1,7 +1,10 @@
#include "prx/libSceAgc/Misc/include/StaticBuffer.hpp"
#include <array>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include "prx/libc/include/General.hpp"
#include "SceTypes.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver.hpp"
@@ -23,13 +26,28 @@ extern "C" {
int APS5_VABI sceAgcSetStaticBuffer(std::uint32_t index, const void* buffer) {
if (index >= StaticBufferCount) return GRAPHICS5_ERROR_INVALID_STATIC_BUFFER;
std::memcpy(StaticTable() + std::size_t{index} * StaticBufferBytes, buffer, StaticBufferBytes);
std::array<std::uint8_t, StaticBufferBytes> words{};
const int savedErrno = errno;
const bool copied = GuestCopyIn_nid_no_patch(words.data(), buffer, words.size());
if (!copied) {
errno = savedErrno;
return GRAPHICS5_ERROR_INVALID_STATIC_BUFFER;
}
std::memcpy(StaticTable() + std::size_t{index} * StaticBufferBytes, words.data(), words.size());
errno = savedErrno;
return 0;
}
int APS5_VABI sceAgcGetStaticBuffer(std::uint32_t index, void* buffer) {
if (index >= StaticBufferCount) return GRAPHICS5_ERROR_INVALID_STATIC_BUFFER;
std::memcpy(buffer, StaticTable() + std::size_t{index} * StaticBufferBytes, StaticBufferBytes);
std::array<std::uint8_t, StaticBufferBytes> words{};
std::memcpy(words.data(), StaticTable() + std::size_t{index} * StaticBufferBytes, words.size());
const int savedErrno = errno;
if (!GuestCopyOut_nid_no_patch(buffer, words.data(), words.size())) {
errno = savedErrno;
return GRAPHICS5_ERROR_INVALID_STATIC_BUFFER;
}
errno = savedErrno;
return 0;
}
@@ -41,7 +59,14 @@ int APS5_VABI sceAgcSetStaticQword(std::uint32_t index, std::uint64_t value) {
int APS5_VABI sceAgcGetStaticQword(std::uint32_t index, std::uint64_t* value) {
if (index >= StaticQwordCount) return GRAPHICS5_ERROR_INVALID_STATIC_BUFFER;
std::memcpy(value, StaticTable() + StaticQwordOffset + std::size_t{index} * sizeof(*value), sizeof(*value));
std::uint64_t word = 0;
std::memcpy(&word, StaticTable() + StaticQwordOffset + std::size_t{index} * sizeof(word), sizeof(word));
const int savedErrno = errno;
if (!GuestCopyOut_nid_no_patch(value, &word, sizeof(word))) {
errno = savedErrno;
return GRAPHICS5_ERROR_INVALID_STATIC_BUFFER;
}
errno = savedErrno;
return 0;
}
@@ -21,19 +21,28 @@ int APS5_VABI sceAgcGetGsPrimPayload(std::uint32_t* payload, const Shader* gs) {
if (payload == nullptr || gs == nullptr) {
throw std::runtime_error(std::string(__func__) + ": payload or gs is null");
}
if (gs->num_cx_registers != 0 && gs->cx_registers == nullptr) {
Shader shader{};
if (!GuestCopyIn_nid_no_patch(&shader, gs, sizeof(shader))) {
throw std::runtime_error(std::string(__func__) + ": gs is not readable");
}
if (shader.num_cx_registers != 0 && shader.cx_registers == nullptr) {
throw std::runtime_error(std::string(__func__) + ": gs->cx_registers is null but num_cx_registers != 0");
}
std::uint32_t bytes = 0;
for (std::uint32_t i = 0; i < gs->num_cx_registers; ++i) {
const ShaderRegister& reg = gs->cx_registers[i];
for (std::uint32_t i = 0; i < shader.num_cx_registers; ++i) {
ShaderRegister reg{};
if (!GuestCopyIn_nid_no_patch(&reg, shader.cx_registers + i, sizeof(reg))) {
throw std::runtime_error(std::string(__func__) + ": gs->cx_registers is not readable");
}
if (reg.offset == ShaderRegs::SPI_SHADER_IDX_FORMAT && (reg.value & IDX0_EXPORT_FORMAT_MASK) == SPI_SHADER_2COMP) {
bytes = TwoComponentPayloadBytes;
break;
}
}
*payload = bytes;
if (!GuestCopyOut_nid_no_patch(payload, &bytes, sizeof(bytes))) {
throw std::runtime_error(std::string(__func__) + ": payload is not writable");
}
return 0;
}
@@ -6,11 +6,6 @@
extern "C" {
std::uint32_t* APS5_VABI sceAgcCbMemsetExclusive(CommandBuffer* buffer, void* destination, const void* pattern, std::uint64_t size) {
NotImplemented_nid_no_patch(__func__);
return 0;
}
int APS5_VABI sceAgcAcbInitializeDefaultHardwareState() {
NotImplemented_nid_no_patch(__func__);
return 0;
+67 -15
View File
@@ -255,6 +255,34 @@ void testTagHeaders() {
}
}
void testWaitConsoleArguments() {
const auto pointer = [](std::uintptr_t address) { return reinterpret_cast<const volatile void*>(address); };
{
Storage storage;
const auto* wait = sceAgcAcbWaitRegMem(&storage.buffer, 1, 2, 3, pointer(4), 5, 0, 0);
const std::array<std::uint32_t, 16> expected{0xc0027900u, 0x342u, 0xc8020000u, 4u, 0xc0079300u, 0x06000012u, 0u, 0u, 5u, 0u, 0u, 0u, 0u, 0xc0017900u, 0x342u, 0xc8000000u};
check(wait == storage.words.data() && std::equal(expected.begin(), expected.end(), wait), "ACB wait does not match the console's packet");
check(storage.buffer.cursor_up == storage.words.data() + expected.size(), "ACB wait cursor advance mismatch");
}
{
Storage storage;
const auto* wait = sceAgcDcbWaitRegMem(&storage.buffer, 1, 2, 3, 4, pointer(5), 0, 1, 0xffff0);
const std::array<std::uint32_t, 16> expected{0xc0027904u, 0x342u, 0xc8020000u, 5u, 0xc0079300u, 0x152u, 0u, 0u, 0u, 0u, 1u, 0u, 0xffffu, 0xc0017904u, 0x342u, 0xc8000000u};
check(wait == storage.words.data() && std::equal(expected.begin(), expected.end(), wait), "DCB wait does not match the console's packet");
check(storage.buffer.cursor_up == storage.words.data() + expected.size(), "DCB wait cursor advance mismatch");
}
const auto rejects = [](const auto& build, const char* message) {
Storage storage;
storage.words.fill(0xdeadbeefu);
const auto before = storage.words;
check(build(storage.buffer) == nullptr && storage.words == before && storage.buffer.cursor_up == storage.words.data(), message);
};
rejects([&](CommandBuffer& buffer) { return sceAgcAcbWaitRegMem(&buffer, 0x11, 0x22, 0x33, pointer(0x44444444u), 0x55555555u, 0, 0); }, "ACB wait with size 0x11 wrote a packet");
rejects([&](CommandBuffer& buffer) { return sceAgcAcbWaitRegMem(&buffer, 0x22, 0x44, 0, nullptr, 0, 0, 0); }, "ACB wait with size 0x22 wrote a packet");
rejects([&](CommandBuffer& buffer) { return sceAgcDcbWaitRegMem(&buffer, 0x11, 0x22, 0x33, 0x44, pointer(0x55555555u), 0, 0, 0); }, "DCB wait with size 0x11 wrote a packet");
rejects([&](CommandBuffer& buffer) { return sceAgcDcbWaitRegMem(&buffer, 0x22, 0x44, 0, 0, nullptr, 0, 0, 0); }, "DCB wait with size 0x22 wrote a packet");
}
void testJumpTargetPatch() {
const auto target = [](std::uintptr_t address) { return reinterpret_cast<const volatile std::uint32_t*>(address); };
Storage storage;
@@ -617,19 +645,30 @@ void testFlowPackets() {
check(called.words[3] == 0x0f2fffffu, "unchained INDIRECT_BUFFER control word mismatch");
Storage compute;
sceAgcAcbJump(&compute.buffer, 1, target, 0x10);
check(compute.words[0] == 0xc0023f00u && compute.words[3] == 0x1f300010u, "compute jumps did not chain");
Storage rejected;
rejected.words.fill(0xa5a5a5a5u);
const auto rejectedWords = rejected.words;
const auto* rejectedCursor = rejected.buffer.cursor_up;
expectFailure([&] { sceAgcDcbJump(&rejected.buffer, 2, 0, target, 1); });
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
expectFailure([&] { sceAgcDcbJump(&rejected.buffer, 0, 4, target, 1); });
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
expectFailure([&] { sceAgcDcbJump(&rejected.buffer, 0, 0, target, 0x100000u); });
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
expectFailure([&] { sceAgcAcbJump(&rejected.buffer, 0, reinterpret_cast<const std::uint32_t*>(0x1002ull), 1); });
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
check(compute.words[0] == 0xc0023f00u && compute.words[3] == 0x1f900010u, "compute jumps did not chain");
struct ConsoleJump {
bool compute;
std::uint8_t mode;
std::uint8_t cachePolicy;
std::uintptr_t target;
std::uint32_t size;
std::array<std::uint32_t, 3> words;
};
const std::array<ConsoleJump, 6> consoleJumps{{
{true, 1, 0x11, 0x22222222u, 0x33333333u, {0x22222220u, 0u, 0x1f933333u}},
{true, 1, 1, 2u, 3u, {0u, 0u, 0x1f900003u}},
{true, 1, 0x22, 0x3333333344444444ull, 0u, {0x44444444u, 0x33333333u, 0x2f900000u}},
{false, 0x11, 0x22, 0x33333333u, 0x44444444u, {0x33333330u, 0u, 0x2f344444u}},
{false, 1, 2, 3u, 4u, {0u, 0u, 0x2f300004u}},
{false, 0x22, 0x44, 0u, 0u, {0u, 0u, 0x0f200000u}},
}};
for (const auto& item : consoleJumps) {
Storage storage;
const auto* jumpTarget = reinterpret_cast<const std::uint32_t*>(item.target);
const auto* packet = item.compute ? sceAgcAcbJump(&storage.buffer, item.cachePolicy, jumpTarget, item.size) : sceAgcDcbJump(&storage.buffer, item.mode, item.cachePolicy, jumpTarget, item.size);
check(packet == storage.words.data() && packet[0] == 0xc0023f00u && std::equal(item.words.begin(), item.words.end(), packet + 1), "jump packet does not match the console's");
check(storage.buffer.cursor_up == storage.words.data() + 4, "jump cursor mismatch");
}
check(sceAgcDcbJumpGetSize() == 16 && sceAgcAcbJumpGetSize() == 16, "jump packet sizes");
Storage stall;
sceAgcDcbStallCommandBufferParser(&stall.buffer);
@@ -1162,12 +1201,24 @@ void testDispatchPackets() {
sceAgcCbDispatch(&direct.buffer, 7, 3, 1, 0x8000u);
const std::array<std::uint32_t, 5> directExpected{0xc0031500u, 7, 3, 1, 0x8041u};
check(std::equal(directExpected.begin(), directExpected.end(), direct.words.begin()), "DISPATCH_DIRECT packet mismatch");
const std::array<std::array<std::uint32_t, 2>, 10> modifiers{{
{4u, 0x41u}, {0x100u, 0x41u}, {0x44444444u, 0x41u},
{0xffffffffu, 0xa079u}, {8u, 0x49u}, {16u, 0x51u},
{32u, 0x61u}, {0x2000u, 0x2041u}, {0x8001u, 0x8041u},
{0x40u, 0x41u}
}};
for (const auto& item : modifiers) {
Storage masked;
masked.words.fill(0xdeadbeefu);
auto* packet = sceAgcCbDispatch(&masked.buffer, 1u, 2u, 3u, item[0]);
const std::array<std::uint32_t, 5> expected{0xc0031500u, 1u, 2u, 3u, item[1]};
check(packet == masked.words.data() && std::equal(expected.begin(), expected.end(), packet), "direct dispatch did not mask the modifier");
check(masked.buffer.cursor_up == packet + 5 && masked.words[5] == 0xdeadbeefu, "masked dispatch cursor or sentinel differs");
}
Storage rejected;
rejected.words.fill(0xa5a5a5a5u);
const auto rejectedWords = rejected.words;
const auto* rejectedCursor = rejected.buffer.cursor_up;
expectFailure([&] { sceAgcCbDispatch(&rejected.buffer, 1, 1, 1, 0x100u); });
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
expectFailure([&] { sceAgcAcbDispatchIndirect(&rejected.buffer, reinterpret_cast<const volatile void*>(0x1002ull), 0); });
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
expectFailure([&] { sceAgcAcbDispatchIndirect(&rejected.buffer, nullptr, 0); });
@@ -1314,6 +1365,7 @@ int main(int argc, char** argv) {
testIndexedIndirectDraws();
testMeasuredMultiDraws();
testTagHeaders();
testWaitConsoleArguments();
testMarkers();
testJumpTargetPatch();
testMarkerSpans();
@@ -0,0 +1,171 @@
#include "prx/libSceAgc/Cb/include/Sync.hpp"
#include "prx/libSceAgc/Command/include/Packet.hpp"
#include <array>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <future>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
namespace {
constexpr std::size_t Threads = 8;
constexpr std::size_t PacketsPerThread = 20000;
constexpr std::uint32_t FirstSize = 2;
void check(bool condition, const std::string& message) {
if (!condition) throw std::runtime_error(message);
}
std::size_t totalWords() {
std::size_t words = 0;
for (std::size_t thread = 0; thread < Threads; ++thread) words += PacketsPerThread * (FirstSize + thread);
return words;
}
void testConcurrentNops() {
std::vector<std::uint32_t> words(totalWords(), 0xaaaaaaaau);
CommandBuffer buffer{words.data(), words.data() + words.size(), words.data(), words.data() + words.size(), nullptr, nullptr, 0};
std::atomic<std::size_t> ready{0};
std::vector<std::thread> workers;
std::array<std::string, Threads> errors;
for (std::size_t thread = 0; thread < Threads; ++thread) {
workers.emplace_back([&, thread] {
const auto size = static_cast<std::uint32_t>(FirstSize + thread);
ready.fetch_add(1);
while (ready.load() != Threads) std::this_thread::yield();
try {
for (std::size_t packet = 0; packet < PacketsPerThread; ++packet) sceAgcCbNop_nid_postfix(&buffer, size);
} catch (const std::exception& error) {
errors[thread] = error.what();
}
});
}
for (auto& worker : workers) worker.join();
for (const auto& error : errors) check(error.empty(), "a concurrent NOP failed: " + error);
check(buffer.cursor_up == words.data() + words.size(), "concurrent allocations lost cursor advances");
std::array<std::size_t, Threads> seen{};
for (std::size_t cursor = 0; cursor < words.size();) {
const auto header = words[cursor];
check((header & 0xc000ffffu) == 0xc0001000u, "packet " + std::to_string(cursor) + " has no NOP header");
const auto size = ((header >> 16u) & 0x3fffu) + 2u;
check(size >= FirstSize && size < FirstSize + Threads && cursor + size <= words.size(), "NOP at " + std::to_string(cursor) + " has a size no thread wrote");
for (std::uint32_t word = 1; word < size; ++word) check(words[cursor + word] == 0, "NOP at " + std::to_string(cursor) + " was overwritten");
++seen[size - FirstSize];
cursor += size;
}
for (std::size_t thread = 0; thread < Threads; ++thread) check(seen[thread] == PacketsPerThread, "thread " + std::to_string(thread) + " packets were overwritten");
}
constexpr std::size_t OtherBuffers = 256;
constexpr std::uint32_t GrownWords = 64;
struct BlockedGrowth {
std::vector<std::uint32_t> grown = std::vector<std::uint32_t>(GrownWords, 0xaaaaaaaau);
std::promise<void> entered;
std::future<void> others;
bool othersFinished = false;
};
bool APS5_VABI growAfterOthers(CommandBuffer* buffer, std::uint32_t, void* user) {
auto& growth = *static_cast<BlockedGrowth*>(user);
growth.entered.set_value();
growth.othersFinished = growth.others.wait_for(std::chrono::seconds(20)) == std::future_status::ready;
buffer->bottom = growth.grown.data();
buffer->top = growth.grown.data() + growth.grown.size();
buffer->cursor_up = buffer->bottom;
buffer->cursor_down = buffer->top;
return true;
}
void testGrowthDoesNotBlockOtherBuffers() {
std::array<std::uint32_t, 2> full{};
BlockedGrowth growth;
CommandBuffer buffer{full.data(), full.data() + full.size(), full.data() + full.size(), full.data() + full.size(), growAfterOthers, &growth, 0};
std::vector<std::array<std::uint32_t, 2>> storage(OtherBuffers);
std::vector<CommandBuffer> others;
others.reserve(OtherBuffers);
for (auto& words : storage) others.push_back({words.data(), words.data() + words.size(), words.data(), words.data() + words.size(), nullptr, nullptr, 0});
auto entered = growth.entered.get_future();
std::string error;
std::promise<void> finished;
growth.others = finished.get_future();
std::thread appender([&] {
entered.wait();
try {
for (auto& other : others) sceAgcCbNop_nid_postfix(&other, 2);
} catch (const std::exception& failure) {
error = failure.what();
}
finished.set_value();
});
sceAgcCbNop_nid_postfix(&buffer, 2);
appender.join();
check(error.empty(), "an append to another buffer failed: " + error);
check(growth.othersFinished, "appends to other buffers waited for a buffer that was growing");
check(buffer.cursor_up == growth.grown.data() + 2, "the grown buffer did not receive its packet");
for (const auto& other : others) check(other.cursor_up == other.top, "another buffer lost its packet");
}
struct SlowGrowth {
std::vector<std::uint32_t> grown = std::vector<std::uint32_t>(GrownWords, 0xaaaaaaaau);
std::atomic<bool> entered{false};
std::atomic<std::uint32_t> calls{0};
};
bool APS5_VABI growSlowly(CommandBuffer* buffer, std::uint32_t, void* user) {
auto& growth = *static_cast<SlowGrowth*>(user);
growth.calls.fetch_add(1);
growth.entered.store(true);
std::this_thread::sleep_for(std::chrono::milliseconds(200));
buffer->bottom = growth.grown.data();
buffer->top = growth.grown.data() + growth.grown.size();
buffer->cursor_up = buffer->bottom;
buffer->cursor_down = buffer->top;
sceAgcCbNop_nid_postfix(buffer, 2);
return true;
}
void testGrowthSerializesItsOwnBuffer() {
std::array<std::uint32_t, 2> full{};
SlowGrowth growth;
CommandBuffer buffer{full.data(), full.data() + full.size(), full.data() + full.size(), full.data() + full.size(), growSlowly, &growth, 0};
std::string error;
std::thread second([&] {
while (!growth.entered.load()) std::this_thread::yield();
try {
sceAgcCbNop_nid_postfix(&buffer, 4);
} catch (const std::exception& failure) {
error = failure.what();
}
});
sceAgcCbNop_nid_postfix(&buffer, 3);
second.join();
check(error.empty(), "an append during growth failed: " + error);
check(growth.calls.load() == 1, "an append during growth called the allocation callback again");
check(buffer.cursor_up == growth.grown.data() + 9, "appends around growth lost cursor advances");
check(growth.grown[0] == 0xc0001000u, "the callback's packet is not first in the grown buffer");
const auto first = ((growth.grown[2] >> 16u) & 0x3fffu) + 2u;
check(first == 3 || first == 4, "the grown buffer holds a packet no thread wrote");
const auto next = ((growth.grown[2 + first] >> 16u) & 0x3fffu) + 2u;
check(first + next == 7, "a packet appended around growth was overwritten");
}
}
int main() {
try {
testConcurrentNops();
testGrowthDoesNotBlockOtherBuffers();
testGrowthSerializesItsOwnBuffer();
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
}
@@ -17,7 +17,7 @@ struct Call {
std::array<std::uint32_t, 15> expected(const Call& call) {
return {0xc0017904u, 0x342u, 0xc6000006u, 0xc0073a00u, call.first, static_cast<std::uint32_t>(call.second), static_cast<std::uint32_t>(call.second >> 32u),
call.fourth == 0 ? 1u : call.fourth, static_cast<std::uint32_t>(call.third), static_cast<std::uint32_t>(call.third >> 32u), call.fourth, 0x80u,
call.fourth == 0 ? 1u : call.fourth, static_cast<std::uint32_t>(call.third), static_cast<std::uint32_t>(call.third >> 32u), call.fourth, 0x80u | ((call.modifier & 0x100000000ull) != 0 ? 0u : static_cast<std::uint32_t>((call.modifier >> 3u) & 0x20u)),
0xc0017904u, 0x342u, 0xc6000000u};
}
@@ -30,10 +30,11 @@ int main() {
}
constexpr std::uint64_t ia = 0x123456789a00ull;
constexpr std::uint64_t oa = 0x222233334440ull;
const std::array<Call, 12> calls{{
const std::array<Call, 15> calls{{
{100, ia, 0, 3, 0}, {100, ia, 0, 1, 0}, {0, ia, 0, 3, 0}, {100, ia, oa, 3, 0},
{100, ia, oa, 3, 0x10}, {100, ia, oa, 3, 0x8 | (3ull << 24)}, {100, ia, oa, 3, 0x1 | (2ull << 9) | 0x4 | (5ull << 19)}, {100, ia, oa, 3, 0x100000000ull},
{100, 0, 0, 3, 0}, {100, ia + 1, oa + 2, 3, 0}, {100, ia, oa, 0, 0}, {0xffffffffu, ia, oa, 0xffffffffu, 0},
{100, ia, oa, 3, 0x100}, {0x11111111, 0x22222222, 0x33333333, 0x44444444, 0x55555555}, {100, ia, oa, 3, 0x100000100ull},
}};
for (const auto& call : calls) {
std::array<std::uint32_t, 32> words{};
@@ -95,6 +95,23 @@ void testRejections() {
check(out == Sentinel, "a rejected call wrote the payload");
}
void testUnmappedPointers() {
std::vector<ShaderRegister> cx{{ShaderRegs::SPI_SHADER_IDX_FORMAT, 2u}};
const Shader gs = makeGs(cx);
std::uint32_t out = Sentinel;
auto* unmappedPayload = reinterpret_cast<std::uint32_t*>(std::uintptr_t{0x10});
const auto* unmappedShader = reinterpret_cast<const Shader*>(std::uintptr_t{0x10});
expectFailure([&] { sceAgcGetGsPrimPayload(unmappedPayload, &gs); }, "an unwritable payload pointer was accepted");
expectFailure([&] { sceAgcGetGsPrimPayload(&out, unmappedShader); }, "an unreadable shader was accepted");
Shader unreadable{};
unreadable.cx_registers = reinterpret_cast<ShaderRegister*>(std::uintptr_t{0x10});
unreadable.num_cx_registers = 1;
expectFailure([&] { sceAgcGetGsPrimPayload(&out, &unreadable); }, "an unreadable register array was accepted");
check(out == Sentinel, "a rejected call wrote the payload");
unreadable.num_cx_registers = 0;
expectPayload(unreadable, 0, "an empty register array was read");
}
}
int main() {
@@ -106,6 +123,7 @@ int main() {
testSearchContinuesPastAMismatch();
testCountBoundsTheSearch();
testRejections();
testUnmappedPointers();
LibcRunShutdown_nid_postfix();
std::puts("AGC GS primitive payload tests passed");
return 0;
@@ -55,6 +55,19 @@ void testComputeEventWrite() {
check(flush == storage.words.data() + 2 && flush[0] == 0xc0004600u && flush[1] == 0x407u, "ACB CS_PARTIAL_FLUSH does not carry event index 4");
check(storage.buffer.cursor_up == storage.words.data() + 4, "ACB EVENT_WRITE cursor advance mismatch");
expectFailure(storage, [&] { sceAgcAcbEventWrite(&storage.buffer, 0x40, nullptr); }, "an ACB event type above 0x3f was accepted");
struct Case {
std::uint8_t eventType;
std::uintptr_t address;
};
for (const Case item : {Case{0x11, 0x22222222u}, Case{1, 2u}, Case{0x22, 0x3333333344444444ull}}) {
Storage console;
const auto* written = sceAgcAcbEventWrite(&console.buffer, item.eventType, reinterpret_cast<const volatile void*>(item.address));
check(written == console.words.data() && written[0] == 0xc0004600u && written[1] == item.eventType && console.buffer.cursor_up == console.words.data() + 2, "ACB EVENT_WRITE with an address does not match the console's packet");
}
alignas(8) std::uint64_t counters = 0;
for (const auto eventType : {std::uint8_t{0x38}, std::uint8_t{0x39}}) {
expectFailure(storage, [&] { sceAgcAcbEventWrite(&storage.buffer, eventType, &counters); }, "an ACB sample event with an address was accepted");
}
}
}
@@ -50,6 +50,7 @@ void testSystemSoftwareVersion() {
expectFailure([&] { sceAgcDcbGetSystemSoftwareVersion(nullptr, packet.data()); });
expectFailure([&] { sceAgcDcbGetSystemSoftwareVersion(&version, nullptr); });
expectFailure([&] { sceAgcDcbGetSystemSoftwareVersion(reinterpret_cast<std::uint32_t*>(std::uintptr_t{0x10}), packet.data()); });
expectFailure([&] { sceAgcDcbGetSystemSoftwareVersion(&version, reinterpret_cast<const std::uint32_t*>(std::uintptr_t{0x10})); });
for (const auto header : {0x80000000u, 0x3fff1000u, 0x40001000u, 0x00027600u}) {
std::array<std::uint32_t, 3> invalidHeader{header, 0xbeefcafeu, 0};
expectFailure([&] { sceAgcDcbGetSystemSoftwareVersion(&version, invalidHeader.data()); });
@@ -78,6 +79,7 @@ void testDataPacketPayloadAddress() {
expectFailure([&] { sceAgcGetDataPacketPayloadAddress(&addr, nullptr, 1); });
expectFailure([&] { sceAgcGetDataPacketPayloadAddress(reinterpret_cast<std::uint32_t**>(std::uintptr_t{0x10}), packet.data(), 1); });
expectFailure([&] { sceAgcGetDataPacketPayloadAddress_0090(reinterpret_cast<std::uint32_t**>(std::uintptr_t{0x10}), packet.data(), 1); });
expectFailure([&] { sceAgcGetDataPacketPayloadAddress_0090(&addr, reinterpret_cast<std::uint32_t*>(std::uintptr_t{0x10}), 0); });
}
void testDataPacketPayloadRange() {
@@ -98,6 +100,8 @@ void testDataPacketPayloadRange() {
expectFailure([&] { sceAgcGetDataPacketPayloadRange(nullptr, packet.data(), 1); });
expectFailure([&] { sceAgcGetDataPacketPayloadRange(&range, nullptr, 1); });
expectFailure([&] { sceAgcGetDataPacketPayloadRange(reinterpret_cast<SceAgcMemoryRange*>(std::uintptr_t{0x10}), packet.data(), 1); });
expectFailure([&] { sceAgcGetDataPacketPayloadRange(&range, reinterpret_cast<std::uint32_t*>(std::uintptr_t{0x10}), 0); });
expectFailure([&] { sceAgcGetDataPacketPayloadRange(&range, reinterpret_cast<std::uint32_t*>(std::uintptr_t{0x10}), 1); });
}
void testRejections() {
@@ -106,6 +110,7 @@ void testRejections() {
expectFailure([&] { sceAgcGetPacketSize(&word); });
}
expectFailure([] { sceAgcGetPacketSize(nullptr); });
expectFailure([] { sceAgcGetPacketSize(reinterpret_cast<std::uint32_t*>(std::uintptr_t{0x10})); });
std::array<std::uint32_t, 2> words{0x00100000u, 0x000000c0u};
auto* misaligned = reinterpret_cast<std::uint32_t*>(reinterpret_cast<unsigned char*>(words.data()) + 1);
expectFailure([&] { sceAgcGetPacketSize(misaligned); });
@@ -3,6 +3,7 @@
#include "prx/libSceAgc/DcbDraw/include/IndexBuffer.hpp"
#include "prx/libSceAgc/Command/include/Packet.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
@@ -40,6 +41,28 @@ void testSizes() {
check(sceAgcDcbSetBoolPredicationEnableGetSize() == bytes, "bool predication size");
}
void testConsoleArguments() {
struct Case {
std::uint8_t condition;
std::uint8_t operation;
std::uint8_t waitOperation;
std::uintptr_t address;
std::uint32_t count;
std::array<std::uint32_t, 4> words;
};
const std::array<Case, 3> cases{{
{0x11, 0x22, 0x33, 0x44444444u, 0x55555555u, {0xc0022000u, 0x00021100u, 0x44444440u, 0u}},
{1, 2, 3, 4u, 5u, {0xc0022000u, 0x00021100u, 0u, 0u}},
{0x22, 0x44, 0, 0u, 0u, {0xc0022000u, 0x00040000u, 0u, 0u}},
}};
for (const auto& item : cases) {
Storage storage;
const auto* packet = sceAgcDcbSetPredication(&storage.buffer, item.condition, item.operation, item.waitOperation, reinterpret_cast<const volatile void*>(item.address), item.count);
check(packet == storage.words.data() && std::equal(item.words.begin(), item.words.end(), packet), "SET_PREDICATION does not match the console's packet");
check(storage.buffer.cursor_up == storage.words.data() + item.words.size(), "SET_PREDICATION cursor mismatch");
}
}
void testPacket() {
Storage storage;
auto* packet = sceAgcDcbSetIndexCount(&storage.buffer, 7);
@@ -78,6 +101,7 @@ void testRange() {
int main() {
try {
testSizes();
testConsoleArguments();
testPacket();
testRange();
std::puts("agc predication tests passed");
@@ -1,10 +1,13 @@
#include "prx/libSceAgc/Misc/include/StaticBuffer.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "prx/libc/include/GuestArena.hpp"
#ifdef __APPLE__
#include "prx/libSceAgcDriver/Execution/include/Driver/DriverMemory.hpp"
#endif
#include <array>
#include <cerrno>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
@@ -43,6 +46,42 @@ void testBuffers() {
check(slot(0) == fetchShaderTable, "static buffer writes changed slot 0");
}
void testInvalidGuestPointers() {
const auto before = slot(2);
errno = E2BIG;
check(sceAgcSetStaticBuffer(2, nullptr) == InvalidStaticBuffer, "static buffer set accepted a null guest pointer");
check(errno == E2BIG, "a rejected static buffer set changed errno");
check(sceAgcSetStaticBuffer(2, reinterpret_cast<const void*>(0x1)) == InvalidStaticBuffer, "static buffer set accepted an unmapped guest pointer");
check(slot(2) == before, "rejected static buffer set changed slot 2");
std::array<std::uint8_t, 16> out{};
out.fill(0xAA);
errno = E2BIG;
check(sceAgcGetStaticBuffer(2, nullptr) == InvalidStaticBuffer, "static buffer get accepted a null guest pointer");
check(errno == E2BIG, "a rejected static buffer get changed errno");
check(sceAgcGetStaticBuffer(2, reinterpret_cast<void*>(0x1)) == InvalidStaticBuffer, "static buffer get accepted an unmapped guest pointer");
for (std::uint8_t byte : out) check(byte == 0xAA, "rejected static buffer get touched the sentinel output");
std::uint64_t qword = 0xAA;
errno = E2BIG;
check(sceAgcGetStaticQword(0, nullptr) == InvalidStaticBuffer, "static qword get accepted a null guest pointer");
check(errno == E2BIG, "a rejected static qword get changed errno");
check(sceAgcGetStaticQword(0, reinterpret_cast<std::uint64_t*>(0x1)) == InvalidStaticBuffer, "static qword get accepted an unmapped guest pointer");
check(qword == 0xAA, "rejected static qword get touched the sentinel output");
}
void testReadOnlyGuestPages() {
auto* page = static_cast<std::byte*>(GuestArena::GuestArenaAllocate_nid_postfix(65536u, 4096u));
check(page != nullptr, "cannot reserve a read-only guest page fixture");
GuestArena::GuestArenaCommit_nid_postfix(page, 65536u, 0x02, 4096u);
const auto before = slot(1);
errno = E2BIG;
check(sceAgcGetStaticBuffer(1, page) == InvalidStaticBuffer, "static buffer get wrote into a read-only guest page");
check(errno == E2BIG, "a rejected read-only static buffer get changed errno");
GuestArena::GuestArenaReset_nid_postfix(page, 65536u);
GuestAllocations::GuestAllocationsInvalidate_nid_postfix(reinterpret_cast<std::uintptr_t>(page), 65536u);
GuestArena::GuestArenaRelease_nid_postfix(page, 65536u);
check(slot(1) == before, "rejected static buffer get changed slot 1");
}
void testQwords() {
check(sceAgcSetStaticQword(0, 0x0123456789abcdefull) == 0, "writing static qword 0 failed");
check(sceAgcSetStaticQword(3, 0xfedcba9876543210ull) == 0, "writing static qword 3 failed");
@@ -71,6 +110,8 @@ int main() {
#endif
try {
testBuffers();
testInvalidGuestPointers();
testReadOnlyGuestPages();
testQwords();
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
+7 -1
View File
@@ -134,12 +134,17 @@ endforeach()
set(agcMultisampleUploadSpv ${agcTextureDetileGeneratedDir}/MultisampleUpload.spv)
set(agcMultisampleUploadHeader ${agcTextureDetileGeneratedDir}/MultisampleUpload_spv.h)
set(agcMultisampleUploadFragSpv ${agcTextureDetileGeneratedDir}/MultisampleUploadFrag.spv)
set(agcMultisampleUploadFragHeader ${agcTextureDetileGeneratedDir}/MultisampleUploadFrag_spv.h)
add_custom_command(
OUTPUT "${agcMultisampleUploadHeader}"
OUTPUT "${agcMultisampleUploadHeader}" "${agcMultisampleUploadFragHeader}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${agcTextureDetileGeneratedDir}"
COMMAND "$<TARGET_FILE:glslang-standalone>" -V --target-env vulkan1.1 -o "${agcMultisampleUploadSpv}" "${CMAKE_CURRENT_SOURCE_DIR}/Graphics/shaders/MultisampleUpload.comp"
COMMAND ${CMAKE_COMMAND} -DINPUT=${agcMultisampleUploadSpv} -DOUTPUT=${agcMultisampleUploadHeader}
-DSYMBOL=MULTISAMPLE_UPLOAD_SPV -P "${CMAKE_CURRENT_SOURCE_DIR}/embed_spirv.cmake"
COMMAND "$<TARGET_FILE:glslang-standalone>" -V --target-env vulkan1.1 -S frag -DCOLOR_ATTACHMENT_UPLOAD=1 -o "${agcMultisampleUploadFragSpv}" "${CMAKE_CURRENT_SOURCE_DIR}/Graphics/shaders/MultisampleUpload.comp"
COMMAND ${CMAKE_COMMAND} -DINPUT=${agcMultisampleUploadFragSpv} -DOUTPUT=${agcMultisampleUploadFragHeader}
-DSYMBOL=MULTISAMPLE_UPLOAD_FRAG_SPV -P "${CMAKE_CURRENT_SOURCE_DIR}/embed_spirv.cmake"
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/Graphics/shaders/MultisampleUpload.comp" glslang-standalone
VERBATIM
)
@@ -491,6 +496,7 @@ set(agcDriverSources
${agcTextureDetileShaderHeader}
${agcReadbackHeaders}
${agcMultisampleUploadHeader}
${agcMultisampleUploadFragHeader}
${agcCmaskClearShaderHeader}
${agcPackedMergeShaderHeader}
${agcMeshArgumentsShaderHeader}
@@ -2,6 +2,7 @@
#include "prx/libc/include/HostThread.hpp"
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdio>
@@ -71,6 +72,10 @@ public:
return enabled;
}
static void Stop() {
if (auto* trace = current.load(std::memory_order_acquire)) trace->stop();
}
template<typename... TArgs>
static void Log(const char* format, TArgs... args) {
if (!Enabled()) return;
@@ -100,8 +105,12 @@ private:
friend struct CaptureTraceTestAccess;
static CaptureTrace& instance() {
static CaptureTrace trace;
return trace;
static auto* const trace = [] {
static CaptureTrace value;
current.store(&value, std::memory_order_release);
return &value;
}();
return *trace;
}
CaptureTrace() {
@@ -117,12 +126,18 @@ private:
}
~CaptureTrace() {
{
std::lock_guard lock(mutex);
stopping = true;
}
changed.notify_one();
if (worker.joinable()) worker.join();
stop();
}
void stop() {
std::call_once(stopped, [this] {
{
std::lock_guard lock(mutex);
stopping = true;
}
changed.notify_one();
if (worker.joinable()) worker.join();
});
}
void append(std::string line) {
@@ -195,6 +210,8 @@ private:
}
}
inline static std::atomic<CaptureTrace*> current{nullptr};
std::once_flag stopped;
std::ofstream output;
std::mutex mutex;
std::condition_variable changed;
@@ -1,6 +1,7 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRAWINPUTSINPLACE_HPP
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRAWINPUTSINPLACE_HPP
#include <cstddef>
#include <vulkan/vulkan.h>
namespace AgcDriver {
@@ -9,6 +10,10 @@ inline bool DrawInputsInPlaceUsable(VkDriverId driver, bool windows) {
return !windows || driver != VK_DRIVER_ID_NVIDIA_PROPRIETARY;
}
inline std::size_t DrawInputsInPlaceBelow(VkDriverId driver, bool windows) {
return DrawInputsInPlaceUsable(driver, windows) ? 0 : 1024;
}
}
#endif
@@ -39,6 +39,9 @@ extern "C" void AgcDriverReleaseSettled_nid_postfix();
extern "C" bool AgcDriverSettledHeld_nid_postfix();
extern "C" bool AgcDriverSettled_nid_postfix();
extern "C" std::size_t AgcDriverAwaitedWaits_nid_postfix(AgcDriver::AwaitedWait* waits, std::size_t capacity);
extern "C" void AgcDriverTrackRewindTails_nid_postfix();
extern "C" bool AgcDriverRewindTailsUnread_nid_postfix();
extern "C" void AgcDriverCheckFailure_nid_postfix();
extern "C" void AgcDriverWaitForPipelineJournal_nid_postfix();
extern "C" std::uint64_t AgcDriverDispatchesAdoptedAhead_nid_postfix();
extern "C" std::uint64_t AgcDriverDispatchesRejectedAhead_nid_postfix();
@@ -97,7 +97,7 @@ struct DrawEntryCounters {
std::array<std::uint64_t, MaxDispatchVariants> variantHitsByRank{};
double validateUs = 0;
std::uint64_t registerKeyLookups = 0, registerKeyHits = 0, decodeSkipped = 0, decodePartial = 0, facadeMismatches = 0, verifyDecodes = 0, verifyDecodeMismatches = 0;
std::uint64_t registerKeyLookups = 0, registerKeyHits = 0, decodeSkipped = 0, decodePartial = 0, facadeMismatches = 0, verifyDecodes = 0, verifyDecodeMismatches = 0, restartPatchSkipped = 0;
double keyUs = 0;
std::uint64_t absentNewRegisters = 0, absentUserWords = 0, absentEvicted = 0, absentNeverInserted = 0, evictions = 0, byteEvictions = 0;
std::array<std::uint64_t, 6> registerKeyMissChanges{};
@@ -28,6 +28,15 @@ public:
std::uint64_t retired = 0;
std::size_t items = 0;
std::vector<Range> writes;
Watch() = default;
Watch(std::uint64_t retired, std::size_t items) : retired(retired), items(items) {}
Watch(Watch&& other) noexcept : retired(other.retired), items(other.items), writes(std::move(other.writes)), pinned(std::exchange(other.pinned, nullptr)) {}
Watch(const Watch&) = delete;
Watch& operator=(const Watch&) = delete;
~Watch();
private:
friend class DrawPipeline;
DrawPipeline* pinned = nullptr;
};
enum class DrainReason : std::uint8_t { Packet, Flush, Labels, Capture, Indirect, Submission, Count };
enum class QueuedWrite : std::uint8_t { None, Stored, Unknown };
@@ -39,6 +48,7 @@ public:
static bool& Active();
static std::atomic<std::uint64_t>& EpochToken();
static void FollowEpoch(std::uint64_t token);
static void NoteEpochSince(std::uint64_t token, std::uint64_t since);
static unsigned Committers();
void Enqueue(Commit commit, std::vector<Range> writes, std::uint64_t labelAddress = 0, std::vector<std::byte> labelBytes = {}, std::vector<Range> reads = {}, bool draw = false);
@@ -54,8 +64,10 @@ public:
std::size_t Outstanding() const { return outstanding.load(std::memory_order_acquire); }
bool Overlaps(std::uint64_t address, std::size_t bytes);
bool OverlapsAny(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges);
static bool CountedWatch();
std::uint64_t CountedLookups() const { return countedLookups.load(std::memory_order_relaxed); }
Watch WatchWrites();
bool WrittenSince(const Watch& watch, const std::vector<Range>& reads);
bool WrittenSince(Watch& watch, const std::vector<Range>& reads);
std::uint64_t Retired() const { return retiredItems.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); }
@@ -85,6 +97,8 @@ private:
void rethrowFailure();
void report(std::chrono::steady_clock::time_point now);
void countWrites(const std::vector<Range>& writes, bool added);
void releaseWatch(Watch& watch);
void unpinWatch(Watch& watch);
std::mutex mutex;
std::condition_variable wake;
@@ -92,6 +106,9 @@ private:
std::deque<Item> items;
std::vector<std::pair<Range, std::uint32_t>> queuedWrites;
std::vector<Item> retired;
std::uint64_t reclaimedItems = 0;
std::size_t watchers = 0;
std::atomic<std::uint64_t> countedLookups{0};
std::exception_ptr failure;
std::atomic<std::size_t> outstanding{0};
std::atomic<std::uint64_t> retiredItems{0};
@@ -0,0 +1,51 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_RELOCATIONRUNS_HPP
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_DRAW_RELOCATIONRUNS_HPP
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <span>
#include <utility>
namespace AgcDriver::DriverDetail {
template <typename Emit>
void ForEachRelocationRun(std::uint64_t address, std::size_t words, std::span<const std::pair<std::uint64_t, std::int32_t>> reads, std::uint64_t relocatable, Emit&& emit) {
if (words == 0) return;
auto read = std::lower_bound(reads.begin(), reads.end(), std::make_pair(address, std::numeric_limits<std::int32_t>::min()));
std::size_t start = 0;
std::size_t taggedEnd = 0;
std::int8_t current = -1;
const auto append = [&](std::size_t end) {
if (start != end) emit(start, end, current);
start = end;
};
while (read != reads.end()) {
const auto [at, origin] = *read;
do { ++read; } while (read != reads.end() && read->first == at);
const auto distance = at - address;
if (distance / sizeof(std::uint32_t) >= words) break;
if (distance % sizeof(std::uint32_t) != 0 || origin < 0 || origin >= 64 || (relocatable >> origin & 1u) == 0) continue;
const auto word = static_cast<std::size_t>(distance / sizeof(std::uint32_t));
if (word > taggedEnd && current != -1) {
append(taggedEnd);
current = -1;
}
const auto next = static_cast<std::int8_t>(origin);
if (next != current) {
append(word);
current = next;
}
taggedEnd = word + 1;
}
if (current != -1 && taggedEnd < words) {
append(taggedEnd);
current = -1;
}
append(words);
}
}
#endif
@@ -79,6 +79,8 @@ public:
std::uint64_t FlipSubmissions() const;
std::uint64_t RewindTailFlips() const;
std::vector<AwaitedWait> AwaitedWaits();
void TrackRewindTails();
bool RewindTailsUnread();
void WaitForPipelineJournal();
bool WaitIdleFor(std::chrono::milliseconds timeout);
bool WaitIdleUnlessTitleWaitsFor(std::chrono::milliseconds timeout);
@@ -253,7 +255,7 @@ private:
static std::chrono::steady_clock::time_point& packetStartedAt();
static PendingDrawPhases& pendingDrawPhases();
void addDrawPhases(const std::array<double, DrawDriverPhaseCount>& ms, bool drawn, std::uint64_t captures);
void noteLabelStore(std::uint64_t address, std::span<const std::byte> bytes, std::uint64_t stamp, std::uint32_t queue);
void noteLabelStore(std::uint64_t address, std::span<const std::byte> bytes, std::uint64_t stamp, std::uint32_t queue, bool ordered = true);
void noteLabelPass(std::span<const std::uint32_t> packet, std::uint32_t queue);
void noteLabelIssue(std::span<const std::uint32_t> packet, std::uint32_t queue);
void retireLabelTakes(std::uint32_t queue, std::uint64_t received);
@@ -393,7 +395,13 @@ private:
static Graphics::Recorder::LateStatistics& lateCountsSeen();
static EpochBumps& epochBumps();
static void bumpEpoch(std::uint64_t EpochBumps::*counter);
static void bumpWaitEpoch(std::uint64_t address, std::size_t bytes);
static void bumpEpochSince(std::uint64_t EpochBumps::*counter, std::uint64_t since);
static void raiseEpochSince(std::uint64_t since);
static void publishReadPoint();
static std::uint32_t& epochQueue();
static std::uint64_t queueEpochSince(std::uint32_t queue);
std::uint64_t storeOrderingSince(std::span<const std::uint32_t> packet, std::uint64_t address, std::size_t bytes, std::uint64_t received, std::uint32_t queue);
static void bumpWaitEpoch(std::uint64_t address, std::size_t bytes, std::uint64_t since = 0);
static std::chrono::steady_clock::time_point& lastEpochBump();
static std::deque<const std::uint32_t*>& releasedTails();
void noteReleasedTails(const Submission& submission);
@@ -447,6 +455,10 @@ private:
std::atomic<std::uint64_t> shape{0};
};
std::array<AwaitedSlot, SubmissionQueueEnd - 0x20 + 1> awaitedSlots{};
std::atomic<bool> tracksTails{false};
std::mutex tailsMutex;
std::vector<std::pair<std::uint32_t, const std::uint32_t*>> unreadTails;
void noteTailRead(const std::uint32_t* read, std::uint32_t queue, const std::uint32_t* next);
static bool stillAwaited(const AwaitedSlot& slot, std::uint64_t awaited);
void noteWaitFields(std::uint32_t queue, std::span<const std::uint32_t> packet);
std::atomic<bool> captureHold{false};
@@ -17,8 +17,10 @@ inline constexpr std::chrono::microseconds PollTryInterval{1000};
struct LabelStore {
std::uint64_t stamp = 0;
std::uint64_t generation = 0;
std::uint32_t value = 0;
std::uint32_t queue = 0xffffffffu;
bool ordered = true;
};
struct WriteRecord {
@@ -4,6 +4,7 @@
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <limits>
#include <span>
namespace AgcDriver {
@@ -15,7 +16,11 @@ struct FrameDumpIoFailure {
};
inline FrameDumpIoFailure WriteBmpStream_nid_no_patch(std::FILE* file, std::uint32_t width, std::uint32_t height, std::span<const std::byte> pixels) noexcept {
const std::uint32_t imageBytes = width * height * 4;
if (width == 0 || height == 0 || width > std::numeric_limits<std::int32_t>::max() || height > std::numeric_limits<std::int32_t>::max()) return {"dimensions", EINVAL};
const auto pixelBytes = static_cast<std::uint64_t>(width) * height * 4;
if (pixelBytes > std::numeric_limits<std::uint32_t>::max() - 54) return {"dimensions", EOVERFLOW};
if (pixels.size() != pixelBytes) return {"pixels", EINVAL};
const auto imageBytes = static_cast<std::uint32_t>(pixelBytes);
const std::uint32_t header[13] = {0, 0, 54, 40, width, static_cast<std::uint32_t>(-static_cast<std::int32_t>(height)), 1u | (32u << 16u), 0, imageBytes, 2835, 2835, 0, 0};
const std::uint16_t magic = 0x4d42;
const std::uint32_t fileBytes = 54 + imageBytes;
@@ -77,6 +77,9 @@ using FreshCollectHook = bool (*)(std::uintptr_t address, std::size_t bytes, voi
void SetFreshCollectHook(FreshCollectHook hook);
#endif
bool Watched(std::uint64_t address, std::size_t bytes);
bool OnlyRewatchedSince(std::uint64_t address, std::size_t bytes, std::uint64_t generation);
bool Rewatched(std::uint64_t address, std::size_t bytes);
void RewatchedBlocks(std::uint64_t address, std::size_t bytes, std::span<const std::uint64_t> since, std::span<std::uint8_t> rewatched);
std::uint64_t CollectWrites(std::uint64_t address, std::size_t bytes);
struct WriteSubscription;
bool WriteIndexEnabled();
@@ -153,8 +156,15 @@ bool StoredAllSince_nid_no_patch(std::uint64_t address, std::size_t bytes, std::
// for every collect: nothing is reused without an ordering point. APS5_PACKET_EPOCH=1 makes the
// workers bump before every packet as before. CollectEpochBumps counts the bumps ([guestmem] line).
void BumpCollectEpoch();
void BumpCollectEpochSince(std::uint64_t since);
void RaiseCollectSince(std::uint64_t since);
void ShareCollectWalks(bool share);
bool CollectWalksShared();
std::uint64_t CollectSince();
std::uint64_t SteadyNanoseconds();
void AdoptLatestCollectEpoch();
std::uint64_t ProofSerial();
std::uint64_t OwnProofBreaks();
void BreakProofs();
void MarkProofThread();
std::uint64_t CollectEpoch();
@@ -228,7 +228,7 @@ inline Registers BuildInitialContextRegisters() {
{0x105, 0}, {0x106, 0}, {0x107, 0}, {0x108, 0},
{0x10b, 0}, {0x10c, 0}, {0x10d, 0},
{0x1b1, 0}, {0x1b3, 0}, {0x1b4, 0}, {0x1b6, 0}, {0x1c3, 0}, {0x1c4, 0}, {0x1c5, 0},
{0x1ff, 0}, {0x280, 0x00080008}, {0x281, 0xffff0000}, {0x292, 2}, {0x293, 0}, {0x29b, 0},
{0x1ff, 0}, {0x280, 0x00080008}, {0x281, 0xffff0000}, {0x282, 0x00000008}, {0x292, 2}, {0x293, 0}, {0x29b, 0},
{0x2ce, 0}, {0x2d3, 0}, {0x2d5, 0}, {0x2d6, 0}, {0x2db, 0},
{0x2dc, 0xaa00}, {0x2df, 0}, {0x2e4, 0}, {0x2f8, 0}, {0x2f9, 0x2d},
{0x30e, 0xffffffff}, {0x30f, 0xffffffff}, {0x313, 0x6000},
@@ -17,6 +17,10 @@ inline bool LdsLockFencesRequired(VkDriverId driver) {
return driver == VK_DRIVER_ID_MOLTENVK;
}
inline bool DeviceAtomicWorkgroupMemoryBarriersRequired(VkDriverId driver) {
return driver == VK_DRIVER_ID_AMD_PROPRIETARY;
}
}
#endif
@@ -123,10 +123,10 @@ bool OverlapsLabel(std::span<const ShaderRecompiler::MemoryRegion> regions, cons
void Driver::resolveGroupAhead(const Submission& submission, const QueueState& live, std::size_t from) {
static const bool allQueues = std::getenv("APS5_GROUP_CAPTURE_ALL_QUEUES") != nullptr;
if (!allQueues && submission.queue == 0) return;
if (submission.queue == 0 && DrawPipeline::Depth() != 0 && DrawPipeline::Queue0().Busy()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, (submission.commands[from] >> 8u) & 0xffu);
auto& resolved = resolvedAhead();
const auto localDevice = device.Load();
if (resolved.contains(from) || localDevice == nullptr) return;
if (submission.queue == 0 && DrawPipeline::Depth() != 0 && DrawPipeline::Queue0().Busy()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, (submission.commands[from] >> 8u) & 0xffu);
auto& stats = groupCaptureStats();
const auto begin = std::chrono::steady_clock::now();
++stats.runs;
@@ -132,6 +132,7 @@ struct DrawTail {
DrawPhaseTiming phaseTiming{false, phaseMs, phaseLap};
Pm4::DrawParameters drawParameters{};
Pm4::DrawParameters resolvedParameters{};
std::vector<DrawUserPatch> userPatches;
bool pipelined = false;
bool traceIndirect = false;
std::uint64_t dumpTarget = 0;
@@ -423,7 +424,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
auto& dataEntry = tail.dataEntry;
auto& shapeKey = tail.shapeKey;
std::uint64_t drawIdentity = 0, drawAlias = 0;
std::vector<DrawUserPatch> userPatches;
auto& userPatches = tail.userPatches;
if (registerKey) {
const auto keyStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
std::shared_ptr<const DrawRelocation> relocation;
@@ -639,7 +640,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
if (program.binary.stage == Stage::Fragment || roles[i] == Role::GeometryBack) return;
vertexInfos[i] = DecodeOrderedVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, decodeReads[i], 8u - program.firstUserSgpr);
if (vertexInfos[i]) {
vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, readRegister(queue.context, 0x207), program.tailContinuation.get()) | graphics.layerExports;
vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, readRegister(queue.context, 0x207), program.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports;
vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode;
Graphics::ApplyPointSize(graphics, *vertexInfos[i]);
}
@@ -901,7 +902,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
decodeReads[i].clear();
vertexInfos[i] = Graphics::DecodeVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, &decodeReads[i], false, 8u - program.firstUserSgpr);
if (vertexInfos[i]) {
vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, tail.reg207, program.tailContinuation.get()) | graphics.layerExports;
vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, tail.reg207, program.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports;
vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode;
Graphics::ApplyPointSize(graphics, *vertexInfos[i]);
}
@@ -1467,6 +1468,16 @@ void Driver::restartFinishedDraw(DrawTail& tail) {
program.snapshot = std::move(snapshot);
}
}
if (tail.drawHit && !tail.userPatches.empty()) {
if (verifyDrawRecipe()) {
std::lock_guard cacheLock(drawCacheMutex);
++drawEntryCounters.restartPatchSkipped;
} else {
auto patched = std::make_shared<DrawDecode>(*tail.decode);
for (const auto& patch : tail.userPatches) patched->programs[patch.program].userData[patch.index] = patch.value;
tail.decode = std::move(patched);
}
}
const auto& programs = *tail.programs;
const auto& graphics = tail.decode->state;
const auto& roles = tail.decode->roles;
@@ -1498,7 +1509,7 @@ void Driver::restartFinishedDraw(DrawTail& tail) {
if (program.binary.stage == Stage::Fragment || roles[i] == Role::GeometryBack) continue;
tail.vertexInfos[i] = DecodeOrderedVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, tail.decodeReads[i], 8u - program.firstUserSgpr);
if (!tail.vertexInfos[i]) continue;
tail.vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, tail.reg207, program.tailContinuation.get()) | graphics.layerExports;
tail.vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, tail.reg207, program.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports;
tail.vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode;
Graphics::ApplyPointSize(graphics, *tail.vertexInfos[i]);
}
@@ -61,7 +61,7 @@ std::size_t Driver::drawCacheEntries() {
static const std::size_t entries = [] {
const char* text = std::getenv("APS5_DRAW_CACHE_ENTRIES");
const auto parsed = text != nullptr ? std::strtoull(text, nullptr, 10) : 0ull;
return parsed != 0 ? static_cast<std::size_t>(parsed) : std::size_t{4096};
return parsed != 0 ? static_cast<std::size_t>(parsed) : std::size_t{65536};
}();
return entries;
}
@@ -2,6 +2,7 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include <algorithm>
#include <array>
@@ -41,11 +42,12 @@ ShaderRecompiler::ShaderVertexStageInfo DecodeOrderedVertexStageInfo(std::span<c
};
if (!DrawPipeline::Active()) return decode();
auto& queue = DrawPipeline::Queue0();
const auto watch = queue.WatchWrites();
auto watch = queue.WatchWrites();
auto info = decode();
if (watch.items == 0 && !queue.Busy() && queue.Retired() == watch.retired) return info;
std::vector<DrawPipeline::Range> ranges;
ranges.reserve(reads.size());
struct RangesStorage {};
auto& ranges = HostThreadLocal<std::vector<DrawPipeline::Range>, RangesStorage>();
ranges.clear();
for (const auto& read : reads) ranges.emplace_back(read.address, read.address + read.size);
if (!queue.WrittenSince(watch, ranges)) return info;
queue.NoteDecodeDrain();
@@ -205,6 +207,7 @@ std::shared_ptr<DrawDecode> Driver::decodeDraw(const QueueState& queue, const Su
}
product->pixel = Graphics::DecodePixelStageInfo(queue.context, Graphics::ExportMappings(product->state), Graphics::PixelProgramSkipped(queue), fragmentHeader);
Graphics::NormalizeUnusedViewportDepth(product->state, product->pixel);
Graphics::ApplyViewportIndex(context, product->state);
Graphics::ApplyDepthRemap(context, product->state);
Graphics::ApplyDepthBoundsEmulation(context, product->state, product->pixel);
static const bool readOnlyDepthBoundsCompare = [] {
@@ -291,11 +291,35 @@ std::atomic<std::uint64_t>& DrawPipeline::EpochToken() {
return token;
}
namespace {
struct EpochSince {
std::atomic<std::uint64_t> token{0};
std::atomic<std::uint64_t> since{0};
};
std::array<EpochSince, 4096>& epochSinces() {
static std::array<EpochSince, 4096> sinces;
return sinces;
}
}
void DrawPipeline::NoteEpochSince(std::uint64_t token, std::uint64_t since) {
auto& slot = epochSinces()[token % epochSinces().size()];
slot.token.store(0, std::memory_order_relaxed);
slot.since.store(since, std::memory_order_relaxed);
slot.token.store(token, std::memory_order_release);
}
void DrawPipeline::FollowEpoch(std::uint64_t token) {
static thread_local std::uint64_t followed = 0;
if (followed == token) return;
followed = token;
GuestMemory::BumpCollectEpoch();
const auto& slot = epochSinces()[token % epochSinces().size()];
const bool noted = slot.token.load(std::memory_order_acquire) == token;
const auto since = slot.since.load(std::memory_order_relaxed);
GuestMemory::BumpCollectEpochSince(noted && slot.token.load(std::memory_order_acquire) == token ? since : 0);
}
unsigned DrawPipeline::Committers() {
@@ -348,7 +372,10 @@ void DrawPipeline::enqueue(Item item) {
const ClearOnExit<Item> clearReclaim{reclaim};
const auto lockStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
std::unique_lock lock(mutex);
if (!retired.empty()) std::swap(retired, reclaim);
if (!retired.empty() && watchers == 0) {
reclaimedItems += retired.size();
std::swap(retired, reclaim);
}
if (profile) lockWaitNs += elapsedNs(lockStart);
rethrowFailure();
if (closing) {
@@ -508,6 +535,7 @@ void DrawPipeline::ReleaseRetired() {
std::vector<Item> done;
std::lock_guard lock(mutex);
std::swap(done, retired);
reclaimedItems += done.size();
}
void DrawPipeline::Drain(DrainReason reason, std::uint32_t opcode) {
@@ -617,26 +645,78 @@ void DrawPipeline::countWrites(const std::vector<Range>& writes, bool added) {
}
}
DrawPipeline::Watch DrawPipeline::WatchWrites() {
if (!Busy()) return {Retired(), 0, {}};
bool DrawPipeline::CountedWatch() {
static const bool counted = std::getenv("APS5_NO_DECODE_WATCH_COUNTS") == nullptr;
return counted;
}
DrawPipeline::Watch::~Watch() {
if (pinned != nullptr) pinned->releaseWatch(*this);
}
void DrawPipeline::unpinWatch(Watch& watch) {
if (watch.pinned == nullptr) return;
--watchers;
watch.pinned = nullptr;
}
void DrawPipeline::releaseWatch(Watch& watch) {
std::lock_guard lock(mutex);
Watch watch{retiredItems.load(std::memory_order_relaxed), items.size(), {}};
unpinWatch(watch);
}
DrawPipeline::Watch DrawPipeline::WatchWrites() {
if (!Busy()) return Watch{Retired(), 0};
std::lock_guard lock(mutex);
Watch watch{retiredItems.load(std::memory_order_relaxed), items.size()};
if (CountedWatch()) {
if (watch.items != 0) {
++watchers;
watch.pinned = this;
}
return watch;
}
for (const auto& item : items) watch.writes.insert(watch.writes.end(), item.writes.begin(), item.writes.end());
return watch;
}
bool DrawPipeline::WrittenSince(const Watch& watch, const std::vector<Range>& reads) {
const auto overlaps = [&reads](const std::vector<Range>& writes) {
return std::any_of(reads.begin(), reads.end(), [&writes](const Range& read) {
return std::any_of(writes.begin(), writes.end(), [&read](const Range& write) { return read.first < write.second && write.first < read.second; });
});
bool DrawPipeline::WrittenSince(Watch& watch, const std::vector<Range>& reads) {
auto hullBegin = std::numeric_limits<std::uint64_t>::max();
std::uint64_t hullEnd = 0;
for (const auto& read : reads) {
hullBegin = std::min(hullBegin, read.first);
hullEnd = std::max(hullEnd, read.second);
}
const auto overlaps = [&](const std::vector<Range>& writes) {
for (const auto& write : writes) {
if (write.second <= hullBegin || hullEnd <= write.first) continue;
if (std::any_of(reads.begin(), reads.end(), [&write](const Range& read) { return read.first < write.second && write.first < read.second; })) return true;
}
return false;
};
if (DrawFinisher::Overlap() && DrawFinisher::Get().PendingOverlapsAny(reads)) return true;
if (DrawFinisher::Overlap() && DrawFinisher::Get().PendingOverlapsAny(reads)) {
releaseWatch(watch);
return true;
}
std::lock_guard lock(mutex);
struct Unpin {
DrawPipeline& queue;
Watch& watch;
~Unpin() { queue.unpinWatch(watch); }
} unpin{*this, watch};
if (std::any_of(items.begin(), items.end(), [&](const Item& item) { return overlaps(item.writes); })) return true;
const auto retiredNow = retiredItems.load(std::memory_order_relaxed);
if (retiredNow == watch.retired) return false;
return retiredNow - watch.retired > watch.items || overlaps(watch.writes);
const auto since = retiredNow - watch.retired;
if (since > watch.items) return true;
if (watch.pinned == nullptr) return overlaps(watch.writes);
if (watch.retired < reclaimedItems || watch.retired - reclaimedItems + since > retired.size()) return true;
countedLookups.fetch_add(1, std::memory_order_relaxed);
const auto first = static_cast<std::size_t>(watch.retired - reclaimedItems);
for (std::size_t index = first; index < first + static_cast<std::size_t>(since); ++index) {
if (overlaps(retired[index].writes)) return true;
}
return false;
}
bool DrawPipeline::Busy() const {
@@ -110,9 +110,11 @@ std::optional<DrawVerdict> Driver::precheckDraw(const QueueState& queue, const S
traceIndirect = traceIndirectEnabled;
if (traceIndirect && drawParameters.indirect) std::fprintf(stderr, "[draw] indirect packet %s args 0x%llx count %u reached\n", Pm4::Name(packet[0]).c_str(), static_cast<unsigned long long>(drawParameters.indirect->arguments), drawParameters.indirect->count);
{
const auto colorControl = queue.context.find(0x202);
const bool colorDisabled = colorControl != queue.context.end() && ((colorControl->second >> 4u) & 7u) == 0u;
const auto targetMask = queue.context.find(0x8e);
const auto shaderMask = queue.context.find(0x8f);
const bool colorWrites = targetMask != queue.context.end() && shaderMask != queue.context.end() && Graphics::ColorWriteMask(queue.context) != 0;
const bool colorWrites = !colorDisabled && targetMask != queue.context.end() && shaderMask != queue.context.end() && Graphics::ColorWriteMask(queue.context) != 0;
if (!colorWrites && !queue.shader.contains(0x8)) {
const auto word = [&](std::uint32_t offset) { const auto it = queue.context.find(offset); return it == queue.context.end() ? 0u : it->second; };
if ((word(0x200) & 3u) == 0 || ((word(0x010) & 3u) == 0 && (word(0x011) & 1u) == 0)) return DrawVerdict::Nothing;
@@ -254,6 +254,9 @@ bool Driver::sameDecode(const DrawDecode& a, const DrawDecode& b) {
}
if (s.colorRop != t.colorRop || s.hasColorTarget != t.hasColorTarget || s.rectList != t.rectList || s.rasterizerDiscard != t.rasterizerDiscard || s.renderExtent.width != t.renderExtent.width || s.renderExtent.height != t.renderExtent.height || s.topology != t.topology || s.negativeOneToOne != t.negativeOneToOne || s.depthClamp != t.depthClamp || s.conservativeRasterization != t.conservativeRasterization || s.perSampleShading != t.perSampleShading || s.cullMode != t.cullMode || s.polygonMode != t.polygonMode || s.lineWidth != t.lineWidth || s.frontFace != t.frontFace || !sameBlend(s.blend, t.blend) || s.blendConstants != t.blendConstants) return false;
if (std::memcmp(&s.viewport, &t.viewport, sizeof(VkViewport)) != 0 || std::memcmp(&s.scissor, &t.scissor, sizeof(VkRect2D)) != 0) return false;
if (s.viewportExports != t.viewportExports || s.extraViewports.size() != t.extraViewports.size() || s.viewportScissors.size() != t.viewportScissors.size()) return false;
if (!s.extraViewports.empty() && std::memcmp(s.extraViewports.data(), t.extraViewports.data(), s.extraViewports.size() * sizeof(VkViewport)) != 0) return false;
if (!s.viewportScissors.empty() && std::memcmp(s.viewportScissors.data(), t.viewportScissors.data(), s.viewportScissors.size() * sizeof(VkRect2D)) != 0) return false;
const auto& p = a.pixel;
const auto& q = b.pixel;
if (p.interpolatorCount != q.interpolatorCount || p.interpolatorSettings != q.interpolatorSettings || p.wave32 != q.wave32 || p.inputAddr != q.inputAddr || p.hasPerspectiveCenterVgpr != q.hasPerspectiveCenterVgpr || p.perspectiveCentroid != q.perspectiveCentroid || p.posX != q.posX || p.posY != q.posY || p.posZ != q.posZ || p.posW != q.posW || p.frontFace != q.frontFace || p.frontFaceAllBits != q.frontFaceAllBits || p.ancillary != q.ancillary || p.sampleShading != q.sampleShading || p.noPerspective != q.noPerspective || p.linearCentroid != q.linearCentroid || p.pixelKillEnable != q.pixelKillEnable || p.depthExportEnable != q.depthExportEnable || p.depthExportMin != q.depthExportMin || p.depthExportMax != q.depthExportMax || p.sampleMaskExportEnable != q.sampleMaskExportEnable || p.earlyZ != q.earlyZ || p.executeOnNoop != q.executeOnNoop || p.conservativeZExport != q.conservativeZExport || p.orderedPixelShader != q.orderedPixelShader || p.stencilRefExportEnable != q.stencilRefExportEnable || p.stencilOperationValueExport != q.stencilOperationValueExport || p.targetOutputMode != q.targetOutputMode || p.targetExportMapping != q.targetExportMapping) return false;
@@ -1,6 +1,7 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
#include "ControlFlow/GraphBuilder.hpp"
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/RelocationRuns.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp"
@@ -158,11 +159,6 @@ void Driver::tagVariantRuns(DispatchVariant& variant, std::span<const ShaderReco
if (reads[i].second >= 0 && ((reads[i].first & 3u) != 0 || !covered(reads[i].first))) drop(reads[i].second);
}
}
const auto origin = [&](std::uint64_t address) -> std::int8_t {
const auto found = std::lower_bound(reads.begin(), reads.end(), std::make_pair(address, std::numeric_limits<std::int32_t>::min()));
if (found == reads.end() || found->first != address || found->second < 0) return -1;
return (relocatable >> found->second & 1u) != 0 ? static_cast<std::int8_t>(found->second) : std::int8_t {-1};
};
variant.relocatableWords = relocatable;
for (std::size_t index = 0; index < regions.size(); ++index) {
const auto& region = regions[index];
@@ -175,17 +171,11 @@ void Driver::tagVariantRuns(DispatchVariant& variant, std::span<const ShaderReco
variant.runs.emplace_back(region.guestAddress, region.guestAddress + region.bytes.size());
continue;
}
std::size_t start = 0;
auto current = count != 0 ? origin(region.guestAddress) : std::int8_t {-1};
for (std::size_t word = 1; word <= count; ++word) {
const auto next = word < count ? origin(region.guestAddress + word * sizeof(std::uint32_t)) : std::int8_t {-2};
if (next == current) continue;
AppendSharedWords(variant.shared, variant.runs.size(), offset + start, region.bytes.subspan(start * sizeof(std::uint32_t), (word - start) * sizeof(std::uint32_t)), supplied);
variant.runs.emplace_back(region.guestAddress + start * sizeof(std::uint32_t), region.guestAddress + word * sizeof(std::uint32_t));
variant.runBases.push_back(current);
start = word;
current = next;
}
ForEachRelocationRun(region.guestAddress, count, reads, relocatable, [&](std::size_t first, std::size_t last, std::int8_t origin) {
AppendSharedWords(variant.shared, variant.runs.size(), offset + first, region.bytes.subspan(first * sizeof(std::uint32_t), (last - first) * sizeof(std::uint32_t)), supplied);
variant.runs.emplace_back(region.guestAddress + first * sizeof(std::uint32_t), region.guestAddress + last * sizeof(std::uint32_t));
variant.runBases.push_back(origin);
});
}
}
@@ -169,6 +169,18 @@ extern "C" std::size_t AgcDriverAwaitedWaits_nid_postfix(AgcDriver::AwaitedWait*
return count;
}
extern "C" void AgcDriverTrackRewindTails_nid_postfix() {
AgcDriver::DriverDetail::Driver::Get().TrackRewindTails();
}
extern "C" bool AgcDriverRewindTailsUnread_nid_postfix() {
return AgcDriver::DriverDetail::Driver::Get().RewindTailsUnread();
}
extern "C" void AgcDriverCheckFailure_nid_postfix() {
AgcDriver::DriverDetail::Driver::Get().CheckFailure();
}
extern "C" void AgcDriverWaitForPipelineJournal_nid_postfix() {
AgcDriver::DriverDetail::Driver::Get().WaitForPipelineJournal();
}
@@ -1,4 +1,5 @@
#include "prx/libSceAgcDriver/Execution/include/AsyncLog.hpp"
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
#include "prx/libc/include/HostThread.hpp"
#include "prx/libSceAgcDriver/Graphics/include/PipelineJournal.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
@@ -211,6 +212,7 @@ void Driver::stop() {
PerformanceTrace::StopOutput();
FlushAsyncLogAtEnd_nid_no_patch();
StopProfileOutput_nid_no_patch();
CaptureTrace::Stop();
stopped = true;
}
@@ -395,6 +397,10 @@ void Driver::ReportFailure(std::exception_ptr error) {
first = !failure;
if (first) failure = error;
failed.store(true, std::memory_order_release);
{
std::lock_guard tails(tailsMutex);
unreadTails.clear();
}
for (const auto& [handle, output] : outputs) output->Fail(failure);
for (auto& [queue, worker] : workers) {
for (const auto& item : worker.pending) {
@@ -208,7 +208,7 @@ bool Driver::copyBuffer(QueueState& queue, std::uint32_t queueId, std::span<cons
};
std::size_t bytes = 0;
if (table) {
Graphics::FinishLeaseWork();
Graphics::FinishLeaseWrites();
const auto tableAddress = base(0);
const bool tableAccessible = GuestMemory::Accessible(reinterpret_cast<const void*>(tableAddress), 32);
bool published = false;
@@ -237,7 +237,7 @@ bool Driver::copyBuffer(QueueState& queue, std::uint32_t queueId, std::span<cons
}
bytes = range->bytes;
} else if (indexed) {
Graphics::FinishLeaseWork();
Graphics::FinishLeaseWrites();
const bool recordAccessible = GuestMemory::Accessible(reinterpret_cast<const void*>(record), 12);
bool published = false;
@@ -268,9 +268,13 @@ void Driver::execute(Submission& submission) {
auto& packetCounters = PacketCounters::ThisThread();
static const bool epochEach = std::getenv("APS5_SUBMISSION_EPOCH_EACH") != nullptr;
const bool orderedAtSubmit = submission.rewindTail == nullptr && submission.enqueuedAt != std::chrono::steady_clock::time_point{};
const auto submittedAt = orderedAtSubmit ? static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(submission.enqueuedAt.time_since_epoch()).count()) : 0;
if (epochEach || submission.enqueuedAt == std::chrono::steady_clock::time_point{} || submission.enqueuedAt > lastEpochBump()) {
if (!epochEach) noteReleasedTails(submission);
bumpEpoch(&EpochBumps::submissions);
bumpEpochSince(&EpochBumps::submissions, submittedAt);
} else {
raiseEpochSince(submittedAt);
}
clearResolvedAhead();
gateOpened() = true;
@@ -338,7 +342,7 @@ void Driver::execute(Submission& submission) {
continue;
}
if (!DrawPipeline::Queue0().Overlaps(awaited, awaitedBytes) && Pm4::WaitSatisfiedUnchecked(packet) && !OwnStoreRejects(packet, awaited, awaitedBytes, submission.queue)) {
bumpWaitEpoch(awaited, awaitedBytes);
bumpWaitEpoch(awaited, awaitedBytes, storeOrderingSince(packet, awaited, awaitedBytes, submission.received, submission.queue));
++waitOutcomes().atEntry;
gateOpened() = true;
noteLabelPass(packet, submission.queue);
@@ -360,7 +364,9 @@ void Driver::execute(Submission& submission) {
if (predicated) {
landPendingWaits(submission.queue);
recordQueuedLabelsBeforeRead(submission.queue);
if (!Pm4::PredicationPasses(queue)) {
const bool passes = Pm4::PredicationPasses(queue);
publishReadPoint();
if (!passes) {
cursor = opcode == 0x3f ? submission.conditionalEnds.at(cursor) : nextCursor;
continue;
}
@@ -491,10 +497,7 @@ void Driver::execute(Submission& submission) {
currentPacketOffset() = cursor;
if (gateOpened()) {
gateOpened() = false;
if (!pipelineDispatch() || submission.queue != 0) {
if (pipelined && DrawPipeline::Queue0().Busy()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, opcode);
timed(&WorkerProfile::dispatchMs, [&] { resolveGroupAhead(submission, queue, cursor); });
}
if (!pipelineDispatch() || submission.queue != 0) timed(&WorkerProfile::dispatchMs, [&] { resolveGroupAhead(submission, queue, cursor); });
}
const bool ringOverlap = submission.queue != 0 && Graphics::Recorder::DispatchOverlapEnabled();
if (ringOverlap) Graphics::Recorder::SetDispatchOrder(submission.queue + 1u, ringOrder.afterDispatch);
@@ -199,7 +199,7 @@ bool Driver::preparePacketMemory(const Submission& submission, QueueState& queue
recordDeferredLabels(localDevice.get(), submission.queue);
const auto stamp = ++eventSerial;
const auto reason = localDevice != nullptr ? localDevice->WriteLabelOnGpu(store->address, bytes, stamp, submission.queue) : 4;
if (reason == 0 || reason == 1 || reason == 5) noteLabelStore(store->address, bytes, stamp, submission.queue);
if (reason == 0 || reason == 1 || reason == 5) noteLabelStore(store->address, bytes, stamp, submission.queue, false);
if (reason == 0 || reason == 5) {
if (reason == 0) ++storesOnGpu;
else ++storesBehindCompletions;
@@ -470,13 +470,13 @@ void Driver::commitStore(std::uint32_t queue, std::uint64_t address, std::span<c
reason = localDevice->WriteLabelOnGpu(address, bytes, stamp, queue);
}
if (reason == 0 || reason == 5 || reason == 6) {
noteLabelStore(address, bytes, stamp, queue);
noteLabelStore(address, bytes, stamp, queue, false);
if (reason == 0) ++storesOnGpu;
else ++storesBehindCompletions;
} else {
if (reason != 1 && localDevice != nullptr) localDevice->WaitIdle();
GuestMemory::Write(address, bytes, 1);
noteLabelStore(address, bytes, stamp != 0 ? stamp : ++eventSerial, queue);
noteLabelStore(address, bytes, stamp != 0 ? stamp : ++eventSerial, queue, false);
++storesOnCpu;
}
Graphics::Recorder::CloseLabelGroup(GuestMemory::TrackerGeneration());
@@ -154,6 +154,7 @@ void Driver::reapCompletionLabels() {
void Driver::run(std::uint32_t id) noexcept {
onWorkerThread() = true;
epochQueue() = id;
char role[32];
std::snprintf(role, sizeof role, "queue worker 0x%x", id);
PinWorkerThread(role);
@@ -291,7 +292,8 @@ void Driver::run(std::uint32_t id) noexcept {
OrderHold hold{orderHolders};
const auto released = [&] { return failure || stopping || orderReleased(id, submission.received); };
StallWatch stall(id);
while (!released() && !poll(released)) stall.Check("order behind queue 0 for event", submission.received, &lock);
const auto wake = [&](const auto& done) { return changed.wait_for(lock, std::chrono::microseconds(200), done); };
while (!released() && !wake(released)) stall.Check("order behind queue 0 for event", submission.received, &lock);
}
rethrowFailure();
}
@@ -22,6 +22,7 @@
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <optional>
@@ -730,6 +731,7 @@ void Driver::executeRewindTail(const Submission& stalled) {
tail.enqueuedAt = std::chrono::steady_clock::now();
}
copyCommands(tail, stalled.rewindTail, stalled.rewindWords);
noteTailRead(stalled.rewindTail, tail.queue, tail.rewindTail);
if (APS5_ENABLE_TIMING_LOG) tail.copiedAt = std::chrono::steady_clock::now();
validate(tail, stalled.rewindTail);
readRegisterLists(tail);
@@ -864,6 +866,7 @@ void Driver::Submit(const Packet* packet, std::uint32_t queue, bool cpuFlip) {
lastFlipWork = submission.flipWork;
}
if (!submission.flips.empty()) ++flipSubmissionsOfThread();
if (submission.rewindTail != nullptr) noteTailRead(nullptr, queue, submission.rewindTail);
enqueue(std::move(submission));
++accepted;
}
@@ -963,6 +966,40 @@ bool Driver::orderReleased(std::uint32_t queue, std::uint64_t received) const {
return runningWorkers.load(std::memory_order_acquire) == 0 && !completionsPending() && !Graphics::Recorder::SnapshotWriteOverlaps(awaited, 4);
}
void Driver::TrackRewindTails() {
tracksTails.store(true, std::memory_order_relaxed);
}
void Driver::noteTailRead(const std::uint32_t* read, std::uint32_t queue, const std::uint32_t* next) {
if (!tracksTails.load(std::memory_order_relaxed)) return;
std::lock_guard lock(tailsMutex);
if (read != nullptr) {
if (const auto copied = std::ranges::find(unreadTails, std::pair{queue, read}); copied != unreadTails.end()) unreadTails.erase(copied);
}
if (next != nullptr) unreadTails.emplace_back(queue, next);
}
bool Driver::RewindTailsUnread() {
CheckFailure();
std::lock_guard lock(tailsMutex);
return std::ranges::any_of(unreadTails, [&](const auto& tail) {
const auto [queue, words] = tail;
if ((std::atomic_ref<std::uint32_t>(*const_cast<std::uint32_t*>(words - 1)).load(std::memory_order_acquire) & Pm4::RewindValid) == 0) return false;
const auto& slot = awaitedSlots[queue == 0 ? 0 : queue - 0x20 + 1];
const auto awaited = slot.address.load(std::memory_order_acquire);
if (awaited == 0 || awaited == reinterpret_cast<std::uint64_t>(words - 1) || !awaitsTitle(awaited)) return true;
const auto shape = slot.shape.load(std::memory_order_relaxed);
const auto reference = slot.reference.load(std::memory_order_relaxed);
const auto mask = slot.mask.load(std::memory_order_relaxed);
if (slot.address.load(std::memory_order_acquire) != awaited) return true;
const auto bytes = static_cast<std::uint32_t>(shape >> 32u);
if (bytes == 0) return (std::atomic_ref<std::uint32_t>(*reinterpret_cast<std::uint32_t*>(awaited)).load(std::memory_order_acquire) & Pm4::RewindValid) != 0;
std::uint64_t value = 0;
std::memcpy(&value, reinterpret_cast<const void*>(awaited), bytes == 8 ? 8 : 4);
return Pm4::WaitCompares(static_cast<std::uint32_t>(shape), reference, mask, value);
});
}
void Driver::noteWaitFields(std::uint32_t queue, std::span<const std::uint32_t> packet) {
const auto fields = Pm4::DecodeWait(packet);
auto& slot = awaitedSlots[queue == 0 ? 0 : queue - 0x20 + 1];
@@ -2329,7 +2329,7 @@ std::vector<PreparedGraphicsStage> PrepareGraphicsStages(const DrawDecode& decod
continue;
}
if (vertex) {
vertex->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, decoded.state.paClVsOutCntl, program.tailContinuation.get()) | decoded.state.layerExports;
vertex->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, decoded.state.paClVsOutCntl, program.tailContinuation.get()) | decoded.state.layerExports | decoded.state.viewportExports;
vertex->depthRemapMode = decoded.state.depthRemap.mode;
Graphics::ApplyPointSize(decoded.state, *vertex);
}
@@ -1,6 +1,7 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp"
#include "prx/libSceAgcDriver/Execution/include/Mutex.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include <algorithm>
#include <cstdlib>
#include <cstring>
@@ -8,14 +9,17 @@
namespace AgcDriver::DriverDetail {
void Driver::noteLabelStore(std::uint64_t address, std::span<const std::byte> bytes, std::uint64_t stamp, std::uint32_t queue) {
void Driver::noteLabelStore(std::uint64_t address, std::span<const std::byte> bytes, std::uint64_t stamp, std::uint32_t queue, bool ordered) {
if (!KeepsLabelStore(address, bytes.size())) return;
const auto generation = GuestMemory::TrackerGeneration();
std::lock_guard lock(labelStoresMutex);
for (std::size_t offset = 0; offset < bytes.size(); offset += 4) {
auto& history = labelStores[address + offset];
std::shift_right(history.begin(), history.end(), 1);
history[0].stamp = stamp;
history[0].queue = queue;
history[0].generation = generation;
history[0].ordered = ordered;
std::memcpy(&history[0].value, bytes.data() + offset, 4);
}
}
@@ -101,6 +105,35 @@ bool Driver::findWaitProducer(std::uint64_t address, std::size_t bytes, std::uin
return found;
}
std::uint64_t Driver::storeOrderingSince(std::span<const std::uint32_t> packet, std::uint64_t address, std::size_t bytes, std::uint64_t received, std::uint32_t queue) {
if (!GuestMemory::CollectWalksShared()) return 0;
std::uint32_t writer = queue;
std::uint64_t generation = 0;
{
std::lock_guard lock(labelStoresMutex);
const auto low = labelStores.find(address);
if (low == labelStores.end()) return 0;
const auto high = bytes == 8 ? labelStores.find(address + 4) : labelStores.end();
if (bytes == 8 && high == labelStores.end()) return 0;
const LabelStore* matched = nullptr;
for (std::size_t index = 0; index < low->second.size(); ++index) {
const auto& store = low->second[index];
if (store.stamp <= received || !store.ordered || store.generation == 0) return 0;
if (bytes == 8 && high->second[index].stamp != store.stamp) return 0;
const std::uint64_t value = store.value | (bytes == 8 ? static_cast<std::uint64_t>(high->second[index].value) << 32u : 0u);
if (Pm4::WaitComparesValue(packet, value)) {
matched = &store;
break;
}
}
if (matched == nullptr) return 0;
writer = matched->queue;
generation = matched->generation;
}
if (!GuestMemory::UnchangedSinceCollected(address, bytes, generation)) return 0;
return writer == queue ? GuestMemory::CollectSince() : queueEpochSince(writer);
}
bool Driver::storedSince(std::span<const std::uint32_t> packet, std::uint64_t address, std::size_t bytes, std::uint64_t received, std::uint32_t queue, std::uint32_t* writer) {
std::lock_guard lock(labelStoresMutex);
const auto low = labelStores.find(address);
@@ -136,13 +136,24 @@ void Driver::waitMemory(std::span<const std::uint32_t> packet, std::uint32_t que
bool warned = false;
struct EpochPoint {
Driver* driver;
std::uint32_t queue;
std::uint64_t address;
std::size_t bytes;
std::span<const std::uint32_t> packet;
std::uint64_t received;
bool inherit = true;
bool bump = true;
std::uint64_t since = 0;
~EpochPoint() {
if (bump) bumpWaitEpoch(address, bytes);
if (bump && since == 0 && inherit) since = driver->storeOrderingSince(packet, address, bytes, received, queue);
if (bump) bumpWaitEpoch(address, bytes, since);
}
} epochPoint{awaited, awaitedBytes};
} epochPoint{this, queue, awaited, awaitedBytes, packet, received, !requireMemory};
const auto orderedBy = [&](std::uint32_t writer) {
if (writer == queue) epochPoint.bump = false;
else epochPoint.since = storeOrderingSince(packet, awaited, awaitedBytes, received, queue);
};
bool ownStoreUnlanded = false;
const auto memorySatisfied = [&] {
ownStoreUnlanded = false;
@@ -151,22 +162,25 @@ void Driver::waitMemory(std::span<const std::uint32_t> packet, std::uint32_t que
ownStoreUnlanded = true;
return false;
};
const auto storedByOwnLabel = [&] {
const auto orderByStore = [&] {
std::uint32_t writer = queue;
return !requireMemory && storedSince(packet, awaited, awaitedBytes, received, queue, &writer) && writer == queue;
if (!requireMemory && storedSince(packet, awaited, awaitedBytes, received, queue, &writer)) orderedBy(writer);
};
GuestMemory::CheckRange(reinterpret_cast<const void*>(awaited), awaitedBytes, awaitedBytes);
if (traceGpu) std::fprintf(stderr, "[gpu] %.1f queue 0x%x waits 0x%llx == 0x%x (now 0x%x)\n", TraceMs(), queue, static_cast<unsigned long long>(awaited), packet[4],
*reinterpret_cast<const volatile std::uint32_t*>(awaited));
if (memorySatisfied()) {
++outcomes.atEntry;
if (storedByOwnLabel()) epochPoint.bump = false;
orderByStore();
return;
}
if (heldAtSubmit) {
epochPoint.inherit = false;
return;
}
if (heldAtSubmit) return;
if (std::uint32_t writer = queue; !requireMemory && storedSince(packet, awaited, awaitedBytes, received, queue, &writer)) {
if (writer != queue) notePendingWait(packet, queue, received);
else epochPoint.bump = false;
orderedBy(writer);
return;
}
@@ -193,6 +207,7 @@ void Driver::waitMemory(std::span<const std::uint32_t> packet, std::uint32_t que
return false;
}
if (hit->late) {
epochPoint.inherit = false;
if (hit->generation == refusedGeneration) return false;
if (!GuestMemory::UnchangedSinceCollected(awaited, awaitedBytes, hit->generation)) {
++outcomes.lateRefusedCpuStore;
@@ -210,6 +225,7 @@ void Driver::waitMemory(std::span<const std::uint32_t> packet, std::uint32_t que
if (!hit->late) epochPoint.bump = false;
} else {
notePendingWait(packet, queue, received);
if (!hit->late) epochPoint.since = storeOrderingSince(packet, awaited, awaitedBytes, received, queue);
}
return true;
};
@@ -364,7 +380,7 @@ void Driver::waitMemory(std::span<const std::uint32_t> packet, std::uint32_t que
while (!memorySatisfied()) {
if (std::uint32_t writer = queue; !requireMemory && storedSince(packet, awaited, awaitedBytes, received, queue, &writer)) {
if (writer != queue) notePendingWait(packet, queue, received);
else epochPoint.bump = false;
orderedBy(writer);
return;
}
++polls;
@@ -441,7 +457,7 @@ void Driver::waitMemory(std::span<const std::uint32_t> packet, std::uint32_t que
}
}
++outcomes.polled;
if (storedByOwnLabel()) epochPoint.bump = false;
orderByStore();
}
}
@@ -1,7 +1,12 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp"
#include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include <array>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <unordered_map>
@@ -33,13 +38,78 @@ std::chrono::steady_clock::time_point& Driver::lastEpochBump() {
}
void Driver::bumpEpoch(std::uint64_t EpochBumps::*counter) {
lastEpochBump() = std::chrono::steady_clock::now();
GuestMemory::BumpCollectEpoch();
if (DrawPipeline::Active()) DrawPipeline::EpochToken().fetch_add(1, std::memory_order_relaxed);
++(epochBumps().*counter);
bumpEpochSince(counter, 0);
}
void Driver::bumpWaitEpoch(std::uint64_t address, std::size_t bytes) {
namespace {
std::array<std::atomic<std::uint64_t>, 64>& queueSinces() {
static std::array<std::atomic<std::uint64_t>, 64> sinces{};
return sinces;
}
std::size_t queueSinceSlot(std::uint32_t queue) {
return queue == 0 ? 0 : queue >= 0x20 && queue < 0x20 + 63 ? queue - 0x20 + 1 : 64;
}
void publishQueuePoint(std::uint32_t queue, std::uint64_t point) {
const auto slot = queueSinceSlot(queue);
if (slot >= queueSinces().size()) return;
auto& published = queueSinces()[slot];
auto current = published.load(std::memory_order_relaxed);
while (current < point && !published.compare_exchange_weak(current, point, std::memory_order_release, std::memory_order_relaxed)) {}
}
void publishQueueSince(std::uint32_t queue) {
publishQueuePoint(queue, GuestMemory::CollectSince());
}
}
void Driver::publishReadPoint() {
publishQueuePoint(epochQueue(), GuestMemory::SteadyNanoseconds());
}
std::uint32_t& Driver::epochQueue() {
static thread_local std::uint32_t queue = 0xffffffffu;
return queue;
}
std::uint64_t Driver::queueEpochSince(std::uint32_t queue) {
const auto slot = queueSinceSlot(queue);
return slot < queueSinces().size() ? queueSinces()[slot].load(std::memory_order_acquire) : 0;
}
void Driver::bumpEpochSince(std::uint64_t EpochBumps::*counter, std::uint64_t since) {
lastEpochBump() = std::chrono::steady_clock::now();
GuestMemory::ShareCollectWalks(!Graphics::RuntimeSwitches::Set(Graphics::RuntimeSwitch::NoSharedCollectWalks));
GuestMemory::BumpCollectEpochSince(since);
if (DrawPipeline::Active()) DrawPipeline::NoteEpochSince(DrawPipeline::EpochToken().fetch_add(1, std::memory_order_relaxed) + 1, GuestMemory::CollectSince());
publishQueueSince(epochQueue());
++(epochBumps().*counter);
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
if (!profile) return;
struct Lags {
std::uint64_t bumps = 0, now = 0, lagNs = 0;
std::chrono::steady_clock::time_point reported = std::chrono::steady_clock::now();
};
static thread_local Lags lags;
++lags.bumps;
if (since == 0) ++lags.now;
else lags.lagNs += GuestMemory::SteadyNanoseconds() - GuestMemory::CollectSince();
if (std::chrono::steady_clock::now() - lags.reported < std::chrono::seconds(10)) return;
AgcDriver::ProfilePrint_nid_no_patch("[epoch] queue 0x%x (10 s): %llu ordering points, %llu at the bump, the rest %.2f ms earlier on average\n", epochQueue(), static_cast<unsigned long long>(lags.bumps), static_cast<unsigned long long>(lags.now), lags.bumps > lags.now ? static_cast<double>(lags.lagNs) / 1e6 / static_cast<double>(lags.bumps - lags.now) : 0.0);
lags = Lags{};
}
void Driver::raiseEpochSince(std::uint64_t since) {
const auto before = GuestMemory::CollectSince();
GuestMemory::RaiseCollectSince(since);
publishQueueSince(epochQueue());
if (GuestMemory::CollectSince() != before && DrawPipeline::Active() && !Graphics::RuntimeSwitches::Set(Graphics::RuntimeSwitch::NoSharedCollectWalks)) DrawPipeline::NoteEpochSince(DrawPipeline::EpochToken().fetch_add(1, std::memory_order_relaxed) + 1, GuestMemory::CollectSince());
}
void Driver::bumpWaitEpoch(std::uint64_t address, std::size_t bytes, std::uint64_t since) {
struct Ordered {
std::uint64_t value = 0;
std::uint64_t generation = 0;
@@ -48,7 +118,7 @@ void Driver::bumpWaitEpoch(std::uint64_t address, std::size_t bytes) {
auto& ordered = HostThreadLocal<std::unordered_map<std::uint64_t, Ordered>, OrderedStorage>();
static const bool memo = std::getenv("APS5_NO_ORDERED_WAITS") == nullptr;
if (!GuestMemory::Accessible(reinterpret_cast<const void*>(address), bytes)) {
bumpEpoch(&EpochBumps::waits);
bumpEpochSince(&EpochBumps::waits, since);
return;
}
const auto generation = memo ? GuestMemory::CollectWritesUncached(address, bytes) : 0;
@@ -60,7 +130,7 @@ void Driver::bumpWaitEpoch(std::uint64_t address, std::size_t bytes) {
return;
}
}
bumpEpoch(&EpochBumps::waits);
bumpEpochSince(&EpochBumps::waits, since);
if (generation == 0) return;
if (ordered.size() >= 4096) ordered.clear();
ordered[address] = {value, generation};
@@ -322,6 +322,8 @@ void raiseForgetSlot(std::atomic<std::uint64_t>& slot, std::uint64_t serial) {
}
std::atomic<std::uint64_t> forgetBytes{0};
std::atomic<std::uint64_t> collectMemoHits{0};
std::atomic<std::uint64_t> sharedWalkHits{0};
std::atomic<bool> sharedCollectWalks{std::getenv("APS5_NO_SHARED_COLLECT_WALKS") == nullptr};
std::atomic<std::uint64_t> collectEpochBumps{0};
std::atomic<std::uint64_t> unwatchSerial{0};
// Walks that reported at least one written page (the ones the probe pass used to double), and the
@@ -570,7 +572,7 @@ public:
for (std::size_t i = 0; i < MemoryCounterCount; ++i) {
AgcDriver::ProfilePrint_nid_no_patch(" %s %llu calls %.0f MiB %.1f s", MemoryCounterNames[i], static_cast<unsigned long long>(totals[i][0]), totals[i][1] / 1048576.0, totals[i][2] / 1e9);
}
AgcDriver::ProfilePrint_nid_no_patch(" collect-memo hits %llu, collect epochs %llu", static_cast<unsigned long long>(collectMemoHits.load()), static_cast<unsigned long long>(collectEpochBumps.load()));
AgcDriver::ProfilePrint_nid_no_patch(" collect-memo hits %llu (%llu from other threads' walks), collect epochs %llu", static_cast<unsigned long long>(collectMemoHits.load()), static_cast<unsigned long long>(sharedWalkHits.load()), static_cast<unsigned long long>(collectEpochBumps.load()));
AgcDriver::ProfilePrint_nid_no_patch(" collect-dirty %llu tracker waits %llu / %llu", static_cast<unsigned long long>(collectDirty.load()), static_cast<unsigned long long>(trackerWaits.load()), static_cast<unsigned long long>(trackerAcquisitions.load()));
AgcDriver::ProfilePrint_nid_no_patch(" | arena 0x%llx+0x%llx image 0x%llx+0x%llx forgets %llu (%.0f MiB)", static_cast<unsigned long long>(PagesBase()), static_cast<unsigned long long>(PagesSize()), static_cast<unsigned long long>(ImagePagesBase()), static_cast<unsigned long long>(ImagePagesSize()), static_cast<unsigned long long>(forgetCalls.load()), forgetBytes.load() / 1048576.0);
{
@@ -1380,24 +1382,33 @@ struct WriteTracker {
struct ObservationLeaf {
std::array<std::atomic<std::uint64_t>, LeafBlocks> ticks{};
std::array<std::atomic<std::uint64_t>, LeafBlocks / CoarseBlocks> coarse{};
std::array<std::atomic<std::uint64_t>, LeafBlocks> times{};
std::array<std::atomic<std::uint64_t>, LeafBlocks / CoarseBlocks> coarseTimes{};
};
std::unique_ptr<std::atomic<ObservationLeaf*>[]> observationLeaves;
std::size_t observationLeafCount = 0;
std::atomic<const std::atomic<ObservationLeaf*>*> observationTable{nullptr};
std::atomic<std::uint64_t> observationFloor{0};
std::atomic<std::uint64_t> observationTimeFloor{0};
std::atomic<std::uint64_t> observationUnwatched{std::numeric_limits<std::uint64_t>::max()};
std::atomic<std::uint64_t> observationMapping{std::numeric_limits<std::uint64_t>::max()};
struct ExactObservation {
std::uint64_t first = 0;
std::uint64_t stop = 0;
std::uint64_t tick = 0;
std::uint64_t time = 0;
};
std::array<ExactObservation, 16> exactObservations{};
std::size_t nextExactObservation = 0;
bool exactlyObserved(std::uint64_t first, std::uint64_t stop, std::uint64_t need) const {
bool exactlyObserved(std::uint64_t first, std::uint64_t stop, std::uint64_t need, std::uint64_t timeNeed, bool& hitByTime) const {
for (const auto& entry : exactObservations) {
if (entry.tick >= need && entry.first <= first && stop <= entry.stop) return true;
if (entry.first > first || stop > entry.stop) continue;
if (entry.tick >= need) return true;
if (timeNeed != 0 && entry.time > timeNeed) {
hitByTime = true;
return true;
}
}
return false;
}
@@ -1437,12 +1448,20 @@ struct WriteTracker {
return leaf != nullptr ? leaf->ticks[block % LeafBlocks].load(std::memory_order_relaxed) : 0;
}
bool observedSince(std::uint64_t first, std::uint64_t stop, std::uint64_t epoch, std::uint64_t unwatched, std::uint64_t mapping) const {
std::uint64_t observedTime(std::uint64_t block) const {
if (block / LeafBlocks >= observationLeafCount) return 0;
const auto* leaf = observationLeaves[block / LeafBlocks].load(std::memory_order_relaxed);
return leaf != nullptr ? leaf->times[block % LeafBlocks].load(std::memory_order_relaxed) : 0;
}
bool observedSince(std::uint64_t first, std::uint64_t stop, std::uint64_t epoch, std::uint64_t since, std::uint64_t unwatched, std::uint64_t mapping) const {
const auto* table = observationTable.load(std::memory_order_acquire);
if (table == nullptr || observationUnwatched.load(std::memory_order_acquire) != unwatched || observationMapping.load(std::memory_order_acquire) != mapping) return false;
if (!inObservationRange(first, stop)) return false;
const auto need = std::max(epoch, observationFloor.load(std::memory_order_acquire));
const auto timeNeed = since != 0 ? std::max(since, observationTimeFloor.load(std::memory_order_acquire)) : 0;
const auto last = blockOf(stop - 1);
bool fromSharedTime = false;
auto block = blockOf(first);
while (block <= last) {
const auto index = block / LeafBlocks;
@@ -1452,18 +1471,31 @@ struct WriteTracker {
const auto end = std::min<std::uint64_t>(last + 1, (index + 1) * LeafBlocks);
while (block < end) {
if (block % CoarseBlocks == 0 && block + CoarseBlocks <= end) {
if (leaf->coarse[(block % LeafBlocks) / CoarseBlocks].load(std::memory_order_acquire) < need) return false;
block += CoarseBlocks;
continue;
const auto group = (block % LeafBlocks) / CoarseBlocks;
if (leaf->coarse[group].load(std::memory_order_acquire) >= need) {
block += CoarseBlocks;
continue;
}
if (timeNeed == 0) return false;
if (leaf->coarseTimes[group].load(std::memory_order_acquire) > timeNeed) {
fromSharedTime = true;
block += CoarseBlocks;
continue;
}
}
const auto slot = block % LeafBlocks;
if (leaf->ticks[slot].load(std::memory_order_acquire) < need) {
if (timeNeed == 0 || leaf->times[slot].load(std::memory_order_acquire) <= timeNeed) return false;
fromSharedTime = true;
}
if (leaf->ticks[block % LeafBlocks].load(std::memory_order_acquire) < need) return false;
++block;
}
}
if (fromSharedTime) sharedWalkHits.fetch_add(1, std::memory_order_relaxed);
return true;
}
void publishObserved(std::uint64_t first, std::uint64_t last, std::uint64_t tick) {
void publishObserved(std::uint64_t first, std::uint64_t last, std::uint64_t tick, std::uint64_t walkStarted) {
for (auto block = first; block <= last;) {
const auto index = block / LeafBlocks;
auto* leaf = observationLeaves[index].load(std::memory_order_relaxed);
@@ -1473,13 +1505,21 @@ struct WriteTracker {
}
const auto end = std::min<std::uint64_t>(last + 1, (index + 1) * LeafBlocks);
for (auto at = block; at < end; ++at) {
auto& slot = leaf->ticks[at % LeafBlocks];
if (slot.load(std::memory_order_relaxed) < tick) slot.store(tick, std::memory_order_release);
const auto slot = at % LeafBlocks;
auto& tickSlot = leaf->ticks[slot];
if (tickSlot.load(std::memory_order_relaxed) < tick) tickSlot.store(tick, std::memory_order_release);
auto& timeSlot = leaf->times[slot];
if (timeSlot.load(std::memory_order_relaxed) < walkStarted) timeSlot.store(walkStarted, std::memory_order_release);
}
for (auto group = (block % LeafBlocks) / CoarseBlocks; group <= ((end - 1) % LeafBlocks) / CoarseBlocks; ++group) {
std::uint64_t least = std::numeric_limits<std::uint64_t>::max();
for (std::size_t at = group * CoarseBlocks; at < (group + 1) * CoarseBlocks; ++at) least = std::min(least, leaf->ticks[at].load(std::memory_order_relaxed));
leaf->coarse[group].store(least, std::memory_order_release);
std::uint64_t leastTick = std::numeric_limits<std::uint64_t>::max();
std::uint64_t leastTime = std::numeric_limits<std::uint64_t>::max();
for (std::size_t at = group * CoarseBlocks; at < (group + 1) * CoarseBlocks; ++at) {
leastTick = std::min(leastTick, leaf->ticks[at].load(std::memory_order_relaxed));
leastTime = std::min(leastTime, leaf->times[at].load(std::memory_order_relaxed));
}
leaf->coarse[group].store(leastTick, std::memory_order_release);
leaf->coarseTimes[group].store(leastTime, std::memory_order_release);
}
block = end;
}
@@ -1566,6 +1606,8 @@ struct WriteTracker {
}
};
std::unordered_map<std::uint64_t, DriverPieces> driverPieces;
std::unordered_map<std::uint64_t, std::uint64_t> rewatchStamps;
std::atomic<bool> anyRewatchStamp{false};
struct CpuPages {
std::array<std::uint64_t, WritePagesPerBlock> pages{};
@@ -1942,6 +1984,7 @@ struct ThreadCollectMemo {
void syncObservationContext(WriteTracker& tracker, std::uint64_t unwatched, std::uint64_t mapping) {
if (tracker.observationUnwatched.load(std::memory_order_relaxed) == unwatched && tracker.observationMapping.load(std::memory_order_relaxed) == mapping) return;
tracker.observationFloor.store(nextCollectEpoch.fetch_add(1, std::memory_order_acq_rel) + 1, std::memory_order_release);
tracker.observationTimeFloor.store(SteadyNanoseconds(), std::memory_order_release);
tracker.observationUnwatched.store(unwatched, std::memory_order_release);
tracker.observationMapping.store(mapping, std::memory_order_release);
}
@@ -2066,6 +2109,8 @@ bool walkWrites(WriteTracker& tracker, std::uint64_t first, std::uint64_t stop,
return complete;
}
struct CollectSinceSlot {};
Observation observe(std::uint64_t address, std::size_t bytes, bool memoized) {
using Status = Observation::Status;
if (bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address) return {Status::Uncovered, 0};
@@ -2076,7 +2121,8 @@ Observation observe(std::uint64_t address, std::size_t bytes, bool memoized) {
if (stop <= first) return {Status::Uncovered, 0};
const auto epoch = currentCollectEpoch();
const bool shared = memoized && collectMemoEnabled() && HostThreadSlot<std::uint64_t, CollectEpochSlot>::Get() != 0;
if (shared && tracker.observedSince(first, stop, epoch, unwatchSerial.load(std::memory_order_acquire), GuestAllocations::GuestAllocationsGeneration_nid_postfix())) {
const auto since = shared && sharedCollectWalks.load(std::memory_order_relaxed) ? HostThreadSlot<std::uint64_t, CollectSinceSlot>::Get() : 0;
if (shared && tracker.observedSince(first, stop, epoch, since, unwatchSerial.load(std::memory_order_acquire), GuestAllocations::GuestAllocationsGeneration_nid_postfix())) {
collectMemoHits.fetch_add(1, std::memory_order_relaxed);
return {Status::Complete, tracker.stable.load(std::memory_order_acquire)};
}
@@ -2093,20 +2139,23 @@ Observation observe(std::uint64_t address, std::size_t bytes, bool memoized) {
struct RunSlot {};
auto& runs = ThreadScratch<std::vector<Run>, RunSlot>();
runs.clear();
bool hitByTime = false;
if (!shared) runs.push_back({first, stop, false});
else {
const auto need = std::max(epoch, tracker.observationFloor.load(std::memory_order_relaxed));
const auto timeNeed = since != 0 ? std::max(since, tracker.observationTimeFloor.load(std::memory_order_relaxed)) : 0;
const auto lastBlock = tracker.blockOf(stop - 1);
const auto addRun = [&](std::uint64_t from, std::uint64_t to) {
const auto begin = tracker.blockBegin(from);
const auto end = tracker.blockBegin(to + 1);
if (tracker.covers(begin, static_cast<std::size_t>(end - begin))) runs.push_back({begin, end, false});
else if (!tracker.exactlyObserved(std::max(first, begin), std::min(stop, end), need)) runs.push_back({std::max(first, begin), std::min(stop, end), true});
else if (!tracker.exactlyObserved(std::max(first, begin), std::min(stop, end), need, timeNeed, hitByTime)) runs.push_back({std::max(first, begin), std::min(stop, end), true});
};
bool open = false;
std::uint64_t from = 0;
for (auto block = tracker.blockOf(first); block <= lastBlock; ++block) {
if (tracker.observedTick(block) < need) {
const bool satisfied = tracker.observedTick(block) >= need || (timeNeed != 0 && tracker.observedTime(block) > timeNeed && (hitByTime = true));
if (!satisfied) {
if (!open) from = block;
open = true;
} else if (open) {
@@ -2116,9 +2165,13 @@ Observation observe(std::uint64_t address, std::size_t bytes, bool memoized) {
}
if (open) addRun(from, lastBlock);
}
if (runs.empty()) collectMemoHits.fetch_add(1, std::memory_order_relaxed);
if (runs.empty()) {
collectMemoHits.fetch_add(1, std::memory_order_relaxed);
if (hitByTime) sharedWalkHits.fetch_add(1, std::memory_order_relaxed);
}
std::optional<TimedAccess> timed;
if (!runs.empty()) timed.emplace(CounterCollect, bytes);
const auto walkStarted = !runs.empty() ? SteadyNanoseconds() : 0;
std::size_t done = 0;
auto status = Status::Complete;
for (auto& run : runs) {
@@ -2135,7 +2188,7 @@ Observation observe(std::uint64_t address, std::size_t bytes, bool memoized) {
#endif
break;
}
if (shared && run.exact) tracker.exactObservations[tracker.nextExactObservation++ % tracker.exactObservations.size()] = {run.first, run.stop, tick};
if (shared && run.exact) tracker.exactObservations[tracker.nextExactObservation++ % tracker.exactObservations.size()] = {run.first, run.stop, tick, walkStarted};
++done;
}
lock.Stabilize();
@@ -2145,7 +2198,7 @@ Observation observe(std::uint64_t address, std::size_t bytes, bool memoized) {
auto from = tracker.blockOf(runs[index].first);
if (tracker.blockBegin(from) < runs[index].first) ++from;
const auto end = tracker.blockOf(runs[index].stop);
if (end > from) tracker.publishObserved(from, end - 1, tick);
if (end > from) tracker.publishObserved(from, end - 1, tick, walkStarted);
}
if (status != Status::Complete) return {status, 0};
return {Status::Complete, generation};
@@ -2241,7 +2294,37 @@ std::uint64_t CollectWrittenBlocks(std::uint64_t address, std::size_t bytes, std
return tracker.generation.load(std::memory_order_relaxed);
}
std::uint64_t SteadyNanoseconds() {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count());
}
void ShareCollectWalks(bool share) {
if (sharedCollectWalks.load(std::memory_order_relaxed) != share) sharedCollectWalks.store(share, std::memory_order_relaxed);
}
bool CollectWalksShared() {
return sharedCollectWalks.load(std::memory_order_relaxed);
}
std::uint64_t CollectSince() {
return HostThreadSlot<std::uint64_t, CollectSinceSlot>::Get();
}
void RaiseCollectSince(std::uint64_t since) {
const auto now = SteadyNanoseconds();
const auto raised = since == 0 ? now : std::min(since, now);
if (raised > HostThreadSlot<std::uint64_t, CollectSinceSlot>::Get()) HostThreadSlot<std::uint64_t, CollectSinceSlot>::Set(raised);
}
void BumpCollectEpochSince(std::uint64_t since) {
const auto now = SteadyNanoseconds();
const auto previous = HostThreadSlot<std::uint64_t, CollectSinceSlot>::Get();
BumpCollectEpoch();
HostThreadSlot<std::uint64_t, CollectSinceSlot>::Set(since == 0 ? now : std::max(previous, std::min(since, now)));
}
void BumpCollectEpoch() {
HostThreadSlot<std::uint64_t, CollectSinceSlot>::Set(SteadyNanoseconds());
const auto epoch = nextCollectEpoch.fetch_add(1, std::memory_order_acq_rel) + 1;
HostThreadSlot<std::uint64_t, CollectEpochSlot>::Set(epoch);
auto last = lastBumpedEpoch.load(std::memory_order_relaxed);
@@ -2269,14 +2352,20 @@ std::uint64_t CollectEpochBumps() {
namespace {
std::atomic<std::uint64_t> proofSerial{1};
thread_local bool proofThread = false;
struct OwnProofBreaksSlot {};
}
std::uint64_t ProofSerial() {
return proofSerial.load(std::memory_order_acquire);
}
std::uint64_t OwnProofBreaks() {
return HostThreadSlot<std::uint64_t, OwnProofBreaksSlot>::Get();
}
void BreakProofs() {
proofSerial.fetch_add(1, std::memory_order_acq_rel);
HostThreadSlot<std::uint64_t, OwnProofBreaksSlot>::Set(OwnProofBreaks() + 1);
}
void MarkProofThread() {
@@ -2331,6 +2420,9 @@ void unwatchLocked(WriteTracker& tracker, std::uint64_t address, std::size_t byt
unwatchSerial.fetch_add(1, std::memory_order_release);
bumpSubscriptions(address, bytes, WriteBumpSource::Unwatch);
}
if (bytes != 0 && !tracker.rewatchStamps.empty()) {
for (auto block = tracker.blockOf(address); block <= tracker.blockOf(address + bytes - 1); ++block) tracker.rewatchStamps.erase(block);
}
#else
if (GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(reinterpret_cast<const void*>(address), bytes)) {
unwatchSerial.fetch_add(1, std::memory_order_release);
@@ -2410,6 +2502,8 @@ void Rewatch(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges) {
for (auto block = tracker.blockOf(begin); block <= tracker.blockOf(end - 1); ++block) {
tracker.driverPieces.erase(block);
tracker.stamp(block, tracker.generation, StampKind::Cpu);
tracker.rewatchStamps[block] = tracker.stampOf(block);
tracker.anyRewatchStamp.store(true, std::memory_order_release);
}
restored = true;
}
@@ -2520,6 +2614,60 @@ bool WriteWatched() {
return tracker.watched;
}
bool OnlyRewatchedSince(std::uint64_t address, std::size_t bytes, std::uint64_t generation) {
if (bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address || generation == 0) return false;
auto& tracker = Tracker();
if (!tracker.anyRewatchStamp.load(std::memory_order_acquire)) return false;
const auto lock = lockTracker(tracker);
tracker.initialize();
if (!tracker.watched || !tracker.covers(address, bytes)) return false;
bool rewatched = false;
for (auto block = tracker.blockOf(address); block <= tracker.blockOf(address + bytes - 1); ++block) {
const auto stamp = tracker.stampOf(block);
if (stamp <= generation) continue;
const auto found = tracker.rewatchStamps.find(block);
if (found == tracker.rewatchStamps.end() || found->second != stamp) return false;
rewatched = true;
}
return rewatched;
}
bool Rewatched(std::uint64_t address, std::size_t bytes) {
if (bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address) return false;
auto& tracker = Tracker();
if (!tracker.anyRewatchStamp.load(std::memory_order_acquire)) return false;
const auto lock = lockTracker(tracker);
tracker.initialize();
if (!tracker.watched || !tracker.covers(address, bytes)) return false;
for (auto block = tracker.blockOf(address); block <= tracker.blockOf(address + bytes - 1); ++block) {
if (tracker.rewatchStamps.contains(block)) return true;
}
return false;
}
void RewatchedBlocks(std::uint64_t address, std::size_t bytes, std::span<const std::uint64_t> since, std::span<std::uint8_t> rewatched) {
std::fill(rewatched.begin(), rewatched.end(), std::uint8_t{0});
if (bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address) return;
auto& tracker = Tracker();
if (!tracker.anyRewatchStamp.load(std::memory_order_acquire)) return;
const auto lock = lockTracker(tracker);
tracker.initialize();
if (!tracker.watched) return;
const auto end = address + bytes;
const auto first = tracker.blockOf(address);
for (auto block = first; block <= tracker.blockOf(end - 1); ++block) {
const auto k = static_cast<std::size_t>(block - first);
if (k >= since.size() || k >= rewatched.size()) break;
const auto found = tracker.rewatchStamps.find(block);
if (found == tracker.rewatchStamps.end()) continue;
const auto begin = std::max(address, tracker.blockBegin(block));
const auto stop = std::min<std::uint64_t>(end, tracker.blockBegin(block) + WriteBlockBytes);
if (!tracker.covers(begin, static_cast<std::size_t>(stop - begin))) continue;
const auto stamp = tracker.stampOf(block);
if (since[k] == 0 || (stamp > since[k] && stamp == found->second)) rewatched[k] = 1;
}
}
bool Watched(std::uint64_t address, std::size_t bytes) {
if (bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address) return false;
auto& tracker = Tracker();
@@ -2635,6 +2783,10 @@ static GuestAllocations::Lease::Ranges pinStoreRanges(std::uint64_t address, std
return pinned;
}
struct BreakWhenStored {
~BreakWhenStored() { BreakProofs(); }
};
static std::atomic<bool> ownStoreCompare{false};
void SetOwnStoreCompare(bool compare) {
@@ -2645,6 +2797,7 @@ std::uint64_t storeOwn(std::uint64_t address, std::size_t bytes, bool imaged, co
if (bytes == 0) return 0;
const auto pinned = pinStoreRanges(address, bytes);
BreakProofs();
const BreakWhenStored breakStored;
const auto stampStored = [complete](WriteTracker& tracker, std::pair<std::uint64_t, std::uint64_t> stored) -> std::uint64_t {
if (stored.second <= stored.first) return 0;
++tracker.generation;
@@ -2712,6 +2865,7 @@ std::uint64_t StoreOwnBytes(std::uint64_t address, std::span<const std::byte> so
static std::uint64_t markWritten(std::uint64_t address, std::size_t bytes, bool complete, std::uint64_t* order = nullptr) {
BreakProofs();
const BreakWhenStored breakStored;
auto& tracker = Tracker();
auto lock = lockTracker(tracker);
if (order != nullptr) *order = 0;
@@ -89,6 +89,12 @@ void require(bool condition, const char* reason) {
if (!condition) throw std::runtime_error(reason);
}
constexpr std::uint32_t GcnPrepareFlipMarker = 0x68750777u;
constexpr std::uint32_t GcnPrepareFlipLabelMarker = 0x68750778u;
constexpr std::size_t GcnFlipReservationWords = 64;
constexpr std::uint32_t GcnReleaseEventControl = 0xf3fu;
constexpr std::uint32_t GcnVolatileTextureCacheAction = 0x10000u;
std::uint64_t address(std::uint32_t low, std::uint32_t high) {
return low | (static_cast<std::uint64_t>(high) << 32u);
}
@@ -155,11 +161,13 @@ bool memorySelector(std::uint32_t selector) {
}
std::uint32_t dmaSource(std::span<const std::uint32_t> packet) {
return ((packet[1] >> 29u) & 3u) | ((packet[6] >> 24u) & 4u) | ((packet[6] >> 25u) & 8u);
const auto selector = ((packet[1] >> 29u) & 3u) | ((packet[6] >> 24u) & 4u) | ((packet[6] >> 25u) & 8u);
return selector == (DmaSelectGds | 12u) ? DmaSelectGds : selector;
}
std::uint32_t dmaDestination(std::span<const std::uint32_t> packet) {
return ((packet[1] >> 20u) & 3u) | ((packet[6] >> 25u) & 4u) | ((packet[6] >> 26u) & 8u);
const auto selector = ((packet[1] >> 20u) & 3u) | ((packet[6] >> 25u) & 4u) | ((packet[6] >> 26u) & 8u);
return selector == (DmaSelectGds | 12u) ? DmaSelectGds : selector;
}
// The bytes a COPY_DATA or DMA_DATA stores: an immediate is a repeating 32-bit pattern, a memory
@@ -328,7 +336,11 @@ void Validate(std::span<const std::uint32_t> packet, std::uint32_t queue) {
require((header & 3u) == 0, "unsupported NOP header flags");
switch ((header >> 2u) & 0x3fu) {
case 0:
require((packet[1] & 0xffff0000u) != 0x68750000u, "typed user-data and legacy flip markers are not implemented");
if ((packet[1] & 0xffff0000u) == 0x68750000u) {
require(ShaderRecompiler::GcnGuestShaders(), "typed user-data and legacy flip markers are not implemented");
require(packet.size() != GcnFlipReservationWords, "a GCN flip reservation in a command buffer is not implemented");
require(packet[1] != GcnPrepareFlipMarker && packet[1] != GcnPrepareFlipLabelMarker, "legacy flip markers are not implemented");
}
break;
case 0x09: size(2); break;
case 0x06: size(4); require(packet[3] == 0, "unsupported rendering wait mode"); break;
@@ -354,6 +366,7 @@ void Validate(std::span<const std::uint32_t> packet, std::uint32_t queue) {
const bool registerWrite = opcode == 0x69 || opcode == 0x76 || opcode == 0x79 || opcode == 0x7a || (opcode == 0x37 && ((packet[1] >> 8u) & 0xfu) == 0);
auto allowedFlags = opcode == 0x11 || opcode == 0x15 || opcode == 0x16 ? 2u : registerWrite ? 6u : opcode == 0x3c || opcode == 0x93 ? 2u : 0u;
if (opcode != 0x20 && opcode != 0x22) allowedFlags |= 1u;
if (queue != 0 && ShaderRecompiler::GcnGuestShaders()) allowedFlags |= 2u;
if ((flags & ~allowedFlags) != 0) throw std::runtime_error("PM4 header flags 0x" + ToHex(flags) + " are not implemented");
switch (opcode) {
case 0x11:
@@ -491,7 +504,7 @@ void Validate(std::span<const std::uint32_t> packet, std::uint32_t queue) {
}
case 0x58: {
require(packet.size() == 7 || packet.size() == 8, "invalid ACQUIRE_MEM packet size");
const auto controlMask = packet.size() == 8 ? 0x86287fc3u : 0xfeecfffbu;
const auto controlMask = packet.size() == 8 ? 0x86287fc3u : 0xfeecfffbu | (ShaderRecompiler::GcnGuestShaders() ? GcnVolatileTextureCacheAction : 0u);
require((packet[1] & ~controlMask) == 0, "unsupported ACQUIRE_MEM control flags");
require(queue == 0 || (packet[1] & 0x06287fc3u) == 0, "graphics cache operation in compute queue");
require(packet[3] <= 0xffu && packet[5] <= 0xffu, "invalid ACQUIRE_MEM range high bits");
@@ -549,7 +562,12 @@ void Validate(std::span<const std::uint32_t> packet, std::uint32_t queue) {
break;
}
case 0x49: {
size(8);
require(packet.size() == 8 || (packet.size() == 7 && ShaderRecompiler::GcnGuestShaders()), "invalid packet size");
if (packet.size() == 7) {
require((packet[1] & ~GcnReleaseEventControl) == 0, "GCN RELEASE_MEM event control bits beyond the event type and index are not implemented");
const auto interruptSelect = (packet[2] >> 24u) & 7u;
require(interruptSelect == 0 || interruptSelect == 3, "an interrupting GCN RELEASE_MEM has no interrupt context dword");
}
const auto dataSelect = packet[2] >> 29u;
require(dataSelect != 4 || ShaderRecompiler::GcnGuestShaders(), "RELEASE_MEM of the 64-bit system counter (DATA_SEL 4) is not implemented");
require(dataSelect <= 5, "reserved RELEASE_MEM DATA_SEL");
@@ -579,6 +579,7 @@ struct VulkanDevice::State {
bool fragmentBarycentricBuiltins = false;
bool hostInterpolationFirst = false;
bool geometryShader = false;
bool multiViewport = false;
bool largePoints = false;
bool sampleRateShading = false;
bool storageImageMultisample = false;
@@ -605,6 +606,7 @@ struct VulkanDevice::State {
bool subgroupControlBarriers = true;
bool workgroupScopeFences = true;
bool ldsLockFences = false;
bool deviceAtomicWorkgroupMemoryBarriers = false;
// VK_EXT_descriptor_indexing with non-uniform image array indexing (bindless image tables in
// graphics stages, and compute workgroups wider than a wave).
bool descriptorIndexing = false;
@@ -651,6 +653,7 @@ struct VulkanDevice::State {
VkDeviceSize hostImportAlignment = 0;
bool drawInputsInPlace = true;
bool hostPointerImport = false;
std::size_t drawInputsInPlaceBelow = 0;
bool dmaBufImport = false;
bool sparseBinding = false;
bool sparseResidencyBuffer = false;
@@ -734,6 +737,7 @@ struct VulkanDevice::State {
std::shared_ptr<Graphics::BufferPool> bufferPool;
std::unique_ptr<Graphics::Buffer> emptyBuffer;
std::unique_ptr<Graphics::Buffer> oversizedBuffer;
std::unique_ptr<Graphics::Buffer> atomicLockTable;
std::unique_ptr<Graphics::PlaceholderImages> placeholderImages;
std::unique_ptr<Graphics::TextureCache> textureCache;
std::unique_ptr<Graphics::PipelineCache> pipelineCache;
@@ -1222,6 +1226,7 @@ struct VulkanDevice::State {
vertexInputs.reset();
emptyBuffer.reset();
oversizedBuffer.reset();
atomicLockTable.reset();
placeholderImages.reset();
samplerCache.reset();
textureCache.reset();
@@ -1319,7 +1324,7 @@ ComputePipelineReplayResult VulkanDevice::ReplayComputePipeline(const ComputePip
ShaderRecompiler::RecompileResult shader;
shader.spirv = capture.spirv;
for (const auto& value : capture.specialization) shader.specialization.push_back({value.id, value.value});
const Graphics::PipelineSpecialization specialization(shader);
const Graphics::PipelineSpecialization specialization(shader, graphicsContext().atomicLockTable);
const auto& limits = state->properties.limits;
require(capture.sets.size() <= limits.maxBoundDescriptorSets, "captured descriptor sets exceed device limits");
for (const auto& range : capture.pushConstants) require(range.offset + range.size <= limits.maxPushConstantsSize, "captured push constants exceed device limits");
@@ -1648,6 +1653,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
state->subgroupControlBarriers = SubgroupControlBarrierUsable(driver.driverID);
state->workgroupScopeFences = WorkgroupScopeFenceUsable(driver.driverID);
state->ldsLockFences = LdsLockFencesRequired(driver.driverID);
state->deviceAtomicWorkgroupMemoryBarriers = DeviceAtomicWorkgroupMemoryBarriersRequired(driver.driverID);
}
{
const auto driverText = state->driverInfo.empty() ? std::to_string(state->properties.driverVersion) : state->driverInfo;
@@ -1942,6 +1948,8 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
constexpr bool windows = false;
#endif
state->drawInputsInPlace = std::getenv("APS5_NO_DRAW_INPUTS_IN_PLACE") == nullptr && (std::getenv("APS5_DRAW_INPUTS_IN_PLACE") != nullptr || DrawInputsInPlaceUsable(driverProperties.driverID, windows));
const char* inPlaceBelow = std::getenv("APS5_DRAW_INPUTS_IN_PLACE_BELOW");
state->drawInputsInPlaceBelow = std::getenv("APS5_NO_DRAW_INPUTS_IN_PLACE") != nullptr ? 0 : inPlaceBelow != nullptr ? static_cast<std::size_t>(std::strtoull(inPlaceBelow, nullptr, 10)) : DrawInputsInPlaceBelow(driverProperties.driverID, windows);
if (!compileOnly) Graphics::SetHostImportWindow(8ull << 20u);
if (!compileOnly) Graphics::SetHostImportMaxBytes(maintenance3.maxMemoryAllocationSize);
if (!compileOnly) Pm4::RequestImportableGds(state->hostPointerImport && state->properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU);
@@ -2231,6 +2239,9 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
enabled.sampleRateShading = available.sampleRateShading;
enabled.geometryShader = available.geometryShader;
state->geometryShader = enabled.geometryShader == VK_TRUE;
enabled.multiViewport = available.multiViewport && state->properties.limits.maxViewports >= Graphics::MaxViewports ? VK_TRUE : VK_FALSE;
state->multiViewport = enabled.multiViewport == VK_TRUE;
if (enabled.multiViewport) state->capabilities.push_back(spv::CapabilityMultiViewport);
enabled.largePoints = available.largePoints;
state->largePoints = enabled.largePoints == VK_TRUE;
state->sampleRateShading = enabled.sampleRateShading == VK_TRUE;
@@ -2704,6 +2715,11 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
state->oversizedBuffer = std::make_unique<Graphics::Buffer>(graphicsContext(), Graphics::EmptyBufferBytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
std::ranges::fill(state->oversizedBuffer->Bytes(), std::byte{0});
if (!compileOnly && Pm4::GdsImportable() && Graphics::HostImportFor(graphicsContext(), Pm4::GdsAddress(), Pm4::GdsBytes, Graphics::ImportRequester::Map) == nullptr) Pm4::RejectGdsImport();
if (!state->imageInt64Atomics || !state->bufferInt64Atomics) {
state->atomicLockTable = std::make_unique<Graphics::Buffer>(graphicsContext(), ShaderRecompiler::RuntimeAbi::AtomicLockCount * sizeof(std::uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT);
const auto words = state->atomicLockTable->Bytes();
std::memset(words.data(), 0, words.size());
}
static const bool headlessPipelineCache = std::getenv("APS5_HEADLESS_PIPELINE_CACHE") != nullptr;
state->pipelineCache = std::make_unique<Graphics::PipelineCache>(graphicsContext(), state->properties, window != nullptr || compileOnly || headlessPipelineCache);
state->detiler = std::make_unique<Graphics::TextureDetiler>(graphicsContext());
@@ -4740,6 +4756,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::buildTarget() const {
target.pixelFunctionStorageDwords = state->pixelFunctionStorageDwords;
target.deviceScopeLdsMemoryBarriers = !state->workgroupScopeFences;
target.ldsLockFences = state->ldsLockFences;
target.deviceAtomicWorkgroupMemoryBarriers = state->deviceAtomicWorkgroupMemoryBarriers;
target.meshWindowBuffer = state->driverId == VK_DRIVER_ID_NVIDIA_PROPRIETARY && std::getenv("APS5_NO_MESH_WINDOW_BUFFER") == nullptr;
target.meshInlineFunctions = state->driverId == VK_DRIVER_ID_NVIDIA_PROPRIETARY && std::getenv("APS5_NO_MESH_INLINE_FUNCTIONS") == nullptr;
target.srgbDecodeFormats = state->srgbDecodeFormats & ~state->srgbCopyFormats;
@@ -4881,6 +4898,7 @@ Graphics::Context VulkanDevice::buildContext() const {
context.pipelineLinkTimeOptimization = state->pipelineLinkTimeOptimization;
context.dynamicColorWriteMask = state->dynamicColorWriteMask;
context.drawInputsInPlace = state->drawInputsInPlace;
context.drawInputsInPlaceBelow = state->drawInputsInPlaceBelow;
context.discreteGpu = state->properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU;
context.integratedGpu = state->properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
context.provokingVertexModePerPipeline = state->provokingVertexModePerPipeline;
@@ -4903,6 +4921,7 @@ Graphics::Context VulkanDevice::buildContext() const {
context.imageTableUpdateAfterBind = ImageTableUpdateAfterBind(context);
context.samplerTableUpdateAfterBind = SamplerTableUpdateAfterBind(context);
context.geometryShader = state->geometryShader;
context.multiViewport = state->multiViewport;
context.largePoints = state->largePoints;
context.sampleRateShading = state->sampleRateShading;
context.fillModeNonSolid = state->fillModeNonSolid;
@@ -4915,6 +4934,7 @@ Graphics::Context VulkanDevice::buildContext() const {
context.shaderTerminateInvocation = state->shaderTerminateInvocation;
context.nullDescriptors = state->shaderProfile != nullptr && state->shaderProfile->NullDescriptors();
context.bufferInt64Atomics = state->bufferInt64Atomics;
context.atomicLockTable = state->atomicLockTable ? state->atomicLockTable->DeviceAddress() : 0;
context.placeholderImages = state->placeholderImages.get();
context.viewportIndexLayer = state->viewportIndexLayer;
context.imageFormatList = state->imageFormatList;
@@ -6178,7 +6198,7 @@ std::shared_ptr<ComputePipelineObjects> VulkanDevice::createComputePipeline(cons
layoutInfo.pPushConstantRanges = pushStages != 0 ? &push : nullptr;
check(state->DeviceFunction<PFN_vkCreatePipelineLayout>("vkCreatePipelineLayout")(state->device, &layoutInfo, nullptr, &objects->layout), "vkCreatePipelineLayout");
const VkPipelineCreateFlags pipelineFlags = computePipelineFlags();
const Graphics::PipelineSpecialization specialization(shader);
const Graphics::PipelineSpecialization specialization(shader, context.atomicLockTable);
const auto subgroupSize = computeSubgroupSize(shader);
const auto stageFlags = computeStageFlags(shader);
if (const auto* directory = ComputePipelineDumpDirectory(); directory != nullptr && *directory != 0 && !state->probingFloatControls && ComputePipelineCapture::OptionalEnabled() && CaptureComputePipeline(shader.spirv.size())) {
@@ -6227,7 +6247,7 @@ VkPipeline VulkanDevice::splitComputePipeline(const Graphics::Context& context,
if (const auto found = objects.splitPipelines.find(base); found != objects.splitPipelines.end()) return found->second;
std::array<ShaderRecompiler::PipelineSpecializationConstant, ShaderRecompiler::PipelineSpecialization::WorkgroupOffsetWords> offsets{};
for (std::uint32_t component = 0; component < offsets.size(); ++component) offsets[component] = {ShaderRecompiler::PipelineSpecialization::WorkgroupOffsetBase + component, base[component]};
const Graphics::PipelineSpecialization specialization(shader, offsets);
const Graphics::PipelineSpecialization specialization(shader, context.atomicLockTable, offsets);
VkShaderModule module = Graphics::CreateShaderModule(state->DeviceFunction<PFN_vkCreateShaderModule>("vkCreateShaderModule"), state->device, state->graphicsPipelineLibrary, shader.spirv.data(), shader.spirv.size() * sizeof(std::uint32_t), "vkCreateShaderModule");
VkPipeline pipeline = VK_NULL_HANDLE;
try {
@@ -227,6 +227,7 @@ struct Context {
VkDeviceSize hostImportAlignment = 0;
mutable std::vector<std::pair<std::pair<VkFormat, std::uint32_t>, bool>> stencilShadowCopyProbes;
bool drawInputsInPlace = true;
std::size_t drawInputsInPlaceBelow = 0;
bool discreteGpu = false;
bool integratedGpu = false;
bool hostPointerImport = true;
@@ -299,6 +300,7 @@ struct Context {
bool imageTableUpdateAfterBind = false;
bool samplerTableUpdateAfterBind = false;
bool geometryShader = false;
bool multiViewport = false;
bool largePoints = false;
bool sampleRateShading = false;
bool fillModeNonSolid = false;
@@ -311,6 +313,7 @@ struct Context {
bool shaderCullDistance = false;
bool nullDescriptors = false;
bool bufferInt64Atomics = false;
VkDeviceAddress atomicLockTable = 0;
const PlaceholderImages* placeholderImages = nullptr;
bool viewportIndexLayer = false;
bool demoteToHelperInvocation = false;
@@ -64,6 +64,7 @@ bool DccAlphaOnMsb(VkFormat format, std::uint32_t componentSwap);
// The keys of a texture's DCC surface when they fast-clear it to a value encodable here, else
// Uncompressed (the texels are read as stored; other keys are reported once).
DccKeys TextureClearKeys(const GuestTextureResource& resource, std::uint64_t guestBytes);
DccKeys ScannedDccKeys(std::uint64_t metaAddress, std::size_t keyCount);
// The last stable key scan of one surface's metadata (ProvedClearKeys): the keys read and the write
// generation the key range was collected at before the scan. Held by the image or texture of the
// surface, read and written under GuestMemory::GpuMutex only.
@@ -19,6 +19,10 @@ class StorageTexture;
VkImageView DepthSurfaceView(const Context& context, const DepthTarget& target, bool depthWritten = true, bool stencilTested = false);
VkImageView DepthSurfaceViewWithStencilWriteIntent(const Context& context, const DepthTarget& target, bool depthWritten, bool stencilTested, bool stencilWritten, std::optional<std::uint8_t> overwrittenStencil = std::nullopt);
VkImageView RepeatDepthSurfaceView(const Context& context, const DepthTarget& target, bool depthWritten, bool stencilWritten);
bool DepthTargetOverlaps(const DepthTarget& target, std::uint64_t address, std::uint64_t bytes);
const char* DepthPlanesObligation(VkDevice device, std::uint64_t address, std::uint64_t bytes);
const char* DepthTargetObligation(const Context& context, const DepthTarget& target, bool depthWritten);
SampleOrderTarget DepthSurfaceOrderTarget(const Context& context, const DepthTarget& target);
DepthSampleLocations DepthSurfaceSampleLocations(const Context& context, const DepthTarget& target);
enum class DepthPlaneScope { Overlapped, Whole };
@@ -9,6 +9,7 @@
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include <array>
#include <cstdint>
#include <limits>
#include <memory>
#include <vector>
@@ -71,7 +72,8 @@ DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uin
bool BindsIndexCopy(const State& state);
DrawInputCopy CopyZeroPaddedDrawInput(const Context& context, std::uint64_t address, std::size_t bytes, std::size_t validBytes, std::size_t stride = 0);
void KeepDrawInput(Recorder* recorder, std::uint64_t address, const DrawInputCopy& copy, Recorder::SnapshotUse use, std::uint32_t derived, std::uint32_t lowest = 0);
const HostImport* InPlaceDrawInput(const Context& context, std::uint64_t address, std::size_t bytes, std::size_t alignment, bool* behindGpuWrite = nullptr);
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());
struct InPlaceIndices {
std::optional<std::uint32_t> highest;
std::uint32_t lowest = 0;
@@ -201,6 +203,16 @@ VertexPlanScratchState ThreadVertexPlanScratch();
enum class DrawStopForTest { None = 0, ReturnAfterResolve = 1, ThrowAfterResolve = 2 };
void SetSpaceKeepFailuresForTest(std::uint32_t count);
void SetDrawStopAfterResolveForTest(DrawStopForTest stop);
enum class TargetMemoEvent : std::uint8_t {
Lookup, Hit, OverlapCached, OverlapComputed, Accept, AcceptWithDepthMiss, DepthHit, AvoidedRefreshLookups,
Invalid, ThreadChanged, Descriptor, ResidentGone, ResidentEvicted, DepthOverlap, Metadata,
Epoch, Proofs, Pending, Unwatch, Allocations, Surfaces, Released, Claims, Recorder, Device,
PostDepthInvalidated, DepthFallback, Admission, RecipeInvalidated, Build, VerifyChecked, Count
};
std::uint64_t TargetMemoEvents(TargetMemoEvent event);
const char* TargetMemoEventName(TargetMemoEvent event);
std::uint64_t TargetMemoBuildsForTest();
std::uint64_t TargetMemoHitNanosecondsForTest(const Context& context, const State& state, std::size_t repeats, std::size_t& hits);
}
@@ -119,7 +119,12 @@ bool MultisampledColorFillAbsorbs(std::uint64_t address, std::size_t bytes, std:
void NoteColorMetadataFill(std::uint64_t address, std::size_t bytes, std::uint32_t pattern);
std::shared_ptr<Texture> MultisampleTargetFmaskTexture_nid_no_patch(const Context& context, const GuestTextureResource& resource, VkComponentMapping components);
void ClearMultisampleTargets(VkDevice device);
bool MultisampleDccUnwatchLocksGpu(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges);
void SaveMultisampleDccBeforeUnwatch(std::uint64_t address, std::size_t bytes);
void SetMultisampleDccPublishHookForTest(void (*hook)());
void SetMultisampleDccCopyHookForTest(void (*hook)());
std::uint64_t MultisampleTargetRangeGeneration();
std::uint64_t MultisampleClaimSerial();
std::optional<std::vector<ShaderRecompiler::BdaAbi::Range>> ExcludeMultisampleTargetRanges(
VkDevice device, std::span<const ShaderRecompiler::BdaAbi::Range> ranges, std::uint64_t& generation);
void InstallResidentImageReadGuard_nid_no_patch();
@@ -26,6 +26,7 @@ public:
std::uint64_t Offset(std::uint32_t x, std::uint32_t y, std::uint32_t layer, std::uint32_t fragment) const;
void Detile(std::span<const std::byte> source, std::span<std::byte> destination) const;
void Tile(std::span<const std::byte> source, std::span<std::byte> destination) const;
void TileHoisted(std::span<const std::byte> source, std::span<std::byte> destination) const;
private:
std::uint64_t offset(std::uint32_t x, std::uint32_t y, std::uint32_t layer, std::uint32_t fragment) const;
@@ -49,6 +50,8 @@ private:
std::vector<std::uint32_t> fragmentOffsets;
};
std::vector<std::byte> ExpandPagedSnapshot(std::size_t bytes, std::span<const std::uint32_t> words, std::span<const std::size_t> starts, std::span<const std::byte> stored, std::size_t pageBytes, std::size_t repeated);
}
#endif
@@ -80,6 +80,7 @@ private:
void release() noexcept;
void setLibraryState(CommandState& recording, const State& state) const;
void setColorWriteMasks(CommandState& recording, const State& state, const State* masked, bool secondChannel) const;
void setViewports(CommandState& recording, const State& state) const;
Context context;
std::vector<VkShaderModule> _modules;
VkPipelineLayout layout = VK_NULL_HANDLE;
@@ -119,6 +120,8 @@ private:
std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const ShaderResources& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
// `created` reports whether this call built the pipeline (false: served from the store or private).
std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, bool* created = nullptr, std::uint64_t* storeHash = nullptr);
bool DefersPipelineBuild(std::span<const CompiledShader> shaders);
std::shared_ptr<Pipeline> ResidentPipelineOrDeferredBuild(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout, std::uint64_t* storeHash);
std::shared_ptr<Pipeline> TouchCachedPipeline(const Context& context, std::uint64_t hash, const std::weak_ptr<Pipeline>& expected);
// Cumulative pipeline store outcomes since start-up (the [pipecache] line reports 10 s windows).
struct PipelineStoreCounters {
@@ -52,18 +52,20 @@ public:
}
}
explicit PipelineSpecialization(const ShaderRecompiler::RecompileResult& shader, std::uint32_t layerBase = 0u, std::uint32_t layerCount = 0xffffffffu) {
values = shader.specialization;
PipelineSpecialization(const ShaderRecompiler::RecompileResult& shader, VkDeviceAddress atomicLockTable, std::uint32_t layerBase, std::uint32_t layerCount) : PipelineSpecialization(shader, atomicLockTable) {
for (auto& constant : values) {
if (constant.id == ShaderRecompiler::PipelineSpecialization::MeshLayerBase) constant.value = layerBase;
if (constant.id == ShaderRecompiler::PipelineSpecialization::MeshLayerCount) constant.value = layerCount;
}
Validate(shader);
describe(values);
}
PipelineSpecialization(const ShaderRecompiler::RecompileResult& shader, std::span<const ShaderRecompiler::PipelineSpecializationConstant> replaced) : values(shader.specialization) {
PipelineSpecialization(const ShaderRecompiler::RecompileResult& shader, VkDeviceAddress atomicLockTable, std::span<const ShaderRecompiler::PipelineSpecializationConstant> replaced = {}) : values(shader.specialization) {
Validate(shader);
for (auto& constant : values) {
if (!ShaderRecompiler::PipelineSpecialization::IsAtomicLockTable(constant.id)) continue;
Require(atomicLockTable != 0, "a shader emulates 64-bit atomics, but the device has no atomic lock table");
constant.value = static_cast<std::uint32_t>(atomicLockTable >> (32u * (constant.id - ShaderRecompiler::PipelineSpecialization::AtomicLockTableBase)));
}
for (const auto& constant : replaced) {
const auto found = std::ranges::find(values, constant.id, &ShaderRecompiler::PipelineSpecializationConstant::id);
Require(found != values.end(), "a replaced pipeline specialization ID is not supplied by the shader");
@@ -52,9 +52,13 @@ constexpr PlaceholderImageShape PlaceholderImageShapeOf(std::uint32_t heap) {
samples[dimension]};
}
constexpr std::optional<PlaceholderImageShape> PlaceholderImageShapeForDevice(std::uint32_t heap, bool storageImageMultisample) {
const auto shape = PlaceholderImageShapeOf(heap);
constexpr std::optional<PlaceholderImageShape> PlaceholderImageShapeForDevice(std::uint32_t heap, bool storageImageMultisample, bool imageInt64Atomics) {
auto shape = PlaceholderImageShapeOf(heap);
if (!storageImageMultisample && (shape.usage & VK_IMAGE_USAGE_STORAGE_BIT) != 0 && shape.samples != VK_SAMPLE_COUNT_1_BIT) return std::nullopt;
if (!imageInt64Atomics && shape.format == VK_FORMAT_R64_UINT) {
shape.format = VK_FORMAT_R32G32_UINT;
shape.features = static_cast<VkFormatFeatureFlags>(VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT);
}
return shape;
}
@@ -71,6 +71,7 @@ public:
void BindPipeline(const Context& context, VkPipeline pipeline, std::uint32_t dynamicSlots);
void SetViewport(const Context& context, const VkViewport& viewport);
void SetScissor(const Context& context, const VkRect2D& scissor);
void SetViewports(const Context& context, std::span<const VkViewport> viewports, std::span<const VkRect2D> scissors);
void SetDepthBias(const Context& context, float constant, float clamp, float slope);
void SetDepthBounds(const Context& context, float minimum, float maximum);
void SetCullMode(const Context& context, VkCullModeFlags mode);
@@ -20,8 +20,11 @@ enum class RuntimeSwitch : std::size_t {
NoSpaceReuseRecords,
PipelineDispatchMisses,
NoMemoPendingCollect,
NoSharedCollectWalks,
NoExtendedFastProofs,
TableSnapshot,
NoTargetMemo,
NoTargetMemoOverlapCache,
Count,
};
@@ -68,6 +68,7 @@ std::vector<SampleOrderStep> PlanSampleOrder(const Context& context, const State
SampleOrderPass SampleOrderPassFor(const Context& context, const State& state, const SampleOrder& order);
void RecordSampleOrder(const Context& context, CommandState& recording, const SampleOrderPass& pass, std::span<const SampleOrderTarget> targets, bool toHost, std::vector<std::shared_ptr<void>>& kept);
void RecordDepthSampleLocations(const Context& context, VkCommandBuffer commands, const DepthSampleLocations& depth);
void RecordDepthSampleImport(const Context& context, CommandState& recording, const SampleOrderTarget& target, VkImageView samples, std::vector<std::shared_ptr<void>>& kept);
std::array<std::span<const std::uint32_t>, 9> SampleOrderShaderModules();
void ClearSampleOrders(VkDevice device);
@@ -56,11 +56,11 @@ struct StorageTextureBudgetSnapshot {
std::uint64_t selectedBudget = 0;
};
StorageTextureBudgetSnapshot CalculateStorageTextureBudget(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported, std::uint64_t sampledBytes, std::uint64_t storageBytes);
StorageTextureBudgetSnapshot CalculateStorageTextureBudget(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported, std::uint64_t sampledBytes, std::uint64_t storageBytes, bool demand = false);
std::uint64_t TextureCacheBudget(const VkPhysicalDeviceMemoryProperties& memory);
std::uint64_t StorageTextureCeiling(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported);
std::uint64_t StorageTextureBudget(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported, std::uint64_t sampledBytes, std::uint64_t storageBytes);
std::uint64_t SampledTextureBudget(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported, std::uint64_t textureBytes, std::uint64_t storageBytes = 0);
std::uint64_t StorageTextureBudget(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported, std::uint64_t sampledBytes, std::uint64_t storageBytes, bool demand = false);
std::uint64_t SampledTextureBudget(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported, std::uint64_t textureBytes, std::uint64_t storageBytes = 0, bool demand = false);
bool SampledBudgetReportDue(std::uint64_t reported, std::uint64_t budget, std::chrono::steady_clock::duration sinceReport);
std::optional<std::uint32_t> LargestDeviceLocalHeap(const VkPhysicalDeviceMemoryProperties& memory);
std::uint64_t StorageTextureCacheBudget(const Context& context);
@@ -6,6 +6,7 @@
#include "prx/libSceAgcDriver/Graphics/include/GuestTextureResource.hpp"
#include "prx/libSceAgcDriver/Execution/include/QueueState.hpp"
#include <vector>
#include <bit>
#include <array>
#include <atomic>
#include <cstddef>
@@ -94,6 +95,22 @@ struct ColorTarget {
std::uint16_t stagedMask = 0;
VkFormat stagedFormat = VK_FORMAT_UNDEFINED;
bool operator==(const ColorTarget& other) const {
return address == other.address && extent.width == other.extent.width && extent.height == other.extent.height && format == other.format &&
bytes == other.bytes && componentMapping == other.componentMapping && tileMode == other.tileMode && elementBytes == other.elementBytes &&
packing == other.packing && dccAddress == other.dccAddress && chainDccAddress == other.chainDccAddress &&
dccAlphaOnMsb == other.dccAlphaOnMsb && dccPipeAligned == other.dccPipeAligned && cmaskAddress == other.cmaskAddress &&
cmaskBytes == other.cmaskBytes && cmaskFastClear == other.cmaskFastClear && eqaaFragments == other.eqaaFragments &&
surfaceAddress == other.surfaceAddress && surfaceExtent.width == other.surfaceExtent.width &&
surfaceExtent.height == other.surfaceExtent.height && mipCount == other.mipCount && mip == other.mip && mipTail == other.mipTail &&
clearWords == other.clearWords && slot == other.slot && depth == other.depth && depthSlice == other.depthSlice &&
arrayAddress == other.arrayAddress && arrayLastSlice == other.arrayLastSlice && arraySlice == other.arraySlice && layers == other.layers &&
exportIndex == other.exportIndex && uintExport == other.uintExport && volume == other.volume && pipeBankXor == other.pipeBankXor &&
samples == other.samples && coverageSamples == other.coverageSamples && dccControl == other.dccControl &&
fmaskAddress == other.fmaskAddress && fmaskPipeBankXor == other.fmaskPipeBankXor && gcnFmaskBytes == other.gcnFmaskBytes &&
partialWriteMask == other.partialWriteMask && mergeBlend == other.mergeBlend && staged == other.staged && stagedMask == other.stagedMask && stagedFormat == other.stagedFormat;
}
std::uint64_t MemoryAddress() const {
return volume && tileMode != ColorTileMode::Linear ? surfaceAddress : address;
}
@@ -120,6 +137,16 @@ struct DepthTarget {
bool gcn = false;
bool depthPartiallyResident = false;
bool stencilPartiallyResident = false;
bool operator==(const DepthTarget& other) const {
return address == other.address && stencilAddress == other.stencilAddress && extent.width == other.extent.width &&
extent.height == other.extent.height && format == other.format &&
std::bit_cast<std::uint32_t>(clearDepth) == std::bit_cast<std::uint32_t>(other.clearDepth) && clearStencil == other.clearStencil &&
htileAddress == other.htileAddress && htileStencil == other.htileStencil && samples == other.samples && depthSwizzle == other.depthSwizzle &&
pipeBankXor == other.pipeBankXor && firstSlice == other.firstSlice && lastSlice == other.lastSlice && iterate256 == other.iterate256 &&
htilePipeAligned == other.htilePipeAligned && htileVrsEncoding == other.htileVrsEncoding && htileDepthOnly == other.htileDepthOnly &&
gcn == other.gcn && depthPartiallyResident == other.depthPartiallyResident && stencilPartiallyResident == other.stencilPartiallyResident;
}
};
struct State {
@@ -158,9 +185,12 @@ struct State {
std::uint32_t meshLayerBase = 0;
std::uint32_t meshLayerCount = 0xffffffffu;
std::uint32_t layerExports = 0;
std::uint32_t viewportExports = 0;
VkPrimitiveTopology topology;
bool primitiveRestart = false;
VkViewport viewport;
std::vector<VkViewport> extraViewports;
std::vector<VkRect2D> viewportScissors;
bool negativeOneToOne;
bool depthClamp = false;
float depthScale = 1;
@@ -206,6 +236,8 @@ struct State {
// PA_CL_VS_OUT_CNTL bits that place position exports (clip and cull distances, the misc and the two
// distance vectors); a vertex program that exports pos1..pos3 depends on them.
inline constexpr std::uint32_t PositionExportLayoutBits = 0xffffu | (1u << 21u) | (1u << 22u) | (1u << 23u);
inline constexpr std::uint32_t ViewportIndexExport = 1u << 19u;
inline constexpr std::uint32_t MaxViewports = 16;
inline constexpr std::uint8_t CopyRop = 0xccu;
VkLogicOp LogicOpFromRop(std::uint8_t rop);
@@ -214,6 +246,8 @@ ShaderStages DecodeShaderStages(const QueueState& queue, bool vertexWorkgroup =
void ApplyPointSize(const State& state, ShaderRecompiler::ShaderVertexStageInfo& vertex);
State DecodeState(const QueueState& queue, bool vertexWorkgroup = false);
void ApplyDepthRemap(const Context& context, State& state);
void ApplyViewportIndex(const Context& context, State& state);
inline std::uint32_t ViewportCount(const State& state) { return 1u + static_cast<std::uint32_t>(state.extraViewports.size()); }
void ApplyDepthBoundsEmulation(const Context& context, State& state, const ShaderRecompiler::ShaderPixelStageInfo& pixel);
void ApplyReadOnlyDepthBoundsComparison(State& state, const ShaderRecompiler::ShaderPixelStageInfo& pixel, bool enabled);
void NormalizeUnusedViewportDepth(State& state, const ShaderRecompiler::ShaderPixelStageInfo& pixel);
@@ -347,7 +381,7 @@ struct DrawKeyRange {
};
inline constexpr std::array<DrawKeyRange, 53> DrawKeyRegisters{{
{RegisterBank::Context, 0x000, 1}, {RegisterBank::Context, 0x002, 2}, {RegisterBank::Context, 0x005, 1}, {RegisterBank::Context, 0x007, 7}, {RegisterBank::Context, 0x010, 6}, {RegisterBank::Context, 0x01a, 5},
{RegisterBank::Context, 0x080, 4}, {RegisterBank::Context, 0x08c, 4}, {RegisterBank::Context, 0x090, 2}, {RegisterBank::Context, 0x094, 2}, {RegisterBank::Context, 0x0b4, 2}, {RegisterBank::Context, 0x105, 4}, {RegisterBank::Context, 0x10b, 3}, {RegisterBank::Context, 0x10f, 6},
{RegisterBank::Context, 0x080, 4}, {RegisterBank::Context, 0x08c, 4}, {RegisterBank::Context, 0x090, 2}, {RegisterBank::Context, 0x094, 0x20}, {RegisterBank::Context, 0x0b4, 2}, {RegisterBank::Context, 0x105, 4}, {RegisterBank::Context, 0x10b, 3}, {RegisterBank::Context, 0x10f, 0x60},
// SPI_PS_INPUT_CNTL_0..31, SPI_PS_INPUT_ENA/ADDR, SPI_PS_IN_CONTROL .. SPI_BARYC_CNTL, SPI_SHADER_POS/Z/COL_FORMAT,
// CB_BLEND0..7_CONTROL, GE_MAX_OUTPUT_PER_SUBGROUP.
{RegisterBank::Context, 0x191, 32}, {RegisterBank::Context, 0x1b3, 2}, {RegisterBank::Context, 0x1b6, 3}, {RegisterBank::Context, 0x1c3, 3}, {RegisterBank::Context, 0x1e0, 8}, {RegisterBank::Context, 0x1ff, 1},
@@ -339,6 +339,7 @@ public:
static void FlushAllPending(const char* reason, VkDevice device = VK_NULL_HANDLE);
static bool FlushAllPendingUntil(const char* reason, const std::function<bool()>& stop, VkDevice device = VK_NULL_HANDLE);
static bool WaitForFlushing(std::uint64_t address, std::size_t bytes, const StorageTexture* except = nullptr);
static void InstallUnwatchHook();
static void SaveBeforeUnwatch(std::uint64_t address, std::size_t bytes);
static bool UnwatchHookLocksGpu(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges);
static void SetPublishHookForTest(void (*hook)());
@@ -371,6 +372,9 @@ public:
// it was then.
static std::uint64_t PendingSerial();
static bool PendingClearOnThread(std::uint64_t address, std::size_t bytes);
static std::uint64_t OwnPendingMoves();
static std::uint64_t OwnRefreshWork();
static void NoteRefreshWork();
// One registry scan for several ranges (the fast Revalidate): each query's `overlaps` receives
// whether an image other than `except` has results pending, or is being stored right now, over
// [begin, end), and `found` the image FindPending would return for the range (null: none);
@@ -431,6 +435,10 @@ public:
static bool OrderedFlushArmedForTest();
// A consumer found the image current and used it (Refresh, the fast revalidation).
void NoteProved() const;
void NoteUsed() const {
if (!usedUnlisted.load(std::memory_order_relaxed)) usedUnlisted.store(true, std::memory_order_relaxed);
}
bool TakeUsed() const { return usedUnlisted.load(std::memory_order_relaxed) && usedUnlisted.exchange(false, std::memory_order_relaxed); }
// Whether the storage cache holds this image (set and cleared by the cache under its mutex, the
// clear before the eviction's flush): what a lookup of its surface would return.
bool Cached() const { return cached.load(std::memory_order_acquire); }
@@ -528,17 +536,20 @@ public:
// Keeps the image current with guest memory (see GuestMemory::CollectWrites).
bool Refresh();
bool RefreshLayers(std::uint32_t first, std::uint32_t count);
static void SetRefreshUnchangedHookForTest(void (*hook)(std::uint64_t address, std::size_t bytes));
inline static std::atomic<std::uint64_t> epochRefreshes{0};
static std::uint64_t SinglePassMoves();
static std::uint64_t SlabRetiles();
static std::uint64_t PaddingSeedCopies();
static std::uint64_t LinearImportRetiles();
static std::uint64_t RefreshesProved();
const char* RefreshObligation(std::uint32_t first = 0, std::uint32_t count = 0) const;
static std::uint64_t ClearHandOvers();
static std::uint64_t CreationHandOvers();
static std::uint64_t HandedOverSuperseded();
static void SetClearHandOver(bool enabled);
static std::uint64_t UntrackedCompares();
static std::uint64_t RewatchedConfirms();
static std::uint64_t GuestSnapshots();
static std::uint64_t OccasionalLabelStores();
std::uint64_t GuestBytes() const;
@@ -584,6 +595,9 @@ private:
bool originalHolds(std::uint64_t address, std::size_t bytes) const;
bool guestBytesStillHeld() const;
bool compareUntracked(std::uint64_t address, std::size_t bytes, std::span<std::uint8_t> changed, bool memoize = false) const;
enum class RewatchProof { None, Unchanged, Changed };
RewatchProof rewatchProof(std::uint64_t begin, std::uint64_t end, bool queried) const;
void confirmRewatched(std::uint64_t spanBegin, std::span<std::uint8_t> stamped, std::span<std::uint8_t> cpu, std::vector<bool>* comparedUnits) const;
// Stores the pending tracked layers overlapping [address, address + bytes) to guest memory; in
// each, 64 KiB blocks the CPU wrote since the layer's generation keep the CPU's bytes. Block
// units asked for in pieces too often are all stored at once for a while (the hysteresis:
@@ -715,8 +729,10 @@ private:
bool refresh(std::uint32_t firstLayer, std::uint32_t lastLayer);
void noteLayersBehind(std::uint32_t firstLayer, std::uint32_t lastLayer, const std::vector<bool>& outside);
void refreshGeneration();
std::uint64_t advanceUnchanged(std::uint32_t unit, std::uint64_t to);
std::uint64_t collectedLayerGeneration(std::uint32_t layer, std::uint64_t whole, bool uncached = false) const;
bool refreshProved();
std::pair<std::uint32_t, std::uint32_t> refreshUnits(std::uint32_t first, std::uint32_t count) const;
bool keysReplacedByClear() const;
void takeRefreshProof(bool aliased);
bool otherPendingOverlaps() const;
@@ -909,6 +925,7 @@ private:
std::atomic<bool> cached{false};
// The present a consumer last proved the image current at (NoteProved).
mutable std::atomic<std::uint64_t> provedPresent{0};
mutable std::atomic<bool> usedUnlisted{false};
// Hook skips of this image since FlushPending last listed it (AccessKeptByCpu), the read site
// of the last one (a GuestMemory::ReadSite), and the first pending layer under its access with
// the version and layer generation seen: a listing counts a flush after a skip only while that
@@ -14,6 +14,9 @@
namespace AgcDriver::Graphics {
class Buffer;
class Recorder;
std::shared_ptr<void> RecordMultisampleColorUpload(const Context& context, VkCommandBuffer commands, VkImage image, VkFormat format, VkExtent2D extent, std::uint32_t samples, std::uint32_t elementBytes, const Buffer& source, VkDeviceSize stride, Recorder* recorder);
// The part of a mip one Dispatch moves: only elements whose tiled offset (relative to the mip's
// tiled base; the linear offset of a linear surface) lies in [rangeBegin, rangeEnd), with the
@@ -2,8 +2,18 @@
#extension GL_EXT_shader_image_load_formatted : require
layout(constant_id = 0) const uint ELEMENT_BYTES = 4u;
layout(local_size_x = 64) in;
layout(set = 0, binding = 0, std430) readonly buffer Input { uint data[]; } sourceBuffer;
#ifdef COLOR_ATTACHMENT_UPLOAD
layout(location = 0) out uvec4 destinationColor;
layout(push_constant) uniform Push {
uint width;
uint fragments;
uint firstElement;
uint elements;
} params;
#else
layout(local_size_x = 64) in;
layout(set = 0, binding = 1) uniform uimage2DMSArray destinationImage;
layout(push_constant) uniform Push {
uint width;
@@ -14,13 +24,9 @@ layout(push_constant) uniform Push {
uint elements;
uint rowThreads;
} params;
#endif
void main() {
uint index = gl_GlobalInvocationID.y * params.rowThreads + gl_GlobalInvocationID.x;
if (index >= params.elements) return;
uint element = params.firstElement + index;
uint pixel = element / params.fragments;
ivec3 coordinate = ivec3(pixel % params.width, (pixel / params.width) % params.height, pixel / (params.width * params.height));
uvec4 readElement(uint index) {
uint address = index * ELEMENT_BYTES;
uvec4 value = uvec4(0u);
if (ELEMENT_BYTES < 4u) {
@@ -28,5 +34,22 @@ void main() {
} else {
for (uint component = 0u; component < ELEMENT_BYTES / 4u; ++component) value[component] = sourceBuffer.data[(address >> 2u) + component];
}
imageStore(destinationImage, coordinate, int(element % params.fragments), value);
return value;
}
void main() {
#ifdef COLOR_ATTACHMENT_UPLOAD
uvec2 pixel = uvec2(gl_FragCoord.xy);
uint element = (pixel.y * params.width + pixel.x) * params.fragments + uint(gl_SampleID);
uint index = element - params.firstElement;
if (element < params.firstElement || index >= params.elements) discard;
destinationColor = readElement(index);
#else
uint index = gl_GlobalInvocationID.y * params.rowThreads + gl_GlobalInvocationID.x;
if (index >= params.elements) return;
uint element = params.firstElement + index;
uint pixel = element / params.fragments;
ivec3 coordinate = ivec3(pixel % params.width, (pixel / params.width) % params.height, pixel / (params.width * params.height));
imageStore(destinationImage, coordinate, int(element % params.fragments), readElement(index));
#endif
}
@@ -13,6 +13,9 @@ layout(push_constant) uniform Parameters {
uint always;
} parameters;
const uint LineWords = 8u;
shared uint lineChanged[64u / LineWords];
uint differingBytes(uint difference) {
uint folded = difference | (difference >> 1u);
folded |= folded >> 2u;
@@ -22,14 +25,24 @@ uint differingBytes(uint difference) {
void main() {
uint index = gl_GlobalInvocationID.x;
if (index >= parameters.count) return;
uint value = parameters.result.words[index];
uint before = parameters.snapshot.words[index];
uint changed = differingBytes(value ^ before);
if (changed == 0u && parameters.always == 0u) return;
uint lane = gl_LocalInvocationID.x;
if (lane < 64u / LineWords) lineChanged[lane] = 0u;
barrier();
bool inside = index < parameters.count;
uint value = 0u;
uint before = 0u;
uint changed = 0u;
if (inside) {
value = parameters.result.words[index];
before = parameters.snapshot.words[index];
changed = differingBytes(value ^ before);
if (changed != 0u || parameters.always != 0u) atomicOr(lineChanged[lane / LineWords], 1u);
}
barrier();
if (!inside || lineChanged[lane / LineWords] == 0u) return;
uint held = parameters.target.words[index];
uint kept = differingBytes(held ^ before);
uint stored = parameters.always != 0u ? 0xffffffffu : changed & ~kept;
if (stored != 0u) parameters.target.words[index] = (held & ~stored) | (value & stored);
parameters.target.words[index] = (held & ~stored) | (value & stored);
if (uint64_t(parameters.counter) != 0ul && (changed & kept) != 0u) atomicAdd(parameters.counter.words[0], 1u);
}
@@ -14,6 +14,9 @@ layout(push_constant) uniform Parameters {
uint counting;
} parameters;
const uint LineWords = 8u;
shared uint lineChanged[64u / LineWords];
uint differingBytes(uint difference) {
uint folded = difference | (difference >> 1u);
folded |= folded >> 2u;
@@ -23,14 +26,24 @@ uint differingBytes(uint difference) {
void main() {
uint index = gl_GlobalInvocationID.x;
if (index >= parameters.count) return;
uint value = result.words[parameters.resultBase + index];
uint before = snapshot.words[parameters.snapshotBase + index];
uint changed = differingBytes(value ^ before);
if (changed == 0u && parameters.always == 0u) return;
uint lane = gl_LocalInvocationID.x;
if (lane < 64u / LineWords) lineChanged[lane] = 0u;
barrier();
bool inside = index < parameters.count;
uint value = 0u;
uint before = 0u;
uint changed = 0u;
if (inside) {
value = result.words[parameters.resultBase + index];
before = snapshot.words[parameters.snapshotBase + index];
changed = differingBytes(value ^ before);
if (changed != 0u || parameters.always != 0u) atomicOr(lineChanged[lane / LineWords], 1u);
}
barrier();
if (!inside || lineChanged[lane / LineWords] == 0u) return;
uint held = target.words[parameters.targetBase + index];
uint kept = differingBytes(held ^ before);
uint stored = parameters.always != 0u ? 0xffffffffu : changed & ~kept;
if (stored != 0u) target.words[parameters.targetBase + index] = (held & ~stored) | (value & stored);
target.words[parameters.targetBase + index] = (held & ~stored) | (value & stored);
if (parameters.counting != 0u && (changed & kept) != 0u) atomicAdd(counter.words[0], 1u);
}
@@ -481,11 +481,11 @@ void BdaResources::checkFault(const BdaResources& record) const {
ShaderRecompiler::BdaAbi::Fault report{};
std::memcpy(&report, record.faultBytes().data(), sizeof(report));
if (report.state == ShaderRecompiler::BdaAbi::FaultState::Empty) {
Require(static_cast<std::uint32_t>(report.reason) == 0 && report.address == 0 && report.bytes == 0 && report.stage == 0 && report.instruction == 0 && report.otherFaults == 0, "BDA fault record has data without publication");
Require(static_cast<std::uint32_t>(report.reason) == 0 && report.address == 0 && report.bytes == 0 && report.stage == 0 && report.instruction == 0 && report.claim == 0, "BDA fault record has data without publication");
if (!reportOnly) checkSrtGuard(record);
return;
}
Require(report.state == ShaderRecompiler::BdaAbi::FaultState::Ready && report.otherFaults <= 1, "incomplete or invalid BDA fault record");
Require(report.state == ShaderRecompiler::BdaAbi::FaultState::Ready && (report.claim & ~(ShaderRecompiler::BdaAbi::FaultClaimed | ShaderRecompiler::BdaAbi::FaultClaimOtherFaults)) == 0, "incomplete or invalid BDA fault record");
Require(report.reason != ShaderRecompiler::BdaAbi::FaultReason::InvalidRectangle, "rect-list requires finite nondegenerate axis-aligned positions with equal positive W");
if (report.reason == ShaderRecompiler::BdaAbi::FaultReason::LoopLimit) {
// APS5_LOOP_GUARD: the shader left a loop that ran past the guard; the dispatch result is kept.
@@ -536,7 +536,7 @@ void BdaResources::checkFault(const BdaResources& record) const {
}
}
if (report.reason == ShaderRecompiler::BdaAbi::FaultReason::Unaligned) {
if (report.otherFaults == 0) throw BdaUnalignedAccess(message.str(), report.instruction);
if (ShaderRecompiler::BdaAbi::OtherFaults(report) == 0) throw BdaUnalignedAccess(message.str(), report.instruction);
message << "; a fault of another kind was recorded in the same dispatch";
}
throw std::runtime_error(message.str());
@@ -118,7 +118,7 @@ const SwizzleTables& standardTables(std::uint32_t bytesPerElement, std::uint32_t
ColorTargetLayout::ColorTargetLayout(std::uint32_t width, std::uint32_t height, ColorTileMode mode, std::uint32_t bytesPerElement, std::uint32_t pipeBankXor) : width(width), height(height), pitch(width), mode(mode), bytes(0), elementBytes(bytesPerElement), pipeBankXor(pipeBankXor) {
require(width != 0 && height != 0 && width <= 16384 && height <= 16384, "AGC graphics: invalid color surface extent");
require(std::has_single_bit(bytesPerElement) && bytesPerElement <= 16u, "AGC graphics: unsupported color element size");
require(pipeBankXor == 0 || (ColorTileModeIsXor(mode) && pipeBankXor < ColorTileModeBlockBytes(mode) && pipeBankXor % 256u == 0), "AGC graphics: a color pipe/bank XOR applies only to whole 256-byte units of XOR swizzle blocks");
require(pipeBankXor == 0 || (ColorTileModeIsGcn(mode) && !ColorTileModeIsLinear(mode)) || (ColorTileModeIsXor(mode) && pipeBankXor < ColorTileModeBlockBytes(mode) && pipeBankXor % 256u == 0), "AGC graphics: a color pipe/bank XOR applies only to whole 256-byte units of XOR swizzle blocks");
require(mode != ColorTileMode::D64KBX || (pipeBankXor & ~0xcf00u) == 0, "AGC graphics: unsupported display color pipe/bank XOR column bits");
std::uint32_t paddedHeight = height;
switch (mode) {
@@ -167,6 +167,7 @@ ColorTargetLayout::ColorTargetLayout(std::uint32_t width, std::uint32_t height,
case ColorTileMode::GcnDisplay2D:
case ColorTileMode::GcnThin2D: {
const auto geometry = GcnTiling(ColorTextureTileMode(mode), bytesPerElement);
require((pipeBankXor & ~(geometry.bankMask << geometry.bankShift)) == 0, "AGC graphics: a PS4 color bank XOR applies only to the bank bits of a 2D-tiled mode");
blockWidth = geometry.blockWidth;
blockHeight = geometry.blockHeight;
pitch = (width + blockWidth - 1u) / blockWidth * blockWidth;
@@ -189,7 +190,7 @@ std::size_t ColorTargetLayout::offset(std::uint32_t x, std::uint32_t y) const {
if (gcn) {
std::uint32_t inBlock = 0;
for (std::uint32_t bit = 0; bit < 16u; ++bit) inBlock |= parity((x & gcnEquation[bit] & 0xfffu) ^ ((y << 12u) & gcnEquation[bit] & 0xfff000u)) << bit;
return block * blockBytes + inBlock;
return block * blockBytes + (inBlock ^ pipeBankXor);
}
auto inBlock = xOffsets[x % blockWidth] ^ yOffsets[y % blockHeight];
if (equation != nullptr) {
@@ -708,6 +708,11 @@ bool DccAlphaOnMsb(VkFormat format, std::uint32_t componentSwap) {
return componentSwap != standardReversed && componentSwap != alternateReversed;
}
DccKeys ScannedDccKeys(std::uint64_t metaAddress, std::size_t keyCount) {
const std::span keys(reinterpret_cast<const std::uint8_t*>(metaAddress), keyCount);
return std::ranges::all_of(keys, [&](std::uint8_t key) { return key == keys.front(); }) ? ByteKeys(keys.front()) : DccKeys::Mixed;
}
DccKeys TextureClearKeys(const GuestTextureResource& resource, std::uint64_t guestBytes) {
bool memoized = false;
return textureClearKeys(resource, guestBytes, memoized);
@@ -285,6 +285,9 @@ struct DepthSamplingState {
bool unevenPlanes = false;
std::optional<std::uint8_t> overwriteStencil;
std::optional<MultisampleColorAlias> stencilAlias;
std::shared_ptr<Buffer> importedSamples;
bool importedPerSample = false;
bool importedByCopy = false;
void Refuse(const char* reason) {
if (refusal.empty()) refusal = reason;
@@ -454,6 +457,104 @@ DepthSamplingState prepareUniformPlaneSampling(const Context& context, const Dep
return state;
}
bool bareDepthTarget(const DepthTarget& target) {
return target.samples != 1u && target.format == VK_FORMAT_D32_SFLOAT && target.stencilAddress == 0u && target.htileAddress == 0u && !target.htileStencil;
}
constexpr VkImageUsageFlags importedSampleUsage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
constexpr VkImageUsageFlags copiedSampleUsage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
constexpr VkImageCreateFlags importedSampleFlags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT;
bool detilesDepthSamples(const Context& context, const DepthTarget& target, VkImageUsageFlags sampleUsage) {
if (context.detiler == nullptr || context.imageFormatProperties == nullptr || !context.storageImageMultisample || !context.storageImageWriteWithoutFormat) return false;
const auto supports = [&](VkFormat format, VkImageUsageFlags usage, VkImageCreateFlags flags) {
VkImageFormatProperties properties{};
return context.imageFormatProperties(context.physical, format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usage, flags, &properties) == VK_SUCCESS && (properties.sampleCounts & target.samples) != 0u && target.extent.width <= properties.maxExtent.width && target.extent.height <= properties.maxExtent.height;
};
return supports(TextureDetiler::ImageElementFormat(4u), VK_IMAGE_USAGE_STORAGE_BIT, 0u) && supports(VK_FORMAT_R32_SFLOAT, sampleUsage, importedSampleFlags);
}
bool importsDepthSamples(const Context& context, const DepthTarget& target) {
return context.sampleRateShading && detilesDepthSamples(context, target, importedSampleUsage);
}
bool copiesDepthSamples(const Context& context, const DepthTarget& target) {
return context.depthRangeUnrestricted && DirectDepthCopy(context, VK_FORMAT_D32_SFLOAT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_FORMAT_R32_SFLOAT) && detilesDepthSamples(context, target, copiedSampleUsage);
}
const char* readDepthPlane(const Context& context, const DepthTarget& target, const MultisampleTextureLayout& layout, DepthSamplingState& state) {
const auto& plane = state.initial.front();
std::vector<std::byte> tiled(plane.bytes);
GuestMemory::Read(plane.address, std::span(tiled));
const auto linearBytes = static_cast<std::size_t>(layout.LinearBytes());
auto samples = std::make_shared<Buffer>(context, linearBytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
const auto linear = samples->Bytes().first(linearBytes);
layout.Detile(tiled, linear);
std::uint32_t first = 0u;
std::memcpy(&first, linear.data(), sizeof(first));
bool uniform = true;
bool exact = true;
for (std::size_t offset = 0u; offset < linearBytes; offset += sizeof(std::uint32_t)) {
std::uint32_t bits = 0u;
std::memcpy(&bits, linear.data() + offset, sizeof(bits));
const auto depth = std::bit_cast<float>(bits);
uniform = uniform && bits == first;
exact = exact && (bits == 0u || (std::isnormal(depth) && depth > 0.0f && depth <= 1.0f));
}
const auto value = std::bit_cast<float>(first);
if (uniform && value >= 0.0f && value <= 1.0f) {
state.initialDepth = value;
return nullptr;
}
const bool drawn = exact && importsDepthSamples(context, target);
if (!drawn && !copiesDepthSamples(context, target)) {
if (!exact) return "native multisample depth plane without HTILE holds a sample other than +0 or a normal depth in (0, 1], which only a bit copy through VK_KHR_maintenance8 with VK_EXT_depth_range_unrestricted imports";
return "importing an uneven native multisample depth plane requires multisampled storage image writes without format, sample-rate shading and a sampled multisampled R32 float image";
}
state.importedSamples = std::move(samples);
state.importedPerSample = true;
state.importedByCopy = !drawn;
return nullptr;
}
DepthSamplingState prepareDepthPlaneSampling(const Context& context, const DepthTarget& target, DepthSamplingState state) {
const auto refuse = [&](const char* reason) {
state.refusal = reason;
state.importedSamples.reset();
state.importedPerSample = false;
state.importedByCopy = false;
return state;
};
if (target.depthSwizzle != 24u || target.firstSlice != 0u || target.lastSlice != 0u) return refuse("native multisample depth arrays or non-Z_X layout are not implemented");
if ((target.pipeBankXor & ~0xcf00u) != 0u) return refuse("unsupported native multisample depth XOR");
if (target.address == 0u || (target.address & 65535u) != 0u) return refuse("native multisample depth base is not aligned");
state.initial = {{target.address, static_cast<std::size_t>(MultisampledDepthBytes_nid_no_patch(target.extent, 4u, target.samples)), 0u}};
auto& plane = state.initial.front();
if (plane.address > std::numeric_limits<std::uint64_t>::max() - plane.bytes) return refuse("native depth import range overflows");
if (!GuestMemory::Accessible(reinterpret_cast<const void*>(plane.address), plane.bytes) || !GuestMemory::Watched(plane.address, plane.bytes)) return refuse("native multisample depth import requires watched accessible guest memory");
const MultisampleTextureLayout layout(TextureTileMode::kZ64KBX, 4u, target.samples, target.extent.width, target.extent.height, 1u, target.pipeBankXor);
if (layout.Bytes() != plane.bytes) return refuse("native multisample depth plane layout differs from its guarded range");
if (const auto alias = MultisampleColorTargetOver(plane.address, plane.bytes)) {
const auto depthValue = aliasedDepth(*alias, plane, target.samples);
if (!depthValue) {
reportAlias(*alias, plane, "depth");
return refuse(depthAliasRefusal);
}
state.aliasDepth = *depthValue;
}
if (auto* recorder = RecorderFor(context)) recorder->SyncThrough(plane.address, plane.bytes);
StorageTexture::FlushPending(plane.address, plane.bytes);
GuestMemory::FlushGpuWrites(plane.address, plane.bytes);
if (!GuestMemory::Accessible(reinterpret_cast<const void*>(plane.address), plane.bytes) || !GuestMemory::Watched(plane.address, plane.bytes)) return refuse("native multisample depth import requires watched accessible guest memory");
plane.generation = GuestMemory::CollectWritesUncached(plane.address, plane.bytes);
if (plane.generation == 0u) return refuse("native multisample depth import requires tracked generations");
if (state.aliasDepth) state.initialDepth = *state.aliasDepth;
else if (const auto* reason = readDepthPlane(context, target, layout, state)) return refuse(reason);
GuestMemory::CollectWritesUncached(plane.address, plane.bytes);
if (!GuestMemory::UnchangedSinceAll(state.initial)) return refuse("guest writes raced native multisample depth import");
return state;
}
DepthSamplingState prepareDepthSampling(const Context& context, const DepthTarget& target) {
DepthSamplingState state;
const auto refuse = [&](const char* reason) {
@@ -462,6 +563,7 @@ DepthSamplingState prepareDepthSampling(const Context& context, const DepthTarge
};
if (target.samples != 2u && target.samples != 4u && target.samples != 8u) return refuse("unsupported native depth sample count");
if (uniformPlaneTarget(target)) return prepareUniformPlaneSampling(context, target, std::move(state));
if (bareDepthTarget(target)) return prepareDepthPlaneSampling(context, target, std::move(state));
const bool stencil = target.format == VK_FORMAT_D32_SFLOAT_S8_UINT;
const bool stencilPlane = stencil && !target.htileStencil && target.htileDepthOnly;
if (target.format != VK_FORMAT_D16_UNORM && target.format != VK_FORMAT_D32_SFLOAT && !stencil) return refuse("native multisample stencil or depth format import is not implemented");
@@ -907,8 +1009,13 @@ public:
const VkClearDepthStencilValue clear{this->sampling.initialDepth.value_or(target.clearDepth), this->sampling.initialStencil.value_or(this->sampling.aliasStencil.value_or(target.clearStencil))};
context.Function<PFN_vkCmdClearDepthStencilImage>("vkCmdClearDepthStencilImage")(commands, image, VK_IMAGE_LAYOUT_GENERAL, &clear, 1, &toGeneral.subresourceRange);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);
std::vector<std::shared_ptr<void>> imported;
if (this->sampling.importedSamples != nullptr) importSamples(commands, recorder, imported);
if (batch) batch->SubmitAndWait();
else Recorder::CountBarriers(Recorder::CommandClass::Draw, 2);
else {
Recorder::CountBarriers(Recorder::CommandClass::Draw, 2);
for (auto& object : imported) recorder->Keep(std::move(object));
}
} catch (...) {
release();
throw;
@@ -939,7 +1046,7 @@ public:
if (stencilFillNote != 0u) pending->SyncThrough(sampling.initial[2].address, sampling.initial[2].bytes);
}
}
const auto newestHtileNote = recorder != nullptr ? recorder->NewestStoreNote(sampling.initial[1].address, sampling.initial[1].bytes) : 0u;
const auto newestHtileNote = recorder != nullptr && sampling.initial.size() > 1u ? recorder->NewestStoreNote(sampling.initial[1].address, sampling.initial[1].bytes) : 0u;
const bool queuedFill = clearPattern.has_value() && clearFillNote != 0u && newestHtileNote == clearFillNote;
const auto newestStencilNote = recorder != nullptr && sampling.initial.size() > 2u ? recorder->NewestStoreNote(sampling.initial[2].address, sampling.initial[2].bytes) : 0u;
const bool queuedStencilFill = stencilClearValue.has_value() && stencilFillNote != 0u && newestStencilNote == stencilFillNote;
@@ -964,7 +1071,7 @@ public:
if (index == 0u) depthValue = aliasedDepth(*alias, range, target.samples);
else if (index == 2u && separatePlane) stencilValue = aliasedStencil(*alias, range, target.samples);
bool kept = false;
if (depthValue) kept = std::bit_cast<std::uint32_t>(*depthValue) == std::bit_cast<std::uint32_t>(sampling.initialDepth.value_or(target.clearDepth));
if (depthValue) kept = !sampling.importedPerSample && std::bit_cast<std::uint32_t>(*depthValue) == std::bit_cast<std::uint32_t>(sampling.initialDepth.value_or(target.clearDepth));
else if (stencilValue) kept = stencilClearGeneration != 0u ? *stencilValue == *stencilClearValue : *stencilValue == sampling.aliasStencil;
const bool stencilRange = index == 2u || (index == 1u && uniform);
if (!kept) reportAlias(*alias, range, stencilRange ? "stencil plane" : index == 1u ? "HTILE" : "depth");
@@ -1028,7 +1135,7 @@ public:
const bool identity = stencil ? resource.format == 5u : resource.baseAddress == target.address && resource.format == (target.format == VK_FORMAT_D16_UNORM ? 7u : 22u);
Require(identity && resource.width == target.extent.width && resource.height == target.extent.height && resource.samples == target.samples, "native multisample depth sampled identity or format mismatch");
Require(resource.dimension == TextureDimension::k2DMsaa && resource.tileMode == TextureTileMode::kZ64KBX && resource.depthOrLastArray == 0u && resource.baseArray == 0u && resource.baseLevel == 0u && resource.lastLevel == 0u && resource.mipCount == 1u && resource.allocatedMipCount == 1u && resource.minLod == 0u, "native multisample depth sampled array, mip or layout is not implemented");
if (uniformPlaneTarget(target)) {
if (uniformPlaneTarget(target) || bareDepthTarget(target)) {
Require(resource.pipeBankXor == target.pipeBankXor && resource.dccAddress == 0u && !resource.dccAlphaOnMsb, "native multisample depth sampled metadata or XOR mismatch");
return;
}
@@ -1148,6 +1255,8 @@ public:
std::shared_ptr<Texture> Sampled(std::span<const std::uint32_t> words, const GuestTextureResource& resource, VkComponentMapping components, bool drawn = false, VkImageViewType multisampleViewType = VK_IMAGE_VIEW_TYPE_2D, bool copySource = false) {
if (!copySource) CheckCurrent();
CheckResource(resource);
const bool compressionEnabled = words.size() > 6u && ((words[6] >> 21u) & 1u) != 0u;
Require(!bareDepthTarget(target) || !compressionEnabled, "native multisample depth without HTILE sampled through a descriptor that enables HTILE compression is not implemented");
std::array<std::uint32_t, 13> key{};
std::copy_n(words.begin(), std::min<std::size_t>(words.size(), 8), key.begin());
key[8] = components.r;
@@ -1684,6 +1793,10 @@ public:
backingGeneration = 0;
}
const StorageTexture* MirrorStorage() const {
return mirrorPlane.storage.get();
}
bool AnyStale() const {
return staleCount != 0;
}
@@ -1692,6 +1805,10 @@ public:
depthMark = nextPlaneSerial();
}
bool AllStale() const {
return staleCount != 0 && staleCount == staleUnits.size();
}
void MarkAllStale(std::uint64_t planeBytes) {
SizeUnits(planeBytes);
staleUnits.assign(staleUnits.size(), true);
@@ -1805,6 +1922,7 @@ public:
unitGeneration.assign(unitGeneration.size(), generation);
return;
}
StorageTexture::NoteRefreshWork();
if (clearing) {
ClearStale();
ForgetClear(VK_IMAGE_ASPECT_DEPTH_BIT);
@@ -1851,6 +1969,7 @@ public:
const bool changed = stencilGeneration != 0u && GuestMemory::WrittenSince(resource.baseAddress, bytes, stencilGeneration);
stencilGeneration = generation;
if (!changed || (pendingClear & VK_IMAGE_ASPECT_STENCIL_BIT) != 0) return;
StorageTexture::NoteRefreshWork();
stencilStale = false;
{
struct Syncing {
@@ -1950,9 +2069,7 @@ private:
}
std::vector<std::byte> Expand() const {
std::vector<std::byte> bytes(range.bytes);
for (std::size_t offset = 0u; offset < bytes.size(); ++offset) bytes[offset] = Byte(offset);
return bytes;
return ExpandPagedSnapshot(range.bytes, words, starts, stored, PageBytes, Repeated);
}
};
std::vector<PublicationPlane> publication;
@@ -1961,7 +2078,7 @@ private:
std::exception_ptr publicationFailure;
void capturePublication() {
if (target.format != VK_FORMAT_D32_SFLOAT_S8_UINT || context.detiler == nullptr) return;
if ((target.format != VK_FORMAT_D32_SFLOAT_S8_UINT && !bareDepthTarget(target)) || context.detiler == nullptr) return;
try {
const auto lease = GuestAllocations::GuestAllocationsAcquireAll_nid_postfix();
CheckCurrent();
@@ -2109,6 +2226,74 @@ private:
return VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | (HasStencil(hostFormat) ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : 0u);
}
void importSamples(VkCommandBuffer commands, Recorder* recorder, std::vector<std::shared_ptr<void>>& kept) {
constexpr std::uint32_t sampleBytes = sizeof(float);
const auto staged = std::move(sampling.importedSamples);
Require(context.detiler != nullptr && hostFormat == VK_FORMAT_D32_SFLOAT, "importing native multisample depth samples requires a texture detiler and a D32 float host image");
kept.push_back(staged);
VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
info.flags = importedSampleFlags;
info.imageType = VK_IMAGE_TYPE_2D;
info.format = VK_FORMAT_R32_SFLOAT;
info.extent = {target.extent.width, target.extent.height, 1};
info.mipLevels = 1;
info.arrayLayers = 1;
info.samples = static_cast<VkSampleCountFlagBits>(target.samples);
info.tiling = VK_IMAGE_TILING_OPTIMAL;
const bool copied = sampling.importedByCopy;
info.usage = copied ? copiedSampleUsage : importedSampleUsage;
info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VkImage created = VK_NULL_HANDLE;
Check(context.Function<PFN_vkCreateImage>("vkCreateImage")(context.device, &info, nullptr, &created), "vkCreateImage native depth samples");
const auto source = std::make_shared<OwnedImage>(context, created, VK_NULL_HANDLE);
kept.push_back(source);
source->Allocate(context, info, "vkAllocateMemory native depth samples");
Check(context.Function<PFN_vkBindImageMemory>("vkBindImageMemory")(context.device, source->image, source->allocation.Memory(), source->allocation.Offset()), "vkBindImageMemory native depth samples");
const auto storage = std::make_shared<Texture>(context, source->image, TextureDetiler::ImageElementFormat(4u), VK_IMAGE_ASPECT_COLOR_BIT, VkComponentMapping{}, VK_IMAGE_VIEW_TYPE_2D_ARRAY, 0u, source, VK_IMAGE_USAGE_STORAGE_BIT);
kept.push_back(storage);
VkImageMemoryBarrier toGeneral{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
toGeneral.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
toGeneral.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
toGeneral.newLayout = VK_IMAGE_LAYOUT_GENERAL;
toGeneral.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
toGeneral.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
toGeneral.image = source->image;
toGeneral.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &toGeneral);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
const auto alignment = std::max<VkDeviceSize>(4u, context.limits.minStorageBufferOffsetAlignment);
const auto stride = context.limits.maxStorageBufferRange / alignment * alignment;
Require(stride != 0u, "importing native multisample depth samples needs a storage range of at least one aligned element");
const auto bytes = static_cast<std::uint64_t>(target.extent.width) * target.extent.height * target.samples * sampleBytes;
Require(staged->Bytes().size() >= bytes, "the staged native multisample depth samples do not cover the target");
for (std::uint64_t offset = 0u; offset < bytes; offset += stride) {
const auto count = std::min<std::uint64_t>(stride, bytes - offset);
context.detiler->DispatchMultisampleImage(commands, sampleBytes, staged->Handle(), offset, count, storage->View(), target.extent.width, target.extent.height, 1u, target.samples, static_cast<std::uint32_t>(offset / sampleBytes), static_cast<std::uint32_t>(count / sampleBytes));
}
if (copied) copySamples(commands, source->image);
else drawSamples(commands, recorder, source, kept);
if (recorder != nullptr) Recorder::CountBarriers(copied ? Recorder::CommandClass::Copy : Recorder::CommandClass::Draw, 4);
}
void drawSamples(VkCommandBuffer commands, Recorder* recorder, const std::shared_ptr<OwnedImage>& samples, std::vector<std::shared_ptr<void>>& kept) {
const auto sampled = std::make_shared<Texture>(context, samples->image, VK_FORMAT_R32_SFLOAT, VK_IMAGE_ASPECT_COLOR_BIT, VkComponentMapping{}, VK_IMAGE_VIEW_TYPE_2D, 0u, samples, VK_IMAGE_USAGE_SAMPLED_BIT);
kept.push_back(sampled);
CommandState batchState;
if (recorder == nullptr) batchState.Begin(commands);
auto& recording = recorder != nullptr ? recorder->GraphicsState() : batchState;
Require(recording.Commands() == commands, "the native multisample depth sample import draws outside the command buffer that imports it");
RecordDepthSampleImport(context, recording, {image, view, hostFormat, target.extent, target.samples, SampleOrderMethod::Depth, owned}, sampled->View(), kept);
}
void copySamples(VkCommandBuffer commands, VkImage samples) {
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT);
const VkImageCopy copy{{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, {0, 0, 0}, {VK_IMAGE_ASPECT_DEPTH_BIT, 0, 0, 1}, {0, 0, 0}, {target.extent.width, target.extent.height, 1}};
context.Function<PFN_vkCmdCopyImage>("vkCmdCopyImage")(commands, samples, VK_IMAGE_LAYOUT_GENERAL, image, VK_IMAGE_LAYOUT_GENERAL, 1, &copy);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
directDepthCopies.fetch_add(1, std::memory_order_relaxed);
}
void createSampleShadow() {
VkImage image = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
@@ -2986,9 +3171,10 @@ void DepthSurface::PublishToGuest() {
} scope{publicationInProgress};
publicationInProgress = true;
if (publicationFailure) std::rethrow_exception(publicationFailure);
const bool htile = !uniformPlaneTarget(target);
Require(target.format == VK_FORMAT_D32_SFLOAT_S8_UINT && hostFormat == target.format && publication.size() == (htile ? 3u : 2u), "sample-preserving guest publication of native multisample depth is not implemented for this owner");
const std::size_t stencilPlane = publication.size() - 1u;
const bool bare = bareDepthTarget(target);
const bool htile = !uniformPlaneTarget(target) && !bare;
const bool publishable = bare ? publication.size() == 1u : target.format == VK_FORMAT_D32_SFLOAT_S8_UINT && publication.size() == (htile ? 3u : 2u);
Require(publishable && hostFormat == target.format, "sample-preserving guest publication of native multisample depth is not implemented for this owner");
Require(sampling.refusal.empty(), sampling.refusal);
RequireStencilProven();
Require(!clearPending && clearGeneration == 0u && stencilClearGeneration == 0u && pendingClear == 0u, "native multisample depth publication with an unapplied clear is not implemented");
@@ -3023,18 +3209,19 @@ void DepthSurface::PublishToGuest() {
Require(active->load(std::memory_order_acquire), "the native multisample depth owner was released during publication");
if (useSampleShadow) {
if (sampleShadow == nullptr) createSampleShadow();
refreshSampleShadow(true, true);
refreshSampleShadow(true, HasStencil(hostFormat));
if (auto* recorder = RecorderFor(context)) recorder->Sync();
}
std::array<std::vector<std::byte>, 3> result;
for (const std::size_t index : {std::size_t{0u}, stencilPlane}) {
for (std::size_t index = 0u; index < publication.size(); ++index) {
if (htile && index == 1u) continue;
const auto elementBytes = index == 0u ? 4u : 1u;
const auto aspect = index == 0u ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_STENCIL_BIT;
const MultisampleTextureLayout layout(TextureTileMode::kZ64KBX, elementBytes, target.samples, target.extent.width, target.extent.height, 1u, target.pipeBankXor);
Require(layout.Bytes() == publication[index].range.bytes, "native multisample depth publication layout differs from its guarded range");
const auto linear = readBackSamples(aspect, layout.LinearBytes() / elementBytes);
result[index] = publication[index].Expand();
layout.Tile(linear->Bytes().first(static_cast<std::size_t>(layout.LinearBytes())), result[index]);
layout.TileHoisted(linear->Bytes().first(static_cast<std::size_t>(layout.LinearBytes())), result[index]);
}
if (htile) {
result[1] = publication[1].Expand();
@@ -3548,6 +3735,7 @@ void retireStoringStale(DepthSurface& surface) {
const auto resource = mirrorResource(surface.target);
const auto planeBytes = surface.MirrorBytes();
std::uint64_t generation = 0;
GuestMemory::CollectWritesUncached(surface.target.address, static_cast<std::size_t>(planeBytes));
const auto written = surface.WrittenUnits(resource, generation);
const auto removed = unmappedUnits(surface.target.address, planeBytes, surface.unitBytes, surface.staleUnits.size(), surface.depthMark);
const auto reused = surface.ChangedBackingUnits();
@@ -3747,6 +3935,91 @@ float HostDepthBiasConstant(const Context& context, VkFormat format, float const
return constant * 256.0f;
}
VkImageView RepeatDepthSurfaceView(const Context& context, const DepthTarget& target, bool depthWritten, bool stencilWritten) {
if (target.depthPartiallyResident || target.stencilPartiallyResident) return VK_NULL_HANDLE;
std::lock_guard gpu(GuestMemory::GpuMutex());
std::lock_guard lock(surfacesMutex());
auto* surface = drawnDepth;
if (surface == nullptr || target.samples != 1u || surface->retired || surface->syncing || surface->pendingClear != 0u || surface->context.device != context.device || !surface->active->load(std::memory_order_acquire) || !sameSurface(surface->target, target)) return VK_NULL_HANDLE;
surface->written = ++depthWrites;
if (depthWritten && mirrorable(target)) {
surface->NoteDepthWork();
if (!surface->AllStale()) {
const auto planeBytes = surface->MirrorBytes();
surface->MarkAllStale(planeBytes);
noteStalePlane(target.address, target.address + planeBytes);
}
}
if (stencilWritten) surface->MarkStencilStale(true);
return surface->view;
}
const char* DepthPlanesObligation(VkDevice device, std::uint64_t address, std::uint64_t bytes) {
std::lock_guard gpu(GuestMemory::GpuMutex());
std::lock_guard lock(surfacesMutex());
for (const auto& surface : surfaces()) {
if (surface->context.device != device || !surface->Overlaps(address, bytes)) continue;
if (surface->AnyStale()) return "a depth plane to store";
if (!surface->retired) return "a depth surface to retire";
}
return nullptr;
}
const char* DepthTargetObligation(const Context& context, const DepthTarget& target, bool depthWritten) {
const bool nativeOwner = RoutesToNativeDepthOwner(target);
std::lock_guard gpu(GuestMemory::GpuMutex());
std::lock_guard lock(surfacesMutex());
DepthSurface* surface = nullptr;
for (const auto& candidate : surfaces()) {
if (candidate->active->load(std::memory_order_acquire) && candidate->context.device == context.device && sameSurface(candidate->target, target)) {
surface = candidate.get();
break;
}
}
if (surface == nullptr || surface != drawnDepth) return "another depth surface";
if (surface->pendingClear != 0u) return "a pending depth clear";
if (depthWritten && mirrorable(target) && !surface->AnyStale()) return "marking a depth write";
if (target.htileAddress != 0u) {
const auto& cleared = clearedHtiles();
if (std::ranges::any_of(cleared, [&](const auto& entry) { return HtileFillCovers(target.htileAddress, target.extent, entry.first, entry.second); })) return "an HTILE clear to take";
const auto bytes = static_cast<std::size_t>(HtileMetadataBytes(target.extent));
auto* recorder = RecorderFor(context);
const VkImageAspectFlags aspects = VK_IMAGE_ASPECT_DEPTH_BIT | (target.htileStencil ? VK_IMAGE_ASPECT_STENCIL_BIT : 0u);
if (recorder != nullptr && recorder->PendingWriteOverlaps(target.htileAddress, bytes)) {
const auto landed = htileAfterPendingFills(*recorder, target.htileAddress, bytes);
if (landed.has_value() ? (aspects & HtileFillClears(*landed, target.htileStencil)) != 0u : htileAfterMaskClear(*recorder, target, bytes).has_value()) return "a pending HTILE clear";
} else if (!nativeOwner) {
const std::span words(reinterpret_cast<const std::uint32_t*>(target.htileAddress), bytes / 4u);
VkImageAspectFlags clears = aspects;
for (const auto word : words) clears &= HtileFillClears(word, target.htileStencil);
if (clears != 0u) return "an HTILE clear to store back";
}
}
const auto owner = depthOwners().find({context.device, target.address});
if (owner != depthOwners().end() && owner->second.surface != surface && owner->second.surface->active->load(std::memory_order_acquire) && !owner->second.surface->retired) return "a plane ownership move";
if (!surface->AnyStale() && surface->MirrorStorage() != nullptr) {
if (const auto* owed = surface->MirrorStorage()->RefreshObligation()) return owed;
}
return nullptr;
}
bool DepthTargetOverlaps(const DepthTarget& target, std::uint64_t address, std::uint64_t bytes) {
if (bytes == 0u) return false;
const auto limit = std::numeric_limits<std::uint64_t>::max();
if (address > limit - bytes || target.firstSlice != 0u || target.lastSlice != 0u) return true;
const auto dimensionLimit = std::numeric_limits<std::uint32_t>::max() - 1023u;
if (target.extent.width == 0u || target.extent.height == 0u || target.extent.width > dimensionLimit || target.extent.height > dimensionLimit) return true;
if (target.samples != 1u && target.samples != 2u && target.samples != 4u && target.samples != 8u) return true;
if (target.samples != 1u && (target.extent.width > 16384u || target.extent.height > 16384u)) return true;
if (static_cast<std::uint64_t>(target.extent.width) + 1023u > limit / (static_cast<std::uint64_t>(target.extent.height) + 1023u) / 4u / target.samples) return true;
const auto overlaps = [&](std::uint64_t begin, std::uint64_t size) {
return size != 0u && (begin > limit - size || (address < begin + size && begin < address + bytes));
};
const auto planeBytes = [&](std::uint32_t bytesPerTexel) { return target.samples == 1u ? DepthSliceBytes(target.extent, bytesPerTexel) : MultisampledDepthBytes_nid_no_patch(target.extent, bytesPerTexel, target.samples); };
const bool d16 = target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT;
return overlaps(target.address, planeBytes(d16 ? 2u : 4u)) || (target.stencilAddress != 0u && overlaps(target.stencilAddress, planeBytes(1u))) || (target.htileAddress != 0u && overlaps(target.htileAddress, HtileMetadataBytes(target.extent)));
}
namespace {
bool resident(std::uint64_t address, std::uint64_t bytes) {
Loaded 100 of 2301 files, more files were not shown because too many files have changed in this diff. Show more