From 4d2a8643e00b78989ff7d0027435a94c3641c28d Mon Sep 17 00:00:00 2001 From: Celegans12 <53881228+Celegans12@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:17:36 +0100 Subject: [PATCH] feat(agc): reuse unchanged untracked storage snapshots Reuse exact read-only storage copies when owned proofs and driver write evidence hold. Flush adjusted ranges and preserve fallback memo behavior where native arena write watching is unavailable. Separate storage and draw arm, reuse, refusal and eviction trace counts. Exercise writes, refused proofs, cache eviction and trace loss paths. --- .../Execution/include/PerformanceTrace.hpp | 17 +- .../Execution/src/PerformanceTrace.cpp | 6 + .../Execution/src/PerformanceTraceThread.cpp | 6 + .../Graphics/include/Recorder.hpp | 4 +- .../Graphics/include/RuntimeSwitches.hpp | 1 + .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 2 +- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 43 ++-- .../Graphics/src/RuntimeSwitches.cpp | 2 + .../Graphics/src/ShaderResources.cpp | 19 +- .../tests/PerformanceTrace.cpp | 8 +- .../prx/libSceAgcDriver/tests/Recorder.cpp | 242 ++++++++++++++++++ .../cmake/agc_driver_recorder_tests.cmake | 12 +- docs/dev/ENVIRONMENT.md | 3 +- docs/dev/debt/libSceAgcDriver.md | 5 + tools/tests/test_trace_digest.py | 15 ++ tools/trace_digest.py | 20 +- 16 files changed, 362 insertions(+), 43 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp index 0526a4300a6d..c08bdecc413a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp @@ -344,6 +344,7 @@ struct TraceSummary { std::uint64_t firstPresent = 0; double gpuBusyMs = 0; std::uint64_t ownedDrawUnbound = 0; + std::uint64_t ownedStorageUnbound = 0; std::string trace; std::optional> interval; std::optional host; @@ -693,8 +694,10 @@ class TraceFormat { std::map phases; std::map ownedCounts; std::map graphicsCounts; - bool dropped = summary.ownedDrawUnbound != 0; + std::map storageCounts; + bool dropped = summary.ownedDrawUnbound != 0 || summary.ownedStorageUnbound != 0; if (summary.ownedDrawUnbound != 0) ownedCounts["OwnedDraw.unbound"] = summary.ownedDrawUnbound; + if (summary.ownedStorageUnbound != 0) storageCounts["OwnedStorage.unbound"] = summary.ownedStorageUnbound; struct DroppedThread { std::string name; std::uint64_t eventsLost = 0; @@ -717,6 +720,7 @@ class TraceFormat { if (total.stage == nullptr && std::find(WorkerBusyScopes.begin(), WorkerBusyScopes.end(), scope) != WorkerBusyScopes.end()) busy += total.length; if (total.stage == nullptr && GraphicsTrackScope(scope)) graphicsCounts[std::string(scope)] += total.count; else if (scope.starts_with("OwnedDraw.") && total.stage == nullptr) ownedCounts[std::string(scope)] += total.count; + else if (scope.starts_with("OwnedStorage.") && total.stage == nullptr) storageCounts[std::string(scope)] += total.count; else if (scope != WorkerWaitScope) phases[Name(total.scope, total.stage)] += total.length; } if (!thread.name.starts_with(WorkerPrefix)) continue; @@ -751,6 +755,15 @@ class TraceFormat { output += ':' + std::to_string(value); } output += '}'; + output += ",\"owned_storage_counts\":{"; + firstCount = true; + for (const auto& [name, value] : storageCounts) { + if (!firstCount) output += ','; + firstCount = false; + AppendString(output, name); + output += ':' + std::to_string(value); + } + output += '}'; output += ",\"graphics_track\":{"; bool firstGraphics = true; for (const auto& [name, value] : graphicsCounts) { @@ -936,6 +949,7 @@ class PerformanceTrace { static void CountOwnedDraw(const char* scope, std::uint64_t amount = 1); static std::uint64_t OwnedDrawUnbound(); + static std::uint64_t OwnedStorageUnbound(); static void SetOverlayTotals(bool on); static bool OverlayTotals(); @@ -954,6 +968,7 @@ class PerformanceTrace { static std::atomic recording; static std::atomic ownedDrawUnbound; + static std::atomic ownedStorageUnbound; inline static std::atomic buffering{false}; inline static std::atomic presentCount{0}; static thread_local TraceThread* local; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceTrace.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceTrace.cpp index 1cdc4a161a66..8f7f08cc8d94 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceTrace.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceTrace.cpp @@ -44,12 +44,14 @@ struct Session { bool windowOpen = false; std::vector> windowBase; std::uint64_t windowOwnedUnbound = 0; + std::uint64_t windowStorageUnbound = 0; std::optional interval; bool intervalOpen = false; std::uint64_t intervalFirstPresent = 0; double intervalGpuBusy = 0; std::vector> intervalBase; std::uint64_t intervalOwnedUnbound = 0; + std::uint64_t intervalStorageUnbound = 0; std::vector intervalPresents; Clock::time_point first{}; std::uint64_t present = 0; @@ -269,6 +271,7 @@ void PerformanceTrace::OpenInterval(Clock::time_point now, std::uint64_t present state.intervalFirstPresent = present; state.intervalGpuBusy = VulkanDevice::PresentCounts().gpuBusyMs; state.intervalOwnedUnbound = OwnedDrawUnbound(); + state.intervalStorageUnbound = OwnedStorageUnbound(); state.intervalPresents.assign(1, now); if (summaryWriter()) return; summaryWriter() = std::make_unique([directory = traceDirectory()](std::string_view text) { @@ -298,6 +301,7 @@ void PerformanceTrace::FlushInterval(Clock::time_point now, std::uint32_t width, } auto summary = identity(width, height, device); summary.ownedDrawUnbound = OwnedDrawUnbound() - state.intervalOwnedUnbound; + summary.ownedStorageUnbound = OwnedStorageUnbound() - state.intervalStorageUnbound; summary.window = state.interval->Describe(); summary.firstPresent = state.intervalFirstPresent; summary.gpuBusyMs = VulkanDevice::PresentCounts().gpuBusyMs - state.intervalGpuBusy; @@ -351,6 +355,7 @@ void PerformanceTrace::Present(std::uint32_t width, std::uint32_t height, const state.windowOpen = true; state.windowBase = totalsOf(state.threads); state.windowOwnedUnbound = OwnedDrawUnbound(); + state.windowStorageUnbound = OwnedStorageUnbound(); state.firstPresent = present; state.gpuBusyAtOpen = VulkanDevice::PresentCounts().gpuBusyMs; TraceClockSample clock; @@ -399,6 +404,7 @@ void PerformanceTrace::Present(std::uint32_t width, std::uint32_t height, const const auto process = processId(); auto summary = identity(width, height, device); summary.ownedDrawUnbound = OwnedDrawUnbound() - state.windowOwnedUnbound; + summary.ownedStorageUnbound = OwnedStorageUnbound() - state.windowStorageUnbound; summary.window = state.window->Describe(); summary.firstPresent = state.firstPresent; summary.gpuBusyMs = VulkanDevice::PresentCounts().gpuBusyMs - state.gpuBusyAtOpen; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceTraceThread.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceTraceThread.cpp index d91066bf99b1..640270e8c105 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceTraceThread.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/PerformanceTraceThread.cpp @@ -4,16 +4,22 @@ namespace AgcDriver { std::atomic PerformanceTrace::recording{false}; std::atomic PerformanceTrace::ownedDrawUnbound{0}; +std::atomic PerformanceTrace::ownedStorageUnbound{0}; void PerformanceTrace::CountOwnedDraw(const char* scope, std::uint64_t amount) { if (amount == 0 || !Recording()) return; if (auto* thread = Thread()) thread->Count(scope, amount); + else if (std::string_view(scope).starts_with("OwnedStorage.")) ownedStorageUnbound.fetch_add(1, std::memory_order_relaxed); else ownedDrawUnbound.fetch_add(1, std::memory_order_relaxed); } std::uint64_t PerformanceTrace::OwnedDrawUnbound() { return ownedDrawUnbound.load(std::memory_order_relaxed); } +std::uint64_t PerformanceTrace::OwnedStorageUnbound() { + return ownedStorageUnbound.load(std::memory_order_relaxed); +} + thread_local TraceThread* PerformanceTrace::local = nullptr; thread_local const char* PerformanceTrace::localName = nullptr; std::atomic PerformanceTrace::binder{nullptr}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index c00de07e1be2..751e19f7b9b4 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -238,7 +238,7 @@ class Recorder { std::uint64_t note = 0; }; std::size_t OwnedDrawInputEntries() const { return ownedDrawInputs; } - OwnedDrawInputProof ArmOwnedDrawInput(std::uint64_t address, std::size_t bytes) const; + OwnedDrawInputProof ArmOwnedDrawInput(std::uint64_t address, std::size_t bytes, SnapshotUse use) const; std::shared_ptr ReusableOwnedDrawInput(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived, std::size_t from = 0, std::uint32_t* lowest = nullptr); void KeepOwnedDrawInput(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof, std::shared_ptr buffer, SnapshotUse use, std::uint32_t derived, std::size_t from = 0, std::uint32_t lowest = 0); static constexpr std::size_t ContainingSnapshotProbes = 16; @@ -1100,7 +1100,7 @@ class Recorder { }; std::map indexRanges; std::list indexRangeRecency; - bool ownedDrawInputHolds(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof) const; + bool ownedDrawInputHolds(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof, SnapshotUse use) const; bool refreshDrawSnapshot(DrawSnapshot& entry, std::uint64_t address, std::size_t bytes); std::shared_ptr containingDrawSnapshot(std::uint64_t address, std::size_t bytes, VkDeviceSize* offset); mutable std::weak_ptr publishedWriteRanges; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp index ae08b75a0661..5aacb39d738a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp @@ -17,6 +17,7 @@ enum class RuntimeSwitch : std::size_t { NoSizeOnlySurfaceBytes, PipelineDispatchMisses, NoExtendedFastProofs, + NoOwnedDrawSnapshots, Count, }; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index a964781ea650..bb923abd009a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -1490,7 +1490,7 @@ DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uin copy.registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); copy.generation = GuestMemory::CollectWrites(address, bytes); if (copy.generation != 0) copy.buffer = recorder->ReusableDrawSnapshot(address, bytes, use, ©.derived, 0, nullptr, from, ©.lowest); - else if (owned) copy.owned = recorder->ArmOwnedDrawInput(address, bytes); + else if (owned) copy.owned = recorder->ArmOwnedDrawInput(address, bytes, use); if (copy.buffer != nullptr) { copy.reused = true; return copy; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 700e7a2287c0..b01407daab05 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -3635,7 +3635,7 @@ std::shared_ptr Recorder::containingDrawSnapshot(std::uint64_t address, for (std::size_t probe = 0; probe < ContainingSnapshotProbes && entry != drawSnapshots.begin(); ++probe) { --entry; const auto& [start, use, held] = entry->first; - if (use != SnapshotUse::Storage || start + held < address + bytes || (address - start) % alignment != 0) continue; + if (use != SnapshotUse::Storage || !entry->second.owned.words.empty() || start + held < address + bytes || (address - start) % alignment != 0) continue; if (entry->second.registryGeneration != registry || !GuestMemory::UnchangedSince(address, bytes, entry->second.generation)) continue; auto& recency = drawSnapshotPools[SnapshotPool(use)].recency; recency.splice(recency.end(), recency, entry->second.recent); @@ -3710,8 +3710,11 @@ void Recorder::KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::u } while (!pool.recency.empty() && (pool.bytes + bytes > budget || pool.recency.size() >= maxEntries)) { const auto victim = drawSnapshots.find(pool.recency.front()); - if (!storage) { - const bool ownedVictim = !victim->second.owned.words.empty(); + const bool ownedVictim = !victim->second.owned.words.empty(); + if (storage) { + OwnedDrawTraceCount(ownedVictim ? "OwnedStorage.evicted_owned" : "OwnedStorage.evicted_other"); + if (ownedInsertion) OwnedDrawTraceCount(ownedVictim ? "OwnedStorage.evicted_owned_by_owned" : "OwnedStorage.evicted_other_by_owned"); + } else { OwnedDrawTraceCount(ownedVictim ? "OwnedDraw.evicted_owned" : "OwnedDraw.evicted_other"); if (ownedInsertion) OwnedDrawTraceCount(ownedVictim ? "OwnedDraw.evicted_owned_by_owned" : "OwnedDraw.evicted_other_by_owned"); } @@ -3728,18 +3731,18 @@ void Recorder::KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::u pool.bytes += bytes; } -Recorder::OwnedDrawInputProof Recorder::ArmOwnedDrawInput(std::uint64_t address, std::size_t bytes) const { +Recorder::OwnedDrawInputProof Recorder::ArmOwnedDrawInput(std::uint64_t address, std::size_t bytes, SnapshotUse use) const { GuestMemory::AssertGpuLockHeld("arm owned draw input"); - OwnedDrawTraceCount("OwnedDraw.arm_attempt"); + OwnedDrawTraceCount(use == SnapshotUse::Storage ? "OwnedStorage.arm_attempt" : "OwnedDraw.arm_attempt"); if (bytes == 0 || bytes > DrawInputBudget || bytes > std::numeric_limits::max() - address || !GuestMemory::WriteWatched() || PendingWriteOverlaps(address, bytes)) { - OwnedDrawTraceCount("OwnedDraw.arm_refused"); + OwnedDrawTraceCount(use == SnapshotUse::Storage ? "OwnedStorage.arm_refused" : "OwnedDraw.arm_refused"); return {}; } OwnedDrawInputProof proof; proof.words.resize((address + bytes - 1) / 65536 - address / 65536 + 1); - OwnedDrawTraceCount("OwnedDraw.arm_blocks_requested", proof.words.size()); + OwnedDrawTraceCount(use == SnapshotUse::Storage ? "OwnedStorage.arm_blocks_requested" : "OwnedDraw.arm_blocks_requested", proof.words.size()); if (!GuestArena::GuestArenaArmOwned_nid_no_patch(static_cast(address), bytes, proof.words.data(), proof.words.size(), 1)) { - OwnedDrawTraceCount("OwnedDraw.arm_refused"); + OwnedDrawTraceCount(use == SnapshotUse::Storage ? "OwnedStorage.arm_refused" : "OwnedDraw.arm_refused"); return {}; } proof.registry = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); @@ -3747,31 +3750,30 @@ Recorder::OwnedDrawInputProof Recorder::ArmOwnedDrawInput(std::uint64_t address, proof.since = GuestMemory::TrackerGeneration(); proof.note = NewestWriteNote(address, bytes); if (proof.since == 0 || (proof.forget & 1u) != 0) { - OwnedDrawTraceCount("OwnedDraw.arm_refused"); + OwnedDrawTraceCount(use == SnapshotUse::Storage ? "OwnedStorage.arm_refused" : "OwnedDraw.arm_refused"); return {}; } - OwnedDrawTraceCount("OwnedDraw.arm_success"); + OwnedDrawTraceCount(use == SnapshotUse::Storage ? "OwnedStorage.arm_success" : "OwnedDraw.arm_success"); return proof; } -bool Recorder::ownedDrawInputHolds(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof) const { +bool Recorder::ownedDrawInputHolds(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof, SnapshotUse use) const { GuestMemory::AssertGpuLockHeld("check owned draw input"); - OwnedDrawTraceCount("OwnedDraw.proof_check"); + OwnedDrawTraceCount(use == SnapshotUse::Storage ? "OwnedStorage.proof_check" : "OwnedDraw.proof_check"); if (proof.words.empty() || proof.since == 0 || (proof.forget & 1u) != 0 || !GuestMemory::WriteWatched()) return false; if (proof.registry != GuestAllocations::GuestAllocationsGeneration_nid_postfix() || proof.forget != GuestMemory::ForgetSerial()) return false; if (PendingWriteOverlaps(address, bytes) || proof.note != NewestWriteNote(address, bytes) || GuestMemory::NewestStamp(address, bytes) > proof.since) return false; - OwnedDrawTraceCount("OwnedDraw.arena_check"); - OwnedDrawTraceCount("OwnedDraw.check_blocks_requested", proof.words.size()); + OwnedDrawTraceCount(use == SnapshotUse::Storage ? "OwnedStorage.arena_check" : "OwnedDraw.arena_check"); + OwnedDrawTraceCount(use == SnapshotUse::Storage ? "OwnedStorage.check_blocks_requested" : "OwnedDraw.check_blocks_requested", proof.words.size()); return GuestArena::GuestArenaOwnedUnchanged_nid_no_patch(static_cast(address), bytes, proof.words.data(), proof.words.size()); } std::shared_ptr Recorder::ReusableOwnedDrawInput(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived, std::size_t from, std::uint32_t* lowest) { GuestMemory::AssertGpuLockHeld("reuse owned draw input"); - Require(use != SnapshotUse::Storage, "an owned draw input is a vertex or index buffer"); const auto found = drawSnapshots.find({address, use, bytes}); if (found == drawSnapshots.end() || found->second.owned.words.empty() || found->second.from > from) return {}; - if (!ownedDrawInputHolds(address, bytes, found->second.owned)) { - OwnedDrawTraceCount("OwnedDraw.invalidated"); + if (!ownedDrawInputHolds(address, bytes, found->second.owned, use)) { + OwnedDrawTraceCount(use == SnapshotUse::Storage ? "OwnedStorage.invalidated" : "OwnedDraw.invalidated"); eraseDrawSnapshot(found); return {}; } @@ -3779,7 +3781,7 @@ std::shared_ptr Recorder::ReusableOwnedDrawInput(std::uint64_t address, if (verify) { const auto held = found->second.from; const bool equal = GuestMemory::EqualsCommittedUnsynced(address + held, found->second.buffer->Bytes().subspan(held)); - if (!ownedDrawInputHolds(address, bytes, found->second.owned)) { + if (!ownedDrawInputHolds(address, bytes, found->second.owned, use)) { eraseDrawSnapshot(found); return {}; } @@ -3789,13 +3791,12 @@ std::shared_ptr Recorder::ReusableOwnedDrawInput(std::uint64_t address, recency.splice(recency.end(), recency, found->second.recent); if (derived != nullptr) *derived = found->second.derived; if (lowest != nullptr) *lowest = found->second.lowest; - OwnedDrawTraceCount("OwnedDraw.reused"); + OwnedDrawTraceCount(use == SnapshotUse::Storage ? "OwnedStorage.reused" : "OwnedDraw.reused"); return found->second.buffer; } void Recorder::KeepOwnedDrawInput(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof, std::shared_ptr buffer, SnapshotUse use, std::uint32_t derived, std::size_t from, std::uint32_t lowest) { - Require(use != SnapshotUse::Storage, "an owned draw input is a vertex or index buffer"); - if (buffer == nullptr || buffer->Bytes().size() != bytes || !ownedDrawInputHolds(address, bytes, proof)) return; + if (buffer == nullptr || buffer->Bytes().size() != bytes || !ownedDrawInputHolds(address, bytes, proof, use)) return; auto kept = proof; KeepDrawSnapshot(address, bytes, proof.since, proof.registry, std::move(buffer), use, derived, from, lowest, true); if (const auto found = drawSnapshots.find({address, use, bytes}); found != drawSnapshots.end()) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp index 5b462f7f9278..42d4931c2aac 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp @@ -23,6 +23,7 @@ constexpr std::array SwitchNames{ "APS5_NO_SIZE_ONLY_SURFACE_BYTES", "APS5_PIPELINE_DISPATCH_MISSES", "APS5_NO_EXTENDED_FAST_PROOFS", + "APS5_NO_OWNED_DRAW_SNAPSHOTS", }; struct SwitchValues { @@ -35,6 +36,7 @@ struct SwitchValues { std::getenv("APS5_NO_SIZE_ONLY_SURFACE_BYTES") != nullptr, std::getenv("APS5_PIPELINE_DISPATCH_MISSES") != nullptr, std::getenv("APS5_NO_EXTENDED_FAST_PROOFS") != nullptr, + std::getenv("APS5_NO_OWNED_DRAW_SNAPSHOTS") != nullptr, }; for (std::size_t index = 0; index < SwitchCount; ++index) set[index].store(environment[index], std::memory_order_relaxed); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 9e9ecac72a11..19c44936e74d 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Execution/include/ThreadScratch.hpp" #include "ThreadOwned.hpp" #include "prx/libc/include/HostThreadLocal.hpp" +#include "prx/libc/include/GuestArena.hpp" #include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" @@ -14,6 +15,7 @@ #include "prx/libSceAgcDriver/Graphics/include/MemoryAccounting.hpp" #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp" #include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" #include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp" #include @@ -7129,15 +7131,22 @@ std::shared_ptr ShaderResources::PrepareDrawBindi const auto begin = address - item.adjustment; const auto bytes = static_cast(GuestBufferMemory::ViewBytes(size, item.adjustment)); if (override == moved.end() && (bytes > maxSnapshotBytes || totalSnapshotBytes + bytes > maxSnapshotBytes)) continue; + const bool owned = !usesBda && override == moved.end() && bytes > uploadLimit && !RuntimeSwitches::Set(RuntimeSwitch::NoOwnedDrawSnapshots) && GuestArena::GuestArenaWriteWatched_nid_postfix() && !GuestMemory::Watched(begin, bytes); + if (owned) { + if (guestMemory.WritesOverlap(begin, bytes)) continue; + GuestMemory::FlushGpuWrites(begin, bytes); + stamped = false; + if (recorder.PendingWriteOverlaps(begin, bytes)) continue; + } const auto registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); if (!stamped) { stamp = {GuestMemory::TrackerGeneration(), GuestMemory::CollectEpoch(), registryGeneration}; stamped = true; } VkDeviceSize offset = 0; - auto buffer = recorder.UnwrittenDrawSnapshot(begin, bytes, stamp, &offset); + auto buffer = owned ? recorder.ReusableOwnedDrawInput(begin, bytes, Recorder::SnapshotUse::Storage, nullptr) : recorder.UnwrittenDrawSnapshot(begin, bytes, stamp, &offset); static const bool verifySnapshots = std::getenv("APS5_VERIFY_DRAW_SNAPSHOTS") != nullptr; - if (verifySnapshots && buffer != nullptr) { + if (verifySnapshots && !owned && buffer != nullptr) { static std::atomic checked{0}, differing{0}; const auto fast = buffer->Bytes().subspan(static_cast(offset), bytes); VkDeviceSize slowOffset = 0; @@ -7157,13 +7166,15 @@ std::shared_ptr ShaderResources::PrepareDrawBindi const auto generation = GuestMemory::CollectWrites(begin, bytes); buffer = recorder.ReusableDrawSnapshot(begin, bytes, Recorder::SnapshotUse::Storage, nullptr, generation, &offset); if (buffer == nullptr) { + const auto proof = owned && generation == 0 ? recorder.ArmOwnedDrawInput(begin, bytes, Recorder::SnapshotUse::Storage) : Recorder::OwnedDrawInputProof{}; buffer = std::make_shared(context, bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); std::memcpy(buffer->Bytes().data(), reinterpret_cast(begin), bytes); - recorder.KeepDrawSnapshot(begin, bytes, generation, registryGeneration, buffer); + if (owned && generation == 0) recorder.KeepOwnedDrawInput(begin, bytes, proof, buffer, Recorder::SnapshotUse::Storage, 0); + else recorder.KeepDrawSnapshot(begin, bytes, generation, registryGeneration, buffer); } } if (GuestMemory::TrackerGeneration() != stamp[0]) stamped = false; - else if (!uploaded || stamp[1] != 0) recorder.NoteUnwrittenDrawSnapshot(begin, bytes, stamp, buffer, offset); + else if (!owned && (!uploaded || stamp[1] != 0)) recorder.NoteUnwrittenDrawSnapshot(begin, bytes, stamp, buffer, offset); } selected.push_back(index); keep({begin, std::move(buffer), offset, bytes}); diff --git a/core/libs/prx/libSceAgcDriver/tests/PerformanceTrace.cpp b/core/libs/prx/libSceAgcDriver/tests/PerformanceTrace.cpp index c9ef5fe8b038..32afa70e07e8 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PerformanceTrace.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PerformanceTrace.cpp @@ -355,19 +355,21 @@ void SummaryFields() { "\"worker_busy_pct\":{\"queue worker 0x0\":35.000}," "\"phase_totals_ms\":{\"Driver.Completion\":2.000,\"Driver.Packet\":12.000,\"Driver.Packet.draw\":10.000,\"Driver.Present\":6.000,\"Driver.Present.inflight_wait\":4.000}," "\"top_phases_ms_per_frame\":{\"Driver.Packet\":6.000,\"Driver.Packet.draw\":5.000,\"Driver.Present\":3.000,\"Driver.Present.inflight_wait\":2.000,\"Driver.Completion\":1.000}," - "\"owned_draw_counts\":{},\"graphics_track\":{},\"trace_dropped\":false,\"trace\":\"aps5-trace-abc-7.json.gz\"}\n"; + "\"owned_draw_counts\":{},\"owned_storage_counts\":{},\"graphics_track\":{},\"trace_dropped\":false,\"trace\":\"aps5-trace-abc-7.json.gz\"}\n"; Check(line == expected, "summary line changed"); auto unboundSummary = summary; unboundSummary.ownedDrawUnbound = 3; const auto unboundLine = TraceFormat::Summary(unboundSummary, threads, presents); - Check(unboundLine.find("\"owned_draw_counts\":{\"OwnedDraw.unbound\":3},\"graphics_track\":{},\"trace_dropped\":true") != std::string::npos, "unbound draw counts were not marked as incomplete"); + Check(unboundLine.find("\"owned_draw_counts\":{\"OwnedDraw.unbound\":3},\"owned_storage_counts\":{},\"graphics_track\":{},\"trace_dropped\":true") != std::string::npos, "unbound draw counts were not marked as incomplete"); auto counted = threads; counted[0].totals.push_back({"OwnedDraw.arm_attempt", nullptr, {}, 5}); counted[1].totals.push_back({"OwnedDraw.arm_attempt", nullptr, {}, 3}); counted[1].totals.push_back({"OwnedDraw.reused", nullptr, {}, 2}); counted[0].totals.push_back({"OwnedDraw.arm_blocks_requested", nullptr, {}, 17}); + counted[0].totals.push_back({"OwnedStorage.reused", nullptr, {}, 4}); const auto countedLine = TraceFormat::Summary(summary, counted, presents); Check(countedLine.find("\"owned_draw_counts\":{\"OwnedDraw.arm_attempt\":8,\"OwnedDraw.arm_blocks_requested\":17,\"OwnedDraw.reused\":2}") != std::string::npos, "named owned counts were not summed across threads"); + Check(countedLine.find("\"owned_storage_counts\":{\"OwnedStorage.reused\":4}") != std::string::npos, "storage counts were not separated from draw counts"); counted[0].totals.push_back({"Graphics.Barrier.draw", nullptr, {}, 4}); counted[1].totals.push_back({"Graphics.Barrier.draw", nullptr, {}, 3}); counted[1].totals.push_back({"Graphics.Copy.bytes", nullptr, {}, 65536}); @@ -502,7 +504,7 @@ void IntervalSummaryFields() { "\"worker_busy_pct\":{\"queue worker 0x0\":30.000}," "\"phase_totals_ms\":{\"Driver.Packet\":12.000}," "\"top_phases_ms_per_frame\":{\"Driver.Packet\":6.000}," - "\"owned_draw_counts\":{},\"graphics_track\":{},\"trace_dropped\":false,\"trace\":\"\"}\n"; + "\"owned_draw_counts\":{},\"owned_storage_counts\":{},\"graphics_track\":{},\"trace_dropped\":false,\"trace\":\"\"}\n"; Check(line == expected, "interval summary line changed"); } diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index 20b876fed86a..1c556e917f16 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -5972,6 +5972,218 @@ void vertexWindowSeriesTests(const Device& device, Recorder& recorder) { Require(!stored.reused && std::memcmp(stored.buffer->Bytes().data() + bytes - quad, reinterpret_cast(address + bytes - quad), quad) == 0, "a store in the vertex window that served the falling draws was not seen"); } +void ownedStorageSnapshotTests(const Device& device, Recorder& recorder) { + using namespace AgcDriver::GuestMemory; + constexpr std::size_t bytes = 4 * 65536; + constexpr std::size_t copyBytes = 65536; + auto context = device.GetContext(); + Require(context.hostImportAlignment != 0 && context.hostImportAlignment <= 65536, "owned storage tests need host imports aligned within 64 KiB"); +#ifdef _WIN32 + void* block = AllocateWatched(bytes, 65536); + constexpr bool reusable = true; +#else + void* block = std::aligned_alloc(65536, bytes); + constexpr bool reusable = false; +#endif + Require(block != nullptr, "cannot allocate the owned storage fixture"); + struct Release { + void* block; + ~Release() { +#ifdef _WIN32 + ReleaseWatched(block, bytes); +#else + std::free(block); +#endif + } + } release{block}; + std::memset(block, 0x31, bytes); + const auto address = reinterpret_cast(block); + const auto begin = address + 65536; + const auto element = begin + 1; + { + GuestAllocations::Mutation mutation; + mutation.Add(block, bytes, true, true, true); + } + struct Unregister { + const Context& context; + void* block; + ~Unregister() { + { + GuestAllocations::Mutation mutation; + mutation.Remove(block); + } + HostImportFor(context, reinterpret_cast(block), bytes); + } + } unregister{context, block}; + Require(HostImportFor(context, address, bytes) != nullptr, "the owned storage fixture was not imported"); + ShaderRecompiler::RecompileResult program; + program.pushConstants.resize(4); + 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(element), static_cast(element >> 32u) & 0xffffu, static_cast(copyBytes - 1), 0x31000000u}; + binding.bufferWritten = {false}; + program.bindings.push_back(binding); + const CompiledShader shader{ShaderRecompiler::ShaderStage::Compute, &program, 0}; + DescriptorCache cache(context); + context.descriptorCache = &cache; + Recorder snapshots(context); + snapshots.Activate(); + { + ShaderResources resources(context, shader); + Unwatch(address, bytes); + Require(!Watched(begin, copyBytes), "the owned storage fixture is tracked"); + const auto draw = [&] { + const auto bindings = resources.PrepareDrawBindings(snapshots); + Require(bindings != nullptr && bindings->snapshots.size() == 1, "the ordinary read-only storage input was not snapshotted"); + const auto& snapshot = bindings->snapshots.front(); + const auto contents = snapshot.Bytes(); + Require(contents.size() == copyBytes && std::memcmp(contents.data(), reinterpret_cast(begin), copyBytes) == 0, "the storage snapshot has stale or incorrectly adjusted bytes"); + return snapshot.buffer; + }; + BumpCollectEpoch(); + const auto first = draw(); + BumpCollectEpoch(); + const auto second = draw(); + Require((second == first) == reusable, "an unchanged untracked storage input was copied again"); + if (!reusable) Require(draw() == second, "a host without native owned proofs lost its epoch memo"); + auto* guest = reinterpret_cast(begin); + guest[128] ^= 0xffu; + if (!reusable) BumpCollectEpoch(); + const auto cpu = draw(); + Require(cpu != second, "the epoch memo hid a CPU store from the owned storage proof"); + guest[0] ^= 0xffu; + if (!reusable) BumpCollectEpoch(); + const auto prefix = draw(); + Require(prefix != cpu, "the owned storage proof omitted its adjusted prefix"); + guest[copyBytes - 1] ^= 0xffu; + if (!reusable) BumpCollectEpoch(); + const auto tail = draw(); + Require(tail != prefix, "the owned storage proof omitted its final copied byte"); + MarkWritten(begin + 256, 4); + const auto gpu = draw(); + Require(gpu != tail, "an owned storage input outlived an untracked GPU stamp"); + MarkPossiblyWritten(begin + 512, 4); + Require(draw() != gpu, "an owned storage input outlived a possible GPU store"); +#ifdef _WIN32 + const auto beforePrefixWrite = draw(); + snapshots.OnComplete([guest] { guest[0] ^= 0x5au; }); + snapshots.NotePendingWrite(begin, 1); + const auto afterPrefixWrite = draw(); + Require(afterPrefixWrite != beforePrefixWrite && !snapshots.PendingWriteOverlaps(begin, 1), "a pending writer in the adjusted prefix was not flushed"); +#endif + snapshots.NotePendingWrite(element + 1024, 4); + Require(resources.PrepareDrawBindings(snapshots) == nullptr, "a pending writer was replaced by a CPU storage snapshot"); + snapshots.Sync(); +#ifdef _WIN32 + const auto beforeCollect = draw(); + std::array pages{}; + auto count = pages.size(); + Require(GuestArena::GuestArenaCollectWrites_nid_postfix(begin, copyBytes, pages.data(), &count, true), "the storage clearing collect failed"); + Require(draw() != beforeCollect, "a clearing collect left an owned storage snapshot reusable"); + const auto beforeProtection = draw(); + GuestArena::GuestArenaSetProtection_nid_postfix(begin, copyBytes, PAGE_READWRITE); + Require(draw() != beforeProtection, "a protection notification left an owned storage snapshot reusable"); + GuestArena::GuestArenaPinWritable_nid_postfix(reinterpret_cast(begin), copyBytes); + const auto pinned = draw(); + const auto pinnedAgain = draw(); + Require(pinnedAgain != pinned, "an unchanged input with a refused owned proof unexpectedly reused its old snapshot"); + guest[16] ^= 0xffu; + Require(draw() != pinnedAgain, "a refused owned arm fell back to the stale epoch memo"); + GuestArena::GuestArenaUnpinWritable_nid_postfix(reinterpret_cast(begin), copyBytes); +#endif + const auto beforeRegistry = draw(); + alignas(64) static std::byte other[64]; + { + GuestAllocations::Mutation mutation; + mutation.Add(other, sizeof(other), true, true, true); + } + { + GuestAllocations::Mutation mutation; + mutation.Remove(other); + } + Require(draw() != beforeRegistry, "an owned storage input outlived a registry mutation"); + if (const auto disabled = RuntimeSwitches::Find("APS5_NO_OWNED_DRAW_SNAPSHOTS"); disabled.has_value()) { + RuntimeSwitches::Assign(*disabled, true); + BumpCollectEpoch(); + const auto off = draw(); + BumpCollectEpoch(); + Require(draw() != off, "disabled owned storage snapshots still reused an untracked copy"); + RuntimeSwitches::Assign(*disabled, false); + } + snapshots.Sync(); + } +#ifdef _WIN32 + { + auto mixed = program; + auto& shared = mixed.bindings.front(); + shared.count = 3; + shared.guestDescriptor.clear(); + for (const auto [start, length] : {std::pair{address, std::size_t{256}}, std::pair{element, copyBytes - 1}, std::pair{address + 2 * copyBytes, std::size_t{256}}}) { + const std::array descriptor{static_cast(start), static_cast(start >> 32u) & 0xffffu, static_cast(length), 0x31000000u}; + shared.guestDescriptor.insert(shared.guestDescriptor.end(), descriptor.begin(), descriptor.end()); + } + shared.bufferWritten = {false, false, false}; + const CompiledShader threeBuffers{ShaderRecompiler::ShaderStage::Compute, &mixed, 0}; + ShaderResources resources(context, threeBuffers); + Unwatch(address, bytes); + BumpCollectEpoch(); + const auto first = resources.PrepareDrawBindings(snapshots); + Require(first != nullptr && first->snapshots.size() == 3, "the mixed storage fixture did not select all three buffers"); + const auto last = address + 2 * copyBytes; + snapshots.OnComplete([last] { + reinterpret_cast(last)[0] ^= 0x5au; + MarkWritten(last, 1); + }); + snapshots.NotePendingWrite(begin, 1); + const auto second = resources.PrepareDrawBindings(snapshots); + Require(second != nullptr && second->snapshots.size() == 3 && !snapshots.PendingWriteOverlaps(begin, 1), "the mixed storage fixture did not flush its adjusted prefix"); + Require(second->snapshots[1].buffer == first->snapshots[1].buffer, "the disjoint completion prevented the middle owned storage hit"); + const auto after = second->snapshots[2].Bytes(); + Require(after.size() == 256 && std::memcmp(after.data(), reinterpret_cast(last), after.size()) == 0, "an owned storage flush left a later epoch memo on an old tracker stamp"); + snapshots.Sync(); + } + { + auto overlapping = program; + auto& shared = overlapping.bindings.front(); + shared.count = 2; + const std::array prefix{static_cast(begin), static_cast(begin >> 32u) & 0xffffu, 1, 0x31000000u}; + shared.guestDescriptor.insert(shared.guestDescriptor.end(), prefix.begin(), prefix.end()); + shared.bufferWritten.push_back(true); + const CompiledShader writesPrefix{ShaderRecompiler::ShaderStage::Compute, &overlapping, 0}; + ShaderResources resources(context, writesPrefix); + Unwatch(address, bytes); + Require(resources.PrepareDrawBindings(snapshots) == nullptr, "a storage snapshot included another writable binding in its adjusted prefix"); + } + const std::array ranges{std::pair{address, address + bytes}}; + Rewatch(ranges); + Require(Watched(begin, copyBytes), "the containing-range fixture did not become tracked"); + const auto proof = snapshots.ArmOwnedDrawInput(begin, copyBytes, Recorder::SnapshotUse::Storage); + Require(!proof.words.empty(), "the containing-range fixture refused its owned proof"); + auto held = std::make_shared(context, copyBytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); + std::memcpy(held->Bytes().data(), reinterpret_cast(begin), copyBytes); + snapshots.KeepOwnedDrawInput(begin, copyBytes, proof, held, Recorder::SnapshotUse::Storage, 0); + const auto offset = std::max(context.limits.minStorageBufferOffsetAlignment, 4); + reinterpret_cast(begin)[offset] ^= 0xffu; + VkDeviceSize selectedOffset = 0; + Require(snapshots.ReusableDrawSnapshot(begin + offset, copyBytes / 2, Recorder::SnapshotUse::Storage, nullptr, proof.since, &selectedOffset) == nullptr, "a containing-range lookup bypassed an owned storage proof"); + if (std::getenv("TEST_OWNED_STORAGE_EVICT") != nullptr) { + constexpr std::uint64_t fakeBase = 0x2000000000ull; + for (std::size_t i = 0; i < Recorder::DrawSnapshotEntries; ++i) + snapshots.KeepDrawSnapshot(fakeBase + i * 65536, copyBytes, 1, 1, held, Recorder::SnapshotUse::Storage); + const auto fresh = snapshots.ArmOwnedDrawInput(begin, copyBytes, Recorder::SnapshotUse::Storage); + Require(!fresh.words.empty(), "storage eviction fixture could not arm its input"); + std::memcpy(held->Bytes().data(), reinterpret_cast(begin), copyBytes); + snapshots.KeepOwnedDrawInput(begin, copyBytes, fresh, held, Recorder::SnapshotUse::Storage, 0); + } +#endif + snapshots.Sync(); + recorder.Activate(); +} + void ownedDrawInputTests(const Device& device, Recorder& recorder) { using namespace AgcDriver::GuestMemory; using Use = Recorder::SnapshotUse; @@ -16851,6 +17063,36 @@ int main(int argc, char** argv) { std::cout << "DCC keys under unit shadows tests passed\n"; return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--owned-storage-snapshots-only") { + const bool traceOwned = std::getenv("TEST_OWNED_STORAGE_TRACE") != nullptr; + if (traceOwned) AgcDriver::PerformanceTrace::Present(1, 1, nullptr); + ownedStorageSnapshotTests(device, recorder); + if (traceOwned) { +#ifdef _WIN32 + const auto threads = AgcDriver::PerformanceTrace::ThreadTotals(); + Require(threads.has_value(), "cannot collect owned storage trace totals"); + std::map counts; + for (const auto& thread : *threads) for (const auto& total : thread.totals) { + if (std::string_view(total.scope).starts_with("OwnedStorage.") || std::string_view(total.scope).starts_with("OwnedDraw.")) counts[total.scope] += total.count; + } + Require(counts["OwnedStorage.arm_attempt"] == counts["OwnedStorage.arm_success"] + counts["OwnedStorage.arm_refused"] && counts["OwnedStorage.arm_refused"] != 0 && counts["OwnedStorage.arm_success"] != 0 && counts["OwnedStorage.reused"] != 0 && counts["OwnedStorage.invalidated"] != 0, "owned storage trace missed decisions"); + Require(counts["OwnedStorage.proof_check"] >= counts["OwnedStorage.arena_check"] && counts["OwnedStorage.arena_check"] != 0 && counts["OwnedStorage.check_blocks_requested"] >= counts["OwnedStorage.arena_check"] && counts["OwnedStorage.arm_blocks_requested"] >= counts["OwnedStorage.arm_success"], "owned storage trace missed proof or block counts"); + Require(counts["OwnedDraw.arm_attempt"] == 0 && counts["OwnedDraw.reused"] == 0 && counts["OwnedDraw.proof_check"] == 0 && counts["OwnedDraw.arena_check"] == 0 && counts["OwnedDraw.arm_blocks_requested"] == 0 && counts["OwnedDraw.check_blocks_requested"] == 0, "storage decisions were counted as draw inputs"); + if (std::getenv("TEST_OWNED_STORAGE_EVICT") != nullptr) Require(counts["OwnedStorage.evicted_other"] != 0 && counts["OwnedStorage.evicted_other_by_owned"] != 0, "owned storage insertion did not count its non-owned eviction"); +#endif + if (std::getenv("TEST_OWNED_STORAGE_UNBOUND") != nullptr) { + const auto beforeStorage = AgcDriver::PerformanceTrace::OwnedStorageUnbound(); + const auto beforeDraw = AgcDriver::PerformanceTrace::OwnedDrawUnbound(); + std::thread unbound([] { AgcDriver::PerformanceTrace::CountOwnedDraw("OwnedStorage.test_unbound"); }); + unbound.join(); + Require(AgcDriver::PerformanceTrace::OwnedStorageUnbound() == beforeStorage + 1 && AgcDriver::PerformanceTrace::OwnedDrawUnbound() == beforeDraw, "unbound storage event was lost or counted as draw"); + } + AgcDriver::PerformanceTrace::Present(1, 1, nullptr); + AgcDriver::PerformanceTrace::StopOutput(); + } + std::cout << "Owned storage snapshot tests passed\n"; + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--owned-draw-inputs-only") { const bool traceOwned = std::getenv("TEST_OWNED_TRACE") != nullptr; if (traceOwned) AgcDriver::PerformanceTrace::Present(1, 1, nullptr); 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 bea9a8b6cda7..8c9f99dd5e4d 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 @@ -435,6 +435,16 @@ if(BUILD_TESTING) set_tests_properties(agc_multisample_guest_access PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME agc_repeat_storage_guard COMMAND agc_driver_recorder_tests --repeat-storage-guard-only) set_tests_properties(agc_repeat_storage_guard PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME agc_owned_storage_snapshots COMMAND agc_driver_recorder_tests --owned-storage-snapshots-only) + add_test(NAME agc_owned_storage_snapshots_verify COMMAND agc_driver_recorder_tests --owned-storage-snapshots-only) + add_test(NAME agc_owned_storage_snapshots_trace COMMAND agc_driver_recorder_tests --owned-storage-snapshots-only) + add_test(NAME agc_owned_storage_snapshots_trace_unbound COMMAND agc_driver_recorder_tests --owned-storage-snapshots-only) + add_test(NAME agc_owned_storage_snapshots_trace_eviction COMMAND agc_driver_recorder_tests --owned-storage-snapshots-only) + set_tests_properties(agc_owned_storage_snapshots_trace_unbound PROPERTIES ENVIRONMENT "TEST_OWNED_STORAGE_TRACE=1;TEST_OWNED_STORAGE_UNBOUND=1;APS5_TRACE_FRAMES=0:1;APS5_TRACE_DIR=${CMAKE_CURRENT_BINARY_DIR}/owned-storage-trace-unbound-test") + set_tests_properties(agc_owned_storage_snapshots_trace_eviction PROPERTIES ENVIRONMENT "TEST_OWNED_STORAGE_TRACE=1;TEST_OWNED_STORAGE_EVICT=1;APS5_TRACE_FRAMES=0:1;APS5_TRACE_DIR=${CMAKE_CURRENT_BINARY_DIR}/owned-storage-trace-eviction-test") + set_tests_properties(agc_owned_storage_snapshots_trace PROPERTIES ENVIRONMENT "TEST_OWNED_STORAGE_TRACE=1;APS5_TRACE_FRAMES=0:1;APS5_TRACE_DIR=${CMAKE_CURRENT_BINARY_DIR}/owned-storage-trace-test") + set_tests_properties(agc_owned_storage_snapshots agc_owned_storage_snapshots_verify agc_owned_storage_snapshots_trace agc_owned_storage_snapshots_trace_unbound agc_owned_storage_snapshots_trace_eviction PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + set_tests_properties(agc_owned_storage_snapshots_verify PROPERTIES ENVIRONMENT "APS5_VERIFY_OWNED_DRAW_INPUTS=1") add_test(NAME agc_owned_draw_inputs COMMAND agc_driver_recorder_tests --owned-draw-inputs-only) add_test(NAME agc_owned_draw_inputs_verify COMMAND agc_driver_recorder_tests --owned-draw-inputs-only) add_test(NAME agc_owned_draw_inputs_trace COMMAND agc_driver_recorder_tests --owned-draw-inputs-only) @@ -467,7 +477,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_recorder_stored_bytes 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_untracked_forget agc_draw_snapshot_epoch agc_multisample_guest_access agc_repeat_storage_guard agc_owned_draw_inputs agc_owned_draw_inputs_verify agc_owned_draw_inputs_trace agc_owned_draw_inputs_trace_unbound agc_owned_draw_inputs_trace_eviction agc_draw_inputs_in_place agc_draw_inputs_copied agc_draw_input_reuse agc_resident_present agc_slice_dirty agc_queued_write_groups agc_metadata_pass agc_tiled_resolve agc_changed_copy agc_bound_changed_copy PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(agc_recorder_read_list agc_recorder_stored_bytes 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_untracked_forget agc_draw_snapshot_epoch agc_multisample_guest_access agc_repeat_storage_guard agc_owned_storage_snapshots agc_owned_storage_snapshots_verify agc_owned_storage_snapshots_trace agc_owned_storage_snapshots_trace_unbound agc_owned_storage_snapshots_trace_eviction agc_owned_draw_inputs agc_owned_draw_inputs_verify agc_owned_draw_inputs_trace agc_owned_draw_inputs_trace_unbound agc_owned_draw_inputs_trace_eviction agc_draw_inputs_in_place agc_draw_inputs_copied agc_draw_input_reuse agc_resident_present agc_slice_dirty agc_queued_write_groups agc_metadata_pass agc_tiled_resolve agc_changed_copy agc_bound_changed_copy 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 58c661ceff58..7049cdfccb03 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -362,6 +362,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_OPPORTUNISTIC_REAP` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | skips retiring already-finished batches before a submit | | `APS5_NO_ORDERED_WAITS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/WaitStatistics.cpp` | | bumps the collect epoch at every memory wait instead of skipping a wait on an unchanged flag an earlier wait already ordered | | `APS5_NO_OWNED_DRAW_INPUTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp` | | disables token-based reuse of untracked vertex/index copies; APS5_AB can toggle it | +| `APS5_NO_OWNED_DRAW_SNAPSHOTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp` | | disables owned-token reuse of untracked read-only storage snapshots; APS5_AB can toggle it | | `APS5_NO_OWN_IMAGE_REFRESH` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | lets a Pending failure of the fast proof take the full walk instead of the own-object refresh | | `APS5_NO_PARALLEL_MIRROR_REFRESH` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | | disables the mirror-refresh thread pool, so mirror refreshes run on the calling thread | | `APS5_NO_PATTERN_FILL_HLE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferFill.cpp` | | disables the dword-pattern fill HLE | @@ -575,7 +576,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_VERIFY_DRAW_SNAPSHOTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | re-reads a reused draw snapshot and counts the ones that differ | | `APS5_VERIFY_GUARD_SPANS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/MultisampleTarget.cpp` | | checks every guard check that the thread's copy of the guard ranges answered without a lock against the guard list and takes the list's answer; a copy that was current, or a copy refilled after the list changed, that still misses an overlapping guard prints a `[guard-spans] verify` line (the first twenty), and a `[guard-spans]` line every 10 s counts the checks and misses (it also prints with `APS5_PROFILE_DRAW`) | | `APS5_VERIFY_KNOWN_VALUES` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferCopy.cpp` | | serves known values through the hook too and counts mismatches | -| `APS5_VERIFY_OWNED_DRAW_INPUTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | compares reused owned input bytes and throws if they differ while the proof still holds | +| `APS5_VERIFY_OWNED_DRAW_INPUTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | compares reused vertex/index and storage copies and throws if bytes differ while the owned proof still holds | | `APS5_VERIFY_PROOFS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp` | | runs the full walk beside every own-object refresh proof and aborts on a different decision | | `APS5_VERIFY_RECIPE` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | makes the ordinary prepare path beside a recipe hit and compares the answers | | `APS5_VERIFY_REGISTER_KEYS` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRegisterKey.cpp` | | checks the incremental register fingerprint against the full state | diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index e0c6642003cd..ebdba5e74128 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -469,6 +469,11 @@ Eligible single-sample draws retain native finite bounds inside [0, 1] and use a - [Graphics state suppression ownership](../../../core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp) (libSceAgcDriver) - `Context::Function`, `Context::Resolved` and the device setup lookup reject a graphics pipeline bind, a tracked dynamic state command, `vkCmdBindShadersEXT` or `vkCmdExecuteCommands` by name at compile time, and the device table hands those entry points only to `CommandState` and `Context::BindComputePipeline`. `CommandState` cannot be copied or moved, and `FunctionName` keeps its name private, so neither a duplicate tracker nor an edited name can bypass the check. Two routes stay open because the type system cannot see them: a raw `deviceProc` lookup cast to the function type, and a second `CommandState` begun on a recorder batch's command buffer (`Begin` is public for presentation, the overlay and tests, which record their own command buffers). - [Stale depth planes over reused guest memory](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) (libSceAgcDriver): a depth surface outlives the guest memory it mirrors, so a flush over a later allocation stores pending results into it; a pending fast clear used to skip the guest-write check and write zero there. A flush now drops a unit whose recorded allocation (`backingSerial`) changed, and a storing sync drops the units the guest wrote and forgets the clear. Not covered: reuse inside one unchanged registration with no write since the last sync, and the stencil plane, which compares bytes with its last mark. Closes when: surfaces are retired on allocation changes (an unmap hook that keeps the `surfacesMutex`/`GuestAllocations` lock order) instead of at flush time. PPSA27616 reached this through a cubemap of 128x128 depth faces whose memory its heap had taken back. - [Plain label read in the PM4 wait](../../../core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp) (libSceAgcDriver) - `Pm4::WaitSatisfiedUnchecked` reads the awaited label with a volatile load, not an atomic one, so ThreadSanitizer reports it against a title store made atomically (`agc_driver_pm4_rewind_trace` fails under it). An aligned 4 or 8 byte load on x86-64 and arm64 is not torn, so the wait sees the old or the new value. Closes when: the read is an `atomic_ref` acquire load. +- [Owned storage snapshots](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) (libSceAgcDriver) - ordinary read-only storage buffers above the draw upload limit can reuse exact owned proofs. + On hosts with native arena write watching, the selected untracked path bypasses the epoch memo even when arming is refused, so refused ranges lose same-epoch memo reuse and are copied again. + Hosts without native arena write watching, tracked ranges, small uploads, moved overrides, writable buffers and BDA paths retain their existing behavior. + Proofs cover the full adjusted copy range, share the existing 1 GiB/1,024-entry storage pool, and do not serve containing-range lookups. Guest CPU stores still follow the ordinary submission synchronization contract. + No title or performance result is measured. `APS5_NO_OWNED_DRAW_SNAPSHOTS` restores the previous path; the existing `APS5_VERIFY_OWNED_DRAW_INPUTS` verifier also checks owned storage hits. ### Opt-in draw paths diff --git a/tools/tests/test_trace_digest.py b/tools/tests/test_trace_digest.py index 06be0ada9d72..53a4005927d0 100644 --- a/tools/tests/test_trace_digest.py +++ b/tools/tests/test_trace_digest.py @@ -512,6 +512,21 @@ def test_graphics_track_interval_counts_are_preserved(self): with self.assertRaises(ValueError): trace_digest.validate_interval(first) + def test_owned_storage_interval_counts_are_separate(self): + first = interval_line(0.0, 30.0, 20.0, 5.0) + old = interval_line(30.0, 60.0, 20.0, 5.0) + first["owned_draw_counts"] = {"OwnedDraw.reused": 2} + first["owned_storage_counts"] = {"OwnedStorage.reused": 5} + trace_digest.validate_interval(first) + result = trace_digest.digest_intervals([first, old]) + self.assertEqual(result["intervals"][0]["owned_storage_counts"], {"OwnedStorage.reused": 5}) + text = trace_digest.markdown_intervals(result) + self.assertIn("OwnedStorage.reused", text) + self.assertIn("| 2 | - |", text) + first["owned_storage_counts"] = {"bad": -1} + with self.assertRaises(ValueError): + trace_digest.validate_interval(first) + def test_empty_summary_jsonl_files_remain_valid(self): path = self.trace.with_name("aps5-summary.jsonl") for text in ("", "\n \t\r\n"): diff --git a/tools/trace_digest.py b/tools/trace_digest.py index e7364f81c86d..4aa0d7ee1143 100644 --- a/tools/trace_digest.py +++ b/tools/trace_digest.py @@ -505,9 +505,10 @@ def validate_interval(record): raise ValueError(f"{field} must be an object") for name, value in values.items(): interval_number(value, f"{field}.{name}") - counts = record.get("owned_draw_counts", {}) - if not isinstance(counts, dict) or any(not isinstance(name, str) or type(value) is not int or value < 0 for name, value in counts.items()): - raise ValueError("owned_draw_counts must map names to non-negative integers") + for field in ("owned_draw_counts", "owned_storage_counts"): + counts = record.get(field, {}) + if not isinstance(counts, dict) or any(not isinstance(name, str) or type(value) is not int or value < 0 for name, value in counts.items()): + raise ValueError(f"{field} must map names to non-negative integers") graphics = record.get("graphics_track", {}) if not isinstance(graphics, dict) or any(not isinstance(name, str) or type(value) is not int or value < 0 for name, value in graphics.items()): raise ValueError("graphics_track must map names to non-negative integers") @@ -533,7 +534,7 @@ def digest_intervals(lines): "frame_ms": line["frame_ms"], "gpu_busy_ms_per_present": line["gpu_busy_ms_per_present"], "busiest_worker": {"thread": busiest[0], "pct": busiest[1]} if busiest else None, "top_phase": {"name": largest[0], "ms_per_frame": largest[1]} if largest else None, - "trace_dropped": line.get("trace_dropped", False), "owned_draw_counts": line.get("owned_draw_counts"), + "trace_dropped": line.get("trace_dropped", False), "owned_draw_counts": line.get("owned_draw_counts"), "owned_storage_counts": line.get("owned_storage_counts"), "graphics_track": line.get("graphics_track")}) first = lines[0] if lines else {} keys = ("commit", "dirty", "env", "gpu", "driver", "os", "resolution", @@ -559,11 +560,12 @@ def markdown_intervals(result): phase = f"{row['top_phase']['name']} {row['top_phase']['ms_per_frame']:.1f}" if row["top_phase"] else "-" lines.append(f"| {index} | {row['start_s']:.0f}-{row['end_s']:.0f}{' (dropped)' if row['trace_dropped'] else ''} | {row['presents']} | {frame['p50']:.1f} | {frame['p90']:.1f} " f"| {frame['p99']:.1f} | {frame['max']:.1f} | {row['gpu_busy_ms_per_present']:.1f} | {worker} | {table_cell(phase)} |") - count_names = sorted({name for row in rows for name in (row["owned_draw_counts"] or {})}) - if count_names: - lines += ["", "| # | " + " | ".join(table_cell(name) for name in count_names) + " |", "|---|" + "---|" * len(count_names)] - for index, row in enumerate(rows, 1): - lines.append(f"| {index} | " + " | ".join(str(row["owned_draw_counts"].get(name, 0)) if row["owned_draw_counts"] is not None else "-" for name in count_names) + " |") + for field in ("owned_draw_counts", "owned_storage_counts"): + count_names = sorted({name for row in rows for name in (row[field] or {})}) + if count_names: + lines += ["", "| # | " + " | ".join(table_cell(name) for name in count_names) + " |", "|---|" + "---|" * len(count_names)] + for index, row in enumerate(rows, 1): + lines.append(f"| {index} | " + " | ".join(str(row[field].get(name, 0)) if row[field] is not None else "-" for name in count_names) + " |") track = [row["graphics_track"] or {} for row in rows] if any(track): lines += ["", "| # | passes | continued | closed | top close reason | barriers | merged | copies | copy MiB |",