From 590c15c57d8cf98498fda6a5b547cf06d71cdcfd Mon Sep 17 00:00:00 2001 From: mjnhbg3 <2287071+mjnhbg3@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:43:29 -0500 Subject: [PATCH] fix(agc): honor release memory L2 write-back requests --- .../libSceAgcDriver/Execution/include/Pm4.hpp | 1 + .../src/Driver/Dispatch/DispatchAhead.cpp | 4 +- .../src/Driver/Packets/PacketMemory.cpp | 14 +- .../prx/libSceAgcDriver/Execution/src/Pm4.cpp | 12 + .../Graphics/include/Texture.hpp | 1 + .../libSceAgcDriver/Graphics/src/Texture.cpp | 29 ++ core/libs/prx/libSceAgcDriver/tests/Pm4.cpp | 42 ++ ...river_storage_completion_reuse_tests.cmake | 78 ++++ .../execution/StorageCompletionReuse.cpp | 401 ++++++++++++++++++ .../changes/gpu-completion-reuse-rebase.md | 5 + 10 files changed, 582 insertions(+), 5 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_completion_reuse_tests.cmake create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/StorageCompletionReuse.cpp create mode 100644 docs/dev/debt/changes/gpu-completion-reuse-rebase.md diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Pm4.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Pm4.hpp index 3e481e5f9174..f9a81f1b1d05 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Pm4.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Pm4.hpp @@ -102,6 +102,7 @@ bool AccessesMemory(std::uint32_t header); // Whether an ACQUIRE_MEM packet asks only for GPU cache actions (no CPU-visible memory // synchronization): such a packet needs a pipeline barrier, not a device drain. bool UsesGpuCacheBarrier(std::span packet); +bool ReleaseWritesBackL2(std::span packet); bool IsTagMarker(std::span packet); inline bool Predicated(std::uint32_t header) { return !FillerPacket(header) && (header & 1u) != 0; } bool PredicationPasses(const QueueState& queue); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp index 9b3af9ed1e7a..b55e71fb7d7f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp @@ -155,7 +155,7 @@ void Driver::resolveGroupAhead(const Submission& submission, const QueueState& l const auto count = Pm4::PacketWords(header); if (limit + count > commands.size()) break; const auto opcode = (header >> 8u) & 0xffu; - if (header == FlipPacketHeader || header == RenderingWaitPacketHeader || opcode == 0x22 || opcode == 0x3f || opcode == 0x3c || opcode == 0x93) break; + if (header == FlipPacketHeader || header == RenderingWaitPacketHeader || opcode == 0x22 || opcode == 0x3f || opcode == 0x3c || opcode == 0x93 || Pm4::ReleaseWritesBackL2(std::span(commands).subspan(limit, count))) break; if (opcode == 0x15 || opcode == 0x16) hasFurtherDispatch = true; limit += count; } @@ -259,7 +259,7 @@ void Driver::resolveGroupAhead(const Submission& submission, const QueueState& l const auto packet = std::span(commands).subspan(cursor, count); const auto opcode = (header >> 8u) & 0xffu; const auto next = cursor + count; - if (header == FlipPacketHeader || header == RenderingWaitPacketHeader || opcode == 0x22 || (Pm4::Predicated(header) && scratch.predication.operation != 0)) break; + if (header == FlipPacketHeader || header == RenderingWaitPacketHeader || opcode == 0x22 || Pm4::ReleaseWritesBackL2(packet) || (Pm4::Predicated(header) && scratch.predication.operation != 0)) break; if (opcode == 0x3c || opcode == 0x93) { if (!Pm4::WaitSatisfiedUnchecked(packet) && !WrittenByRun(packet, labels)) break; } else if (opcode == 0x15 || opcode == 0x16) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp index 30c8c52adadc..ee9483d77cb6 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp @@ -60,6 +60,14 @@ bool Driver::preparePacketMemory(const Submission& submission, QueueState& queue wroteOnGpu = false; bool orderedAlready = false; + const bool releaseWriteBack = Pm4::ReleaseWritesBackL2(packet); + if (releaseWriteBack) { + GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Flush); + std::lock_guard gpuLock(GuestMemory::GpuMutex()); + const auto localDevice = device.Load(); + recordDeferredLabels(localDevice.get(), submission.queue); + if (localDevice != nullptr) Graphics::StorageTexture::StoreBeforeRelease(localDevice->Device()); + } endOfPipeInterrupt = interrupt.has_value(); interruptDeferred = false; @@ -73,7 +81,7 @@ bool Driver::preparePacketMemory(const Submission& submission, QueueState& queue std::lock_guard gpuLock(GuestMemory::GpuMutex()); const auto localDevice = device.Load(); recordDeferredLabels(localDevice.get(), submission.queue); - bool workOpen = Graphics::Recorder::RecordedWorkSinceSubmit() != 0; + bool workOpen = releaseWriteBack || Graphics::Recorder::RecordedWorkSinceSubmit() != 0; int reason = localDevice != nullptr ? 0 : 1; if (label.has_value()) { const auto bytes = label->Bytes(); @@ -114,7 +122,7 @@ bool Driver::preparePacketMemory(const Submission& submission, QueueState& queue if (!drainAll && !endOfPipeInterrupt && (opcode == 0x49 || opcode == 0x37)) { if (const auto label = Pm4::DecodeLabelWrite(packet)) { const auto bytes = label->Bytes(); - if (DeferLabels() && bytes.size() <= DeferredLabel::Capacity && bytes.size() % 4 == 0 && label->address % 4 == 0) { + if (!releaseWriteBack && DeferLabels() && bytes.size() <= DeferredLabel::Capacity && bytes.size() % 4 == 0 && label->address % 4 == 0) { auto& deferred = deferredLabels(); if (deferred.labels.empty()) deferred.since = std::chrono::steady_clock::now(); @@ -484,7 +492,7 @@ void Driver::commitStore(std::uint32_t queue, std::uint64_t address, std::span packet, std::uint32_t opcode) { static const bool ordered = std::getenv("APS5_PIPELINE_DRAIN_LABELS") == nullptr; - if (!ordered || !DeferLabels() || (opcode != 0x49 && opcode != 0x37) || !deferredLabels().labels.empty()) return false; + if (!ordered || !DeferLabels() || (opcode != 0x49 && opcode != 0x37) || !deferredLabels().labels.empty() || Pm4::ReleaseWritesBackL2(packet)) return false; if (Pm4::DecodeLabelWrite(packet).has_value()) return true; return opcode == 0x49 && ((packet[2] >> 29u) == 0 || (packet[3] | (static_cast(packet[4]) << 32u)) == 0); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp index a9f824c8581e..410d954ca0ac 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp @@ -566,6 +566,14 @@ void Validate(std::span packet, std::uint32_t queue) { const auto interruptSelect = (packet[2] >> 24u) & 7u; require(interruptSelect == 0 || interruptSelect == 3, "an interrupting GCN RELEASE_MEM has no interrupt context dword"); } + if (ReleaseWritesBackL2(packet)) { + require((packet[1] & 0x00cf0000u) == 0, "RELEASE_MEM GL2 write-back scope, discard or sequence is not implemented"); + const auto eventType = packet[1] & 0x3fu; + const auto eventIndex = (packet[1] >> 8u) & 0xfu; + const bool endOfPipe = eventIndex == 5u && (eventType == 0x04u || eventType == 0x14u || eventType == 0x28u || eventType == 0x29u || eventType == 0x2bu || eventType == 0x2du); + const bool computeDone = queue != 0 && eventIndex == 6u && eventType == 0x2fu; + require(endOfPipe || computeDone, "RELEASE_MEM GL2 write-back event/index is not implemented"); + } const auto dataSelect = packet[2] >> 29u; require(dataSelect != 4 || ShaderRecompiler::GcnGuestShaders(), "RELEASE_MEM of the 64-bit system counter (DATA_SEL 4) is not implemented"); require(dataSelect <= 5, "reserved RELEASE_MEM DATA_SEL"); @@ -730,6 +738,10 @@ std::uint32_t ReadCondition(std::span packet) { return value; } +bool ReleaseWritesBackL2(std::span packet) { + return packet.size() >= 2 && ((packet[0] >> 8u) & 0xffu) == 0x49u && (packet[1] & 0x00200000u) != 0; +} + std::optional DecodeLabelWrite(std::span packet) { const auto opcode = (packet[0] >> 8u) & 0xffu; if (opcode == 0x49 && packet.size() >= 7) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp index e875a6d6c731..44e2a556ff3a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Texture.hpp @@ -337,6 +337,7 @@ class StorageTexture : public std::enable_shared_from_this { // overlapping pending image, as before). static bool FlushPending(std::uint64_t address, std::size_t bytes, const StorageTexture* except = nullptr, const char* reason = "memory access", PublishScope scope = PublishScope::Whole, bool* published = nullptr, bool waited = false, VkDevice device = VK_NULL_HANDLE); static void FlushAllPending(const char* reason, VkDevice device = VK_NULL_HANDLE); + static void StoreBeforeRelease(VkDevice device); static bool FlushAllPendingUntil(const char* reason, const std::function& stop, VkDevice device = VK_NULL_HANDLE); static bool WaitForFlushing(std::uint64_t address, std::size_t bytes, const StorageTexture* except = nullptr); static void SaveBeforeUnwatch(std::uint64_t address, std::size_t bytes); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index 691462952a33..5637da472d40 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -5226,8 +5226,10 @@ bool StorageTexture::FlushPending(std::uint64_t address, std::size_t bytes, cons return scope == PublishScope::None || !AnyShadowedOverlaps(address, bytes); }; if (nothingToStore()) return false; + const bool requirePublication = reason != nullptr && std::strcmp(reason, "release") == 0; if (AgcDriver::DriverDetail::DrawPipeline::HeldReads(address, bytes)) { queuedReadHeld.fetch_add(1, std::memory_order_relaxed); + Require(!requirePublication, "RELEASE_MEM GL2 write-back with queued draw reads is not implemented"); return false; } std::unique_lock drawnHold; @@ -5250,6 +5252,11 @@ bool StorageTexture::FlushPending(std::uint64_t address, std::size_t bytes, cons auto& pending = Pending(); std::lock_guard lock(pending.mutex); const auto* exempt = Refreshing::Get(); + if (requirePublication) { + Require(std::none_of(pending.flushing.begin(), pending.flushing.end(), [&](const StorageTexture* texture) { + return texture != except && texture != exempt && (device == VK_NULL_HANDLE || texture->context.device == device) && texture->overlaps(address, bytes); + }), "RELEASE_MEM GL2 write-back during another image publication is not implemented"); + } for (auto it = pending.textures.MayOverlap(address, bytes) ? pending.textures.begin() : pending.textures.end(); it != pending.textures.end();) { auto* texture = *it; if (texture != except && texture != exempt && (device == VK_NULL_HANDLE || texture->context.device == device) && texture->overlaps(address, bytes)) { @@ -5757,6 +5764,28 @@ void StorageTexture::FlushAllPending(const char* reason, VkDevice device) { static_cast(FlushPending(0, std::numeric_limits::max(), nullptr, reason, PublishScope::Whole, nullptr, false, device)); } +void StorageTexture::StoreBeforeRelease(VkDevice device) { + GuestMemory::AssertGpuLockHeld("StorageTexture::StoreBeforeRelease"); + constexpr auto bytes = std::numeric_limits::max(); + bool imagesPending = false; + { + auto& pending = Pending(); + std::lock_guard lock(pending.mutex); + const auto sameDevice = [device](const StorageTexture* texture) { return device == VK_NULL_HANDLE || texture->context.device == device; }; + Require(std::none_of(pending.flushing.begin(), pending.flushing.end(), sameDevice), "RELEASE_MEM GL2 write-back during another image publication is not implemented"); + imagesPending = std::any_of(pending.textures.begin(), pending.textures.end(), sameDevice); + } + if (!imagesPending && !DepthPlanesStale() && !AnyShadowedOverlaps(0, bytes)) return; + Require(!AgcDriver::DriverDetail::DrawPipeline::HeldReads(0, bytes), "RELEASE_MEM GL2 write-back with queued draw reads is not implemented"); + static const bool gpuOrdered = std::getenv("APS5_NO_FLUSH_GPU_ORDERED") == nullptr; + struct OrderedScope { + bool previous; + explicit OrderedScope(bool on) : previous(GpuOrderedFlush()) { GpuOrderedFlush() = previous || on; } + ~OrderedScope() { GpuOrderedFlush() = previous; } + } ordered{gpuOrdered}; + static_cast(FlushPending(0, bytes, nullptr, "release", PublishScope::Whole, nullptr, false, device)); +} + bool StorageTexture::FlushAllPendingUntil(const char* reason, const std::function& stop, VkDevice device) { std::optional onCpu; if (reason != nullptr && std::strcmp(reason, "idle") == 0) onCpu.emplace(); diff --git a/core/libs/prx/libSceAgcDriver/tests/Pm4.cpp b/core/libs/prx/libSceAgcDriver/tests/Pm4.cpp index 739215eaa15f..04ef96bf2cfe 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Pm4.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Pm4.cpp @@ -1086,6 +1086,47 @@ void testEventWrite() { } } +void testReleaseMemWriteback() { + const auto release = [](std::uint32_t control) { return makePacket(0x49, {control, 1u << 29u, 0x1000, 0, 1, 0, 0}); }; + for (const auto control : {0x00200514u, 0x00300514u, 0x0030c514u, 0x0630c528u}) { + const auto packet = release(control); + check(AgcDriver::Pm4::ReleaseWritesBackL2(packet), "RELEASE_MEM lost an explicit GL2 write-back"); + for (const auto queue : {0u, 0x20u}) AgcDriver::Pm4::Validate(packet, queue); + } + for (const auto control : {0x514u, 0x528u, 0x0000c514u, 0x00100514u}) { + const auto packet = release(control); + AgcDriver::Pm4::Validate(packet, 0); + check(!AgcDriver::Pm4::ReleaseWritesBackL2(packet), "RELEASE_MEM without GL2 write-back requested publication"); + } + const auto computeDone = release(0x0020062fu); + AgcDriver::Pm4::Validate(computeDone, 0x20); + check(AgcDriver::Pm4::ReleaseWritesBackL2(computeDone), "a compute CS_DONE release lost GL2 write-back"); + for (const auto event : {0x04u, 0x14u, 0x28u, 0x29u, 0x2bu, 0x2du}) { + for (const auto queue : {0u, 0x20u}) AgcDriver::Pm4::Validate(release(0x00200500u | event), queue); + } + expectFailure([&] { AgcDriver::Pm4::Validate(computeDone, 0); }, "RELEASE_MEM GL2 write-back event/index"); + for (const auto control : {0x0020052fu, 0x00200630u, 0x00200414u, 0x00200614u, 0x00200510u, 0x00200014u}) { + for (const auto queue : {0u, 0x20u}) { + expectFailure([&] { AgcDriver::Pm4::Validate(release(control), queue); }, "RELEASE_MEM GL2 write-back event/index"); + } + } + for (const auto control : {0u, 2u << 24u, 3u << 24u, 4u << 24u}) { + const auto packet = makePacket(0x49, {0x00300514, control, 0, 0, 0, 0, 0}); + AgcDriver::Pm4::Validate(packet, 0); + check(AgcDriver::Pm4::ReleaseWritesBackL2(packet), "a release without label data lost GL2 write-back"); + } + for (const auto flags : {0x10000u, 0x20000u, 0x40000u, 0x60000u, 0x80000u, 0x400000u, 0x800000u, 0xc00000u}) { + const auto packet = release(0x00200514u | flags); + for (const auto queue : {0u, 0x20u}) { + expectFailure([&] { AgcDriver::Pm4::Validate(packet, queue); }, "RELEASE_MEM GL2 write-back scope"); + } + } + check(!AgcDriver::Pm4::ReleaseWritesBackL2({}), "an empty packet requested GL2 write-back"); + const auto packet = release(0x00200514u); + check(!AgcDriver::Pm4::ReleaseWritesBackL2(std::span(packet).first(1)), "a header without release control requested GL2 write-back"); + check(!AgcDriver::Pm4::ReleaseWritesBackL2(makePacket(0x37, {0x00200514, 0x1000, 0, 1})), "WRITE_DATA was classified as a GL2 write-back release"); +} + void testAcquireMem() { const auto captured = makePacket(0x58, {0x02007fc0, 0, 0, 0, 0, 10, 0x200}); AgcDriver::Pm4::Validate(captured, 0); @@ -2868,6 +2909,7 @@ int main(int argc, char** argv) { testGcnReleaseMemSystemCounter(); testGcnCalledBufferPacketForms(); testAcquireMem(); + testReleaseMemWriteback(); testConditionalWrite(); testConditionalWriteSubmission(); testConditionalWriteRegisters(); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_completion_reuse_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_completion_reuse_tests.cmake new file mode 100644 index 000000000000..cb0277aba704 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_storage_completion_reuse_tests.cmake @@ -0,0 +1,78 @@ +target_link_libraries(agc_driver_storage_completion_reuse_tests PRIVATE libkernel) + +if(BUILD_TESTING) + set_tests_properties(agc_driver_storage_completion_reuse PROPERTIES TIMEOUT 30) + add_test(NAME agc_driver_storage_completion_reuse_writeback COMMAND agc_driver_storage_completion_reuse_tests medium compared writeback) + set_tests_properties(agc_driver_storage_completion_reuse_writeback PROPERTIES + ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 + WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) + if(WIN32) + set_tests_properties(agc_driver_storage_completion_reuse_writeback PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() + foreach(reuseSize IN ITEMS small medium large) + foreach(reuseMemory IN ITEMS compared watched) + foreach(reuseImport IN ITEMS allowed disabled) + if(reuseSize STREQUAL "medium" AND reuseMemory STREQUAL "compared" AND reuseImport STREQUAL "allowed") + continue() + endif() + set(reuseTest "agc_driver_storage_completion_reuse_${reuseSize}_${reuseMemory}") + set(reuseEnvironment "ANYPS5_NO_SHADER_CACHE=1") + if(reuseImport STREQUAL "disabled") + string(APPEND reuseTest "_no_import") + list(APPEND reuseEnvironment "APS5_NO_HOST_IMPORT=1") + endif() + add_test(NAME ${reuseTest} COMMAND agc_driver_storage_completion_reuse_tests ${reuseSize} ${reuseMemory}) + set_tests_properties(${reuseTest} PROPERTIES + ENVIRONMENT "${reuseEnvironment}" SKIP_RETURN_CODE 77 + WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) + if(WIN32) + set_tests_properties(${reuseTest} PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() + endforeach() + endforeach() + endforeach() + foreach(reuseRoute IN ITEMS label64 timestamp cache-only interrupt conditional no-interrupt compute) + string(REPLACE "-" "_" reuseSuffix "${reuseRoute}") + set(reuseTest "agc_driver_storage_completion_reuse_${reuseSuffix}") + add_test(NAME ${reuseTest} COMMAND agc_driver_storage_completion_reuse_tests medium compared explicit ${reuseRoute}) + set_tests_properties(${reuseTest} PROPERTIES + ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 + WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) + if(WIN32) + set_tests_properties(${reuseTest} PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() + endforeach() + foreach(reuseExecution IN ITEMS deferred immediate dispatch_items) + set(reuseTest "agc_driver_storage_completion_reuse_${reuseExecution}") + set(reuseEnvironment "ANYPS5_NO_SHADER_CACHE=1") + set(reuseRoute "no-interrupt") + if(reuseExecution STREQUAL "dispatch_items") + set(reuseRoute "label32") + list(APPEND reuseEnvironment "APS5_DRAW_PIPELINE=1" "APS5_PIPELINED_DRAWS=8" "APS5_PIPELINE_DISPATCH=1") + else() + list(APPEND reuseEnvironment "APS5_PIPELINED_DRAWS=0") + if(reuseExecution STREQUAL "immediate") + list(APPEND reuseEnvironment "APS5_LABEL_LOCK_EACH=1") + endif() + endif() + add_test(NAME ${reuseTest} COMMAND agc_driver_storage_completion_reuse_tests medium compared explicit ${reuseRoute}) + set_tests_properties(${reuseTest} PROPERTIES + ENVIRONMENT "${reuseEnvironment}" SKIP_RETURN_CODE 77 + WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) + if(WIN32) + set_tests_properties(${reuseTest} PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() + endforeach() + add_test(NAME agc_driver_storage_completion_reuse_consumer_ahead COMMAND agc_driver_storage_completion_reuse_tests medium compared explicit consumer) + set_tests_properties(agc_driver_storage_completion_reuse_consumer_ahead PROPERTIES + ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_GROUP_CAPTURE_ALL_QUEUES=1;APS5_PIPELINED_DRAWS=0" SKIP_RETURN_CODE 77 + WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" TIMEOUT 30) + if(WIN32) + set_tests_properties(agc_driver_storage_completion_reuse_consumer_ahead PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StorageCompletionReuse.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCompletionReuse.cpp new file mode 100644 index 000000000000..372e0240d087 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StorageCompletionReuse.cpp @@ -0,0 +1,401 @@ +#include "prx/libkernel/include/Api.hpp" +#include "prx/libkernel/Equeue/Equeue.hpp" +#include "prx/libSceAgcDriver/Eq/include/Event.hpp" +#include "prx/libSceAgcDriver/Eq/include/Query.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Graphics/include/GuestTextureResource.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using AgcDriver::Graphics::StorageTexture; +constexpr std::size_t PageBlock = 0x10000; +constexpr std::uint32_t Texel = 0x00ffffffu; +constexpr std::uint8_t Initial = 0xa5; +constexpr std::uint8_t Guard = 0x3c; + +alignas(256) constexpr std::array StoreCode{ + 0x7e02020c, 0x7e0402f2, 0x7e0602f2, 0x7e0802f2, 0x7e0a0280, 0xf0201f08, 0x00010200, 0xbf810000, +}; + +alignas(256) constexpr std::array LoadRowCode{ + 0x7e020280, 0xf0001108, 0x00010300, 0x34080082, 0xbf8c3f70, 0xe0701000, 0x80000304, 0xbf810000, +}; + +std::uint64_t Address(const void* pointer) { + return static_cast(reinterpret_cast(pointer)); +} + +struct Shape { + std::uint32_t width; + std::uint32_t height; + std::size_t bytes; +}; + +std::array Descriptor(std::uint64_t address, Shape shape) { + return { + static_cast(address >> 8u), + static_cast((address >> 40u) & 0xffu) | (56u << 20u) | (((shape.width - 1u) & 3u) << 30u), + ((shape.width - 1u) >> 2u) | ((shape.height - 1u) << 14u), + 0xfacu | (0x1bu << 20u) | (9u << 28u), + 0u, 0u, 0u, 0u, + }; +} + +class GuestBlock { +public: + GuestBlock(std::size_t imageBytes, bool watched) : bytes(imageBytes + 2 * PageBlock), watched(watched) { +#ifdef _WIN32 + if (watched) { + data = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(bytes, PageBlock)); + if (data != nullptr) GuestArena::GuestArenaCommit_nid_postfix(data, bytes, PAGE_READWRITE, PageBlock); + } else { + data = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + } +#else + void* mapped = mmap(nullptr, bytes + PageBlock, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (mapped != MAP_FAILED) { + const auto begin = reinterpret_cast(mapped); + const auto aligned = (begin + PageBlock - 1) & ~std::uintptr_t{PageBlock - 1}; + if (aligned != begin) munmap(mapped, aligned - begin); + const auto tail = begin + bytes + PageBlock - aligned - bytes; + if (tail != 0) munmap(reinterpret_cast(aligned + bytes), tail); + data = reinterpret_cast(aligned); + if (watched) GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(data, bytes); + } +#endif + Require(data != nullptr, "storage completion reuse: cannot allocate guest memory"); + std::memset(data, Guard, bytes); + GuestAllocations::Mutation().Add(data, bytes, true, true, true); + } + + ~GuestBlock() { + GuestAllocations::Mutation().Remove(data); +#ifdef _WIN32 + if (watched) { + GuestArena::GuestArenaReset_nid_postfix(data, bytes); + GuestArena::GuestArenaRelease_nid_postfix(data, bytes); + } else { + VirtualFree(data, 0, MEM_RELEASE); + } +#else + if (watched) GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(data, bytes); + munmap(data, bytes); +#endif + } + + GuestBlock(const GuestBlock&) = delete; + GuestBlock& operator=(const GuestBlock&) = delete; + std::uint8_t* Data() const { return data + PageBlock; } + + std::size_t ChangedGuards() const { + const volatile std::uint8_t* cpu = data; + std::size_t changed = 0; + for (std::size_t offset = 0; offset < PageBlock; ++offset) { + changed += cpu[offset] != Guard; + changed += cpu[bytes - PageBlock + offset] != Guard; + } + return changed; + } + +private: + std::size_t bytes; + bool watched; + std::uint8_t* data = nullptr; +}; + +enum class Route { Label32, Label64, Timestamp, CacheOnly, Interrupt, Conditional, NoInterrupt, Compute, Consumer }; + +class Events { +public: + explicit Events(bool enabled) { + if (!enabled) return; + Require(sceKernelCreateEqueue(&queue, "AGC storage completion") == 0, "storage completion reuse: cannot create event queue"); + owner = EqueuePin_nid_postfix(queue); + Require(owner != nullptr, "storage completion reuse: cannot pin event queue"); + Require(sceAgcDriverAddEqEvent(queue, 0, &tag) == 0, "storage completion reuse: cannot register end-of-pipe event"); + } + + ~Events() { + if (queue == 0) return; + sceAgcDriverDeleteEqEvent(queue, 0); + owner.reset(); + sceKernelDeleteEqueue(queue); + } + + void Drain() { + if (owner == nullptr) return; + std::array event{}; + while (owner->GetTriggeredEvents(event.data(), 1) != 0) {} + } + + bool Arrived(std::uint32_t context) { + std::array event{}; + if (owner->GetTriggeredEvents(event.data(), 1) == 0) return false; + Require(event[0].udata == &tag && sceAgcDriverGetEqContextId(event.data()) == context, + "storage completion reuse: an unexpected end-of-pipe event arrived"); + return true; + } + +private: + KernelEqueue queue = 0; + KernelEqueueRef owner; + int tag = 0; +}; + +void StoreThenLabel(const GuestBlock& image, Shape shape, std::uint32_t* label, std::uint32_t value, std::uint32_t releaseFlags, Route route, const GuestBlock* output) { + std::vector words; + const auto registers = [&](std::uint32_t first, std::span values) { + words.push_back(0xc0007600u | (static_cast(values.size()) << 16u)); + words.push_back(first); + words.insert(words.end(), values.begin(), values.end()); + }; + const std::array threads{shape.width, 1, 1}; + registers(0x207, threads); + const auto code = Address(StoreCode.data()); + const std::array program{static_cast(code >> 8u), static_cast(code >> 40u)}; + registers(0x20c, program); + std::array userData{}; + const auto texture = Descriptor(Address(image.Data()), shape); + std::copy(texture.begin(), texture.end(), userData.begin() + 4); + const std::array layout{(static_cast(userData.size()) << 1u) | 0x80u}; + registers(0x213, layout); + registers(0x240, userData); + words.insert(words.end(), {0xc0031500u, shape.height, 1, 1, 0x41u}); + const auto destination = Address(label); + const auto release = [&](std::uint32_t flags, std::uint32_t dataSelect, std::uint32_t interruptSelect, std::uint64_t address, std::uint32_t low, std::uint32_t high) { + words.insert(words.end(), {0xc0064900u, flags, (dataSelect << 29u) | (interruptSelect << 24u), + static_cast(address), static_cast(address >> 32u), low, high, value}); + }; + if (route == Route::Consumer) { + Require(output != nullptr, "storage completion reuse: consumer output is absent"); + release(releaseFlags, 0, 0, 0, 0, 0); + const auto readCode = Address(LoadRowCode.data()); + const std::array readProgram{static_cast(readCode >> 8u), static_cast(readCode >> 40u)}; + registers(0x20c, readProgram); + const auto outputAddress = Address(output->Data()); + std::array readData{}; + readData[0] = static_cast(outputAddress); + readData[1] = static_cast((outputAddress >> 32u) & 0xffffu); + readData[2] = shape.width * sizeof(Texel); + readData[3] = 0x31016facu; + auto linear = texture; + linear[1] = (linear[1] & ~(0x1ffu << 20u)) | (20u << 20u); + linear[3] = 0xfacu | (9u << 28u); + std::copy(linear.begin(), linear.end(), readData.begin() + 4); + const std::array readLayout{static_cast(readData.size()) << 1u}; + registers(0x213, readLayout); + registers(0x240, readData); + words.insert(words.end(), {0xc0031500u, 1, 1, 1, 0x41u}); + release(0x514u, 1, 0, destination, value, 0); + } else if (route == Route::CacheOnly) { + release(releaseFlags, 0, 0, 0, 0, 0); + release(0x514u, 1, 0, destination, value, 0); + } else if (route == Route::Interrupt) { + release(releaseFlags, 0, 2, 0, 0, 0); + } else { + const auto dataSelect = route == Route::Label64 ? 2u : route == Route::Timestamp ? 3u : 1u; + const auto interruptSelect = route == Route::Conditional ? 3u : route == Route::NoInterrupt ? 0u : 2u; + release(releaseFlags, dataSelect, interruptSelect, destination, value, route == Route::Label64 ? 0x12345678u : 0u); + } + Packet packet{words.data(), static_cast(words.size()), 0, {}}; + AgcDriver::Submit(&packet, route == Route::Compute ? 0x20u : 0u); +} + +std::uint64_t ClockStamp() { + return static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count() / 10); +} + +void AwaitCompletion(std::uint32_t* label, std::uint32_t value, Route route, Events& events, std::uint64_t started) { + const auto complete = [&] { + if (route == Route::Interrupt) return events.Arrived(value); + if (route == Route::Label64 || route == Route::Timestamp) { + const auto observed = std::atomic_ref(*reinterpret_cast(label)).load(std::memory_order_acquire); + return route == Route::Timestamp ? observed >= started && observed <= ClockStamp() : observed == ((0x12345678ull << 32u) | value); + } + return std::atomic_ref(*label).load(std::memory_order_acquire) == value; + }; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (!complete()) { + Require(std::chrono::steady_clock::now() < deadline, "storage completion reuse: completion did not arrive"); + std::this_thread::sleep_for(std::chrono::microseconds(100)); + } +} + +bool LabelMatches(std::uint32_t* label, std::uint32_t value, Route route, std::uint64_t started, std::uint64_t completed) { + const auto observed = std::atomic_ref(*reinterpret_cast(label)).load(std::memory_order_acquire); + if (route == Route::Timestamp) return observed >= started && observed <= completed; + if (route == Route::Interrupt) return observed == UINT64_MAX; + const auto high = route == Route::Label64 ? 0x12345678ull : 0xffffffffull; + return observed == ((high << 32u) | value); +} + +std::uint64_t Link(std::uint32_t pass, std::size_t offset) { + return 0x0000000280000010ull + (static_cast(pass) << 24u) + offset; +} + +void WriteLinks(std::uint8_t* image, std::size_t bytes, std::uint32_t pass) { + for (std::size_t block = 0; block < bytes; block += PageBlock) { + for (const auto within : {std::size_t{0}, std::size_t{8}, PageBlock - sizeof(std::uint64_t)}) { + const auto offset = block + within; + const auto link = Link(pass, offset); + std::memcpy(image + offset, &link, sizeof(link)); + } + } +} + +struct Comparison { + std::size_t differences = 0; + std::size_t first = 0; +}; + +Comparison Compare(const std::uint8_t* actual, std::span expected) { + const volatile std::uint8_t* cpu = actual; + Comparison result; + for (std::size_t offset = 0; offset < expected.size(); ++offset) { + if (cpu[offset] == expected[offset]) continue; + if (result.differences == 0) result.first = offset; + ++result.differences; + } + return result; +} + +void Publish(const GuestBlock& image, std::size_t bytes) { + std::array read{}; + AgcDriver::GuestMemory::Read(Address(image.Data()) + bytes / 2, read); + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + StorageTexture::FlushAllPending("storage completion reuse fixture"); +} + +int Run(Shape shape, bool watched, std::uint32_t releaseFlags, Route route, const std::string& routeName) { + GuestBlock image(shape.bytes, watched); + GuestBlock labels(PageBlock, false); + std::unique_ptr output; + std::vector outputBytes; + if (route == Route::Consumer) { + output = std::make_unique(PageBlock, false); + outputBytes.resize(PageBlock, Initial); + for (std::size_t offset = 0; offset < shape.width * sizeof(Texel); offset += sizeof(Texel)) { + std::memcpy(outputBytes.data() + offset, &Texel, sizeof(Texel)); + } + } + Events events(route == Route::Interrupt); + const auto resource = AgcDriver::Graphics::DecodeTextureResource(Descriptor(Address(image.Data()), shape)); + Require(resource.width == shape.width && resource.height == shape.height && + AgcDriver::Graphics::DescribeSurface(resource).guestBytes == shape.bytes, + "storage completion reuse: descriptor does not cover the requested surface"); + const bool imageWatched = AgcDriver::GuestMemory::Watched(Address(image.Data()), shape.bytes); + if (watched && !imageWatched) { + std::printf("[storage completion reuse] SKIP: guest write-watch tracking is unavailable for the requested watched allocation\n"); + return VulkanTestSkipped; + } + Require(imageWatched == watched, "storage completion reuse: compared allocation is unexpectedly write-watched"); + std::vector gpuBytes(shape.bytes); + for (std::size_t offset = 0; offset < shape.bytes; offset += sizeof(Texel)) std::memcpy(gpuBytes.data() + offset, &Texel, sizeof(Texel)); + auto* label = reinterpret_cast(labels.Data()); + std::size_t failures = 0; + struct Shutdown { + ~Shutdown() { try { AgcDriverShutdown_nid_postfix(); } catch (...) {} } + } shutdown; + for (std::uint32_t pass = 0; pass < 4; ++pass) { + const bool same = (pass & 1u) != 0; + std::memset(image.Data(), Initial, shape.bytes); + WriteLinks(image.Data(), shape.bytes, pass); + if (output) std::memset(output->Data(), Initial, PageBlock); + std::atomic_ref(*reinterpret_cast(label)).store(UINT64_MAX, std::memory_order_release); + events.Drain(); + const auto started = ClockStamp(); + StoreThenLabel(image, shape, label, pass + 1, releaseFlags, route, output.get()); + AwaitCompletion(label, pass + 1, route, events, started); + const auto completed = ClockStamp(); + const auto visible = Compare(image.Data(), gpuBytes); + const auto consumed = output ? Compare(output->Data(), outputBytes) : Comparison{}; + const auto cpuPass = same ? pass : pass + 100; + WriteLinks(image.Data(), shape.bytes, cpuPass); + auto expected = gpuBytes; + WriteLinks(expected.data(), shape.bytes, cpuPass); + Publish(image, shape.bytes); + const auto kept = Compare(image.Data(), expected); + const auto guards = image.ChangedGuards() + labels.ChangedGuards() + (output ? output->ChangedGuards() : 0); + const bool labelMatches = LabelMatches(label, pass + 1, route, started, completed); + std::printf("[storage completion reuse] bytes=%zu memory=%s release=0x%x route=%s pass=%u links=%s before=%zu first=0x%zx after=%zu first=0x%zx consumed=%zu first=0x%zx guards=%zu label=%d\n", + shape.bytes, watched ? "watched" : "compared", releaseFlags, routeName.c_str(), pass, same ? "same" : "new", + visible.differences, visible.first, kept.differences, kept.first, consumed.differences, consumed.first, guards, labelMatches); + failures += visible.differences != 0 || kept.differences != 0 || consumed.differences != 0 || guards != 0 || !labelMatches; + } + AgcDriverWaitIdle_nid_postfix(); + if (releaseFlags == 0x514u) { + std::printf("[storage completion reuse] diagnostic only: legacy release had %zu differing passes; its cache visibility contract is not asserted\n", failures); + return 0; + } + Require(failures == 0, "storage completion reuse: completion visibility or later CPU ownership was lost"); + return 0; +} + +} + +int main(int argc, char** argv) { + try { + Require(argc == 1 || (argc >= 3 && argc <= 5), "storage completion reuse: expected size, memory mode and optional release mode and route"); + const std::string size = argc == 1 ? "medium" : argv[1]; + const Shape shape = size == "small" ? Shape{128, 128, PageBlock} : + size == "medium" ? Shape{256, 256, 4 * PageBlock} : + size == "large" ? Shape{256, 2048, 32 * PageBlock} : Shape{}; + Require(shape.bytes != 0, "storage completion reuse: unknown size"); + const std::string memory = argc == 1 ? "compared" : argv[2]; + const std::string release = argc < 4 ? "explicit" : argv[3]; + Require(release == "explicit" || release == "writeback" || release == "legacy", "storage completion reuse: unknown release mode"); + std::uint32_t releaseFlags = release == "explicit" ? 0x00300514u : release == "writeback" ? 0x00200514u : 0x514u; + Require(memory == "watched" || memory == "compared", "storage completion reuse: unknown memory mode"); + const std::string routeName = argc < 5 ? "label32" : argv[4]; + Route route = Route::Label32; + if (routeName == "label64") route = Route::Label64; + else if (routeName == "timestamp") route = Route::Timestamp; + else if (routeName == "cache-only") route = Route::CacheOnly; + else if (routeName == "interrupt") route = Route::Interrupt; + else if (routeName == "conditional") route = Route::Conditional; + else if (routeName == "no-interrupt") route = Route::NoInterrupt; + else if (routeName == "compute") { route = Route::Compute; releaseFlags = 0x0020062fu; } + else if (routeName == "consumer") route = Route::Consumer; + else Require(routeName == "label32", "storage completion reuse: unknown route"); + { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + } + return Run(shape, memory == "watched", releaseFlags, route, routeName); + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/docs/dev/debt/changes/gpu-completion-reuse-rebase.md b/docs/dev/debt/changes/gpu-completion-reuse-rebase.md new file mode 100644 index 000000000000..0695d083b25c --- /dev/null +++ b/docs/dev/debt/changes/gpu-completion-reuse-rebase.md @@ -0,0 +1,5 @@ +# libSceAgcDriver + +## add Functional + +- [RELEASE_MEM GL2 write-back](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp) throws for nonzero GL2_US/RANGE/DISCARD/SEQ, non-EOP event/index pairs except ACE CS_DONE, queued draw reads, and another thread's unfinished image publication. Those scopes, graphics EOS cache operations and cross-queue ownership are not modeled. Global write-back uses existing image/depth/shadow publication before completion. [AMD PAL](https://github.com/GPUOpen-Drivers/pal/blob/c5e800072a32f68b6ccc4422936d96167c6e0728/src/core/hw/gfxip/gfx9/gfx9CmdUtil.cpp#L3428) establishes the event/GCR fields; no PS5 comparison was run. GPU-ordered host imports, concurrent CPU-store races and title performance remain unverified.