Merge main into feat/shader-nested-sampler-tables
Moves this branch's FormatVersion to 93, above main's 88 (#18455).
This commit is contained in:
commit
3c58f422ee
2229 files changed
+118969
-10983
No files matched your search
@@ -7,7 +7,7 @@
|
||||
<!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md -->
|
||||
- [ ] Based on current `main`; no other open PR implements the same functions
|
||||
- [ ] One topic per PR; follow-ups go in a new PR
|
||||
- [ ] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md)
|
||||
- [ ] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) and the licence notice of code adapted from upstream (see AGENTS.md)
|
||||
- [ ] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file
|
||||
- [ ] No notes, investigation `.md` files or images added to the repository (attach them to this PR)
|
||||
- [ ] New third-party code is a submodule built from source
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
name: Bug report tools
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- .github/workflows/bug-report-tools.yml
|
||||
- tools/bug_report.py
|
||||
- tools/tests/test_bug_report.py
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: bug-report-tools-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
bug-report:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Test bug report bundle
|
||||
run: python3 tools/tests/test_bug_report.py
|
||||
@@ -356,7 +356,13 @@ jobs:
|
||||
- run: |
|
||||
repeat=()
|
||||
if [ "$RUNNER_OS" = Windows ]; then repeat=(--repeat after-timeout:2); fi
|
||||
ctest --test-dir build-relinker --output-on-failure --timeout 120 --parallel 4 --no-tests=error "${repeat[@]}"
|
||||
ctest --test-dir build-relinker --output-on-failure --timeout 120 --parallel 4 --no-tests=error "${repeat[@]}" --output-log ctest.log
|
||||
- name: Report tests slower than 30 s
|
||||
if: ${{ !cancelled() }}
|
||||
run: |
|
||||
[ -f ctest.log ] || exit 0
|
||||
awk '/Test +#[0-9]+: / && $NF == "sec" { for (i = 1; i <= NF; i++) if ($i ~ /^#[0-9]+:$/) name = $(i + 1); t = $(NF - 1) + 0; if (t > max[name]) max[name] = t }
|
||||
END { for (name in max) if (max[name] > 30) printf "::warning title=Slow test::%s took %.1f s on %s; tests must finish in 30 s (CONTRIBUTING.md)\n", name, max[name], ENVIRON["RUNNER_OS"] }' ctest.log
|
||||
|
||||
relinker-asan:
|
||||
needs: eligibility
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
name: Conflict label (PR)
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [synchronize, reopened]
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: conflict-label-pr-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
pr:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
pull-requests: write
|
||||
steps:
|
||||
- env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
run: |
|
||||
for attempt in $(seq 1 20); do
|
||||
state=$(gh api "repos/$GH_REPO/pulls/$PR" --jq '"\(.mergeable) \(any(.labels[]; .name == "needs rebase"))"')
|
||||
read -r mergeable labeled <<< "$state"
|
||||
[ "$mergeable" != null ] && break
|
||||
sleep 15
|
||||
done
|
||||
if [ "$mergeable" = true ] && [ "$labeled" = true ]; then
|
||||
if ! gh api -X DELETE "repos/$GH_REPO/issues/$PR/labels/needs%20rebase" --silent; then
|
||||
labeled=$(gh api "repos/$GH_REPO/pulls/$PR" --jq 'any(.labels[]; .name == "needs rebase")')
|
||||
[ "$labeled" = false ]
|
||||
fi
|
||||
elif [ "$mergeable" = false ] && [ "$labeled" = false ]; then
|
||||
gh api "repos/$GH_REPO/issues/$PR/labels" -f 'labels[]=needs rebase' --silent
|
||||
fi
|
||||
@@ -97,6 +97,9 @@
|
||||
[submodule "3rdparty/libpsl"]
|
||||
path = 3rdparty/libpsl
|
||||
url = https://github.com/rockdaboot/libpsl.git
|
||||
[submodule "3rdparty/libwpe"]
|
||||
path = 3rdparty/libwpe
|
||||
url = https://github.com/WebPlatformForEmbedded/libwpe.git
|
||||
[submodule "3rdparty/icu"]
|
||||
path = 3rdparty/icu
|
||||
url = https://github.com/unicode-org/icu.git
|
||||
|
||||
+1
Submodule 3rdparty/libwpe added at b90a839686.
@@ -2,11 +2,11 @@
|
||||
|
||||
AnyPS5 relinks PS5 executables into native Linux or Windows programs that run against reimplemented system libraries; it is not an emulator. The rules are [CONTRIBUTING.md](CONTRIBUTING.md) and [CONVENTIONS](docs/dev/CONVENTIONS.md); these are the ones agents break.
|
||||
|
||||
- No comments in code, except `#endif` and namespace ends.
|
||||
- No comments in code, except `#endif`, namespace ends, and the licence and copyright notice of code adapted from an upstream source (for example ICU or WebRTC). That notice stays verbatim at the top of the file, with a link to the pinned upstream commit. Attribution facts and known gaps still go in `docs/dev/debt/<library>.md`.
|
||||
- An export you cannot implement calls `NotImplemented_nid_no_patch(__func__)`; never return a made-up success.
|
||||
- Implement the function for every input. Never special-case a value, ID or path seen in one title's trace; if the general behaviour is unknown, throw and record it in `docs/dev/debt/<library>.md`.
|
||||
- New third-party code is a submodule at `3rdparty/<name>`: add its `.gitmodules` entry (`git submodule add <url> 3rdparty/<name>`) and build it from source with CMake. Never `find_package` or copy sources in.
|
||||
- Known gaps go in `docs/dev/debt/<library>.md`; notes, reports and logs go in the pull request. Add no other files.
|
||||
- Known gaps go in `docs/dev/debt/<library>.md`, added, changed or removed through a fragment in `docs/dev/debt/changes/` ([format](docs/dev/TechnicalDebt.md#fragments)); notes, reports and logs go in the pull request. Add no other files.
|
||||
- Commit subjects and PR titles are Conventional Commits.
|
||||
- PR body: copy [the template](.github/pull_request_template.md), keep every line, tick every box, and fill `What`, `Tested`, `Depends on` (#N or none), `Fixes` (Fixes #N or none), `Unblocks` (title ID and discussion, or none), `GPUs tested` (AGC, shader recompiler, VideoOut; otherwise n/a) and `AI-assisted` (yes or no).
|
||||
- Before starting a function run `python3 tools/pr_overlap.py --names <function>`; before pushing run `python3 tools/check_conventions.py --base origin/main`; before opening run `python3 tools/pr_overlap.py --branch <branch>`.
|
||||
|
||||
+51
-3
@@ -33,7 +33,7 @@ function(add_test_executable target)
|
||||
set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "$<1:${ANYPS5_TEST_OUTPUT_DIRECTORY}>")
|
||||
endif()
|
||||
if(MINGW)
|
||||
target_sources(${target} PRIVATE $<TARGET_OBJECTS:anyps5_windows_test_exit> "${CMAKE_BINARY_DIR}/WindowsManifest.rc")
|
||||
target_sources(${target} PRIVATE $<TARGET_OBJECTS:anyps5_windows_test_exit> $<TARGET_OBJECTS:anyps5_windows_test_manifest>)
|
||||
set_property(GLOBAL APPEND PROPERTY ANYPS5_TEST_EXECUTABLES ${target})
|
||||
target_link_options(${target} PRIVATE LINKER:--wrap=main)
|
||||
target_link_options(${target} PRIVATE LINKER:--disable-high-entropy-va)
|
||||
@@ -209,6 +209,7 @@ endif()
|
||||
|
||||
if(MINGW)
|
||||
add_library(anyps5_windows_test_exit OBJECT cmake/WindowsTestExit.cpp)
|
||||
add_library(anyps5_windows_test_manifest OBJECT "${CMAKE_BINARY_DIR}/WindowsManifest.rc")
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTING)
|
||||
@@ -262,6 +263,10 @@ if(BUILD_TESTING)
|
||||
target_include_directories(pad_command_file_tests PRIVATE core/libs)
|
||||
add_test(NAME pad_command_file COMMAND pad_command_file_tests)
|
||||
set_tests_properties(pad_command_file PROPERTIES TIMEOUT 20)
|
||||
add_test_executable(pad_recording_tests core/libs/prx/libScePad/tests/PadRecording.cpp)
|
||||
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)
|
||||
if(Python3_Interpreter_FOUND)
|
||||
get_property(windows_tooling_before DIRECTORY PROPERTY TESTS)
|
||||
add_test(NAME mingw_host_only_test_targets COMMAND ${Python3_EXECUTABLE}
|
||||
@@ -332,6 +337,8 @@ if(BUILD_TESTING)
|
||||
add_test(NAME tools_progress_diff_json COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_diff_json.py)
|
||||
set_tests_properties(tools_progress_diff_json PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME tools_progress_diff COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_diff.py)
|
||||
add_test(NAME progress_wrappers COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_wrappers.py)
|
||||
add_test(NAME progress_read_encoding COMMAND ${Python3_EXECUTABLE}
|
||||
@@ -419,6 +426,7 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(performance_bisect PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME emsdk_pin COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_emsdk_pin.py)
|
||||
set_tests_properties(emsdk_pin PROPERTIES TIMEOUT 20)
|
||||
set(conventions_wrapped_declarations_source "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_wrapped_declarations.py")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${conventions_wrapped_declarations_source}")
|
||||
file(STRINGS "${conventions_wrapped_declarations_source}" conventions_wrapped_declarations_cases REGEX "^class [A-Za-z0-9_]*Tests\\(|^ def test_")
|
||||
@@ -441,13 +449,16 @@ if(BUILD_TESTING)
|
||||
endforeach()
|
||||
add_test(NAME conventions_ci_gate COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_ci_gate.py)
|
||||
set_tests_properties(conventions_ci_gate PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME preview_pad_timeline COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_preview_pad_timeline.py)
|
||||
set_tests_properties(preview_pad_timeline PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME conventions_git_errors COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_git.py)
|
||||
set_tests_properties(conventions_git_errors PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME tools_base_ref COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_base_ref.py)
|
||||
set_tests_properties(tools_base_ref PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME tools_configure_diff COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_compare_configure_checks.py)
|
||||
set_tests_properties(tools_configure_diff PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME ctest_no_tests_flag COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_ctest_no_tests_flag.py)
|
||||
@@ -461,6 +472,9 @@ if(BUILD_TESTING)
|
||||
add_test(NAME conventions_debt_length COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_debt_length.py)
|
||||
set_tests_properties(conventions_debt_length PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME conventions_debt_fragments COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_debt_fragments.py)
|
||||
set_tests_properties(conventions_debt_fragments PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME conventions_debt_labels COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_debt_labels.py)
|
||||
set_tests_properties(conventions_debt_labels PROPERTIES TIMEOUT 20)
|
||||
@@ -492,9 +506,20 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(tools_pe_inventory PROPERTIES TIMEOUT 20)
|
||||
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_skips COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py)
|
||||
set_tests_properties(check_skips PROPERTIES TIMEOUT 20)
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py
|
||||
SkipJsonTests RequiredTestsTests SkipReportTests NotRunTests)
|
||||
add_test(NAME check_skips_privilege COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py CheckSkipsTests)
|
||||
add_test(NAME check_skips_ctest_policy COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py CtestSkipPolicyTests)
|
||||
add_test(NAME check_skips_device_policy COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py DeviceSkipPolicyTests)
|
||||
add_test(NAME check_skips_cli_output COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py SkipCliOutputTests)
|
||||
set_tests_properties(check_skips check_skips_privilege check_skips_ctest_policy
|
||||
check_skips_device_policy check_skips_cli_output PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME relinker_seed_manifest COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_relinker_seed_manifest.py)
|
||||
set_tests_properties(relinker_seed_manifest PROPERTIES TIMEOUT 20)
|
||||
@@ -542,15 +567,19 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(relinker_fuzz_configurations PROPERTIES TIMEOUT 30)
|
||||
add_test(NAME configure_seed COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedTests)
|
||||
set_tests_properties(configure_seed PROPERTIES TIMEOUT 30)
|
||||
add_test(NAME configure_seed_paths COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedPathTests)
|
||||
set_tests_properties(configure_seed_paths PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME configure_seed_round_trips COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedRoundTripTests)
|
||||
set_tests_properties(configure_seed_round_trips PROPERTIES TIMEOUT 30)
|
||||
add_test(NAME configure_seed_stdout COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedStdoutTests)
|
||||
set_tests_properties(configure_seed_stdout PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME configure_seed_parsing COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ChecksParsingTests)
|
||||
set_tests_properties(configure_seed_parsing PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME vulkan_validation_gate_reports COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_vulkan_validation_gate.py ReportTests)
|
||||
add_test(NAME vulkan_validation_gate_integration COMMAND ${Python3_EXECUTABLE}
|
||||
@@ -601,6 +630,8 @@ if(BUILD_TESTING)
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_debt_report.py)
|
||||
add_test(NAME agc_test_split COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_agc_test_split.py)
|
||||
add_test(NAME debt_fold COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_debt_fold.py)
|
||||
add_test(NAME stubgen_stdout_newlines COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_stubgen_stdout_newlines.py)
|
||||
add_test(NAME hardware_oracle COMMAND ${Python3_EXECUTABLE}
|
||||
@@ -660,6 +691,9 @@ if(BUILD_TESTING)
|
||||
add_test(NAME pad_input COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pad_input.py)
|
||||
set_tests_properties(pad_input PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME harfbuzz_icu_script_names COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_harfbuzz_icu_script_names.py)
|
||||
set_tests_properties(harfbuzz_icu_script_names PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME stale_conflicts_workflow COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_stale_conflicts_workflow.py)
|
||||
add_test(NAME pad_timeline COMMAND ${Python3_EXECUTABLE}
|
||||
@@ -723,18 +757,22 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(tools_annotation_symbols_json PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME conventions_body_bom COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_body_bom.py)
|
||||
set_tests_properties(conventions_body_bom PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME conventions_blob_reads COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_blob_reads.py)
|
||||
set_tests_properties(conventions_blob_reads PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME ab_split_csv COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_ab_split_csv.py)
|
||||
set_tests_properties(ab_split_csv PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME conventions_agent_files COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_agent_files.py)
|
||||
set_tests_properties(conventions_agent_files PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME tools_nid_offline COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_nid_offline.py)
|
||||
set_tests_properties(tools_nid_offline PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME conventions_alignment COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_alignment.py)
|
||||
set_tests_properties(conventions_alignment PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME tools_intervals_complete COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_intervals_complete.py)
|
||||
set_tests_properties(tools_intervals_complete PROPERTIES TIMEOUT 20)
|
||||
@@ -809,6 +847,13 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(tools_seed_check PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME tools_cmake_fuzzer_sanitizers COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_cmake_fuzzer_sanitizers.py)
|
||||
set_tests_properties(tools_cmake_fuzzer_sanitizers PROPERTIES TIMEOUT 120)
|
||||
|
||||
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)
|
||||
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)
|
||||
@@ -923,6 +968,9 @@ set(LIBUSB_INSTALL_TARGETS OFF CACHE BOOL "" FORCE)
|
||||
set(LIBUSB_BUILD_TESTING OFF CACHE BOOL "" FORCE)
|
||||
set(LIBUSB_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
|
||||
set(LIBUSB_ENABLE_UDEV OFF CACHE BOOL "" FORCE)
|
||||
if(APPLE)
|
||||
set(HAVE_PIPE2 "" CACHE INTERNAL "")
|
||||
endif()
|
||||
add_subdirectory(3rdparty/libusb-cmake EXCLUDE_FROM_ALL)
|
||||
set_target_properties(usb-1.0 PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
|
||||
+8
-1
@@ -14,7 +14,7 @@
|
||||
- Avoid non-standard extensions (`__attribute__`, etc.) where standard C++ is enough. Helper symbols that must not become NIDs use the `_nid_no_patch` or `_nid_no_patch_cut` suffix.
|
||||
- `alignas` takes at most 8192: MinGW GCC, the Windows compiler, rejects static objects aligned above it. A larger block is aligned at run time inside a bigger buffer.
|
||||
- The relinker uses only the C++20 standard library.
|
||||
- Third-party code is added as a submodule under `3rdparty/` and built from source, not found on the system. With `ANYPS5_USE_SYSTEM_DEPS=ON` the packages packaged by the distributions (SDL2, freetype, Vulkan-Headers, SPIRV-Headers, glslang and SPIRV-Tools) come from the system instead; that resolution lives in [cmake/SystemDeps.cmake](cmake/SystemDeps.cmake) and the default build never reads the system.
|
||||
- Third-party code is added as a submodule under `3rdparty/` and built from source, not found on the system. With `ANYPS5_USE_SYSTEM_DEPS=ON` the packages packaged by the distributions (SDL2, freetype, Vulkan-Headers, SPIRV-Headers, glslang and SPIRV-Tools, the last only with `ANYPS5_ENABLE_SPIRV_TOOLS=ON`) come from the system instead; that resolution lives in [cmake/SystemDeps.cmake](cmake/SystemDeps.cmake) and the default build never reads the system.
|
||||
- Don't add tests that only check that a symbol is exported: a missing export already fails at startup.
|
||||
- Each test finishes in 30 s on the CI runners, Vulkan tests included (Linux runs them on lavapipe), counting the first run with no shader cache. ctest runs in parallel there, so a slow test competes for the cores and times out on some runs and not others. Split or shrink a test that gets close instead of raising its timeout. CI reports every test over 30 s as a warning on the pull request.
|
||||
|
||||
@@ -59,6 +59,7 @@ The [pull request template](.github/pull_request_template.md) is the checklist f
|
||||
- One branch per topic, based on current `main`. Follow-up work goes in a new pull request, not into an open one.
|
||||
- Open pull requests per author are limited by how many of theirs are merged into `main`: 1 with none merged, 20 with at least 1, no limit from 20. A pull request opened or reopened over the limit is closed automatically; reopen it once another one is merged or closed.
|
||||
- Before starting, check that no open pull request already implements the same functions: `python3 tools/pr_overlap.py --names <function>...` prints, for each name, whether `main` implements it or still stubs it and which open pull requests add it.
|
||||
- Technical debt entries are added, changed and removed through a fragment in `docs/dev/debt/changes/`, not by editing the debt files; the format is in [technical debt](docs/dev/TechnicalDebt.md#fragments).
|
||||
- Keep the branch up to date with `main` and resolve conflicts yourself; rebasing and force-pushing is fine.
|
||||
- An AGC test executable and its tests are registered in `core/libs/prx/libSceAgcDriver/tests/cmake/<executable>.cmake`; the tests of an execution test in `tests/execution/` go in the fragment of its `agc_driver_<name>_tests` executable. `CMakeLists.txt` includes the fragments in sorted order, so a fragment uses nothing another fragment defines. A pull request whose change to `libSceAgcDriver/CMakeLists.txt` conflicts after the split rebases and runs `python3 tools/agc_test_split.py resolve` during the stopped rebase, which moves its registrations to their fragments and leaves conflict markers where `main` changed the same lines.
|
||||
- A new libc or libkernel test executable and its tests are registered in `core/libs/prx/libc/tests/cmake/<executable>.cmake` or `core/libs/prx/libkernel/tests/cmake/<executable>.cmake`. That library's `CMakeLists.txt` includes the fragments in sorted order after its own registrations, so a fragment can use what `CMakeLists.txt` defines but nothing another fragment defines. Tests already registered in `CMakeLists.txt` stay there.
|
||||
@@ -80,3 +81,9 @@ The [pull request template](.github/pull_request_template.md) is the checklist f
|
||||
## Documentation
|
||||
|
||||
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.
|
||||
|
||||
## 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`.
|
||||
- `tools/pr_labels.py (--pr N | --all) [--dry-run] [--json]` labels pull requests from their title and template fields. `--dry-run` prints the planned changes and writes nothing.
|
||||
- `tools/pr_unchanged.py [--dry-run]` labels open pull requests whose merge would not change `main`. `--dry-run` prints the planned changes and writes nothing.
|
||||
+17
-17
@@ -91,24 +91,24 @@ add_library(icu_common STATIC EXCLUDE_FROM_ALL
|
||||
${ICU_SOURCE_DIR}/common/uvector.cpp
|
||||
${ICU_SOURCE_DIR}/common/uvectr32.cpp
|
||||
${ICU_SOURCE_DIR}/stubdata/stubdata.cpp)
|
||||
target_sources(icu_common PRIVATE
|
||||
${ICU_SOURCE_DIR}/common/fixedstring.cpp
|
||||
${ICU_SOURCE_DIR}/common/localebuilder.cpp
|
||||
${ICU_SOURCE_DIR}/common/locid.cpp
|
||||
${ICU_SOURCE_DIR}/common/loclikely.cpp
|
||||
${ICU_SOURCE_DIR}/common/loclikelysubtags.cpp
|
||||
${ICU_SOURCE_DIR}/common/lsr.cpp
|
||||
${ICU_SOURCE_DIR}/common/resource.cpp
|
||||
${ICU_SOURCE_DIR}/common/ucol_swp.cpp
|
||||
${ICU_SOURCE_DIR}/common/uloc.cpp
|
||||
${ICU_SOURCE_DIR}/common/uloc_keytype.cpp
|
||||
${ICU_SOURCE_DIR}/common/uloc_tag.cpp
|
||||
${ICU_SOURCE_DIR}/common/uresbund.cpp
|
||||
${ICU_SOURCE_DIR}/common/uresdata.cpp
|
||||
${ICU_SOURCE_DIR}/common/ustrenum.cpp
|
||||
${ICU_SOURCE_DIR}/common/utypes.cpp)
|
||||
if(WIN32)
|
||||
target_sources(icu_common PRIVATE
|
||||
${ICU_SOURCE_DIR}/common/fixedstring.cpp
|
||||
${ICU_SOURCE_DIR}/common/localebuilder.cpp
|
||||
${ICU_SOURCE_DIR}/common/locid.cpp
|
||||
${ICU_SOURCE_DIR}/common/loclikely.cpp
|
||||
${ICU_SOURCE_DIR}/common/loclikelysubtags.cpp
|
||||
${ICU_SOURCE_DIR}/common/lsr.cpp
|
||||
${ICU_SOURCE_DIR}/common/resource.cpp
|
||||
${ICU_SOURCE_DIR}/common/ucol_swp.cpp
|
||||
${ICU_SOURCE_DIR}/common/uloc.cpp
|
||||
${ICU_SOURCE_DIR}/common/uloc_keytype.cpp
|
||||
${ICU_SOURCE_DIR}/common/uloc_tag.cpp
|
||||
${ICU_SOURCE_DIR}/common/uresbund.cpp
|
||||
${ICU_SOURCE_DIR}/common/uresdata.cpp
|
||||
${ICU_SOURCE_DIR}/common/ustrenum.cpp
|
||||
${ICU_SOURCE_DIR}/common/utypes.cpp
|
||||
${ICU_SOURCE_DIR}/common/wintz.cpp)
|
||||
target_sources(icu_common PRIVATE ${ICU_SOURCE_DIR}/common/wintz.cpp)
|
||||
endif()
|
||||
target_include_directories(icu_common SYSTEM PUBLIC ${ICU_SOURCE_DIR}/common)
|
||||
target_compile_definitions(icu_common PUBLIC U_STATIC_IMPLEMENTATION PRIVATE U_COMMON_IMPLEMENTATION UCONFIG_NO_FILE_IO=1 UCONFIG_USE_WINDOWS_LCID_MAPPING_API=0)
|
||||
|
||||
@@ -45,3 +45,4 @@ if(UNIX)
|
||||
target_link_libraries(jxr PRIVATE m)
|
||||
endif()
|
||||
set_source_files_properties(${JXR_SOURCE_DIR}/image/decode/postprocess.c PROPERTIES COMPILE_OPTIONS -fwrapv)
|
||||
target_compile_options(jxr PRIVATE $<$<C_COMPILER_ID:GNU,Clang,AppleClang>:-fno-sanitize=shift>)
|
||||
@@ -0,0 +1,30 @@
|
||||
function(add_bundled_libwpe_key_unicode)
|
||||
if(TARGET wpe_key_unicode)
|
||||
return()
|
||||
endif()
|
||||
|
||||
set(WPE_SOURCE_DIR ${CMAKE_SOURCE_DIR}/3rdparty/libwpe)
|
||||
if(NOT EXISTS ${WPE_SOURCE_DIR}/src/key-unicode.c)
|
||||
message(FATAL_ERROR "libwpe: ${WPE_SOURCE_DIR}/src/key-unicode.c is missing; initialize the submodule with git submodule update --init 3rdparty/libwpe")
|
||||
endif()
|
||||
|
||||
add_library(wpe_key_unicode STATIC EXCLUDE_FROM_ALL ${WPE_SOURCE_DIR}/src/key-unicode.c)
|
||||
target_include_directories(wpe_key_unicode PUBLIC ${WPE_SOURCE_DIR}/include)
|
||||
target_compile_definitions(wpe_key_unicode
|
||||
PUBLIC
|
||||
__WPE_H_INSIDE__
|
||||
wpe_export_h
|
||||
WPE_EXPORT=
|
||||
PRIVATE
|
||||
WPE_COMPILATION
|
||||
)
|
||||
set_target_properties(wpe_key_unicode PROPERTIES
|
||||
POSITION_INDEPENDENT_CODE ON
|
||||
C_VISIBILITY_PRESET hidden
|
||||
)
|
||||
if(MINGW OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
target_link_options(wpe_key_unicode INTERFACE LINKER:--exclude-libs,libwpe_key_unicode.a)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
add_bundled_libwpe_key_unicode()
|
||||
@@ -6,7 +6,10 @@ function(add_png_decoder target runtimeTarget)
|
||||
add_library(${target} STATIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/src/Png.cpp)
|
||||
target_include_directories(${target} PUBLIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/include)
|
||||
target_include_directories(${target} SYSTEM PRIVATE ${PROJECT_SOURCE_DIR}/3rdparty/stb)
|
||||
target_link_libraries(${target} PRIVATE ${runtimeTarget})
|
||||
target_link_libraries(${target} PRIVATE ${runtimeTarget} zlibstatic)
|
||||
if(MINGW OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
target_link_options(${target} INTERFACE "LINKER:--exclude-libs,$<TARGET_FILE_NAME:zlibstatic>")
|
||||
endif()
|
||||
set_target_properties(${target} PROPERTIES
|
||||
CXX_EXTENSIONS OFF
|
||||
CXX_VISIBILITY_PRESET hidden
|
||||
|
||||
@@ -7,11 +7,7 @@
|
||||
#include <cstdlib>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
|
||||
#define STB_IMAGE_WRITE_STATIC
|
||||
#define STB_IMAGE_WRITE_IMPLEMENTATION
|
||||
#define STBI_WRITE_NO_STDIO
|
||||
#include "stb_image_write.h"
|
||||
#include "zlib.h"
|
||||
|
||||
#define STB_IMAGE_STATIC
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
@@ -250,11 +246,13 @@ std::vector<std::uint8_t> Encode(std::span<const std::uint8_t> pixels, std::uint
|
||||
}
|
||||
}
|
||||
|
||||
int compressedSize = 0;
|
||||
const std::unique_ptr<unsigned char, void (*)(unsigned char*)> compressed(
|
||||
stbi_zlib_compress(filtered.data(), static_cast<int>(filtered.size()), &compressedSize, options.compressionLevel),
|
||||
[](unsigned char* memory) { STBIW_FREE(memory); });
|
||||
if (!compressed) throw std::runtime_error("Png::Encode: encoding failed");
|
||||
const auto inputSize = static_cast<uLong>(filtered.size());
|
||||
uLongf compressedSize = compressBound(inputSize);
|
||||
const auto compressed = std::make_unique<std::uint8_t[]>(compressedSize);
|
||||
if (compress2(compressed.get(), &compressedSize, filtered.data(), inputSize, options.compressionLevel) != Z_OK) {
|
||||
throw std::runtime_error("Png::Encode: encoding failed");
|
||||
}
|
||||
if (compressedSize > INT_MAX) throw std::runtime_error("Png::Encode: PNG chunk is too large");
|
||||
|
||||
std::vector<std::uint8_t> header;
|
||||
appendBigEndian32(header, width);
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <optional>
|
||||
#include <source_location>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
@@ -13,7 +15,11 @@
|
||||
#define STBI_NO_STDIO
|
||||
#include "stb_image.h"
|
||||
|
||||
static void Require(bool value) { if (!value) std::abort(); }
|
||||
static void Require(bool value, std::source_location location = std::source_location::current()) {
|
||||
if (value) return;
|
||||
std::fprintf(stderr, "%s:%u: PNG assertion failed\n", location.file_name(), location.line());
|
||||
std::abort();
|
||||
}
|
||||
|
||||
template<typename TFunction>
|
||||
static bool ThrowsInvalidArgument(TFunction function) {
|
||||
@@ -225,7 +231,7 @@ static void RequireRoundTrip(std::uint32_t channels, Decoder::Png::ColorType col
|
||||
}
|
||||
}
|
||||
|
||||
static std::vector<std::uint8_t> RowFilters(const std::vector<std::uint8_t>& png, std::uint32_t height, std::uint32_t rowSize) {
|
||||
static std::vector<std::uint8_t> ImageData(const std::vector<std::uint8_t>& png) {
|
||||
std::vector<std::uint8_t> stream;
|
||||
for (std::size_t offset = 8; offset + 12 <= png.size();) {
|
||||
const std::size_t length = static_cast<std::size_t>(png[offset]) << 24 | static_cast<std::size_t>(png[offset + 1]) << 16
|
||||
@@ -235,7 +241,11 @@ static std::vector<std::uint8_t> RowFilters(const std::vector<std::uint8_t>& png
|
||||
if (std::equal(data - 4, data, "IDAT")) stream.insert(stream.end(), data, data + length);
|
||||
offset += 12 + length;
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
static std::vector<std::uint8_t> RowFilters(const std::vector<std::uint8_t>& png, std::uint32_t height, std::uint32_t rowSize) {
|
||||
const std::vector<std::uint8_t> stream = ImageData(png);
|
||||
int size = 0;
|
||||
char* rows = stbi_zlib_decode_malloc(reinterpret_cast<const char*>(stream.data()), static_cast<int>(stream.size()), &size);
|
||||
Require(rows && static_cast<std::size_t>(size) == static_cast<std::size_t>(height) * (rowSize + 1));
|
||||
@@ -245,6 +255,67 @@ static std::vector<std::uint8_t> RowFilters(const std::vector<std::uint8_t>& png
|
||||
return filters;
|
||||
}
|
||||
|
||||
static std::vector<std::uint8_t> StoredRows(const std::vector<std::uint8_t>& stream) {
|
||||
Require(stream.size() >= 11 && (stream[0] & 15) == 8 && (stream[1] & 0x20) == 0);
|
||||
Require((static_cast<unsigned>(stream[0]) * 256 + stream[1]) % 31 == 0);
|
||||
std::vector<std::uint8_t> rows;
|
||||
std::size_t offset = 2;
|
||||
std::size_t blocks = 0;
|
||||
bool final = false;
|
||||
while (!final) {
|
||||
Require(offset + 5 <= stream.size() - 4);
|
||||
const std::uint8_t header = stream[offset++];
|
||||
Require((header & 6) == 0);
|
||||
final = (header & 1) != 0;
|
||||
const unsigned length = stream[offset] | static_cast<unsigned>(stream[offset + 1]) << 8;
|
||||
const unsigned inverse = stream[offset + 2] | static_cast<unsigned>(stream[offset + 3]) << 8;
|
||||
Require((length ^ inverse) == 0xFFFF);
|
||||
offset += 4;
|
||||
Require(length <= stream.size() - offset - 4);
|
||||
rows.insert(rows.end(), stream.begin() + offset, stream.begin() + offset + length);
|
||||
offset += length;
|
||||
++blocks;
|
||||
}
|
||||
Require(offset + 4 == stream.size());
|
||||
const std::uint32_t checksum = static_cast<std::uint32_t>(stream[offset]) << 24 | static_cast<std::uint32_t>(stream[offset + 1]) << 16
|
||||
| static_cast<std::uint32_t>(stream[offset + 2]) << 8 | stream[offset + 3];
|
||||
Require(checksum == Adler32(rows));
|
||||
if (rows.size() > 0xFFFF) Require(blocks > 1);
|
||||
return rows;
|
||||
}
|
||||
|
||||
static void RequireCompressionLevels(std::uint32_t channels) {
|
||||
constexpr std::uint32_t width = 256;
|
||||
constexpr std::uint32_t height = 65;
|
||||
const std::uint32_t rowSize = width * channels;
|
||||
std::vector<std::uint8_t> pixels(rowSize * height);
|
||||
for (std::size_t i = 0; i < pixels.size(); ++i) pixels[i] = static_cast<std::uint8_t>(i / channels % width);
|
||||
for (const std::uint8_t filters : {Decoder::Png::FILTER_NONE, Decoder::Png::FILTER_SUB}) {
|
||||
for (int level = 0; level <= 9; ++level) {
|
||||
const auto png = Decoder::Png::Encode(pixels, width, height, channels, {level, filters});
|
||||
if (level == 0) {
|
||||
const auto rows = StoredRows(ImageData(png));
|
||||
Require(rows.size() == static_cast<std::size_t>(rowSize + 1) * height);
|
||||
if (filters == Decoder::Png::FILTER_NONE) {
|
||||
for (std::uint32_t y = 0; y < height; ++y) {
|
||||
const auto row = rows.begin() + static_cast<std::size_t>(rowSize + 1) * y;
|
||||
Require(*row == 0);
|
||||
Require(std::equal(pixels.begin() + rowSize * y, pixels.begin() + rowSize * (y + 1), row + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const auto filter : RowFilters(png, height, rowSize)) Require(filter == (filters == Decoder::Png::FILTER_NONE ? 0 : 1));
|
||||
const auto image = Decoder::Png::Decode(png);
|
||||
Require(image && image->width == width && image->height == height);
|
||||
for (std::size_t pixel = 0; pixel < width * height; ++pixel) {
|
||||
const auto expected = pixels[pixel * channels];
|
||||
Require(image->pixels[pixel * 4] == expected && image->pixels[pixel * 4 + 1] == expected && image->pixels[pixel * 4 + 2] == expected);
|
||||
Require(image->pixels[pixel * 4 + 3] == (channels % 2 == 0 ? expected : 255));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void RequireFilterSets(std::uint32_t channels) {
|
||||
constexpr std::uint32_t width = 16;
|
||||
constexpr std::uint32_t height = 6;
|
||||
@@ -277,6 +348,7 @@ static void RequireFilterSets(std::uint32_t channels) {
|
||||
}
|
||||
|
||||
int main() {
|
||||
for (const std::uint32_t channels : {1, 2, 3, 4}) RequireCompressionLevels(channels);
|
||||
RequireRoundTrip(1, Decoder::Png::ColorType::Grayscale);
|
||||
RequireRoundTrip(2, Decoder::Png::ColorType::GrayscaleAlpha);
|
||||
RequireRoundTrip(3, Decoder::Png::ColorType::Rgb);
|
||||
|
||||
@@ -354,7 +354,7 @@ if(BUILD_TESTING)
|
||||
target_compile_options(guest_kernel_sys_paths_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
target_link_options(guest_kernel_sys_paths_tests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
foreach(case IN ITEMS statfs symlinkat symlinkat_errors futimesat)
|
||||
foreach(case IN ITEMS statfs symlinkat symlinkat_errors futimesat readlink_limits readlinkat_limits)
|
||||
add_test(NAME guest_kernel_sys_paths_${case} COMMAND guest_kernel_sys_paths_tests ${UNPATCHED_DIR} unpatched ${case})
|
||||
add_test(NAME guest_kernel_sys_paths_${case}_patched COMMAND guest_kernel_sys_paths_tests ${PATCHED_DIR} patched ${case})
|
||||
set_tests_properties(guest_kernel_sys_paths_${case} guest_kernel_sys_paths_${case}_patched PROPERTIES TIMEOUT 20)
|
||||
@@ -364,7 +364,9 @@ if(BUILD_TESTING)
|
||||
ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:${kernelSysPathsRuntimeDirectory}")
|
||||
endif()
|
||||
endforeach()
|
||||
set_tests_properties(guest_kernel_sys_paths_symlinkat guest_kernel_sys_paths_symlinkat_patched PROPERTIES SKIP_RETURN_CODE 77)
|
||||
set_tests_properties(guest_kernel_sys_paths_symlinkat guest_kernel_sys_paths_symlinkat_patched
|
||||
guest_kernel_sys_paths_readlink_limits guest_kernel_sys_paths_readlink_limits_patched
|
||||
guest_kernel_sys_paths_readlinkat_limits guest_kernel_sys_paths_readlinkat_limits_patched PROPERTIES SKIP_RETURN_CODE 77)
|
||||
|
||||
add_test_executable(guest_posix_scalar_io_tests tests/GuestPosixScalarIo.cpp)
|
||||
target_include_directories(guest_posix_scalar_io_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
@@ -441,6 +443,16 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(guest_kernel_sys_constant_unknowns PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
|
||||
endif()
|
||||
add_test_executable(guest_kernel_sys_named_object_tests tests/GuestKernelSysNamedObject.cpp)
|
||||
target_include_directories(guest_kernel_sys_named_object_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_kernel_sys_named_object_tests PRIVATE libkernel_sys libkernel libc)
|
||||
configure_windows_unwind(guest_kernel_sys_named_object_tests)
|
||||
add_test(NAME guest_kernel_sys_named_object COMMAND guest_kernel_sys_named_object_tests)
|
||||
set_tests_properties(guest_kernel_sys_named_object PROPERTIES TIMEOUT 20)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_kernel_sys_named_object PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
|
||||
endif()
|
||||
add_test_executable(nid_buffer_validation_tests nid/tests/BufferValidation.cpp)
|
||||
target_include_directories(nid_buffer_validation_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/nid/include)
|
||||
target_compile_features(nid_buffer_validation_tests PRIVATE cxx_std_20)
|
||||
@@ -594,6 +606,16 @@ if(BUILD_TESTING)
|
||||
add_test(NAME guest_kernel_sys_pwrite COMMAND guest_kernel_sys_pwrite_tests ${UNPATCHED_DIR} unpatched)
|
||||
add_test(NAME guest_kernel_sys_pwrite_patched COMMAND guest_kernel_sys_pwrite_tests ${PATCHED_DIR} patched)
|
||||
set_tests_properties(guest_kernel_sys_pwrite guest_kernel_sys_pwrite_patched PROPERTIES TIMEOUT 20)
|
||||
add_test_executable(guest_media_framework_interface_catalog_exports_tests tests/GuestMediaFrameworkInterfaceCatalogExports.cpp)
|
||||
target_include_directories(guest_media_framework_interface_catalog_exports_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_media_framework_interface_catalog_exports_tests PRIVATE libSceMediaFrameworkInterface libkernel libc)
|
||||
configure_windows_unwind(guest_media_framework_interface_catalog_exports_tests)
|
||||
add_test(NAME guest_media_framework_interface_catalog_exports COMMAND guest_media_framework_interface_catalog_exports_tests)
|
||||
set_tests_properties(guest_media_framework_interface_catalog_exports PROPERTIES TIMEOUT 20)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_media_framework_interface_catalog_exports PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceMediaFrameworkInterface>")
|
||||
endif()
|
||||
if(MINGW)
|
||||
get_filename_component(kernelSysPwriteRuntimeDirectory "${CMAKE_CXX_COMPILER}" DIRECTORY)
|
||||
set_tests_properties(guest_kernel_sys_pwrite guest_kernel_sys_pwrite_patched PROPERTIES
|
||||
@@ -852,6 +874,17 @@ if(BUILD_TESTING)
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_kernel_sys_thread_name_tests tests/GuestKernelSysThreadName.cpp)
|
||||
target_include_directories(guest_kernel_sys_thread_name_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_kernel_sys_thread_name_tests PRIVATE libkernel_sys libkernel libc)
|
||||
configure_windows_unwind(guest_kernel_sys_thread_name_tests)
|
||||
add_test(NAME guest_kernel_sys_thread_name COMMAND guest_kernel_sys_thread_name_tests)
|
||||
set_tests_properties(guest_kernel_sys_thread_name PROPERTIES TIMEOUT 20)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_kernel_sys_thread_name PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
|
||||
endif()
|
||||
|
||||
add_test_executable(crash_text_tests tests/CrashText.cpp)
|
||||
target_include_directories(crash_text_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
if(MINGW)
|
||||
@@ -1313,6 +1346,19 @@ if(BUILD_TESTING)
|
||||
add_subdirectory(tests/register_context)
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_savedata_progress_tests tests/GuestSaveDataProgress.cpp)
|
||||
target_include_directories(guest_savedata_progress_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_savedata_progress_tests PRIVATE libSceSaveData.native)
|
||||
configure_windows_unwind(guest_savedata_progress_tests)
|
||||
add_test(NAME guest_savedata_progress COMMAND guest_savedata_progress_tests)
|
||||
if(MINGW)
|
||||
target_compile_options(guest_savedata_progress_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_savedata_progress PROPERTIES
|
||||
ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSaveData.native>")
|
||||
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)
|
||||
@@ -1700,6 +1746,7 @@ if(BUILD_TESTING)
|
||||
|
||||
endif()
|
||||
|
||||
include(prx/libfreetype/NewGlyph.cmake)
|
||||
include(prx/libSceFreeType/CurveBounds.cmake)
|
||||
target_sources(libwebrtc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/prx/libwebrtc/src/FileWrapper.cpp)
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
@@ -46,6 +47,22 @@ std::uint64_t Address(const void* pointer) {
|
||||
return reinterpret_cast<std::uintptr_t>(pointer);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool loadGuest(T& value, const void* address) {
|
||||
const int savedErrno = errno;
|
||||
const bool copied = GuestCopyIn_nid_no_patch(const_cast<void*>(static_cast<const void*>(&value)), address, sizeof(T));
|
||||
errno = savedErrno;
|
||||
return copied;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool storeGuest(void* address, const T& value) {
|
||||
const int savedErrno = errno;
|
||||
const bool copied = GuestCopyOut_nid_no_patch(address, &value, sizeof(T));
|
||||
errno = savedErrno;
|
||||
return copied;
|
||||
}
|
||||
|
||||
int AppendReverbJob(AcmBatchInfo& batch, std::uint32_t blockSize, const ReverbEntry& input, const ReverbEntry* entries, std::uint32_t count) {
|
||||
const auto offset = batch.offset;
|
||||
const auto capacity = batch.buffer_size;
|
||||
@@ -220,19 +237,12 @@ int APS5_VABI sceAcm_ConvReverb_SharedInput_2() {
|
||||
int APS5_VABI sceAcmBatchStartBuffer(AcmContextId context, const void* batch_commands, size_t batch_size, AcmBatchError* batch_error, AcmBatchId* batch) {
|
||||
(void)batch_commands;
|
||||
(void)batch_size;
|
||||
if (!batch) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (!batch || batch_error) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (context == 0) return SCE_ACM_ERROR_BAD_CONTEXT;
|
||||
std::lock_guard<std::mutex> lock(g_mutex);
|
||||
if (!g_contexts.contains(context)) return SCE_ACM_ERROR_BAD_CONTEXT;
|
||||
AcmBatchId id = g_nextId.fetch_add(1, std::memory_order_relaxed);
|
||||
while (id == 0) id = g_nextId.fetch_add(1, std::memory_order_relaxed);
|
||||
if (batch_error) {
|
||||
AcmBatchError err{};
|
||||
const int savedErrno = errno;
|
||||
const bool copied = GuestCopyOut_nid_no_patch(batch_error, &err, sizeof(err));
|
||||
errno = savedErrno;
|
||||
if (!copied) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
}
|
||||
const int savedErrno = errno;
|
||||
const bool copied = GuestCopyOut_nid_no_patch(batch, &id, sizeof(id));
|
||||
errno = savedErrno;
|
||||
@@ -243,19 +253,12 @@ int APS5_VABI sceAcmBatchStartBuffer(AcmContextId context, const void* batch_com
|
||||
int APS5_VABI sceAcmBatchStartBuffers(AcmContextId context, uint32_t batch_info_count, const AcmBatchInfo* const batch_info[], AcmBatchError* batch_error, AcmBatchId* batch) {
|
||||
(void)batch_info_count;
|
||||
(void)batch_info;
|
||||
if (!batch) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (!batch || batch_error) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (context == 0) return SCE_ACM_ERROR_BAD_CONTEXT;
|
||||
std::lock_guard<std::mutex> lock(g_mutex);
|
||||
if (!g_contexts.contains(context)) return SCE_ACM_ERROR_BAD_CONTEXT;
|
||||
AcmBatchId id = g_nextId.fetch_add(1, std::memory_order_relaxed);
|
||||
while (id == 0) id = g_nextId.fetch_add(1, std::memory_order_relaxed);
|
||||
if (batch_error) {
|
||||
AcmBatchError err{};
|
||||
const int savedErrno = errno;
|
||||
const bool copied = GuestCopyOut_nid_no_patch(batch_error, &err, sizeof(err));
|
||||
errno = savedErrno;
|
||||
if (!copied) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
}
|
||||
const int savedErrno = errno;
|
||||
const bool copied = GuestCopyOut_nid_no_patch(batch, &id, sizeof(id));
|
||||
errno = savedErrno;
|
||||
@@ -302,67 +305,92 @@ int APS5_VABI sceAcmContextDestroy(AcmContextId context) {
|
||||
|
||||
int APS5_VABI sceAcm_ConvReverb_SharedInput(AcmBatchInfo* batch, std::uint32_t mode, AcmReverbInput* input, std::uint32_t outputCount, const AcmReverbFilter* const* filters, const float* gains, const AcmReverbOutput* const* outputs) {
|
||||
if (!batch || mode != 1 || !input || !filters) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const auto blockSize = input->blockSize;
|
||||
AcmReverbInput source{};
|
||||
if (!loadGuest(source, input)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const auto blockSize = source.blockSize;
|
||||
if (blockSize != 128 && blockSize != 256 && blockSize != 512 && blockSize != 1024) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
for (std::uint32_t index = 0; index < outputCount; ++index) {
|
||||
if (!filters[index] || filters[index]->blockCount == 0) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const AcmReverbFilter* filterPointer = nullptr;
|
||||
AcmReverbFilter filter{};
|
||||
if (!loadGuest(filterPointer, filters + index) || !filterPointer || !loadGuest(filter, filterPointer) || filter.blockCount == 0) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
}
|
||||
const auto blockCount = input->blockCount;
|
||||
if (!input->history || blockCount == 0) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (input->availableBlocks != 0 && input->currentBlock != 0 && input->currentBlock > blockCount) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (std::uint64_t{blockCount} * blockSize * (input->sampleFormat == 0 ? 8 : 4) > 0xFFFFFFFFu) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
input->currentBlock = (input->availableBlocks == 0 || input->currentBlock == 0 ? blockCount : input->currentBlock) - 1;
|
||||
input->availableBlocks = std::min(input->availableBlocks + 1, blockCount);
|
||||
const auto channelCount = input->channelCount;
|
||||
if (channelCount == 0 || channelCount > 256 || !input->inputChannels || input->sampleFormat > 1) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const bool wideSamples = input->sampleFormat == 0;
|
||||
const auto blockCount = source.blockCount;
|
||||
if (!source.history || blockCount == 0) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (source.availableBlocks != 0 && source.currentBlock != 0 && source.currentBlock > blockCount) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (std::uint64_t{blockCount} * blockSize * (source.sampleFormat == 0 ? 8 : 4) > 0xFFFFFFFFu) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const std::uint32_t nextCurrentBlock = (source.availableBlocks == 0 || source.currentBlock == 0 ? blockCount : source.currentBlock) - 1;
|
||||
const std::uint32_t nextAvailableBlocks = std::min(source.availableBlocks + 1, blockCount);
|
||||
source.currentBlock = nextCurrentBlock;
|
||||
source.availableBlocks = nextAvailableBlocks;
|
||||
if (!storeGuest(input, source)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const auto channelCount = source.channelCount;
|
||||
if (channelCount == 0 || channelCount > 256 || !source.inputChannels || source.sampleFormat > 1) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const bool wideSamples = source.sampleFormat == 0;
|
||||
const std::uint32_t slotBytes = blockSize * (wideSamples ? 8 : 4);
|
||||
const std::uint32_t current = input->currentBlock;
|
||||
const std::uint32_t current = nextCurrentBlock;
|
||||
std::vector<const void*> sources(channelCount);
|
||||
std::vector<void*> destinations(channelCount);
|
||||
for (std::uint32_t channel = 0; channel < channelCount; ++channel) {
|
||||
const auto* history = input->history[channel];
|
||||
if (!history || history->blockMetadata || !history->samples || !input->inputChannels[channel]) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const AcmReverbBuffer* historyPointer = nullptr;
|
||||
AcmReverbBuffer history{};
|
||||
const void* inputChannel = nullptr;
|
||||
if (!loadGuest(historyPointer, source.history + channel) || !historyPointer || !loadGuest(history, historyPointer) || !loadGuest(inputChannel, source.inputChannels + channel)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (history.blockMetadata || !history.samples || !inputChannel) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const auto position = wideSamples ? channel : channelCount - 1 - channel;
|
||||
sources[position] = input->inputChannels[channel];
|
||||
destinations[position] = static_cast<std::byte*>(history->samples) + current * slotBytes;
|
||||
sources[position] = inputChannel;
|
||||
destinations[position] = static_cast<std::byte*>(history.samples) + current * slotBytes;
|
||||
}
|
||||
AcmBatchInfo work = *batch;
|
||||
AcmBatchInfo work{};
|
||||
const int readErrno = errno;
|
||||
const bool read = GuestCopyIn_nid_no_patch(&work, batch, sizeof(work));
|
||||
errno = readErrno;
|
||||
if (!read) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (const auto result = sceAcm_FFT(&work, static_cast<std::int32_t>(2 * blockSize), channelCount, 0, sources.data(), wideSamples ? 0 : 1, destinations.data(), 9)) return result;
|
||||
if (outputCount == 0 || !outputs) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const auto headerOffset = work.offset;
|
||||
if (headerOffset > work.buffer_size || work.buffer_size - headerOffset < 8) return SCE_ACM_ERROR_BATCH_FULL;
|
||||
work.offset += 8;
|
||||
const auto available = input->availableBlocks;
|
||||
const auto available = nextAvailableBlocks;
|
||||
const auto start = current >= blockCount ? current - blockCount : current;
|
||||
std::uint64_t flags = 0;
|
||||
std::uint32_t smallestBlockCount = blockCount;
|
||||
for (std::uint32_t channel = 0; channel < channelCount; ++channel) {
|
||||
const ReverbEntry inputEntry{input->history[channel]->samples, available, start * slotBytes, blockCount * slotBytes, nullptr, nullptr, nullptr, nullptr, 0.0f, wideSamples};
|
||||
const AcmReverbBuffer* historyPointer = nullptr;
|
||||
AcmReverbBuffer history{};
|
||||
if (!loadGuest(historyPointer, source.history + channel) || !loadGuest(history, historyPointer)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const ReverbEntry inputEntry{history.samples, available, start * slotBytes, blockCount * slotBytes, nullptr, nullptr, nullptr, nullptr, 0.0f, wideSamples};
|
||||
flags |= std::uint64_t{1} << (wideSamples ? 21 : 20);
|
||||
std::array<ReverbEntry, 8> entries{};
|
||||
std::uint32_t entryCount = 0;
|
||||
for (std::uint32_t outputIndex = 0; outputIndex < outputCount; ++outputIndex) {
|
||||
const auto* filter = filters[outputIndex];
|
||||
const auto* output = outputs[outputIndex];
|
||||
const auto filterChannels = filter->channelCount;
|
||||
if (!filter->channels || !output || !output->workspace || !output->samples || filter->blockSize != blockSize || output->blockSize != blockSize || filterChannels == 0 || output->channelCount != std::max(channelCount, filterChannels)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const AcmReverbFilter* filterPointer = nullptr;
|
||||
const AcmReverbOutput* outputPointer = nullptr;
|
||||
AcmReverbFilter filter{};
|
||||
AcmReverbOutput output{};
|
||||
float gain = 1.0f;
|
||||
if (!loadGuest(filterPointer, filters + outputIndex) || !loadGuest(outputPointer, outputs + outputIndex) || !filterPointer || !outputPointer || !loadGuest(filter, filterPointer) || !loadGuest(output, outputPointer) || (gains && !loadGuest(gain, gains + outputIndex))) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const auto filterChannels = filter.channelCount;
|
||||
if (!filter.channels || !output.workspace || !output.samples || filter.blockSize != blockSize || output.blockSize != blockSize || filterChannels == 0 || output.channelCount != std::max(channelCount, filterChannels)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (filterChannels != channelCount && channelCount != 1 && filterChannels != 1) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (Address(filter->blockMetadata) & 3) return SCE_ACM_ERROR_ALIGNMENT;
|
||||
if (filter->sampleFormat > 1) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const bool wideFilter = filter->sampleFormat == 0;
|
||||
flags |= (filterChannels != 1 && channelCount == 1 ? std::uint64_t{1} << 17 : 0) | (filterChannels == 1 && channelCount != 1 ? std::uint64_t{1} << 18 : 0) | (filterChannels == channelCount ? std::uint64_t{1} << 19 : 0) | (std::uint64_t{1} << (wideFilter ? 23 : 22)) | (filter->blockMetadata ? std::uint64_t{1} << 27 : 0) | (std::uint64_t{1} << (filterChannels == 1 ? 39 : (0x47 - std::countl_zero(filterChannels - 1)) & 63));
|
||||
smallestBlockCount = std::min(smallestBlockCount, filter->blockCount);
|
||||
if (Address(filter.blockMetadata) & 3) return SCE_ACM_ERROR_ALIGNMENT;
|
||||
if (filter.sampleFormat > 1) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const bool wideFilter = filter.sampleFormat == 0;
|
||||
flags |= (filterChannels != 1 && channelCount == 1 ? std::uint64_t{1} << 17 : 0) | (filterChannels == 1 && channelCount != 1 ? std::uint64_t{1} << 18 : 0) | (filterChannels == channelCount ? std::uint64_t{1} << 19 : 0) | (std::uint64_t{1} << (wideFilter ? 23 : 22)) | (filter.blockMetadata ? std::uint64_t{1} << 27 : 0) | (std::uint64_t{1} << (filterChannels == 1 ? 39 : (0x47 - std::countl_zero(filterChannels - 1)) & 63));
|
||||
smallestBlockCount = std::min(smallestBlockCount, filter.blockCount);
|
||||
const auto first = filterChannels == channelCount ? channel : 0;
|
||||
const auto last = filterChannels == channelCount ? channel + 1 : channelCount == 1 ? filterChannels : 1;
|
||||
const auto length = std::min(available, filter->blockCount);
|
||||
const auto length = std::min(available, filter.blockCount);
|
||||
for (auto filterChannel = first; filterChannel < last; ++filterChannel) {
|
||||
const auto outputChannel = channel - first + filterChannel;
|
||||
const auto* block = filter->channels[filterChannel];
|
||||
if (!block || !block->samples || !output->workspace[outputChannel] || !output->samples[outputChannel]) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if ((Address(block->blockMetadata) & 3) || ((Address(block->samples) | Address(output->workspace[outputChannel]) | Address(output->samples[outputChannel])) & 127)) return SCE_ACM_ERROR_ALIGNMENT;
|
||||
if (block->blockMetadata) flags |= std::uint64_t{1} << 26;
|
||||
entries[entryCount++] = {block->samples, length, 0, 0xFFFFFFFF, block->blockMetadata, filter->blockMetadata, output->workspace[outputChannel], output->samples[outputChannel], gains ? gains[outputIndex] : 1.0f, wideFilter};
|
||||
const AcmReverbBuffer* blockPointer = nullptr;
|
||||
void* workspaceChannel = nullptr;
|
||||
void* samplesChannel = nullptr;
|
||||
AcmReverbBuffer block{};
|
||||
if (!loadGuest(blockPointer, filter.channels + filterChannel) || !loadGuest(workspaceChannel, output.workspace + outputChannel) || !loadGuest(samplesChannel, output.samples + outputChannel)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (!blockPointer || !loadGuest(block, blockPointer) || !block.samples || !workspaceChannel || !samplesChannel) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if ((Address(block.blockMetadata) & 3) || ((Address(block.samples) | Address(workspaceChannel) | Address(samplesChannel)) & 127)) return SCE_ACM_ERROR_ALIGNMENT;
|
||||
if (block.blockMetadata) flags |= std::uint64_t{1} << 26;
|
||||
entries[entryCount++] = {block.samples, length, 0, 0xFFFFFFFF, block.blockMetadata, filter.blockMetadata, workspaceChannel, samplesChannel, gain, wideFilter};
|
||||
if (entryCount == entries.size()) {
|
||||
if (const auto result = AppendReverbJob(work, blockSize, inputEntry, entries.data(), entryCount)) return result;
|
||||
entryCount = 0;
|
||||
@@ -376,8 +404,10 @@ int APS5_VABI sceAcm_ConvReverb_SharedInput(AcmBatchInfo* batch, std::uint32_t m
|
||||
flags |= (std::uint64_t{std::min(outputCount - 1, 15u)} << 29) | (std::uint64_t{1} << ((64 - std::countl_zero(channelCount)) & 63)) | (std::uint64_t{std::min(smallestBlockCount, 7u)} << 45);
|
||||
const std::uint64_t header = ((flags & 0xFFFF) ? std::uint64_t{1} << 63 : flags) | ((0x0B + static_cast<std::uint64_t>(std::countr_zero(blockSize >> 7))) << 8);
|
||||
std::memcpy(static_cast<std::byte*>(work.buffer) + headerOffset, &header, sizeof(header));
|
||||
*batch = work;
|
||||
return 0;
|
||||
const int savedErrno = errno;
|
||||
const bool copied = GuestCopyOut_nid_no_patch(batch, &work, sizeof(work));
|
||||
errno = savedErrno;
|
||||
return copied ? 0 : SCE_ACM_ERROR_BAD_POINTER;
|
||||
}
|
||||
|
||||
int APS5_VABI sceAcm_FFT(AcmBatchInfo* batch, std::int32_t transformSize, std::uint32_t transformCount, std::int32_t inputFormat, const void* const* inputs, std::int32_t outputFormat, void* const* outputs, std::int32_t flags) {
|
||||
@@ -388,42 +418,50 @@ int APS5_VABI sceAcm_Panner(AcmBatchInfo* batch, std::uint32_t sourceCount, cons
|
||||
if (!batch || sourceCount == 0 || sourceCount > 65535 || sourceMode > 2 || outputMode > 1 || channelCount == 0 || channelCount > 36 || !sources || !sourceParameters || !sourceMatrices || !outputChannels) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
std::uintptr_t alignment = reinterpret_cast<std::uintptr_t>(sources) | reinterpret_cast<std::uintptr_t>(sourceParameters) | reinterpret_cast<std::uintptr_t>(sourceMatrices) | reinterpret_cast<std::uintptr_t>(inputChannels) | reinterpret_cast<std::uintptr_t>(outputChannels);
|
||||
for (std::uint32_t index = 0; index < sourceCount; ++index) {
|
||||
if (!sources[index] || !sourceParameters[index] || !sourceMatrices[index]) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
std::uint32_t parameterMode;
|
||||
std::memcpy(¶meterMode, sourceParameters[index], sizeof(parameterMode));
|
||||
const void* source = nullptr;
|
||||
const void* parameters = nullptr;
|
||||
const void* matrix = nullptr;
|
||||
std::uint32_t parameterMode = 0;
|
||||
if (!loadGuest(source, sources + index) || !loadGuest(parameters, sourceParameters + index) || !loadGuest(matrix, sourceMatrices + index)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (!source || !parameters || !matrix) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (!loadGuest(parameterMode, parameters)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (parameterMode > 1) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
alignment |= reinterpret_cast<std::uintptr_t>(sources[index]) | reinterpret_cast<std::uintptr_t>(sourceParameters[index]) | reinterpret_cast<std::uintptr_t>(sourceMatrices[index]);
|
||||
alignment |= reinterpret_cast<std::uintptr_t>(source) | reinterpret_cast<std::uintptr_t>(parameters) | reinterpret_cast<std::uintptr_t>(matrix);
|
||||
}
|
||||
for (std::uint32_t index = 0; index < channelCount; ++index) {
|
||||
if (!outputChannels[index]) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
alignment |= reinterpret_cast<std::uintptr_t>(outputChannels[index]);
|
||||
if (inputChannels) alignment |= reinterpret_cast<std::uintptr_t>(inputChannels[index]);
|
||||
const void* inputChannel = nullptr;
|
||||
void* outputChannel = nullptr;
|
||||
if (!loadGuest(outputChannel, outputChannels + index)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (!outputChannel) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
alignment |= reinterpret_cast<std::uintptr_t>(outputChannel);
|
||||
if (inputChannels) {
|
||||
if (!loadGuest(inputChannel, inputChannels + index)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
alignment |= reinterpret_cast<std::uintptr_t>(inputChannel);
|
||||
}
|
||||
}
|
||||
if (alignment & 127) return static_cast<int>(0x8194000A);
|
||||
const auto offset = batch->offset;
|
||||
const auto capacity = batch->buffer_size;
|
||||
if (offset > capacity || capacity - offset < 8) return static_cast<int>(0x81940009);
|
||||
auto* buffer = static_cast<std::byte*>(batch->buffer);
|
||||
const auto writeWord = [buffer](std::size_t position, std::uint64_t value) { std::memcpy(buffer + position, &value, sizeof(value)); };
|
||||
AcmBatchInfo work{};
|
||||
if (!loadGuest(work, batch)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const auto offset = work.offset;
|
||||
const auto capacity = work.buffer_size;
|
||||
if (offset > capacity || capacity - offset < 160) return static_cast<int>(0x81940009);
|
||||
auto* buffer = static_cast<std::byte*>(work.buffer);
|
||||
const auto encodedCount = sourceCount < 255 ? sourceCount : 255;
|
||||
writeWord(offset, (static_cast<std::uint64_t>(channelCount) << 24) | (static_cast<std::uint64_t>(encodedCount) << 16) | (std::uint64_t{1} << (sourceMode + 32)) | (std::uint64_t{1} << (outputMode + 35)) | 0x300);
|
||||
if (capacity < 128 || capacity - offset < 152) return static_cast<int>(0x81940009);
|
||||
const auto descriptorOffset = capacity - 128;
|
||||
std::memset(buffer + descriptorOffset, 0, 128);
|
||||
writeWord(descriptorOffset, sourceCount);
|
||||
writeWord(descriptorOffset + 8, reinterpret_cast<std::uintptr_t>(inputChannels));
|
||||
writeWord(descriptorOffset + 16, reinterpret_cast<std::uintptr_t>(outputChannels));
|
||||
writeWord(descriptorOffset + 24, reinterpret_cast<std::uintptr_t>(sources));
|
||||
writeWord(descriptorOffset + 32, sourceMode | (static_cast<std::uint64_t>(outputMode) << 32));
|
||||
writeWord(descriptorOffset + 40, channelCount);
|
||||
writeWord(descriptorOffset + 48, reinterpret_cast<std::uintptr_t>(sourceParameters));
|
||||
writeWord(descriptorOffset + 56, reinterpret_cast<std::uintptr_t>(sourceMatrices));
|
||||
writeWord(offset + 8, 0x8000000000000D);
|
||||
writeWord(offset + 16, reinterpret_cast<std::uintptr_t>(buffer + descriptorOffset));
|
||||
if (capacity - offset < 160) return static_cast<int>(0x81940009);
|
||||
writeWord(offset + 24, 10);
|
||||
batch->offset = offset + 32;
|
||||
batch->buffer_size = descriptorOffset;
|
||||
const std::size_t descriptorOffset = capacity - 128;
|
||||
const std::array<std::uint64_t, 4> command{(static_cast<std::uint64_t>(channelCount) << 24) | (static_cast<std::uint64_t>(encodedCount) << 16) | (std::uint64_t{1} << (sourceMode + 32)) | (std::uint64_t{1} << (outputMode + 35)) | 0x300, 0x8000000000000D, reinterpret_cast<std::uintptr_t>(buffer + descriptorOffset), 10};
|
||||
std::array<std::uint64_t, 16> descriptor{};
|
||||
descriptor[0] = sourceCount;
|
||||
descriptor[1] = reinterpret_cast<std::uintptr_t>(inputChannels);
|
||||
descriptor[2] = reinterpret_cast<std::uintptr_t>(outputChannels);
|
||||
descriptor[3] = reinterpret_cast<std::uintptr_t>(sources);
|
||||
descriptor[4] = sourceMode | (static_cast<std::uint64_t>(outputMode) << 32);
|
||||
descriptor[5] = channelCount;
|
||||
descriptor[6] = reinterpret_cast<std::uintptr_t>(sourceParameters);
|
||||
descriptor[7] = reinterpret_cast<std::uintptr_t>(sourceMatrices);
|
||||
if (!storeGuest(buffer + offset, command) || !storeGuest(buffer + descriptorOffset, descriptor)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
work.offset = offset + 32;
|
||||
work.buffer_size = descriptorOffset;
|
||||
if (!storeGuest(batch, work)) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -464,13 +502,38 @@ int APS5_VABI sceAcm_IFFT(AcmBatchInfo* batch, std::int32_t transformSize, std::
|
||||
int APS5_VABI sceAcmBatchJobNotification(AcmBatchInfo* batch, std::uint32_t value, void* notification) {
|
||||
if (value == 0 || !batch || !notification) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
if (reinterpret_cast<std::uintptr_t>(notification) & 0x7f) return SCE_ACM_ERROR_ALIGNMENT;
|
||||
const std::uint64_t offset = batch->offset;
|
||||
const std::uint64_t end = offset + 0x10;
|
||||
if (end > batch->buffer_size) return SCE_ACM_ERROR_BATCH_FULL;
|
||||
std::memset(notification, 0, 0x80);
|
||||
AcmBatchInfo localBatch{};
|
||||
const int savedErrno = errno;
|
||||
const bool copiedIn = GuestCopyIn_nid_no_patch(&localBatch, batch, sizeof(localBatch));
|
||||
errno = savedErrno;
|
||||
if (!copiedIn) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const std::uint64_t offset = localBatch.offset;
|
||||
if (offset > localBatch.buffer_size || localBatch.buffer_size - offset < 0x10) return SCE_ACM_ERROR_BATCH_FULL;
|
||||
const int savedErrnoProbe = errno;
|
||||
const bool batchWritable = GuestCopyOut_nid_no_patch(&batch->offset, &localBatch.offset, sizeof(localBatch.offset));
|
||||
errno = savedErrnoProbe;
|
||||
if (!batchWritable) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
std::byte existingWords[0x10]{};
|
||||
const int savedErrnoBufProbe = errno;
|
||||
const bool bufWritable = GuestCopyIn_nid_no_patch(existingWords, static_cast<const std::byte*>(localBatch.buffer) + offset, sizeof(existingWords)) &&
|
||||
GuestCopyOut_nid_no_patch(static_cast<std::byte*>(localBatch.buffer) + offset, existingWords, sizeof(existingWords));
|
||||
errno = savedErrnoBufProbe;
|
||||
if (!bufWritable) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const std::byte zeroNotification[0x80]{};
|
||||
const int savedErrnoNotif = errno;
|
||||
const bool copiedNotif = GuestCopyOut_nid_no_patch(notification, zeroNotification, sizeof(zeroNotification));
|
||||
errno = savedErrnoNotif;
|
||||
if (!copiedNotif) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const std::uint64_t words[2] = {0xeu | (static_cast<std::uint64_t>(static_cast<std::uint8_t>(value)) << 24), reinterpret_cast<std::uintptr_t>(notification)};
|
||||
std::memcpy(static_cast<std::byte*>(batch->buffer) + offset, words, sizeof(words));
|
||||
batch->offset = end;
|
||||
const int savedErrnoBuf = errno;
|
||||
const bool copiedBuf = GuestCopyOut_nid_no_patch(static_cast<std::byte*>(localBatch.buffer) + offset, words, sizeof(words));
|
||||
errno = savedErrnoBuf;
|
||||
if (!copiedBuf) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
const std::uint64_t end = offset + sizeof(words);
|
||||
const int savedErrnoBack = errno;
|
||||
const bool copiedBack = GuestCopyOut_nid_no_patch(&batch->offset, &end, sizeof(end));
|
||||
errno = savedErrnoBack;
|
||||
if (!copiedBack) return SCE_ACM_ERROR_BAD_POINTER;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -480,23 +543,32 @@ extern "C" {
|
||||
|
||||
void* APS5_VABI libSceAcmUnknown_9_plus_f3tPdeyP0_nid_no_patch(void* ring) {
|
||||
if (!ring) return nullptr;
|
||||
auto* const fields = static_cast<std::byte*>(ring);
|
||||
constexpr std::size_t ringBytes = 0x14;
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(ring);
|
||||
if (address > std::numeric_limits<std::uintptr_t>::max() - ringBytes) return nullptr;
|
||||
std::array<std::byte, ringBytes> fields{};
|
||||
const int savedErrno = errno;
|
||||
const bool readable = GuestCopyIn_nid_no_patch(fields.data(), ring, fields.size());
|
||||
errno = savedErrno;
|
||||
if (!readable) return nullptr;
|
||||
std::uint64_t base = 0;
|
||||
std::uint32_t capacity = 0;
|
||||
std::uint32_t count = 0;
|
||||
std::uint32_t index = 0;
|
||||
std::memcpy(&base, fields, sizeof(base));
|
||||
std::memcpy(&capacity, fields + 0x8, sizeof(capacity));
|
||||
std::memcpy(&count, fields + 0xc, sizeof(count));
|
||||
std::memcpy(&base, fields.data(), sizeof(base));
|
||||
std::memcpy(&capacity, fields.data() + 0x8, sizeof(capacity));
|
||||
std::memcpy(&count, fields.data() + 0xc, sizeof(count));
|
||||
const std::uint32_t nextCount = std::min(count + 1u, capacity);
|
||||
std::memcpy(fields + 0xc, &nextCount, sizeof(nextCount));
|
||||
std::uint32_t next = capacity;
|
||||
if (count != 0) {
|
||||
std::memcpy(&index, fields + 0x10, sizeof(index));
|
||||
std::memcpy(&index, fields.data() + 0x10, sizeof(index));
|
||||
next = index + 1u;
|
||||
}
|
||||
if (next == capacity) next = 0;
|
||||
std::memcpy(fields + 0x10, &next, sizeof(next));
|
||||
const std::array<std::uint32_t, 2> updated{nextCount, next};
|
||||
const bool writable = GuestCopyOut_nid_no_patch(reinterpret_cast<void*>(address + 0xc), updated.data(), sizeof(updated));
|
||||
errno = savedErrno;
|
||||
if (!writable) return nullptr;
|
||||
return reinterpret_cast<void*>(base + (static_cast<std::uint64_t>(next << 8) << 2));
|
||||
}
|
||||
APS5_EXPORT("9+f3tPdeyP0", libSceAcmUnknown_9_plus_f3tPdeyP0_nid_no_patch);
|
||||
|
||||
@@ -12,7 +12,7 @@ uint32_t* APS5_VABI sceAgcAcbCopyData(CommandBuffer* buf, uint8_t dst, uint8_t d
|
||||
std::uint64_t APS5_VABI sceAgcAcbCopyDataGetSize();
|
||||
std::uint32_t* APS5_VABI sceAgcAcbDmaData(CommandBuffer* buf, std::uint8_t dst, std::uint8_t dstCachePolicy, std::uint64_t dstAddress, std::uint8_t src, std::uint8_t srcCachePolicy, std::uint64_t srcAddress, std::uint32_t numBytes, std::uint8_t waitForPrevious, std::uint8_t writeConfirm);
|
||||
std::uint32_t APS5_VABI sceAgcAcbDmaDataGetSize();
|
||||
std::uint32_t* APS5_VABI sceAgcAcbAtomicMem(CommandBuffer* buf, std::uint8_t atomicOp, std::uint8_t command, std::uint8_t cachePolicy, const volatile void* address, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval);
|
||||
std::uint32_t* APS5_VABI sceAgcAcbAtomicMem(CommandBuffer* buf, std::uint8_t atomicOp, std::uint8_t command, const volatile void* address, std::uint8_t cachePolicy, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval);
|
||||
std::uint32_t APS5_VABI sceAgcAcbAtomicMemGetSize();
|
||||
std::uint32_t APS5_VABI sceAgcAcbAtomicGdsGetSize();
|
||||
std::uint32_t* APS5_VABI sceAgcAcbPrimeUtcl2(CommandBuffer* buf, const volatile void* address, std::uint32_t sizeInBytes);
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
extern "C" {
|
||||
|
||||
std::uint32_t* APS5_VABI sceAgcAcbAcquireMem(CommandBuffer* buf, std::uint32_t gcrControl, const volatile void* base, std::uint64_t sizeBytes, std::uint32_t pollCycles) {
|
||||
return sceAgcDcbAcquireMem(buf, 1, 0, gcrControl, base, sizeBytes, pollCycles);
|
||||
return Agc::Command::WriteAcquireMem(buf, 0, 0, gcrControl, base, sizeBytes, pollCycles, __func__);
|
||||
}
|
||||
|
||||
uint32_t APS5_VABI sceAgcAcbAcquireMemGetSize(void) {
|
||||
@@ -34,8 +34,8 @@ std::uint32_t APS5_VABI sceAgcAcbDmaDataGetSize() {
|
||||
return 28;
|
||||
}
|
||||
|
||||
std::uint32_t* APS5_VABI sceAgcAcbAtomicMem(CommandBuffer* buf, std::uint8_t atomicOp, std::uint8_t command, std::uint8_t cachePolicy, const volatile void* address, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval) {
|
||||
return Agc::Command::WriteAtomicMem(buf, atomicOp, command, cachePolicy, address, srcData, compareData, loopInterval, __func__);
|
||||
std::uint32_t* APS5_VABI sceAgcAcbAtomicMem(CommandBuffer* buf, std::uint8_t atomicOp, std::uint8_t command, const volatile void* address, std::uint8_t cachePolicy, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval) {
|
||||
return Agc::Command::WriteAtomicMem(buf, 0, atomicOp, command, cachePolicy, reinterpret_cast<std::uintptr_t>(address), srcData, compareData, loopInterval, __func__);
|
||||
}
|
||||
|
||||
std::uint32_t APS5_VABI sceAgcAcbAtomicMemGetSize() {
|
||||
|
||||
@@ -29,15 +29,11 @@ std::uint32_t APS5_VABI sceAgcCbBranchGetSize() {
|
||||
}
|
||||
|
||||
std::uint32_t* APS5_VABI sceAgcCbCondWrite(CommandBuffer* buf, std::uint32_t compareFunction, std::uint32_t writeSpace, const volatile void* writeAddress, std::uint32_t writeData, const volatile void* pollAddress, std::uint32_t reference, std::uint32_t mask) {
|
||||
Agc::Command::Require(compareFunction <= 6, __func__, "invalid write comparison");
|
||||
Agc::Command::Require(writeSpace == 1, __func__, "only memory writes are supported");
|
||||
const auto destination = reinterpret_cast<std::uintptr_t>(writeAddress);
|
||||
const auto source = reinterpret_cast<std::uintptr_t>(pollAddress);
|
||||
Agc::Command::CheckAddress(destination, 4, __func__);
|
||||
Agc::Command::CheckAddress(source, 4, __func__);
|
||||
Agc::Command::CheckBits(destination, 0xffffffffffffull, __func__);
|
||||
Agc::Command::CheckBits(source, 0xffffffffffffull, __func__);
|
||||
return Agc::Command::Emit(buf, 0x45u, {0x10u | compareFunction | (writeSpace << 8u), static_cast<std::uint32_t>(source), static_cast<std::uint32_t>(source >> 32u), reference, mask, static_cast<std::uint32_t>(destination), static_cast<std::uint32_t>(destination >> 32u), writeData}, __func__);
|
||||
return Agc::Command::Emit(buf, 0x45u, {0x10u | (compareFunction & 7u) | ((writeSpace & 3u) << 8u), static_cast<std::uint32_t>(source), static_cast<std::uint32_t>(source >> 32u), reference, mask, static_cast<std::uint32_t>(destination), static_cast<std::uint32_t>(destination >> 32u), writeData}, __func__);
|
||||
}
|
||||
|
||||
std::uint32_t APS5_VABI sceAgcCbCondWriteGetSize() {
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
namespace Agc::Command {
|
||||
|
||||
std::uint32_t* WriteDma(CommandBuffer* buffer, bool compute, std::uint8_t engine, std::uint8_t dst, std::uint8_t dstCachePolicy, std::uint64_t dstAddress, std::uint8_t src, std::uint8_t srcCachePolicy, std::uint64_t srcAddress, std::uint32_t numBytes, std::uint8_t waitForPrevious, std::uint8_t writeConfirm, std::uint8_t blockEngine, const char* function);
|
||||
std::uint32_t* WriteAcquireMem(CommandBuffer* buffer, std::uint32_t engine, std::uint32_t cbDbOp, std::uint32_t gcrControl, const volatile void* base, std::uint64_t sizeBytes, std::uint32_t pollCycles, const char* function);
|
||||
std::uint32_t* WriteCopyData(CommandBuffer* buffer, bool compute, std::uint8_t dst, std::uint8_t dstCachePolicy, std::uint64_t dstAddress, std::uint8_t src, std::uint8_t srcCachePolicy, std::uint64_t srcAddressOrImmediate, std::uint8_t itemSize, std::uint8_t writeConfirm, const char* function);
|
||||
std::uint32_t* WriteAtomicMem(CommandBuffer* buffer, std::uint8_t atomicOp, std::uint8_t command, std::uint8_t cachePolicy, const volatile void* address, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval, const char* function);
|
||||
std::uint32_t* WriteAtomicMem(CommandBuffer* buffer, std::uint8_t engine, std::uint8_t atomicOp, std::uint8_t command, std::uint8_t cachePolicy, std::uint64_t address, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval, const char* function);
|
||||
std::uint32_t* WritePrimeUtcl2(CommandBuffer* buffer, const volatile void* address, std::uint32_t sizeInBytes, const char* function);
|
||||
std::uint32_t* WriteData(CommandBuffer* buffer, bool compute, std::uint8_t dst, std::uint8_t cachePolicy, std::uint64_t address, const void* data, std::uint32_t count, std::uint8_t increment, std::uint8_t writeConfirm, const char* function);
|
||||
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);
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
#include "prx/libSceAgc/Command/include/Memory.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace Agc::Command {
|
||||
|
||||
std::uint32_t* WriteAcquireMem(CommandBuffer* buffer, std::uint32_t engine, std::uint32_t cbDbOp, std::uint32_t gcrControl, const volatile void* base, std::uint64_t sizeBytes, std::uint32_t pollCycles, const char* function) {
|
||||
constexpr std::uint64_t lastPage = (1ull << 40u) - 1u;
|
||||
const auto requested = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(base));
|
||||
const bool wholeRange = (cbDbOp & 0x04004000u) != 0;
|
||||
const std::uint64_t page = wholeRange ? 1u : requested >> 8u;
|
||||
const std::uint64_t blocks = !wholeRange && sizeBytes <= (lastPage << 8u) - (requested & 0xffu) ? (sizeBytes + (requested & 0xffu) + 0xffu) >> 8u : page < lastPage ? lastPage - page : 0;
|
||||
const auto control = gcrControl & 0x7ffffu;
|
||||
return Emit(buffer, 0x58u, {((engine & 1u) << 31u) | (cbDbOp & 0x06007fc0u), static_cast<std::uint32_t>(blocks), static_cast<std::uint32_t>(blocks >> 32u) & 0xffu,
|
||||
static_cast<std::uint32_t>(page), static_cast<std::uint32_t>(page >> 32u) & 0xffffffu, std::min(pollCycles >> 4u, 0xffffu), control | ((control & 0x4000u) << 1u)}, function);
|
||||
}
|
||||
|
||||
std::uint32_t* WriteDma(CommandBuffer* buffer, bool compute, std::uint8_t engine, std::uint8_t dst, std::uint8_t dstCachePolicy, std::uint64_t dstAddress, std::uint8_t src, std::uint8_t srcCachePolicy, std::uint64_t srcAddress, std::uint32_t numBytes, std::uint8_t waitForPrevious, std::uint8_t writeConfirm, std::uint8_t blockEngine, const char* function) {
|
||||
CheckBits(engine, 1, function);
|
||||
CheckBits(dst, 0xfu, function);
|
||||
CheckBits(dstCachePolicy, 3, function);
|
||||
CheckBits(srcCachePolicy, 3, function);
|
||||
engine &= 1u;
|
||||
dst &= 0xfu;
|
||||
dstCachePolicy &= 3u;
|
||||
srcCachePolicy &= 3u;
|
||||
CheckBits(waitForPrevious, 1, function);
|
||||
CheckBits(writeConfirm, 1, function);
|
||||
CheckBits(blockEngine, 1, function);
|
||||
@@ -19,7 +31,7 @@ std::uint32_t* WriteDma(CommandBuffer* buffer, bool compute, std::uint8_t engine
|
||||
const auto slot = src == 0x14u ? 0u : src == 0x24u ? 1u : 2u;
|
||||
srcAddress = (engine == 1 ? 0x30148u : 0x30174u) + slot * 8u;
|
||||
} else {
|
||||
CheckBits(src, 0xfu, function);
|
||||
src &= 0xfu;
|
||||
}
|
||||
const auto control = engine | (static_cast<std::uint32_t>(srcCachePolicy) << 13u) | ((dst & 3u) << 20u) | (static_cast<std::uint32_t>(dstCachePolicy) << 25u) | ((src & 3u) << 29u) | (static_cast<std::uint32_t>(blockEngine) << 31u);
|
||||
const auto command = numBytes | ((src & 4u) << 24u) | ((dst & 4u) << 25u) | ((src & 8u) << 25u) | ((dst & 8u) << 26u) | (static_cast<std::uint32_t>(waitForPrevious) << 30u) | (static_cast<std::uint32_t>(writeConfirm) << 31u);
|
||||
@@ -27,8 +39,8 @@ std::uint32_t* WriteDma(CommandBuffer* buffer, bool compute, std::uint8_t engine
|
||||
}
|
||||
|
||||
std::uint32_t* WriteCopyData(CommandBuffer* buffer, bool compute, std::uint8_t dst, std::uint8_t dstCachePolicy, std::uint64_t dstAddress, std::uint8_t src, std::uint8_t srcCachePolicy, std::uint64_t srcAddressOrImmediate, std::uint8_t itemSize, std::uint8_t writeConfirm, const char* function) {
|
||||
CheckBits(dstCachePolicy, 3, function);
|
||||
CheckBits(srcCachePolicy, 3, function);
|
||||
dstCachePolicy &= 3u;
|
||||
srcCachePolicy &= 3u;
|
||||
CheckBits(itemSize, 1, function);
|
||||
CheckBits(writeConfirm, 1, function);
|
||||
const auto srcSelect = compute ? static_cast<std::uint32_t>(src) & 0xfu : (static_cast<std::uint32_t>(src) >> 1u) & 0xfu;
|
||||
@@ -39,14 +51,9 @@ std::uint32_t* WriteCopyData(CommandBuffer* buffer, bool compute, std::uint8_t d
|
||||
return Emit(buffer, 0x40u, {control, static_cast<std::uint32_t>(srcAddressOrImmediate), static_cast<std::uint32_t>(srcAddressOrImmediate >> 32u), static_cast<std::uint32_t>(dstAddress), static_cast<std::uint32_t>(dstAddress >> 32u)}, function);
|
||||
}
|
||||
|
||||
std::uint32_t* WriteAtomicMem(CommandBuffer* buffer, std::uint8_t atomicOp, std::uint8_t command, std::uint8_t cachePolicy, const volatile void* address, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval, const char* function) {
|
||||
CheckBits(atomicOp, 0x7fu, function);
|
||||
CheckBits(command, 0xfu, function);
|
||||
CheckBits(cachePolicy, 3, function);
|
||||
CheckBits(loopInterval, 0x1fffu, function);
|
||||
const auto guestAddress = reinterpret_cast<std::uintptr_t>(address);
|
||||
CheckAddress(guestAddress, (atomicOp & 0x60u) == 0x60u ? 8 : 4, function);
|
||||
return Emit(buffer, 0x1eu, {atomicOp | (static_cast<std::uint32_t>(command) << 8u) | (static_cast<std::uint32_t>(cachePolicy) << 25u), static_cast<std::uint32_t>(guestAddress), static_cast<std::uint32_t>(guestAddress >> 32u), static_cast<std::uint32_t>(srcData), static_cast<std::uint32_t>(srcData >> 32u), static_cast<std::uint32_t>(compareData), static_cast<std::uint32_t>(compareData >> 32u), loopInterval}, function);
|
||||
std::uint32_t* WriteAtomicMem(CommandBuffer* buffer, std::uint8_t engine, std::uint8_t atomicOp, std::uint8_t command, std::uint8_t cachePolicy, std::uint64_t address, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval, const char* function) {
|
||||
const auto control = (atomicOp & 0x7fu) | ((static_cast<std::uint32_t>(command) & 0xfu) << 8u) | ((static_cast<std::uint32_t>(cachePolicy) & 3u) << 25u) | ((static_cast<std::uint32_t>(engine) & 3u) << 30u);
|
||||
return Emit(buffer, 0x1eu, {control, static_cast<std::uint32_t>(address), static_cast<std::uint32_t>(address >> 32u), static_cast<std::uint32_t>(srcData), static_cast<std::uint32_t>(srcData >> 32u), static_cast<std::uint32_t>(compareData), static_cast<std::uint32_t>(compareData >> 32u), loopInterval & 0x1fffu}, function);
|
||||
}
|
||||
|
||||
std::uint32_t* WritePrimeUtcl2(CommandBuffer* buffer, const volatile void* address, std::uint32_t sizeInBytes, const char* function) {
|
||||
@@ -62,15 +69,17 @@ std::uint32_t* WriteData(CommandBuffer* buffer, bool compute, std::uint8_t dst,
|
||||
CheckBits(writeConfirm, 1, function);
|
||||
Require(compute || (address & 3u) == 0, function, "misaligned write address");
|
||||
Require(dst != 0 || writeConfirm == 0, function, "register writes do not support write confirmation");
|
||||
std::vector<std::uint32_t> snapshot(count);
|
||||
std::memcpy(snapshot.data(), data, count * sizeof(std::uint32_t));
|
||||
std::array<std::uint32_t, 64> inlineSnapshot;
|
||||
std::vector<std::uint32_t> heapSnapshot(count > inlineSnapshot.size() ? count : 0u);
|
||||
auto* snapshot = count > inlineSnapshot.size() ? heapSnapshot.data() : inlineSnapshot.data();
|
||||
std::memcpy(snapshot, data, count * sizeof(std::uint32_t));
|
||||
const auto destination = compute ? static_cast<std::uint32_t>(dst) << 8u : ((dst & 1u) << 30u) | ((dst & 0x1eu) << 7u);
|
||||
auto* packet = Allocate(buffer, count + 4u, function);
|
||||
packet[0] = Header(0x37u, count + 4u);
|
||||
packet[1] = destination | (static_cast<std::uint32_t>(increment) << 16u) | (static_cast<std::uint32_t>(writeConfirm) << 20u) | (static_cast<std::uint32_t>(cachePolicy) << 25u);
|
||||
packet[2] = static_cast<std::uint32_t>(address);
|
||||
packet[3] = static_cast<std::uint32_t>(address >> 32u);
|
||||
std::copy(snapshot.begin(), snapshot.end(), packet + 4);
|
||||
std::copy_n(snapshot, count, packet + 4);
|
||||
return packet;
|
||||
}
|
||||
|
||||
|
||||
@@ -46,17 +46,12 @@ std::uint32_t APS5_VABI sceAgcDcbDrawIndexIndirectGetSize() {
|
||||
}
|
||||
|
||||
uint32_t* APS5_VABI sceAgcDcbDrawIndexIndirectMulti(CommandBuffer* buf, uint32_t data_offset_in_bytes, uint32_t count_indirect, uint32_t max_count_or_count, const volatile void* count_addr, uint32_t stride_in_bytes, uint64_t modifier) {
|
||||
Agc::Command::CheckBits(count_indirect, 1, __func__);
|
||||
Agc::Command::Require((data_offset_in_bytes & 3u) == 0 && (stride_in_bytes & 3u) == 0 && stride_in_bytes >= 20, __func__, "invalid indirect draw offset or stride");
|
||||
Agc::Command::Require((count_indirect & 1u) == 0 || count_indirect == 1, __func__, "an odd count selector above 1 is not measured");
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(count_addr);
|
||||
if (count_indirect != 0) {
|
||||
Agc::Command::CheckAddress(address, 4, __func__);
|
||||
} else {
|
||||
Agc::Command::Require(address == 0, __func__, "count address supplied for a direct draw count");
|
||||
}
|
||||
if (count_indirect == 1) Agc::Command::CheckAddress(address, 4, __func__);
|
||||
const auto offsets = Agc::Command::DrawPatchOffsets(modifier, __func__);
|
||||
const auto low = static_cast<std::uint32_t>(modifier);
|
||||
const auto control = Agc::Command::DrawIndexLocation(modifier) | ((low & 0x10u) << 23u) | (count_indirect << 30u) | ((low & 8u) << 28u);
|
||||
const auto control = Agc::Command::DrawIndexLocation(modifier) | ((low & 0x10u) << 23u) | ((count_indirect & 1u) << 30u) | ((low & 8u) << 28u);
|
||||
const auto initiator = Agc::Command::DrawInitiator(modifier, true, __func__);
|
||||
auto* packet = Agc::Command::Allocate(buf, 16, __func__);
|
||||
packet[0] = Agc::Command::Header(0x79u, 3, 4);
|
||||
|
||||
@@ -20,18 +20,13 @@ std::uint32_t APS5_VABI sceAgcDcbDrawIndirectGetSize() {
|
||||
}
|
||||
|
||||
std::uint32_t* APS5_VABI sceAgcDcbDrawIndirectMulti(CommandBuffer* buf, std::uint32_t dataOffsetInBytes, std::uint32_t countIndirect, std::uint32_t maxCountOrCount, const volatile void* countAddress, std::uint32_t strideInBytes, std::uint64_t modifier) {
|
||||
Agc::Command::CheckBits(countIndirect, 1, __func__);
|
||||
Agc::Command::Require((dataOffsetInBytes & 3u) == 0 && (strideInBytes & 3u) == 0 && strideInBytes >= 16, __func__, "invalid indirect draw offset or stride");
|
||||
Agc::Command::Require((countIndirect & 1u) == 0 || countIndirect == 1, __func__, "an odd count selector above 1 is not measured");
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(countAddress);
|
||||
if (countIndirect != 0) {
|
||||
Agc::Command::CheckAddress(address, 4, __func__);
|
||||
} else {
|
||||
Agc::Command::Require(address == 0, __func__, "count address supplied for a direct draw count");
|
||||
}
|
||||
if (countIndirect == 1) Agc::Command::CheckAddress(address, 4, __func__);
|
||||
const auto offsets = Agc::Command::DrawPatchOffsets(modifier, __func__);
|
||||
const auto initiator = Agc::Command::DrawInitiator(modifier, false, __func__);
|
||||
const auto low = static_cast<std::uint32_t>(modifier);
|
||||
const auto control = Agc::Command::DrawIndexLocation(modifier) | ((low & 0x10u) << 23u) | (countIndirect << 30u) | ((low & 8u) << 28u);
|
||||
const auto control = Agc::Command::DrawIndexLocation(modifier) | ((low & 0x10u) << 23u) | ((countIndirect & 1u) << 30u) | ((low & 8u) << 28u);
|
||||
auto* packet = Agc::Command::Allocate(buf, 16, __func__);
|
||||
packet[0] = Agc::Command::Header(0x79u, 3, 4);
|
||||
packet[1] = 0x342u;
|
||||
|
||||
@@ -17,15 +17,12 @@ std::uint32_t APS5_VABI sceAgcDcbSetNumInstancesGetSize() {
|
||||
}
|
||||
|
||||
uint32_t* APS5_VABI sceAgcDcbSetBaseIndirectArgs(CommandBuffer* buf, uint32_t shader_type, const volatile void* indirect_base_addr) {
|
||||
// SET_BASE with base index 1; header bit 1 selects the dispatch (compute) base over the draw base.
|
||||
Agc::Command::CheckBits(shader_type, 1, __func__);
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(indirect_base_addr);
|
||||
if (address != 0) Agc::Command::CheckAddress(address, 8, __func__);
|
||||
Agc::Command::CheckBits(address, 0xffffffffffffull, __func__);
|
||||
Agc::Command::Require((address & 1u) == 0, __func__, "an odd indirect base address is not measured");
|
||||
auto* packet = Agc::Command::Allocate(buf, 4, __func__);
|
||||
packet[0] = Agc::Command::Header(0x11u, 4, shader_type != 0 ? 2u : 0u);
|
||||
packet[0] = Agc::Command::Header(0x11u, 4) | (shader_type << 1u);
|
||||
packet[1] = 1;
|
||||
packet[2] = static_cast<std::uint32_t>(address);
|
||||
packet[2] = static_cast<std::uint32_t>(address) & ~6u;
|
||||
packet[3] = static_cast<std::uint32_t>(address >> 32u);
|
||||
return packet;
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ uint32_t* APS5_VABI sceAgcDcbCopyData(CommandBuffer* buf, uint8_t dst, uint8_t d
|
||||
std::uint64_t APS5_VABI sceAgcDcbCopyDataGetSize();
|
||||
std::uint32_t* APS5_VABI sceAgcDcbDmaData(CommandBuffer* buf, std::uint8_t engine, std::uint8_t dst, std::uint8_t dstCachePolicy, std::uint64_t dstAddress, std::uint8_t src, std::uint8_t srcCachePolicy, std::uint64_t srcAddress, std::uint32_t numBytes, std::uint8_t waitForPrevious, std::uint8_t writeConfirm, std::uint8_t blockEngine);
|
||||
std::uint32_t APS5_VABI sceAgcDcbDmaDataGetSize();
|
||||
std::uint32_t* APS5_VABI sceAgcDcbAtomicMem(CommandBuffer* buf, std::uint8_t atomicOp, std::uint8_t command, std::uint8_t cachePolicy, const volatile void* address, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval);
|
||||
std::uint32_t* APS5_VABI sceAgcDcbAtomicMem(CommandBuffer* buf, std::uint8_t engine, std::uint8_t atomicOp, std::uint8_t command, std::uint8_t cachePolicy, const volatile void* address, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval);
|
||||
std::uint32_t APS5_VABI sceAgcDcbAtomicMemGetSize();
|
||||
std::uint32_t* APS5_VABI sceAgcDcbWriteData(CommandBuffer* buf, std::uint8_t dst, std::uint8_t cachePolicy, std::uint64_t address, const void* data, std::uint32_t numDwords, std::uint8_t increment, std::uint8_t writeConfirm);
|
||||
uint32_t APS5_VABI sceAgcDcbWriteDataGetSize(uint32_t numDwords);
|
||||
|
||||
@@ -11,19 +11,7 @@
|
||||
extern "C" {
|
||||
|
||||
std::uint32_t* APS5_VABI sceAgcDcbAcquireMem(CommandBuffer* buf, std::uint8_t engine, std::uint32_t cbDbOp, std::uint32_t gcrControl, const volatile void* base, std::uint64_t sizeBytes, std::uint32_t pollCycles) {
|
||||
Agc::Command::CheckBits(engine, 1, __func__);
|
||||
Agc::Command::CheckBits(cbDbOp, 0x7fffffffu, __func__);
|
||||
Agc::Command::CheckBits(gcrControl, 0x7ffffu, __func__);
|
||||
// The range only scopes cache maintenance, so round it outward to the 256-byte granularity the
|
||||
// packet encodes instead of rejecting unaligned ranges.
|
||||
const auto requested = reinterpret_cast<std::uintptr_t>(base);
|
||||
auto address = requested & ~static_cast<std::uintptr_t>(0xffu);
|
||||
auto wholeAddressSpace = sizeBytes == 0xffffffffffffffffull || (address >> 40u) != 0 || sizeBytes > (1ull << 40u);
|
||||
if (!wholeAddressSpace) sizeBytes = (sizeBytes + (requested - address) + 0xffu) & ~0xffull;
|
||||
wholeAddressSpace = wholeAddressSpace || sizeBytes >= (1ull << 40u);
|
||||
if (wholeAddressSpace) address = 0;
|
||||
const auto pollWord = std::min<std::uint32_t>(pollCycles >> 4u, 0xffffu);
|
||||
return Agc::Command::Emit(buf, 0x58u, {(static_cast<std::uint32_t>(engine) << 31u) | cbDbOp, wholeAddressSpace ? 0u : static_cast<std::uint32_t>(sizeBytes >> 8u), 0, static_cast<std::uint32_t>(address >> 8u), 0, pollWord, gcrControl | ((gcrControl & 0x4000u) << 1u)}, __func__);
|
||||
return Agc::Command::WriteAcquireMem(buf, engine, cbDbOp, gcrControl, base, sizeBytes, pollCycles, __func__);
|
||||
}
|
||||
|
||||
uint32_t APS5_VABI sceAgcDcbAcquireMemGetSize(void) {
|
||||
@@ -46,8 +34,8 @@ std::uint32_t APS5_VABI sceAgcDcbDmaDataGetSize() {
|
||||
return 28;
|
||||
}
|
||||
|
||||
std::uint32_t* APS5_VABI sceAgcDcbAtomicMem(CommandBuffer* buf, std::uint8_t atomicOp, std::uint8_t command, std::uint8_t cachePolicy, const volatile void* address, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval) {
|
||||
return Agc::Command::WriteAtomicMem(buf, atomicOp, command, cachePolicy, address, srcData, compareData, loopInterval, __func__);
|
||||
std::uint32_t* APS5_VABI sceAgcDcbAtomicMem(CommandBuffer* buf, std::uint8_t engine, std::uint8_t atomicOp, std::uint8_t command, std::uint8_t cachePolicy, const volatile void* address, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval) {
|
||||
return Agc::Command::WriteAtomicMem(buf, engine, atomicOp, command, cachePolicy, reinterpret_cast<std::uintptr_t>(address), srcData, compareData, loopInterval, __func__);
|
||||
}
|
||||
|
||||
std::uint32_t APS5_VABI sceAgcDcbAtomicMemGetSize() {
|
||||
|
||||
@@ -16,8 +16,7 @@ int APS5_VABI sceAgcInit(std::uint32_t version) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int APS5_VABI sceAgcInit_0090(std::uint32_t* state, std::uint32_t version) {
|
||||
Agc::Command::CheckAddress(reinterpret_cast<std::uintptr_t>(state), alignof(std::uint32_t), __func__);
|
||||
int APS5_VABI sceAgcInit_0090(std::uint32_t*, std::uint32_t version) {
|
||||
return sceAgcInit(version);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,11 +20,13 @@ uint32_t APS5_VABI sceAgcGetPacketSize(uint32_t* packet) {
|
||||
int APS5_VABI sceAgcGetDataPacketPayloadAddress_0090(uint32_t** addr, uint32_t* cmd, int type) {
|
||||
Agc::Command::CheckAddress(reinterpret_cast<std::uintptr_t>(addr), alignof(uint32_t*), __func__);
|
||||
Agc::Command::CheckAddress(reinterpret_cast<std::uintptr_t>(cmd), alignof(uint32_t), __func__);
|
||||
uint32_t* payload = nullptr;
|
||||
if (type != 0) {
|
||||
*addr = cmd + 2;
|
||||
payload = cmd + 2;
|
||||
} else {
|
||||
*addr = (~cmd[0] & 0x3fff0000u) != 0 ? cmd + 1 : nullptr;
|
||||
payload = (~cmd[0] & 0x3fff0000u) != 0 ? cmd + 1 : nullptr;
|
||||
}
|
||||
Agc::Command::Require(GuestCopyOut_nid_no_patch(addr, &payload, sizeof(payload)), __func__, "destination pointer is not writable");
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -36,16 +38,18 @@ int APS5_VABI sceAgcGetDataPacketPayloadRange(SceAgcMemoryRange* range, uint32_t
|
||||
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;
|
||||
SceAgcMemoryRange result{};
|
||||
if (type != 0) {
|
||||
range->base = cmd + 2;
|
||||
range->size = count_bytes;
|
||||
result.base = cmd + 2;
|
||||
result.size = count_bytes;
|
||||
} else if ((~cmd[0] & 0x3fff0000u) == 0) {
|
||||
range->base = nullptr;
|
||||
range->size = 0;
|
||||
result.base = nullptr;
|
||||
result.size = 0;
|
||||
} else {
|
||||
range->base = cmd + 1;
|
||||
range->size = count_bytes + sizeof(uint32_t);
|
||||
result.base = cmd + 1;
|
||||
result.size = count_bytes + sizeof(uint32_t);
|
||||
}
|
||||
Agc::Command::Require(GuestCopyOut_nid_no_patch(range, &result, sizeof(result)), __func__, "destination pointer is not writable");
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -55,7 +59,8 @@ int APS5_VABI sceAgcDcbGetSystemSoftwareVersion(uint32_t* destination, const uin
|
||||
Agc::Command::Require((packet[0] & 0xc0000000u) == 0xc0000000u, __func__, "source pointer is not a PM4 packet");
|
||||
const auto size = ((packet[0] >> 16u) & 0x3fffu) + 2u;
|
||||
Agc::Command::Require(size >= 3u, __func__, "PM4 packet is too short to carry a software version");
|
||||
*destination = packet[1];
|
||||
const auto version = packet[1];
|
||||
Agc::Command::Require(GuestCopyOut_nid_no_patch(destination, &version, sizeof(version)), __func__, "destination pointer is not writable");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@ extern "C" {
|
||||
|
||||
int APS5_VABI sceAgcGetIsTrinityMode(bool* isTrinityMode) {
|
||||
Agc::Command::CheckAddress(reinterpret_cast<std::uintptr_t>(isTrinityMode), alignof(bool), __func__);
|
||||
*isTrinityMode = false;
|
||||
const bool trinity = false;
|
||||
Agc::Command::Require(GuestCopyOut_nid_no_patch(isTrinityMode, &trinity, sizeof(trinity)), __func__, "destination pointer is not writable");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ void ResolveRelativePtr(T*& field) {
|
||||
}
|
||||
|
||||
bool GetProgramAddressRegisterOffset(std::uint8_t type, std::uint32_t& loOffset);
|
||||
int PatchProgramAddressRegister(ShaderRegister* regs, std::uint32_t numRegs, std::uint8_t type, std::uint64_t base);
|
||||
int PatchProgramAddressRegister(ShaderRegister* regs, std::uint32_t numRegs, std::uint8_t type, std::uint64_t base, std::uint64_t previousBase = 0);
|
||||
std::uint32_t GraphicsPrimTypeToGsOut(std::uint32_t primType);
|
||||
std::uint32_t ShaderSemanticWord(const ShaderSemantic& s);
|
||||
std::uint32_t ApplyInterpolantDefaultValue(std::uint32_t value, std::uint32_t psWord);
|
||||
|
||||
@@ -35,24 +35,27 @@ int APS5_VABI sceAgcCreateShader(Shader** dst, void* header, const volatile void
|
||||
std::uint32_t programOffset = 0;
|
||||
(void)GetProgramAddressRegisterOffset(h->type, programOffset);
|
||||
|
||||
ResolveRelativePtr(h->cx_registers);
|
||||
ResolveRelativePtr(h->sh_registers);
|
||||
ResolveRelativePtr(h->user_data);
|
||||
ResolveRelativePtr(h->specials);
|
||||
ResolveRelativePtr(h->input_semantics);
|
||||
ResolveRelativePtr(h->output_semantics);
|
||||
const auto previousBase = reinterpret_cast<std::uint64_t>(h->code);
|
||||
if (previousBase == 0) {
|
||||
ResolveRelativePtr(h->cx_registers);
|
||||
ResolveRelativePtr(h->sh_registers);
|
||||
ResolveRelativePtr(h->user_data);
|
||||
ResolveRelativePtr(h->specials);
|
||||
ResolveRelativePtr(h->input_semantics);
|
||||
ResolveRelativePtr(h->output_semantics);
|
||||
|
||||
if (h->user_data != nullptr) {
|
||||
ResolveRelativePtr(h->user_data->direct_resource_offset);
|
||||
ResolveRelativePtr(h->user_data->sharp_resource_offset[0]);
|
||||
ResolveRelativePtr(h->user_data->sharp_resource_offset[1]);
|
||||
ResolveRelativePtr(h->user_data->sharp_resource_offset[2]);
|
||||
ResolveRelativePtr(h->user_data->sharp_resource_offset[3]);
|
||||
if (h->user_data != nullptr) {
|
||||
ResolveRelativePtr(h->user_data->direct_resource_offset);
|
||||
ResolveRelativePtr(h->user_data->sharp_resource_offset[0]);
|
||||
ResolveRelativePtr(h->user_data->sharp_resource_offset[1]);
|
||||
ResolveRelativePtr(h->user_data->sharp_resource_offset[2]);
|
||||
ResolveRelativePtr(h->user_data->sharp_resource_offset[3]);
|
||||
}
|
||||
}
|
||||
|
||||
h->code = code;
|
||||
|
||||
int result = PatchProgramAddressRegister(h->sh_registers, h->num_sh_registers, h->type, base);
|
||||
int result = PatchProgramAddressRegister(h->sh_registers, h->num_sh_registers, h->type, base, previousBase);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ bool GetProgramAddressRegisterOffset(std::uint8_t type, std::uint32_t& loOffset)
|
||||
}
|
||||
}
|
||||
|
||||
int PatchProgramAddressRegister(ShaderRegister* regs, std::uint32_t numRegs, std::uint8_t type, std::uint64_t base) {
|
||||
int PatchProgramAddressRegister(ShaderRegister* regs, std::uint32_t numRegs, std::uint8_t type, std::uint64_t base, std::uint64_t previousBase) {
|
||||
std::uint32_t loOffset = 0;
|
||||
if (!GetProgramAddressRegisterOffset(type, loOffset)) {
|
||||
return 0;
|
||||
@@ -37,9 +37,13 @@ int PatchProgramAddressRegister(ShaderRegister* regs, std::uint32_t numRegs, std
|
||||
if (hiIndex >= numRegs || regs[hiIndex].offset != loOffset + 1u) {
|
||||
throw std::runtime_error("sceAgcCreateShader: shader program address hi register missing");
|
||||
}
|
||||
const std::uint64_t shaderOffset =
|
||||
const std::uint64_t patched =
|
||||
(static_cast<std::uint64_t>(regs[i].value) << 8u) |
|
||||
((static_cast<std::uint64_t>(regs[hiIndex].value) & 0xFFu) << 40u);
|
||||
if (patched < previousBase) {
|
||||
throw std::runtime_error(std::string(__func__) + ": shader program address below the previous code address");
|
||||
}
|
||||
const std::uint64_t shaderOffset = patched - previousBase;
|
||||
if (base > 0xffffffffffffull || shaderOffset > 0xffffffffffffull - base) {
|
||||
throw std::runtime_error(std::string(__func__) + ": shader program address overflow");
|
||||
}
|
||||
|
||||
@@ -24,15 +24,19 @@ struct Storage {
|
||||
}
|
||||
};
|
||||
|
||||
using Writer = std::uint32_t* (APS5_VABI *)(CommandBuffer*, std::uint8_t, std::uint8_t, std::uint8_t, const volatile void*, std::uint64_t, std::uint64_t, std::uint16_t);
|
||||
using Writer = std::uint32_t* (APS5_VABI *)(CommandBuffer*, std::uint8_t, std::uint8_t, const volatile void*, std::uint8_t, std::uint64_t, std::uint64_t, std::uint16_t);
|
||||
|
||||
void testPacket(Writer writer, std::uint32_t size, std::uint8_t atomicOp, std::uintptr_t address) {
|
||||
std::uint32_t* APS5_VABI writeDcb(CommandBuffer* buffer, std::uint8_t atomicOp, std::uint8_t command, const volatile void* address, std::uint8_t cachePolicy, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval) {
|
||||
return sceAgcDcbAtomicMem(buffer, 1, atomicOp, command, cachePolicy, address, srcData, compareData, loopInterval);
|
||||
}
|
||||
|
||||
void testPacket(Writer writer, std::uint32_t size, std::uint8_t atomicOp, std::uintptr_t address, std::uint32_t engineBits) {
|
||||
check(size == 36, "ATOMIC_MEM packet size");
|
||||
Storage storage;
|
||||
auto* packet = writer(&storage.buffer, atomicOp, 0x5, 2, reinterpret_cast<const volatile void*>(address), 0x1122334455667788ull, 0x99aabbccddeeff00ull, 0x1abc);
|
||||
auto* packet = writer(&storage.buffer, atomicOp, 0x5, reinterpret_cast<const volatile void*>(address), 2, 0x1122334455667788ull, 0x99aabbccddeeff00ull, 0x1abc);
|
||||
const std::array<std::uint32_t, 9> expected{
|
||||
0xc0071e00u,
|
||||
atomicOp | (0x5u << 8u) | (2u << 25u),
|
||||
atomicOp | (0x5u << 8u) | (2u << 25u) | engineBits,
|
||||
static_cast<std::uint32_t>(address),
|
||||
static_cast<std::uint32_t>(address >> 32u),
|
||||
0x55667788u,
|
||||
@@ -46,14 +50,24 @@ void testPacket(Writer writer, std::uint32_t size, std::uint8_t atomicOp, std::u
|
||||
check(std::all_of(storage.words.begin() + expected.size(), storage.words.end(), [](std::uint32_t word) { return word == Sentinel; }), "ATOMIC_MEM wrote past its nine words");
|
||||
}
|
||||
|
||||
void testMasking() {
|
||||
Storage compute;
|
||||
const auto* packet = sceAgcAcbAtomicMem(&compute.buffer, 0xff, 0xff, reinterpret_cast<const volatile void*>(0x1002ull), 0xff, 0, 0, 0xffff);
|
||||
check(packet[1] == (0x7fu | 0xf00u | (3u << 25u)) && packet[2] == 0x1002u && packet[8] == 0x1fffu, "compute ATOMIC_MEM did not mask its fields");
|
||||
Storage draw;
|
||||
const auto* drawPacket = sceAgcDcbAtomicMem(&draw.buffer, 0xff, 0xff, 0xff, 0xff, reinterpret_cast<const volatile void*>(0x1002ull), 0, 0, 0xffff);
|
||||
check(drawPacket[1] == (0x7fu | 0xf00u | (3u << 25u) | 0xc0000000u) && drawPacket[2] == 0x1002u && drawPacket[8] == 0x1fffu, "draw ATOMIC_MEM did not mask its fields");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
testPacket(sceAgcDcbAtomicMem, sceAgcDcbAtomicMemGetSize(), 0x2f, 0x0000123456789ab4ull);
|
||||
testPacket(sceAgcDcbAtomicMem, sceAgcDcbAtomicMemGetSize(), 0x6f, 0x0000123456789ab8ull);
|
||||
testPacket(sceAgcAcbAtomicMem, sceAgcAcbAtomicMemGetSize(), 0x2f, 0x0000123456789ab4ull);
|
||||
testPacket(sceAgcAcbAtomicMem, sceAgcAcbAtomicMemGetSize(), 0x6f, 0x0000123456789ab8ull);
|
||||
testPacket(writeDcb, sceAgcDcbAtomicMemGetSize(), 0x2f, 0x0000123456789ab4ull, 0x40000000u);
|
||||
testPacket(writeDcb, sceAgcDcbAtomicMemGetSize(), 0x6f, 0x0000123456789ab8ull, 0x40000000u);
|
||||
testPacket(sceAgcAcbAtomicMem, sceAgcAcbAtomicMemGetSize(), 0x2f, 0x0000123456789ab4ull, 0);
|
||||
testPacket(sceAgcAcbAtomicMem, sceAgcAcbAtomicMemGetSize(), 0x6f, 0x0000123456789ab8ull, 0);
|
||||
testMasking();
|
||||
std::puts("AGC atomic memory tests passed");
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "prx/libSceAgc/Command/include/Packet.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <stdexcept>
|
||||
@@ -50,28 +51,44 @@ void testPacket() {
|
||||
check(sceAgcCbCondWriteGetSize() == 9 * sizeof(std::uint32_t), "COND_WRITE size mismatch");
|
||||
}
|
||||
|
||||
void testConsoleArguments() {
|
||||
struct Case {
|
||||
std::uint32_t compareFunction;
|
||||
std::uint32_t writeSpace;
|
||||
std::uintptr_t writeAddress;
|
||||
std::uint32_t writeData;
|
||||
std::uintptr_t pollAddress;
|
||||
std::array<std::uint32_t, 9> packet;
|
||||
};
|
||||
const Case cases[] = {
|
||||
{0x11111111u, 0x22222222u, 0x33333333u, 0x44444444u, 0x55555555u, {0xc0074500u, 0x211u, 0x55555555u, 0, 0, 1, 0x33333333u, 0, 0x44444444u}},
|
||||
{1, 2, 3, 4, 5, {0xc0074500u, 0x211u, 5, 0, 0, 1, 3, 0, 4}},
|
||||
{0x22222222u, 0x44444444u, 0, 0, 0, {0xc0074500u, 0x12u, 0, 0, 0, 1, 0, 0, 0}},
|
||||
};
|
||||
for (const Case& entry : cases) {
|
||||
Storage storage;
|
||||
const auto* packet = sceAgcCbCondWrite(&storage.buffer, entry.compareFunction, entry.writeSpace, at(entry.writeAddress), entry.writeData, at(entry.pollAddress), 0, 1);
|
||||
check(packet == storage.words.data(), "console COND_WRITE arguments were refused");
|
||||
for (std::size_t index = 0; index < entry.packet.size(); ++index) check(packet[index] == entry.packet[index], "console COND_WRITE packet mismatch");
|
||||
check(storage.buffer.cursor_up == storage.words.data() + 9 && storage.words[9] == Sentinel, "console COND_WRITE cursor advance");
|
||||
}
|
||||
}
|
||||
|
||||
void testInvalid() {
|
||||
Storage storage;
|
||||
const auto before = storage.words;
|
||||
const auto poll = at(0x1000u);
|
||||
const auto write = at(0x2000u);
|
||||
expectFailure([&] { sceAgcCbCondWrite(&storage.buffer, 7, 1, write, 0, poll, 0, 0); });
|
||||
expectFailure([&] { sceAgcCbCondWrite(&storage.buffer, 3, 0, write, 0, poll, 0, 0); });
|
||||
expectFailure([&] { sceAgcCbCondWrite(&storage.buffer, 3, 2, write, 0, poll, 0, 0); });
|
||||
expectFailure([&] { sceAgcCbCondWrite(&storage.buffer, 3, 1, nullptr, 0, poll, 0, 0); });
|
||||
expectFailure([&] { sceAgcCbCondWrite(&storage.buffer, 3, 1, at(0x2002u), 0, poll, 0, 0); });
|
||||
expectFailure([&] { sceAgcCbCondWrite(&storage.buffer, 3, 1, write, 0, nullptr, 0, 0); });
|
||||
expectFailure([&] { sceAgcCbCondWrite(&storage.buffer, 3, 1, write, 0, at(0x1001u), 0, 0); });
|
||||
expectFailure([&] { sceAgcCbCondWrite(&storage.buffer, 3, 1, at(0x0001000000000000u), 0, poll, 0, 0); });
|
||||
expectFailure([&] { sceAgcCbCondWrite(&storage.buffer, 3, 1, write, 0, at(0x0001000000000000u), 0, 0); });
|
||||
check(storage.words == before && storage.buffer.cursor_up == storage.words.data(), "failed COND_WRITE modified the buffer");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
testPacket();
|
||||
testConsoleArguments();
|
||||
testInvalid();
|
||||
std::puts("AGC COND_WRITE tests passed");
|
||||
return 0;
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <tuple>
|
||||
#include <cstdio>
|
||||
#include <stdexcept>
|
||||
#include <cstring>
|
||||
@@ -186,11 +187,39 @@ void testIndexedIndirectDraws() {
|
||||
check(sceAgcDcbDrawIndexIndirectMultiGetSize() == expectedMulti.size() * sizeof(std::uint32_t), "indexed indirect multi draw size differs from its packets");
|
||||
const auto before = storage.words;
|
||||
expectFailure([&] { sceAgcDcbDrawIndexIndirect(&storage.buffer, 2, 0); });
|
||||
expectFailure([&] { sceAgcDcbDrawIndexIndirectMulti(&storage.buffer, 0, 1, 8, &count, 16, 0); });
|
||||
expectFailure([&] { sceAgcDcbDrawIndexIndirectMulti(&storage.buffer, 0, 0, 8, &count, 20, 0); });
|
||||
expectFailure([&] { sceAgcDcbDrawIndexIndirectMulti(&storage.buffer, 0, 1, 8, nullptr, 20, 0); });
|
||||
expectFailure([&] { sceAgcDcbDrawIndexIndirectMulti(&storage.buffer, 0, 3, 8, &count, 20, 0); });
|
||||
check(storage.words == before, "invalid indexed indirect draw modified packet memory");
|
||||
}
|
||||
|
||||
void testMeasuredMultiDraws() {
|
||||
struct Case {
|
||||
std::uint32_t offset;
|
||||
std::uint32_t selector;
|
||||
std::uint32_t count;
|
||||
std::uintptr_t address;
|
||||
std::uint32_t stride;
|
||||
};
|
||||
const std::array<Case, 3> cases{{{0x11111111u, 0x22222222u, 0x33333333u, 0x44444444u, 0x55555555u}, {1, 2, 3, 4, 5}, {0x22222222u, 0x44444444u, 0, 0, 0}}};
|
||||
for (const auto& item : cases) {
|
||||
const auto* address = reinterpret_cast<const volatile void*>(item.address);
|
||||
Storage indexed;
|
||||
const auto* indexedPacket = sceAgcDcbDrawIndexIndirectMulti(&indexed.buffer, item.offset, item.selector, item.count, address, item.stride, 0);
|
||||
const std::array<std::uint32_t, 16> expectedIndexed{0xc0017904u, 0x342u, 0xc6000005u, 0xc0083800u, item.offset, 0x280u, 0x280u, 0x280u, item.count, static_cast<std::uint32_t>(item.address), 0u, item.stride, 0u, 0xc0017904u, 0x342u, 0xc6000000u};
|
||||
check(indexedPacket == indexed.words.data() && std::equal(expectedIndexed.begin(), expectedIndexed.end(), indexedPacket), "indexed indirect multi draw differs from the console's packet");
|
||||
Storage plain;
|
||||
const auto* plainPacket = sceAgcDcbDrawIndirectMulti(&plain.buffer, item.offset, item.selector, item.count, address, item.stride, 0);
|
||||
const std::array<std::uint32_t, 16> expectedPlain{0xc0017904u, 0x342u, 0xc6000008u, 0xc0082c00u, item.offset, 0x280u, 0x280u, 0x280u, item.count, static_cast<std::uint32_t>(item.address), 0u, item.stride, 2u, 0xc0017904u, 0x342u, 0xc6000000u};
|
||||
check(plainPacket == plain.words.data() && std::equal(expectedPlain.begin(), expectedPlain.end(), plainPacket), "indirect multi draw differs from the console's packet");
|
||||
}
|
||||
Storage refused;
|
||||
const auto before = refused.words;
|
||||
alignas(4) std::uint32_t count = 0;
|
||||
expectFailure([&] { sceAgcDcbDrawIndirectMulti(&refused.buffer, 0, 1, 8, nullptr, 16, 0); });
|
||||
expectFailure([&] { sceAgcDcbDrawIndirectMulti(&refused.buffer, 0, 0x11111111u, 8, &count, 16, 0); });
|
||||
check(refused.words == before && refused.buffer.cursor_up == refused.words.data(), "refused indirect multi draw modified the buffer");
|
||||
}
|
||||
|
||||
void testTagHeaders() {
|
||||
Storage draw;
|
||||
const auto* multi = sceAgcDcbDrawIndirectMulti(&draw.buffer, 0x40, 0, 5, nullptr, 16, 0);
|
||||
@@ -496,9 +525,20 @@ void testIndirectBase() {
|
||||
check(bound[1] == 1 && bound[2] == static_cast<std::uint32_t>(address) && bound[3] == static_cast<std::uint32_t>(address >> 32u), "indirect base address mismatch");
|
||||
const auto* cleared = sceAgcDcbSetBaseIndirectArgs(&storage.buffer, 1, nullptr);
|
||||
check(cleared == bound + 4 && (cleared[0] & 2u) != 0 && cleared[1] == 1 && cleared[2] == 0 && cleared[3] == 0, "indirect base was not cleared");
|
||||
const auto* masked = sceAgcDcbSetBaseIndirectArgs(&storage.buffer, 0, reinterpret_cast<const volatile void*>(address + 6));
|
||||
check(masked == cleared + 4 && masked[0] == 0xc0021100u && masked[2] == static_cast<std::uint32_t>(address) && masked[3] == static_cast<std::uint32_t>(address >> 32u), "indirect base kept address bits 1 and 2");
|
||||
const std::array<std::uint32_t, 4> expectedWide{0xe2223322u, 1u, 0x22222220u, 0u};
|
||||
const auto* wide = sceAgcDcbSetBaseIndirectArgs(&storage.buffer, 0x11111111u, reinterpret_cast<const volatile void*>(std::uintptr_t{0x22222222u}));
|
||||
check(wide == masked + 4 && std::equal(expectedWide.begin(), expectedWide.end(), wide), "indirect base differs from the console's packet for a wide shader type");
|
||||
const std::array<std::uint32_t, 4> expectedCompute{0xc0021102u, 1u, 0u, 0u};
|
||||
const auto* compute = sceAgcDcbSetBaseIndirectArgs(&storage.buffer, 1, reinterpret_cast<const volatile void*>(std::uintptr_t{2}));
|
||||
check(compute == wide + 4 && std::equal(expectedCompute.begin(), expectedCompute.end(), compute), "indirect base differs from the console's packet for a compute base");
|
||||
const std::array<std::uint32_t, 4> expectedHigh{0xc4465544u, 1u, 0x44444440u, 0x33333333u};
|
||||
const auto* high = sceAgcDcbSetBaseIndirectArgs(&storage.buffer, 0x22222222u, reinterpret_cast<const volatile void*>(std::uintptr_t{0x3333333344444444ull}));
|
||||
check(high == compute + 4 && std::equal(expectedHigh.begin(), expectedHigh.end(), high), "indirect base differs from the console's packet for a 64-bit address");
|
||||
const auto before = storage.words;
|
||||
expectFailure([&] { sceAgcDcbSetBaseIndirectArgs(&storage.buffer, 0, reinterpret_cast<const volatile void*>(address + 4)); });
|
||||
check(storage.words == before, "misaligned indirect base modified packet memory");
|
||||
expectFailure([&] { sceAgcDcbSetBaseIndirectArgs(&storage.buffer, 0, reinterpret_cast<const volatile void*>(address + 1)); });
|
||||
check(storage.words == before, "odd indirect base modified packet memory");
|
||||
}
|
||||
|
||||
void testContextState() {
|
||||
@@ -773,29 +813,29 @@ void testMemory() {
|
||||
check(storage.words == beforeMask, "invalid mask patch modified packet memory");
|
||||
|
||||
Storage acquireStorage;
|
||||
auto* acquire = sceAgcDcbAcquireMem(&acquireStorage.buffer, 0, 0x1234u, 0x567u, nullptr, 0x1000, 0);
|
||||
auto* acquire = sceAgcDcbAcquireMem(&acquireStorage.buffer, 0, 0x1200u, 0x567u, nullptr, 0x1000, 0);
|
||||
check(acquire[0] == Agc::Command::Header(0x58u, 8), "acquire mem header mismatch");
|
||||
check(acquire[1] == 0x1234u, "acquire mem engine bit was set");
|
||||
check(acquire[1] == 0x1200u, "acquire mem engine bit was set");
|
||||
check(sceAgcAcquireMemSetEngine(acquire, 1) == 0, "sceAgcAcquireMemSetEngine failed");
|
||||
check(acquire[1] == 0x80001234u, "acquire mem engine bit was not set to 1");
|
||||
check(acquire[1] == 0x80001200u, "acquire mem engine bit was not set to 1");
|
||||
check(sceAgcAcquireMemSetEngine(acquire, 0) == 0, "sceAgcAcquireMemSetEngine failed");
|
||||
check(acquire[1] == 0x1234u, "acquire mem engine bit was not cleared to 0");
|
||||
check(acquire[1] == 0x1200u, "acquire mem engine bit was not cleared to 0");
|
||||
check(sceAgcAcquireMemSetEngine(acquire, 1) == 0, "sceAgcAcquireMemSetEngine failed");
|
||||
check(acquire[1] == 0x80001234u, "acquire mem engine bit was not set to 1");
|
||||
check(acquire[1] == 0x80001200u, "acquire mem engine bit was not set to 1");
|
||||
check(sceAgcAcquireMemSetEngine(acquire, 2) == 0, "sceAgcAcquireMemSetEngine failed with engine 2");
|
||||
check(acquire[1] == 0x1234u, "engine 2 did not clear the engine bit");
|
||||
check(acquire[1] == 0x1200u, "engine 2 did not clear the engine bit");
|
||||
check(sceAgcAcquireMemSetEngine(acquire, 3) == 0, "sceAgcAcquireMemSetEngine failed with engine 3");
|
||||
check(acquire[1] == 0x80001234u, "engine 3 did not set the engine bit");
|
||||
check(acquire[1] == 0x80001200u, "engine 3 did not set the engine bit");
|
||||
check(sceAgcAcquireMemSetEngine(acquire, 4) == 0, "sceAgcAcquireMemSetEngine failed with engine 4");
|
||||
check(acquire[1] == 0x1234u, "engine 4 did not clear the engine bit");
|
||||
check(acquire[1] == 0x1200u, "engine 4 did not clear the engine bit");
|
||||
check(sceAgcAcquireMemSetEngine(acquire, static_cast<std::uint8_t>(0xffffffffu)) == 0, "sceAgcAcquireMemSetEngine failed with 0xffffffff");
|
||||
check(acquire[1] == 0x80001234u, "0xffffffff did not set the engine bit");
|
||||
check(acquire[1] == 0x80001200u, "0xffffffff did not set the engine bit");
|
||||
check(sceAgcAcquireMemSetEngine(acquire, 0) == 0, "sceAgcAcquireMemSetEngine failed");
|
||||
check(acquire[1] == 0x1234u, "acquire mem engine bit was not cleared to 0");
|
||||
check(acquire[1] == 0x1200u, "acquire mem engine bit was not cleared to 0");
|
||||
check(sceAgcAcquireMemSetEngine(acquire, 0xffu) == 0, "sceAgcAcquireMemSetEngine failed with 0xff");
|
||||
check(acquire[1] == 0x80001234u, "0xff did not set the engine bit");
|
||||
check(acquire[1] == 0x80001200u, "0xff did not set the engine bit");
|
||||
check(sceAgcAcquireMemSetEngine(acquire, 0) == 0, "sceAgcAcquireMemSetEngine failed");
|
||||
check(acquire[1] == 0x1234u, "acquire mem engine bit was not cleared to 0");
|
||||
check(acquire[1] == 0x1200u, "acquire mem engine bit was not cleared to 0");
|
||||
const auto beforeAcquire = acquireStorage.words;
|
||||
expectFailure([&] { sceAgcAcquireMemSetEngine(nullptr, 0); });
|
||||
auto* misalignedAcquire = reinterpret_cast<std::uint32_t*>(reinterpret_cast<unsigned char*>(acquire) + 1);
|
||||
@@ -812,7 +852,7 @@ void testMemory() {
|
||||
check(customLengthAcquire[1] == 0x80004321u, "custom length acquire mem engine bit was not set");
|
||||
|
||||
auto* acbAcquire = sceAgcAcbAcquireMem(&acquireStorage.buffer, 0x567u, nullptr, 0x1000, 0);
|
||||
check(acbAcquire[1] == 0x80000000u, "ACB acquire mem engine bit was not default 1");
|
||||
check(acbAcquire[1] == 0u, "ACB acquire mem did not select engine 0");
|
||||
check(sceAgcAcquireMemSetEngine(acbAcquire, 0) == 0, "sceAgcAcquireMemSetEngine failed on ACB acquire");
|
||||
check(acbAcquire[1] == 0u, "ACB acquire mem engine bit was not cleared to 0");
|
||||
}
|
||||
@@ -974,10 +1014,6 @@ void testCopyDataAndComputeEvents() {
|
||||
rejected.words.fill(0xa5a5a5a5u);
|
||||
const auto rejectedWords = rejected.words;
|
||||
const auto* rejectedCursor = rejected.buffer.cursor_up;
|
||||
expectFailure([&] { sceAgcDcbCopyData(&rejected.buffer, 4, 4, 0x1000, 0xa, 0, 1, 0, 0); });
|
||||
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
|
||||
expectFailure([&] { sceAgcDcbCopyData(&rejected.buffer, 4, 0, 0x1000, 0xa, 4, 1, 0, 0); });
|
||||
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
|
||||
expectFailure([&] { sceAgcAcbCopyData(&rejected.buffer, 2, 0, 0x4000, 5, 0, 1, 2, 0); });
|
||||
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
|
||||
expectFailure([&] { sceAgcAcbCopyData(&rejected.buffer, 2, 0, 0x4000, 5, 0, 1, 0, 2); });
|
||||
@@ -1011,7 +1047,13 @@ void testDefaults() {
|
||||
std::uint32_t state = 0x12345678;
|
||||
check(sceAgcInit_0090(&state, 8) == 0 && state == 0x12345678, "AGC initialization failed or modified caller state");
|
||||
check(sceAgcInit_0090(&state, 13) == 0 && state == 0x12345678, "AGC version 13 initialization changed caller state");
|
||||
expectFailure([] { sceAgcInit_0090(nullptr, 8); });
|
||||
for (const std::uint32_t version : {0u, 1u, 8u, 13u, 14u, 0xffffc278u, 0xffffffffu}) {
|
||||
const auto expected = sceAgcInit(version);
|
||||
for (const std::uintptr_t ignored : {std::uintptr_t{0}, std::uintptr_t{1}, std::uintptr_t{2}, std::uintptr_t{3}, std::uintptr_t{0x10001}, ~std::uintptr_t{0}, reinterpret_cast<std::uintptr_t>(&state)}) {
|
||||
check(sceAgcInit_0090(reinterpret_cast<std::uint32_t*>(ignored), version) == expected, "legacy AGC initialization inspected the ignored argument");
|
||||
check(state == 0x12345678, "legacy AGC initialization modified its ignored argument");
|
||||
}
|
||||
}
|
||||
check(sceAgcInit_0090(&state, 14) == 0 && state == 0x12345678, "out-of-range AGC initialization version changed caller state");
|
||||
check(sceAgcInit(8) == 0, "AGC version initialization failed");
|
||||
check(sceAgcInit(13) == 0, "AGC version 13 initialization failed");
|
||||
@@ -1192,33 +1234,37 @@ void testAcquireMem() {
|
||||
sceAgcDcbAcquireMem(&measured.buffer, 0, 0, gcrControl, base, 0x1000, 0xa0);
|
||||
check(measured.words[7] == gcrWord, "acquire cache control word does not set bit 15 with bit 14");
|
||||
}
|
||||
Storage whole;
|
||||
sceAgcDcbAcquireMem(&whole.buffer, 0, 0, 0, base, 0xffffffffffffffffull, 0);
|
||||
check(whole.words[0] == 0xc0065800u && whole.words[2] == 0 && whole.words[4] == 0 && whole.words[6] == 0, "an unbounded acquire did not cover the whole address space");
|
||||
Storage large;
|
||||
sceAgcDcbAcquireMem(&large.buffer, 0, 0, 0, base, (1ull << 40u) + 1u, 0);
|
||||
check(large.words[2] == 0 && large.words[4] == 0, "an acquire over 1 TiB did not cover the whole address space");
|
||||
Storage exact;
|
||||
sceAgcDcbAcquireMem(&exact.buffer, 0, 0, 0, base, 1ull << 40u, 0);
|
||||
check(exact.words[2] == 0 && exact.words[4] == 0, "an acquire of exactly 1 TiB did not cover the whole address space");
|
||||
Storage encodable;
|
||||
sceAgcDcbAcquireMem(&encodable.buffer, 0, 0, 0, nullptr, (1ull << 40u) - 0x100u, 0);
|
||||
check(encodable.words[2] == 0xffffffffu && encodable.words[4] == 0, "an acquire just below 1 TiB was not encoded as its exact size");
|
||||
Storage roundedUp;
|
||||
sceAgcDcbAcquireMem(&roundedUp.buffer, 0, 0, 0, reinterpret_cast<const volatile void*>(0x1ull), (1ull << 40u) - 0xffu, 0);
|
||||
check(roundedUp.words[2] == 0 && roundedUp.words[4] == 0, "an acquire rounded up to 1 TiB did not cover the whole address space");
|
||||
const auto* measuredBase = reinterpret_cast<const volatile void*>(0x100000ull);
|
||||
const std::array<std::tuple<std::uint64_t, std::uint32_t, std::uint32_t>, 13> sizes{{{0, 0, 0}, {1, 1, 0}, {0xff, 1, 0}, {0x100, 1, 0}, {0x101, 2, 0}, {0x1000, 0x10, 0}, {0xffffffffull, 0x1000000u, 0}, {0x100000000ull, 0x1000000u, 0}, {1ull << 40u, 0, 1}, {(1ull << 48u) - 0x100u, 0xffffffffu, 0xff}, {(1ull << 48u) - 0xffu, 0xffffefffu, 0xff}, {(1ull << 48u) - 1u, 0xffffefffu, 0xff}, {0xffffffffffffffffull, 0xffffefffu, 0xff}}};
|
||||
for (const auto& [sizeBytes, low, high] : sizes) {
|
||||
Storage measured;
|
||||
sceAgcDcbAcquireMem(&measured.buffer, 0, 0, 0x4380u, measuredBase, sizeBytes, 0xa0);
|
||||
const std::array<std::uint32_t, 8> expectedSize{0xc0065800u, 0, low, high, 0x1000u, 0, 10, 0xc380u};
|
||||
check(std::equal(expectedSize.begin(), expectedSize.end(), measured.words.begin()), "acquire size is not the measured block count");
|
||||
}
|
||||
Storage offset;
|
||||
sceAgcDcbAcquireMem(&offset.buffer, 0, 0, 0x4380u, reinterpret_cast<const volatile void*>(0x100010ull), 0x1000, 0xa0);
|
||||
check(offset.words[2] == 0x11u && offset.words[4] == 0x1000u, "an unaligned acquire base did not round its range outward");
|
||||
const std::array<std::pair<std::uint32_t, std::uint32_t>, 9> operations{{{1, 0}, {2, 0}, {4, 0}, {8, 0}, {0x10, 0}, {0x100, 0x100}, {0x1000, 0x1000}, {0x10000, 0}, {0x100000, 0}}};
|
||||
for (const auto& [cbDbOp, word] : operations) {
|
||||
Storage measured;
|
||||
sceAgcDcbAcquireMem(&measured.buffer, 0, cbDbOp, 0x4380u, measuredBase, 0x1000, 0xa0);
|
||||
check(measured.words[1] == word && measured.words[2] == 0x10u && measured.words[4] == 0x1000u, "acquire CB/DB operation is not the measured word");
|
||||
}
|
||||
for (const std::uint32_t cbDbOp : {0x7fffffffu, 0x4000u, 0x4000000u}) {
|
||||
Storage depth;
|
||||
sceAgcDcbAcquireMem(&depth.buffer, 1, cbDbOp, 0x4380u, measuredBase, 0x1000, 0xa0);
|
||||
const std::array<std::uint32_t, 8> expectedWhole{0xc0065800u, 0x80000000u | (cbDbOp & 0x06007fc0u), 0xfffffffeu, 0xffu, 1, 0, 10, 0xc380u};
|
||||
check(std::equal(expectedWhole.begin(), expectedWhole.end(), depth.words.begin()), "a DB operation did not cover the whole range");
|
||||
}
|
||||
Storage high;
|
||||
sceAgcDcbAcquireMem(&high.buffer, 3, 0x2000200u, 0xfff84000u, reinterpret_cast<const volatile void*>(0xabcdef0123456700ull), 0x100, 0);
|
||||
const std::array<std::uint32_t, 8> expectedHigh{0xc0065800u, 0x82000200u, 1, 0, 0x01234567u, 0xabcdefu, 0, 0xc000u};
|
||||
check(std::equal(expectedHigh.begin(), expectedHigh.end(), high.words.begin()), "acquire did not keep the engine low bit, the CB fields, 19 control bits and the base high bits");
|
||||
Storage asynchronous;
|
||||
sceAgcAcbAcquireMem(&asynchronous.buffer, 0x55u, base, 0x100, 80);
|
||||
const std::array<std::uint32_t, 8> compute{0xc0065800u, 0x80000000u, 2, 0, 0x12345678u, 0, 5, 0x55u};
|
||||
check(std::equal(compute.begin(), compute.end(), asynchronous.words.begin()), "the asynchronous compute acquire did not select engine 1 with no CB/DB operation");
|
||||
Storage rejected;
|
||||
rejected.words.fill(0xa5a5a5a5u);
|
||||
const auto rejectedWords = rejected.words;
|
||||
const auto* rejectedCursor = rejected.buffer.cursor_up;
|
||||
expectFailure([&] { sceAgcDcbAcquireMem(&rejected.buffer, 2, 0, 0, base, 0x100, 0); });
|
||||
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
|
||||
expectFailure([&] { sceAgcDcbAcquireMem(&rejected.buffer, 0, 0, 0x80000u, base, 0x100, 0); });
|
||||
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
|
||||
const std::array<std::uint32_t, 8> compute{0xc0065800u, 0, 2, 0, 0x12345678u, 0, 5, 0x55u};
|
||||
check(std::equal(compute.begin(), compute.end(), asynchronous.words.begin()), "the asynchronous compute acquire did not select engine 0 with no CB/DB operation");
|
||||
Storage saturatedAsync;
|
||||
sceAgcAcbAcquireMem(&saturatedAsync.buffer, 0, base, 0x100, 0xffffffffu);
|
||||
check(saturatedAsync.words[6] == 0xffffu, "the asynchronous compute acquire did not saturate the poll word at 0xffff");
|
||||
@@ -1266,6 +1312,7 @@ int main(int argc, char** argv) {
|
||||
testDispatchPackets();
|
||||
testClearState();
|
||||
testIndexedIndirectDraws();
|
||||
testMeasuredMultiDraws();
|
||||
testTagHeaders();
|
||||
testMarkers();
|
||||
testJumpTargetPatch();
|
||||
|
||||
@@ -39,7 +39,6 @@ void testDrawQueueCopy() {
|
||||
check(packet == storage.words.data() && std::equal(expected.begin(), expected.end(), packet), "DCB COPY_DATA packet mismatch");
|
||||
check(storage.buffer.cursor_up == storage.words.data() + expected.size(), "DCB COPY_DATA cursor advance mismatch");
|
||||
check(sceAgcDcbCopyDataGetSize() == expected.size() * sizeof(std::uint32_t), "DCB COPY_DATA size differs from its packet");
|
||||
expectFailure(storage, [&] { sceAgcDcbCopyData(&storage.buffer, 2, 4, 0x1000, 4, 0, 0x2000, 0, 0); }, "a DCB destination cache policy above 3 was accepted");
|
||||
expectFailure(storage, [&] { sceAgcDcbCopyData(&storage.buffer, 2, 0, 0x1000, 4, 0, 0x2000, 2, 0); }, "a DCB item size above 1 was accepted");
|
||||
expectFailure(storage, [&] { sceAgcDcbCopyData(&storage.buffer, 2, 0, 0x1000, 10, 0, 0x100000000ull, 0, 0); }, "a DCB 32-bit immediate wider than 32 bits was accepted");
|
||||
}
|
||||
@@ -57,6 +56,24 @@ void testComputeQueueCopy() {
|
||||
expectFailure(storage, [&] { sceAgcAcbCopyData(&storage.buffer, 1, 0, 0x1000, 5, 0, 0, 0, 2); }, "an ACB write confirm above 1 was accepted");
|
||||
}
|
||||
|
||||
template <typename TWriter>
|
||||
void expectConsolePacket(TWriter writer, const std::array<std::uint32_t, 5>& body) {
|
||||
Storage storage;
|
||||
const auto* packet = writer(&storage.buffer);
|
||||
check(packet == storage.words.data() && packet[0] == 0xc0044000u, "console COPY_DATA arguments were refused");
|
||||
check(std::equal(body.begin(), body.end(), packet + 1), "console COPY_DATA packet mismatch");
|
||||
check(storage.buffer.cursor_up == packet + 6, "console COPY_DATA cursor advance mismatch");
|
||||
}
|
||||
|
||||
void testConsoleArguments() {
|
||||
expectConsolePacket([](CommandBuffer* buffer) { return sceAgcAcbCopyData(buffer, 0x11, 0x22, 0x33333333u, 0x44, 0x55, 0, 1, 0); }, {0x04012104u, 0, 0, 0x33333333u, 0});
|
||||
expectConsolePacket([](CommandBuffer* buffer) { return sceAgcAcbCopyData(buffer, 1, 2, 3, 4, 5, 0, 1, 0); }, {0x04012104u, 0, 0, 3, 0});
|
||||
expectConsolePacket([](CommandBuffer* buffer) { return sceAgcAcbCopyData(buffer, 0x22, 0x44, 0, 0, 0, 0, 1, 0); }, {0x00010200u, 0, 0, 0, 0});
|
||||
expectConsolePacket([](CommandBuffer* buffer) { return sceAgcDcbCopyData(buffer, 0x11, 0x22, 0x33333333u, 0x44, 0x55, 0, 1, 0); }, {0x04012802u, 0, 0, 0x33333333u, 0});
|
||||
expectConsolePacket([](CommandBuffer* buffer) { return sceAgcDcbCopyData(buffer, 1, 2, 3, 4, 5, 0, 1, 0); }, {0x04012002u, 0, 0, 3, 0});
|
||||
expectConsolePacket([](CommandBuffer* buffer) { return sceAgcDcbCopyData(buffer, 0x22, 0x44, 0, 0, 0, 0, 1, 0); }, {0x00010100u, 0, 0, 0, 0});
|
||||
}
|
||||
|
||||
void testWriteDataSize() {
|
||||
Storage storage;
|
||||
const std::array<std::uint32_t, 3> payload{1, 2, 3};
|
||||
@@ -67,13 +84,48 @@ void testWriteDataSize() {
|
||||
check(sceAgcDcbWriteDataGetSize(1) == 20 && sceAgcDcbWriteDataGetSize(0x3ffd) == 0x3ffd * 4 + 16, "DCB WRITE_DATA size is not four header words plus the payload");
|
||||
}
|
||||
|
||||
struct LargeStorage {
|
||||
std::array<std::uint32_t, 256> words{};
|
||||
CommandBuffer buffer{words.data(), words.data() + words.size(), words.data(), words.data() + words.size(), nullptr, nullptr, 0};
|
||||
};
|
||||
|
||||
bool APS5_VABI clobberAndMove(CommandBuffer* buffer, std::uint32_t, void* userData) {
|
||||
auto& spare = *static_cast<LargeStorage*>(userData);
|
||||
std::fill(buffer->bottom, buffer->top, 0xdeadbeefu);
|
||||
buffer->bottom = spare.words.data();
|
||||
buffer->top = spare.words.data() + spare.words.size();
|
||||
buffer->cursor_up = buffer->bottom;
|
||||
buffer->cursor_down = buffer->top;
|
||||
return true;
|
||||
}
|
||||
|
||||
void testWriteDataReadsPayloadBeforeCallback() {
|
||||
for (const auto writer : {sceAgcDcbWriteData, sceAgcAcbWriteData}) {
|
||||
for (const std::uint32_t count : {4u, 64u, 65u, 100u}) {
|
||||
LargeStorage full;
|
||||
LargeStorage spare;
|
||||
for (std::uint32_t i = 0; i < count; ++i) full.words[i] = 0x1000u + i;
|
||||
full.buffer.cursor_up = full.words.data() + count;
|
||||
full.buffer.cursor_down = full.buffer.cursor_up + 1;
|
||||
full.buffer.callback = clobberAndMove;
|
||||
full.buffer.user_data = &spare;
|
||||
const auto* packet = writer(&full.buffer, 5, 0, 0x2000, full.words.data(), count, 1, 0);
|
||||
check(packet == spare.words.data() && packet[0] == (0xc0003700u | ((count + 2u) << 16u)) && packet[2] == 0x2000u, "WRITE_DATA header mismatch after the allocation callback");
|
||||
for (std::uint32_t i = 0; i < count; ++i) check(packet[4 + i] == 0x1000u + i, "WRITE_DATA payload was not read before the allocation callback");
|
||||
check(full.buffer.cursor_up == packet + count + 4u, "WRITE_DATA cursor mismatch after the allocation callback");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
testDrawQueueCopy();
|
||||
testComputeQueueCopy();
|
||||
testConsoleArguments();
|
||||
testWriteDataSize();
|
||||
testWriteDataReadsPayloadBeforeCallback();
|
||||
} catch (const std::exception& error) {
|
||||
std::fprintf(stderr, "%s\n", error.what());
|
||||
return 1;
|
||||
|
||||
@@ -13,6 +13,7 @@ const Shader* registered = nullptr;
|
||||
unsigned registrations = 0;
|
||||
|
||||
alignas(256) const std::array<std::uint32_t, 64> code{0xbf810000u};
|
||||
alignas(256) const std::array<std::uint32_t, 64> movedCode{0xbf810000u};
|
||||
|
||||
void check(bool condition, const char* message) {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
@@ -47,13 +48,13 @@ void fill(Binary& binary, ShaderRegs::ShaderBinaryType type, std::uint32_t low)
|
||||
binary.shader.specials = relative(&binary.specials, &binary.shader.specials);
|
||||
}
|
||||
|
||||
Shader* create(Binary& binary) {
|
||||
Shader* create(Binary& binary, const std::array<std::uint32_t, 64>& at = code) {
|
||||
registered = nullptr;
|
||||
registrations = 0;
|
||||
Shader* created = nullptr;
|
||||
check(sceAgcCreateShader(&created, &binary.shader, code.data()) == 0, "sceAgcCreateShader failed");
|
||||
check(sceAgcCreateShader(&created, &binary.shader, at.data()) == 0, "sceAgcCreateShader failed");
|
||||
check(created == &binary.shader && registered == &binary.shader && registrations == 1, "the created shader is not the header, registered once");
|
||||
check(binary.shader.code == code.data(), "the code address was not stored in the header");
|
||||
check(binary.shader.code == at.data(), "the code address was not stored in the header");
|
||||
return created;
|
||||
}
|
||||
|
||||
@@ -88,6 +89,22 @@ void testPixelWithUserData() {
|
||||
check(binary.registers[0].value == static_cast<std::uint32_t>(program >> 8u) && binary.registers[1].value == (0xabcdef00u | static_cast<std::uint32_t>((program >> 40u) & 0xffu)), "SPI_SHADER_PGM_LO_PS and _HI_PS do not hold the code address");
|
||||
}
|
||||
|
||||
void testCreatedAgain() {
|
||||
Binary binary;
|
||||
fill(binary, ShaderRegs::ShaderBinaryType::Ps, ShaderRegs::SPI_SHADER_PGM_LO_PS);
|
||||
binary.shader.user_data = relative(&binary.userData, &binary.shader.user_data);
|
||||
binary.userData.direct_resource_offset = relative(binary.direct.data(), &binary.userData.direct_resource_offset);
|
||||
create(binary);
|
||||
create(binary);
|
||||
check(binary.shader.sh_registers == binary.registers.data() && binary.shader.specials == &binary.specials && binary.shader.user_data == &binary.userData, "a second create resolved the header's pointers again");
|
||||
check(binary.userData.direct_resource_offset == binary.direct.data(), "a second create resolved the user data's pointers again");
|
||||
const auto program = reinterpret_cast<std::uint64_t>(code.data()) + 0x1000u;
|
||||
check(binary.registers[0].value == static_cast<std::uint32_t>(program >> 8u) && binary.registers[1].value == (0xabcdef00u | static_cast<std::uint32_t>((program >> 40u) & 0xffu)), "a second create from the same code moved the program address");
|
||||
create(binary, movedCode);
|
||||
const auto moved = reinterpret_cast<std::uint64_t>(movedCode.data()) + 0x1000u;
|
||||
check(binary.registers[0].value == static_cast<std::uint32_t>(moved >> 8u) && binary.registers[1].value == (0xabcdef00u | static_cast<std::uint32_t>((moved >> 40u) & 0xffu)), "a create from other code did not rebase the program address onto it");
|
||||
}
|
||||
|
||||
void testWithoutProgramAddress() {
|
||||
Binary binary;
|
||||
fill(binary, ShaderRegs::ShaderBinaryType::Fs, 0x30u);
|
||||
@@ -107,6 +124,7 @@ int main() {
|
||||
try {
|
||||
testCompute();
|
||||
testPixelWithUserData();
|
||||
testCreatedAgain();
|
||||
testWithoutProgramAddress();
|
||||
std::puts("AGC create shader tests passed");
|
||||
return 0;
|
||||
|
||||
@@ -74,6 +74,39 @@ void testCommand(TWriter writer, TSize size, std::uint32_t control) {
|
||||
check(shortBuffer.words == before && shortBuffer.buffer.cursor_up == shortBuffer.words.data(), "failed DMA write modified the buffer");
|
||||
}
|
||||
|
||||
void expectPacket(std::uint32_t* packet, const Storage& storage, const std::array<std::uint32_t, 6>& body) {
|
||||
check(packet == storage.words.data() && packet[0] == 0xc0055000u, "console DMA arguments were refused");
|
||||
check(std::equal(body.begin(), body.end(), packet + 1), "console DMA packet mismatch");
|
||||
check(storage.buffer.cursor_up == packet + 7 && storage.words[7] == Sentinel, "console DMA cursor advance");
|
||||
}
|
||||
|
||||
void testConsoleArguments() {
|
||||
{
|
||||
Storage storage;
|
||||
expectPacket(sceAgcAcbDmaData(&storage.buffer, 0x11, 0x22, 0x33333333u, 0x44, 0x55, 0, 1, 0, 0), storage, {0x04102000u, 0, 0, 0x33333333u, 0, 0x04000001u});
|
||||
}
|
||||
{
|
||||
Storage storage;
|
||||
expectPacket(sceAgcAcbDmaData(&storage.buffer, 1, 2, 3, 4, 5, 0, 1, 0, 0), storage, {0x04102000u, 0, 0, 3, 0, 0x04000001u});
|
||||
}
|
||||
{
|
||||
Storage storage;
|
||||
expectPacket(sceAgcAcbDmaData(&storage.buffer, 0x22, 0x44, 0, 0, 0, 0, 1, 0, 0), storage, {0x00200000u, 0, 0, 0, 0, 1});
|
||||
}
|
||||
{
|
||||
Storage storage;
|
||||
expectPacket(sceAgcDcbDmaData(&storage.buffer, 0x11, 0x22, 0x33, 0x44444444u, 0x55, 0, 1, 0x8f6170u, 0, 0, 0), storage, {0x26200001u, 1, 0, 0x44444444u, 0, 0x048f6170u});
|
||||
}
|
||||
{
|
||||
Storage storage;
|
||||
expectPacket(sceAgcDcbDmaData(&storage.buffer, 1, 2, 3, 4, 5, 0, 1, 0x8f62d0u, 0, 1, 0), storage, {0x26200001u, 1, 0, 4, 0, 0x848f62d0u});
|
||||
}
|
||||
{
|
||||
Storage storage;
|
||||
expectPacket(sceAgcDcbDmaData(&storage.buffer, 0x22, 0x44, 0, 0, 0, 0, 1, 0x8f6430u, 0, 1, 0), storage, {0, 1, 0, 0, 0, 0x888f6430u});
|
||||
}
|
||||
}
|
||||
|
||||
void testPatches() {
|
||||
constexpr std::uint64_t PatchedDestination = 0x0000aabbccddeeffull;
|
||||
constexpr std::uint64_t PatchedSource = 0x0000102030405060ull;
|
||||
@@ -101,6 +134,7 @@ int main() {
|
||||
testCommand(writeCompute, sceAgcAcbDmaDataGetSize, 0x44102000u);
|
||||
testCommand(writeDraw, sceAgcDcbDmaDataGetSize, 0xc4102001u);
|
||||
check(sceAgcAcbDmaDataGetSize() == sceAgcDcbDmaDataGetSize(), "compute and draw DMA sizes differ");
|
||||
testConsoleArguments();
|
||||
testPatches();
|
||||
std::puts("AGC DMA data tests passed");
|
||||
return 0;
|
||||
|
||||
@@ -49,12 +49,57 @@ void testSystemSoftwareVersion() {
|
||||
expectFailure([&] { sceAgcDcbGetSystemSoftwareVersion(&version, tooShort.data()); });
|
||||
expectFailure([&] { sceAgcDcbGetSystemSoftwareVersion(nullptr, packet.data()); });
|
||||
expectFailure([&] { sceAgcDcbGetSystemSoftwareVersion(&version, nullptr); });
|
||||
expectFailure([&] { sceAgcDcbGetSystemSoftwareVersion(reinterpret_cast<std::uint32_t*>(std::uintptr_t{0x10}), packet.data()); });
|
||||
for (const auto header : {0x80000000u, 0x3fff1000u, 0x40001000u, 0x00027600u}) {
|
||||
std::array<std::uint32_t, 3> invalidHeader{header, 0xbeefcafeu, 0};
|
||||
expectFailure([&] { sceAgcDcbGetSystemSoftwareVersion(&version, invalidHeader.data()); });
|
||||
}
|
||||
}
|
||||
|
||||
void testDataPacketPayloadAddress() {
|
||||
std::array<std::uint32_t, 4> packet{0xc0020000u, 0x11111111u, 0x22222222u, 0x33333333u};
|
||||
std::uint32_t* addr = nullptr;
|
||||
check(sceAgcGetDataPacketPayloadAddress_0090(&addr, packet.data(), 1) == 0, "type 1 query succeeded");
|
||||
check(addr == packet.data() + 2, "type 1 payload address points to word 2");
|
||||
addr = nullptr;
|
||||
check(sceAgcGetDataPacketPayloadAddress(&addr, packet.data(), 1) == 0, "alias query succeeded");
|
||||
check(addr == packet.data() + 2, "alias payload address matches versioned");
|
||||
|
||||
addr = nullptr;
|
||||
check(sceAgcGetDataPacketPayloadAddress(&addr, packet.data(), 0) == 0, "type 0 query succeeded");
|
||||
check(addr == packet.data() + 1, "type 0 payload address points to word 1 when mask nonzero");
|
||||
|
||||
std::array<std::uint32_t, 2> zeroMaskPacket{0xffff0000u, 0x11111111u};
|
||||
addr = packet.data();
|
||||
check(sceAgcGetDataPacketPayloadAddress(&addr, zeroMaskPacket.data(), 0) == 0, "zero mask query succeeded");
|
||||
check(addr == nullptr, "zero mask type 0 payload address is null");
|
||||
|
||||
expectFailure([&] { sceAgcGetDataPacketPayloadAddress(nullptr, packet.data(), 1); });
|
||||
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); });
|
||||
}
|
||||
|
||||
void testDataPacketPayloadRange() {
|
||||
std::array<std::uint32_t, 4> packet{0xc0040000u, 0x11111111u, 0x22222222u, 0x33333333u};
|
||||
SceAgcMemoryRange range{};
|
||||
check(sceAgcGetDataPacketPayloadRange(&range, packet.data(), 1) == 0, "type 1 payload range query succeeded");
|
||||
check(range.base == packet.data() + 2 && range.size == ((packet[0] >> 14u) & 0xfffcu), "type 1 payload range populated");
|
||||
|
||||
range = {};
|
||||
check(sceAgcGetDataPacketPayloadRange(&range, packet.data(), 0) == 0, "type 0 payload range query succeeded");
|
||||
check(range.base == packet.data() + 1 && range.size == (((packet[0] >> 14u) & 0xfffcu) + sizeof(std::uint32_t)), "type 0 payload range populated");
|
||||
|
||||
std::array<std::uint32_t, 2> zeroMaskPacket{0xffff0000u, 0x11111111u};
|
||||
range = {packet.data(), 128};
|
||||
check(sceAgcGetDataPacketPayloadRange(&range, zeroMaskPacket.data(), 0) == 0, "zero mask payload range query succeeded");
|
||||
check(range.base == nullptr && range.size == 0, "zero mask payload range empty");
|
||||
|
||||
expectFailure([&] { sceAgcGetDataPacketPayloadRange(nullptr, packet.data(), 1); });
|
||||
expectFailure([&] { sceAgcGetDataPacketPayloadRange(&range, nullptr, 1); });
|
||||
expectFailure([&] { sceAgcGetDataPacketPayloadRange(reinterpret_cast<SceAgcMemoryRange*>(std::uintptr_t{0x10}), packet.data(), 1); });
|
||||
}
|
||||
|
||||
void testRejections() {
|
||||
for (const auto header : {0x80000000u, 0x3fff1000u, 0x40001000u, 0x00047600u}) {
|
||||
std::uint32_t word = header;
|
||||
@@ -73,6 +118,8 @@ int main() {
|
||||
testPacketSize();
|
||||
testRejections();
|
||||
testSystemSoftwareVersion();
|
||||
testDataPacketPayloadAddress();
|
||||
testDataPacketPayloadRange();
|
||||
LibcRunShutdown_nid_postfix();
|
||||
std::puts("AGC packet info tests passed");
|
||||
return 0;
|
||||
|
||||
@@ -33,6 +33,7 @@ void testTrinityMode() {
|
||||
|
||||
void testRejections() {
|
||||
expectFailure([] { sceAgcGetIsTrinityMode(nullptr); });
|
||||
expectFailure([] { sceAgcGetIsTrinityMode(reinterpret_cast<bool*>(std::uintptr_t{0x10})); });
|
||||
}
|
||||
|
||||
void testExportLinked() {
|
||||
|
||||
@@ -263,6 +263,8 @@ function(agc_embedded_shader SOURCE STEM SYMBOL OUT_LIST)
|
||||
endfunction()
|
||||
set(agcDepthTransferShaderHeaders)
|
||||
agc_embedded_shader(DepthToStorage.comp DepthToStorage DEPTH_TO_STORAGE_SPV agcDepthTransferShaderHeaders)
|
||||
set(agcStagingCopyBackBoundShaderHeaders)
|
||||
agc_embedded_shader(StagingCopyBackBound.comp StagingCopyBackBound STAGING_COPY_BACK_BOUND_SPV agcStagingCopyBackBoundShaderHeaders)
|
||||
foreach(agcPresentationStage IN ITEMS Vert Frag)
|
||||
string(TOLOWER "${agcPresentationStage}" agcPresentationExtension)
|
||||
string(TOUPPER "${agcPresentationStage}" agcPresentationSymbol)
|
||||
@@ -429,6 +431,7 @@ set(agcDriverSources
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/FrameCapture.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/FrameRecorder.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/VulkanDevice.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Float16NanProbe.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/FloatFlushProbe.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/FloatProbeTolerance.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/Float16ConversionProbe.cpp
|
||||
@@ -501,6 +504,7 @@ set(agcDriverSources
|
||||
${agcSampleDumpsShaderHeader}
|
||||
${agcPresentationShaderHeaders}
|
||||
${agcDepthTransferShaderHeaders}
|
||||
${agcStagingCopyBackBoundShaderHeaders}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Eq/src/Event.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Eq/src/Query.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/Resource/src/Lifecycle.cpp
|
||||
@@ -895,7 +899,7 @@ if(BUILD_TESTING)
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
|
||||
foreach(partialStoreTest agc_driver_depth_plane_partial_store_unimported agc_driver_depth_plane_partial_store_image_copy agc_driver_depth_plane_partial_store_buffer_copy)
|
||||
foreach(partialStoreTest agc_driver_depth_plane_partial_store_unimported agc_driver_depth_plane_partial_store_image_copy agc_driver_depth_plane_partial_store_buffer_copy agc_driver_depth_plane_partial_store_upload_image)
|
||||
set_tests_properties(${partialStoreTest} PROPERTIES
|
||||
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_HOST_IMPORT=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
if(WIN32)
|
||||
|
||||
@@ -21,7 +21,13 @@ public:
|
||||
std::uint64_t address;
|
||||
};
|
||||
|
||||
class DrawCompilePending final : public std::runtime_error {
|
||||
public:
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
bool SkipRefusedDraws();
|
||||
bool AsyncDrawCompile();
|
||||
|
||||
void ReportRefusedDraw(const RefusedDraw& refused);
|
||||
std::optional<std::size_t> RefusedShaderCount();
|
||||
|
||||
@@ -53,6 +53,7 @@ struct DispatchVariant {
|
||||
std::array<std::uint32_t, 4> meshIndexDescriptor{};
|
||||
|
||||
std::shared_ptr<const ShaderSnapshot> shader;
|
||||
std::shared_ptr<const PreparedShaderState::UserDataLink> linking;
|
||||
|
||||
AtomicSharedPtr<const Recipe> recipe;
|
||||
|
||||
|
||||
@@ -163,6 +163,8 @@ private:
|
||||
bool parkedOnTitle() const;
|
||||
void noteAwaitingTitle(std::uint32_t queue, std::uint64_t awaited);
|
||||
void releaseFlipHold();
|
||||
void beginFlipReady(std::uint32_t handle);
|
||||
void endFlipReady(std::uint32_t handle);
|
||||
void finishFlipWork(const std::shared_ptr<FlipWork>& work, std::uint64_t workSerial);
|
||||
std::uint64_t submitFlipWork(std::uint32_t queue);
|
||||
void waitFlipWork(std::uint64_t workSerial);
|
||||
@@ -186,6 +188,7 @@ private:
|
||||
static bool stampValidate();
|
||||
static bool dataHits();
|
||||
static bool verifyDataHits();
|
||||
static std::vector<ShaderRecompiler::MemoryRegion> dispatchRegions(std::span<const ShaderRecompiler::MemoryRegion> memory, std::span<const ShaderRecompiler::MemoryRegion> captured, const PreparedShaderState::UserDataLink* linking);
|
||||
static bool pipelineDispatch();
|
||||
static std::size_t dispatchVariants();
|
||||
static bool insertCompare();
|
||||
@@ -196,7 +199,7 @@ private:
|
||||
void classifyDiffering(std::uint64_t program, std::uint64_t key, const DispatchVariant& old, const DispatchVariant& fresh, const ShaderRecompiler::ResourceCapture* capture, EntryCounters& counters);
|
||||
void reportDispatchCache(EntryCounters& counters);
|
||||
void lookupDispatch(std::uint64_t address, const Submission& submission, std::uint64_t key, bool noDispatchCache, bool traceCache, bool profile, std::span<const ShaderRecompiler::MemoryRegion> memory, DispatchPhaseTiming& phaseTiming, std::array<double, DriverPhaseCount>& phaseMs, std::shared_ptr<const ShaderRecompiler::RecompileResult>& compiledResult, std::shared_ptr<DispatchVariant>& keepVariant, std::vector<ShaderRecompiler::MemoryRegion>& captured, std::vector<std::uint32_t>& liveWords, bool& dataHit, bool& cached, bool& validated, std::shared_ptr<DispatchEntry>& missedEntry, bool& missedDiffering);
|
||||
void insertDispatch(std::uint64_t address, std::uint64_t key, bool noDispatchCache, bool profile, const std::shared_ptr<const ShaderSnapshot>& registeredShader, std::uint64_t forgetAtCapture, std::span<const ShaderRecompiler::MemoryRegion> memory, const std::shared_ptr<ShaderMemory>& shaderMemory, const std::vector<ShaderRecompiler::MemoryRegion>& captured, const std::shared_ptr<const ShaderRecompiler::ResourceCapture>& capture, const std::shared_ptr<const ShaderRecompiler::RecompileResult>& compiledResult, const std::shared_ptr<DispatchEntry>& missedEntry, bool missedDiffering, std::shared_ptr<DispatchVariant>& attachVariant, DispatchPhaseTiming& phaseTiming);
|
||||
void insertDispatch(std::uint64_t address, std::uint64_t key, bool noDispatchCache, bool profile, const std::shared_ptr<const ShaderSnapshot>& registeredShader, std::uint64_t forgetAtCapture, std::span<const ShaderRecompiler::MemoryRegion> memory, const std::shared_ptr<ShaderMemory>& shaderMemory, const std::vector<ShaderRecompiler::MemoryRegion>& captured, const std::shared_ptr<const ShaderRecompiler::ResourceCapture>& capture, const std::shared_ptr<const ShaderRecompiler::RecompileResult>& compiledResult, const std::shared_ptr<DispatchEntry>& missedEntry, bool missedDiffering, std::shared_ptr<DispatchVariant>& attachVariant, DispatchPhaseTiming& phaseTiming, const std::shared_ptr<const PreparedShaderState::UserDataLink>& linking = {});
|
||||
void dispatch(QueueState& queue, std::span<const std::uint32_t> packet, const Submission& submission, std::uint64_t indirectArguments = 0);
|
||||
void verifyDataHit(const ShaderSnapshot& snapshot, std::size_t codeOffset, ShaderRecompiler::RecompileRequest request, std::span<const ShaderRecompiler::MemoryRegion> memory, std::uint64_t address, const DispatchVariant& variant, std::span<const std::uint32_t> liveWords, const ShaderRecompiler::RecompileResult& patched);
|
||||
static bool drawEntries();
|
||||
@@ -322,7 +325,7 @@ private:
|
||||
void noteForeignWriter(std::uint64_t begin, std::uint64_t end, std::uint32_t queue);
|
||||
void noteDrawWriters(std::span<const Graphics::CompiledShader> stages, std::uint32_t queue);
|
||||
static std::vector<std::pair<std::uint64_t, std::uint64_t>> drawWriteRanges(const Graphics::State& graphics, std::span<const Graphics::CompiledShader> stages);
|
||||
void commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, const std::shared_ptr<DrawEntry>& recipeDonor, VulkanDevice::DrawTraceContext trace = {}, std::uint64_t shape = 0);
|
||||
void commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, const std::shared_ptr<DrawEntry>& recipeDonor, VulkanDevice::DrawTraceContext trace = {}, std::uint64_t shape = 0, const std::vector<std::uint32_t>* contentKey = nullptr);
|
||||
bool labelPacketQueues(std::span<const std::uint32_t> packet, std::uint32_t opcode);
|
||||
bool enqueueLabelPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue, std::optional<std::uint32_t> interrupt);
|
||||
bool enqueueDmaPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue, const QueueState& state);
|
||||
@@ -342,7 +345,7 @@ private:
|
||||
bool validateCaptured(std::uint64_t program, std::uint32_t queue, std::span<const ShaderRecompiler::MemoryRegion> captured, const ShaderRecompiler::RecompileResult& compiled, bool inPlace, const PendingView& view, bool* unmapped = nullptr, std::optional<SampledReadScope>* sampling = nullptr, const DataMask* data = nullptr, std::span<const VouchedRegions> vouched = {});
|
||||
static void appendEntryRegions(const DispatchVariant& variant, std::vector<ShaderRecompiler::MemoryRegion>& regions, const std::vector<std::uint32_t>* words = nullptr);
|
||||
static std::shared_ptr<const ShaderRecompiler::RecompileResult> patchDataWords(const DispatchVariant& variant, const std::vector<std::uint32_t>& words);
|
||||
bool syncPendingRuns(std::uint64_t program, std::uint32_t queue, const ShaderRecompiler::RecompileResult& compiled, std::span<const ShaderRecompiler::MemoryRegion> regions, std::uint64_t& synced, PendingView& pending, std::optional<SampledReadScope>& sampling, std::span<const VouchedRegions> skipped = {});
|
||||
bool syncPendingRuns(std::uint64_t program, std::uint32_t queue, const ShaderRecompiler::RecompileResult& compiled, std::span<const ShaderRecompiler::MemoryRegion> regions, std::uint64_t& synced, PendingView& pending, std::optional<SampledReadScope>& sampling, std::span<const VouchedRegions> skipped = {}, const PreparedShaderState::UserDataLink* linking = nullptr);
|
||||
EntryOutcome validateVariant(std::uint64_t program, std::uint32_t queue, const DispatchVariant& variant, std::span<const ShaderRecompiler::MemoryRegion> regions, std::uint64_t& imagesFlushed, std::uint64_t& runsSynced, std::optional<SampledReadScope>& sampling, std::vector<std::pair<std::uint32_t, std::uint32_t>>* live = nullptr);
|
||||
static int waitTimeoutMs();
|
||||
static bool pollReapAll();
|
||||
@@ -365,6 +368,7 @@ private:
|
||||
std::shared_ptr<DispatchVariant> keepVariant, attachVariant;
|
||||
std::shared_ptr<DispatchEntry> missedEntry;
|
||||
std::shared_ptr<ShaderMemory> shaderMemory;
|
||||
std::shared_ptr<const PreparedShaderState::UserDataLink> linking;
|
||||
std::vector<ShaderRecompiler::MemoryRegion> captured;
|
||||
std::vector<std::uint32_t> liveWords;
|
||||
std::shared_ptr<const ShaderRecompiler::ResourceCapture> capture;
|
||||
@@ -405,7 +409,8 @@ private:
|
||||
void recordQueuedLabelsBeforeRead(std::uint32_t queue);
|
||||
bool recordQueuedLabelsAfterCapture(std::uint32_t queue, std::span<const ShaderRecompiler::MemoryRegion> regions);
|
||||
static void runCaptureCheckHook();
|
||||
static bool capturedMemoryChanged(std::span<const ShaderRecompiler::MemoryRegion> regions, std::span<Graphics::GuestMemorySnapshot> compared = {});
|
||||
static bool capturedCurrent(std::span<const ShaderRecompiler::MemoryRegion> captured, const ShaderSnapshot& code, const PreparedShaderState::UserDataLink* linking);
|
||||
static bool capturedMemoryChanged(std::span<const ShaderRecompiler::MemoryRegion> regions, std::span<Graphics::GuestMemorySnapshot> compared = {}, const PreparedShaderState::UserDataLink* linking = nullptr);
|
||||
void noteQueuedLabels(std::uint32_t queue);
|
||||
void recordQueuedLabelsByTry(std::uint32_t queue, std::atomic<std::uint64_t>& counter);
|
||||
static void recordQueuedLabelsFromHook();
|
||||
@@ -530,6 +535,7 @@ private:
|
||||
std::atomic<std::uint64_t> idleEpoch{0};
|
||||
std::atomic<std::uint64_t> queue0Awaited{0};
|
||||
std::atomic<std::uint32_t> flipsAhead{0};
|
||||
std::map<std::uint32_t, std::uint32_t> flipsReadying;
|
||||
std::atomic<std::uint32_t> flipHolders{0};
|
||||
std::shared_ptr<FlipWork> lastFlipWork;
|
||||
std::atomic<bool> queue0AwaitsTitle{false};
|
||||
|
||||
@@ -34,6 +34,7 @@ struct Submission {
|
||||
|
||||
std::shared_ptr<const ShaderRegistry> shaders;
|
||||
std::map<std::size_t, std::shared_ptr<IFlipRequest>> flips;
|
||||
std::map<std::size_t, std::uint32_t> flipHandles;
|
||||
std::map<std::size_t, std::shared_ptr<IRenderingWait>> renderingWaits;
|
||||
std::map<std::size_t, std::size_t> conditionalEnds;
|
||||
std::map<std::size_t, std::vector<std::uint32_t>> registerLists;
|
||||
|
||||
@@ -158,6 +158,13 @@ struct PreparedShaderState {
|
||||
std::vector<std::uint64_t> callees;
|
||||
std::vector<std::vector<std::uint32_t>> code;
|
||||
std::shared_ptr<const ShaderRecompiler::LinkedCalls> linked;
|
||||
std::vector<std::uint32_t> tableUserData;
|
||||
std::vector<std::shared_ptr<const ShaderRecompiler::SrtGuestWords>> dependencies;
|
||||
|
||||
void AppendRegions(std::vector<ShaderRecompiler::MemoryRegion>& regions) const;
|
||||
void VouchRegions(std::span<const ShaderRecompiler::MemoryRegion> regions, std::vector<VouchedRegions>& vouched) const;
|
||||
static bool Restamp(const ShaderRecompiler::SrtGuestWords& block, ShaderMemory::PendingWriteQuery pending);
|
||||
bool Overlaps(std::uint64_t address, std::size_t bytes) const;
|
||||
};
|
||||
std::vector<Entry> entries;
|
||||
std::vector<UserDataLink> userDataLinks;
|
||||
@@ -325,6 +332,8 @@ std::uint64_t DepthCopyPixelProgramAddress(bool multisampled);
|
||||
std::uint32_t DepthCopyPixelUserWords(bool multisampled);
|
||||
ShaderSnapshot PrepareDepthCopyPixelProgram(bool multisampled);
|
||||
bool DriverOwnedProgram(std::uint64_t codeAddress);
|
||||
std::uint64_t StencilCopyPixelProgramAddress(bool multisampled);
|
||||
ShaderSnapshot PrepareStencilCopyPixelProgram(bool multisampled);
|
||||
std::optional<ShaderRecompiler::ShaderFloatMode> RegisteredFloatMode(const ShaderSnapshot& snapshot);
|
||||
std::optional<ShaderRecompiler::ShaderFloatMode> DispatchFloatMode(const ShaderSnapshot& snapshot, const Registers& live);
|
||||
std::shared_ptr<const ShaderSnapshot> RegisteredHeader(const ShaderRegistry& registry, const Shader* shader);
|
||||
@@ -349,8 +358,23 @@ ShaderRecompiler::RectListShaders PreparedRectangle(const ShaderSnapshot& snapsh
|
||||
ShaderRecompiler::RectListShaders DrawRectangle(const ShaderSnapshot& front, const std::shared_ptr<const ShaderSnapshot>& fragment, std::uint64_t vertexId, std::uint64_t fragmentId, const ShaderRecompiler::SpirvTarget& target);
|
||||
|
||||
std::shared_ptr<const ShaderRecompiler::SourceHandle> SourceHandleFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request);
|
||||
ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request);
|
||||
std::shared_ptr<const ShaderRecompiler::ResourceCapture> CaptureInvocation(ShaderMemory& memory, const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, ShaderRecompiler::PreparedShaderInvocation& invocation);
|
||||
struct OwnedRecompileRequest {
|
||||
ShaderRecompiler::RecompileRequest request;
|
||||
std::vector<std::uint32_t> code;
|
||||
std::vector<std::byte> header;
|
||||
std::vector<std::uint32_t> userData;
|
||||
std::vector<std::uint32_t> fallbacks;
|
||||
std::vector<std::vector<std::byte>> regionBytes;
|
||||
std::vector<ShaderRecompiler::MemoryRegion> regions;
|
||||
std::vector<std::vector<std::uint32_t>> linkedWords;
|
||||
std::vector<std::vector<std::byte>> linkedHeaders;
|
||||
std::vector<ShaderRecompiler::LinkedProgram> linked;
|
||||
};
|
||||
|
||||
std::shared_ptr<OwnedRecompileRequest> OwnRecompileRequest(const ShaderRecompiler::RecompileRequest& source, ShaderRecompiler::MemoryRegionView memory);
|
||||
ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, bool deferPreparation = false, std::shared_ptr<const PreparedShaderState::UserDataLink>* linking = nullptr);
|
||||
std::shared_ptr<const ShaderRecompiler::RecompileResult> MaterializeInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr<const ShaderRecompiler::ResourceCapture>& capture, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address);
|
||||
std::shared_ptr<const ShaderRecompiler::ResourceCapture> CaptureInvocation(ShaderMemory& memory, const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, ShaderRecompiler::PreparedShaderInvocation& invocation, std::shared_ptr<const PreparedShaderState::UserDataLink>* linking = nullptr);
|
||||
bool StageLinksUserDataCallees(const ShaderSnapshot& snapshot, std::size_t codeOffset);
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_FLOAT16NANPROBE_HPP
|
||||
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_FLOAT16NANPROBE_HPP
|
||||
|
||||
#include "Recompiler.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace AgcDriver {
|
||||
|
||||
class VulkanDevice;
|
||||
|
||||
struct Float16NanProbeResult {
|
||||
std::uint32_t mismatches = 0;
|
||||
std::uint32_t compared = 0;
|
||||
};
|
||||
|
||||
Float16NanProbeResult ProbeFloat16HostNans(VulkanDevice& device, const ShaderRecompiler::SpirvTarget& target);
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -6,6 +6,7 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/VideoOutput.hpp"
|
||||
#include "SceShaders.hpp"
|
||||
#include "SceTypes.hpp"
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
@@ -44,6 +45,7 @@ public:
|
||||
void PresentBuffer(const DisplayBuffer& buffer);
|
||||
void FrameBoundary();
|
||||
void RewindTailFlips(std::uint64_t flips);
|
||||
static void SetStartIdleWaitForTest(std::function<bool()> wait);
|
||||
|
||||
private:
|
||||
enum class State { Waiting, Recording, Done };
|
||||
@@ -112,6 +114,8 @@ private:
|
||||
std::uint64_t snapshotBytes = 0;
|
||||
std::uint64_t recordedCalls = 0;
|
||||
std::uint64_t startAttempts = 0;
|
||||
std::atomic<std::uint64_t> unrecordedAccepts{0};
|
||||
inline static std::function<bool()> startIdleWaitForTest;
|
||||
std::uint64_t unreadableBytes = 0;
|
||||
std::uint64_t hostOnlySampleBytes = 0;
|
||||
std::uint64_t allocationsGeneration = 0;
|
||||
|
||||
@@ -46,6 +46,7 @@ bool EqualsCommittedUnsynced(std::uint64_t address, std::span<const std::byte> b
|
||||
// space cannot be queried).
|
||||
enum class Compare : std::uint8_t { Equal, Differs, Unmapped };
|
||||
Compare CompareMapped(std::uint64_t address, std::span<const std::byte> bytes);
|
||||
void SetCompareMappedHook(void (*hook)(std::uint64_t address, std::size_t bytes));
|
||||
Compare CopyMapped(std::uint64_t address, std::span<std::byte> out);
|
||||
void WriteChangedCommitted(std::uint64_t address, std::span<const std::byte> current, std::span<const std::byte> original);
|
||||
void Write(std::uint64_t address, std::span<const std::byte> source, std::size_t alignment = 1);
|
||||
@@ -134,9 +135,17 @@ bool StoredAllSince_nid_no_patch(std::uint64_t address, std::size_t bytes, std::
|
||||
// submission runs. The driver's own writes (Write, WriteChanged, MarkWritten) stamp their blocks, so
|
||||
// they are never hidden. APS5_NO_COLLECT_MEMO=1 disables the memo. CollectWritesUncached always walks:
|
||||
// for decisions about which blocks the CPU wrote while a GPU result was pending (a stale answer there
|
||||
// stores old texels over reused memory).
|
||||
// stores old texels over reused memory). The collect that starts such a pending period
|
||||
// (StorageTexture::markLayersPending) may be memoized: its caller reads TrackerGeneration after it,
|
||||
// so a store the memoized walk missed is stamped above that generation by a later walk (at the
|
||||
// latest the decision's own uncached one) and counts as made while the result was pending, while a
|
||||
// store ordered before the draw was made before the epoch's ordering point, so the memoized walk,
|
||||
// which started after that point, stamped it. APS5_NO_MEMO_PENDING_COLLECT walks there again.
|
||||
// The epoch is per queue worker: BumpCollectEpoch advances the calling thread's epoch to a value no
|
||||
// other thread ever holds (one worker's walk never satisfies another's check) at the hardware
|
||||
// other thread ever holds. Each 64 KiB block records the counter value read before its last complete
|
||||
// walk, and a request of epoch e is answered by any walk of the block made at or after e, by
|
||||
// whichever thread: such a walk started after the bump that produced e. A mapping or unwatch change
|
||||
// invalidates every recorded walk. The calling thread's epoch advances at the hardware
|
||||
// ordering points of its queue: the start of a submission, a WAIT_REG_MEM the CPU may have satisfied
|
||||
// (at entry, polled, timed out, or by another queue's recorded label; a label this queue recorded
|
||||
// itself orders no CPU write), a device drain, and before reaping completions outside a submission.
|
||||
@@ -153,6 +162,13 @@ std::uint64_t CollectEpochBumps();
|
||||
std::uint64_t ThreadCollectEpoch();
|
||||
std::uint64_t UnwatchSerial();
|
||||
std::uint64_t CollectWritesUncached(std::uint64_t address, std::size_t bytes);
|
||||
struct Observation {
|
||||
enum class Status { Complete, Refused, Uncovered, Failed };
|
||||
Status status = Status::Failed;
|
||||
std::uint64_t generation = 0;
|
||||
};
|
||||
Observation Observe(std::uint64_t address, std::size_t bytes);
|
||||
void SetObservationHookForTest(void (*hook)(int point));
|
||||
// The tracker's current generation (every collect and MarkWritten bumps it): a stamp taken after
|
||||
// a set of driver stores, for UnchangedSinceCollected to compare against later. Read under the
|
||||
// tracker mutex, so every collect that bumped before it has finished its walk and every later
|
||||
@@ -196,18 +212,22 @@ public:
|
||||
// current acquisition is the outermost, so code that releases the mutex around a wait
|
||||
// (Recorder::SyncThrough for the flush hook) gives up no caller's hold.
|
||||
std::uint32_t DepthOnThisThread() const;
|
||||
std::uint32_t Waiters() const { return waiters.load(std::memory_order_relaxed); }
|
||||
|
||||
private:
|
||||
void enter();
|
||||
void block();
|
||||
bool tryEnter();
|
||||
void acquired();
|
||||
Mutex mutex;
|
||||
std::atomic<std::uint32_t> waiters{0};
|
||||
// The holder's thread token and recursion depth, written by the holder only; another thread
|
||||
// reads the owner just to see that it is not itself.
|
||||
std::atomic<const void*> owner{nullptr};
|
||||
std::uint32_t depth = 0;
|
||||
};
|
||||
GpuMutexType& GpuMutex();
|
||||
std::function<bool()> YieldToGpuMutexWaiters(std::function<bool()> stop);
|
||||
// Called on the thread that just gave up its outermost hold, right after the mutex was released:
|
||||
// work the hold deferred to run without it (the recorder's release of the objects completed batches
|
||||
// kept). One hook, set once; it must not take GpuMutex itself.
|
||||
@@ -292,8 +312,9 @@ PacketTag CurrentPacket();
|
||||
// DrawCache: a draw entry's per-stage value validation (Driver.cpp drawCache), where a draw
|
||||
// capture's hook waits reappear on a hit.
|
||||
// Every enumerator needs its name in ReadSiteName's table (GuestMemory.cpp).
|
||||
enum class ReadSite : std::uint8_t { Unknown = 0, Capture, DispatchCache, TextureCompare, TextureRead, BufferUpload, IndexBuffer, VertexBuffer, Registers, IndirectArguments, Wait, Label, Scanout, Store, MirrorRefresh, DrawCache, Count };
|
||||
enum class ReadSite : std::uint8_t { Unknown = 0, Capture, DispatchCache, TextureCompare, TextureRead, BufferUpload, IndexBuffer, VertexBuffer, Registers, IndirectArguments, Wait, Label, Scanout, Store, MirrorRefresh, DrawCache, HostWrite, Count };
|
||||
const char* ReadSiteName(ReadSite site);
|
||||
bool WritesGuestMemory(ReadSite site);
|
||||
// Sets the calling thread's read site and returns the previous one (nested scopes restore it).
|
||||
ReadSite SetReadSite(ReadSite site);
|
||||
ReadSite CurrentReadSite();
|
||||
|
||||
@@ -264,6 +264,7 @@ std::int32_t OverlayScale(VkExtent2D extent, const OverlayContent& content, std:
|
||||
std::int32_t OverlayScaleRequest(const char* value);
|
||||
OverlayLayout LayOutOverlay(const OverlayContent& content, VkExtent2D extent, OverlayCorner corner);
|
||||
std::array<std::array<float, 4>, OverlayColorCount> OverlayPalette(VkFormat format, VkColorSpaceKHR colorSpace);
|
||||
std::array<std::array<float, 4>, OverlayColorCount> ColorblindOverlayPalette(std::array<std::array<float, 4>, OverlayColorCount> palette);
|
||||
|
||||
class PerformanceOverlay {
|
||||
public:
|
||||
|
||||
@@ -105,6 +105,7 @@ bool UsesGpuCacheBarrier(std::span<const std::uint32_t> packet);
|
||||
bool IsTagMarker(std::span<const std::uint32_t> packet);
|
||||
inline bool Predicated(std::uint32_t header) { return !FillerPacket(header) && (header & 1u) != 0; }
|
||||
bool PredicationPasses(const QueueState& queue);
|
||||
std::size_t PredicationBytes(const Predication& predication);
|
||||
bool WaitSatisfied(std::span<const std::uint32_t> packet);
|
||||
// WaitSatisfied for a polling loop: the caller has validated the address once, so the value is read
|
||||
// directly instead of through the checked guest memory path.
|
||||
|
||||
@@ -220,9 +220,9 @@ private:
|
||||
inline Registers BuildInitialContextRegisters() {
|
||||
Registers result{
|
||||
{0x200, 0}, {0x201, 0}, {0x202, 0xcc0010}, {0x203, 0},
|
||||
{0x204, 0}, {0x205, 0}, {0x206, 1087}, {0x207, 0},
|
||||
{0x204, 0}, {0x205, 0}, {0x206, 0}, {0x207, 0},
|
||||
{0x0, 0}, {0x2, 0}, {0x3, 0}, {0x4, 0}, {0x8, 0}, {0x9, 0x3f800000}, {0xa, 0}, {0xb, 0}, {0x10, 0}, {0x11, 0},
|
||||
{0x80, 0}, {0x83, 0xffff}, {0x8c, 0xaa99aaaa}, {0x8d, 0}, {0x8e, 0}, {0x8f, 0},
|
||||
{0x80, 0}, {0x83, 0xffff}, {0x8c, 0xaa99aaaa}, {0x8d, 0}, {0x8e, 0xffffffffu}, {0x8f, 0xffffffffu},
|
||||
{0xc, 0}, {0xd, 0x40004000}, {0x81, 0x80000000}, {0x82, 0x40004000},
|
||||
{0x90, 0x80000000}, {0x91, 0x40004000},
|
||||
{0x105, 0}, {0x106, 0}, {0x107, 0}, {0x108, 0},
|
||||
@@ -282,6 +282,7 @@ struct Predication {
|
||||
std::uint64_t address = 0;
|
||||
std::uint32_t operation = 0;
|
||||
bool executeWhenSet = false;
|
||||
bool runWhenUnwritten = false;
|
||||
};
|
||||
|
||||
struct QueueState {
|
||||
|
||||
@@ -61,6 +61,9 @@ public:
|
||||
static void SetWaitedMsProvider(WaitedMsProvider provider);
|
||||
explicit ShaderMemory(std::span<const ShaderRecompiler::MemoryRegion> initial, PendingWriteQuery pendingWrite = nullptr, PendingWriteObserver observe = nullptr, HookWaitCounter hookWaits = nullptr, PendingWriteQuery pendingSpan = nullptr);
|
||||
~ShaderMemory();
|
||||
static constexpr std::size_t KeepBytes = 256;
|
||||
bool KeepTable(std::uint64_t address);
|
||||
static std::uint64_t TablesKept();
|
||||
ShaderMemory(const ShaderMemory&) = delete;
|
||||
ShaderMemory& operator=(const ShaderMemory&) = delete;
|
||||
// Returns what the capture resolved (plan, snapshot, specialization) for
|
||||
@@ -87,7 +90,7 @@ public:
|
||||
std::uint64_t calls, blocks, refused, words;
|
||||
};
|
||||
static VouchCounts Vouches();
|
||||
static bool Vouched(PendingWriteQuery pending, std::uint64_t address, std::uint64_t bytes, const ShaderRecompiler::SrtWriteStamp& stamp);
|
||||
static bool Vouched(PendingWriteQuery pending, std::uint64_t address, std::uint64_t bytes, const ShaderRecompiler::SrtWriteStamp& stamp, bool uncached = false);
|
||||
static std::uint64_t descriptorScope(void* context, std::size_t bytes);
|
||||
|
||||
private:
|
||||
@@ -128,6 +131,7 @@ private:
|
||||
WordMask raw;
|
||||
WordMask read;
|
||||
WordMask recent;
|
||||
WordMask kept;
|
||||
bool wordwise = false;
|
||||
bool lazy = false;
|
||||
std::uint64_t backing = 0;
|
||||
@@ -150,6 +154,7 @@ private:
|
||||
bool invalidateRawPages();
|
||||
bool pagesCurrent();
|
||||
static bool snapshotCurrent(void* context, std::span<const ShaderRecompiler::RegisteredImageView> views);
|
||||
bool invalidateChangedRawPages();
|
||||
Page& page(std::uint64_t base);
|
||||
void preparePage(Page& page, std::uint64_t base);
|
||||
[[nodiscard]] std::size_t pageAtOrAfter(std::uint64_t base) const;
|
||||
@@ -164,6 +169,7 @@ private:
|
||||
// the caller keeps them alive for as long as the capture is used.
|
||||
std::vector<std::pair<std::uint64_t, std::span<const std::byte>>> initial;
|
||||
std::vector<std::pair<std::uint64_t, Page*>> pages;
|
||||
std::vector<std::pair<std::uint64_t, std::uint64_t>> keptRanges;
|
||||
std::uint64_t lastBase = ~std::uint64_t{0};
|
||||
Page* lastPage = nullptr;
|
||||
std::vector<Supplied> supplied;
|
||||
@@ -212,7 +218,7 @@ struct VouchedRegions {
|
||||
std::uint64_t low = 0;
|
||||
std::uint64_t high = 0;
|
||||
};
|
||||
std::size_t VouchSharedRegions(std::span<const SharedWords> shared, std::size_t regions, ShaderMemory::PendingWriteQuery pending, std::vector<VouchedRegions>& vouched);
|
||||
std::size_t VouchSharedRegions(std::span<const SharedWords> shared, std::size_t regions, ShaderMemory::PendingWriteQuery pending, std::vector<VouchedRegions>& vouched, std::span<const std::shared_ptr<const ShaderRecompiler::SrtGuestWords>> restampable = {}, bool (*restamp)(const ShaderRecompiler::SrtGuestWords&, ShaderMemory::PendingWriteQuery) = nullptr);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#include "prx/libc/include/HostThreadSlot.hpp"
|
||||
#include "ThreadOwned.hpp"
|
||||
#include <memory>
|
||||
|
||||
namespace AgcDriver {
|
||||
|
||||
@@ -16,6 +17,47 @@ T& ThreadScratch() {
|
||||
return *object;
|
||||
}
|
||||
|
||||
template<typename T, typename Tag>
|
||||
class ExclusiveScratch {
|
||||
public:
|
||||
ExclusiveScratch() {
|
||||
auto& slot = Slot();
|
||||
if (slot.busy) {
|
||||
owned = std::make_unique<Held>();
|
||||
held = owned.get();
|
||||
} else {
|
||||
held = &slot;
|
||||
}
|
||||
held->busy = true;
|
||||
}
|
||||
|
||||
~ExclusiveScratch() {
|
||||
held->value.clear();
|
||||
held->busy = false;
|
||||
}
|
||||
|
||||
ExclusiveScratch(const ExclusiveScratch&) = delete;
|
||||
ExclusiveScratch& operator=(const ExclusiveScratch&) = delete;
|
||||
|
||||
T* operator->() const { return &held->value; }
|
||||
T& operator*() const { return held->value; }
|
||||
bool Nested() const { return owned != nullptr; }
|
||||
|
||||
static bool Busy() { return Slot().busy; }
|
||||
static const T& Resting() { return Slot().value; }
|
||||
|
||||
private:
|
||||
struct Held {
|
||||
T value;
|
||||
bool busy = false;
|
||||
};
|
||||
|
||||
static Held& Slot() { return ThreadScratch<Held, Tag>(); }
|
||||
|
||||
std::unique_ptr<Held> owned;
|
||||
Held* held = nullptr;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -85,6 +85,7 @@ public:
|
||||
VulkanDevice& operator=(const VulkanDevice&) = delete;
|
||||
std::string DeviceName() const;
|
||||
std::string DriverInfo() const;
|
||||
VkDriverId DriverId() const;
|
||||
bool SupportsImageFormat(VkFormat format, VkImageUsageFlags usage) const;
|
||||
bool BdaAtomicsUsable() const;
|
||||
bool RasterOrderGroupUsable() const;
|
||||
@@ -364,7 +365,8 @@ public:
|
||||
static std::uint64_t DrawRecipeHits();
|
||||
// `recipe`, when given, receives the DrawRecipe a recorded, cacheable, reusable, direct draw
|
||||
// built for its draw-cache entry (design_cpu_final M8); null otherwise.
|
||||
void Draw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders, std::span<const Graphics::GuestMemorySnapshot> snapshots = {}, std::shared_ptr<const DrawRecipe>* recipe = nullptr, const DrawTraceContext* trace = nullptr, std::uint64_t shape = 0);
|
||||
void Draw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders, std::span<const Graphics::GuestMemorySnapshot> snapshots = {}, std::shared_ptr<const DrawRecipe>* recipe = nullptr, const DrawTraceContext* trace = nullptr, std::uint64_t shape = 0, const std::vector<std::uint32_t>* contentKey = nullptr);
|
||||
std::vector<std::uint32_t> DrawContentKey(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders) const;
|
||||
bool DrawInputsInPlace() const;
|
||||
std::optional<std::string> KnownDrawRejection(const Graphics::State& graphics, std::span<const Graphics::CompiledShader> shaders) const;
|
||||
void ColorMetadataPass(const Graphics::ColorMetadataPass& pass);
|
||||
|
||||
@@ -13,13 +13,17 @@ namespace AgcDriver::GuestMemory {
|
||||
|
||||
class WriteWatchCoverage {
|
||||
public:
|
||||
void Initialize(std::uint64_t address, std::size_t bytes) {
|
||||
void Initialize(std::uint64_t address, std::size_t bytes, bool summarize = true) {
|
||||
base = address;
|
||||
size = bytes;
|
||||
excluded.assign(bytes / BlockBytes + (bytes % BlockBytes != 0), 0);
|
||||
excludedGenerations.clear();
|
||||
summary.clear();
|
||||
if (summarize) summary.assign((excluded.size() + BlocksPerWord - 1) / BlocksPerWord, 0);
|
||||
}
|
||||
|
||||
bool Summarized() const { return !summary.empty(); }
|
||||
|
||||
bool Covers(std::uint64_t address, std::size_t bytes) const {
|
||||
if (bytes == 0 || bytes > size || address < base || address - base > size - bytes) return false;
|
||||
const auto first = (address - base) / BlockBytes;
|
||||
@@ -28,6 +32,7 @@ public:
|
||||
const auto lastPage = (address - base + bytes - 1) % BlockBytes / PageBytes;
|
||||
if (first == last) return (excluded[first] & pageMask(firstPage, lastPage + 1)) == 0;
|
||||
if ((excluded[first] & pageMask(firstPage, PagesPerBlock)) != 0 || (excluded[last] & pageMask(0, lastPage + 1)) != 0) return false;
|
||||
if (!summary.empty()) return noneExcluded(first + 1, last);
|
||||
return std::none_of(excluded.begin() + first + 1, excluded.begin() + last, [](auto mask) { return mask != 0; });
|
||||
}
|
||||
|
||||
@@ -55,6 +60,7 @@ public:
|
||||
auto& stamps = excludedGenerations[block];
|
||||
for (auto page = from; page < to; ++page) stamps[page] = std::max(stamps[page], std::max<std::uint64_t>(generation, 1));
|
||||
excluded[block] |= mask;
|
||||
updateSummary(block);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
@@ -88,6 +94,7 @@ public:
|
||||
changed = true;
|
||||
}
|
||||
if (excluded[block] == 0) excludedGenerations.erase(block);
|
||||
updateSummary(block);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
@@ -96,6 +103,22 @@ private:
|
||||
static std::uint16_t pageMask(std::size_t first, std::size_t end) {
|
||||
return static_cast<std::uint16_t>(((1u << end) - 1u) & ~((1u << first) - 1u));
|
||||
}
|
||||
void updateSummary(std::size_t block) {
|
||||
if (summary.empty()) return;
|
||||
const auto bit = std::uint64_t{1} << (block % BlocksPerWord);
|
||||
if (excluded[block] != 0) summary[block / BlocksPerWord] |= bit;
|
||||
else summary[block / BlocksPerWord] &= ~bit;
|
||||
}
|
||||
bool noneExcluded(std::size_t from, std::size_t to) const {
|
||||
if (from >= to) return true;
|
||||
const auto firstWord = from / BlocksPerWord;
|
||||
const auto lastWord = (to - 1) / BlocksPerWord;
|
||||
const auto lowMask = ~std::uint64_t{0} << (from % BlocksPerWord);
|
||||
const auto highMask = ~std::uint64_t{0} >> (BlocksPerWord - 1 - (to - 1) % BlocksPerWord);
|
||||
if (firstWord == lastWord) return (summary[firstWord] & lowMask & highMask) == 0;
|
||||
if ((summary[firstWord] & lowMask) != 0 || (summary[lastWord] & highMask) != 0) return false;
|
||||
return std::none_of(summary.begin() + firstWord + 1, summary.begin() + lastWord, [](auto word) { return word != 0; });
|
||||
}
|
||||
bool excludedBlocks(std::uint64_t address, std::size_t bytes, std::size_t& first, std::size_t& last) const {
|
||||
if (bytes == 0 || size == 0) return false;
|
||||
if (address < base) {
|
||||
@@ -113,9 +136,11 @@ private:
|
||||
static constexpr std::size_t BlockBytes = 65536;
|
||||
static constexpr std::size_t PageBytes = 4096;
|
||||
static constexpr std::size_t PagesPerBlock = BlockBytes / PageBytes;
|
||||
static constexpr std::size_t BlocksPerWord = 64;
|
||||
std::uint64_t base = 0;
|
||||
std::size_t size = 0;
|
||||
std::vector<std::uint16_t> excluded;
|
||||
std::vector<std::uint64_t> summary;
|
||||
std::unordered_map<std::uint64_t, std::array<std::uint64_t, PagesPerBlock>> excludedGenerations;
|
||||
};
|
||||
|
||||
|
||||
@@ -138,7 +138,8 @@ void ComputePipelineCapture::Validate() const {
|
||||
RequireCapture(mainEntry, "compute main entry point missing");
|
||||
RequireCapture(deviceName.size() < VK_MAX_PHYSICAL_DEVICE_NAME_SIZE && deviceName.find('\0') == std::string::npos, "invalid device name");
|
||||
RequireCapture((flags & ~(VK_PIPELINE_CREATE_DISPATCH_BASE_BIT | VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR)) == 0, "unsupported pipeline flags");
|
||||
RequireCapture(stageFlags == 0 || (stageFlags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT && requiredSubgroupSize != 0), "unsupported shader stage flags");
|
||||
constexpr VkPipelineShaderStageCreateFlags anySize = VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT | VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT;
|
||||
RequireCapture(stageFlags == 0 || (stageFlags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT && requiredSubgroupSize != 0) || (stageFlags == anySize && requiredSubgroupSize == 0), "unsupported shader stage flags");
|
||||
RequireCapture(requiredSubgroupSize == 0 || (requiredSubgroupSize <= 128 && (requiredSubgroupSize & (requiredSubgroupSize - 1u)) == 0), "invalid required subgroup size");
|
||||
RequireCapture(sets.size() <= 8, "too many descriptor sets");
|
||||
std::size_t totalBindings = 0;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
@@ -95,6 +96,14 @@ bool SkipRefusedDraws() {
|
||||
return skip;
|
||||
}
|
||||
|
||||
bool AsyncDrawCompile() {
|
||||
static const bool enabled = [] {
|
||||
const char* text = std::getenv("APS5_ASYNC_DRAW_COMPILE");
|
||||
return text != nullptr && std::strcmp(text, "0") != 0;
|
||||
}();
|
||||
return enabled;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct RefusedShaders {
|
||||
|
||||
@@ -13,15 +13,14 @@ void Driver::verifyDataHit(const ShaderSnapshot& snapshot, std::size_t codeOffse
|
||||
std::abort();
|
||||
};
|
||||
auto verifyMemory = std::make_shared<ShaderMemory>(memory, &queryPendingWrite, &observePendingWrite, hookWaitCounter(), &QueryPendingSpan);
|
||||
auto invocation = InvocationFor(snapshot, codeOffset, request);
|
||||
const auto capture = CaptureInvocation(*verifyMemory, snapshot, codeOffset, request, invocation);
|
||||
std::shared_ptr<const PreparedShaderState::UserDataLink> linking;
|
||||
auto invocation = InvocationFor(snapshot, codeOffset, request, false, &linking);
|
||||
const auto capture = CaptureInvocation(*verifyMemory, snapshot, codeOffset, request, invocation, &linking);
|
||||
const auto regions = verifyMemory->Regions();
|
||||
request.context.memory = regions;
|
||||
const auto result = invocation.Materialize(*capture);
|
||||
std::size_t position = 0, run = 0;
|
||||
for (const auto& region : regions) {
|
||||
const bool registered = std::any_of(memory.begin(), memory.end(), [&](const auto& known) { return region.guestAddress >= known.guestAddress && region.guestAddress < known.guestAddress + known.bytes.size(); });
|
||||
if (registered) continue;
|
||||
for (const auto& region : dispatchRegions(memory, regions, linking.get())) {
|
||||
if (run >= variant.runs.size() || variant.runs[run].first != region.guestAddress || variant.runs[run].second != region.guestAddress + region.bytes.size()) fail("the read set", position, run);
|
||||
const auto count = region.bytes.size() / sizeof(std::uint32_t);
|
||||
if (position + count > liveWords.size() || std::memcmp(region.bytes.data(), liveWords.data() + position, region.bytes.size()) != 0) fail("the captured bytes", position, run);
|
||||
|
||||
@@ -67,21 +67,32 @@ void ReportDispatchItems(bool profile) {
|
||||
std::fprintf(stderr, "[dispatch-item] %llu commit items (%llu recipes rebuilt on the committer, %llu queued after a cache miss, %llu queued without a recipe, %llu cached ones kept off the queue as not plain); drained instead, cumulative:%s\n", static_cast<unsigned long long>(itemCommits.load(std::memory_order_relaxed)), static_cast<unsigned long long>(itemRebuilds.load(std::memory_order_relaxed)), static_cast<unsigned long long>(itemMisses.load(std::memory_order_relaxed)), static_cast<unsigned long long>(itemRecipeLess.load(std::memory_order_relaxed)), static_cast<unsigned long long>(itemNotPlain.load(std::memory_order_relaxed)), drained.c_str());
|
||||
}
|
||||
|
||||
bool CapturedCurrent(std::span<const ShaderRecompiler::MemoryRegion> captured, const ShaderSnapshot& code) {
|
||||
}
|
||||
|
||||
bool Driver::capturedCurrent(std::span<const ShaderRecompiler::MemoryRegion> captured, const ShaderSnapshot& code, const PreparedShaderState::UserDataLink* linking) {
|
||||
const auto registered = [&](const ShaderRecompiler::MemoryRegion& region) {
|
||||
const auto address = region.guestAddress;
|
||||
return ((address >= code.codeAddress && address < code.codeAddress + code.code.size() * sizeof(std::uint32_t)) || (!code.header.empty() && address >= code.headerAddress && address < code.headerAddress + code.header.size())) && (linking == nullptr || !linking->Overlaps(address, region.bytes.size()));
|
||||
};
|
||||
for (const auto& region : captured) {
|
||||
const auto address = region.guestAddress;
|
||||
const auto bytes = region.bytes.size();
|
||||
if (bytes == 0 || (address >= code.codeAddress && address < code.codeAddress + code.code.size() * sizeof(std::uint32_t)) || (!code.header.empty() && address >= code.headerAddress && address < code.headerAddress + code.header.size())) continue;
|
||||
if (bytes == 0) continue;
|
||||
if (registered(region)) continue;
|
||||
if (Driver::QueryPendingSpan(address, bytes, {}) != ShaderMemory::PendingWrite::None || !GuestMemory::Accessible(reinterpret_cast<const void*>(address), bytes)) return false;
|
||||
GuestMemory::GuardRead(address, bytes);
|
||||
GuestMemory::FlushGpuWrites(address, bytes);
|
||||
if (std::memcmp(region.bytes.data(), reinterpret_cast<const void*>(address), bytes) != 0) return false;
|
||||
}
|
||||
std::vector<VouchedRegions> vouched;
|
||||
if (linking != nullptr && vouchedValidation() && !validateLegacy()) linking->VouchRegions(captured, vouched);
|
||||
for (std::size_t index = 0, range = 0; index < captured.size(); ++index) {
|
||||
while (range < vouched.size() && index >= vouched[range].end) ++range;
|
||||
if ((range < vouched.size() && index >= vouched[range].begin) || registered(captured[index])) continue;
|
||||
if (GuestMemory::CompareMapped(captured[index].guestAddress, captured[index].bytes) != GuestMemory::Compare::Equal) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
bool Driver::pipelineDispatch() {
|
||||
return DispatchItemsEnabled();
|
||||
}
|
||||
@@ -265,6 +276,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
|
||||
std::shared_ptr<DispatchVariant> attachVariant;
|
||||
|
||||
std::shared_ptr<ShaderMemory> shaderMemory;
|
||||
std::shared_ptr<const PreparedShaderState::UserDataLink> linking;
|
||||
std::vector<ShaderRecompiler::MemoryRegion> captured;
|
||||
|
||||
std::vector<std::uint32_t> liveWords;
|
||||
@@ -316,7 +328,8 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
|
||||
if (fromAhead) {
|
||||
if (const auto hook = aheadAdoptHook.load(std::memory_order_acquire)) hook();
|
||||
const auto* aheadViews = ahead.capture != nullptr ? &ahead.capture->snapshot.registeredImages : ahead.keepVariant != nullptr && ahead.keepVariant->registeredViews != nullptr ? ahead.keepVariant->registeredViews.get() : nullptr;
|
||||
if (!CapturedCurrent(ahead.captured, snapshot) || (aheadViews != nullptr && !CaptureRegisteredViewsCurrent(*aheadViews))) {
|
||||
const auto* aheadLinking = ahead.linking != nullptr ? ahead.linking.get() : ahead.keepVariant != nullptr ? ahead.keepVariant->linking.get() : nullptr;
|
||||
if (!capturedCurrent(ahead.captured, snapshot, aheadLinking) || (aheadViews != nullptr && !CaptureRegisteredViewsCurrent(*aheadViews))) {
|
||||
fromAhead = false;
|
||||
++dispatchesRejectedAhead;
|
||||
++groupStats.memoryMismatches;
|
||||
@@ -355,6 +368,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
|
||||
keepVariant = std::move(ahead.keepVariant);
|
||||
attachVariant = std::move(ahead.attachVariant);
|
||||
shaderMemory = std::move(ahead.shaderMemory);
|
||||
linking = std::move(ahead.linking);
|
||||
captured = std::move(ahead.captured);
|
||||
liveWords = std::move(ahead.liveWords);
|
||||
capture = std::move(ahead.capture);
|
||||
@@ -397,14 +411,14 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
|
||||
|
||||
static const bool dumpShaders = std::getenv("APS5_DUMP_SHADERS") != nullptr;
|
||||
try {
|
||||
auto invocation = InvocationFor(snapshot, codeOffset, request);
|
||||
auto invocation = InvocationFor(snapshot, codeOffset, request, AsyncDrawCompile(), &linking);
|
||||
timing.Mark("prepared_invocation");
|
||||
|
||||
const auto waitedBefore = traceCapSync() ? Graphics::Recorder::ThreadWaitedMs() : 0.0;
|
||||
forgetAtCapture = GuestMemory::ForgetSerial();
|
||||
capture = [&] {
|
||||
const SampledReadScope sampling(evidenceReads);
|
||||
return CaptureInvocation(*shaderMemory, snapshot, codeOffset, request, invocation);
|
||||
return CaptureInvocation(*shaderMemory, snapshot, codeOffset, request, invocation, &linking);
|
||||
}();
|
||||
captured = shaderMemory->Regions();
|
||||
request.context.memory = captured;
|
||||
@@ -416,7 +430,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
|
||||
|
||||
|
||||
timing.Mark("capture_resources");
|
||||
compiledResult = invocation.Materialize(*capture);
|
||||
compiledResult = MaterializeInBackground(invocation, capture, request.context.memory, address);
|
||||
timing.Mark("materialize");
|
||||
if (profile && compiledResult->cacheHit) cacheHits.fetch_add(1, std::memory_order_relaxed);
|
||||
const auto elapsed = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - started).count();
|
||||
@@ -427,6 +441,8 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
|
||||
}
|
||||
if (const auto limit = MaxComputeSpirvWords(); limit != 0 && compiledResult->spirv.size() > limit)
|
||||
throw std::runtime_error(std::to_string(compiledResult->spirv.size()) + " SPIR-V words, above APS5_MAX_COMPUTE_SPIRV_WORDS (" + std::to_string(limit) + ")");
|
||||
} catch (const DrawCompilePending&) {
|
||||
return;
|
||||
} catch (const std::exception& error) {
|
||||
std::string dump;
|
||||
if (dumpShaders) {
|
||||
@@ -449,9 +465,11 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
|
||||
}
|
||||
if (profile) recompileMs.fetch_add(phaseTiming.Elapsed(), std::memory_order_relaxed);
|
||||
phaseTiming.Phase(PhaseRecompile);
|
||||
if (!resolving) insertDispatch(address, key, noDispatchCache || !CacheableResult(*compiledResult), profile, registeredShader, forgetAtCapture, memory, shaderMemory, captured, capture, compiledResult, missedEntry, missedDiffering, attachVariant, phaseTiming);
|
||||
if (!resolving) insertDispatch(address, key, noDispatchCache || !CacheableResult(*compiledResult), profile, registeredShader, forgetAtCapture, memory, shaderMemory, captured, capture, compiledResult, missedEntry, missedDiffering, attachVariant, phaseTiming, linking);
|
||||
if (linking != nullptr) linking->AppendRegions(captured);
|
||||
}
|
||||
const auto* registeredViews = capture != nullptr ? &capture->snapshot.registeredImages : keepVariant != nullptr && keepVariant->registeredViews != nullptr ? keepVariant->registeredViews.get() : nullptr;
|
||||
const auto* captureLinking = linking != nullptr ? linking.get() : keepVariant != nullptr ? keepVariant->linking.get() : nullptr;
|
||||
if (resolving) {
|
||||
auto& parked = resolvedAhead()[currentPacketOffset()];
|
||||
parked = ResolvedDispatch{};
|
||||
@@ -466,6 +484,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
|
||||
parked.attachVariant = attachVariant;
|
||||
parked.missedEntry = missedEntry;
|
||||
parked.shaderMemory = shaderMemory;
|
||||
parked.linking = linking;
|
||||
parked.captured = std::move(captured);
|
||||
parked.liveWords = std::move(liveWords);
|
||||
parked.capture = capture;
|
||||
@@ -565,7 +584,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
|
||||
}
|
||||
if (pipelined) {
|
||||
runCaptureCheckHook();
|
||||
if (capturedMemoryChanged(captured)) {
|
||||
if (capturedMemoryChanged(captured, {}, captureLinking)) {
|
||||
const RecaptureScope recapture;
|
||||
dispatch(queue, packet, submission, indirectArguments);
|
||||
return;
|
||||
@@ -690,7 +709,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
|
||||
if (!captureChecked) {
|
||||
captureChecked = true;
|
||||
runCaptureCheckHook();
|
||||
if (capturedMemoryChanged(captured, snapshots)) {
|
||||
if (capturedMemoryChanged(captured, snapshots, captureLinking)) {
|
||||
gpuLock.unlock();
|
||||
const RecaptureScope recapture;
|
||||
dispatch(queue, packet, submission, indirectArguments);
|
||||
|
||||
@@ -82,9 +82,9 @@ bool InCode(const ShaderRecompiler::MemoryRegion& region, const std::shared_ptr<
|
||||
return !code->header.empty() && region.guestAddress >= code->headerAddress && region.guestAddress < code->headerAddress + code->header.size();
|
||||
}
|
||||
|
||||
bool OverlapsRange(std::span<const ShaderRecompiler::MemoryRegion> regions, const std::vector<std::pair<std::uint64_t, std::uint64_t>>& ranges, const std::shared_ptr<const ShaderSnapshot>& code) {
|
||||
bool OverlapsRange(std::span<const ShaderRecompiler::MemoryRegion> regions, const std::vector<std::pair<std::uint64_t, std::uint64_t>>& ranges, const std::shared_ptr<const ShaderSnapshot>& code, const PreparedShaderState::UserDataLink* linking) {
|
||||
for (const auto& region : regions) {
|
||||
if (InCode(region, code)) continue;
|
||||
if (InCode(region, code) && (linking == nullptr || !linking->Overlaps(region.guestAddress, region.bytes.size()))) continue;
|
||||
for (const auto& [begin, end] : ranges) {
|
||||
if (begin < region.guestAddress + region.bytes.size() && region.guestAddress < end) return true;
|
||||
}
|
||||
@@ -179,6 +179,7 @@ void Driver::resolveGroupAhead(const Submission& submission, const QueueState& l
|
||||
const auto packet = std::span(commands).subspan(scan, count);
|
||||
const auto opcode = (header >> 8u) & 0xffu;
|
||||
const auto next = scan + count;
|
||||
if (opcode == 0x45 && ((packet[1] >> 8u) & 3u) == 0) break;
|
||||
if (opcode == 0x15 || opcode == 0x16) {
|
||||
if (count < (opcode == 0x15 ? 5u : 3u)) break;
|
||||
if (scan > from) {
|
||||
@@ -293,7 +294,8 @@ void Driver::resolveGroupAhead(const Submission& submission, const QueueState& l
|
||||
++stats.labelOverlaps;
|
||||
break;
|
||||
}
|
||||
if (OverlapsRange(found->second.captured, writes, found->second.registeredShader)) {
|
||||
const auto* linking = found->second.linking != nullptr ? found->second.linking.get() : found->second.keepVariant != nullptr ? found->second.keepVariant->linking.get() : nullptr;
|
||||
if (OverlapsRange(found->second.captured, writes, found->second.registeredShader, linking)) {
|
||||
resolved.erase(found);
|
||||
++stats.writtenBefore;
|
||||
break;
|
||||
@@ -311,7 +313,7 @@ void Driver::resolveGroupAhead(const Submission& submission, const QueueState& l
|
||||
std::array<double, DriverPhaseCount> phaseMs{};
|
||||
auto phaseLap = lap;
|
||||
DispatchPhaseTiming phaseTiming{profile, lap, phaseMs, phaseLap};
|
||||
insertDispatch(found->second.address, found->second.key, found->second.noDispatchCache, profile, found->second.registeredShader, found->second.forgetAtCapture, memory, found->second.shaderMemory, found->second.captured, found->second.capture, found->second.compiledResult, found->second.missedEntry, found->second.missedDiffering, found->second.attachVariant, phaseTiming);
|
||||
insertDispatch(found->second.address, found->second.key, found->second.noDispatchCache, profile, found->second.registeredShader, found->second.forgetAtCapture, memory, found->second.shaderMemory, found->second.captured, found->second.capture, found->second.compiledResult, found->second.missedEntry, found->second.missedDiffering, found->second.attachVariant, phaseTiming, found->second.linking);
|
||||
}
|
||||
bool bounded = false;
|
||||
const auto itemWrites = DispatchWriteRanges(*found->second.compiledResult, bounded);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchCache.hpp"
|
||||
#include "ControlFlow/GraphBuilder.hpp"
|
||||
#include "Optimization/SrtWalker.hpp"
|
||||
#include <cstdlib>
|
||||
|
||||
namespace AgcDriver::DriverDetail {
|
||||
@@ -66,7 +68,15 @@ Driver::DispatchCacheFootprint Driver::DispatchCacheSize() {
|
||||
|
||||
std::uint64_t Driver::variantBytes(const DispatchVariant& variant) {
|
||||
const auto held = [](const auto& values) { return static_cast<std::uint64_t>(values.capacity() * sizeof(values[0])); };
|
||||
return sizeof(DispatchVariant) + held(variant.runs) + held(variant.words) + held(variant.shared) + held(variant.dataPositions) + held(variant.dataSlots) + held(variant.runBases) + held(variant.shaderDataPatches) + held(variant.captured) + held(variant.spans) + (variant.registeredViews != nullptr ? held(*variant.registeredViews) : 0u) + (variant.vertexInfo != nullptr ? sizeof(ShaderRecompiler::ShaderVertexStageInfo) : 0) + (variant.memory != nullptr ? variant.memory->Bytes() : 0);
|
||||
auto bytes = sizeof(DispatchVariant) + held(variant.runs) + held(variant.words) + held(variant.shared) + held(variant.dataPositions) + held(variant.dataSlots) + held(variant.runBases) + held(variant.shaderDataPatches) + held(variant.captured) + held(variant.spans) + (variant.registeredViews != nullptr ? held(*variant.registeredViews) : 0u) + (variant.vertexInfo != nullptr ? sizeof(ShaderRecompiler::ShaderVertexStageInfo) : 0) + (variant.memory != nullptr ? variant.memory->Bytes() : 0);
|
||||
if (variant.linking != nullptr) {
|
||||
const auto& link = *variant.linking;
|
||||
bytes += sizeof(link) + held(link.callees) + held(link.code) + held(link.tableUserData) + held(link.dependencies);
|
||||
for (const auto& code : link.code) bytes += held(code);
|
||||
for (const auto& dependency : link.dependencies) bytes += sizeof(*dependency) + held(dependency->words) + held(dependency->runs) + (dependency->stamp != nullptr ? sizeof(*dependency->stamp) : 0u);
|
||||
if (link.linked != nullptr) bytes += sizeof(*link.linked) + held(link.linked->code) + held(link.linked->fallbacks);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
void Driver::accountVariant(const DispatchVariant& variant, bool added) {
|
||||
|
||||
@@ -14,23 +14,51 @@ bool CacheableResult(const ShaderRecompiler::RecompileResult& compiled) {
|
||||
});
|
||||
}
|
||||
|
||||
void Driver::insertDispatch(std::uint64_t address, std::uint64_t key, bool noDispatchCache, bool profile, const std::shared_ptr<const ShaderSnapshot>& registeredShader, std::uint64_t forgetAtCapture, std::span<const ShaderRecompiler::MemoryRegion> memory, const std::shared_ptr<ShaderMemory>& shaderMemory, const std::vector<ShaderRecompiler::MemoryRegion>& captured, const std::shared_ptr<const ShaderRecompiler::ResourceCapture>& capture, const std::shared_ptr<const ShaderRecompiler::RecompileResult>& compiledResult, const std::shared_ptr<DispatchEntry>& missedEntry, bool missedDiffering, std::shared_ptr<DispatchVariant>& attachVariant, DispatchPhaseTiming& phaseTiming) {
|
||||
std::vector<ShaderRecompiler::MemoryRegion> Driver::dispatchRegions(std::span<const ShaderRecompiler::MemoryRegion> memory, std::span<const ShaderRecompiler::MemoryRegion> captured, const PreparedShaderState::UserDataLink* linking) {
|
||||
std::vector<ShaderRecompiler::MemoryRegion> linkRegions;
|
||||
if (linking != nullptr) linking->AppendRegions(linkRegions);
|
||||
std::stable_sort(linkRegions.begin(), linkRegions.end(), [](const auto& left, const auto& right) { return left.guestAddress < right.guestAddress; });
|
||||
std::vector<ShaderRecompiler::MemoryRegion> srtRegions;
|
||||
for (const auto& region : captured) {
|
||||
const bool registered = std::any_of(memory.begin(), memory.end(), [&](const auto& known) { return region.guestAddress >= known.guestAddress && region.guestAddress < known.guestAddress + known.bytes.size(); });
|
||||
const bool dependency = std::any_of(linkRegions.begin(), linkRegions.end(), [&](const auto& linked) { return region.guestAddress == linked.guestAddress && region.bytes.data() == linked.bytes.data() && region.bytes.size() == linked.bytes.size(); });
|
||||
if (registered || dependency) continue;
|
||||
auto address = region.guestAddress;
|
||||
const auto end = address + region.bytes.size();
|
||||
const auto append = [&](std::uint64_t begin, std::uint64_t stop, std::span<const std::byte> bytes) {
|
||||
if (begin < stop) srtRegions.push_back({begin, bytes.first(static_cast<std::size_t>(stop - begin))});
|
||||
};
|
||||
for (const auto& linked : linkRegions) {
|
||||
const auto low = std::max(address, linked.guestAddress);
|
||||
const auto high = std::min(end, linked.guestAddress + linked.bytes.size());
|
||||
if (low >= high || (low - region.guestAddress) % sizeof(std::uint32_t) != 0 || (high - low) % sizeof(std::uint32_t) != 0) continue;
|
||||
append(address, low, region.bytes.subspan(static_cast<std::size_t>(address - region.guestAddress)));
|
||||
const auto original = region.bytes.subspan(static_cast<std::size_t>(low - region.guestAddress), static_cast<std::size_t>(high - low));
|
||||
const auto dependency = linked.bytes.subspan(static_cast<std::size_t>(low - linked.guestAddress), original.size());
|
||||
append(low, high, std::ranges::equal(original, dependency) ? dependency : original);
|
||||
address = high;
|
||||
}
|
||||
append(address, end, region.bytes.subspan(static_cast<std::size_t>(address - region.guestAddress)));
|
||||
}
|
||||
srtRegions.insert(srtRegions.end(), linkRegions.begin(), linkRegions.end());
|
||||
std::stable_sort(srtRegions.begin(), srtRegions.end(), [](const auto& left, const auto& right) { return left.guestAddress < right.guestAddress; });
|
||||
return srtRegions;
|
||||
}
|
||||
|
||||
void Driver::insertDispatch(std::uint64_t address, std::uint64_t key, bool noDispatchCache, bool profile, const std::shared_ptr<const ShaderSnapshot>& registeredShader, std::uint64_t forgetAtCapture, std::span<const ShaderRecompiler::MemoryRegion> memory, const std::shared_ptr<ShaderMemory>& shaderMemory, const std::vector<ShaderRecompiler::MemoryRegion>& captured, const std::shared_ptr<const ShaderRecompiler::ResourceCapture>& capture, const std::shared_ptr<const ShaderRecompiler::RecompileResult>& compiledResult, const std::shared_ptr<DispatchEntry>& missedEntry, bool missedDiffering, std::shared_ptr<DispatchVariant>& attachVariant, DispatchPhaseTiming& phaseTiming, const std::shared_ptr<const PreparedShaderState::UserDataLink>& linking) {
|
||||
if (!noDispatchCache) {
|
||||
auto fresh = std::make_shared<DispatchVariant>();
|
||||
fresh->compiled = compiledResult;
|
||||
if (capture != nullptr && !capture->snapshot.registeredImages.empty()) fresh->registeredViews = std::make_shared<const std::vector<ShaderRecompiler::RegisteredImageView>>(capture->snapshot.registeredImages);
|
||||
fresh->shader = registeredShader;
|
||||
fresh->linking = linking;
|
||||
fresh->forgetSerial = forgetAtCapture;
|
||||
|
||||
std::vector<ShaderRecompiler::MemoryRegion> srtRegions;
|
||||
const auto srtRegions = dispatchRegions(memory, captured, linking.get());
|
||||
std::size_t capturedWords = 0;
|
||||
for (const auto& region : captured) {
|
||||
const bool registered = std::any_of(memory.begin(), memory.end(), [&](const auto& known) { return region.guestAddress >= known.guestAddress && region.guestAddress < known.guestAddress + known.bytes.size(); });
|
||||
if (registered) continue;
|
||||
srtRegions.push_back(region);
|
||||
capturedWords += region.bytes.size() / sizeof(std::uint32_t);
|
||||
}
|
||||
const auto supplied = shaderMemory->SuppliedBlocks();
|
||||
for (const auto& region : srtRegions) capturedWords += region.bytes.size() / sizeof(std::uint32_t);
|
||||
auto supplied = shaderMemory->SuppliedBlocks();
|
||||
if (linking != nullptr) supplied.insert(supplied.end(), linking->dependencies.begin(), linking->dependencies.end());
|
||||
fresh->runs.reserve(srtRegions.size());
|
||||
fresh->words.reserve(capturedWords);
|
||||
for (const auto& region : srtRegions) {
|
||||
@@ -44,15 +72,23 @@ void Driver::insertDispatch(std::uint64_t address, std::uint64_t key, bool noDis
|
||||
|
||||
DataWordPositionCounts dataCounts;
|
||||
if (dataHits() && !stampValidate() && capture != nullptr && !capture->readTrace.leaves.empty()) {
|
||||
auto otherReads = capture->readTrace.otherReads;
|
||||
if (linking != nullptr) {
|
||||
for (const auto& [slot, address] : capture->readTrace.leaves) {
|
||||
if (linking->Overlaps(address, sizeof(std::uint32_t))) otherReads.push_back(address);
|
||||
}
|
||||
std::sort(otherReads.begin(), otherReads.end());
|
||||
otherReads.erase(std::unique(otherReads.begin(), otherReads.end()), otherReads.end());
|
||||
}
|
||||
for (std::size_t b = 0; b < compiledResult->bindings.size(); ++b) {
|
||||
if (compiledResult->bindings[b].role != ShaderRecompiler::DescriptorRole::FlattenedSrt) continue;
|
||||
fresh->flatBinding = static_cast<std::uint32_t>(b);
|
||||
dataCounts = DataWordPositions(fresh->runs, capture->readTrace.leaves, capture->readTrace.otherReads, fresh->words, compiledResult->bindings[b].guestDescriptor, fresh->dataPositions, fresh->dataSlots);
|
||||
dataCounts = DataWordPositions(fresh->runs, capture->readTrace.leaves, otherReads, fresh->words, compiledResult->bindings[b].guestDescriptor, fresh->dataPositions, fresh->dataSlots);
|
||||
break;
|
||||
}
|
||||
}
|
||||
bool stable = true;
|
||||
if (stampValidate()) {
|
||||
if (stampValidate() && linking == nullptr) {
|
||||
|
||||
fresh->memory = shaderMemory;
|
||||
fresh->captured = captured;
|
||||
|
||||
@@ -32,7 +32,7 @@ void Driver::lookupDispatch(std::uint64_t address, const Submission& submission,
|
||||
|
||||
std::vector<std::pair<std::uint32_t, std::uint32_t>> liveData;
|
||||
const auto waitedBeforeValidate = profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0;
|
||||
if (!stampValidate()) {
|
||||
if (!stampValidate() || variants.front()->linking != nullptr) {
|
||||
const GuestMemory::ReadSiteScope site(GuestMemory::ReadSite::DispatchCache);
|
||||
|
||||
std::optional<SampledReadScope> sampling;
|
||||
@@ -135,7 +135,7 @@ void Driver::lookupDispatch(std::uint64_t address, const Submission& submission,
|
||||
counters.dataWordsRefreshed += liveData.size();
|
||||
++counters.dataHitsByRank[rank];
|
||||
}
|
||||
if (stampValidate()) {
|
||||
if (stampValidate() && variant->linking == nullptr) {
|
||||
captured = variant->captured;
|
||||
} else {
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp"
|
||||
#include "ThreadOwned.hpp"
|
||||
#include "Optimization/SrtWalker.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
@@ -30,9 +31,19 @@ void Driver::appendEntryRegions(const DispatchVariant& variant, std::vector<Shad
|
||||
const auto& source = words != nullptr ? *words : variant.words;
|
||||
regions.reserve(regions.size() + variant.runs.size());
|
||||
std::size_t offset = 0;
|
||||
std::size_t shared = 0;
|
||||
for (const auto& [begin, end] : variant.runs) {
|
||||
const auto count = static_cast<std::size_t>((end - begin) / sizeof(std::uint32_t));
|
||||
regions.push_back({begin, std::as_bytes(std::span<const std::uint32_t>(source).subspan(offset, count))});
|
||||
auto bytes = std::as_bytes(std::span<const std::uint32_t>(source).subspan(offset, count));
|
||||
while (shared < variant.shared.size() && variant.shared[shared].first + variant.shared[shared].count <= offset) ++shared;
|
||||
if (variant.linking != nullptr && shared < variant.shared.size()) {
|
||||
const auto& entry = variant.shared[shared];
|
||||
if (entry.first <= offset && offset + count <= entry.first + entry.count) {
|
||||
const auto block = entry.block.lock();
|
||||
if (block != nullptr && std::ranges::find(variant.linking->dependencies, block) != variant.linking->dependencies.end()) bytes = std::as_bytes(std::span(block->words).subspan(entry.offset + offset - entry.first, count));
|
||||
}
|
||||
}
|
||||
regions.push_back({begin, bytes});
|
||||
offset += count;
|
||||
}
|
||||
}
|
||||
@@ -46,7 +57,7 @@ std::shared_ptr<const ShaderRecompiler::RecompileResult> Driver::patchDataWords(
|
||||
return patched;
|
||||
}
|
||||
|
||||
bool Driver::syncPendingRuns(std::uint64_t program, std::uint32_t queue, const ShaderRecompiler::RecompileResult& compiled, std::span<const ShaderRecompiler::MemoryRegion> regions, std::uint64_t& synced, PendingView& pending, std::optional<SampledReadScope>& sampling, std::span<const VouchedRegions> skipped) {
|
||||
bool Driver::syncPendingRuns(std::uint64_t program, std::uint32_t queue, const ShaderRecompiler::RecompileResult& compiled, std::span<const ShaderRecompiler::MemoryRegion> regions, std::uint64_t& synced, PendingView& pending, std::optional<SampledReadScope>& sampling, std::span<const VouchedRegions> skipped, const PreparedShaderState::UserDataLink* linking) {
|
||||
using Policy = ShaderMemory::PendingWrite;
|
||||
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
|
||||
for (std::size_t index = 0, range = 0; index < regions.size(); ++index) {
|
||||
@@ -58,7 +69,8 @@ bool Driver::syncPendingRuns(std::uint64_t program, std::uint32_t queue, const S
|
||||
if (!pending.Overlaps(region.guestAddress, region.bytes.size())) continue;
|
||||
if (!sampling) sampling.emplace(siteSampling() ? evidenceValidations : evidenceReads);
|
||||
std::uint64_t ValidateCounters::*reason = &ValidateCounters::syncedOff;
|
||||
const auto policy = validateSkipEnabled() ? classifyPendingWrite(region.guestAddress, region.bytes.size(), reason, pending) : Policy::Sync;
|
||||
const bool dependency = linking != nullptr && linking->Overlaps(region.guestAddress, region.bytes.size());
|
||||
const auto policy = validateSkipEnabled() && !dependency ? classifyPendingWrite(region.guestAddress, region.bytes.size(), reason, pending) : Policy::Sync;
|
||||
if (policy != Policy::Sync) continue;
|
||||
if (validateSkipEnabled() && (validateLegacy() ? !GuestMemory::EqualsCommittedUnsynced(region.guestAddress, region.bytes) : GuestMemory::CompareMapped(region.guestAddress, region.bytes) != GuestMemory::Compare::Equal)) {
|
||||
if (profile) {
|
||||
@@ -120,7 +132,7 @@ EntryOutcome Driver::validateVariant(std::uint64_t program, std::uint32_t queue,
|
||||
thread_local std::vector<VouchedRegions>* vouchedSlot = nullptr;
|
||||
auto& vouched = ShaderRecompiler::ThreadOwned(vouchedSlot);
|
||||
vouched.clear();
|
||||
if (!variant.shared.empty() && vouchedValidation() && !validateLegacy() && variant.runs.size() == regions.size()) VouchSharedRegions(variant.shared, regions.size(), &QueryPendingSpan, vouched);
|
||||
if (!variant.shared.empty() && vouchedValidation() && !validateLegacy() && variant.runs.size() == regions.size()) VouchSharedRegions(variant.shared, regions.size(), &QueryPendingSpan, vouched, variant.linking != nullptr ? std::span(variant.linking->dependencies) : std::span<const std::shared_ptr<const ShaderRecompiler::SrtGuestWords>>{}, &PreparedShaderState::UserDataLink::Restamp);
|
||||
PendingView pending;
|
||||
pending.Load();
|
||||
std::erase_if(vouched, [&](const VouchedRegions& range) { return pending.Overlaps(range.low, static_cast<std::size_t>(range.high - range.low)); });
|
||||
@@ -138,7 +150,7 @@ EntryOutcome Driver::validateVariant(std::uint64_t program, std::uint32_t queue,
|
||||
}
|
||||
}
|
||||
const std::span<const std::pair<std::uint64_t, std::uint64_t>> runs = vouched.empty() ? std::span<const std::pair<std::uint64_t, std::uint64_t>>(variant.runs) : std::span<const std::pair<std::uint64_t, std::uint64_t>>(checked);
|
||||
if (!syncPendingRuns(program, queue, *variant.compiled, regions, runsSynced, pending, sampling, vouched)) return EntryOutcome::Differing;
|
||||
if (!syncPendingRuns(program, queue, *variant.compiled, regions, runsSynced, pending, sampling, vouched, variant.linking.get())) return EntryOutcome::Differing;
|
||||
auto publish = Graphics::Recorder::PublishGeneration();
|
||||
auto pendingSerial = Graphics::StorageTexture::PendingSerial();
|
||||
auto forget = GuestMemory::ForgetSerial();
|
||||
@@ -149,7 +161,7 @@ EntryOutcome Driver::validateVariant(std::uint64_t program, std::uint32_t queue,
|
||||
if (Graphics::StorageTexture::FlushPending(region.guestAddress, region.bytes.size(), nullptr, "dispatch-cache entry")) ++imagesFlushed;
|
||||
}
|
||||
pending.Load();
|
||||
if (!syncPendingRuns(program, queue, *variant.compiled, regions, runsSynced, pending, sampling)) return EntryOutcome::Differing;
|
||||
if (!syncPendingRuns(program, queue, *variant.compiled, regions, runsSynced, pending, sampling, {}, variant.linking.get())) return EntryOutcome::Differing;
|
||||
publish = Graphics::Recorder::PublishGeneration();
|
||||
pendingSerial = Graphics::StorageTexture::PendingSerial();
|
||||
forget = GuestMemory::ForgetSerial();
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp"
|
||||
#include "Optimization/ResourceProgram.hpp"
|
||||
#include "prx/libc/include/HostThreadLocal.hpp"
|
||||
#include <atomic>
|
||||
@@ -240,6 +241,21 @@ std::optional<HeldReason> writesBeyondTargets(const ShaderRecompiler::RecompileR
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
bool DrawTableSnapshotEnabled() {
|
||||
return Graphics::RuntimeSwitches::Set(Graphics::RuntimeSwitch::TableSnapshot);
|
||||
}
|
||||
|
||||
void KeepUserDataTables(ShaderMemory& memory, const std::vector<DrawProgram>& programs) {
|
||||
for (const auto& program : programs) {
|
||||
const std::span<const std::uint32_t> userData = program.userData;
|
||||
for (std::size_t index = 0; index + 1u < userData.size(); ++index) {
|
||||
if (userData[index + 1u] > 0xffffu) continue;
|
||||
const auto address = static_cast<std::uint64_t>(userData[index]) | (static_cast<std::uint64_t>(userData[index + 1u]) << 32u);
|
||||
if (address != 0) static_cast<void>(memory.KeepTable(address));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DrawFinisher::Pending heldWrites(const DrawTail& tail) {
|
||||
DrawFinisher::Pending held;
|
||||
held.key = tail.drawKey;
|
||||
@@ -299,6 +315,13 @@ bool EmptyIndirectSkip() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
void FinishLeaseWritesBeforeRead() {
|
||||
if (!Graphics::LeaseWritesMayBePending()) return;
|
||||
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Indirect);
|
||||
std::lock_guard gpuLock(GuestMemory::GpuMutex());
|
||||
Graphics::FinishLeaseWrites();
|
||||
}
|
||||
|
||||
struct CpuIndirectProgramsStorage {};
|
||||
|
||||
std::unordered_map<std::uint64_t, bool>& CpuIndirectPrograms() {
|
||||
@@ -541,6 +564,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
|
||||
const auto& indirect = *drawParameters.indirect;
|
||||
recordQueuedLabelsBeforeRead(submission.queue);
|
||||
const auto readStart = std::chrono::steady_clock::now();
|
||||
FinishLeaseWritesBeforeRead();
|
||||
const auto count = std::min(indirect.countIndirect ? Pm4::ReadDrawCount(indirect) : indirect.count, indirect.count);
|
||||
bool any = false;
|
||||
for (std::uint32_t record = 0; record < count && !any; ++record) any = recordDraws(Pm4::ReadDrawArguments(indirect, record));
|
||||
@@ -747,6 +771,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
|
||||
tail.submissionSerial = submission.serial;
|
||||
tail.packetOffset = static_cast<std::size_t>(packet.data() - submission.commands.data());
|
||||
noteFinisherHandOff(true);
|
||||
if (DrawTableSnapshotEnabled()) KeepUserDataTables(*shaderMemory, programs);
|
||||
DrawFinisher::Pending held;
|
||||
if (DrawFinisher::Overlap()) held = heldWrites(tail);
|
||||
DrawFinisher::Get().Enqueue([this, tailHolder] {
|
||||
@@ -756,6 +781,8 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
|
||||
PerformanceTimer finishTiming("Driver.DrawFinish");
|
||||
try {
|
||||
if (finishDraw(job, finishTiming) == DrawVerdict::Rejected) throw std::runtime_error(job.ownRejected);
|
||||
} catch (const DrawCompilePending&) {
|
||||
CaptureTrace::Log("draw-pending submission=%llu offset=%zu finisher=1", static_cast<unsigned long long>(job.submissionSerial), job.packetOffset);
|
||||
} catch (const RefusedDraw& refused) {
|
||||
CaptureTrace::Log("draw-refused submission=%llu offset=%zu finisher=1 reason=%.256s", static_cast<unsigned long long>(job.submissionSerial), job.packetOffset, refused.what());
|
||||
ReportRefusedDraw(refused);
|
||||
@@ -943,17 +970,21 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
|
||||
std::vector<std::uint32_t> pushOffsets(programs.size(), 0);
|
||||
std::optional<ShaderRecompiler::MeshBarycentricLayout> meshBarycentrics;
|
||||
std::vector<std::size_t> resultIndex(programs.size(), 0);
|
||||
const bool fixedSlots = localDevice->GraphicsPipelineLibraries();
|
||||
const bool hasFragment = std::ranges::any_of(programs, [](const DrawProgram& program) { return program.binary.stage == ShaderRecompiler::ShaderStage::Fragment; });
|
||||
for (std::size_t i = 0; i < programs.size(); ++i) {
|
||||
if (roles[i] == Role::GeometryBack) continue;
|
||||
const auto& program = programs[i];
|
||||
pushCursorBytes = Graphics::StagePushOffset(pushCursorBytes, program.binary.stage, localDevice->GraphicsPipelineLibraries());
|
||||
pushCursorBytes = Graphics::StagePushOffset(pushCursorBytes, program.binary.stage, fixedSlots);
|
||||
require(pushCursorBytes <= Graphics::PushBlockBytes(fixedSlots), "stage push constant offset exceeds the pipeline push constant block");
|
||||
const auto pushBudget = Graphics::StagePushBudget(Graphics::StagePushLimit(graphics.stages, pushCursorBytes, graphics.depthRemap.mode != 0u), pushCursorBytes, program.binary.stage, fixedSlots, hasFragment);
|
||||
pushOffsets[i] = pushCursorBytes;
|
||||
if (drawHit) {
|
||||
|
||||
programResults[i] = stageData[i].compiled != nullptr ? stageData[i].compiled.get() : matched[i]->compiled.get();
|
||||
memory.insert(memory.end(), matchedRegions[i].begin(), matchedRegions[i].end());
|
||||
} else {
|
||||
const auto candidate = std::find_if(dataCandidates[i].begin(), dataCandidates[i].end(), [&](const auto& kept) { return kept.first->pushOffset == pushCursorBytes; });
|
||||
const auto candidate = std::find_if(dataCandidates[i].begin(), dataCandidates[i].end(), [&](const auto& kept) { return kept.first->pushOffset == pushCursorBytes && kept.first->compiled->pushConstants.size() <= pushBudget; });
|
||||
if (candidate != dataCandidates[i].end() && !verifyDrawDataHits()) {
|
||||
matched[i] = candidate->first;
|
||||
stageCaptures[i].registeredViews = matched[i]->registeredViews;
|
||||
@@ -987,8 +1018,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
|
||||
fold(result, drawParameters);
|
||||
}
|
||||
try {
|
||||
const auto slotEnd = (pushCursorBytes / Graphics::PipelinePushSlotBytes + 1u) * Graphics::PipelinePushSlotBytes;
|
||||
require(result.pushConstants.size() <= slotEnd - pushCursorBytes, "stage push constants exceed the pipeline push constant block");
|
||||
require(result.pushConstants.size() <= pushBudget, "stage push constants exceed the pipeline push constant block");
|
||||
stages.push_back({program.binary.stage, &result, result.pushConstants.empty() ? 0u : pushCursorBytes, stageCaptures[i].registeredViews.get()});
|
||||
pushCursorBytes += static_cast<std::uint32_t>(result.pushConstants.size());
|
||||
} catch (...) {
|
||||
@@ -1154,6 +1184,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
|
||||
}
|
||||
recordQueuedLabelsBeforeRead(submission.queue);
|
||||
const auto readStart = std::chrono::steady_clock::now();
|
||||
FinishLeaseWritesBeforeRead();
|
||||
const auto count = std::min(indirect.countIndirect ? Pm4::ReadDrawCount(indirect) : indirect.count, indirect.count);
|
||||
std::vector<Pm4::DrawArguments> records;
|
||||
for (std::uint32_t record = 0; record < count; ++record) records.push_back(Pm4::ReadDrawArguments(indirect, record));
|
||||
@@ -1372,10 +1403,11 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
|
||||
const auto commitPacket = tail.packetOpcode;
|
||||
const auto epoch = DrawFinisher::OnFinisherThread() ? tail.epoch : DrawPipeline::EpochToken().load(std::memory_order_relaxed);
|
||||
auto reads = QueuedDrawReadRanges(drawParameters, stages);
|
||||
auto commit = [this, localDevice = std::move(localDevice), decode = std::move(decode), drawParameters, stages = std::move(stages), snapshots = std::move(snapshots), recipe = std::move(recipe), recipeStages = std::move(recipeStages), drawKey, recipeDonor, shape = tail.shapeKey, commitQueue, commitPacket, epoch, trace = trace, writablePrograms = std::move(writablePrograms), results = std::move(results), memory = std::move(memory), linked = std::move(linked), stageCaptures = std::move(stageCaptures), matched = std::move(matched), matchedRegions = std::move(matchedRegions), fresh = std::move(fresh), decodeReads = std::move(decodeReads), shaderMemory = std::move(shaderMemory), entry = std::move(entry), dataEntry = std::move(dataEntry), compiledStages = std::move(compiledStages), stageData = std::move(stageData)]() mutable {
|
||||
auto contentKey = recipe == nullptr && DrawFinisher::OnFinisherThread() ? localDevice->DrawContentKey(decode->state, drawParameters, stages) : std::vector<std::uint32_t>{};
|
||||
auto commit = [this, contentKey = std::move(contentKey), localDevice = std::move(localDevice), decode = std::move(decode), drawParameters, stages = std::move(stages), snapshots = std::move(snapshots), recipe = std::move(recipe), recipeStages = std::move(recipeStages), drawKey, recipeDonor, shape = tail.shapeKey, commitQueue, commitPacket, epoch, trace = trace, writablePrograms = std::move(writablePrograms), results = std::move(results), memory = std::move(memory), linked = std::move(linked), stageCaptures = std::move(stageCaptures), matched = std::move(matched), matchedRegions = std::move(matchedRegions), fresh = std::move(fresh), decodeReads = std::move(decodeReads), shaderMemory = std::move(shaderMemory), entry = std::move(entry), dataEntry = std::move(dataEntry), compiledStages = std::move(compiledStages), stageData = std::move(stageData)]() mutable {
|
||||
DrawPipeline::FollowEpoch(epoch);
|
||||
GuestMemory::SetCurrentPacket(commitPacket, commitQueue);
|
||||
commitDraw(localDevice, commitQueue, decode->state, drawParameters, stages, snapshots, recipe, recipeStages, drawKey, recipeDonor, trace, shape);
|
||||
commitDraw(localDevice, commitQueue, decode->state, drawParameters, stages, snapshots, recipe, recipeStages, drawKey, recipeDonor, trace, shape, contentKey.empty() ? nullptr : &contentKey);
|
||||
};
|
||||
auto held = std::make_shared<decltype(commit)>(std::move(commit));
|
||||
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Draw, [held] { (*held)(); }, std::move(writes), 0, {}, std::move(reads), true);
|
||||
@@ -1473,7 +1505,7 @@ void Driver::restartFinishedDraw(DrawTail& tail) {
|
||||
tail.shaderMemory = std::make_unique<ShaderMemory>(tail.memory, &queryPendingWrite, &observePendingWrite, hookWaitCounter(), &QueryPendingSpan);
|
||||
}
|
||||
|
||||
void Driver::commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, const std::shared_ptr<DrawEntry>& recipeDonor, VulkanDevice::DrawTraceContext trace, std::uint64_t shape) {
|
||||
void Driver::commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, const std::shared_ptr<DrawEntry>& recipeDonor, VulkanDevice::DrawTraceContext trace, std::uint64_t shape, const std::vector<std::uint32_t>* contentKey) {
|
||||
const auto* tracePtr = trace.token != 0 ? &trace : nullptr;
|
||||
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Draw);
|
||||
std::lock_guard gpuLock(GuestMemory::GpuMutex());
|
||||
@@ -1492,7 +1524,7 @@ void Driver::commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t
|
||||
VulkanDevice::NoteRecipe(VulkanDevice::RecipeEvent::Restart, VulkanDevice::RecipeKind::Draw);
|
||||
}
|
||||
std::shared_ptr<const DrawRecipe> built;
|
||||
localDevice->Draw(graphics, drawParameters, stages, snapshots, recipeStages.empty() ? nullptr : &built, tracePtr, shape);
|
||||
localDevice->Draw(graphics, drawParameters, stages, snapshots, recipeStages.empty() ? nullptr : &built, tracePtr, shape, contentKey);
|
||||
if (built != nullptr) attachDrawRecipe(drawKey, recipeStages, std::move(built), recipeDonor);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,8 +7,11 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp"
|
||||
#include "Optimization/ResourceProgram.hpp"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <span>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
@@ -58,6 +61,105 @@ void TraceShaderRequestFailure(std::uint64_t token, const Submission& submission
|
||||
}
|
||||
}
|
||||
|
||||
struct PendingMaterialize {
|
||||
std::mutex mutex;
|
||||
bool finished = false;
|
||||
std::shared_ptr<const ShaderRecompiler::RecompileResult> result;
|
||||
std::exception_ptr failure;
|
||||
};
|
||||
|
||||
struct PendingMaterializes {
|
||||
static constexpr std::size_t Limit = 4096;
|
||||
static constexpr double CheapMs = 2.0;
|
||||
std::mutex mutex;
|
||||
std::map<std::pair<std::uint64_t, std::uint64_t>, std::shared_ptr<PendingMaterialize>> byKey;
|
||||
std::map<std::uint64_t, double> lastMs;
|
||||
};
|
||||
|
||||
double ElapsedMs(std::chrono::steady_clock::time_point since) {
|
||||
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - since).count();
|
||||
}
|
||||
|
||||
PendingMaterializes& pendingMaterializes() {
|
||||
static auto* pending = new PendingMaterializes();
|
||||
return *pending;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
std::shared_ptr<const ShaderRecompiler::RecompileResult> MaterializeInBackground(const ShaderRecompiler::PreparedShaderInvocation& invocation, const std::shared_ptr<const ShaderRecompiler::ResourceCapture>& capture, ShaderRecompiler::MemoryRegionView memory, std::uint64_t address) {
|
||||
if (!AsyncDrawCompile()) return invocation.Materialize(*capture);
|
||||
bool contended = false;
|
||||
if (auto memoized = invocation.MaterializeIfMemoized(*capture, &contended)) return memoized;
|
||||
auto& pending = pendingMaterializes();
|
||||
bool cheap = false;
|
||||
{
|
||||
std::lock_guard lock(pending.mutex);
|
||||
const auto found = pending.lastMs.find(address);
|
||||
cheap = !contended && found != pending.lastMs.end() && found->second < PendingMaterializes::CheapMs;
|
||||
}
|
||||
if (cheap) {
|
||||
const auto started = std::chrono::steady_clock::now();
|
||||
auto result = invocation.Materialize(*capture);
|
||||
const auto ms = ElapsedMs(started);
|
||||
std::lock_guard lock(pending.mutex);
|
||||
pending.lastMs[address] = ms;
|
||||
return result;
|
||||
}
|
||||
const std::pair key{address, invocation.SnapshotKey(*capture)};
|
||||
std::shared_ptr<PendingMaterialize> job;
|
||||
bool started = false;
|
||||
{
|
||||
std::lock_guard lock(pending.mutex);
|
||||
if (pending.byKey.size() >= PendingMaterializes::Limit) {
|
||||
std::erase_if(pending.byKey, [](const auto& entry) {
|
||||
std::lock_guard entryLock(entry.second->mutex);
|
||||
return entry.second->finished;
|
||||
});
|
||||
}
|
||||
auto& slot = pending.byKey[key];
|
||||
if (slot == nullptr) {
|
||||
slot = std::make_shared<PendingMaterialize>();
|
||||
started = true;
|
||||
}
|
||||
job = slot;
|
||||
}
|
||||
if (started) {
|
||||
const auto owned = OwnRecompileRequest(invocation.Request(), memory);
|
||||
const auto rebound = std::make_shared<const ShaderRecompiler::PreparedShaderInvocation>(invocation.Rebound(owned->request));
|
||||
SubmitLibraryPrebuild([job, owned, rebound, capture, address] {
|
||||
std::shared_ptr<const ShaderRecompiler::RecompileResult> result;
|
||||
std::exception_ptr failure;
|
||||
const auto started = std::chrono::steady_clock::now();
|
||||
try {
|
||||
result = rebound->Materialize(*capture);
|
||||
} catch (...) {
|
||||
failure = std::current_exception();
|
||||
}
|
||||
{
|
||||
const auto ms = ElapsedMs(started);
|
||||
auto& registry = pendingMaterializes();
|
||||
std::lock_guard lock(registry.mutex);
|
||||
registry.lastMs[address] = ms;
|
||||
}
|
||||
{
|
||||
std::lock_guard lock(job->mutex);
|
||||
job->result = std::move(result);
|
||||
job->failure = failure;
|
||||
job->finished = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
std::lock_guard lock(job->mutex);
|
||||
if (!job->finished) throw DrawCompilePending("the draw's shader is still being specialized in the background");
|
||||
}
|
||||
{
|
||||
std::lock_guard lock(pending.mutex);
|
||||
if (const auto found = pending.byKey.find(key); found != pending.byKey.end() && found->second == job) pending.byKey.erase(found);
|
||||
}
|
||||
if (job->failure != nullptr) std::rethrow_exception(job->failure);
|
||||
return job->result;
|
||||
}
|
||||
|
||||
std::shared_ptr<const ShaderRecompiler::RecompileResult> Driver::materializeDrawStage(std::size_t i, std::uint32_t pushOffset, const QueueState& queue, const Submission& submission, std::size_t packetOffset, std::uint64_t traceToken, const std::vector<DrawProgram>& programs, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector<std::optional<ShaderRecompiler::ShaderVertexStageInfo>>& vertexInfos, std::vector<ShaderRecompiler::MemoryRegion>& memory, const std::vector<ShaderRecompiler::LinkedProgram>& linked, const Pm4::DrawParameters& drawParameters, const std::shared_ptr<VulkanDevice>& localDevice, ShaderMemory& shaderMemory, std::vector<StageCapture>& stageCaptures, std::vector<bool>& recompiled, bool drawHit, const std::vector<std::shared_ptr<DispatchVariant>>& matched, const std::vector<std::vector<ShaderRecompiler::MemoryRegion>>& matchedRegions, bool profile, std::uint64_t dumpTarget, std::uint64_t dumpSlot1, std::uint64_t& captures, DrawPhaseTiming& phaseTiming, std::array<double, DrawDriverPhaseCount>& phaseMs, std::string& rejected, const std::optional<ShaderRecompiler::MeshBarycentricLayout>& meshBarycentrics) try {
|
||||
@@ -66,20 +168,23 @@ std::shared_ptr<const ShaderRecompiler::RecompileResult> Driver::materializeDraw
|
||||
phaseTiming.Phase(DrawRowVectors);
|
||||
const auto& program = programs[i];
|
||||
const auto waveSize = Graphics::StageWaveSize(graphics.stages, program.binary.stage);
|
||||
const bool fixedSlots = localDevice->GraphicsPipelineLibraries();
|
||||
require(pushOffset <= Graphics::PushBlockBytes(fixedSlots), "stage push constant offset exceeds the pipeline push constant block");
|
||||
const bool hasFragment = std::ranges::any_of(programs, [](const DrawProgram& value) { return value.binary.stage == Stage::Fragment; });
|
||||
const auto pushBytes = Graphics::StagePushBudget(Graphics::StagePushLimit(graphics.stages, pushOffset, graphics.depthRemap.mode != 0u), pushOffset, program.binary.stage, fixedSlots, hasFragment);
|
||||
ShaderRecompiler::RecompileRequest request{
|
||||
program.binary,
|
||||
{waveSize, program.firstUserSgpr, program.userData, std::nullopt, program.binary.stage == Stage::Fragment ? std::optional(pixel) : std::nullopt, vertexInfos[i], memory, RegisteredFloatMode(*program.snapshot)},
|
||||
localDevice->Target(),
|
||||
{0, 0, pushOffset, Graphics::StagePushLimit(graphics.stages, pushOffset, graphics.depthRemap.mode != 0u) - pushOffset % Graphics::PipelinePushSlotBytes},
|
||||
{0, 0, pushOffset, pushBytes},
|
||||
ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, Graphics::StageMeshConfiguration(graphics.stages, program.binary.stage), graphics.stages.tessellation, {drawParameters.indexAddress, drawParameters.indexCount, drawParameters.indexSize, drawParameters.instanceCount}, program.binary.stage == Stage::Mesh ? meshBarycentrics : std::nullopt}
|
||||
};
|
||||
if (graphics.depthRemap.mode != 0u && pushOffset < Graphics::PipelinePushSlotBytes) {
|
||||
request.layout.pushConstantSizeBytes = std::min(request.layout.pushConstantSizeBytes, ShaderRecompiler::DepthRemapPushOffsetBytes - pushOffset);
|
||||
}
|
||||
const auto waitedBefore = traceCapSync() || profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0;
|
||||
auto invocation = [&] {
|
||||
try {
|
||||
return InvocationFor(*program.snapshot, program.codeOffset, request);
|
||||
return InvocationFor(*program.snapshot, program.codeOffset, request, AsyncDrawCompile());
|
||||
} catch (const DrawCompilePending&) {
|
||||
throw;
|
||||
} catch (...) {
|
||||
TraceShaderRequestFailure(traceToken, submission, packetOffset, program, std::current_exception());
|
||||
throw;
|
||||
@@ -159,8 +264,10 @@ std::shared_ptr<const ShaderRecompiler::RecompileResult> Driver::materializeDraw
|
||||
|
||||
timing.Mark("capture_resources");
|
||||
try {
|
||||
stageCapture.compiled = invocation.Materialize(*capture);
|
||||
stageCapture.compiled = MaterializeInBackground(invocation, capture, request.context.memory, program.binary.codeAddress);
|
||||
stageCapture.capture = capture;
|
||||
} catch (const DrawCompilePending&) {
|
||||
throw;
|
||||
} catch (const std::exception& error) {
|
||||
TraceMaterializationFailure(traceToken, submission, packetOffset, i, "capture-or-materialize", std::current_exception());
|
||||
throw named(error, request.context.memory);
|
||||
@@ -188,6 +295,8 @@ std::shared_ptr<const ShaderRecompiler::RecompileResult> Driver::materializeDraw
|
||||
stageCapture.userDataMask = mask;
|
||||
phaseTiming.Phase(DrawRowRecompile);
|
||||
return stageCapture.compiled;
|
||||
} catch (const DrawCompilePending&) {
|
||||
throw;
|
||||
} catch (const std::exception& error) {
|
||||
if (!SkipRefusedDraws()) throw;
|
||||
throw RefusedDraw(programs[i].binary.codeAddress, error.what());
|
||||
|
||||
@@ -195,8 +195,15 @@ std::shared_ptr<DrawDecode> Driver::decodeDraw(const QueueState& queue, const Su
|
||||
auto product = std::make_shared<DrawDecode>();
|
||||
product->state = Graphics::DecodeState(queue, VertexWorkgroupRequired(queue, *submission.shaders));
|
||||
DecodeGraphicsPrograms(*product, queue, *submission.shaders, false, true);
|
||||
product->state.depthCopySource = std::ranges::any_of(product->programs, [](const DrawProgram& program) { return program.binary.codeAddress == DepthCopyPixelProgramAddress(true); });
|
||||
product->pixel = Graphics::DecodePixelStageInfo(queue.context, Graphics::ExportMappings(product->state), Graphics::PixelProgramSkipped(queue));
|
||||
product->state.depthCopySource = std::ranges::any_of(product->programs, [](const DrawProgram& program) { return program.binary.codeAddress == DepthCopyPixelProgramAddress(true) || program.binary.codeAddress == StencilCopyPixelProgramAddress(true); });
|
||||
std::span<const std::byte> fragmentHeader;
|
||||
for (const auto& program : product->programs) {
|
||||
if (program.binary.stage == ShaderRecompiler::ShaderStage::Fragment) {
|
||||
fragmentHeader = program.binary.header;
|
||||
break;
|
||||
}
|
||||
}
|
||||
product->pixel = Graphics::DecodePixelStageInfo(queue.context, Graphics::ExportMappings(product->state), Graphics::PixelProgramSkipped(queue), fragmentHeader);
|
||||
Graphics::NormalizeUnusedViewportDepth(product->state, product->pixel);
|
||||
Graphics::ApplyDepthRemap(context, product->state);
|
||||
Graphics::ApplyDepthBoundsEmulation(context, product->state, product->pixel);
|
||||
|
||||
@@ -9,6 +9,8 @@ namespace AgcDriver::DriverDetail {
|
||||
|
||||
void Driver::lookupDraw(const Submission& submission, const std::shared_ptr<VulkanDevice>& localDevice, const Graphics::State& graphics, const ShaderRecompiler::ShaderPixelStageInfo& pixel, const std::vector<DrawProgram>& programs, const std::vector<ShaderRecompiler::ProgramRole>& roles, const std::vector<std::optional<ShaderRecompiler::ShaderVertexStageInfo>>& vertexInfos, bool useDrawEntries, bool registerKey, bool profile, std::uint64_t& drawKey, std::shared_ptr<DrawEntry>& entry, std::vector<std::shared_ptr<DispatchVariant>>& matched, std::vector<std::vector<ShaderRecompiler::MemoryRegion>>& matchedRegions, bool& drawHit, bool& verifyHit, DrawPhaseTiming& phaseTiming, std::array<double, DrawDriverPhaseCount>& phaseMs, const std::shared_ptr<DrawEntry>& dataEntry, DrawDataCandidates& dataCandidates, std::vector<StageDataHit>& stageData) {
|
||||
using Role = ShaderRecompiler::ProgramRole;
|
||||
const bool fixedSlots = localDevice->GraphicsPipelineLibraries();
|
||||
const bool hasFragment = std::ranges::any_of(programs, [](const DrawProgram& program) { return program.binary.stage == ShaderRecompiler::ShaderStage::Fragment; });
|
||||
if (useDrawEntries) {
|
||||
if (!registerKey) {
|
||||
drawKey = 0xcbf29ce484222325ull;
|
||||
@@ -142,14 +144,16 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptr<Vulk
|
||||
for (std::size_t i = 0; !miss && i < programs.size(); ++i) {
|
||||
if (roles[i] == Role::GeometryBack) continue;
|
||||
++stageValidations;
|
||||
cursor = Graphics::StagePushOffset(cursor, programs[i].binary.stage, localDevice->GraphicsPipelineLibraries());
|
||||
cursor = Graphics::StagePushOffset(cursor, programs[i].binary.stage, fixedSlots);
|
||||
if (cursor > Graphics::PushBlockBytes(fixedSlots)) { miss = DrawMiss::Layout; break; }
|
||||
const auto pushBudget = Graphics::StagePushBudget(Graphics::StagePushLimit(graphics.stages, cursor, graphics.depthRemap.mode != 0u), cursor, programs[i].binary.stage, fixedSlots, hasFragment);
|
||||
const auto& variants = entry->stages[i];
|
||||
auto outcome = EntryOutcome::Differing;
|
||||
bool anyLayout = false;
|
||||
for (std::size_t rank = 0; rank < variants.size(); ++rank) {
|
||||
const auto& variant = variants[rank];
|
||||
if (variant->registeredViews != nullptr && !CaptureRegisteredViewsCurrent(*variant->registeredViews)) continue;
|
||||
if (variant->pushOffset != cursor) continue;
|
||||
if (variant->pushOffset != cursor || variant->compiled->pushConstants.size() > pushBudget) continue;
|
||||
if (programs[i].binary.stage == ShaderRecompiler::ShaderStage::Mesh && !std::equal(variant->meshIndexDescriptor.begin(), variant->meshIndexDescriptor.end(), programs[i].userData.begin() + ShaderRecompiler::MeshIndexBufferUserWord)) {
|
||||
if (!anyLayout) outcome = EntryOutcome::Differing;
|
||||
anyLayout = true;
|
||||
|
||||
@@ -25,8 +25,8 @@ bool indirectRecordsDraw(const Pm4::DrawParameters::IndirectDraw& indirect) {
|
||||
|
||||
QueueState DepthCopyDraw(const QueueState& queue, const Graphics::DepthCopyPass& copy) {
|
||||
const bool multisampled = copy.source.samples != 1u;
|
||||
const auto address = DepthCopyPixelProgramAddress(multisampled);
|
||||
const auto words = Graphics::DepthCopySourceWords(copy.source);
|
||||
const auto address = copy.stencil ? StencilCopyPixelProgramAddress(multisampled) : DepthCopyPixelProgramAddress(multisampled);
|
||||
const auto words = Graphics::DepthCopySourceWords(copy.source, copy.stencil);
|
||||
QueueState draw = queue;
|
||||
draw.context.insert_or_assign(0x000u, 0u);
|
||||
draw.shader.insert_or_assign(0x008u, static_cast<std::uint32_t>(address >> 8u));
|
||||
@@ -39,8 +39,8 @@ QueueState DepthCopyDraw(const QueueState& queue, const Graphics::DepthCopyPass&
|
||||
draw.context.insert_or_assign(0x1b4u, 0x8002u);
|
||||
draw.context.insert_or_assign(0x1b6u, 0u);
|
||||
draw.context.insert_or_assign(0x1c4u, 0u);
|
||||
draw.context.insert_or_assign(0x1c5u, 1u);
|
||||
draw.context.insert_or_assign(0x08fu, 1u);
|
||||
draw.context.insert_or_assign(0x1c5u, copy.stencil ? 2u : 1u);
|
||||
draw.context.insert_or_assign(0x08fu, copy.stencil ? 3u : 1u);
|
||||
draw.context.insert_or_assign(0x203u, 0u);
|
||||
if (const auto alpha = draw.context.find(0x2dcu); alpha != draw.context.end()) draw.context.insert_or_assign(0x2dcu, alpha->second & ~1u);
|
||||
return draw;
|
||||
|
||||
@@ -69,7 +69,7 @@ std::vector<std::pair<std::uint64_t, std::uint64_t>> DispatchWriteRanges(const S
|
||||
const auto words = std::span<const std::uint32_t>(binding.guestDescriptor).subspan(static_cast<std::size_t>(element) * 8, 8);
|
||||
if (Graphics::IsNullTextureResource(words)) continue;
|
||||
const auto resource = Graphics::DecodeTextureResource(words);
|
||||
const auto surfaceBytes = Graphics::DescribeSurface(resource).guestBytes;
|
||||
const auto surfaceBytes = Graphics::SurfaceGuestBytes(resource);
|
||||
ranges.emplace_back(resource.baseAddress, resource.baseAddress + (surfaceBytes != 0 ? surfaceBytes : UnknownImageBytes));
|
||||
if (resource.dccAddress != 0) ranges.emplace_back(resource.dccAddress, resource.dccAddress + (surfaceBytes != 0 ? surfaceBytes / 256 + 1 : UnknownImageBytes));
|
||||
}
|
||||
@@ -114,7 +114,7 @@ std::vector<std::pair<std::uint64_t, std::uint64_t>> DrawWriteRanges(const Graph
|
||||
if (Graphics::IsNullTextureResource(words)) continue;
|
||||
const auto resource = Graphics::DecodeTextureResource(words);
|
||||
if (resource.baseAddress == 0) continue;
|
||||
const auto surfaceBytes = Graphics::DescribeSurface(resource).guestBytes;
|
||||
const auto surfaceBytes = Graphics::SurfaceGuestBytes(resource);
|
||||
add(resource.baseAddress, surfaceBytes != 0 ? surfaceBytes : UnknownBytes);
|
||||
add(resource.dccAddress, surfaceBytes != 0 ? surfaceBytes / 256 + 1 : UnknownBytes);
|
||||
}
|
||||
|
||||
@@ -349,7 +349,7 @@ void Driver::execute(Submission& submission) {
|
||||
}
|
||||
timing.Mark("pipeline_prepare");
|
||||
if (pipelined && DrawPipeline::Queue0().Busy() && !keepsDrawPipeline(packet, header, opcode)) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, header == FlipPacketHeader ? 0xffu : opcode);
|
||||
if (pipelined && predicated && DrawPipeline::Queue0().Busy() && DrawPipeline::Queue0().Overlaps(queue.predication.address, queue.predication.operation == 3 ? 8 : 4)) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, opcode);
|
||||
if (pipelined && predicated && DrawPipeline::Queue0().Busy() && DrawPipeline::Queue0().Overlaps(queue.predication.address, Pm4::PredicationBytes(queue.predication))) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, opcode);
|
||||
timing.Mark("pipeline_drain");
|
||||
std::shared_lock deviceUse(deviceReplacement, std::defer_lock);
|
||||
if (opcode != 0x3c && opcode != 0x93 && header != RenderingWaitPacketHeader && header != FlipPacketHeader) deviceUse.lock();
|
||||
@@ -475,6 +475,14 @@ void Driver::execute(Submission& submission) {
|
||||
if (queueTiming) frame->CollectBackground();
|
||||
frame->NoteFlipBatches(batchesAtFlip, unsignaledAtFlip);
|
||||
CaptureTrace::Log("flip frame=%llu submission=%llu offset=%zu batch=%llu unsignaled=%llu", static_cast<unsigned long long>(frameSerial.load()), static_cast<unsigned long long>(submission.serial), cursor, static_cast<unsigned long long>(batchesAtFlip), static_cast<unsigned long long>(unsignaledAtFlip));
|
||||
struct FlipReadying {
|
||||
Driver& driver;
|
||||
std::uint32_t handle;
|
||||
FlipReadying(Driver& owner, std::uint32_t flipHandle) : driver(owner), handle(flipHandle) { driver.beginFlipReady(handle); }
|
||||
FlipReadying(const FlipReadying&) = delete;
|
||||
FlipReadying& operator=(const FlipReadying&) = delete;
|
||||
~FlipReadying() { driver.endFlipReady(handle); }
|
||||
} readying(*this, submission.flipHandles.at(cursor));
|
||||
flipHold.Release();
|
||||
submission.flips.at(cursor)->GpuReady(frame);
|
||||
} else if (opcode == 0x15 || opcode == 0x16) {
|
||||
@@ -547,6 +555,8 @@ void Driver::execute(Submission& submission) {
|
||||
} else if (traceDraws) {
|
||||
std::fprintf(stderr, "[draw] target 0x%llx mask 0x%x ok\n",static_cast<unsigned long long>(color), readRegister(queue.context, 0x8e));
|
||||
}
|
||||
} catch (const DrawCompilePending&) {
|
||||
countSkip(Graphics::DrawSkip::Thrown);
|
||||
} catch (const RefusedDraw& refused) {
|
||||
CaptureTrace::Log("draw-refused submission=%llu offset=%zu reason=%.256s", static_cast<unsigned long long>(submission.serial), cursor, refused.what());
|
||||
countSkip(Graphics::DrawSkip::Thrown);
|
||||
|
||||
@@ -577,6 +577,17 @@ void Driver::releaseFlipHold() {
|
||||
if (flipHolders.load(std::memory_order_acquire) != 0) changed.notify_all();
|
||||
}
|
||||
|
||||
void Driver::beginFlipReady(std::uint32_t handle) {
|
||||
std::lock_guard lock(mutex);
|
||||
++flipsReadying[handle];
|
||||
}
|
||||
|
||||
void Driver::endFlipReady(std::uint32_t handle) {
|
||||
std::lock_guard lock(mutex);
|
||||
const auto found = flipsReadying.find(handle);
|
||||
if (found != flipsReadying.end() && --found->second == 0) flipsReadying.erase(found);
|
||||
}
|
||||
|
||||
void Driver::finishFlipWork(const std::shared_ptr<FlipWork>& work, std::uint64_t workSerial) {
|
||||
std::lock_guard lock(mutex);
|
||||
if (work != nullptr) {
|
||||
@@ -620,6 +631,7 @@ void Driver::reserveOutputs(Submission& submission) {
|
||||
require(submission.queue == 0, "EOP flips on async queues are not implemented");
|
||||
require(eopTokens.insert(token).second, "EOP flip token repeated in a submission");
|
||||
submission.flips.emplace(cursor, flip->second.request);
|
||||
submission.flipHandles.emplace(cursor, flip->second.info.handle);
|
||||
}
|
||||
}
|
||||
noteHeldAtSubmit(submission, cursor);
|
||||
@@ -630,6 +642,7 @@ void Driver::reserveOutputs(Submission& submission) {
|
||||
auto request = output->second->Reserve(info);
|
||||
require(request != nullptr, "video output returned a null flip reservation");
|
||||
submission.flips.emplace(cursor, std::move(request));
|
||||
submission.flipHandles.emplace(cursor, words[1]);
|
||||
}
|
||||
cursor += Pm4::PacketWords(words[0]);
|
||||
}
|
||||
@@ -815,7 +828,7 @@ void Driver::Submit(const Packet* packet, std::uint32_t queue, bool cpuFlip) {
|
||||
checkStopping();
|
||||
require(accepted != std::numeric_limits<std::uint64_t>::max(), "submission serial overflow");
|
||||
reserveOutputs(submission);
|
||||
if (unorderedFlip && capture == nullptr && accepted != 0 && flipsAhead.load(std::memory_order_acquire) == 0) {
|
||||
if (unorderedFlip && capture == nullptr && accepted != 0 && flipsAhead.load(std::memory_order_acquire) == 0 && !flipsReadying.contains(submission.flipHandles.begin()->second)) {
|
||||
const auto now = FrameTiming::Clock::now();
|
||||
auto frame = std::make_shared<FrameTiming>(++frameSerial);
|
||||
frame->IncludeSubmission(accepted, now, now, now, true);
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
#include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
|
||||
#include "CacheKey.hpp"
|
||||
#include "prx/libc/include/HostThreadLocal.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/ShaderPreparation.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/ShaderPreparationScope.hpp"
|
||||
#include "CompiledVariant.hpp"
|
||||
@@ -53,6 +53,7 @@
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include <tuple>
|
||||
#include <unordered_map>
|
||||
#include "Optimization/ShaderStageInputInfo.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/RegistrationPreparationBudget.hpp"
|
||||
@@ -984,14 +985,40 @@ std::string hexText(std::uint64_t value) {
|
||||
return text;
|
||||
}
|
||||
|
||||
std::vector<std::uint32_t> ReadUserDataCallee(std::uint64_t address, std::uint32_t linkRegister, bool allowGetpc = false) {
|
||||
void RecordLinkDependency(std::shared_ptr<ShaderRecompiler::SrtGuestWords> block, std::vector<std::shared_ptr<const ShaderRecompiler::SrtGuestWords>>& dependencies) {
|
||||
if (block->runs.empty()) return;
|
||||
for (const auto& kept : dependencies) {
|
||||
if (kept->runs == block->runs && kept->words == block->words) return;
|
||||
}
|
||||
block->low = block->runs.front().first;
|
||||
block->high = block->runs.back().first + block->runs.back().second * sizeof(std::uint32_t);
|
||||
block->ordered = true;
|
||||
block->stamp = std::make_shared<ShaderRecompiler::SrtStampCell>();
|
||||
PreparedShaderState::UserDataLink::Restamp(*block, &Driver::QueryPendingSpan);
|
||||
dependencies.push_back(std::move(block));
|
||||
}
|
||||
|
||||
void RecordLinkDependency(std::uint64_t address, std::span<const std::byte> bytes, std::vector<std::shared_ptr<const ShaderRecompiler::SrtGuestWords>>& dependencies) {
|
||||
bytes = bytes.first(bytes.size() / sizeof(std::uint32_t) * sizeof(std::uint32_t));
|
||||
if (bytes.empty()) return;
|
||||
auto block = std::make_shared<ShaderRecompiler::SrtGuestWords>();
|
||||
block->words.resize(bytes.size() / sizeof(std::uint32_t));
|
||||
std::memcpy(block->words.data(), bytes.data(), bytes.size());
|
||||
block->runs.emplace_back(address, static_cast<std::uint32_t>(block->words.size()));
|
||||
RecordLinkDependency(std::move(block), dependencies);
|
||||
}
|
||||
|
||||
std::vector<std::uint32_t> ReadUserDataCallee(std::uint64_t address, std::uint32_t linkRegister, std::vector<std::shared_ptr<const ShaderRecompiler::SrtGuestWords>>& dependencies, bool allowGetpc = false) {
|
||||
constexpr std::uint64_t page = 4096u;
|
||||
constexpr std::size_t limitWords = 1024u * 1024u / 4u;
|
||||
if (address % 4u != 0u) throw std::runtime_error("its callee address " + hexText(address) + " is not dword aligned");
|
||||
std::vector<std::uint32_t> words;
|
||||
const auto finish = [&] {
|
||||
const auto length = ShaderRecompiler::UserDataCalleeLength(words, linkRegister, allowGetpc);
|
||||
if (length) words.resize(*length);
|
||||
if (length) {
|
||||
words.resize(*length);
|
||||
RecordLinkDependency(address, std::as_bytes(std::span(words)), dependencies);
|
||||
}
|
||||
return length.has_value();
|
||||
};
|
||||
std::size_t nextCheck = 0;
|
||||
@@ -1012,16 +1039,17 @@ std::vector<std::uint32_t> ReadUserDataCallee(std::uint64_t address, std::uint32
|
||||
throw std::runtime_error("its callee at " + hexText(address) + " does not return within " + std::to_string(limitWords * 4u) + " bytes");
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> ReadGuestBytes(std::uint64_t address, std::uint64_t bytes, const char* what) {
|
||||
std::vector<std::uint8_t> ReadGuestBytes(std::uint64_t address, std::uint64_t bytes, const char* what, std::vector<std::shared_ptr<const ShaderRecompiler::SrtGuestWords>>& dependencies, bool record = true) {
|
||||
if (address > UINTPTR_MAX - bytes || !GuestMemory::Accessible(reinterpret_cast<const void*>(static_cast<std::uintptr_t>(address)), static_cast<std::size_t>(bytes))) {
|
||||
throw std::runtime_error(std::string("its ") + what + " at " + hexText(address) + " + " + hexText(bytes) + " is not readable");
|
||||
}
|
||||
std::vector<std::uint8_t> data(static_cast<std::size_t>(bytes));
|
||||
GuestMemory::Read(address, std::as_writable_bytes(std::span(data)));
|
||||
if (record) RecordLinkDependency(address, std::as_bytes(std::span(data)), dependencies);
|
||||
return data;
|
||||
}
|
||||
|
||||
std::vector<ShaderRecompiler::TableCallee> ReadTableCallees(const ShaderRecompiler::RecompileRequest& request, const ShaderRecompiler::TableCall& call) {
|
||||
std::vector<ShaderRecompiler::TableCallee> ReadTableCallees(const ShaderRecompiler::RecompileRequest& request, const ShaderRecompiler::TableCall& call, std::vector<std::shared_ptr<const ShaderRecompiler::SrtGuestWords>>& dependencies) {
|
||||
constexpr std::uint64_t limitBytes = 64u << 20u;
|
||||
constexpr std::size_t limitCallees = 64u;
|
||||
const auto slot = call.userDataRegister - request.context.userDataBaseRegister;
|
||||
@@ -1033,31 +1061,45 @@ std::vector<ShaderRecompiler::TableCallee> ReadTableCallees(const ShaderRecompil
|
||||
std::memcpy(descriptor.fields.data(), words, sizeof(words));
|
||||
} else {
|
||||
const auto pointer = call.constantPointer ? *call.constantPointer : static_cast<std::uint64_t>(request.context.userData[slot]) | static_cast<std::uint64_t>(request.context.userData[slot + 1u]) << 32u;
|
||||
const auto words = ReadGuestBytes(pointer + call.descriptorOffset, 16u, "call table descriptor");
|
||||
const auto words = ReadGuestBytes(pointer + call.descriptorOffset, 16u, "call table descriptor", dependencies);
|
||||
std::memcpy(descriptor.fields.data(), words.data(), words.size());
|
||||
}
|
||||
if (call.nestedDescriptorOffset) {
|
||||
if (*call.nestedDescriptorOffset + 16ull > descriptor.GetSize()) throw std::runtime_error("the buffer holding its call table descriptor has " + std::to_string(descriptor.GetSize()) + " bytes, too few for offset " + hexText(*call.nestedDescriptorOffset));
|
||||
const auto nested = ReadGuestBytes(descriptor.Base48() + *call.nestedDescriptorOffset, 16u, "nested call table descriptor");
|
||||
const auto nested = ReadGuestBytes(descriptor.Base48() + *call.nestedDescriptorOffset, 16u, "nested call table descriptor", dependencies);
|
||||
std::memcpy(descriptor.fields.data(), nested.data(), nested.size());
|
||||
}
|
||||
const auto bytes = descriptor.GetSize();
|
||||
if (bytes > limitBytes) throw std::runtime_error("its call table of " + std::to_string(bytes) + " bytes is larger than the " + std::to_string(limitBytes) + " bytes that are searched for callees");
|
||||
const auto table = bytes == 0u ? std::vector<std::uint8_t>{} : ReadGuestBytes(descriptor.Base48(), bytes, "call table");
|
||||
const auto table = bytes == 0u ? std::vector<std::uint8_t>{} : ReadGuestBytes(descriptor.Base48(), bytes, "call table", dependencies, false);
|
||||
auto dependency = std::make_shared<ShaderRecompiler::SrtGuestWords>();
|
||||
std::set<std::uint64_t> targets;
|
||||
for (std::uint64_t offset = call.entryOffset; offset + 8u <= bytes; offset += call.entryStride) {
|
||||
std::uint64_t target = 0;
|
||||
std::memcpy(&target, table.data() + offset, sizeof(target));
|
||||
const auto address = descriptor.Base48() + offset;
|
||||
if (!dependency->runs.empty() && address <= dependency->runs.back().first + dependency->runs.back().second * sizeof(std::uint32_t)) {
|
||||
auto& run = dependency->runs.back();
|
||||
run.second = static_cast<std::uint32_t>((address + sizeof(target) - run.first) / sizeof(std::uint32_t));
|
||||
} else {
|
||||
dependency->runs.emplace_back(address, 2u);
|
||||
}
|
||||
if (target != 0u) targets.insert(target);
|
||||
if (call.entryStride == 0u) break;
|
||||
}
|
||||
for (const auto& [address, count] : dependency->runs) {
|
||||
const auto offset = dependency->words.size();
|
||||
dependency->words.resize(offset + count);
|
||||
std::memcpy(dependency->words.data() + offset, table.data() + address - descriptor.Base48(), count * sizeof(std::uint32_t));
|
||||
}
|
||||
RecordLinkDependency(std::move(dependency), dependencies);
|
||||
if (targets.size() > limitCallees) throw std::runtime_error("its call table holds " + std::to_string(targets.size()) + " distinct targets; at most " + std::to_string(limitCallees) + " are linked");
|
||||
std::vector<ShaderRecompiler::TableCallee> callees;
|
||||
for (const auto target : targets) callees.push_back({target, ReadUserDataCallee(target, call.linkRegister, true)});
|
||||
for (const auto target : targets) callees.push_back({target, ReadUserDataCallee(target, call.linkRegister, dependencies, true)});
|
||||
return callees;
|
||||
}
|
||||
|
||||
std::shared_ptr<const ShaderRecompiler::LinkedCalls> LinkUserDataCallees(const ShaderRecompiler::RecompileRequest& request, const ShaderSnapshot& snapshot, std::size_t codeOffset) {
|
||||
std::shared_ptr<const PreparedShaderState::UserDataLink> LinkUserDataCallees(const ShaderRecompiler::RecompileRequest& request, const ShaderSnapshot& snapshot, std::size_t codeOffset) {
|
||||
const bool gcnVertex = ShaderRecompiler::GcnGuestShaders() && request.shader.stage == ShaderRecompiler::ShaderStage::Vertex;
|
||||
if (request.shader.stage != ShaderRecompiler::ShaderStage::Compute && !gcnVertex) return nullptr;
|
||||
const auto code = request.shader.code;
|
||||
@@ -1070,16 +1112,16 @@ std::shared_ptr<const ShaderRecompiler::LinkedCalls> LinkUserDataCallees(const S
|
||||
const auto sameProgram = [&](const PreparedShaderState::UserDataLink& link) {
|
||||
return link.codeOffset == codeOffset && link.userDataBaseRegister == swappc.userDataBaseRegister && link.userDataCount == swappc.userDataCount && link.waveSize == swappc.waveSize;
|
||||
};
|
||||
std::vector<std::uint32_t> current;
|
||||
const auto unchanged = [&](const PreparedShaderState::UserDataLink& link) {
|
||||
for (std::size_t index = 0; index < link.callees.size(); ++index) {
|
||||
const auto address = addressOf(link.sites->calls[index]);
|
||||
const auto& words = link.code[index];
|
||||
if (address != link.callees[index] || !GuestMemory::Accessible(reinterpret_cast<const void*>(static_cast<std::uintptr_t>(address)), words.size() * 4u)) return false;
|
||||
current.resize(words.size());
|
||||
GuestMemory::Read(address, std::as_writable_bytes(std::span(current)));
|
||||
if (current != words) return false;
|
||||
if (address != link.callees[index]) return false;
|
||||
const auto bytes = std::as_bytes(std::span(link.code[index]));
|
||||
GuestMemory::GuardRead(address, bytes.size());
|
||||
GuestMemory::FlushGpuWrites(address, bytes.size());
|
||||
if (GuestMemory::CompareMapped(address, bytes) != GuestMemory::Compare::Equal) return false;
|
||||
}
|
||||
if (!link.sites->tableCalls.empty() && !std::ranges::equal(link.tableUserData, request.context.userData)) return false;
|
||||
return true;
|
||||
};
|
||||
auto& prepared = *snapshot.prepared;
|
||||
@@ -1091,7 +1133,11 @@ std::shared_ptr<const ShaderRecompiler::LinkedCalls> LinkUserDataCallees(const S
|
||||
std::shared_ptr<const UserDataCallSites> sites;
|
||||
for (auto candidate = candidates.rbegin(); candidate != candidates.rend(); ++candidate) {
|
||||
sites = candidate->sites;
|
||||
if (candidate->linked != nullptr && unchanged(*candidate)) return candidate->linked;
|
||||
if (candidate->linked != nullptr && unchanged(*candidate)) {
|
||||
auto reused = std::make_shared<PreparedShaderState::UserDataLink>(*candidate);
|
||||
for (std::size_t index = 0; index < reused->callees.size(); ++index) RecordLinkDependency(reused->callees[index], std::as_bytes(std::span(reused->code[index])), reused->dependencies);
|
||||
return reused;
|
||||
}
|
||||
}
|
||||
if (sites == nullptr) {
|
||||
auto found = std::make_shared<UserDataCallSites>();
|
||||
@@ -1104,23 +1150,25 @@ std::shared_ptr<const ShaderRecompiler::LinkedCalls> LinkUserDataCallees(const S
|
||||
const auto& calls = sites->calls;
|
||||
const auto& tableCalls = sites->tableCalls;
|
||||
PreparedShaderState::UserDataLink link{codeOffset, swappc.userDataBaseRegister, swappc.userDataCount, swappc.waveSize, sites, {}, {}, nullptr};
|
||||
const auto remember = [&] {
|
||||
const auto remember = [&](const PreparedShaderState::UserDataLink& retained) {
|
||||
std::lock_guard lock(prepared.mutex);
|
||||
auto& links = prepared.userDataLinks;
|
||||
if (link.linked == nullptr && std::any_of(links.begin(), links.end(), sameProgram)) return;
|
||||
if (retained.linked == nullptr && std::any_of(links.begin(), links.end(), sameProgram)) return;
|
||||
if (std::count_if(links.begin(), links.end(), sameProgram) >= static_cast<std::ptrdiff_t>(UserDataLinksPerProgram)) links.erase(std::find_if(links.begin(), links.end(), sameProgram));
|
||||
links.push_back(link);
|
||||
auto memo = retained;
|
||||
memo.dependencies = decltype(memo.dependencies){};
|
||||
links.push_back(std::move(memo));
|
||||
};
|
||||
if (calls.empty() && tableCalls.empty()) {
|
||||
link.linked = std::make_shared<const ShaderRecompiler::LinkedCalls>();
|
||||
remember();
|
||||
return link.linked;
|
||||
remember(link);
|
||||
return std::make_shared<const PreparedShaderState::UserDataLink>(std::move(link));
|
||||
}
|
||||
std::vector<std::vector<std::uint32_t>> callees;
|
||||
for (const auto& call : calls) {
|
||||
const auto address = addressOf(call);
|
||||
try {
|
||||
callees.push_back(ReadUserDataCallee(address, call.linkRegister));
|
||||
callees.push_back(ReadUserDataCallee(address, call.linkRegister, link.dependencies));
|
||||
} catch (const std::exception& error) {
|
||||
throw std::runtime_error("AGC driver: compute shader " + hexText(request.shader.codeAddress) + " calls user data s[" + std::to_string(call.userDataRegister) + ":" +
|
||||
std::to_string(call.userDataRegister + 1u) + "] at program counter " + hexText(call.programCounter) + ", but " + error.what());
|
||||
@@ -1129,25 +1177,82 @@ std::shared_ptr<const ShaderRecompiler::LinkedCalls> LinkUserDataCallees(const S
|
||||
std::vector<std::vector<ShaderRecompiler::TableCallee>> tableCallees;
|
||||
for (const auto& call : tableCalls) {
|
||||
try {
|
||||
tableCallees.push_back(ReadTableCallees(request, call));
|
||||
tableCallees.push_back(ReadTableCallees(request, call, link.dependencies));
|
||||
} catch (const std::exception& error) {
|
||||
throw std::runtime_error("AGC driver: compute shader " + hexText(request.shader.codeAddress) + " calls a target loaded from a table at program counter " + hexText(call.programCounter) + ", but " + error.what());
|
||||
}
|
||||
}
|
||||
auto linked = std::make_shared<const ShaderRecompiler::LinkedCalls>(ShaderRecompiler::LinkCalls(program, calls, callees, tableCalls, tableCallees));
|
||||
if (!tableCalls.empty()) {
|
||||
remember();
|
||||
return linked;
|
||||
}
|
||||
if (!tableCalls.empty()) link.tableUserData.assign(request.context.userData.begin(), request.context.userData.end());
|
||||
for (const auto& call : calls) link.callees.push_back(addressOf(call));
|
||||
link.code = std::move(callees);
|
||||
link.linked = linked;
|
||||
remember();
|
||||
return linked;
|
||||
if (tableCalls.empty()) remember(link);
|
||||
else remember({codeOffset, swappc.userDataBaseRegister, swappc.userDataCount, swappc.waveSize, sites});
|
||||
return std::make_shared<const PreparedShaderState::UserDataLink>(std::move(link));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void PreparedShaderState::UserDataLink::AppendRegions(std::vector<ShaderRecompiler::MemoryRegion>& regions) const {
|
||||
for (const auto& dependency : dependencies) {
|
||||
std::size_t offset = 0;
|
||||
for (const auto& [address, count] : dependency->runs) {
|
||||
regions.push_back({address, std::as_bytes(std::span(dependency->words).subspan(offset, count))});
|
||||
offset += count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void PreparedShaderState::UserDataLink::VouchRegions(std::span<const ShaderRecompiler::MemoryRegion> regions, std::vector<VouchedRegions>& vouched) const {
|
||||
const auto publish = Graphics::Recorder::PublishGeneration();
|
||||
const auto pending = Graphics::StorageTexture::PendingSerial();
|
||||
const auto forget = GuestMemory::ForgetSerial();
|
||||
const auto layout = GuestAllocations::GuestAllocationsGeneration_nid_postfix();
|
||||
vouched.clear();
|
||||
if ((forget & 1u) != 0) return;
|
||||
std::vector<SharedWords> shared;
|
||||
std::size_t first = 0;
|
||||
for (std::size_t index = 0; index < regions.size(); ++index) {
|
||||
AppendSharedWords(shared, index, first, regions[index].bytes, dependencies);
|
||||
first += regions[index].bytes.size() / sizeof(std::uint32_t);
|
||||
}
|
||||
VouchSharedRegions(shared, regions.size(), &Driver::QueryPendingSpan, vouched, dependencies, &Restamp);
|
||||
if (Graphics::Recorder::PublishGeneration() != publish || Graphics::StorageTexture::PendingSerial() != pending || GuestMemory::ForgetSerial() != forget || GuestAllocations::GuestAllocationsGeneration_nid_postfix() != layout) vouched.clear();
|
||||
}
|
||||
|
||||
bool PreparedShaderState::UserDataLink::Restamp(const ShaderRecompiler::SrtGuestWords& block, ShaderMemory::PendingWriteQuery pending) {
|
||||
if (block.stamp == nullptr || block.runs.empty() || block.low >= block.high) return false;
|
||||
const auto bytes = static_cast<std::size_t>(block.high - block.low);
|
||||
if (pending != nullptr && pending(block.low, bytes, {}) != ShaderMemory::PendingWrite::None) return false;
|
||||
GuestMemory::GuardRead(block.low, bytes);
|
||||
GuestMemory::FlushGpuWrites(block.low, bytes);
|
||||
const auto publish = Graphics::Recorder::PublishGeneration();
|
||||
const auto pendingSerial = Graphics::StorageTexture::PendingSerial();
|
||||
const auto forget = GuestMemory::ForgetSerial();
|
||||
const auto layout = GuestAllocations::GuestAllocationsGeneration_nid_postfix();
|
||||
const auto generation = GuestMemory::CollectWritesUncached(block.low, bytes);
|
||||
if (generation == 0 || (forget & 1u) != 0) return false;
|
||||
std::size_t offset = 0;
|
||||
for (const auto& [address, count] : block.runs) {
|
||||
const auto words = std::span(block.words).subspan(offset, count);
|
||||
if (GuestMemory::CompareMapped(address, std::as_bytes(words)) != GuestMemory::Compare::Equal) return false;
|
||||
offset += count;
|
||||
}
|
||||
if (offset != block.words.size()) return false;
|
||||
if (GuestMemory::CollectWritesUncached(block.low, bytes) == 0 || !GuestMemory::UnchangedSince(block.low, bytes, generation)) return false;
|
||||
if (pending != nullptr && pending(block.low, bytes, {}) != ShaderMemory::PendingWrite::None) return false;
|
||||
if (Graphics::Recorder::PublishGeneration() != publish || Graphics::StorageTexture::PendingSerial() != pendingSerial || GuestMemory::ForgetSerial() != forget || GuestAllocations::GuestAllocationsGeneration_nid_postfix() != layout) return false;
|
||||
ShaderRecompiler::StoreStamp(block, {generation, layout});
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PreparedShaderState::UserDataLink::Overlaps(std::uint64_t address, std::size_t bytes) const {
|
||||
return std::any_of(dependencies.begin(), dependencies.end(), [&](const auto& dependency) {
|
||||
return std::any_of(dependency->runs.begin(), dependency->runs.end(), [&](const auto& run) { return address < run.first + run.second * sizeof(std::uint32_t) && run.first < address + bytes; });
|
||||
});
|
||||
}
|
||||
|
||||
bool StageLinksUserDataCallees(const ShaderSnapshot& snapshot, std::size_t codeOffset) {
|
||||
if (!snapshot.prepared) return false;
|
||||
std::lock_guard lock(snapshot.prepared->mutex);
|
||||
@@ -1156,11 +1261,113 @@ bool StageLinksUserDataCallees(const ShaderSnapshot& snapshot, std::size_t codeO
|
||||
});
|
||||
}
|
||||
|
||||
ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request) {
|
||||
std::shared_ptr<OwnedRecompileRequest> OwnRecompileRequest(const ShaderRecompiler::RecompileRequest& source, ShaderRecompiler::MemoryRegionView memory) {
|
||||
auto owned = std::make_shared<OwnedRecompileRequest>();
|
||||
owned->request = source;
|
||||
owned->code.assign(source.shader.code.begin(), source.shader.code.end());
|
||||
owned->header.assign(source.shader.header.begin(), source.shader.header.end());
|
||||
owned->userData.assign(source.context.userData.begin(), source.context.userData.end());
|
||||
owned->request.shader.code = owned->code;
|
||||
owned->request.shader.header = owned->header;
|
||||
owned->request.context.userData = owned->userData;
|
||||
owned->fallbacks.assign(source.context.linkedCallFallbacks.begin(), source.context.linkedCallFallbacks.end());
|
||||
owned->request.context.linkedCallFallbacks = owned->fallbacks;
|
||||
owned->regionBytes.reserve(memory.size());
|
||||
owned->regions.reserve(memory.size());
|
||||
for (const auto& region : memory) {
|
||||
const auto& bytes = owned->regionBytes.emplace_back(region.bytes.begin(), region.bytes.end());
|
||||
owned->regions.push_back({region.guestAddress, bytes});
|
||||
}
|
||||
owned->request.context.memory = std::span<const ShaderRecompiler::MemoryRegion>(owned->regions);
|
||||
if (owned->request.graphics) {
|
||||
const auto programs = owned->request.graphics->linkedPrograms;
|
||||
owned->linkedWords.reserve(programs.size() * 2u);
|
||||
owned->linkedHeaders.reserve(programs.size());
|
||||
owned->linked.reserve(programs.size());
|
||||
for (const auto& program : programs) {
|
||||
auto copy = program;
|
||||
copy.binary.code = owned->linkedWords.emplace_back(program.binary.code.begin(), program.binary.code.end());
|
||||
copy.binary.header = owned->linkedHeaders.emplace_back(program.binary.header.begin(), program.binary.header.end());
|
||||
copy.userData = owned->linkedWords.emplace_back(program.userData.begin(), program.userData.end());
|
||||
owned->linked.push_back(copy);
|
||||
}
|
||||
owned->request.graphics->linkedPrograms = owned->linked;
|
||||
}
|
||||
return owned;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct PendingPreparation {
|
||||
std::mutex mutex;
|
||||
bool finished = false;
|
||||
std::shared_ptr<const ShaderRecompiler::SourceHandle> handle;
|
||||
std::exception_ptr failure;
|
||||
};
|
||||
|
||||
struct PendingPreparations {
|
||||
std::mutex mutex;
|
||||
std::map<std::tuple<const ShaderSnapshot*, std::size_t, std::uint64_t>, std::shared_ptr<PendingPreparation>> byKey;
|
||||
};
|
||||
|
||||
PendingPreparations& pendingPreparations() {
|
||||
static auto* pending = new PendingPreparations();
|
||||
return *pending;
|
||||
}
|
||||
|
||||
std::shared_ptr<const ShaderRecompiler::SourceHandle> PrepareInBackground(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& source, std::span<const std::uint64_t> key) {
|
||||
const auto keyWords = std::span<const std::uint32_t>(reinterpret_cast<const std::uint32_t*>(key.data()), key.size() * 2u);
|
||||
const auto flags = (source.context.convertedSamples ? 1u : 0u) | (source.context.layerRowSamples ? 2u : 0u);
|
||||
const std::tuple id{&snapshot, codeOffset, ShaderRecompiler::HashSpirvWords(source.shader.code, ShaderRecompiler::HashSpirvWords(keyWords, flags))};
|
||||
auto& pending = pendingPreparations();
|
||||
std::shared_ptr<PendingPreparation> job;
|
||||
bool started = false;
|
||||
{
|
||||
std::lock_guard lock(pending.mutex);
|
||||
auto& slot = pending.byKey[id];
|
||||
if (slot == nullptr) {
|
||||
slot = std::make_shared<PendingPreparation>();
|
||||
started = true;
|
||||
}
|
||||
job = slot;
|
||||
}
|
||||
if (started) {
|
||||
const auto owned = OwnRecompileRequest(source, source.context.memory);
|
||||
SubmitLibraryPrebuild([job, owned] {
|
||||
std::shared_ptr<const ShaderRecompiler::SourceHandle> handle;
|
||||
std::exception_ptr failure;
|
||||
try {
|
||||
handle = PrepareShaderWithDiagnostics(owned->request);
|
||||
} catch (...) {
|
||||
failure = std::current_exception();
|
||||
}
|
||||
std::lock_guard lock(job->mutex);
|
||||
job->handle = std::move(handle);
|
||||
job->failure = failure;
|
||||
job->finished = true;
|
||||
});
|
||||
}
|
||||
{
|
||||
std::lock_guard lock(job->mutex);
|
||||
if (!job->finished) throw DrawCompilePending("the draw's shader is still being prepared in the background");
|
||||
}
|
||||
{
|
||||
std::lock_guard lock(pending.mutex);
|
||||
if (const auto found = pending.byKey.find(id); found != pending.byKey.end() && found->second == job) pending.byKey.erase(found);
|
||||
}
|
||||
if (job->failure != nullptr) std::rethrow_exception(job->failure);
|
||||
return job->handle;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, bool deferPreparation, std::shared_ptr<const PreparedShaderState::UserDataLink>* linking) {
|
||||
require(codeOffset < snapshot.code.size(), "prepared shader code offset is outside the snapshot");
|
||||
const auto code = std::span(snapshot.code).subspan(codeOffset);
|
||||
require(request.shader.code.data() == code.data() && request.shader.code.size() == code.size(), "prepared invocation does not refer to registered code");
|
||||
const auto shared = LinkUserDataCallees(request, snapshot, codeOffset);
|
||||
const auto link = LinkUserDataCallees(request, snapshot, codeOffset);
|
||||
if (linking != nullptr) *linking = link != nullptr && !link->dependencies.empty() ? link : nullptr;
|
||||
const auto shared = link != nullptr ? link->linked : nullptr;
|
||||
ShaderRecompiler::LinkedCalls tail;
|
||||
if (shared == nullptr || shared->code.empty()) tail.code = LinkGraphicsUserDataTail(request, snapshot);
|
||||
const auto& linked = shared != nullptr && tail.code.empty() ? *shared : tail;
|
||||
@@ -1190,16 +1397,21 @@ ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& s
|
||||
}
|
||||
NoteOwnPreparation(preparedAtUse);
|
||||
ReportPreparedAtUse(snapshot, source);
|
||||
auto handle = PrepareShaderWithDiagnostics(source);
|
||||
std::shared_ptr<const ShaderRecompiler::SourceHandle> handle = deferPreparation ? PrepareInBackground(snapshot, codeOffset, source, key) : PrepareShaderWithDiagnostics(source);
|
||||
invocationRequest = source;
|
||||
invocationRequest.shader.code = ShaderRecompiler::GetPreparedCode(*handle);
|
||||
auto invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(invocationRequest, handle, key);
|
||||
if (!invocation.has_value() && deferPreparation) {
|
||||
handle = PrepareShaderWithDiagnostics(source);
|
||||
invocationRequest.shader.code = ShaderRecompiler::GetPreparedCode(*handle);
|
||||
invocation = ShaderRecompiler::PreparedShaderInvocation::TryCreate(invocationRequest, handle, key);
|
||||
}
|
||||
if (!invocation.has_value()) throw std::runtime_error("AGC driver: an artifact prepared at use does not match its invocation");
|
||||
snapshot.prepared->entries.push_back({codeOffset, std::move(handle)});
|
||||
return std::move(*invocation);
|
||||
}
|
||||
|
||||
std::shared_ptr<const ShaderRecompiler::ResourceCapture> CaptureInvocation(ShaderMemory& memory, const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, ShaderRecompiler::PreparedShaderInvocation& invocation) {
|
||||
std::shared_ptr<const ShaderRecompiler::ResourceCapture> CaptureInvocation(ShaderMemory& memory, const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request, ShaderRecompiler::PreparedShaderInvocation& invocation, std::shared_ptr<const PreparedShaderState::UserDataLink>* linking) {
|
||||
const auto record = [&](std::vector<std::size_t>& offsets) {
|
||||
std::lock_guard lock(snapshot.prepared->mutex);
|
||||
if (std::ranges::find(offsets, codeOffset) == offsets.end()) offsets.push_back(codeOffset);
|
||||
@@ -1214,7 +1426,7 @@ std::shared_ptr<const ShaderRecompiler::ResourceCapture> CaptureInvocation(Shade
|
||||
if (invocation.Request().context.layerRowSamples) throw;
|
||||
record(snapshot.prepared->layerRowSamples);
|
||||
}
|
||||
invocation = InvocationFor(snapshot, codeOffset, request);
|
||||
invocation = InvocationFor(snapshot, codeOffset, request, false, linking);
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
@@ -2093,7 +2305,7 @@ std::vector<PreparedGraphicsStage> PrepareGraphicsStages(const DrawDecode& decod
|
||||
std::vector<PreparedGraphicsStage> prepared;
|
||||
std::uint32_t pushOffset = 0;
|
||||
const bool fixedSlots = target.fixedPushSlots;
|
||||
const auto capacity = Graphics::StagePushLimit(decoded.state.stages, 0, decoded.state.depthRemap.mode != 0u);
|
||||
const bool hasFragment = !decoded.roles.empty() && decoded.roles.back() == ShaderRecompiler::ProgramRole::Fragment;
|
||||
for (std::size_t index = 0; index < decoded.programs.size(); ++index) {
|
||||
if (decoded.roles[index] == ShaderRecompiler::ProgramRole::GeometryBack) continue;
|
||||
const auto& program = decoded.programs[index];
|
||||
@@ -2101,10 +2313,8 @@ std::vector<PreparedGraphicsStage> PrepareGraphicsStages(const DrawDecode& decod
|
||||
const auto wave = Graphics::StageWaveSize(decoded.state.stages, program.binary.stage);
|
||||
pushOffset = Graphics::StagePushOffset(pushOffset, program.binary.stage, fixedSlots);
|
||||
const auto offset = pushOffset;
|
||||
auto room = (fixedSlots && fragment ? Graphics::PipelinePushSlotBytes : capacity) - pushOffset % Graphics::PipelinePushSlotBytes;
|
||||
if (decoded.state.depthRemap.mode != 0u && offset < Graphics::PipelinePushSlotBytes) {
|
||||
room = std::min(room, ShaderRecompiler::DepthRemapPushOffsetBytes - offset);
|
||||
}
|
||||
require(pushOffset <= Graphics::PushBlockBytes(fixedSlots), "prepared stage push constant offset exceeds the pipeline push constant block");
|
||||
const auto room = Graphics::StagePushBudget(Graphics::StagePushLimit(decoded.state.stages, pushOffset, decoded.state.depthRemap.mode != 0u), pushOffset, program.binary.stage, fixedSlots, hasFragment);
|
||||
if (deferUnprepared && DeferFailedRegistration(*program.snapshot)) {
|
||||
prepared.push_back({program.snapshot, {program.codeOffset, nullptr}, program.binary.stage, offset, nullptr});
|
||||
continue;
|
||||
@@ -2445,6 +2655,20 @@ std::uint64_t NullPixelProgramAddress() {
|
||||
|
||||
alignas(256) static const std::uint32_t DepthCopyMultisamplePixelCode[64] = {0x360604ffu, 0x0000ffffu, 0x2c080490u, 0x7e0a0208u, 0xf0000130u, 0x00000603u, 0xbf8c3f70u, 0xf8001801u, 0x00000006u, 0xbf810000u};
|
||||
alignas(256) static const std::uint32_t DepthCopySinglePixelCode[64] = {0x360604ffu, 0x0000ffffu, 0x2c080490u, 0xf0000108u, 0x00000603u, 0xbf8c3f70u, 0xf8001801u, 0x00000006u, 0xbf810000u};
|
||||
alignas(256) static const std::uint32_t StencilCopyMultisamplePixelCode[64] = {0x360604ffu, 0x0000ffffu, 0x2c080490u, 0x7e0a0208u, 0xf0000130u, 0x00000603u, 0xbf8c3f70u, 0xf8001803u, 0x00000606u, 0xbf810000u};
|
||||
alignas(256) static const std::uint32_t StencilCopySinglePixelCode[64] = {0x360604ffu, 0x0000ffffu, 0x2c080490u, 0xf0000108u, 0x00000603u, 0xbf8c3f70u, 0xf8001803u, 0x00000606u, 0xbf810000u};
|
||||
static Shader StencilCopyPixelHeader(const std::uint32_t* code) {
|
||||
Shader shader{};
|
||||
shader.file_header = 0x34333231u;
|
||||
shader.version = 0x18u;
|
||||
shader.code = code;
|
||||
shader.header_size = sizeof(Shader);
|
||||
shader.shader_size = 64u * sizeof(std::uint32_t);
|
||||
shader.type = 1;
|
||||
return shader;
|
||||
}
|
||||
static const Shader StencilCopyMultisamplePixelShader = StencilCopyPixelHeader(StencilCopyMultisamplePixelCode);
|
||||
static const Shader StencilCopySinglePixelShader = StencilCopyPixelHeader(StencilCopySinglePixelCode);
|
||||
static const Shader DepthCopyMultisamplePixelShader = [] {
|
||||
Shader shader{};
|
||||
shader.file_header = 0x34333231u;
|
||||
@@ -2470,12 +2694,16 @@ std::uint64_t DepthCopyPixelProgramAddress(bool multisampled) {
|
||||
return reinterpret_cast<std::uintptr_t>(multisampled ? DepthCopyMultisamplePixelCode : DepthCopySinglePixelCode);
|
||||
}
|
||||
|
||||
std::uint64_t StencilCopyPixelProgramAddress(bool multisampled) {
|
||||
return reinterpret_cast<std::uintptr_t>(multisampled ? StencilCopyMultisamplePixelCode : StencilCopySinglePixelCode);
|
||||
}
|
||||
|
||||
std::uint32_t DepthCopyPixelUserWords(bool multisampled) {
|
||||
return multisampled ? 9u : 8u;
|
||||
}
|
||||
|
||||
bool DriverOwnedProgram(std::uint64_t codeAddress) {
|
||||
return codeAddress == NullPixelProgramAddress() || codeAddress == DepthCopyPixelProgramAddress(false) || codeAddress == DepthCopyPixelProgramAddress(true);
|
||||
return codeAddress == NullPixelProgramAddress() || codeAddress == DepthCopyPixelProgramAddress(false) || codeAddress == DepthCopyPixelProgramAddress(true) || codeAddress == StencilCopyPixelProgramAddress(false) || codeAddress == StencilCopyPixelProgramAddress(true);
|
||||
}
|
||||
|
||||
void Driver::ResolveGraphicsAbi(const Shader* vertex, const Shader* pixel, std::uint32_t primitiveType) {
|
||||
@@ -2637,6 +2865,25 @@ ShaderSnapshot PrepareDepthCopyPixelProgram(bool multisampled) {
|
||||
return copy;
|
||||
}
|
||||
|
||||
ShaderSnapshot PrepareStencilCopyPixelProgram(bool multisampled) {
|
||||
const auto& shader = multisampled ? StencilCopyMultisamplePixelShader : StencilCopySinglePixelShader;
|
||||
const auto* code = multisampled ? StencilCopyMultisamplePixelCode : StencilCopySinglePixelCode;
|
||||
ShaderSnapshot copy{StencilCopyPixelProgramAddress(multisampled), reinterpret_cast<std::uintptr_t>(&shader), shader.type, {}, {}};
|
||||
copy.code.assign(code, code + 64);
|
||||
copy.header.resize(sizeof(Shader));
|
||||
std::memcpy(copy.header.data(), &shader, sizeof(Shader));
|
||||
auto state = DecodeRegisteredState(copy);
|
||||
state.shader.insert_or_assign(0x008u, static_cast<std::uint32_t>(copy.codeAddress >> 8u));
|
||||
state.shader.insert_or_assign(0x009u, static_cast<std::uint32_t>(copy.codeAddress >> 40u));
|
||||
state.shader.insert_or_assign(0x00bu, DepthCopyPixelUserWords(multisampled) << 1u);
|
||||
state.context.insert_or_assign(0x1b3u, 0x8002u);
|
||||
state.context.insert_or_assign(0x1b4u, 0x8002u);
|
||||
state.context.insert_or_assign(0x1c5u, 2u);
|
||||
copy.registeredState = std::make_shared<const RegisteredShaderState>(std::move(state));
|
||||
copy.prepared->deferred = true;
|
||||
return copy;
|
||||
}
|
||||
|
||||
std::shared_ptr<const ShaderRegistry> Driver::RegisteredShaders() {
|
||||
std::lock_guard lock(mutex);
|
||||
return shaders;
|
||||
@@ -2749,6 +2996,7 @@ void Driver::RegisterShader(const Shader* shader) {
|
||||
}
|
||||
for (const bool multisampled : {false, true}) {
|
||||
if (shaders->find(DepthCopyPixelProgramAddress(multisampled)) == shaders->end()) PublishRegisteredShader(shaders, std::make_shared<const ShaderSnapshot>(PrepareDepthCopyPixelProgram(multisampled)));
|
||||
if (shaders->find(StencilCopyPixelProgramAddress(multisampled)) == shaders->end()) PublishRegisteredShader(shaders, std::make_shared<const ShaderSnapshot>(PrepareStencilCopyPixelProgram(multisampled)));
|
||||
}
|
||||
transaction.Commit();
|
||||
if (preparation != nullptr) PrepareRegisteredInBackground(published, std::move(preparation));
|
||||
|
||||
+9
-2
@@ -208,10 +208,17 @@ void Driver::runCaptureCheckHook() {
|
||||
if (const auto hook = captureCheckHook.load(std::memory_order_acquire)) hook();
|
||||
}
|
||||
|
||||
bool Driver::capturedMemoryChanged(std::span<const ShaderRecompiler::MemoryRegion> regions, std::span<Graphics::GuestMemorySnapshot> compared) {
|
||||
bool Driver::capturedMemoryChanged(std::span<const ShaderRecompiler::MemoryRegion> regions, std::span<Graphics::GuestMemorySnapshot> compared, const PreparedShaderState::UserDataLink* linking) {
|
||||
if (recapturing()) return false;
|
||||
const bool mark = compared.size() == regions.size();
|
||||
for (std::size_t i = 0; i < regions.size(); ++i) {
|
||||
std::vector<VouchedRegions> vouched;
|
||||
if (linking != nullptr && vouchedValidation() && !validateLegacy()) linking->VouchRegions(regions, vouched);
|
||||
for (std::size_t i = 0, range = 0; i < regions.size(); ++i) {
|
||||
while (range < vouched.size() && i >= vouched[range].end) ++range;
|
||||
if (range < vouched.size() && i >= vouched[range].begin) {
|
||||
if (mark) compared[i].compared = true;
|
||||
continue;
|
||||
}
|
||||
const auto outcome = GuestMemory::CompareMapped(regions[i].guestAddress, regions[i].bytes);
|
||||
if (outcome == GuestMemory::Compare::Differs) return true;
|
||||
if (mark && outcome == GuestMemory::Compare::Equal) compared[i].compared = true;
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/Float16NanProbe.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace AgcDriver {
|
||||
namespace {
|
||||
|
||||
using ShaderRecompiler::ShaderStage;
|
||||
|
||||
constexpr std::uint32_t Threads = 256;
|
||||
constexpr std::uint32_t Inputs = 4;
|
||||
constexpr std::uint32_t Results = 16;
|
||||
constexpr std::uint32_t Combinations = 4096;
|
||||
alignas(256) std::array<std::uint32_t, Threads * Inputs> Input{};
|
||||
alignas(256) std::array<std::uint32_t, Threads * Results> Output{};
|
||||
|
||||
alignas(256) constexpr std::array<std::uint32_t, 26> PackedCode{
|
||||
0x34020084u, 0x34060085u, 0xe0381000u, 0x80000401u, 0xbf8c3f70u,
|
||||
0xcc0f400au, 0x18020b04u,
|
||||
0xcc10400bu, 0x18020b04u,
|
||||
0xcc0e400cu, 0x1c1a0b04u,
|
||||
0xcc0f4a0du, 0x30020b04u,
|
||||
0xcc10c00eu, 0x18020d04u,
|
||||
0xcc0e330fu, 0x8c1a0b04u,
|
||||
0x7e200306u, 0x78200b04u,
|
||||
0xcc0ec011u, 0x3c1a0f04u,
|
||||
0xe0781000u, 0x80010a03u, 0xe0781010u, 0x80010e03u, 0xbf810000u,
|
||||
};
|
||||
constexpr std::uint32_t PackedResults = 8;
|
||||
|
||||
alignas(256) constexpr std::array<std::uint32_t, 41> ScalarCode{
|
||||
0x34020084u, 0x34060086u, 0xe0381000u, 0x80000401u, 0xbf8c3f70u,
|
||||
0x64140b04u,
|
||||
0x66160b04u,
|
||||
0x68180b04u,
|
||||
0x6a1a0b04u,
|
||||
0xd74b000eu, 0x041a0b04u,
|
||||
0xd74b980fu, 0x041a0b04u,
|
||||
0xd74b3110u, 0xc4160d04u,
|
||||
0x7e220306u, 0x6c220b04u,
|
||||
0x6e240b04u, 0x00003d55u,
|
||||
0x70260b04u, 0x00000001u,
|
||||
0xd74ba214u, 0x241a0b04u,
|
||||
0x662a08f2u,
|
||||
0xd5328116u, 0x20020b04u,
|
||||
0xd5350217u, 0x40020d04u,
|
||||
0xd5338018u, 0x00020b04u,
|
||||
0xd5340019u, 0x20020b04u,
|
||||
0xe0781000u, 0x80010a03u, 0xe0781010u, 0x80010e03u, 0xe0781020u, 0x80011203u, 0xe0781030u, 0x80011603u, 0xbf810000u,
|
||||
};
|
||||
constexpr std::uint32_t ScalarFmaFirst = 4;
|
||||
constexpr std::uint32_t ScalarFmaLast = 10;
|
||||
|
||||
constexpr std::array<std::uint32_t, 16> Halves{
|
||||
0x7e00u, 0xfe00u, 0xff2au, 0x7d55u, 0xfc01u, 0x7c01u, 0x7c00u, 0xfc00u,
|
||||
0x0000u, 0x8000u, 0x0001u, 0x0400u, 0x3c00u, 0xbc00u, 0x3555u, 0x7bffu,
|
||||
};
|
||||
|
||||
std::array<std::uint32_t, 4> BufferDescriptor(const void* data, std::uint32_t bytes) {
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(data);
|
||||
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu), bytes, 0x31016facu};
|
||||
}
|
||||
|
||||
bool IsNan16(std::uint32_t half) {
|
||||
return (half & 0x7fffu) > 0x7c00u;
|
||||
}
|
||||
|
||||
std::uint32_t Half(std::uint32_t combination, std::uint32_t operand) {
|
||||
return Halves[(combination >> (operand * 4u)) & 15u];
|
||||
}
|
||||
|
||||
void FillRows(std::uint32_t first) {
|
||||
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
|
||||
const std::uint32_t low = (first + tid) % Combinations;
|
||||
const std::uint32_t high = Combinations - 1u - low;
|
||||
for (std::uint32_t operand = 0; operand < Inputs; ++operand) {
|
||||
const std::uint32_t lowOperand = operand < 3u ? operand : 1u;
|
||||
const std::uint32_t highOperand = operand < 3u ? operand : 2u;
|
||||
Input[tid * Inputs + operand] = Half(low, lowOperand) | (Half(high, highOperand) << 16u);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::uint32_t> Run(VulkanDevice& device, const ShaderRecompiler::RecompileResult& result, std::span<const std::uint32_t> code, std::uint32_t first) {
|
||||
FillRows(first);
|
||||
Output.fill(0xdeadbeefu);
|
||||
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(code.data()));
|
||||
device.WaitIdle();
|
||||
return {Output.begin(), Output.end()};
|
||||
}
|
||||
|
||||
ShaderRecompiler::RecompileResult Compile(ShaderRecompiler::SpirvTarget target, bool hostNans, const std::optional<ShaderRecompiler::ShaderFloatMode>& floatMode, std::span<const std::uint32_t> code) {
|
||||
std::vector<std::uint32_t> userData(8, 0u);
|
||||
const auto input = BufferDescriptor(Input.data(), static_cast<std::uint32_t>(Input.size() * 4u));
|
||||
const auto output = BufferDescriptor(Output.data(), static_cast<std::uint32_t>(Output.size() * 4u));
|
||||
std::copy(input.begin(), input.end(), userData.begin());
|
||||
std::copy(output.begin(), output.end(), userData.begin() + 4);
|
||||
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(code)}}};
|
||||
const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {false, false, false}, false, 1};
|
||||
target.float16HostNans = hostNans;
|
||||
ShaderRecompiler::RecompileRequest request{
|
||||
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(code.data()), code, 0, {}},
|
||||
{32, 0, userData, compute, std::nullopt, std::nullopt, memory},
|
||||
target,
|
||||
{0, 0, 0, 128}
|
||||
};
|
||||
request.useCache = false;
|
||||
request.context.floatMode = floatMode;
|
||||
return ShaderRecompiler::Recompile(request);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Float16NanProbeResult ProbeFloat16HostNans(VulkanDevice& device, const ShaderRecompiler::SpirvTarget& target) {
|
||||
Float16NanProbeResult result;
|
||||
const std::array<std::optional<ShaderRecompiler::ShaderFloatMode>, 3> modes{std::nullopt, ShaderRecompiler::ShaderFloatMode{0xc0u, true, false, true}, ShaderRecompiler::ShaderFloatMode{0xc0u, false, false, true}};
|
||||
for (const auto& mode : modes) {
|
||||
const auto packedSelected = Compile(target, false, mode, PackedCode);
|
||||
const auto packedHost = Compile(target, true, mode, PackedCode);
|
||||
for (std::uint32_t first = 0; first < Combinations; first += Threads) {
|
||||
const auto selected = Run(device, packedSelected, PackedCode, first);
|
||||
const auto host = Run(device, packedHost, PackedCode, first);
|
||||
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
|
||||
for (std::uint32_t index = 0; index < PackedResults; ++index) {
|
||||
++result.compared;
|
||||
if (selected[tid * PackedResults + index] != host[tid * PackedResults + index]) ++result.mismatches;
|
||||
}
|
||||
}
|
||||
if (result.mismatches != 0u) return result;
|
||||
}
|
||||
const auto scalarSelected = Compile(target, false, mode, ScalarCode);
|
||||
const auto scalarHost = Compile(target, true, mode, ScalarCode);
|
||||
for (std::uint32_t first = 0; first < Combinations; first += Threads) {
|
||||
const auto scalarExact = Run(device, scalarSelected, ScalarCode, first);
|
||||
const auto scalar = Run(device, scalarHost, ScalarCode, first);
|
||||
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
|
||||
for (std::uint32_t index = ScalarFmaFirst; index <= ScalarFmaLast; ++index) {
|
||||
const std::uint32_t expected = scalarExact[tid * Results + index];
|
||||
const std::uint32_t actual = scalar[tid * Results + index];
|
||||
for (const std::uint32_t shift : {0u, 16u}) {
|
||||
const std::uint32_t expectedHalf = (expected >> shift) & 0xffffu;
|
||||
const std::uint32_t actualHalf = (actual >> shift) & 0xffffu;
|
||||
++result.compared;
|
||||
if (expectedHalf != actualHalf && !(IsNan16(expectedHalf) && IsNan16(actualHalf) && expectedHalf != 0xfe00u)) ++result.mismatches;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (result.mismatches != 0u) return result;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -213,9 +213,10 @@ std::vector<std::uint32_t> Run(VulkanDevice& device, const ShaderRecompiler::Spi
|
||||
}
|
||||
|
||||
void Compare(FloatFlushProbeResult& result, const std::vector<std::uint32_t>& expected, const std::vector<std::uint32_t>& actual) {
|
||||
const bool nanBits = ShaderRecompiler::ExactF32Arithmetic();
|
||||
for (std::size_t index = 0; index < expected.size(); ++index) {
|
||||
++result.compared;
|
||||
if (expected[index] != actual[index] && !(IsNan(expected[index]) && IsNan(actual[index]))) ++result.mismatches;
|
||||
if (expected[index] != actual[index] && (nanBits || !(IsNan(expected[index]) && IsNan(actual[index])))) ++result.mismatches;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -277,7 +277,17 @@ void FrameRecorder::writeReferenceFrames() {
|
||||
}
|
||||
|
||||
void FrameRecorder::record(FrameCall call, bool prologueCall, std::span<const Shader* const> shaders, const std::function<void()>& accept) {
|
||||
std::lock_guard lock(mutex);
|
||||
std::unique_lock lock(mutex);
|
||||
if (accept && !prologueCall && state != State::Recording) {
|
||||
unrecordedAccepts.fetch_add(1, std::memory_order_relaxed);
|
||||
lock.unlock();
|
||||
struct Accepted {
|
||||
std::atomic<std::uint64_t>& count;
|
||||
~Accepted() { count.fetch_sub(1, std::memory_order_release); }
|
||||
} accepted{unrecordedAccepts};
|
||||
accept();
|
||||
return;
|
||||
}
|
||||
recordLocked(std::move(call), prologueCall, shaders);
|
||||
if (accept) accept();
|
||||
}
|
||||
@@ -553,12 +563,16 @@ void FrameRecorder::stop(const char* reason) {
|
||||
state = State::Done;
|
||||
}
|
||||
|
||||
void FrameRecorder::SetStartIdleWaitForTest(std::function<bool()> wait) {
|
||||
startIdleWaitForTest = std::move(wait);
|
||||
}
|
||||
|
||||
void FrameRecorder::start() {
|
||||
++startAttempts;
|
||||
auto& driver = DriverDetail::Driver::Get();
|
||||
if (!driver.WaitIdleUnlessTitleWaitsFor(std::chrono::seconds(10))) {
|
||||
if (unrecordedAccepts.load(std::memory_order_acquire) != 0 || !(startIdleWaitForTest ? startIdleWaitForTest() : driver.WaitIdleUnlessTitleWaitsFor(std::chrono::seconds(10)))) {
|
||||
if (startAttempts >= 600) {
|
||||
std::fprintf(stderr, "[frame-capture] giving up: the driver was not idle at any of %llu frame boundaries\n", static_cast<unsigned long long>(startAttempts));
|
||||
std::fprintf(stderr, "[frame-capture] giving up: the driver was not idle, or a guest call was still being accepted, at all of %llu frame boundaries\n", static_cast<unsigned long long>(startAttempts));
|
||||
state = State::Done;
|
||||
}
|
||||
return;
|
||||
|
||||
@@ -472,11 +472,15 @@ PacketTag CurrentPacket() {
|
||||
}
|
||||
|
||||
const char* ReadSiteName(ReadSite site) {
|
||||
static const char* const names[static_cast<std::size_t>(ReadSite::Count)] = {"unknown", "capture", "dispatch-cache", "texture-compare", "texture-read", "buffer-upload", "index-buffer", "vertex-buffer", "registers", "indirect-args", "wait", "label", "scanout", "store", "mirror-refresh", "draw-cache"};
|
||||
static const char* const names[static_cast<std::size_t>(ReadSite::Count)] = {"unknown", "capture", "dispatch-cache", "texture-compare", "texture-read", "buffer-upload", "index-buffer", "vertex-buffer", "registers", "indirect-args", "wait", "label", "scanout", "store", "mirror-refresh", "draw-cache", "host-write"};
|
||||
const auto index = static_cast<std::size_t>(site);
|
||||
return index < static_cast<std::size_t>(ReadSite::Count) ? names[index] : "?";
|
||||
}
|
||||
|
||||
bool WritesGuestMemory(ReadSite site) {
|
||||
return site == ReadSite::Store || site == ReadSite::HostWrite;
|
||||
}
|
||||
|
||||
ReadSite SetReadSite(ReadSite site) {
|
||||
const auto previous = HostThreadSlot<ReadSite, CurrentReadSiteSlot>::Get();
|
||||
HostThreadSlot<ReadSite, CurrentReadSiteSlot>::Set(site);
|
||||
@@ -1134,24 +1138,37 @@ bool readableWithoutQuery(std::uintptr_t address, std::size_t bytes) {
|
||||
|
||||
// Checks that [address, address + bytes) is mapped with read (and, if asked, write) access. Returns
|
||||
// an empty string when it is, otherwise why it is not.
|
||||
std::string verify(std::uintptr_t address, std::size_t bytes, bool writable) {
|
||||
bool checkAccess(std::uintptr_t address, std::size_t bytes, bool writable, std::string* reason) {
|
||||
const TimedAccess timed(CounterVerify, bytes);
|
||||
if (onOwnLiveStack(address, bytes)) return {};
|
||||
if (onOwnLiveStack(address, bytes)) return true;
|
||||
#ifdef __linux__
|
||||
if (!writable && readableWithoutQuery(address, bytes)) return {};
|
||||
if (!writable && readableWithoutQuery(address, bytes)) return true;
|
||||
#endif
|
||||
std::string reason;
|
||||
bool accessible = true;
|
||||
const bool queried = describePages(address, bytes, [&](const PageRun& run) {
|
||||
if (!run.readable) {
|
||||
char text[128];
|
||||
std::snprintf(text, sizeof(text), "guest memory is not readable at 0x%llx (range 0x%llx+0x%zx)", static_cast<unsigned long long>(run.begin), static_cast<unsigned long long>(address), bytes);
|
||||
reason = text;
|
||||
accessible = false;
|
||||
if (reason != nullptr) {
|
||||
char text[128];
|
||||
std::snprintf(text, sizeof(text), "guest memory is not readable at 0x%llx (range 0x%llx+0x%zx)", static_cast<unsigned long long>(run.begin), static_cast<unsigned long long>(address), bytes);
|
||||
*reason = text;
|
||||
}
|
||||
} else if (writable && !run.writable) {
|
||||
reason = "guest memory has no write permission";
|
||||
accessible = false;
|
||||
if (reason != nullptr) *reason = "guest memory has no write permission";
|
||||
}
|
||||
return reason.empty();
|
||||
return accessible;
|
||||
});
|
||||
if (!queried && reason.empty()) reason = "cannot query guest memory";
|
||||
if (!queried && accessible) {
|
||||
accessible = false;
|
||||
if (reason != nullptr) *reason = "cannot query guest memory";
|
||||
}
|
||||
return accessible;
|
||||
}
|
||||
|
||||
std::string verify(std::uintptr_t address, std::size_t bytes, bool writable) {
|
||||
std::string reason;
|
||||
checkAccess(address, bytes, writable, &reason);
|
||||
return reason;
|
||||
}
|
||||
|
||||
@@ -1173,7 +1190,7 @@ void CheckRange(const void* pointer, std::size_t bytes, std::size_t alignment, b
|
||||
|
||||
bool Accessible(const void* pointer, std::size_t bytes, bool writable) {
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(pointer);
|
||||
return address != 0 && bytes <= std::numeric_limits<std::uintptr_t>::max() - address && verify(address, bytes, writable).empty();
|
||||
return address != 0 && bytes <= std::numeric_limits<std::uintptr_t>::max() - address && checkAccess(address, bytes, writable, nullptr);
|
||||
}
|
||||
|
||||
std::uint64_t ForgetSerial() {
|
||||
@@ -1352,14 +1369,6 @@ struct WriteTracker {
|
||||
std::atomic<std::uint64_t> generation{1};
|
||||
std::atomic<std::uint64_t> stable{1};
|
||||
std::vector<void*> pages;
|
||||
// Collect memo: page-rounded ranges walked during the current epoch (see BumpCollectEpoch). A
|
||||
// collect fully inside one skips GetWriteWatch, whose cost is proportional to the range's pages,
|
||||
// and the same surfaces are collected several times per epoch (each storage mip binding, a sampled
|
||||
// view plus its storage refresh, a write-back followed by a refresh, and every dispatch of the
|
||||
// epoch binding the same targets). Entries carry the walking thread's epoch, so no entry matches
|
||||
// another thread: the ring consulted first is per thread (ThreadCollectMemo, no mutex, no
|
||||
// eviction by other threads' walks); this shared ring (8 workers with epochs of several packets
|
||||
// hold a few hundred distinct ranges) serves APS5_SHARED_COLLECT_MEMO=1.
|
||||
struct Memo {
|
||||
std::uintptr_t begin = 0;
|
||||
std::uintptr_t end = 0;
|
||||
@@ -1367,8 +1376,31 @@ struct WriteTracker {
|
||||
std::uint64_t unwatched = 0;
|
||||
std::uint64_t mapping = 0;
|
||||
};
|
||||
std::array<Memo, 256> memo{};
|
||||
std::size_t nextMemo = 0;
|
||||
|
||||
struct ObservationLeaf {
|
||||
std::array<std::atomic<std::uint64_t>, LeafBlocks> ticks{};
|
||||
std::array<std::atomic<std::uint64_t>, LeafBlocks / CoarseBlocks> coarse{};
|
||||
};
|
||||
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> 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::array<ExactObservation, 16> exactObservations{};
|
||||
std::size_t nextExactObservation = 0;
|
||||
|
||||
bool exactlyObserved(std::uint64_t first, std::uint64_t stop, std::uint64_t need) const {
|
||||
for (const auto& entry : exactObservations) {
|
||||
if (entry.tick >= need && entry.first <= first && stop <= entry.stop) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void initialize() {
|
||||
if (initialized) return;
|
||||
@@ -1378,13 +1410,79 @@ struct WriteTracker {
|
||||
watched = size != 0 && GuestArena::GuestArenaWriteWatched_nid_postfix();
|
||||
if (!watched) return;
|
||||
leaves.resize((size / WriteBlockBytes + LeafBlocks) / LeafBlocks);
|
||||
coverage.Initialize(base, size);
|
||||
coverage.Initialize(base, size, std::getenv("APS5_NO_COVERAGE_SUMMARY") == nullptr);
|
||||
pages.resize(1u << 16);
|
||||
GuestArena::GuestArenaSetPrivateMappingObserver_nid_postfix(&watchPrivateMapping);
|
||||
#else
|
||||
watched = GuestWriteWatch::GuestWriteWatchAvailable_nid_postfix();
|
||||
if (watched) leaves.resize(LeafCount);
|
||||
#endif
|
||||
if (!watched) return;
|
||||
observationLeafCount = leaves.size();
|
||||
observationLeaves = std::make_unique<std::atomic<ObservationLeaf*>[]>(observationLeafCount);
|
||||
observationTable.store(observationLeaves.get(), std::memory_order_release);
|
||||
}
|
||||
|
||||
bool inObservationRange(std::uint64_t first, std::uint64_t stop) const {
|
||||
#ifdef _WIN32
|
||||
return first >= base && stop <= base + size;
|
||||
#else
|
||||
return stop <= LeafCount * LeafBlocks * WriteBlockBytes;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::uint64_t observedTick(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->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 {
|
||||
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 last = blockOf(stop - 1);
|
||||
auto block = blockOf(first);
|
||||
while (block <= last) {
|
||||
const auto index = block / LeafBlocks;
|
||||
if (index >= observationLeafCount) return false;
|
||||
const auto* leaf = table[index].load(std::memory_order_acquire);
|
||||
if (leaf == nullptr) return false;
|
||||
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;
|
||||
}
|
||||
if (leaf->ticks[block % LeafBlocks].load(std::memory_order_acquire) < need) return false;
|
||||
++block;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void publishObserved(std::uint64_t first, std::uint64_t last, std::uint64_t tick) {
|
||||
for (auto block = first; block <= last;) {
|
||||
const auto index = block / LeafBlocks;
|
||||
auto* leaf = observationLeaves[index].load(std::memory_order_relaxed);
|
||||
if (leaf == nullptr) {
|
||||
leaf = new ObservationLeaf();
|
||||
observationLeaves[index].store(leaf, std::memory_order_release);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
block = end;
|
||||
}
|
||||
}
|
||||
|
||||
bool covers(std::uint64_t address, std::size_t bytes) const {
|
||||
@@ -1761,6 +1859,10 @@ public:
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
void Stabilize() {
|
||||
publish();
|
||||
}
|
||||
|
||||
void Suspend() {
|
||||
lock.unlock();
|
||||
}
|
||||
@@ -1817,18 +1919,14 @@ void watchPrivateMapping(std::uintptr_t address, std::size_t bytes, std::uint64_
|
||||
}
|
||||
#endif
|
||||
|
||||
// Collect epochs are per thread and globally unique: every bump takes a fresh value from one counter,
|
||||
// so a memo entry (stamped with the epoch of its walk) can only match the thread that made it, and
|
||||
// only until that thread's next ordering point (the queue workers bump at theirs, see the header). A
|
||||
// thread that never bumped is given a new epoch for every collect: its walks are never reused (the
|
||||
// presenter, game threads inside the flush hook), as nothing orders the CPU's writes for it.
|
||||
std::atomic<std::uint64_t> nextCollectEpoch{1};
|
||||
struct CollectEpochSlot {};
|
||||
std::atomic<std::uint64_t> lastBumpedEpoch{0};
|
||||
std::atomic<void (*)(int)> observationHook{nullptr};
|
||||
|
||||
std::uint64_t currentCollectEpoch() {
|
||||
if (const auto epoch = HostThreadSlot<std::uint64_t, CollectEpochSlot>::Get(); epoch != 0) return epoch;
|
||||
return nextCollectEpoch.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
return nextCollectEpoch.fetch_add(1, std::memory_order_acq_rel) + 1;
|
||||
}
|
||||
|
||||
bool collectMemoEnabled() {
|
||||
@@ -1836,77 +1934,20 @@ bool collectMemoEnabled() {
|
||||
return !disabled;
|
||||
}
|
||||
|
||||
// The per-thread memo ring (see WriteTracker::Memo): sized to a packet's working set (a dispatch
|
||||
// collects each of its few dozen image surfaces in stage A and again in stage B). Entries of a
|
||||
// thread that never bumps its epoch never match (each collect gets a fresh epoch), as intended.
|
||||
// APS5_SHARED_COLLECT_MEMO=1 uses the tracker's shared ring under its mutex instead.
|
||||
struct ThreadCollectMemo {
|
||||
std::array<WriteTracker::Memo, 64> entries{};
|
||||
std::size_t next = 0;
|
||||
};
|
||||
ThreadCollectMemo& threadCollectMemo() {
|
||||
struct Slot {};
|
||||
auto* memo = HostThreadSlot<ThreadCollectMemo*, Slot>::Get();
|
||||
if (memo == nullptr) {
|
||||
ShaderRecompiler::ThreadOwned(memo);
|
||||
HostThreadSlot<ThreadCollectMemo*, Slot>::Set(memo);
|
||||
}
|
||||
return *memo;
|
||||
|
||||
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.observationUnwatched.store(unwatched, std::memory_order_release);
|
||||
tracker.observationMapping.store(mapping, std::memory_order_release);
|
||||
}
|
||||
|
||||
struct EpochCollectMap {
|
||||
std::uint64_t epoch = 0;
|
||||
std::uint64_t unwatched = 0;
|
||||
std::uint64_t mapping = 0;
|
||||
std::map<std::uintptr_t, std::uintptr_t> ranges;
|
||||
|
||||
bool Covers(std::uintptr_t begin, std::uintptr_t end) const {
|
||||
if (end <= begin) return false;
|
||||
const auto next = ranges.upper_bound(begin);
|
||||
return next != ranges.begin() && std::prev(next)->second >= end;
|
||||
}
|
||||
|
||||
void Record(std::uintptr_t begin, std::uintptr_t end) {
|
||||
auto next = ranges.upper_bound(begin);
|
||||
if (next != ranges.begin()) {
|
||||
const auto previous = std::prev(next);
|
||||
if (previous->second >= begin) {
|
||||
previous->second = std::max(end, previous->second);
|
||||
while (next != ranges.end() && next->first <= previous->second) {
|
||||
previous->second = std::max(previous->second, next->second);
|
||||
next = ranges.erase(next);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
while (next != ranges.end() && next->first <= end) {
|
||||
end = std::max(end, next->second);
|
||||
next = ranges.erase(next);
|
||||
}
|
||||
ranges.emplace_hint(next, begin, end);
|
||||
}
|
||||
};
|
||||
|
||||
EpochCollectMap& epochCollectMap(std::uint64_t epoch, std::uint64_t unwatched, std::uint64_t mapping) {
|
||||
struct Slot {};
|
||||
auto& map = ThreadScratch<EpochCollectMap, Slot>();
|
||||
if (map.epoch != epoch || map.unwatched != unwatched || map.mapping != mapping) {
|
||||
map.ranges.clear();
|
||||
map.epoch = epoch;
|
||||
map.unwatched = unwatched;
|
||||
map.mapping = mapping;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
bool epochCollectMapEnabled() {
|
||||
static const bool enabled = std::getenv("APS5_NO_EPOCH_COLLECT_MAP") == nullptr;
|
||||
return enabled;
|
||||
}
|
||||
|
||||
bool sharedCollectMemo() {
|
||||
static const bool shared = std::getenv("APS5_SHARED_COLLECT_MEMO") != nullptr;
|
||||
return shared;
|
||||
void observationPoint(int point) {
|
||||
if (const auto hook = observationHook.load(std::memory_order_acquire)) hook(point);
|
||||
}
|
||||
|
||||
struct StampRuns {
|
||||
@@ -2008,6 +2049,7 @@ void noteRefusedWalk(WriteTracker& tracker, std::uint64_t first, std::uint64_t s
|
||||
|
||||
bool walkWrites(WriteTracker& tracker, std::uint64_t first, std::uint64_t stop, StampKind kind, bool armedOnly = false, const WindowCopy* window = nullptr) {
|
||||
++tracker.generation;
|
||||
observationPoint(1);
|
||||
StampRuns runs{tracker, kind, 0, window, {}};
|
||||
#ifdef _WIN32
|
||||
const bool complete = collectWindowsWrites(runs, first, stop, armedOnly);
|
||||
@@ -2024,99 +2066,109 @@ bool walkWrites(WriteTracker& tracker, std::uint64_t first, std::uint64_t stop,
|
||||
return complete;
|
||||
}
|
||||
|
||||
std::uint64_t collectWrites(std::uint64_t address, std::size_t bytes, bool memoized) {
|
||||
if (bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address) return 0;
|
||||
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};
|
||||
auto& tracker = Tracker();
|
||||
// Whole pages, so a page shared with the next range is collected with either.
|
||||
constexpr std::uint64_t page = 4096;
|
||||
auto first = address & ~(page - 1);
|
||||
auto stop = (address + bytes + page - 1) & ~(page - 1);
|
||||
if (stop <= first) return 0;
|
||||
// One epoch for the lookup and the entry made after the walk: an unbumped thread's fresh epoch
|
||||
// must not differ between them.
|
||||
const auto first = address & ~(page - 1);
|
||||
const auto stop = (address + bytes + page - 1) & ~(page - 1);
|
||||
if (stop <= first) return {Status::Uncovered, 0};
|
||||
const auto epoch = currentCollectEpoch();
|
||||
const auto unwatched = unwatchSerial.load(std::memory_order_acquire);
|
||||
const auto mapping = GuestAllocations::GuestAllocationsGeneration_nid_postfix();
|
||||
const bool useMemo = memoized && collectMemoEnabled() && bytes != 0;
|
||||
const bool epochal = HostThreadSlot<std::uint64_t, CollectEpochSlot>::Get() != 0;
|
||||
if (useMemo && epochal && !sharedCollectMemo()) {
|
||||
// An entry exists only for a completed walk of an in-arena range, so the tracker is
|
||||
// initialized and watched; nothing below the lock needs asking.
|
||||
if (epochCollectMapEnabled()) {
|
||||
const auto& map = epochCollectMap(epoch, unwatched, mapping);
|
||||
if (map.Covers(first, stop)) {
|
||||
collectMemoHits.fetch_add(1, std::memory_order_relaxed);
|
||||
return tracker.stable.load(std::memory_order_acquire);
|
||||
}
|
||||
}
|
||||
for (const auto& entry : threadCollectMemo().entries) {
|
||||
if (entry.epoch == epoch && entry.unwatched == unwatched && entry.mapping == mapping && entry.begin <= first && stop <= entry.end) {
|
||||
// The current generation, not the memoized one: blocks stamped since (MarkWritten, an
|
||||
// overlapping collect) were written before this caller reads, and an older value would
|
||||
// make every later UnchangedSince fail until the epoch ends.
|
||||
collectMemoHits.fetch_add(1, std::memory_order_relaxed);
|
||||
return tracker.stable.load(std::memory_order_acquire);
|
||||
}
|
||||
}
|
||||
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())) {
|
||||
collectMemoHits.fetch_add(1, std::memory_order_relaxed);
|
||||
return {Status::Complete, tracker.stable.load(std::memory_order_acquire)};
|
||||
}
|
||||
const auto lock = lockTracker(tracker);
|
||||
auto lock = lockTracker(tracker);
|
||||
tracker.initialize();
|
||||
if (!tracker.watched || bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address || !tracker.covers(address, bytes)) return 0;
|
||||
auto cursor = first;
|
||||
if (useMemo && sharedCollectMemo()) {
|
||||
for (const auto& entry : tracker.memo) {
|
||||
if (entry.epoch == epoch && entry.unwatched == unwatchSerial.load(std::memory_order_relaxed) && entry.mapping == mapping && entry.begin <= cursor && stop <= entry.end) {
|
||||
collectMemoHits.fetch_add(1, std::memory_order_relaxed);
|
||||
return tracker.generation;
|
||||
if (!tracker.watched || !tracker.covers(address, bytes)) return {Status::Uncovered, 0};
|
||||
syncObservationContext(tracker, unwatchSerial.load(std::memory_order_acquire), GuestAllocations::GuestAllocationsGeneration_nid_postfix());
|
||||
const auto tick = nextCollectEpoch.load(std::memory_order_acquire);
|
||||
struct Run {
|
||||
std::uint64_t first;
|
||||
std::uint64_t stop;
|
||||
bool exact;
|
||||
};
|
||||
struct RunSlot {};
|
||||
auto& runs = ThreadScratch<std::vector<Run>, RunSlot>();
|
||||
runs.clear();
|
||||
if (!shared) runs.push_back({first, stop, false});
|
||||
else {
|
||||
const auto need = std::max(epoch, tracker.observationFloor.load(std::memory_order_relaxed));
|
||||
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});
|
||||
};
|
||||
bool open = false;
|
||||
std::uint64_t from = 0;
|
||||
for (auto block = tracker.blockOf(first); block <= lastBlock; ++block) {
|
||||
if (tracker.observedTick(block) < need) {
|
||||
if (!open) from = block;
|
||||
open = true;
|
||||
} else if (open) {
|
||||
addRun(from, block - 1);
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
if (open) addRun(from, lastBlock);
|
||||
}
|
||||
const TimedAccess timed(CounterCollect, bytes);
|
||||
const auto requestedFirst = first;
|
||||
const auto requestedStop = stop;
|
||||
if (useMemo && HostThreadSlot<std::uint64_t, CollectEpochSlot>::Get() != 0 && bytes <= WriteBlockBytes) {
|
||||
const auto begin = first & ~(WriteBlockBytes - 1);
|
||||
const auto end = (stop + WriteBlockBytes - 1) & ~(WriteBlockBytes - 1);
|
||||
if (end > begin && tracker.covers(begin, end - begin)) {
|
||||
first = begin;
|
||||
stop = end;
|
||||
if (runs.empty()) collectMemoHits.fetch_add(1, std::memory_order_relaxed);
|
||||
std::optional<TimedAccess> timed;
|
||||
if (!runs.empty()) timed.emplace(CounterCollect, bytes);
|
||||
std::size_t done = 0;
|
||||
auto status = Status::Complete;
|
||||
for (auto& run : runs) {
|
||||
bool complete = walkWrites(tracker, run.first, run.stop, StampKind::Cpu);
|
||||
if (!complete && (run.first < first || run.stop > stop)) {
|
||||
run = {std::max(first, run.first), std::min(stop, run.stop), true};
|
||||
complete = walkWrites(tracker, run.first, run.stop, StampKind::Cpu);
|
||||
}
|
||||
}
|
||||
if (!walkWrites(tracker, first, stop, StampKind::Cpu)) {
|
||||
if (!complete) {
|
||||
#ifdef _WIN32
|
||||
if (first == requestedFirst && stop == requestedStop) return 0;
|
||||
first = requestedFirst;
|
||||
stop = requestedStop;
|
||||
if (!walkWrites(tracker, first, stop, StampKind::Cpu)) return 0;
|
||||
status = Status::Refused;
|
||||
#else
|
||||
return 0;
|
||||
status = Status::Failed;
|
||||
#endif
|
||||
}
|
||||
// Only a completed walk is remembered; a failed one (uncommitted pages) returned 0 above.
|
||||
if (collectMemoEnabled()) {
|
||||
const auto serial = unwatchSerial.load(std::memory_order_relaxed);
|
||||
if (sharedCollectMemo()) tracker.memo[tracker.nextMemo++ % tracker.memo.size()] = {first, stop, epoch, serial, mapping};
|
||||
else {
|
||||
if (useMemo && epochal) {
|
||||
auto& memo = threadCollectMemo();
|
||||
memo.entries[memo.next++ % memo.entries.size()] = {first, stop, epoch, serial, mapping};
|
||||
}
|
||||
if (epochal && epochCollectMapEnabled()) {
|
||||
epochCollectMap(epoch, serial, mapping).Record(first, stop);
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (shared && run.exact) tracker.exactObservations[tracker.nextExactObservation++ % tracker.exactObservations.size()] = {run.first, run.stop, tick};
|
||||
++done;
|
||||
}
|
||||
return tracker.generation;
|
||||
lock.Stabilize();
|
||||
const auto generation = tracker.generation.load(std::memory_order_relaxed);
|
||||
observationPoint(2);
|
||||
for (std::size_t index = 0; index < done; ++index) {
|
||||
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 (status != Status::Complete) return {status, 0};
|
||||
return {Status::Complete, generation};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Observation Observe(std::uint64_t address, std::size_t bytes) {
|
||||
return observe(address, bytes, true);
|
||||
}
|
||||
|
||||
std::uint64_t CollectWrites(std::uint64_t address, std::size_t bytes) {
|
||||
return collectWrites(address, bytes, true);
|
||||
const auto observation = observe(address, bytes, true);
|
||||
return observation.status == Observation::Status::Complete ? observation.generation : 0;
|
||||
}
|
||||
|
||||
std::uint64_t CollectWritesUncached(std::uint64_t address, std::size_t bytes) {
|
||||
return collectWrites(address, bytes, false);
|
||||
const auto observation = observe(address, bytes, false);
|
||||
return observation.status == Observation::Status::Complete ? observation.generation : 0;
|
||||
}
|
||||
|
||||
void SetObservationHookForTest(void (*hook)(int point)) {
|
||||
observationHook.store(hook, std::memory_order_release);
|
||||
}
|
||||
|
||||
std::uint64_t WriteGeneration() {
|
||||
@@ -2190,7 +2242,7 @@ std::uint64_t CollectWrittenBlocks(std::uint64_t address, std::size_t bytes, std
|
||||
}
|
||||
|
||||
void BumpCollectEpoch() {
|
||||
const auto epoch = nextCollectEpoch.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
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);
|
||||
while (last < epoch && !lastBumpedEpoch.compare_exchange_weak(last, epoch, std::memory_order_release, std::memory_order_relaxed)) {}
|
||||
@@ -2517,7 +2569,7 @@ bool SweepSubscription(const WriteSubscription& subscription) {
|
||||
auto& index = Index();
|
||||
index.sweeps.fetch_add(1, std::memory_order_relaxed);
|
||||
for (const auto& [begin, end] : subscription.spans) {
|
||||
if (collectWrites(begin, static_cast<std::size_t>(end - begin), true) == 0) {
|
||||
if (CollectWrites(begin, static_cast<std::size_t>(end - begin)) == 0) {
|
||||
index.sweepFailures.fetch_add(1, std::memory_order_relaxed);
|
||||
return false;
|
||||
}
|
||||
@@ -3042,7 +3094,14 @@ std::atomic<std::uint64_t> gpuHoldSerial{0};
|
||||
}
|
||||
|
||||
void GpuMutexType::enter() {
|
||||
if (!HeldByThisThread()) LockSpinning(mutex, HandoffSpinWindow());
|
||||
if (HeldByThisThread() || mutex.try_lock()) return;
|
||||
block();
|
||||
}
|
||||
|
||||
void GpuMutexType::block() {
|
||||
waiters.fetch_add(1, std::memory_order_relaxed);
|
||||
LockSpinning(mutex, HandoffSpinWindow());
|
||||
waiters.fetch_sub(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
bool GpuMutexType::tryEnter() {
|
||||
@@ -3129,7 +3188,7 @@ void GpuMutexType::lock() {
|
||||
const auto site = static_cast<std::size_t>(std::exchange(LockStats().nextSite, GpuLockSite::Other));
|
||||
if (!tryEnter()) {
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
LockSpinning(mutex, HandoffSpinWindow());
|
||||
block();
|
||||
trace->Add("GpuMutex.wait", GpuLockSiteNames[site], start, std::chrono::steady_clock::now());
|
||||
}
|
||||
}
|
||||
@@ -3147,7 +3206,7 @@ void GpuMutexType::lock() {
|
||||
HolderMatrixValues before{};
|
||||
if (holders) Holders().Snapshot(before);
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
LockSpinning(mutex, HandoffSpinWindow());
|
||||
block();
|
||||
acquired();
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (auto* trace = PerformanceTrace::Recording() ? PerformanceTrace::Thread() : nullptr) trace->Add("GpuMutex.wait", GpuLockSiteNames[site], start, now);
|
||||
@@ -3258,6 +3317,17 @@ GpuMutexType& GpuMutex() {
|
||||
#endif
|
||||
}
|
||||
|
||||
std::function<bool()> YieldToGpuMutexWaiters(std::function<bool()> stop) {
|
||||
return [stop = std::move(stop), first = true]() mutable {
|
||||
if (stop()) return true;
|
||||
if (first) {
|
||||
first = false;
|
||||
return false;
|
||||
}
|
||||
return GpuMutex().Waiters() != 0;
|
||||
};
|
||||
}
|
||||
|
||||
void TagGpuLockThread(std::uint32_t queue) {
|
||||
LockStats().tag = queue;
|
||||
}
|
||||
@@ -3397,7 +3467,7 @@ void PrepareHostWrite(std::uintptr_t address, std::size_t bytes) {
|
||||
if (GpuMutex().HeldByThisThread()) noteLockedHostWrite(address, bytes);
|
||||
const HostWriteInFlight inFlight;
|
||||
if (hostWritesStopped.load(std::memory_order_seq_cst)) return;
|
||||
const ReadSiteScope site(ReadSite::Store);
|
||||
const ReadSiteScope site(ReadSite::HostWrite);
|
||||
if (!MemoryProfiled()) {
|
||||
FlushGpuWrites(address, bytes);
|
||||
return;
|
||||
@@ -3562,6 +3632,16 @@ bool EqualsCommittedUnsynced(std::uint64_t address, std::span<const std::byte> b
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
thread_local void (*compareMappedHook)(std::uint64_t, std::size_t) = nullptr;
|
||||
|
||||
}
|
||||
|
||||
void SetCompareMappedHook(void (*hook)(std::uint64_t address, std::size_t bytes)) {
|
||||
compareMappedHook = hook;
|
||||
}
|
||||
|
||||
Compare CompareMapped(std::uint64_t address, std::span<const std::byte> bytes) {
|
||||
if (bytes.empty()) return Compare::Equal;
|
||||
if (address == 0 || bytes.size() > std::numeric_limits<std::uintptr_t>::max() - address) return Compare::Unmapped;
|
||||
@@ -3569,7 +3649,10 @@ Compare CompareMapped(std::uint64_t address, std::span<const std::byte> bytes) {
|
||||
// Each run's page state is consulted right before its bytes are compared.
|
||||
const bool queried = describePages(static_cast<std::uintptr_t>(address), bytes.size(), [&](const PageRun& run) {
|
||||
if (!run.readable) outcome = Compare::Unmapped;
|
||||
else if (std::memcmp(reinterpret_cast<const void*>(run.begin), bytes.data() + (run.begin - address), static_cast<std::size_t>(run.end - run.begin)) != 0) outcome = Compare::Differs;
|
||||
else {
|
||||
if (compareMappedHook != nullptr) compareMappedHook(run.begin, static_cast<std::size_t>(run.end - run.begin));
|
||||
if (std::memcmp(reinterpret_cast<const void*>(run.begin), bytes.data() + (run.begin - address), static_cast<std::size_t>(run.end - run.begin)) != 0) outcome = Compare::Differs;
|
||||
}
|
||||
return outcome == Compare::Equal;
|
||||
});
|
||||
return queried ? outcome : Compare::Unmapped;
|
||||
|
||||
@@ -808,8 +808,16 @@ OverlayLayout LayOutOverlay(const OverlayContent& content, VkExtent2D extent, Ov
|
||||
return layout;
|
||||
}
|
||||
|
||||
std::array<std::array<float, 4>, OverlayColorCount> ColorblindOverlayPalette(std::array<std::array<float, 4>, OverlayColorCount> palette) {
|
||||
palette[static_cast<std::size_t>(OverlayColor::Graph)] = {0.34f, 0.71f, 0.91f, 1.0f};
|
||||
palette[static_cast<std::size_t>(OverlayColor::Accent)] = {0.90f, 0.62f, 0.00f, 1.0f};
|
||||
return palette;
|
||||
}
|
||||
|
||||
std::array<std::array<float, 4>, OverlayColorCount> OverlayPalette(VkFormat format, VkColorSpaceKHR colorSpace) {
|
||||
static const bool colorblind = std::getenv("ANYPS5_OVERLAY_PALETTE") != nullptr && std::string_view(std::getenv("ANYPS5_OVERLAY_PALETTE")) == "colorblind";
|
||||
std::array<std::array<float, 4>, OverlayColorCount> palette{{{0.0f, 0.0f, 0.0f, 0.6f}, {1.0f, 1.0f, 1.0f, 1.0f}, {0.35f, 0.8f, 0.35f, 1.0f}, {0.06f, 0.07f, 0.09f, 0.94f}, {0.22f, 0.24f, 0.29f, 1.0f}, {1.0f, 0.78f, 0.2f, 1.0f}, {0.0f, 0.0f, 0.0f, 1.0f}}};
|
||||
if (colorblind) palette = ColorblindOverlayPalette(palette);
|
||||
if (colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT) {
|
||||
for (auto& color : palette) {
|
||||
const float red = srgbDecode(color[0]);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "prx/libc/include/PreciseWait.hpp"
|
||||
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
@@ -370,8 +371,8 @@ void Validate(std::span<const std::uint32_t> packet, std::uint32_t queue) {
|
||||
graphics();
|
||||
size(4);
|
||||
const auto operation = (packet[1] >> 16u) & 7u;
|
||||
require(operation != 1 && operation != 2, "GPU query predication is not implemented");
|
||||
require(operation == 0 || operation == 3 || operation == 4, "invalid predication operation");
|
||||
require(operation != 2, "GPU primitive-count predication is not implemented");
|
||||
require(operation == 0 || operation == 1 || operation == 3 || operation == 4, "invalid predication operation");
|
||||
require((packet[1] & ~0x71100u) == 0, "unsupported SET_PREDICATION bits");
|
||||
if (operation != 0) require(address(packet[2], packet[3]) != 0 && (packet[2] & 0xfu) == 0, "unaligned predication address");
|
||||
break;
|
||||
@@ -537,10 +538,14 @@ void Validate(std::span<const std::uint32_t> packet, std::uint32_t queue) {
|
||||
case 0x45: {
|
||||
size(9);
|
||||
require((packet[1] & ~0x317u) == 0, "COND_WRITE reserved fields are not implemented");
|
||||
require((packet[1] & 0x10u) != 0, "register-space COND_WRITE poll is not implemented");
|
||||
const bool memoryPoll = (packet[1] & 0x10u) != 0;
|
||||
require(memoryPoll || (packet[3] == 0 && registerBankBase(packet[2]) != 0), "register-space COND_WRITE poll outside modeled banks is not implemented");
|
||||
require((packet[1] & 7u) <= 6u, "invalid COND_WRITE compare function");
|
||||
require(((packet[1] >> 8u) & 3u) == 1u, "register or scratch COND_WRITE destination is not implemented");
|
||||
require((packet[2] & 3u) == 0 && (packet[6] & 3u) == 0, "misaligned COND_WRITE address");
|
||||
const auto destination = (packet[1] >> 8u) & 3u;
|
||||
require(destination <= 1u, "scratch or reserved COND_WRITE destination is not implemented");
|
||||
require(destination != 0 || (packet[7] == 0 && registerBankBase(packet[6]) != 0), "COND_WRITE destination outside modeled banks is not implemented");
|
||||
if (destination == 0 && registerBankBase(packet[6]) != ShaderRegisterBase) graphics();
|
||||
require((!memoryPoll || (packet[2] & 3u) == 0) && (destination != 1 || (packet[6] & 3u) == 0), "misaligned COND_WRITE address");
|
||||
break;
|
||||
}
|
||||
case 0x49: {
|
||||
@@ -670,12 +675,33 @@ std::size_t ConditionalWords(std::span<const std::uint32_t> packet) {
|
||||
return packet[4] & ConditionalWordsMask;
|
||||
}
|
||||
|
||||
std::size_t PredicationBytes(const Predication& predication) {
|
||||
if (predication.operation == 1) return SampleDumpBytes + SampleDumpBlockBytes;
|
||||
return predication.operation == 3 ? 8 : 4;
|
||||
}
|
||||
|
||||
bool PredicationPasses(const QueueState& queue) {
|
||||
const auto& predication = queue.predication;
|
||||
if (predication.operation == 0) return true;
|
||||
const std::size_t bytes = predication.operation == 3 ? 8 : 4;
|
||||
std::uint64_t value = 0;
|
||||
const GuestMemory::ReadSiteScope site(GuestMemory::ReadSite::Wait);
|
||||
if (predication.operation == 1) {
|
||||
constexpr std::uint64_t ready = 1ull << 63u;
|
||||
std::array<std::uint64_t, SampleDumpBlocks * SampleDumpStride / sizeof(std::uint64_t)> words{};
|
||||
GuestMemory::Read(predication.address, std::as_writable_bytes(std::span(words)).first(PredicationBytes(predication)), 8);
|
||||
std::uint64_t samples = 0;
|
||||
for (std::uint64_t db = 0; db < SampleDumpBlocks; ++db) {
|
||||
const auto begin = words[db * SampleDumpStride / sizeof(std::uint64_t)];
|
||||
const auto end = words[db * SampleDumpStride / sizeof(std::uint64_t) + 1];
|
||||
if ((begin & ready) == 0 || (end & ready) == 0) {
|
||||
require(predication.runWhenUnwritten, "Z-pass predication waits for a counter pair that was never written");
|
||||
return true;
|
||||
}
|
||||
samples += (end & ~ready) - (begin & ~ready);
|
||||
}
|
||||
return (samples != 0) == predication.executeWhenSet;
|
||||
}
|
||||
const std::size_t bytes = PredicationBytes(predication);
|
||||
std::uint64_t value = 0;
|
||||
GuestMemory::Read(predication.address, std::as_writable_bytes(std::span(&value, 1)).first(bytes), bytes);
|
||||
return (value != 0) == predication.executeWhenSet;
|
||||
}
|
||||
@@ -820,6 +846,7 @@ std::vector<PacketStore> DecodeStores(std::span<const std::uint32_t> packet) {
|
||||
}
|
||||
case 0x45: {
|
||||
const auto write = DecodeConditionalWrite(packet);
|
||||
if (((packet[1] >> 8u) & 3u) != 1u) return {};
|
||||
auto store = known(write.destination, std::as_bytes(std::span(&write.value, 1)));
|
||||
store.conditional = true;
|
||||
return {store};
|
||||
@@ -1146,7 +1173,7 @@ void Execute(std::span<const std::uint32_t> packet, QueueState& queue) {
|
||||
case 0x13: queue.indexBufferSize = packet[1]; return;
|
||||
case 0x20: {
|
||||
const auto operation = (packet[1] >> 16u) & 7u;
|
||||
queue.predication = {operation == 0 ? 0 : address(packet[2], packet[3]), operation, (packet[1] & 0x100u) != 0};
|
||||
queue.predication = {operation == 0 ? 0 : address(packet[2], packet[3]), operation, (packet[1] & 0x100u) != 0, (packet[1] & 0x1000u) != 0};
|
||||
return;
|
||||
}
|
||||
case 0x3f: throw std::runtime_error(std::string(UnsupportedReason(packet[0])));
|
||||
@@ -1247,9 +1274,21 @@ void Execute(std::span<const std::uint32_t> packet, QueueState& queue) {
|
||||
case 0x45: {
|
||||
const auto write = DecodeConditionalWrite(packet);
|
||||
std::uint32_t value = 0;
|
||||
{
|
||||
if ((packet[1] & 0x10u) != 0) {
|
||||
const GuestMemory::ReadSiteScope site(GuestMemory::ReadSite::Wait);
|
||||
GuestMemory::Read(write.compared, std::as_writable_bytes(std::span(&value, 1)), 4);
|
||||
} else {
|
||||
const auto base = registerBankBase(packet[2]);
|
||||
const auto& bank = base == ShaderRegisterBase ? queue.shader : base == ContextRegisterBase ? queue.context : queue.userConfig;
|
||||
require(base != 0 && bank.contains(packet[2] - base), "COND_WRITE poll register has no known value");
|
||||
value = bank.at(packet[2] - base);
|
||||
}
|
||||
if (((packet[1] >> 8u) & 3u) == 0) {
|
||||
if (waitCompares(packet, false, value)) {
|
||||
const auto base = registerBankBase(packet[6]);
|
||||
writeRegister(queue, base == ShaderRegisterBase ? 0x76u : base == ContextRegisterBase ? 0x69u : 0x79u, packet[6] - base, write.value);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (waitCompares(packet, false, value)) GuestMemory::Write(write.destination, std::as_bytes(std::span(&write.value, 1)), 4);
|
||||
return;
|
||||
|
||||
@@ -48,6 +48,7 @@ struct CaptureProfile {
|
||||
std::atomic<std::uint64_t> wordsVerified{0};
|
||||
std::atomic<std::uint64_t> wordMismatches{0};
|
||||
// Words served from the driver's known values (never profile-gated: the [copy] line reads them).
|
||||
std::atomic<std::uint64_t> tablesKept{0};
|
||||
std::atomic<std::uint64_t> wordsKnown{0};
|
||||
std::atomic<std::uint64_t> wordsKnownVerified{0};
|
||||
std::atomic<std::uint64_t> wordsKnownMismatches{0};
|
||||
@@ -320,6 +321,7 @@ ShaderMemory::Page& ShaderMemory::addPage(std::size_t position, std::uint64_t ba
|
||||
owned->raw.Reset();
|
||||
owned->read.Reset();
|
||||
owned->recent.Reset();
|
||||
owned->kept.Reset();
|
||||
owned->wordwise = false;
|
||||
owned->lazy = false;
|
||||
owned->backing = PageBacking(base, PageBytes);
|
||||
@@ -394,7 +396,7 @@ bool ShaderMemory::read(void* context, std::uint64_t address, std::uint32_t* val
|
||||
return spanNeedsSync(spanPolicy) || spanPolicy == PendingWrite::KnownValue;
|
||||
};
|
||||
const auto checkSpanBytes = std::max<std::size_t>(self.descriptorSpanBytes, sizeof(*value));
|
||||
if (page.wordwise && page.valid.Test(index) &&
|
||||
if (page.wordwise && page.valid.Test(index) && !page.kept.Test(index) &&
|
||||
(self.forceSync != 0u ? self.pendingSpan(address, checkSpanBytes, {}) != PendingWrite::None
|
||||
: (spanInvalidatesCache(self.pendingSpan(address, checkSpanBytes, {})) ||
|
||||
(checkSpanBytes > sizeof(*value) && spanInvalidatesCache(self.pendingSpan(address, sizeof(*value), {})))))) {
|
||||
@@ -480,7 +482,10 @@ bool ShaderMemory::read(void* context, std::uint64_t address, std::uint32_t* val
|
||||
}
|
||||
if (observed) report(waitsBefore, before == word);
|
||||
}
|
||||
if ((waited || (page.wordwise && policy == PendingWrite::Sync && !forcedRaw)) && self.invalidateRawPages()) ++self.rawInvalidations;
|
||||
if (waited || (page.wordwise && policy == PendingWrite::Sync && !forcedRaw)) {
|
||||
const bool invalidated = self.forceSync != 0u && !waited ? self.invalidateChangedRawPages() : self.invalidateRawPages();
|
||||
if (invalidated) ++self.rawInvalidations;
|
||||
}
|
||||
if (CaptureProfiled()) CaptureTotals().wordReadNanoseconds += NanosecondsSince(fetchStarted);
|
||||
page.words[index] = word;
|
||||
page.valid.Set(index);
|
||||
@@ -500,6 +505,7 @@ bool ShaderMemory::pagesCurrent() {
|
||||
if (backing == existing->backing) continue;
|
||||
existing->valid.Reset();
|
||||
existing->raw.Reset();
|
||||
existing->kept.Reset();
|
||||
existing->backing = backing;
|
||||
existing->wordwise = false;
|
||||
existing->lazy = false;
|
||||
@@ -514,6 +520,43 @@ bool ShaderMemory::snapshotCurrent(void* context, std::span<const ShaderRecompil
|
||||
return pages && DriverDetail::CaptureRegisteredViewsCurrent(views);
|
||||
}
|
||||
|
||||
bool ShaderMemory::KeepTable(std::uint64_t address) {
|
||||
constexpr std::size_t Words = KeepBytes / sizeof(std::uint32_t);
|
||||
if (address % sizeof(std::uint32_t) != 0 || address > std::numeric_limits<std::uint64_t>::max() - KeepBytes) return false;
|
||||
const auto end = address + KeepBytes;
|
||||
if (overlapsInitial(address, end)) return false;
|
||||
if (std::any_of(keptRanges.begin(), keptRanges.end(), [&](const auto& range) { return range.first < end && address < range.second; })) return false;
|
||||
if (std::any_of(supplied.begin(), supplied.end(), [&](const Supplied& entry) { return entry.begin < end && address < entry.end; })) return false;
|
||||
if (!GuestMemory::Accessible(reinterpret_cast<const void*>(address), KeepBytes)) return false;
|
||||
const auto quiet = [&] { return pendingSpan != nullptr && pendingSpan(address, KeepBytes, {}) == PendingWrite::None; };
|
||||
if (!quiet()) return false;
|
||||
std::array<std::uint32_t, Words> copy;
|
||||
GuestMemory::CopyGuestBytes(copy.data(), reinterpret_cast<const void*>(address), KeepBytes);
|
||||
if (!quiet()) return false;
|
||||
for (auto base = address & ~static_cast<std::uint64_t>(PageBytes - 1); base < end; base += PageBytes) static_cast<void>(page(base));
|
||||
if (!place(address, copy.data(), Words, true, true)) return false;
|
||||
for (auto cursor = address; cursor < end;) {
|
||||
const auto base = cursor & ~static_cast<std::uint64_t>(PageBytes - 1);
|
||||
const auto index = static_cast<std::size_t>((cursor % PageBytes) / sizeof(std::uint32_t));
|
||||
const auto count = static_cast<std::size_t>(std::min<std::uint64_t>((end - cursor) / sizeof(std::uint32_t), PageWords - index));
|
||||
auto& marked = page(base);
|
||||
marked.kept.SetRun(index, count);
|
||||
for (std::size_t word = 0; word < count; ++word) {
|
||||
marked.read.Clear(index + word);
|
||||
marked.recent.Clear(index + word);
|
||||
}
|
||||
cursor += static_cast<std::uint64_t>(count) * sizeof(std::uint32_t);
|
||||
}
|
||||
GuestMemory::GuardRead(address, KeepBytes);
|
||||
keptRanges.emplace_back(address, end);
|
||||
CaptureTotals().tablesKept.fetch_add(1, std::memory_order_relaxed);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::uint64_t ShaderMemory::TablesKept() {
|
||||
return CaptureTotals().tablesKept.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
bool ShaderMemory::invalidateRawPages() {
|
||||
bool invalidated = false;
|
||||
for (auto& [pageBase, existing] : pages) {
|
||||
@@ -525,6 +568,27 @@ bool ShaderMemory::invalidateRawPages() {
|
||||
return invalidated;
|
||||
}
|
||||
|
||||
bool ShaderMemory::invalidateChangedRawPages() {
|
||||
bool invalidated = false;
|
||||
for (auto& [pageBase, existing] : pages) {
|
||||
if (!existing->wordwise || existing->raw.None()) continue;
|
||||
bool changed = false;
|
||||
for (std::size_t index = 0; index < PageWords && !changed; ++index) {
|
||||
if (!existing->raw.Test(index)) continue;
|
||||
const auto address = pageBase + index * sizeof(std::uint32_t);
|
||||
std::uint32_t word = 0;
|
||||
GuestMemory::GuardRead(address, sizeof(word));
|
||||
std::memcpy(&word, reinterpret_cast<const void*>(address), sizeof(word));
|
||||
changed = word != existing->words[index];
|
||||
}
|
||||
if (!changed) continue;
|
||||
existing->valid.ClearMask(existing->raw);
|
||||
existing->raw.Reset();
|
||||
invalidated = true;
|
||||
}
|
||||
return invalidated;
|
||||
}
|
||||
|
||||
bool ShaderMemory::overlapsInitial(std::uint64_t begin, std::uint64_t end) const {
|
||||
if (initial.empty()) return false;
|
||||
const auto after = std::lower_bound(initial.begin(), initial.end(), begin, [](const auto& entry, std::uint64_t value) { return entry.first < value; });
|
||||
@@ -682,12 +746,12 @@ ShaderRecompiler::SrtWriteStamp ShaderMemory::stampWrites(void* context, std::ui
|
||||
return {generation, layout};
|
||||
}
|
||||
|
||||
bool ShaderMemory::Vouched(PendingWriteQuery pending, std::uint64_t address, std::uint64_t bytes, const ShaderRecompiler::SrtWriteStamp& stamp) {
|
||||
bool ShaderMemory::Vouched(PendingWriteQuery pending, std::uint64_t address, std::uint64_t bytes, const ShaderRecompiler::SrtWriteStamp& stamp, bool uncached) {
|
||||
CaptureTotals().vouchCalls.fetch_add(1, std::memory_order_relaxed);
|
||||
if (stamp.generation == 0 || bytes == 0 || address > std::numeric_limits<std::uint64_t>::max() - bytes || stamp.layout != GuestAllocations::GuestAllocationsGeneration_nid_postfix()) return false;
|
||||
if (pending != nullptr && pending(address, static_cast<std::size_t>(bytes), {}) != PendingWrite::None) return false;
|
||||
GuestMemory::FlushGpuWrites(address, static_cast<std::size_t>(bytes));
|
||||
if (GuestMemory::CollectWrites(address, static_cast<std::size_t>(bytes)) == 0) return false;
|
||||
if ((uncached ? GuestMemory::CollectWritesUncached(address, static_cast<std::size_t>(bytes)) : GuestMemory::CollectWrites(address, static_cast<std::size_t>(bytes))) == 0) return false;
|
||||
return GuestMemory::UnchangedSince(address, static_cast<std::size_t>(bytes), stamp.generation);
|
||||
}
|
||||
|
||||
@@ -1051,7 +1115,7 @@ bool SameCapturedWords(std::span<const std::uint32_t> left, std::span<const Shar
|
||||
return same;
|
||||
}
|
||||
|
||||
std::size_t VouchSharedRegions(std::span<const SharedWords> shared, std::size_t regions, ShaderMemory::PendingWriteQuery pending, std::vector<VouchedRegions>& vouched) {
|
||||
std::size_t VouchSharedRegions(std::span<const SharedWords> shared, std::size_t regions, ShaderMemory::PendingWriteQuery pending, std::vector<VouchedRegions>& vouched, std::span<const std::shared_ptr<const ShaderRecompiler::SrtGuestWords>> restampable, bool (*restamp)(const ShaderRecompiler::SrtGuestWords&, ShaderMemory::PendingWriteQuery)) {
|
||||
vouched.clear();
|
||||
if (shared.empty() || regions == 0) return 0;
|
||||
thread_local std::vector<std::pair<const ShaderRecompiler::SrtGuestWords*, bool>>* blocksSlot = nullptr;
|
||||
@@ -1065,7 +1129,8 @@ std::size_t VouchSharedRegions(std::span<const SharedWords> shared, std::size_t
|
||||
if (block == nullptr || block->low >= block->high) continue;
|
||||
auto known = std::find_if(blocks.begin(), blocks.end(), [&](const auto& seen) { return seen.first == block.get(); });
|
||||
if (known == blocks.end()) {
|
||||
const bool good = ShaderMemory::Vouched(pending, block->low, block->high - block->low, ShaderRecompiler::LoadStamp(*block));
|
||||
const bool recoverable = restamp != nullptr && std::ranges::find(restampable, block) != restampable.end();
|
||||
const bool good = ShaderMemory::Vouched(pending, block->low, block->high - block->low, ShaderRecompiler::LoadStamp(*block), recoverable) || (recoverable && restamp(*block, pending));
|
||||
(good ? totals.vouchedBlocks : totals.refusedBlocks).fetch_add(1, std::memory_order_relaxed);
|
||||
known = blocks.insert(blocks.end(), {block.get(), good});
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Float16ConversionProbe.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Float16NanProbe.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/FloatFlushProbe.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp"
|
||||
@@ -594,6 +595,8 @@ struct VulkanDevice::State {
|
||||
bool float16WidenNans = false;
|
||||
bool float16NarrowNans = false;
|
||||
bool float32DenormPreserve = false;
|
||||
bool float16HostNanCandidate = false;
|
||||
bool float16HostNans = false;
|
||||
bool probingFloatControls = false;
|
||||
bool demoteToHelperInvocation = false;
|
||||
bool earlyFragmentSampleMaskTestBeforeSampleCounting = false;
|
||||
@@ -627,11 +630,13 @@ struct VulkanDevice::State {
|
||||
bool pipelineExecutableInfo = false;
|
||||
bool maintenance8 = false;
|
||||
bool pushDescriptors = false;
|
||||
bool depthUploadImage = false;
|
||||
bool maintenance5 = false;
|
||||
bool fillModeNonSolid = false;
|
||||
bool wideLines = false;
|
||||
std::uint32_t srgbDecodeFormats = 0;
|
||||
std::uint32_t srgbCopyFormats = 0;
|
||||
std::uint32_t scaledSampledFormats = 0;
|
||||
bool storageImageWithoutFormat = false;
|
||||
VkSampleCountFlags sampleLocationSampleCounts = 0;
|
||||
VkSampleCountFlags sampleLocationGridSampleCounts = 0;
|
||||
@@ -645,6 +650,7 @@ struct VulkanDevice::State {
|
||||
bool occlusionQueryPrecise = false;
|
||||
VkDeviceSize hostImportAlignment = 0;
|
||||
bool drawInputsInPlace = true;
|
||||
bool hostPointerImport = false;
|
||||
bool dmaBufImport = false;
|
||||
bool sparseBinding = false;
|
||||
bool sparseResidencyBuffer = false;
|
||||
@@ -680,6 +686,8 @@ struct VulkanDevice::State {
|
||||
bool computeWave32 = false;
|
||||
bool meshWave32 = false;
|
||||
std::uint32_t maxComputeSubgroupSize = 0;
|
||||
std::uint32_t minComputeSubgroupSize = 0;
|
||||
bool spannedAnySubgroup = false;
|
||||
bool computeFullSubgroups = false;
|
||||
bool spannedWaves = false;
|
||||
// Indirect draw features enabled (see Graphics::Context).
|
||||
@@ -1288,11 +1296,11 @@ ComputePipelineReplayResult VulkanDevice::ReplayComputePipeline(const ComputePip
|
||||
for (std::size_t index = 0; index < VK_UUID_SIZE; ++index) require(std::to_integer<std::uint8_t>(initialCache[16 + index]) == state->properties.pipelineCacheUUID[index], "replay pipeline cache UUID differs from the driver");
|
||||
}
|
||||
require((capture.flags & VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR) == 0 || state->pipelineExecutableInfo, "captured pipeline statistics feature is not enabled");
|
||||
require(capture.stageFlags == 0 || state->computeFullSubgroups, "captured full compute subgroups are unsupported");
|
||||
if (capture.requiredSubgroupSize != 0) {
|
||||
VkPhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES_EXT};
|
||||
VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &subgroup};
|
||||
state->InstanceFunction<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(state->physical, &properties);
|
||||
require(capture.stageFlags == 0 || state->computeFullSubgroups, "captured full compute subgroups are unsupported");
|
||||
require(state->computeWave32 && capture.requiredSubgroupSize >= subgroup.minSubgroupSize && capture.requiredSubgroupSize <= subgroup.maxSubgroupSize && (subgroup.requiredSubgroupSizeStages & VK_SHADER_STAGE_COMPUTE_BIT) != 0, "captured required subgroup size is unsupported");
|
||||
}
|
||||
const auto target = Target();
|
||||
@@ -1602,6 +1610,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
if (!warning.empty()) std::fprintf(stderr, "%s\n", warning.c_str());
|
||||
}
|
||||
state->srgbDecodeFormats = Graphics::SrgbDecodeFormats(state->InstanceFunction<PFN_vkGetPhysicalDeviceFormatProperties>("vkGetPhysicalDeviceFormatProperties"), selected);
|
||||
state->scaledSampledFormats = Graphics::ScaledSampledFormats(state->InstanceFunction<PFN_vkGetPhysicalDeviceFormatProperties>("vkGetPhysicalDeviceFormatProperties"), selected);
|
||||
state->srgbCopyFormats = Graphics::SrgbCopyFormats(state->InstanceFunction<PFN_vkGetPhysicalDeviceFormatProperties>("vkGetPhysicalDeviceFormatProperties"), selected, state->srgbDecodeFormats);
|
||||
if ((state->subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT) != 0) {
|
||||
state->capabilities.push_back(spv::CapabilityGroupNonUniform);
|
||||
@@ -1629,6 +1638,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
state->deferDestruction = driver.driverID == VK_DRIVER_ID_MOLTENVK && std::getenv("APS5_NO_DEFERRED_DESTRUCTION") == nullptr;
|
||||
state->driverInfo = std::string(driver.driverName) + " " + driver.driverInfo;
|
||||
state->driverId = driver.driverID;
|
||||
state->depthUploadImage = driver.driverID == VK_DRIVER_ID_AMD_PROPRIETARY && state->properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU && std::getenv("APS5_NO_DEPTH_UPLOAD_IMAGE") == nullptr;
|
||||
state->individuallyFreeDescriptorSets = driver.driverID == VK_DRIVER_ID_MESA_LLVMPIPE;
|
||||
state->fusedExactArithmetic = driver.driverID == VK_DRIVER_ID_MOLTENVK;
|
||||
state->tessellationPipelineCache = TessellationPipelineCacheUsable(driver.driverID);
|
||||
@@ -1815,6 +1825,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
floatControls.shaderDenormPreserveFloat16 == VK_TRUE && floatControls.shaderSignedZeroInfNanPreserveFloat16 == VK_TRUE;
|
||||
float16Features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES_KHR};
|
||||
float16Features.shaderFloat16 = VK_TRUE;
|
||||
state->float16HostNanCandidate = float16Rte && std::getenv("APS5_NO_HOST_F16_NANS") == nullptr;
|
||||
if (float16Rte) {
|
||||
deviceExtensions.push_back(VK_KHR_SHADER_FLOAT16_INT8_EXTENSION_NAME);
|
||||
state->capabilities.push_back(spv::CapabilityFloat16);
|
||||
@@ -1910,22 +1921,30 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
state->memoryBudget = hasExtension(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME);
|
||||
// Guest memory is host memory: importing it lets address-based shaders use it in place instead of
|
||||
// copying every registered allocation per draw.
|
||||
if (hasExtension(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) && std::getenv("APS5_NO_HOST_IMPORT") == nullptr) {
|
||||
VkPhysicalDeviceMaintenance3Properties maintenance3{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES};
|
||||
VkPhysicalDeviceDriverProperties driverProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES, &maintenance3};
|
||||
VkPhysicalDeviceExternalMemoryHostPropertiesEXT hostProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT, &driverProperties};
|
||||
VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &hostProperties};
|
||||
const bool importsAllowed = std::getenv("APS5_NO_HOST_IMPORT") == nullptr;
|
||||
VkPhysicalDeviceMaintenance3Properties maintenance3{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES};
|
||||
VkPhysicalDeviceDriverProperties driverProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES, &maintenance3};
|
||||
VkPhysicalDeviceExternalMemoryHostPropertiesEXT hostProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT, &driverProperties};
|
||||
state->hostPointerImport = importsAllowed && hasExtension(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME);
|
||||
if (importsAllowed) {
|
||||
VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, state->hostPointerImport ? static_cast<void*>(&hostProperties) : static_cast<void*>(&driverProperties)};
|
||||
state->InstanceFunction<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(selected, &properties);
|
||||
state->hostImportAlignment = hostProperties.minImportedHostPointerAlignment;
|
||||
}
|
||||
#ifndef _WIN32
|
||||
state->dmaBufImport = importsAllowed && driverProperties.driverID != VK_DRIVER_ID_NVIDIA_PROPRIETARY && hasExtension(VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME) && hasExtension(VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME);
|
||||
#endif
|
||||
if (state->hostPointerImport || state->dmaBufImport) {
|
||||
#ifdef _WIN32
|
||||
state->hostImportAlignment = hostProperties.minImportedHostPointerAlignment;
|
||||
constexpr bool windows = true;
|
||||
#else
|
||||
state->hostImportAlignment = state->hostPointerImport ? hostProperties.minImportedHostPointerAlignment : static_cast<VkDeviceSize>(sysconf(_SC_PAGESIZE));
|
||||
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));
|
||||
if (!compileOnly) Graphics::SetHostImportWindow(8ull << 20u);
|
||||
if (!compileOnly) Graphics::SetHostImportMaxBytes(maintenance3.maxMemoryAllocationSize);
|
||||
if (!compileOnly) Pm4::RequestImportableGds(state->properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU);
|
||||
if (!compileOnly) Pm4::RequestImportableGds(state->hostPointerImport && state->properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU);
|
||||
#ifdef _WIN32
|
||||
// Imported pages are locked; locking is bounded by the process working-set minimum.
|
||||
if (const char* value = std::getenv("APS5_WORKING_SET_MIB"); value != nullptr && !compileOnly) {
|
||||
@@ -1933,9 +1952,8 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
if (!SetProcessWorkingSetSizeEx(GetCurrentProcess(), bytes, bytes * 2, QUOTA_LIMITS_HARDWS_MIN_DISABLE | QUOTA_LIMITS_HARDWS_MAX_DISABLE)) std::fprintf(stderr, "[gpu] SetProcessWorkingSetSizeEx failed: %lu\n", GetLastError());
|
||||
}
|
||||
#endif
|
||||
deviceExtensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME);
|
||||
if (state->hostPointerImport) deviceExtensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME);
|
||||
#ifndef _WIN32
|
||||
state->dmaBufImport = driverProperties.driverID != VK_DRIVER_ID_NVIDIA_PROPRIETARY && hasExtension(VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME) && hasExtension(VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME);
|
||||
if (state->dmaBufImport) {
|
||||
deviceExtensions.push_back(VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME);
|
||||
deviceExtensions.push_back(VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME);
|
||||
@@ -2399,6 +2417,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
state->meshWave32 = state->meshShader && subgroupSizeFeatures.subgroupSizeControl == VK_TRUE && subgroupSize.minSubgroupSize <= 32u && subgroupSize.maxSubgroupSize >= 32u &&
|
||||
(subgroupSize.requiredSubgroupSizeStages & VK_SHADER_STAGE_MESH_BIT_EXT) != 0;
|
||||
state->maxComputeSubgroupSize = subgroupSize.maxSubgroupSize;
|
||||
state->minComputeSubgroupSize = subgroupSize.minSubgroupSize;
|
||||
state->computeFullSubgroups = state->computeWave32 && subgroupSizeFeatures.computeFullSubgroups == VK_TRUE;
|
||||
}
|
||||
if (state->computeWave32 || state->meshWave32) {
|
||||
@@ -2413,7 +2432,8 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
APS5_LOG_OUT("Wave32 programs run on subgroups of %u: compute %d, mesh %d", 32u, state->computeWave32, state->meshWave32);
|
||||
}
|
||||
state->spannedWaves = state->computeFullSubgroups && std::getenv("APS5_NO_SPANNED_WAVE") == nullptr;
|
||||
APS5_LOG_OUT("single-wave wave64 compute spans two full 32-lane subgroups: %d", state->spannedWaves);
|
||||
state->spannedAnySubgroup = state->spannedWaves && state->minComputeSubgroupSize < 32u;
|
||||
APS5_LOG_OUT("single-wave wave64 compute spans full subgroups: %d, of any size: %d", state->spannedWaves, state->spannedAnySubgroup);
|
||||
timelineFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES_KHR};
|
||||
timelineFeatures.timelineSemaphore = VK_TRUE;
|
||||
if (state->timelineSemaphores) {
|
||||
@@ -2811,6 +2831,14 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
};
|
||||
std::fprintf(stderr, "[float-controls] f16 to f32 NaN results: %s; f32 to f16 NaN results: %s (%.0f ms)\n", describe(probe.widen, state->float16WidenNans).c_str(), describe(probe.narrow, state->float16NarrowNans).c_str(), std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - probeStart).count());
|
||||
}
|
||||
if (state->float16HostNanCandidate) {
|
||||
const auto probeStart = std::chrono::steady_clock::now();
|
||||
state->probingFloatControls = true;
|
||||
const auto probe = ProbeFloat16HostNans(*this, Target());
|
||||
state->probingFloatControls = false;
|
||||
state->float16HostNans = probe.mismatches == 0u;
|
||||
std::fprintf(stderr, "[float-controls] f16 NaN results with IEEE_MODE clear: %s (%u of %u probe results differ from the selected NaN, %.0f ms)\n", state->float16HostNans ? "host" : "selected", probe.mismatches, probe.compared, std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - probeStart).count());
|
||||
}
|
||||
// A device without a window is usually replaced by the window's device before the title draws
|
||||
// (Driver::AttachWindow): its replay starts at its first draw or dispatch instead, so the
|
||||
// journal is replayed once, on the device the title draws with.
|
||||
@@ -2835,7 +2863,9 @@ std::uint32_t VulkanDevice::computeSubgroupSize(const ShaderRecompiler::Recompil
|
||||
|
||||
VkPipelineShaderStageCreateFlags VulkanDevice::computeStageFlags(const ShaderRecompiler::RecompileResult& shader) const {
|
||||
if (!shader.fullSubgroups) return 0;
|
||||
require(state->computeFullSubgroups && computeSubgroupSize(shader) == 32u, "a spanned wave64 program needs full 32-lane compute subgroups");
|
||||
require(state->computeFullSubgroups, "a spanned wave64 program needs full compute subgroups");
|
||||
if (shader.hostSubgroupSize == 0u) return VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT | VK_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT;
|
||||
require(computeSubgroupSize(shader) == 32u, "a spanned wave64 program needs full 32-lane compute subgroups");
|
||||
return VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT;
|
||||
}
|
||||
|
||||
@@ -2954,6 +2984,10 @@ void VulkanDevice::WaitIdle() {
|
||||
}
|
||||
std::unique_lock presentQueueLock(state->presentQueueMutex, std::defer_lock);
|
||||
if (state->presentQueue != VK_NULL_HANDLE) presentQueueLock.lock();
|
||||
std::unique_lock settleQueueLock(state->settleQueueMutex, std::defer_lock);
|
||||
if (state->settleQueue != VK_NULL_HANDLE) settleQueueLock.lock();
|
||||
std::unique_lock sparseQueueLock(state->sparseQueueMutex, std::defer_lock);
|
||||
if (state->sparseQueue != VK_NULL_HANDLE) sparseQueueLock.lock();
|
||||
check(state->DeviceFunction<PFN_vkDeviceWaitIdle>("vkDeviceWaitIdle")(state->device), "vkDeviceWaitIdle");
|
||||
Graphics::CheckPixelFunctionLds(graphicsContext());
|
||||
APS5_LOG_CHARS_OUT_DEBUG("VulkanDevice::WaitIdle complete");
|
||||
@@ -2973,7 +3007,7 @@ void VulkanDevice::StoreIdleResults(bool reapFirst, const std::function<bool()>&
|
||||
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Flush);
|
||||
std::lock_guard gpuLock(GuestMemory::GpuMutex());
|
||||
const auto lease = GuestAllocations::GuestAllocationsAcquire_nid_postfix();
|
||||
static_cast<void>(Graphics::StorageTexture::FlushAllPendingUntil("idle", stop, state->device));
|
||||
static_cast<void>(Graphics::StorageTexture::FlushAllPendingUntil("idle", GuestMemory::YieldToGpuMutexWaiters(stop), state->device));
|
||||
SubmitRecorded(reapFirst);
|
||||
}
|
||||
|
||||
@@ -4616,6 +4650,10 @@ std::string VulkanDevice::DriverInfo() const {
|
||||
return state->driverInfo.empty() ? std::to_string(state->properties.driverVersion) : state->driverInfo;
|
||||
}
|
||||
|
||||
VkDriverId VulkanDevice::DriverId() const {
|
||||
return state->driverId;
|
||||
}
|
||||
|
||||
bool VulkanDevice::BdaAtomicsUsable() const {
|
||||
return AgcDriver::BdaAtomicsUsable(state->driverId);
|
||||
}
|
||||
@@ -4666,6 +4704,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::Target() const {
|
||||
require(state->shaderProfile != nullptr, "shader device profile is unavailable");
|
||||
auto target = state->shaderProfile->Target();
|
||||
target.float32FlushToZero = state->float32FlushToZero && !state->float32FlushComputeOnly;
|
||||
target.float16HostNans = state->float16HostNans;
|
||||
target.fusedExactArithmetic = state->fusedExactArithmetic;
|
||||
target.hostInterpolationFirst = state->hostInterpolationFirst;
|
||||
target.float32DenormPreserve = state->float32DenormPreserve;
|
||||
@@ -4690,6 +4729,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::buildTarget() const {
|
||||
target.float64DenormPreserve = state->float64DenormPreserve;
|
||||
target.float16DenormPreserve = state->float16DenormPreserve;
|
||||
target.spannedWaves = state->spannedWaves;
|
||||
target.spannedAnySubgroup = state->spannedAnySubgroup;
|
||||
target.depthRangeRemap = !state->depthRangeUnrestricted;
|
||||
target.fixedPushSlots = state->graphicsPipelineLibrary;
|
||||
target.registrationModules = state->graphicsPipelineLibrary;
|
||||
@@ -4701,6 +4741,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::buildTarget() const {
|
||||
target.deviceScopeLdsMemoryBarriers = !state->workgroupScopeFences;
|
||||
target.ldsLockFences = state->ldsLockFences;
|
||||
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;
|
||||
target.maxImageArrayLayers = limits.maxImageArrayLayers;
|
||||
target.vertexSubgroups = (state->subgroup.supportedStages & VK_SHADER_STAGE_VERTEX_BIT) != 0;
|
||||
@@ -4799,7 +4840,9 @@ Graphics::Context VulkanDevice::buildContext() const {
|
||||
};
|
||||
context.pipelineCacheSynchronization = state->pipelineCache ? &state->pipelineCache->Synchronization() : nullptr;
|
||||
context.individuallyFreeDescriptorSets = state->individuallyFreeDescriptorSets;
|
||||
context.hostImportsInHeapUsage = Graphics::HostImportsInHeapUsage(state->driverId);
|
||||
context.tessellationPipelineCache = state->tessellationPipelineCache;
|
||||
context.hostPointerImport = state->hostPointerImport;
|
||||
context.dmaBufImport = state->dmaBufImport;
|
||||
context.sparseBinding = state->sparseBinding;
|
||||
context.sparseResidencyBuffer = state->sparseResidencyBuffer;
|
||||
@@ -4885,8 +4928,10 @@ Graphics::Context VulkanDevice::buildContext() const {
|
||||
context.pipelineExecutableInfo = state->pipelineExecutableInfo;
|
||||
context.maintenance8 = state->maintenance8;
|
||||
context.pushDescriptors = state->pushDescriptors;
|
||||
context.depthUploadImage = state->depthUploadImage;
|
||||
context.srgbDecodeFormats = state->srgbDecodeFormats;
|
||||
context.srgbCopyFormats = state->srgbCopyFormats;
|
||||
context.scaledSampledFormats = state->scaledSampledFormats;
|
||||
context.sampleLocationSampleCounts = state->sampleLocationSampleCounts;
|
||||
context.sampleLocationGridSampleCounts = state->sampleLocationGridSampleCounts;
|
||||
context.sampleLocationGridSizes = state->sampleLocationGridSizes;
|
||||
@@ -4951,7 +4996,12 @@ bool VulkanDevice::PrebuildGraphicsLibraries(const Graphics::ShaderStages& stage
|
||||
return Graphics::Pipeline::Prebuild(context, state, Graphics::VertexInputLayout{}, layouts.View(), group);
|
||||
}
|
||||
|
||||
void VulkanDevice::Draw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::shared_ptr<const DrawRecipe>* recipe, const DrawTraceContext* trace, std::uint64_t shape) {
|
||||
std::vector<std::uint32_t> VulkanDevice::DrawContentKey(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders) const {
|
||||
if (!state->contextReady) return {};
|
||||
return Graphics::DrawResourceContentKey(state->context, graphics, draw, shaders);
|
||||
}
|
||||
|
||||
void VulkanDevice::Draw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::shared_ptr<const DrawRecipe>* recipe, const DrawTraceContext* trace, std::uint64_t shape, const std::vector<std::uint32_t>* contentKey) {
|
||||
startJournalReplay();
|
||||
for (const auto& shader : shaders) {
|
||||
require(shader.program != nullptr, "missing compiled shader");
|
||||
@@ -4962,7 +5012,7 @@ void VulkanDevice::Draw(const Graphics::State& graphics, const Pm4::DrawParamete
|
||||
static const bool traceDraws = std::getenv("APS5_TRACE_DRAWS") != nullptr;
|
||||
if (traceDraws) APS5_LOG_OUT("VulkanDevice::Draw indices=%u instances=%u indexSize=%u address=0x%llx shaders=%zu colorTarget=%u", draw.indexCount, draw.instanceCount, draw.indexSize, static_cast<unsigned long long>(draw.indexAddress), shaders.size(), static_cast<unsigned>(graphics.hasColorTarget));
|
||||
const auto context = graphicsContext();
|
||||
Graphics::Draw(context, graphics, draw, shaders, snapshots, recipe, trace, shape);
|
||||
Graphics::Draw(context, graphics, draw, shaders, snapshots, recipe, trace, shape, contentKey);
|
||||
if (traceDraws) APS5_LOG_CHARS_OUT("VulkanDevice::Draw complete");
|
||||
}
|
||||
|
||||
@@ -6522,7 +6572,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::recordCompletedDispatch(const Shader
|
||||
const auto syncStart = std::chrono::steady_clock::now();
|
||||
recorder.Sync();
|
||||
timer.phase(PhaseSync);
|
||||
if (resources->HoldsLease()) Graphics::CountLeaseOutcome(true, 0);
|
||||
if (resources->HoldsLease()) Graphics::CountLeaseOutcome(true, 0, !resources->BdaReadOnly());
|
||||
if (profile) {
|
||||
// APS5_PROFILE_DRAW: the [recorder] line's "address-based" syncs by program, every 10 s,
|
||||
// so the programs still waiting here are known (under the GpuMutex, like the rest).
|
||||
@@ -6551,7 +6601,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::recordCompletedDispatch(const Shader
|
||||
} else if (resources->HoldsLease()) {
|
||||
// The lease is in the open batch (kept above, nothing submitted since): the pin waiter
|
||||
// finishes the recorder up to that batch's serial. Prints the [address-sync] leases line.
|
||||
Graphics::CountLeaseOutcome(false, recorder.Submissions() + 1);
|
||||
Graphics::CountLeaseOutcome(false, recorder.Submissions() + 1, !resources->BdaReadOnly());
|
||||
}
|
||||
if (TraceDispatchIo()) std::fprintf(stderr, "[dispatch-io] %s:%s\n", groupsText, resources->Describe().c_str());
|
||||
WatchMemory(programAddress);
|
||||
|
||||
@@ -48,9 +48,6 @@ struct SlabSlot {
|
||||
// builds no longer sweeps the large ones out. Free slots are kept per size, usage and memory
|
||||
// properties, so a lookup does not scan the other slots. Reuse is safe because a Buffer is only released once
|
||||
// the GPU work using it completed (kept until the batch fence, or after a CommandBatch wait).
|
||||
// APS5_NO_BUFFER_CLASSES=1 matches exact sizes only, as before; APS5_BUFFER_POOL_SLOTS=<n> sets the
|
||||
// slot count (the bound applies to each tier below, and is held to a sixth of the device's
|
||||
// maxMemoryAllocationCount so the three tiers keep half of it free).
|
||||
//
|
||||
// The size classes and the exact-size allocations are retained in two tiers with a budget each:
|
||||
// the multi-MiB texture scratch buffers that come back from a batch (GPU-direct uploads and
|
||||
@@ -154,8 +151,6 @@ private:
|
||||
std::uint64_t misses = 0;
|
||||
std::uint64_t evictions = 0;
|
||||
};
|
||||
// The tier a buffer of `capacity` and `properties` is retained in (the large one for everything
|
||||
// when shared; the device tier for device-local memory while it has a budget).
|
||||
Tier& tierFor(std::size_t capacity, VkMemoryPropertyFlags properties);
|
||||
static bool DeviceTierEnabled();
|
||||
static VkDeviceSize deviceBudget(const Context& context);
|
||||
@@ -188,6 +183,7 @@ private:
|
||||
Tier smallTier;
|
||||
Tier largeTier;
|
||||
Tier deviceTier;
|
||||
Tier smallDeviceTier;
|
||||
std::chrono::steady_clock::time_point heapRead{};
|
||||
bool heapOver = false;
|
||||
VkDeviceSize imageBudget = 0;
|
||||
|
||||
@@ -224,11 +224,12 @@ struct Context {
|
||||
TextureCache* textureCache = nullptr;
|
||||
VkPipelineCache pipelineCache = VK_NULL_HANDLE;
|
||||
bool depthClamp = false;
|
||||
// Nonzero when VK_EXT_external_memory_host is enabled: the required host pointer alignment.
|
||||
VkDeviceSize hostImportAlignment = 0;
|
||||
mutable std::vector<std::pair<std::pair<VkFormat, std::uint32_t>, bool>> stencilShadowCopyProbes;
|
||||
bool drawInputsInPlace = true;
|
||||
bool discreteGpu = false;
|
||||
bool integratedGpu = false;
|
||||
bool hostPointerImport = true;
|
||||
bool dmaBufImport = false;
|
||||
bool sparseBinding = false;
|
||||
bool sparseResidencyBuffer = false;
|
||||
@@ -293,6 +294,7 @@ struct Context {
|
||||
std::uint32_t imageTableCapacity = 0;
|
||||
std::uint32_t samplerTableCapacity = 0;
|
||||
bool individuallyFreeDescriptorSets = false;
|
||||
bool hostImportsInHeapUsage = false;
|
||||
bool tessellationPipelineCache = true;
|
||||
bool imageTableUpdateAfterBind = false;
|
||||
bool samplerTableUpdateAfterBind = false;
|
||||
@@ -321,11 +323,13 @@ struct Context {
|
||||
bool pipelineExecutableInfo = false;
|
||||
bool maintenance8 = false;
|
||||
bool pushDescriptors = false;
|
||||
bool depthUploadImage = false;
|
||||
bool graphicsPipelineLibrary = false;
|
||||
bool pipelineLinkTimeOptimization = true;
|
||||
bool dynamicColorWriteMask = false;
|
||||
std::uint32_t srgbDecodeFormats = 0;
|
||||
std::uint32_t srgbCopyFormats = 0;
|
||||
std::uint32_t scaledSampledFormats = 0;
|
||||
bool provokingVertexLast = false;
|
||||
bool provokingVertexModePerPipeline = false;
|
||||
bool singlePassStorage = false;
|
||||
|
||||
@@ -37,6 +37,9 @@ std::uint64_t DepthSurfacesReleased();
|
||||
std::uint64_t DepthSliceBytes(VkExtent2D extent, std::uint32_t bytesPerTexel);
|
||||
bool DirectDepthCopy(const Context& context, VkFormat depthFormat, VkImageAspectFlagBits aspect, VkFormat colorFormat);
|
||||
void SetDirectDepthCopy(bool enabled);
|
||||
bool DepthUploadImage(const Context& context);
|
||||
void SetDepthUploadImage(bool enabled);
|
||||
std::uint64_t DepthUploadCount();
|
||||
std::uint64_t DirectDepthCopyCount();
|
||||
void SetDepthTransferPasses(bool enabled);
|
||||
std::uint64_t DepthTransferPassCount();
|
||||
@@ -111,7 +114,7 @@ struct DepthExpandStatistics {
|
||||
std::uint64_t stored = 0;
|
||||
};
|
||||
DepthExpandStatistics DepthExpandCounts();
|
||||
std::array<std::uint32_t, 8> DepthCopySourceWords(const DepthTarget& target);
|
||||
std::array<std::uint32_t, 8> DepthCopySourceWords(const DepthTarget& target, bool stencil = false);
|
||||
class DepthCopySourceScope {
|
||||
public:
|
||||
explicit DepthCopySourceScope(bool active);
|
||||
|
||||
@@ -35,7 +35,8 @@ struct DrawTraceContext {
|
||||
// `recipe`, when given, receives the DrawRecipe a recorded, cacheable, reusable, non-indirect draw
|
||||
// built for its draw-cache entry (design_cpu_final M8; null otherwise, and always under
|
||||
// APS5_NO_DRAW_RECIPE=1).
|
||||
void Draw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots = {}, std::shared_ptr<const DrawRecipe>* recipe = nullptr, const DrawTraceContext* trace = nullptr, std::uint64_t shape = 0);
|
||||
void Draw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots = {}, std::shared_ptr<const DrawRecipe>* recipe = nullptr, const DrawTraceContext* trace = nullptr, std::uint64_t shape = 0, const std::vector<std::uint32_t>* contentKey = nullptr);
|
||||
std::vector<std::uint32_t> DrawResourceContentKey(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders);
|
||||
|
||||
struct PixelFunctionLdsLayouts {
|
||||
VkDescriptorSetLayout empty = VK_NULL_HANDLE;
|
||||
@@ -66,7 +67,8 @@ struct DrawInputCopy {
|
||||
std::uint64_t registryGeneration = 0;
|
||||
Recorder::OwnedDrawInputProof owned;
|
||||
};
|
||||
DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uint64_t address, std::size_t bytes, std::size_t alignment, Recorder::SnapshotUse use, std::size_t from = 0);
|
||||
DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uint64_t address, std::size_t bytes, std::size_t alignment, Recorder::SnapshotUse use, std::size_t from = 0, bool hostOnly = false);
|
||||
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);
|
||||
@@ -111,7 +113,7 @@ MeshArguments ResolveMeshArguments(const Pm4::DrawArguments& record, const MeshA
|
||||
// storage cache, the template is gone, the pipeline is gone from the pipeline store, or the
|
||||
// template's proof failed (ShaderResources::ProveCurrent; the template is removed from the
|
||||
// resource cache and kept by the batch).
|
||||
enum class DrawRecipeMiss : std::uint8_t { None, NotRecordable, TargetGone, TemplateGone, ObjectsGone, Proof, Count };
|
||||
enum class DrawRecipeMiss : std::uint8_t { None, NotRecordable, TargetGone, TemplateGone, ObjectsGone, Proof, Buffers, Count };
|
||||
const char* DrawRecipeMissName(DrawRecipeMiss miss);
|
||||
struct DrawRecipeOutcome {
|
||||
bool recorded = false;
|
||||
@@ -190,6 +192,12 @@ using AddressDrawReuseCounts = std::array<std::uint64_t, static_cast<std::size_t
|
||||
AddressDrawReuseCounts AddressDrawReuseCounters();
|
||||
const char* AddressDrawReuseName(AddressDrawReuse outcome);
|
||||
std::uint64_t AddressDrawReuseVerifications();
|
||||
struct VertexPlanScratchState {
|
||||
bool busy = false;
|
||||
std::size_t resting = 0;
|
||||
std::size_t capacity = 0;
|
||||
};
|
||||
VertexPlanScratchState ThreadVertexPlanScratch();
|
||||
enum class DrawStopForTest { None = 0, ReturnAfterResolve = 1, ThrowAfterResolve = 2 };
|
||||
void SetSpaceKeepFailuresForTest(std::uint32_t count);
|
||||
void SetDrawStopAfterResolveForTest(DrawStopForTest stop);
|
||||
|
||||
@@ -134,6 +134,8 @@ void SetHostImportWindow(std::uint64_t bytes);
|
||||
void SetHostImportRangeWindow(std::uint64_t bytes);
|
||||
void SetHostImportBudget(std::uint64_t bytes);
|
||||
std::uint64_t HostImportBudgetFor(const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceMemoryBudgetPropertiesEXT* reported, std::uint64_t configured, std::uint64_t liveBytes);
|
||||
bool HostImportsInHeapUsage(VkDriverId driver);
|
||||
VkPhysicalDeviceMemoryBudgetPropertiesEXT UsageWithoutHostImports(const VkPhysicalDeviceMemoryProperties& memory, VkPhysicalDeviceMemoryBudgetPropertiesEXT reported, std::uint64_t liveBytes, bool importsInUsage);
|
||||
std::uint64_t HostImportBudgetWith(std::uint64_t configured, bool set, std::uint64_t reported, bool allocationFailed, std::uint64_t ceiling);
|
||||
void SetAddressCopyLimit(std::uint64_t bytes);
|
||||
void SetHostImportDeferredSettles(bool enabled);
|
||||
@@ -213,11 +215,15 @@ struct HostImportsProof {
|
||||
};
|
||||
// Whether the table still matches `proof` (one lock); false for an empty or stale proof.
|
||||
bool HostImportsUnchanged(const Context& context, const HostImportsProof& proof);
|
||||
bool TouchHostImportsIfUnchanged(const Context& context, const HostImportsProof& proof, std::span<const HostImport* const> imports);
|
||||
bool HostImportsReconciledUnchanged(const Context& context, const HostImportsProof& proof);
|
||||
// The table's identity when it is reconciled with the live registry (one lock), else empty.
|
||||
HostImportsProof HostImportsIdentity(const Context& context);
|
||||
std::uint64_t RetiredImportSerial();
|
||||
void SetDeviceLocalFullForTests(bool full);
|
||||
std::uint64_t StagingShadowsRefused();
|
||||
std::uint64_t ChangedCopySnapshotBytes();
|
||||
std::uint64_t ChangedCopySnapshotsMade();
|
||||
|
||||
// Identity of the read-only image mirror serving [address, address + bytes) (the counterpart of
|
||||
// HostImportSerial for main-image ranges, which no import serves): a serial unique for the life of
|
||||
@@ -237,12 +243,15 @@ std::uint64_t ImageMirrorSerial(const Context& context, std::uint64_t address, s
|
||||
// when synced, and the waiter targets the newest of them. Under APS5_PROFILE_DRAW CountLeaseOutcome
|
||||
// prints the [address-sync] leases line every 10 s from LeaseCounters (cumulative).
|
||||
bool SyncLeaseWork();
|
||||
void CountLeaseOutcome(bool synced, std::uint64_t batchSerial);
|
||||
void CountLeaseOutcome(bool synced, std::uint64_t batchSerial, bool writes);
|
||||
void FinishLeaseWork();
|
||||
void FinishLeaseWrites();
|
||||
bool LeaseWorkPending();
|
||||
bool LeaseWritesMayBePending();
|
||||
struct LeaseStats {
|
||||
std::uint64_t deferred = 0;
|
||||
std::uint64_t synced = 0;
|
||||
std::uint64_t writing = 0;
|
||||
// Pin-contention waits made by guest threads (the waiter calls), how many of them finished the
|
||||
// newest lease batch, how many had to drain the whole recorder instead (no lease batch noted),
|
||||
// how many only dropped the cached address space (no GPU wait, see AddressSpaceStats), and
|
||||
@@ -437,6 +446,8 @@ public:
|
||||
return false;
|
||||
}
|
||||
void MarkStagedWrites() const;
|
||||
void NoteCarriedShadows(const Recorder& recorder) const;
|
||||
static std::uint64_t CarriedShadowCopies();
|
||||
// Whether registered allocations are pinned until write-back (address-based shaders): by this
|
||||
// build's own lease, or by the cached address space it holds.
|
||||
bool HoldsLease() const { return !lease.empty() || space != nullptr; }
|
||||
@@ -524,6 +535,7 @@ private:
|
||||
VkDeviceAddress copySourceAddress = 0;
|
||||
bool copiedBack = false;
|
||||
std::shared_ptr<Buffer> shadowCopy;
|
||||
std::weak_ptr<Buffer> releasedShadowCopy;
|
||||
// An element the shader updates atomically lies inside (AddWritable's `atomic`).
|
||||
bool atomic = false;
|
||||
bool swept = false;
|
||||
|
||||
@@ -100,6 +100,13 @@ bool TakeMultisampledClear(MultisampledCmask& cmask, MultisampledColorFill& colo
|
||||
SampleOrderTarget MultisampleTargetOrderTarget(const Context& context, const ColorTarget& target);
|
||||
std::shared_ptr<Texture> MultisampleTargetTexture(const Context& context, const GuestTextureResource& resource, VkComponentMapping components, VkImageViewType viewType = VK_IMAGE_VIEW_TYPE_2D);
|
||||
std::shared_ptr<Texture> MultisampleTargetFirstSample(const Context& context, const GuestTextureResource& resource, VkComponentMapping components);
|
||||
struct MultisampleColorSnapshot {
|
||||
std::vector<std::byte> original;
|
||||
std::vector<std::byte> current;
|
||||
};
|
||||
|
||||
std::vector<std::byte> ReadMultisampleTargetSamples_nid_no_patch(const Context& context, const ColorTarget& target);
|
||||
MultisampleColorSnapshot ReadMultisampleTargetColorSnapshot_nid_no_patch(const Context& context, const ColorTarget& target);
|
||||
VkImageView MultisampleTargetView(const Context& context, const ColorTarget& target, VkImage* image = nullptr);
|
||||
VkImageView MultisampleTargetView(const Context& context, const ColorTarget& target, std::shared_ptr<void>& owner, VkImage* image = nullptr);
|
||||
void PrepareMultisampleTargetForDraw_nid_no_patch(const Context& context, const ColorTarget& target);
|
||||
@@ -118,6 +125,8 @@ std::optional<std::vector<ShaderRecompiler::BdaAbi::Range>> ExcludeMultisampleTa
|
||||
void InstallResidentImageReadGuard_nid_no_patch();
|
||||
void UpdateResidentImageUnmapObserver_nid_no_patch();
|
||||
void ClaimMultisampleTargetMemory(std::uint64_t address, std::uint64_t bytes);
|
||||
bool MultisampleColorTargetOverlaps(std::uint64_t address, std::uint64_t bytes);
|
||||
void ClaimMultisampleTargetStore(std::uint64_t address, std::uint64_t bytes);
|
||||
void GuardOneFragmentFmask(const Context& context, const ColorTarget& target);
|
||||
bool HoldsMultisampleTargetsLock();
|
||||
void RequireNoMultisampleTarget(std::uint64_t address, std::size_t bytes, const char* access);
|
||||
|
||||
@@ -227,9 +227,12 @@ public:
|
||||
static constexpr std::size_t UnwrittenSnapshotEntries = 4096;
|
||||
static constexpr std::size_t DrawInputBudget = std::size_t{1024} << 20u;
|
||||
static constexpr std::size_t DrawInputEntries = 16384;
|
||||
static constexpr std::size_t DrawInputMirrorBudget = std::size_t{512} << 20u;
|
||||
static bool DrawInputMirrors();
|
||||
std::pair<std::size_t, std::size_t> DrawInputBytes() const;
|
||||
std::shared_ptr<Buffer> UnwrittenDrawSnapshot(std::uint64_t address, std::size_t bytes, const std::array<std::uint64_t, 3>& stamp, VkDeviceSize* offset = nullptr);
|
||||
void NoteUnwrittenDrawSnapshot(std::uint64_t address, std::size_t bytes, const std::array<std::uint64_t, 3>& stamp, std::shared_ptr<Buffer> buffer, VkDeviceSize offset = 0);
|
||||
std::shared_ptr<Buffer> ReusableDrawSnapshot(std::uint64_t address, std::size_t bytes, SnapshotUse use = SnapshotUse::Storage, std::uint32_t* derived = nullptr, std::uint64_t generation = 0, VkDeviceSize* offset = nullptr, std::size_t from = 0, std::uint32_t* lowest = nullptr);
|
||||
std::shared_ptr<Buffer> ReusableDrawSnapshot(std::uint64_t address, std::size_t bytes, SnapshotUse use = SnapshotUse::Storage, std::uint32_t* derived = nullptr, std::uint64_t generation = 0, VkDeviceSize* offset = nullptr, std::size_t from = 0, std::uint32_t* lowest = nullptr, bool mirrored = false);
|
||||
struct OwnedDrawInputProof {
|
||||
std::vector<std::uint64_t> words;
|
||||
std::uint64_t since = 0;
|
||||
@@ -255,11 +258,13 @@ public:
|
||||
bool KnownHighestIndex(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::optional<std::uint32_t>& highest, std::uint32_t* lowest = nullptr);
|
||||
void KeepHighestIndex(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint64_t generation, std::uint64_t registryGeneration, std::optional<std::uint32_t> highest, std::uint32_t lowest = 0);
|
||||
void OnComplete(std::function<void()> action);
|
||||
void OnWriteComplete(std::uint64_t address, std::size_t bytes, std::function<void()> action);
|
||||
void NotePendingWrite(std::uint64_t address, std::size_t bytes);
|
||||
void NotePendingFill(std::uint64_t address, std::size_t bytes, std::uint8_t value);
|
||||
void NotePendingWordFill(std::uint64_t address, std::size_t bytes, std::uint32_t word);
|
||||
// Notes several [begin, end) ranges and publishes the snapshot once (a dispatch writes many buffers).
|
||||
void NotePendingWrites(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges);
|
||||
void NoteStampedWrites(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges);
|
||||
static constexpr std::int16_t ReachValue = -2;
|
||||
void NotePendingReach(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges);
|
||||
bool PendingWriteOverlaps(std::uint64_t address, std::size_t bytes) const;
|
||||
@@ -269,6 +274,8 @@ public:
|
||||
// memory; its completion stores are the caller's business, see VulkanDevice::CopyBuffer).
|
||||
bool PendingWriteSettled(std::uint64_t address, std::size_t bytes) const;
|
||||
std::uint64_t LastWriteNote(std::uint64_t address, std::size_t bytes) const;
|
||||
std::uint64_t WriteNoteCount() const { return writeNoteCount; }
|
||||
std::vector<std::uint64_t> StampedNotesSince(std::uint64_t note) const;
|
||||
std::uint64_t NewestWriteNote(std::uint64_t address, std::size_t bytes) const;
|
||||
std::uint64_t NewestStoreNote(std::uint64_t address, std::size_t bytes) const;
|
||||
struct PendingWrite {
|
||||
@@ -359,6 +366,11 @@ public:
|
||||
bool CountingSamples() const { return countingSamples; }
|
||||
bool RecordMeshArguments(VkCommandBuffer commands, VkDeviceAddress record, VkDeviceAddress arguments, std::span<const std::uint32_t, 7> rules);
|
||||
bool RecordChangedCopy(VkCommandBuffer commands, VkDeviceAddress result, VkDeviceAddress snapshot, VkDeviceAddress target, std::uint32_t dwords, VkDeviceAddress counter = 0);
|
||||
struct BoundWords {
|
||||
VkBuffer buffer = VK_NULL_HANDLE;
|
||||
VkDeviceSize offset = 0;
|
||||
};
|
||||
bool RecordBoundChangedCopy(VkCommandBuffer commands, BoundWords result, BoundWords snapshot, BoundWords target, std::uint32_t dwords, VkBuffer counter = VK_NULL_HANDLE);
|
||||
std::uint64_t SamplesTotal();
|
||||
bool DumpSamples(VkDeviceAddress target, std::uint64_t address = 0);
|
||||
void NoteSampledDraw(VkCommandBuffer commands);
|
||||
@@ -414,10 +426,13 @@ public:
|
||||
// not, before recording): the run is then recorded in place, with a trailing barrier toward
|
||||
// the later work, and the next store starts a new run. Within a run a store contiguous with
|
||||
// the last queued one joins its vkCmdUpdateBuffer, one inside it replaces its bytes (the
|
||||
// later store wins, as in program order), and one overlapping a store queued earlier gets a
|
||||
// transfer-to-transfer barrier first (WAW). Debug aids: APS5_LABEL_RUNS_INLINE=1 records the
|
||||
// stores at once and closes the run at the next command (Commands()) or at Submit, as
|
||||
// before; APS5_NO_LABEL_RUNS=1 gives every store barriers of its own.
|
||||
// later store wins, as in program order), and every store after the first of its group gets a
|
||||
// transfer-to-transfer barrier first (WAW for one overlapping a store queued earlier, program
|
||||
// order otherwise), so the run's stores land for a polling host in program order too and each
|
||||
// earlier one is available to it. Debug
|
||||
// aids: APS5_LABEL_RUNS_INLINE=1 records the stores at once and closes the run at the next
|
||||
// command (Commands()) or at Submit, as before; APS5_NO_LABEL_RUNS=1 gives every store
|
||||
// barriers of its own.
|
||||
void RecordStore(VkBuffer buffer, VkDeviceSize offset, std::span<const std::byte> bytes, std::uint64_t address);
|
||||
bool HasQueuedStores() const { return open != nullptr && !open->run.queued.empty(); }
|
||||
bool QueuedStoreOverlaps(std::uint64_t address, std::size_t bytes) const;
|
||||
@@ -509,6 +524,7 @@ public:
|
||||
// After the calling worker recorded (or dropped) its queued labels: its ranges are cleared and
|
||||
// the entries of its dwords still without a batch (stored by the CPU, or dropped) leave the table.
|
||||
static void ForgetQueuedLabels();
|
||||
static std::uint64_t ThreadClearAccesses();
|
||||
static bool QueuedLabelsPending();
|
||||
// The function the flush hook calls, on the accessing thread (which may hold the GPU mutex),
|
||||
// when an access overlaps one of that thread's queued labels; it records them. Set once.
|
||||
@@ -572,6 +588,8 @@ public:
|
||||
// The recorder of the current device, for code that only has guest addresses (the flush hook)
|
||||
// and for helpers that must not recycle resources the recorded work still uses.
|
||||
static Recorder* Active();
|
||||
bool RenderPassOpen() const;
|
||||
std::uint64_t RenderPassGeneration() const { return passGeneration; }
|
||||
VkDevice Device() const { return context.device; }
|
||||
std::uint64_t Id() const { return id; }
|
||||
static bool Alive(std::uint64_t id);
|
||||
@@ -642,7 +660,7 @@ public:
|
||||
// or APS5_PROFILE_GPU). A class range covers the command with its own barriers (a dispatch's
|
||||
// barriers are classes of their own, its program range stays keyed by the program), so the
|
||||
// union of every range of a batch and the batch span differ by what no class times ('untimed').
|
||||
enum class CommandClass : std::uint8_t { DispatchLeading = 0, DispatchTrailing, IndirectArguments, LabelRun, Fill, FillClear, Copy, StagingIn, StagingOut, Draw, StorageUpload, StorageWriteBack, DccClear, DccKeyStore, PresentBlit, ShadowPublish, TemplateDataRefresh, Count };
|
||||
enum class CommandClass : std::uint8_t { DispatchLeading = 0, DispatchTrailing, IndirectArguments, LabelRun, Fill, FillClear, Copy, StagingIn, StagingOut, Draw, StorageUpload, StorageWriteBack, DccClear, DccKeyStore, PresentBlit, ShadowPublish, TemplateDataRefresh, InputMirror, Count };
|
||||
static constexpr std::uint64_t ClassKey(CommandClass which) { return 0x10 + static_cast<std::uint64_t>(which); }
|
||||
std::uint32_t BeginGpuTiming(CommandClass which) { return BeginGpuTiming(ClassKey(which)); }
|
||||
static void CountBarriers(CommandClass which, std::uint32_t count = 1);
|
||||
@@ -730,6 +748,7 @@ private:
|
||||
std::vector<std::function<void()>> completions;
|
||||
std::vector<std::pair<std::uint64_t, std::uint64_t>> writes;
|
||||
std::vector<std::uint64_t> writeNotes;
|
||||
std::vector<std::uint64_t> stampedNotes;
|
||||
std::vector<std::int16_t> writeValues;
|
||||
std::vector<std::int64_t> writeWords;
|
||||
// In-place reads (see NotePendingRead), dying with the batch: a finished batch's reads are done.
|
||||
@@ -908,6 +927,11 @@ private:
|
||||
int changedCopyState = 0;
|
||||
VkPipelineLayout changedCopyLayout = VK_NULL_HANDLE;
|
||||
VkPipeline changedCopyPipeline = VK_NULL_HANDLE;
|
||||
int boundChangedCopyState = 0;
|
||||
VkDescriptorSetLayout boundChangedCopySetLayout = VK_NULL_HANDLE;
|
||||
VkPipelineLayout boundChangedCopyLayout = VK_NULL_HANDLE;
|
||||
VkPipeline boundChangedCopyPipeline = VK_NULL_HANDLE;
|
||||
PFN_vkCmdPushDescriptorSetKHR cmdPushChangedCopySet = nullptr;
|
||||
int sampleCounterState = 0;
|
||||
std::unique_ptr<Buffer> sampleCounter;
|
||||
VkPipelineLayout sampleLayout = VK_NULL_HANDLE;
|
||||
@@ -1031,6 +1055,7 @@ private:
|
||||
// table is empty (most of the time between label groups).
|
||||
std::atomic<std::size_t> recordedLabels{0};
|
||||
std::unique_ptr<Batch> open;
|
||||
std::uint64_t passGeneration = 0;
|
||||
std::vector<std::shared_ptr<void>> holdKept;
|
||||
std::uint64_t holdKeptSerial = 0;
|
||||
std::deque<std::unique_ptr<Batch>> inFlight;
|
||||
@@ -1058,6 +1083,7 @@ private:
|
||||
std::uint32_t derived;
|
||||
std::size_t from;
|
||||
std::uint32_t lowest;
|
||||
std::shared_ptr<Buffer> mirror;
|
||||
OwnedDrawInputProof owned;
|
||||
};
|
||||
struct DrawSnapshotPool {
|
||||
@@ -1077,6 +1103,9 @@ private:
|
||||
std::array<DrawSnapshotPool, 2> drawSnapshotPools;
|
||||
std::size_t ownedDrawInputs = 0;
|
||||
void eraseDrawSnapshot(std::map<DrawSnapshotKey, DrawSnapshot>::iterator entry);
|
||||
std::size_t drawInputMirrorBytes = 0;
|
||||
void dropDrawInputMirror(std::map<DrawSnapshotKey, DrawSnapshot>::iterator entry);
|
||||
std::shared_ptr<Buffer> mirrorDrawInput(std::map<DrawSnapshotKey, DrawSnapshot>::iterator entry);
|
||||
struct IndexRange {
|
||||
std::uint64_t generation;
|
||||
std::uint64_t registryGeneration;
|
||||
|
||||
@@ -14,7 +14,14 @@ enum class RuntimeSwitch : std::size_t {
|
||||
NoBarrierBatch,
|
||||
NoGuardSpans,
|
||||
NoOwnedDrawInputs,
|
||||
NoPassAttachmentMemo,
|
||||
NoImportSegmentMemo,
|
||||
NoSizeOnlySurfaceBytes,
|
||||
NoSpaceReuseRecords,
|
||||
PipelineDispatchMisses,
|
||||
NoMemoPendingCollect,
|
||||
NoExtendedFastProofs,
|
||||
TableSnapshot,
|
||||
Count,
|
||||
};
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
namespace AgcDriver::Graphics {
|
||||
|
||||
ShaderRecompiler::ShaderPixelStageInfo DecodePixelStageInfo(const Registers& context, const std::array<std::uint8_t, 8>& exportMappings, bool nullProgram = false);
|
||||
ShaderRecompiler::ShaderPixelStageInfo DecodePixelStageInfo(const Registers& context, const std::array<std::uint8_t, 8>& exportMappings, bool nullProgram = false, std::span<const std::byte> shaderHeader = {});
|
||||
bool PixelEarlyZ(std::uint32_t shaderControl);
|
||||
ShaderRecompiler::ShaderPixelStageInfo DefaultUnexportedInputs(ShaderRecompiler::ShaderPixelStageInfo pixel, std::span<const std::uint32_t> parameterExports);
|
||||
ShaderRecompiler::ShaderComputeStageInfo DecodeComputeStageInfo(const Registers& shader, std::span<const std::byte> header);
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include "Recompiler.hpp"
|
||||
#include "IntermediateRepresentation/IrMetadata/ResourcePlan.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Shaders.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
@@ -73,6 +74,7 @@ struct TextureCacheUse {
|
||||
};
|
||||
TextureCacheUse TextureCacheUsage();
|
||||
void OverrideCacheBudgetForTest(std::uint64_t bytes);
|
||||
void SampledFromStorageForTest(bool enabled);
|
||||
std::uint64_t SampledTextureCacheBudget(const Context& context);
|
||||
std::shared_ptr<Texture> CachedSampledTexture(const Context& context, std::span<const std::uint32_t> words, VkImageViewType multisampleViewType = VK_IMAGE_VIEW_TYPE_2D);
|
||||
bool SampledTexturesShareEntry(std::span<const std::uint32_t> first, std::span<const std::uint32_t> second);
|
||||
@@ -182,9 +184,11 @@ struct ImageTableReuseCounts {
|
||||
std::uint64_t variantSurfaces = 0;
|
||||
std::uint64_t variantSubstituted = 0;
|
||||
std::uint64_t variantRejected = 0;
|
||||
std::uint64_t arrayViewsShared = 0;
|
||||
};
|
||||
ImageTableReuseCounts ImageTableReuses();
|
||||
std::uint64_t SampledTexturesCleared();
|
||||
std::uint64_t SampledTexturesImported();
|
||||
std::uint64_t SampledLookupKeyScans();
|
||||
std::uint64_t SampledLookupKeyProofs();
|
||||
|
||||
@@ -228,6 +232,7 @@ public:
|
||||
std::shared_ptr<Buffer> buffer;
|
||||
VkDeviceSize offset = 0;
|
||||
std::size_t bytes = 0;
|
||||
VkBuffer handle = VK_NULL_HANDLE;
|
||||
std::span<std::byte> Bytes() const { return buffer->Bytes().subspan(static_cast<std::size_t>(offset), bytes); }
|
||||
};
|
||||
DescriptorCache* cache = nullptr;
|
||||
@@ -243,6 +248,9 @@ public:
|
||||
std::uint64_t address;
|
||||
std::size_t size;
|
||||
std::span<const std::uint32_t> words;
|
||||
VkBuffer inPlace = VK_NULL_HANDLE;
|
||||
VkDeviceSize inPlaceOffset = 0;
|
||||
std::uint32_t adjustment = 0;
|
||||
};
|
||||
struct DrawUse {
|
||||
DrawUse() = default;
|
||||
@@ -377,6 +385,18 @@ public:
|
||||
void PatchPushConstants(std::span<std::byte, PipelinePushConstantBytes> bytes) const {
|
||||
for (const auto& [position, adjustment] : pushPatches) bytes[position] = static_cast<std::byte>(adjustment);
|
||||
}
|
||||
bool PatchMovedPushConstants(std::span<std::byte, PipelinePushConstantBytes> bytes, std::span<const MovedBuffer> moved) const {
|
||||
bool patched = false;
|
||||
for (const auto& entry : moved) {
|
||||
if (entry.inPlace == VK_NULL_HANDLE || allocations[entry.allocation].pushByte < 0) continue;
|
||||
bytes[static_cast<std::size_t>(allocations[entry.allocation].pushByte)] = static_cast<std::byte>(entry.adjustment);
|
||||
patched = true;
|
||||
}
|
||||
return patched;
|
||||
}
|
||||
static bool MovedPushPatches(std::span<const MovedBuffer> moved) {
|
||||
return std::any_of(moved.begin(), moved.end(), [](const MovedBuffer& entry) { return entry.inPlace != VK_NULL_HANDLE; });
|
||||
}
|
||||
// Whether RefreshData would record anything for `shader` (the per-word compare; verification).
|
||||
bool DataWordsDiffer(const CompiledShader& shader) const;
|
||||
std::size_t BindingCount() const { return bindings.size(); }
|
||||
@@ -441,6 +461,8 @@ private:
|
||||
int tileMode = 0;
|
||||
std::uint64_t dccAddress = 0;
|
||||
bool imageTable = false;
|
||||
std::optional<std::array<std::uint32_t, 8>> storedWords;
|
||||
std::uint32_t storedMip = 0;
|
||||
};
|
||||
std::vector<DescribedRange> describedRanges;
|
||||
struct Allocation {
|
||||
@@ -531,6 +553,7 @@ private:
|
||||
std::uint64_t guestBufferBytes(std::span<const std::uint32_t> words) const;
|
||||
std::size_t addDataBuffer(std::span<const std::uint32_t> words);
|
||||
void requireGuestBuffers(std::span<const MovedBuffer> moved = {}) const;
|
||||
bool movedInPlace(Recorder& recorder, const Allocation& item, std::uint64_t address, std::uint64_t size, MovedBuffer& entry) const;
|
||||
// Stage A: the layout entry of an image binding (samplers are taken at once, the sampler cache
|
||||
// locks itself); stage B looks the sampled textures and storage images up (resolveImageBinding).
|
||||
void addImageBinding(const ShaderRecompiler::DescriptorBinding& binding, VkShaderStageFlags flags);
|
||||
@@ -604,9 +627,12 @@ private:
|
||||
const StorageTexture* source = nullptr;
|
||||
bool depth = false;
|
||||
bool valid = false;
|
||||
std::uint64_t committedGeneration = 0;
|
||||
std::vector<std::pair<std::uint64_t, std::uint64_t>> committed;
|
||||
bool committedProved = false;
|
||||
};
|
||||
bool keepsTemplateRecords() const;
|
||||
void captureValidation();
|
||||
void captureValidation(bool spaceReusable);
|
||||
// A surface of this object the fast proof found a foreign image pending over: the element
|
||||
// (index into textures, or into storageTextures when `storage`) whose own object stands in for
|
||||
// the full walk's lookup (refreshOwnObjects). `viewUncompressed`: a storage-sourced view under
|
||||
@@ -738,6 +764,7 @@ private:
|
||||
std::optional<std::pair<std::uint64_t, std::size_t>> htileClear;
|
||||
std::vector<std::shared_ptr<Texture>> textures;
|
||||
std::vector<bool> textureFirstLayer;
|
||||
std::unordered_set<std::size_t> arrayViewTextures;
|
||||
std::vector<bool> textureBaseLevel;
|
||||
std::vector<bool> textureSrgb;
|
||||
std::vector<std::shared_ptr<StorageTexture>> storageTextures;
|
||||
@@ -748,6 +775,7 @@ private:
|
||||
std::vector<bool> storageWritten;
|
||||
std::vector<bool> storageAtomic;
|
||||
std::vector<bool> storageAtomic64;
|
||||
std::vector<bool> storageUint;
|
||||
std::vector<std::shared_ptr<Sampler>> samplers;
|
||||
std::shared_ptr<Sampler> paddingSampler;
|
||||
struct SamplerSource {
|
||||
@@ -772,6 +800,7 @@ private:
|
||||
std::uint64_t provedEpoch = 0;
|
||||
std::uint64_t provedProof = 0;
|
||||
std::uint64_t provedPending = 0;
|
||||
std::uint64_t provedRetired = 0;
|
||||
bool revalidateFull(std::span<const CompiledShader> shaders, ProofReport* report);
|
||||
// The import table's identity when the direct regions' serials were last proved.
|
||||
HostImportsProof importsProof;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Context.hpp"
|
||||
#include "IntermediateRepresentation/IrMetadata/ResourcePlan.hpp"
|
||||
#include "Recompiler.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
@@ -36,6 +37,16 @@ inline std::uint32_t StagePushOffset(std::uint32_t cursor, ShaderRecompiler::Sha
|
||||
return fixedSlots && stage == ShaderRecompiler::ShaderStage::Fragment ? PipelinePushSlotBytes : cursor;
|
||||
}
|
||||
|
||||
inline std::uint32_t StagePushBudget(std::uint32_t limit, std::uint32_t offset, ShaderRecompiler::ShaderStage stage, bool fixedSlots, bool hasFragment) {
|
||||
const bool fragment = stage == ShaderRecompiler::ShaderStage::Fragment;
|
||||
const auto base = fixedSlots && fragment ? PipelinePushSlotBytes : 0u;
|
||||
if (offset < base) return 0u;
|
||||
const auto capacity = fixedSlots && fragment ? PipelinePushSlotBytes : std::min(limit, PipelinePushSlotBytes);
|
||||
const auto used = offset - base;
|
||||
const auto reserved = !fixedSlots && hasFragment && !fragment ? 4u : 0u;
|
||||
return used <= capacity && reserved <= capacity - used ? capacity - used - reserved : 0u;
|
||||
}
|
||||
|
||||
struct CompiledShader {
|
||||
ShaderRecompiler::ShaderStage stage;
|
||||
const ShaderRecompiler::RecompileResult* program;
|
||||
|
||||
@@ -87,6 +87,7 @@ struct ColorTarget {
|
||||
std::uint32_t dccControl = 0;
|
||||
std::uint64_t fmaskAddress = 0;
|
||||
std::uint32_t fmaskPipeBankXor = 0;
|
||||
std::uint32_t gcnFmaskBytes = 0;
|
||||
std::uint32_t partialWriteMask = 0;
|
||||
std::uint32_t mergeBlend = 0;
|
||||
bool staged = false;
|
||||
@@ -276,6 +277,7 @@ struct DepthCopyPass {
|
||||
DepthTarget source;
|
||||
std::uint32_t sample;
|
||||
ColorTarget color;
|
||||
bool stencil = false;
|
||||
};
|
||||
std::optional<DepthCopyPass> DecodeDepthCopyPass(const QueueState& queue);
|
||||
std::string DepthMaintenanceRejection(const QueueState& queue);
|
||||
|
||||
@@ -70,7 +70,7 @@ struct OwnedImage {
|
||||
|
||||
class Texture {
|
||||
public:
|
||||
Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, bool depthCompare = false, bool layerRows = false, const VkClearColorValue* clear = nullptr, std::optional<std::span<const std::uint32_t>> packedSlabs = std::nullopt);
|
||||
Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, bool depthCompare = false, bool layerRows = false, const VkClearColorValue* clear = nullptr, std::optional<std::span<const std::uint32_t>> packedSlabs = std::nullopt, const HostImport* source = nullptr);
|
||||
Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::shared_ptr<Buffer> staging, bool depthCompare = false, bool layerRows = false, std::optional<std::span<const std::uint32_t>> packedSlabs = std::nullopt);
|
||||
Texture(const Context& context, const std::shared_ptr<ResidentColor>& source, const GuestTextureResource& descriptor, VkComponentMapping components);
|
||||
// A view of a storage image's own VkImage: the sampled texture follows the image's content, so a
|
||||
@@ -107,6 +107,8 @@ public:
|
||||
VkImageView FirstLayerView() const { return firstLayerView; }
|
||||
VkImageView BaseLevelView() const;
|
||||
bool HasSrgbView() const { return srgbInfo.has_value(); }
|
||||
bool HasArrayView() const { return arrayInfo.has_value(); }
|
||||
VkImageView ArrayView() const;
|
||||
VkImageView SrgbView(bool firstLayer, bool baseLevel) const;
|
||||
struct ViewRange {
|
||||
VkImageViewType type;
|
||||
@@ -142,7 +144,7 @@ public:
|
||||
void MarkReleased() { released.store(true, std::memory_order_release); }
|
||||
|
||||
private:
|
||||
Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, std::shared_ptr<Buffer> staging, bool depthCompare, bool layerRows, const VkClearColorValue* clear, std::optional<std::span<const std::uint32_t>> packedSlabs);
|
||||
Texture(const Context& context, TextureDetiler& detiler, const GuestTextureResource& descriptor, VkComponentMapping components, std::span<const std::byte> snapshot, std::shared_ptr<Buffer> staging, bool depthCompare, bool layerRows, const VkClearColorValue* clear, std::optional<std::span<const std::uint32_t>> packedSlabs, const HostImport* source);
|
||||
void release() noexcept;
|
||||
bool refreshBlockCopy();
|
||||
bool refreshSrgbExpand();
|
||||
@@ -167,6 +169,10 @@ private:
|
||||
float srgbMinLod = 0.0f;
|
||||
mutable std::mutex srgbMutex;
|
||||
mutable std::array<VkImageView, 3> srgbViews{};
|
||||
std::optional<VkImageViewCreateInfo> arrayInfo;
|
||||
float arrayMinLod = 0.0f;
|
||||
mutable std::mutex arrayMutex;
|
||||
mutable VkImageView arrayView = VK_NULL_HANDLE;
|
||||
VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||||
VkDeviceSize allocationBytes = 0;
|
||||
VkDeviceSize countedBytes = 0;
|
||||
@@ -336,6 +342,7 @@ public:
|
||||
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)());
|
||||
static void SetPendingHookForTest(void (*hook)(std::uint64_t address, std::size_t bytes));
|
||||
static constexpr std::uint64_t SmallStoreBytes = 64 * 1024;
|
||||
static constexpr std::uint64_t OccasionalStoreBytes = 1024 * 1024;
|
||||
static constexpr std::uint64_t OccasionalWriteFlips = 8;
|
||||
@@ -363,6 +370,7 @@ public:
|
||||
// as it was, and one that finds it unchanged since an earlier read knows the registry is what
|
||||
// it was then.
|
||||
static std::uint64_t PendingSerial();
|
||||
static bool PendingClearOnThread(std::uint64_t address, std::size_t bytes);
|
||||
// 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);
|
||||
@@ -569,6 +577,10 @@ private:
|
||||
std::array<std::uint64_t, 2> unitContentHash(std::uint32_t unit) const;
|
||||
void hashBeforeUnwatch(std::uint64_t address, std::size_t bytes, bool proven);
|
||||
void forgetUnwatchHash(std::uint32_t first, std::uint32_t count);
|
||||
void rebaseBeforeUnwatch(std::uint64_t address, std::size_t bytes, bool proven);
|
||||
void applyRebase(std::uint64_t ticket, std::uint32_t unit);
|
||||
void readBaseline(std::uint32_t unit);
|
||||
void awaitRebase(std::uint32_t unit);
|
||||
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;
|
||||
@@ -654,6 +666,16 @@ private:
|
||||
std::uint64_t end;
|
||||
};
|
||||
std::vector<ImportSegment> importSegments() const;
|
||||
struct SegmentMemo {
|
||||
bool valid = false;
|
||||
std::uint64_t generation = 0;
|
||||
VkDevice device = VK_NULL_HANDLE;
|
||||
std::uint64_t importEpoch = 0;
|
||||
std::uint64_t importRefreshed = 0;
|
||||
std::vector<ImportSegment> segments;
|
||||
};
|
||||
mutable std::mutex segmentMemoMutex;
|
||||
mutable SegmentMemo segmentMemo;
|
||||
PaddingSeeds paddingSeeds(std::span<const ImportSegment> segments, const std::vector<CopiedBytes>& copied) const;
|
||||
// The direct upload and GPU-direct write-back of the runs through their windows (block units);
|
||||
// both return the bytes moved. The upload reads each unit from its unit shadow while fresh,
|
||||
@@ -866,6 +888,7 @@ private:
|
||||
bool pendingFromOthers = false;
|
||||
std::vector<DrawnRect> drawnRects;
|
||||
std::vector<std::uint64_t> storeNotes;
|
||||
std::vector<std::uint64_t> flushNotes;
|
||||
std::uint64_t writtenFlip = 0;
|
||||
std::atomic<bool> writtenOccasionally{false};
|
||||
std::uint64_t version = 0;
|
||||
@@ -876,6 +899,10 @@ private:
|
||||
std::shared_ptr<Buffer> savedBytes;
|
||||
std::vector<std::uint64_t> savedTicket;
|
||||
std::uint64_t lastSaveTicket = 0;
|
||||
std::vector<bool> baselineDue;
|
||||
std::atomic<bool> anyBaselineDue{false};
|
||||
std::vector<std::uint64_t> rebaseTicket;
|
||||
std::uint64_t lastRebaseTicket = 0;
|
||||
// The storage cache let the image go (Flush): a lookup makes a new image of the surface, so
|
||||
// no fill may put results into this one (guarded by the live-image registry lock).
|
||||
bool released = false;
|
||||
|
||||
@@ -16,6 +16,7 @@ VkFormat ResolveTextureFormat(std::uint32_t guestFormat);
|
||||
VkFormat DccClearTextureFormat(std::uint32_t guestFormat);
|
||||
VkComponentSwizzle TextureComponentChannel(std::uint32_t guestFormat, VkComponentSwizzle component);
|
||||
std::uint32_t SrgbDecodeFormats(PFN_vkGetPhysicalDeviceFormatProperties formatProperties, VkPhysicalDevice physical);
|
||||
std::uint32_t ScaledSampledFormats(PFN_vkGetPhysicalDeviceFormatProperties formatProperties, VkPhysicalDevice physical);
|
||||
VkFormat SampledTextureFormat(const Context& context, std::uint32_t guestFormat);
|
||||
std::uint32_t SrgbCopyFormats(PFN_vkGetPhysicalDeviceFormatProperties formatProperties, VkPhysicalDevice physical, std::uint32_t decodeFormats);
|
||||
bool SrgbExpandsToRgba8(const Context& context, std::uint32_t guestFormat);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
@@ -26,8 +27,12 @@ struct TileMipLayout {
|
||||
std::uint32_t gcnSplitStride = 0;
|
||||
};
|
||||
|
||||
inline constexpr std::uint32_t MaxMipLevels = 16u;
|
||||
using MipLayoutStorage = std::array<TileMipLayout, MaxMipLevels>;
|
||||
|
||||
std::vector<TileMipLayout> ComputeMipLayout(TextureTileMode tileMode, std::uint32_t format, std::uint32_t width, std::uint32_t height, std::uint32_t mipCount, std::uint32_t linearPitch = 0u);
|
||||
std::uint64_t ComputeSurfaceSize(const std::vector<TileMipLayout>& mips, std::uint32_t arrayLayers);
|
||||
std::span<const TileMipLayout> ComputeMipLayoutInto(MipLayoutStorage& storage, TextureTileMode tileMode, std::uint32_t format, std::uint32_t width, std::uint32_t height, std::uint32_t mipCount, std::uint32_t linearPitch = 0u);
|
||||
std::uint64_t ComputeSurfaceSize(std::span<const TileMipLayout> mips, std::uint32_t arrayLayers);
|
||||
// Mip chain of an uncompressed surface given its element size (color targets have no texture format).
|
||||
std::vector<TileMipLayout> ComputeElementMipLayout(TextureTileMode tileMode, std::uint32_t bytesPerElement, std::uint32_t width, std::uint32_t height, std::uint32_t mipCount);
|
||||
|
||||
@@ -80,6 +85,8 @@ struct SurfaceGeometry {
|
||||
bool HasLayer(std::uint32_t level, std::uint32_t layer) const { return imageDepth <= 1 || layer < std::max(imageDepth >> level, 1u); }
|
||||
};
|
||||
SurfaceGeometry DescribeSurface(const GuestTextureResource& descriptor);
|
||||
std::uint64_t DescribeSurfaceGuestBytes(const GuestTextureResource& descriptor);
|
||||
std::uint64_t SurfaceGuestBytes(const GuestTextureResource& descriptor);
|
||||
std::vector<TileMipLayout> ComputeGcnMipLayout(TextureTileMode tileMode, std::uint32_t format, std::uint32_t width, std::uint32_t height, std::uint32_t pitch, bool pow2Pad, std::uint32_t mipCount, bool linearGeneral = false, std::uint32_t layers = 1, bool volume = false);
|
||||
struct GcnTileGeometry {
|
||||
std::uint32_t blockBytes;
|
||||
|
||||
@@ -103,6 +103,8 @@ std::size_t PublishShadow(std::uint64_t address, std::size_t bytes, PublishScope
|
||||
// hook-free readers and a build's stage A.
|
||||
bool AnyShadowedOverlaps(std::uint64_t address, std::size_t bytes);
|
||||
bool AnyShadowedOverlaps(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges);
|
||||
bool LiveUnitsClear(std::uint64_t address, std::size_t bytes);
|
||||
bool AnyPublishInProgress();
|
||||
std::vector<std::pair<std::uint64_t, std::uint64_t>> LiveShadowedRanges(std::uint64_t address, std::size_t bytes, PublishScope scope);
|
||||
|
||||
// The sources of a storage upload's surface-relative runs: [begin, end) pieces of them, each read
|
||||
|
||||
Loaded 100 of 2229 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user