From c69c8d9e80f956116301bbc55027104000e79eff Mon Sep 17 00:00:00 2001 From: ee6aba54 <340958984+ee6aba54@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:46:13 +0200 Subject: [PATCH 01/11] fix(agc-driver): keep CPU stores made after a deferred DCC key store was recorded The "uncompressed" key store recorded behind a storage write-back filled the keys' host import whenever the GPU reached it. A title that had released the metadata block by then and reused it (a descriptor table, for one) got the fill pattern over its own bytes; the next dispatch built from such a V# failed in the recompiler with an unsupported format or type. The queued key store now takes a snapshot of the key bytes at record time and the batch stores the 0xff pattern through the changed-copy kernel, so a dword the CPU wrote after the record keeps the CPU's value. A range whose only pending writers are earlier 0xff fills of the same keys stays guarded (the kernel need not repeat them); a pending kernel of the title writing the keys, or a range without a device address or a snapshot, is filled as before. The [labels] line counts the guarded stores; APS5_NO_GUARDED_KEY_STORE=1 restores the fills. --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 1 + .../src/Driver/Packets/PacketFlush.cpp | 2 +- .../Graphics/include/Recorder.hpp | 7 ++- .../Graphics/src/DccMetadata.cpp | 2 +- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 63 ++++++++++++++++--- .../prx/libSceAgcDriver/tests/Recorder.cpp | 59 +++++++++++++++++ 6 files changed, 123 insertions(+), 11 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 1d394668ce72..2c1b3551a857 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -1487,6 +1487,7 @@ if(BUILD_TESTING) add_test(NAME agc_changed_copy COMMAND agc_driver_recorder_tests --changed-copy-only) set_tests_properties(agc_changed_copy PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) add_test(NAME agc_unit_shadow COMMAND agc_driver_recorder_tests --unit-shadow-only) + add_test(NAME agc_guarded_key_store COMMAND agc_driver_recorder_tests --guarded-key-store-only) set_tests_properties(agc_unit_shadow PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30 ENVIRONMENT "APS5_PIN_WAIT_MS=3000") if(WIN32) add_test(NAME agc_storage_cpu_snapshot COMMAND agc_driver_recorder_tests --storage-cpu-snapshot-only) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp index 410a98b3c8cc..c899ef6b9a51 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp @@ -105,7 +105,7 @@ void Driver::flushBetweenPackets(std::uint32_t queue, std::uint32_t header, bool lastReport = reportNow; const auto stores = Graphics::Recorder::StoreCounts(); const auto failed = [](TrySite site) { return static_cast(triesFailed[site].load()); }; - AgcDriver::ProfilePrint_nid_no_patch("[labels] batch flushes between packets: %llu at the next packet, %llu by deadline, %llu by size cap (%llu well overdue, waited for the mutex); %llu boundary reaps; record tries skipped (self-locking next) %llu; failed tries: label %llu, flush %llu, reap %llu, poll %llu, idle %llu, capture %llu, poll-record %llu; at the packet's own lock: %llu label groups (%.0f ms), %llu submits (%.0f ms incl. queue 0's reaps), left to it by a failed try: %llu groups, %llu submits; after a capture: %llu groups recorded by a try, %llu packets redone for a queued label over the capture; %llu suspend points; stores: %llu in %llu runs (%llu joined, %llu replaced, %llu WAW barriers, %llu joins refused; %llu runs recorded at submit, %llu in place before a writer or reader); DCC key stores: %llu queued in %llu runs (%llu before a writer, %llu joined a queued range); queued labels: %llu noted (%llu over a recorded entry), %llu same-queue wait hits, %llu groups recorded from a poll loop, %llu from the flush hook (%llu hook accesses, %llu inside a completion skipped)\n", static_cast(packetFlushes.load()), static_cast(deadlineFlushes.load()), static_cast(capFlushes.load()), static_cast(overdueLocks.load()), static_cast(boundaryReaps.load()), static_cast(recordTriesSkipped.load()), failed(TryLabel), failed(TryFlush), failed(TryReap), failed(TryPoll), failed(TryIdle), failed(TryCapture), failed(TryPollRecord), static_cast(packetLockRecords.load()), packetLockRecordUs.load() / 1000.0, static_cast(packetLockSubmits.load()), packetLockSubmitUs.load() / 1000.0, static_cast(packetLockDeferred.load()), static_cast(packetSubmitDeferred.load()), static_cast(captureTryRecords.load()), static_cast(captureRetries.load()), static_cast(suspendPoints.load()), static_cast(stores.stores), static_cast(stores.runs), static_cast(stores.joined), static_cast(stores.replaced), static_cast(stores.wawBarriers), static_cast(stores.joinsRefused), static_cast(stores.runsAtSubmit), static_cast(stores.runsForced), static_cast(stores.keyStores), static_cast(stores.keyStoreRuns), static_cast(stores.keyStoreRunsForWriter), static_cast(stores.keyStoresJoined), static_cast(stores.queuedNoted), static_cast(stores.queuedOverRecorded), static_cast(stores.queuedHits), static_cast(pollLabelRecords.load()), static_cast(hookLabelRecords.load()), static_cast(stores.queuedHookRecords), static_cast(stores.queuedHookInCompletion)); + AgcDriver::ProfilePrint_nid_no_patch("[labels] batch flushes between packets: %llu at the next packet, %llu by deadline, %llu by size cap (%llu well overdue, waited for the mutex); %llu boundary reaps; record tries skipped (self-locking next) %llu; failed tries: label %llu, flush %llu, reap %llu, poll %llu, idle %llu, capture %llu, poll-record %llu; at the packet's own lock: %llu label groups (%.0f ms), %llu submits (%.0f ms incl. queue 0's reaps), left to it by a failed try: %llu groups, %llu submits; after a capture: %llu groups recorded by a try, %llu packets redone for a queued label over the capture; %llu suspend points; stores: %llu in %llu runs (%llu joined, %llu replaced, %llu WAW barriers, %llu joins refused; %llu runs recorded at submit, %llu in place before a writer or reader); DCC key stores: %llu queued in %llu runs (%llu before a writer, %llu joined a queued range, %llu guarded); queued labels: %llu noted (%llu over a recorded entry), %llu same-queue wait hits, %llu groups recorded from a poll loop, %llu from the flush hook (%llu hook accesses, %llu inside a completion skipped)\n", static_cast(packetFlushes.load()), static_cast(deadlineFlushes.load()), static_cast(capFlushes.load()), static_cast(overdueLocks.load()), static_cast(boundaryReaps.load()), static_cast(recordTriesSkipped.load()), failed(TryLabel), failed(TryFlush), failed(TryReap), failed(TryPoll), failed(TryIdle), failed(TryCapture), failed(TryPollRecord), static_cast(packetLockRecords.load()), packetLockRecordUs.load() / 1000.0, static_cast(packetLockSubmits.load()), packetLockSubmitUs.load() / 1000.0, static_cast(packetLockDeferred.load()), static_cast(packetSubmitDeferred.load()), static_cast(captureTryRecords.load()), static_cast(captureRetries.load()), static_cast(suspendPoints.load()), static_cast(stores.stores), static_cast(stores.runs), static_cast(stores.joined), static_cast(stores.replaced), static_cast(stores.wawBarriers), static_cast(stores.joinsRefused), static_cast(stores.runsAtSubmit), static_cast(stores.runsForced), static_cast(stores.keyStores), static_cast(stores.keyStoreRuns), static_cast(stores.keyStoreRunsForWriter), static_cast(stores.keyStoresJoined), static_cast(stores.keyStoresGuarded), static_cast(stores.queuedNoted), static_cast(stores.queuedOverRecorded), static_cast(stores.queuedHits), static_cast(pollLabelRecords.load()), static_cast(hookLabelRecords.load()), static_cast(stores.queuedHookRecords), static_cast(stores.queuedHookInCompletion)); } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index 9511f9f25b09..e936d5083275 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -77,7 +77,7 @@ class Recorder { // that know their ranges). `seed` (kept) supplies an // unaligned head or tail; [begin, end) is the guest range. Debug aid: APS5_DCC_KEYS_EACH=1 // records every store at once, as before (QueueKeyStore then records and returns). - void QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize last, std::shared_ptr seed, std::uint64_t begin, std::uint64_t end); + void QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize last, std::shared_ptr seed, std::uint64_t begin, std::uint64_t end, VkDeviceAddress target = 0); bool HasQueuedKeyStores() const { return open != nullptr && !open->keyStores.empty(); } bool QueuedKeyStoreOverlaps(std::uint64_t address, std::size_t bytes) const; // Whether `overlaps(begin, end)` holds for a queued store's range. @@ -453,7 +453,7 @@ class Recorder { std::uint64_t stores, runs, joined, replaced, wawBarriers, joinsRefused, queuedNoted, queuedOverRecorded, queuedHits, queuedHookRecords, queuedHookInCompletion; // DCC key stores queued, the runs that recorded them (at Submit, or before a writer of a // queued range), and the queued stores a duplicate range joined. - std::uint64_t keyStores, keyStoreRuns, keyStoreRunsForWriter, keyStoresJoined; + std::uint64_t keyStores, keyStoreRuns, keyStoreRunsForWriter, keyStoresJoined, keyStoresGuarded; // Store runs recorded at Submit, and in place before a later writer or reader of a queued // store's bytes (FlushStores). std::uint64_t runsAtSubmit, runsForced; @@ -669,6 +669,8 @@ class Recorder { std::shared_ptr seed; std::uint64_t begin; std::uint64_t end; + std::shared_ptr snapshot; + VkDeviceAddress target = 0; }; std::vector keyStores; }; @@ -714,6 +716,7 @@ class Recorder { VkPipelineLayout meshArgumentLayout = VK_NULL_HANDLE; VkPipeline meshArgumentPipeline = VK_NULL_HANDLE; int changedCopyState = 0; + std::shared_ptr onesBuffer; VkPipelineLayout changedCopyLayout = VK_NULL_HANDLE; VkPipeline changedCopyPipeline = VK_NULL_HANDLE; int sampleCounterState = 0; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp index eee078cba1c8..78501a42ba4a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp @@ -252,7 +252,7 @@ bool StoreUncompressedOnGpu(const Context& context, Recorder& recorder, std::uin if (AnyShadowedOverlaps(begin, count)) PublishShadow(begin, count, PublishScope::PartialUnits, PublishReason::Keys); // Queued on the open batch and recorded with the batch's other key stores as one run (or before // a later command writing the keys; see Recorder::QueueKeyStore). - recorder.QueueKeyStore(import->buffer, first, last, std::move(seed), begin, begin + count); + recorder.QueueKeyStore(import->buffer, first, last, std::move(seed), begin, begin + count, import->address != 0 ? import->address + first : 0); recorder.NotePendingFill(begin, count, 0xff); GuestMemory::MarkWritten(begin, count); // After the note: an unlocked memo lookup drops an entry the snapshot does not cover yet. The diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 381d36476f90..42a907968456 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -568,7 +568,14 @@ bool LateTrustEnabled() { } // Store-run and queued-label counters (Recorder::StoreCounts), relaxed: they are only reported. std::atomic storeCount{0}, storeRuns{0}, storesJoined{0}, storesReplaced{0}, storeWawBarriers{0}, storeJoinsRefused{0}; -std::atomic keyStoreCount{0}, keyStoreRuns{0}, keyStoreRunsForWriter{0}, keyStoresJoined{0}; +std::atomic keyStoreCount{0}, keyStoreRuns{0}, keyStoreRunsForWriter{0}, keyStoresJoined{0}, keyStoresGuarded{0}; + +bool GuardedKeyStores(const Context& context) { + static const bool disabled = std::getenv("APS5_NO_GUARDED_KEY_STORE") != nullptr; + return !disabled && context.bufferDeviceAddress; +} + +constexpr std::size_t OnesBufferBytes = std::size_t{1} << 20; // Debug aid: APS5_DCC_KEYS_EACH=1 records every DCC key store at once (see Recorder::QueueKeyStore). bool KeyStoresEach() { @@ -1392,7 +1399,7 @@ void Recorder::SetQueuedLabelRecorder(void (*recorder)()) { } Recorder::StoreStatistics Recorder::StoreCounts() { - return StoreStatistics{storeCount.load(std::memory_order_relaxed), storeRuns.load(std::memory_order_relaxed), storesJoined.load(std::memory_order_relaxed), storesReplaced.load(std::memory_order_relaxed), storeWawBarriers.load(std::memory_order_relaxed), storeJoinsRefused.load(std::memory_order_relaxed), queuedLabelsNoted.load(std::memory_order_relaxed), queuedLabelsOverRecorded.load(std::memory_order_relaxed), queuedLabelHits.load(std::memory_order_relaxed), queuedLabelHookRecords.load(std::memory_order_relaxed), queuedLabelHookInCompletion.load(std::memory_order_relaxed), keyStoreCount.load(std::memory_order_relaxed), keyStoreRuns.load(std::memory_order_relaxed), keyStoreRunsForWriter.load(std::memory_order_relaxed), keyStoresJoined.load(std::memory_order_relaxed), storeRunsAtSubmit.load(std::memory_order_relaxed), storeRunsForced.load(std::memory_order_relaxed)}; + return StoreStatistics{storeCount.load(std::memory_order_relaxed), storeRuns.load(std::memory_order_relaxed), storesJoined.load(std::memory_order_relaxed), storesReplaced.load(std::memory_order_relaxed), storeWawBarriers.load(std::memory_order_relaxed), storeJoinsRefused.load(std::memory_order_relaxed), queuedLabelsNoted.load(std::memory_order_relaxed), queuedLabelsOverRecorded.load(std::memory_order_relaxed), queuedLabelHits.load(std::memory_order_relaxed), queuedLabelHookRecords.load(std::memory_order_relaxed), queuedLabelHookInCompletion.load(std::memory_order_relaxed), keyStoreCount.load(std::memory_order_relaxed), keyStoreRuns.load(std::memory_order_relaxed), keyStoreRunsForWriter.load(std::memory_order_relaxed), keyStoresJoined.load(std::memory_order_relaxed), keyStoresGuarded.load(std::memory_order_relaxed), storeRunsAtSubmit.load(std::memory_order_relaxed), storeRunsForced.load(std::memory_order_relaxed)}; } std::uint64_t Recorder::ThreadHookWaits() { @@ -1500,7 +1507,7 @@ void Recorder::endOpenRenderPass(bool barrier) { pass = {}; } -void Recorder::QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize last, std::shared_ptr seed, std::uint64_t begin, std::uint64_t end) { +void Recorder::QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize last, std::shared_ptr seed, std::uint64_t begin, std::uint64_t end, VkDeviceAddress target) { ensureOpen(); // A queued label store over the keys lands first (program order: the key store is later). FlushStoresOverlapping(begin, static_cast(end - begin)); @@ -1514,7 +1521,29 @@ void Recorder::QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize l return; } } - open->keyStores.push_back({buffer, first, last, std::move(seed), begin, end}); + std::shared_ptr snapshot; + const VkDeviceSize fillBegin = std::min((first + 3) & ~VkDeviceSize{3}, last); + const VkDeviceSize fillEnd = std::max(last & ~VkDeviceSize{3}, fillBegin); + const auto guestFill = begin + (fillBegin - first); + const auto fillBytes = static_cast(fillEnd - fillBegin); + bool eligible = target != 0 && fillBytes != 0 && GuardedKeyStores(context) && GuestMemory::Accessible(reinterpret_cast(guestFill), fillBytes); + if (eligible && !PendingWriteSettled(begin, static_cast(end - begin))) { + const auto pending = PendingWritesOver(begin, static_cast(end - begin)); + eligible = std::all_of(pending.begin(), pending.end(), [](const PendingWrite& write) { return write.value == 0xff; }); + } + if (eligible) { + try { + snapshot = std::make_shared(context, fillBytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); + } catch (const std::exception&) { + snapshot = nullptr; + } + if (snapshot != nullptr && (!snapshot->Mapped() || snapshot->DeviceAddress() == 0)) snapshot = nullptr; + if (snapshot != nullptr) { + std::memcpy(snapshot->Bytes().data(), reinterpret_cast(guestFill), fillBytes); + keyStoresGuarded.fetch_add(1, std::memory_order_relaxed); + } + } + open->keyStores.push_back({buffer, first, last, std::move(seed), begin, end, std::move(snapshot), target}); if (KeyStoresEach()) recordKeyStores(false); } @@ -1542,14 +1571,34 @@ void Recorder::recordKeyStores(bool forWriter) { const auto timing = beginTiming(ClassKey(CommandClass::DccKeyStore)); // Ordered behind every earlier recorded read or write of the ranges (the title's DCC clear or // decompress kernel storing keys through a V#), and visible to the work after and to the host. - recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT); + recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); const auto fill = context.Resolved(&DeviceFunctions::cmdFillBuffer, "vkCmdFillBuffer"); const auto copy = context.Resolved(&DeviceFunctions::cmdCopyBuffer, "vkCmdCopyBuffer"); std::uint64_t bytes = 0; + const bool anyGuarded = std::any_of(stores.begin(), stores.end(), [](const Batch::KeyStore& store) { return store.snapshot != nullptr; }); + if (anyGuarded && onesBuffer == nullptr) { + try { + onesBuffer = std::make_shared(context, OnesBufferBytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); + std::memset(onesBuffer->Bytes().data(), 0xff, OnesBufferBytes); + } catch (const std::exception&) { + onesBuffer = nullptr; + } + } + const bool kernel = anyGuarded && onesBuffer != nullptr && onesBuffer->Mapped() && onesBuffer->DeviceAddress() != 0; + if (kernel) open->kept.push_back(onesBuffer); for (const auto& store : stores) { const VkDeviceSize fillBegin = std::min((store.first + 3) & ~VkDeviceSize{3}, store.last); const VkDeviceSize fillEnd = std::max(store.last & ~VkDeviceSize{3}, fillBegin); - if (fillEnd > fillBegin) fill(commands, store.buffer, fillBegin, fillEnd - fillBegin, 0xffffffffu); + bool filled = false; + if (fillEnd > fillBegin && kernel && store.snapshot != nullptr) { + filled = true; + for (VkDeviceSize done = 0; done < fillEnd - fillBegin && filled; done += OnesBufferBytes) { + const auto chunk = static_cast(std::min(OnesBufferBytes, fillEnd - fillBegin - done) / 4u); + filled = RecordChangedCopy(commands, onesBuffer->DeviceAddress(), store.snapshot->DeviceAddress() + done, store.target + (fillBegin - store.first) + done, chunk); + } + open->kept.push_back(store.snapshot); + } + if (fillEnd > fillBegin && !filled) fill(commands, store.buffer, fillBegin, fillEnd - fillBegin, 0xffffffffu); if (store.seed != nullptr) { VkBufferCopy copies[2]; std::uint32_t copyCount = 0; @@ -1559,7 +1608,7 @@ void Recorder::recordKeyStores(bool forWriter) { } bytes += store.last - store.first; } - recordBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); + recordBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); CountBarriers(CommandClass::DccKeyStore, 2); EndGpuTiming(timing, bytes); open->coveredAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index 7125401926fc..7c89a78a610b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -9369,6 +9369,60 @@ void keysFillTests(const Device& device, Recorder& recorder) { recorder.Sync(); } +void guardedKeyStoreTests(const Device& device, Recorder& recorder) { + const auto& context = device.GetContext(); + if (context.hostImportAlignment == 0 || !context.bufferDeviceAddress) { + std::cout << "host imports or buffer device addresses unavailable: guarded key stores not tested\n"; + return; + } + constexpr std::size_t surfaceBytes = 65536 * 4; + constexpr std::size_t keyCount = surfaceBytes / 256; + constexpr std::size_t bytes = surfaceBytes + 65536; +#ifdef _WIN32 + void* block = VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); +#else + void* block = std::aligned_alloc(65536, bytes); +#endif + Require(block != nullptr, "cannot allocate the key store block"); + auto* keys = static_cast(block) + surfaceBytes; + std::memset(block, 0x00, bytes); + const auto address = reinterpret_cast(block); + const auto keysAddress = address + surfaceBytes; + { + GuestAllocations::Mutation mutation; + mutation.Add(block, bytes, true, true, true); + } + struct Unregister { + const Context& context; + void* block; + std::uint64_t address; + ~Unregister() { + { + GuestAllocations::Mutation mutation; + mutation.Remove(block); + } + HostImportFor(context, address, bytes); + } + } unregister{context, block, address}; + if (HostImportFor(context, address, bytes) == nullptr) { + std::cout << "host import of the key store block refused: guarded key stores not tested\n"; + return; + } + recorder.Sync(); + MarkDccUncompressed(context, keysAddress, surfaceBytes, keyCount); + Require(recorder.PendingWriteOverlaps(keysAddress, keyCount), "the key store was not recorded on the GPU"); + auto* late = static_cast(static_cast(keys + 400)); + *late = 0x12345678u; + recorder.Submit(); + device.WaitQueue(); + recorder.Sync(); + Require(keys[0] == 0xff && keys[396] == 0xff && keys[404] == 0xff && keys[keyCount - 1] == 0xff, "the key store did not store the keys"); + const bool guarded = std::getenv("APS5_NO_GUARDED_KEY_STORE") == nullptr; + Require(*late == (guarded ? 0x12345678u : 0xffffffffu), guarded ? "a guarded key store overwrote a CPU store made after it was recorded" : "an unguarded key store kept a CPU store made after it was recorded"); + const auto stores = Recorder::StoreCounts(); + Require(!guarded || stores.keyStoresGuarded >= 1, "the key store was not counted as guarded"); +} + void integerClearTests(const Device& device) { const auto& context = device.GetContext(); std::size_t tested = 0; @@ -9961,6 +10015,10 @@ int main(int argc, char** argv) { changedCopyTests(device, recorder); return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--guarded-key-store-only") { + guardedKeyStoreTests(device, recorder); + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--unit-shadow-only") { if (!AgcDriver::Graphics::UnitShadowEnabled() || device.GetContext().hostImportAlignment == 0) { std::cout << "skipped, unit shadows or host imports are unavailable\n"; @@ -10141,6 +10199,7 @@ int main(int argc, char** argv) { movedMetadataTests(device, recorder); viewPastLastMipTests(device, recorder); keysFillTests(device, recorder); + guardedKeyStoreTests(device, recorder); integerClearTests(device); denormalClearTests(device, recorder); unitShadowTests(device, recorder); From fddbe7b7e5f96857f6a5deb0f557d3015982d503 Mon Sep 17 00:00:00 2001 From: ee6aba54 <340958984+ee6aba54@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:43:14 +0200 Subject: [PATCH 02/11] fix(agc-driver): keep a key store guarded behind the shadow publish that precedes it The publish of the key range's edge units notes a pending write over the keys, which made the key store queued right after it fall back to the plain fill. The publish leaves the key bytes as they are (its slab holds the seed the import had), so the store's snapshot stays exact: publishes note their writes with their own value and the key store treats them like its own fills. (cherry picked from commit a3c8286502a94b13d2fb7676a76c82e87f677d76) --- core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp | 3 ++- core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp | 6 +++--- core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index e936d5083275..5f8ffef289fa 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -124,7 +124,8 @@ class Recorder { void NotePendingFill(std::uint64_t address, std::size_t bytes, std::uint8_t value); void NotePendingWordFill(std::uint64_t address, std::size_t bytes, std::uint32_t word); // Notes several [begin, end) ranges and publishes the snapshot once (a dispatch writes many buffers). - void NotePendingWrites(std::span> ranges); + static constexpr int ShadowPublishWrite = -2; + void NotePendingWrites(std::span> ranges, int value = -1); bool PendingWriteOverlaps(std::uint64_t address, std::size_t bytes) const; // Whether no unfinished batch writes the range any more: no open-batch overlap, and every // overlapping in-flight batch's fence has signaled (its in-place GPU stores are final in host diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 42a907968456..5b7bf2058200 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1529,7 +1529,7 @@ void Recorder::QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize l bool eligible = target != 0 && fillBytes != 0 && GuardedKeyStores(context) && GuestMemory::Accessible(reinterpret_cast(guestFill), fillBytes); if (eligible && !PendingWriteSettled(begin, static_cast(end - begin))) { const auto pending = PendingWritesOver(begin, static_cast(end - begin)); - eligible = std::all_of(pending.begin(), pending.end(), [](const PendingWrite& write) { return write.value == 0xff; }); + eligible = std::all_of(pending.begin(), pending.end(), [](const PendingWrite& write) { return write.value == 0xff || write.value == ShadowPublishWrite; }); } if (eligible) { try { @@ -3014,10 +3014,10 @@ void Recorder::NotePendingWordFill(std::uint64_t address, std::size_t bytes, std std::atomic_thread_fence(std::memory_order_seq_cst); } -void Recorder::NotePendingWrites(std::span> ranges) { +void Recorder::NotePendingWrites(std::span> ranges, int value) { bool publish = false; for (const auto& [begin, end] : ranges) { - if (end > begin && noteWrite(begin, static_cast(end - begin))) publish = true; + if (end > begin && noteWrite(begin, static_cast(end - begin), false, value)) publish = true; } if (!publish) return; publishPendingWrites(ranges); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp index cd2998c06bd1..ab90a1cda4e6 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp @@ -263,7 +263,7 @@ void recordCopies(const UnitShadow& shadow, const std::vector& copie recorder->MarkCovered(publishedAccess); for (const auto& entry : copies) recorder->Keep(entry.slab); // CPU readers reach the import's bytes only after the hook's SyncThrough waits by this note. - recorder->NotePendingWrites(ranges); + recorder->NotePendingWrites(ranges, Recorder::ShadowPublishWrite); } // APS5_SHADOW_VERIFY=1: the published bytes read back from the slabs equal the guest bytes. From 878a18913ff2c836dab59f0a187becd9fc85e119 Mon Sep 17 00:00:00 2001 From: ee6aba54 <340958984+ee6aba54@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:49:22 +0200 Subject: [PATCH 03/11] fix(agc-driver): keep a key store guarded behind the key clears recorded before it A title's DCC key clear is a recorded fill of a known value over the keys. The key store queued behind it saw a pending writer it did not know and fell back to the plain fill, which was a third of the stores in PPSA15304 after #5520 and brought the descriptor faults back. The snapshot now predicts the import: the bytes read at queue time with every pending fill of a known value applied in note order, so the kernel stores the 0xff pattern over the clear's bytes and still keeps a CPU store made after the record. APS5_TRACE_KEY_GUARD=1 prints the pending writers of the stores that stay unguarded. The test records a key clear before the store and expects the keys stored, then a late CPU store kept. (cherry picked from commit 3da4934731c9231976f395b8f517bd2b03578968) --- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 26 +++++++++++++++++-- .../prx/libSceAgcDriver/tests/Recorder.cpp | 24 ++++++++++++++--- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 5b7bf2058200..50fc4a71239d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1527,9 +1527,26 @@ void Recorder::QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize l const auto guestFill = begin + (fillBegin - first); const auto fillBytes = static_cast(fillEnd - fillBegin); bool eligible = target != 0 && fillBytes != 0 && GuardedKeyStores(context) && GuestMemory::Accessible(reinterpret_cast(guestFill), fillBytes); + std::vector pendingFills; if (eligible && !PendingWriteSettled(begin, static_cast(end - begin))) { - const auto pending = PendingWritesOver(begin, static_cast(end - begin)); - eligible = std::all_of(pending.begin(), pending.end(), [](const PendingWrite& write) { return write.value == 0xff || write.value == ShadowPublishWrite; }); + auto pending = PendingWritesOver(begin, static_cast(end - begin)); + eligible = std::all_of(pending.begin(), pending.end(), [](const PendingWrite& write) { return write.value >= 0 || write.value == ShadowPublishWrite; }); + static const bool trace = std::getenv("APS5_TRACE_KEY_GUARD") != nullptr; + static std::atomic traced{0}; + if (!eligible && trace && traced.fetch_add(1, std::memory_order_relaxed) < 40) { + std::string text; + for (const auto& write : pending) { + char item[96]; + std::snprintf(item, sizeof(item), " 0x%llx+0x%llx:%d", static_cast(write.begin), static_cast(write.end - write.begin), write.value); + text += item; + } + std::fprintf(stderr, "[key-guard] unguarded 0x%llx+0x%zx: pending%s\n", static_cast(begin), static_cast(end - begin), text.c_str()); + } + if (eligible) { + std::erase_if(pending, [](const PendingWrite& write) { return write.value < 0; }); + std::sort(pending.begin(), pending.end(), [](const PendingWrite& a, const PendingWrite& b) { return a.note < b.note; }); + pendingFills = std::move(pending); + } } if (eligible) { try { @@ -1540,6 +1557,11 @@ void Recorder::QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize l if (snapshot != nullptr && (!snapshot->Mapped() || snapshot->DeviceAddress() == 0)) snapshot = nullptr; if (snapshot != nullptr) { std::memcpy(snapshot->Bytes().data(), reinterpret_cast(guestFill), fillBytes); + for (const auto& fill : pendingFills) { + const auto from = std::max(fill.begin, guestFill); + const auto to = std::min(fill.end, guestFill + fillBytes); + if (from < to) std::memset(snapshot->Bytes().data() + (from - guestFill), fill.value, static_cast(to - from)); + } keyStoresGuarded.fetch_add(1, std::memory_order_relaxed); } } diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index 7c89a78a610b..e72d5da4c3d7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -9409,18 +9409,36 @@ void guardedKeyStoreTests(const Device& device, Recorder& recorder) { return; } recorder.Sync(); + const auto* import = HostImportFor(context, address, bytes); + Require(import != nullptr, "the key store block lost its import"); + const bool guarded = std::getenv("APS5_NO_GUARDED_KEY_STORE") == nullptr; + { + const auto commands = recorder.Commands(); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); + context.Function("vkCmdFillBuffer")(commands, import->buffer, keysAddress - import->base, keyCount, 0x11111111u); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); + recorder.NotePendingFill(keysAddress, keyCount, 0x11); + } MarkDccUncompressed(context, keysAddress, surfaceBytes, keyCount); Require(recorder.PendingWriteOverlaps(keysAddress, keyCount), "the key store was not recorded on the GPU"); + recorder.Submit(); + device.WaitQueue(); + recorder.Sync(); + Require(keys[0] == 0xff && keys[400] == 0xff && keys[keyCount - 1] == 0xff, "a key store behind a pending key fill did not store the keys"); + const auto guardedAfterFill = Recorder::StoreCounts().keyStoresGuarded; + Require(!guarded || guardedAfterFill >= 1, "the key store behind a pending fill was not guarded"); + std::memset(keys, 0x00, keyCount); + static_cast(AgcDriver::GuestMemory::CollectWritesUncached(keysAddress, keyCount)); + MarkDccUncompressed(context, keysAddress, surfaceBytes, keyCount); + Require(recorder.PendingWriteOverlaps(keysAddress, keyCount), "the second key store was not recorded on the GPU"); auto* late = static_cast(static_cast(keys + 400)); *late = 0x12345678u; recorder.Submit(); device.WaitQueue(); recorder.Sync(); Require(keys[0] == 0xff && keys[396] == 0xff && keys[404] == 0xff && keys[keyCount - 1] == 0xff, "the key store did not store the keys"); - const bool guarded = std::getenv("APS5_NO_GUARDED_KEY_STORE") == nullptr; Require(*late == (guarded ? 0x12345678u : 0xffffffffu), guarded ? "a guarded key store overwrote a CPU store made after it was recorded" : "an unguarded key store kept a CPU store made after it was recorded"); - const auto stores = Recorder::StoreCounts(); - Require(!guarded || stores.keyStoresGuarded >= 1, "the key store was not counted as guarded"); + Require(!guarded || Recorder::StoreCounts().keyStoresGuarded > guardedAfterFill, "the second key store was not counted as guarded"); } void integerClearTests(const Device& device) { From 960c01ac9341328d015e0c67785192d91892b6ab Mon Sep 17 00:00:00 2001 From: ee6aba54 <340958984+ee6aba54@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:48:11 +0200 Subject: [PATCH 04/11] fix(agc-driver): leave the key blocks the CPU wrote after the record to the CPU The guarded key store stored the 0xff pattern wherever the import still held the snapshot's value, so a CPU store of the value the keys already held (zeroing reused memory that was zero) read as untouched and was overwritten. The queued store now collects the guest writes of its range before taking the snapshot and keeps that generation. When the store is recorded, every 64 KiB block of the range the CPU wrote since then is left as the CPU left it, and the kernel only runs over the other blocks, so a store is kept whatever value it wrote. Without write watching the value compare stays the only guard. The [labels] line counts the key blocks left to the CPU. The test places the keys across a block boundary and adds a late store of the value the keys held. --- .../src/Driver/Packets/PacketFlush.cpp | 2 +- .../Graphics/include/Recorder.hpp | 3 +- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 46 +++++++++++--- .../prx/libSceAgcDriver/tests/Recorder.cpp | 61 +++++++++++++------ 4 files changed, 86 insertions(+), 26 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp index c899ef6b9a51..77ee5adf799c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp @@ -105,7 +105,7 @@ void Driver::flushBetweenPackets(std::uint32_t queue, std::uint32_t header, bool lastReport = reportNow; const auto stores = Graphics::Recorder::StoreCounts(); const auto failed = [](TrySite site) { return static_cast(triesFailed[site].load()); }; - AgcDriver::ProfilePrint_nid_no_patch("[labels] batch flushes between packets: %llu at the next packet, %llu by deadline, %llu by size cap (%llu well overdue, waited for the mutex); %llu boundary reaps; record tries skipped (self-locking next) %llu; failed tries: label %llu, flush %llu, reap %llu, poll %llu, idle %llu, capture %llu, poll-record %llu; at the packet's own lock: %llu label groups (%.0f ms), %llu submits (%.0f ms incl. queue 0's reaps), left to it by a failed try: %llu groups, %llu submits; after a capture: %llu groups recorded by a try, %llu packets redone for a queued label over the capture; %llu suspend points; stores: %llu in %llu runs (%llu joined, %llu replaced, %llu WAW barriers, %llu joins refused; %llu runs recorded at submit, %llu in place before a writer or reader); DCC key stores: %llu queued in %llu runs (%llu before a writer, %llu joined a queued range, %llu guarded); queued labels: %llu noted (%llu over a recorded entry), %llu same-queue wait hits, %llu groups recorded from a poll loop, %llu from the flush hook (%llu hook accesses, %llu inside a completion skipped)\n", static_cast(packetFlushes.load()), static_cast(deadlineFlushes.load()), static_cast(capFlushes.load()), static_cast(overdueLocks.load()), static_cast(boundaryReaps.load()), static_cast(recordTriesSkipped.load()), failed(TryLabel), failed(TryFlush), failed(TryReap), failed(TryPoll), failed(TryIdle), failed(TryCapture), failed(TryPollRecord), static_cast(packetLockRecords.load()), packetLockRecordUs.load() / 1000.0, static_cast(packetLockSubmits.load()), packetLockSubmitUs.load() / 1000.0, static_cast(packetLockDeferred.load()), static_cast(packetSubmitDeferred.load()), static_cast(captureTryRecords.load()), static_cast(captureRetries.load()), static_cast(suspendPoints.load()), static_cast(stores.stores), static_cast(stores.runs), static_cast(stores.joined), static_cast(stores.replaced), static_cast(stores.wawBarriers), static_cast(stores.joinsRefused), static_cast(stores.runsAtSubmit), static_cast(stores.runsForced), static_cast(stores.keyStores), static_cast(stores.keyStoreRuns), static_cast(stores.keyStoreRunsForWriter), static_cast(stores.keyStoresJoined), static_cast(stores.keyStoresGuarded), static_cast(stores.queuedNoted), static_cast(stores.queuedOverRecorded), static_cast(stores.queuedHits), static_cast(pollLabelRecords.load()), static_cast(hookLabelRecords.load()), static_cast(stores.queuedHookRecords), static_cast(stores.queuedHookInCompletion)); + AgcDriver::ProfilePrint_nid_no_patch("[labels] batch flushes between packets: %llu at the next packet, %llu by deadline, %llu by size cap (%llu well overdue, waited for the mutex); %llu boundary reaps; record tries skipped (self-locking next) %llu; failed tries: label %llu, flush %llu, reap %llu, poll %llu, idle %llu, capture %llu, poll-record %llu; at the packet's own lock: %llu label groups (%.0f ms), %llu submits (%.0f ms incl. queue 0's reaps), left to it by a failed try: %llu groups, %llu submits; after a capture: %llu groups recorded by a try, %llu packets redone for a queued label over the capture; %llu suspend points; stores: %llu in %llu runs (%llu joined, %llu replaced, %llu WAW barriers, %llu joins refused; %llu runs recorded at submit, %llu in place before a writer or reader); DCC key stores: %llu queued in %llu runs (%llu before a writer, %llu joined a queued range, %llu guarded, %llu key blocks left to a later CPU store); queued labels: %llu noted (%llu over a recorded entry), %llu same-queue wait hits, %llu groups recorded from a poll loop, %llu from the flush hook (%llu hook accesses, %llu inside a completion skipped)\n", static_cast(packetFlushes.load()), static_cast(deadlineFlushes.load()), static_cast(capFlushes.load()), static_cast(overdueLocks.load()), static_cast(boundaryReaps.load()), static_cast(recordTriesSkipped.load()), failed(TryLabel), failed(TryFlush), failed(TryReap), failed(TryPoll), failed(TryIdle), failed(TryCapture), failed(TryPollRecord), static_cast(packetLockRecords.load()), packetLockRecordUs.load() / 1000.0, static_cast(packetLockSubmits.load()), packetLockSubmitUs.load() / 1000.0, static_cast(packetLockDeferred.load()), static_cast(packetSubmitDeferred.load()), static_cast(captureTryRecords.load()), static_cast(captureRetries.load()), static_cast(suspendPoints.load()), static_cast(stores.stores), static_cast(stores.runs), static_cast(stores.joined), static_cast(stores.replaced), static_cast(stores.wawBarriers), static_cast(stores.joinsRefused), static_cast(stores.runsAtSubmit), static_cast(stores.runsForced), static_cast(stores.keyStores), static_cast(stores.keyStoreRuns), static_cast(stores.keyStoreRunsForWriter), static_cast(stores.keyStoresJoined), static_cast(stores.keyStoresGuarded), static_cast(stores.keyBlocksLeftToCpu), static_cast(stores.queuedNoted), static_cast(stores.queuedOverRecorded), static_cast(stores.queuedHits), static_cast(pollLabelRecords.load()), static_cast(hookLabelRecords.load()), static_cast(stores.queuedHookRecords), static_cast(stores.queuedHookInCompletion)); } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index 5f8ffef289fa..0ef4373a460e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -454,7 +454,7 @@ class Recorder { std::uint64_t stores, runs, joined, replaced, wawBarriers, joinsRefused, queuedNoted, queuedOverRecorded, queuedHits, queuedHookRecords, queuedHookInCompletion; // DCC key stores queued, the runs that recorded them (at Submit, or before a writer of a // queued range), and the queued stores a duplicate range joined. - std::uint64_t keyStores, keyStoreRuns, keyStoreRunsForWriter, keyStoresJoined, keyStoresGuarded; + std::uint64_t keyStores, keyStoreRuns, keyStoreRunsForWriter, keyStoresJoined, keyStoresGuarded, keyBlocksLeftToCpu; // Store runs recorded at Submit, and in place before a later writer or reader of a queued // store's bytes (FlushStores). std::uint64_t runsAtSubmit, runsForced; @@ -672,6 +672,7 @@ class Recorder { std::uint64_t end; std::shared_ptr snapshot; VkDeviceAddress target = 0; + std::uint64_t cpuGeneration = 0; }; std::vector keyStores; }; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 50fc4a71239d..be8dbce2a817 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -568,7 +568,7 @@ bool LateTrustEnabled() { } // Store-run and queued-label counters (Recorder::StoreCounts), relaxed: they are only reported. std::atomic storeCount{0}, storeRuns{0}, storesJoined{0}, storesReplaced{0}, storeWawBarriers{0}, storeJoinsRefused{0}; -std::atomic keyStoreCount{0}, keyStoreRuns{0}, keyStoreRunsForWriter{0}, keyStoresJoined{0}, keyStoresGuarded{0}; +std::atomic keyStoreCount{0}, keyStoreRuns{0}, keyStoreRunsForWriter{0}, keyStoresJoined{0}, keyStoresGuarded{0}, keyBlocksLeftToCpu{0}; bool GuardedKeyStores(const Context& context) { static const bool disabled = std::getenv("APS5_NO_GUARDED_KEY_STORE") != nullptr; @@ -576,6 +576,18 @@ bool GuardedKeyStores(const Context& context) { } constexpr std::size_t OnesBufferBytes = std::size_t{1} << 20; +constexpr std::uint64_t KeyGuardBlockBytes = 65536; + +std::vector CpuWrittenBlocks(std::uint64_t address, std::size_t bytes, std::uint64_t generation) { + if (generation == 0 || bytes == 0) return {}; + static_cast(GuestMemory::CollectWritesUncached(address, bytes)); + const auto count = static_cast((address + bytes - 1) / KeyGuardBlockBytes - address / KeyGuardBlockBytes + 1); + std::vector generations(count, generation); + std::vector changed(count); + std::vector cpu(count); + if (!GuestMemory::ChangedBlocks(address, bytes, generations, changed, cpu)) return {}; + return cpu; +} // Debug aid: APS5_DCC_KEYS_EACH=1 records every DCC key store at once (see Recorder::QueueKeyStore). bool KeyStoresEach() { @@ -1399,7 +1411,7 @@ void Recorder::SetQueuedLabelRecorder(void (*recorder)()) { } Recorder::StoreStatistics Recorder::StoreCounts() { - return StoreStatistics{storeCount.load(std::memory_order_relaxed), storeRuns.load(std::memory_order_relaxed), storesJoined.load(std::memory_order_relaxed), storesReplaced.load(std::memory_order_relaxed), storeWawBarriers.load(std::memory_order_relaxed), storeJoinsRefused.load(std::memory_order_relaxed), queuedLabelsNoted.load(std::memory_order_relaxed), queuedLabelsOverRecorded.load(std::memory_order_relaxed), queuedLabelHits.load(std::memory_order_relaxed), queuedLabelHookRecords.load(std::memory_order_relaxed), queuedLabelHookInCompletion.load(std::memory_order_relaxed), keyStoreCount.load(std::memory_order_relaxed), keyStoreRuns.load(std::memory_order_relaxed), keyStoreRunsForWriter.load(std::memory_order_relaxed), keyStoresJoined.load(std::memory_order_relaxed), keyStoresGuarded.load(std::memory_order_relaxed), storeRunsAtSubmit.load(std::memory_order_relaxed), storeRunsForced.load(std::memory_order_relaxed)}; + return StoreStatistics{storeCount.load(std::memory_order_relaxed), storeRuns.load(std::memory_order_relaxed), storesJoined.load(std::memory_order_relaxed), storesReplaced.load(std::memory_order_relaxed), storeWawBarriers.load(std::memory_order_relaxed), storeJoinsRefused.load(std::memory_order_relaxed), queuedLabelsNoted.load(std::memory_order_relaxed), queuedLabelsOverRecorded.load(std::memory_order_relaxed), queuedLabelHits.load(std::memory_order_relaxed), queuedLabelHookRecords.load(std::memory_order_relaxed), queuedLabelHookInCompletion.load(std::memory_order_relaxed), keyStoreCount.load(std::memory_order_relaxed), keyStoreRuns.load(std::memory_order_relaxed), keyStoreRunsForWriter.load(std::memory_order_relaxed), keyStoresJoined.load(std::memory_order_relaxed), keyStoresGuarded.load(std::memory_order_relaxed), keyBlocksLeftToCpu.load(std::memory_order_relaxed), storeRunsAtSubmit.load(std::memory_order_relaxed), storeRunsForced.load(std::memory_order_relaxed)}; } std::uint64_t Recorder::ThreadHookWaits() { @@ -1522,6 +1534,7 @@ void Recorder::QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize l } } std::shared_ptr snapshot; + std::uint64_t cpuGeneration = 0; const VkDeviceSize fillBegin = std::min((first + 3) & ~VkDeviceSize{3}, last); const VkDeviceSize fillEnd = std::max(last & ~VkDeviceSize{3}, fillBegin); const auto guestFill = begin + (fillBegin - first); @@ -1556,6 +1569,7 @@ void Recorder::QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize l } if (snapshot != nullptr && (!snapshot->Mapped() || snapshot->DeviceAddress() == 0)) snapshot = nullptr; if (snapshot != nullptr) { + cpuGeneration = GuestMemory::CollectWritesUncached(guestFill, fillBytes); std::memcpy(snapshot->Bytes().data(), reinterpret_cast(guestFill), fillBytes); for (const auto& fill : pendingFills) { const auto from = std::max(fill.begin, guestFill); @@ -1565,7 +1579,7 @@ void Recorder::QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize l keyStoresGuarded.fetch_add(1, std::memory_order_relaxed); } } - open->keyStores.push_back({buffer, first, last, std::move(seed), begin, end, std::move(snapshot), target}); + open->keyStores.push_back({buffer, first, last, std::move(seed), begin, end, std::move(snapshot), target, cpuGeneration}); if (KeyStoresEach()) recordKeyStores(false); } @@ -1611,16 +1625,34 @@ void Recorder::recordKeyStores(bool forWriter) { for (const auto& store : stores) { const VkDeviceSize fillBegin = std::min((store.first + 3) & ~VkDeviceSize{3}, store.last); const VkDeviceSize fillEnd = std::max(store.last & ~VkDeviceSize{3}, fillBegin); + const auto guestFill = store.begin + (fillBegin - store.first); + const auto cpuWritten = store.snapshot != nullptr ? CpuWrittenBlocks(guestFill, static_cast(fillEnd - fillBegin), store.cpuGeneration) : std::vector{}; + const auto leftToCpu = [&](VkDeviceSize offset) { + const auto block = static_cast((guestFill + offset) / KeyGuardBlockBytes - guestFill / KeyGuardBlockBytes); + return block < cpuWritten.size() && cpuWritten[block] != 0; + }; + std::vector> runs; + for (VkDeviceSize done = 0; done < fillEnd - fillBegin;) { + const auto next = std::min(fillEnd - fillBegin, cpuWritten.empty() ? fillEnd - fillBegin : (guestFill + done) / KeyGuardBlockBytes * KeyGuardBlockBytes + KeyGuardBlockBytes - guestFill); + if (leftToCpu(done)) keyBlocksLeftToCpu.fetch_add(1, std::memory_order_relaxed); + else if (!runs.empty() && runs.back().second == done) runs.back().second = next; + else runs.emplace_back(done, next); + done = next; + } bool filled = false; if (fillEnd > fillBegin && kernel && store.snapshot != nullptr) { filled = true; - for (VkDeviceSize done = 0; done < fillEnd - fillBegin && filled; done += OnesBufferBytes) { - const auto chunk = static_cast(std::min(OnesBufferBytes, fillEnd - fillBegin - done) / 4u); - filled = RecordChangedCopy(commands, onesBuffer->DeviceAddress(), store.snapshot->DeviceAddress() + done, store.target + (fillBegin - store.first) + done, chunk); + for (const auto& [from, to] : runs) { + for (VkDeviceSize done = from; done < to && filled; done += OnesBufferBytes) { + const auto chunk = static_cast(std::min(OnesBufferBytes, to - done) / 4u); + filled = RecordChangedCopy(commands, onesBuffer->DeviceAddress(), store.snapshot->DeviceAddress() + done, store.target + (fillBegin - store.first) + done, chunk); + } } open->kept.push_back(store.snapshot); } - if (fillEnd > fillBegin && !filled) fill(commands, store.buffer, fillBegin, fillEnd - fillBegin, 0xffffffffu); + if (!filled) { + for (const auto& [from, to] : runs) fill(commands, store.buffer, fillBegin + from, to - from, 0xffffffffu); + } if (store.seed != nullptr) { VkBufferCopy copies[2]; std::uint32_t copyCount = 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index e72d5da4c3d7..cdc90788e6f1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -9377,33 +9377,45 @@ void guardedKeyStoreTests(const Device& device, Recorder& recorder) { } constexpr std::size_t surfaceBytes = 65536 * 4; constexpr std::size_t keyCount = surfaceBytes / 256; - constexpr std::size_t bytes = surfaceBytes + 65536; + constexpr std::size_t bytes = surfaceBytes + 2 * 65536; + constexpr std::size_t keysOffset = surfaceBytes + 65536 - keyCount / 2; + const bool watched = AgcDriver::GuestMemory::WriteWatched(); + void* block = nullptr; + if (watched) { + block = AllocateWatched(bytes, 65536); + } else { #ifdef _WIN32 - void* block = VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + block = VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); #else - void* block = std::aligned_alloc(65536, bytes); + block = std::aligned_alloc(65536, bytes); #endif + } Require(block != nullptr, "cannot allocate the key store block"); - auto* keys = static_cast(block) + surfaceBytes; + auto* keys = static_cast(block) + keysOffset; std::memset(block, 0x00, bytes); const auto address = reinterpret_cast(block); - const auto keysAddress = address + surfaceBytes; + const auto keysAddress = address + keysOffset; { GuestAllocations::Mutation mutation; mutation.Add(block, bytes, true, true, true); } struct Unregister { const Context& context; + Recorder& recorder; void* block; std::uint64_t address; + bool watched; ~Unregister() { { GuestAllocations::Mutation mutation; mutation.Remove(block); } HostImportFor(context, address, bytes); + if (!watched) return; + recorder.Sync(); + ReleaseWatched(block, bytes); } - } unregister{context, block, address}; + } unregister{context, recorder, block, address, watched}; if (HostImportFor(context, address, bytes) == nullptr) { std::cout << "host import of the key store block refused: guarded key stores not tested\n"; return; @@ -9427,18 +9439,33 @@ void guardedKeyStoreTests(const Device& device, Recorder& recorder) { Require(keys[0] == 0xff && keys[400] == 0xff && keys[keyCount - 1] == 0xff, "a key store behind a pending key fill did not store the keys"); const auto guardedAfterFill = Recorder::StoreCounts().keyStoresGuarded; Require(!guarded || guardedAfterFill >= 1, "the key store behind a pending fill was not guarded"); - std::memset(keys, 0x00, keyCount); - static_cast(AgcDriver::GuestMemory::CollectWritesUncached(keysAddress, keyCount)); - MarkDccUncompressed(context, keysAddress, surfaceBytes, keyCount); - Require(recorder.PendingWriteOverlaps(keysAddress, keyCount), "the second key store was not recorded on the GPU"); - auto* late = static_cast(static_cast(keys + 400)); - *late = 0x12345678u; - recorder.Submit(); - device.WaitQueue(); - recorder.Sync(); - Require(keys[0] == 0xff && keys[396] == 0xff && keys[404] == 0xff && keys[keyCount - 1] == 0xff, "the key store did not store the keys"); - Require(*late == (guarded ? 0x12345678u : 0xffffffffu), guarded ? "a guarded key store overwrote a CPU store made after it was recorded" : "an unguarded key store kept a CPU store made after it was recorded"); + const auto lateStore = [&](std::uint32_t value) { + std::memset(keys, 0x00, keyCount); + static_cast(AgcDriver::GuestMemory::CollectWritesUncached(keysAddress, keyCount)); + MarkDccUncompressed(context, keysAddress, surfaceBytes, keyCount); + Require(recorder.PendingWriteOverlaps(keysAddress, keyCount), "a later key store was not recorded on the GPU"); + auto* late = static_cast(static_cast(keys + 400)); + *late = value; + recorder.Submit(); + device.WaitQueue(); + recorder.Sync(); + return static_cast(*late); + }; + const auto leftBefore = Recorder::StoreCounts().keyBlocksLeftToCpu; + const auto late = lateStore(0x12345678u); + const std::uint8_t lateBlock = guarded && watched ? 0x00 : 0xff; + Require(keys[0] == lateBlock && keys[396] == lateBlock && keys[404] == lateBlock, guarded && watched ? "a guarded key store wrote into a block the CPU wrote after it was recorded" : "the key store did not store the keys"); + Require(keys[keyCount / 2] == 0xff && keys[keyCount - 1] == 0xff, "the key store did not store the keys of a block the CPU left alone"); + Require(late == (guarded ? 0x12345678u : 0xffffffffu), guarded ? "a guarded key store overwrote a CPU store made after it was recorded" : "an unguarded key store kept a CPU store made after it was recorded"); Require(!guarded || Recorder::StoreCounts().keyStoresGuarded > guardedAfterFill, "the second key store was not counted as guarded"); + Require(!guarded || !watched || Recorder::StoreCounts().keyBlocksLeftToCpu > leftBefore, "the block the CPU wrote was not counted as left to it"); + if (!guarded) return; + if (!watched) { + std::cout << "write watching unavailable: a late CPU store of the value the keys held not tested\n"; + return; + } + Require(lateStore(0u) == 0u, "a guarded key store overwrote a late CPU store of the value the keys held"); + Require(keys[keyCount / 2] == 0xff && keys[keyCount - 1] == 0xff, "the key store did not store the keys of a block the CPU left alone after a same-value store"); } void integerClearTests(const Device& device) { From ef11faff02e74cb21288432e42ae4cd67e62e25a Mon Sep 17 00:00:00 2001 From: ee6aba54 <340958984+ee6aba54@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:08:19 +0200 Subject: [PATCH 05/11] fix(agc-driver): put the libs directory on PATH for agc_guarded_key_store on Windows --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 2c1b3551a857..693780205024 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -1522,7 +1522,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_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 agc_changed_copy 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_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 agc_changed_copy agc_guarded_key_store 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 From e91007b9abae3a31b51d90ac55960be2e1726728 Mon Sep 17 00:00:00 2001 From: ee6aba54 <340958984+ee6aba54@users.noreply.github.com> Date: Sat, 17 Oct 2026 11:54:35 +0200 Subject: [PATCH 06/11] test(agc): count a skipped agc_guarded_key_store as skipped --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 693780205024..1f2aab9caa76 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -1488,6 +1488,7 @@ if(BUILD_TESTING) set_tests_properties(agc_changed_copy PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) add_test(NAME agc_unit_shadow COMMAND agc_driver_recorder_tests --unit-shadow-only) add_test(NAME agc_guarded_key_store COMMAND agc_driver_recorder_tests --guarded-key-store-only) + set_tests_properties(agc_guarded_key_store PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) set_tests_properties(agc_unit_shadow PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30 ENVIRONMENT "APS5_PIN_WAIT_MS=3000") if(WIN32) add_test(NAME agc_storage_cpu_snapshot COMMAND agc_driver_recorder_tests --storage-cpu-snapshot-only) From 408305a586c43361ebcffd7ceb3a2b6bd98ff405 Mon Sep 17 00:00:00 2001 From: ee6aba54 <340958984+ee6aba54@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:42:40 +0200 Subject: [PATCH 07/11] docs(agc-driver): list the key store guard switches in the environment reference --- docs/dev/ENVIRONMENT.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 711614629384..bf0e43e645de 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -234,6 +234,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_GPU_INDIRECT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/IndirectDispatch.cpp` | | reads indirect dispatch arguments on the CPU instead of letting the GPU count them | | `APS5_NO_GPU_INDIRECT_DRAW` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | reads indirect draw arguments through the flush hook on the CPU instead of from the GPU | | `APS5_NO_GPU_SAMPLE_DUMPS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | dumps occlusion-counter samples on the CPU instead of through the GPU copy path | +| `APS5_NO_GUARDED_KEY_STORE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | records a deferred DCC key store as a plain fill, without the guard that keeps the key blocks the CPU wrote after it was recorded | | `APS5_NO_HOLD_PROFILE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp` | | turns off GpuMutex hold-time profiling, keeping only the wait timing | | `APS5_NO_HOOKSYNC_PROFILE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | leaves only the plain hook-sync counts under APS5_PROFILE_DRAW | | `APS5_NO_HOOK_COMPLETION_GUARD` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | lets the flush hook record the accessing worker's queued labels even from inside a completion action | @@ -406,6 +407,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_TRACE_GPU` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/DisplayBuffer.cpp` | | prints GPU wait, submission and scanout events, the execute lines, and waits longer than 200 ms (read in DisplayBuffer, PacketExecution, QueueWorker, Submission and WaitMemory) | | `APS5_TRACE_HOST_IMPORT` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | traces host-import mapping failures | | `APS5_TRACE_INDIRECT_DRAWS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPrecheck.cpp` | | prints indirect draw packets that reach the precheck | +| `APS5_TRACE_KEY_GUARD` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | logs the first 40 key stores left unguarded, with the pending writes over their range | | `APS5_TRACE_LATE_LABELS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitMemory.cpp` | | prints how late labels were trusted or refused | | `APS5_TRACE_PREPARATION_WAIT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp` | | prints where a demanded shader preparation sat in the queue | | `APS5_TRACE_QUERY` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp` | | prints every 16th page query with its cost | From e9f8be66bc85c3282b5ce588ecd6d0222d08da84 Mon Sep 17 00:00:00 2001 From: ee6aba54 <340958984+ee6aba54@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:56:35 +0200 Subject: [PATCH 08/11] fix(agc-driver): address a guarded key store's target from the start of its import's buffer, lead included --- .../libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp | 4 ++++ core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp | 2 +- core/libs/prx/libSceAgcDriver/tests/Recorder.cpp | 7 ++++++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index d8beec5ec499..4a300358d7db 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -63,6 +63,10 @@ inline HostImportStart HostImportBufferStart(const HostImport& import) { return {import.base - import.lead, import.address - import.lead}; } +inline VkDeviceAddress HostImportDeviceAddress(const HostImport& import, std::uint64_t address) { + return HostImportBufferStart(import).device + HostImportOffset(import, address); +} + enum class ImportWatch : std::uint8_t { Watch, Unwatch }; struct ImportProbe { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp index 78501a42ba4a..925d72f329dc 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp @@ -252,7 +252,7 @@ bool StoreUncompressedOnGpu(const Context& context, Recorder& recorder, std::uin if (AnyShadowedOverlaps(begin, count)) PublishShadow(begin, count, PublishScope::PartialUnits, PublishReason::Keys); // Queued on the open batch and recorded with the batch's other key stores as one run (or before // a later command writing the keys; see Recorder::QueueKeyStore). - recorder.QueueKeyStore(import->buffer, first, last, std::move(seed), begin, begin + count, import->address != 0 ? import->address + first : 0); + recorder.QueueKeyStore(import->buffer, first, last, std::move(seed), begin, begin + count, import->address != 0 ? HostImportDeviceAddress(*import, begin) : 0); recorder.NotePendingFill(begin, count, 0xff); GuestMemory::MarkWritten(begin, count); // After the note: an unlocked memo lookup drops an entry the snapshot does not cover yet. The diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index af60a06cf97a..49b05344791b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -9607,11 +9607,16 @@ void guardedKeyStoreTests(const Device& device, Recorder& recorder) { recorder.Sync(); const auto* import = HostImportFor(context, address, bytes); Require(import != nullptr, "the key store block lost its import"); + HostImport leadImport{}; + leadImport.base = keysAddress - 0x40; + leadImport.address = 0x500001000ull; + leadImport.lead = 0x1000; + Require(HostImportDeviceAddress(leadImport, keysAddress) == leadImport.address + 0x40 && HostImportDeviceAddress(*import, keysAddress) == import->address + (keysAddress - import->base), "the device address of a key range in an import with a lead does not point at the keys"); const bool guarded = std::getenv("APS5_NO_GUARDED_KEY_STORE") == nullptr; { const auto commands = recorder.Commands(); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); - context.Function("vkCmdFillBuffer")(commands, import->buffer, keysAddress - import->base, keyCount, 0x11111111u); + context.Function("vkCmdFillBuffer")(commands, import->buffer, HostImportOffset(*import, keysAddress), keyCount, 0x11111111u); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); recorder.NotePendingFill(keysAddress, keyCount, 0x11); } From d8c14598212c7e289556eab298de6d22688b2ae0 Mon Sep 17 00:00:00 2001 From: ee6aba54 <340958984+ee6aba54@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:56:35 +0200 Subject: [PATCH 09/11] docs(agc-driver): record that a guarded key store leaves whole CPU-written blocks to the CPU --- docs/dev/debt/libSceAgcDriver.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 8b92e54ef79f..9d4f4fb0ad49 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -229,3 +229,4 @@ - [Color export type against the target format](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver) - the export-format check refuses a `UINT16_ABGR` export (`SPI_SHADER_COL_FORMAT` 7) into a target whose color-buffer number format is not unsigned integer, but not the reverse. A 32-bit export (`32_R`, `32_GR`, `32_AR` or `32_ABGR`) into an unsigned-integer target leaves `uintExport` clear, so the recompiler declares the fragment output `float4`; `DecodeColorBuffer` maps a number format of 4 to `R32_UINT` from the color buffer alone, independent of the export format, so the float output reaches an integer attachment. Desktop drivers keep the raw bits, but the Khronos validation layer reports `Undefined-Value-ShaderFragmentOutputMismatch` and MoltenVK's Metal compiler refuses the pipeline. Which export format a title pairs with a 32-bit integer target is not measured, so the output type is left following the export format rather than the attachment. - [Long Windows pipeline-cache paths](../../../core/libs/prx/libSceAgcDriver/Graphics/src/PipelineCache.cpp): `readHeader` and the failed-read existence check still use ordinary paths. A filename beyond MAX_PATH can prevent header reuse or be reported missing; the shared content reader and journal normalization do not cover these calls. +- [Guarded DCC key stores](../../../core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp) (libSceAgcDriver) - a deferred key store keeps the guest stores made after it was recorded at the granularity of write watching: a 64 KiB block of the key range the CPU wrote since the record is left exactly as the CPU left it, so key dwords in that block the CPU did not write keep their old value instead of 0xff. In the other blocks the store writes 0xff wherever the import still holds the value it had at the record. Without write watching that value compare is the only guard, and a CPU store of the value the keys already held is overwritten. Which CPU stores the key store overtakes on the console, where it runs when the GPU reaches it, has not been measured. From 49a2c11aed14ea318f8f10b5ae3088d7424106f9 Mon Sep 17 00:00:00 2001 From: ee6aba54 <340958984+ee6aba54@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:19:09 +0100 Subject: [PATCH 10/11] test(agc-driver): expect CPU-written key blocks to be kept only when the import is write-watched On hosts that compare host imports instead of watching them, the guarded key store cannot see which blocks the CPU wrote, so the value compare is the only guard there. Key the block expectation on the import's watch mode and note that case in the debt entry. --- core/libs/prx/libSceAgcDriver/tests/Recorder.cpp | 11 ++++++----- docs/dev/debt/libSceAgcDriver.md | 2 +- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index 5aa2578a0d2b..3eef4e8b7456 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -10450,6 +10450,7 @@ void guardedKeyStoreTests(const Device& device, Recorder& recorder) { leadImport.lead = 0x1000; Require(HostImportDeviceAddress(leadImport, keysAddress) == leadImport.address + 0x40 && HostImportDeviceAddress(*import, keysAddress) == import->address + (keysAddress - import->base), "the device address of a key range in an import with a lead does not point at the keys"); const bool guarded = std::getenv("APS5_NO_GUARDED_KEY_STORE") == nullptr; + const bool blocksWatched = watched && PrepareImportWatch(context) == ImportWatch::Watch; { const auto commands = recorder.Commands(); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); @@ -10479,15 +10480,15 @@ void guardedKeyStoreTests(const Device& device, Recorder& recorder) { }; const auto leftBefore = Recorder::StoreCounts().keyBlocksLeftToCpu; const auto late = lateStore(0x12345678u); - const std::uint8_t lateBlock = guarded && watched ? 0x00 : 0xff; - Require(keys[0] == lateBlock && keys[396] == lateBlock && keys[404] == lateBlock, guarded && watched ? "a guarded key store wrote into a block the CPU wrote after it was recorded" : "the key store did not store the keys"); + const std::uint8_t lateBlock = guarded && blocksWatched ? 0x00 : 0xff; + Require(keys[0] == lateBlock && keys[396] == lateBlock && keys[404] == lateBlock, guarded && blocksWatched ? "a guarded key store wrote into a block the CPU wrote after it was recorded" : "the key store did not store the keys"); Require(keys[keyCount / 2] == 0xff && keys[keyCount - 1] == 0xff, "the key store did not store the keys of a block the CPU left alone"); Require(late == (guarded ? 0x12345678u : 0xffffffffu), guarded ? "a guarded key store overwrote a CPU store made after it was recorded" : "an unguarded key store kept a CPU store made after it was recorded"); Require(!guarded || Recorder::StoreCounts().keyStoresGuarded > guardedAfterFill, "the second key store was not counted as guarded"); - Require(!guarded || !watched || Recorder::StoreCounts().keyBlocksLeftToCpu > leftBefore, "the block the CPU wrote was not counted as left to it"); + Require(!guarded || !blocksWatched || Recorder::StoreCounts().keyBlocksLeftToCpu > leftBefore, "the block the CPU wrote was not counted as left to it"); if (!guarded) return; - if (!watched) { - std::cout << "write watching unavailable: a late CPU store of the value the keys held not tested\n"; + if (!blocksWatched) { + std::cout << "host import not write-watched: a late CPU store of the value the keys held not tested\n"; return; } Require(lateStore(0u) == 0u, "a guarded key store overwrote a late CPU store of the value the keys held"); diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 020fc747a02a..39c984bfc324 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -259,7 +259,7 @@ - [Depth mip levels](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver) - a depth view of mip `DB_DEPTH_VIEW.MIPID` in a chain of `DB_Z_INFO.MAXMIP` levels renders into that level as a surface of its own, at the level's offset and extent from `ComputeElementMipLayout` for the 64 KiB Z_X swizzle, the layout color target mips and sampled depth already use; slices of a chain step by the size of the whole chain. Taken from LEGO Builder's Journey (PPSA05496), which renders depth mip 1 of 64 KiB Z_X surfaces without HTILE; the placement was not compared with a console capture. Multisampled depth mips, other swizzle modes, levels in the packed mip tail and HTILE on a mip chain throw - [Long Windows pipeline-cache paths](../../../core/libs/prx/libSceAgcDriver/Graphics/src/PipelineCache.cpp): `readHeader` and the failed-read existence check still use ordinary paths. A filename beyond MAX_PATH can prevent header reuse or be reported missing; the shared content reader and journal normalization do not cover these calls. -- [Guarded DCC key stores](../../../core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp) (libSceAgcDriver) - a deferred key store keeps the guest stores made after it was recorded at the granularity of write watching: a 64 KiB block of the key range the CPU wrote since the record is left exactly as the CPU left it, so key dwords in that block the CPU did not write keep their old value instead of 0xff. In the other blocks the store writes 0xff wherever the import still holds the value it had at the record. Without write watching that value compare is the only guard, and a CPU store of the value the keys already held is overwritten. Which CPU stores the key store overtakes on the console, where it runs when the GPU reaches it, has not been measured. +- [Guarded DCC key stores](../../../core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp) (libSceAgcDriver) - a deferred key store keeps the guest stores made after it was recorded at the granularity of write watching: a 64 KiB block of the key range the CPU wrote since the record is left exactly as the CPU left it, so key dwords in that block the CPU did not write keep their old value instead of 0xff. In the other blocks the store writes 0xff wherever the import still holds the value it had at the record. Without write watching, and on hosts that compare host imports instead of watching them, that value compare is the only guard, and a CPU store of the value the keys already held is overwritten. Which CPU stores the key store overtakes on the console, where it runs when the GPU reaches it, has not been measured. - [DB_RENDER_CONTROL.STENCIL_CLEAR_ENABLE without a stencil plane](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver): a stencil clear on a depth target whose `DB_STENCIL_INFO` format is `STENCIL_INVALID` is dropped; the depth clear and color writes proceed. AMD PAL ([`gfx9RsrcProcMgr.cpp`](https://github.com/GPUOpen-Drivers/pal/blob/c5e800072a32/src/core/hw/gfxip/rpm/gfx9/gfx9RsrcProcMgr.cpp)) and radeonsi (`si_clear.c`) never set the bit without a stencil plane, and shadPS4 drops it the same way (`vk_rasterizer.cpp`, `StencilValid`). No source states what the hardware does with the bit then; the console was not measured. A read-only stencil plane still throws ### Opt-in draw paths From 13d09412b4ac5eb5459819d8e801aa356b227fa6 Mon Sep 17 00:00:00 2001 From: ee6aba54 <340958984+ee6aba54@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:58:20 +0100 Subject: [PATCH 11/11] test(agc-driver): count a guarded key store run without a case as skipped guardedKeyStoreTests returned without a check when host imports or buffer device addresses were unavailable or the host import of its block was refused, and --guarded-key-store-only returned 0 all the same, so ctest reported agc_guarded_key_store as passed with nothing tested. The function now returns whether a case ran, the standalone entry returns 77 when none did (ctest's SKIP_RETURN_CODE for this test), and the full suite goes on as before. A run whose import is not write-watched still counts as run: its first cases complete, only the same-value late store is left out. --- core/libs/prx/libSceAgcDriver/tests/Recorder.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index 21690c8642f9..f005ac1300a0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -10906,11 +10906,11 @@ void keysFillTests(const Device& device, Recorder& recorder) { recorder.Sync(); } -void guardedKeyStoreTests(const Device& device, Recorder& recorder) { +bool guardedKeyStoreTests(const Device& device, Recorder& recorder) { const auto& context = device.GetContext(); if (context.hostImportAlignment == 0 || !context.bufferDeviceAddress) { std::cout << "host imports or buffer device addresses unavailable: guarded key stores not tested\n"; - return; + return false; } constexpr std::size_t surfaceBytes = 65536 * 4; constexpr std::size_t keyCount = surfaceBytes / 256; @@ -10955,7 +10955,7 @@ void guardedKeyStoreTests(const Device& device, Recorder& recorder) { } unregister{context, recorder, block, address, watched}; if (HostImportFor(context, address, bytes) == nullptr) { std::cout << "host import of the key store block refused: guarded key stores not tested\n"; - return; + return false; } recorder.Sync(); const auto* import = HostImportFor(context, address, bytes); @@ -11002,13 +11002,15 @@ void guardedKeyStoreTests(const Device& device, Recorder& recorder) { Require(late == (guarded ? 0x12345678u : 0xffffffffu), guarded ? "a guarded key store overwrote a CPU store made after it was recorded" : "an unguarded key store kept a CPU store made after it was recorded"); Require(!guarded || Recorder::StoreCounts().keyStoresGuarded > guardedAfterFill, "the second key store was not counted as guarded"); Require(!guarded || !blocksWatched || Recorder::StoreCounts().keyBlocksLeftToCpu > leftBefore, "the block the CPU wrote was not counted as left to it"); - if (!guarded) return; + if (!guarded) return true; if (!blocksWatched) { std::cout << "host import not write-watched: a late CPU store of the value the keys held not tested\n"; - return; + return true; } Require(lateStore(0u) == 0u, "a guarded key store overwrote a late CPU store of the value the keys held"); Require(keys[keyCount / 2] == 0xff && keys[keyCount - 1] == 0xff, "the key store did not store the keys of a block the CPU left alone after a same-value store"); + std::cout << "guarded key store tests passed\n"; + return true; } void integerClearTests(const Device& device) { @@ -11876,7 +11878,7 @@ int main(int argc, char** argv) { return 0; } if (argc == 2 && std::string_view(argv[1]) == "--guarded-key-store-only") { - guardedKeyStoreTests(device, recorder); + if (!guardedKeyStoreTests(device, recorder)) return 77; return 0; } if (argc == 2 && std::string_view(argv[1]) == "--idle-publish-wait-only") {