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

Keeps FormatVersion 79, above main's 69 from #19530.
This commit is contained in:
Yunus Shaikh committed 2026-11-14 00:29:59 -08:00
commit e9ddd12bd2
639 files changed
+27263 -4078

No files matched your search

+4
View File
@@ -7,6 +7,10 @@ on:
permissions: {}
concurrency:
group: area-labels
cancel-in-progress: false
jobs:
label:
runs-on: ubuntu-latest
-2
View File
@@ -1,8 +1,6 @@
name: Conflict label
on:
push:
branches: [main]
schedule:
- cron: '0 * * * *'
workflow_dispatch:
@@ -14,6 +14,10 @@ on:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
library-portability:
runs-on: ubuntu-latest
+4
View File
@@ -14,6 +14,10 @@ on:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
input-mapper:
runs-on: ubuntu-latest
+2
View File
@@ -24,6 +24,8 @@ jobs:
issues: write
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- env:
GH_TOKEN: ${{ github.token }}
GITHUB_REPOSITORY: ${{ github.repository }}
+16 -4
View File
@@ -15,6 +15,7 @@ concurrency:
jobs:
overlap:
runs-on: ubuntu-latest
timeout-minutes: 45
permissions:
contents: read
pull-requests: write
@@ -22,6 +23,7 @@ jobs:
- uses: actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/cache/restore@v6
with:
path: ${{ runner.temp }}/overlap-state.json
@@ -39,6 +41,16 @@ jobs:
shopt -s nullglob
marker='<!-- pr-overlap -->'
unpinned() { sed -E 's#/blob/[0-9a-f]{40}/#/blob/main/#g'; }
retry() {
local attempts=3 delay=1 n=1
while :; do
"$@" && return 0
[ "$n" -ge "$attempts" ] && return 1
sleep "$delay"
delay=$((delay * 2))
n=$((n + 1))
done
}
prev=
for file in "$out"/*.md; do
[ -z "$prev" ] || record "$prev" "$hash"
@@ -47,18 +59,18 @@ jobs:
prev=
[ "$(jq -r --arg pr "$pr" '.[$pr] // empty' "$state")" = "$hash" ] && continue
prev=$pr
comment=$(gh api "repos/$GH_REPO/issues/$pr/comments" --paginate \
comment=$(retry gh api "repos/$GH_REPO/issues/$pr/comments" --paginate \
--jq ".[] | select(.user.login == \"github-actions[bot]\" and (.body | startswith(\"$marker\"))) | [.id, .body] | @json" | head -n1)
id=$(jq -r '.[0] // empty' <<< "${comment:-null}")
if [ -s "$file" ]; then
[ "$(jq -r '.[1]' <<< "${comment:-null}" | unpinned)" = "$(unpinned < "$file")" ] && continue
if [ -n "$id" ]; then
gh api -X PATCH "repos/$GH_REPO/issues/comments/$id" -F body=@"$file" > /dev/null
retry gh api -X PATCH "repos/$GH_REPO/issues/comments/$id" -F body=@"$file" > /dev/null
else
gh pr comment "$pr" --body-file "$file"
retry gh pr comment "$pr" --body-file "$file"
fi
elif [ -n "$id" ]; then
gh api -X DELETE "repos/$GH_REPO/issues/comments/$id"
retry gh api -X DELETE "repos/$GH_REPO/issues/comments/$id"
fi
done
[ -z "$prev" ] || record "$prev" "$hash"
+9
View File
@@ -101,3 +101,12 @@
path = 3rdparty/icu
url = https://github.com/unicode-org/icu.git
shallow = true
[submodule "3rdparty/pixman"]
path = 3rdparty/pixman
url = https://gitlab.freedesktop.org/pixman/pixman.git
[submodule "3rdparty/cairo"]
path = 3rdparty/cairo
url = https://gitlab.freedesktop.org/cairo/cairo.git
[submodule "3rdparty/libpng"]
path = 3rdparty/libpng
url = https://github.com/pnggroup/libpng.git
Vendored Submodule
+1
Submodule 3rdparty/cairo added at 3909090108.
Vendored Submodule
+1
Submodule 3rdparty/libpng added at cd952f49f9.
Vendored Submodule
+1
Submodule 3rdparty/pixman added at 37216a3283.
+3
View File
@@ -381,6 +381,9 @@ if(BUILD_TESTING)
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_export_gap.py)
add_test(NAME unwrap_self COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_unwrap_self.py)
add_test(NAME tools_compile_plan COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_compile_plan.py)
set_tests_properties(tools_compile_plan PROPERTIES TIMEOUT 20)
add_test(NAME audit_dump COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_audit_dump.py)
add_test(NAME forced_include_paths COMMAND ${Python3_EXECUTABLE}
+90
View File
@@ -0,0 +1,90 @@
include(${CMAKE_SOURCE_DIR}/cmake/Pixman.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/LibPng.cmake)
function(add_bundled_cairo)
if(TARGET cairo_backend)
return()
endif()
find_package(Threads REQUIRED)
set(cairoSourceDir ${CMAKE_SOURCE_DIR}/3rdparty/cairo/src)
set(cairoBinaryDir ${CMAKE_BINARY_DIR}/3rdparty/cairo)
file(MAKE_DIRECTORY ${cairoBinaryDir})
file(CONFIGURE OUTPUT ${cairoBinaryDir}/cairo-features.h CONTENT
"#ifndef CAIRO_FEATURES_H\n#define CAIRO_FEATURES_H\n#define CAIRO_HAS_IMAGE_SURFACE 1\n#define CAIRO_HAS_USER_FONT 1\n#define CAIRO_HAS_MIME_SURFACE 1\n#define CAIRO_HAS_RECORDING_SURFACE 1\n#define CAIRO_HAS_OBSERVER_SURFACE 1\n#define CAIRO_HAS_PNG_FUNCTIONS 1\n#endif\n")
if(WIN32)
set(cairoLongSize 4)
set(cairoThreads "")
else()
set(cairoLongSize 8)
set(cairoThreads "#define CAIRO_HAS_PTHREAD 1\n#define CAIRO_HAS_REAL_PTHREAD 1\n#define HAVE_STRNDUP 1\n")
endif()
file(CONFIGURE OUTPUT ${cairoBinaryDir}/config.h CONTENT
"#define SIZEOF_VOID_P 8\n#define SIZEOF_INT 4\n#define SIZEOF_LONG ${cairoLongSize}\n#define SIZEOF_LONG_LONG 8\n#define SIZEOF_SIZE_T 8\n#define HAVE_STDINT_H 1\n#define HAVE_INTTYPES_H 1\n#define HAVE_UINT64_T 1\n#define HAVE___UINT128_T 1\n#define HAVE_CXX11_ATOMIC_PRIMITIVES 1\n#define HAS_PIXMAN_GLYPHS 1\n${cairoThreads}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${cairoSourceDir}/cairo.h)
file(STRINGS ${cairoSourceDir}/cairo.h cairoDeclarations REGEX "^cairo_[a-z0-9_]+ +\\(")
set(cairoRenames "")
set(cairoRestores "")
foreach(declaration IN LISTS cairoDeclarations)
string(REGEX MATCH "^cairo_[a-z0-9_]+" function "${declaration}")
string(APPEND cairoRenames "#define ${function} aps5_${function}\n")
string(APPEND cairoRestores "#undef ${function}\n")
endforeach()
file(CONFIGURE OUTPUT ${cairoBinaryDir}/CairoRename.h CONTENT "#pragma once\n${cairoRenames}")
file(CONFIGURE OUTPUT ${cairoBinaryDir}/CairoBackend.h CONTENT
"#pragma once\n#define CAIRO_DEPRECATED_H\n#include \"CairoRename.h\"\n#include <cairo.h>\n${cairoRestores}")
set(cairoSources
cairo-analysis-surface.c cairo-arc.c cairo-array.c cairo-atomic.c cairo-base64-stream.c
cairo-base85-stream.c cairo-bentley-ottmann-rectangular.c cairo-bentley-ottmann-rectilinear.c
cairo-bentley-ottmann.c cairo-botor-scan-converter.c cairo-boxes-intersect.c cairo-boxes.c
cairo-cache.c cairo-clip-boxes.c cairo-clip-polygon.c cairo-clip-region.c cairo-clip-surface.c
cairo-clip-tor-scan-converter.c cairo-clip.c cairo-color.c cairo-composite-rectangles.c
cairo-compositor.c cairo-contour.c cairo-damage.c cairo-debug.c cairo-default-context.c
cairo-device.c cairo-error.c cairo-fallback-compositor.c cairo-fixed.c
cairo-font-face-twin-data.c cairo-font-face-twin.c cairo-font-face.c cairo-font-options.c
cairo-freed-pool.c cairo-freelist.c cairo-gstate.c cairo-hash.c cairo-hull.c
cairo-image-compositor.c cairo-image-info.c cairo-image-source.c cairo-image-surface.c
cairo-line.c cairo-lzw.c cairo-mask-compositor.c cairo-matrix.c cairo-mempool.c
cairo-mesh-pattern-rasterizer.c cairo-misc.c cairo-mono-scan-converter.c cairo-mutex.c
cairo-no-compositor.c cairo-observer.c cairo-output-stream.c cairo-paginated-surface.c
cairo-path-bounds.c cairo-path-fill.c cairo-path-fixed.c cairo-path-in-fill.c
cairo-path-stroke-boxes.c cairo-path-stroke-polygon.c cairo-path-stroke-traps.c
cairo-path-stroke-tristrip.c cairo-path-stroke.c cairo-path.c cairo-pattern.c cairo-pen.c cairo-png.c
cairo-polygon-intersect.c cairo-polygon-reduce.c cairo-polygon.c cairo-raster-source-pattern.c
cairo-recording-surface.c cairo-rectangle.c cairo-rectangular-scan-converter.c cairo-region.c
cairo-rtree.c cairo-scaled-font.c cairo-shape-mask-compositor.c cairo-slope.c
cairo-spans-compositor.c cairo-spans.c cairo-spline.c cairo-stroke-dash.c cairo-stroke-style.c
cairo-surface-clipper.c cairo-surface-fallback.c cairo-surface-observer.c cairo-surface-offset.c
cairo-surface-snapshot.c cairo-surface-subsurface.c cairo-surface-wrapper.c cairo-surface.c
cairo-time.c cairo-tor-scan-converter.c cairo-tor22-scan-converter.c cairo-toy-font-face.c
cairo-traps-compositor.c cairo-traps.c cairo-tristrip.c cairo-unicode.c cairo-user-font.c
cairo-version.c cairo-wideint.c cairo.c cairo-tag-attributes.c cairo-tag-stack.c)
list(TRANSFORM cairoSources PREPEND ${cairoSourceDir}/)
add_library(cairo_backend STATIC EXCLUDE_FROM_ALL ${cairoSources})
target_include_directories(cairo_backend PUBLIC ${cairoSourceDir} ${cairoBinaryDir})
target_compile_definitions(cairo_backend PRIVATE HAVE_CONFIG_H CAIRO_COMPILATION)
if(WIN32)
target_compile_definitions(cairo_backend PUBLIC CAIRO_WIN32_STATIC_BUILD)
endif()
target_compile_options(cairo_backend PRIVATE -w -fno-strict-aliasing -include ${cairoBinaryDir}/CairoRename.h)
target_link_libraries(cairo_backend PUBLIC pixman_backend png_backend Threads::Threads)
if(NOT WIN32 AND NOT APPLE)
target_link_libraries(cairo_backend PUBLIC m)
endif()
set_target_properties(cairo_backend PROPERTIES
POSITION_INDEPENDENT_CODE ON
C_VISIBILITY_PRESET hidden)
install(FILES
${CMAKE_SOURCE_DIR}/3rdparty/cairo/COPYING
${CMAKE_SOURCE_DIR}/3rdparty/cairo/COPYING-LGPL-2.1
${CMAKE_SOURCE_DIR}/3rdparty/cairo/COPYING-MPL-1.1
DESTINATION licenses/cairo)
endfunction()
add_bundled_cairo()
+37
View File
@@ -0,0 +1,37 @@
include(${CMAKE_SOURCE_DIR}/cmake/Zlib.cmake)
function(add_bundled_libpng)
if(TARGET png_backend)
return()
endif()
set(pngSourceDir ${CMAKE_SOURCE_DIR}/3rdparty/libpng)
set(pngBinaryDir ${CMAKE_BINARY_DIR}/3rdparty/libpng)
configure_file(${pngSourceDir}/scripts/pnglibconf.h.prebuilt ${pngBinaryDir}/pnglibconf.h COPYONLY)
add_library(png_backend STATIC EXCLUDE_FROM_ALL
${pngSourceDir}/png.c
${pngSourceDir}/pngerror.c
${pngSourceDir}/pngget.c
${pngSourceDir}/pngmem.c
${pngSourceDir}/pngpread.c
${pngSourceDir}/pngread.c
${pngSourceDir}/pngrio.c
${pngSourceDir}/pngrtran.c
${pngSourceDir}/pngrutil.c
${pngSourceDir}/pngset.c
${pngSourceDir}/pngtrans.c
${pngSourceDir}/pngwio.c
${pngSourceDir}/pngwrite.c
${pngSourceDir}/pngwtran.c
${pngSourceDir}/pngwutil.c)
target_include_directories(png_backend PUBLIC ${pngSourceDir} ${pngBinaryDir})
target_compile_options(png_backend PRIVATE -w)
target_link_libraries(png_backend PUBLIC zlibstatic)
set_target_properties(png_backend PROPERTIES
POSITION_INDEPENDENT_CODE ON
C_VISIBILITY_PRESET hidden)
install(FILES ${pngSourceDir}/LICENSE DESTINATION licenses/libpng)
endfunction()
add_bundled_libpng()
+12
View File
@@ -0,0 +1,12 @@
include_guard(GLOBAL)
function(add_patched_runtime_targets target)
add_custom_target(${target})
set(index 0)
foreach(output IN LISTS ARGN)
set(driver ${target}_output_${index})
add_custom_target(${driver} DEPENDS "${output}")
add_dependencies(${target} ${driver})
math(EXPR index "${index} + 1")
endforeach()
endfunction()
+67
View File
@@ -0,0 +1,67 @@
function(add_bundled_pixman)
if(TARGET pixman_backend)
return()
endif()
set(pixmanSourceDir ${CMAKE_SOURCE_DIR}/3rdparty/pixman/pixman)
set(pixmanBinaryDir ${CMAKE_BINARY_DIR}/3rdparty/pixman)
file(MAKE_DIRECTORY ${pixmanBinaryDir})
set(PIXMAN_VERSION_MAJOR 0)
set(PIXMAN_VERSION_MINOR 42)
set(PIXMAN_VERSION_MICRO 2)
configure_file(${pixmanSourceDir}/pixman-version.h.in ${pixmanBinaryDir}/pixman-version.h @ONLY)
if(WIN32)
set(pixmanLongSize 4)
else()
set(pixmanLongSize 8)
endif()
file(CONFIGURE OUTPUT ${pixmanBinaryDir}/config.h CONTENT
"#define PACKAGE \"pixman\"\n#define USE_SSE2 1\n#define USE_SSSE3 1\n#define TLS __thread\n#define TOOLCHAIN_SUPPORTS_ATTRIBUTE_CONSTRUCTOR 1\n#define HAVE_BUILTIN_CLZ 1\n#define SIZEOF_LONG ${pixmanLongSize}\n")
add_library(pixman_backend STATIC EXCLUDE_FROM_ALL
${pixmanSourceDir}/pixman.c
${pixmanSourceDir}/pixman-access.c
${pixmanSourceDir}/pixman-access-accessors.c
${pixmanSourceDir}/pixman-bits-image.c
${pixmanSourceDir}/pixman-combine32.c
${pixmanSourceDir}/pixman-combine-float.c
${pixmanSourceDir}/pixman-conical-gradient.c
${pixmanSourceDir}/pixman-filter.c
${pixmanSourceDir}/pixman-x86.c
${pixmanSourceDir}/pixman-mips.c
${pixmanSourceDir}/pixman-arm.c
${pixmanSourceDir}/pixman-ppc.c
${pixmanSourceDir}/pixman-edge.c
${pixmanSourceDir}/pixman-edge-accessors.c
${pixmanSourceDir}/pixman-fast-path.c
${pixmanSourceDir}/pixman-glyph.c
${pixmanSourceDir}/pixman-general.c
${pixmanSourceDir}/pixman-gradient-walker.c
${pixmanSourceDir}/pixman-image.c
${pixmanSourceDir}/pixman-implementation.c
${pixmanSourceDir}/pixman-linear-gradient.c
${pixmanSourceDir}/pixman-matrix.c
${pixmanSourceDir}/pixman-noop.c
${pixmanSourceDir}/pixman-radial-gradient.c
${pixmanSourceDir}/pixman-region16.c
${pixmanSourceDir}/pixman-region32.c
${pixmanSourceDir}/pixman-solid-fill.c
${pixmanSourceDir}/pixman-timer.c
${pixmanSourceDir}/pixman-trap.c
${pixmanSourceDir}/pixman-utils.c
${pixmanSourceDir}/pixman-sse2.c
${pixmanSourceDir}/pixman-ssse3.c)
set_source_files_properties(${pixmanSourceDir}/pixman-sse2.c PROPERTIES COMPILE_OPTIONS -msse2)
set_source_files_properties(${pixmanSourceDir}/pixman-ssse3.c PROPERTIES COMPILE_OPTIONS -mssse3)
target_include_directories(pixman_backend PUBLIC ${pixmanSourceDir} ${pixmanBinaryDir})
target_compile_definitions(pixman_backend PRIVATE HAVE_CONFIG_H)
target_compile_options(pixman_backend PRIVATE -w -fno-strict-aliasing -ftrapping-math)
set_target_properties(pixman_backend PROPERTIES
POSITION_INDEPENDENT_CODE ON
C_VISIBILITY_PRESET hidden)
install(FILES ${CMAKE_SOURCE_DIR}/3rdparty/pixman/COPYING DESTINATION licenses/pixman)
endfunction()
add_bundled_pixman()
+14
View File
@@ -0,0 +1,14 @@
function(add_bundled_zlib)
if(TARGET zlibstatic)
return()
endif()
set(ZLIB_BUILD_TESTING OFF)
set(ZLIB_BUILD_SHARED OFF)
set(ZLIB_BUILD_STATIC ON)
set(ZLIB_INSTALL OFF)
add_subdirectory(${CMAKE_SOURCE_DIR}/3rdparty/zlib ${CMAKE_BINARY_DIR}/3rdparty/zlib EXCLUDE_FROM_ALL)
set_target_properties(zlibstatic PROPERTIES POSITION_INDEPENDENT_CODE ON C_VISIBILITY_PRESET hidden)
endfunction()
add_bundled_zlib()
+9
View File
@@ -5,6 +5,12 @@ function(add_jpeg_decoder target runtimeTarget)
include(ExternalProject)
if(NOT TARGET jpeg_turbo_external)
if(BUILD_TESTING AND Python3_EXECUTABLE)
add_test(NAME jpeg_external_toolchain COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_FUNCTION_LIST_DIR}/tests/test_toolchain.py)
set_tests_properties(jpeg_external_toolchain PROPERTIES TIMEOUT 30
ENVIRONMENT "CMAKE_GENERATOR=${CMAKE_GENERATOR}")
endif()
set(jpeg_turbo_prefix "${CMAKE_BINARY_DIR}/libjpeg-turbo")
if(WIN32)
if(MSVC)
@@ -17,6 +23,9 @@ function(add_jpeg_decoder target runtimeTarget)
endif()
file(MAKE_DIRECTORY "${jpeg_turbo_prefix}/include")
set(jpeg_turbo_platform_args)
if(CMAKE_TOOLCHAIN_FILE)
list(APPEND jpeg_turbo_platform_args "-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}")
endif()
if(APPLE)
list(APPEND jpeg_turbo_platform_args
-DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES}
+64
View File
@@ -0,0 +1,64 @@
import pathlib
import shutil
import subprocess
import tempfile
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[4]
CMAKE = shutil.which("cmake")
class JpegToolchain(unittest.TestCase):
def build(self, configured):
self.assertIsNotNone(CMAKE, "CMake is required for the external-project fixture")
with tempfile.TemporaryDirectory(prefix="jpeg toolchain ") as directory:
root = pathlib.Path(directory)
source = root / "source"
jpeg = source / "3rdparty/libjpeg-turbo"
(jpeg / "src").mkdir(parents=True)
(source / "3rdparty/stb").mkdir()
probe = "int jpeg_toolchain_probe(void) { return 123; }\n"
if configured:
probe = "#if !defined(ANYPS5_JPEG_TOOLCHAIN_PROBE) || ANYPS5_JPEG_TOOLCHAIN_PROBE != 123\n#error nested JPEG build lost the selected toolchain\n#endif\n" + probe
(jpeg / "probe.c").write_text(probe)
(jpeg / "CMakeLists.txt").write_text("""cmake_minimum_required(VERSION 3.20)
project(JpegToolchainChild LANGUAGES C)
add_library(turbojpeg STATIC probe.c)
if(MSVC)
set_target_properties(turbojpeg PROPERTIES OUTPUT_NAME turbojpeg-static)
endif()
install(TARGETS turbojpeg ARCHIVE DESTINATION lib)
""")
helper = (ROOT / "core/Decoder/Jpeg/CMakeLists.txt").as_posix()
(source / "CMakeLists.txt").write_text(f"""cmake_minimum_required(VERSION 3.20)
project(JpegToolchainParent LANGUAGES C CXX)
set(BUILD_TESTING OFF)
add_library(probe_runtime INTERFACE)
include([==[{helper}]==])
add_jpeg_decoder(probe_decoder probe_runtime)
""")
command = [CMAKE, "-S", str(source), "-B", str(root / "build"), "-DCMAKE_BUILD_TYPE=Release"]
if configured:
toolchain = root / "selected toolchain.cmake"
toolchain.write_text('set(CMAKE_C_FLAGS_INIT "${CMAKE_C_FLAGS_INIT} -DANYPS5_JPEG_TOOLCHAIN_PROBE=123")\n')
command.append("-DCMAKE_TOOLCHAIN_FILE=" + str(toolchain))
self.run_command(command)
self.run_command([CMAKE, "--build", str(root / "build"), "--target", "jpeg_turbo_external", "--parallel", "1", "--config", "Release"])
archives = list((root / "build/libjpeg-turbo/lib").glob("*turbojpeg*"))
self.assertTrue(archives)
self.assertTrue(all(path.stat().st_size > 0 for path in archives))
def run_command(self, command):
result = subprocess.run(command, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
self.assertEqual(result.returncode, 0, " ".join(command) + "\n" + result.stdout[-7000:])
def test_selected_toolchain_reaches_nested_compilation(self):
self.build(True)
def test_native_build_without_toolchain_still_builds(self):
self.build(False)
if __name__ == "__main__":
unittest.main()
+22 -1
View File
@@ -333,7 +333,8 @@ endif()
include(prx/libSceFreeType/BuildInfo.cmake)
add_custom_target(libs DEPENDS ${PATCHED_OUTPUTS})
include(${CMAKE_SOURCE_DIR}/cmake/PatchedRuntimeTargets.cmake)
add_patched_runtime_targets(libs ${PATCHED_OUTPUTS})
include(prx/libSceLibreSsl/ErrorQueue.cmake)
include(prx/libSceLibreSsl/MemoryBio.cmake)
include(prx/libSceLibreSsl/Cmac.cmake)
@@ -529,6 +530,16 @@ if(BUILD_TESTING)
add_test(NAME nid_patcher_native_paths COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_native_paths.py $<TARGET_FILE:nid_patcher>)
set_tests_properties(nid_patcher_native_paths PROPERTIES TIMEOUT 20)
if(CMAKE_GENERATOR MATCHES "^Ninja")
add_test(NAME nid_patch_dependencies COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_patch_dependencies.py --mode graph
--build "${CMAKE_BINARY_DIR}" --ninja "${CMAKE_MAKE_PROGRAM}" --config "$<CONFIG>")
add_test(NAME nid_patch_dependencies_helper COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_patch_dependencies.py --mode helper
--cmake "${CMAKE_COMMAND}" --ninja "${CMAKE_MAKE_PROGRAM}"
--generator "${CMAKE_GENERATOR}" --config "$<CONFIG>")
set_tests_properties(nid_patch_dependencies nid_patch_dependencies_helper PROPERTIES TIMEOUT 20)
endif()
endif()
add_test_executable(patched_libraries_tests tests/PatchedLibraries.cpp)
add_dependencies(patched_libraries_tests libs)
@@ -1400,6 +1411,16 @@ if(BUILD_TESTING)
set_tests_properties(thread_local_destructors_unusable_nm PROPERTIES WILL_FAIL TRUE TIMEOUT 30)
endif()
add_test_executable(guest_np_cpp_web_api_catalog_leaderboards_tests tests/GuestNpCppWebApiCatalogLeaderboards.cpp)
target_include_directories(guest_np_cpp_web_api_catalog_leaderboards_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_np_cpp_web_api_catalog_leaderboards_tests PRIVATE libSceNpCppWebApi libc)
configure_windows_unwind(guest_np_cpp_web_api_catalog_leaderboards_tests)
add_test(NAME guest_np_cpp_web_api_catalog_leaderboards COMMAND guest_np_cpp_web_api_catalog_leaderboards_tests)
if(WIN32)
set_tests_properties(guest_np_cpp_web_api_catalog_leaderboards PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceNpCppWebApi>")
endif()
add_test_executable(guest_np_cpp_web_api_intrusive_ptr_tests tests/GuestNpCppWebApiIntrusivePtr.cpp)
target_include_directories(guest_np_cpp_web_api_intrusive_ptr_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_np_cpp_web_api_intrusive_ptr_tests PRIVATE libSceNpCppWebApi libc)
@@ -0,0 +1,137 @@
import argparse
from pathlib import Path
import subprocess
import tempfile
import time
def run(command, success=True):
result = subprocess.run(command, capture_output=True, text=True, timeout=15)
output = result.stdout + result.stderr
if (result.returncode == 0) != success:
raise AssertionError(f"unexpected exit {result.returncode}: {command}\n{output}")
return output
def ninja(args, build, *command):
invocation = [args.ninja, "-C", str(build)]
if (build / f"build-{args.config}.ninja").exists():
invocation.extend(["-f", f"build-{args.config}.ninja"])
return invocation + list(command)
def repository_graph(args):
for selected, unrelated in (("libSceIcu", "libScePad"), ("libScePad", "libSceIcu")):
output = run(ninja(args, args.build, "-t", "query", f"core/libs/libs/{selected}.prx"))
dependencies = []
for line in output.splitlines():
if line.strip() == "outputs:":
break
if line.strip().startswith("|| "):
dependencies.append(line.strip()[3:].replace("\\", "/"))
if not dependencies:
raise AssertionError(f"no patch prerequisites found for {selected}\n{output}")
unwanted = [path for path in dependencies if path.endswith(f"/libs/unpatched/{unrelated}.prx")]
if unwanted:
raise AssertionError(f"focused {selected} patch requires unrelated {unrelated}: {unwanted}")
print(f"{selected}: {len(dependencies)} order-only prerequisites, no unrelated {unrelated}")
def helper_fixture(args):
helper = Path(__file__).resolve().parents[4] / "cmake" / "PatchedRuntimeTargets.cmake"
with tempfile.TemporaryDirectory(prefix="nid patch dependencies ") as temporary:
root = Path(temporary)
source = root / "source"
build = root / "build"
(source / "consumer").mkdir(parents=True)
project = '''cmake_minimum_required(VERSION 3.20)
project(PatchDependencyFixture NONE)
include("@HELPER@")
option(BREAK_UNRELATED "Refuse the unrelated runtime build" ON)
foreach(name wanted unrelated)
file(WRITE "${CMAKE_BINARY_DIR}/${name}.seed" "${name}-initial")
set(unpatched "${CMAKE_BINARY_DIR}/${name}.unpatched")
if(name STREQUAL "unrelated" AND BREAK_UNRELATED)
add_custom_command(OUTPUT "${unpatched}"
COMMAND "${CMAKE_COMMAND}" -E false
DEPENDS "${CMAKE_BINARY_DIR}/${name}.seed")
else()
add_custom_command(OUTPUT "${unpatched}"
COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_BINARY_DIR}/${name}.seed" "${unpatched}"
DEPENDS "${CMAKE_BINARY_DIR}/${name}.seed")
endif()
add_custom_target(${name} DEPENDS "${unpatched}")
set(output "${CMAKE_BINARY_DIR}/${name}.patched")
add_custom_command(OUTPUT "${output}"
COMMAND "${CMAKE_COMMAND}" -E copy "${unpatched}" "${output}"
DEPENDS ${name} "${unpatched}")
list(APPEND patched_outputs "${output}")
endforeach()
add_custom_command(OUTPUT "${CMAKE_BINARY_DIR}/runtime-copy.bin"
COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_BINARY_DIR}/wanted.seed" "${CMAKE_BINARY_DIR}/runtime-copy.bin"
DEPENDS "${CMAKE_BINARY_DIR}/wanted.seed")
list(APPEND patched_outputs "${CMAKE_BINARY_DIR}/runtime-copy.bin")
add_patched_runtime_targets(libs ${patched_outputs})
add_subdirectory(consumer)
'''
(source / "CMakeLists.txt").write_text(project.replace("@HELPER@", helper.as_posix()), encoding="utf-8")
(source / "consumer" / "CMakeLists.txt").write_text(
'add_custom_target(focused DEPENDS "${CMAKE_BINARY_DIR}/wanted.patched")\n', encoding="utf-8")
configure = [args.cmake, "-S", str(source), "-B", str(build), "-G", args.generator,
f"-DCMAKE_MAKE_PROGRAM={args.ninja}"]
run(configure)
commands = run(ninja(args, build, "-t", "commands", "focused"))
if "unrelated.patched" in commands or "-E false" in commands:
raise AssertionError(f"focused command closure includes the unrelated runtime\n{commands}")
run(ninja(args, build, "-j1", "focused"))
wanted = build / "wanted.patched"
if wanted.read_text(encoding="utf-8") != "wanted-initial":
raise AssertionError("focused target did not copy the selected runtime")
if (build / "unrelated.unpatched").exists() or (build / "unrelated.patched").exists():
raise AssertionError("focused target built an unrelated runtime")
time.sleep(1.05)
(build / "wanted.seed").write_text("wanted-changed", encoding="utf-8")
run(ninja(args, build, "-j1", "focused"))
if wanted.read_text(encoding="utf-8") != "wanted-changed":
raise AssertionError("changing the selected input did not regenerate its patched output")
(build / "unrelated.seed").write_text("unrelated-changed", encoding="utf-8")
before = wanted.stat().st_mtime_ns
run(ninja(args, build, "-j1", "focused"))
if wanted.stat().st_mtime_ns != before:
raise AssertionError("changing an unrelated input regenerated the selected output")
commands = run(ninja(args, build, "-t", "commands", "libs"))
for output in ("wanted.patched", "unrelated.patched", "runtime-copy.bin"):
if output not in commands:
raise AssertionError(f"full aggregate no longer generates {output}\n{commands}")
failure = run(ninja(args, build, "-j1", "libs"), success=False)
if "-E false" not in failure:
raise AssertionError(f"aggregate failed for a reason other than the unrelated runtime\n{failure}")
run(configure + ["-DBREAK_UNRELATED=OFF"])
run(ninja(args, build, "-j1", "libs"))
for filename, expected in (("wanted.patched", "wanted-initial"),
("unrelated.patched", "unrelated-initial"),
("runtime-copy.bin", "wanted-initial")):
if (build / filename).read_text(encoding="utf-8") != expected:
raise AssertionError(f"full aggregate did not generate the unchanged output {filename}")
print(f"{args.generator}: focused copy/invalidation, unrelated failure and complete aggregate passed")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--mode", choices=("graph", "helper"), required=True)
parser.add_argument("--build", type=Path)
parser.add_argument("--cmake", default="cmake")
parser.add_argument("--ninja", default="ninja")
parser.add_argument("--generator", choices=("Ninja", "Ninja Multi-Config"), default="Ninja")
parser.add_argument("--config", default="Release")
args = parser.parse_args()
if args.mode == "graph":
if args.build is None:
parser.error("--build is required for the actual repository graph")
repository_graph(args)
else:
helper_fixture(args)
if __name__ == "__main__":
main()
@@ -727,6 +727,20 @@ foreach(agcExecutionTestSource IN LISTS agcExecutionTestSources)
list(APPEND agcExecutionTests ${agcExecutionTest})
endforeach()
add_test_executable(agc_read_lane_elimination_tests EXCLUDE_FROM_ALL tests/ReadLaneElimination.cpp)
target_include_directories(agc_read_lane_elimination_tests PRIVATE ${CMAKE_SOURCE_DIR}/core/shader/recompiler)
target_link_libraries(agc_read_lane_elimination_tests PRIVATE shader_recompiler_agc_driver libc)
set_target_properties(agc_read_lane_elimination_tests PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(agc_read_lane_elimination_tests)
if(BUILD_TESTING)
set_target_properties(agc_read_lane_elimination_tests PROPERTIES EXCLUDE_FROM_ALL OFF)
add_test(NAME agc_read_lane_elimination COMMAND agc_read_lane_elimination_tests)
if(WIN32)
set_tests_properties(agc_read_lane_elimination PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
function(agc_add_default_test agcTest)
string(REGEX REPLACE "_tests$" "" agcTestName "${agcTest}")
set_target_properties(${agcTest} PROPERTIES EXCLUDE_FROM_ALL OFF)
@@ -874,6 +888,12 @@ if(BUILD_TESTING)
OUTPUT_NAME GuestMemoryFixture SUFFIX ".prx" CXX_EXTENSIONS OFF
BUILD_WITH_INSTALL_RPATH TRUE INSTALL_RPATH "$ORIGIN")
endif()
add_test(NAME agc_driver_depth_expand_out_of_place_inline COMMAND agc_driver_depth_expand_out_of_place_tests)
set_tests_properties(agc_driver_depth_expand_out_of_place_inline PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_PIPELINED_DRAWS=0" SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
if(WIN32)
set_tests_properties(agc_driver_depth_expand_out_of_place_inline PROPERTIES ENVIRONMENT_MODIFICATION
"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)
set_tests_properties(${partialStoreTest} PROPERTIES
@@ -154,13 +154,16 @@ private:
static bool copySegment(Submission& submission, const std::uint32_t* guest, std::size_t words, std::size_t& budget, std::size_t depth);
static bool copyLink(Submission& submission, const std::uint32_t* guest, std::size_t words, std::size_t& budget, std::size_t depth, const std::uint32_t*& chained, std::size_t& chainedWords);
static void readRegisterLists(Submission& submission);
bool refreshIndirectSegment(Submission& submission, std::size_t index);
void waitForFlipRoom(const Submission& submission);
void holdFlipBehindWorker(const Submission& submission, bool cpuFlip);
bool holdFlipBehindWorker(const Submission& submission, bool cpuFlip);
void holdFlipBehindWork(const std::shared_ptr<FlipWork>& earlier);
static bool flipWorkDone(const std::shared_ptr<FlipWork>& work);
bool awaitsTitle(std::uint64_t awaited) const;
bool parkedOnTitle() const;
void noteAwaitingTitle(std::uint32_t queue, std::uint64_t awaited);
void releaseFlipHold();
void finishFlipWork(std::uint64_t workSerial);
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);
void reserveOutputs(Submission& submission);
@@ -173,7 +176,7 @@ private:
void deferCompletion(const Submission& submission);
void submitOpenWork(const std::shared_ptr<SubmissionProgress>& progress = {});
void wakeQueueZeroForCompletions();
void completeSubmission(std::uint64_t serial, std::uint64_t received, std::span<const std::uint64_t> labelWrites, const std::shared_ptr<SubmissionProgress>& progress, bool holdsFlip);
void completeSubmission(std::uint64_t serial, std::uint64_t received, std::span<const std::uint64_t> labelWrites, const std::shared_ptr<SubmissionProgress>& progress, const std::shared_ptr<FlipWork>& flipWork);
static bool waitFree(const Submission& submission);
bool queue0Before(std::uint64_t received) const;
bool waitFreeBefore(std::uint64_t received) const;
@@ -197,6 +200,8 @@ private:
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();
bool drawEntriesThisDraw();
static std::atomic<std::uint64_t>& drawCacheUseful();
static bool drawDataHits();
static bool verifyDrawDataHits();
static bool drawStageDataHits();
@@ -256,7 +261,7 @@ private:
static AgcDriver::Mutex& writeHistoryMutex();
static std::size_t& writeCursor();
static void dumpPackets(std::span<const std::uint32_t> commands, const std::uint32_t* guest = nullptr);
static void validate(const Submission& submission, const std::uint32_t* guest = nullptr);
static void validate(const Submission& submission, const std::uint32_t* guest = nullptr, bool report = true);
static bool matchesFillKernel(std::span<const std::uint32_t> code, const std::vector<std::uint32_t>& userData, const ShaderRecompiler::ShaderComputeStageInfo& compute);
static bool fillClearEnabled();
static bool fillClearExactOnly();
@@ -384,6 +389,7 @@ private:
static Graphics::Recorder::LateStatistics& lateCountsSeen();
static EpochBumps& epochBumps();
static void bumpEpoch(std::uint64_t EpochBumps::*counter);
static void bumpWaitEpoch(std::uint64_t address, std::size_t bytes);
static std::chrono::steady_clock::time_point& lastEpochBump();
static std::deque<const std::uint32_t*>& releasedTails();
void noteReleasedTails(const Submission& submission);
@@ -410,7 +416,7 @@ private:
static void timed(double WorkerProfile::*bucket, TWork&& work);
FrameTiming* frameTiming();
FrameTiming* includeTimingSubmission(const Submission& submission, bool firstSegment);
void execute(const Submission& submission);
void execute(Submission& submission);
void deliverGuestEopInterrupt(std::uint32_t queue, std::uint32_t context);
static std::optional<std::uint32_t> releaseInterrupt(std::span<const std::uint32_t> packet, std::uint32_t opcode, bool carriesFlip);
void markCompleted(std::uint64_t serial);
@@ -495,6 +501,7 @@ private:
std::shared_ptr<IFlipRequest> request;
};
std::map<std::uint32_t, EopFlip> eopFlips;
std::set<std::pair<std::uint32_t, std::uint32_t>> renderingWaitTargets;
std::uint32_t nextEopToken = EopFlipTokenBase;
DevicePointer device;
@@ -524,8 +531,7 @@ private:
std::atomic<std::uint64_t> queue0Awaited{0};
std::atomic<std::uint32_t> flipsAhead{0};
std::atomic<std::uint32_t> flipHolders{0};
std::atomic<std::uint32_t> flipWorkOpen{0};
std::atomic<std::uint64_t> flipWorkSerial{0};
std::shared_ptr<FlipWork> lastFlipWork;
std::atomic<bool> queue0AwaitsTitle{false};
std::atomic<std::uint64_t> evidenceReads{0};
@@ -29,6 +29,8 @@ struct StreamCopy {
bool MatchesStreamCopyKernel(std::span<const std::uint32_t> code, const std::vector<std::uint32_t>& userData, const ShaderRecompiler::ShaderComputeStageInfo& compute);
std::optional<StreamCopy> StreamCopyRange(const std::vector<std::uint32_t>& userData, std::uint32_t groups);
bool MatchesIndexedCopyKernel(std::span<const std::uint32_t> code, const std::vector<std::uint32_t>& userData, const ShaderRecompiler::ShaderComputeStageInfo& compute);
bool MatchesTableCopyKernel(std::span<const std::uint32_t> code, const std::vector<std::uint32_t>& userData, const ShaderRecompiler::ShaderComputeStageInfo& compute);
std::optional<StreamCopy> TableCopyRange(const std::array<std::uint32_t, 8>& table, std::uint32_t groups);
std::optional<StreamCopy> IndexedCopyRange(const std::vector<std::uint32_t>& userData, std::uint32_t groups, std::uint32_t count, std::uint32_t sourceOffset, std::uint32_t destinationOffset);
}
@@ -20,6 +20,12 @@
namespace AgcDriver::DriverDetail {
struct FlipWork {
bool finished = false;
std::uint64_t serial = 0;
std::shared_ptr<FlipWork> previous;
};
struct Submission {
std::uint64_t serial;
std::uint32_t queue;
@@ -34,6 +40,7 @@ struct Submission {
bool suspend = false;
bool waitFree = false;
bool holdsFlip = false;
std::shared_ptr<FlipWork> flipWork;
std::uint64_t received = 0;
std::vector<std::uint64_t> labelWrites;
@@ -47,6 +54,14 @@ struct Submission {
std::chrono::steady_clock::time_point orderedAt{};
const std::uint32_t* rewindTail = nullptr;
std::size_t rewindWords = 0;
using PreparedWaits = std::map<std::pair<std::uint32_t, std::uint32_t>, std::shared_ptr<IRenderingWait>>;
struct IndirectSegment {
std::size_t start;
const std::uint32_t* target;
std::size_t words;
std::shared_ptr<const PreparedWaits> waits{};
};
std::vector<IndirectSegment> indirectSegments;
};
struct QueueWorker {
@@ -13,6 +13,8 @@ void ReserveCommitterCore();
void ReserveFinisherCore();
void NameDriverThread(const char* name);
}
#endif
@@ -177,6 +177,7 @@ struct PreparedShaders : PreparedShaderState {
std::weak_ptr<VulkanDevice> device;
};
std::vector<DeferredAbi> deferredAbis;
std::size_t resolving = 0;
bool deferredPreparing = false;
std::mutex mutex;
std::condition_variable settled;
@@ -350,6 +351,7 @@ ShaderRecompiler::RectListShaders DrawRectangle(const ShaderSnapshot& front, con
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);
bool StageLinksUserDataCallees(const ShaderSnapshot& snapshot, std::size_t codeOffset);
}
@@ -43,7 +43,7 @@ struct WaitOutcomes {
};
struct EpochBumps {
std::uint64_t submissions = 0, waits = 0, drains = 0, reaps = 0, packets = 0;
std::uint64_t submissions = 0, waits = 0, drains = 0, reaps = 0, packets = 0, waitsOrdered = 0;
};
void PollSleep();
@@ -47,6 +47,7 @@ inline constexpr Opcode Opcodes[] = {
{0x48, "EVENT_WRITE_EOS"},
{0x49, "RELEASE_MEM"},
{0x50, "DMA_DATA"},
{0x51, "CONTEXT_REG_RMW"},
{0x58, "ACQUIRE_MEM"},
{0x59, "REWIND"},
{0x63, "SET_SH_REG_INDIRECT"},
@@ -0,0 +1,64 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_PROFILECOUNTER_HPP
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_PROFILECOUNTER_HPP
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include "prx/libc/include/HostThreadSlot.hpp"
namespace AgcDriver {
class ProfileCounter {
public:
static constexpr std::size_t Slots = 16;
void Add(std::uint64_t value = 1) noexcept {
slots[ThreadSlot()].value.fetch_add(value, std::memory_order_relaxed);
}
std::uint64_t Sum() const noexcept {
std::uint64_t total = 0;
for (const auto& slot : slots) total += slot.value.load(std::memory_order_relaxed);
return total;
}
std::uint64_t Take() noexcept {
std::uint64_t total = 0;
for (auto& slot : slots) total += slot.value.exchange(0, std::memory_order_relaxed);
return total;
}
static std::size_t ThreadSlot() noexcept {
using Held = HostThreadSlot<std::uint32_t, ProfileCounter>;
std::uint32_t held = Held::Get();
if (held == 0) {
held = static_cast<std::uint32_t>(Shared() ? 0 : NextSlot().fetch_add(1, std::memory_order_relaxed) % Slots) + 1;
Held::Set(held);
}
return held - 1;
}
static bool Shared() noexcept {
static const bool shared = std::getenv("APS5_SHARED_PROFILE_COUNTERS") != nullptr;
return shared;
}
private:
struct alignas(64) Slot {
std::atomic<std::uint64_t> value{0};
};
static std::atomic<std::size_t>& NextSlot() noexcept {
static std::atomic<std::size_t> next{0};
return next;
}
std::array<Slot, Slots> slots{};
};
}
#endif
@@ -102,6 +102,7 @@ public:
std::uint64_t Serial() const { return serial; }
// The Vulkan device handle (a Recipe names the device it was built on).
VkDevice Device() const;
bool DmaBufImportSelected() const;
// Drains everything under the caller's GpuMutex: recorder Sync plus vkDeviceWaitIdle. For suspend,
// resize, device replacement, CPU fill fallback and APS5_DRAIN_ALL; the packet-loop drains use the
// three-step form below so the GPU wait happens without the mutex.
@@ -367,6 +368,7 @@ public:
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);
void DepthExpandPass(const Graphics::DepthExpandPass& pass);
// A draw-cache hit recorded from its recipe (Graphics::DrawWithRecipe), under the mutex after
// the packet's labels; Rebuild when the recipe's device is not this one or DrawWithRecipe
// missed (nothing recorded: the caller runs Draw with the hit's stages and re-attaches).
@@ -142,7 +142,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
if (indirectArguments == 0 && (packet[4] & 0x2u) != 0) {
partialGroups = Pm4::PartialGroupThreads({packet[1], packet[2], packet[3]}, {readRegister(queue.shader, 0x207), readRegister(queue.shader, 0x208), readRegister(queue.shader, 0x209)});
}
const bool pipelineCandidate = !resolving && !fromAhead && DispatchItemsEnabled() && DrawPipeline::Active() && indirectArguments == 0 && deferredLabels().labels.empty() && !matchesCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesStreamCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesIndexedCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute);
const bool pipelineCandidate = !resolving && !fromAhead && DispatchItemsEnabled() && DrawPipeline::Active() && indirectArguments == 0 && deferredLabels().labels.empty() && !matchesCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesStreamCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesTableCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) && !MatchesIndexedCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute);
const bool partialLastGroup = partialGroups != std::array<std::uint32_t, 3>{};
std::optional<std::pair<std::uint64_t, std::size_t>> htileClearCompletion;
Graphics::HtileMaskClear htileMask;
@@ -150,7 +150,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
if (indirectArguments == 0 && Graphics::MatchMultisampledSingleClear(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads)) return;
if (!partialLastGroup && matchesFillKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute)) return;
if (!partialLastGroup && indirectArguments == 0 && (MatchDwordPatternFill(packet, std::span(snapshot.code).subspan(codeOffset), userData, compute) || MatchConstantDwordFill(packet, std::span(snapshot.code).subspan(codeOffset), userData, compute) || MatchClampedGlobalFill(packet, std::span(snapshot.code).subspan(codeOffset), userData, compute) || MatchMemoryValueBufferFill(packet, std::span(snapshot.code).subspan(codeOffset), userData, compute))) return;
if (!partialLastGroup && indirectArguments == 0 && (matchesCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) || MatchesStreamCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) || MatchesIndexedCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute))) return;
if (!partialLastGroup && indirectArguments == 0 && (matchesCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) || MatchesStreamCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) || MatchesIndexedCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute) || MatchesTableCopyKernel(std::span(snapshot.code).subspan(codeOffset), userData, compute))) return;
} else {
if (indirectArguments == 0 && Graphics::TakeMultisampledSingleClear(std::span(snapshot.code).subspan(codeOffset), userData, compute.numThreads)) {
pendingDispatchPhases().outcome = DispatchOutcome::FillHle;
@@ -642,6 +642,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
const bool noteWrites = writeEvidenceEnabled() || traceCapSync();
const auto keysFill = indirectArguments == 0 && !partialLastGroup ? MatchSgprPatternFill(packet, std::span(snapshot.code).subspan(codeOffset), userData, compute) : std::nullopt;
const auto filledKeys = keysFill ? KeysFillMemo(keysFill->pattern, false, true) : std::nullopt;
if (keysFill) Graphics::RetireMultisampleColorTargetsOnFmaskWrite(keysFill->base, keysFill->bytes);
std::optional<Graphics::DepthPlaneClear> depthPlaneClear;
if (indirectArguments == 0 && !partialLastGroup) {
@@ -390,7 +390,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
timing.Mark("device_setup");
phaseTiming.Phase(DrawRowVectors);
const bool useDrawEntries = drawEntries() && !ShaderRecompiler::DebugProbeActive() && !dumpGraphics && dumpTarget == 0 && dumpSlot1 == 0;
const bool useDrawEntries = drawEntries() && !ShaderRecompiler::DebugProbeActive() && !dumpGraphics && dumpTarget == 0 && dumpSlot1 == 0 && drawEntriesThisDraw();
tail.registerKey = useDrawEntries && registerKeyEnabled();
const bool registerKey = tail.registerKey;
auto& drawKey = tail.drawKey;
@@ -469,7 +469,10 @@ DrawVerdict Driver::draw(QueueState& queue, std::span<const std::uint32_t> packe
const auto kept = drawCache.find(shape->second);
if (kept != drawCache.end() && kept->second->decode != nullptr && kept->second->shape == shapeKey) dataEntry = kept->second;
}
if (dataEntry != nullptr) ++drawEntryCounters.dataHits;
if (dataEntry != nullptr) {
++drawEntryCounters.dataHits;
drawCacheUseful().fetch_add(1, std::memory_order_relaxed);
}
}
}
if (traceDrawCache()) traceDrawKeyLookup(drawKeyComponents, found == drawCache.end());
@@ -6,6 +6,7 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Memory/WriteEvidence.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include <cstdlib>
#include <mutex>
namespace AgcDriver::DriverDetail {
@@ -122,6 +123,47 @@ bool DrawKeySightings::SeenBefore(std::uint64_t key) {
return false;
}
std::atomic<std::uint64_t>& Driver::drawCacheUseful() {
static std::atomic<std::uint64_t> useful{0};
return useful;
}
namespace {
struct EntryBackoff {
static constexpr std::uint64_t Window = 4096;
static constexpr std::uint64_t ProbeEvery = 16;
static constexpr std::uint64_t UsefulShare = 32;
std::uint64_t draws = 0;
std::uint64_t windowStart = 0;
std::uint64_t probes = 0;
std::uint64_t usefulAtWindow = 0;
bool backingOff = false;
bool use(std::uint64_t useful) {
++draws;
if (draws - windowStart >= Window) {
const auto measured = backingOff ? probes : draws - windowStart;
backingOff = (useful - usefulAtWindow) * UsefulShare < measured;
usefulAtWindow = useful;
windowStart = draws;
probes = 0;
}
if (backingOff && draws % ProbeEvery != 0) return false;
++probes;
return true;
}
};
}
bool Driver::drawEntriesThisDraw() {
static std::mutex mutex;
static EntryBackoff backoff;
std::lock_guard lock(mutex);
return backoff.use(drawCacheUseful().load(std::memory_order_relaxed));
}
bool Driver::admitDrawKey(std::uint64_t key, std::uint64_t shape) {
std::lock_guard cacheLock(drawCacheMutex);
if (drawCache.contains(key)) return true;
@@ -167,12 +167,24 @@ std::shared_ptr<const ShaderRecompiler::RecompileResult> Driver::materializeDraw
}
timing.Mark("materialize");
const auto walked = capture->userDataUse.asValue | capture->userDataUse.asBase;
auto mask = walked == 0 ? ~std::uint64_t{0} : walked | stageCapture.compiled->userDataRegisterReads;
auto mask = capture->plan != nullptr && capture->plan->srtPlanComplete ? walked | stageCapture.compiled->userDataRegisterReads : ~std::uint64_t{0};
if (vertexInfos[i]) {
for (const auto reg : {static_cast<std::uint32_t>(vertexInfos[i]->fetchAttribReg), static_cast<std::uint32_t>(vertexInfos[i]->fetchBufferReg)}) {
mask |= reg + 1u < 64u ? std::uint64_t{3} << reg : ~std::uint64_t{0};
}
}
if (program.snapshot && program.snapshot->userDataTailRegister) {
const auto reg = *program.snapshot->userDataTailRegister;
if (reg >= program.firstUserSgpr) {
const auto slot = reg - program.firstUserSgpr;
mask |= slot + 1u < 64u ? std::uint64_t{3} << slot : ~std::uint64_t{0};
} else {
mask = ~std::uint64_t{0};
}
}
if (program.snapshot && StageLinksUserDataCallees(*program.snapshot, program.codeOffset)) {
mask = ~std::uint64_t{0};
}
stageCapture.userDataMask = mask;
phaseTiming.Phase(DrawRowRecompile);
return stageCapture.compiled;
@@ -199,6 +199,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptr<Vulk
counters.stageDataWords += dataWords;
if (registerKey) ++counters.registerKeyHits;
++drawCacheHits;
drawCacheUseful().fetch_add(1, std::memory_order_relaxed);
bool rotate = false;
for (std::size_t i = 0; i < programs.size(); ++i) {
if (matched[i] == nullptr) continue;
@@ -5,6 +5,7 @@
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/HandoffSpin.hpp"
#include "prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp"
#include "prx/libSceAgcDriver/Execution/include/ProfileCounter.hpp"
#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp"
#include "prx/libSceAgcDriver/Execution/include/WorkerSampler.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
@@ -28,19 +29,19 @@ constexpr std::array<const char*, static_cast<std::size_t>(DrawPipeline::DrainRe
constexpr std::array<const char*, static_cast<std::size_t>(DrawPipeline::CommitKind::Count)> KindNames{"other", "draw", "indirect", "colormeta", "dispatch", "sampledump", "dmafill", "dmawrite", "dmacopy", "store", "endofpipe", "seal", "submitend", "completion", "bufferfill"};
std::atomic<unsigned> runningCommitters{0};
std::atomic<std::uint64_t> drawKeys{0};
std::atomic<std::uint64_t> drawKeysSameAsPrevious{0};
std::atomic<std::uint64_t> drawKeysSeenRecently{0};
std::atomic<std::uint64_t> drawShapesSameAsPrevious{0};
std::atomic<std::uint64_t> drawShapesSeenRecently{0};
ProfileCounter drawKeys;
ProfileCounter drawKeysSameAsPrevious;
ProfileCounter drawKeysSeenRecently;
ProfileCounter drawShapesSameAsPrevious;
ProfileCounter drawShapesSeenRecently;
std::uint64_t elapsedNs(std::chrono::steady_clock::time_point since) {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - since).count());
}
std::atomic<std::uint64_t> heldReadRanges{0};
std::atomic<std::uint64_t> heldReadQueries{0};
std::atomic<std::uint64_t> heldReadHits{0};
ProfileCounter heldReadRanges;
ProfileCounter heldReadQueries;
ProfileCounter heldReadHits;
template<typename TItem>
struct ClearOnExit {
@@ -69,15 +70,15 @@ bool DrawPipeline::MetadataPassesPipelined() {
}
namespace {
std::atomic<std::uint64_t> pipelinedMetadataPasses{0};
ProfileCounter pipelinedMetadataPasses;
}
std::uint64_t DrawPipeline::PipelinedMetadataPasses() {
return pipelinedMetadataPasses.load(std::memory_order_relaxed);
return pipelinedMetadataPasses.Sum();
}
void DrawPipeline::CountPipelinedMetadataPass() {
pipelinedMetadataPasses.fetch_add(1, std::memory_order_relaxed);
pipelinedMetadataPasses.Add(1);
}
bool DrawFinisher::Overlap() {
@@ -205,6 +206,7 @@ void DrawFinisher::Enqueue(Job job, Pending held) {
}
void DrawFinisher::run() {
NameDriverThread("draw-finish");
PerformanceTrace::BindThread("draw finisher");
ReserveFinisherCore();
for (;;) {
@@ -266,7 +268,7 @@ std::size_t DrawPipeline::Depth() {
static const std::size_t depth = [] {
const char* text = std::getenv("APS5_PIPELINED_DRAWS");
if (std::getenv("APS5_LOCKED_DRAW_PREPARE") != nullptr || std::getenv("APS5_DRAW_DRAIN") != nullptr || std::getenv("APS5_DRAIN_ALL") != nullptr || std::getenv("APS5_NO_WORDWISE_CAPTURE") != nullptr) return std::size_t{0};
if (text == nullptr) return std::size_t{8};
if (text == nullptr) return std::size_t{32};
const auto value = std::strtoull(text, nullptr, 10);
return value == 0 ? std::size_t{0} : value == 1 ? std::size_t{8} : static_cast<std::size_t>(std::min<unsigned long long>(value, 256));
}();
@@ -322,11 +324,11 @@ void DrawPipeline::NoteDrawKey(std::uint64_t key, std::uint64_t shape) {
thread_local std::uint64_t previousShape = 0;
const auto shapeSlot = static_cast<std::size_t>((shape ^ (shape >> 29u)) % RecentSlots);
const auto slot = static_cast<std::size_t>((key ^ (key >> 29u)) % RecentSlots);
drawKeys.fetch_add(1, std::memory_order_relaxed);
if (key == previous) drawKeysSameAsPrevious.fetch_add(1, std::memory_order_relaxed);
if (recent[slot] == key) drawKeysSeenRecently.fetch_add(1, std::memory_order_relaxed);
if (shape == previousShape) drawShapesSameAsPrevious.fetch_add(1, std::memory_order_relaxed);
if (recentShapes[shapeSlot] == shape) drawShapesSeenRecently.fetch_add(1, std::memory_order_relaxed);
drawKeys.Add(1);
if (key == previous) drawKeysSameAsPrevious.Add(1);
if (recent[slot] == key) drawKeysSeenRecently.Add(1);
if (shape == previousShape) drawShapesSameAsPrevious.Add(1);
if (recentShapes[shapeSlot] == shape) drawShapesSeenRecently.Add(1);
recent[slot] = key;
previous = key;
recentShapes[shapeSlot] = shape;
@@ -367,7 +369,7 @@ void DrawPipeline::enqueue(Item item) {
}
depthSum += items.size();
++enqueued;
heldReadRanges.fetch_add(item.reads.size(), std::memory_order_relaxed);
heldReadRanges.Add(item.reads.size());
countWrites(item.writes, true);
items.push_back(std::move(item));
outstanding.fetch_add(1, std::memory_order_release);
@@ -411,7 +413,7 @@ void DrawPipeline::report(std::chrono::steady_clock::time_point now) {
const auto queued = enqueued == 0 ? 0.0 : static_cast<double>(depthSum) / static_cast<double>(enqueued);
const auto decodeDrainCount = decodeDrains.load(std::memory_order_relaxed);
char reads[96];
std::snprintf(reads, sizeof(reads), " %llu read ranges, %llu stores held, %llu decode drains", static_cast<unsigned long long>(heldReadRanges.load(std::memory_order_relaxed)), static_cast<unsigned long long>(heldReadHits.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(decodeDrainCount - reportedDecodeDrains));
std::snprintf(reads, sizeof(reads), " %llu read ranges, %llu stores held, %llu decode drains", static_cast<unsigned long long>(heldReadRanges.Sum()), static_cast<unsigned long long>(heldReadHits.Take()), static_cast<unsigned long long>(decodeDrainCount - reportedDecodeDrains));
reportedDecodeDrains = decodeDrainCount;
AgcDriver::ProfilePrint_nid_no_patch("[draw] pipelined (10 s, depth %zu): %llu commits at %.1f us each on the committer, %llu failed; %llu enqueued behind %.2f on average, waiting %.1f us per draw for room, %.2f us for the lock; %llu committer wakes;%s; drains:%s\n", Depth(), static_cast<unsigned long long>(commits), perCommit, static_cast<unsigned long long>(commitErrors), static_cast<unsigned long long>(enqueued), queued, perDraw, enqueued == 0 ? 0.0 : static_cast<double>(lockWaitNs) / 1e3 / static_cast<double>(enqueued), static_cast<unsigned long long>(wakes), reads, drainText.c_str());
std::string kindText;
@@ -425,7 +427,7 @@ void DrawPipeline::report(std::chrono::steady_clock::time_point now) {
}
AgcDriver::ProfilePrint_nid_no_patch("[commits] by kind (10 s):%s\n", kindText.c_str());
const auto vk = Graphics::TakeVkDrawCounts();
AgcDriver::ProfilePrint_nid_no_patch("[vkdraw] (10 s): %llu vkCmdDraw, %llu vkCmdDrawIndexed, %llu vkCmdDrawIndirect calls, %llu mesh; draw keys %llu, same as the previous draw %llu, seen within the last 4096 draws %llu; draw shapes (state without per-draw user words) same as the previous %llu, seen within the last 4096 %llu\n", static_cast<unsigned long long>(vk.direct), static_cast<unsigned long long>(vk.indexed), static_cast<unsigned long long>(vk.indirect), static_cast<unsigned long long>(vk.mesh), static_cast<unsigned long long>(drawKeys.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(drawKeysSameAsPrevious.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(drawKeysSeenRecently.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(drawShapesSameAsPrevious.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(drawShapesSeenRecently.exchange(0, std::memory_order_relaxed)));
AgcDriver::ProfilePrint_nid_no_patch("[vkdraw] (10 s): %llu vkCmdDraw, %llu vkCmdDrawIndexed, %llu vkCmdDrawIndirect calls, %llu mesh; draw keys %llu, same as the previous draw %llu, seen within the last 4096 draws %llu; draw shapes (state without per-draw user words) same as the previous %llu, seen within the last 4096 %llu\n", static_cast<unsigned long long>(vk.direct), static_cast<unsigned long long>(vk.indexed), static_cast<unsigned long long>(vk.indirect), static_cast<unsigned long long>(vk.mesh), static_cast<unsigned long long>(drawKeys.Take()), static_cast<unsigned long long>(drawKeysSameAsPrevious.Take()), static_cast<unsigned long long>(drawKeysSeenRecently.Take()), static_cast<unsigned long long>(drawShapesSameAsPrevious.Take()), static_cast<unsigned long long>(drawShapesSeenRecently.Take()));
commits = commitNs = commitErrors = enqueued = fullWaitNs = depthSum = wakes = lockWaitNs = 0;
drains = {};
drainWaitNs = {};
@@ -433,6 +435,7 @@ void DrawPipeline::report(std::chrono::steady_clock::time_point now) {
void DrawPipeline::run() {
NameDriverThread("draw-commit");
PerformanceTrace::BindThread("draw committer");
ReserveCommitterCore();
StartCommitterSampler();
@@ -537,11 +540,11 @@ bool DrawPipeline::HeldReads(std::uint64_t address, std::size_t bytes) {
const auto end = address + bytes;
auto& pipeline = Queue0();
std::lock_guard lock(pipeline.mutex);
heldReadQueries.fetch_add(1, std::memory_order_relaxed);
heldReadQueries.Add(1);
for (const auto& item : pipeline.items) {
for (const auto& [begin, limit] : item.reads) {
if (address >= limit || begin >= end) continue;
heldReadHits.fetch_add(1, std::memory_order_relaxed);
heldReadHits.Add(1);
return true;
}
}
@@ -549,7 +552,7 @@ bool DrawPipeline::HeldReads(std::uint64_t address, std::size_t bytes) {
}
std::uint64_t DrawPipeline::HeldReadQueries() {
return heldReadQueries.load(std::memory_order_relaxed);
return heldReadQueries.Sum();
}
void DrawPipeline::ReleaseRunningReads() {
@@ -6,6 +6,7 @@
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/Pm4.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp"
#include <algorithm>
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include <cstdlib>
@@ -13,6 +14,15 @@ namespace AgcDriver::DriverDetail {
namespace {
bool indirectRecordsDraw(const Pm4::DrawParameters::IndirectDraw& indirect) {
const auto count = std::min(indirect.countIndirect ? Pm4::ReadDrawCount(indirect) : indirect.count, indirect.count);
for (std::uint32_t record = 0; record < count; ++record) {
const auto arguments = Pm4::ReadDrawArguments(indirect, record);
if (arguments.count != 0 && arguments.instances != 0) return true;
}
return false;
}
QueueState DepthCopyDraw(const QueueState& queue, const Graphics::DepthCopyPass& copy) {
const bool multisampled = copy.source.samples != 1u;
const auto address = DepthCopyPixelProgramAddress(multisampled);
@@ -45,15 +55,19 @@ bool Driver::drawPrecheck() {
std::optional<DrawVerdict> Driver::precheckDraw(const QueueState& queue, const Submission& submission, std::size_t packetOffset, std::span<const std::uint32_t> packet, const Pm4::DrawParameters& drawParameters, std::string& rejected, bool& traceIndirect) {
if (!drawParameters.indirect && !drawParameters.indexed && (drawParameters.indexCount == 0 || drawParameters.instanceCount == 0)) return DrawVerdict::Nothing;
if (const auto pass = Graphics::DecodeColorMetadataPass(queue)) {
require(!drawParameters.indirect, "indirect CB metadata passes are unsupported");
if (DrawPipeline::Active() && DrawPipeline::MetadataPassesPipelined() && deferredLabels().labels.empty()) {
auto writes = Graphics::PipelinedColorMetadataPassWrites(*pass);
const auto metadata = Graphics::DecodeColorMetadataPass(queue);
std::optional<Graphics::DepthExpandPass> expand;
if (!metadata) expand = Graphics::DecodeDepthExpandPass(queue);
if (metadata || expand) {
require(!metadata || !drawParameters.indirect, "indirect CB metadata passes are unsupported");
if (expand && !drawParameters.indirect && (drawParameters.indexCount == 0 || drawParameters.instanceCount == 0)) return DrawVerdict::Nothing;
if (metadata && DrawPipeline::Active() && DrawPipeline::MetadataPassesPipelined() && deferredLabels().labels.empty()) {
auto writes = Graphics::PipelinedColorMetadataPassWrites(*metadata);
const auto localDevice = device.Load();
if (!writes.empty() && localDevice != nullptr) {
const auto queueId = submission.queue;
const auto opcode = (packet[0] >> 8u) & 0xffu;
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::ColorMetadata, [this, localDevice, queueId, opcode, pass = *pass] {
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::ColorMetadata, [this, localDevice, queueId, opcode, pass = *metadata] {
GuestMemory::SetCurrentPacket(opcode, queueId);
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Draw);
std::lock_guard gpuLock(GuestMemory::GpuMutex());
@@ -67,12 +81,17 @@ std::optional<DrawVerdict> Driver::precheckDraw(const QueueState& queue, const S
}
}
if (DrawPipeline::Active()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, (packet[0] >> 8u) & 0xffu);
if (expand && drawParameters.indirect) {
recordQueuedLabelsBeforeRead(submission.queue);
if (!indirectRecordsDraw(*drawParameters.indirect)) return DrawVerdict::Nothing;
}
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Draw);
std::lock_guard gpuLock(GuestMemory::GpuMutex());
if (device == nullptr) device = std::make_shared<VulkanDevice>();
const std::shared_ptr<VulkanDevice> localDevice = device;
recordLabelsForPacket(localDevice.get(), submission.queue);
localDevice->ColorMetadataPass(*pass);
if (metadata) localDevice->ColorMetadataPass(*metadata);
else localDevice->DepthExpandPass(*expand);
return DrawVerdict::Drawn;
}
if (const auto copy = Graphics::DecodeDepthCopyPass(queue)) {
@@ -48,14 +48,22 @@ std::optional<Graphics::IndirectDrawPath> Driver::ClassifyIndirectDraw(const Sha
require(offset <= std::numeric_limits<std::uint32_t>::max() - x, "draw vertex offset overflow");
constant = x + offset;
} else if (conflict) fail(Path::FetchUnknown);
else if (k != p || shared) fail(Path::NotFolded);
else if (k < 0) {
static const bool gpuUnfolded = std::getenv("APS5_NO_GPU_UNFOLDED_INDIRECT") == nullptr;
const auto first = static_cast<std::int32_t>(frontProgram.firstUserSgpr);
const auto bit = static_cast<std::uint32_t>(p - first);
const bool read = p < first || bit >= 64u || (result.userDataRegisterReads & (std::uint64_t{1} << bit)) != 0;
if (!gpuUnfolded || read) fail(Path::NotFolded);
rule = Rule::Constant;
constant = x;
} else if (k != p || shared) fail(Path::NotFolded);
else if (x != 0) fail(Path::IndxOffset);
else rule = Rule::InPlace;
};
dimension(result.vertexOffsetSgpr, indirect.baseVertexSgpr, result.vertexOffsetShared, result.vertexOffsetConflict, drawParameters.indexed ? 0u : indirect.indxOffset, indirect.vertexRule, indirect.vertexConstant);
dimension(result.instanceOffsetSgpr, indirect.startInstanceSgpr, result.instanceOffsetShared, result.instanceOffsetConflict, 0u, indirect.instanceRule, indirect.instanceConstant);
if (!support.firstInstance && (indirect.instanceRule == Rule::InPlace || indirect.instanceConstant != 0)) fail(Path::FeatureGap);
if ((indirect.vertexRule == Rule::Constant || indirect.instanceRule == Rule::Constant) && indirect.count > 256) fail(Path::FeatureGap);
if ((indirect.vertexRule == Rule::Constant || indirect.instanceRule == Rule::Constant) && indirect.count > 1024) fail(Path::FeatureGap);
static const std::uint64_t vertexCap = [] { const char* text = std::getenv("APS5_INDIRECT_VERTEX_MIB"); return (text ? std::strtoull(text, nullptr, 10) : 64ull) << 20u; }();
for (const auto& attribute : result.vertexAttributes) {
@@ -2,6 +2,7 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Memory/BufferCopy.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/Mutex.hpp"
#include <algorithm>
@@ -67,6 +68,25 @@ bool MatchesIndexedCopyKernel(std::span<const std::uint32_t> code, const std::ve
return stride(1) == 16 && stride(5) == 16 && stride(9) == 16 && !swizzled(1) && !swizzled(5) && !swizzled(9) && userData[3] == userData[7] && type == 0 && !addTid && outOfBounds == 0 && userData[10] >= 1;
}
bool MatchesTableCopyKernel(std::span<const std::uint32_t> code, const std::vector<std::uint32_t>& userData, const ShaderRecompiler::ShaderComputeStageInfo& compute) {
static const bool enabled = std::getenv("APS5_NO_COPY_HLE") == nullptr;
if (!enabled || userData.size() != 2 || compute.numThreads[0] != 64 || compute.numThreads[1] != 1 || compute.numThreads[2] != 1 || !compute.groupIdEnable[0]) return false;
static constexpr std::array<std::uint32_t, 11> kernel{0xd7460000u, 0x04010c02u, 0xf40c0100u, 0xfa000000u, 0xbf8cc07fu, 0xe030e000u, 0x80010100u, 0xbf8c3f70u, 0xe0706000u, 0x80020100u, 0xbf810000u};
return code.size() >= kernel.size() && std::equal(kernel.begin(), kernel.end(), code.begin());
}
std::optional<StreamCopy> TableCopyRange(const std::array<std::uint32_t, 8>& table, std::uint32_t groups) {
const auto base = [&](std::size_t word) { return table[word] | (static_cast<std::uint64_t>(table[word + 1] & 0xffffu) << 32u); };
const auto stride = [&](std::size_t word) { return (table[word + 1] >> 16u) & 0x3fffu; };
const auto swizzled = [&](std::size_t word) { return ((table[word + 1] >> 31u) & 1u) != 0; };
if (stride(0) != 4 || stride(4) != 4 || swizzled(0) || swizzled(4) || table[3] != 0x00005204u || table[7] != 0x00005204u) return std::nullopt;
const auto elements = std::min<std::uint64_t>(std::uint64_t{groups} * 64u, table[6]);
if (elements == 0 || elements > table[2]) return std::nullopt;
const StreamCopy copy{base(0), base(4), static_cast<std::size_t>(elements) * 4u};
if (copy.bytes > (16u << 20u) || copy.source % 4 != 0 || copy.destination % 4 != 0) return std::nullopt;
return copy;
}
std::optional<StreamCopy> IndexedCopyRange(const std::vector<std::uint32_t>& userData, std::uint32_t groups, std::uint32_t count, std::uint32_t sourceOffset, std::uint32_t destinationOffset) {
const auto base = [&](std::size_t word) { return userData[word] | (static_cast<std::uint64_t>(userData[word + 1] & 0xffffu) << 32u); };
const auto elements = std::min<std::uint64_t>(std::uint64_t{groups} * 64u, count);
@@ -144,7 +164,8 @@ bool Driver::knownValueVerify() {
bool Driver::copyBuffer(QueueState& queue, std::uint32_t queueId, std::span<const std::uint32_t> packet, std::span<const std::uint32_t> code, const std::vector<std::uint32_t>& userData, const ShaderRecompiler::ShaderComputeStageInfo& compute, const std::shared_ptr<VulkanDevice>& localDevice, std::uint64_t programAddress) {
const bool hashed = matchesCopyKernel(code, userData, compute);
const bool indexed = !hashed && MatchesIndexedCopyKernel(code, userData, compute);
const bool stream = !hashed && !indexed;
const bool table = !hashed && !indexed && MatchesTableCopyKernel(code, userData, compute);
const bool stream = !hashed && !indexed && !table;
if (stream && !MatchesStreamCopyKernel(code, userData, compute)) return false;
const auto started = std::chrono::steady_clock::now();
static const std::size_t cpuMax = [] {
@@ -157,9 +178,9 @@ bool Driver::copyBuffer(QueueState& queue, std::uint32_t queueId, std::span<cons
return text ? static_cast<std::size_t>(std::strtoull(text, nullptr, 10)) : std::numeric_limits<std::size_t>::max();
}();
const auto base = [&](std::size_t word) { return userData[word] | (static_cast<std::uint64_t>(userData[word + 1] & 0xffffu) << 32u); };
auto source = base(0);
auto destination = base(4);
const auto record = stream ? std::uint64_t{0} : base(8);
auto source = table ? std::uint64_t{0} : base(0);
auto destination = table ? std::uint64_t{0} : base(4);
const auto record = stream || table ? std::uint64_t{0} : base(8);
std::array<std::uint32_t, 3> groups{packet[1], packet[2], packet[3]};
if ((packet[4] & 0x20u) != 0) {
for (std::uint32_t axis = 0; axis < 3; ++axis) {
@@ -186,7 +207,29 @@ bool Driver::copyBuffer(QueueState& queue, std::uint32_t queueId, std::span<cons
return false;
};
std::size_t bytes = 0;
if (stream) {
if (table) {
Graphics::FinishLeaseWork();
const auto tableAddress = base(0);
const bool tableAccessible = GuestMemory::Accessible(reinterpret_cast<const void*>(tableAddress), 32);
bool published = false;
if (!tableAccessible || Graphics::Recorder::SnapshotWriteOverlaps(tableAddress, 32) || Graphics::StorageTexture::FlushPending(tableAddress, 32, nullptr, "table copy descriptors", Graphics::PublishScope::Whole, &published) || published || labelPending(tableAddress, 32)) {
if (traceCopy()) traceCopyPending(tableAccessible ? "copy descriptors" : "inaccessible copy descriptors", tableAddress, 32, 0, 0, 0, localDevice);
countCopy(CopyRecordPending, 0, started, locked);
return false;
}
std::array<std::uint32_t, 8> descriptors{};
std::memcpy(descriptors.data(), reinterpret_cast<const void*>(tableAddress), sizeof(descriptors));
const auto range = TableCopyRange(descriptors, groups[0]);
if (!range || (tableAddress < range->destination + range->bytes && range->destination < tableAddress + 32)) {
countCopy(CopyShape, range ? range->bytes : 0, started, locked);
return false;
}
source = range->source;
destination = range->destination;
bytes = range->bytes;
static std::atomic<std::uint64_t> tableCopies{0};
if ((tableCopies.fetch_add(1, std::memory_order_relaxed) & 0xfffu) == 0) std::fprintf(stderr, "[copyhle] table copy 0x%llx -> 0x%llx (0x%zx bytes), %llu so far\n", static_cast<unsigned long long>(source), static_cast<unsigned long long>(destination), bytes, static_cast<unsigned long long>(tableCopies.load(std::memory_order_relaxed)));
} else if (stream) {
const auto range = StreamCopyRange(userData, groups[0]);
if (!range) {
countCopy(CopyShape, 0, started, locked);
@@ -247,6 +290,7 @@ bool Driver::copyBuffer(QueueState& queue, std::uint32_t queueId, std::span<cons
countCopy(outcome.path, bytes, started, locked, &outcome);
if (traceCopy() && bytes <= cpuMax && outcome.path != CopyCpu) traceCopyRefused(outcome, source, destination, bytes, localDevice);
if (outcome.path == CopyNotImported || outcome.path == CopyOverGpuMax) return false;
Graphics::NoteCopyDestination(destination, bytes);
if (outcome.path == CopyCpu) noteForeignWriter(destination, destination + bytes, queueId);
return true;
@@ -47,7 +47,7 @@ void Driver::dumpPackets(std::span<const std::uint32_t> commands, const std::uin
}
}
void Driver::validate(const Submission& submission, const std::uint32_t* guest) {
void Driver::validate(const Submission& submission, const std::uint32_t* guest, bool report) {
const std::span<const std::uint32_t> commands = submission.commands;
const auto queue = submission.queue;
std::vector<std::size_t> guarded;
@@ -59,10 +59,12 @@ void Driver::validate(const Submission& submission, const std::uint32_t* guest)
char what[128];
std::snprintf(what, sizeof(what), "unsupported PM4 packet type: header 0x%08x at DWORD %zu of %zu", header, cursor, commands.size());
dumpPackets(commands, guest);
std::fprintf(stderr, "[gpu] dwords %zu..%zu:", cursor >= 8 ? cursor - 8 : 0, std::min(commands.size(), cursor + 8));
for (std::size_t i = cursor >= 8 ? cursor - 8 : 0; i < std::min(commands.size(), cursor + 8); ++i) std::fprintf(stderr, " %08x", commands[i]);
std::fprintf(stderr, "\n");
if (report) {
dumpPackets(commands, guest);
std::fprintf(stderr, "[gpu] dwords %zu..%zu:", cursor >= 8 ? cursor - 8 : 0, std::min(commands.size(), cursor + 8));
for (std::size_t i = cursor >= 8 ? cursor - 8 : 0; i < std::min(commands.size(), cursor + 8); ++i) std::fprintf(stderr, " %08x", commands[i]);
std::fprintf(stderr, "\n");
}
throw std::runtime_error(std::string("AGC driver: ") + what);
}
const auto count = Pm4::PacketWords(header);
@@ -76,7 +78,7 @@ void Driver::validate(const Submission& submission, const std::uint32_t* guest)
guarded.push_back(end->second);
}
} catch (const std::exception& error) {
dumpPackets(commands, guest);
if (report) dumpPackets(commands, guest);
throw std::runtime_error("AGC driver: " + Pm4::Name(header) + " at DWORD " + std::to_string(cursor) + ": " + error.what());
}
cursor += count;
@@ -77,6 +77,9 @@ bool keepsDrawPipeline(std::span<const std::uint32_t> packet, std::uint32_t head
case 0x11: case 0x12: case 0x13: case 0x20: case 0x26: case 0x2a: case 0x2f: case 0x3f: case 0x42: case 0x58: case 0x59: case 0x69: case 0x76: case 0x79: case 0x7a: case 0x81: return true;
case 0x46: return packet.size() >= 2 && (packet[1] & 0x3fu) != 0x39u;
case 0x15: return orderedFills();
case 0x40:
return packet.size() >= 6 && !Pm4::CopyDataToRegister(packet) && Pm4::CopyDataSource(packet) == Pm4::CopyDataGpuClockSource &&
!DrawPipeline::Queue0().Overlaps(packet[4] | (static_cast<std::uint64_t>(packet[5]) << 32u), Pm4::CopyDataBytes(packet));
case 0x63: case 0x64: case 0x9f:
return packet.size() >= 5 && !DrawPipeline::Queue0().Overlaps(packet[1] | (static_cast<std::uint64_t>(packet[2]) << 32u), static_cast<std::size_t>(packet[4]) * 8);
case 0x50: {
@@ -157,13 +160,14 @@ void Driver::timed(double WorkerProfile::*bucket, TWork&& work) {
if (report && bucket != &WorkerProfile::waitMs) PerformanceCounters::AddDriverNanoseconds(static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count()));
}
void Driver::execute(const Submission& submission) {
void Driver::execute(Submission& submission) {
auto* submissionTiming = includeTimingSubmission(submission, true);
struct FlipHold {
Driver& driver;
std::uint32_t queue;
bool held;
bool working;
std::shared_ptr<FlipWork> work;
void Release() {
if (!held) return;
held = false;
@@ -173,13 +177,13 @@ void Driver::execute(const Submission& submission) {
if (!working) return;
const auto workSerial = driver.submitFlipWork(queue);
working = false;
driver.finishFlipWork(workSerial);
driver.finishFlipWork(work, workSerial);
}
~FlipHold() {
Release();
if (working) driver.finishFlipWork(0);
if (working) driver.finishFlipWork(work, 0);
}
} flipHold{*this, submission.queue, submission.holdsFlip, submission.holdsFlip};
} flipHold{*this, submission.queue, submission.holdsFlip, submission.holdsFlip, submission.flipWork};
const bool pipelined = submission.queue == 0 && DrawPipeline::Depth() != 0;
static const bool orderedWaits = std::getenv("APS5_PIPELINE_DRAIN_LABELS") == nullptr;
DrawPipeline::Active() = pipelined;
@@ -279,10 +283,19 @@ void Driver::execute(const Submission& submission) {
if (queue0) DrawFinisher::Get().Settle();
}
} settleFinisher{submission.queue == 0};
std::size_t nextSegment = 0;
auto* const executingPacket = workerPacket();
for (std::size_t cursor = 0; cursor < submission.commands.size();) {
if (packetEpoch()) bumpEpoch(&EpochBumps::packets);
CheckFailure();
while (nextSegment < submission.indirectSegments.size() && submission.indirectSegments[nextSegment].start <= cursor) {
if (submission.indirectSegments[nextSegment].start == cursor && refreshIndirectSegment(submission, nextSegment)) {
recent.commands = submission.commands;
continue;
}
++nextSegment;
}
if (cursor >= submission.commands.size()) break;
const auto header = submission.commands[cursor];
if (Pm4::FillerPacket(header)) { ++cursor; continue; }
const auto count = Pm4::PacketWords(header);
@@ -325,7 +338,7 @@ void Driver::execute(const Submission& submission) {
continue;
}
if (!DrawPipeline::Queue0().Overlaps(awaited, awaitedBytes) && Pm4::WaitSatisfiedUnchecked(packet) && !OwnStoreRejects(packet, awaited, awaitedBytes, submission.queue)) {
bumpEpoch(&EpochBumps::waits);
bumpWaitEpoch(awaited, awaitedBytes);
++waitOutcomes().atEntry;
gateOpened() = true;
noteLabelPass(packet, submission.queue);
@@ -619,8 +632,8 @@ void Driver::execute(const Submission& submission) {
}
if ((std::atomic_ref<std::uint32_t>(*const_cast<std::uint32_t*>(submission.rewindTail - 1)).load(std::memory_order_acquire) & 0x80000000u) != 0) {
const bool holdsFlip = std::exchange(flipHold.working, false);
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::SubmitEnd, [this, holdsFlip, progress = submission.progress] {
if (holdsFlip) finishFlipWork(submitFlipWork(0));
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::SubmitEnd, [this, holdsFlip, flipWork = submission.flipWork, progress = submission.progress] {
if (holdsFlip) finishFlipWork(flipWork, submitFlipWork(0));
else submitOpenWork(progress);
wakeQueueZeroForCompletions();
}, {});
@@ -205,7 +205,7 @@ bool Driver::preparePacketMemory(const Submission& submission, QueueState& queue
else ++storesBehindCompletions;
wroteOnGpu = true;
drained = false;
} else if (reason == 1) {
} else if (reason == 1 || (reason == 3 && opcode == 0x40 && Pm4::CopyDataSource(packet) == Pm4::CopyDataGpuClockSource && !localDevice->StoresPendingOver(store->address, bytes.size()))) {
GuestMemory::Write(store->address, bytes, 1);
++storesOnCpu;
wroteOnGpu = true;
@@ -48,7 +48,7 @@ PacketTimer::~PacketTimer() {
auto& poll = Driver::pollStats();
AgcDriver::ProfilePrint_nid_no_patch( "[poll] queue 0x%x (10 s): ticks %llu, table hits %llu, tries %llu / failed %llu, submits %llu, reaps %llu (%llu with work; by reason: behind completion %llu / other %llu), refusals: %s %llu, %s %llu, %s %llu, %s %llu, %s %llu; longest try hold %.1f us, try holds %.1f ms\n", queue, static_cast<unsigned long long>(poll.ticks), static_cast<unsigned long long>(poll.tableHits), static_cast<unsigned long long>(poll.tries), static_cast<unsigned long long>(poll.triesFailed), static_cast<unsigned long long>(poll.submits), static_cast<unsigned long long>(poll.reaps), static_cast<unsigned long long>(poll.reapsWithWork), static_cast<unsigned long long>(poll.reapsBehindCompletion), static_cast<unsigned long long>(poll.reapsOther), LabelRefusalNames[1], static_cast<unsigned long long>(poll.refusals[1]), LabelRefusalNames[2], static_cast<unsigned long long>(poll.refusals[2]), LabelRefusalNames[3], static_cast<unsigned long long>(poll.refusals[3]), LabelRefusalNames[4], static_cast<unsigned long long>(poll.refusals[4]), LabelRefusalNames[5], static_cast<unsigned long long>(poll.refusals[5]), poll.longestTryHoldUs, poll.tryHoldUs / 1000.0);
poll = PollStats{};
AgcDriver::ProfilePrint_nid_no_patch( "[packets] queue 0x%x %llu submissions, time by packet (10 s):%s, flush %.0fms; DISPATCH_DIRECT by outcome:%s; per submission (%llu submitted): validate %.1f us, copy %.1f us, dequeue %.1f us, complete %.1f us; suspend points %llu x %.1f us, %llu skipped (nothing open); end submits %llu made, %llu skipped, %llu notifies skipped; waits satisfied: at entry %llu, from recorder %llu (%llu while polling, same queue %llu, %llu without the GPU mutex, %llu late-trusted), polled %llu (%llu entered without the GPU mutex, %llu entry tries failed; late candidates %llu: refused cpu-store %llu, overwritten %llu, unclosed %llu, queued %llu), timed out %llu; poll submits %llu, poll reaps %llu; epoch bumps: submissions %llu, waits %llu, drains %llu, reaps %llu, packets %llu\n", queue, static_cast<unsigned long long>(profile.submissions), report.c_str(), profile.flushMs, outcomes.c_str(), static_cast<unsigned long long>(submitted), validateUs, copyUs, dequeueUs, completeUs, static_cast<unsigned long long>(suspends), suspendUs, static_cast<unsigned long long>(costs.suspendsSkipped.exchange(0)), static_cast<unsigned long long>(costs.endSubmits.exchange(0)), static_cast<unsigned long long>(costs.endSkipped.exchange(0)), static_cast<unsigned long long>(costs.notifiesSkipped.exchange(0)), static_cast<unsigned long long>(waits.atEntry), static_cast<unsigned long long>(waits.fromRecorder + waits.fromRecorderPolling), static_cast<unsigned long long>(waits.fromRecorderPolling), static_cast<unsigned long long>(waits.fromRecorderSameQueue), static_cast<unsigned long long>(waits.fromRecorderUnlocked), static_cast<unsigned long long>(waits.fromRecorderLate), static_cast<unsigned long long>(waits.polled), static_cast<unsigned long long>(waits.entriesUnlocked), static_cast<unsigned long long>(waits.entryTriesFailed), static_cast<unsigned long long>(late.candidates - lateSeen.candidates), static_cast<unsigned long long>(waits.lateRefusedCpuStore), static_cast<unsigned long long>(late.overwritten - lateSeen.overwritten), static_cast<unsigned long long>(late.unclosed - lateSeen.unclosed), static_cast<unsigned long long>(late.queued - lateSeen.queued), static_cast<unsigned long long>(waits.timedOut), static_cast<unsigned long long>(waits.pollSubmits), static_cast<unsigned long long>(waits.pollReaps), static_cast<unsigned long long>(epochs.submissions), static_cast<unsigned long long>(epochs.waits), static_cast<unsigned long long>(epochs.drains), static_cast<unsigned long long>(epochs.reaps), static_cast<unsigned long long>(epochs.packets));
AgcDriver::ProfilePrint_nid_no_patch( "[packets] queue 0x%x %llu submissions, time by packet (10 s):%s, flush %.0fms; DISPATCH_DIRECT by outcome:%s; per submission (%llu submitted): validate %.1f us, copy %.1f us, dequeue %.1f us, complete %.1f us; suspend points %llu x %.1f us, %llu skipped (nothing open); end submits %llu made, %llu skipped, %llu notifies skipped; waits satisfied: at entry %llu, from recorder %llu (%llu while polling, same queue %llu, %llu without the GPU mutex, %llu late-trusted), polled %llu (%llu entered without the GPU mutex, %llu entry tries failed; late candidates %llu: refused cpu-store %llu, overwritten %llu, unclosed %llu, queued %llu), timed out %llu; poll submits %llu, poll reaps %llu; epoch bumps: submissions %llu, waits %llu (%llu ordered by an earlier wait), drains %llu, reaps %llu, packets %llu\n", queue, static_cast<unsigned long long>(profile.submissions), report.c_str(), profile.flushMs, outcomes.c_str(), static_cast<unsigned long long>(submitted), validateUs, copyUs, dequeueUs, completeUs, static_cast<unsigned long long>(suspends), suspendUs, static_cast<unsigned long long>(costs.suspendsSkipped.exchange(0)), static_cast<unsigned long long>(costs.endSubmits.exchange(0)), static_cast<unsigned long long>(costs.endSkipped.exchange(0)), static_cast<unsigned long long>(costs.notifiesSkipped.exchange(0)), static_cast<unsigned long long>(waits.atEntry), static_cast<unsigned long long>(waits.fromRecorder + waits.fromRecorderPolling), static_cast<unsigned long long>(waits.fromRecorderPolling), static_cast<unsigned long long>(waits.fromRecorderSameQueue), static_cast<unsigned long long>(waits.fromRecorderUnlocked), static_cast<unsigned long long>(waits.fromRecorderLate), static_cast<unsigned long long>(waits.polled), static_cast<unsigned long long>(waits.entriesUnlocked), static_cast<unsigned long long>(waits.entryTriesFailed), static_cast<unsigned long long>(late.candidates - lateSeen.candidates), static_cast<unsigned long long>(waits.lateRefusedCpuStore), static_cast<unsigned long long>(late.overwritten - lateSeen.overwritten), static_cast<unsigned long long>(late.unclosed - lateSeen.unclosed), static_cast<unsigned long long>(late.queued - lateSeen.queued), static_cast<unsigned long long>(waits.timedOut), static_cast<unsigned long long>(waits.pollSubmits), static_cast<unsigned long long>(waits.pollReaps), static_cast<unsigned long long>(epochs.submissions), static_cast<unsigned long long>(epochs.waits), static_cast<unsigned long long>(epochs.waitsOrdered), static_cast<unsigned long long>(epochs.drains), static_cast<unsigned long long>(epochs.reaps), static_cast<unsigned long long>(epochs.packets));
lateSeen = late;
waits = WaitOutcomes{};
epochs = EpochBumps{};
@@ -91,6 +91,7 @@ void Driver::Present(const PresentationWindow& window, const DisplayBuffer* buff
if (!pinned) {
pinned = true;
PinWorkerThread("presenter");
NameDriverThread("presenter");
GuestMemory::MarkPresenterThread();
}
CheckFailure();
@@ -74,8 +74,8 @@ void Driver::deferCompletion(const Submission& submission) {
completionDeferred() = true;
static const bool traceGpu = std::getenv("APS5_TRACE_GPU") != nullptr;
if (traceGpu) std::fprintf(stderr, "[gpu] %.1f deferred completion serial=%llu to the draw pipeline\n", TraceMs(), static_cast<unsigned long long>(submission.serial));
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Completion, [this, serial = submission.serial, received, labelWrites = submission.labelWrites, progress = submission.progress, holdsFlip = submission.holdsFlip] {
completeSubmission(serial, received, labelWrites, progress, holdsFlip);
DrawPipeline::Queue0().Enqueue(DrawPipeline::CommitKind::Completion, [this, serial = submission.serial, received, labelWrites = submission.labelWrites, progress = submission.progress, flipWork = submission.holdsFlip ? submission.flipWork : nullptr] {
completeSubmission(serial, received, labelWrites, progress, flipWork);
}, {});
}
@@ -107,7 +107,7 @@ std::uint64_t Driver::submitFlipWork(std::uint32_t queue) {
return localDevice != nullptr ? localDevice->SubmitAndEpoch() : 0;
}
void Driver::completeSubmission(std::uint64_t serial, std::uint64_t received, std::span<const std::uint64_t> labelWrites, const std::shared_ptr<SubmissionProgress>& progress, bool holdsFlip) {
void Driver::completeSubmission(std::uint64_t serial, std::uint64_t received, std::span<const std::uint64_t> labelWrites, const std::shared_ptr<SubmissionProgress>& progress, const std::shared_ptr<FlipWork>& flipWork) {
struct Complete {
Driver& driver;
std::uint64_t serial, received;
@@ -125,7 +125,7 @@ void Driver::completeSubmission(std::uint64_t serial, std::uint64_t received, st
if (notify) driver.changed.notify_all();
}
} complete{*this, serial, received, labelWrites};
if (holdsFlip) finishFlipWork(submitFlipWork(0));
if (flipWork != nullptr) finishFlipWork(flipWork, submitFlipWork(0));
else submitOpenWork(progress);
}
@@ -157,6 +157,9 @@ void Driver::run(std::uint32_t id) noexcept {
char role[32];
std::snprintf(role, sizeof role, "queue worker 0x%x", id);
PinWorkerThread(role);
char threadName[16];
std::snprintf(threadName, sizeof threadName, "qworker 0x%x", id);
NameDriverThread(threadName);
GuestMemory::TagGpuLockThread(id);
StartWorkerSampler(id);
@@ -29,6 +29,43 @@ namespace AgcDriver::DriverDetail {
namespace {
void noteIndirectSegment(Submission& submission, std::size_t start, const std::uint32_t* target, std::size_t words) {
if (submission.commands.size() - start != words || !std::equal(submission.commands.begin() + static_cast<std::ptrdiff_t>(start), submission.commands.end(), target)) return;
submission.indirectSegments.push_back({start, target, words});
}
void collectLabelDwords(std::span<const std::uint32_t> packet, std::set<std::uint64_t>& dwords) {
const auto opcode = (packet[0] >> 8u) & 0xffu;
if ((packet[0] >> 30u) != 3u || (opcode != 0x49 && opcode != 0x37)) return;
const auto label = Pm4::DecodeLabelWrite(packet);
if (!label.has_value()) return;
const auto bytes = label->Bytes();
if (label->address % 4 != 0 || bytes.size() > 64) return;
for (std::size_t offset = 0; offset < bytes.size(); offset += 4) dwords.insert(label->address + offset);
}
bool awaitsAny(std::span<const std::uint32_t> commands, std::size_t cursor, const std::set<std::uint64_t>& dwords) {
if (cursor >= commands.size()) return false;
const auto packet = commands.subspan(cursor, std::min<std::size_t>(Pm4::PacketWords(commands[cursor]), commands.size() - cursor));
const auto opcode = (packet[0] >> 8u) & 0xffu;
if ((opcode != 0x3c && opcode != 0x93) || packet.size() < 7) return false;
const auto wait = Pm4::DecodeWait(packet);
for (std::size_t offset = 0; offset < wait.bytes; offset += 4) {
if (dwords.contains(wait.address + offset)) return true;
}
return false;
}
template<typename Map>
void shiftKeys(Map& map, std::size_t start, std::size_t end, std::ptrdiff_t delta) {
Map shifted;
for (auto& [key, value] : map) {
if (key >= start && key < end) continue;
shifted.emplace(key >= end ? static_cast<std::size_t>(static_cast<std::ptrdiff_t>(key) + delta) : key, std::move(value));
}
map = std::move(shifted);
}
bool& submitsQueue0() {
struct SubmitsQueue0Storage {};
return HostThreadLocal<bool, SubmitsQueue0Storage>();
@@ -141,8 +178,10 @@ void Driver::noteReleasedTails(const Submission& submission) {
void Driver::copyCommands(Submission& submission, const std::uint32_t* guest, std::size_t words) {
submission.commands.clear();
submission.conditionalEnds.clear();
submission.indirectSegments.clear();
std::size_t budget = std::size_t{1} << 26u;
copySegment(submission, guest, words, budget, 0);
std::ranges::sort(submission.indirectSegments, {}, &Submission::IndirectSegment::start);
}
bool Driver::copySegment(Submission& submission, const std::uint32_t* guest, std::size_t words, std::size_t& budget, std::size_t depth) {
@@ -193,10 +232,13 @@ bool Driver::copyLink(Submission& submission, const std::uint32_t* guest, std::s
const std::size_t targetWords = guest[cursor + 10] & 0xfffffu;
if (targetWords != 0) {
GuestMemory::CheckRange(target, targetWords * sizeof(std::uint32_t), alignof(std::uint32_t));
const auto start = submission.commands.size();
if (copySegment(submission, target, targetWords, budget, depth + 1)) {
require(guarded.empty(), "a REWIND inside a conditional execution range is not implemented");
return true;
}
noteIndirectSegment(submission, start, target, targetWords);
if (guarded.empty()) return false;
}
cursor += count;
continue;
@@ -226,10 +268,12 @@ bool Driver::copyLink(Submission& submission, const std::uint32_t* guest, std::s
chainedWords = targetWords;
return false;
}
const auto start = submission.commands.size();
if (copySegment(submission, target, targetWords, budget, depth + 1)) {
require(guarded.empty(), "a REWIND inside a conditional execution range is not implemented");
return true;
}
noteIndirectSegment(submission, start, target, targetWords);
cursor += count;
continue;
}
@@ -252,6 +296,102 @@ bool Driver::copyLink(Submission& submission, const std::uint32_t* guest, std::s
return false;
}
bool Driver::refreshIndirectSegment(Submission& submission, std::size_t index) {
const auto segment = submission.indirectSegments[index];
const auto address = reinterpret_cast<std::uint64_t>(segment.target);
const auto bytes = segment.words * sizeof(std::uint32_t);
const bool pipelineWrites = DrawPipeline::Active() && DrawPipeline::Queue0().Overlaps(address, bytes);
const bool finisherWrites = DrawFinisher::Busy() && DrawFinisher::Get().PendingOverlaps(address, address + bytes);
const bool recordedWrites = [&] {
std::lock_guard gpu(GuestMemory::GpuMutex());
const auto* recorder = Graphics::Recorder::Active();
return recorder != nullptr && recorder->PendingWriterSerial(address, bytes) != 0;
}();
if (!pipelineWrites && !finisherWrites && !recordedWrites) return false;
if (pipelineWrites) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, 0x3f);
if (finisherWrites) DrawFinisher::Get().Drain();
std::vector<std::uint32_t> words(segment.words);
GuestMemory::Read(address, std::as_writable_bytes(std::span(words)), alignof(std::uint32_t));
const auto end = segment.start + segment.words;
if (std::equal(words.begin(), words.end(), submission.commands.begin() + static_cast<std::ptrdiff_t>(segment.start))) return false;
Submission expanded{};
expanded.queue = submission.queue;
std::size_t budget = std::size_t{1} << 26u;
try {
if (copySegment(expanded, words.data(), words.size(), budget, 0)) return false;
validate(expanded, segment.target, false);
readRegisterLists(expanded);
} catch (const std::exception& error) {
static std::atomic<int> reported{0};
if (reported.fetch_add(1, std::memory_order_relaxed) < 8) std::fprintf(stderr, "[gpu] indirect buffer 0x%llx (%zu dwords) changed since its submission but runs as copied: %s\n", static_cast<unsigned long long>(address), segment.words, error.what());
return false;
}
const auto inside = [&](std::size_t cursor) { return cursor >= segment.start && cursor < end; };
if (std::ranges::any_of(submission.flips, [&](const auto& entry) { return inside(entry.first); })) return false;
{
std::lock_guard lock(mutex);
for (std::size_t cursor = 0; cursor < expanded.commands.size(); cursor += Pm4::FillerPacket(expanded.commands[cursor]) ? 1u : Pm4::PacketWords(expanded.commands[cursor])) {
const auto* packet = expanded.commands.data() + cursor;
if (packet[0] == FlipPacketHeader) return false;
if (EopRelease(std::span(expanded.commands).subspan(cursor)) && eopFlips.contains(packet[7])) return false;
if (packet[0] != RenderingWaitPacketHeader) continue;
const std::pair<std::uint32_t, std::uint32_t> target{packet[1], packet[2]};
const auto prepared = segment.waits != nullptr ? segment.waits->find(target) : Submission::PreparedWaits::const_iterator{};
if (segment.waits == nullptr || prepared == segment.waits->end()) {
renderingWaitTargets.insert(target);
return false;
}
expanded.renderingWaits.emplace(cursor, prepared->second);
}
}
if (DrawPipeline::Active() && DrawPipeline::Queue0().Busy()) DrawPipeline::Queue0().Drain(DrawPipeline::DrainReason::Packet, 0x3f);
if (DrawFinisher::Busy()) DrawFinisher::Get().Drain();
const auto delta = static_cast<std::ptrdiff_t>(expanded.commands.size()) - static_cast<std::ptrdiff_t>(segment.words);
const auto moved = [&](std::size_t cursor) { return cursor >= end ? static_cast<std::size_t>(static_cast<std::ptrdiff_t>(cursor) + delta) : cursor; };
auto& commands = submission.commands;
commands.erase(commands.begin() + static_cast<std::ptrdiff_t>(segment.start), commands.begin() + static_cast<std::ptrdiff_t>(end));
commands.insert(commands.begin() + static_cast<std::ptrdiff_t>(segment.start), expanded.commands.begin(), expanded.commands.end());
shiftKeys(submission.flips, segment.start, end, delta);
shiftKeys(submission.renderingWaits, segment.start, end, delta);
for (auto& [cursor, wait] : expanded.renderingWaits) submission.renderingWaits.emplace(segment.start + cursor, std::move(wait));
shiftKeys(submission.registerLists, segment.start, end, delta);
for (auto& [cursor, list] : expanded.registerLists) submission.registerLists.emplace(segment.start + cursor, std::move(list));
std::map<std::size_t, std::size_t> ends;
for (const auto& [begin, rangeEnd] : submission.conditionalEnds) {
if (!inside(begin)) ends.emplace(moved(begin), moved(rangeEnd));
}
for (const auto& [begin, rangeEnd] : expanded.conditionalEnds) ends.emplace(segment.start + begin, segment.start + rangeEnd);
submission.conditionalEnds = std::move(ends);
std::set<std::size_t> held;
for (const auto cursor : submission.heldAtSubmit) {
if (!inside(cursor)) held.insert(moved(cursor));
}
submission.heldAtSubmit = std::move(held);
std::vector<Submission::IndirectSegment> segments(submission.indirectSegments.begin(), submission.indirectSegments.begin() + static_cast<std::ptrdiff_t>(index));
for (const auto& nested : expanded.indirectSegments) segments.push_back({segment.start + nested.start, nested.target, nested.words, segment.waits});
for (auto later = submission.indirectSegments.begin() + static_cast<std::ptrdiff_t>(index) + 1; later != submission.indirectSegments.end(); ++later) segments.push_back({moved(later->start), later->target, later->words, later->waits});
std::ranges::sort(segments, {}, &Submission::IndirectSegment::start);
submission.indirectSegments = std::move(segments);
std::set<std::uint64_t> written;
for (std::size_t cursor = 0; cursor < expanded.commands.size(); cursor += Pm4::FillerPacket(expanded.commands[cursor]) ? 1u : Pm4::PacketWords(expanded.commands[cursor])) {
if (Pm4::FillerPacket(expanded.commands[cursor])) continue;
collectLabelDwords(std::span<const std::uint32_t>(expanded.commands).subspan(cursor, std::min<std::size_t>(Pm4::PacketWords(expanded.commands[cursor]), expanded.commands.size() - cursor)), written);
}
if (!written.empty()) {
std::lock_guard lock(mutex);
auto& worker = workers[submission.queue];
for (const auto dword : written) {
submission.labelWrites.push_back(dword);
++worker.unfinishedWrites[dword];
}
const auto after = segment.start + expanded.commands.size();
std::erase_if(submission.heldAtSubmit, [&](std::size_t cursor) { return cursor >= after && awaitsAny(submission.commands, cursor, written); });
for (auto& later : worker.pending) std::erase_if(later.heldAtSubmit, [&](std::size_t cursor) { return awaitsAny(later.commands, cursor, written); });
}
clearResolvedAhead();
return true;
}
ReferencedProgramScan ReferencedPrograms(std::span<const std::uint32_t> commands, const std::map<std::size_t, std::vector<std::uint32_t>>& registerLists) {
constexpr std::array<std::uint32_t, 7> programRegisters{0x008u, 0x048u, 0x088u, 0x0c8u, 0x108u, 0x148u, 0x20cu};
std::array<std::uint32_t, programRegisters.size() * 2> values{};
@@ -363,30 +503,45 @@ void Driver::noteAwaitingTitle(std::uint32_t queue, std::uint64_t awaited) {
changed.notify_all();
}
void Driver::holdFlipBehindWorker(const Submission& submission, bool cpuFlip) {
if (submission.queue != 0 || onWorkerThread()) return;
bool Driver::holdFlipBehindWorker(const Submission& submission, bool cpuFlip) {
if (submission.queue != 0 || onWorkerThread()) return false;
bool candidate = false;
for (std::size_t cursor = 0; cursor < submission.commands.size() && !candidate; cursor += Pm4::PacketWords(submission.commands[cursor])) {
const auto words = std::span(submission.commands).subspan(cursor);
candidate = words[0] == FlipPacketHeader || EopRelease(words);
}
if (!candidate) return;
if (!candidate) return false;
std::unique_lock lock(mutex);
bool flips = false;
for (std::size_t cursor = 0; cursor < submission.commands.size() && !flips; cursor += Pm4::PacketWords(submission.commands[cursor])) {
const auto words = std::span(submission.commands).subspan(cursor);
flips = words[0] == FlipPacketHeader || (EopRelease(words) && eopFlips.contains(words[7]));
}
if (!flips) return;
if (!flips) return false;
flipHolders.fetch_add(1, std::memory_order_acq_rel);
changed.wait(lock, [&] { return failure != nullptr || stopping.load(std::memory_order_acquire) || shutdownToken.stop_requested() || flipsAhead.load(std::memory_order_acquire) == 0 || queue0AwaitsTitle.load(std::memory_order_acquire); });
flipHolders.fetch_sub(1, std::memory_order_acq_rel);
if (cpuFlip || failure != nullptr || stopping.load(std::memory_order_acquire) || shutdownToken.stop_requested() || flipsAhead.load(std::memory_order_acquire) != 0) return;
return !cpuFlip && !(failure != nullptr || stopping.load(std::memory_order_acquire) || shutdownToken.stop_requested()) && flipsAhead.load(std::memory_order_acquire) == 0;
}
bool Driver::flipWorkDone(const std::shared_ptr<FlipWork>& work) {
if (work == nullptr) return true;
if (!work->finished || !flipWorkDone(work->previous)) return false;
if (work->previous != nullptr) {
work->serial = std::max(work->serial, work->previous->serial);
work->previous.reset();
}
return true;
}
void Driver::holdFlipBehindWork(const std::shared_ptr<FlipWork>& earlier) {
if (earlier == nullptr) return;
std::unique_lock lock(mutex);
flipHolders.fetch_add(1, std::memory_order_acq_rel);
changed.wait(lock, [&] { return failure != nullptr || stopping.load(std::memory_order_acquire) || shutdownToken.stop_requested() || flipWorkOpen.load(std::memory_order_acquire) == 0 || queue0AwaitsTitle.load(std::memory_order_acquire); });
changed.wait(lock, [&] { return failure != nullptr || stopping.load(std::memory_order_acquire) || shutdownToken.stop_requested() || flipWorkDone(earlier) || queue0AwaitsTitle.load(std::memory_order_acquire); });
flipHolders.fetch_sub(1, std::memory_order_acq_rel);
if (failure != nullptr || stopping.load(std::memory_order_acquire) || shutdownToken.stop_requested() || flipWorkOpen.load(std::memory_order_acquire) != 0) return;
const auto workSerial = flipWorkSerial.load(std::memory_order_acquire);
if (failure != nullptr || stopping.load(std::memory_order_acquire) || shutdownToken.stop_requested() || !flipWorkDone(earlier)) return;
const auto workSerial = earlier->serial;
lock.unlock();
waitFlipWork(workSerial);
}
@@ -422,16 +577,33 @@ void Driver::releaseFlipHold() {
if (flipHolders.load(std::memory_order_acquire) != 0) changed.notify_all();
}
void Driver::finishFlipWork(std::uint64_t workSerial) {
void Driver::finishFlipWork(const std::shared_ptr<FlipWork>& work, std::uint64_t workSerial) {
std::lock_guard lock(mutex);
if (workSerial > flipWorkSerial.load(std::memory_order_relaxed)) flipWorkSerial.store(workSerial, std::memory_order_release);
flipWorkOpen.fetch_sub(1, std::memory_order_acq_rel);
if (work != nullptr) {
work->serial = std::max(work->serial, workSerial);
work->finished = true;
flipWorkDone(work);
}
if (flipHolders.load(std::memory_order_acquire) != 0) changed.notify_all();
}
void Driver::reserveOutputs(Submission& submission) {
std::set<std::uint32_t> eopTokens;
const auto prepare = [&](Submission::IndirectSegment& segment) {
auto waits = std::make_shared<Submission::PreparedWaits>();
for (const auto& target : renderingWaitTargets) {
const auto output = outputs.find(target.first);
if (output == outputs.end()) continue;
try {
if (auto wait = output->second->CaptureRenderingWait(target.second)) waits->emplace(target, std::move(wait));
} catch (const std::exception&) {
}
}
segment.waits = std::move(waits);
};
std::size_t nextSegment = 0;
for (std::size_t cursor = 0; cursor < submission.commands.size();) {
while (nextSegment < submission.indirectSegments.size() && submission.indirectSegments[nextSegment].start <= cursor) prepare(submission.indirectSegments[nextSegment++]);
const auto* words = submission.commands.data() + cursor;
if (words[0] == RenderingWaitPacketHeader) {
const auto output = outputs.find(words[1]);
@@ -439,6 +611,7 @@ void Driver::reserveOutputs(Submission& submission) {
auto wait = output->second->CaptureRenderingWait(words[2]);
require(wait != nullptr, "video output returned a null rendering wait");
submission.renderingWaits.emplace(cursor, std::move(wait));
renderingWaitTargets.emplace(words[1], words[2]);
}
if (EopRelease(std::span(submission.commands).subspan(cursor))) {
const auto token = words[7];
@@ -611,7 +784,8 @@ void Driver::Submit(const Packet* packet, std::uint32_t queue, bool cpuFlip) {
readRegisterLists(submission);
if (APS5_ENABLE_TIMING_LOG) submission.validatedAt = std::chrono::steady_clock::now();
waitForFlipRoom(submission);
holdFlipBehindWorker(submission, cpuFlip);
const bool holdsWork = holdFlipBehindWorker(submission, cpuFlip);
std::shared_ptr<FlipWork> earlierFlipWork;
const auto scan = ReferencedPrograms(submission.commands, submission.registerLists);
if (!scan.complete || submission.rewindTail != nullptr) {
AwaitRegistrationPreparation();
@@ -671,7 +845,10 @@ void Driver::Submit(const Packet* packet, std::uint32_t queue, bool cpuFlip) {
if (queue == 0 && !submission.flips.empty()) {
submission.holdsFlip = true;
flipsAhead.fetch_add(1, std::memory_order_acq_rel);
flipWorkOpen.fetch_add(1, std::memory_order_acq_rel);
submission.flipWork = std::make_shared<FlipWork>();
submission.flipWork->previous = lastFlipWork;
if (holdsWork) earlierFlipWork = lastFlipWork;
lastFlipWork = submission.flipWork;
}
if (!submission.flips.empty()) ++flipSubmissionsOfThread();
enqueue(std::move(submission));
@@ -698,6 +875,7 @@ void Driver::Submit(const Packet* packet, std::uint32_t queue, bool cpuFlip) {
}
CheckFailure();
}
holdFlipBehindWork(earlierFlipWork);
}
void Driver::SuspendPoint() {
@@ -4,19 +4,24 @@
#include "prx/libc/include/CpuTopology.hpp"
#include "prx/libc/include/general/ThreadName.hpp"
#include <array>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <optional>
#include <vector>
#ifdef _WIN32
#include <tlhelp32.h>
#elif defined(__linux__)
#else
#include <pthread.h>
#ifdef __linux__
#include <dirent.h>
#include <string>
#include <sched.h>
#include <unistd.h>
#endif
#endif
namespace AgcDriver::DriverDetail {
@@ -34,6 +39,19 @@ std::uint64_t WorkerAffinityMask() {
return mask;
}
void NameDriverThread(const char* name) {
#ifdef _WIN32
const HRESULT nameResult = ThreadName::SetCurrent(name);
if (FAILED(nameResult)) std::fprintf(stderr, "[thread-name] could not name %s (0x%08lx)\n", name, static_cast<unsigned long>(nameResult));
#elif defined(__APPLE__)
const int nameResult = pthread_setname_np(name);
if (nameResult != 0) std::fprintf(stderr, "[thread-name] could not name %s (%s)\n", name, std::strerror(nameResult));
#else
const int nameResult = pthread_setname_np(pthread_self(), name);
if (nameResult != 0) std::fprintf(stderr, "[thread-name] could not name %s (%s)\n", name, std::strerror(nameResult));
#endif
}
#ifdef __linux__
namespace {
void NoteWorkerThread();
@@ -42,10 +60,6 @@ void NoteWorkerThread();
void PinWorkerThread(const char* role) {
TracyZone::NameThread(role);
#ifdef _WIN32
const HRESULT nameResult = ThreadName::SetCurrent(role);
if (FAILED(nameResult)) std::fprintf(stderr, "[thread-name] could not name %s (0x%08lx)\n", role, static_cast<unsigned long>(nameResult));
#endif
#ifdef __linux__
NoteWorkerThread();
#endif
@@ -201,6 +201,11 @@ void AwaitRegisteredPreparation(PreparedShaders& prepared, std::unique_lock<std:
if (prepared.failure != nullptr) std::rethrow_exception(prepared.failure);
}
bool RegisteredPreparationFailed(const ShaderSnapshot& snapshot) {
std::lock_guard lock(snapshot.prepared->mutex);
return snapshot.prepared->failure != nullptr;
}
bool CommittedAbi(const ShaderSnapshot& snapshot, std::span<const std::uint64_t> key) {
std::unique_lock lock(snapshot.prepared->mutex);
AwaitRegisteredPreparation(*snapshot.prepared, lock);
@@ -594,7 +599,7 @@ void ShaderPreparationTransaction::Commit() {
auto& destination = *change.destination;
for (auto index = std::min(change.baseEntries, destination.entries.size()); index < destination.entries.size(); ++index) {
const auto& entry = destination.entries[index];
if (std::ranges::none_of(change.prepared.entries, [&](const auto& existing) { return existing.codeOffset == entry.codeOffset && existing.handle == entry.handle; })) change.prepared.entries.push_back(entry);
if (std::ranges::none_of(change.prepared.entries, [&](const auto& existing) { return existing.codeOffset == entry.codeOffset && existing.handle->artifact == entry.handle->artifact; })) change.prepared.entries.push_back(entry);
}
for (auto index = std::min(change.baseAbis, destination.registeredAbis.size()); index < destination.registeredAbis.size(); ++index) {
const auto& abi = destination.registeredAbis[index];
@@ -797,7 +802,7 @@ void PublishRegisteredShader(std::shared_ptr<ShaderRegistry>& registry, const st
const auto found = registry->find(snapshot->codeAddress);
if (found != registry->end()) {
for (const auto& current : found->second) {
if (current->headerAddress == snapshot->headerAddress && current->type == snapshot->type && current->code == snapshot->code && current->header == snapshot->header) {
if (current->headerAddress == snapshot->headerAddress && current->type == snapshot->type && current->code == snapshot->code && current->header == snapshot->header && !RegisteredPreparationFailed(*current)) {
if (current == found->second.back()) {
transaction.Commit();
return;
@@ -895,7 +900,7 @@ void ReportPreparedAtUse(const ShaderSnapshot& snapshot, const ShaderRecompiler:
return;
}
if (!snapshot.header.empty()) {
if (!snapshot.prepared->deferred) APS5_LOG_ERR("Shader 0x%llx stage %u has no artifact prepared at registration for the state of this draw or dispatch; preparing it at use", static_cast<unsigned long long>(request.shader.codeAddress), static_cast<std::uint32_t>(request.shader.stage));
if (!snapshot.prepared->deferred && snapshot.prepared->resolving == 0) APS5_LOG_ERR("Shader 0x%llx stage %u has no artifact prepared at registration for the state of this draw or dispatch; preparing it at use", static_cast<unsigned long long>(request.shader.codeAddress), static_cast<std::uint32_t>(request.shader.stage));
return;
}
if (request.shader.stage == ShaderRecompiler::ShaderStage::Compute) {
@@ -1031,6 +1036,11 @@ std::vector<ShaderRecompiler::TableCallee> ReadTableCallees(const ShaderRecompil
const auto words = ReadGuestBytes(pointer + call.descriptorOffset, 16u, "call table descriptor");
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");
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");
@@ -1138,6 +1148,14 @@ std::shared_ptr<const ShaderRecompiler::LinkedCalls> LinkUserDataCallees(const S
}
bool StageLinksUserDataCallees(const ShaderSnapshot& snapshot, std::size_t codeOffset) {
if (!snapshot.prepared) return false;
std::lock_guard lock(snapshot.prepared->mutex);
return std::any_of(snapshot.prepared->userDataLinks.begin(), snapshot.prepared->userDataLinks.end(), [&](const auto& link) {
return link.codeOffset == codeOffset && ((link.linked != nullptr && !link.linked->code.empty()) || !link.callees.empty() || (link.sites != nullptr && (!link.sites->calls.empty() || !link.sites->tableCalls.empty())));
});
}
ShaderRecompiler::PreparedShaderInvocation InvocationFor(const ShaderSnapshot& snapshot, std::size_t codeOffset, const ShaderRecompiler::RecompileRequest& request) {
require(codeOffset < snapshot.code.size(), "prepared shader code offset is outside the snapshot");
const auto code = std::span(snapshot.code).subspan(codeOffset);
@@ -1532,6 +1550,51 @@ void DeferPipelineStage(PreparedShaderState& prepared, const ShaderSnapshot& sna
prepared.deferred = true;
}
class ResolvingAbi {
public:
explicit ResolvingAbi(std::shared_ptr<const ShaderSnapshot> owner) : snapshot(std::move(owner)) {
std::lock_guard lock(snapshot->prepared->mutex);
++snapshot->prepared->resolving;
}
ResolvingAbi(const ResolvingAbi&) = delete;
ResolvingAbi& operator=(const ResolvingAbi&) = delete;
~ResolvingAbi() {
std::lock_guard lock(snapshot->prepared->mutex);
--snapshot->prepared->resolving;
}
const ShaderSnapshot& Snapshot() const {
return *snapshot;
}
private:
std::shared_ptr<const ShaderSnapshot> snapshot;
};
void PrepareResolvedAbi(const ResolvingAbi& resolving, RegisteredPreparation& plan) {
PerformanceContext timingContext(FrameTiming::Preparation());
const auto& snapshot = resolving.Snapshot();
std::vector<PreparedShaders::Entry> entries;
std::optional<std::string> failure;
try {
if (RegistrationPrepareWithinMemoryBudget()) entries = PrepareRegistered(plan);
else LogRegistrationPrepareDeferred();
} catch (const std::exception& error) {
failure = error.what();
}
std::lock_guard lock(snapshot.prepared->mutex);
if (failure) {
DeferPipelineStage(*snapshot.prepared, snapshot, failure->c_str());
return;
}
for (auto& entry : entries) {
const auto duplicate = std::ranges::any_of(snapshot.prepared->entries, [&](const auto& existing) { return existing.codeOffset == entry.codeOffset && existing.handle->artifact == entry.handle->artifact; });
if (!duplicate) snapshot.prepared->entries.push_back(std::move(entry));
}
}
std::optional<std::string> FailedRegistration(const ShaderSnapshot& snapshot) {
std::unique_lock lock(snapshot.prepared->mutex);
try {
@@ -1601,7 +1664,7 @@ public:
if (pool == nullptr) continue;
std::unique_lock lock(pool->mutex, std::try_to_lock);
if (!lock.owns_lock()) return std::nullopt;
pending += pool->tasks.size() + pool->running;
pending += pool->tasks.size() + pool->background.size() + pool->running;
}
return pending;
}
@@ -1658,6 +1721,19 @@ public:
task();
}
void SubmitBackground(std::function<void()> task) {
{
std::unique_lock lock(mutex);
if (threads != 0 && !closed) {
background.push_back({std::move(task), nullptr, 0});
lock.unlock();
ready.notify_one();
return;
}
}
task();
}
void Prioritize(const PreparedShaders& prepared) {
std::lock_guard lock(mutex);
moveToFront(prepared);
@@ -1704,6 +1780,8 @@ public:
}
idle.notify_all();
}
std::ranges::move(background, std::back_inserter(dropped));
background.clear();
idle.wait(lock, [&] { return tasks.empty() && running == 0; });
joined.swap(workers);
}
@@ -1713,6 +1791,7 @@ public:
private:
static constexpr std::size_t StackBytes = 64u << 20u;
static constexpr unsigned ForegroundBeforeBackground = 8;
void moveToFront(const PreparedShaders& prepared) {
const auto found = std::ranges::find_if(tasks, [&](const auto& task) { return task.prepared == &prepared; });
@@ -1790,17 +1869,25 @@ private:
{
std::unique_lock lock(pool.mutex);
auto next = pool.tasks.end();
bool fromBackground = false;
pool.ready.wait(lock, [&] {
next = std::ranges::find_if(pool.tasks, [&](const Task& queued) { return !queued.budgeted || pool.budgetedRunning < pool.budgetedLimit; });
return next != pool.tasks.end() || (pool.closed && pool.tasks.empty());
fromBackground = !pool.background.empty() && (next == pool.tasks.end() || pool.foregroundRun >= ForegroundBeforeBackground);
return fromBackground || next != pool.tasks.end() || (pool.closed && pool.tasks.empty());
});
if (next == pool.tasks.end()) {
if (fromBackground) {
task = std::move(pool.background.front());
pool.background.pop_front();
pool.foregroundRun = 0;
} else if (next == pool.tasks.end()) {
liveWorkers.fetch_sub(1, std::memory_order_acq_rel);
return nullptr;
} else {
task = std::move(*next);
pool.tasks.erase(next);
if (!pool.background.empty()) ++pool.foregroundRun;
if (task.program != 0) pool.waitingPrograms.fetch_sub(1, std::memory_order_relaxed);
}
task = std::move(*next);
pool.tasks.erase(next);
if (task.program != 0) pool.waitingPrograms.fetch_sub(1, std::memory_order_relaxed);
++pool.running;
if (task.budgeted) ++pool.budgetedRunning;
}
@@ -1816,7 +1903,7 @@ private:
if (budgeted) --pool.budgetedRunning;
pool.unfinished.erase(sequence);
pool.disown(prepared, sequence);
drained = pool.tasks.empty() && pool.running == 0;
drained = pool.tasks.empty() && pool.background.empty() && pool.running == 0;
pool.idle.notify_all();
}
if (budgeted) pool.ready.notify_all();
@@ -1840,6 +1927,8 @@ private:
std::condition_variable idle;
std::deque<Task> tasks;
std::atomic<std::size_t> waitingPrograms{0};
std::deque<Task> background;
unsigned foregroundRun = 0;
std::vector<Worker> workers;
unsigned threads = 0;
inline static std::atomic<unsigned> liveWorkers{0};
@@ -2268,24 +2357,35 @@ void Driver::ResolveShaderAbi(const Shader* shader, std::span<const ShaderRegist
struct RegisteredAbiKeyStorage {};
auto& key = HostThreadLocal<std::vector<std::uint64_t>, RegisteredAbiKeyStorage>();
BuildRegisteredAbiKey(state, *localDevice, key);
if (LazyShaderPreparation()) {
if (LazyShaderPreparation() || AsyncRegistrationPrepare()) {
if (CommittedAbi(*snapshot, key) && !transaction.Tracks(*snapshot)) {
transaction.Commit();
return;
}
const auto& resolved = transaction.Read(*snapshot).registeredAbis;
if (std::ranges::find(resolved, key) != resolved.end()) {
transaction.Commit();
return;
}
std::optional<std::string> invalid;
std::unique_ptr<RegisteredPreparation> plan;
try {
static_cast<void>(PlanRegistered(*snapshot, *localDevice, state, false));
plan = PlanRegistered(*snapshot, *localDevice, state, false);
} catch (const std::exception& error) {
invalid = error.what();
}
auto& prepared = transaction.Edit(*snapshot);
if (invalid) DeferPipelineStage(prepared, *snapshot, invalid->c_str());
prepared.registeredAbis.push_back(key);
prepared.deferred = true;
if (LazyShaderPreparation()) prepared.deferred = true;
transaction.Commit();
if (invalid) return;
if (!LazyShaderPreparation()) {
if (plan == nullptr) return;
plan->prebuildDevice = localDevice;
RegistrationPreparePool::Instance().SubmitBackground([resolving = std::make_shared<ResolvingAbi>(snapshot), plan = std::shared_ptr<RegisteredPreparation>(std::move(plan))] { PrepareResolvedAbi(*resolving, *plan); });
return;
}
PreparedShaders::DeferredAbi deferred{key, {}, {}, localDevice};
for (const auto reg : context) deferred.context.emplace_back(reg.offset, reg.value);
for (const auto reg : primitive) deferred.primitive.emplace_back(reg.offset, reg.value);
@@ -2572,7 +2672,7 @@ void Driver::RegisterShader(const Shader* shader) {
const auto found = shaders->find(snapshot.codeAddress);
if (found != shaders->end()) {
for (const auto& current : found->second) {
if (current->headerAddress == snapshot.headerAddress && current->type == snapshot.type && current->code == snapshot.code && current->header == snapshot.header) {
if (current->headerAddress == snapshot.headerAddress && current->type == snapshot.type && current->code == snapshot.code && current->header == snapshot.header && !RegisteredPreparationFailed(*current)) {
const auto identical = current;
PublishRegisteredShader(shaders, identical);
transaction.Commit();
@@ -89,7 +89,7 @@ bool Driver::reapEachPacket() {
std::uint64_t Driver::batchCap() {
static const std::uint64_t value = [] {
const char* text = std::getenv("APS5_BATCH_CAP");
return text ? std::strtoull(text, nullptr, 10) : 64ull;
return text ? std::strtoull(text, nullptr, 10) : 512ull;
}();
return value;
}
@@ -136,11 +136,13 @@ void Driver::waitMemory(std::span<const std::uint32_t> packet, std::uint32_t que
bool warned = false;
struct EpochPoint {
std::uint64_t address;
std::size_t bytes;
bool bump = true;
~EpochPoint() {
if (bump) bumpEpoch(&EpochBumps::waits);
if (bump) bumpWaitEpoch(address, bytes);
}
} epochPoint;
} epochPoint{awaited, awaitedBytes};
bool ownStoreUnlanded = false;
const auto memorySatisfied = [&] {
ownStoreUnlanded = false;
@@ -1,7 +1,9 @@
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include <cstdlib>
#include <unordered_map>
namespace AgcDriver::DriverDetail {
@@ -37,6 +39,33 @@ void Driver::bumpEpoch(std::uint64_t EpochBumps::*counter) {
++(epochBumps().*counter);
}
void Driver::bumpWaitEpoch(std::uint64_t address, std::size_t bytes) {
struct Ordered {
std::uint64_t value = 0;
std::uint64_t generation = 0;
};
struct OrderedStorage {};
auto& ordered = HostThreadLocal<std::unordered_map<std::uint64_t, Ordered>, OrderedStorage>();
static const bool memo = std::getenv("APS5_NO_ORDERED_WAITS") == nullptr;
if (!GuestMemory::Accessible(reinterpret_cast<const void*>(address), bytes)) {
bumpEpoch(&EpochBumps::waits);
return;
}
const auto generation = memo ? GuestMemory::CollectWritesUncached(address, bytes) : 0;
const std::uint64_t value = bytes == 8 ? *reinterpret_cast<const volatile std::uint64_t*>(address) : *reinterpret_cast<const volatile std::uint32_t*>(address);
if (generation != 0) {
const auto found = ordered.find(address);
if (found != ordered.end() && found->second.value == value && GuestMemory::UnchangedSince(address, bytes, found->second.generation)) {
++epochBumps().waitsOrdered;
return;
}
}
bumpEpoch(&EpochBumps::waits);
if (generation == 0) return;
if (ordered.size() >= 4096) ordered.clear();
ordered[address] = {value, generation};
}
bool Driver::packetEpoch() {
static const bool packet = std::getenv("APS5_PACKET_EPOCH") != nullptr;
return packet;
@@ -1177,10 +1177,11 @@ OverlayRect PerformanceOverlay::RecordRects(VkCommandBuffer commands, std::size_
begin.framebuffer = framebuffer;
begin.renderArea = area;
context.Function<PFN_vkCmdBeginRenderPass>("vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, drawing);
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(extent.width), static_cast<float>(extent.height), 0.0f, 1.0f};
context.Function<PFN_vkCmdSetViewport>("vkCmdSetViewport")(commands, 0, 1, &viewport);
context.Function<PFN_vkCmdSetScissor>("vkCmdSetScissor")(commands, 0, 1, &area);
Graphics::CommandState state;
state.Begin(commands, false);
state.BindPipeline(context, drawing, 0);
state.SetViewport(context, {0.0f, 0.0f, static_cast<float>(extent.width), static_cast<float>(extent.height), 0.0f, 1.0f});
state.SetScissor(context, area);
const OverlayParameters parameters{OverlayPalette(format, colorSpace), {static_cast<float>(extent.width), static_cast<float>(extent.height)}};
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), &parameters);
const VkBuffer buffer = slot.rects->Handle();
@@ -3,6 +3,7 @@
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/PreciseWait.hpp"
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
#include <algorithm>
#include <atomic>
#include <thread>
@@ -91,6 +92,17 @@ std::uint64_t address(std::uint32_t low, std::uint32_t high) {
return low | (static_cast<std::uint64_t>(high) << 32u);
}
using GcnSystemCounterTicks = std::chrono::duration<std::uint64_t, std::ratio<1, 800000000>>;
const auto GcnSystemCounterStart = std::chrono::steady_clock::now();
std::uint64_t ReleaseMemValue(std::span<const std::uint32_t> packet) {
const auto dataSelect = packet[2] >> 29u;
if (dataSelect == 3) return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() / 10);
if (dataSelect == 4) return std::chrono::duration_cast<GcnSystemCounterTicks>(std::chrono::steady_clock::now() - GcnSystemCounterStart).count();
return address(packet[5], packet[6]);
}
std::uint32_t registerOffset(std::uint32_t value) {
require(value != 0xffffffffu, "indirect register sentinel semantics are not implemented");
const auto offset = value & ~0x70000000u;
@@ -266,7 +278,7 @@ std::string_view UnsupportedReason(std::uint32_t header) {
case 0x11: case 0x12: case 0x13: case 0x15: case 0x16: case 0x20: case 0x22: case 0x26: case 0x27:
case 0x2a: case 0x2d: case 0x2f: case 0x35: case 0x37: case 0x40: case 0x42: case 0x45: case 0x46: case 0x50:
case 0x58: case 0x63: case 0x64: case 0x69: case 0x76: case 0x79: case 0x7a:
case 0x81: case 0x83: case 0x91: case 0x9f: case 0x28: return {};
case 0x51: case 0x81: case 0x83: case 0x91: case 0x9f: case 0x28: return {};
case 0x24: case 0x25: case 0x2c: case 0x38:
if (IndirectDrawsDisabled()) return "graphics draw, shader stages and guest render-target materialization are not implemented";
return {};
@@ -348,6 +360,11 @@ void Validate(std::span<const std::uint32_t> packet, std::uint32_t queue) {
require(packet[1] == 1 && (packet[2] & 3u) == 0 && packet[3] <= 0xffffu, "unsupported indirect base index, alignment or address bits");
if ((header & 2u) == 0) graphics();
break;
case 0x51:
graphics();
size(4);
require((packet[1] & 0xffff0000u) == 0, "CONTEXT_REG_RMW reserved offset bits are not implemented");
break;
case 0x12: graphics(); size(2); require((packet[1] & ~0xfu) == 0, "unsupported CLEAR_STATE payload bits"); break;
case 0x20: {
graphics();
@@ -529,9 +546,9 @@ void Validate(std::span<const std::uint32_t> packet, std::uint32_t queue) {
case 0x49: {
size(8);
const auto dataSelect = packet[2] >> 29u;
require(dataSelect != 4, "RELEASE_MEM of the 64-bit system counter (DATA_SEL 4) is not implemented");
require(dataSelect != 4 || ShaderRecompiler::GcnGuestShaders(), "RELEASE_MEM of the 64-bit system counter (DATA_SEL 4) is not implemented");
require(dataSelect <= 5, "reserved RELEASE_MEM DATA_SEL");
require(dataSelect <= 3, "GDS RELEASE_MEM data is not implemented");
require(dataSelect != 5, "GDS RELEASE_MEM data is not implemented");
require(dataSelect == 0 || address(packet[3], packet[4]) == 0 || (packet[3] & (dataSelect == 1 ? 3u : 7u)) == 0, "misaligned RELEASE_MEM destination");
break;
}
@@ -676,10 +693,9 @@ std::optional<LabelWrite> DecodeLabelWrite(std::span<const std::uint32_t> packet
if (opcode == 0x49 && packet.size() >= 7) {
const auto dataSelect = packet[2] >> 29u;
const auto destination = address(packet[3], packet[4]);
if (dataSelect == 0 || dataSelect > 3) return std::nullopt;
if (dataSelect == 0 || dataSelect > 4) return std::nullopt;
if (destination == 0) return std::nullopt;
std::uint64_t value = address(packet[5], packet[6]);
if (dataSelect == 3) value = static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() / 10);
const auto value = ReleaseMemValue(packet);
LabelWrite label{destination, {}};
label.inlineSize = dataSelect == 1 ? 4 : 8;
std::memcpy(label.inlineBytes.data(), &value, label.inlineSize);
@@ -776,7 +792,7 @@ std::vector<PacketStore> DecodeStores(std::span<const std::uint32_t> packet) {
case 0x49: {
const auto label = DecodeLabelWrite(packet);
if (!label.has_value()) return {};
if ((packet[2] >> 29u) == 3) return {runTime(label->address, label->Bytes().size())};
if ((packet[2] >> 29u) >= 3) return {runTime(label->address, label->Bytes().size())};
return {known(label->address, label->Bytes())};
}
case 0x37: {
@@ -1203,13 +1219,17 @@ void Execute(std::span<const std::uint32_t> packet, QueueState& queue) {
const auto dataSelect = packet[2] >> 29u;
const auto destination = address(packet[3], packet[4]);
if (dataSelect == 0 || destination == 0) return;
std::uint64_t value = address(packet[5], packet[6]);
if (dataSelect == 3) {
value = static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() / 10);
}
const auto value = ReleaseMemValue(packet);
GuestMemory::Write(destination, std::as_bytes(std::span(&value, 1)).first(dataSelect == 1 ? 4 : 8), dataSelect == 1 ? 4 : 8);
return;
}
case 0x51: {
const auto offset = packet[1];
require(queue.context.contains(offset), "CONTEXT_REG_RMW register has no known value");
const auto value = (queue.context.at(offset) & ~packet[2]) | (packet[3] & packet[2]);
writeRegister(queue, 0x69, offset, value);
return;
}
case 0x69: case 0x76: case 0x79: case 0x7a: {
if (IsTagMarker(packet)) return;
const auto offset = registerOffset(packet[1]);
@@ -3,6 +3,7 @@
#include "prx/libSceAgcDriver/Execution/include/AspectFit.hpp"
#include "prx/libSceAgcDriver/Execution/include/DisplayFormat.hpp"
#include "prx/libSceAgcDriver/Execution/include/PqToSdr.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp"
#include "prx/libSceAgcDriver/Graphics/shaders/PresentationPassFrag_spv.h"
#include "prx/libSceAgcDriver/Graphics/shaders/PresentationPassVert_spv.h"
@@ -360,10 +361,11 @@ void PresentationPass::draw(VkCommandBuffer commands, const Slot& slot, const Ta
begin.framebuffer = framebuffer;
begin.renderArea = {{0, 0}, extent};
context.Function<PFN_vkCmdBeginRenderPass>("vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, entry.pipeline);
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(extent.width), static_cast<float>(extent.height), 0.0f, 1.0f};
context.Function<PFN_vkCmdSetViewport>("vkCmdSetViewport")(commands, 0, 1, &viewport);
context.Function<PFN_vkCmdSetScissor>("vkCmdSetScissor")(commands, 0, 1, &scissor);
Graphics::CommandState state;
state.Begin(commands, false);
state.BindPipeline(context, entry.pipeline, 0);
state.SetViewport(context, {0.0f, 0.0f, static_cast<float>(extent.width), static_cast<float>(extent.height), 0.0f, 1.0f});
state.SetScissor(context, scissor);
context.Function<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &slot.set, 0, nullptr);
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(parameters), parameters);
context.Function<PFN_vkCmdDraw>("vkCmdDraw")(commands, 3, 1, 0, 0);
@@ -1,6 +1,7 @@
#include "prx/libSceAgcDriver/Execution/include/PresentationUpscaler.hpp"
#include "prx/libSceAgcDriver/Execution/include/AspectFit.hpp"
#include "prx/libSceAgcDriver/Execution/include/PresentationPass.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp"
#include "prx/libSceAgcDriver/Graphics/shaders/FsrEasuFrag_spv.h"
#include "prx/libSceAgcDriver/Graphics/shaders/FsrRcasFrag_spv.h"
@@ -344,11 +345,15 @@ void PresentationUpscaler::draw(VkCommandBuffer commands, const Target& entry, V
begin.framebuffer = framebuffer;
begin.renderArea = {{0, 0}, extent};
context.Function<PFN_vkCmdBeginRenderPass>("vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, entry.pipeline);
// Not tracked across passes: suppress = false makes the state emit every command, as before.
Graphics::CommandState recording;
recording.Begin(commands, false);
const VkDynamicState dynamicStates[2] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
recording.BindPipeline(context, entry.pipeline, Graphics::CommandState::DynamicSlots(dynamicStates));
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(extent.width), static_cast<float>(extent.height), 0.0f, 1.0f};
const VkRect2D scissor{{0, 0}, extent};
context.Function<PFN_vkCmdSetViewport>("vkCmdSetViewport")(commands, 0, 1, &viewport);
context.Function<PFN_vkCmdSetScissor>("vkCmdSetScissor")(commands, 0, 1, &scissor);
recording.SetViewport(context, viewport);
recording.SetScissor(context, scissor);
context.Function<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, 0, nullptr);
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, size, parameters);
context.Function<PFN_vkCmdDraw>("vkCmdDraw")(commands, 3, 1, 0, 0);
@@ -347,7 +347,7 @@ void ShaderMemory::preparePage(Page& page, std::uint64_t base) {
// A page is either mapped whole or read word by word where the guest mapped less than a page,
// or where recorded GPU work writes into it (a whole-page read would wait for that work).
if (GuestMemory::Accessible(reinterpret_cast<const void*>(base), PageBytes)) {
if (WordwisePages() && pendingWrite != nullptr && pendingWrite(base, PageBytes, {}) != PendingWrite::None) {
if (WordwisePages() && pendingSpan != nullptr && pendingSpan(base, PageBytes, {}) != PendingWrite::None) {
page.wordwise = true;
++CaptureTotals().pagesWordwise;
return;
@@ -395,9 +395,9 @@ bool ShaderMemory::read(void* context, std::uint64_t address, std::uint32_t* val
};
const auto checkSpanBytes = std::max<std::size_t>(self.descriptorSpanBytes, sizeof(*value));
if (page.wordwise && page.valid.Test(index) &&
(self.forceSync != 0u ? self.pendingWrite(address, checkSpanBytes, {}) != PendingWrite::None
: (spanInvalidatesCache(self.pendingWrite(address, checkSpanBytes, {})) ||
(checkSpanBytes > sizeof(*value) && spanInvalidatesCache(self.pendingWrite(address, sizeof(*value), {})))))) {
(self.forceSync != 0u ? self.pendingSpan(address, checkSpanBytes, {}) != PendingWrite::None
: (spanInvalidatesCache(self.pendingSpan(address, checkSpanBytes, {})) ||
(checkSpanBytes > sizeof(*value) && spanInvalidatesCache(self.pendingSpan(address, sizeof(*value), {})))))) {
page.valid.Clear(index);
page.raw.Clear(index);
}
@@ -407,10 +407,10 @@ bool ShaderMemory::read(void* context, std::uint64_t address, std::uint32_t* val
bool forcedRaw = false;
if (page.wordwise) {
if (self.descriptorSpanBytes > sizeof(word) &&
(self.forceSync != 0u ? self.pendingWrite(address, self.descriptorSpanBytes, {}) != PendingWrite::None
: spanNeedsSync(self.pendingWrite(address, self.descriptorSpanBytes, {})))) {
(self.forceSync != 0u ? self.pendingSpan(address, self.descriptorSpanBytes, {}) != PendingWrite::None
: spanNeedsSync(self.pendingSpan(address, self.descriptorSpanBytes, {})))) {
policy = PendingWrite::Sync;
forcedRaw = self.forceSync != 0u && !spanNeedsSync(self.pendingWrite(address, self.descriptorSpanBytes, {}));
forcedRaw = self.forceSync != 0u && !spanNeedsSync(self.pendingSpan(address, self.descriptorSpanBytes, {}));
} else {
policy = self.pendingWrite(address, sizeof(word), std::as_writable_bytes(std::span(&word, 1)));
if (self.forceSync != 0u && policy != PendingWrite::None) {
@@ -653,8 +653,8 @@ bool ShaderMemory::accessible(void* context, std::uint64_t address, std::uint64_
bool ShaderMemory::pending(void* context, std::uint64_t address, std::uint64_t bytes) {
const auto& self = *static_cast<const ShaderMemory*>(context);
if (self.pendingWrite == nullptr || bytes == 0) return false;
const auto policy = self.pendingWrite(address, static_cast<std::size_t>(bytes), {});
if (self.pendingSpan == nullptr || bytes == 0) return false;
const auto policy = self.pendingSpan(address, static_cast<std::size_t>(bytes), {});
return policy == PendingWrite::Sync || policy == PendingWrite::VerifyRaw || policy == PendingWrite::VerifyKnownValue;
}
@@ -457,7 +457,7 @@ struct ComputePipelineKey {
ShaderRecompiler::PipelineIdentity identity;
bool pushConstants = false;
auto operator<=>(const ComputePipelineKey&) const = default;
static ComputePipelineKey Of(const ShaderRecompiler::RecompileResult& shader, bool pushConstants) { return {shader.Identity(), pushConstants}; }
static ComputePipelineKey Of(const ShaderRecompiler::RecompileResult& shader, bool pushConstants) { return {Graphics::DescribedPipelineIdentity(shader), pushConstants}; }
};
constexpr std::uint64_t WorkgroupMemoryGranule = 1u << 20u;
@@ -823,11 +823,11 @@ struct VulkanDevice::State {
}
template<typename TFunction>
TFunction DeviceFunction(const char* name) const {
TFunction DeviceFunction(Graphics::FunctionName name) const {
++Graphics::DeviceProcLookups();
auto function = reinterpret_cast<TFunction>(deviceProc(device, name));
auto function = reinterpret_cast<TFunction>(deviceProc(device, name.Value()));
if (function == nullptr) {
throw std::runtime_error(std::string("Vulkan device function missing: ") + name);
throw std::runtime_error(std::string("Vulkan device function missing: ") + name.Value());
}
return function;
}
@@ -1202,6 +1202,7 @@ struct VulkanDevice::State {
Graphics::ClearRetainedSpaces(device);
Graphics::ClearCachedTextures(device);
Graphics::ClearSnapshotCopies(device);
Graphics::ClearUploadCopies(device);
Graphics::ClearImageMirrors(device);
Graphics::ClearHostImports(device);
patternBuffers.clear();
@@ -1942,7 +1943,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
#endif
}
VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT listRestartFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIMITIVE_TOPOLOGY_LIST_RESTART_FEATURES_EXT};
if (hasExtension(VK_EXT_PRIMITIVE_TOPOLOGY_LIST_RESTART_EXTENSION_NAME)) {
if (hasExtension(VK_EXT_PRIMITIVE_TOPOLOGY_LIST_RESTART_EXTENSION_NAME) && std::getenv("APS5_NO_LIST_RESTART") == nullptr) {
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &listRestartFeatures};
state->InstanceFunction<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(selected, &features);
state->primitiveListRestart = listRestartFeatures.primitiveTopologyListRestart == VK_TRUE;
@@ -2539,7 +2540,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
const auto host = std::ranges::find_first_of(hosts, available);
if (std::ranges::find(available, VK_TIME_DOMAIN_DEVICE_KHR) != available.end() && host != hosts.end()) {
state->hostTimeDomain = *host;
state->calibratedTimestamps = state->DeviceFunction<PFN_vkGetCalibratedTimestampsKHR>(khr ? "vkGetCalibratedTimestampsKHR" : "vkGetCalibratedTimestampsEXT");
state->calibratedTimestamps = khr ? state->DeviceFunction<PFN_vkGetCalibratedTimestampsKHR>("vkGetCalibratedTimestampsKHR") : state->DeviceFunction<PFN_vkGetCalibratedTimestampsKHR>("vkGetCalibratedTimestampsEXT");
}
}
state->DeviceFunction<PFN_vkGetDeviceQueue>("vkGetDeviceQueue")(state->device, family, 0, &state->queue);
@@ -4908,6 +4909,10 @@ void VulkanDevice::ColorMetadataPass(const Graphics::ColorMetadataPass& pass) {
Graphics::RunColorMetadataPass(graphicsContext(), pass);
}
void VulkanDevice::DepthExpandPass(const Graphics::DepthExpandPass& pass) {
Graphics::RunDepthExpandPass(graphicsContext(), pass);
}
bool VulkanDevice::PrebuildGraphicsLibraries(const Graphics::ShaderStages& stages, std::span<const Graphics::CompiledShader> shaders) {
PerformanceTimer timing("Vulkan.GraphicsPipelinePrebuild");
const auto context = graphicsContext();
@@ -5469,6 +5474,10 @@ VkDevice VulkanDevice::Device() const {
return state->device;
}
bool VulkanDevice::DmaBufImportSelected() const {
return Graphics::DmaBufImportSelected(graphicsContext());
}
VulkanDevice::DispatchMoveCount VulkanDevice::DispatchMoveCounts() {
auto& moves = DispatchMoves();
DispatchMoveCount count{moves.checked.load(), moves.exact.load(), moves.moved.load(), 0, 0, moves.rebuilt.load(), moves.kept.load(), moves.served.load()};
@@ -5953,7 +5962,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) {
recorder.Keep(std::move(checked));
}
}
context.Resolved(&Graphics::DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->pipeline);
context.BindComputePipeline(commands, record.objects->pipeline);
if (record.bindings != nullptr) Graphics::Require(record.bindings->allocation.set != VK_NULL_HANDLE, "dispatch overlay has no descriptor set");
if (record.bindings != nullptr) context.Resolved(&Graphics::DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout, 0, 1, &record.bindings->allocation.set, 0, nullptr);
else resources.Bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, record.objects->layout);
@@ -6033,7 +6042,6 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) {
std::snprintf(text, sizeof(text), "Vulkan dispatch: workgroup count %ux%ux%u%s exceeds device limits %ux%ux%u and the shader takes no workgroup offset", record.x, record.y, record.z, counted, limit[0], limit[1], limit[2]);
throw std::runtime_error(text);
}
const auto bindPipeline = context.Resolved(&Graphics::DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline");
const auto dispatchChunk = context.Resolved(&Graphics::DeviceFunctions::cmdDispatch, "vkCmdDispatch");
bool firstChunk = true;
for (std::uint32_t zBase = 0; zBase < record.z; zBase += limit[2]) {
@@ -6041,7 +6049,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) {
for (std::uint32_t xBase = 0; xBase < record.x; xBase += limit[0]) {
if (!firstChunk) {
Graphics::RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
bindPipeline(commands, VK_PIPELINE_BIND_POINT_COMPUTE, splitComputePipeline(context, *record.shader->program, *record.objects, {xBase, yBase, zBase}));
context.BindComputePipeline(commands, splitComputePipeline(context, *record.shader->program, *record.objects, {xBase, yBase, zBase}));
}
firstChunk = false;
dispatchChunk(commands, std::min(limit[0], record.x - xBase), std::min(limit[1], record.y - yBase), std::min(limit[2], record.z - zBase));
@@ -18,6 +18,7 @@
#include <shared_mutex>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace AgcDriver::Graphics {
@@ -31,6 +32,7 @@ class RenderCache;
class DrawQueue;
class GraphicsPipelineCache;
class Recorder;
class CommandState;
class DescriptorCache;
class SamplerCache;
class ShaderResources;
@@ -99,6 +101,43 @@ struct BdaUnalignedAccess : std::runtime_error {
std::uint32_t instruction;
};
void TrackedCommandOutsideCommandState();
class FunctionName {
public:
consteval FunctionName(const char* name) : value(name) {
constexpr std::array<std::string_view, 32> tracked{
"vkCmdBindPipeline", "vkCmdSetViewport", "vkCmdSetViewportWithCount", "vkCmdSetViewportWithCountEXT",
"vkCmdSetScissor", "vkCmdSetScissorWithCount", "vkCmdSetScissorWithCountEXT", "vkCmdSetColorWriteMaskEXT", "vkCmdSetDepthBias",
"vkCmdSetDepthBias2EXT", "vkCmdSetDepthBounds", "vkCmdSetCullMode", "vkCmdSetCullModeEXT",
"vkCmdSetFrontFace", "vkCmdSetFrontFaceEXT", "vkCmdSetDepthTestEnable", "vkCmdSetDepthTestEnableEXT",
"vkCmdSetDepthWriteEnable", "vkCmdSetDepthWriteEnableEXT", "vkCmdSetDepthCompareOp", "vkCmdSetDepthCompareOpEXT",
"vkCmdSetDepthBoundsTestEnable", "vkCmdSetDepthBoundsTestEnableEXT", "vkCmdSetStencilTestEnable", "vkCmdSetStencilTestEnableEXT",
"vkCmdSetStencilOp", "vkCmdSetStencilOpEXT", "vkCmdSetStencilCompareMask", "vkCmdSetStencilWriteMask",
"vkCmdSetStencilReference", "vkCmdBindShadersEXT", "vkCmdExecuteCommands"};
for (const auto entry : tracked) {
if (entry == name) TrackedCommandOutsideCommandState();
}
}
constexpr const char* Value() const { return value; }
private:
const char* value;
};
template<typename TFunction>
class TrackedFunction {
public:
TrackedFunction& operator=(TFunction bound) {
function = bound;
return *this;
}
private:
friend struct Context;
TFunction function = nullptr;
};
// Device entry points resolved once per device (VulkanDevice's State fills it after setup): the
// loader's vkGetDeviceProcAddr is a name lookup under its global mutex per call, paid at every
// record site otherwise. Null members (tests, APS5_NO_PROC_TABLE=1) resolve per call (Resolved).
@@ -107,7 +146,7 @@ struct DeviceFunctions {
PFN_vkCmdCopyBuffer cmdCopyBuffer = nullptr;
PFN_vkCmdUpdateBuffer cmdUpdateBuffer = nullptr;
PFN_vkCmdFillBuffer cmdFillBuffer = nullptr;
PFN_vkCmdBindPipeline cmdBindPipeline = nullptr;
TrackedFunction<PFN_vkCmdBindPipeline> cmdBindPipeline;
PFN_vkCmdBindDescriptorSets cmdBindDescriptorSets = nullptr;
PFN_vkCmdPushConstants cmdPushConstants = nullptr;
PFN_vkCmdDispatch cmdDispatch = nullptr;
@@ -116,22 +155,22 @@ struct DeviceFunctions {
PFN_vkCmdEndRenderPass cmdEndRenderPass = nullptr;
PFN_vkCmdBeginRenderingKHR cmdBeginRendering = nullptr;
PFN_vkCmdEndRenderingKHR cmdEndRendering = nullptr;
PFN_vkCmdSetViewport cmdSetViewport = nullptr;
PFN_vkCmdSetScissor cmdSetScissor = nullptr;
PFN_vkCmdSetColorWriteMaskEXT cmdSetColorWriteMask = nullptr;
PFN_vkCmdSetDepthBounds cmdSetDepthBounds = nullptr;
PFN_vkCmdSetDepthBias cmdSetDepthBias = nullptr;
PFN_vkCmdSetCullModeEXT cmdSetCullMode = nullptr;
PFN_vkCmdSetFrontFaceEXT cmdSetFrontFace = nullptr;
PFN_vkCmdSetDepthTestEnableEXT cmdSetDepthTestEnable = nullptr;
PFN_vkCmdSetDepthWriteEnableEXT cmdSetDepthWriteEnable = nullptr;
PFN_vkCmdSetDepthCompareOpEXT cmdSetDepthCompareOp = nullptr;
PFN_vkCmdSetDepthBoundsTestEnableEXT cmdSetDepthBoundsTestEnable = nullptr;
PFN_vkCmdSetStencilTestEnableEXT cmdSetStencilTestEnable = nullptr;
PFN_vkCmdSetStencilOpEXT cmdSetStencilOp = nullptr;
PFN_vkCmdSetStencilCompareMask cmdSetStencilCompareMask = nullptr;
PFN_vkCmdSetStencilWriteMask cmdSetStencilWriteMask = nullptr;
PFN_vkCmdSetStencilReference cmdSetStencilReference = nullptr;
TrackedFunction<PFN_vkCmdSetViewport> cmdSetViewport;
TrackedFunction<PFN_vkCmdSetScissor> cmdSetScissor;
TrackedFunction<PFN_vkCmdSetColorWriteMaskEXT> cmdSetColorWriteMask;
TrackedFunction<PFN_vkCmdSetDepthBounds> cmdSetDepthBounds;
TrackedFunction<PFN_vkCmdSetDepthBias> cmdSetDepthBias;
TrackedFunction<PFN_vkCmdSetCullModeEXT> cmdSetCullMode;
TrackedFunction<PFN_vkCmdSetFrontFaceEXT> cmdSetFrontFace;
TrackedFunction<PFN_vkCmdSetDepthTestEnableEXT> cmdSetDepthTestEnable;
TrackedFunction<PFN_vkCmdSetDepthWriteEnableEXT> cmdSetDepthWriteEnable;
TrackedFunction<PFN_vkCmdSetDepthCompareOpEXT> cmdSetDepthCompareOp;
TrackedFunction<PFN_vkCmdSetDepthBoundsTestEnableEXT> cmdSetDepthBoundsTestEnable;
TrackedFunction<PFN_vkCmdSetStencilTestEnableEXT> cmdSetStencilTestEnable;
TrackedFunction<PFN_vkCmdSetStencilOpEXT> cmdSetStencilOp;
TrackedFunction<PFN_vkCmdSetStencilCompareMask> cmdSetStencilCompareMask;
TrackedFunction<PFN_vkCmdSetStencilWriteMask> cmdSetStencilWriteMask;
TrackedFunction<PFN_vkCmdSetStencilReference> cmdSetStencilReference;
PFN_vkCmdBindVertexBuffers cmdBindVertexBuffers = nullptr;
PFN_vkCmdBindIndexBuffer cmdBindIndexBuffer = nullptr;
PFN_vkCmdDraw cmdDraw = nullptr;
@@ -304,19 +343,35 @@ struct Context {
VertexBufferFormats* vertexFormats = nullptr;
template<typename TFunction>
TFunction Function(const char* name) const {
Require(deviceProc != nullptr, "missing Vulkan device function resolver");
++DeviceProcLookups();
const auto function = reinterpret_cast<TFunction>(deviceProc(device, name));
if (function == nullptr) throw std::runtime_error(std::string("AGC graphics: missing Vulkan function: ") + name);
return function;
TFunction Function(FunctionName name) const {
return lookup<TFunction>(name.Value());
}
// The table's entry point, or a per-call lookup while the table is absent or lacks it.
template<typename TFunction>
TFunction Resolved(TFunction DeviceFunctions::*member, const char* name) const {
TFunction Resolved(TFunction DeviceFunctions::*member, FunctionName name) const {
if (functions != nullptr && functions->*member != nullptr) return functions->*member;
return Function<TFunction>(name);
return lookup<TFunction>(name.Value());
}
class ComputeBinder {
public:
void operator()(VkCommandBuffer commands, VkPipeline pipeline) const {
bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
}
private:
friend struct Context;
explicit ComputeBinder(PFN_vkCmdBindPipeline function) : bind(function) {}
PFN_vkCmdBindPipeline bind;
};
ComputeBinder ComputeBinding() const {
return ComputeBinder(tracked(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline"));
}
void BindComputePipeline(VkCommandBuffer commands, VkPipeline pipeline) const {
ComputeBinding()(commands, pipeline);
}
std::uint32_t MemoryType(std::uint32_t mask, VkMemoryPropertyFlags flags) const {
@@ -420,6 +475,25 @@ struct Context {
if (refused >= memory.memoryTypeCount || (memory.memoryHeaps[memory.memoryTypes[refused].heapIndex].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) == 0) return std::nullopt;
return HostMemoryType(mask);
}
private:
friend class CommandState;
friend void FillDeviceFunctions(const Context& context, DeviceFunctions& functions);
template<typename TFunction>
TFunction lookup(const char* name) const {
Require(deviceProc != nullptr, "missing Vulkan device function resolver");
++DeviceProcLookups();
const auto function = reinterpret_cast<TFunction>(deviceProc(device, name));
if (function == nullptr) throw std::runtime_error(std::string("AGC graphics: missing Vulkan function: ") + name);
return function;
}
template<typename TFunction>
TFunction tracked(TrackedFunction<TFunction> DeviceFunctions::*member, const char* name) const {
if (functions != nullptr && (functions->*member).function != nullptr) return (functions->*member).function;
return lookup<TFunction>(name);
}
};
inline VkShaderModule CreateShaderModule(const Context& context, const std::uint32_t* code, std::size_t bytes, const char* operation) {
@@ -66,6 +66,7 @@ bool DepthSurfaceAt(const Context& context, std::span<const std::uint32_t> words
std::uint64_t HtileDepthClearAddress(std::span<const std::uint32_t> code, std::span<const std::uint32_t> userData, const std::array<std::uint32_t, 3>& numThreads);
std::size_t HtileDepthClearBytes_nid_no_patch(std::span<const std::uint32_t> code, std::span<const std::uint32_t> userData, const ShaderRecompiler::ShaderComputeStageInfo& compute, std::span<const std::uint32_t> packet, std::uint64_t indirectArguments);
bool NoteHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes, std::size_t nativeBytes = 0u);
void NoteCopyDestination(std::uint64_t address, std::size_t bytes);
void ArmHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes);
void QueueHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes);
void CompleteHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes);
@@ -102,6 +103,14 @@ VkFormat HostDepthFormat(const Context& context, VkFormat format);
float HostDepthBiasConstant(const Context& context, VkFormat format, float constant);
std::shared_ptr<StorageTexture> DepthSurfaceStorage(const Context& context, std::span<const std::uint32_t> words, const GuestTextureResource& resource, std::uint32_t mip);
bool DepthSurfaceStoreBack(const Context& context, const StorageTexture& storage);
void RunDepthExpandPass(const Context& context, const DepthExpandPass& pass);
void StoreDepthExpandWrites(const Context& context);
struct DepthExpandStatistics {
std::uint64_t expands = 0;
std::uint64_t skipped = 0;
std::uint64_t stored = 0;
};
DepthExpandStatistics DepthExpandCounts();
std::array<std::uint32_t, 8> DepthCopySourceWords(const DepthTarget& target);
class DepthCopySourceScope {
public:
@@ -60,16 +60,19 @@ struct DrawInputCopy {
std::shared_ptr<Buffer> buffer;
bool reused = false;
std::uint32_t derived = 0;
std::uint32_t lowest = 0;
std::size_t from = 0;
std::uint64_t generation = 0;
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);
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 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);
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);
struct InPlaceIndices {
std::optional<std::uint32_t> highest;
std::uint32_t lowest = 0;
bool reused = false;
};
InPlaceIndices InPlaceIndexRange(Recorder& recorder, std::uint64_t address, std::size_t bytes, std::uint32_t indexSize, bool skipRestart);
@@ -134,7 +137,7 @@ bool DrawRecipes();
// draw index, the vertex ranges, the device features, APS5_NO_GPU_INDIRECT_DRAW) or under the device
// lock in Draw (the memory state of the records). `readMs` is the CPU read's time (its sync);
// `rewritten` counts a GPU-side draw whose records were copied and patched with a constant.
enum class IndirectDrawPath : std::uint8_t { Gpu, NotFolded, FetchUnknown, NonVertexPath, IndxOffset, DrawIndex, VertexRange, FeatureGap, PendingImage, PendingLabelOrCopy, NotImported, Disabled, IndexRange, IndexLimitUnknown, Count };
enum class IndirectDrawPath : std::uint8_t { Gpu, NotFolded, FetchUnknown, NonVertexPath, IndxOffset, DrawIndex, VertexRange, FeatureGap, PendingImage, PendingLabelOrCopy, NotImported, Disabled, IndexRange, IndexLimitUnknown, Settled, Count };
void CountIndirectDraw(IndirectDrawPath path, double readMs, bool rewritten = false);
std::array<std::uint64_t, static_cast<std::size_t>(IndirectDrawPath::Count)> IndirectDrawCounts();
void CountEmptyIndirectDraw(double readMs);
@@ -176,6 +179,12 @@ void RunColorMetadataPass(const Context& context, const ColorMetadataPass& pass)
std::vector<std::pair<std::uint64_t, std::uint64_t>> PipelinedColorMetadataPassWrites(const ColorMetadataPass& pass);
bool DrawPipelineEnabled();
bool CommitTrims();
struct FragmentOutputLookups {
std::uint64_t last = 0;
std::uint64_t memo = 0;
std::uint64_t validated = 0;
};
FragmentOutputLookups ThreadFragmentOutputLookups();
enum class AddressDrawReuse : std::uint8_t { Reused, Built, NotReadOnly, NotSpaceOnly, SnapshotOutside, PartialOverlap, SnapshotChanged, MovedBuffer, PatchedData, SpaceChanged, InUse, Revalidation, Count };
using AddressDrawReuseCounts = std::array<std::uint64_t, static_cast<std::size_t>(AddressDrawReuse::Count)>;
AddressDrawReuseCounts AddressDrawReuseCounters();
@@ -91,6 +91,7 @@ ImportProbe ProbeImportWriteProtection(const Context& context);
ImportProbe ProbeDmaBufImportWriteProtection(const Context& context);
ImportWatch PrepareImportWatch(const Context& context);
void SetImportWatch(const Context& context, ImportWatch watch);
bool DmaBufImportSelected(const Context& context);
enum class ImportRequester : std::uint8_t { Map, Build, Access, Join, Segment, ColorTarget };
inline constexpr std::size_t ImportRequesterCount = 6;
@@ -122,6 +123,7 @@ void ReportHostImports();
// (alignment and budget permitting), or null. Bytes at `address` are at `HostImportOffset(*import,
// address)` in the import's buffer.
const HostImport* HostImportFor(const Context& context, std::uint64_t address, std::size_t bytes, ImportRequester requester = ImportRequester::Access);
bool HostImportUsesDmaBuf(const Context& context, std::uint64_t address, std::size_t bytes);
const HostImport* ExistingHostImportFor(const Context& context, std::uint64_t address, std::size_t bytes);
void RequireGpuLockBeforeImports(const char* where);
bool ImportsHeldByThisThread();
@@ -161,6 +163,7 @@ bool ImportMappedRanges(const Context& context, const GuestAllocations::Mapped&
// with the registry or making one (HostImportFor may take a registry lease): a hint for choices
// made outside the device lock (a sampled texture's path, a dispatch's pre-sync); the path taken
// re-checks with HostImportFor when it binds the import.
bool HostImportOverlaps(const Context& context, std::uint64_t address, std::size_t bytes);
bool HostImportCovers(const Context& context, std::uint64_t address, std::size_t bytes);
bool ComparedHostImportCovers(const Context& context, std::uint64_t address, std::size_t bytes);
std::uint64_t HostImportSetGeneration();
@@ -307,6 +310,7 @@ struct RetainedAddressSpace {
RetainedAddressSpace* next = nullptr;
};
void ClearRetainedSpaces(VkDevice device);
void ClearUploadCopies(VkDevice device);
std::size_t RetainedSpaceCount();
struct AddressCopy {
@@ -613,6 +617,7 @@ private:
bool regionsSorted = false;
bool regionsOverlap = false;
std::vector<std::pair<std::uint64_t, std::uint64_t>> writes;
std::vector<std::pair<std::uint64_t, std::uint64_t>> reads;
std::vector<std::pair<std::uint64_t, std::uint64_t>> readsOverBase;
std::vector<std::pair<std::uint64_t, std::uint64_t>> servedInsideBase;
std::vector<std::pair<std::uint64_t, std::vector<std::byte>>> heapReferences;
@@ -0,0 +1,43 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_KEPTUNITS_HPP
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_KEPTUNITS_HPP
#include <algorithm>
#include <cstdint>
#include <map>
#include <span>
namespace AgcDriver::Graphics {
struct UnitLayout {
std::uint64_t base = 0;
std::uint64_t unitBytes = 0;
std::uint64_t totalBytes = 0;
std::uint64_t Begin(std::uint32_t unit) const {
return base + static_cast<std::uint64_t>(unit) * unitBytes;
}
std::uint64_t End(std::uint32_t unit) const {
return Begin(unit) + std::min<std::uint64_t>(unitBytes, totalBytes - static_cast<std::uint64_t>(unit) * unitBytes);
}
};
inline void StampUnkeptUnits(const std::map<std::uint64_t, std::uint64_t>& kept, const UnitLayout& layout, std::span<const std::uint64_t> generations, std::span<std::uint64_t> stamps, std::uint32_t first, std::uint32_t count, std::uint64_t stamp) {
if (count == 0) return;
auto at = kept.lower_bound(layout.Begin(first));
if (at == kept.end() || at->first >= layout.End(first + count - 1)) {
std::fill_n(stamps.begin() + first, count, stamp);
return;
}
for (std::uint32_t unit = first; unit < first + count; ++unit) {
if (at != kept.end() && at->first < layout.Begin(unit)) at = kept.lower_bound(layout.Begin(unit));
const auto end = layout.End(unit);
bool held = false;
for (; at != kept.end() && at->first < end; ++at) held = held || at->second == generations[unit];
if (!held) stamps[unit] = stamp;
}
}
}
#endif
@@ -123,6 +123,7 @@ bool HoldsMultisampleTargetsLock();
void RequireNoMultisampleTarget(std::uint64_t address, std::size_t bytes, const char* access);
void RequireNoMultisampleColorTarget(std::uint64_t address, std::size_t bytes, const char* access);
void RetireMultisampleColorTarget(const std::shared_ptr<std::atomic<bool>>& active);
void RetireMultisampleColorTargetsOnFmaskWrite(std::uint64_t address, std::size_t bytes);
std::vector<std::pair<std::uint64_t, std::uint64_t>> HostOnlySampleRanges(std::uint64_t address, std::size_t bytes);
}
@@ -8,6 +8,7 @@
namespace AgcDriver::Graphics {
struct VertexInputLayout;
class CommandState;
void LogPipelineStatistics_nid_no_patch(const Context& context, VkPipeline pipeline, std::span<const CompiledShader> shaders = {});
@@ -49,15 +50,15 @@ public:
VkPipelineLayout Layout() const;
std::shared_ptr<Framebuffer> AcquireFramebuffer(std::span<const VkImageView> targets, std::span<const std::shared_ptr<void>> owners, VkExtent2D extent, std::uint32_t layers = 1);
// Begins the render pass on the framebuffer, binds the pipeline and sets its dynamic state.
void Begin(VkCommandBuffer commands, const Framebuffer& framebuffer, VkExtent2D extent, const State& state, const State* masked = nullptr) const;
void Begin(CommandState& recording, const Framebuffer& framebuffer, VkExtent2D extent, const State& state, const State* masked = nullptr) const;
// The same inside a render pass another pipeline of the same attachments began (compatible by
// construction: the attachment formats alone decide).
void Continue(VkCommandBuffer commands, const State& state, const State* masked = nullptr) const;
void Continue(CommandState& recording, const State& state, const State* masked = nullptr) const;
bool SplitsFaces() const { return backFaces != VK_NULL_HANDLE; }
bool Optimized() const { return optimized != nullptr && optimized->handle.load() != VK_NULL_HANDLE; }
void ContinueBackFaces(VkCommandBuffer commands, const State& state, const State* masked = nullptr) const;
void ContinueBackFaces(CommandState& recording, const State& state, const State* masked = nullptr) const;
bool SplitsSecondChannel() const { return secondChannel != VK_NULL_HANDLE; }
void ContinueSecondChannel(VkCommandBuffer commands, const State& state, const State* masked = nullptr) const;
void ContinueSecondChannel(CommandState& recording, const State& state, const State* masked = nullptr) const;
const SampleOrder& HostSampleOrder() const { return sampleOrder; }
bool ReordersSamples() const { return Graphics::ReordersSamples(sampleOrder); }
bool SampleLocationsEnabled() const { return sampleLocationsEnabled; }
@@ -77,8 +78,8 @@ private:
std::shared_ptr<Framebuffer> framebuffer;
};
void release() noexcept;
void setLibraryState(VkCommandBuffer commands, const State& state) const;
void setColorWriteMasks(VkCommandBuffer commands, const State& state, const State* masked, bool secondChannel) const;
void setLibraryState(CommandState& recording, const State& state) const;
void setColorWriteMasks(CommandState& recording, const State& state, const State* masked, bool secondChannel) const;
Context context;
std::vector<VkShaderModule> _modules;
VkPipelineLayout layout = VK_NULL_HANDLE;
@@ -93,6 +94,7 @@ private:
bool depthBounds = false;
bool depthBias = false;
bool libraries = false;
std::uint32_t dynamicSlots = 0;
std::shared_ptr<OptimizedPipeline> optimized;
bool dynamicRendering = false;
VkFormat depthFormat = VK_FORMAT_UNDEFINED;
@@ -139,6 +141,7 @@ struct DescribedSetLayouts {
PipelineSetLayouts View() const { return {layouts.main, layouts.fragment, layouts.split, mainKey, fragmentKey}; }
};
DescribedSetLayouts DescribeSetLayouts(const Context& context, std::span<const CompiledShader> shaders);
ShaderRecompiler::PipelineIdentity DescribedPipelineIdentity(const ShaderRecompiler::RecompileResult& shader);
bool SplitsSets(const Context& context, std::span<const CompiledShader> shaders);
// Destroys the cached pipelines of a device; to be called before the device goes away. Without it,
// entries of a gone device are recognised by their buffer pool (made and reset with the device, so
@@ -31,6 +31,104 @@ namespace AgcDriver::Graphics {
class Buffer;
class DeviceBuffer;
class CommandState {
public:
enum Slot : std::uint32_t {
Viewport,
Scissor,
DepthBias,
DepthBounds,
CullMode,
FrontFace,
DepthTest,
DepthWrite,
DepthCompare,
DepthBoundsTest,
StencilTest,
StencilOpFront,
StencilOpBack,
CompareMaskFront,
CompareMaskBack,
WriteMaskFront,
WriteMaskBack,
ReferenceFront,
ReferenceBack,
ColorWriteMask,
SlotCount
};
static constexpr std::uint32_t Mask(Slot slot) { return 1u << slot; }
static std::uint32_t DynamicSlots(std::span<const VkDynamicState> states);
CommandState() = default;
CommandState(const CommandState&) = delete;
CommandState& operator=(const CommandState&) = delete;
void Begin(VkCommandBuffer commands, bool suppress = true);
void Invalidate() noexcept;
VkCommandBuffer Commands() const { return commands; }
bool Known(Slot slot) const { return (valid & Mask(slot)) != 0; }
VkPipeline BoundPipeline() const { return pipelineKnown ? pipeline : VK_NULL_HANDLE; }
void BindPipeline(const Context& context, VkPipeline pipeline, std::uint32_t dynamicSlots);
void SetViewport(const Context& context, const VkViewport& viewport);
void SetScissor(const Context& context, const VkRect2D& scissor);
void SetDepthBias(const Context& context, float constant, float clamp, float slope);
void SetDepthBounds(const Context& context, float minimum, float maximum);
void SetCullMode(const Context& context, VkCullModeFlags mode);
void SetFrontFace(const Context& context, VkFrontFace face);
void SetDepthTestEnable(const Context& context, VkBool32 enable);
void SetDepthWriteEnable(const Context& context, VkBool32 enable);
void SetDepthCompareOp(const Context& context, VkCompareOp compare);
void SetDepthBoundsTestEnable(const Context& context, VkBool32 enable);
void SetStencilTestEnable(const Context& context, VkBool32 enable);
void SetStencilOp(const Context& context, VkStencilFaceFlags faces, VkStencilOp failOp, VkStencilOp passOp, VkStencilOp depthFailOp, VkCompareOp compareOp);
void SetStencilCompareMask(const Context& context, VkStencilFaceFlags faces, std::uint32_t mask);
void SetStencilWriteMask(const Context& context, VkStencilFaceFlags faces, std::uint32_t mask);
void SetStencilReference(const Context& context, VkStencilFaceFlags faces, std::uint32_t reference);
void SetColorWriteMasks(const Context& context, std::span<const VkColorComponentFlags> masks);
private:
struct StencilOps {
VkStencilOp failOp;
VkStencilOp passOp;
VkStencilOp depthFailOp;
VkCompareOp compareOp;
bool operator==(const StencilOps&) const = default;
};
struct ColorWriteMasks {
std::uint32_t count;
std::array<VkColorComponentFlags, 8> masks;
};
void wrote(std::uint32_t slots) { valid |= slots & trackable; overwritten |= slots; }
template<typename TValue, typename TEqual, typename TEmit>
void apply(Slot slot, TValue CommandState::*field, const TValue& value, TEqual equal, TEmit emit);
template<typename TValue, typename TEmit>
void applyFaces(Slot first, VkStencilFaceFlags faces, std::array<TValue, 2> CommandState::*field, const TValue& value, TEmit emit);
VkCommandBuffer commands = VK_NULL_HANDLE;
std::uint32_t trackable = 0;
std::uint32_t valid = 0;
std::uint32_t overwritten = 0;
std::uint32_t dynamicSlots = 0;
VkPipeline pipeline = VK_NULL_HANDLE;
bool pipelineKnown = false;
VkViewport viewport{};
VkRect2D scissor{};
std::array<float, 3> depthBias{};
std::array<float, 2> depthBounds{};
VkCullModeFlags cullMode = 0;
VkFrontFace frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
VkBool32 depthTest = 0;
VkBool32 depthWrite = 0;
VkCompareOp depthCompare = VK_COMPARE_OP_NEVER;
VkBool32 depthBoundsTest = 0;
VkBool32 stencilTest = 0;
std::array<StencilOps, 2> stencilOps{};
std::array<std::uint32_t, 2> compareMasks{};
std::array<std::uint32_t, 2> writeMasks{};
std::array<std::uint32_t, 2> references{};
ColorWriteMasks colorWriteMasks{};
};
// Accumulates GPU work across guest commands so the CPU does not wait for each one. Dispatches and the
// copies that feed them record into one open batch; Submit sends it to the queue without waiting and
// Sync waits for every batch, then runs its completion actions (write-backs) in order. Objects handed
@@ -90,7 +188,7 @@ public:
PassBreak reason = PassBreak::Continued;
};
DrawPassStart StartDrawPass(std::uint64_t key, bool forced, bool fenced, const PassAccess& access);
void LeaveRenderPassOpen(std::uint64_t key, std::uint32_t timing, bool fenced, const PassAccess& access, std::function<void(VkCommandBuffer)> afterPass = {});
void LeaveRenderPassOpen(std::uint64_t key, std::uint32_t timing, bool fenced, const PassAccess& access, std::function<void(CommandState&)> afterPass = {});
void SealPassWriteOnly();
// DCC "uncompressed" key stores (DccMetadata.cpp StoreUncompressedOnGpu): queued on the open
// batch and recorded as one run (one barrier pair for every queued fill) at Submit, before a
@@ -131,7 +229,7 @@ public:
static constexpr std::size_t DrawInputEntries = 16384;
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::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);
struct OwnedDrawInputProof {
std::vector<std::uint64_t> words;
std::uint64_t since = 0;
@@ -141,10 +239,10 @@ public:
};
std::size_t OwnedDrawInputEntries() const { return ownedDrawInputs; }
OwnedDrawInputProof ArmOwnedDrawInput(std::uint64_t address, std::size_t bytes) const;
std::shared_ptr<Buffer> ReusableOwnedDrawInput(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived);
void KeepOwnedDrawInput(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof, std::shared_ptr<Buffer> buffer, SnapshotUse use, std::uint32_t derived);
std::shared_ptr<Buffer> ReusableOwnedDrawInput(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived, std::size_t from = 0, std::uint32_t* lowest = nullptr);
void KeepOwnedDrawInput(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof, std::shared_ptr<Buffer> buffer, SnapshotUse use, std::uint32_t derived, std::size_t from = 0, std::uint32_t lowest = 0);
static constexpr std::size_t ContainingSnapshotProbes = 16;
void KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::uint64_t generation, std::uint64_t registryGeneration, std::shared_ptr<Buffer> buffer, SnapshotUse use = SnapshotUse::Storage, std::uint32_t derived = 0, bool ownedInsertion = false);
void KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::uint64_t generation, std::uint64_t registryGeneration, std::shared_ptr<Buffer> buffer, SnapshotUse use = SnapshotUse::Storage, std::uint32_t derived = 0, std::size_t from = 0, std::uint32_t lowest = 0, bool ownedInsertion = false);
static constexpr std::size_t DrawUploadChunk = std::size_t{1} << 20u;
struct UploadSlice {
std::shared_ptr<Buffer> buffer;
@@ -154,8 +252,8 @@ public:
UploadSlice DrawUpload(std::size_t bytes);
static constexpr std::size_t IndexRangeEntries = 16384;
static constexpr std::size_t KeptIndexRangeIndices = 4096;
bool KnownHighestIndex(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::optional<std::uint32_t>& highest);
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);
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 NotePendingWrite(std::uint64_t address, std::size_t bytes);
void NotePendingFill(std::uint64_t address, std::size_t bytes, std::uint8_t value);
@@ -269,7 +367,8 @@ public:
bool QueuesSampleDumps() const;
void PrepareSampleSlot();
void EndPassSamples();
void RecordUncounted(const std::function<void(VkCommandBuffer)>& record);
void RecordUncounted(const std::function<void(CommandState&)>& record);
CommandState& GraphicsState();
struct SampleDumpStatistics {
std::uint64_t queued;
std::uint64_t queuedInPass;
@@ -622,6 +721,7 @@ private:
};
struct Batch {
VkCommandBuffer commands = VK_NULL_HANDLE;
CommandState graphicsState;
VkFence fence = VK_NULL_HANDLE;
std::vector<std::shared_ptr<void>> kept;
std::size_t keptBytes = 0;
@@ -745,7 +845,7 @@ private:
bool fenced = false;
std::uint64_t key = 0;
std::uint32_t timing = NoTiming;
std::function<void(VkCommandBuffer)> afterPass;
std::function<void(CommandState&)> afterPass;
PassBreak closedBy = PassBreak::NewBatch;
} renderPass;
PassHazards passHazards;
@@ -838,11 +938,10 @@ private:
PFN_vkCmdEndQuery cmdEndQuery = nullptr;
PFN_vkCmdResetQueryPool cmdResetQueryPool = nullptr;
PFN_vkCmdCopyQueryPoolResults cmdCopyQueryPoolResults = nullptr;
PFN_vkCmdBindPipeline cmdBindPipeline = nullptr;
PFN_vkCmdPushConstants cmdPushConstants = nullptr;
PFN_vkCmdDispatch cmdDispatch = nullptr;
template<typename TFunction>
TFunction function(TFunction resolved, const char* name) const {
TFunction function(TFunction resolved, FunctionName name) const {
return resolved != nullptr ? resolved : context.Function<TFunction>(name);
}
VkResult fenceStatus(VkFence fence) const { return function(getFenceStatus, "vkGetFenceStatus")(context.device, fence); }
@@ -957,6 +1056,8 @@ private:
std::list<DrawSnapshotKey>::iterator recent;
std::shared_ptr<Buffer> buffer;
std::uint32_t derived;
std::size_t from;
std::uint32_t lowest;
OwnedDrawInputProof owned;
};
struct DrawSnapshotPool {
@@ -981,6 +1082,7 @@ private:
std::uint64_t registryGeneration;
std::list<DrawSnapshotKey>::iterator recent;
std::optional<std::uint32_t> highest;
std::uint32_t lowest;
};
std::map<DrawSnapshotKey, IndexRange> indexRanges;
std::list<DrawSnapshotKey> indexRangeRecency;
@@ -11,6 +11,8 @@
namespace AgcDriver::Graphics {
class CommandState;
struct HostSampleLocations {
VkExtent2D grid{1, 1};
SampleOrder order{};
@@ -64,7 +66,7 @@ VkFormat SampleOrderStorageFormat(const Context& context, VkFormat format, std::
std::string SampleOrderRefusal(const Context& context, const State& state);
std::vector<SampleOrderStep> PlanSampleOrder(const Context& context, const State& state, const SampleOrder& order, VkAttachmentLoadOp load = VK_ATTACHMENT_LOAD_OP_LOAD, VkAttachmentStoreOp store = VK_ATTACHMENT_STORE_OP_STORE);
SampleOrderPass SampleOrderPassFor(const Context& context, const State& state, const SampleOrder& order);
void RecordSampleOrder(const Context& context, VkCommandBuffer commands, const SampleOrderPass& pass, std::span<const SampleOrderTarget> targets, bool toHost, std::vector<std::shared_ptr<void>>& kept);
void RecordSampleOrder(const Context& context, CommandState& recording, const SampleOrderPass& pass, std::span<const SampleOrderTarget> targets, bool toHost, std::vector<std::shared_ptr<void>>& kept);
void RecordDepthSampleLocations(const Context& context, VkCommandBuffer commands, const DepthSampleLocations& depth);
std::array<std::span<const std::uint32_t>, 9> SampleOrderShaderModules();
void ClearSampleOrders(VkDevice device);
@@ -6,6 +6,8 @@
#include "Recompiler.hpp"
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <span>
namespace AgcDriver::Graphics {
@@ -85,8 +87,9 @@ inline VkShaderStageFlags PushConstantStages(std::span<const CompiledShader> sha
}
inline std::array<std::byte, PipelinePushConstantBytes> AssemblePushConstants(std::span<const CompiledShader> shaders) {
static_assert(PipelinePushConstantBytes % 4 == 0 && PipelinePushConstantBytes / 4 <= 64 && PipelinePushSlotBytes / 4 < 64, "the occupied mask holds one bit per DWORD of the block");
std::array<std::byte, PipelinePushConstantBytes> result{};
std::array<bool, PipelinePushConstantBytes> occupied{};
std::uint64_t occupied = 0;
for (const auto& shader : shaders) {
Require(shader.program != nullptr, "missing compiled shader");
const auto& bytes = shader.program->pushConstants;
@@ -94,12 +97,10 @@ inline std::array<std::byte, PipelinePushConstantBytes> AssemblePushConstants(st
Require(bytes.size() % 4 == 0 && shader.pushConstantOffset % 4 == 0, "shader push constant range is not DWORD aligned");
Require(shader.pushConstantOffset < PipelinePushConstantBytes && bytes.size() <= PipelinePushConstantBytes - shader.pushConstantOffset, "shader push constant range lies outside the pipeline push constant block");
Require(bytes.size() <= PipelinePushSlotBytes - shader.pushConstantOffset % PipelinePushSlotBytes, "shader push constant range crosses a push constant slot");
for (std::size_t i = 0; i < bytes.size(); ++i) {
const auto position = shader.pushConstantOffset + i;
Require(!occupied[position], "shader push constant ranges of different stages overlap");
occupied[position] = true;
result[position] = bytes[i];
}
const auto range = ((std::uint64_t{1} << (bytes.size() / 4)) - 1) << (shader.pushConstantOffset / 4);
Require((occupied & range) == 0, "shader push constant ranges of different stages overlap");
occupied |= range;
std::memcpy(result.data() + shader.pushConstantOffset, bytes.data(), bytes.size());
}
return result;
}
@@ -266,6 +266,12 @@ struct ColorMetadataPass {
std::optional<ColorTarget> source;
};
std::optional<ColorMetadataPass> DecodeColorMetadataPass(const QueueState& queue);
struct DepthExpandPass {
DepthTarget source;
std::uint64_t destination;
std::uint64_t stencilDestination = 0;
};
std::optional<DepthExpandPass> DecodeDepthExpandPass(const QueueState& queue);
struct DepthCopyPass {
DepthTarget source;
std::uint32_t sample;
@@ -130,6 +130,14 @@ public:
PerUseCopy CopyKind() const { return perUseCopy; }
bool RefreshedPerUse() const { return perUseCopy == PerUseCopy::RemadePerUse; }
void MarkRefreshedPerUse() { perUseCopy = PerUseCopy::RemadePerUse; }
void SetReuseLookup(std::function<std::shared_ptr<Texture>()> lookup) { reuseLookup = std::move(lookup); }
bool HasReuseLookup() const { return static_cast<bool>(reuseLookup); }
bool ReuseLookupHolds() const;
struct ReuseLookupCounts {
std::uint64_t held;
std::uint64_t changed;
};
static ReuseLookupCounts TakeReuseLookupCounts();
bool Released() const { return released.load(std::memory_order_acquire); }
void MarkReleased() { released.store(true, std::memory_order_release); }
@@ -167,6 +175,7 @@ private:
std::shared_ptr<StorageTexture> storageSource;
std::unique_ptr<CommandBatch> upload;
PerUseCopy perUseCopy = PerUseCopy::None;
std::function<std::shared_ptr<Texture>()> reuseLookup;
std::atomic<bool> released{false};
bool copiedOnce = false;
bool srgbExpand = false;
@@ -486,6 +495,7 @@ public:
static const char* CopyRefusal(const Context& context, const StorageTexture* destination, const StorageTexture& source, std::uint64_t address);
VkImage Image() const { return image; }
const GuestTextureResource& Descriptor() const { return descriptor; }
std::size_t GuestCopyCapacity() const { return original.capacity(); }
std::uint32_t ImageLayers() const { return geometry.imageLayers; }
std::uint32_t ImageDepth() const { return geometry.imageDepth; }
VkFormat ImageFormat() const { return imageFormat; }
@@ -527,6 +537,7 @@ public:
std::uint64_t BudgetBytes() const;
std::size_t OriginalSnapshotBytes() const { return original.capacity(); }
VkDeviceSize AllocationBytes() const { return memoryBytes; }
bool AnyLayerPending() const;
private:
std::atomic<std::uint64_t> provedEpoch{0};
@@ -572,7 +583,7 @@ private:
void storeTrappedOverlaps(const char* reason);
bool unchangedSinceBaseline(std::uint64_t from, std::uint64_t to) const;
bool cpuLeftUnchanged(std::uint32_t layer, std::uint64_t from, std::uint64_t to, bool edge) const;
void saveBeforeUnwatch();
void saveBeforeUnwatch(std::uint64_t address, std::size_t bytes);
void forgetKeptAtUnwatch(std::uint32_t unit);
bool keptAtUnwatchHolds(std::uint64_t from, std::uint32_t unit) const;
bool keptForCpu(std::uint32_t unit) const;
@@ -588,6 +599,7 @@ private:
void applyStoredSave(std::uint64_t ticket, const std::vector<std::uint32_t>& units);
void cancelStoredSave(std::uint32_t unit);
void cancelStoredSaves();
void releaseUnheldOriginal();
// Lets the batches holding the saves of the units `layers` selects (every unit for none) complete.
void awaitStoredSave(const std::vector<bool>* layers);
bool guestBytesSettled() const;
@@ -346,6 +346,18 @@ struct VertexCopyPlan {
std::vector<std::uint32_t> alignments;
};
inline std::vector<std::size_t> VertexCopyStarts(const VertexCopyPlan& plan, std::span<const VertexFetch> fetches, std::uint32_t minIndex, std::uint32_t firstInstance) {
Require(plan.copyOf.size() == fetches.size(), "vertex copy plan does not match its fetches");
std::vector<std::size_t> starts(plan.copies.size(), 0);
for (std::size_t i = 0; i < fetches.size(); ++i) {
const auto& fetch = fetches[i];
Require(fetch.fetchIndex <= 1, "unsupported vertex fetch index");
starts[plan.copyOf[i]] = static_cast<std::size_t>(static_cast<std::uint64_t>(fetch.stride) * (fetch.fetchIndex == 0 ? minIndex : firstInstance));
}
for (std::size_t range = 0; range < starts.size(); ++range) Require(starts[range] < plan.copies[range].second - plan.copies[range].first, "vertex copy starts past its range");
return starts;
}
inline VertexCopyPlan PlanVertexCopies(std::span<const VertexFetch> fetches) {
VertexCopyPlan plan;
plan.copyOf.assign(fetches.size(), 0);
@@ -389,10 +401,15 @@ inline std::optional<std::uint32_t> ZeroFetchVertex(std::span<const ShaderRecomp
return zeroFrom;
}
inline std::optional<std::uint32_t> ClampDrawIndices(std::span<std::byte> indices, std::uint32_t indexSize, bool skipRestart, std::uint32_t limit) {
struct DrawIndexBounds {
std::uint32_t lowest;
std::uint32_t highest;
};
inline std::optional<DrawIndexBounds> ClampDrawIndices(std::span<std::byte> indices, std::uint32_t indexSize, bool skipRestart, std::uint32_t limit) {
Require(indexSize == 2 || indexSize == 4, "unsupported index size");
const auto restartIndex = indexSize == 2 ? 0xffffu : 0xffffffffu;
std::optional<std::uint32_t> highest;
std::optional<DrawIndexBounds> bounds;
for (std::size_t offset = 0; offset + indexSize <= indices.size(); offset += indexSize) {
std::uint32_t index = 0;
if (indexSize == 2) {
@@ -412,41 +429,44 @@ inline std::optional<std::uint32_t> ClampDrawIndices(std::span<std::byte> indice
std::memcpy(indices.data() + offset, &index, sizeof(index));
}
}
highest = std::max(highest.value_or(0u), index);
bounds = bounds ? DrawIndexBounds{std::min(bounds->lowest, index), std::max(bounds->highest, index)} : DrawIndexBounds{index, index};
}
return highest;
return bounds;
}
template <typename TIndex>
std::optional<std::uint32_t> HighestDrawIndexOf(std::span<const std::byte> indices, bool skipRestart) {
std::optional<DrawIndexBounds> DrawIndexBoundsOf(std::span<const std::byte> indices, bool skipRestart) {
constexpr auto restartIndex = std::numeric_limits<TIndex>::max();
const auto count = indices.size() / sizeof(TIndex);
const auto* data = indices.data();
TIndex lowest = restartIndex;
TIndex highest = 0;
if (!skipRestart) {
for (std::size_t i = 0; i < count; ++i) {
TIndex index;
std::memcpy(&index, data + i * sizeof(TIndex), sizeof(TIndex));
lowest = std::min(lowest, index);
highest = std::max(highest, index);
}
if (count == 0) return std::nullopt;
return highest;
return DrawIndexBounds{lowest, highest};
}
TIndex kept = 0;
for (std::size_t i = 0; i < count; ++i) {
TIndex index;
std::memcpy(&index, data + i * sizeof(TIndex), sizeof(TIndex));
const TIndex valid = index == restartIndex ? TIndex{0} : TIndex(~TIndex{0});
lowest = std::min(lowest, index);
highest = std::max(highest, static_cast<TIndex>(index & valid));
kept |= valid;
}
if (kept == 0) return std::nullopt;
return highest;
return DrawIndexBounds{lowest, highest};
}
inline std::optional<std::uint32_t> HighestDrawIndex(std::span<const std::byte> indices, std::uint32_t indexSize, bool skipRestart) {
inline std::optional<DrawIndexBounds> DrawIndexRange(std::span<const std::byte> indices, std::uint32_t indexSize, bool skipRestart) {
Require(indexSize == 2 || indexSize == 4, "unsupported index size");
return indexSize == 2 ? HighestDrawIndexOf<std::uint16_t>(indices, skipRestart) : HighestDrawIndexOf<std::uint32_t>(indices, skipRestart);
return indexSize == 2 ? DrawIndexBoundsOf<std::uint16_t>(indices, skipRestart) : DrawIndexBoundsOf<std::uint32_t>(indices, skipRestart);
}
inline std::uint32_t CompactListRestart(std::span<std::byte> indices, std::uint32_t indexSize, std::uint32_t primitiveSize) {
@@ -19,6 +19,8 @@
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp"
#include "prx/libSceAgcDriver/Execution/include/Mutex.hpp"
#include "prx/libSceAgcDriver/Graphics/shaders/DepthToStorage_spv.h"
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
@@ -41,6 +43,7 @@
#include <span>
#include <stdexcept>
#include <tuple>
#include <utility>
#include <vector>
namespace AgcDriver::Graphics {
@@ -147,7 +150,7 @@ public:
const VkDescriptorImageInfo depthInfo{VK_NULL_HANDLE, depthPlane, VK_IMAGE_LAYOUT_GENERAL};
const VkDescriptorImageInfo texelInfo{VK_NULL_HANDLE, texels, VK_IMAGE_LAYOUT_GENERAL};
const std::array<VkWriteDescriptorSet, 2> writes{imageWrite(0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, depthInfo), imageWrite(1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, texelInfo)};
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
context.BindComputePipeline(commands, pipeline);
pushSet(commands, VK_PIPELINE_BIND_POINT_COMPUTE, layout, 0, static_cast<std::uint32_t>(writes.size()), writes.data());
const auto pushConstants = context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants");
const auto dispatch = context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch");
@@ -1281,6 +1284,16 @@ public:
return false;
}
void CopyDepthTo(const std::shared_ptr<StorageTexture>& storage) {
ApplyFastClear();
copyPlane(depthPlane, storage, false, true);
}
void CopyStencilTo(const std::shared_ptr<StorageTexture>& storage) {
ApplyFastClear();
copyPlane(stencilPlane, storage, true, true);
}
bool StoreBackCovering(const StorageTexture& candidate) {
for (const bool stencil : {false, true}) {
if (!CoversPlane(candidate, stencil)) continue;
@@ -2123,6 +2136,11 @@ struct DepthPlaneSlice {
std::uint64_t written = 0;
};
bool DepthPlaneReuse() {
static const bool enabled = std::getenv("APS5_NO_DEPTH_PLANE_REUSE") == nullptr;
return enabled;
}
class DepthPlaneCopy {
public:
DepthPlaneCopy(const Context& context, VkExtent2D extent, VkFormat format, std::uint32_t layers) : context(context), extent(extent), format(format), layers(layers), guestLayers(layers), surfaceLayers(layers) {
@@ -2203,7 +2221,7 @@ public:
auto& texture = textures[key];
if (texture == nullptr) {
texture = std::make_shared<Texture>(context, image, format, aspect(), components, viewType, baseLayer, owned, 0, viewLayers);
texture->MarkRefreshedPerUse();
if (!DepthPlaneReuse()) texture->MarkRefreshedPerUse();
}
return texture;
}
@@ -2569,15 +2587,42 @@ std::map<std::uint64_t, std::size_t>& clearedHtiles() {
return *cleared;
}
bool takeClearedHtile(const DepthTarget& target) {
if (target.htileAddress == 0) return false;
std::map<std::uint64_t, std::size_t>::iterator findClearedHtile(const DepthTarget& target) {
auto& cleared = clearedHtiles();
const auto found = std::find_if(cleared.begin(), cleared.end(), [&](const auto& entry) { return HtileFillCovers(target.htileAddress, target.extent, entry.first, entry.second); });
if (found == cleared.end()) return false;
cleared.erase(found);
if (target.htileAddress == 0) return cleared.end();
return std::find_if(cleared.begin(), cleared.end(), [&](const auto& entry) { return HtileFillCovers(target.htileAddress, target.extent, entry.first, entry.second); });
}
bool takeClearedHtile(const DepthTarget& target) {
const auto found = findClearedHtile(target);
if (found == clearedHtiles().end()) return false;
clearedHtiles().erase(found);
return true;
}
struct ExpandWrite {
const DepthSurface* source = nullptr;
std::uint64_t written = 0;
std::weak_ptr<StorageTexture> destination;
std::uint64_t version = 0;
};
using ExpandKey = std::pair<VkDevice, std::uint64_t>;
std::map<ExpandKey, ExpandWrite>& expandWrites() {
static auto* writes = new std::map<ExpandKey, ExpandWrite>();
return *writes;
}
std::map<ExpandKey, std::size_t>& unstoredExpands() {
static auto* writes = new std::map<ExpandKey, std::size_t>();
return *writes;
}
std::atomic<std::uint64_t> expandsRun{0};
std::atomic<std::uint64_t> expandsSkipped{0};
std::atomic<std::uint64_t> expandsStored{0};
DepthSurface* drawnDepth = nullptr;
std::atomic<std::uint64_t> surfacesSerial{0};
@@ -2895,10 +2940,31 @@ bool storeHtileOnGpu(const Context& context, Recorder& recorder, std::uint64_t a
return true;
}
std::mutex& copyDestinationsMutex() {
static std::mutex mutex;
return mutex;
}
std::vector<std::pair<std::uint64_t, std::uint64_t>>& copyDestinations() {
static auto* ranges = new std::vector<std::pair<std::uint64_t, std::uint64_t>>();
return *ranges;
}
bool copiedOver(std::uint64_t address, std::size_t bytes) {
std::lock_guard lock(copyDestinationsMutex());
return std::any_of(copyDestinations().begin(), copyDestinations().end(), [&](const auto& range) { return address < range.second && range.first < address + bytes; });
}
void forgetCopiesInside(std::uint64_t address, std::size_t bytes) {
std::lock_guard lock(copyDestinationsMutex());
std::erase_if(copyDestinations(), [&](const auto& range) { return address <= range.first && range.second <= address + bytes; });
}
VkImageAspectFlags storeBackClearedHtile(const Context& context, const DepthTarget& target) {
if (target.htileAddress == 0) return 0;
const auto bytes = static_cast<std::size_t>(HtileMetadataBytes(target.extent));
if (!GuestMemory::Accessible(reinterpret_cast<const void*>(target.htileAddress), bytes, true)) return 0;
if (copiedOver(target.htileAddress, bytes)) return 0;
const auto collected = GuestMemory::CollectWrites(target.htileAddress, bytes);
auto* recorder = RecorderFor(context);
const bool pending = recorder != nullptr && recorder->PendingWriteOverlaps(target.htileAddress, bytes);
@@ -3787,7 +3853,17 @@ void ForgetHtileMasks_nid_no_patch(std::uint64_t recorderId) {
std::erase_if(htileMasks(), [&](const HtileMaskWrite& write) { return write.recorderId == recorderId; });
}
void NoteCopyDestination(std::uint64_t address, std::size_t bytes) {
if (bytes == 0) return;
std::lock_guard lock(copyDestinationsMutex());
auto& ranges = copyDestinations();
std::erase_if(ranges, [&](const auto& range) { return address <= range.first && range.second <= address + bytes; });
ranges.emplace_back(address, address + bytes);
if (ranges.size() > 256u) ranges.erase(ranges.begin());
}
bool NoteHtileDepthClear(std::uint64_t htileAddress, std::size_t bytes, std::size_t nativeBytes) {
forgetCopiesInside(htileAddress, bytes);
std::lock_guard lock(surfacesMutex());
forgetHtileReads(htileAddress, bytes);
bool existing = false;
@@ -3865,6 +3941,8 @@ void ClearDepthSurfaces(VkDevice device) {
std::erase_if(depthOwners(), [&](const auto& entry) { return entry.first.first == device; });
std::erase_if(stencilOwners(), [&](const auto& entry) { return entry.first.first == device; });
std::erase_if(surfaces(), [&](const auto& surface) { return surface->context.device == device; });
std::erase_if(expandWrites(), [&](const auto& entry) { return entry.first.first == device; });
std::erase_if(unstoredExpands(), [&](const auto& entry) { return entry.first.first == device; });
std::erase_if(planeCopies(), [&](const auto& entry) { return std::get<0>(entry.first) == device; });
std::erase_if(layeredStorages(), [&](const auto& entry) { return std::get<0>(entry.first) == device; });
{
@@ -3992,6 +4070,9 @@ std::shared_ptr<Texture> DepthSurfaceTexture(const Context& context, std::span<c
copy->lastUse = ++planeCopyClock();
copy->lastPresent = Recorder::Presents();
auto texture = copy->Refresh(slices, resource, components, cube || resource.dimension == TextureDimension::k2DArray ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D, layered && !cube ? resource.baseArray : 0u);
if (DepthPlaneReuse() && !texture->HasReuseLookup()) {
texture->SetReuseLookup([context, lookupWords = std::vector<std::uint32_t>(words.begin(), words.end()), resource, components] { return DepthSurfaceTexture(context, lookupWords, resource, components); });
}
evictPlaneCopies(copyKey);
return texture;
}
@@ -4070,6 +4151,7 @@ std::optional<float> planeFillDepth(const DepthTarget& target, std::uint64_t add
}
void NoteDepthMetadataFill(std::uint64_t address, std::size_t bytes, std::uint32_t pattern) {
forgetCopiesInside(address, bytes);
std::lock_guard gpu(GuestMemory::GpuMutex());
std::lock_guard lock(surfacesMutex());
forgetHtileReads(address, bytes);
@@ -4310,6 +4392,166 @@ void RetireDepthSurfaces(VkDevice device, std::uint64_t address, std::uint64_t b
}
}
namespace {
bool sixteenBitDepth(VkFormat format) {
return format == VK_FORMAT_D16_UNORM || format == VK_FORMAT_D16_UNORM_S8_UINT;
}
GuestTextureResource depthPlaneView(std::uint64_t address, VkExtent2D extent, VkFormat format) {
GuestTextureResource plane{};
plane.baseAddress = address;
plane.width = extent.width;
plane.height = extent.height;
plane.mipCount = 1;
plane.tileMode = TextureTileMode::kZ64KBX;
plane.dimension = TextureDimension::k2D;
plane.format = FindGuestColorTargetFormat(format, format == VK_FORMAT_R8_UINT ? 1u : format == VK_FORMAT_R16_UNORM ? 2u : 4u).value();
plane.dstSelX = 4;
plane.dstSelY = 5;
plane.dstSelZ = 6;
plane.dstSelW = 7;
return plane;
}
void recordPlaneClear(const Context& context, const std::shared_ptr<StorageTexture>& plane, float depth) {
auto* recorder = Recorder::Active();
Require(recorder != nullptr, "depth plane clears need an active recorder");
const auto commands = recorder->Commands();
recorder->Keep(plane);
const auto timing = recorder->BeginGpuTiming(Recorder::CommandClass::FillClear);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
VkClearColorValue clear{};
clear.float32[0] = depth;
const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
context.Function<PFN_vkCmdClearColorImage>("vkCmdClearColorImage")(commands, plane->Image(), VK_IMAGE_LAYOUT_GENERAL, &clear, 1, &range);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
Recorder::CountBarriers(Recorder::CommandClass::FillClear, 2);
recorder->EndGpuTiming(timing, plane->GuestBytes());
}
void recordPlaneCopy(const Context& context, const std::shared_ptr<StorageTexture>& source, const std::shared_ptr<StorageTexture>& destination, VkExtent2D extent) {
auto* recorder = Recorder::Active();
Require(recorder != nullptr, "depth plane copies need an active recorder");
const auto commands = recorder->Commands();
recorder->Keep(source);
recorder->Keep(destination);
const auto timing = recorder->BeginGpuTiming(Recorder::CommandClass::Copy);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT);
VkImageCopy region{};
region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
region.dstSubresource = region.srcSubresource;
region.extent = {extent.width, extent.height, 1};
context.Function<PFN_vkCmdCopyImage>("vkCmdCopyImage")(commands, source->Image(), VK_IMAGE_LAYOUT_GENERAL, destination->Image(), VK_IMAGE_LAYOUT_GENERAL, 1, &region);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
Recorder::CountBarriers(Recorder::CommandClass::Copy, 2);
recorder->EndGpuTiming(timing, destination->GuestBytes());
}
}
void RunDepthExpandPass(const Context& context, const DepthExpandPass& pass) {
const auto& source = pass.source;
const auto failure = [&](std::uint64_t destination, const char* what) {
char text[288];
std::snprintf(text, sizeof(text), "AGC graphics: an out-of-place DB expand from 0x%llx (%ux%u) to 0x%llx %s is not implemented", static_cast<unsigned long long>(source.address), source.extent.width, source.extent.height, static_cast<unsigned long long>(destination), what);
return std::runtime_error(text);
};
{
std::lock_guard lock(surfacesMutex());
for (const auto address : {pass.destination, pass.stencilDestination}) {
if (address != 0 && planeSurface(context.device, address) != nullptr) throw failure(address, "into a live depth surface");
}
}
const bool d16 = sixteenBitDepth(source.format);
expandsRun.fetch_add(1, std::memory_order_relaxed);
bool copied = false;
for (const bool stencil : {false, true}) {
const auto address = stencil ? pass.stencilDestination : pass.destination;
if (address == 0) continue;
const auto planeFormat = stencil ? VK_FORMAT_R8_UINT : d16 ? VK_FORMAT_R16_UNORM : VK_FORMAT_R32_SFLOAT;
const auto destination = CachedStorageSurface(context, depthPlaneView(address, source.extent, planeFormat));
if (destination == nullptr) throw failure(address, "without a storage image of the write base");
const ExpandKey key{context.device, address};
enum class Read { Surface, Clear, GuestBytes } read = Read::Surface;
ExpandWrite wrote;
{
std::lock_guard lock(surfacesMutex());
const auto owner = depthOwners().find({context.device, source.address});
if (owner != depthOwners().end()) {
auto* surface = owner->second.surface;
const auto& target = surface->target;
if (sixteenBitDepth(target.format) != d16 || surface->hostFormat != target.format || target.samples != 1 || target.extent.width != source.extent.width || target.extent.height != source.extent.height) throw failure(address, "from a depth surface of another extent, format or sample count");
if (stencil && target.stencilAddress != source.stencilAddress) throw failure(address, "of a stencil plane its depth surface does not hold");
surface->ApplyFastClear();
const auto last = expandWrites().find(key);
if (last != expandWrites().end() && last->second.source == surface && last->second.written == surface->written && last->second.destination.lock() == destination && last->second.version == destination->Version()) continue;
if (stencil) surface->CopyStencilTo(destination);
else surface->CopyDepthTo(destination);
wrote.source = surface;
wrote.written = surface->written;
} else {
read = !stencil && findClearedHtile(source) != clearedHtiles().end() ? Read::Clear : Read::GuestBytes;
}
}
if (read == Read::Clear) recordPlaneClear(context, destination, source.clearDepth);
if (read == Read::GuestBytes) {
const auto plane = CachedStorageSurface(context, depthPlaneView(stencil ? source.stencilAddress : source.address, source.extent, planeFormat));
if (plane == nullptr) throw failure(address, "without a storage image of the read base");
recordPlaneCopy(context, plane, destination, source.extent);
}
destination->MarkDirty();
wrote.destination = destination;
wrote.version = destination->Version();
{
std::lock_guard lock(surfacesMutex());
expandWrites()[key] = std::move(wrote);
unstoredExpands()[key] = static_cast<std::size_t>(destination->GuestBytes());
}
copied = true;
static bool reported[2][3] = {};
if (!std::exchange(reported[stencil ? 1 : 0][static_cast<int>(read)], true)) {
const auto from = static_cast<unsigned long long>(stencil ? source.stencilAddress : source.address);
const auto written = static_cast<unsigned long long>(address);
if (read == Read::Surface) std::fprintf(stderr, "[gpu] DB expand: the %s plane of 0x%llx (%ux%u) is written at 0x%llx\n", stencil ? "stencil" : "depth", from, source.extent.width, source.extent.height, written);
else std::fprintf(stderr, "[gpu] DB expand: 0x%llx (%ux%u) has no depth surface; %s written at 0x%llx\n", from, source.extent.width, source.extent.height, read == Read::Clear ? "DB_DEPTH_CLEAR (an HTILE clear is pending) is" : "its guest bytes are", written);
}
}
if (!copied) expandsSkipped.fetch_add(1, std::memory_order_relaxed);
}
void StoreDepthExpandWrites(const Context& context) {
std::vector<std::pair<std::uint64_t, std::size_t>> planes;
{
std::lock_guard lock(surfacesMutex());
auto& unstored = unstoredExpands();
for (auto entry = unstored.begin(); entry != unstored.end();) {
if (entry->first.first != context.device) {
++entry;
continue;
}
planes.emplace_back(entry->first.second, entry->second);
entry = unstored.erase(entry);
}
}
std::vector<std::pair<std::uint64_t, std::size_t>> kept;
for (const auto& [address, bytes] : planes) {
if (!HostImportOverlaps(context, address, bytes)) {
const std::array<std::pair<std::uint64_t, std::uint64_t>, 1> range{{{address, address + bytes}}};
if (StorageTexture::AnyPendingOverlaps(range)) kept.emplace_back(address, bytes);
continue;
}
if (StorageTexture::FlushPending(address, bytes, nullptr, "DB expand")) expandsStored.fetch_add(1, std::memory_order_relaxed);
}
if (kept.empty()) return;
std::lock_guard lock(surfacesMutex());
for (const auto& [address, bytes] : kept) unstoredExpands().try_emplace({context.device, address}, bytes);
}
DepthExpandStatistics DepthExpandCounts() {
return {expandsRun.load(std::memory_order_relaxed), expandsSkipped.load(std::memory_order_relaxed), expandsStored.load(std::memory_order_relaxed)};
}
void RetireCoveredDepthSurfaces(VkDevice device, std::span<const std::pair<std::uint64_t, std::uint64_t>> written, std::span<const WrittenStorageExtent> extents) {
std::lock_guard gpu(GuestMemory::GpuMutex());
std::lock_guard lock(surfacesMutex());
@@ -21,6 +21,7 @@
#include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp"
#include "prx/libSceAgcDriver/Execution/include/Mutex.hpp"
#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp"
#include "prx/libSceAgcDriver/Execution/include/ThreadScratch.hpp"
#include "ThreadOwned.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
@@ -739,7 +740,7 @@ constexpr std::array<const char*, PhaseCount> DrawPhaseNames{"validate", "vertex
enum SyncReason : std::size_t { SyncNone, SyncNotResident, SyncNoRecorder, SyncDisabled, SyncCopiedWrites, SyncLease, SyncCount };
constexpr std::array<const char*, SyncCount> SyncReasonNames{"none", "non-resident target", "no recorder", "disabled", "copied writes", "lease"};
constexpr std::size_t IndirectPathCount = static_cast<std::size_t>(IndirectDrawPath::Count);
constexpr std::array<const char*, IndirectPathCount> IndirectDrawPathNames{"gpu-side", "patched SGPR not folded", "fetch offset unknown", "non-vertex path", "GE_INDX_OFFSET", "draw index", "vertex range too large", "feature gap", "pending image results", "pending label or copied write", "not imported", "disabled", "index range not fully readable", "index limit unknown"};
constexpr std::array<const char*, IndirectPathCount> IndirectDrawPathNames{"gpu-side", "patched SGPR not folded", "fetch offset unknown", "non-vertex path", "GE_INDX_OFFSET", "draw index", "vertex range too large", "feature gap", "pending image results", "pending label or copied write", "not imported", "disabled", "index range not fully readable", "index limit unknown", "records settled"};
// What became of one draw, for the totals.
struct DrawOutcome {
@@ -1163,35 +1164,55 @@ std::vector<std::uint64_t>& validationKeyScratch() {
return key;
}
struct LastFragmentOutputs {
std::vector<std::uint64_t> key;
std::uint32_t outputs = 0;
bool valid = false;
FragmentOutputLookups lookups;
};
struct LastFragmentOutputsTag {};
bool LastFragmentOutputsEnabled() {
static const bool enabled = std::getenv("APS5_NO_LAST_FRAGMENT_OUTPUTS") == nullptr;
return enabled;
}
std::uint32_t CachedFragmentOutputs(const Context& context, std::span<const CompiledShader> shaders, const State& state, bool& memoized, bool& hit) {
memoized = false;
hit = false;
auto& key = validationKeyScratch();
const bool keyed = ValidationKey(context, shaders, state, key);
static std::map<std::vector<std::uint64_t>, std::uint32_t> memo;
struct LastKeyStorage {};
auto& lastKey = HostThreadLocal<std::vector<std::uint64_t>, LastKeyStorage>();
thread_local std::uint32_t lastOutputs = 0;
thread_local bool lastValid = false;
const bool trims = keyed && CommitTrims();
if (trims && lastValid && key == lastKey) {
auto& last = ThreadScratch<LastFragmentOutputs, LastFragmentOutputsTag>();
const bool remembers = keyed && LastFragmentOutputsEnabled();
if (remembers && last.valid && key == last.key) {
memoized = true;
hit = true;
return lastOutputs;
++last.lookups.last;
return last.outputs;
}
const auto remember = [&](std::uint32_t outputs) {
if (!remembers) return;
last.key = key;
last.outputs = outputs;
last.valid = true;
};
if (keyed) {
memoized = true;
std::lock_guard lock(validationMutex());
if (const auto found = memo.find(key); found != memo.end()) {
std::optional<std::uint32_t> found;
{
std::lock_guard lock(validationMutex());
if (const auto entry = memo.find(key); entry != memo.end()) found = entry->second;
}
if (found) {
hit = true;
if (trims) {
lastKey = key;
lastOutputs = found->second;
lastValid = true;
}
return found->second;
++last.lookups.memo;
remember(*found);
return *found;
}
}
++last.lookups.validated;
std::uint32_t outputs = 0;
try {
for (const auto location : ValidateShaders(shaders, state, context.subgroup, context.fragmentShaderBarycentric, context.descriptorIndexing, context.imageInt64Atomics, context.geometryShader, context.sampleRateShading, context.bufferInt64Atomics, context.shaderClipDistance, context.shaderCullDistance, context.viewportIndexLayer, context.runtimeDescriptorArray, context.demoteToHelperInvocation, context.shaderTerminateInvocation, context.meshShader, context.shaderResourceMinLod, context.fmaFloat16)) {
@@ -1213,6 +1234,7 @@ std::uint32_t CachedFragmentOutputs(const Context& context, std::span<const Comp
if (memo.size() >= 1024) memo.clear();
memo.emplace(key, outputs);
}
remember(outputs);
return outputs;
}
@@ -1447,9 +1469,11 @@ void reportDrawEnd(const State& state, const DrawTimer& timer, const ShaderResou
}
DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uint64_t address, std::size_t bytes, std::size_t alignment, Recorder::SnapshotUse use) {
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) {
Require(use != Recorder::SnapshotUse::Storage, "a draw input is a vertex or index buffer");
Require(from == 0 || (use == Recorder::SnapshotUse::Vertex && from < bytes), "only a vertex input starts past its address");
DrawInputCopy copy;
copy.from = from;
if (recorder != nullptr && bytes != 0) {
GuestMemory::FlushGpuWrites(address, bytes);
#ifdef _WIN32
@@ -1457,14 +1481,14 @@ DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uin
#else
constexpr bool owned = false;
#endif
if (owned && recorder->OwnedDrawInputEntries() != 0) copy.buffer = recorder->ReusableOwnedDrawInput(address, bytes, use, &copy.derived);
if (owned && recorder->OwnedDrawInputEntries() != 0) copy.buffer = recorder->ReusableOwnedDrawInput(address, bytes, use, &copy.derived, from, &copy.lowest);
if (copy.buffer != nullptr) {
copy.reused = true;
return copy;
}
copy.registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix();
copy.generation = GuestMemory::CollectWrites(address, bytes);
if (copy.generation != 0) copy.buffer = recorder->ReusableDrawSnapshot(address, bytes, use, &copy.derived);
if (copy.generation != 0) copy.buffer = recorder->ReusableDrawSnapshot(address, bytes, use, &copy.derived, 0, nullptr, from, &copy.lowest);
else if (owned) copy.owned = recorder->ArmOwnedDrawInput(address, bytes);
if (copy.buffer != nullptr) {
copy.reused = true;
@@ -1472,7 +1496,10 @@ DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uin
}
}
copy.buffer = std::make_shared<Buffer>(context, bytes, use == Recorder::SnapshotUse::Vertex ? VK_BUFFER_USAGE_VERTEX_BUFFER_BIT : VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
GuestMemory::Read(address, copy.buffer->Bytes(), alignment);
static const bool poisonPrefix = std::getenv("APS5_POISON_VERTEX_PREFIX") != nullptr;
const auto held = copy.buffer->Bytes();
if (poisonPrefix) std::fill(held.begin(), held.begin() + static_cast<std::ptrdiff_t>(from), std::byte{0x7f});
GuestMemory::Read(address + from, held.subspan(from), alignment);
return copy;
}
@@ -1507,13 +1534,13 @@ DrawInputCopy CopyZeroPaddedDrawInput(const Context& context, std::uint64_t addr
return copy;
}
void KeepDrawInput(Recorder* recorder, std::uint64_t address, const DrawInputCopy& copy, Recorder::SnapshotUse use, std::uint32_t derived) {
void KeepDrawInput(Recorder* recorder, std::uint64_t address, const DrawInputCopy& copy, Recorder::SnapshotUse use, std::uint32_t derived, std::uint32_t lowest) {
if (recorder == nullptr || copy.reused || copy.buffer == nullptr) return;
if (copy.generation == 0) {
if (!copy.owned.words.empty() && !RuntimeSwitches::Set(RuntimeSwitch::NoOwnedDrawInputs)) recorder->KeepOwnedDrawInput(address, copy.buffer->Bytes().size(), copy.owned, copy.buffer, use, derived);
if (!copy.owned.words.empty() && !RuntimeSwitches::Set(RuntimeSwitch::NoOwnedDrawInputs)) recorder->KeepOwnedDrawInput(address, copy.buffer->Bytes().size(), copy.owned, copy.buffer, use, derived, copy.from, lowest);
return;
}
recorder->KeepDrawSnapshot(address, copy.buffer->Bytes().size(), copy.generation, copy.registryGeneration, copy.buffer, use, derived);
recorder->KeepDrawSnapshot(address, copy.buffer->Bytes().size(), copy.generation, copy.registryGeneration, copy.buffer, use, derived, copy.from, lowest);
}
const HostImport* InPlaceDrawInput(const Context& context, std::uint64_t address, std::size_t bytes, std::size_t alignment, bool* behindGpuWrite) {
@@ -1542,19 +1569,25 @@ const HostImport* InPlaceDrawInput(const Context& context, std::uint64_t address
InPlaceIndices InPlaceIndexRange(Recorder& recorder, std::uint64_t address, std::size_t bytes, std::uint32_t indexSize, bool skipRestart) {
const std::span<const std::byte> range(reinterpret_cast<const std::byte*>(address), bytes);
InPlaceIndices indices;
const auto scan = [&] {
const auto bounds = DrawIndexRange(range, indexSize, skipRestart);
if (!bounds) return;
indices.highest = bounds->highest;
indices.lowest = bounds->lowest;
};
if (bytes < Recorder::KeptIndexRangeIndices * indexSize) {
indices.highest = HighestDrawIndex(range, indexSize, skipRestart);
scan();
return indices;
}
const auto use = indexSize == 2 ? (skipRestart ? Recorder::SnapshotUse::Index16Restart : Recorder::SnapshotUse::Index16) : (skipRestart ? Recorder::SnapshotUse::Index32Restart : Recorder::SnapshotUse::Index32);
const auto registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix();
const auto generation = GuestMemory::CollectWrites(address, bytes);
if (generation != 0 && recorder.KnownHighestIndex(address, bytes, use, indices.highest)) {
if (generation != 0 && recorder.KnownHighestIndex(address, bytes, use, indices.highest, &indices.lowest)) {
indices.reused = true;
return indices;
}
indices.highest = HighestDrawIndex(range, indexSize, skipRestart);
recorder.KeepHighestIndex(address, bytes, use, generation, registryGeneration, indices.highest);
scan();
recorder.KeepHighestIndex(address, bytes, use, generation, registryGeneration, indices.highest, indices.lowest);
return indices;
}
@@ -1571,6 +1604,7 @@ struct DrawInputs {
VkBuffer indexHandle = VK_NULL_HANDLE;
VkDeviceSize indexOffset = 0;
std::uint32_t maxIndex = 0;
std::uint32_t minIndex = 0;
std::optional<std::uint32_t> indexCount;
std::uint32_t listRestartPrimitive = 0;
VertexInputLayout vertexInput;
@@ -1749,6 +1783,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
timer.phase(PhaseValidate);
timing.Mark("validate");
inputs.maxIndex = draw.indexed ? 0u : draw.firstVertex + draw.indexCount - 1u;
inputs.minIndex = draw.indexed ? 0u : draw.firstVertex;
if (state.quadList || StripPatches(state, shaders)) {
Require(!draw.indirect, state.quadList ? "indirect quad-list draw is unsupported" : "an indirect triangle strip through emulated barycentric patches is unsupported");
Require(state.quadList || !draw.indexed || !state.primitiveRestart, "an indexed triangle strip with primitive restart through emulated barycentric patches is unsupported");
@@ -1844,18 +1879,19 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
const auto count = draw.indirect ? draw.indexCount : CompactListRestart(bytes, draw.indexSize, primitiveSize);
const auto kept = bytes.first(static_cast<std::size_t>(count) * draw.indexSize);
const bool restartLeft = draw.indirect.has_value();
auto highest = HighestDrawIndex(kept, draw.indexSize, restartLeft);
auto bounds = DrawIndexRange(kept, draw.indexSize, restartLeft);
constexpr std::uint32_t ZeroFetchSlack = 0x10000u;
if (const auto zeroFrom = highest && !shaders.front().program->vertexAttributes.empty() ? ZeroFetchVertex(shaders.front().program->vertexAttributes) : std::nullopt) {
if (const auto zeroFrom = bounds && !shaders.front().program->vertexAttributes.empty() ? ZeroFetchVertex(shaders.front().program->vertexAttributes) : std::nullopt) {
const auto limit = *zeroFrom > draw.firstVertex ? *zeroFrom - draw.firstVertex : 0u;
if (*highest >= limit && *highest - limit >= ZeroFetchSlack) highest = ClampDrawIndices(kept, draw.indexSize, restartLeft, limit);
if (bounds->highest >= limit && bounds->highest - limit >= ZeroFetchSlack) bounds = ClampDrawIndices(kept, draw.indexSize, restartLeft, limit);
}
if (!highest) {
if (!bounds) {
inputs.nothing = true;
return inputs;
}
Require(*highest <= context.limits.maxDrawIndexedIndexValue, "index exceeds the device's indexed draw limit");
inputs.maxIndex = *highest;
Require(bounds->highest <= context.limits.maxDrawIndexedIndexValue, "index exceeds the device's indexed draw limit");
inputs.maxIndex = bounds->highest;
inputs.minIndex = bounds->lowest;
inputs.indexCount = count;
inputs.listRestartPrimitive = primitiveSize;
inputs.indices = std::move(compacted);
@@ -1870,15 +1906,21 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
if (import == nullptr) copy = CopyDrawInput(context, context.recorder, draw.indexAddress, static_cast<std::size_t>(indexBytes), draw.indexSize, use);
else GuestMemory::CheckRange(reinterpret_cast<const void*>(draw.indexAddress), static_cast<std::size_t>(indexBytes), draw.indexSize);
std::optional<std::uint32_t> highest;
std::uint32_t lowest = 0;
if (import != nullptr) {
highest = InPlaceIndexRange(*context.recorder, draw.indexAddress, static_cast<std::size_t>(indexBytes), draw.indexSize, skipRestart).highest;
const auto range = InPlaceIndexRange(*context.recorder, draw.indexAddress, static_cast<std::size_t>(indexBytes), draw.indexSize, skipRestart);
highest = range.highest;
lowest = range.lowest;
} else if (!copy.reused) {
highest = HighestDrawIndex(copy.buffer->Bytes().first(static_cast<std::size_t>(indexBytes)), draw.indexSize, skipRestart);
KeepDrawInput(context.recorder, draw.indexAddress, copy, use, skipRestart ? (highest ? *highest + 1u : 0u) : highest.value_or(0u));
} else if (!skipRestart) {
highest = copy.derived;
} else if (copy.derived != 0) {
highest = copy.derived - 1u;
if (const auto bounds = DrawIndexRange(copy.buffer->Bytes().first(static_cast<std::size_t>(indexBytes)), draw.indexSize, skipRestart)) {
highest = bounds->highest;
lowest = bounds->lowest;
}
KeepDrawInput(context.recorder, draw.indexAddress, copy, use, skipRestart ? (highest ? *highest + 1u : 0u) : highest.value_or(0u), lowest);
} else {
lowest = copy.lowest;
if (!skipRestart) highest = copy.derived;
else if (copy.derived != 0) highest = copy.derived - 1u;
}
if (!highest) {
inputs.nothing = true;
@@ -1892,18 +1934,21 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
auto clamped = std::make_shared<Buffer>(context, static_cast<std::size_t>(indexBytes), VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
const auto bytes = clamped->Bytes().first(static_cast<std::size_t>(indexBytes));
GuestMemory::Read(draw.indexAddress, bytes, draw.indexSize);
highest = ClampDrawIndices(bytes, draw.indexSize, skipRestart, limit);
const auto clampedBounds = ClampDrawIndices(bytes, draw.indexSize, skipRestart, limit);
import = nullptr;
copy = DrawInputCopy{};
copy.buffer = std::move(clamped);
if (!highest) {
if (!clampedBounds) {
inputs.nothing = true;
return inputs;
}
highest = clampedBounds->highest;
lowest = clampedBounds->lowest;
}
}
Require(*highest <= context.limits.maxDrawIndexedIndexValue, "index exceeds the device's indexed draw limit");
inputs.maxIndex = *highest;
inputs.minIndex = lowest;
if (skipRestart && state.stages.mesh && (state.stages.mesh->inputPrimitive == 5 || state.stages.mesh->inputPrimitive == 6)) {
const auto indexSpan = import != nullptr ? std::span<const std::byte>(reinterpret_cast<const std::byte*>(draw.indexAddress), static_cast<std::size_t>(indexBytes)) : copy.buffer->Bytes().first(static_cast<std::size_t>(indexBytes));
inputs.restartTable = MeshRestartTable(indexSpan, draw.indexSize);
@@ -1926,6 +1971,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
if (draw.indexed) {
Require(draw.firstVertex <= std::numeric_limits<std::uint32_t>::max() - inputs.maxIndex, "indexed draw vertex range overflow");
inputs.maxIndex += draw.firstVertex;
inputs.minIndex += draw.firstVertex;
}
std::vector<VertexFetch> fetches;
std::vector<std::size_t> fetchValid;
@@ -1968,6 +2014,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
plannedFetches.push_back(fetches[f]);
}
const auto plan = PlanVertexCopies(plannedFetches);
const auto rangeFrom = args == nullptr && !state.stages.mesh ? VertexCopyStarts(plan, plannedFetches, inputs.minIndex, draw.firstInstance) : std::vector<std::size_t>(plan.copies.size(), 0);
std::vector<VkBuffer> rangeHandles;
std::vector<VkDeviceSize> rangeOffsets;
rangeHandles.reserve(plan.copies.size());
@@ -1983,7 +2030,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
inputs.inPlaceReads.emplace_back(begin, end);
continue;
}
auto copy = CopyDrawInput(context, context.recorder, begin, bytes, 1, Recorder::SnapshotUse::Vertex);
auto copy = CopyDrawInput(context, context.recorder, begin, bytes, 1, Recorder::SnapshotUse::Vertex, rangeFrom[range]);
KeepDrawInput(context.recorder, begin, copy, Recorder::SnapshotUse::Vertex, 0);
rangeHandles.push_back(copy.buffer->Handle());
rangeOffsets.push_back(0);
@@ -2596,7 +2643,8 @@ void patchDepthRemapPush(std::array<std::byte, PipelinePushConstantBytes>& block
std::memcpy(block.data() + ShaderRecompiler::DepthRemapPushOffsetBytes, words.data(), sizeof(words));
}
void recordStencilReplay(const Context& context, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, std::span<const std::pair<std::uint32_t, std::shared_ptr<Pipeline>>> replay, std::span<const CompiledShader> shaders, const ShaderResources& resources, const std::array<std::byte, PipelinePushConstantBytes>* bytes = nullptr, VkShaderStageFlags stages = 0) {
void recordStencilReplay(const Context& context, CommandState& recording, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, std::span<const std::pair<std::uint32_t, std::shared_ptr<Pipeline>>> replay, std::span<const CompiledShader> shaders, const ShaderResources& resources, const std::array<std::byte, PipelinePushConstantBytes>* bytes = nullptr, VkShaderStageFlags stages = 0) {
const auto commands = recording.Commands();
State selected = state;
auto block = bytes != nullptr ? *bytes : AssemblePushConstants(shaders);
if (bytes == nullptr) {
@@ -2614,7 +2662,7 @@ void recordStencilReplay(const Context& context, VkCommandBuffer commands, const
selected.stencilReplayReference = reference;
selected.stencilFront.reference = reference;
selected.stencilBack.reference = reference;
context.Resolved(&DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, VK_STENCIL_FACE_FRONT_AND_BACK, reference);
recording.SetStencilReference(context, VK_STENCIL_FACE_FRONT_AND_BACK, reference);
std::memcpy(block.data() + referenceOffset, &reference, sizeof(reference));
pipeline->PushConstants(commands, stages, block);
recordDrawCommands(context, commands, selected, piece, inputs, nullptr, VK_NULL_HANDLE, 0, nullptr, unusedSubdraw, firstIndex);
@@ -2856,6 +2904,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam
outcome.passBegun = !continued;
outcome.passBreak = start.reason;
const auto commands = start.commands;
auto& recording = recorder->GraphicsState();
if (!continued) {
recorder->PrepareSampleSlot();
PerformanceTrace::Amount(PerformanceTrace::RenderPassScope, 1);
@@ -2884,7 +2933,7 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam
bool rewritten = false;
if (!meshIndirect && !inputs.restartTable.empty()) meshArguments = directMeshArguments(context, draw, inputs.restartTable);
if (continued) {
record.pipeline->Continue(commands, state, record.masked);
record.pipeline->Continue(recording, state, record.masked);
} else {
for (const auto& proxy : record.proxies) {
proxy->RecordAttachmentProxyLoad(commands, VK_IMAGE_LAYOUT_GENERAL);
@@ -2917,12 +2966,12 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam
// layout, which a lean draw renders in: no transitions.
if (!record.reordered.empty()) {
std::vector<std::shared_ptr<void>> kept;
RecordSampleOrder(context, commands, record.reorderPass, record.reordered, true, kept);
RecordSampleOrder(context, recording, record.reorderPass, record.reordered, true, kept);
for (auto& object : kept) recorder->Keep(std::move(object));
}
for (const auto& write : record.staged) RecordStagedClear(context, commands, *write.temporary);
APS5_LOG_OUT_DEBUG("Beginning pipeline renderExtent=%ux%u", state.renderExtent.width, state.renderExtent.height);
record.pipeline->Begin(commands, *record.framebuffer, state.renderExtent, state, record.masked);
record.pipeline->Begin(recording, *record.framebuffer, state.renderExtent, state, record.masked);
}
APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK");
if (drawBindings != nullptr) {
@@ -2950,15 +2999,15 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam
noteDrawFaultToken(context, *recorder, commands, shaders, draw, static_cast<std::uint32_t>(state.stages.mesh.has_value() ? AgcDriver::FaultStage::mesh : AgcDriver::FaultStage::graphics), record.indirect != nullptr ? record.indirect->args : nullptr);
if (record.stencilReplay.empty()) recordDrawCommands(context, commands, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw);
else {
recordStencilReplay(context, commands, state, draw, inputs, record.stencilReplay, shaders, resources, record.pushBytes, record.pushStages);
recordStencilReplay(context, recording, state, draw, inputs, record.stencilReplay, shaders, resources, record.pushBytes, record.pushStages);
for (const auto& [reference, pipeline] : record.stencilReplay) recorder->Keep(pipeline);
}
if (record.pipeline->SplitsFaces()) {
record.pipeline->ContinueBackFaces(commands, state, record.masked);
record.pipeline->ContinueBackFaces(recording, state, record.masked);
recordDrawCommands(context, commands, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw);
}
if (record.pipeline->SplitsSecondChannel()) {
record.pipeline->ContinueSecondChannel(commands, state, record.masked);
record.pipeline->ContinueSecondChannel(recording, state, record.masked);
recordDrawCommands(context, commands, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw);
}
recorder->EndGpuTiming(eachDrawTiming);
@@ -2970,16 +3019,17 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam
if (args != nullptr) CountIndirectDraw(record.indirect->path, record.indirect->readMs, rewritten);
auto checkRecords = indirectRecordCheck(record.indirect);
APS5_LOG_CHARS_OUT_DEBUG("Draw recorded");
std::function<void(VkCommandBuffer)> storeProxies;
std::function<void(CommandState&)> storeProxies;
if (!continued && (!record.proxies.empty() || !record.reordered.empty() || record.depthLocations)) {
storeProxies = [proxies = record.proxies, reordered = record.reordered, reorderPass = record.reorderPass, depthLocations = record.depthLocations, context, recorder](VkCommandBuffer passCommands) {
storeProxies = [proxies = record.proxies, reordered = record.reordered, reorderPass = record.reorderPass, depthLocations = record.depthLocations, context, recorder](CommandState& passRecording) {
const auto passCommands = passRecording.Commands();
for (const auto& proxy : proxies) {
proxy->RecordAttachmentProxyStore(passCommands, VK_IMAGE_LAYOUT_GENERAL);
Recorder::CountBarriers(Recorder::CommandClass::Draw, 2);
}
if (!reordered.empty()) {
std::vector<std::shared_ptr<void>> kept;
RecordSampleOrder(context, passCommands, reorderPass, reordered, false, kept);
RecordSampleOrder(context, passRecording, reorderPass, reordered, false, kept);
for (auto& object : kept) recorder->Keep(std::move(object));
}
if (depthLocations) {
@@ -3533,6 +3583,8 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
if (context.copiedWriters != nullptr && std::any_of(context.copiedWriters->begin(), context.copiedWriters->end(), overlaps)) return IndirectDrawPath::PendingLabelOrCopy;
if (std::any_of(DrawCopiedWriters()->begin(), DrawCopiedWriters()->end(), overlaps)) return IndirectDrawPath::PendingLabelOrCopy;
if ((import = HostImportFor(context, address, bytes)) == nullptr) return IndirectDrawPath::NotImported;
static const bool settledReads = std::getenv("APS5_NO_SETTLED_INDIRECT_READ") == nullptr;
if (settledReads && recorder != nullptr && recorder->PendingWriteSettled(address, bytes)) return IndirectDrawPath::Settled;
return IndirectDrawPath::Gpu;
};
const auto rangeBytes = args->RangeBytes();
@@ -3546,7 +3598,8 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
else indirect.path = decide(args->arguments, static_cast<std::size_t>(rangeBytes), indirect.argumentImport);
if (indirect.path == IndirectDrawPath::Gpu && args->countIndirect) {
Require(context.drawIndirectCount, "indirect draw count without VK_KHR_draw_indirect_count must be resolved by the driver");
indirect.path = decide(args->countAddress, 4, indirect.countImport);
const auto countPath = decide(args->countAddress, 4, indirect.countImport);
if (countPath != IndirectDrawPath::Settled) indirect.path = countPath;
}
if (indirect.path != IndirectDrawPath::Gpu) {
// The reads wait for the producing batch through the flush hook, as the driver's
@@ -3841,6 +3894,9 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D
if (recorded && recorder->HasQueuedStores() && (resources->HoldsLease() || recorder->AnyQueuedStore(touches))) recorder->FlushStores();
const auto commands = recorded ? recorder->Commands() : batch->Handle();
if (recorded) prepared.spaceKeep = reserveSpaceKeep(*recorder, *resources);
std::optional<CommandState> batchRecording;
if (!recorded) batchRecording.emplace().Begin(commands, false);
auto& recording = recorded ? recorder->GraphicsState() : *batchRecording;
if (recorded) recorder->PrepareSampleSlot();
APS5_LOG_CHARS_OUT_DEBUG("CommandBatch created");
// The draw's [gputime] class range: from its first barrier to the download barrier.
@@ -3926,9 +3982,9 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D
imageBarrier(context, commands, binding.target->Image(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
}
std::vector<std::shared_ptr<void>> reorderKept;
RecordSampleOrder(context, commands, reorderPass, reordered, true, reorderKept);
RecordSampleOrder(context, recording, reorderPass, reordered, true, reorderKept);
APS5_LOG_OUT_DEBUG("Beginning pipeline renderExtent=%ux%u", state.renderExtent.width, state.renderExtent.height);
pipeline->Begin(commands, *framebuffer, state.renderExtent, state, masked.has_value() ? &*masked : nullptr);
pipeline->Begin(recording, *framebuffer, state.renderExtent, state, masked.has_value() ? &*masked : nullptr);
APS5_LOG_CHARS_OUT_DEBUG("Pipeline Begin OK");
const auto drawUse = recorded ? resources->BeginDrawUse(*recorder) : nullptr;
resources->BindDrawUse(commands, pipeline->Layout(), drawUse.get());
@@ -3941,15 +3997,15 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D
if (recorded) noteDrawFaultToken(context, *recorder, commands, shaders, draw, static_cast<std::uint32_t>(state.stages.mesh.has_value() ? AgcDriver::FaultStage::mesh : AgcDriver::FaultStage::graphics), args);
if (stencilReplay.empty()) recordDrawCommands(context, commands, state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw);
else {
recordStencilReplay(context, commands, state, draw, inputs, stencilReplay, shaders, *resources);
recordStencilReplay(context, recording, state, draw, inputs, stencilReplay, shaders, *resources);
if (recorded) for (const auto& [reference, selectedPipeline] : stencilReplay) recorder->Keep(selectedPipeline);
}
if (pipeline->SplitsFaces()) {
pipeline->ContinueBackFaces(commands, state, masked.has_value() ? &*masked : nullptr);
pipeline->ContinueBackFaces(recording, state, masked.has_value() ? &*masked : nullptr);
recordDrawCommands(context, commands, state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw);
}
if (pipeline->SplitsSecondChannel()) {
pipeline->ContinueSecondChannel(commands, state, masked.has_value() ? &*masked : nullptr);
pipeline->ContinueSecondChannel(recording, state, masked.has_value() ? &*masked : nullptr);
recordDrawCommands(context, commands, state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw);
}
if (meshArguments != nullptr && recorded) recorder->Keep(meshArguments);
@@ -3962,7 +4018,7 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D
APS5_LOG_CHARS_OUT_DEBUG("Draw recorded");
if (recorded) recorder->EndPassSamples();
EndRenderPass(context, commands);
RecordSampleOrder(context, commands, reorderPass, reordered, false, reorderKept);
RecordSampleOrder(context, recording, reorderPass, reordered, false, reorderKept);
if (depthLocations) {
RecordDepthSampleLocations(context, commands, *depthLocations);
countBarrier(2);
@@ -4455,6 +4511,10 @@ bool CommitTrims() {
return DrawPipelineEnabled();
}
FragmentOutputLookups ThreadFragmentOutputLookups() {
return ThreadScratch<LastFragmentOutputs, LastFragmentOutputsTag>().lookups;
}
VkDrawCounts TakeVkDrawCounts() {
VkDrawCounts counts;
@@ -237,13 +237,14 @@ void FirstSampleCopy::Record(Recorder& recorder, VkImageView source, VkImageLayo
write.pImageInfo = &imageInfo;
context.Function<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(context.device, 1, &write, 0, nullptr);
recorder.Keep(pool);
recorder.RecordUncounted([&](VkCommandBuffer commands) {
recorder.RecordUncounted([&](CommandState& recording) {
const auto commands = recording.Commands();
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
begin.renderPass = renderPass;
begin.framebuffer = framebuffer;
begin.renderArea = {{0, 0}, extent};
context.Resolved(&DeviceFunctions::cmdBeginRenderPass, "vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
recording.BindPipeline(context, pipeline, 0);
context.Function<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &set, 0, nullptr);
context.Function<PFN_vkCmdDraw>("vkCmdDraw")(commands, 3, 1, 0, 0);
context.Resolved(&DeviceFunctions::cmdEndRenderPass, "vkCmdEndRenderPass")(commands);
@@ -146,7 +146,7 @@ void GpuColorTransfer::dispatch(VkCommandBuffer commands, bool toTiled, bool swa
const auto barrier = context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier");
barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr);
const std::array<std::uint32_t, 5> push{width, height, (width + 127u) / 128u, (toTiled ? 1u : 0u) | (swapRedBlue ? 2u : 0u) | (tiledSource ? 4u : 0u) | (tenBit ? 8u : 0u) | (halfFloat ? 16u : 0u) | (pqWhiteNits ? 32u : 0u), std::bit_cast<std::uint32_t>(pqWhiteNits.value_or(0.0f))};
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
context.BindComputePipeline(commands, pipeline);
context.Function<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &descriptorSet, 0, nullptr);
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data());
context.Function<PFN_vkCmdDispatch>("vkCmdDispatch")(commands, (width + 7u) / 8u, (height + 7u) / 8u, 1);
@@ -9,6 +9,7 @@
#include "ThreadOwned.hpp"
#include "prx/libSceAgcDriver/Graphics/include/SnapshotCopies.hpp"
#include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ResidentMirror.hpp"
@@ -236,6 +237,10 @@ bool addressSpaceCacheEnabled() {
return !disabled;
}
struct DmaBufImportFailure : std::runtime_error {
using std::runtime_error::runtime_error;
};
struct ImportFailure {
std::uint64_t base;
std::uint64_t bytes;
@@ -424,6 +429,7 @@ struct HostImports {
bool allocationFailed = false;
std::uint8_t reportNoted = 0;
std::map<std::uint64_t, std::uint64_t> spaceUses;
bool dmaBufSelected = false;
std::uint64_t budgetRefusals = 0;
std::array<const HostImport*, 4> recentImports{};
std::uint64_t recentEpoch = std::numeric_limits<std::uint64_t>::max();
@@ -684,7 +690,20 @@ VkResult createImportBuffer(const Context& context, VkExternalMemoryHandleTypeFl
return context.Function<PFN_vkCreateBuffer>("vkCreateBuffer")(context.device, &info, nullptr, buffer);
}
const char* bindImport(const Context& context, HostImport& entry, VkExternalMemoryHandleTypeFlagBits handleType, const void* import, std::uint32_t importTypes, bool& allocated, VkResult& failure) {
std::optional<std::uint32_t> coherentImportType(const Context& context, std::uint32_t types) {
constexpr VkMemoryPropertyFlags coherent = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
std::optional<std::uint32_t> plain;
for (std::uint32_t i = 0; i < context.memory.memoryTypeCount; ++i) {
if ((types & (1u << i)) == 0) continue;
const auto flags = context.memory.memoryTypes[i].propertyFlags;
if ((flags & coherent) != coherent) continue;
if ((flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) != 0) return i;
if (!plain.has_value()) plain = i;
}
return plain;
}
const char* bindImport(const Context& context, HostImport& entry, VkExternalMemoryHandleTypeFlagBits handleType, const void* import, std::uint32_t importTypes, bool& allocated, VkResult& failure, bool hostCoherent = false) {
const auto failed = [&](const char* step, VkResult result) -> const char* {
if (entry.buffer) context.Function<PFN_vkDestroyBuffer>("vkDestroyBuffer")(context.device, entry.buffer, nullptr);
if (allocated && entry.memory) MemoryAccounting::Free(context, entry.memory);
@@ -711,10 +730,16 @@ const char* bindImport(const Context& context, HostImport& entry, VkExternalMemo
context.Function<PFN_vkGetBufferMemoryRequirements>("vkGetBufferMemoryRequirements")(context.device, entry.buffer, &requirements);
const auto types = requirements.memoryTypeBits & importTypes;
if (types == 0) return failed("memory type selection", VK_ERROR_FORMAT_NOT_SUPPORTED);
std::uint32_t type = static_cast<std::uint32_t>(std::countr_zero(types));
if (hostCoherent && context.memory.memoryTypeCount != 0) {
const auto coherent = coherentImportType(context, types);
if (!coherent.has_value()) return failed("memory type selection without host coherency", VK_ERROR_FORMAT_NOT_SUPPORTED);
type = *coherent;
}
const VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, import, VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, 0};
VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags};
allocation.allocationSize = entry.bytes;
allocation.memoryTypeIndex = static_cast<std::uint32_t>(std::countr_zero(types));
allocation.memoryTypeIndex = type;
if (const auto result = MemoryAccounting::Allocate(context, allocation, "guest memory import", &entry.memory); result != VK_SUCCESS) return failed("vkAllocateMemory", result);
allocated = true;
entry.memoryType = allocation.memoryTypeIndex;
@@ -734,7 +759,7 @@ const char* createHostPointerImport(const Context& context, HostImport& entry, V
}
const VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT, nullptr, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, host};
bool allocated = false;
return bindImport(context, entry, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, &import, pointer.memoryTypeBits, allocated, failure);
return bindImport(context, entry, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, &import, pointer.memoryTypeBits, allocated, failure, true);
}
#ifndef _WIN32
@@ -1477,6 +1502,7 @@ void decideImportWatch(const Context& context, HostImports& state) {
state.unwatchImports = true;
state.unwatchDmaBufImports = false;
state.watchPrivateImports = false;
state.dmaBufSelected = false;
if (context.hostImportAlignment == 0 || !GuestMemory::WriteWatched()) return;
if (context.settleQueue == VK_NULL_HANDLE || context.settleQueueMutex == nullptr) {
std::fprintf(stderr, "[write-watch] Windows direct host imports use comparisons (no second queue to settle imports on); separate shared aliases retain guest write tracking\n");
@@ -1494,6 +1520,7 @@ void decideImportWatch(const Context& context, HostImports& state) {
state.watchDevice = context.device;
state.unwatchImports = false;
state.unwatchDmaBufImports = false;
state.dmaBufSelected = false;
if (context.hostImportAlignment == 0) return;
if (!GuestMemory::WriteWatched()) {
// Without a write watch the write-protection probes cannot measure, but the dma-buf
@@ -1540,6 +1567,7 @@ void decideImportWatch(const Context& context, HostImports& state) {
state.unwatchDmaBufImports = dmaBuf.writtenAfterSubmit != 0 || dmaBuf.writtenAfterFill != 0 || dmaBuf.writtenByCpu == 0;
state.dmaBufImportsCoherent = dmaBuf.staleAfterFill == 0;
std::fprintf(stderr, "[write-watch] dma-buf imports keep write protection: %s (%u of %u scratch pages written after a GPU read, %u after a GPU write, %u after the import, %u seen after a CPU store, %u stale after a GPU store over CPU writes); imported ranges %s%s\n", state.unwatchDmaBufImports ? "no" : "yes", dmaBuf.writtenAfterSubmit, dmaBuf.pages, dmaBuf.writtenAfterFill, dmaBuf.writtenAtImport, dmaBuf.writtenByCpu, dmaBuf.staleAfterFill, state.unwatchDmaBufImports ? "are compared" : "stay watched", state.dmaBufImportsCoherent ? "" : "; dma-buf imports are not CPU-coherent and are not used");
state.dmaBufSelected = state.unwatchImports && !state.unwatchDmaBufImports && state.dmaBufImportsCoherent;
#endif
}
@@ -1628,7 +1656,7 @@ bool importStaysWatched(const Context& context, HostImports& state, const Import
return importWatching(context, state, !pages.writable, pages.writable, run.bytes).hostPointer;
#else
const auto watching = importWatching(context, state, false, true, run.bytes);
return watching.hostPointer && (watching.dmaBuf || !sharedBacked(context, run.base, run.bytes));
return sharedBacked(context, run.base, run.bytes) ? watching.dmaBuf && (watching.hostPointer || state.dmaBufSelected) : watching.hostPointer;
#endif
}
@@ -2469,7 +2497,12 @@ const HostImport* importRunAt(const Context& context, HostImports& state, Import
#endif
const bool watchedHostPointer = watching.hostPointer;
const bool watchedDmaBuf = watching.dmaBuf;
GuestMemory::ImportWatched(base, bytes, [&] {
#ifndef _WIN32
const bool dmaBufOnly = state.dmaBufSelected && sharedBacked(context, base, bytes);
#else
constexpr bool dmaBufOnly = false;
#endif
if (!dmaBufOnly) GuestMemory::ImportWatched(base, bytes, [&] {
step = watchedDmaBuf == watchedHostPointer ? createImport(context, entry, result, state.dmaBufImportsCoherent) : createHostPointerImport(context, entry, result);
#ifdef _WIN32
if (step == nullptr && settled && (step = settleImport(context, state, entry, result)) != nullptr) {
@@ -2481,7 +2514,28 @@ const HostImport* importRunAt(const Context& context, HostImports& state, Import
return step == nullptr;
}, watchedHostPointer);
#ifndef _WIN32
if (step != nullptr && watchedDmaBuf != watchedHostPointer && state.dmaBufImportsCoherent) {
if (dmaBufOnly) {
GuestMemory::ImportWatched(base, bytes, [&] {
try {
step = createSharedBackingImport(context, entry, result);
} catch (const std::exception& error) {
throw DmaBufImportFailure(error.what());
}
return step == nullptr;
}, watchedDmaBuf);
if (step != nullptr && (std::strcmp(step, "UDMABUF_CREATE") == 0 || std::strcmp(step, "UDMABUF_CREATE_LIST") == 0)) {
if (requester == ImportRequester::ColorTarget && !watchedHostPointer) return failedImport();
std::fprintf(stderr, "[gpu] dma-buf import of 0x%llx+0x%llx refused by udmabuf; host-pointer import\n", static_cast<unsigned long long>(base), static_cast<unsigned long long>(bytes));
GuestMemory::ImportWatched(base, bytes, [&] {
step = createHostPointerImport(context, entry, result);
return step == nullptr;
}, watchedHostPointer);
} else if (step != nullptr) {
char message[160];
std::snprintf(message, sizeof(message), "AGC graphics: dma-buf import of 0x%llx+0x%llx failed at %s (%d)", static_cast<unsigned long long>(base), static_cast<unsigned long long>(bytes), step, static_cast<int>(result));
throw DmaBufImportFailure(message);
}
} else if (step != nullptr && watchedDmaBuf != watchedHostPointer && state.dmaBufImportsCoherent) {
int runsFile = -1;
std::array<GuestArena::SharedBackingRun, DmaBufRunLimit> runs{};
std::size_t count = 0;
@@ -2501,6 +2555,11 @@ const HostImport* importRunAt(const Context& context, HostImports& state, Import
entry.buffer = VK_NULL_HANDLE;
entry.memory = VK_NULL_HANDLE;
entry.chunk.reset();
if (dmaBufOnly) {
char message[160];
std::snprintf(message, sizeof(message), "AGC graphics: dma-buf import of 0x%llx+0x%llx failed at %s (%d)", static_cast<unsigned long long>(base), static_cast<unsigned long long>(bytes), step, static_cast<int>(result));
throw DmaBufImportFailure(message);
}
} else if (traceSettle) {
std::fprintf(stderr, "[gpu] settled the dma-buf import of 0x%llx+0x%llx on the settle queue in %.2f ms\n", static_cast<unsigned long long>(base), static_cast<unsigned long long>(bytes), std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count());
}
@@ -2545,6 +2604,7 @@ const HostImport* importRunAt(const Context& context, HostImports& state, Import
#endif
return failedImport();
}
if (requester == ImportRequester::ColorTarget && !GuestMemory::Watched(base, static_cast<std::size_t>(bytes))) return failedImport();
first = state.imports.lower_bound(base);
if (first != state.imports.begin() && std::prev(first)->second.base + std::prev(first)->second.bytes > base) --first;
std::vector<std::pair<std::uint64_t, std::uint64_t>> unwatched;
@@ -2931,6 +2991,123 @@ std::shared_ptr<Buffer> snapshotCopy(const Context& context, std::uint64_t addre
return buffer;
}
struct UploadCopies {
using Key = std::tuple<std::uint64_t, std::size_t, VkBufferUsageFlags>;
using Pieces = std::vector<std::pair<std::uint64_t, std::uint64_t>>;
AgcDriver::Mutex mutex;
VkDevice device = VK_NULL_HANDLE;
struct Entry {
std::shared_ptr<Buffer> buffer;
std::uint64_t generation = 0;
Pieces pieces;
std::list<Key>::iterator recent;
};
std::map<Key, Entry> entries;
std::list<Key> recency;
std::size_t bytes = 0;
};
std::size_t uploadCacheBudget() {
static const std::size_t bytes = [] {
const char* value = std::getenv("APS5_UPLOAD_CACHE_MIB");
return static_cast<std::size_t>(value != nullptr ? std::strtoull(value, nullptr, 10) : 512ull) << 20u;
}();
return bytes;
}
constexpr std::size_t uploadCacheEntries = 256;
UploadCopies& UploadCopyCache() {
static UploadCopies copies;
return copies;
}
void resetUploadCache(UploadCopies& copies, VkDevice device) {
copies.entries.clear();
copies.recency.clear();
copies.bytes = 0;
copies.device = device;
}
std::uint64_t collectUploadWrites(std::uint64_t begin, bool sparse, const UploadCopies::Pieces& backed, std::size_t bytes) {
if (!GuestMemory::WriteWatched()) return 0;
if (!sparse) return GuestMemory::CollectWrites(begin, bytes);
std::uint64_t generation = 0;
for (const auto& [first, last] : backed) {
generation = GuestMemory::CollectWrites(first, static_cast<std::size_t>(last - first));
if (generation == 0) return 0;
}
return generation;
}
bool uploadUnchanged(std::uint64_t begin, bool sparse, const UploadCopies::Pieces& backed, std::size_t bytes, std::uint64_t generation) {
if (generation == 0) return false;
if (!sparse) return GuestMemory::CollectWritesUncached(begin, bytes) != 0 && GuestMemory::UnchangedSince(begin, bytes, generation);
for (const auto& [first, last] : backed) {
const auto size = static_cast<std::size_t>(last - first);
if (GuestMemory::CollectWritesUncached(first, size) == 0 || !GuestMemory::UnchangedSince(first, size, generation)) return false;
}
return true;
}
std::shared_ptr<Buffer> findUploaded(const Context& context, std::uint64_t begin, bool sparse, const UploadCopies::Pieces& backed, std::size_t bytes, VkBufferUsageFlags usage, std::uint64_t& generation) {
generation = 0;
if (uploadCacheBudget() == 0) return nullptr;
auto& copies = UploadCopyCache();
const UploadCopies::Key key{begin, bytes, usage};
{
std::lock_guard lock(copies.mutex);
if (copies.device != context.device) {
resetUploadCache(copies, context.device);
return nullptr;
}
const auto found = copies.entries.find(key);
if (found == copies.entries.end() || found->second.pieces != backed) return nullptr;
generation = found->second.generation;
}
if (!uploadUnchanged(begin, sparse, backed, bytes, generation)) return nullptr;
std::lock_guard lock(copies.mutex);
const auto found = copies.entries.find(key);
if (found == copies.entries.end() || found->second.generation != generation) return nullptr;
copies.recency.splice(copies.recency.end(), copies.recency, found->second.recent);
return found->second.buffer;
}
void insertUploaded(const Context& context, std::uint64_t begin, const UploadCopies::Pieces& backed, std::size_t bytes, VkBufferUsageFlags usage, const std::shared_ptr<Buffer>& buffer, std::uint64_t generation) {
const auto budget = uploadCacheBudget();
if (budget == 0 || generation == 0 || bytes > budget) return;
auto& copies = UploadCopyCache();
const UploadCopies::Key key{begin, bytes, usage};
std::lock_guard lock(copies.mutex);
if (copies.device != context.device) resetUploadCache(copies, context.device);
if (const auto found = copies.entries.find(key); found != copies.entries.end()) {
copies.recency.erase(found->second.recent);
copies.bytes -= std::get<1>(found->first);
copies.entries.erase(found);
}
while (!copies.recency.empty() && (copies.bytes + bytes > budget || copies.entries.size() >= uploadCacheEntries)) {
const auto oldest = copies.entries.find(copies.recency.front());
copies.bytes -= std::get<1>(oldest->first);
copies.entries.erase(oldest);
copies.recency.pop_front();
}
copies.recency.push_back(key);
copies.entries.emplace(key, UploadCopies::Entry{buffer, generation, backed, std::prev(copies.recency.end())});
copies.bytes += bytes;
}
void forgetUploaded(const Context& context, std::uint64_t begin, std::size_t bytes, VkBufferUsageFlags usage) {
auto& copies = UploadCopyCache();
std::lock_guard lock(copies.mutex);
if (copies.device != context.device) return;
const UploadCopies::Key key{begin, bytes, usage};
if (const auto found = copies.entries.find(key); found != copies.entries.end()) {
copies.recency.erase(found->second.recent);
copies.bytes -= std::get<1>(found->first);
copies.entries.erase(found);
}
}
bool mirrorsEnabled() {
static const bool disabled = std::getenv("APS5_NO_LEASE_MIRROR") != nullptr;
return !disabled;
@@ -4473,12 +4650,20 @@ ImportWatch PrepareImportWatch(const Context& context) {
return state.unwatchImports ? ImportWatch::Unwatch : ImportWatch::Watch;
}
bool DmaBufImportSelected(const Context& context) {
auto& state = Imports();
std::lock_guard lock(state.mutex);
decideImportWatch(context, state);
return state.dmaBufSelected;
}
void SetImportWatch(const Context& context, ImportWatch watch) {
auto& state = Imports();
std::lock_guard lock(state.mutex);
state.watchDevice = context.device;
state.unwatchImports = watch == ImportWatch::Unwatch;
state.unwatchDmaBufImports = state.unwatchImports;
state.dmaBufSelected = false;
state.gateRefusals.clear();
}
@@ -4717,6 +4902,15 @@ bool ImportsHeldByThisThread() {
return importsHeld != 0;
}
bool HostImportUsesDmaBuf(const Context& context, std::uint64_t address, std::size_t bytes) {
if (context.hostImportAlignment == 0 || bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address) return false;
auto& state = Imports();
std::lock_guard lock(state.mutex);
if (importsStale(context, state)) return false;
const auto* entry = peekImport(state, address, address + bytes);
return entry != nullptr && entry->dmaBuf;
}
const HostImport* ExistingHostImportFor(const Context& context, std::uint64_t address, std::size_t bytes) {
if (context.hostImportAlignment == 0 || bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address) return nullptr;
auto& state = Imports();
@@ -4858,6 +5052,8 @@ bool ImportMappedRanges(const Context& context, const GuestAllocations::Mapped&
}
if (!state.importedAtMap.emplace(range->address, range->bytes).second && findImport(state, range->address, range->address + range->bytes) == nullptr) continue;
importAllocation(context, state, range->address, current, ImportRequester::Map, 0, false);
} catch (const DmaBufImportFailure&) {
throw;
} catch (const std::exception& error) {
std::fprintf(stderr, "[gpu] import of GPU memory mapped at 0x%llx+0x%zx failed: %s\n", static_cast<unsigned long long>(range->address), range->bytes, error.what());
}
@@ -4899,6 +5095,16 @@ bool HostImportCovers(const Context& context, std::uint64_t address, std::size_t
return state.device == context.device && peekImport(state, address, address + bytes) != nullptr;
}
bool HostImportOverlaps(const Context& context, std::uint64_t address, std::size_t bytes) {
if (context.hostImportAlignment == 0 || bytes == 0 || bytes > std::numeric_limits<std::uint64_t>::max() - address) return false;
auto& state = Imports();
std::lock_guard lock(state.mutex);
if (state.device != context.device) return false;
const auto next = state.imports.lower_bound(address);
if (next != state.imports.end() && next->first < address + bytes) return true;
return next != state.imports.begin() && std::prev(next)->second.base + std::prev(next)->second.bytes > address;
}
bool ComparedHostImportCovers(const Context& context, std::uint64_t address, std::size_t bytes) {
#ifdef _WIN32
static_cast<void>(context);
@@ -5598,6 +5804,7 @@ void GuestBufferMemory::AddReadable(std::uint64_t address, std::size_t bytes) {
// direct-write mark, and UploadPrepare copies it without the device lock. A written descriptor
// overlapping the range still covers it through its own Writes() entry.
addDescriptorRegion(address, bytes, false, false, true);
reads.emplace_back(address, address + bytes);
}
bool GuestBufferMemory::SpaceOnly() const {
@@ -5647,6 +5854,12 @@ void ClearRetainedSpaces(VkDevice device) {
pruneRetained([device](const RetainedAddressSpace& node) { return node.device == device; });
}
void ClearUploadCopies(VkDevice device) {
auto& copies = UploadCopyCache();
std::lock_guard lock(copies.mutex);
if (copies.device == device) resetUploadCache(copies, VK_NULL_HANDLE);
}
std::size_t RetainedSpaceCount() {
std::size_t count = 0;
pruneRetained([&count](const RetainedAddressSpace&) {
@@ -5986,6 +6199,15 @@ CopyStats& Copies() {
// region takes the path it would take without staging (Region::unstaged).
std::atomic<bool> deviceLocalFullForTests{false};
std::atomic<std::uint64_t> liveShadowBytes{0};
std::atomic<std::uint64_t> liveShadowLimit{std::numeric_limits<std::uint64_t>::max()};
std::uint64_t shadowBytesLimit(std::uint64_t heapBytes) {
static const char* const setting = std::getenv("APS5_STAGING_SHADOW_MAX_MIB");
if (setting != nullptr) return std::strtoull(setting, nullptr, 10) << 20u;
return std::max<std::uint64_t>(std::uint64_t{256} << 20u, heapBytes / 16u);
}
bool deviceLocalHasRoom(const Context& context, std::size_t bytes) {
if (deviceLocalFullForTests.load(std::memory_order_relaxed)) return false;
static std::atomic<std::int64_t> checkedMs{std::numeric_limits<std::int64_t>::min()};
@@ -6001,18 +6223,26 @@ bool deviceLocalHasRoom(const Context& context, std::size_t bytes) {
const auto budget = reported.heapBudget[heap];
const auto usage = reported.heapUsage[heap];
room.store(budget == 0 ? std::numeric_limits<std::uint64_t>::max() : usage + budget / 8u < budget ? budget - budget / 8u - usage : 0u, std::memory_order_relaxed);
liveShadowLimit.store(shadowBytesLimit(budget != 0 ? budget : context.memory.memoryHeaps[heap].size), std::memory_order_relaxed);
checkedMs.store(nowMs, std::memory_order_relaxed);
}
return bytes <= room.load(std::memory_order_relaxed);
}
std::shared_ptr<Buffer> stagingBuffer(const Context& context, std::size_t bytes, VkBufferUsageFlags usage) {
if (!deviceLocalHasRoom(context, bytes)) {
if (!deviceLocalHasRoom(context, bytes) || liveShadowBytes.load(std::memory_order_relaxed) + bytes > liveShadowLimit.load(std::memory_order_relaxed)) {
Copies().stagingRefused.fetch_add(1, std::memory_order_relaxed);
return nullptr;
}
try {
if (auto buffer = Buffer::WithinDeviceLocalHeadroom(context, bytes, usage)) return buffer;
if (auto buffer = Buffer::WithinDeviceLocalHeadroom(context, bytes, usage)) {
liveShadowBytes.fetch_add(bytes, std::memory_order_relaxed);
auto* shadow = buffer.get();
return std::shared_ptr<Buffer>(shadow, [owner = std::move(buffer), bytes](Buffer*) mutable {
owner.reset();
liveShadowBytes.fetch_sub(bytes, std::memory_order_relaxed);
});
}
static std::atomic<int> reported{0};
if (reported.fetch_add(1, std::memory_order_relaxed) < 4) std::fprintf(stderr, "[buffers] staging shadow of %zu bytes refused: its device-local heap is within an eighth of its budget\n", bytes);
Copies().stagingRefused.fetch_add(1, std::memory_order_relaxed);
@@ -6078,7 +6308,7 @@ void reportStaging() {
const auto staged = stats.staged.load();
const auto in = stats.stagedInBytes.load();
const auto out = stats.stagedOutBytes.load();
AgcDriver::ProfilePrint_nid_no_patch("[buffers] staging: %llu regions staged device-local (%llu with atomics, %llu of reused builds), %.0f KiB copied in, %.0f KiB copied back, %llu without copy-back, %llu shadows refused; last 10 s: %llu regions, %.0f KiB in, %.0f KiB back\n", static_cast<unsigned long long>(staged), static_cast<unsigned long long>(stats.stagedAtomic.load()), static_cast<unsigned long long>(stats.stagedReused.load()), in / 1024.0, out / 1024.0, static_cast<unsigned long long>(stats.stagedLost.load()), static_cast<unsigned long long>(stats.stagingRefused.load()), static_cast<unsigned long long>(staged - lastStaged), (in - lastIn) / 1024.0, (out - lastOut) / 1024.0);
AgcDriver::ProfilePrint_nid_no_patch("[buffers] staging: %llu regions staged device-local (%llu with atomics, %llu of reused builds), %.0f KiB copied in, %.0f KiB copied back, %llu without copy-back, %llu shadows refused, %llu MiB in live shadows (limit %llu MiB); last 10 s: %llu regions, %.0f KiB in, %.0f KiB back\n", static_cast<unsigned long long>(staged), static_cast<unsigned long long>(stats.stagedAtomic.load()), static_cast<unsigned long long>(stats.stagedReused.load()), in / 1024.0, out / 1024.0, static_cast<unsigned long long>(stats.stagedLost.load()), static_cast<unsigned long long>(stats.stagingRefused.load()), static_cast<unsigned long long>(liveShadowBytes.load() >> 20u), static_cast<unsigned long long>(liveShadowLimit.load() >> 20u), static_cast<unsigned long long>(staged - lastStaged), (in - lastIn) / 1024.0, (out - lastOut) / 1024.0);
lastStaged = staged;
lastIn = in;
lastOut = out;
@@ -6388,6 +6618,7 @@ void GuestBufferMemory::UploadFinish(bool addressable, std::optional<std::pair<s
Require(prepared && !uploaded, "guest memory upload was not prepared");
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
const auto started = std::chrono::steady_clock::now();
if (addressable) StoreDepthExpandWrites(context);
for (const auto& region : regions) CompletePendingCpuWrites(context, region.begin, static_cast<std::size_t>(region.end - region.begin));
if (space != nullptr) completeSpaceWrites();
uploaded = true;
@@ -6407,6 +6638,9 @@ void GuestBufferMemory::UploadFinish(bool addressable, std::optional<std::pair<s
for (const auto& region : regions) static_cast<void>(FlushDepthPlanes(region.begin, static_cast<std::size_t>(region.end - region.begin)));
for (const auto& [begin, end] : writes) RequireNoResidentDepthRead_nid_no_patch(begin, static_cast<std::size_t>(end - begin), htileClear);
for (const auto& [begin, end] : writes) StorageTexture::FlushPending(begin, static_cast<std::size_t>(end - begin), nullptr, "written buffer range");
if (addressable) {
for (const auto& [begin, end] : reads) StorageTexture::FlushPending(begin, static_cast<std::size_t>(end - begin), nullptr, "imported buffer region");
}
if (context.hostImportAlignment != 0) {
auto& state = Imports();
std::lock_guard lock(state.mutex);
@@ -6603,6 +6837,7 @@ void GuestBufferMemory::UploadFinish(bool addressable, std::optional<std::pair<s
copyRegion(region, addressable);
if (profile) copyUs += microsecondsSince(copyStart);
}
if (addressable) StoreDepthExpandWrites(context);
if (heapsEnd > heapsBegin) StorageTexture::PublishShadowsOnly(heapsBegin, static_cast<std::size_t>(heapsEnd - heapsBegin), PublishScope::Whole, "address-based heaps");
if (!gpuCopies.empty()) recordGpuCopies(gpuCopies, addressable);
takeHeapReferences();
@@ -6658,6 +6893,40 @@ void GuestBufferMemory::copyRegion(Region& region, bool addressable) {
region.bufferEnd = end < region.end ? end : 0;
}
const auto allocated = region.bufferEnd != 0 ? region.bufferEnd - region.begin : bytes;
const bool written = region.writable && WritesOverlap(region.begin, static_cast<std::size_t>(bytes));
const bool cacheable = region.buffer == nullptr && (region.hostBacked || region.writable) && !written;
std::uint64_t uploadGeneration = 0;
if (cacheable) {
if (auto cached = findUploaded(context, region.begin, region.sparse, region.backed, static_cast<std::size_t>(allocated), usage, uploadGeneration)) {
bool unchanged = true;
{
const GuestMemory::ReadSiteScope site(GuestMemory::ReadSite::BufferUpload);
if (const auto hook = GuestMemory::CurrentFlushHook()) {
if (!region.sparse) {
hook(region.begin, static_cast<std::size_t>(allocated));
} else {
for (const auto& [first, last] : region.backed) hook(first, static_cast<std::size_t>(last - first));
}
unchanged = uploadUnchanged(region.begin, region.sparse, region.backed, static_cast<std::size_t>(allocated), uploadGeneration);
}
}
if (unchanged) {
region.buffer = std::move(cached);
region.snapshot.clear();
static std::atomic<std::uint64_t> hits{0}, hitBytes{0};
const auto hit = hits.fetch_add(1, std::memory_order_relaxed) + 1;
hitBytes.fetch_add(allocated, std::memory_order_relaxed);
if (profile && hit % 1000 == 0) {
AgcDriver::ProfilePrint_nid_no_patch("[buffers] %llu upload cache hits, %.0f MiB served\n", static_cast<unsigned long long>(hit), static_cast<double>(hitBytes.load(std::memory_order_relaxed)) / 1048576.0);
}
return;
}
forgetUploaded(context, region.begin, static_cast<std::size_t>(allocated), usage);
}
uploadGeneration = collectUploadWrites(region.begin, region.sparse, region.backed, static_cast<std::size_t>(allocated));
} else if (written) {
forgetUploaded(context, region.begin, static_cast<std::size_t>(allocated), usage);
}
// A buffer made by UploadPrepare for a GPU copy that fell back here (its import went) is kept.
const bool shared = region.buffer == nullptr && !region.hostBacked && !region.writable && !region.sparse && region.bufferEnd == 0 && region.snapshot.size() == bytes;
if (shared) region.buffer = snapshotCopy(context, region.begin, region.snapshot, usage);
@@ -6669,7 +6938,6 @@ void GuestBufferMemory::copyRegion(Region& region, bool addressable) {
if (region.hostBacked || region.writable) {
// Only ranges a descriptor may write need the copy the write-back diffs against; the
// registered ranges of an address-based shader are read-only to it (AddressRanges).
const bool written = region.writable && WritesOverlap(region.begin, static_cast<std::size_t>(bytes));
if (!region.sparse) {
GuestMemory::Read(region.begin, region.buffer->Bytes());
readBytes += region.buffer->Bytes().size();
@@ -6695,6 +6963,7 @@ void GuestBufferMemory::copyRegion(Region& region, bool addressable) {
readBytes += region.snapshot.size();
}
region.snapshot.clear();
if (uploadGeneration != 0 && uploadUnchanged(region.begin, region.sparse, region.backed, static_cast<std::size_t>(allocated), uploadGeneration)) insertUploaded(context, region.begin, region.backed, static_cast<std::size_t>(allocated), usage, region.buffer, uploadGeneration);
if (profile) readUs.fetch_add(microsecondsSince(readStart), std::memory_order_relaxed);
if (profile) {
static AgcDriver::Mutex reasonsMutex;
@@ -96,7 +96,7 @@ void TextureDetiler::DispatchMultisampleReadback(VkCommandBuffer commands, VkFor
{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, set, 1u, 0u, 1u, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, &image, nullptr, nullptr}
}};
context.Function<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(context.device, static_cast<std::uint32_t>(writes.size()), writes.data(), 0u, nullptr);
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
context.BindComputePipeline(commands, pipeline);
context.Function<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, readbackPipelineLayout, 0u, 1u, &set, 0u, nullptr);
const std::array<std::uint32_t, 7> push{width, height, layers, fragments, firstElement, elements, static_cast<std::uint32_t>(groupsX * 64u)};
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, readbackPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data());
@@ -1938,6 +1938,28 @@ void RetireMultisampleColorTarget(const std::shared_ptr<std::atomic<bool>>& acti
anyGuarded().store(!guarded().empty(), std::memory_order_release);
}
void RetireMultisampleColorTargetsOnFmaskWrite(std::uint64_t address, std::size_t bytes) {
if (bytes == 0 || !anyGuarded().load(std::memory_order_acquire)) return;
std::unique_lock lock(guardedMutex());
bool changed = false;
std::vector<std::shared_ptr<std::atomic<bool>>> retired;
for (const auto& range : guarded()) {
if (!range.fmask && range.plane != fmaskPlane) continue;
if (!range.use->hostOnly.load(std::memory_order_acquire) || range.use->claimed.load(std::memory_order_acquire)) continue;
if (address > range.address || range.address + range.bytes > address + bytes) continue;
if (std::find(retired.begin(), retired.end(), range.active) == retired.end()) retired.push_back(range.active);
}
if (retired.empty()) return;
for (const auto& active : retired) active->store(false, std::memory_order_release);
std::erase_if(guarded(), [&](const auto& range) {
if (std::find(retired.begin(), retired.end(), range.active) == retired.end()) return false;
if (range.metadataValid) range.metadataValid->store(false, std::memory_order_release);
return true;
});
guardedGeneration().fetch_add(1, std::memory_order_release);
anyGuarded().store(!guarded().empty(), std::memory_order_release);
}
std::vector<std::pair<std::uint64_t, std::uint64_t>> HostOnlySampleRanges(std::uint64_t address, std::size_t bytes) {
std::vector<std::pair<std::uint64_t, std::uint64_t>> ranges;
AppendHostWrittenDepthRanges(address, bytes, ranges);
@@ -58,7 +58,7 @@ void TextureDetiler::DispatchMultisampleImage(VkCommandBuffer commands, std::uin
const VkDescriptorImageInfo image{VK_NULL_HANDLE, arrayView, VK_IMAGE_LAYOUT_GENERAL};
const std::array<VkWriteDescriptorSet, 2> writes{{{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, set, 0u, 0u, 1u, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, nullptr, &buffer, nullptr}, {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, set, 1u, 0u, 1u, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &image, nullptr, nullptr}}};
context.Function<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(context.device, 2u, writes.data(), 0u, nullptr);
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target);
context.BindComputePipeline(commands, target);
context.Function<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0u, 1u, &set, 0u, nullptr);
const std::array<std::uint32_t, 7> push{width, height, layers, fragments, firstElement, elements, static_cast<std::uint32_t>(groupsX * 64u)};
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0u, sizeof(push), push.data());
@@ -9,6 +9,7 @@
#include "prx/libSceAgcDriver/Graphics/include/PatchVertexLayer.hpp"
#include "prx/libSceAgcDriver/Graphics/include/PipelineSpecialization.hpp"
#include "prx/libSceAgcDriver/Graphics/include/SampleOrder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/VertexInput.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include "prx/libSceAgcDriver/Execution/include/Mutex.hpp"
@@ -19,9 +20,11 @@
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <list>
#include <mutex>
#include <spirv/unified1/spirv.hpp>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
@@ -243,6 +246,10 @@ void ValidateProvokingVertex(const Context& context, const State& state, std::sp
});
if (!context.provokingVertexLast && !observed) return;
Require(context.provokingVertexLast, "last provoking vertex requires VK_EXT_provoking_vertex with provokingVertexLast enabled");
for (const auto& shader : shaders) {
if (shader.stage != ShaderRecompiler::ShaderStage::Fragment || shader.program == nullptr) continue;
Require(std::none_of(shader.program->fragmentParameters.begin(), shader.program->fragmentParameters.end(), [](const ShaderRecompiler::FragmentParameter& parameter) { return parameter.flat && parameter.custom; }), "last provoking vertex is unsupported for a pass-through input read only at P0, which takes the first vertex's value as a flat input");
}
const bool meshPrimitives = state.stages.path == ShaderPath::Geometry && state.stages.mesh;
Require(!state.stages.tessellation && (meshPrimitives || (state.stages.path == ShaderPath::Vertex && !state.stages.mesh)), "last provoking vertex is unsupported for generated primitive pipelines");
Require(state.rectList || state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, "last provoking vertex is unsupported for this primitive topology");
@@ -684,6 +691,7 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput
if (depthBias) dynamicStates.push_back(VK_DYNAMIC_STATE_DEPTH_BIAS);
if (libraries) dynamicStates.assign(PipelineLibraryDynamicStates().begin(), PipelineLibraryDynamicStates().end());
if (context.dynamicColorWriteMask) dynamicStates.push_back(VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT);
dynamicSlots = CommandState::DynamicSlots(dynamicStates);
VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
dynamic.dynamicStateCount = static_cast<std::uint32_t>(dynamicStates.size());
dynamic.pDynamicStates = dynamicStates.data();
@@ -934,7 +942,8 @@ std::shared_ptr<Framebuffer> Pipeline::AcquireFramebuffer(std::span<const VkImag
return framebuffer;
}
void Pipeline::Begin(VkCommandBuffer commands, const Framebuffer& framebuffer, VkExtent2D extent, const State& state, const State* masked) const {
void Pipeline::Begin(CommandState& recording, const Framebuffer& framebuffer, VkExtent2D extent, const State& state, const State* masked) const {
const auto commands = recording.Commands();
if (dynamicRendering) {
const auto views = framebuffer.Views();
Require(views.size() == attachments, "render targets do not match the pipeline's attachments");
@@ -962,7 +971,7 @@ void Pipeline::Begin(VkCommandBuffer commands, const Framebuffer& framebuffer, V
if (outputs && depthFormat != VK_FORMAT_UNDEFINED) rendering.pDepthAttachment = &depth;
if (outputs && depthFormat != VK_FORMAT_UNDEFINED && HasStencil(depthFormat)) rendering.pStencilAttachment = &depth;
context.Resolved(&DeviceFunctions::cmdBeginRendering, "vkCmdBeginRenderingKHR")(commands, &rendering);
Continue(commands, state, masked);
Continue(recording, state, masked);
return;
}
VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
@@ -981,67 +990,73 @@ void Pipeline::Begin(VkCommandBuffer commands, const Framebuffer& framebuffer, V
sampleLocations.pPostSubpassSampleLocations = &post;
if (sampleLocationsEnabled) begin.pNext = &sampleLocations;
context.Resolved(&DeviceFunctions::cmdBeginRenderPass, "vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
Continue(commands, state, masked);
Continue(recording, state, masked);
}
void Pipeline::Continue(VkCommandBuffer commands, const State& state, const State* masked) const {
void Pipeline::Continue(CommandState& recording, const State& state, const State* masked) const {
if (optimized != nullptr) optimized->Schedule();
const auto best = optimized != nullptr ? optimized->handle.load() : VK_NULL_HANDLE;
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, best != VK_NULL_HANDLE ? best : pipeline);
context.Resolved(&DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &state.viewport);
context.Resolved(&DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &state.scissor);
setColorWriteMasks(commands, state, masked, false);
if (state.stencilReplayReference) context.Resolved(&DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, VK_STENCIL_FACE_FRONT_AND_BACK, *state.stencilReplayReference);
recording.BindPipeline(context, best != VK_NULL_HANDLE ? best : pipeline, dynamicSlots);
recording.SetViewport(context, state.viewport);
recording.SetScissor(context, state.scissor);
setColorWriteMasks(recording, state, masked, false);
if (state.stencilReplayReference) recording.SetStencilReference(context, VK_STENCIL_FACE_FRONT_AND_BACK, *state.stencilReplayReference);
if (libraries) {
setLibraryState(commands, state);
setLibraryState(recording, state);
return;
}
if (depthBias) context.Resolved(&DeviceFunctions::cmdSetDepthBias, "vkCmdSetDepthBias")(commands, HostDepthBiasConstant(context, state.depth->format, state.depthBiasConstant), state.depthBiasClamp, state.depthBiasSlope);
if (depthBias) recording.SetDepthBias(context, HostDepthBiasConstant(context, state.depth->format, state.depthBiasConstant), state.depthBiasClamp, state.depthBiasSlope);
if (!depthBounds) return;
context.Resolved(&DeviceFunctions::cmdSetDepthBounds, "vkCmdSetDepthBounds")(commands, state.minDepthBounds, state.maxDepthBounds);
recording.SetDepthBounds(context, state.minDepthBounds, state.maxDepthBounds);
}
void Pipeline::setLibraryState(VkCommandBuffer commands, const State& state) const {
void Pipeline::setLibraryState(CommandState& recording, const State& state) const {
const bool depth = state.depth.has_value();
context.Resolved(&DeviceFunctions::cmdSetCullMode, "vkCmdSetCullModeEXT")(commands, state.cullMode);
context.Resolved(&DeviceFunctions::cmdSetFrontFace, "vkCmdSetFrontFaceEXT")(commands, state.frontFace);
context.Resolved(&DeviceFunctions::cmdSetDepthBias, "vkCmdSetDepthBias")(commands, depthBias ? HostDepthBiasConstant(context, state.depth->format, state.depthBiasConstant) : 0.0f, depthBias ? state.depthBiasClamp : 0.0f, depthBias ? state.depthBiasSlope : 0.0f);
context.Resolved(&DeviceFunctions::cmdSetDepthBounds, "vkCmdSetDepthBounds")(commands, depthBounds ? state.minDepthBounds : 0.0f, depthBounds ? state.maxDepthBounds : 1.0f);
context.Resolved(&DeviceFunctions::cmdSetDepthTestEnable, "vkCmdSetDepthTestEnableEXT")(commands, depth && state.depthTest);
context.Resolved(&DeviceFunctions::cmdSetDepthWriteEnable, "vkCmdSetDepthWriteEnableEXT")(commands, depth && state.depthWrite);
context.Resolved(&DeviceFunctions::cmdSetDepthCompareOp, "vkCmdSetDepthCompareOpEXT")(commands, depth ? state.depthCompare : VK_COMPARE_OP_ALWAYS);
context.Resolved(&DeviceFunctions::cmdSetDepthBoundsTestEnable, "vkCmdSetDepthBoundsTestEnableEXT")(commands, depthBounds);
context.Resolved(&DeviceFunctions::cmdSetStencilTestEnable, "vkCmdSetStencilTestEnableEXT")(commands, depth && state.stencilTest);
recording.SetCullMode(context, state.cullMode);
recording.SetFrontFace(context, state.frontFace);
recording.SetDepthBias(context, depthBias ? HostDepthBiasConstant(context, state.depth->format, state.depthBiasConstant) : 0.0f, depthBias ? state.depthBiasClamp : 0.0f, depthBias ? state.depthBiasSlope : 0.0f);
recording.SetDepthBounds(context, depthBounds ? state.minDepthBounds : 0.0f, depthBounds ? state.maxDepthBounds : 1.0f);
recording.SetDepthTestEnable(context, depth && state.depthTest);
recording.SetDepthWriteEnable(context, depth && state.depthWrite);
recording.SetDepthCompareOp(context, depth ? state.depthCompare : VK_COMPARE_OP_ALWAYS);
recording.SetDepthBoundsTestEnable(context, depthBounds);
recording.SetStencilTestEnable(context, depth && state.stencilTest);
const auto stencil = [&](VkStencilFaceFlags face, const VkStencilOpState& op) {
context.Resolved(&DeviceFunctions::cmdSetStencilOp, "vkCmdSetStencilOpEXT")(commands, face, op.failOp, op.passOp, op.depthFailOp, op.compareOp);
context.Resolved(&DeviceFunctions::cmdSetStencilCompareMask, "vkCmdSetStencilCompareMask")(commands, face, op.compareMask);
context.Resolved(&DeviceFunctions::cmdSetStencilWriteMask, "vkCmdSetStencilWriteMask")(commands, face, op.writeMask);
context.Resolved(&DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, face, op.reference);
recording.SetStencilOp(context, face, op.failOp, op.passOp, op.depthFailOp, op.compareOp);
recording.SetStencilCompareMask(context, face, op.compareMask);
recording.SetStencilWriteMask(context, face, op.writeMask);
recording.SetStencilReference(context, face, op.reference);
};
stencil(VK_STENCIL_FACE_FRONT_BIT, depth ? state.stencilFront : VkStencilOpState{});
stencil(VK_STENCIL_FACE_BACK_BIT, depth ? state.stencilBack : VkStencilOpState{});
const auto front = depth ? state.stencilFront : VkStencilOpState{};
const auto back = depth ? state.stencilBack : VkStencilOpState{};
if (std::memcmp(&front, &back, sizeof(front)) == 0) {
stencil(VK_STENCIL_FACE_FRONT_AND_BACK, front);
return;
}
stencil(VK_STENCIL_FACE_FRONT_BIT, front);
stencil(VK_STENCIL_FACE_BACK_BIT, back);
}
void Pipeline::ContinueSecondChannel(VkCommandBuffer commands, const State& state, const State* masked) const {
void Pipeline::ContinueSecondChannel(CommandState& recording, const State& state, const State* masked) const {
Require(secondChannel != VK_NULL_HANDLE, "the pipeline blends every channel in one pass");
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, secondChannel);
setColorWriteMasks(commands, state, masked, true);
recording.BindPipeline(context, secondChannel, dynamicSlots);
setColorWriteMasks(recording, state, masked, true);
}
void Pipeline::setColorWriteMasks(VkCommandBuffer commands, const State& state, const State* masked, bool secondChannel) const {
void Pipeline::setColorWriteMasks(CommandState& recording, const State& state, const State* masked, bool secondChannel) const {
if (!context.dynamicColorWriteMask || state.blends.empty()) return;
const auto masks = channelWriteMasks(state, masked != nullptr ? std::span(masked->blends) : std::span(state.blends), secondChannel);
context.Resolved(&DeviceFunctions::cmdSetColorWriteMask, "vkCmdSetColorWriteMaskEXT")(commands, 0, static_cast<std::uint32_t>(state.blends.size()), masks.data());
recording.SetColorWriteMasks(context, std::span(masks).first(state.blends.size()));
}
void Pipeline::ContinueBackFaces(VkCommandBuffer commands, const State& state, const State* masked) const {
void Pipeline::ContinueBackFaces(CommandState& recording, const State& state, const State* masked) const {
Require(backFaces != VK_NULL_HANDLE, "the pipeline draws both faces in one pass");
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, backFaces);
setColorWriteMasks(commands, state, masked, false);
context.Resolved(&DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &state.viewport);
context.Resolved(&DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &state.scissor);
context.Resolved(&DeviceFunctions::cmdSetDepthBias, "vkCmdSetDepthBias")(commands, HostDepthBiasConstant(context, state.depth->format, state.backDepthBiasConstant), state.depthBiasClamp, state.backDepthBiasSlope);
if (depthBounds) context.Resolved(&DeviceFunctions::cmdSetDepthBounds, "vkCmdSetDepthBounds")(commands, state.minDepthBounds, state.maxDepthBounds);
recording.BindPipeline(context, backFaces, dynamicSlots);
setColorWriteMasks(recording, state, masked, false);
recording.SetViewport(context, state.viewport);
recording.SetScissor(context, state.scissor);
recording.SetDepthBias(context, HostDepthBiasConstant(context, state.depth->format, state.backDepthBiasConstant), state.depthBiasClamp, state.backDepthBiasSlope);
if (depthBounds) recording.SetDepthBounds(context, state.minDepthBounds, state.maxDepthBounds);
}
void Pipeline::PushConstants(VkCommandBuffer commands, VkShaderStageFlags stages, std::span<const std::byte, PipelinePushConstantBytes> bytes) const {
@@ -1056,11 +1071,44 @@ void Pipeline::PushConstants(VkCommandBuffer commands, VkShaderStageFlags stages
namespace {
class KeyWriter {
public:
KeyWriter(std::vector<std::byte>& storage, std::size_t capacity) {
if (storage.size() < capacity) storage.resize(capacity);
begin = out = storage.data();
end = begin + capacity;
}
template<typename TValue>
void Put(const TValue& value) {
static_assert(std::is_trivially_copyable_v<TValue>);
reserve(sizeof(TValue));
std::memcpy(out, &value, sizeof(TValue));
out += sizeof(TValue);
}
void PutBytes(const void* data, std::size_t bytes) {
if (bytes == 0) return;
reserve(bytes);
std::memcpy(out, data, bytes);
out += bytes;
}
std::size_t Length() const { return static_cast<std::size_t>(out - begin); }
private:
void reserve(std::size_t bytes) const {
if (bytes > static_cast<std::size_t>(end - out)) [[unlikely]] throw std::length_error("pipeline key larger than its buffer");
}
std::byte* begin;
std::byte* out;
std::byte* end;
};
template<typename TValue>
void append(std::vector<std::byte>& key, const TValue& value) {
static_assert(std::is_trivially_copyable_v<TValue>);
const auto bytes = std::as_bytes(std::span(&value, 1));
key.insert(key.end(), bytes.begin(), bytes.end());
void append(KeyWriter& key, const TValue& value) {
key.Put(value);
}
// Everything the Pipeline objects are built from, or empty when a stage's result has no module
@@ -1069,18 +1117,16 @@ void append(std::vector<std::byte>& key, const TValue& value) {
// replay insert an entry a later draw finds; a generated stage (rect-list pair, geometry) is keyed
// by its identity like the others, so a replayed pipeline built from another device's generated
// module is missed rather than used.
void pipelineKey(std::vector<std::byte>& key, const Context& context, const State& state, const VertexInputLayout& input, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout) {
key.clear();
std::size_t pipelineKey(std::vector<std::byte>& storage, const Context& context, const State& state, const VertexInputLayout& input, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout) {
const auto capacity = 512 + sizeof(State) + sizeof(Context) + shaders.size() * 64 + input.bindings.size() * sizeof(VkVertexInputBindingDescription) + input.attributes.size() * sizeof(VkVertexInputAttributeDescription) + resources.mainKey.size_bytes() + resources.fragmentKey.size_bytes() + state.blends.size() * sizeof(VkPipelineColorBlendAttachmentState) + state.colors.size() * 64;
KeyWriter key(storage, capacity);
append(key, context.device);
append(key, attachmentLayout);
append(key, shaders.size());
for (const auto& shader : shaders) {
Require(shader.program != nullptr, "missing compiled shader");
const auto identity = shader.program->Identity();
if (identity.Empty()) {
key.clear();
return;
}
if (identity.Empty()) return 0;
append(key, shader.stage);
append(key, identity.low);
append(key, identity.high);
@@ -1091,22 +1137,15 @@ void pipelineKey(std::vector<std::byte>& key, const Context& context, const Stat
append(key, state.meshLayerCount);
append(key, PushConstantStages(shaders));
append(key, input.bindings.size());
for (const auto& binding : input.bindings) {
append(key, binding.binding);
append(key, binding.stride);
append(key, binding.inputRate);
}
static_assert(sizeof(VkVertexInputBindingDescription) == 3 * sizeof(std::uint32_t) && offsetof(VkVertexInputBindingDescription, binding) == 0 && offsetof(VkVertexInputBindingDescription, stride) == 4 && offsetof(VkVertexInputBindingDescription, inputRate) == 8 && sizeof(VkVertexInputRate) == sizeof(std::uint32_t));
key.PutBytes(input.bindings.data(), input.bindings.size() * sizeof(VkVertexInputBindingDescription));
append(key, input.attributes.size());
for (const auto& attribute : input.attributes) {
append(key, attribute.location);
append(key, attribute.binding);
append(key, attribute.format);
append(key, attribute.offset);
}
static_assert(sizeof(VkVertexInputAttributeDescription) == 4 * sizeof(std::uint32_t) && offsetof(VkVertexInputAttributeDescription, location) == 0 && offsetof(VkVertexInputAttributeDescription, binding) == 4 && offsetof(VkVertexInputAttributeDescription, format) == 8 && offsetof(VkVertexInputAttributeDescription, offset) == 12 && sizeof(VkFormat) == sizeof(std::uint32_t));
key.PutBytes(input.attributes.data(), input.attributes.size() * sizeof(VkVertexInputAttributeDescription));
append(key, resources.mainKey.size());
for (const auto word : resources.mainKey) append(key, word);
key.PutBytes(resources.mainKey.data(), resources.mainKey.size_bytes());
append(key, resources.fragmentKey.size());
for (const auto word : resources.fragmentKey) append(key, word);
key.PutBytes(resources.fragmentKey.data(), resources.fragmentKey.size_bytes());
append(key, state.hasColorTarget);
append(key, state.rectList);
append(key, state.topology);
@@ -1121,8 +1160,8 @@ void pipelineKey(std::vector<std::byte>& key, const Context& context, const Stat
append(key, state.conservativeRasterization);
append(key, state.blends.size());
for (const auto& blend : state.blends) append(key, keyedBlend(context, blend));
append(key, state.colorRop);
for (const auto value : state.blendConstants) append(key, value);
key.Put(state.colorRop);
key.PutBytes(state.blendConstants.data(), sizeof(state.blendConstants));
append(key, state.samples);
append(key, state.perSampleShading);
append(key, state.mergedCoverage);
@@ -1191,9 +1230,10 @@ void pipelineKey(std::vector<std::byte>& key, const Context& context, const Stat
append(key, context.sampleLocationGridSampleCounts);
append(key, context.storageImageMultisample);
append(key, context.shaderStencilExport);
return key.Length();
}
std::uint64_t hashKey(const std::vector<std::byte>& key) {
std::uint64_t hashKey(std::span<const std::byte> key) {
return std::hash<std::string_view>{}(std::string_view(reinterpret_cast<const char*>(key.data()), key.size()));
}
@@ -1315,8 +1355,9 @@ std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& st
if (disabled) return std::make_shared<Pipeline>(context, state, vertexInput, resources, shaders, attachmentLayout);
auto& store = Pipelines();
struct PipelineKeyStorage {};
auto& key = HostThreadLocal<std::vector<std::byte>, PipelineKeyStorage>();
pipelineKey(key, context, state, vertexInput, resources, shaders, attachmentLayout);
auto& storage = HostThreadLocal<std::vector<std::byte>, PipelineKeyStorage>();
const auto length = pipelineKey(storage, context, state, vertexInput, resources, shaders, attachmentLayout);
const std::span<const std::byte> key(storage.data(), length);
if (key.empty()) {
std::lock_guard lock(store.mutex);
++store.uncached;
@@ -1331,7 +1372,7 @@ std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& st
const auto found = store.index.find(hash);
if (found == store.index.end()) return nullptr;
const auto it = found->second;
if (it->key != key) {
if (it->key.size() != key.size() || std::memcmp(it->key.data(), key.data(), key.size()) != 0) {
collision = true;
return nullptr;
}
@@ -1393,10 +1434,10 @@ std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& st
store.capacity = std::min(store.capacity * 2u, PipelineStore::MaximumEntries);
}
if (replaying) {
store.entries.push_front({context.device, context.bufferPool, context.bufferPool != nullptr, hash, std::vector<std::byte>(key), pipeline});
store.entries.push_front({context.device, context.bufferPool, context.bufferPool != nullptr, hash, std::vector<std::byte>(key.begin(), key.end()), pipeline});
store.index[hash] = store.entries.begin();
} else {
store.entries.push_back({context.device, context.bufferPool, context.bufferPool != nullptr, hash, std::vector<std::byte>(key), pipeline});
store.entries.push_back({context.device, context.bufferPool, context.bufferPool != nullptr, hash, std::vector<std::byte>(key.begin(), key.end()), pipeline});
store.index[hash] = std::prev(store.entries.end());
}
while (store.entries.size() > storeBound(store)) {
@@ -1432,7 +1473,10 @@ std::shared_ptr<Pipeline> TouchCachedPipeline(const Context& context, std::uint6
}
void BuildPipelineStoreKey(std::vector<std::byte>& key, const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout) {
pipelineKey(key, context, state, vertexInput, resources, shaders, attachmentLayout);
struct PipelineScratchStorage {};
auto& storage = HostThreadLocal<std::vector<std::byte>, PipelineScratchStorage>();
const auto length = pipelineKey(storage, context, state, vertexInput, resources, shaders, attachmentLayout);
key.assign(storage.begin(), storage.begin() + static_cast<std::ptrdiff_t>(length));
}
PipelineStoreCounters PipelineStoreTotals() {
@@ -56,7 +56,7 @@ static_assert(sizeof(ShaderRecompiler::TessellationConfiguration) == 40, "Tessel
constexpr std::uint32_t FileMagic = 0x4c4a5041u;
// Bumped when the recipe codec, CanonicalPipelineState or the store key change in a way the
// layout guards above do not catch (a field renumbered or reinterpreted at the same size).
constexpr std::uint32_t FileFormat = 17u;
constexpr std::uint32_t FileFormat = 18u;
constexpr std::uint32_t ModuleRecord = 1u;
constexpr std::uint32_t GraphicsRecord = 2u;
constexpr std::uint32_t ComputeRecord = 3u;
@@ -831,7 +831,7 @@ public:
void RecordCompute(const ShaderRecompiler::RecompileResult& shader, bool pushConstants) {
if (!Enabled() || !bound.load(std::memory_order_acquire)) return;
const auto identity = shader.Identity();
const auto identity = DescribedPipelineIdentity(shader);
if (identity.Empty()) return;
Pending pending;
pending.kind = ComputeRecord;
@@ -950,7 +950,7 @@ private:
if (decode && !loaded.indexModules.contains(identity)) {
ShaderRecompiler::RecompileResult result;
std::vector<std::byte> module;
decoded = expandModule(payload, module) && ShaderRecompiler::ShaderDiskCache::DecodeResult(module, result) && result.Identity() == identity;
decoded = expandModule(payload, module) && ShaderRecompiler::ShaderDiskCache::DecodeResult(module, result) && (static_cast<ShaderRecompiler::ShaderStage>(stage) == ShaderRecompiler::ShaderStage::Compute ? DescribedPipelineIdentity(result) : result.Identity()) == identity;
if (decoded) loaded.modules.emplace(identity, LoadedModule{static_cast<ShaderRecompiler::ShaderStage>(stage), payloadOffset, record.payloadBytes, record.payloadHash, static_cast<std::uint32_t>(module.size())});
else ++dropped;
}
@@ -1454,7 +1454,7 @@ private:
auto bytes = std::make_shared<std::vector<std::byte>>();
if (!expandModule(payload, *bytes)) return nullptr;
auto result = std::make_shared<ShaderRecompiler::RecompileResult>();
if (!ShaderRecompiler::ShaderDiskCache::DecodeResult(*bytes, *result, bytes) || !(result->Identity() == identity)) return nullptr;
if (!ShaderRecompiler::ShaderDiskCache::DecodeResult(*bytes, *result, bytes) || !((module.stage == ShaderRecompiler::ShaderStage::Compute ? DescribedPipelineIdentity(*result) : result->Identity()) == identity)) return nullptr;
return result;
}
@@ -3,6 +3,7 @@
#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp"
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
#include "prx/libSceAgcDriver/Execution/include/Mutex.hpp"
#include "prx/libSceAgcDriver/Execution/include/ProfileCounter.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include "prx/libc/include/HostThreadSlot.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
@@ -33,12 +34,15 @@
#include <algorithm>
#include <array>
#include <atomic>
#include <bit>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <functional>
#include <iterator>
#include <limits>
#include <map>
@@ -604,8 +608,8 @@ bool KeyStoresEach() {
std::atomic<std::uint64_t> queuedLabelsNoted{0}, queuedLabelsOverRecorded{0}, queuedLabelHits{0}, queuedLabelHookRecords{0}, queuedLabelHookInCompletion{0};
// Read-tracking counters (Recorder::ReadCounts), relaxed: they are only reported.
constexpr std::size_t ReadKinds = static_cast<std::size_t>(Recorder::ReadKind::Count);
std::atomic<std::uint64_t> readsNoted{0}, readQueries{0}, readStaleIgnored{0};
std::atomic<std::uint64_t> readHits[ReadKinds]{};
ProfileCounter readsNoted, readQueries, readStaleIgnored;
ProfileCounter readHits[ReadKinds];
bool ReadTrackingEnabled() {
// APS5_COPY_READ_TRACKING=0: no in-place reads are noted; the copy HLE's CPU path then requires
@@ -1362,7 +1366,6 @@ Recorder::Recorder(const Context& context, bool timelineSemaphores) : context(co
cmdEndQuery = context.Function<PFN_vkCmdEndQuery>("vkCmdEndQuery");
cmdResetQueryPool = context.Function<PFN_vkCmdResetQueryPool>("vkCmdResetQueryPool");
cmdCopyQueryPoolResults = context.Function<PFN_vkCmdCopyQueryPoolResults>("vkCmdCopyQueryPoolResults");
cmdBindPipeline = context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline");
cmdPushConstants = context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants");
cmdDispatch = context.Function<PFN_vkCmdDispatch>("vkCmdDispatch");
}
@@ -1494,6 +1497,181 @@ void Recorder::CountRecordedWork() {
workSinceSubmit.fetch_add(1, std::memory_order_relaxed);
}
namespace {
bool sameBits(float left, float right) {
return std::bit_cast<std::uint32_t>(left) == std::bit_cast<std::uint32_t>(right);
}
template<std::size_t Count>
bool sameBits(const std::array<float, Count>& left, const std::array<float, Count>& right) {
for (std::size_t index = 0; index < Count; ++index) {
if (!sameBits(left[index], right[index])) return false;
}
return true;
}
bool sameBits(const VkViewport& left, const VkViewport& right) {
return sameBits(left.x, right.x) && sameBits(left.y, right.y) && sameBits(left.width, right.width) && sameBits(left.height, right.height) && sameBits(left.minDepth, right.minDepth) && sameBits(left.maxDepth, right.maxDepth);
}
bool sameBits(const VkRect2D& left, const VkRect2D& right) {
return left.offset.x == right.offset.x && left.offset.y == right.offset.y && left.extent.width == right.extent.width && left.extent.height == right.extent.height;
}
}
std::uint32_t CommandState::DynamicSlots(std::span<const VkDynamicState> states) {
std::uint32_t slots = 0;
for (const auto state : states) {
switch (state) {
case VK_DYNAMIC_STATE_VIEWPORT: slots |= Mask(Viewport); break;
case VK_DYNAMIC_STATE_SCISSOR: slots |= Mask(Scissor); break;
case VK_DYNAMIC_STATE_DEPTH_BIAS: slots |= Mask(DepthBias); break;
case VK_DYNAMIC_STATE_DEPTH_BOUNDS: slots |= Mask(DepthBounds); break;
case VK_DYNAMIC_STATE_CULL_MODE: slots |= Mask(CullMode); break;
case VK_DYNAMIC_STATE_FRONT_FACE: slots |= Mask(FrontFace); break;
case VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE: slots |= Mask(DepthTest); break;
case VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE: slots |= Mask(DepthWrite); break;
case VK_DYNAMIC_STATE_DEPTH_COMPARE_OP: slots |= Mask(DepthCompare); break;
case VK_DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE: slots |= Mask(DepthBoundsTest); break;
case VK_DYNAMIC_STATE_STENCIL_TEST_ENABLE: slots |= Mask(StencilTest); break;
case VK_DYNAMIC_STATE_STENCIL_OP: slots |= Mask(StencilOpFront) | Mask(StencilOpBack); break;
case VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK: slots |= Mask(CompareMaskFront) | Mask(CompareMaskBack); break;
case VK_DYNAMIC_STATE_STENCIL_WRITE_MASK: slots |= Mask(WriteMaskFront) | Mask(WriteMaskBack); break;
case VK_DYNAMIC_STATE_STENCIL_REFERENCE: slots |= Mask(ReferenceFront) | Mask(ReferenceBack); break;
case VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT: slots |= Mask(ColorWriteMask); break;
default: throw std::runtime_error("AGC graphics: a pipeline declares a dynamic state the command tracker does not follow");
}
}
return slots;
}
void CommandState::Begin(VkCommandBuffer recording, bool suppress) {
commands = recording;
trackable = suppress ? ~0u : 0u;
Invalidate();
}
void CommandState::Invalidate() noexcept {
valid = 0;
overwritten = 0;
dynamicSlots = 0;
pipeline = VK_NULL_HANDLE;
pipelineKnown = false;
}
template<typename TValue, typename TEqual, typename TEmit>
void CommandState::apply(Slot slot, TValue CommandState::*field, const TValue& value, TEqual equal, TEmit emit) {
if (Known(slot) && equal(this->*field, value)) return;
emit();
this->*field = value;
wrote(Mask(slot));
}
template<typename TValue, typename TEmit>
void CommandState::applyFaces(Slot first, VkStencilFaceFlags faces, std::array<TValue, 2> CommandState::*field, const TValue& value, TEmit emit) {
VkStencilFaceFlags needed = 0;
for (std::uint32_t face = 0; face < 2; ++face) {
const VkStencilFaceFlags bit = 1u << face;
if ((faces & bit) == 0) continue;
if (!Known(static_cast<Slot>(first + face)) || !((this->*field)[face] == value)) needed |= bit;
}
if (needed == 0) return;
emit(needed);
for (std::uint32_t face = 0; face < 2; ++face) {
if ((needed & (1u << face)) == 0) continue;
(this->*field)[face] = value;
wrote(Mask(static_cast<Slot>(first + face)));
}
}
void CommandState::BindPipeline(const Context& context, VkPipeline bound, std::uint32_t slots) {
if (pipelineKnown && pipeline == bound && dynamicSlots == slots && (overwritten & ~slots) == 0) return;
context.tracked(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, bound);
pipeline = bound;
pipelineKnown = trackable != 0 && bound != VK_NULL_HANDLE;
dynamicSlots = slots;
valid &= slots;
overwritten = 0;
}
void CommandState::SetViewport(const Context& context, const VkViewport& value) {
apply(Viewport, &CommandState::viewport, value, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.tracked(&DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &value); });
}
void CommandState::SetScissor(const Context& context, const VkRect2D& value) {
apply(Scissor, &CommandState::scissor, value, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.tracked(&DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &value); });
}
void CommandState::SetDepthBias(const Context& context, float constant, float clamp, float slope) {
const std::array<float, 3> bias{constant, clamp, slope};
apply(DepthBias, &CommandState::depthBias, bias, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.tracked(&DeviceFunctions::cmdSetDepthBias, "vkCmdSetDepthBias")(commands, constant, clamp, slope); });
}
void CommandState::SetDepthBounds(const Context& context, float minimum, float maximum) {
const std::array<float, 2> bounds{minimum, maximum};
apply(DepthBounds, &CommandState::depthBounds, bounds, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.tracked(&DeviceFunctions::cmdSetDepthBounds, "vkCmdSetDepthBounds")(commands, minimum, maximum); });
}
void CommandState::SetCullMode(const Context& context, VkCullModeFlags mode) {
apply(CullMode, &CommandState::cullMode, mode, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetCullMode, "vkCmdSetCullModeEXT")(commands, mode); });
}
void CommandState::SetFrontFace(const Context& context, VkFrontFace face) {
apply(FrontFace, &CommandState::frontFace, face, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetFrontFace, "vkCmdSetFrontFaceEXT")(commands, face); });
}
void CommandState::SetDepthTestEnable(const Context& context, VkBool32 enable) {
apply(DepthTest, &CommandState::depthTest, enable, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetDepthTestEnable, "vkCmdSetDepthTestEnableEXT")(commands, enable); });
}
void CommandState::SetDepthWriteEnable(const Context& context, VkBool32 enable) {
apply(DepthWrite, &CommandState::depthWrite, enable, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetDepthWriteEnable, "vkCmdSetDepthWriteEnableEXT")(commands, enable); });
}
void CommandState::SetDepthCompareOp(const Context& context, VkCompareOp compare) {
apply(DepthCompare, &CommandState::depthCompare, compare, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetDepthCompareOp, "vkCmdSetDepthCompareOpEXT")(commands, compare); });
}
void CommandState::SetDepthBoundsTestEnable(const Context& context, VkBool32 enable) {
apply(DepthBoundsTest, &CommandState::depthBoundsTest, enable, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetDepthBoundsTestEnable, "vkCmdSetDepthBoundsTestEnableEXT")(commands, enable); });
}
void CommandState::SetStencilTestEnable(const Context& context, VkBool32 enable) {
apply(StencilTest, &CommandState::stencilTest, enable, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetStencilTestEnable, "vkCmdSetStencilTestEnableEXT")(commands, enable); });
}
void CommandState::SetStencilOp(const Context& context, VkStencilFaceFlags faces, VkStencilOp failOp, VkStencilOp passOp, VkStencilOp depthFailOp, VkCompareOp compareOp) {
applyFaces(StencilOpFront, faces, &CommandState::stencilOps, StencilOps{failOp, passOp, depthFailOp, compareOp}, [&](VkStencilFaceFlags needed) { context.tracked(&DeviceFunctions::cmdSetStencilOp, "vkCmdSetStencilOpEXT")(commands, needed, failOp, passOp, depthFailOp, compareOp); });
}
void CommandState::SetStencilCompareMask(const Context& context, VkStencilFaceFlags faces, std::uint32_t mask) {
applyFaces(CompareMaskFront, faces, &CommandState::compareMasks, mask, [&](VkStencilFaceFlags needed) { context.tracked(&DeviceFunctions::cmdSetStencilCompareMask, "vkCmdSetStencilCompareMask")(commands, needed, mask); });
}
void CommandState::SetStencilWriteMask(const Context& context, VkStencilFaceFlags faces, std::uint32_t mask) {
applyFaces(WriteMaskFront, faces, &CommandState::writeMasks, mask, [&](VkStencilFaceFlags needed) { context.tracked(&DeviceFunctions::cmdSetStencilWriteMask, "vkCmdSetStencilWriteMask")(commands, needed, mask); });
}
void CommandState::SetStencilReference(const Context& context, VkStencilFaceFlags faces, std::uint32_t reference) {
applyFaces(ReferenceFront, faces, &CommandState::references, reference, [&](VkStencilFaceFlags needed) { context.tracked(&DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, needed, reference); });
}
void CommandState::SetColorWriteMasks(const Context& context, std::span<const VkColorComponentFlags> masks) {
ColorWriteMasks value{};
Require(!masks.empty() && masks.size() <= value.masks.size(), "color write masks exceed the color attachments");
value.count = static_cast<std::uint32_t>(masks.size());
std::ranges::copy(masks, value.masks.begin());
const auto covered = [](const ColorWriteMasks& known, const ColorWriteMasks& wanted) { return wanted.count <= known.count && std::equal(wanted.masks.begin(), wanted.masks.begin() + wanted.count, known.masks.begin()); };
apply(ColorWriteMask, &CommandState::colorWriteMasks, value, covered, [&] { context.tracked(&DeviceFunctions::cmdSetColorWriteMask, "vkCmdSetColorWriteMaskEXT")(commands, 0, value.count, masks.data()); });
}
CommandState& Recorder::GraphicsState() {
Require(open != nullptr, "no batch is open for graphics state");
return open->graphicsState;
}
Recorder* Recorder::Active() {
return activeRecorder;
}
@@ -1867,7 +2045,7 @@ Recorder::DrawPassStart Recorder::StartDrawPass(std::uint64_t key, bool forced,
return {commands, false, !elide, reason};
}
void Recorder::LeaveRenderPassOpen(std::uint64_t key, std::uint32_t timing, bool fenced, const PassAccess& access, std::function<void(VkCommandBuffer)> afterPass) {
void Recorder::LeaveRenderPassOpen(std::uint64_t key, std::uint32_t timing, bool fenced, const PassAccess& access, std::function<void(CommandState&)> afterPass) {
Require(open != nullptr, "no batch is open for the render pass");
auto& pass = open->renderPass;
if (!pass.open) {
@@ -1894,7 +2072,7 @@ void Recorder::endOpenRenderPass(PassBreak by, bool barrier) {
recordBarrier(open->commands, PassEndBarrier.srcStage, PassEndBarrier.dstStage, PassEndBarrier.srcAccess, PassEndBarrier.dstAccess);
CountBarriers(CommandClass::Draw);
}
if (pass.afterPass) pass.afterPass(open->commands);
if (pass.afterPass) pass.afterPass(open->graphicsState);
EndGpuTiming(pass.timing);
open->coveredAccess = barrier ? VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : 0;
open->hostReadOwed = true;
@@ -1990,6 +2168,8 @@ void Recorder::ensureOpen() {
VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
Check(function(beginCommandBuffer, "vkBeginCommandBuffer")(batch->commands, &begin), "vkBeginCommandBuffer recorder");
static const bool suppress = std::getenv("APS5_NO_STATE_SUPPRESSION") == nullptr;
batch->graphicsState.Begin(batch->commands, suppress);
} catch (...) {
release(*batch);
throw;
@@ -2524,7 +2704,7 @@ bool Recorder::RecordDispatchArguments(VkCommandBuffer commands, VkDeviceAddress
}
if (dispatchArgumentState < 0) return false;
recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
function(cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, dispatchArgumentPipeline);
context.BindComputePipeline(commands, dispatchArgumentPipeline);
const auto* limit = context.limits.maxComputeWorkGroupCount;
struct {
VkDeviceAddress source;
@@ -2752,8 +2932,8 @@ void Recorder::EndPassSamples() {
if (open != nullptr && open->segmentActive) endSegment(*open);
}
void Recorder::RecordUncounted(const std::function<void(VkCommandBuffer)>& record) {
const auto commands = Commands();
void Recorder::RecordUncounted(const std::function<void(CommandState&)>& record) {
Commands();
if (open->segmentActive) endSegment(*open);
const bool counted = open->sampleActive;
if (counted) {
@@ -2762,7 +2942,7 @@ void Recorder::RecordUncounted(const std::function<void(VkCommandBuffer)>& recor
open->endedSamples.push_back(open->samples);
open->samples = VK_NULL_HANDLE;
}
record(commands);
record(open->graphicsState);
if (counted) beginSamples(*open);
}
@@ -2842,7 +3022,7 @@ void Recorder::recordQueuedDumps(VkCommandBuffer commands, std::span<const Batch
void Recorder::dispatchDumps(VkCommandBuffer commands, std::uint32_t firstDump, std::uint32_t dumps, std::uint32_t firstSegment, std::uint32_t lastSegment) {
recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
function(cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, dumpPipeline);
context.BindComputePipeline(commands, dumpPipeline);
struct {
VkDeviceAddress counter;
VkDeviceAddress list;
@@ -2903,9 +3083,9 @@ void Recorder::endSamples(Batch& batch) {
void Recorder::foldSamples(Batch& batch, VkDeviceAddress target) {
const auto commands = batch.commands;
const auto copy = function(cmdCopyQueryPoolResults, "vkCmdCopyQueryPoolResults");
const auto bind = function(cmdBindPipeline, "vkCmdBindPipeline");
const auto push = function(cmdPushConstants, "vkCmdPushConstants");
const auto dispatch = function(cmdDispatch, "vkCmdDispatch");
const auto bindCompute = context.ComputeBinding();
std::size_t done = 0;
do {
const auto count = static_cast<std::uint32_t>(std::min<std::size_t>(SampleFoldCapacity, pendingSamples.size() - done));
@@ -2918,7 +3098,7 @@ void Recorder::foldSamples(Batch& batch, VkDeviceAddress target) {
done += count;
const bool last = done == pendingSamples.size();
recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, samplePipeline);
bindCompute(commands, samplePipeline);
struct {
VkDeviceAddress counter;
VkDeviceAddress target;
@@ -3010,7 +3190,7 @@ bool Recorder::RecordMeshArguments(VkCommandBuffer commands, VkDeviceAddress rec
}
if (meshArgumentState < 0) return false;
recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
function(cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, meshArgumentPipeline);
context.BindComputePipeline(commands, meshArgumentPipeline);
struct {
VkDeviceAddress record;
VkDeviceAddress arguments;
@@ -3056,7 +3236,7 @@ bool Recorder::RecordChangedCopy(VkCommandBuffer commands, VkDeviceAddress resul
}
if (changedCopyState < 0) return false;
static const bool alwaysCopy = std::getenv("APS5_CHANGED_COPY_ALWAYS") != nullptr;
function(cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, changedCopyPipeline);
context.BindComputePipeline(commands, changedCopyPipeline);
const auto perDispatch = static_cast<std::uint32_t>(std::min<std::uint64_t>(std::uint64_t{context.limits.maxComputeWorkGroupCount[0]} * GroupSize, std::numeric_limits<std::uint32_t>::max() - GroupSize));
for (std::uint32_t done = 0; done < dwords;) {
const auto count = std::min(dwords - done, perDispatch);
@@ -3325,7 +3505,8 @@ void Recorder::NoteUnwrittenDrawSnapshot(std::uint64_t address, std::size_t byte
unwrittenBytes += bytes;
}
std::shared_ptr<Buffer> Recorder::ReusableDrawSnapshot(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived, std::uint64_t generation, VkDeviceSize* offset) {
std::shared_ptr<Buffer> Recorder::ReusableDrawSnapshot(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived, std::uint64_t generation, VkDeviceSize* offset, std::size_t from, std::uint32_t* lowest) {
Require(from == 0 || (use == SnapshotUse::Vertex && from < bytes), "only a vertex snapshot starts past its address");
auto found = use == SnapshotUse::Vertex ? drawSnapshots.lower_bound({address, use, bytes}) : drawSnapshots.find({address, use, bytes});
if (found == drawSnapshots.end() || std::get<0>(found->first) != address || std::get<1>(found->first) != use) {
if (use != SnapshotUse::Storage || offset == nullptr) return {};
@@ -3338,16 +3519,23 @@ std::shared_ptr<Buffer> Recorder::ReusableDrawSnapshot(std::uint64_t address, st
}
const bool sameRegistry = found->second.registryGeneration == GuestAllocations::GuestAllocationsGeneration_nid_postfix();
const auto guestBytes = use == SnapshotUse::PaddedVertex ? static_cast<std::size_t>(found->second.derived) : bytes;
if (!sameRegistry || !GuestMemory::UnchangedSince(address, guestBytes, found->second.generation)) {
const auto held = std::max(from, found->second.from);
if (!sameRegistry || (held < guestBytes && !GuestMemory::UnchangedSince(address + held, guestBytes - held, found->second.generation))) {
if (!sameRegistry || generation == 0 || use != SnapshotUse::Storage || !refreshDrawSnapshot(found->second, address, bytes)) {
eraseDrawSnapshot(found);
return {};
}
found->second.generation = generation;
}
if (found->second.from > from) {
const auto start = from - std::min(from, std::get<2>(found->first) - found->second.from);
GuestMemory::Read(address + start, found->second.buffer->Bytes().subspan(start, found->second.from - start), 1);
found->second.from = start;
}
auto& recency = drawSnapshotPools[SnapshotPool(use)].recency;
recency.splice(recency.end(), recency, found->second.recent);
if (derived != nullptr) *derived = found->second.derived;
if (lowest != nullptr) *lowest = found->second.lowest;
return found->second.buffer;
}
@@ -3419,7 +3607,8 @@ static void OwnedDrawTraceCount(const char* name, std::uint64_t amount = 1) {
PerformanceTrace::CountOwnedDraw(name, amount);
}
void Recorder::KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::uint64_t generation, std::uint64_t registryGeneration, std::shared_ptr<Buffer> buffer, SnapshotUse use, std::uint32_t derived, bool ownedInsertion) {
void Recorder::KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::uint64_t generation, std::uint64_t registryGeneration, std::shared_ptr<Buffer> buffer, SnapshotUse use, std::uint32_t derived, std::size_t from, std::uint32_t lowest, bool ownedInsertion) {
Require(from == 0 || (use == SnapshotUse::Vertex && from < bytes), "only a vertex snapshot starts past its address");
const bool storage = use == SnapshotUse::Storage;
const auto budget = storage ? DrawSnapshotBudget : DrawInputBudget;
const auto maxEntries = storage ? DrawSnapshotEntries : DrawInputEntries;
@@ -3442,7 +3631,7 @@ void Recorder::KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::u
const DrawSnapshotKey key{address, use, bytes};
pool.recency.push_back(key);
try {
drawSnapshots.emplace(key, DrawSnapshot{generation, registryGeneration, std::prev(pool.recency.end()), std::move(buffer), derived});
drawSnapshots.emplace(key, DrawSnapshot{generation, registryGeneration, std::prev(pool.recency.end()), std::move(buffer), derived, from, lowest});
} catch (...) {
pool.recency.pop_back();
throw;
@@ -3487,11 +3676,11 @@ bool Recorder::ownedDrawInputHolds(std::uint64_t address, std::size_t bytes, con
return GuestArena::GuestArenaOwnedUnchanged_nid_no_patch(static_cast<std::uintptr_t>(address), bytes, proof.words.data(), proof.words.size());
}
std::shared_ptr<Buffer> Recorder::ReusableOwnedDrawInput(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived) {
std::shared_ptr<Buffer> Recorder::ReusableOwnedDrawInput(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived, std::size_t from, std::uint32_t* lowest) {
GuestMemory::AssertGpuLockHeld("reuse owned draw input");
Require(use != SnapshotUse::Storage, "an owned draw input is a vertex or index buffer");
const auto found = drawSnapshots.find({address, use, bytes});
if (found == drawSnapshots.end() || found->second.owned.words.empty()) return {};
if (found == drawSnapshots.end() || found->second.owned.words.empty() || found->second.from > from) return {};
if (!ownedDrawInputHolds(address, bytes, found->second.owned)) {
OwnedDrawTraceCount("OwnedDraw.invalidated");
eraseDrawSnapshot(found);
@@ -3499,7 +3688,8 @@ std::shared_ptr<Buffer> Recorder::ReusableOwnedDrawInput(std::uint64_t address,
}
static const bool verify = std::getenv("APS5_VERIFY_OWNED_DRAW_INPUTS") != nullptr;
if (verify) {
const bool equal = GuestMemory::EqualsCommittedUnsynced(address, found->second.buffer->Bytes());
const auto held = found->second.from;
const bool equal = GuestMemory::EqualsCommittedUnsynced(address + held, found->second.buffer->Bytes().subspan(held));
if (!ownedDrawInputHolds(address, bytes, found->second.owned)) {
eraseDrawSnapshot(found);
return {};
@@ -3509,22 +3699,23 @@ std::shared_ptr<Buffer> Recorder::ReusableOwnedDrawInput(std::uint64_t address,
auto& recency = drawSnapshotPools[SnapshotPool(use)].recency;
recency.splice(recency.end(), recency, found->second.recent);
if (derived != nullptr) *derived = found->second.derived;
if (lowest != nullptr) *lowest = found->second.lowest;
OwnedDrawTraceCount("OwnedDraw.reused");
return found->second.buffer;
}
void Recorder::KeepOwnedDrawInput(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof, std::shared_ptr<Buffer> buffer, SnapshotUse use, std::uint32_t derived) {
void Recorder::KeepOwnedDrawInput(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof, std::shared_ptr<Buffer> buffer, SnapshotUse use, std::uint32_t derived, std::size_t from, std::uint32_t lowest) {
Require(use != SnapshotUse::Storage, "an owned draw input is a vertex or index buffer");
if (buffer == nullptr || buffer->Bytes().size() != bytes || !ownedDrawInputHolds(address, bytes, proof)) return;
auto kept = proof;
KeepDrawSnapshot(address, bytes, proof.since, proof.registry, std::move(buffer), use, derived, true);
KeepDrawSnapshot(address, bytes, proof.since, proof.registry, std::move(buffer), use, derived, from, lowest, true);
if (const auto found = drawSnapshots.find({address, use, bytes}); found != drawSnapshots.end()) {
found->second.owned = std::move(kept);
++ownedDrawInputs;
}
}
bool Recorder::KnownHighestIndex(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::optional<std::uint32_t>& highest) {
bool Recorder::KnownHighestIndex(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::optional<std::uint32_t>& highest, std::uint32_t* lowest) {
const auto found = indexRanges.find({address, use, bytes});
if (found == indexRanges.end()) return false;
if (found->second.registryGeneration != GuestAllocations::GuestAllocationsGeneration_nid_postfix() || !GuestMemory::UnchangedSince(address, bytes, found->second.generation)) {
@@ -3534,10 +3725,11 @@ bool Recorder::KnownHighestIndex(std::uint64_t address, std::size_t bytes, Snaps
}
indexRangeRecency.splice(indexRangeRecency.end(), indexRangeRecency, found->second.recent);
highest = found->second.highest;
if (lowest != nullptr) *lowest = found->second.lowest;
return true;
}
void Recorder::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) {
void Recorder::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) {
Require(use != SnapshotUse::Storage && use != SnapshotUse::Vertex, "a highest index belongs to an index buffer");
if (generation == 0) return;
const DrawSnapshotKey key{address, use, bytes};
@@ -3551,7 +3743,7 @@ void Recorder::KeepHighestIndex(std::uint64_t address, std::size_t bytes, Snapsh
}
indexRangeRecency.push_back(key);
try {
indexRanges.emplace(key, IndexRange{generation, registryGeneration, std::prev(indexRangeRecency.end()), highest});
indexRanges.emplace(key, IndexRange{generation, registryGeneration, std::prev(indexRangeRecency.end()), highest, lowest});
} catch (...) {
indexRangeRecency.pop_back();
throw;
@@ -3868,7 +4060,7 @@ void Recorder::NotePendingRead(std::uint64_t address, std::size_t bytes, ReadKin
if (bytes == 0 || !ReadTrackingEnabled()) return;
ensureOpen();
open->reads.push_back({address, address + bytes, kind});
readsNoted.fetch_add(1, std::memory_order_relaxed);
readsNoted.Add(1);
}
void Recorder::NotePendingReads(std::span<const std::pair<std::uint64_t, std::uint64_t>> ranges, ReadKind kind) {
@@ -3878,7 +4070,7 @@ void Recorder::NotePendingReads(std::span<const std::pair<std::uint64_t, std::ui
CaptureTrace::Log("buffer-read batch=%llu address=%llx bytes=%llu kind=%d", static_cast<unsigned long long>(submissions + 1), static_cast<unsigned long long>(begin), static_cast<unsigned long long>(end - begin), static_cast<int>(kind));
if (end > begin) open->reads.push_back({begin, end, kind});
}
readsNoted.fetch_add(ranges.size(), std::memory_order_relaxed);
readsNoted.Add(ranges.size());
}
bool Recorder::ValidReadList(const ReadList& ranges) {
@@ -3896,7 +4088,7 @@ void Recorder::NotePendingReadList(std::shared_ptr<const ReadList> ranges, ReadK
return;
}
ensureOpen();
readsNoted.fetch_add(ranges->size(), std::memory_order_relaxed);
readsNoted.Add(ranges->size());
for (const auto& note : open->readLists) {
if (note.ranges == ranges && note.kind == kind) return;
}
@@ -3940,11 +4132,11 @@ std::vector<std::pair<std::uint64_t, std::uint64_t>> Recorder::notedReads(const
bool Recorder::PendingReadOverlaps(std::uint64_t address, std::size_t bytes, bool ignoreSignaled) const {
if (bytes == 0) return false;
readQueries.fetch_add(1, std::memory_order_relaxed);
readQueries.Add(1);
const auto end = address + bytes;
if (open != nullptr) {
if (const auto kind = readOverlap(*open, address, end)) {
readHits[static_cast<std::size_t>(*kind)].fetch_add(1, std::memory_order_relaxed);
readHits[static_cast<std::size_t>(*kind)].Add(1);
return true;
}
}
@@ -3953,10 +4145,10 @@ bool Recorder::PendingReadOverlaps(std::uint64_t address, std::size_t bytes, boo
const auto kind = readOverlap(**it, address, end);
if (!kind.has_value()) continue;
if (ignoreSignaled && signaled(**it)) {
readStaleIgnored.fetch_add(1, std::memory_order_relaxed);
readStaleIgnored.Add(1);
continue;
}
readHits[static_cast<std::size_t>(*kind)].fetch_add(1, std::memory_order_relaxed);
readHits[static_cast<std::size_t>(*kind)].Add(1);
return true;
}
return false;
@@ -3975,8 +4167,8 @@ std::optional<Recorder::PendingReadInfo> Recorder::DescribePendingRead(std::uint
}
Recorder::ReadStatistics Recorder::ReadCounts() {
ReadStatistics counts{readsNoted.load(std::memory_order_relaxed), readQueries.load(std::memory_order_relaxed), readStaleIgnored.load(std::memory_order_relaxed), {}};
for (std::size_t kind = 0; kind < ReadKinds; ++kind) counts.hits[kind] = readHits[kind].load(std::memory_order_relaxed);
ReadStatistics counts{readsNoted.Sum(), readQueries.Sum(), readStaleIgnored.Sum(), {}};
for (std::size_t kind = 0; kind < ReadKinds; ++kind) counts.hits[kind] = readHits[kind].Sum();
return counts;
}
@@ -274,32 +274,32 @@ void FillDeviceFunctions(const Context& context, DeviceFunctions& functions) {
functions.cmdCopyBuffer = context.Function<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer");
functions.cmdUpdateBuffer = context.Function<PFN_vkCmdUpdateBuffer>("vkCmdUpdateBuffer");
functions.cmdFillBuffer = context.Function<PFN_vkCmdFillBuffer>("vkCmdFillBuffer");
functions.cmdBindPipeline = context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline");
functions.cmdBindPipeline = context.lookup<PFN_vkCmdBindPipeline>("vkCmdBindPipeline");
functions.cmdBindDescriptorSets = context.Function<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets");
functions.cmdPushConstants = context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants");
functions.cmdDispatch = context.Function<PFN_vkCmdDispatch>("vkCmdDispatch");
functions.cmdDispatchIndirect = context.Function<PFN_vkCmdDispatchIndirect>("vkCmdDispatchIndirect");
functions.cmdBeginRenderPass = context.Function<PFN_vkCmdBeginRenderPass>("vkCmdBeginRenderPass");
functions.cmdEndRenderPass = context.Function<PFN_vkCmdEndRenderPass>("vkCmdEndRenderPass");
functions.cmdSetViewport = context.Function<PFN_vkCmdSetViewport>("vkCmdSetViewport");
functions.cmdSetScissor = context.Function<PFN_vkCmdSetScissor>("vkCmdSetScissor");
if (context.dynamicColorWriteMask) functions.cmdSetColorWriteMask = context.Function<PFN_vkCmdSetColorWriteMaskEXT>("vkCmdSetColorWriteMaskEXT");
functions.cmdSetDepthBounds = context.Function<PFN_vkCmdSetDepthBounds>("vkCmdSetDepthBounds");
functions.cmdSetDepthBias = context.Function<PFN_vkCmdSetDepthBias>("vkCmdSetDepthBias");
functions.cmdSetViewport = context.lookup<PFN_vkCmdSetViewport>("vkCmdSetViewport");
functions.cmdSetScissor = context.lookup<PFN_vkCmdSetScissor>("vkCmdSetScissor");
if (context.dynamicColorWriteMask) functions.cmdSetColorWriteMask = context.lookup<PFN_vkCmdSetColorWriteMaskEXT>("vkCmdSetColorWriteMaskEXT");
functions.cmdSetDepthBounds = context.lookup<PFN_vkCmdSetDepthBounds>("vkCmdSetDepthBounds");
functions.cmdSetDepthBias = context.lookup<PFN_vkCmdSetDepthBias>("vkCmdSetDepthBias");
if (context.graphicsPipelineLibrary) {
functions.cmdBeginRendering = context.Function<PFN_vkCmdBeginRenderingKHR>("vkCmdBeginRenderingKHR");
functions.cmdEndRendering = context.Function<PFN_vkCmdEndRenderingKHR>("vkCmdEndRenderingKHR");
functions.cmdSetCullMode = context.Function<PFN_vkCmdSetCullModeEXT>("vkCmdSetCullModeEXT");
functions.cmdSetFrontFace = context.Function<PFN_vkCmdSetFrontFaceEXT>("vkCmdSetFrontFaceEXT");
functions.cmdSetDepthTestEnable = context.Function<PFN_vkCmdSetDepthTestEnableEXT>("vkCmdSetDepthTestEnableEXT");
functions.cmdSetDepthWriteEnable = context.Function<PFN_vkCmdSetDepthWriteEnableEXT>("vkCmdSetDepthWriteEnableEXT");
functions.cmdSetDepthCompareOp = context.Function<PFN_vkCmdSetDepthCompareOpEXT>("vkCmdSetDepthCompareOpEXT");
functions.cmdSetDepthBoundsTestEnable = context.Function<PFN_vkCmdSetDepthBoundsTestEnableEXT>("vkCmdSetDepthBoundsTestEnableEXT");
functions.cmdSetStencilTestEnable = context.Function<PFN_vkCmdSetStencilTestEnableEXT>("vkCmdSetStencilTestEnableEXT");
functions.cmdSetStencilOp = context.Function<PFN_vkCmdSetStencilOpEXT>("vkCmdSetStencilOpEXT");
functions.cmdSetStencilCompareMask = context.Function<PFN_vkCmdSetStencilCompareMask>("vkCmdSetStencilCompareMask");
functions.cmdSetStencilWriteMask = context.Function<PFN_vkCmdSetStencilWriteMask>("vkCmdSetStencilWriteMask");
functions.cmdSetStencilReference = context.Function<PFN_vkCmdSetStencilReference>("vkCmdSetStencilReference");
functions.cmdSetCullMode = context.lookup<PFN_vkCmdSetCullModeEXT>("vkCmdSetCullModeEXT");
functions.cmdSetFrontFace = context.lookup<PFN_vkCmdSetFrontFaceEXT>("vkCmdSetFrontFaceEXT");
functions.cmdSetDepthTestEnable = context.lookup<PFN_vkCmdSetDepthTestEnableEXT>("vkCmdSetDepthTestEnableEXT");
functions.cmdSetDepthWriteEnable = context.lookup<PFN_vkCmdSetDepthWriteEnableEXT>("vkCmdSetDepthWriteEnableEXT");
functions.cmdSetDepthCompareOp = context.lookup<PFN_vkCmdSetDepthCompareOpEXT>("vkCmdSetDepthCompareOpEXT");
functions.cmdSetDepthBoundsTestEnable = context.lookup<PFN_vkCmdSetDepthBoundsTestEnableEXT>("vkCmdSetDepthBoundsTestEnableEXT");
functions.cmdSetStencilTestEnable = context.lookup<PFN_vkCmdSetStencilTestEnableEXT>("vkCmdSetStencilTestEnableEXT");
functions.cmdSetStencilOp = context.lookup<PFN_vkCmdSetStencilOpEXT>("vkCmdSetStencilOpEXT");
functions.cmdSetStencilCompareMask = context.lookup<PFN_vkCmdSetStencilCompareMask>("vkCmdSetStencilCompareMask");
functions.cmdSetStencilWriteMask = context.lookup<PFN_vkCmdSetStencilWriteMask>("vkCmdSetStencilWriteMask");
functions.cmdSetStencilReference = context.lookup<PFN_vkCmdSetStencilReference>("vkCmdSetStencilReference");
}
functions.cmdBindVertexBuffers = context.Function<PFN_vkCmdBindVertexBuffers>("vkCmdBindVertexBuffers");
functions.cmdBindIndexBuffer = context.Function<PFN_vkCmdBindIndexBuffer>("vkCmdBindIndexBuffer");
@@ -154,6 +154,8 @@ private:
}
};
constexpr std::array<VkDynamicState, 4> depthOrderDynamicStates{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_STENCIL_WRITE_MASK, VK_DYNAMIC_STATE_STENCIL_REFERENCE};
class SampleOrders {
public:
explicit SampleOrders(const Context& context) : context(context) {
@@ -175,13 +177,14 @@ public:
write.pImageInfo = &imageInfo;
context.Function<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(context.device, 1, &write, 0, nullptr);
const StoragePush push{map, {region.width, region.height}, target.samples};
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
context.BindComputePipeline(commands, pipeline);
context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, storagePipelineLayout, 0, 1, &set, 0, nullptr);
context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, storagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push);
context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, ((region.width + 1u) / 2u + 7u) / 8u, ((region.height + 1u) / 2u + 7u) / 8u, 1);
}
void Depth(VkCommandBuffer commands, const SampleOrderTarget& target, const std::array<std::uint32_t, 4>& map, VkExtent2D region, const SampleOrderPass& order, std::vector<std::shared_ptr<void>>& kept) {
void Depth(CommandState& recording, const SampleOrderTarget& target, const std::array<std::uint32_t, 4>& map, VkExtent2D region, const SampleOrderPass& order, std::vector<std::shared_ptr<void>>& kept) {
const auto commands = recording.Commands();
const bool stencil = target.method != SampleOrderMethod::Depth;
auto copy = copyFor(target.format, target.samples, target.extent, stencil);
kept.push_back(copy);
@@ -243,13 +246,14 @@ public:
context.Resolved(&DeviceFunctions::cmdBeginRenderPass, "vkCmdBeginRenderPass")(commands, &begin, VK_SUBPASS_CONTENTS_INLINE);
const VkViewport viewport{0.0f, 0.0f, static_cast<float>(region.width), static_cast<float>(region.height), 0.0f, 1.0f};
const VkRect2D scissor{{0, 0}, region};
context.Resolved(&DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &viewport);
context.Resolved(&DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &scissor);
recording.SetViewport(context, viewport);
recording.SetScissor(context, scissor);
context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, sampledPipelineLayout, 0, 1, &set, 0, nullptr);
const auto slots = CommandState::DynamicSlots(depthOrderDynamicStates);
const auto draw = [&](VkPipeline pipeline, std::uint32_t bit, std::uint32_t writeMask, std::uint32_t reference) {
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
context.Resolved(&DeviceFunctions::cmdSetStencilWriteMask, "vkCmdSetStencilWriteMask")(commands, VK_STENCIL_FACE_FRONT_AND_BACK, writeMask);
context.Resolved(&DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, VK_STENCIL_FACE_FRONT_AND_BACK, reference);
recording.BindPipeline(context, pipeline, slots);
recording.SetStencilWriteMask(context, VK_STENCIL_FACE_FRONT_AND_BACK, writeMask);
recording.SetStencilReference(context, VK_STENCIL_FACE_FRONT_AND_BACK, reference);
const DepthPush push{map, bit};
context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, sampledPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push), &push);
context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, 3, 1, 0, 0);
@@ -419,10 +423,9 @@ private:
depthStencil.stencilTestEnable = stencil ? VK_TRUE : VK_FALSE;
depthStencil.front = replace;
depthStencil.back = replace;
const std::array<VkDynamicState, 4> dynamicStates{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_STENCIL_WRITE_MASK, VK_DYNAMIC_STATE_STENCIL_REFERENCE};
VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};
dynamic.dynamicStateCount = static_cast<std::uint32_t>(dynamicStates.size());
dynamic.pDynamicStates = dynamicStates.data();
dynamic.dynamicStateCount = static_cast<std::uint32_t>(depthOrderDynamicStates.size());
dynamic.pDynamicStates = depthOrderDynamicStates.data();
VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
info.stageCount = static_cast<std::uint32_t>(stages.size());
info.pStages = stages.data();
@@ -638,8 +641,9 @@ SampleOrderPass SampleOrderPassFor(const Context& context, const State& state, c
return {order, state.renderExtent, SampleLocations(state), ReordersSamples(order) && ValidateSampleLocations(context, state)};
}
void RecordSampleOrder(const Context& context, VkCommandBuffer commands, const SampleOrderPass& pass, std::span<const SampleOrderTarget> targets, bool toHost, std::vector<std::shared_ptr<void>>& kept) {
void RecordSampleOrder(const Context& context, CommandState& recording, const SampleOrderPass& pass, std::span<const SampleOrderTarget> targets, bool toHost, std::vector<std::shared_ptr<void>>& kept) {
if (targets.empty() || !ReordersSamples(pass.order)) return;
const auto commands = recording.Commands();
auto& reorder = ordersFor(context);
const auto map = mapFor(pass.order, toHost);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, reorderStages, anyWrite, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);
@@ -648,7 +652,7 @@ void RecordSampleOrder(const Context& context, VkCommandBuffer commands, const S
const auto region = regionOf(pass, target.extent);
if (region.width == 0 || region.height == 0) continue;
if (target.method == SampleOrderMethod::Storage) reorder.Storage(commands, target, map, region);
else reorder.Depth(commands, target, map, region, pass, kept);
else reorder.Depth(recording, target, map, region, pass, kept);
if (target.keep != nullptr) kept.push_back(target.keep);
}
RecordMemoryBarrier(context, commands, reorderStages, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, anyAccess);
@@ -104,12 +104,36 @@ struct AllocationIdentity {
bool operator==(const AllocationIdentity&) const = default;
};
AllocationIdentity LookupAllocationIdentity(std::uintptr_t address) {
const auto range = GuestAllocations::GuestAllocationsLookup_nid_postfix(address, false);
if (range == nullptr) return {};
return {range->address, range->bytes, range->allocationAddress, range->allocationBytes, range->backingSerial, (range->readable ? 1u : 0u) | (range->writable ? 2u : 0u) | (range->gpu ? 4u : 0u)};
}
struct AllocationIdentityMemo {
std::uintptr_t address = 0;
std::uint64_t generation = 0;
bool valid = false;
AllocationIdentity identity;
};
constexpr std::size_t AllocationIdentitySlots = 4096;
struct AllocationIdentityTag {};
AllocationIdentity ImageAllocationIdentity(std::span<const std::uint32_t> words) {
const auto address = TextureResourceAllocationAddress(words);
if (!address) return {};
const auto range = GuestAllocations::GuestAllocationsLookup_nid_postfix(static_cast<std::uintptr_t>(*address), false);
if (range == nullptr) return {};
return {range->address, range->bytes, range->allocationAddress, range->allocationBytes, range->backingSerial, (range->readable ? 1u : 0u) | (range->writable ? 2u : 0u) | (range->gpu ? 4u : 0u)};
const auto key = static_cast<std::uintptr_t>(*address);
const auto generation = GuestAllocations::GuestAllocationsGeneration_nid_postfix();
auto& memos = HostThreadLocal<std::unique_ptr<std::array<AllocationIdentityMemo, AllocationIdentitySlots>>, AllocationIdentityTag>();
if (memos == nullptr) memos = std::make_unique<std::array<AllocationIdentityMemo, AllocationIdentitySlots>>();
auto& memo = (*memos)[((static_cast<std::uint64_t>(key) * 0x9e3779b97f4a7c15ull) >> 32u) % AllocationIdentitySlots];
if (memo.valid && memo.address == key && memo.generation == generation) return memo.identity;
memo.identity = LookupAllocationIdentity(key);
memo.address = key;
memo.generation = generation;
memo.valid = true;
return memo.identity;
}
struct TextureKey {
@@ -1068,6 +1092,7 @@ std::shared_ptr<Texture> cachedTexture(const Context& context, std::span<const s
}
}
if (source != nullptr && resource.dccAddress != 0 && (keys.has_value() ? *keys : scanKeys()) == DccKeys::ClearSingle) source.reset();
if (source != nullptr && resource.dccAddress != 0 && source->Descriptor().dccAddress != resource.dccAddress && (keys.has_value() ? IsDccClear(*keys) : IsDccClear(scanKeys()))) source.reset();
// Otherwise a surface in host-imported memory is viewed through its cached storage image (made
// here when there is none): its refresh after a CPU or GPU write is a GPU-direct detile from the
@@ -1112,7 +1137,7 @@ std::shared_ptr<Texture> cachedTexture(const Context& context, std::span<const s
// after them is current at the generation of a second (memoized) collect. The store marks the
// surface's DCC keys uncompressed, so the keys are read after it.
const auto flushStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
const bool stagedClear = source != nullptr && resource.dccAddress != 0 && [&] {
const bool stagedClear = source != nullptr && source->AnyLayerPending() && resource.dccAddress != 0 && source->Descriptor().dccAddress == resource.dccAddress && [&] {
const auto observedKeys = keys.has_value() ? *keys : scanKeys();
return IsDccClear(observedKeys) || observedKeys == DccKeys::ClearSingle;
}();
@@ -2732,6 +2757,29 @@ DescribedSetLayouts DescribeSetLayouts(const Context& context, std::span<const C
return result;
}
ShaderRecompiler::PipelineIdentity DescribedPipelineIdentity(const ShaderRecompiler::RecompileResult& shader) {
const auto hash = shader.spirv.ContentHash();
if (hash == ShaderRecompiler::SpirvContentHash{}) return {};
ShaderRecompiler::PipelineIdentity identity{hash.low, hash.high};
const auto mix = [&](std::uint64_t value) {
identity.low = (identity.low ^ value) * 0x9e3779b97f4a7c15ull;
identity.low ^= identity.low >> 29u;
identity.high = (identity.high ^ (value + 0x7f4a7c159e3779b9ull)) * 0xc2b2ae3d27d4eb4full;
identity.high ^= identity.high >> 31u;
};
mix(shader.specialization.size());
for (const auto& constant : shader.specialization) mix(constant.id | (static_cast<std::uint64_t>(constant.value) << 32u));
mix(shader.hostSubgroupSize | (shader.fullSubgroups ? 0x10000u : 0u) | (static_cast<std::uint64_t>(shader.workgroupMemoryDwords) << 32u));
mix(shader.bindings.size());
for (const auto& binding : shader.bindings) {
const bool fixedCapacity = binding.role == ShaderRecompiler::DescriptorRole::ImageTable || binding.role == ShaderRecompiler::DescriptorRole::ImageStorageTable || binding.role == ShaderRecompiler::DescriptorRole::SamplerTable;
const std::uint64_t count = fixedCapacity ? 0u : binding.count;
mix(binding.descriptorSet | (static_cast<std::uint64_t>(binding.binding) << 16u) | (static_cast<std::uint64_t>(binding.kind) << 40u) | (count << 48u));
}
if (identity.Empty()) identity.low = 1;
return identity;
}
void ShaderResources::buildComplete() {
PerformanceTimer frameTiming("Resources.Complete");
BuildLookups lookups;
@@ -3674,7 +3722,7 @@ bool ShaderResources::fastRevalidate(std::uint64_t serialBefore, std::span<const
auto& surface = validatedTextures[i];
if (!surface.valid) return fail(FastFail::NoRecord);
if (surface.depth) {
if (!DepthSurfaceHolds(context, surface.resource, textures[i].get())) return fail(FastFail::Depth);
if (!textures[i]->HasReuseLookup() && !DepthSurfaceHolds(context, surface.resource, textures[i].get())) return fail(FastFail::Depth);
continue;
}
if (textures[i]->Released()) return fail(FastFail::Replaced);
@@ -3815,7 +3863,7 @@ bool ShaderResources::fastRevalidateEach() {
auto& surface = validatedTextures[i];
if (!surface.valid) return false;
if (surface.depth) {
if (!DepthSurfaceHolds(context, surface.resource, textures[i].get())) return false;
if (!textures[i]->HasReuseLookup() && !DepthSurfaceHolds(context, surface.resource, textures[i].get())) return false;
continue;
}
if (textures[i]->Released()) return false;
@@ -4042,7 +4090,7 @@ void ShaderResources::subscribeIndex(std::span<const CompiledShader> shaders) {
depthCopyTextures.clear();
indexElements.assign(textures.size(), {});
for (std::size_t i = 0; i < textures.size(); ++i) {
if (textures[i] != nullptr && textures[i]->IsDepthCopy()) depthCopyTextures.push_back(i);
if (textures[i] != nullptr && (textures[i]->IsDepthCopy() || textures[i]->HasReuseLookup())) depthCopyTextures.push_back(i);
}
std::vector<std::pair<std::uint64_t, std::uint64_t>> ranges;
ranges.reserve(textures.size() + 4);
@@ -4204,7 +4252,7 @@ bool ShaderResources::reresolveElements(const std::vector<std::size_t>& elements
recorder->Keep(textures[i]);
textures[i] = std::move(texture);
depthCopyTextures.erase(std::remove(depthCopyTextures.begin(), depthCopyTextures.end(), i), depthCopyTextures.end());
if (textures[i]->IsDepthCopy()) depthCopyTextures.insert(std::lower_bound(depthCopyTextures.begin(), depthCopyTextures.end(), i), i);
if (textures[i]->IsDepthCopy() || textures[i]->HasReuseLookup()) depthCopyTextures.insert(std::lower_bound(depthCopyTextures.begin(), depthCopyTextures.end(), i), i);
const auto first = std::lower_bound(indexImagePositions.begin(), indexImagePositions.end(), i, [](const ImagePosition& entry, std::size_t texture) { return entry.texture < texture; });
for (auto entry = first; entry != indexImagePositions.end() && entry->texture == i; ++entry) {
const auto& current = textures[i];
@@ -4360,7 +4408,7 @@ bool ShaderResources::Revalidate(std::span<const CompiledShader> shaders, ProofR
const bool ok = revalidateFull(shaders, report);
noteEpochProof(false, false, false);
if (ok) {
provedEpoch = epoch;
provedEpoch = std::any_of(textures.begin(), textures.end(), [](const std::shared_ptr<Texture>& texture) { return texture != nullptr && texture->HasReuseLookup(); }) ? 0 : epoch;
provedProof = proof;
provedPending = pending;
} else {
@@ -4651,10 +4699,21 @@ bool ShaderResources::revalidateFull(std::span<const CompiledShader> shaders, Pr
comparedTableSpans.erase(std::remove_if(comparedTableSpans.begin(), comparedTableSpans.end(), [](const auto& span) { return span.second.empty(); }), comparedTableSpans.end());
}
if (writeSubscription != nullptr) {
for (const auto index : depthCopyTextures) textures[index]->RefreshDepthCopy();
for (const auto index : depthCopyTextures) {
if (textures[index]->HasReuseLookup()) {
if (!textures[index]->ReuseLookupHolds()) return finish(fast, false, ProofFailure::Changed);
} else {
textures[index]->RefreshDepthCopy();
}
}
} else {
for (const auto& texture : textures) {
if (texture != nullptr && texture->IsDepthCopy()) texture->RefreshDepthCopy();
if (texture == nullptr) continue;
if (texture->HasReuseLookup()) {
if (!texture->ReuseLookupHolds()) return finish(fast, false, ProofFailure::Changed);
} else if (texture->IsDepthCopy()) {
texture->RefreshDepthCopy();
}
}
}
return finish(fast, true);
@@ -5377,8 +5436,7 @@ std::size_t ShaderResources::addGuestBuffer(std::span<const std::uint32_t> words
Require(!written || !overlap(address, size, indexAddress, indexBytes), "writable shader buffer aliases the index buffer");
written = written || allWritten;
const std::uint64_t recordBytes = descriptor.Stride() != 0 ? descriptor.Stride() : extent;
constexpr std::uint64_t WidestBufferStoreBytes = 16;
const bool swept = (read || (context.discreteGpu && descriptor.Stride() > WidestBufferStoreBytes)) && dispatchThreads != 0 && recordBytes != 0 && dispatchThreads * recordBytes * 2u >= byteSize;
const bool swept = (read || (context.discreteGpu && descriptor.Stride() != 0)) && dispatchThreads != 0 && recordBytes != 0 && dispatchThreads * recordBytes * 2u >= byteSize;
if (written) guestMemory.AddWritable(address, size, atomic, swept);
else {
guestMemory.AddReadable(address, size);
@@ -137,6 +137,7 @@ struct Module {
return;
}
if (stage == Stage::TessellationControl || stage == Stage::TessellationEvaluation) {
if (stage == Stage::TessellationEvaluation && !input && value == spv::BuiltInLayer && layerOutput && (signature == "u32" || signature == "i32")) return;
const bool clipInput = value == spv::BuiltInClipDistance && signature.size() == 6 && signature.starts_with("f32[") && signature[4] >= '1' && signature[4] <= '8' && signature[5] == ']';
Require(input && (clipInput || (value == spv::BuiltInPosition && signature == "f32x4") || (value == spv::BuiltInTessCoord && stage == Stage::TessellationEvaluation && signature == "f32x3") || ((value == spv::BuiltInInvocationId || value == spv::BuiltInPrimitiveId || value == spv::BuiltInPatchVertices) && (signature == "i32" || signature == "u32"))), "unsupported tessellation built-in");
return;
@@ -116,7 +116,7 @@ public:
const auto x = static_cast<std::uint32_t>(area.offset.x);
const auto y = static_cast<std::uint32_t>(area.offset.y);
const MergePush push{{x, y}, {x + area.extent.width, y + area.extent.height}, mask, samples};
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
context.BindComputePipeline(commands, pipeline);
context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, 0, nullptr);
context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push);
context.Resolved(&DeviceFunctions::cmdDispatch, "vkCmdDispatch")(commands, (area.extent.width + 7u) / 8u, (area.extent.height + 7u) / 8u, 1);
@@ -1126,6 +1126,23 @@ void intersect(VkRect2D& result, const Registers& registers, std::uint32_t offse
result.extent = {std::min(oldRight, right) > left ? std::min(oldRight, right) - left : 0, std::min(oldBottom, bottom) > top ? std::min(oldBottom, bottom) - top : 0};
}
struct ExpandedPlanes {
bool depth = false;
bool stencil = false;
};
ExpandedPlanes outOfPlacePlanes(const Registers& cx) {
const auto control = find(cx, 0x000);
if (control == cx.end() || (control->second & 0x60u) == 0) return {};
const auto value = [&](std::uint32_t offset) {
const auto found = find(cx, offset);
return found == cx.end() ? 0u : found->second;
};
const auto base = [&](std::uint32_t low, std::uint32_t high) { return (static_cast<std::uint64_t>(value(high) & 0xffu) << 40u) | (static_cast<std::uint64_t>(value(low)) << 8u); };
const auto view = value(0x002);
return {(value(0x010) & 3u) != 0 && (view & 0x01000000u) == 0 && base(0x012, 0x01a) != base(0x014, 0x01c), (value(0x011) & 1u) != 0 && (view & 0x02000000u) == 0 && base(0x013, 0x01b) != base(0x015, 0x01d)};
}
}
VkExtent2D SampleLocationGrid(const State& state) {
@@ -1365,6 +1382,11 @@ std::string DepthMaintenanceRejection(const QueueState& queue) {
if (DepthResummarizeDrawsNothing(queue)) return {};
const auto control = find(queue.context, 0x000);
if (control == queue.context.end()) return {};
if (const auto planes = outOfPlacePlanes(queue.context); planes.depth || planes.stencil) {
char text[192];
std::snprintf(text, sizeof(text), "AGC graphics: an out-of-place DB expand (DB_RENDER_CONTROL 0x%08x) is run by the draw precheck, in order, and is not drawn", control->second);
return text;
}
constexpr std::uint32_t maintenance = 0x0000101cu;
if ((control->second & maintenance) == 0) return {};
const auto depthControl = find(queue.context, 0x200);
@@ -2654,6 +2676,51 @@ std::optional<ColorMetadataPass> DecodeColorMetadataPass(const QueueState& queue
return pass;
}
std::optional<DepthExpandPass> DecodeDepthExpandPass(const QueueState& queue) {
const auto& cx = queue.context;
const auto planes = outOfPlacePlanes(cx);
if (!planes.depth && !planes.stencil) return std::nullopt;
const auto control = read(cx, 0x000);
const auto value = [&](std::uint32_t offset) {
const auto found = find(cx, offset);
return found == cx.end() ? 0u : found->second;
};
const auto base = [&](std::uint32_t low, std::uint32_t high) { return (static_cast<std::uint64_t>(value(high) & 0xffu) << 40u) | (static_cast<std::uint64_t>(value(low)) << 8u); };
const auto zInfo = value(0x010);
const auto view = value(0x002);
const auto source = base(0x012, 0x01a);
const auto destination = base(0x014, 0x01c);
const auto reject = [&](const char* what) {
char text[320];
std::snprintf(text, sizeof(text), "AGC graphics: an out-of-place DB expand (DB_RENDER_CONTROL 0x%08x, DB_Z_INFO 0x%08x, DB_Z_READ_BASE 0x%llx, DB_Z_WRITE_BASE 0x%llx) %s is not implemented", control, zInfo, static_cast<unsigned long long>(source), static_cast<unsigned long long>(destination), what);
throw std::runtime_error(text);
};
const auto copySelection = (control & 0xcu) == 0 ? 0xf80u : 0u;
if ((control & ~(0x60u | 0x2000u | copySelection)) != 0) reject("with clear, copy, resummarize or decompress bits");
if ((control & 0x40u) == 0) reject("without DEPTH_COMPRESS_DISABLE");
if ((value(0x200) & 0xc000000fu) != 0) reject("with depth, stencil or depth bounds tests");
const bool colorMasks = find(cx, 0x8e) != cx.end() && find(cx, 0x8f) != cx.end();
if (((value(0x202) >> 4u) & 7u) != 0 && colorMasks && ColorWriteMask(cx) != 0) reject("with color writes");
if ((zInfo & 3u) == 0u) reject("of a surface without a depth plane");
if ((zInfo & 3u) == 2u) reject("of a Z_24 depth plane");
if (((zInfo >> 2u) & 3u) != 0) reject("of a multisampled depth surface");
if (((zInfo >> 4u) & 0x1fu) != 24u) reject("of a depth surface in a swizzle mode other than SW_64KB_Z_X");
if ((zInfo & 0x000f1000u) != 0) reject("of a partially resident or mipmapped depth surface");
if ((view & 0x3c000000u) != 0) reject("of a depth view with a mip level");
if ((value(0x207) & LayerExports) != 0) reject("with layer exports");
if (((source | destination | (planes.stencil ? base(0x013, 0x01b) | base(0x015, 0x01d) : 0u)) & 0xffffu) != 0) reject("between bases that are not 64 KiB aligned");
zero(cx, 0x80, ~0u, "window offset");
if (const auto viewportControl = read(cx, 0x206); viewportControl != 0x43fu) throw std::runtime_error(vteMessage(viewportControl));
auto target = decodeDepthPlane(cx);
target.clearDepth = readFloat(cx, 0x00b);
target.clearStencil = static_cast<std::uint8_t>(read(cx, 0x00a) & 0xffu);
if (!drawCovers(cx, target.extent)) reject("over part of the depth surface");
const auto slice = static_cast<std::uint64_t>(target.firstSlice);
DepthExpandPass pass{target, planes.depth ? destination + slice * DepthSliceBytes(target.extent, (zInfo & 3u) == 1u ? 2u : 4u) : 0u};
if (planes.stencil) pass.stencilDestination = base(0x015, 0x01d) + slice * DepthSliceBytes(target.extent, 1u);
return pass;
}
std::string DrawRejection(const QueueState& queue, bool indexed) {
if (auto reason = DepthMaintenanceRejection(queue); !reason.empty()) return reason;
const auto& cx = queue.context;
@@ -23,6 +23,7 @@
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
#include "prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp"
#include "prx/libSceAgcDriver/Graphics/include/KeptUnits.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libc/include/GuestWriteWatch.hpp"
#include "prx/libkernel/include/Api.hpp"
@@ -144,6 +145,7 @@ std::atomic<std::uint64_t> queuedReadHeld{0};
// hook for the read site of the last skip; images evictStale dropped (the [hooksync] and [storage] lines).
std::atomic<std::uint64_t> flushedAfterSkip{0}, flushedAfterSkipSameSite{0}, staleEvicted{0};
std::atomic<std::uint64_t> depthCopyTextures{0}, depthCopyRefreshes{0};
std::atomic<std::uint64_t> reuseLookupsHeld{0}, reuseLookupsChanged{0};
std::atomic<std::uint64_t> refreshesProved{0};
std::atomic<std::uint64_t> refreshesProvedPendingKeys{0};
std::atomic<std::uint64_t> untrackedCompares{0};
@@ -1343,6 +1345,16 @@ Texture::DepthCopyCounts Texture::TakeDepthCopyCounts() {
return {depthCopyTextures.exchange(0, std::memory_order_relaxed), depthCopyRefreshes.exchange(0, std::memory_order_relaxed)};
}
bool Texture::ReuseLookupHolds() const {
const bool held = reuseLookup().get() == this;
(held ? reuseLookupsHeld : reuseLookupsChanged).fetch_add(1, std::memory_order_relaxed);
return held;
}
Texture::ReuseLookupCounts Texture::TakeReuseLookupCounts() {
return {reuseLookupsHeld.exchange(0, std::memory_order_relaxed), reuseLookupsChanged.exchange(0, std::memory_order_relaxed)};
}
bool Texture::CanCopyFrom(const StorageTexture& source, const GuestTextureResource& descriptor) {
const auto& from = source.Descriptor();
if (IsBlockCompressed(descriptor.format) || IsBlockCompressed(from.format)) return false;
@@ -2575,6 +2587,8 @@ bool StorageTexture::refresh(std::uint32_t firstLayer, std::uint32_t lastLayer)
bool stamped = true;
bool tracked = true;
bool compared = false;
std::vector<bool> unitTracked;
std::vector<bool> unitCompared;
bool keysChanged = false;
bool cpuWrote = false;
bool direct = false;
@@ -2595,12 +2609,35 @@ bool StorageTexture::refresh(std::uint32_t firstLayer, std::uint32_t lastLayer)
const auto firstBlock = static_cast<std::size_t>(scopeBegin / 65536 - descriptor.baseAddress / 65536);
const auto blocks = static_cast<std::size_t>((scopeBegin + scopeBytes - 1) / 65536 - scopeBegin / 65536 + 1);
compared = !tracked && (scoped ? compareUntracked(scopeBegin, scopeBytes, std::span(stampedBlocks).subspan(firstBlock, blocks), true) : compareUntracked(descriptor.baseAddress, static_cast<std::size_t>(guestBytes), stampedBlocks, true));
unitTracked.clear();
unitCompared.clear();
if (!tracked && !compared) {
unitTracked.assign(trackedLayers, false);
unitCompared.assign(trackedLayers, false);
compared = true;
for (auto unit = firstLayer; unit < lastLayer; ++unit) {
const auto begin = layerBegin(unit);
const auto unitBytes = static_cast<std::size_t>(layerBytes(unit));
const auto offset = static_cast<std::size_t>(begin / 65536 - descriptor.baseAddress / 65536);
const auto count = static_cast<std::size_t>((begin + unitBytes - 1) / 65536 - begin / 65536 + 1);
auto changed = std::span(stampedBlocks).subspan(offset, count);
auto cpu = std::span(cpuBlocks).subspan(offset, count);
GuestMemory::CollectWritesUncached(begin, unitBytes);
unitTracked[unit] = GuestMemory::ChangedBlocks(begin, unitBytes, std::span(generations).subspan(offset, count), changed, cpu);
if (!unitTracked[unit]) {
unitCompared[unit] = compareUntracked(begin, unitBytes, changed, true);
if (unitCompared[unit]) std::copy(changed.begin(), changed.end(), cpu.begin());
}
compared = compared && (unitTracked[unit] || unitCompared[unit]);
}
} else if (compared) {
cpuBlocks = stampedBlocks;
}
if (compared) {
for (const auto& [from, unitGeneration] : keptAtUnwatch) {
const auto unit = static_cast<std::uint32_t>((from - descriptor.baseAddress) / trackedLayerBytes);
if (keptAtUnwatchHolds(from, unit)) stampedBlocks[static_cast<std::size_t>(from / 65536 - descriptor.baseAddress / 65536)] = GuestMemory::BlockWritten;
}
cpuBlocks = stampedBlocks;
if (scoped) {
std::fill(stampedBlocks.begin(), stampedBlocks.begin() + static_cast<std::ptrdiff_t>(firstBlock), GuestMemory::BlockWritten);
std::fill(stampedBlocks.begin() + static_cast<std::ptrdiff_t>(firstBlock + blocks), stampedBlocks.end(), GuestMemory::BlockWritten);
@@ -2740,8 +2777,8 @@ bool StorageTexture::refresh(std::uint32_t firstLayer, std::uint32_t lastLayer)
// unit's stamps say nothing, so it is stored.
const auto droppable = [&](std::uint32_t unit) {
if (keysChanged && IsDccClear(keys)) return true;
if (compared) return stampedBlocks.at(unit) == GuestMemory::BlockWritten;
if (!tracked || layerGeneration[unit] == 0 || unit >= stampedBlocks.size() || stampedBlocks[unit] != GuestMemory::BlockWritten) return false;
if (unitCompared.empty() ? compared : unitCompared[unit]) return stampedBlocks.at(unit) == GuestMemory::BlockWritten;
if (!(unitTracked.empty() ? tracked : unitTracked[unit]) || layerGeneration[unit] == 0 || unit >= stampedBlocks.size() || stampedBlocks[unit] != GuestMemory::BlockWritten) return false;
const auto begin = layerBegin(unit);
const auto bytes = layerBytes(unit);
const bool edge = begin % 65536 != 0 || bytes != 65536;
@@ -3202,6 +3239,7 @@ void StorageTexture::upload(const std::vector<bool>* layers) {
if (GuestMemory::Watched(descriptor.baseAddress, static_cast<std::size_t>(guestBytes))) {
layerOriginal.assign(trackedLayers, false);
cancelStoredSaves();
releaseUnheldOriginal();
} else if (!guestBytesStillHeld()) {
captureGuestBytes(nullptr);
}
@@ -3262,6 +3300,7 @@ void StorageTexture::upload(const std::vector<bool>* layers) {
if (GuestMemory::Watched(descriptor.baseAddress, static_cast<std::size_t>(guestBytes))) {
layerOriginal.assign(trackedLayers, false);
cancelStoredSaves();
releaseUnheldOriginal();
} else {
captureGuestBytes(layers);
}
@@ -4538,9 +4577,7 @@ void StorageTexture::markLayersPending(std::uint32_t first, std::uint32_t count)
layerPending.SetRange(first, count, true);
}
const auto pendingSince = GuestMemory::TrackerGeneration();
for (std::uint32_t layer = first; layer < first + count; ++layer) {
if (!keptForCpu(layer)) layerPendingSince[layer] = pendingSince;
}
StampUnkeptUnits(keptAtUnwatch, {descriptor.baseAddress, trackedLayerBytes, guestBytes}, layerGeneration, layerPendingSince, first, count, pendingSince);
// Results of this image now cover the alias's results borrowed into these units: this image
// stores them, the alias no longer has to (its results, unchanged since the borrow, are in
// this image's content). An alias written since keeps its own newer results pending.
@@ -4789,6 +4826,7 @@ std::uint64_t StorageTexture::storeDrawnRect(const DrawnArea& area, std::span<co
if (!copies.empty()) copyBuffer(commands, scratch->Handle(), segment.import->buffer, static_cast<std::uint32_t>(copies.size()), copies.data());
}
if (!saveUnits.empty()) {
if (original.size() != guestBytes) original.resize(static_cast<std::size_t>(guestBytes));
const auto saved = savedBytes->Bytes();
for (const auto unit : saveUnits) {
const auto offset = static_cast<std::size_t>(layerBegin(unit) - descriptor.baseAddress);
@@ -5182,6 +5220,7 @@ bool StorageTexture::UnwatchHookLocksGpu(std::span<const std::pair<std::uint64_t
}
void StorageTexture::SaveBeforeUnwatch(std::uint64_t address, std::size_t bytes) {
if (bytes == 0) return;
std::vector<std::shared_ptr<StorageTexture>> overlapping;
{
auto& pending = Pending();
@@ -5207,7 +5246,7 @@ void StorageTexture::SaveBeforeUnwatch(std::uint64_t address, std::size_t bytes)
RequireGpuLockBeforeImports("the unwatch hook");
std::lock_guard gpu(GuestMemory::GpuMutex());
for (const auto& texture : live) texture->hashBeforeUnwatch(address, bytes, proven);
for (const auto& texture : overlapping) texture->saveBeforeUnwatch();
for (const auto& texture : overlapping) texture->saveBeforeUnwatch(address, bytes);
}
void StorageTexture::forgetKeptAtUnwatch(std::uint32_t unit) {
@@ -5239,11 +5278,12 @@ void StorageTexture::forgetSavedOver(std::uint64_t address, std::size_t bytes) {
cancelStoredSave(unit);
}
}
releaseUnheldOriginal();
}
void StorageTexture::saveBeforeUnwatch() {
void StorageTexture::saveBeforeUnwatch(std::uint64_t address, std::size_t bytes) {
std::vector<bool> units(trackedLayers, false);
for (std::uint32_t unit = 0; unit < trackedLayers; ++unit) units[unit] = layerPending[unit] && !layerOriginal[unit];
for (std::uint32_t unit = 0; unit < trackedLayers; ++unit) units[unit] = layerPending[unit] && !layerOriginal[unit] && layerBegin(unit) < address + bytes && address < layerBegin(unit) + layerBytes(unit);
const auto runs = unitRuns(units);
if (runs.empty()) return;
original.resize(static_cast<std::size_t>(guestBytes));
@@ -5310,6 +5350,12 @@ void StorageTexture::cancelStoredSaves() {
savedTicket.assign(trackedLayers, 0);
}
void StorageTexture::releaseUnheldOriginal() {
if (original.capacity() == 0 || std::any_of(layerOriginal.begin(), layerOriginal.end(), [](bool held) { return held; })) return;
std::vector<std::byte>().swap(original);
comparedRanges = {};
}
void StorageTexture::awaitStoredSave(const std::vector<bool>* layers) {
std::uint64_t first = descriptor.baseAddress + guestBytes;
std::uint64_t last = descriptor.baseAddress;
@@ -5959,6 +6005,7 @@ bool StorageTexture::evictStale(std::uint64_t address, std::size_t bytes, std::s
layerOriginal[layer] = false;
cancelStoredSave(layer);
}
releaseUnheldOriginal();
if (!anyLayerPending()) {
++dropped;
staleEvicted.fetch_add(1, std::memory_order_relaxed);
@@ -6255,6 +6302,7 @@ bool StorageTexture::clearByKeysFill(DccKeys keys, std::uint8_t key) {
recorder->EndGpuTiming(timing, guestBytes);
layerOriginal.assign(trackedLayers, false);
cancelStoredSaves();
releaseUnheldOriginal();
uploadedKeys = keys;
filledKeys = DccKeys::Uncompressed;
keyProof = {};
@@ -6402,6 +6450,7 @@ bool StorageTexture::FillClear(std::span<const std::uint32_t, 4> pattern, std::u
if (watched) {
layerOriginal.assign(trackedLayers, false);
cancelStoredSaves();
releaseUnheldOriginal();
}
uploadedKeys = DccKeys::Uncompressed;
if (layer != WholeImage && trackedLayers > 1) {
@@ -6543,6 +6592,7 @@ void StorageTexture::MarkWholeWritten() {
if (GuestMemory::Watched(descriptor.baseAddress, static_cast<std::size_t>(guestBytes))) {
layerOriginal.assign(trackedLayers, false);
cancelStoredSaves();
releaseUnheldOriginal();
} else {
captureGuestBytes(nullptr);
}
@@ -6567,6 +6617,7 @@ void StorageTexture::MarkUnitsWritten(const std::vector<bool>& units) {
layerOriginal[unit] = false;
cancelStoredSave(unit);
}
releaseUnheldOriginal();
} else {
captureGuestBytes(&units);
}
@@ -6718,6 +6769,10 @@ std::optional<DccKeys> StorageTexture::clearHandOver() {
return keys;
}
bool StorageTexture::AnyLayerPending() const {
return anyLayerPending();
}
void StorageTexture::supersedeHandedOver(std::uint32_t first, std::uint32_t count) {
const auto begin = layerBegin(first);
const auto end = first + count >= trackedLayers ? descriptor.baseAddress + guestBytes : layerBegin(first + count);
@@ -7115,8 +7170,20 @@ void StorageTexture::writeBackLayers(const std::vector<bool>& layers) {
std::vector<std::uint8_t> cpuBlocks(drawn.drawn ? spanBlocks : 0);
const bool tracked = GuestMemory::ChangedBlocks(firstStored, static_cast<std::size_t>(lastStored - firstStored), generations, changedBlocks, cpuBlocks);
std::vector<bool> compared(trackedLayers, false);
std::vector<bool> unitTracked;
if (!tracked) {
awaitStoredSave(&layers);
for (std::uint32_t layer = 0; layer < trackedLayers; ++layer) {
if (!layers[layer] || layerOriginal[layer]) continue;
const auto begin = layerBegin(layer);
const auto bytes = static_cast<std::size_t>(layerBytes(layer));
const auto offset = static_cast<std::size_t>((begin - spanBegin) / block);
const auto count = static_cast<std::size_t>((begin + bytes - spanBegin + block - 1) / block) - offset;
auto cpu = cpuBlocks.empty() ? std::span<std::uint8_t>{} : std::span(cpuBlocks).subspan(offset, count);
GuestMemory::CollectWritesUncached(begin, bytes);
if (unitTracked.empty()) unitTracked.assign(trackedLayers, false);
unitTracked[layer] = GuestMemory::ChangedBlocks(begin, bytes, std::span(generations).subspan(offset, count), std::span(changedBlocks).subspan(offset, count), cpu);
}
std::vector<bool> saved(trackedLayers, false);
for (std::uint32_t layer = 0; layer < trackedLayers; ++layer) saved[layer] = layers[layer] && layerOriginal[layer];
for (const auto& [begin, end] : unitRuns(saved)) {
@@ -7132,6 +7199,7 @@ void StorageTexture::writeBackLayers(const std::vector<bool>& layers) {
layerOriginal[layer] = false;
cancelStoredSave(layer);
}
releaseUnheldOriginal();
};
bool unsavedOutsideWatch = false;
std::string unsavedCause;
@@ -7139,10 +7207,11 @@ void StorageTexture::writeBackLayers(const std::vector<bool>& layers) {
if (!layers[layer]) continue;
const auto begin = layerBegin(layer);
const auto end = begin + layerBytes(layer);
const bool unknown = tracked ? layerGeneration[layer] == 0 : !compared[layer];
const bool layerTracked = unitTracked.empty() ? tracked : unitTracked[layer];
const bool unknown = layerTracked ? layerGeneration[layer] == 0 : !compared[layer];
if (unknown && !drawn.rect) {
if (!tracked && !unsavedOutsideWatch) unsavedCause = std::string("storing storage image results pending over memory outside the write watch without the guest bytes saved before them is not implemented (unit ") + std::to_string(layer) + " of " + std::to_string(trackedLayers) + ": " + BaselineMissText(pendingMiss[layer]) + ")";
unsavedOutsideWatch = unsavedOutsideWatch || !tracked;
if (!layerTracked && !unsavedOutsideWatch) unsavedCause = std::string("storing storage image results pending over memory outside the write watch without the guest bytes saved before them is not implemented (unit ") + std::to_string(layer) + " of " + std::to_string(trackedLayers) + ": " + BaselineMissText(pendingMiss[layer]) + ")";
unsavedOutsideWatch = unsavedOutsideWatch || !layerTracked;
keep.emplace_back(begin, end);
continue;
}
@@ -7154,7 +7223,7 @@ void StorageTexture::writeBackLayers(const std::vector<bool>& layers) {
const auto index = static_cast<std::size_t>((at - spanBegin) / block);
const bool kept = keptAtUnwatchHolds(from, layer);
const bool written = kept || unknown || (changedBlocks[index] == GuestMemory::BlockWritten && (compared[layer] || !edge || GuestMemory::StoredOver(from, static_cast<std::size_t>(to - from), unitBlockGeneration(layer, at))) && !cpuLeftUnchanged(layer, from, to, edge));
if (written && (!drawn.rect || (tracked && !kept && !unknown && cpuBlocks[index] == 0))) {
if (written && (!drawn.rect || (layerTracked && !kept && !unknown && cpuBlocks[index] == 0))) {
skippedAny = true;
skippedLayer[layer] = true;
keptBlocks.emplace_back(from, layer);
@@ -265,7 +265,7 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode
writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
writes[1].pBufferInfo = &destinationInfo;
context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast<std::uint32_t>(writes.size()), writes.data(), 0, nullptr);
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target);
context.BindComputePipeline(commands, target);
context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, 0, nullptr);
Push push{};
push.srcBase = static_cast<std::uint32_t>(sourceBase);
@@ -331,7 +331,7 @@ void TextureDetiler::DispatchRepack(VkCommandBuffer commands, VkBuffer source, s
writes[index].pBufferInfo = index == 0 ? &sourceInfo : &destinationInfo;
}
context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast<std::uint32_t>(writes.size()), writes.data(), 0, nullptr);
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, repackPipeline);
context.BindComputePipeline(commands, repackPipeline);
context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, 0, nullptr);
const std::array<std::uint32_t, 5> push{static_cast<std::uint32_t>(sourceOffset - sourceDescriptorOffset), static_cast<std::uint32_t>(destinationOffset - destinationDescriptorOffset), static_cast<std::uint32_t>(words), static_cast<std::uint32_t>(std::min(words, rowWords)), static_cast<std::uint32_t>(depthToFloat)};
context.Resolved(&DeviceFunctions::cmdPushConstants, "vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), push.data());
@@ -413,7 +413,7 @@ void TextureDetiler::DispatchCmaskClear(VkCommandBuffer commands, VkBuffer cmask
constexpr VkAccessFlags anyWrite = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT;
constexpr VkAccessFlags anyAccess = anyWrite | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_HOST_READ_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT;
barrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, anyWrite, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipeline);
context.BindComputePipeline(commands, cmaskPipeline);
context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, cmaskPipelineLayout, 0, 1, &set, 0, nullptr);
const std::uint32_t mask = elementBytes >= 4 ? 0xffffffffu : (1u << (elementBytes * 8u)) - 1u;
const std::array<std::uint32_t, 7> push{static_cast<std::uint32_t>(base), width, height, (width + 1023u) / 1024u, clearWords[0] & mask, elementBytes == 8 ? clearWords[1] : 0u, write ? 1u : 0u};
@@ -456,7 +456,7 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til
writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
writes[1].pImageInfo = &imageInfo;
context.Resolved(&DeviceFunctions::updateDescriptorSets, "vkUpdateDescriptorSets")(context.device, static_cast<std::uint32_t>(writes.size()), writes.data(), 0, nullptr);
context.Resolved(&DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, target);
context.BindComputePipeline(commands, target);
context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, imagePipelineLayout, 0, 1, &set, 0, nullptr);
Push push{};
push.srcBase = static_cast<std::uint32_t>(retile ? 0 : base);
@@ -79,7 +79,7 @@ public:
VkMemoryBarrier upload{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT};
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &upload, 0, nullptr, 0, nullptr);
for (const auto* pipeline : pipelines) {
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->pipeline);
context.BindComputePipeline(commands, pipeline->pipeline);
context.Function<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline->layout, 0, 1, &pipeline->set, 0, nullptr);
context.Function<PFN_vkCmdDispatch>("vkCmdDispatch")(commands, groups, 1, 1);
}
@@ -134,6 +134,7 @@ void snapshotTableTests(const Context& context, const BdaTestAccess& access) {
Require(a.memory->CachedAddressTable()->serial == b.memory->CachedAddressTable()->serial && c.memory->CachedAddressTable()->serial != a.memory->CachedAddressTable()->serial, "cached BDA table serials do not follow the build's ranges");
}
ClearSnapshotCopies(importing.device);
ClearUploadCopies(importing.device);
auto e = build(first, false, true, snapshotAddress);
Require(e.snapshot != a.snapshot, "a snapshot copy outlived the teardown of its device's copies");
for (auto* item : {&a, &b, &c, &d, &e, &plain}) item->memory->WriteBack();
@@ -161,6 +162,7 @@ void snapshotTableTests(const Context& context, const BdaTestAccess& access) {
for (auto& item : builds) item.memory->WriteBack();
}
ClearSnapshotCopies(importing.device);
ClearUploadCopies(importing.device);
change(false);
::operator delete(block, std::align_val_t{piece});
}
@@ -307,6 +309,7 @@ void fixedReadOnlyRangeMirrorTests(const Context& context, const BdaTestAccess&
upload(copying, reinterpret_cast<std::uintptr_t>(block), 64, false, 0, "a guest buffer inside a releasable read-only allocation is mirrored as a fixed range");
registry(false);
ClearSnapshotCopies(copying.device);
ClearUploadCopies(copying.device);
::operator delete(block, std::align_val_t{page});
std::cout << "a guest buffer inside the main image's read-only pages is bound through a fixed mirror; one in the image's writable pages or in a releasable allocation is copied\n";
}
@@ -4293,6 +4296,7 @@ void RunHeapMirrorUnwatchTests(const Context& context, const BdaTestAccess& acce
ClearImageMirrors(importing.device);
ClearHostImports(importing.device);
ClearSnapshotCopies(importing.device);
ClearUploadCopies(importing.device);
#ifndef _WIN32
GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(pieces[0].pointer, heapBytes);
#endif
@@ -4367,6 +4371,7 @@ void RunSparseHeapMirrorUnwatchTests(const Context& context, const BdaTestAccess
registry(false);
ClearImageMirrors(context.device);
ClearSnapshotCopies(context.device);
ClearUploadCopies(context.device);
#ifdef _WIN32
GuestArena::GuestArenaReset_nid_postfix(guest, reserved);
GuestArena::GuestArenaRelease_nid_postfix(guest, reserved);
@@ -4424,6 +4429,7 @@ void RunSparseHeapMirrorBudgetTests(const Context& context, const BdaTestAccess&
registry(false);
ClearImageMirrors(context.device);
ClearSnapshotCopies(context.device);
ClearUploadCopies(context.device);
#ifdef _WIN32
GuestArena::GuestArenaReset_nid_postfix(guest, reserved);
GuestArena::GuestArenaRelease_nid_postfix(guest, reserved);
@@ -4485,6 +4491,7 @@ void RunHeapMirrorReferenceSizeTests(const Context& context, const BdaTestAccess
registry(false);
ClearImageMirrors(context.device);
ClearSnapshotCopies(context.device);
ClearUploadCopies(context.device);
#ifdef _WIN32
GuestArena::GuestArenaReset_nid_postfix(guest, heapBytes);
GuestArena::GuestArenaRelease_nid_postfix(guest, heapBytes);
@@ -4560,6 +4567,7 @@ void RunHeapMirrorRunUnwatchTests(const Context& context, const BdaTestAccess& a
registry(false);
ClearImageMirrors(context.device);
ClearSnapshotCopies(context.device);
ClearUploadCopies(context.device);
#ifdef _WIN32
GuestArena::GuestArenaReset_nid_postfix(guest, allocated);
GuestArena::GuestArenaRelease_nid_postfix(guest, allocated);
@@ -4688,6 +4696,7 @@ void RunAddressCopyCapTests(const Context& context, const BdaTestAccess& access,
ClearImageMirrors(importing.device);
ClearHostImports(importing.device);
ClearSnapshotCopies(importing.device);
ClearUploadCopies(importing.device);
#ifndef _WIN32
GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(pieces[0].pointer, heapBytes);
#endif
@@ -4787,6 +4796,7 @@ void RunAddressCopyCapMirrorTests(const Context& context, const BdaTestAccess& a
ClearImageMirrors(importing.device);
ClearHostImports(importing.device);
ClearSnapshotCopies(importing.device);
ClearUploadCopies(importing.device);
#ifndef _WIN32
GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(pieces[1].pointer, mirroredBytes);
#endif
@@ -4878,6 +4888,7 @@ void RunUnwatchedMirrorImportTests(const Context& context, const BdaTestAccess&
ClearImageMirrors(importing.device);
ClearHostImports(importing.device);
ClearSnapshotCopies(importing.device);
ClearUploadCopies(importing.device);
#ifndef _WIN32
GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(pieces[1].pointer, rangeBytes);
#endif
@@ -5556,4 +5567,5 @@ void RunBdaResourceTests(const Context& context, const BdaTestAccess& access) {
const auto heapCopies = AddressCopyOverflow({{0x10000, 0x30000, 0x18000, nullptr, true, true}, {0x40000, 0x50000, 0x10000, nullptr, true, false}}, 0x2000);
Require(heapCopies.find("0x10000+0x20000 (0.1 MiB committed, import over the host import budget, heap not fully write-watched)") != std::string::npos && heapCopies.find("0x40000+0x10000 (0.1 MiB committed, heap not fully write-watched)") != std::string::npos, "the copy limit does not name a copied heap's reason");
ClearSnapshotCopies(context.device);
ClearUploadCopies(context.device);
}
@@ -0,0 +1,153 @@
#pragma once
#include "prx/libSceAgcDriver/Graphics/include/Context.hpp"
#include "prx/libSceAgcDriver/Graphics/include/PipelineLibrary.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include <algorithm>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <vector>
namespace CommandStateLog {
using namespace AgcDriver::Graphics;
inline std::vector<std::string> stateLog;
inline std::vector<VkPipeline> statePipelines;
inline std::uint64_t statePipelineId(VkPipeline pipeline) {
const auto found = std::find(statePipelines.begin(), statePipelines.end(), pipeline);
if (found != statePipelines.end()) return static_cast<std::uint64_t>(found - statePipelines.begin());
statePipelines.push_back(pipeline);
return statePipelines.size() - 1u;
}
inline std::uint64_t stateWord(float value) { return std::bit_cast<std::uint32_t>(value); }
inline std::uint64_t stateWord(std::uint32_t value) { return value; }
inline std::uint64_t stateWord(std::int32_t value) { return static_cast<std::uint32_t>(value); }
inline std::uint64_t stateWord(VkPipeline value) { return statePipelineId(value); }
template<typename... TArguments>
std::string stateLine(const char* name, TArguments... arguments) {
std::string line = name;
((line += ' ' + std::to_string(stateWord(arguments))), ...);
return line;
}
template<typename... TArguments>
void stateNote(const char* name, TArguments... arguments) {
stateLog.push_back(stateLine(name, arguments...));
}
inline VKAPI_ATTR void VKAPI_CALL stateBind(VkCommandBuffer, VkPipelineBindPoint point, VkPipeline pipeline) { stateNote("bind", static_cast<std::uint32_t>(point), pipeline); }
inline VKAPI_ATTR void VKAPI_CALL stateViewport(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport* viewport) { stateNote("viewport", viewport->x, viewport->y, viewport->width, viewport->height, viewport->minDepth, viewport->maxDepth); }
inline VKAPI_ATTR void VKAPI_CALL stateScissor(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D* scissor) { stateNote("scissor", scissor->offset.x, scissor->offset.y, scissor->extent.width, scissor->extent.height); }
inline VKAPI_ATTR void VKAPI_CALL stateDepthBounds(VkCommandBuffer, float minimum, float maximum) { stateNote("bounds", minimum, maximum); }
inline VKAPI_ATTR void VKAPI_CALL stateDepthBias(VkCommandBuffer, float constant, float clamp, float slope) { stateNote("bias", constant, clamp, slope); }
inline VKAPI_ATTR void VKAPI_CALL stateCullMode(VkCommandBuffer, VkCullModeFlags mode) { stateNote("cull", static_cast<std::uint32_t>(mode)); }
inline VKAPI_ATTR void VKAPI_CALL stateFrontFace(VkCommandBuffer, VkFrontFace face) { stateNote("front", static_cast<std::uint32_t>(face)); }
inline VKAPI_ATTR void VKAPI_CALL stateDepthTest(VkCommandBuffer, VkBool32 enable) { stateNote("depthtest", static_cast<std::uint32_t>(enable)); }
inline VKAPI_ATTR void VKAPI_CALL stateDepthWrite(VkCommandBuffer, VkBool32 enable) { stateNote("depthwrite", static_cast<std::uint32_t>(enable)); }
inline VKAPI_ATTR void VKAPI_CALL stateDepthCompare(VkCommandBuffer, VkCompareOp compare) { stateNote("depthcompare", static_cast<std::uint32_t>(compare)); }
inline VKAPI_ATTR void VKAPI_CALL stateBoundsTest(VkCommandBuffer, VkBool32 enable) { stateNote("boundstest", static_cast<std::uint32_t>(enable)); }
inline VKAPI_ATTR void VKAPI_CALL stateStencilTest(VkCommandBuffer, VkBool32 enable) { stateNote("stenciltest", static_cast<std::uint32_t>(enable)); }
inline VKAPI_ATTR void VKAPI_CALL stateStencilOp(VkCommandBuffer, VkStencilFaceFlags faces, VkStencilOp failOp, VkStencilOp passOp, VkStencilOp depthFailOp, VkCompareOp compareOp) { stateNote("stencilop", static_cast<std::uint32_t>(faces), static_cast<std::uint32_t>(failOp), static_cast<std::uint32_t>(passOp), static_cast<std::uint32_t>(depthFailOp), static_cast<std::uint32_t>(compareOp)); }
inline VKAPI_ATTR void VKAPI_CALL stateCompareMask(VkCommandBuffer, VkStencilFaceFlags faces, std::uint32_t mask) { stateNote("comparemask", static_cast<std::uint32_t>(faces), mask); }
inline VKAPI_ATTR void VKAPI_CALL stateWriteMask(VkCommandBuffer, VkStencilFaceFlags faces, std::uint32_t mask) { stateNote("writemask", static_cast<std::uint32_t>(faces), mask); }
inline VKAPI_ATTR void VKAPI_CALL stateReference(VkCommandBuffer, VkStencilFaceFlags faces, std::uint32_t reference) { stateNote("reference", static_cast<std::uint32_t>(faces), reference); }
inline VKAPI_ATTR void VKAPI_CALL stateColorWriteMask(VkCommandBuffer, std::uint32_t first, std::uint32_t count, const VkColorComponentFlags* masks) {
auto line = stateLine("colormask", first, count);
for (std::uint32_t index = 0; index < count; ++index) line += ' ' + std::to_string(masks[index]);
stateLog.push_back(line);
}
inline void expectStateLog(const std::vector<std::string>& expected, const std::string& what) {
if (stateLog != expected) {
std::string actual;
for (const auto& line : stateLog) actual += "[" + line + "]";
std::string wanted;
for (const auto& line : expected) wanted += "[" + line + "]";
stateLog.clear();
throw std::runtime_error(what + ": recorded " + actual + " but expected " + wanted);
}
stateLog.clear();
}
inline VkPipeline stateFakePipeline(std::size_t index) {
while (statePipelines.size() <= index) statePipelines.push_back(reinterpret_cast<VkPipeline>(static_cast<std::uintptr_t>(0x5a000 + 16 * (statePipelines.size() + 1))));
return statePipelines[index];
}
inline DeviceFunctions stateFunctions() {
DeviceFunctions functions;
functions.cmdBindPipeline = stateBind;
functions.cmdSetViewport = stateViewport;
functions.cmdSetScissor = stateScissor;
functions.cmdSetDepthBounds = stateDepthBounds;
functions.cmdSetDepthBias = stateDepthBias;
functions.cmdSetCullMode = stateCullMode;
functions.cmdSetFrontFace = stateFrontFace;
functions.cmdSetDepthTestEnable = stateDepthTest;
functions.cmdSetDepthWriteEnable = stateDepthWrite;
functions.cmdSetDepthCompareOp = stateDepthCompare;
functions.cmdSetDepthBoundsTestEnable = stateBoundsTest;
functions.cmdSetStencilTestEnable = stateStencilTest;
functions.cmdSetStencilOp = stateStencilOp;
functions.cmdSetStencilCompareMask = stateCompareMask;
functions.cmdSetStencilWriteMask = stateWriteMask;
functions.cmdSetStencilReference = stateReference;
functions.cmdSetColorWriteMask = stateColorWriteMask;
return functions;
}
inline void stateTrackedDraw(CommandState& recording, const Context& context, VkPipeline pipeline) {
recording.BindPipeline(context, pipeline, CommandState::DynamicSlots(PipelineLibraryDynamicStates()));
recording.SetViewport(context, VkViewport{0.0f, 0.0f, 64.0f, 32.0f, 0.0f, 1.0f});
recording.SetScissor(context, VkRect2D{{1, 2}, {30, 20}});
recording.SetDepthBias(context, 2.0f, 0.0f, 1.0f);
recording.SetDepthBounds(context, 0.25f, 0.75f);
recording.SetCullMode(context, VK_CULL_MODE_BACK_BIT);
recording.SetFrontFace(context, VK_FRONT_FACE_CLOCKWISE);
recording.SetDepthTestEnable(context, VK_TRUE);
recording.SetDepthWriteEnable(context, VK_TRUE);
recording.SetDepthCompareOp(context, VK_COMPARE_OP_LESS);
recording.SetDepthBoundsTestEnable(context, VK_TRUE);
recording.SetStencilTestEnable(context, VK_TRUE);
for (const VkStencilFaceFlags face : {VK_STENCIL_FACE_FRONT_BIT, VK_STENCIL_FACE_BACK_BIT}) {
recording.SetStencilOp(context, face, VK_STENCIL_OP_KEEP, VK_STENCIL_OP_REPLACE, VK_STENCIL_OP_KEEP, VK_COMPARE_OP_ALWAYS);
recording.SetStencilCompareMask(context, face, 0xffu);
recording.SetStencilWriteMask(context, face, 0x0fu);
recording.SetStencilReference(context, face, 3u);
}
}
inline std::vector<std::string> stateTrackedDrawLines(VkPipeline pipeline) {
std::vector<std::string> lines{
stateLine("bind", 0u, pipeline),
stateLine("viewport", 0.0f, 0.0f, 64.0f, 32.0f, 0.0f, 1.0f),
stateLine("scissor", 1, 2, 30u, 20u),
stateLine("bias", 2.0f, 0.0f, 1.0f),
stateLine("bounds", 0.25f, 0.75f),
stateLine("cull", static_cast<std::uint32_t>(VK_CULL_MODE_BACK_BIT)),
stateLine("front", static_cast<std::uint32_t>(VK_FRONT_FACE_CLOCKWISE)),
stateLine("depthtest", 1u),
stateLine("depthwrite", 1u),
stateLine("depthcompare", static_cast<std::uint32_t>(VK_COMPARE_OP_LESS)),
stateLine("boundstest", 1u),
stateLine("stenciltest", 1u)};
for (const VkStencilFaceFlags face : {VK_STENCIL_FACE_FRONT_BIT, VK_STENCIL_FACE_BACK_BIT}) {
const auto bits = static_cast<std::uint32_t>(face);
lines.push_back(stateLine("stencilop", bits, static_cast<std::uint32_t>(VK_STENCIL_OP_KEEP), static_cast<std::uint32_t>(VK_STENCIL_OP_REPLACE), static_cast<std::uint32_t>(VK_STENCIL_OP_KEEP), static_cast<std::uint32_t>(VK_COMPARE_OP_ALWAYS)));
lines.push_back(stateLine("comparemask", bits, 0xffu));
lines.push_back(stateLine("writemask", bits, 0x0fu));
lines.push_back(stateLine("reference", bits, 3u));
}
return lines;
}
}
@@ -318,6 +318,48 @@ void TestStencilUnormView(const Context& context) {
ClearDepthSurfaces(context.device);
}
void TestCopiedHtileProvesNoClear(const Context& context) {
ClearDepthSurfaces(context.device);
constexpr VkExtent2D extent{1024, 512};
const auto bytes = static_cast<std::size_t>(HtileMetadataBytes(extent));
std::vector<std::uint32_t> words(bytes / 4u, 0xffffffffu);
const auto htile = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(words.data()));
DepthTarget target{0xc0000000, 0, extent, VK_FORMAT_D32_SFLOAT, 1.0f, 0};
target.htileAddress = htile;
AgcDriver::GuestMemory::BumpCollectEpoch();
DepthSurfaceView(context, target);
const auto image = lastImage;
std::fill(words.begin(), words.end(), 0u);
NoteCopyDestination(htile, bytes);
AgcDriver::GuestMemory::BumpCollectEpoch();
clearedImages.clear();
DepthSurfaceView(context, target);
Require(std::ranges::find(clearedImages, image) == clearedImages.end(), "clear words that a copy wrote into an HTILE must not fast-clear its depth surface");
NoteHtileDepthClear(htile, bytes);
AgcDriver::GuestMemory::BumpCollectEpoch();
clearedImages.clear();
DepthSurfaceView(context, target);
Require(std::ranges::find(clearedImages, image) != clearedImages.end(), "an HTILE fill after the copy must fast-clear the depth surface");
ClearDepthSurfaces(context.device);
}
void TestFilledHtileAfterCopyClears(const Context& context) {
ClearDepthSurfaces(context.device);
constexpr VkExtent2D extent{1024, 512};
const auto bytes = static_cast<std::size_t>(HtileMetadataBytes(extent));
std::vector<std::uint32_t> words(bytes / 4u, 0u);
const auto htile = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(words.data()));
DepthTarget target{0xc0000000, 0, extent, VK_FORMAT_D32_SFLOAT, 1.0f, 0};
target.htileAddress = htile;
NoteCopyDestination(htile, bytes);
NoteDepthMetadataFill(htile, bytes, 0u);
AgcDriver::GuestMemory::BumpCollectEpoch();
clearedImages.clear();
DepthSurfaceView(context, target);
Require(std::ranges::find(clearedImages, lastImage) != clearedImages.end(), "a metadata fill after a copy must forget it so a surface bound later fast-clears");
ClearDepthSurfaces(context.device);
}
void TestD16StencilFallback(const Context& context) {
Require(HostDepthFormat(context, VK_FORMAT_D16_UNORM_S8_UINT) == VK_FORMAT_D16_UNORM_S8_UINT && HostDepthBiasConstant(context, VK_FORMAT_D16_UNORM_S8_UINT, 2.0f) == 2.0f, "a device with D16_UNORM_S8_UINT must keep it and its depth bias");
static int withoutTag = 0;
@@ -828,6 +870,8 @@ void RunDepthSurfaceReuseTests() {
context.limits.maxFramebufferHeight = 16384;
context.limits.maxFramebufferLayers = 1;
TestD16StencilFallback(context);
TestCopiedHtileProvesNoClear(context);
TestFilledHtileAfterCopyClears(context);
TestMultisampleDepthOwnership(context);
TestMultisampleStencilAliases(context);
TestStencilUnormView(context);
+47 -1
View File
@@ -329,6 +329,52 @@ void testFlipHoldCoversTrailingLabel() {
AgcDriverUnregisterVideoOutput_nid_postfix(7, output);
}
void testFlipHoldQueuesHeldSubmission() {
auto output = std::make_shared<Output>();
AgcDriverRegisterVideoOutput_nid_postfix(7, output);
{
std::lock_guard lock(output->state->mutex);
output->state->gate = true;
output->state->waiting = false;
}
struct GateRelease {
std::shared_ptr<State> state;
~GateRelease() {
{
std::lock_guard lock(state->mutex);
state->gate = false;
}
state->changed.notify_all();
}
} gateRelease{output->state};
std::array<std::uint32_t, 10> words{0xc004105c, 7, 0xfffffffeu, 1, 0, 0, 0xc0021018, 7, 0, 0};
Packet frame{words.data(), static_cast<std::uint32_t>(words.size()), 0, {}};
check(sceAgcDriverSubmitDcb(&frame) == 0, "flip submission with a trailing rendering wait failed");
{
std::unique_lock lock(output->state->mutex);
check(output->state->changed.wait_for(lock, std::chrono::seconds(5), [&] { return output->state->waiting; }), "worker did not reach the rendering wait after the flip");
}
const int reserved = output->state->alive.load();
auto next = std::async(std::launch::async, [] { submitFlip(); });
const bool held = next.wait_for(std::chrono::milliseconds(200)) == std::future_status::timeout;
const bool queued = output->state->alive.load() == reserved + 1;
const bool ordered = output->state->ready == 1;
{
std::lock_guard lock(output->state->mutex);
output->state->gate = false;
}
output->state->changed.notify_all();
const bool released = next.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
check(held, "a flip returned while the previous flip submission had not completed");
check(queued, "a held flip submission was not queued while the title waited for the previous flip submission");
check(ordered, "a queued flip ran ahead of the previous flip submission");
check(released, "a flip stayed held after the previous flip submission completed");
next.get();
AgcDriverWaitIdle_nid_postfix();
check(output->state->ready == 2, "a queued held flip was lost");
AgcDriverUnregisterVideoOutput_nid_postfix(7, output);
}
void testComputeRenderingWait() {
auto output = std::make_shared<Output>();
AgcDriverRegisterVideoOutput_nid_postfix(7, output);
@@ -504,7 +550,7 @@ int main(int argc, char** argv) {
return 0;
}
if (argc == 2) testReset(std::string(argv[1]) == "compute");
else { testFlipAndBoundary(); testFlipHold(); testFlipHoldCoversTrailingLabel(); testComputeRenderingWait(); testComputeFlip(); testFailure(); }
else { testFlipAndBoundary(); testFlipHold(); testFlipHoldCoversTrailingLabel(); testFlipHoldQueuesHeldSubmission(); testComputeRenderingWait(); testComputeFlip(); testFailure(); }
const auto shutdown = expectFailure([] { LibcRunShutdown_nid_postfix(); });
check(shutdown.find(argc == 2 ? (std::string(argv[1]) == "compute" ? "not readable" : "required shader register") : "intentional flip failure") != std::string::npos, "shutdown lost worker failure");
std::puts("AGC flip and suspend tests passed");
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,264 @@
#include "prx/libSceAgcDriver/Graphics/include/KeptUnits.hpp"
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using AgcDriver::Graphics::StampUnkeptUnits;
using AgcDriver::Graphics::UnitLayout;
using Kept = std::map<std::uint64_t, std::uint64_t>;
constexpr std::uint64_t Untouched = 0xdead;
constexpr std::uint64_t Stamp = 0x5151;
void Require(bool condition, const std::string& message) {
if (!condition) throw std::runtime_error(message);
}
std::uint64_t ReferenceBegin(const UnitLayout& layout, std::uint32_t unit) {
return layout.base + static_cast<std::uint64_t>(unit) * layout.unitBytes;
}
std::uint64_t ReferenceBytes(const UnitLayout& layout, std::uint32_t unit) {
return std::min<std::uint64_t>(layout.unitBytes, layout.totalBytes - static_cast<std::uint64_t>(unit) * layout.unitBytes);
}
bool ReferenceKeptForCpu(const Kept& kept, const UnitLayout& layout, const std::vector<std::uint64_t>& generations, std::uint32_t unit) {
const auto begin = ReferenceBegin(layout, unit);
const auto end = begin + ReferenceBytes(layout, unit);
for (auto it = kept.lower_bound(begin); it != kept.end() && it->first < end; ++it) {
if (it->second == generations[unit]) return true;
}
return false;
}
void ReferenceStamp(const Kept& kept, const UnitLayout& layout, const std::vector<std::uint64_t>& generations, std::vector<std::uint64_t>& stamps, std::uint32_t first, std::uint32_t count) {
for (std::uint32_t unit = first; unit < first + count; ++unit) {
if (!ReferenceKeptForCpu(kept, layout, generations, unit)) stamps[unit] = Stamp;
}
}
std::vector<std::uint64_t> Walk(const Kept& kept, const UnitLayout& layout, const std::vector<std::uint64_t>& generations, std::uint32_t first, std::uint32_t count) {
std::vector<std::uint64_t> stamps(generations.size(), Untouched);
StampUnkeptUnits(kept, layout, generations, stamps, first, count, Stamp);
return stamps;
}
std::vector<std::uint64_t> Reference(const Kept& kept, const UnitLayout& layout, const std::vector<std::uint64_t>& generations, std::uint32_t first, std::uint32_t count) {
std::vector<std::uint64_t> stamps(generations.size(), Untouched);
ReferenceStamp(kept, layout, generations, stamps, first, count);
return stamps;
}
std::string Describe(const UnitLayout& layout, std::uint32_t first, std::uint32_t count, const std::string& label) {
return label + " (base " + std::to_string(layout.base) + ", unit " + std::to_string(layout.unitBytes) + ", total " + std::to_string(layout.totalBytes) + ", first " + std::to_string(first) + ", count " + std::to_string(count) + ")";
}
void Compare(const Kept& kept, const UnitLayout& layout, const std::vector<std::uint64_t>& generations, std::uint32_t first, std::uint32_t count, const std::string& label) {
const auto expected = Reference(kept, layout, generations, first, count);
const auto actual = Walk(kept, layout, generations, first, count);
for (std::size_t unit = 0; unit < expected.size(); ++unit) {
Require(expected[unit] == actual[unit], Describe(layout, first, count, label) + ": unit " + std::to_string(unit) + " differs from the per-unit answer");
}
}
constexpr std::uint64_t Block = 65536;
constexpr std::uint64_t Base = 0x400000000;
UnitLayout Blocks(std::uint32_t units, std::uint64_t tail = 0) {
return {Base, Block, units * Block - (Block - (tail == 0 ? Block : tail))};
}
std::vector<std::uint64_t> Generations(std::uint32_t units, std::uint64_t value) {
return std::vector<std::uint64_t>(units, value);
}
void CheckEmptyMap() {
const auto layout = Blocks(8);
const auto generations = Generations(8, 3);
const auto stamps = Walk({}, layout, generations, 2, 4);
for (std::uint32_t unit = 0; unit < 8; ++unit) {
Require(stamps[unit] == (unit >= 2 && unit < 6 ? Stamp : Untouched), "an empty map must stamp exactly the requested units");
}
Compare({}, layout, generations, 0, 8, "empty map");
}
void CheckZeroCount() {
const auto layout = Blocks(4);
const Kept kept{{Base, 1}};
const auto stamps = Walk(kept, layout, Generations(4, 1), 2, 0);
for (const auto value : stamps) Require(value == Untouched, "a zero count must stamp nothing");
}
void CheckKeptInsideOneUnit() {
const auto layout = Blocks(6);
const auto generations = Generations(6, 7);
const Kept kept{{Base + 2 * Block + 100, 7}};
const auto stamps = Walk(kept, layout, generations, 0, 6);
for (std::uint32_t unit = 0; unit < 6; ++unit) {
Require(stamps[unit] == (unit == 2 ? Untouched : Stamp), "a matching entry must keep exactly its own unit");
}
Compare(kept, layout, generations, 0, 6, "one kept unit");
}
void CheckBoundaries() {
const auto layout = Blocks(5);
const auto generations = Generations(5, 9);
const Kept atBegin{{Base + Block, 9}};
const Kept atLastByte{{Base + 2 * Block - 1, 9}};
const Kept atNextBegin{{Base + 2 * Block, 9}};
const Kept beforeBase{{Base - 1, 9}};
const Kept atEnd{{Base + 5 * Block, 9}};
for (const auto& kept : {atBegin, atLastByte, atNextBegin, beforeBase, atEnd}) {
for (std::uint32_t first = 0; first < 5; ++first) {
for (std::uint32_t count = 0; first + count <= 5; ++count) Compare(kept, layout, generations, first, count, "entry on a unit boundary");
}
}
const auto lastByte = Walk(atLastByte, layout, generations, 0, 5);
Require(lastByte[1] == Untouched && lastByte[2] == Stamp, "an entry on the last byte of a unit belongs to that unit");
const auto nextBegin = Walk(atNextBegin, layout, generations, 0, 5);
Require(nextBegin[1] == Stamp && nextBegin[2] == Untouched, "an entry on the first byte of a unit belongs to that unit");
}
void CheckRangeStartsInsideAndBeforeKeptRanges() {
const auto layout = Blocks(10);
auto generations = Generations(10, 4);
const Kept kept{{Base + 1 * Block, 4}, {Base + 3 * Block + 16, 4}, {Base + 4 * Block, 4}, {Base + 7 * Block + 8, 4}};
for (std::uint32_t first = 0; first < 10; ++first) {
for (std::uint32_t count = 0; first + count <= 10; ++count) Compare(kept, layout, generations, first, count, "range over kept ranges");
}
generations[3] = 5;
generations[7] = 5;
for (std::uint32_t first = 0; first < 10; ++first) {
for (std::uint32_t count = 0; first + count <= 10; ++count) Compare(kept, layout, generations, first, count, "range over kept ranges with other generations");
}
}
void CheckAdjacentAndOverlappingEntries() {
const auto layout = Blocks(4);
auto generations = Generations(4, 6);
Kept kept;
for (std::uint64_t at = Base; at < Base + 4 * Block; at += 4096) kept.emplace(at, 6 + (at / 4096) % 3);
for (std::uint32_t first = 0; first < 4; ++first) {
for (std::uint32_t count = 0; first + count <= 4; ++count) Compare(kept, layout, generations, first, count, "dense entries");
}
generations = {6, 7, 8, 9};
for (std::uint32_t first = 0; first < 4; ++first) {
for (std::uint32_t count = 0; first + count <= 4; ++count) Compare(kept, layout, generations, first, count, "dense entries and per-unit generations");
}
const Kept twoInOne{{Base + Block + 1, 99}, {Base + Block + 2, 6}, {Base + Block + 3, 98}};
const auto stamps = Walk(twoInOne, layout, Generations(4, 6), 0, 4);
Require(stamps[1] == Untouched, "a matching entry between two others must keep the unit");
}
void CheckLastUnitIsShort() {
const auto layout = Blocks(5, 4096);
Require(layout.totalBytes == 4 * Block + 4096, "the test layout must have a short last unit");
const auto generations = Generations(5, 2);
const Kept inTail{{Base + 4 * Block + 4000, 2}};
const Kept pastTail{{Base + 4 * Block + 4096, 2}};
const Kept beyond{{Base + 5 * Block, 2}};
for (const auto& kept : {inTail, pastTail, beyond}) {
for (std::uint32_t first = 0; first < 5; ++first) {
for (std::uint32_t count = 0; first + count <= 5; ++count) Compare(kept, layout, generations, first, count, "short last unit");
}
}
const auto past = Walk(pastTail, layout, generations, 0, 5);
Require(past[4] == Stamp, "an entry past the last byte of the image belongs to no unit");
const auto tail = Walk(inTail, layout, generations, 0, 5);
Require(tail[4] == Untouched, "an entry in the short last unit keeps it");
}
void CheckSingleUnitImage() {
const UnitLayout layout{Base, 123456, 123456};
const auto generations = Generations(1, 11);
for (const Kept& kept : {Kept{}, Kept{{Base, 11}}, Kept{{Base + 123455, 11}}, Kept{{Base + 123456, 11}}, Kept{{Base, 12}}}) {
Compare(kept, layout, generations, 0, 1, "single unit");
}
}
void CheckZeroSizedUnits() {
const UnitLayout layout{Base, 0, 0};
const auto generations = Generations(3, 1);
const Kept kept{{Base, 1}, {Base + 1, 1}};
const auto stamps = Walk(kept, layout, generations, 0, 3);
for (const auto value : stamps) Require(value == Stamp, "zero-sized units hold no entry");
Compare(kept, layout, generations, 0, 3, "zero-sized units");
}
void CheckLayoutsWithGaps() {
const UnitLayout layout{Base, Block, 3 * Block / 2};
const auto generations = Generations(4, 1);
for (std::uint64_t key = Base; key < Base + 6 * Block; key += Block / 4) {
const Kept kept{{key, 1}};
for (std::uint32_t first = 0; first < 4; ++first) {
for (std::uint32_t count = 0; first + count <= 4; ++count) Compare(kept, layout, generations, first, count, "units past the end of the image");
}
}
}
class Random {
public:
explicit Random(std::uint64_t seed) : state(seed) {}
std::uint64_t Next(std::uint64_t bound) {
state = state * 6364136223846793005ull + 1442695040888963407ull;
return bound == 0 ? 0 : (state >> 33) % bound;
}
private:
std::uint64_t state;
};
void CheckRandomShapes() {
Random random(12345);
const std::uint64_t unitSizes[] = {0, 1, 3, 4096, 65536, 65536, 65536, 100000};
for (int round = 0; round < 40000; ++round) {
UnitLayout layout;
layout.base = random.Next(4) == 0 ? random.Next(1000) : Base + random.Next(0x10000) * 4096;
layout.unitBytes = unitSizes[random.Next(8)];
const auto units = static_cast<std::uint32_t>(1 + random.Next(12));
layout.totalBytes = random.Next(8) == 0 ? random.Next(units * (layout.unitBytes + 1) + 1) : layout.unitBytes * units - (random.Next(2) == 0 ? 0 : random.Next(layout.unitBytes + 1));
std::vector<std::uint64_t> generations(units);
for (auto& generation : generations) generation = 1 + random.Next(3);
Kept kept;
const auto entries = random.Next(14);
const auto span = layout.totalBytes + 2 * layout.unitBytes + 8;
for (std::uint64_t entry = 0; entry < entries; ++entry) {
const auto offset = random.Next(span + 16);
const auto key = layout.base + offset - std::min<std::uint64_t>(offset, 8);
kept[key] = 1 + random.Next(3);
}
const auto first = static_cast<std::uint32_t>(random.Next(units));
const auto count = static_cast<std::uint32_t>(random.Next(units - first + 1));
Compare(kept, layout, generations, first, count, "random shape " + std::to_string(round));
}
}
}
int main() {
try {
CheckEmptyMap();
CheckZeroCount();
CheckKeptInsideOneUnit();
CheckBoundaries();
CheckRangeStartsInsideAndBeforeKeptRanges();
CheckAdjacentAndOverlappingEntries();
CheckLastUnitIsShort();
CheckSingleUnitImage();
CheckZeroSizedUnits();
CheckLayoutsWithGaps();
CheckRandomShapes();
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
std::cout << "kept unit walk tests passed\n";
return 0;
}
+73 -3
View File
@@ -14,6 +14,7 @@
#include "prx/libSceAgcDriver/Submit/include/Acb.hpp"
#include "prx/libc/include/FailureReport.hpp"
#include "prx/libc/include/Shutdown.hpp"
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
#include <algorithm>
#include <array>
#include <atomic>
@@ -86,7 +87,7 @@ void testCatalog() {
const auto reason = AgcDriver::Pm4::UnsupportedReason(packet[0]);
if (!reason.empty()) expectFailure([&] { AgcDriver::Pm4::Validate(packet, 0); }, std::string(reason).c_str());
}
check(values.size() == 56, "reference opcode catalog is incomplete");
check(values.size() == 57, "reference opcode catalog is incomplete");
check(AgcDriver::Pm4::Name(makePacket(0x3a, {0})[0]) == "DRAW_INDEX_MULTI_INST", "opcode 0x3a is not DRAW_INDEX_MULTI_INST");
expectFailure([] { AgcDriver::Pm4::Validate(makePacket(0xff, {0}), 0); }, "not known");
check(AgcDriver::Pm4::KnownName(makePacket(0xff, {0})[0]).empty() && AgcDriver::Pm4::Name(makePacket(0xff, {0})[0]) == "UNKNOWN_0xff", "an unknown opcode is named");
@@ -175,6 +176,36 @@ void testRegisters() {
expectFailure([&] { AgcDriver::Pm4::Validate(makePacket(0x9f, {0, 0, 0x80000000, 0}), 0x20); }, "compute");
}
void testContextRegRmw() {
AgcDriver::QueueState state;
execute(state, makePacket(0x69, {0x202, 0x12345678}));
const auto before = AgcDriver::DriverDetail::RegisterStateKey(state);
execute(state, {0xc0025100, 0x202, 0x00ff00ff, 0x005500aa});
check(state.context.at(0x202) == 0x125556aa, "CONTEXT_REG_RMW lost preserved or replaced bits");
check(AgcDriver::DriverDetail::RegisterStateKey(state) != before, "CONTEXT_REG_RMW did not change the fingerprint");
execute(state, makePacket(0x69, {0x202, 0x12345678}));
execute(state, makePacket(0x51, {0x202, 0x00ff00ff, 0xff55ffaa}));
check(state.context.at(0x202) == 0x125556aa, "CONTEXT_REG_RMW used data outside the mask");
alignas(4) std::uint32_t readback = 0;
execute(state, makePacket(0x40, {0x00100200, 0xa202, 0, low(&readback), high(&readback)}));
check(readback == 0x125556aa, "COPY_DATA did not read the CONTEXT_REG_RMW value");
execute(state, makePacket(0x51, {0x202, 0, 0xffffffffu}));
check(state.context.at(0x202) == 0x125556aa, "zero-mask CONTEXT_REG_RMW changed the register");
execute(state, makePacket(0x51, {0x202, 0xffffffffu, 0xabcdef01}));
check(state.context.at(0x202) == 0xabcdef01, "full-mask CONTEXT_REG_RMW did not replace the register");
for (const auto& packet : {makePacket(0x51, {0x202, 0}), makePacket(0x51, {0x202, 0, 0, 0})})
expectFailure([&] { AgcDriver::Pm4::Validate(packet, 0); }, "packet size");
expectFailure([&] { execute(state, makePacket(0x51, {0xffff, 0, 0})); }, "no known value");
expectFailure([&] { execute(state, makePacket(0x51, {0xffff, 0xffffffffu, 1})); }, "no known value");
expectFailure([&] { AgcDriver::Pm4::Validate(makePacket(0x51, {0x202, 0, 0}), 0x20); }, "compute queue");
expectFailure([&] { AgcDriver::Pm4::Validate(makePacket(0x51, {0x10000, 0, 0}), 0); }, "reserved offset");
AgcDriver::QueueState reset;
check(!reset.context.empty(), "context reset state is empty");
const auto [offset, value] = *reset.context.begin();
execute(reset, makePacket(0x51, {offset, 0xff, 0x5a}));
check(reset.context.at(offset) == ((value & ~0xffu) | 0x5au), "CONTEXT_REG_RMW did not read a defined reset value");
}
void testRegisterFile() {
AgcDriver::Registers registers{{0x300, 3}, {0x10, 1}, {0x41, 2}};
check(registers.size() == 3 && !registers.contains(0x11) && registers.at(0x41) == 2, "register file lookup");
@@ -1298,6 +1329,30 @@ void testReleaseMemDataSelects() {
for (const auto select : {6u, 7u}) expectFailure([&] { AgcDriver::Pm4::Validate(release(select), 0); }, "reserved RELEASE_MEM DATA_SEL");
}
void testGcnReleaseMemSystemCounter() {
alignas(8) static std::uint64_t target = 0;
const auto release = makePacket(0x49, {0x0030c514, 4u << 29u, low(&target), high(&target), 1, 0, 0});
const auto ticks = [](std::chrono::steady_clock::duration elapsed) { return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed).count()) * 4u / 5u; };
AgcDriver::QueueState state;
ShaderRecompiler::SetGcnGuestShaders(true);
const auto firstStart = std::chrono::steady_clock::now();
execute(state, release);
const auto firstEnd = std::chrono::steady_clock::now();
const auto first = target;
std::this_thread::sleep_for(std::chrono::milliseconds(20));
const auto secondStart = std::chrono::steady_clock::now();
execute(state, release);
const auto secondEnd = std::chrono::steady_clock::now();
const auto second = target;
const auto label = AgcDriver::Pm4::DecodeLabelWrite(release);
const auto stores = AgcDriver::Pm4::DecodeStores(release);
ShaderRecompiler::SetGcnGuestShaders(false);
check(first < 60ull * 800000000ull, "the GCN DATA_SEL 4 counter did not start near zero");
check(second - first + 1 >= ticks(secondStart - firstEnd) && second - first <= ticks(secondEnd - firstStart) + 1, "the GCN DATA_SEL 4 counter does not advance at 800 MHz");
check(label.has_value() && label->Bytes().size() == 8, "a GCN DATA_SEL 4 RELEASE_MEM did not resolve as an 8-byte label");
check(stores.size() == 1 && stores[0].value == AgcDriver::Pm4::PacketStore::Value::RunTime && stores[0].bytes == 8, "a GCN DATA_SEL 4 RELEASE_MEM did not decode as an 8-byte run-time store");
}
void testMemSemaphore() {
alignas(8) static std::uint64_t semaphore = 0;
alignas(8) static std::uint32_t marker = 0;
@@ -1471,12 +1526,20 @@ void testBranchSubmission() {
auto words = joinPackets({branch(1, 0, &first, nullptr), writeWord(results[2], 73)});
submitWords(words);
AgcDriverWaitIdle_nid_postfix();
check(results[0] == 71 && results[1] == 0 && results[2] == 73, "an always-taken if-then COND_INDIRECT_BUFFER did not run its buffer");
check(results[0] == 71 && results[1] == 0, "an always-taken if-then COND_INDIRECT_BUFFER did not run its buffer");
check(results[2] == 0, "the packet after a taken COND_INDIRECT_BUFFER ran: the branch returned like a call");
results.fill(0);
words = joinPackets({branch(2, 0, &first, &second), writeWord(results[2], 74)});
submitWords(words);
AgcDriverWaitIdle_nid_postfix();
check(results[0] == 71 && results[1] == 0 && results[2] == 74, "an always-taken if-then-else COND_INDIRECT_BUFFER ran the wrong buffer");
check(results[0] == 71 && results[1] == 0 && results[2] == 0, "an always-taken if-then-else COND_INDIRECT_BUFFER ran the wrong buffer or returned from it");
static std::vector<std::uint32_t> wrapper;
results.fill(0);
wrapper = joinPackets({branch(1, 0, &first, nullptr), writeWord(results[1], 76)});
words = joinPackets({indirectBuffer(wrapper), writeWord(results[2], 77)});
submitWords(words);
AgcDriverWaitIdle_nid_postfix();
check(results[0] == 71 && results[1] == 0 && results[2] == 77, "a COND_INDIRECT_BUFFER in a called buffer did not replace the rest of that buffer and return to its caller");
results.fill(0);
words = joinPackets({branch(1, 0, nullptr, nullptr), writeWord(results[2], 75)});
submitWords(words);
@@ -2599,6 +2662,11 @@ void testPredicatedIndirectBufferKeepsBusyPipeline() {
int main(int argc, char** argv) {
try {
if (argc == 2 && std::string_view(argv[1]) == "context-reg-rmw") {
testContextRegRmw();
std::puts("PM4 CONTEXT_REG_RMW test passed");
return 0;
}
if (argc == 2 && std::string(argv[1]) == "failure") {
testAsyncMemoryFailure();
std::puts("PM4 asynchronous memory failure propagated to idle, suspend, submit and shutdown");
@@ -2640,6 +2708,7 @@ int main(int argc, char** argv) {
testWriteChangedStoresExactlyTheChangedRuns();
testWriteChangedKeepingGuestKeepsCpuWrites();
testRegisters();
testContextRegRmw();
testRegisterFile();
testContextAndBases();
testIndexedDraw();
@@ -2658,6 +2727,7 @@ int main(int argc, char** argv) {
testConditionReadSynchronization();
testEventWrite();
testReleaseMemDataSelects();
testGcnReleaseMemSystemCounter();
testAcquireMem();
testConditionalWrite();
testConditionalWriteSubmission();
@@ -0,0 +1,106 @@
#include "prx/libSceAgcDriver/Execution/include/ProfileCounter.hpp"
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <set>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#endif
namespace {
using AgcDriver::ProfileCounter;
void Require(bool condition, const std::string& message) {
if (!condition) throw std::runtime_error(message);
}
void CheckSums(std::size_t threads) {
constexpr std::uint64_t Adds = 200000;
static ProfileCounter counter;
const auto before = counter.Sum();
std::vector<std::size_t> slots(threads);
std::vector<std::thread> pool;
for (std::size_t index = 0; index < threads; ++index) {
pool.emplace_back([&, index] {
slots[index] = ProfileCounter::ThreadSlot();
for (std::uint64_t add = 0; add < Adds; ++add) counter.Add(add % 3 == 0 ? 2 : 1);
});
}
for (auto& thread : pool) thread.join();
std::uint64_t expected = 0;
for (std::uint64_t add = 0; add < Adds; ++add) expected += add % 3 == 0 ? 2 : 1;
Require(counter.Sum() - before == expected * threads, "a profile counter lost adds across " + std::to_string(threads) + " threads");
const std::set<std::size_t> distinct(slots.begin(), slots.end());
if (ProfileCounter::Shared()) Require(distinct.size() == 1 && *distinct.begin() == 0, "APS5_SHARED_PROFILE_COUNTERS did not put every thread on one slot");
else Require(distinct.size() == std::min<std::size_t>(threads, ProfileCounter::Slots), "threads up to the slot count did not get slots of their own");
}
void CheckTake() {
static ProfileCounter counter;
std::vector<std::thread> pool;
for (int index = 0; index < 6; ++index) pool.emplace_back([] { counter.Add(5); });
for (auto& thread : pool) thread.join();
Require(counter.Take() == 30, "Take did not return the adds of every thread");
Require(counter.Sum() == 0 && counter.Take() == 0, "Take did not reset every slot");
}
void RunBench(int threads) {
constexpr std::uint64_t Adds = 5000000;
static ProfileCounter sharded;
static std::atomic<std::uint64_t> shared{0};
const auto measure = [&](auto&& add) {
std::atomic<bool> start{false};
std::vector<double> nanoseconds(static_cast<std::size_t>(threads));
std::vector<std::thread> pool;
for (int index = 0; index < threads; ++index) {
pool.emplace_back([&, index] {
while (!start.load(std::memory_order_acquire)) std::this_thread::yield();
const auto begin = std::chrono::steady_clock::now();
for (std::uint64_t value = 0; value < Adds; ++value) add();
nanoseconds[static_cast<std::size_t>(index)] = std::chrono::duration<double, std::nano>(std::chrono::steady_clock::now() - begin).count() / static_cast<double>(Adds);
});
}
start.store(true, std::memory_order_release);
for (auto& thread : pool) thread.join();
double total = 0;
for (const auto value : nanoseconds) total += value;
return total / threads;
};
const double one = measure([] { shared.fetch_add(1, std::memory_order_relaxed); });
const double many = measure([] { sharded.Add(); });
std::printf("profile counter bench, %d threads: one shared atomic %.1f ns per add, ProfileCounter %.1f ns per add%s\n", threads, one, many, ProfileCounter::Shared() ? " (APS5_SHARED_PROFILE_COUNTERS)" : "");
}
}
int main(int argc, char** argv) {
try {
if (argc == 3 && std::string_view(argv[1]) == "--bench") {
RunBench(std::stoi(argv[2]));
return 0;
}
#ifdef _WIN32
if (argc == 2 && std::string_view(argv[1]) == "--tls-expansion") {
for (int taken = 0; taken < 64; ++taken) if (TlsAlloc() >= 64) break;
Require(ProfileCounter::ThreadSlot() < ProfileCounter::Slots, "no slot from an expansion TLS index");
}
#endif
for (const std::size_t threads : {1u, 2u, 4u, 16u, 20u}) CheckSums(threads);
CheckTake();
std::puts("profile counter tests passed");
return 0;
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
}
@@ -0,0 +1,167 @@
#include "IntermediateRepresentation/IrProgram.hpp"
#include "Optimization/ReadLaneEliminator.hpp"
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <exception>
#include <functional>
#include <initializer_list>
using namespace ShaderRecompiler;
namespace {
struct Builder {
IrProgram program;
IrBlock* block = nullptr;
Builder() {
block = &newBlock();
program.SetEntryBlock(*block);
}
IrBlock& newBlock() {
auto& created = program.CreateBlock();
program.BlockOrder().push_back(&created);
return created;
}
IrValue& constant(std::uint32_t value) {
auto& created = program.CreateValue(IrOpcode::Void, IrType::U32);
created.SetImmediateU32(value);
return created;
}
IrValue& emit(IrOpcode opcode, IrType type, std::initializer_list<IrValue*> arguments) {
auto& created = program.CreateValue(opcode, type);
for (auto* argument : arguments) created.AddArgument(argument);
block->AppendInstruction(&created);
return created;
}
IrValue& unknown() {
return emit(IrOpcode::LaneId, IrType::U32, {});
}
void keep(IrValue& value) {
static_cast<void>(emit(IrOpcode::ReferenceU32, IrType::Void, {&value}));
}
};
struct Spill {
Builder b;
IrValue* stored = nullptr;
IrValue* read = nullptr;
};
Spill SpillWrittenInBranch(bool storedBeforeBranch, bool prefixBeforeRead = false) {
Spill spill;
auto& b = spill.b;
IrBlock& entry = *b.block;
IrBlock& then = b.newBlock();
IrBlock& merge = b.newBlock();
entry.AddBranch(&then);
entry.AddBranch(&merge);
then.AddBranch(&merge);
auto& initial = b.unknown();
if (storedBeforeBranch) spill.stored = &b.unknown();
b.block = &then;
if (!storedBeforeBranch) spill.stored = &b.unknown();
auto& written = b.emit(IrOpcode::WriteLane, IrType::U32, {spill.stored, &b.constant(5u), &initial});
b.block = &merge;
auto& slot = b.emit(IrOpcode::Phi, IrType::U32, {});
slot.AddPhiOperand(&entry, &initial);
slot.AddPhiOperand(&then, &written);
if (prefixBeforeRead) static_cast<void>(b.unknown());
spill.read = &b.emit(IrOpcode::ReadLane, IrType::U32, {&slot, &b.constant(5u)});
b.keep(*spill.read);
return spill;
}
bool expect(const char* name, bool condition) {
if (!condition) std::fprintf(stderr, "%s\n", name);
return condition;
}
bool run(const char* name, const std::function<bool()>& test) {
try {
return expect(name, test());
} catch (const std::exception& error) {
std::fprintf(stderr, "%s: %s\n", name, error.what());
return false;
}
}
}
int main() {
bool passed = true;
passed &= run("a lane value stored inside a branch reaches the read after the merge through a phi", [] {
auto spill = SpillWrittenInBranch(false, true);
const auto stats = ReadLaneEliminator{}.Eliminate(spill.b.program, 64u);
if (stats.rewrittenReads != 1u || spill.read->Opcode() != IrOpcode::Identity) return false;
const IrValue* phi = spill.read->Argument(0);
if (!phi->IsPhi() || phi->Parent() != spill.read->Parent() || phi->ArgumentCount() != 2u) return false;
bool phiBeforeEveryNonPhi = false;
bool sawNonPhi = false;
for (const IrValue* instruction : phi->Parent()->Instructions()) {
if (!instruction->IsPhi()) sawNonPhi = true;
if (instruction == phi) {
phiBeforeEveryNonPhi = !sawNonPhi;
break;
}
}
if (!phiBeforeEveryNonPhi) return false;
bool stored = false;
bool undefined = false;
for (std::size_t index = 0; index < phi->ArgumentCount(); index++) {
const IrValue* operand = phi->Argument(index);
stored = stored || (operand == spill.stored && operand->Parent() == phi->PhiBlock(index));
undefined = undefined || (operand->Opcode() == IrOpcode::UndefU32 && operand->Parent() == &spill.b.program.EntryBlock());
}
return stored && undefined;
});
passed &= run("a lane value computed before the branch replaces the read after the merge", [] {
auto spill = SpillWrittenInBranch(true);
const auto stats = ReadLaneEliminator{}.Eliminate(spill.b.program, 64u);
return stats.rewrittenReads == 1u && spill.read->Opcode() == IrOpcode::Identity && spill.read->Argument(0) == spill.stored;
});
passed &= run("a loop read before its same-block store uses the preceding iteration value", [] {
Builder b;
IrBlock& entry = *b.block;
IrBlock& loop = b.newBlock();
IrBlock& exit = b.newBlock();
entry.AddBranch(&loop);
loop.AddBranch(&loop);
loop.AddBranch(&exit);
auto& initial = b.unknown();
b.block = &loop;
auto& slot = b.emit(IrOpcode::Phi, IrType::U32, {});
slot.AddPhiOperand(&entry, &initial);
auto& read = b.emit(IrOpcode::ReadLane, IrType::U32, {&slot, &b.constant(5u)});
b.keep(read);
auto& stored = b.unknown();
auto& written = b.emit(IrOpcode::WriteLane, IrType::U32, {&stored, &b.constant(5u), &slot});
slot.AddPhiOperand(&loop, &written);
const auto stats = ReadLaneEliminator{}.Eliminate(b.program, 64u);
if (stats.rewrittenReads != 1u || read.Opcode() != IrOpcode::Identity) return false;
const IrValue* reaching = read.Argument(0);
if (!reaching->IsPhi() || reaching->Parent() != &loop || reaching->ArgumentCount() != 2u) return false;
bool entryUndefined = false;
bool backedgeStore = false;
for (std::size_t index = 0; index < reaching->ArgumentCount(); index++) {
const IrValue* operand = reaching->Argument(index);
entryUndefined = entryUndefined || (reaching->PhiBlock(index) == &entry && operand->Opcode() == IrOpcode::UndefU32);
backedgeStore = backedgeStore || (reaching->PhiBlock(index) == &loop && operand == &stored);
}
return entryUndefined && backedgeStore;
});
if (!passed) return 1;
std::puts("read lane elimination tests passed");
return 0;
}
+502 -46
View File
@@ -13,6 +13,7 @@
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/FirstSampleCopy.hpp"
#include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp"
#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp"
#include "prx/libSceAgcDriver/Graphics/include/MapImportGate.hpp"
@@ -43,6 +44,7 @@
#include "ImageTableAbi.hpp"
#include "IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/BufferFormat.hpp"
#include "HostImportLifetime.hpp"
#include "CommandStateLog.hpp"
#include "ShaderCacheDirectory.hpp"
#include "SampleLod_spv.h"
#include "BufferUpdate_spv.h"
@@ -54,6 +56,7 @@
#include "prx/libSceAgcDriver/Graphics/include/ColorTargetTransfer.hpp"
#include "BdaAbi.hpp"
#include "ShaderCacheSourceVersion.hpp"
#include "WatchedBlock.hpp"
#include <SDL_loadso.h>
#ifdef __APPLE__
#include <mach/mach.h>
@@ -108,35 +111,6 @@ struct TestConfigurationError : std::runtime_error {
using namespace AgcDriver::Graphics;
using AgcDriver::GuestMemory::GpuMutex;
void* AllocateWatched(std::size_t bytes, std::size_t alignment) {
if (!AgcDriver::GuestMemory::WriteWatched()) return nullptr;
#ifdef _WIN32
void* block = GuestArena::GuestArenaAllocate_nid_postfix(bytes, alignment);
GuestArena::GuestArenaCommit_nid_postfix(block, bytes, PAGE_READWRITE, bytes);
#else
void* raw = mmap(nullptr, bytes + alignment, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (raw == MAP_FAILED) throw std::runtime_error("cannot map the watched block");
const auto begin = reinterpret_cast<std::uintptr_t>(raw);
const auto aligned = (begin + alignment - 1) & ~(static_cast<std::uintptr_t>(alignment) - 1);
if (aligned != begin) munmap(raw, aligned - begin);
if (aligned + bytes != begin + bytes + alignment) munmap(reinterpret_cast<void*>(aligned + bytes), begin + alignment - aligned);
void* block = reinterpret_cast<void*>(aligned);
GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(block, bytes);
#endif
if (!AgcDriver::GuestMemory::Watched(reinterpret_cast<std::uint64_t>(block), bytes)) throw std::runtime_error("the watched block is not watched");
return block;
}
void ReleaseWatched(void* block, std::size_t bytes) {
#ifdef _WIN32
GuestArena::GuestArenaReset_nid_postfix(block, bytes);
GuestArena::GuestArenaRelease_nid_postfix(block, bytes);
#else
munmap(block, bytes);
GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(block, bytes);
#endif
}
bool collectMappingHistoryTests() {
constexpr std::size_t bytes = 131072;
auto* memory = static_cast<std::uint8_t*>(AllocateWatched(bytes, 65536));
@@ -835,7 +809,7 @@ void copiedDirectOrderingTests(const Device& device, Recorder& recorder) {
const auto commands = recorder.Commands();
recorder.Keep(resources);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, release.pipeline);
context.BindComputePipeline(commands, release.pipeline);
resources->Bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, release.layout);
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, release.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(delta), &delta);
context.Function<PFN_vkCmdDispatch>("vkCmdDispatch")(commands, count, 1, 1);
@@ -1112,7 +1086,7 @@ void copiedWriteBackTests(const Device& device, Recorder& recorder) {
const auto commands = recorder.Commands();
recorder.Keep(copied);
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, release.pipeline);
context.BindComputePipeline(commands, release.pipeline);
copied->Bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, release.layout);
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, release.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(delta), &delta);
context.Function<PFN_vkCmdDispatch>("vkCmdDispatch")(commands, 1, 1, 1);
@@ -4544,7 +4518,8 @@ bool readWrittenStagingTests(const Device& device, Recorder& recorder) {
Require(buildInPlace(1024, true, 16, 0), "a dispatch touching 16 KiB of a read and written 12 MiB element staged all of it");
Require(buildInPlace(0, true, 16, 0), "a dispatch of unknown size staged a read and written 12 MiB element");
Require(buildInPlace((12u << 20u) / 32u, false, 32, 0) != context.discreteGpu, context.discreteGpu ? "a dispatch sweeping a written-only 12 MiB element of 32-byte records bound it in place on a discrete GPU" : "a dispatch sweeping a written-only 12 MiB element of 32-byte records staged it on a GPU without separate VRAM");
Require(buildInPlace((12u << 20u) / 16u, false, 16, 0), "a dispatch sweeping a written-only 12 MiB element of 16-byte records, which its stores write contiguously, staged it");
Require(buildInPlace((12u << 20u) / 16u, false, 16, 0) != context.discreteGpu, context.discreteGpu ? "a dispatch sweeping a written-only 12 MiB element of 16-byte records bound it in place on a discrete GPU" : "a dispatch sweeping a written-only 12 MiB element of 16-byte records staged it on an integrated GPU");
Require(buildInPlace((12u << 20u) / 12u, false, 12, 0) != context.discreteGpu, context.discreteGpu ? "a dispatch sweeping a written-only 12 MiB element of 12-byte records bound it in place on a discrete GPU" : "a dispatch sweeping a written-only 12 MiB element of 12-byte records staged it on an integrated GPU");
Require(buildInPlace(1024, false, 32, 0), "a dispatch touching 32 KiB of a written-only 12 MiB element staged all of it");
Require(buildInPlace((12u << 20u) / 32u, false, 0, 32), "a dispatch writing a written-only 12 MiB raw element staged it");
Require(buildInPlace(204800, false, 160, 0, 204800u * 160u) != context.discreteGpu, context.discreteGpu ? "a dispatch sweeping a written-only 31.25 MiB element of 160-byte records bound it in place on a discrete GPU" : "a dispatch sweeping a written-only 31.25 MiB element of 160-byte records staged it on a GPU without separate VRAM");
@@ -5858,6 +5833,35 @@ void drawSnapshotUploadTests(const Device& device, Recorder& recorder) {
recorder.Activate();
}
void vertexWindowSeriesTests(const Device& device, Recorder& recorder) {
using namespace AgcDriver::GuestMemory;
using Use = Recorder::SnapshotUse;
constexpr std::size_t bytes = 65536;
void* block = AllocateWatched(bytes, 65536);
struct Release {
void* block;
~Release() { ReleaseWatched(block, bytes); }
} release{block};
auto* words = static_cast<std::uint32_t*>(block);
for (std::uint32_t i = 0; i < bytes / sizeof(std::uint32_t); ++i) words[i] = i * 7;
const auto& context = device.GetContext();
const auto address = reinterpret_cast<std::uint64_t>(block);
constexpr std::size_t quad = 4 * 32;
constexpr std::size_t draws = bytes / quad;
std::shared_ptr<Buffer> served;
for (std::size_t k = 0; k < draws; ++k) {
const auto from = (draws - 1 - k) * quad;
const auto copy = CopyDrawInput(context, &recorder, address, from + quad, 1, Use::Vertex, from);
Require(std::memcmp(copy.buffer->Bytes().data() + from, reinterpret_cast<const void*>(address + from), quad) == 0, "a draw at a falling lowest vertex got other bytes than the guest's");
KeepDrawInput(&recorder, address, copy, Use::Vertex, 0);
if (k == 0) served = copy.buffer;
Require(copy.buffer == served, "a draw below the vertex window of an earlier draw over the same buffer was copied again instead of filled into its snapshot");
}
words[(bytes - quad) / 4] = 0x4242;
const auto stored = CopyDrawInput(context, &recorder, address, bytes, 1, Use::Vertex, bytes - quad);
Require(!stored.reused && std::memcmp(stored.buffer->Bytes().data() + bytes - quad, reinterpret_cast<const void*>(address + bytes - quad), quad) == 0, "a store in the vertex window that served the falling draws was not seen");
}
void ownedDrawInputTests(const Device& device, Recorder& recorder) {
using namespace AgcDriver::GuestMemory;
using Use = Recorder::SnapshotUse;
@@ -6017,6 +6021,17 @@ void ownedDrawInputTests(const Device& device, Recorder& recorder) {
Require(!crossing.reused && crossing.owned.words.size() == 2, "a draw input spanning two blocks did not arm both");
KeepDrawInput(&recorder, address + 65536 - 128, crossing, Use::Index32, 0);
Require(copy(Use::Index32, 256, 65536 - 128).reused, "a two-block owned input was not reused");
constexpr std::size_t windowAt = 8192;
constexpr std::size_t windowBytes = 1024;
constexpr std::size_t windowFrom = 512;
const auto* windowGuest = static_cast<const std::byte*>(block) + windowAt;
const auto windowed = CopyDrawInput(context, &recorder, address + windowAt, windowBytes, 1, Use::Vertex, windowFrom);
Require(!windowed.reused && !windowed.owned.words.empty() && std::memcmp(windowed.buffer->Bytes().data() + windowFrom, windowGuest + windowFrom, windowBytes - windowFrom) == 0, "a windowed vertex input was not armed as an owned copy");
KeepDrawInput(&recorder, address + windowAt, windowed, Use::Vertex, 0);
const auto inside = CopyDrawInput(context, &recorder, address + windowAt, windowBytes, 1, Use::Vertex, windowFrom + 64);
Require(inside.reused && inside.buffer == windowed.buffer, "an owned vertex window was not reused by a draw that starts inside it");
const auto below = CopyDrawInput(context, &recorder, address + windowAt, windowBytes, 1, Use::Vertex);
Require(!below.reused && std::memcmp(below.buffer->Bytes().data(), windowGuest, windowBytes) == 0, "an owned vertex window served a draw that starts below it");
#endif
recorder.Sync();
}
@@ -6094,6 +6109,56 @@ void drawInputReuseTests(const Device& device, Recorder& recorder) {
KeepDrawInput(&recorder, pool, after, Use::Vertex, 0);
const auto small = CopyDrawInput(context, &recorder, pool, 4096, 1, Use::Vertex);
Require(small.reused && small.buffer == after.buffer, "the new vertex snapshot does not serve shorter reads");
const auto window = address + 32768;
const auto sameAsGuest = [&](const DrawInputCopy& copy, std::size_t from, std::size_t to) { return copy.buffer->Bytes().size() >= to && std::memcmp(copy.buffer->Bytes().data() + from, reinterpret_cast<const void*>(window + from), to - from) == 0; };
const auto tail = CopyDrawInput(context, &recorder, window, 16384, 1, Use::Vertex, 8192);
Require(!tail.reused && tail.from == 8192 && tail.buffer->Bytes().size() == 16384 && sameAsGuest(tail, 8192, 16384), "a vertex window copy is wrong");
KeepDrawInput(&recorder, window, tail, Use::Vertex, 0);
Require(CopyDrawInput(context, &recorder, window, 16384, 1, Use::Vertex, 8192).buffer == tail.buffer, "the same vertex window was copied again");
Require(CopyDrawInput(context, &recorder, window, 12288, 1, Use::Vertex, 9216).buffer == tail.buffer, "a vertex window inside the kept one was copied again");
words[(32768 + 1024) / 4] = 0x1234;
Require(CopyDrawInput(context, &recorder, window, 16384, 1, Use::Vertex, 8192).reused, "a store below a vertex window made its snapshot stale");
words[(32768 + 13312) / 4] = 0x5678;
const auto lower = CopyDrawInput(context, &recorder, window, 12288, 1, Use::Vertex, 4096);
Require(lower.reused && lower.buffer == tail.buffer && sameAsGuest(lower, 4096, 12288), "a vertex window below the kept one was not filled in from the guest");
const auto past = CopyDrawInput(context, &recorder, window, 16384, 1, Use::Vertex, 8192);
Require(!past.reused && sameAsGuest(past, 8192, 16384), "filling in a vertex window hid a store past the read that filled it");
KeepDrawInput(&recorder, window, past, Use::Vertex, 0);
const auto below = CopyDrawInput(context, &recorder, window, 4096, 1, Use::Vertex, 1024);
Require(below.reused && below.buffer == past.buffer && sameAsGuest(below, 1024, 4096), "a read below a vertex window was not filled in from the guest into its snapshot");
Require(CopyDrawInput(context, &recorder, window, 16384, 1, Use::Vertex, 8192).buffer == past.buffer, "a read below a vertex window dropped its snapshot");
const auto filled = CopyDrawInput(context, &recorder, window, 16384, 1, Use::Vertex);
Require(filled.reused && filled.buffer == past.buffer && sameAsGuest(filled, 0, 16384), "a whole read did not fill in the kept vertex window from the guest");
Require(CopyDrawInput(context, &recorder, window, 16384, 1, Use::Vertex, 4096).buffer == past.buffer, "a filled-in vertex window was copied again");
words[(32768 + 5120) / 4] = 0x9abc;
const auto refilled = CopyDrawInput(context, &recorder, window, 16384, 1, Use::Vertex, 4096);
Require(!refilled.reused && sameAsGuest(refilled, 4096, 16384), "a store in a filled-in vertex window was not seen");
bool refused = false;
try {
CopyDrawInput(context, &recorder, window, 256, 4, Use::Index32, 4);
} catch (const std::runtime_error& error) {
refused = std::string_view(error.what()).find("only a vertex input starts past its address") != std::string_view::npos;
if (!refused) throw;
}
Require(refused, "an index copy started past its address");
refused = false;
try {
CopyDrawInput(context, &recorder, window, 256, 1, Use::Vertex, 256);
} catch (const std::runtime_error& error) {
refused = std::string_view(error.what()).find("only a vertex input starts past its address") != std::string_view::npos;
if (!refused) throw;
}
Require(refused, "a vertex window started at its end");
const auto indices = CopyDrawInput(context, &recorder, window + 24576, 256, 4, Use::Index32);
KeepDrawInput(&recorder, window + 24576, indices, Use::Index32, 9, 7);
const auto keptIndices = CopyDrawInput(context, &recorder, window + 24576, 256, 4, Use::Index32);
Require(keptIndices.reused && keptIndices.derived == 9 && keptIndices.lowest == 7, "a kept index copy lost its lowest index");
const auto rangeAddress = window + 28672;
const auto rangeGeneration = CollectWrites(rangeAddress, 4096);
recorder.KeepHighestIndex(rangeAddress, 4096, Use::Index16, rangeGeneration, GuestAllocations::GuestAllocationsGeneration_nid_postfix(), 9u, 4u);
std::optional<std::uint32_t> rangeHighest;
std::uint32_t rangeLowest = 0;
Require(recorder.KnownHighestIndex(rangeAddress, 4096, Use::Index16, rangeHighest, &rangeLowest) && rangeHighest == 9u && rangeLowest == 4u, "a kept index range lost its lowest index");
recorder.Sync();
}
@@ -6176,9 +6241,9 @@ void drawInputInPlaceTests(const Device& device, Recorder& recorder, bool copied
first[2] = 0xffff;
std::memcpy(reinterpret_cast<void*>(indices), first.data(), kept * 2);
auto range = InPlaceIndexRange(recorder, indices, kept, 2, false);
Require(!range.reused && range.highest == 0xffffu, "an in-place index range was not scanned at its first use");
Require(!range.reused && range.highest == 0xffffu && range.lowest == 1u, "an in-place index range was not scanned at its first use");
range = InPlaceIndexRange(recorder, indices, kept, 2, false);
Require(range.reused && range.highest == 0xffffu, "an unchanged in-place index range was scanned again");
Require(range.reused && range.highest == 0xffffu && range.lowest == 1u, "an unchanged in-place index range was scanned again");
range = InPlaceIndexRange(recorder, indices, kept, 2, true);
Require(!range.reused && range.highest == 9u, "an in-place index range served a scan made under the other restart rule");
Require(!InPlaceIndexRange(recorder, indices, kept + 2, 2, true).reused, "an in-place index range served a scan of another size");
@@ -6197,7 +6262,7 @@ void drawInputInPlaceTests(const Device& device, Recorder& recorder, bool copied
Require(!InPlaceIndexRange(recorder, indices, kept * 2 - 4, 4, false).reused, "a 32-bit in-place index range below the kept size was kept");
Require(!InPlaceIndexRange(recorder, indices, kept * 2, 4, false).reused, "a 32-bit in-place index range was not scanned at its first use");
range = InPlaceIndexRange(recorder, indices, kept * 2, 4, false);
Require(range.reused && range.highest == 0x000c0003u, "an unchanged 32-bit in-place index range was scanned again");
Require(range.reused && range.highest == 0x000c0003u && range.lowest == 0x00010001u, "an unchanged 32-bit in-place index range was scanned again");
const std::vector<std::uint16_t> restarts(Recorder::KeptIndexRangeIndices, 0xffff);
std::memcpy(reinterpret_cast<void*>(indices + 20480), restarts.data(), kept);
Require(!InPlaceIndexRange(recorder, indices + 20480, kept, 2, true).highest.has_value(), "an index range of restart indices has a highest index");
@@ -8149,7 +8214,7 @@ bool pendingAfterLeavingWatchTests(const Device& device, Recorder& recorder) {
throw;
}
if (refused) {
const std::string unitCause = "(unit " + std::to_string(write == Write::PendingWithoutHook ? 0 : lastUnit) + " of " + std::to_string(units) + ": " + cause;
const std::string unitCause = "(unit " + std::to_string(lastUnit) + " of " + std::to_string(units) + ": " + cause;
Require(refusal.find(unitCause) != std::string::npos, "(p) " + what + ": the refusal does not name the cause '" + unitCause + "': " + refusal);
}
if (unhashed && refused) {
@@ -11495,16 +11560,17 @@ public:
recorder.PrepareSampleSlot();
begin(commands);
}
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
recorder.GraphicsState().BindPipeline(context, pipeline, 0);
recorder.NoteSampledDraw(commands);
context.Function<PFN_vkCmdDraw>("vkCmdDraw")(commands, 3, 1, 0, 0);
recorder.LeaveRenderPassOpen(PassKey, Recorder::NoTiming, false, PassAccess{});
return continued;
}
void Record(VkCommandBuffer commands) const {
void Record(CommandState& recording) const {
const auto commands = recording.Commands();
begin(commands);
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
recording.BindPipeline(context, pipeline, 0);
context.Function<PFN_vkCmdDraw>("vkCmdDraw")(commands, 3, 1, 0, 0);
EndRenderPass(context, commands);
}
@@ -11891,6 +11957,68 @@ void sampleDumpTests(const Device& device, Recorder& recorder) {
inPassSampleDumpTests(recorder, context, cover, words, address, target);
}
std::uint32_t uncountedGraphicsBinds = 0;
PFN_vkCmdBindPipeline uncountedRealBind = nullptr;
VKAPI_ATTR void VKAPI_CALL countingBind(VkCommandBuffer commands, VkPipelineBindPoint point, VkPipeline pipeline) {
if (point == VK_PIPELINE_BIND_POINT_GRAPHICS) ++uncountedGraphicsBinds;
uncountedRealBind(commands, point, pipeline);
}
void firstSampleCopyTrackingTest(const Device& device) {
auto context = device.GetContext();
uncountedRealBind = reinterpret_cast<PFN_vkCmdBindPipeline>(context.deviceProc(context.device, "vkCmdBindPipeline"));
DeviceFunctions hooks;
hooks.cmdBindPipeline = countingBind;
context.functions = &hooks;
const bool suppressing = std::getenv("APS5_NO_STATE_SUPPRESSION") == nullptr;
VkImageCreateInfo imageInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
imageInfo.extent = {8, 8, 1};
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.samples = VK_SAMPLE_COUNT_4_BIT;
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VkImage image = VK_NULL_HANDLE;
Check(context.Function<PFN_vkCreateImage>("vkCreateImage")(context.device, &imageInfo, nullptr, &image), "vkCreateImage first sample source");
VkMemoryRequirements requirements{};
context.Function<PFN_vkGetImageMemoryRequirements>("vkGetImageMemoryRequirements")(context.device, image, &requirements);
VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
allocation.allocationSize = requirements.size;
allocation.memoryTypeIndex = context.MemoryType(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VkDeviceMemory memory = VK_NULL_HANDLE;
Check(context.Function<PFN_vkAllocateMemory>("vkAllocateMemory")(context.device, &allocation, nullptr, &memory), "vkAllocateMemory first sample source");
Check(context.Function<PFN_vkBindImageMemory>("vkBindImageMemory")(context.device, image, memory, 0), "vkBindImageMemory first sample source");
VkImageViewCreateInfo viewInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
viewInfo.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageView view = VK_NULL_HANDLE;
Check(context.Function<PFN_vkCreateImageView>("vkCreateImageView")(context.device, &viewInfo, nullptr, &view), "vkCreateImageView first sample source");
FirstSampleCopy copy(context, VK_FORMAT_R8G8B8A8_UNORM, {8, 8});
Recorder recorder(context);
VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.image = image;
barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(recorder.Commands(), VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
uncountedGraphicsBinds = 0;
copy.Record(recorder, view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
Require(uncountedGraphicsBinds == 1, "the first sample copy did not bind its pipeline through the recorder's graphics state");
Require((recorder.GraphicsState().BoundPipeline() != VK_NULL_HANDLE) == suppressing, "the first sample copy left the recorder's graphics state without its pipeline");
recorder.Submit();
recorder.Sync();
context.Function<PFN_vkDestroyImageView>("vkDestroyImageView")(context.device, view, nullptr);
context.Function<PFN_vkDestroyImage>("vkDestroyImage")(context.device, image, nullptr);
context.Function<PFN_vkFreeMemory>("vkFreeMemory")(context.device, memory, nullptr);
}
void uncountedPassTests(const Device& device) {
auto context = device.GetContext();
context.bufferDeviceAddress = false;
@@ -11900,13 +12028,212 @@ void uncountedPassTests(const Device& device) {
Require(!recorder.QueuesSampleDumps(), "a recorder without buffer device addresses counted samples in segments");
const auto base = recorder.SamplesTotal();
cover.Draw(recorder);
recorder.RecordUncounted([&](VkCommandBuffer commands) { cover.Record(commands); });
const bool suppressing = std::getenv("APS5_NO_STATE_SUPPRESSION") == nullptr;
const VkRect2D area{{0, 0}, {8, 8}};
recorder.Commands();
auto& tracked = recorder.GraphicsState();
tracked.SetScissor(context, area);
Require(tracked.Known(CommandState::Scissor) == suppressing, "the recorder's graphics state does not follow APS5_NO_STATE_SUPPRESSION");
recorder.RecordUncounted([&](CommandState& recording) {
Require(&recording == &tracked, "the uncounted recording got another graphics state than the recorder's");
Require(recording.Known(CommandState::Scissor) == suppressing, "the graphics state was forgotten entering an uncounted recording");
cover.Record(recording);
});
Require(!tracked.Known(CommandState::Scissor), "the static pipeline of an uncounted recording left the scissor known");
Require((tracked.BoundPipeline() != VK_NULL_HANDLE) == suppressing, "the pipeline an uncounted recording bound is not the tracked one");
cover.Draw(recorder);
recorder.Submit();
recorder.Sync();
const auto counted = recorder.SamplesTotal() - base;
Require(counted != 0, "the draws around an uncounted pass were not counted");
if (context.occlusionQueryPrecise) Require(counted == 2 * CoverPass::Samples, "the batch-wide occlusion query counted " + std::to_string(counted) + " samples, not the " + std::to_string(2 * CoverPass::Samples) + " of the two draws around an uncounted pass");
Recorder plain(context);
plain.Commands();
auto& state = plain.GraphicsState();
state.SetScissor(context, area);
Require(state.Known(CommandState::Scissor) == suppressing, "the plain recorder could not set the scissor");
try {
plain.RecordUncounted([&](CommandState&) {
state.SetScissor(context, VkRect2D{{0, 0}, {4, 4}});
throw std::runtime_error("uncounted recording failed");
});
} catch (const std::runtime_error&) {
}
Require(state.Known(CommandState::Scissor) == suppressing, "the graphics state was forgotten after an uncounted recording threw");
plain.Submit();
plain.Sync();
firstSampleCopyTrackingTest(device);
}
class CommandBufferReuse {
public:
explicit CommandBufferReuse(Context& context) : context(context), resolver(context.deviceProc) {
Require(active == nullptr, "nested command buffer reuse");
active = this;
context.deviceProc = resolve;
}
~CommandBufferReuse() {
context.deviceProc = resolver;
if (!retained.empty()) reinterpret_cast<PFN_vkFreeCommandBuffers>(resolver(context.device, "vkFreeCommandBuffers"))(context.device, pool, static_cast<std::uint32_t>(retained.size()), retained.data());
active = nullptr;
}
CommandBufferReuse(const CommandBufferReuse&) = delete;
CommandBufferReuse& operator=(const CommandBufferReuse&) = delete;
std::uint32_t Reused() const { return reused; }
private:
static VKAPI_ATTR VkResult VKAPI_CALL allocateBuffers(VkDevice device, const VkCommandBufferAllocateInfo* info, VkCommandBuffer* buffers) {
if (info->commandBufferCount == 1 && !active->retained.empty()) {
*buffers = active->retained.back();
active->retained.pop_back();
++active->reused;
return VK_SUCCESS;
}
return reinterpret_cast<PFN_vkAllocateCommandBuffers>(active->resolver(device, "vkAllocateCommandBuffers"))(device, info, buffers);
}
static VKAPI_ATTR void VKAPI_CALL freeBuffers(VkDevice, VkCommandPool pool, std::uint32_t count, const VkCommandBuffer* buffers) {
active->pool = pool;
active->retained.insert(active->retained.end(), buffers, buffers + count);
}
static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL resolve(VkDevice device, const char* name) {
if (std::strcmp(name, "vkAllocateCommandBuffers") == 0) return reinterpret_cast<PFN_vkVoidFunction>(allocateBuffers);
if (std::strcmp(name, "vkFreeCommandBuffers") == 0) return reinterpret_cast<PFN_vkVoidFunction>(freeBuffers);
return active->resolver(device, name);
}
Context& context;
PFN_vkGetDeviceProcAddr resolver;
VkCommandPool pool = VK_NULL_HANDLE;
std::vector<VkCommandBuffer> retained;
std::uint32_t reused = 0;
static inline CommandBufferReuse* active = nullptr;
};
void graphicsStateTests(const Device& device) {
using namespace CommandStateLog;
const bool suppressing = std::getenv("APS5_NO_STATE_SUPPRESSION") == nullptr;
auto context = device.GetContext();
const auto hooks = stateFunctions();
context.functions = &hooks;
statePipelines.clear();
stateLog.clear();
const auto drawn = [&](Recorder& recorder, VkPipeline pipeline) {
recorder.Commands();
stateTrackedDraw(recorder.GraphicsState(), context, pipeline);
};
const auto first = stateFakePipeline(0);
const auto second = stateFakePipeline(1);
const auto full = stateTrackedDrawLines(first);
const auto none = [&](VkPipeline pipeline) { return suppressing ? std::vector<std::string>{} : stateTrackedDrawLines(pipeline); };
{
CommandBufferReuse reuse(context);
Recorder recorder(context);
VkCommandBuffer previous = VK_NULL_HANDLE;
for (std::uint32_t round = 0; round < 3; ++round) {
drawn(recorder, first);
const auto commands = recorder.Commands();
Require(recorder.GraphicsState().Commands() == commands, "the recorder's graphics state records into another command buffer");
if (round != 0) Require(commands == previous && reuse.Reused() == round, "the reopened batch did not reuse its command buffer handle");
previous = commands;
expectStateLog(full, "the first draw of batch " + std::to_string(round));
drawn(recorder, first);
expectStateLog(none(first), "an identical second draw of batch " + std::to_string(round));
recorder.Submit();
recorder.Sync();
}
}
{
CommandBufferReuse reuse(context);
Recorder recorder(context);
drawn(recorder, first);
const auto abandoned = recorder.Commands();
expectStateLog(full, "the draw before a failed submit");
recorder.FailNextSubmitsForTest(1);
bool failed = false;
try {
recorder.Submit();
} catch (const std::runtime_error&) {
failed = true;
}
recorder.FailNextSubmitsForTest(0);
Require(failed, "the injected submit failure did not surface");
drawn(recorder, first);
Require(recorder.Commands() == abandoned && reuse.Reused() == 1, "the batch opened after the failed submit did not recycle the abandoned command buffer handle");
expectStateLog(full, "the first draw after a failed submit on a recycled command buffer handle");
recorder.Submit();
recorder.Sync();
}
{
Recorder one(context);
Recorder other(context);
drawn(one, first);
expectStateLog(full, "the first recorder's first draw");
drawn(other, first);
expectStateLog(full, "the second recorder's first draw after the first recorder's");
Require(&one.GraphicsState() != &other.GraphicsState(), "two recorders share one graphics state");
drawn(one, first);
expectStateLog(none(first), "the first recorder's repeated draw after the second recorder's first");
drawn(other, second);
expectStateLog(suppressing ? std::vector<std::string>{stateLine("bind", 0u, second)} : stateTrackedDrawLines(second), "the second recorder binding another pipeline");
drawn(one, first);
expectStateLog(none(first), "the first recorder's draw after the second recorder bound another pipeline");
drawn(other, second);
expectStateLog(none(second), "the second recorder's repeated draw of its pipeline");
one.Submit();
other.Submit();
one.Sync();
other.Sync();
}
{
Recorder recorder(context);
drawn(recorder, first);
expectStateLog(full, "the draw before raw state commands");
const VkViewport moved{0.0f, 0.0f, 8.0f, 8.0f, 0.0f, 1.0f};
recorder.RecordUncounted([&](CommandState& recording) {
recording.BindPipeline(context, second, 0);
recording.SetViewport(context, moved);
});
expectStateLog({stateLine("bind", 0u, second), stateLine("viewport", 0.0f, 0.0f, 8.0f, 8.0f, 0.0f, 1.0f)}, "a static pipeline and a moved viewport in an uncounted recording");
drawn(recorder, first);
expectStateLog(full, "the same draw after a static pipeline invalidated the dynamic state");
recorder.RecordUncounted([&](CommandState& recording) {
recording.BindPipeline(context, second, CommandState::DynamicSlots(PipelineLibraryDynamicStates()));
recording.SetViewport(context, moved);
});
expectStateLog({stateLine("bind", 0u, second), stateLine("viewport", 0.0f, 0.0f, 8.0f, 8.0f, 0.0f, 1.0f)}, "a dynamic pipeline and a moved viewport in an uncounted recording");
drawn(recorder, first);
expectStateLog(suppressing ? std::vector<std::string>{stateLine("bind", 0u, first), stateLine("viewport", 0.0f, 0.0f, 64.0f, 32.0f, 0.0f, 1.0f)} : full, "the same draw after an uncounted recording moved only the viewport");
recorder.RecordUncounted([&](CommandState& recording) {
recording.BindPipeline(context, second, CommandState::DynamicSlots(PipelineLibraryDynamicStates()));
});
expectStateLog({stateLine("bind", 0u, second)}, "a dynamic pipeline in an uncounted recording");
drawn(recorder, first);
expectStateLog(suppressing ? std::vector<std::string>{stateLine("bind", 0u, first)} : full, "the same draw after an uncounted recording that only bound another pipeline");
recorder.Submit();
recorder.Sync();
}
{
Recorder recorder(context);
drawn(recorder, first);
expectStateLog(full, "the draw before an uncounted recording");
recorder.RecordUncounted([](CommandState&) {});
drawn(recorder, first);
expectStateLog(none(first), "the same draw after an empty uncounted recording");
try {
recorder.RecordUncounted([&](CommandState& recording) {
recording.BindPipeline(context, second, CommandState::DynamicSlots(PipelineLibraryDynamicStates()));
throw std::runtime_error("uncounted recording failed");
});
} catch (const std::runtime_error&) {
}
expectStateLog({stateLine("bind", 0u, second)}, "the bind before an uncounted recording threw");
drawn(recorder, first);
expectStateLog(suppressing ? std::vector<std::string>{stateLine("bind", 0u, first)} : full, "the same draw after an uncounted recording that threw");
recorder.Submit();
recorder.Sync();
}
statePipelines.clear();
stateLog.clear();
std::cout << "graphics state through the recorder passed (" << (suppressing ? "suppressing" : "unsuppressed") << ")\n";
}
void cmaskPassTests(const Device& device, Recorder& recorder) {
@@ -13171,7 +13498,7 @@ public:
context.Function<PFN_vkUpdateDescriptorSets>("vkUpdateDescriptorSets")(context.device, 2, writes, 0, nullptr);
const auto commands = recorder.Commands();
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT);
context.Function<PFN_vkCmdBindPipeline>("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
context.BindComputePipeline(commands, pipeline);
context.Function<PFN_vkCmdBindDescriptorSets>("vkCmdBindDescriptorSets")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &set, 0, nullptr);
const float parameters[]{lod, layer};
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(parameters), parameters);
@@ -14915,7 +15242,7 @@ bool clearHandOverTests(const Device& device, Recorder& recorder, bool watched)
constexpr std::array<std::uint8_t, 4> blue{0, 0, 255, 255};
constexpr std::array<std::uint8_t, 8> green{0, 0, 0x00, 0x3c, 0, 0, 0x00, 0x3c};
constexpr std::array<std::uint8_t, 8> cleared{};
enum class Order { Superseded, ReadFirst, Rewritten, CpuStore };
enum class Order { Superseded, ReadFirst, Rewritten, CpuStore, SampledClear };
enum class Path { Refresh, Creation, Detached };
struct Outcome {
std::vector<std::byte> bytes;
@@ -14925,9 +15252,10 @@ bool clearHandOverTests(const Device& device, Recorder& recorder, bool watched)
};
const auto pathName = [](Path path) { return std::string(path == Path::Refresh ? ", at B's refresh" : path == Path::Creation ? ", at B's creation" : ", at B's creation after A left the cache"); };
const auto run = [&](bool on, Order order, Path path) {
const std::string where = what + pathName(path) + (order == Order::Superseded ? ", A never read again" : order == Order::ReadFirst ? ", A read before B wrote" : order == Order::Rewritten ? ", A written again after the hand-over" : ", a CPU store before B wrote") + (on ? ", on" : ", off");
const std::string where = what + pathName(path) + (order == Order::Superseded ? ", A never read again" : order == Order::ReadFirst ? ", A read before B wrote" : order == Order::Rewritten ? ", A written again after the hand-over" : order == Order::CpuStore ? ", a CPU store before B wrote" : ", B sampled under clear keys") + (on ? ", on" : ", off");
StorageTexture::SetClearHandOver(on);
recorder.Sync();
ClearCachedTextures(context.device);
std::memset(memory, 0x55, surfaceA);
std::memset(memory + surfaceA, 0x00, keyCount);
Outcome outcome{};
@@ -14936,7 +15264,7 @@ bool clearHandOverTests(const Device& device, Recorder& recorder, bool watched)
{
auto imageA = StorageTexture::Create(context, detiler, resourceA, 0);
std::shared_ptr<StorageTexture> imageB;
if (path == Path::Refresh) imageB = StorageTexture::Create(context, detiler, resourceB, 0);
if (path == Path::Refresh) imageB = CachedStorageSurface(context, resourceB);
draw(imageA, {{1.0f, 0.0f, 0.0f, 1.0f}});
const std::weak_ptr<StorageTexture> weakA = imageA;
if (path == Path::Refresh) {
@@ -14978,6 +15306,22 @@ bool clearHandOverTests(const Device& device, Recorder& recorder, bool watched)
if (order == Order::CpuStore) {
std::memset(memory + 65536, 0x77, 65536);
}
if (order == Order::SampledClear) {
const auto meta = resourceB.dccAddress >> 8u;
std::array<std::uint32_t, 8> words{};
words[0] = static_cast<std::uint32_t>(resourceB.baseAddress >> 8u);
words[1] = static_cast<std::uint32_t>((resourceB.baseAddress >> 40u) & 0xffu) | (resourceB.format << 20u) | (((resourceB.width - 1u) & 3u) << 30u);
words[2] = ((resourceB.width - 1u) >> 2u) | ((resourceB.height - 1u) << 14u);
words[3] = 0xfa4u | (27u << 20u) | (9u << 28u);
words[6] = (1u << 21u) | static_cast<std::uint32_t>((meta & 0xffu) << 24u);
words[7] = static_cast<std::uint32_t>(meta >> 8u);
const auto sampled = CachedSampledTexture(context, words);
Require(sampled != nullptr && sampled->ViewsStorageImage() && sampled->SharedStorageSource() == imageB, where + ": B sampled under clear keys did not view B's cleared storage image");
if (on && watched) {
Require(std::all_of(memory, memory + 2 * 65536, [](std::uint8_t value) { return value == 0x55; }), where + ": sampling B stored A's results over B");
Require(filled(readMemory(address, 65536), red), where + ": reading A's memory after B was sampled, before B wrote, did not see A's results");
}
}
draw(imageB, {{0.0f, 1.0f, 0.0f, 1.0f}});
Require(StorageTexture::FlushPending(address, bytes, nullptr, "clear-key hand-over test", PublishScope::Whole), where + ": nothing was pending at the end");
recorder.Submit();
@@ -14986,15 +15330,17 @@ bool clearHandOverTests(const Device& device, Recorder& recorder, bool watched)
outcome.bytes = readMemory(address, surfaceA);
Require(filled(readImage(imageB, 128, 128, 8), green), where + ": B lost its results");
}
ClearCachedTextures(context.device);
outcome.handOvers = StorageTexture::ClearHandOvers() + StorageTexture::CreationHandOvers() - handOvers;
outcome.superseded = StorageTexture::HandedOverSuperseded() - superseded;
recorder.Sync();
return outcome;
};
for (const auto path : {Path::Refresh, Path::Creation, Path::Detached})
for (const auto order : {Order::Superseded, Order::ReadFirst, Order::Rewritten, Order::CpuStore}) {
for (const auto order : {Order::Superseded, Order::ReadFirst, Order::Rewritten, Order::CpuStore, Order::SampledClear}) {
if (path == Path::Detached && order == Order::Rewritten) continue;
const std::string name = what + pathName(path) + (order == Order::Superseded ? ", A never read again" : order == Order::ReadFirst ? ", A read before B wrote" : order == Order::Rewritten ? ", A written again after the hand-over" : ", a CPU store before B wrote");
if (path != Path::Refresh && order == Order::SampledClear) continue;
const std::string name = what + pathName(path) + (order == Order::Superseded ? ", A never read again" : order == Order::ReadFirst ? ", A read before B wrote" : order == Order::Rewritten ? ", A written again after the hand-over" : order == Order::CpuStore ? ", a CPU store before B wrote" : ", B sampled under clear keys");
const auto off = run(false, order, path);
const auto on = run(true, order, path);
const auto& lastA = order == Order::Rewritten ? blue : red;
@@ -15008,6 +15354,7 @@ bool clearHandOverTests(const Device& device, Recorder& recorder, bool watched)
continue;
}
if (order == Order::Superseded) Require(on.superseded == 2, name + ": B's results did not drop A's two units under B (dropped " + std::to_string(on.superseded) + ")");
if (order == Order::SampledClear && watched) Require(on.superseded == 1, name + ": B's write did not drop only A's remaining unit after the sample-time read (dropped " + std::to_string(on.superseded) + ")");
if (order == Order::ReadFirst) Require(on.superseded <= 1, name + ": a unit stored by the read was dropped again");
}
static_assert(2 * keyCount <= bytes - surfaceA, "B's and C's DCC keys both follow A inside the block");
@@ -15528,6 +15875,98 @@ void Run(Context context) {
}
#endif
namespace UnwatchScopeTest {
constexpr std::size_t Unit = 65536;
constexpr std::size_t Bytes = 4 * Unit;
constexpr std::uint32_t Initial = 0x11111111u;
constexpr std::uint32_t Gpu = 0xa1a1a1a1u;
constexpr std::uint32_t Cpu = 0xc3c3c3c3u;
std::size_t readBytes = 0;
void CountReads(std::uint64_t, std::size_t bytes) {
readBytes += bytes;
}
class WatchedBlock {
public:
WatchedBlock() : data(AllocateWatched(Bytes, Unit)) {
Require(data != nullptr, "cannot allocate watched surface");
std::fill_n(static_cast<std::uint32_t*>(data), Bytes / 4, Initial);
GuestAllocations::Mutation().Add(data, Bytes, true, true, true);
Require(AgcDriver::GuestMemory::Watched(Address(), Bytes), "surface is not watched");
}
~WatchedBlock() {
GuestAllocations::Mutation().Remove(data);
ReleaseWatched(data, Bytes);
}
std::uint64_t Address() const { return reinterpret_cast<std::uint64_t>(data); }
std::uint32_t* Words() const { return static_cast<std::uint32_t*>(data); }
private:
void* data;
};
bool Run(Context context, Recorder& recorder, bool refresh = false, bool edge = false, bool linear = false) {
if (!AgcDriver::GuestMemory::WriteWatched()) return false;
context.hostImportAlignment = 0;
TextureDetiler detiler(context);
context.detiler = &detiler;
WatchedBlock block;
std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex());
GuestTextureResource descriptor{};
descriptor.baseAddress = block.Address();
descriptor.width = 128;
descriptor.height = 128;
descriptor.depthOrLastArray = 3;
descriptor.mipCount = 1;
descriptor.tileMode = linear ? TextureTileMode::kLinear : TextureTileMode::kR64KBX;
descriptor.dimension = TextureDimension::k2DArray;
descriptor.format = 20;
descriptor.dstSelX = 0;
descriptor.dstSelY = 1;
descriptor.dstSelZ = 2;
descriptor.dstSelW = 3;
auto image = StorageTexture::Create(context, detiler, descriptor, 0);
recorder.Sync();
Require(image->BlockUnits() == !linear && image->TrackedUnits() == 4 && image->GuestBytes() == Bytes, "surface does not have four independent units");
{
CommandBatch batch(context);
RecordMemoryBarrier(context, batch.Handle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
VkClearColorValue value{};
value.uint32[0] = Gpu;
const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 4};
context.Function<PFN_vkCmdClearColorImage>("vkCmdClearColorImage")(batch.Handle(), image->Image(), VK_IMAGE_LAYOUT_GENERAL, &value, 1, &range);
RecordMemoryBarrier(context, batch.Handle(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT);
batch.SubmitAndWait();
}
image->MarkWholeWritten();
Require(!image->GuestSnapshotValid(), "GPU results unexpectedly retain a complete CPU baseline");
struct ResetGuard {
~ResetGuard() { AgcDriver::GuestMemory::SetReadGuard(nullptr); }
} reset;
AgcDriver::GuestMemory::SetReadGuard(&CountReads);
AgcDriver::GuestMemory::Unwatch(block.Address() + (edge ? 4096 : 0), edge ? 4096 : Unit);
AgcDriver::GuestMemory::SetReadGuard(nullptr);
const auto firstUnwatchBytes = readBytes;
Require(!AgcDriver::GuestMemory::Watched(block.Address(), Unit), "first unit stayed watched");
Require(AgcDriver::GuestMemory::Watched(block.Address() + Unit, Bytes - Unit), "unwatch changed neighbouring units");
std::fill_n(block.Words() + Unit / 4, Unit / 4, Cpu);
AgcDriver::GuestMemory::Unwatch(block.Address() + Unit, Unit);
std::fill_n(block.Words() + 2 * Unit / 4, Unit / 4, Cpu);
if (refresh) image->Refresh();
image->WriteBack();
recorder.Sync();
for (std::size_t index = 0; index < Bytes / 4; ++index) {
const auto expected = index >= Unit / 4 && index < 3 * Unit / 4 ? Cpu : Gpu;
Require(block.Words()[index] == expected, "partial unwatch lost CPU writes or another unit's GPU results");
}
image.reset();
std::cout << "first unwatch copied " << firstUnwatchBytes << " bytes for " << Unit << " bytes leaving the watch; CPU/GPU preservation passed\n";
Require(firstUnwatchBytes == Unit, "unwatch copied pending units outside the range leaving the watch");
return true;
}
}
namespace SmallElementDetileTest {
std::uint32_t equationOffset(const TextureSwizzleEquation& equation, std::uint32_t x, std::uint32_t y) {
@@ -16170,6 +16609,11 @@ int main(int argc, char** argv) {
}
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--unwatch-snapshot-scope-only") return UnwatchScopeTest::Run(device.GetContext(), recorder) ? 0 : 77;
if (argc == 2 && std::string_view(argv[1]) == "--unwatch-snapshot-scope-refresh-only") return UnwatchScopeTest::Run(device.GetContext(), recorder, true) ? 0 : 77;
if (argc == 2 && std::string_view(argv[1]) == "--unwatch-snapshot-scope-edge-only") return UnwatchScopeTest::Run(device.GetContext(), recorder, false, true) ? 0 : 77;
if (argc == 2 && std::string_view(argv[1]) == "--unwatch-snapshot-scope-linear-only") return UnwatchScopeTest::Run(device.GetContext(), recorder, false, false, true) ? 0 : 77;
if (argc == 2 && std::string_view(argv[1]) == "--unwatch-snapshot-scope-linear-refresh-only") return UnwatchScopeTest::Run(device.GetContext(), recorder, true, false, true) ? 0 : 77;
if (argc == 2 && std::string_view(argv[1]) == "--small-tiled-shadow-label-only") {
return smallTiledShadowLabelTests(device, recorder) ? 0 : 77;
}
@@ -16254,6 +16698,10 @@ int main(int argc, char** argv) {
std::cout << "Occlusion counter dump tests passed\n";
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--graphics-state-only") {
graphicsStateTests(device);
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--snapshot-read-into-staging-only") {
if (!snapshotReadIntoStagingTests(device, recorder)) return 77;
std::cout << "Snapshot read into staging tests passed\n";
@@ -16309,6 +16757,13 @@ int main(int argc, char** argv) {
std::cout << "In-place draw input tests passed\n";
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--draw-input-reuse-only") {
if (!AgcDriver::GuestMemory::WriteWatched()) return 77;
drawInputReuseTests(device, recorder);
vertexWindowSeriesTests(device, recorder);
std::cout << "Draw input reuse tests passed\n";
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--draw-inputs-copied-only") {
drawInputInPlaceTests(device, recorder, true);
std::cout << "Copied draw input tests passed\n";
@@ -16406,6 +16861,7 @@ int main(int argc, char** argv) {
unwrittenSnapshotTests(device);
drawSnapshotUploadTests(device, recorder);
drawInputReuseTests(device, recorder);
if (AgcDriver::GuestMemory::WriteWatched()) vertexWindowSeriesTests(device, recorder);
drawInputInPlaceTests(device, recorder);
RunResidentPresentTests(device.GetContext());
sliceDirtyTests(device, recorder);
Loaded 100 of 639 files, more files were not shown because too many files have changed in this diff. Show more