From bd23785d4a30559d7ab15e021fb940cc694e94a1 Mon Sep 17 00:00:00 2001 From: panicDa3m0n <44086061+panicDa3m0n@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:07:10 +0200 Subject: [PATCH 1/6] perf(agc): keep draw snapshots in resizable BAR memory Draw snapshots of read-only storage buffers and the vertex and index copies of draws now live in device-local host-visible memory when the device exposes it through a resizable BAR (a heap of at least 4 GiB), and in host memory otherwise. The CPU still fills them with memcpy, but the GPU reads them from VRAM instead of over PCIe. The CPU never reads that memory back: refreshing a stale snapshot rewrites its changed blocks without comparing them, and the highest index of a copied index buffer is scanned from a host copy. APS5_NO_BAR_SNAPSHOTS keeps the previous host memory. On an RTX 4070 Ti SUPER (driver 616.64, PCIe 4.0 x16), shaders read host memory at 6-8 GB/s sequentially and 1.4 GB/s scattered, against 650 and 92 GB/s from VRAM. AI-assisted: yes. --- .../Graphics/include/Context.hpp | 18 +++++++++++++++ .../Graphics/include/Resources.hpp | 1 + .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 16 +++++++++++--- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 4 ++-- .../Graphics/src/ShaderResources.cpp | 2 +- .../prx/libSceAgcDriver/tests/Graphics.cpp | 22 +++++++++++++++++++ docs/dev/ENVIRONMENT.md | 1 + 7 files changed, 58 insertions(+), 6 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index 4167955e8c92..713c845bbdde 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -151,6 +152,18 @@ inline std::uint64_t& DeviceProcLookups() { inline constexpr std::size_t EmptyBufferBytes = 16; +inline VkMemoryPropertyFlags SnapshotMemoryProperties(const VkPhysicalDeviceMemoryProperties& memory, bool disabled) { + constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + constexpr VkMemoryPropertyFlags bar = host | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + constexpr VkDeviceSize ResizableBarBytes = VkDeviceSize{4} << 30u; + if (disabled) return host; + for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) { + const auto& type = memory.memoryTypes[i]; + if ((type.propertyFlags & bar) == bar && type.heapIndex < memory.memoryHeapCount && memory.memoryHeaps[type.heapIndex].size >= ResizableBarBytes) return bar; + } + return host; +} + struct Context { VkDevice device; VkPhysicalDevice physical; @@ -289,6 +302,11 @@ struct Context { return Function(name); } + VkMemoryPropertyFlags SnapshotProperties() const { + static const bool disabled = std::getenv("APS5_NO_BAR_SNAPSHOTS") != nullptr; + return SnapshotMemoryProperties(memory, disabled); + } + std::uint32_t MemoryType(std::uint32_t mask, VkMemoryPropertyFlags flags) const { for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) { if ((mask & (1u << i)) != 0 && (memory.memoryTypes[i].propertyFlags & flags) == flags) return i; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp index 674cff0c47d0..7d814f21d940 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Resources.hpp @@ -18,6 +18,7 @@ class Buffer { // shadows of GuestBufferMemory) has no mapping and its bytes move by GPU copies alone. std::span Bytes(); bool Mapped() const { return mapping != nullptr; } + VkMemoryPropertyFlags Properties() const { return properties; } void Invalidate(); private: diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 71872541dad6..94ff467d9682 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libc/include/HostThreadLocal.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetTransfer.hpp" #include "prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp" @@ -950,11 +951,20 @@ DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uin return copy; } } - copy.buffer = std::make_shared(context, bytes, use == Recorder::SnapshotUse::Vertex ? VK_BUFFER_USAGE_VERTEX_BUFFER_BIT : VK_BUFFER_USAGE_INDEX_BUFFER_BIT); + copy.buffer = std::make_shared(context, bytes, use == Recorder::SnapshotUse::Vertex ? VK_BUFFER_USAGE_VERTEX_BUFFER_BIT : VK_BUFFER_USAGE_INDEX_BUFFER_BIT, context.SnapshotProperties()); GuestMemory::Read(address, copy.buffer->Bytes(), alignment); return copy; } +std::span HostReadableInput(const DrawInputCopy& copy, std::uint64_t address, std::size_t bytes, std::size_t alignment) { + if ((copy.buffer->Properties() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) return copy.buffer->Bytes().first(bytes); + struct ScratchTag; + auto& scratch = HostThreadLocal, ScratchTag>(); + scratch.resize(bytes); + GuestMemory::Read(address, scratch, alignment); + return scratch; +} + DrawInputCopy CopyZeroPaddedDrawInput(const Context& context, std::uint64_t address, std::size_t bytes, std::size_t validBytes, std::size_t stride) { Require(validBytes <= bytes, "the valid bytes of a vertex fetch exceed the fetch"); GuestMemory::FlushGpuWrites(address, bytes); @@ -1226,7 +1236,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P if (import != nullptr) { highest = InPlaceIndexRange(*context.recorder, draw.indexAddress, static_cast(indexBytes), draw.indexSize, skipRestart).highest; } else if (!copy.reused) { - highest = HighestDrawIndex(copy.buffer->Bytes().first(static_cast(indexBytes)), draw.indexSize, skipRestart); + highest = HighestDrawIndex(HostReadableInput(copy, draw.indexAddress, static_cast(indexBytes), draw.indexSize), 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; @@ -1259,7 +1269,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P Require(!fanGeometry || !state.primitiveRestart || *highest != (draw.indexSize == 2 ? 0xffffu : 0xffffffffu), "primitive restart in a triangle fan geometry draw is unsupported"); inputs.maxIndex = *highest; if (skipRestart && state.stages.mesh && state.stages.mesh->inputPrimitive == 6) { - const auto indexSpan = import != nullptr ? std::span(reinterpret_cast(draw.indexAddress), static_cast(indexBytes)) : copy.buffer->Bytes().first(static_cast(indexBytes)); + const auto indexSpan = import != nullptr ? std::span(reinterpret_cast(draw.indexAddress), static_cast(indexBytes)) : HostReadableInput(copy, draw.indexAddress, static_cast(indexBytes), draw.indexSize); inputs.restartTable = MeshRestartTable(indexSpan, draw.indexSize); } if (import != nullptr) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 9f03343a6756..70f1df15f363 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -2736,7 +2736,7 @@ Recorder::UploadSlice Recorder::DrawUpload(std::size_t bytes) { const VkDeviceSize alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 16); auto offset = (drawUploadUsed + alignment - 1) & ~(alignment - 1); if (drawUpload == nullptr || offset + bytes > drawUpload->Bytes().size()) { - drawUpload = std::make_shared(context, std::max(DrawUploadChunk, bytes), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); + drawUpload = std::make_shared(context, std::max(DrawUploadChunk, bytes), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, context.SnapshotProperties()); offset = 0; } drawUploadUsed = offset + bytes; @@ -2820,7 +2820,7 @@ bool Recorder::refreshDrawSnapshot(DrawSnapshot& entry, std::uint64_t address, s spans.push_back({held.data() + offset, reinterpret_cast(from), static_cast(to - from)}); } equal.assign(spans.size(), 0); - CompareSpans(spans, equal); + if ((entry.buffer->Properties() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) CompareSpans(spans, equal); for (std::size_t k = 0; k < spans.size(); ++k) { if (equal[k] != 0) continue; const auto offset = static_cast(static_cast(spans[k].first) - held.data()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index d6d84cd4aa5f..57d53b5e7791 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -5489,7 +5489,7 @@ std::shared_ptr ShaderResources::PrepareDrawBindi const auto generation = GuestMemory::CollectWrites(begin, bytes); buffer = recorder.ReusableDrawSnapshot(begin, bytes, Recorder::SnapshotUse::Storage, nullptr, generation); if (buffer == nullptr) { - buffer = std::make_shared(context, bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); + buffer = std::make_shared(context, bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, context.SnapshotProperties()); std::memcpy(buffer->Bytes().data(), reinterpret_cast(begin), bytes); recorder.KeepDrawSnapshot(begin, bytes, generation, registryGeneration, buffer); } diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index b8e4c70b4b4c..f6025f54d111 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -10187,6 +10187,27 @@ void meshIndexBufferTests() { expectFailure([] { static_cast(AgcDriver::Graphics::MeshIndexBufferDescriptor(AgcDriver::Pm4::DrawParameters{0, 3, 2, 1, 0, true})); }, "invalid mesh index buffer range"); } +void snapshotMemoryTests() { + constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + constexpr VkMemoryPropertyFlags bar = host | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + VkPhysicalDeviceMemoryProperties memory{}; + memory.memoryHeapCount = 2; + memory.memoryHeaps[0] = {VkDeviceSize{16} << 30u, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + memory.memoryHeaps[1] = {VkDeviceSize{32} << 30u, 0}; + memory.memoryTypeCount = 3; + memory.memoryTypes[0] = {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0}; + memory.memoryTypes[1] = {host | VK_MEMORY_PROPERTY_HOST_CACHED_BIT, 1}; + memory.memoryTypes[2] = {bar, 0}; + Require(AgcDriver::Graphics::SnapshotMemoryProperties(memory, false) == bar, "a resizable BAR over the whole device heap was not chosen for snapshots"); + Require(AgcDriver::Graphics::SnapshotMemoryProperties(memory, true) == host, "disabled BAR snapshots still chose device-local memory"); + memory.memoryHeapCount = 3; + memory.memoryHeaps[2] = {VkDeviceSize{256} << 20u, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT}; + memory.memoryTypes[2] = {bar, 2}; + Require(AgcDriver::Graphics::SnapshotMemoryProperties(memory, false) == host, "a 256 MiB BAR window was taken for snapshots"); + memory.memoryTypeCount = 2; + Require(AgcDriver::Graphics::SnapshotMemoryProperties(memory, false) == host, "a device without host-visible device memory did not keep host snapshots"); +} + void stagingPoolBudgetTests() { if (std::getenv("APS5_STAGING_POOL_MIB") != nullptr) return; VkPhysicalDeviceMemoryProperties memory{}; @@ -11254,6 +11275,7 @@ int main(int argc, char** argv) { meshArgumentTests(); meshIndexBufferTests(); stagingPoolBudgetTests(); + snapshotMemoryTests(); validationTests(); vertexCopyTests(); highestDrawIndexTests(); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index dd75c7f25f79..69490c35d00f 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -191,6 +191,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_ATOMIC_STAGING` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | binds atomic shader elements in place instead of staging them through a device-local buffer | | `APS5_NO_BARRIER_BATCH` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records the staging, write-back and label-run leading barriers that a covering barrier already orders, instead of leaving them out | | `APS5_NO_BARRIER_ELISION` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records every leading barrier instead of merging it into the following submission | +| `APS5_NO_BAR_SNAPSHOTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp` | | keeps draw snapshots and draw input copies in host memory instead of the device-local host-visible memory a resizable BAR exposes | | `APS5_NO_BDA_TABLE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp` | | builds every BDA descriptor table instead of reusing the recent-table cache | | `APS5_NO_BLOCK_TRACKING` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | tracks array layers, or the whole surface, instead of 64 KiB blocks | | `APS5_NO_BUFFER_CLASSES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp` | | matches exact sizes in the buffer pool instead of rounding up to size classes | From 99f0ebbcff595b3b8f75f4edcaab7e036cec7538 Mon Sep 17 00:00:00 2001 From: panicDa3m0n <44086061+panicDa3m0n@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:42:59 +0200 Subject: [PATCH 2/6] fix(agc): keep index copies in host memory The CPU scans an index copy for its highest index and, for mesh strips, its restart table. With the copy in device-local memory the scans read the guest's index buffer a second time, so a store between the copy and the scan gave a highest index or restart table that did not match the bound copy. Index copies now stay in host memory and the scans read the copy itself; vertex copies stay in BAR memory. agc_draw_input_memory copies indices, stores to the guest source, and checks that the copy is in host memory and keeps its highest index. --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 4 +++- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 16 +++------------- core/libs/prx/libSceAgcDriver/tests/Recorder.cpp | 15 +++++++++++++++ docs/dev/ENVIRONMENT.md | 2 +- 4 files changed, 22 insertions(+), 15 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 5d300d3b4d8e..b6d5cd4f77ef 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -1615,6 +1615,8 @@ if(BUILD_TESTING) set_tests_properties(agc_draw_inputs_in_place PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME agc_draw_inputs_copied COMMAND agc_driver_recorder_tests --draw-inputs-copied-only) set_tests_properties(agc_draw_inputs_copied PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME agc_draw_input_memory COMMAND agc_driver_recorder_tests --draw-input-memory-only) + set_tests_properties(agc_draw_input_memory PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME agc_resident_present COMMAND agc_driver_recorder_tests --resident-present-only) set_tests_properties(agc_resident_present PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME agc_queued_write_groups COMMAND agc_driver_recorder_tests --queued-write-groups-only) @@ -1625,7 +1627,7 @@ if(BUILD_TESTING) add_test(NAME agc_metadata_pass COMMAND agc_driver_recorder_tests --metadata-pass-only) set_tests_properties(agc_metadata_pass PROPERTIES SKIP_RETURN_CODE 77) if(WIN32) - set_tests_properties(agc_recorder_read_list agc_host_import_unmap agc_parked_import_unmap agc_host_import_retirement agc_sparse_run_import agc_sparse_run_import_copied agc_unit_shadow agc_idle_publish_wait agc_descriptor_pool_recycling agc_draw_snapshot_cap agc_draw_snapshot_epoch agc_multisample_guest_access agc_draw_inputs_in_place agc_draw_inputs_copied agc_resident_present agc_slice_dirty agc_queued_write_groups agc_metadata_pass agc_tiled_resolve PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(agc_recorder_read_list agc_host_import_unmap agc_parked_import_unmap agc_host_import_retirement agc_sparse_run_import agc_sparse_run_import_copied agc_unit_shadow agc_idle_publish_wait agc_descriptor_pool_recycling agc_draw_snapshot_cap agc_draw_snapshot_epoch agc_multisample_guest_access agc_draw_inputs_in_place agc_draw_inputs_copied agc_draw_input_memory agc_resident_present agc_slice_dirty agc_queued_write_groups agc_metadata_pass agc_tiled_resolve PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") add_test(NAME agc_host_import_second_mapping COMMAND agc_driver_recorder_tests --host-import-second-mapping-only) set_tests_properties(agc_host_import_second_mapping PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT_MODIFICATION diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 94ff467d9682..eedb10710bac 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1,5 +1,4 @@ #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" -#include "prx/libc/include/HostThreadLocal.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetTransfer.hpp" #include "prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp" @@ -951,20 +950,11 @@ DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uin return copy; } } - copy.buffer = std::make_shared(context, bytes, use == Recorder::SnapshotUse::Vertex ? VK_BUFFER_USAGE_VERTEX_BUFFER_BIT : VK_BUFFER_USAGE_INDEX_BUFFER_BIT, context.SnapshotProperties()); + copy.buffer = use == Recorder::SnapshotUse::Vertex ? std::make_shared(context, bytes, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, context.SnapshotProperties()) : std::make_shared(context, bytes, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); GuestMemory::Read(address, copy.buffer->Bytes(), alignment); return copy; } -std::span HostReadableInput(const DrawInputCopy& copy, std::uint64_t address, std::size_t bytes, std::size_t alignment) { - if ((copy.buffer->Properties() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) return copy.buffer->Bytes().first(bytes); - struct ScratchTag; - auto& scratch = HostThreadLocal, ScratchTag>(); - scratch.resize(bytes); - GuestMemory::Read(address, scratch, alignment); - return scratch; -} - DrawInputCopy CopyZeroPaddedDrawInput(const Context& context, std::uint64_t address, std::size_t bytes, std::size_t validBytes, std::size_t stride) { Require(validBytes <= bytes, "the valid bytes of a vertex fetch exceed the fetch"); GuestMemory::FlushGpuWrites(address, bytes); @@ -1236,7 +1226,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P if (import != nullptr) { highest = InPlaceIndexRange(*context.recorder, draw.indexAddress, static_cast(indexBytes), draw.indexSize, skipRestart).highest; } else if (!copy.reused) { - highest = HighestDrawIndex(HostReadableInput(copy, draw.indexAddress, static_cast(indexBytes), draw.indexSize), draw.indexSize, skipRestart); + highest = HighestDrawIndex(copy.buffer->Bytes().first(static_cast(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; @@ -1269,7 +1259,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P Require(!fanGeometry || !state.primitiveRestart || *highest != (draw.indexSize == 2 ? 0xffffu : 0xffffffffu), "primitive restart in a triangle fan geometry draw is unsupported"); inputs.maxIndex = *highest; if (skipRestart && state.stages.mesh && state.stages.mesh->inputPrimitive == 6) { - const auto indexSpan = import != nullptr ? std::span(reinterpret_cast(draw.indexAddress), static_cast(indexBytes)) : HostReadableInput(copy, draw.indexAddress, static_cast(indexBytes), draw.indexSize); + const auto indexSpan = import != nullptr ? std::span(reinterpret_cast(draw.indexAddress), static_cast(indexBytes)) : copy.buffer->Bytes().first(static_cast(indexBytes)); inputs.restartTable = MeshRestartTable(indexSpan, draw.indexSize); } if (import != nullptr) { diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index 97f02e7f2f2d..eec01a0191a9 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -4440,6 +4440,15 @@ void drawInputReuseTests(const Device& device, Recorder& recorder) { recorder.Sync(); } +void drawInputMemoryTests(const Device& device) { + alignas(64) static std::array indices{}; + for (std::uint32_t i = 0; i < indices.size(); ++i) indices[i] = i; + const auto copy = CopyDrawInput(device.GetContext(), nullptr, reinterpret_cast(indices.data()), sizeof(indices), 4, Recorder::SnapshotUse::Index32); + indices[9] = 0x10000; + Require((copy.buffer->Properties() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0, "an index copy left host memory, so its highest index would be scanned from the guest instead of the copy"); + Require(HighestDrawIndex(copy.buffer->Bytes(), 4, false) == 63u, "the highest index of an index copy followed a later store to the guest"); +} + void drawInputInPlaceTests(const Device& device, Recorder& recorder, bool copied = false) { auto context = device.GetContext(); constexpr std::size_t bytes = 65536; @@ -10415,6 +10424,11 @@ 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-memory-only") { + drawInputMemoryTests(device); + std::cout << "Draw input memory 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"; @@ -10494,6 +10508,7 @@ int main(int argc, char** argv) { unwrittenSnapshotTests(device); drawSnapshotUploadTests(device, recorder); drawInputReuseTests(device, recorder); + drawInputMemoryTests(device); drawInputInPlaceTests(device, recorder); RunResidentPresentTests(device.GetContext()); sliceDirtyTests(device, recorder); diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 69490c35d00f..540455524a28 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -191,7 +191,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_ATOMIC_STAGING` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | binds atomic shader elements in place instead of staging them through a device-local buffer | | `APS5_NO_BARRIER_BATCH` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records the staging, write-back and label-run leading barriers that a covering barrier already orders, instead of leaving them out | | `APS5_NO_BARRIER_ELISION` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records every leading barrier instead of merging it into the following submission | -| `APS5_NO_BAR_SNAPSHOTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp` | | keeps draw snapshots and draw input copies in host memory instead of the device-local host-visible memory a resizable BAR exposes | +| `APS5_NO_BAR_SNAPSHOTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp` | | keeps draw snapshots and vertex copies in host memory instead of the device-local host-visible memory a resizable BAR exposes | | `APS5_NO_BDA_TABLE_CACHE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BdaResources.cpp` | | builds every BDA descriptor table instead of reusing the recent-table cache | | `APS5_NO_BLOCK_TRACKING` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | tracks array layers, or the whole surface, instead of 64 KiB blocks | | `APS5_NO_BUFFER_CLASSES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp` | | matches exact sizes in the buffer pool instead of rounding up to size classes | From c7bc487b6b5c8376e754f22cb9fb516f3b3c340d Mon Sep 17 00:00:00 2001 From: panicDa3m0n <44086061+panicDa3m0n@users.noreply.github.com> Date: Thu, 22 Oct 2026 13:43:05 +0200 Subject: [PATCH 3/6] fix(agc): give mapped device-local buffers a host memory fallback A Buffer asked for device-local host-visible memory now takes host memory when the reported budget of the device-local heap has no room for it, as DeviceMemoryType places device buffers. It also takes host memory when its allocation, or the allocation of its slab block, is still refused after the pool trim and the cache reclaim, as device buffers and images do through RefusedDeviceMemoryFallback. Properties() then reports host memory, so refreshing such a snapshot compares its blocks again. MappedDevicePlacement in tests/BufferPool.cpp checks both placements for a buffer and for a slab. --- .../Graphics/include/BufferPool.hpp | 4 +- .../Graphics/include/Context.hpp | 40 ++++++++++++++++--- .../Graphics/src/BufferPool.cpp | 8 ++-- .../Graphics/src/Resources.cpp | 12 ++++-- .../prx/libSceAgcDriver/tests/BufferPool.cpp | 35 +++++++++++++++- 5 files changed, 84 insertions(+), 15 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp index 657c5351c49d..01d6a514559d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp @@ -33,6 +33,7 @@ struct SlabSlot { VkDeviceMemory memory; VkDeviceSize offset; void* mapping; + std::uint32_t memoryType = 0; }; // Released buffer allocations kept for reuse, since creating, binding and mapping one costs tens of @@ -74,7 +75,7 @@ class BufferPool { void Put(const BufferAllocation& allocation) noexcept; static bool SlabEligible(std::size_t capacity, VkDeviceSize alignment, VkDeviceSize size, VkDeviceSize atom); static VkDeviceSize SlabBlockBytes(std::size_t capacity); - SlabSlot TakeSlot(const Context& context, std::uint32_t memoryType, std::size_t capacity, bool addressable); + SlabSlot TakeSlot(const Context& context, std::uint32_t memoryType, std::size_t capacity, bool addressable, std::optional hostType = std::nullopt); VkDeviceSize PutSlot(VkDeviceMemory memory, VkDeviceSize offset) noexcept; std::size_t SlabBlocks(); @@ -86,6 +87,7 @@ class BufferPool { std::vector free; std::uint32_t used = 0; std::uint64_t slab = 0; + std::uint32_t memoryType = 0; }; struct Slab { std::vector available; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index 713c845bbdde..ad7251492908 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -152,16 +152,17 @@ inline std::uint64_t& DeviceProcLookups() { inline constexpr std::size_t EmptyBufferBytes = 16; +inline constexpr VkMemoryPropertyFlags HostBufferProperties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; +inline constexpr VkMemoryPropertyFlags MappedDeviceProperties = HostBufferProperties | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + inline VkMemoryPropertyFlags SnapshotMemoryProperties(const VkPhysicalDeviceMemoryProperties& memory, bool disabled) { - constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - constexpr VkMemoryPropertyFlags bar = host | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; constexpr VkDeviceSize ResizableBarBytes = VkDeviceSize{4} << 30u; - if (disabled) return host; + if (disabled) return HostBufferProperties; for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) { const auto& type = memory.memoryTypes[i]; - if ((type.propertyFlags & bar) == bar && type.heapIndex < memory.memoryHeapCount && memory.memoryHeaps[type.heapIndex].size >= ResizableBarBytes) return bar; + if ((type.propertyFlags & MappedDeviceProperties) == MappedDeviceProperties && type.heapIndex < memory.memoryHeapCount && memory.memoryHeaps[type.heapIndex].size >= ResizableBarBytes) return MappedDeviceProperties; } - return host; + return HostBufferProperties; } struct Context { @@ -372,6 +373,35 @@ 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); } + + VkMemoryPropertyFlags MappedBufferProperties(std::uint32_t mask, VkMemoryPropertyFlags flags, VkDeviceSize bytes) const { + if ((flags & MappedDeviceProperties) != MappedDeviceProperties || memoryProperties2 == nullptr || physical == VK_NULL_HANDLE) return flags; + VkPhysicalDeviceMemoryBudgetPropertiesEXT reported{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT}; + VkPhysicalDeviceMemoryProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2}; + properties.pNext = &reported; + memoryProperties2(physical, &properties); + const auto heap = memory.memoryTypes[MemoryType(mask, flags)].heapIndex; + const auto budget = reported.heapBudget[heap]; + const auto usage = reported.heapUsage[heap]; + if (budget == 0 || (usage < budget && bytes <= budget - usage)) return flags; + static std::atomic placements{0}, placedBytes{0}; + const auto count = placements.fetch_add(1) + 1; + const auto total = placedBytes.fetch_add(bytes) + bytes; + if (count <= 5 || (count & (count - 1)) == 0) std::fprintf(stderr, "[gpu] mapped buffer: device-local heap %u uses %llu of its %llu MiB budget, %llu bytes placed in host memory; %llu such allocations, %llu MiB\n", heap, static_cast(usage >> 20u), static_cast(budget >> 20u), static_cast(bytes), static_cast(count), static_cast(total >> 20u)); + return HostBufferProperties; + } + + std::optional RefusedMappedMemoryFallback(std::uint32_t mask, VkMemoryPropertyFlags flags, std::uint32_t refused) const { + if ((flags & MappedDeviceProperties) != MappedDeviceProperties || refused >= memory.memoryTypeCount || (memory.memoryHeaps[memory.memoryTypes[refused].heapIndex].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) == 0) return std::nullopt; + std::optional host; + for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) { + const auto& type = memory.memoryTypes[i]; + if ((mask & (1u << i)) == 0 || (type.propertyFlags & HostBufferProperties) != HostBufferProperties || (memory.memoryHeaps[type.heapIndex].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0) continue; + if ((type.propertyFlags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) != 0) return i; + if (!host) host = i; + } + return host; + } }; inline VkShaderModule CreateShaderModule(const Context& context, const std::uint32_t* code, std::size_t bytes, const char* operation) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp index 128970a898fa..224d3a24cabe 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp @@ -235,7 +235,7 @@ std::uint64_t BufferPool::SlabKey(std::uint32_t memoryType, std::size_t capacity return (static_cast(memoryType) << 40u) | (static_cast(addressable ? 1u : 0u) << 39u) | static_cast(capacity); } -SlabSlot BufferPool::TakeSlot(const Context& context, std::uint32_t memoryType, std::size_t capacity, bool addressable) { +SlabSlot BufferPool::TakeSlot(const Context& context, std::uint32_t memoryType, std::size_t capacity, bool addressable, std::optional hostType) { const auto key = SlabKey(memoryType, capacity, addressable); const auto takeFrom = [&](SlabBlock& block, Slab& slab) { const auto index = block.free.back(); @@ -243,7 +243,7 @@ SlabSlot BufferPool::TakeSlot(const Context& context, std::uint32_t memoryType, if (block.used++ == 0) --slab.emptyBlocks; if (block.free.empty()) slab.available.erase(std::find(slab.available.begin(), slab.available.end(), &block)); const auto offset = static_cast(index) * block.slotBytes; - return SlabSlot{block.memory, offset, block.mapping != nullptr ? block.mapping + offset : nullptr}; + return SlabSlot{block.memory, offset, block.mapping != nullptr ? block.mapping + offset : nullptr, block.memoryType}; }; { std::lock_guard lock(slabMutex); @@ -263,8 +263,8 @@ SlabSlot BufferPool::TakeSlot(const Context& context, std::uint32_t memoryType, if (addressable) allocation.pNext = &flags; allocation.allocationSize = blockBytes; allocation.memoryTypeIndex = memoryType; - block->memory = AllocateMemory(allocation, "vkAllocateMemory buffer slab"); - if ((context.memory.memoryTypes[memoryType].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) { + block->memory = AllocateMemory(allocation, "vkAllocateMemory buffer slab", hostType, &block->memoryType); + if ((context.memory.memoryTypes[block->memoryType].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) { void* mapping = nullptr; const auto mapped = mapMemory(device, block->memory, 0, VK_WHOLE_SIZE, 0, &mapping); Check(mapped, "vkMapMemory buffer slab"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp index 4f30207defe0..c6157ec70c65 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp @@ -82,9 +82,13 @@ Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usag // The CPU reads most of these buffers back (write-back, diffs), which is very slow from // write-combined memory, so the default host properties prefer cached host memory. const bool useSlab = (properties & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0 && BufferPool::SlabEligible(capacity, requirements.alignment, requirements.size, context.limits.nonCoherentAtomSize); - allocation.memoryTypeIndex = context.BufferMemoryType(requirements.memoryTypeBits, properties, useSlab ? BufferPool::SlabBlockBytes(capacity) : allocation.allocationSize); + const auto placedBytes = useSlab ? BufferPool::SlabBlockBytes(capacity) : allocation.allocationSize; + this->properties = context.MappedBufferProperties(requirements.memoryTypeBits, properties, placedBytes); + allocation.memoryTypeIndex = context.BufferMemoryType(requirements.memoryTypeBits, this->properties, placedBytes); + const auto refused = context.RefusedMappedMemoryFallback(requirements.memoryTypeBits, this->properties, allocation.memoryTypeIndex); if (useSlab) { - const auto slot = cache->TakeSlot(context, allocation.memoryTypeIndex, capacity, addressable); + const auto slot = cache->TakeSlot(context, allocation.memoryTypeIndex, capacity, addressable, refused); + if (slot.memoryType != allocation.memoryTypeIndex) this->properties = HostBufferProperties; memory = slot.memory; offset = slot.offset; slab = true; @@ -95,7 +99,9 @@ Buffer::Buffer(const Context& context, std::size_t size, VkBufferUsageFlags usag ready = true; return; } - memory = cache->AllocateMemory(allocation, "vkAllocateMemory buffer"); + std::uint32_t allocatedType = allocation.memoryTypeIndex; + memory = cache->AllocateMemory(allocation, "vkAllocateMemory buffer", refused, &allocatedType); + if (allocatedType != allocation.memoryTypeIndex) this->properties = HostBufferProperties; Check(context.Function("vkBindBufferMemory")(context.device, buffer, memory, 0), "vkBindBufferMemory"); initializeAddress(usage); if ((properties & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) Check(context.Function("vkMapMemory")(context.device, memory, 0, VK_WHOLE_SIZE, 0, &mapping), "vkMapMemory"); diff --git a/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp b/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp index abdf8f0166f4..a64d00c5d9f2 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp @@ -52,6 +52,7 @@ struct MockDevice { std::map> bound; std::set liveBuffers; std::deque results; + std::uint32_t memoryTypeBits = 3; VkDeviceSize limit = 0; VkResult pressureResult = VK_ERROR_OUT_OF_DEVICE_MEMORY; std::uint64_t attempts = 0; @@ -73,7 +74,7 @@ VKAPI_ATTR VkResult VKAPI_CALL mockCreateBuffer(VkDevice, const VkBufferCreateIn } VKAPI_ATTR void VKAPI_CALL mockGetBufferMemoryRequirements(VkDevice, VkBuffer buffer, VkMemoryRequirements* requirements) { - *requirements = {mock.sizes.at(buffer), 256, 3}; + *requirements = {mock.sizes.at(buffer), 256, mock.memoryTypeBits}; } VKAPI_ATTR VkResult VKAPI_CALL mockAllocateMemory(VkDevice, const VkMemoryAllocateInfo* info, const VkAllocationCallbacks*, VkDeviceMemory* memory) { @@ -89,7 +90,7 @@ VKAPI_ATTR VkResult VKAPI_CALL mockAllocateMemory(VkDevice, const VkMemoryAlloca return result; } *memory = reinterpret_cast(static_cast(mock.next++)); - if (info->memoryTypeIndex == 1) mock.hostMemory[*memory].resize(info->allocationSize); + if (info->memoryTypeIndex != 0) mock.hostMemory[*memory].resize(info->allocationSize); mock.memoryBytes[*memory] = info->allocationSize; mock.memoryTypes[*memory] = info->memoryTypeIndex; mock.liveBytes += info->allocationSize; @@ -254,6 +255,35 @@ void RefusedDevicePlacement() { Expect(mock.liveBuffers.empty(), "a failed device buffer left its VkBuffer alive"); } +void MappedDevicePlacement() { + constexpr auto mapped = HostVisible | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + const auto placed = [&](std::size_t bytes) { + auto context = budgetContext(); + context.memory.memoryTypeCount = 3; + context.memory.memoryTypes[2] = {mapped, 0}; + Buffer buffer(context, bytes, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, mapped); + const auto type = mock.memoryTypes.at(MemoryOf(buffer.Handle())); + Expect(buffer.Properties() == (type == 2 ? mapped : HostVisible), "a mapped buffer's properties do not name the memory it was placed in"); + return type; + }; + mock = MockDevice{}; + mock.memoryTypeBits = 7; + reportedBudget = 1620 * MiB; + reportedUsage = 200 * MiB; + Expect(placed(9 * MiB) == 2, "a mapped device-local buffer within the device-local budget was not placed in its device-local type"); + Expect(placed(4096) == 2, "a mapped device-local slab within the device-local budget was not placed in its device-local type"); + reportedUsage = 1615 * MiB; + Expect(placed(9 * MiB) == 1, "a mapped device-local buffer over the device-local budget was not placed in host memory"); + reportedUsage = 1619 * MiB; + Expect(placed(4096) == 1, "a mapped device-local slab whose block exceeds the device-local budget was not placed in host memory"); + reportedUsage = 200 * MiB; + mock.results = {VK_ERROR_OUT_OF_DEVICE_MEMORY}; + Expect(placed(9 * MiB) == 1, "a mapped device-local buffer still refused device memory after reclaiming the pool was not placed in host memory"); + mock.results = {VK_ERROR_OUT_OF_DEVICE_MEMORY}; + Expect(placed(4096) == 1, "a mapped device-local slab still refused device memory after reclaiming the pool was not placed in host memory"); + Expect(mock.results.empty() && mock.liveBytes == 0 && mock.liveBuffers.empty(), "mapped buffer placement left a refusal unused or leaked memory"); +} + void AttachmentReclaim() { mock = MockDevice{}; auto context = budgetContext(); @@ -1048,6 +1078,7 @@ int main(int argc, char** argv) { ImageMemoryOverBudget(); HostPlacement(); RefusedDevicePlacement(); + MappedDevicePlacement(); AttachmentReclaim(); } catch (const std::exception& error) { std::fprintf(stderr, "FAIL: %s\n", error.what()); From b8663c514ef58c97fd9269a954fe6f0cf8596657 Mon Sep 17 00:00:00 2001 From: panicDa3m0n <44086061+panicDa3m0n@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:01:10 +0200 Subject: [PATCH 4/6] fix(agc): place mapped buffers in host memory when none of their memory types is mapped device-local MappedBufferProperties looked up the BAR type with MemoryType(mask, flags), which throws when the buffer's memoryTypeBits exclude it, and returned the flags unchanged without VK_EXT_memory_budget, so BufferMemoryType threw the same way. The buffer's own memory types are checked first now: a mask with no mapped device-local type takes HostBufferProperties, with a rate-limited line. MappedDevicePlacement checks a buffer and a slab whose mask excludes the BAR type and keeps the host type, with and without the budget extension. --- .../Graphics/include/Context.hpp | 19 ++++++++++++++++--- .../prx/libSceAgcDriver/tests/BufferPool.cpp | 10 +++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index ad7251492908..4c30e0a3de3a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -308,10 +308,15 @@ struct Context { return SnapshotMemoryProperties(memory, disabled); } - std::uint32_t MemoryType(std::uint32_t mask, VkMemoryPropertyFlags flags) const { + std::optional MatchingMemoryType(std::uint32_t mask, VkMemoryPropertyFlags flags) const { for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) { if ((mask & (1u << i)) != 0 && (memory.memoryTypes[i].propertyFlags & flags) == flags) return i; } + return std::nullopt; + } + + std::uint32_t MemoryType(std::uint32_t mask, VkMemoryPropertyFlags flags) const { + if (const auto type = MatchingMemoryType(mask, flags)) return *type; throw std::runtime_error("AGC graphics: required Vulkan memory type is unavailable"); } @@ -375,12 +380,20 @@ struct Context { } VkMemoryPropertyFlags MappedBufferProperties(std::uint32_t mask, VkMemoryPropertyFlags flags, VkDeviceSize bytes) const { - if ((flags & MappedDeviceProperties) != MappedDeviceProperties || memoryProperties2 == nullptr || physical == VK_NULL_HANDLE) return flags; + if ((flags & MappedDeviceProperties) != MappedDeviceProperties) return flags; + const auto mapped = MatchingMemoryType(mask, flags); + if (!mapped) { + static std::atomic placements{0}; + const auto count = placements.fetch_add(1) + 1; + if (count <= 5 || (count & (count - 1)) == 0) std::fprintf(stderr, "[gpu] mapped buffer: none of the buffer's memory types (mask 0x%x) is mapped device-local, placed in host memory; %llu such allocations\n", mask, static_cast(count)); + return HostBufferProperties; + } + if (memoryProperties2 == nullptr || physical == VK_NULL_HANDLE) return flags; VkPhysicalDeviceMemoryBudgetPropertiesEXT reported{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT}; VkPhysicalDeviceMemoryProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2}; properties.pNext = &reported; memoryProperties2(physical, &properties); - const auto heap = memory.memoryTypes[MemoryType(mask, flags)].heapIndex; + const auto heap = memory.memoryTypes[*mapped].heapIndex; const auto budget = reported.heapBudget[heap]; const auto usage = reported.heapUsage[heap]; if (budget == 0 || (usage < budget && bytes <= budget - usage)) return flags; diff --git a/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp b/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp index a64d00c5d9f2..f9142e2427c9 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp @@ -257,8 +257,9 @@ void RefusedDevicePlacement() { void MappedDevicePlacement() { constexpr auto mapped = HostVisible | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - const auto placed = [&](std::size_t bytes) { + const auto placed = [&](std::size_t bytes, bool budget = true) { auto context = budgetContext(); + if (!budget) context.memoryProperties2 = nullptr; context.memory.memoryTypeCount = 3; context.memory.memoryTypes[2] = {mapped, 0}; Buffer buffer(context, bytes, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, mapped); @@ -281,6 +282,13 @@ void MappedDevicePlacement() { Expect(placed(9 * MiB) == 1, "a mapped device-local buffer still refused device memory after reclaiming the pool was not placed in host memory"); mock.results = {VK_ERROR_OUT_OF_DEVICE_MEMORY}; Expect(placed(4096) == 1, "a mapped device-local slab still refused device memory after reclaiming the pool was not placed in host memory"); + mock.memoryTypeBits = 3; + Expect(placed(9 * MiB) == 1, "a mapped device-local buffer whose memory types exclude the BAR type was not placed in the host type"); + Expect(placed(4096) == 1, "a mapped device-local slab whose memory types exclude the BAR type was not placed in the host type"); + Expect(placed(9 * MiB, false) == 1, "a mapped device-local buffer whose memory types exclude the BAR type was not placed in the host type without the memory budget extension"); + Expect(placed(4096, false) == 1, "a mapped device-local slab whose memory types exclude the BAR type was not placed in the host type without the memory budget extension"); + mock.memoryTypeBits = 7; + Expect(placed(9 * MiB, false) == 2, "a mapped device-local buffer without the memory budget extension was not placed in its device-local type"); Expect(mock.results.empty() && mock.liveBytes == 0 && mock.liveBuffers.empty(), "mapped buffer placement left a refusal unused or leaked memory"); } From 539e1d1f6a7da4cca3a083d8f257a31aed92081b Mon Sep 17 00:00:00 2001 From: panicDa3m0n <44086061+panicDa3m0n@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:29:46 +0100 Subject: [PATCH 5/6] fix(agc): file a fallback slab block under the memory type it was allocated in A slab block that fell back to the host memory type stayed in the slab of the requested type, so a later buffer of the same class whose memoryTypeBits exclude the host type could take a slot in it and bind memory of a type it does not permit. The block now goes to the slab of the type it was allocated in. A request still takes a free slot of the host slab before allocating, when the buffer allows that type as its fallback. The buffer pool test's vkBindBufferMemory also checks the buffer's memoryTypeBits. FallbackSlabTypes keeps a fallback slab alive, gives its free slot to a second buffer that allows the host type without a new allocation, and sends a buffer whose mask excludes the host type to a slab of its own. --- .../Graphics/src/BufferPool.cpp | 8 +++- .../prx/libSceAgcDriver/tests/BufferPool.cpp | 37 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp index 8b0361196de6..5f65600866d4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp @@ -251,6 +251,10 @@ SlabSlot BufferPool::TakeSlot(const Context& context, std::uint32_t memoryType, std::lock_guard lock(slabMutex); auto& slab = slabs[key]; if (!slab.available.empty()) return takeFrom(*slab.available.back(), slab); + if (hostType.has_value() && *hostType != memoryType) { + auto& host = slabs[SlabKey(*hostType, capacity, addressable)]; + if (!host.available.empty()) return takeFrom(*host.available.back(), host); + } } const auto blockBytes = SlabBlockBytes(capacity); const auto release = [this](SlabBlock* block) noexcept { @@ -259,13 +263,13 @@ SlabSlot BufferPool::TakeSlot(const Context& context, std::uint32_t memoryType, }; std::unique_ptr block(new SlabBlock, release); block->slotBytes = capacity; - block->slab = key; VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; const VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, nullptr, VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT, 0}; if (addressable) allocation.pNext = &flags; allocation.allocationSize = blockBytes; allocation.memoryTypeIndex = memoryType; block->memory = AllocateMemory(allocation, "vkAllocateMemory buffer slab", hostType, &block->memoryType); + block->slab = block->memoryType == memoryType ? key : SlabKey(block->memoryType, capacity, addressable); if ((context.memory.memoryTypes[block->memoryType].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) { void* mapping = nullptr; const auto mapped = mapMemory(device, block->memory, 0, VK_WHOLE_SIZE, 0, &mapping); @@ -276,7 +280,7 @@ SlabSlot BufferPool::TakeSlot(const Context& context, std::uint32_t memoryType, block->free.reserve(slots); for (std::uint32_t index = slots; index-- != 0;) block->free.push_back(index); std::lock_guard lock(slabMutex); - auto& slab = slabs[key]; + auto& slab = slabs[block->slab]; if (slab.blocks == slab.available.capacity()) slab.available.reserve(std::max(1, slab.available.capacity() * 2)); auto& inserted = *block; const auto owner = slabBlocks.try_emplace(inserted.memory).first; diff --git a/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp b/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp index 8fda882479be..ee6644bc047b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BufferPool.cpp @@ -51,6 +51,7 @@ struct MockDevice { std::map memoryBytes; std::map memoryTypes; std::map> bound; + std::map bufferTypeBits; std::set liveBuffers; std::deque results; std::uint32_t memoryTypeBits = 3; @@ -76,6 +77,7 @@ VKAPI_ATTR VkResult VKAPI_CALL mockCreateBuffer(VkDevice, const VkBufferCreateIn VKAPI_ATTR void VKAPI_CALL mockGetBufferMemoryRequirements(VkDevice, VkBuffer buffer, VkMemoryRequirements* requirements) { *requirements = {mock.sizes.at(buffer), 256, mock.memoryTypeBits}; + mock.bufferTypeBits[buffer] = mock.memoryTypeBits; } VKAPI_ATTR VkResult VKAPI_CALL mockAllocateMemory(VkDevice, const VkMemoryAllocateInfo* info, const VkAllocationCallbacks*, VkDeviceMemory* memory) { @@ -103,6 +105,11 @@ VKAPI_ATTR VkResult VKAPI_CALL mockBindBufferMemory(VkDevice, VkBuffer buffer, V ++mock.binds; if (mock.bindResult != VK_SUCCESS) return mock.bindResult; if (offset + mock.sizes.at(buffer) > mock.memoryBytes.at(memory)) return VK_ERROR_OUT_OF_DEVICE_MEMORY; + const auto permitted = mock.bufferTypeBits.contains(buffer) ? mock.bufferTypeBits.at(buffer) : mock.memoryTypeBits; + if (((permitted >> mock.memoryTypes.at(memory)) & 1u) == 0) { + Expect(false, "a buffer was bound to memory type " + std::to_string(mock.memoryTypes.at(memory)) + ", which its memoryTypeBits " + std::to_string(permitted) + " exclude"); + return VK_ERROR_UNKNOWN; + } mock.bound[buffer] = {memory, offset}; return VK_SUCCESS; } @@ -293,6 +300,35 @@ void MappedDevicePlacement() { Expect(mock.results.empty() && mock.liveBytes == 0 && mock.liveBuffers.empty(), "mapped buffer placement left a refusal unused or leaked memory"); } +void FallbackSlabTypes() { + constexpr auto mapped = HostVisible | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + mock = MockDevice{}; + reportedBudget = 1620 * MiB; + reportedUsage = 200 * MiB; + { + auto context = budgetContext(); + context.memory.memoryTypeCount = 3; + context.memory.memoryTypes[2] = {mapped, 0}; + mock.memoryTypeBits = 7; + mock.results = {VK_ERROR_OUT_OF_DEVICE_MEMORY}; + Buffer fallback(context, 4096, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, mapped); + Expect(mock.memoryTypes.at(MemoryOf(fallback.Handle())) == 1, "a mapped slab buffer refused device memory was not placed in the host type"); + const auto attempts = mock.attempts; + Buffer shared(context, 4096, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, mapped); + Expect(MemoryOf(shared.Handle()) == MemoryOf(fallback.Handle()), "a mapped slab buffer allowing the host type did not take the free slot of the host slab before any device-local block existed"); + Expect(mock.attempts == attempts, "a mapped slab buffer allowing the host type allocated memory although the host slab had a free slot"); + Expect(shared.Properties() == HostVisible, "a mapped slab buffer placed in the host slab does not report host properties"); + mock.memoryTypeBits = 5; + Buffer device(context, 4096, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, mapped); + Expect(mock.memoryTypes.at(MemoryOf(device.Handle())) == 2, "a mapped slab buffer whose memory types exclude the host type took the host slab of an earlier fallback"); + Expect(device.Properties() == mapped, "a mapped slab buffer placed in its device-local type does not report device-local properties"); + mock.memoryTypeBits = 7; + Buffer host(context, 4096, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, mapped); + Expect(mock.memoryTypes.at(MemoryOf(host.Handle())) == 2, "a mapped slab buffer did not take the free slot of its device-local slab"); + } + Expect(mock.results.empty() && mock.liveBytes == 0 && mock.liveBuffers.empty(), "fallback slab placement left a refusal unused or leaked memory"); +} + void AttachmentReclaim() { mock = MockDevice{}; auto context = budgetContext(); @@ -1239,6 +1275,7 @@ int main(int argc, char** argv) { HostPlacement(); RefusedDevicePlacement(); MappedDevicePlacement(); + FallbackSlabTypes(); AttachmentReclaim(); } catch (const std::exception& error) { std::fprintf(stderr, "FAIL: %s\n", error.what()); From 601e9e99a9aca5301ed0eaf79449540debc644e5 Mon Sep 17 00:00:00 2001 From: Dean Galvin Date: Thu, 5 Nov 2026 19:47:57 +1300 Subject: [PATCH 6/6] fix(agc): compare BAR draw snapshots against a host copy Device-local snapshot buffers skipped the byte compare to avoid reading resizable BAR memory back, so every CPU store of identical bytes copied the draw input again. Keep a host copy of each device-local storage snapshot, compare against it, and write changed blocks to both; BAR is never read. --- .../Graphics/include/Recorder.hpp | 1 + .../libSceAgcDriver/Graphics/src/Recorder.cpp | 25 +++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index cba50b30fd25..77702871cee9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -932,6 +932,7 @@ class Recorder { std::list::iterator recent; std::shared_ptr buffer; std::uint32_t derived; + std::vector shadow; }; struct DrawSnapshotPool { std::list recency; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 9e1e070cd585..24135526c344 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -3163,25 +3163,35 @@ bool Recorder::refreshDrawSnapshot(DrawSnapshot& entry, std::uint64_t address, s differing.clear(); spans.clear(); const bool sole = entry.buffer.use_count() == 1; + const bool deviceLocal = (entry.buffer->Properties() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; + const bool shadowed = deviceLocal && entry.shadow.size() == bytes; + std::byte* const compared = shadowed ? entry.shadow.data() : held.data(); GuestMemory::ChangedBlocks(address, bytes, generations, changed); for (std::size_t k = 0; k < count; ++k) { if (changed[k] == GuestMemory::BlockUnchanged) continue; const auto from = std::max(address, aligned + k * block); const auto to = std::min(end, aligned + (k + 1) * block); const auto offset = static_cast(from - address); - spans.push_back({held.data() + offset, reinterpret_cast(from), static_cast(to - from)}); + spans.push_back({compared + offset, reinterpret_cast(from), static_cast(to - from)}); } equal.assign(spans.size(), 0); - if ((entry.buffer->Properties() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0) CompareSpans(spans, equal); + if (!deviceLocal || shadowed) CompareSpans(spans, equal); for (std::size_t k = 0; k < spans.size(); ++k) { if (equal[k] != 0) continue; - const auto offset = static_cast(static_cast(spans[k].first) - held.data()); + const auto offset = static_cast(static_cast(spans[k].first) - compared); const auto length = spans[k].bytes; if (!sole) return false; if (!differing.empty() && differing.back().first + differing.back().second == offset) differing.back().second += length; else differing.emplace_back(offset, length); } - for (const auto& [offset, length] : differing) std::memcpy(held.data() + offset, reinterpret_cast(address + offset), length); + for (const auto& [offset, length] : differing) { + std::memcpy(held.data() + offset, reinterpret_cast(address + offset), length); + if (shadowed) std::memcpy(entry.shadow.data() + offset, reinterpret_cast(address + offset), length); + } + if (deviceLocal && !shadowed) { + entry.shadow.resize(bytes); + std::memcpy(entry.shadow.data(), reinterpret_cast(address), bytes); + } return true; } @@ -3200,7 +3210,12 @@ 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}); + std::vector shadow; + if (storage && (buffer->Properties() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0 && GuestMemory::UnchangedSince(address, bytes, generation)) { + shadow.resize(bytes); + std::memcpy(shadow.data(), reinterpret_cast(address), bytes); + } + drawSnapshots.emplace(key, DrawSnapshot{generation, registryGeneration, std::prev(pool.recency.end()), std::move(buffer), derived, std::move(shadow)}); } catch (...) { pool.recency.pop_back(); throw;