diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 698965452653..b5bdf102ffec 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -134,6 +134,19 @@ add_custom_command( VERBATIM ) +set(agcStagingCopyBackShaderSource ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/shaders/StagingCopyBack.comp) +set(agcStagingCopyBackShaderSpv ${agcTextureDetileGeneratedDir}/StagingCopyBack.spv) +set(agcStagingCopyBackShaderHeader ${agcTextureDetileGeneratedDir}/StagingCopyBack_spv.h) +add_custom_command( + OUTPUT "${agcStagingCopyBackShaderHeader}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${agcTextureDetileGeneratedDir}" + COMMAND "$" -V --target-env vulkan1.1 -o "${agcStagingCopyBackShaderSpv}" "${agcStagingCopyBackShaderSource}" + COMMAND ${CMAKE_COMMAND} -DINPUT=${agcStagingCopyBackShaderSpv} -DOUTPUT=${agcStagingCopyBackShaderHeader} + -DSYMBOL=STAGING_COPY_BACK_SPV -P "${CMAKE_CURRENT_SOURCE_DIR}/embed_spirv.cmake" + DEPENDS "${agcStagingCopyBackShaderSource}" glslang-standalone + VERBATIM +) + set(agcCmaskClearShaderSource ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/shaders/CmaskClear.comp) set(agcCmaskClearShaderSpv ${agcTextureDetileGeneratedDir}/CmaskClear.spv) set(agcCmaskClearShaderHeader ${agcTextureDetileGeneratedDir}/CmaskClear_spv.h) @@ -403,6 +416,7 @@ set(agcDriverSources ${agcMultisampleUploadHeader} ${agcCmaskClearShaderHeader} ${agcMeshArgumentsShaderHeader} + ${agcStagingCopyBackShaderHeader} ${agcTextureDetileImageShaderHeader} ${agcTextureRepackShaderHeader} ${agcDispatchArgumentsShaderHeader} diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp index 3d32f4cdb163..5c4ee7ae8543 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp @@ -54,6 +54,7 @@ void Write(std::uint64_t address, std::span source, std::size_t void WriteChanged(std::uint64_t address, std::span current, std::span original); void WriteChanged(std::uint64_t address, std::span current, std::span original, std::uint32_t byteStoreLimit); std::uint32_t ChangedByteStoreLimit(); +void WriteChangedKeepingGuest(std::uint64_t address, std::span current, std::span original); // Write tracking. The guest arena is reserved with page write watching, so CollectWrites learns which // pages of a range the CPU wrote since they were last collected, stamps their 64 KiB blocks with a new 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 8c0bda1fd1a0..8ac7070e5e1b 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 for captured memory that changed before recording; %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(captureChangeRetries.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 for captured memory that changed before recording; %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(captureChangeRetries.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/Execution/src/GuestMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp index 909a08831547..31e2fae660ee 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp @@ -3024,7 +3024,7 @@ void WriteChanged(std::uint64_t address, std::span current, std WriteChanged(address, current, original, ChangedByteStoreLimit()); } -void WriteChanged(std::uint64_t address, std::span current, std::span original, std::uint32_t byteStoreLimit) { +static void writeChanged(std::uint64_t address, std::span current, std::span original, std::uint32_t byteStoreLimit, bool keepGuest) { require(current.size() == original.size(), "write-back snapshot sizes differ"); BreakProofs(); if (current.empty()) return; @@ -3044,7 +3044,9 @@ void WriteChanged(std::uint64_t address, std::span current, std std::size_t at = 0; for (; at + 16 <= size; at += 16) { const auto bytes = _mm_loadu_si128(reinterpret_cast(current.data() + at)); - const auto same = _mm_cmpeq_epi8(bytes, _mm_loadu_si128(reinterpret_cast(original.data() + at))); + const auto uploaded = _mm_loadu_si128(reinterpret_cast(original.data() + at)); + auto same = _mm_cmpeq_epi8(bytes, uploaded); + if (keepGuest) same = _mm_or_si128(same, _mm_xor_si128(_mm_cmpeq_epi8(_mm_loadu_si128(reinterpret_cast(destination + at)), uploaded), _mm_set1_epi8(-1))); const auto equal = static_cast(_mm_movemask_epi8(same)); if (equal == 0xffffu) continue; const auto changed = ~equal & 0xffffu; @@ -3063,7 +3065,7 @@ void WriteChanged(std::uint64_t address, std::span current, std } if (masked) _mm_sfence(); for (; at < size; ++at) { - if (current[at] == original[at]) continue; + if (current[at] == original[at] || (keepGuest && destination[at] != original[at])) continue; destination[at] = current[at]; firstChanged = std::min(firstChanged, at); lastChanged = std::max(lastChanged, at + 1); @@ -3072,6 +3074,14 @@ void WriteChanged(std::uint64_t address, std::span current, std }); } +void WriteChanged(std::uint64_t address, std::span current, std::span original, std::uint32_t byteStoreLimit) { + writeChanged(address, current, original, byteStoreLimit, false); +} + +void WriteChangedKeepingGuest(std::uint64_t address, std::span current, std::span original) { + writeChanged(address, current, original, ChangedByteStoreLimit(), true); +} + void Write(std::uint64_t address, std::span source, std::size_t alignment) { if (source.empty()) return; // A store, as in WriteChanged. diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp index 64355013caab..1af7c978cc69 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp @@ -57,6 +57,19 @@ inline VkDeviceSize HostImportOffset(const HostImport& import, std::uint64_t add return address - import.base + import.lead; } +struct HostImportStart { + std::uint64_t guest; + VkDeviceAddress device; +}; + +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 { @@ -467,7 +480,9 @@ class GuestBufferMemory { bool gpuCopy = false; VkBuffer copySource = VK_NULL_HANDLE; std::uint64_t copySourceBase = 0; + VkDeviceAddress copySourceAddress = 0; bool copiedBack = false; + std::shared_ptr shadowCopy; // An element the shader updates atomically lies inside (AddWritable's `atomic`). bool atomic = false; bool swept = false; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index 5a143dbb2f89..519a428b50c8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -98,7 +98,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. @@ -149,7 +149,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 @@ -244,6 +245,7 @@ class Recorder { void CountSamples(); bool CountingSamples() const { return countingSamples; } bool RecordMeshArguments(VkCommandBuffer commands, VkDeviceAddress record, VkDeviceAddress arguments, std::span rules); + bool RecordChangedCopy(VkCommandBuffer commands, VkDeviceAddress result, VkDeviceAddress snapshot, VkDeviceAddress target, std::uint32_t dwords, VkDeviceAddress counter = 0); std::uint64_t SamplesTotal(); bool DumpSamples(VkDeviceAddress target, std::uint64_t address = 0); void NoteSampledDraw(VkCommandBuffer commands); @@ -493,7 +495,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, 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; @@ -724,6 +726,9 @@ class Recorder { std::shared_ptr seed; std::uint64_t begin; std::uint64_t end; + std::shared_ptr snapshot; + VkDeviceAddress target = 0; + std::uint64_t cpuGeneration = 0; }; std::vector keyStores; std::vector drawTraceTokens; @@ -770,6 +775,10 @@ class Recorder { int meshArgumentState = 0; 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; std::unique_ptr sampleCounter; VkPipelineLayout sampleLayout = VK_NULL_HANDLE; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/shaders/StagingCopyBack.comp b/core/libs/prx/libSceAgcDriver/Graphics/shaders/StagingCopyBack.comp new file mode 100644 index 000000000000..a950cfef8d4d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/shaders/StagingCopyBack.comp @@ -0,0 +1,34 @@ +#version 450 +#extension GL_EXT_buffer_reference : require +#extension GL_EXT_shader_explicit_arithmetic_types_int64 : require + +layout(local_size_x = 64) in; +layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint words[]; }; +layout(push_constant) uniform Parameters { + Words result; + Words snapshot; + Words target; + Words counter; + uint count; + uint always; +} parameters; + +uint differingBytes(uint difference) { + uint folded = difference | (difference >> 1u); + folded |= folded >> 2u; + folded |= folded >> 4u; + return (folded & 0x01010101u) * 0xffu; +} + +void main() { + uint index = gl_GlobalInvocationID.x; + if (index >= parameters.count) return; + uint value = parameters.result.words[index]; + uint before = parameters.snapshot.words[index]; + uint held = parameters.target.words[index]; + uint changed = differingBytes(value ^ before); + uint kept = differingBytes(held ^ before); + uint stored = parameters.always != 0u ? 0xffffffffu : changed & ~kept; + if (stored != 0u) parameters.target.words[index] = (held & ~stored) | (value & stored); + if (uint64_t(parameters.counter) != 0ul && (changed & kept) != 0u) atomicAdd(parameters.counter.words[0], 1u); +} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp index 2526b73538d3..6197acd714c3 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/DccMetadata.cpp @@ -249,7 +249,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 ? 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/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index bd4f3a1c0b78..3e157bd8059d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -5331,8 +5331,13 @@ std::uint64_t gpuCopyLimit() { return limit; } -VkBufferUsageFlags gpuCopyUsage(bool addressable) { - return VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | (addressable ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u); +bool changedCopyBacks(const Context& context) { + static const bool disabled = std::getenv("APS5_NO_CHANGED_COPY_BACK") != nullptr; + return !disabled && context.bufferDeviceAddress; +} + +VkBufferUsageFlags gpuCopyUsage(const Context& context, bool addressable) { + return VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | (addressable || changedCopyBacks(context) ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u); } // Device-local staging. A written V# element bound in place makes the shader store into host @@ -5351,10 +5356,11 @@ VkBufferUsageFlags gpuCopyUsage(bool addressable) { // (resolveOverlays), and AddressRanges cuts the import's range around it so that its pointers reach // the shadow as its descriptor does. The // shadow is per use, not resident: a reused build records its copy-in anew (RecordStagingCopies). -// Accepted trade-off, as for the misaligned copies above: a CPU write into a staged range between -// the copy-in and the copy-back is rolled back by the copy-back (the whole written element range, -// since store extents are not known), for the batch's latency; the staging window keeps the -// exposure to the elements named on the [buffers] staging line and APS5_TRACE_STAGING. +// Accepted trade-off, as for the misaligned copies above: the copy-back stores only the bytes the +// shader changed where the import still holds the copy-in (RecordChangedCopy), but a CPU write +// between the copy-in and the copy-back is rolled back at the unaligned ends of a range, in a region +// that is not 4-byte aligned and without a shadow copy; the staging window keeps the exposure to +// the elements named on the [buffers] staging line and APS5_TRACE_STAGING. // APS5_NO_WRITTEN_SHADOW=1 and APS5_NO_ATOMIC_STAGING=1 bind those elements in place as before; // APS5_WRITTEN_SHADOW_MIN_KIB / APS5_WRITTEN_SHADOW_MAX_KIB (16 / 2048, 8192 on a discrete GPU) bound // the written window: on an integrated GPU a kernel streaming once through a large buffer (the @@ -5731,7 +5737,7 @@ void GuestBufferMemory::UploadPrepare(bool addressable) { const bool misaligned = !bindableInPlace(HostImportOffset(*entry, region.begin), addressable); if (staged) { const auto allocateStart = std::chrono::steady_clock::now(); - region.buffer = stagingBuffer(context, static_cast(region.end - region.begin), gpuCopyUsage(addressable)); + region.buffer = stagingBuffer(context, static_cast(region.end - region.begin), gpuCopyUsage(context, addressable)); if (profile) allocateUs.fetch_add(microsecondsSince(allocateStart), std::memory_order_relaxed); if (region.buffer == nullptr) { // No shadow to be had: in place when aligned, else the host copy below. @@ -5743,7 +5749,7 @@ void GuestBufferMemory::UploadPrepare(bool addressable) { if (!staged) { if (!gpuCopyEligible(region)) continue; const auto allocateStart = std::chrono::steady_clock::now(); - region.buffer = std::make_shared(context, static_cast(region.end - region.begin), gpuCopyUsage(addressable), copyBufferProperties(false)); + region.buffer = std::make_shared(context, static_cast(region.end - region.begin), gpuCopyUsage(context, addressable), copyBufferProperties(false)); if (profile) allocateUs.fetch_add(microsecondsSince(allocateStart), std::memory_order_relaxed); } region.deviceLocal = staged; @@ -5963,7 +5969,9 @@ void GuestBufferMemory::UploadFinish(bool addressable, std::optionalbuffer; - region.copySourceBase = entry->base - entry->lead; + const auto start = HostImportBufferStart(*entry); + region.copySourceBase = start.guest; + region.copySourceAddress = start.device; } } if (region.direct != nullptr) { @@ -6163,12 +6171,12 @@ void GuestBufferMemory::recordGpuCopies(std::span copies, bool ad if (region->buffer == nullptr) { // Not made by UploadPrepare (the registry was stale then): made here, under the lock. const auto allocateStart = std::chrono::steady_clock::now(); - if (region->deviceLocal) region->buffer = stagingBuffer(context, static_cast(bytes), gpuCopyUsage(addressable)); + if (region->deviceLocal) region->buffer = stagingBuffer(context, static_cast(bytes), gpuCopyUsage(context, addressable)); if (region->buffer == nullptr) { // Or no shadow to be had: a host copy serves the region instead, aligned or not. region->deviceLocal = false; region->unstaged = true; - region->buffer = std::make_shared(context, static_cast(bytes), gpuCopyUsage(addressable), copyBufferProperties(false)); + region->buffer = std::make_shared(context, static_cast(bytes), gpuCopyUsage(context, addressable), copyBufferProperties(false)); } if (profile) allocateUs.fetch_add(microsecondsSince(allocateStart), std::memory_order_relaxed); } @@ -6231,6 +6239,28 @@ void GuestBufferMemory::recordGpuCopies(std::span copies, bool ad } } } + std::vector shadowed; + for (auto* region : copies) { + const auto bytes = static_cast(region->end - region->begin); + if (!changedCopyBacks(context) || region->buffer->DeviceAddress() == 0 || !WritesOverlap(region->begin, bytes)) { + region->shadowCopy = nullptr; + continue; + } + if (region->shadowCopy == nullptr) region->shadowCopy = stagingBuffer(context, bytes, gpuCopyUsage(context, true)); + if (region->shadowCopy == nullptr || region->shadowCopy->DeviceAddress() == 0) { + region->shadowCopy = nullptr; + continue; + } + shadowed.push_back(region); + } + if (!shadowed.empty()) { + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); + Recorder::CountBarriers(Recorder::CommandClass::StagingIn); + for (auto* region : shadowed) { + CopyBuffer(context, commands, region->buffer->Handle(), 0, region->shadowCopy->Handle(), 0, region->end - region->begin); + recorder->Keep(region->shadowCopy); + } + } if (stagedAny) reportStaging(); // The copied bytes are visible to the shaders bound to the buffers, which may also store into // them. Every stage: dispatches and draws share this path, and draws run mesh, task and @@ -6289,7 +6319,7 @@ void GuestBufferMemory::RecordCopyBacks(Recorder& recorder) { commands = recorder.Commands(&covered); timing = recorder.BeginGpuTiming(StagingCopyBackKey); // The shader's stores into the buffer (whichever stage made them) precede the copy. - constexpr BarrierMask leading{VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT}; + constexpr BarrierMask leading{VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT}; if (!Recorder::ElideCovered(Recorder::CommandClass::StagingOut, leading, covered)) { RecordMemoryBarrier(context, commands, leading.srcStage, leading.dstStage, leading.srcAccess, leading.dstAccess); Recorder::CountBarriers(Recorder::CommandClass::StagingOut); @@ -6298,7 +6328,34 @@ void GuestBufferMemory::RecordCopyBacks(Recorder& recorder) { } // Exactly the sub-range the shader may write, in place in the import: what the shader // would have stored there itself had the range been bindable. - CopyBuffer(context, commands, region.buffer->Handle(), from - region.begin, region.copySource, from - region.copySourceBase, to - from); + auto whole = from; + auto wholeEnd = to; + if (region.shadowCopy != nullptr && region.copySourceAddress != 0 && region.begin % 4u == 0 && region.copySourceBase % 4u == 0) { + const auto alignedFrom = (from + 3u) & ~std::uint64_t{3}; + const auto alignedTo = to & ~std::uint64_t{3}; + static const bool traceDivergence = std::getenv("APS5_TRACE_COPY_BACK") != nullptr; + std::shared_ptr counter; + if (traceDivergence && alignedFrom < alignedTo) { + counter = std::make_shared(context, 16, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); + std::memset(counter->Bytes().data(), 0, 16); + } + if (alignedFrom < alignedTo && recorder.RecordChangedCopy(commands, region.buffer->DeviceAddress() + (alignedFrom - region.begin), region.shadowCopy->DeviceAddress() + (alignedFrom - region.begin), region.copySourceAddress + (alignedFrom - region.copySourceBase), static_cast((alignedTo - alignedFrom) / 4u), counter != nullptr ? counter->DeviceAddress() : 0)) { + if (counter != nullptr) { + recorder.Keep(counter); + recorder.OnComplete([counter, alignedFrom, alignedTo, regionBegin = region.begin, regionEnd = region.end] { + std::uint32_t diverged = 0; + std::memcpy(&diverged, counter->Bytes().data(), sizeof(diverged)); + static const bool alwaysCopy = std::getenv("APS5_CHANGED_COPY_ALWAYS") != nullptr; + if (diverged != 0) std::fprintf(stderr, "[copy-back] 0x%llx+0x%llx (region 0x%llx+0x%llx): %u dwords where the shader and the CPU changed the same bytes; %s\n", static_cast(alignedFrom), static_cast(alignedTo - alignedFrom), static_cast(regionBegin), static_cast(regionEnd - regionBegin), diverged, alwaysCopy ? "the shader's bytes were stored (APS5_CHANGED_COPY_ALWAYS)" : "the CPU's bytes were kept"); + }); + } + if (from < alignedFrom) CopyBuffer(context, commands, region.buffer->Handle(), from - region.begin, region.copySource, from - region.copySourceBase, alignedFrom - from); + if (alignedTo < to) CopyBuffer(context, commands, region.buffer->Handle(), alignedTo - region.begin, region.copySource, alignedTo - region.copySourceBase, to - alignedTo); + whole = wholeEnd; + recorder.Keep(region.shadowCopy); + } + } + if (whole < wholeEnd) CopyBuffer(context, commands, region.buffer->Handle(), whole - region.begin, region.copySource, whole - region.copySourceBase, wholeEnd - whole); copiedBytes += to - from; recorder.Keep(region.buffer); if (profile) { @@ -6318,7 +6375,7 @@ void GuestBufferMemory::RecordCopyBacks(Recorder& recorder) { // indirect dispatch's arguments) and to the host once the batch completed; the caller's // pending-write note makes CPU readers wait for that. constexpr VkAccessFlags copiedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_HOST_READ_BIT; - RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, copiedAccess); + RecordMemoryBarrier(context, 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, copiedAccess); Recorder::CountBarriers(Recorder::CommandClass::StagingOut); recorder.MarkCovered(copiedAccess); recorder.EndGpuTiming(timing, copiedBytes); @@ -6594,10 +6651,12 @@ void GuestBufferMemory::MarkDirectWrites() const { namespace { -void storeChanged(std::uint64_t address, std::span current, std::span original) { +using ChangedStore = void (*)(std::uint64_t, std::span, std::span); + +void storeChanged(std::uint64_t address, std::span current, std::span original, ChangedStore store) { const auto writable = GuestMemory::DescribeCommitted(address, current.size(), true); if (writable.whole) { - GuestMemory::WriteChanged(address, current, original); + store(address, current, original); return; } const auto unchanged = [&](std::uint64_t from, std::uint64_t to) { @@ -6612,7 +6671,7 @@ void storeChanged(std::uint64_t address, std::span current, std if (cursor < first) unchanged(cursor, first); const auto at = static_cast(first - address); const auto length = static_cast(last - first); - GuestMemory::WriteChanged(first, current.subspan(at, length), original.subspan(at, length)); + store(first, current.subspan(at, length), original.subspan(at, length)); cursor = last; } if (cursor < address + current.size()) unchanged(cursor, address + current.size()); @@ -6682,7 +6741,8 @@ void GuestBufferMemory::WriteBack() { Require(uploaded && !committed, "guest memory cannot be committed twice or before upload"); const auto merged = mergeWrites(writes); // The CPU keeps running while the GPU works, so storing whole ranges would roll back its writes to - // bytes the shader never touched. Only runs that differ from the uploaded copy are stored. + // bytes the shader never touched. Only runs that differ from the uploaded copy are stored, and a + // host copy leaves the bytes the CPU changed since its upload as they are. for (const auto& [begin, end] : merged) { const auto* found = owner(begin, end); Require(found != nullptr, "write-back range has no GPU owner"); @@ -6710,7 +6770,7 @@ void GuestBufferMemory::WriteBack() { if (mirror.resident == nullptr) { const auto current = mirror.buffer->Bytes().subspan(offset, length); if (mirror.sparse) storeSparse(mirror, begin, current, reference->second); - else storeChanged(begin, current, reference->second); + else storeChanged(begin, current, reference->second, GuestMemory::WriteChanged); continue; } std::vector current(length); @@ -6722,7 +6782,7 @@ void GuestBufferMemory::WriteBack() { } mirror.resident->Store(begin, current); if (mirror.sparse) storeSparse(mirror, begin, current, reference->second); - else storeChanged(begin, current, reference->second); + else storeChanged(begin, current, reference->second, GuestMemory::WriteChanged); continue; } const auto current = mirror.buffer->Bytes().subspan(offset, length); @@ -6758,7 +6818,7 @@ void GuestBufferMemory::WriteBack() { if (!region.sparse) { const auto first = static_cast(begin - region.begin); const auto length = static_cast(end - begin); - storeChanged(begin, region.buffer->Bytes().subspan(first, length), std::span(region.uploaded).subspan(first, length)); + storeChanged(begin, region.buffer->Bytes().subspan(first, length), std::span(region.uploaded).subspan(first, length), GuestMemory::WriteChangedKeepingGuest); continue; } std::size_t packed = 0; @@ -6767,7 +6827,7 @@ void GuestBufferMemory::WriteBack() { const auto to = std::min(last, end); if (from < to) { const auto length = static_cast(to - from); - storeChanged(from, region.buffer->Bytes().subspan(static_cast(from - region.begin), length), std::span(region.uploaded).subspan(packed + static_cast(from - first), length)); + storeChanged(from, region.buffer->Bytes().subspan(static_cast(from - region.begin), length), std::span(region.uploaded).subspan(packed + static_cast(from - first), length), GuestMemory::WriteChangedKeepingGuest); } packed += static_cast(last - first); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 29a199e19196..0b474916dbfa 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -13,6 +13,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libSceAgcDriver/Graphics/include/DeferredDestruction.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/MeshArguments_spv.h" +#include "prx/libSceAgcDriver/Graphics/shaders/StagingCopyBack_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/SampleCounter_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/SampleDumps_spv.h" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -578,7 +579,26 @@ 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}, keyBlocksLeftToCpu{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; +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() { @@ -1236,6 +1256,8 @@ Recorder::~Recorder() { } if (meshArgumentPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, meshArgumentPipeline, nullptr); if (meshArgumentLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, meshArgumentLayout, nullptr); + if (changedCopyPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, changedCopyPipeline, nullptr); + if (changedCopyLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, changedCopyLayout, nullptr); if (sampleCounterState > 0) { samplesPassed.store(SamplesTotal(), std::memory_order_release); if (samplePools != nullptr) std::static_pointer_cast(samplePools)->close(); @@ -1422,7 +1444,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), keyBlocksLeftToCpu.load(std::memory_order_relaxed), storeRunsAtSubmit.load(std::memory_order_relaxed), storeRunsForced.load(std::memory_order_relaxed)}; } std::uint64_t Recorder::ThreadHookWaits() { @@ -1653,7 +1675,7 @@ void Recorder::endOpenRenderPass(PassBreak by, bool barrier) { pass.closedBy = by; } -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)); @@ -1667,7 +1689,53 @@ 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; + 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); + 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))) { + 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 { + 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) { + 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); + 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); + } + } + open->keyStores.push_back({buffer, first, last, std::move(seed), begin, end, std::move(snapshot), target, cpuGeneration}); if (KeyStoresEach()) recordKeyStores(false); } @@ -1695,14 +1763,52 @@ 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); + 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 (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 (!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; @@ -1712,7 +1818,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; @@ -2756,6 +2862,58 @@ bool Recorder::RecordMeshArguments(VkCommandBuffer commands, VkDeviceAddress rec return true; } +bool Recorder::RecordChangedCopy(VkCommandBuffer commands, VkDeviceAddress result, VkDeviceAddress snapshot, VkDeviceAddress target, std::uint32_t dwords, VkDeviceAddress counter) { + constexpr std::uint32_t PushBytes = 40; + constexpr std::uint32_t GroupSize = 64; + if (changedCopyState == 0) { + changedCopyState = -1; + VkShaderModule module = VK_NULL_HANDLE; + try { + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes}; + VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layoutInfo.pushConstantRangeCount = 1; + layoutInfo.pPushConstantRanges = &push; + Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &changedCopyLayout), "vkCreatePipelineLayout changed copy"); + VkShaderModuleCreateInfo moduleInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + moduleInfo.codeSize = sizeof(STAGING_COPY_BACK_SPV); + moduleInfo.pCode = STAGING_COPY_BACK_SPV; + Check(context.Function("vkCreateShaderModule")(context.device, &moduleInfo, nullptr, &module), "vkCreateShaderModule changed copy"); + VkComputePipelineCreateInfo pipelineInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipelineInfo.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + pipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + pipelineInfo.stage.module = module; + pipelineInfo.stage.pName = "main"; + pipelineInfo.layout = changedCopyLayout; + Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &changedCopyPipeline), "vkCreateComputePipelines changed copy"); + context.Function("vkDestroyShaderModule")(context.device, module, nullptr); + changedCopyState = 1; + } catch (const std::exception& error) { + if (module != VK_NULL_HANDLE) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); + std::fprintf(stderr, "[gpu] staged write-backs copy their whole ranges: %s\n", error.what()); + } + } + if (changedCopyState < 0) return false; + static const bool alwaysCopy = std::getenv("APS5_CHANGED_COPY_ALWAYS") != nullptr; + function(cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, changedCopyPipeline); + const auto perDispatch = static_cast(std::min(std::uint64_t{context.limits.maxComputeWorkGroupCount[0]} * GroupSize, std::numeric_limits::max() - GroupSize)); + for (std::uint32_t done = 0; done < dwords;) { + const auto count = std::min(dwords - done, perDispatch); + struct { + VkDeviceAddress result; + VkDeviceAddress snapshot; + VkDeviceAddress target; + VkDeviceAddress counter; + std::uint32_t count; + std::uint32_t always; + } parameters{result + VkDeviceAddress{done} * 4u, snapshot + VkDeviceAddress{done} * 4u, target + VkDeviceAddress{done} * 4u, counter, count, alwaysCopy ? 1u : 0u}; + static_assert(sizeof(parameters) == PushBytes); + function(cmdPushConstants, "vkCmdPushConstants")(commands, changedCopyLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); + function(cmdDispatch, "vkCmdDispatch")(commands, (count + GroupSize - 1) / GroupSize, 1, 1); + done += count; + } + return true; +} + void Recorder::beginSamples(Batch& batch) { auto cache = std::static_pointer_cast(samplePools); if (sampleCounterState > 0 && cache == nullptr) { @@ -3232,10 +3390,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 c9a8e2e6a614..11a6771ae111 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp @@ -320,7 +320,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. diff --git a/core/libs/prx/libSceAgcDriver/tests/Pm4.cpp b/core/libs/prx/libSceAgcDriver/tests/Pm4.cpp index ae55bc2ec43f..adb2819f08aa 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Pm4.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Pm4.cpp @@ -892,6 +892,29 @@ void testWriteChangedStoresExactlyTheChangedRuns() { } } +void testWriteChangedKeepingGuestKeepsCpuWrites() { + alignas(256) static std::uint8_t guest[1024 + 13]; + std::vector original(sizeof(guest)), current(sizeof(guest)); + std::uint32_t seed = 777; + const auto next = [&] { return seed = seed * 1103515245u + 12345u, seed >> 16u; }; + std::vector cpu(sizeof(guest)); + for (std::size_t i = 0; i < sizeof(guest); ++i) { + original[i] = static_cast(next()); + const auto kind = next() % 4; + current[i] = kind >= 2 ? static_cast(static_cast(original[i]) ^ (1u + next() % 255u)) : original[i]; + cpu[i] = kind % 2 == 1 ? static_cast(static_cast(original[i]) ^ (1u + next() % 255u)) : static_cast(original[i]); + guest[i] = cpu[i]; + } + AgcDriver::GuestMemory::WriteChangedKeepingGuest(reinterpret_cast(guest), current, original); + for (std::size_t i = 0; i < sizeof(guest); ++i) { + const auto expected = cpu[i] != static_cast(original[i]) ? cpu[i] : static_cast(current[i]); + check(guest[i] == expected, "write-back overwrote a byte the CPU changed since the upload, or skipped one it did not"); + } + for (std::size_t i = 0; i < sizeof(guest); ++i) guest[i] = static_cast(original[i]); + AgcDriver::GuestMemory::WriteChangedKeepingGuest(reinterpret_cast(guest), current, original); + for (std::size_t i = 0; i < sizeof(guest); ++i) check(guest[i] == static_cast(current[i]), "write-back skipped a changed byte although the guest still held the upload"); +} + void testWriteChangedChunksOfEveryDensity() { alignas(64) static std::uint8_t guest[128]; constexpr std::size_t Tail = 5; @@ -2183,6 +2206,7 @@ int main(int argc, char** argv) { testWriteChangedKeepsUntouchedBytes(); testWriteChangedChunksOfEveryDensity(); testWriteChangedStoresExactlyTheChangedRuns(); + testWriteChangedKeepingGuestKeepsCpuWrites(); testRegisters(); testRegisterFile(); testContextAndBases(); diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index 3b519c100b2c..bcc835914024 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -1033,6 +1033,166 @@ void copiedDirectOrderingTests(const Device& device, Recorder& recorder) { std::cout << "Copied producers precede fresh and reused direct consumers\n"; } +void copiedWriteBackTests(const Device& device, Recorder& recorder) { + auto context = device.GetContext(); + context.hostImportAlignment = 0; + context.dmaBufImport = false; + recorder.Sync(); + alignas(4096) static std::uint32_t block[1024]; + std::memset(block, 0, sizeof(block)); + const auto address = reinterpret_cast(block); + ShaderRecompiler::RecompileResult program; + ShaderRecompiler::DescriptorBinding binding; + binding.kind = ShaderRecompiler::DescriptorKind::StorageBuffer; + binding.role = ShaderRecompiler::DescriptorRole::GuestBuffers; + binding.descriptorSet = 0; + binding.binding = 0; + binding.count = 1; + binding.guestDescriptor = {static_cast(address), static_cast(address >> 32u) & 0xffffu, 1024, 0x31000000u}; + binding.bufferWritten = {true}; + program.bindings.push_back(binding); + const CompiledShader compute{ShaderRecompiler::ShaderStage::Compute, &program, 0}; + struct Release { + const Context& context; + Recorder& recorder; + VkPipeline pipeline = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkShaderModule module = VK_NULL_HANDLE; + std::shared_ptr layoutOwner; + ~Release() { + recorder.Sync(); + if (pipeline) context.Function("vkDestroyPipeline")(context.device, pipeline, nullptr); + if (layout) context.Function("vkDestroyPipelineLayout")(context.device, layout, nullptr); + if (module) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); + } + } release{context, recorder}; + release.layoutOwner = std::make_shared(context, compute); + Require(release.layoutOwner->HasCopiedWrites(), "the written buffer did not take the copied path"); + const auto setLayout = release.layoutOwner->Layout(); + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(std::uint32_t)}; + VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layoutInfo.setLayoutCount = 1; + layoutInfo.pSetLayouts = &setLayout; + layoutInfo.pushConstantRangeCount = 1; + layoutInfo.pPushConstantRanges = &push; + Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &release.layout), "copied write-back pipeline layout"); + VkShaderModuleCreateInfo moduleInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + moduleInfo.codeSize = sizeof(BUFFER_UPDATE_SPV); + moduleInfo.pCode = BUFFER_UPDATE_SPV; + Check(context.Function("vkCreateShaderModule")(context.device, &moduleInfo, nullptr, &release.module), "copied write-back shader module"); + VkComputePipelineCreateInfo pipelineInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipelineInfo.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_COMPUTE_BIT, release.module, "main", nullptr}; + pipelineInfo.layout = release.layout; + Check(context.Function("vkCreateComputePipelines")(context.device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &release.pipeline), "copied write-back pipeline"); + const auto run = [&](std::uint32_t delta) { + auto copied = std::make_shared(context, compute); + Require(copied->HasCopiedWrites(), "a use of the written buffer did not take the copied path"); + const auto commands = recorder.Commands(); + recorder.Keep(copied); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); + context.Function("vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, release.pipeline); + copied->Bind(commands, VK_PIPELINE_BIND_POINT_COMPUTE, release.layout); + context.Function("vkCmdPushConstants")(commands, release.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(delta), &delta); + context.Function("vkCmdDispatch")(commands, 1, 1, 1); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); + copied->MarkGpuWrites(recorder); + recorder.Sync(); + return copied; + }; + block[0] = 0x10; + block[1] = 0x20; + const auto first = run(1); + block[0] = 0x70; + block[1] = 0x25; + first->WriteBackBuffers(); + Require(block[0] == 0x70, "a copied write-back stored the shader's dword over the one the CPU wrote after the upload"); + Require(block[1] == 0x25, "a copied write-back rolled back a dword the shader never touched"); + const auto second = run(2); + second->WriteBackBuffers(); + Require(block[0] == 0x72, "the next use of the copied buffer did not read the dword the CPU wrote"); + block[0] = 0x10; + const auto third = run(1); + block[0] = 0x00aa0010u; + third->WriteBackBuffers(); + Require(block[0] == 0x00aa0011u, "a copied write-back did not merge the shader's byte with the CPU's byte of the same dword"); + std::cout << "Copied write-backs keep the bytes the CPU wrote after the upload\n"; +} + +void changedCopyTests(const Device& device, Recorder& recorder) { + Require(recorder.Idle(), "the changed copy test needs an idle recorder"); + constexpr std::uint32_t words = 70000; + constexpr auto usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + auto result = std::make_shared(device.GetContext(), words * 4u, usage); + auto snapshot = std::make_shared(device.GetContext(), words * 4u, usage); + auto target = std::make_shared(device.GetContext(), words * 4u, usage); + if (result->DeviceAddress() == 0 || snapshot->DeviceAddress() == 0 || target->DeviceAddress() == 0) { + std::cout << "changed copy tests skipped: no buffer device addresses\n"; + return; + } + constexpr std::uint32_t byteMasks[] = {0xffffffffu, 0x000000ffu, 0x0000ff00u, 0x00ff0000u, 0xff000000u, 0x00ffff00u}; + std::vector uploaded(words), shader(words), held(words), expected(words); + std::uint32_t contested = 0; + std::uint32_t mixed = 0; + for (std::uint32_t i = 0; i < words; ++i) { + uploaded[i] = i * 2654435761u; + shader[i] = i % 7 == 0 ? uploaded[i] ^ (0x5a5a5a5au & byteMasks[(i / 7) % 6]) : uploaded[i]; + held[i] = i % 5 == 0 ? uploaded[i] ^ (0xc3c3c3c3u & byteMasks[(i / 5 + 1) % 6]) : uploaded[i]; + bool overlap = false; + for (std::uint32_t shift = 0; shift < 32; shift += 8) { + const auto mask = 0xffu << shift; + const bool byShader = (shader[i] & mask) != (uploaded[i] & mask); + const bool byCpu = (held[i] & mask) != (uploaded[i] & mask); + expected[i] |= (byShader && !byCpu ? shader[i] : held[i]) & mask; + overlap = overlap || (byShader && byCpu); + } + contested += overlap ? 1u : 0u; + mixed += expected[i] != shader[i] && expected[i] != held[i] ? 1u : 0u; + } + Require(contested != 0 && mixed != 0, "the changed copy data lacks words both sides changed or words that mix their bytes"); + auto counter = std::make_shared(device.GetContext(), 16, usage); + std::memset(counter->Bytes().data(), 0, 16); + std::memcpy(snapshot->Bytes().data(), uploaded.data(), words * 4u); + std::memcpy(result->Bytes().data(), shader.data(), words * 4u); + std::memcpy(target->Bytes().data(), held.data(), words * 4u); + Require(recorder.RecordChangedCopy(recorder.Commands(), result->DeviceAddress(), snapshot->DeviceAddress(), target->DeviceAddress(), words, counter->DeviceAddress()), "the changed copy kernel is unavailable"); + recorder.Keep(result); + recorder.Keep(snapshot); + recorder.Keep(target); + recorder.Keep(counter); + recorder.Submit(); + device.WaitQueue(); + recorder.Sync(); + std::vector stored(words); + std::memcpy(stored.data(), target->Bytes().data(), words * 4u); + for (std::uint32_t i = 0; i < words; ++i) { + Require(stored[i] == expected[i], "changed copy word " + std::to_string(i) + ": " + std::to_string(stored[i]) + ", expected " + std::to_string(expected[i]) + " (the shader's changed bytes over the target's own)"); + } + std::uint32_t counted = 0; + std::memcpy(&counted, counter->Bytes().data(), sizeof(counted)); + Require(counted == contested, "the changed copy counted " + std::to_string(counted) + " words with bytes both sides changed, expected " + std::to_string(contested)); + constexpr std::uint64_t lead = 0x1000; + auto imported = std::make_shared(device.GetContext(), lead + words * 4u, usage); + std::memset(imported->Bytes().data(), 0xa5, lead); + std::memcpy(imported->Bytes().data() + lead, held.data(), words * 4u); + HostImport import{}; + import.base = 0x7f0000011000ull; + import.bytes = words * 4u; + import.address = imported->DeviceAddress() + lead; + import.lead = lead; + const auto start = HostImportBufferStart(import); + Require(start.guest == import.base - lead && start.device == imported->DeviceAddress() && HostImportOffset(import, import.base) == lead, "the copy source of an import with a lead does not start at the import's buffer"); + Require(recorder.RecordChangedCopy(recorder.Commands(), result->DeviceAddress(), snapshot->DeviceAddress(), start.device + (import.base - start.guest), words), "the changed copy kernel is unavailable"); + recorder.Keep(imported); + recorder.Submit(); + device.WaitQueue(); + recorder.Sync(); + for (std::uint64_t i = 0; i < lead; ++i) Require(imported->Bytes()[i] == std::byte{0xa5}, "the changed copy into an import with a lead wrote byte " + std::to_string(i) + " of the lead"); + std::memcpy(stored.data(), imported->Bytes().data() + lead, words * 4u); + for (std::uint32_t i = 0; i < words; ++i) { + Require(stored[i] == expected[i], "changed copy word " + std::to_string(i) + " after a lead: " + std::to_string(stored[i]) + ", expected " + std::to_string(expected[i])); + } +} + void readTrackingTests(const Device& device, Recorder& recorder) { Require(Recorder::ReadTracking(), "read tracking is off (APS5_COPY_READ_TRACKING=0 set?)"); Require(recorder.Idle() && !recorder.PendingReadOverlaps(0x10000, 16), "a fresh recorder reports a read"); @@ -4123,6 +4283,11 @@ bool bdaStagingTests(const Device& device, Recorder& recorder) { std::uint32_t innerAdjustment = 0; Require(memory.Descriptor(element + 16, 64, innerAdjustment).buffer == view.buffer, "a read inside the staged element does not read its shadow"); recorder.Sync(); + const bool changedCopy = std::getenv("APS5_NO_CHANGED_COPY_BACK") == nullptr; + auto* contested = static_cast(words + first + 70); + auto* untouched = static_cast(words + first + 100); + *contested = 0x11111133u; + *untouched = 0x44444444u; auto commands = recorder.Commands(); fill(commands, view.buffer, view.offset + adjustment + 64u * 4u, 64, 0x22222222u); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT); @@ -4132,7 +4297,9 @@ bool bdaStagingTests(const Device& device, Recorder& recorder) { std::size_t wrong = 0; for (std::size_t index = 0; index < bytes / 4u; ++index) { const auto at = index >= first ? index - first : bytes; - const auto expected = at >= 64 && at < 80 ? 0x22222222u : 0x11111111u; + auto expected = at >= 64 && at < 80 ? 0x22222222u : 0x11111111u; + if (at == 70 && changedCopy) expected = 0x22222233u; + if (at == 100 && changedCopy) expected = 0x44444444u; if (words[index] != expected && wrong++ < 8) std::cout << "address-based staging copy-back dword " << index << " holds 0x" << std::hex << words[index] << ", expected 0x" << expected << std::dec << "\n"; } Require(wrong == 0, "an address-based staged copy-back left the wrong guest bytes"); @@ -13012,6 +13179,113 @@ void keysFillTests(const Device& device, Recorder& recorder) { recorder.Sync(); } +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 false; + } + constexpr std::size_t surfaceBytes = 65536 * 4; + constexpr std::size_t keyCount = surfaceBytes / 256; + 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 + block = VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); +#else + block = std::aligned_alloc(65536, bytes); +#endif + } + Require(block != nullptr, "cannot allocate the key store block"); + auto* keys = static_cast(block) + keysOffset; + std::memset(block, 0x00, bytes); + const auto address = reinterpret_cast(block); + 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, 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 false; + } + 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 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); + 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); + } + 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"); + 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 && 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 || !blocksWatched || Recorder::StoreCounts().keyBlocksLeftToCpu > leftBefore, "the block the CPU wrote was not counted as left to it"); + 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 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) { const auto& context = device.GetContext(); std::size_t tested = 0; @@ -13906,6 +14180,10 @@ int main(int argc, char** argv) { copiedDirectOrderingTests(device, recorder); return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--copied-write-back-only") { + copiedWriteBackTests(device, recorder); + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--completion-wait-only") { completionWaitTests(device, recorder); std::cout << "Completion wait tests passed\n"; @@ -14049,6 +14327,14 @@ int main(int argc, char** argv) { parkedImportUnmapTests(device); return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--changed-copy-only") { + changedCopyTests(device, recorder); + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--guarded-key-store-only") { + if (!guardedKeyStoreTests(device, recorder)) return 77; + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--window-import-unmap-only") { gpu.unlock(); windowImportUnmapTests(device); @@ -14224,6 +14510,7 @@ int main(int argc, char** argv) { readListTests(device, recorder); overlappedRangeTests(recorder); spaceWriteSyncTests(device, recorder); + changedCopyTests(device, recorder); writeSettledTests(device, recorder); completionCountTests(device, recorder); afterRecordedWorkTests(device, recorder); @@ -14272,6 +14559,7 @@ int main(int argc, char** argv) { movedMetadataTests(device, recorder); viewPastLastMipTests(device, recorder); keysFillTests(device, recorder); + guardedKeyStoreTests(device, recorder); clearHandOverTests(device, recorder, false); clearHandOverTests(device, recorder, true); integerClearTests(device); @@ -14311,6 +14599,7 @@ int main(int argc, char** argv) { shadowedKeyStoreTests(device, recorder); sampleDumpTests(device, recorder); copiedDirectOrderingTests(device, recorder); + copiedWriteBackTests(device, recorder); gpu.unlock(); hostImportUnmapTests(device, recorder); drawSnapshotPatchTests(device); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake index 1a60ec98e73d..1ebe48eaf1fe 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake @@ -288,6 +288,12 @@ if(BUILD_TESTING) set_tests_properties(agc_copied_direct_ordering PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() + add_test(NAME agc_copied_write_back COMMAND agc_driver_recorder_tests --copied-write-back-only) + set_tests_properties(agc_copied_write_back PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + if(WIN32) + set_tests_properties(agc_copied_write_back PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() add_test(NAME agc_storage_writeback_blocks COMMAND agc_driver_recorder_tests --writeback-blocks-only) set_tests_properties(agc_storage_writeback_blocks PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30 ENVIRONMENT "APS5_PIN_WAIT_MS=3000") if(WIN32) @@ -332,6 +338,10 @@ if(BUILD_TESTING) endif() add_test(NAME agc_sparse_run_import_copied COMMAND agc_driver_recorder_tests --sparse-run-copied-only) set_tests_properties(agc_sparse_run_import_copied PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + 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_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) add_test(NAME agc_unit_shadow COMMAND agc_driver_recorder_tests --unit-shadow-only) set_tests_properties(agc_unit_shadow PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30 ENVIRONMENT "APS5_PIN_WAIT_MS=3000") add_test(NAME agc_idle_publish_wait COMMAND agc_driver_recorder_tests --idle-publish-wait-only) @@ -389,7 +399,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_window_import_unmap agc_host_import_retirement agc_sparse_run_import agc_sparse_run_import_copied agc_unit_shadow agc_driver_recorder agc_idle_publish_wait agc_recorder_command_buffer_release agc_descriptor_pool_recycling agc_draw_snapshot_cap agc_draw_snapshot_epoch agc_multisample_guest_access agc_repeat_storage_guard agc_draw_inputs_in_place agc_draw_inputs_copied agc_resident_present agc_slice_dirty agc_queued_write_groups agc_metadata_pass agc_tiled_resolve PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(agc_recorder_read_list agc_host_import_unmap agc_parked_import_unmap agc_window_import_unmap agc_host_import_retirement agc_sparse_run_import agc_sparse_run_import_copied agc_unit_shadow agc_driver_recorder agc_idle_publish_wait agc_recorder_command_buffer_release agc_descriptor_pool_recycling agc_draw_snapshot_cap agc_draw_snapshot_epoch agc_multisample_guest_access agc_repeat_storage_guard 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 diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index aa1c03d9f229..c555db6e0941 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -118,6 +118,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_CAPTURE_INPUTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | records each draw's inputs in the capture trace (requires APS5_CAPTURE_TRACE) | | `APS5_CAPTURE_TRACE` | presence | `core/libs/prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp` | | writes capture events to capture-trace.log | | `APS5_CAPTURE_TRACE_PATH` | string | `core/libs/prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp` | capture-trace.log | file path for the capture events log | +| `APS5_CHANGED_COPY_ALWAYS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes the changed-byte copy-back store every byte of the range, not only those the shader changed and the import still holds at their copy-in value | | `APS5_CHECK_INDIRECT_ARGS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | reads GPU-side indirect draw records back on the CPU and prints the first ones | | `APS5_COMPLETION_STORE_SYNC` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | makes a store made by a completion action wait for later batches over its range | | `APS5_COPY_DESTINATION_STRICT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | refuses a CPU copy whose destination has any pending writer, not only an unsettled one | @@ -236,6 +237,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_BLOCK_TRACKING` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | tracks array layers, or the whole surface, instead of 64 KiB blocks | | `APS5_NO_BUFFER_CLASSES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp` | | matches exact sizes in the buffer pool instead of rounding up to size classes | | `APS5_NO_CACHED_PRECOLLECT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | leaves the write-watch walks of a cached object's Revalidate under the GPU mutex | +| `APS5_NO_CHANGED_COPY_BACK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | copies a GPU-copied buffer's whole range back into its import instead of only the bytes the shader changed | | `APS5_NO_CLEAR_HAND_OVER` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | writes other images' pending results back at a clear-key storage refresh instead of handing them over to the refreshed image | | `APS5_NO_CLEARED_VIEW` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | keeps fast-cleared surfaces as CPU snapshots instead of viewing the cleared storage image | | `APS5_NO_COLLECT_MEMO` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp` | | disables the per-thread memo of write-watch collects | @@ -283,6 +285,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `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_GPU_THREAD_DIMENSIONS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/IndirectDispatch.cpp` | | reads the thread counts of an indirect dispatch with USE_THREAD_DIMENSIONS on the CPU instead of turning them into group counts and a thread limit on the GPU | +| `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 | @@ -461,6 +464,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_TRACE_BIGBUF` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | lists every copied guest region of at least 1 MiB | | `APS5_TRACE_CAPSYNC` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WriteEvidence.cpp` | | prints every unlocked hook wait | | `APS5_TRACE_CONTEXT_STATE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp` | | logs context-state operations and the context registers written | +| `APS5_TRACE_COPY_BACK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | logs, per copied-back range, the dwords in which the shader and the CPU changed the same bytes, and whether the CPU's bytes were kept or, with APS5_CHANGED_COPY_ALWAYS, the shader's stored | | `APS5_TRACE_COPY_HLE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferCopy.cpp` | | traces the CPU copy HLE's refusals | | `APS5_TRACE_DCC_KEYS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/DisplayBuffer.cpp` | | traces stores of uncompressed DCC keys | | `APS5_TRACE_DIR` | string | `core/libs/prx/libSceAgcDriver/Execution/src/PerformanceTrace.cpp` | . | directory for the trace and summary files | @@ -476,6 +480,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_MEMORY_BUDGET` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/MemoryAccounting.cpp` | | tracks Vulkan allocation bytes by heap and category, separates active and retained memory, and reports dynamic storage-cache budget terms at most every 10 seconds | | `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 | diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 7e2a12858979..ce8941cb04c8 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -321,7 +321,8 @@ - [Heap mirror reference storage](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ReferenceStorage.cpp) (libSceAgcDriver): the 8-buffer/2 GiB idle cap and 2 s reuse window are unmeasured choices. Idle release is polled by a take, an eligible return, a heap mirror sweep or a present; without another poll, expired buffers remain until process shutdown. A title taking references less often than every 2 s reallocates them. The cap covers idle storage only, not buffers still held by active references. - [Host import windows and budget](../../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp) (libSceAgcDriver): a registered range larger than 64 MiB is imported one 64 MiB window at a time for buffer and fill accesses; an access across window edges imports the cells it touches, grown to the union of the range's imports it overlaps. An address-based build (`AcquireRegistered`) imports the range whole and replaces its windows. Live imports stay under a budget: `APS5_HOST_IMPORT_MIB`, else the larger of 6 GiB and half the physical memory, at most the largest host heap less half that heap, kept between 2 and 4 GiB (imports, type-3 mirrors and buffers and textures placed in host memory share it; on a 16 GiB machine whose host heap is half the memory, a 2 GiB reserve left too little for the rest, and on a 32 GiB machine a reserve of half its 16 GiB heap left imports 8 GiB, less than the 10466 MiB one title holds at once). Where the device enables `VK_EXT_memory_budget`, that host heap's reported budget less its other usage and an eighth, in 64 MiB steps, read at most once a second, also bounds the default budget once an import's `vkAllocateMemory` has failed; a set `APS5_HOST_IMPORT_MIB` is never lowered by the report. The report's other usage includes the host-visible copies and heap mirrors that stand in for refused imports, so it grows with the refusals; the first time the report would lower the budget, `[gpu] host import budget: host heap ...` prints the heap's reported budget and usage and the live imports. An import's `vkAllocateMemory` failure within an eighth of the budget, or the third in a row, lowers the budget to the live imports until the device or the configured budget changes; an isolated failure further below only marks its range failed. Live imports are not capped by `maxMemoryAllocationCount`: NVIDIA's Windows driver reports 4096, while Village held 27,167 live imports without a failure. A new import beyond it retires the least recently used imports not used in the current or the previous frame (a frame ends at a flip packet or a CPU flip), so a set used in every frame keeps its imports and what does not fit is copied, as below the budget; until two frames have ended imports age by lookups, an import being evictable 256 lookups after its last use; after that, without flips (a loading stretch, compute-only work) no frame ends and nothing more becomes evictable, so imports that do not fit are copied instead of evicting by recency; one that would not fit even then is refused before anything is retired, and imports made when a range is mapped never evict. An address-based build does not evict either, except for a range the budget refused (or remembers refusing) and no mirror serves whose copy would take the build's copies past `APS5_ADDRESS_COPY_MAX_MIB`; that eviction also takes imports the recency rule protects whose single range is releasable and write-watched, so a heap mirror can serve it, as long as the build has not taken them yet. A heap mirror, sparse or not, whose range has left the write watch is refreshed in full at each use, every block counted as written, unless the build can import its range first, evicting for it as the copy cap does, with the imports of earlier builds no longer held; a build plans its range again only once the import path takes the range. A request that may not evict (an address-based build, an import when a range is mapped) remembers a refused range or block, with the live bytes and the budget at the refusal, and is answered from that memory, still counted as refused, until live imports drop below those bytes, the budget changes or one of its ranges changes. A request that may evict remembers its refusal too, answering later requests for the same run from memory with the room the refusal left (a request whose range fits in that room steps down to a smaller block without scanning the imports again, and a refusal that stepped down is remembered for each block it tried), while no import was made or retired, the budget has not grown, the import window and the run are unchanged, and no import can have become evictable since: no frame has ended (or, before two frames have ended, 256 lookups have not passed), and no build holding an import two frames old has raised its floor. A join remembers its refusal the same way, apart from other requests for the same run, so a buffer bound across refused ranges does not try the join again at every upload. The shutdown line `[gpu] host imports at shutdown` gives the live, made, refused (and remembered) and failed counts per requester. The 64 MiB window, the two-frame protection, the 2 GiB reserve, the eighth, the 64 MiB steps and the three failures are choices, not measured. - [Piece-split ranges over the host import budget](../../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp) (libSceAgcDriver): an address-based build imports a registered range larger than the device's largest allocation in pieces. If the budget refuses a piece, the range is mirrored or copied without the evicting retry other refused ranges get when their copy would pass `APS5_ADDRESS_COPY_MAX_MIB`, so such a copy can still exceed that cap and end the build. -- [Device-local staging](../../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp) (libSceAgcDriver) - a written or atomic buffer element inside a host import, including one an address-based compute build reaches through its pointers, is copied to device memory before the dispatch and copied back whole after it, so a CPU store into that range in between is rolled back. +- [Device-local staging](../../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp) (libSceAgcDriver) - a written or atomic buffer element inside a host import, including one an address-based compute build reaches through its pointers, is copied to device memory before the dispatch and copied back after it. The copy-back stores only the bytes the shader changed and the import still holds at their copy-in value, so a CPU store in between survives; where both changed the same byte, the CPU's byte is kept, whichever the console would store last. The whole range is still copied back, rolling CPU stores back, at the unaligned ends of a range, for an element or import offset that is not 4-byte aligned, without a shadow copy or buffer device addresses, with `APS5_NO_CHANGED_COPY_BACK`, and when a synchronous draw stores a GPU-copied region from the CPU (no copy-back recorded, no copy-in snapshot). A CPU store made while the copy-back runs can still be overwritten by it. +- [Write-back conflicts with CPU stores](../../../core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp) (libSceAgcDriver) - a buffer region the CPU copies for a dispatch is stored back with `WriteChangedKeepingGuest`: a byte takes the shader's value only where the shader changed it and guest memory still holds the uploaded value, so a CPU store made after the upload wins where both changed the same byte. A CPU store that restores the uploaded value is indistinguishable from no store and takes the shader's byte. Writable image mirrors, heap mirrors, storage image write-backs and tiled colour targets use `WriteChanged`, which stores every byte the GPU changed: a CPU store into the same byte between the upload and the write-back is overwritten there, as before; a CPU store into a byte the GPU left alone survives on every path. Which side the console would store last is not measured. - [Committed reads of released pages](../../../core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp) (libSceAgcDriver) - `ReadCommitted` and `EqualsCommitted` find the readable pages of a range first and read them afterwards. On Windows they read through `ReadProcessMemory`, so a page released in between reads as zero and is left out of the comparison instead of faulting: Demon's Souls (PPSA01342) samples a texture at 0x38400 of 352 MiB while it loads the tutorial level, a range that holds no guest allocation and on Windows covers host heap pages other threads release, which stopped it with an access violation. A texture outside every registered guest allocation still takes the host bytes found there, as it did before; what the console returns for it is not measured. On Linux the pages are copied directly, so a page released between the check and the copy still faults. - [Periodic pipeline cache saves skip busy intervals](../../../core/libs/prx/libSceAgcDriver/Graphics/src/PipelineCache.cpp) (libSceAgcDriver) - the saver thread snapshots the Vulkan pipeline cache only when no pipeline creation holds it (`TryLockForSnapshot`); otherwise it skips that 10 s interval. A blocking snapshot queued behind a long creation (an NVIDIA compile of a 1.5M-word compute pipeline runs for minutes) makes the writer-preferring `shared_mutex` hold every later pipeline creation on every queue until that compile ends, which froze Yōtei's (PPSA26344) loading at frame 797-799 for the whole compile. While creations overlap without a gap, no periodic save happens, so a crash in that stretch loses the pipelines built since the last save; `SaveNow` and the teardown save still wait for the lock. How often busy stretches skip saves in practice is not measured. - [Registration preparation at submit](../../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Queues/Submission.cpp) (libSceAgcDriver) - `Driver::Submit` waits for every registration-time shader preparation queued before the call, not only those of the shaders the commands use, so a submission behind a long queue of unrelated preparations waits for all of them on the submitting thread. Waiting there instead of in the queue worker keeps the GPU side of a submission short: a title that sees a submission take seconds treats the GPU as hung (Goat Simulator 3, PPSA04159, then stops submitting and its garbage collector fails a 10 s timeout). On the console shaders are compiled ahead of time, so neither wait exists; how long a title tolerates a slow submit call is not known. @@ -348,6 +349,7 @@ - [Depth view mip on a single-level surface](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver) - a `DB_DEPTH_VIEW.MIPID` above zero on a surface whose `DB_Z_INFO.MAXMIP` is zero selects the first level. In Flashback (PPSA08546) the depth view follows a mipmapped colour target from mip 1 to 6 over six slices of a 128x128 Z_X depth array; the depth allocation is six 64 KiB slices (the next allocation starts 0x61000 bytes later, too small for a mip tail) and every view uses the same base and extent, so the field has no other level to select. The console was not measured. A depth copy from such a view still throws - [Long Windows pipeline-cache paths](../../../core/libs/prx/libSceAgcDriver/Graphics/src/PipelineCache.cpp) (libSceAgcDriver) - whether retail console filesystem APIs normalize non-canonical or relative cache paths beyond MAX_PATH without truncation remains unmeasured against console diagnostics. On Windows, filesystem journal normalization and shared content readers do not cover non-canonical or relative pipeline cache paths beyond MAX_PATH. +- [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 (`vk_rasterizer.cpp`, `StencilValid`) and KytyPS5 (PS5, `depthRenderTarget.cpp`, `has_stencil`) drop it the same way; fpPS4 sets the clear from the bit alone, but its host depth format then has no stencil aspect to clear. No source states what the hardware does with the bit then; the console was not measured. A read-only stencil plane still throws - [Swept write-only staging](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) (libSceAgcDriver): on a discrete GPU a write-only element whose V# stride is wider than the widest buffer store (16 bytes) and that a direct dispatch sweeps is staged in a device-local shadow. The shadow still takes a copy-in, because the copy-back covers the whole element and the stores may leave part of each record unwritten. A sweep proven to write every byte of the element (from the offsets and widths of its stores within the record) could skip the copy-in, about 10 ms per frame in Diablo II: Resurrected; that proof is not made. Store widths are not recorded per instruction either, so a record of 16 bytes or less stays in place even when its stores are narrower. - [Adaptive staging](../../../core/libs/prx/libSceAgcDriver/Graphics/include/AdaptiveStaging.hpp) (libSceAgcDriver): whether a staged element pays for its two copies is decided by probing the frame GPU time, not from the element's accesses. The probe is measured on one title (PPSA03912, NVIDIA on Linux). It judges by the whole frame's GPU time, so a scene whose GPU load moves by itself can keep the slower mode until the next probe, 20 to 160 s later, and each probe runs a few frames in the slower mode.