diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/FrameCapture.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/FrameCapture.hpp index 35da6389f1c3..ff03d22e0adc 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/FrameCapture.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/FrameCapture.hpp @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include #include #include @@ -79,13 +81,24 @@ class FrameCaptureWriter { static constexpr std::string_view CallsName = "calls.bin"; static constexpr std::string_view MemoryName = "memory.bin"; static constexpr std::string_view HeaderName = "capture.json"; - static constexpr std::string_view CallsMagic = "aps5-frame-calls 2\n"; + static constexpr std::string_view CallsMagic = "aps5-frame-calls 3\n"; + static constexpr std::string_view CallsMagicV2 = "aps5-frame-calls 2\n"; static constexpr std::string_view CallsMagicV1 = "aps5-frame-calls 1\n"; - static constexpr std::string_view MemoryMagic = "aps5-frame-memory 1\n"; + static constexpr std::string_view MemoryMagic = "aps5-frame-memory 2\n"; + static constexpr std::string_view MemoryMagicV1 = "aps5-frame-memory 1\n"; static constexpr std::size_t BlockBytes = 64u * 1024u; static constexpr std::size_t ChunkBytes = 4u * 1024u * 1024u; + static constexpr std::uint64_t CachedDeltaBytes = 512u * 1024u * 1024u; - explicit FrameCaptureWriter(const std::filesystem::path& directory, int level = 1); + struct DeltaCosts { + std::uint64_t compared = 0; + std::uint64_t evicted = 0; + double compareSeconds = 0; + }; + + static constexpr std::uint32_t CallsVersion = 3; + + explicit FrameCaptureWriter(const std::filesystem::path& directory, int level = 1, std::uint64_t cacheBudget = CachedDeltaBytes, std::uint32_t callsVersion = CallsVersion); FrameCaptureWriter(const FrameCaptureWriter&) = delete; FrameCaptureWriter& operator=(const FrameCaptureWriter&) = delete; @@ -98,11 +111,22 @@ class FrameCaptureWriter { std::uint64_t RawBytes() const; std::uint64_t StoredBytes() const; + std::uint64_t SharedBytes() const; + DeltaCosts Costs() const; const std::filesystem::path& Directory() const; private: - void writeChunk(const FrameMemoryChunk& chunk, std::span payload); + using DeltaKey = std::pair; + struct DeltaPayload { + std::uint64_t offset = 0; + std::uint64_t compressedBytes = 0; + std::shared_ptr> bytes; + std::list::iterator use; + }; + + std::uint64_t writeChunk(const FrameMemoryChunk& chunk, std::span payload, std::uint64_t sharedOffset = 0); std::vector compress(std::span bytes) const; + void cacheDelta(const DeltaKey& key, std::uint64_t offset, std::uint64_t compressedBytes, std::shared_ptr> bytes); std::filesystem::path directory; int level; @@ -111,6 +135,13 @@ class FrameCaptureWriter { std::ofstream memory; std::uint64_t rawBytes = 0; std::uint64_t storedBytes = 0; + std::uint64_t sharedBytes = 0; + std::uint64_t cacheBudget = CachedDeltaBytes; + std::uint64_t cachedBytes = 0; + DeltaCosts costs; + std::uint64_t memoryOffset = 0; + std::map deltaPayloads; + std::list deltaUses; bool finished = false; }; @@ -139,7 +170,7 @@ class FrameCaptureReader { std::vector calls; std::vector chunks; std::string header; - std::uint32_t version = 2; + std::uint32_t version = 3; bool truncated = false; }; diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/FrameRecorder.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/FrameRecorder.hpp index 67be2fc6a413..625b098c401b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/FrameRecorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/FrameRecorder.hpp @@ -6,6 +6,8 @@ #include "prx/libSceAgcDriver/Execution/include/VideoOutput.hpp" #include "SceShaders.hpp" #include "SceTypes.hpp" +#include +#include #include #include #include @@ -44,7 +46,46 @@ class FrameRecorder { void Suspend(const std::function& accept); void PresentBuffer(const DisplayBuffer& buffer); void FrameBoundary(); + static void NoteGpuStore(std::uint64_t address, std::span bytes) { + if (notingGpuStores.load(std::memory_order_relaxed)) Active()->noteGpuStore(address, bytes); + } + static void NoteGpuFill(std::uint64_t address, std::uint64_t bytes, const std::array& pattern) { + if (notingGpuStores.load(std::memory_order_relaxed)) Active()->noteGpuFill(address, bytes, pattern); + } void RewindTailFlips(std::uint64_t flips); + static void MergeOverlappingBlocks(std::vector>& blocks); + struct CapturedSpans { + std::map spans; + void Add(std::uint64_t begin, std::uint64_t end); + template void Covering(std::uint64_t begin, std::uint64_t end, const Visit& visit) const { + auto span = spans.upper_bound(begin); + if (span != spans.begin()) --span; + for (; span != spans.end() && span->first < end; ++span) { + const auto first = std::max(begin, span->first); + const auto stop = std::min(end, span->second); + if (first < stop) visit(first, stop); + } + } + }; + struct GpuStores { + struct FillRun { + std::uint64_t origin = 0; + std::uint64_t end = 0; + std::array pattern{}; + std::uint32_t At(std::uint64_t word) const; + }; + struct StoredWord { + std::uint32_t value = 0; + std::uint8_t known = 0; + }; + static constexpr std::size_t WordLimit = 64u * 1024u; + std::map words; + std::map fills; + void Store(std::uint64_t address, std::span bytes); + void Fill(std::uint64_t address, std::uint64_t bytes, const std::array& pattern); + void Forget(std::uint64_t begin, std::uint64_t end); + std::uint64_t KeepTitleWords(std::uint64_t address, std::span bytes, std::vector>& runs, bool zero); + }; static void SetStartIdleWaitForTest(std::function wait); private: @@ -61,6 +102,7 @@ class FrameRecorder { }; FrameRecorder(std::filesystem::path directory, std::filesystem::path trigger, std::uint64_t atBoundary, std::uint64_t frames); + struct Span { std::uint64_t address = 0; std::uint64_t bytes = 0; @@ -73,13 +115,17 @@ class FrameRecorder { void emitDelta(); static void collectShaderPages(std::span shaders, std::set& blocks, std::set& hostPages); void emitShaderDelta(std::span shaders); - void writeDelta(std::span spans, std::span hostPages, std::span added = {}); + void writeDelta(std::span spans, std::span> hostSpans, std::span added = {}); void frameBoundaryLocked(); bool triggered(); void start(); void finish(); void snapshot(const Range& range); void readGuest(std::uint64_t address, std::span bytes); + void noteGpuStore(std::uint64_t address, std::span bytes); + void noteGpuFill(std::uint64_t address, std::uint64_t bytes, const std::array& pattern); + void endGpuStores(); + void keepTitleWords(std::uint64_t address, std::span bytes, std::vector>& runs, bool zero); void writeReferenceFrames(); bool abandonIfDiskLow(); void stop(const char* reason); @@ -87,6 +133,8 @@ class FrameRecorder { std::vector committedRanges(); std::vector newRanges(); std::uint64_t blockSince(std::uint64_t block) const; + static bool collectsDeltas(const Range& range); + static void seedUnwatchedPages(std::uint64_t address, std::span bytes); std::filesystem::path directory; std::filesystem::path trigger; @@ -101,6 +149,10 @@ class FrameRecorder { std::vector ranges; std::map shaderMarks; std::map hostPageHashes; + inline static std::atomic notingGpuStores{false}; + std::mutex gpuStoresMutex; + GpuStores gpuStores; + std::uint64_t gpuStoreBytes = 0; std::mutex displayMutex; std::map displayBuffers; std::uint64_t ordinal = 0; @@ -118,6 +170,8 @@ class FrameRecorder { inline static std::function startIdleWaitForTest; std::uint64_t unreadableBytes = 0; std::uint64_t hostOnlySampleBytes = 0; + std::uint64_t unwatchedChangedBytes = 0; + double unwatchedCompareSeconds = 0; std::uint64_t allocationsGeneration = 0; std::uint64_t lateRanges = 0; std::vector warnings; diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp index 36c1eaef5a62..6cf85cf21ab3 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp @@ -138,6 +138,7 @@ void SetOwnStoreCompare(bool compare); void SetLeftWatchCompare(bool compare); void SeedComparedPages(std::uint64_t address, std::span bytes); void UpdateComparedPages(std::uint64_t address, std::span bytes); +void ForgetComparedPages(std::uint64_t address, std::size_t bytes); void ChangedComparedPages(std::uint64_t address, std::size_t bytes, std::vector>& changed); void SetComparedDecisionHookForTest(void (*hook)()); bool StoredOver(std::uint64_t address, std::size_t bytes, std::uint64_t generation); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferFill.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferFill.cpp index 1df2c9daee50..193b7522dfee 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferFill.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferFill.cpp @@ -5,6 +5,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Memory/DwordPatternFill.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" +#include "prx/libSceAgcDriver/Execution/include/FrameRecorder.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" @@ -430,6 +431,7 @@ void Driver::storeBufferFill(std::uint32_t queueId, std::uint64_t base, std::siz for (std::size_t done = 0; done < bytes; done += chunk) GuestMemory::Write(base + done, std::span(block).first(std::min(chunk, bytes - done)), 16); phase(FillCpu); } + FrameRecorder::NoteGpuFill(base, bytes, pattern); if (noteMetadata && uniform) { Graphics::NoteDepthMetadataFill(base, bytes, pattern[0]); Graphics::NoteColorMetadataFill(base, bytes, pattern[0]); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp index 5d75ec65379a..7c6805097920 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketMemory.cpp @@ -3,6 +3,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/SynchronizationStatistics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" +#include "prx/libSceAgcDriver/Execution/include/FrameRecorder.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libkernel/Time/include/SleepWake.hpp" #include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" @@ -341,7 +342,9 @@ void Driver::dumpSampleCounters(std::uint64_t address, std::uint32_t blocks) { for (std::uint64_t db = 0; db < Pm4::SampleDumpBlocks; ++db) { if (((blocks >> db) & 1u) == 0) continue; const std::uint64_t value = ready | (db == first ? samples : 0u); - GuestMemory::Write(address + db * Pm4::SampleDumpStride, std::as_bytes(std::span(&value, 1)).first(Pm4::SampleDumpBlockBytes), 8); + const auto bytes = std::as_bytes(std::span(&value, 1)).first(Pm4::SampleDumpBlockBytes); + GuestMemory::Write(address + db * Pm4::SampleDumpStride, bytes, 8); + FrameRecorder::NoteGpuStore(address + db * Pm4::SampleDumpStride, bytes); } } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/LabelHistory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/LabelHistory.cpp index d17f239df0bb..a522342ba480 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/LabelHistory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/LabelHistory.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/FrameRecorder.hpp" #include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -10,6 +11,7 @@ namespace AgcDriver::DriverDetail { void Driver::noteLabelStore(std::uint64_t address, std::span bytes, std::uint64_t stamp, std::uint32_t queue, bool ordered) { + FrameRecorder::NoteGpuStore(address, bytes); if (!KeepsLabelStore(address, bytes.size())) return; const auto generation = GuestMemory::TrackerGeneration(); std::lock_guard lock(labelStoresMutex); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/FrameCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/FrameCapture.cpp index 6acbb14ec276..fa159f597de2 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/FrameCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/FrameCapture.cpp @@ -3,9 +3,12 @@ #include #include #include +#include #include #include #include +#include +#include #include #include #include @@ -199,7 +202,8 @@ std::string_view FrameCallName(FrameCallKind kind) { throw std::runtime_error("frame capture: unknown call kind " + std::to_string(static_cast(kind))); } -FrameCaptureWriter::FrameCaptureWriter(const std::filesystem::path& directory, int level) : directory(directory), level(level) { +FrameCaptureWriter::FrameCaptureWriter(const std::filesystem::path& directory, int level, std::uint64_t cacheBudget, std::uint32_t callsVersion) : directory(directory), level(level), cacheBudget(cacheBudget) { + requireCapture(callsVersion == 2 || callsVersion == CallsVersion, "a capture writer writes calls format 2 or " + std::to_string(CallsVersion) + ", not " + std::to_string(callsVersion)); std::error_code error; std::filesystem::create_directories(directory, error); requireCapture(!error && std::filesystem::is_directory(directory), "cannot create the directory " + directory.string()); @@ -207,8 +211,10 @@ FrameCaptureWriter::FrameCaptureWriter(const std::filesystem::path& directory, i calls.open(directory / CallsName, std::ios::binary | std::ios::trunc); memory.open(directory / MemoryName, std::ios::binary | std::ios::trunc); requireCapture(calls.is_open() && memory.is_open(), "cannot create the capture files in " + directory.string()); - calls.write(CallsMagic.data(), static_cast(CallsMagic.size())); + const auto magic = callsVersion == 2 ? CallsMagicV2 : CallsMagic; + calls.write(magic.data(), static_cast(magic.size())); memory.write(MemoryMagic.data(), static_cast(MemoryMagic.size())); + memoryOffset = MemoryMagic.size(); requireCapture(calls.good() && memory.good(), "cannot write the capture files in " + directory.string()); } @@ -279,16 +285,41 @@ std::uint64_t FrameCaptureWriter::WriteSnapshot(std::uint64_t address, std::span void FrameCaptureWriter::WriteDelta(std::uint64_t group, std::uint64_t completed, std::uint64_t address, std::span bytes) { for (std::size_t at = 0; at < bytes.size(); at += ChunkBytes) { const auto part = bytes.subspan(at, std::min(ChunkBytes, bytes.size() - at)); - const auto payload = compress(part); FrameMemoryChunk chunk; chunk.kind = FrameMemoryKind::Delta; chunk.group = group; chunk.completed = completed; chunk.address = address + at; chunk.bytes = part.size(); + const DeltaKey key{chunk.address, chunk.bytes}; + std::optional earlier; + { + std::lock_guard lock(mutex); + if (const auto found = deltaPayloads.find(key); found != deltaPayloads.end()) { + deltaUses.splice(deltaUses.end(), deltaUses, found->second.use); + earlier = found->second; + } + } + if (earlier) { + const auto compared = std::chrono::steady_clock::now(); + const bool same = std::memcmp(earlier->bytes->data(), part.data(), part.size()) == 0; + const auto compareSeconds = std::chrono::duration(std::chrono::steady_clock::now() - compared).count(); + std::lock_guard lock(mutex); + ++costs.compared; + costs.compareSeconds += compareSeconds; + if (same) { + chunk.compressedBytes = earlier->compressedBytes; + writeChunk(chunk, {}, earlier->offset); + sharedBytes += chunk.bytes; + continue; + } + } + earlier.reset(); + const auto payload = compress(part); chunk.compressedBytes = payload.size(); + auto cached = part.size() <= cacheBudget ? std::make_shared>(part.begin(), part.end()) : nullptr; std::lock_guard lock(mutex); - writeChunk(chunk, payload); + cacheDelta(key, writeChunk(chunk, payload), payload.size(), std::move(cached)); } } @@ -329,11 +360,21 @@ std::uint64_t FrameCaptureWriter::StoredBytes() const { return storedBytes; } +std::uint64_t FrameCaptureWriter::SharedBytes() const { + std::lock_guard lock(mutex); + return sharedBytes; +} + +FrameCaptureWriter::DeltaCosts FrameCaptureWriter::Costs() const { + std::lock_guard lock(mutex); + return costs; +} + const std::filesystem::path& FrameCaptureWriter::Directory() const { return directory; } -void FrameCaptureWriter::writeChunk(const FrameMemoryChunk& chunk, std::span payload) { +std::uint64_t FrameCaptureWriter::writeChunk(const FrameMemoryChunk& chunk, std::span payload, std::uint64_t sharedOffset) { requireCapture(!finished, "memory written after the capture finished"); Encoder encoder; encoder.Put(static_cast(chunk.kind)); @@ -345,12 +386,33 @@ void FrameCaptureWriter::writeChunk(const FrameMemoryChunk& chunk, std::span(payload.size())); - encoder.Put(std::uint64_t{0}); + encoder.Put(sharedOffset); memory.write(reinterpret_cast(encoder.bytes.data()), static_cast(encoder.bytes.size())); memory.write(reinterpret_cast(payload.data()), static_cast(payload.size())); requireCapture(memory.good(), "cannot write " + (directory / MemoryName).string()); if (chunk.kind != FrameMemoryKind::Range) rawBytes += chunk.bytes; storedBytes += payload.size(); + const auto payloadOffset = memoryOffset + ChunkHeaderBytes; + memoryOffset = payloadOffset + payload.size(); + return payloadOffset; +} + +void FrameCaptureWriter::cacheDelta(const DeltaKey& key, std::uint64_t offset, std::uint64_t compressedBytes, std::shared_ptr> bytes) { + if (const auto found = deltaPayloads.find(key); found != deltaPayloads.end()) { + cachedBytes -= key.second; + deltaUses.erase(found->second.use); + deltaPayloads.erase(found); + } + if (!bytes) return; + while (cachedBytes + key.second > cacheBudget) { + cachedBytes -= deltaUses.front().second; + deltaPayloads.erase(deltaUses.front()); + deltaUses.pop_front(); + ++costs.evicted; + } + cachedBytes += key.second; + deltaUses.push_back(key); + deltaPayloads.emplace(key, DeltaPayload{offset, compressedBytes, std::move(bytes), std::prev(deltaUses.end())}); } std::vector FrameCaptureWriter::compress(std::span bytes) const { @@ -375,8 +437,9 @@ FrameCaptureReader::FrameCaptureReader(const std::filesystem::path& directory) : const auto callsPath = directory / FrameCaptureWriter::CallsName; const auto callBytes = readFile(callsPath); if (hasMagic(callBytes, FrameCaptureWriter::CallsMagicV1)) version = 1; + else if (hasMagic(callBytes, FrameCaptureWriter::CallsMagicV2)) version = 2; else requireMagic(callBytes, FrameCaptureWriter::CallsMagic, callsPath); - std::size_t at = (version == 1 ? FrameCaptureWriter::CallsMagicV1 : FrameCaptureWriter::CallsMagic).size(); + std::size_t at = (version == 1 ? FrameCaptureWriter::CallsMagicV1 : version == 2 ? FrameCaptureWriter::CallsMagicV2 : FrameCaptureWriter::CallsMagic).size(); while (at < callBytes.size()) { if (callBytes.size() - at < 8) { truncated = true; @@ -402,7 +465,9 @@ FrameCaptureReader::FrameCaptureReader(const std::filesystem::path& directory) : std::string magic(FrameCaptureWriter::MemoryMagic.size(), '\0'); memory.seekg(0); memory.read(magic.data(), static_cast(magic.size())); - requireCapture(memory.good() && magic == FrameCaptureWriter::MemoryMagic, memoryPath.string() + " is not a frame capture file"); + requireCapture(memory.good() && (magic == FrameCaptureWriter::MemoryMagic || magic == FrameCaptureWriter::MemoryMagicV1), memoryPath.string() + " is not a frame capture file"); + const bool sharing = magic == FrameCaptureWriter::MemoryMagic; + std::map payloads; std::uint64_t offset = magic.size(); while (offset < size) { if (size - offset < ChunkHeaderBytes) { @@ -426,13 +491,26 @@ FrameCaptureReader::FrameCaptureReader(const std::filesystem::path& directory) : chunk.completed = decoder.Take("completed serial"); chunk.address = decoder.Take("address"); chunk.bytes = decoder.Take("bytes"); - chunk.compressedBytes = decoder.Take("compressed bytes"); + const auto stored = decoder.Take("compressed bytes"); + const auto shared = sharing ? decoder.Take("shared payload") : 0; + if (shared != 0) { + const auto found = payloads.find(shared); + requireCapture(chunk.kind == FrameMemoryKind::Delta && found != payloads.end() && chunks[found->second].address == chunk.address && chunks[found->second].bytes == chunk.bytes && stored == 0, + memoryPath.string() + ": chunk at byte " + std::to_string(offset) + " shares no earlier delta of its address and size"); + chunk.offset = shared; + chunk.compressedBytes = chunks[found->second].compressedBytes; + chunks.push_back(chunk); + offset += ChunkHeaderBytes; + continue; + } + chunk.compressedBytes = stored; requireCapture((chunk.kind == FrameMemoryKind::Range) == (chunk.compressedBytes == 0), memoryPath.string() + ": chunk payload does not match its kind at byte " + std::to_string(offset)); chunk.offset = offset + ChunkHeaderBytes; if (size - chunk.offset < chunk.compressedBytes) { truncated = true; break; } + if (chunk.kind == FrameMemoryKind::Delta) payloads[chunk.offset] = chunks.size(); chunks.push_back(chunk); offset = chunk.offset + chunk.compressedBytes; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp index 9b74ee66f804..16f4612f45cf 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp @@ -350,7 +350,7 @@ void FrameRecorder::emitDelta() { std::vector owners; for (std::size_t index = 0; index < ranges.size(); ++index) { const auto& range = ranges[index]; - if (range.kind != FrameRangeKind::Watched && range.kind != FrameRangeKind::Unwatched) continue; + if (!collectsDeltas(range)) continue; spans.push_back({range.address, range.bytes, range.since}); owners.push_back(index); } @@ -422,11 +422,48 @@ void FrameRecorder::emitShaderDelta(std::span shaders) { std::set hostPages; collectShaderPages(shaders, blocks, hostPages); if (blocks.empty() && hostPages.empty()) return; + const auto added = newRanges(); + CapturedSpans captured; + for (const auto& list : {std::span(ranges), std::span(added)}) { + for (const auto& range : list) { + if (range.readable) captured.Add(range.address, range.address + range.bytes); + } + } + const auto inside = [&](std::uint64_t begin, std::uint64_t end, const auto& visit) { captured.Covering(begin, end, visit); }; std::vector spans; - for (const auto block : blocks) spans.push_back({block, FrameCaptureWriter::BlockBytes, blockSince(block)}); - const std::vector pages(hostPages.begin(), hostPages.end()); - writeDelta(spans, pages); - for (const auto& span : spans) shaderMarks[span.address] = span.since; + for (const auto block : blocks) { + const auto since = blockSince(block); + inside(block, block + FrameCaptureWriter::BlockBytes, [&](std::uint64_t first, std::uint64_t stop) { spans.push_back({first, stop - first, since}); }); + } + const auto blockSpans = spans.size(); + std::vector> hostSpans; + for (const auto page : hostPages) inside(page, page + HostPageBytes, [&](std::uint64_t first, std::uint64_t stop) { hostSpans.emplace_back(first, stop); }); + writeDelta(spans, hostSpans, added); + std::map marks; + for (std::size_t index = 0; index < blockSpans; ++index) { + const auto block = spans[index].address & ~std::uint64_t{FrameCaptureWriter::BlockBytes - 1}; + const auto [found, inserted] = marks.try_emplace(block, spans[index].since); + if (!inserted) found->second = std::min(found->second, spans[index].since); + } + for (const auto& [block, since] : marks) shaderMarks[block] = since; +} + +bool FrameRecorder::collectsDeltas(const Range& range) { + return range.readable && ((range.access & FrameRangeAccess::Writable) != 0 || range.kind == FrameRangeKind::Watched || range.kind == FrameRangeKind::Unwatched); +} + +void FrameRecorder::seedUnwatchedPages(std::uint64_t address, std::span bytes) { + for (std::size_t at = 0; at < bytes.size();) { + const auto block = static_cast(std::min(FrameCaptureWriter::BlockBytes - (address + at) % FrameCaptureWriter::BlockBytes, bytes.size() - at)); + if (!GuestMemory::Watched(address + at, block)) { + for (std::size_t page = at; page < at + block;) { + const auto size = std::min(HostPageBytes - (address + page) % HostPageBytes, at + block - page); + if (!GuestMemory::Watched(address + page, size)) GuestMemory::SeedComparedPages(address + page, bytes.subspan(page, size)); + page += size; + } + } + at += block; + } } std::uint64_t FrameRecorder::blockSince(std::uint64_t block) const { @@ -443,42 +480,77 @@ std::uint64_t FrameRecorder::blockSince(std::uint64_t block) const { return covered == FrameCaptureWriter::BlockBytes ? std::max(mark, since) : mark; } -void FrameRecorder::writeDelta(std::span spans, std::span hostPages, std::span added) { +void FrameRecorder::CapturedSpans::Add(std::uint64_t begin, std::uint64_t end) { + if (begin >= end) return; + auto next = spans.upper_bound(begin); + if (next != spans.begin() && std::prev(next)->second >= begin) --next; + while (next != spans.end() && next->first <= end) { + begin = std::min(begin, next->first); + end = std::max(end, next->second); + next = spans.erase(next); + } + spans.emplace(begin, end); +} + +void FrameRecorder::MergeOverlappingBlocks(std::vector>& blocks) { + std::ranges::sort(blocks); + std::size_t merged = 0; + for (const auto& block : blocks) { + const bool aligned = block.first % 4 == 0 && block.second % 4 == 0 && merged != 0 && blocks[merged - 1].first % 4 == 0 && blocks[merged - 1].second % 4 == 0; + if (aligned && block.first < blocks[merged - 1].second) blocks[merged - 1].second = std::max(blocks[merged - 1].second, block.second); + else blocks[merged++] = block; + } + blocks.resize(merged); +} + +void FrameRecorder::writeDelta(std::span spans, std::span> hostSpans, std::span added) { if (abandonIfDiskLow()) return; std::vector> blocks; std::vector> written; for (auto& span : spans) { - span.since = GuestMemory::CollectWrittenBlocks(span.address, static_cast(span.bytes), span.since, written); + if (const auto since = GuestMemory::CollectWrittenBlocks(span.address, static_cast(span.bytes), span.since, written); since != 0) span.since = since; blocks.insert(blocks.end(), written.begin(), written.end()); + const auto compare = std::chrono::steady_clock::now(); GuestMemory::ChangedComparedPages(span.address, static_cast(span.bytes), written); + unwatchedCompareSeconds += std::chrono::duration(std::chrono::steady_clock::now() - compare).count(); + for (const auto& [begin, end] : written) unwatchedChangedBytes += end - begin; blocks.insert(blocks.end(), written.begin(), written.end()); } - std::ranges::sort(blocks); - std::vector> merged; - for (const auto& [begin, end] : blocks) { - if (!merged.empty() && merged.back().second >= begin) merged.back().second = std::max(merged.back().second, end); - else merged.emplace_back(begin, end); - } - blocks = std::move(merged); + MergeOverlappingBlocks(blocks); auto& driver = DriverDetail::Driver::Get(); const struct Hold { DriverDetail::Driver& driver; ~Hold() { driver.ReleaseSettled(); } } hold{driver}; auto [accepted, completed] = driver.SerialProgress(); - if (completed < accepted && (!added.empty() || !blocks.empty())) { + if (completed < accepted && (!added.empty() || !blocks.empty() || !hostSpans.empty())) { if (!driver.WaitSettledFor(std::chrono::seconds(10))) { stop("stopped: the GPU work submitted before a memory delta neither finished nor waited for the title within 10 s"); return; } std::tie(accepted, completed) = driver.SerialProgress(); } - std::vector parked; - for (const auto& wait : driver.AwaitedWaits()) parked.push_back(wait.address); + std::vector> parked; + for (const auto& wait : driver.AwaitedWaits()) { + if (wait.bytes == 0) parked.push_back({wait.address, 0, 0, 0}); + else parked.push_back({wait.address, wait.reference, wait.mask, wait.function | (std::uint64_t{wait.bytes} << 32u)}); + } std::ranges::sort(parked); const auto group = deltaGroups + 1; bool any = false; std::vector bytes; + std::vector> runs; + const auto writeTitleWords = [&](std::uint64_t address, bool zero = false) { + keepTitleWords(address, bytes, runs, zero); + for (const auto& [offset, length] : runs) { + writer->WriteDelta(group, completed, address + offset, std::span(bytes).subspan(offset, length)); + deltaBytes += length; + any = true; + } + }; + const auto forgetHostPages = [&](std::uint64_t begin, std::uint64_t end) { + hostPageHashes.erase(hostPageHashes.lower_bound(begin & ~std::uint64_t{HostPageBytes - 1}), hostPageHashes.lower_bound(end)); + }; for (const auto& range : added) { writer->WriteRange(range.address, range.bytes, range.kind, range.protection, range.access); auto& stored = ranges.emplace_back(range); @@ -492,35 +564,29 @@ void FrameRecorder::writeDelta(std::span spans, std::span(std::min(FrameCaptureWriter::BlockBytes, range.bytes - at))); readGuest(range.address + at, bytes); - if (stored.kind == FrameRangeKind::Unwatched) GuestMemory::SeedComparedPages(range.address + at, bytes); + if (collectsDeltas(stored)) seedUnwatchedPages(range.address + at, bytes); const bool zero = std::all_of(bytes.begin(), bytes.end(), [](std::byte value) { return value == std::byte{0}; }); - if (!zero || collected) { - writer->WriteDelta(group, completed, range.address + at, bytes); - deltaBytes += bytes.size(); - any = true; - } + writeTitleWords(range.address + at, zero && !collected); at += bytes.size(); } } - for (const auto page : hostPages) { - if (!GuestMemory::Accessible(reinterpret_cast(static_cast(page)), HostPageBytes)) continue; - bytes.resize(HostPageBytes); - std::memcpy(bytes.data(), reinterpret_cast(static_cast(page)), HostPageBytes); + for (const auto& [begin, end] : hostSpans) { + const auto* host = reinterpret_cast(static_cast(begin)); + if (!GuestMemory::Accessible(host, static_cast(end - begin))) continue; + bytes.assign(host, host + (end - begin)); const auto hash = contentHash(bytes); - auto& known = hostPageHashes[page]; - if (known == hash) continue; - known = hash; - writer->WriteDelta(group, completed, page, bytes); - deltaBytes += bytes.size(); - any = true; + if (const auto found = hostPageHashes.find(begin); found != hostPageHashes.end() && found->second == hash) continue; + GuestMemory::UpdateComparedPages(begin, bytes); + forgetHostPages(begin, end); + hostPageHashes[begin] = hash; + writeTitleWords(begin); } for (const auto& [begin, end] : blocks) { bytes.resize(static_cast(end - begin)); readGuest(begin, bytes); GuestMemory::UpdateComparedPages(begin, bytes); - writer->WriteDelta(group, completed, begin, bytes); - deltaBytes += bytes.size(); - any = true; + forgetHostPages(begin, end); + writeTitleWords(begin); } if (!any) return; deltaGroups = group; @@ -529,10 +595,144 @@ void FrameRecorder::writeDelta(std::span spans, std::spanWriteCall(call); } +void FrameRecorder::endGpuStores() { + notingGpuStores = false; + std::lock_guard lock(gpuStoresMutex); + gpuStores.words.clear(); + gpuStores.fills.clear(); +} + +void FrameRecorder::noteGpuStore(std::uint64_t address, std::span bytes) { + std::lock_guard lock(gpuStoresMutex); + gpuStores.Store(address, bytes); +} + +void FrameRecorder::noteGpuFill(std::uint64_t address, std::uint64_t bytes, const std::array& pattern) { + std::lock_guard lock(gpuStoresMutex); + gpuStores.Fill(address, bytes, pattern); +} + +void FrameRecorder::keepTitleWords(std::uint64_t address, std::span bytes, std::vector>& runs, bool zero) { + std::lock_guard lock(gpuStoresMutex); + gpuStoreBytes += gpuStores.KeepTitleWords(address, bytes, runs, zero); +} + +void FrameRecorder::GpuStores::Store(std::uint64_t address, std::span bytes) { + if (bytes.empty()) return; + const auto end = address + bytes.size(); + Forget(address, end); + if (bytes.size() > WordLimit) return; + for (auto at = address; at < end;) { + const auto word = at & ~std::uint64_t{3}; + auto& stored = words[word]; + for (; at < end && at < word + 4; ++at) { + const auto shift = static_cast(at - word) * 8u; + stored.value = (stored.value & ~(0xffu << shift)) | (std::to_integer(bytes[at - address]) << shift); + stored.known |= static_cast(1u << (at - word)); + } + } +} + +void FrameRecorder::GpuStores::Fill(std::uint64_t address, std::uint64_t bytes, const std::array& pattern) { + if (bytes == 0) return; + Forget(address, address + bytes); + if (address % 4 == 0 && bytes % 4 == 0) fills.emplace(address, FillRun{address, address + bytes, pattern}); +} + +std::uint32_t FrameRecorder::GpuStores::FillRun::At(std::uint64_t word) const { + return pattern[((word - origin) % 16) / 4]; +} + +void FrameRecorder::GpuStores::Forget(std::uint64_t begin, std::uint64_t end) { + const auto low = begin & ~std::uint64_t{3}; + const auto high = (end + 3) & ~std::uint64_t{3}; + const auto outside = [&](std::uint64_t word) { + std::uint8_t mask = 0; + for (std::uint64_t byte = 0; byte < 4; ++byte) { + if (word + byte < begin || word + byte >= end) mask |= static_cast(1u << byte); + } + return mask; + }; + for (auto word = words.lower_bound(low); word != words.end() && word->first < end;) { + word->second.known &= outside(word->first); + if (word->second.known == 0) word = words.erase(word); + else ++word; + } + auto fill = fills.upper_bound(begin); + if (fill != fills.begin()) --fill; + while (fill != fills.end() && fill->first < end) { + if (fill->second.end <= begin) { + ++fill; + continue; + } + const auto start = fill->first; + const auto kept = fill->second; + fill = fills.erase(fill); + if (start < low) fills.emplace(start, FillRun{kept.origin, low, kept.pattern}); + if (high < kept.end) fills.emplace(high, FillRun{kept.origin, kept.end, kept.pattern}); + for (const auto word : {low, high - 4}) { + const auto mask = outside(word); + if (mask != 0 && start <= word && word < kept.end) words[word] = StoredWord{kept.At(word), mask}; + } + } +} + +std::uint64_t FrameRecorder::GpuStores::KeepTitleWords(std::uint64_t address, std::span bytes, std::vector>& runs, bool zero) { + runs.clear(); + const auto end = address + bytes.size(); + auto word = words.lower_bound(address & ~std::uint64_t{3}); + auto fill = fills.upper_bound(address); + if (fill != fills.begin()) --fill; + if (fill != fills.end() && fill->second.end <= address) ++fill; + const bool stored = word != words.end() && word->first < end; + const bool filled = fill != fills.end() && fill->first < end; + if (zero && !stored && !filled) return 0; + if (!stored && !filled) { + if (!bytes.empty()) runs.emplace_back(0, bytes.size()); + return 0; + } + std::uint64_t driverBytes = 0; + std::size_t open = bytes.size(); + for (auto at = address & ~std::uint64_t{3}; at < end; at += 4) { + std::uint32_t expected = 0; + std::uint8_t known = 0; + if (word != words.end() && word->first == at) { + expected = word->second.value; + known = word->second.known; + ++word; + } else { + while (fill != fills.end() && fill->second.end <= at) ++fill; + if (fill != fills.end() && fill->first <= at) { + expected = fill->second.At(at); + known = 0xf; + } + } + const auto first = std::max(at, address); + const auto last = std::min(at + 4, end); + std::uint32_t current = 0; + std::memcpy(reinterpret_cast(¤t) + (first - at), bytes.data() + (first - address), static_cast(last - first)); + const auto differs = current ^ expected; + for (auto byte = first; byte < last; ++byte) { + const auto offset = static_cast(byte - address); + const bool driver = (known & (1u << (byte - at))) != 0 && ((differs >> ((byte - at) * 8u)) & 0xffu) == 0; + if (driver) { + ++driverBytes; + if (open != bytes.size()) runs.emplace_back(open, offset - open); + open = bytes.size(); + } else if (open == bytes.size()) { + open = offset; + } + } + } + if (open != bytes.size()) runs.emplace_back(open, bytes.size() - open); + for (const auto& [offset, length] : runs) Forget(address + offset, address + offset + length); + return driverBytes; +} + void FrameRecorder::snapshot(const Range& range) { writer->WriteRange(range.address, range.bytes, range.kind, range.protection, range.access); if (!range.readable) { @@ -544,7 +744,7 @@ void FrameRecorder::snapshot(const Range& range) { if (abandonIfDiskLow()) return; bytes.resize(static_cast(std::min(SnapshotPieceBytes, range.bytes - at))); readGuest(range.address + at, bytes); - if (range.kind == FrameRangeKind::Unwatched) GuestMemory::SeedComparedPages(range.address + at, bytes); + if (collectsDeltas(range)) seedUnwatchedPages(range.address + at, bytes); snapshotBytes += writer->WriteSnapshot(range.address + at, bytes); } } @@ -573,6 +773,7 @@ void FrameRecorder::stop(const char* reason) { std::fprintf(stderr, "[frame-capture] %s\n", failure.what()); } writer.reset(); + endGpuStores(); state = State::Done; } @@ -599,6 +800,7 @@ void FrameRecorder::start() { allocationsGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); ranges = committedRanges(); writer = std::make_unique(directory); + notingGpuStores = true; std::vector> written; for (auto& range : ranges) { if (range.kind == FrameRangeKind::Watched || range.kind == FrameRangeKind::Unwatched) range.since = GuestMemory::CollectWrittenBlocks(range.address, static_cast(range.bytes), std::numeric_limits::max(), written); @@ -659,10 +861,15 @@ void FrameRecorder::finish() { writer->WriteCall(end); writeReferenceFrames(); writer->Finish(header()); + const auto costs = writer->Costs(); + std::fprintf(stderr, "[frame-capture] delta costs: %.1f MiB of unwatched pages changed, found by compares taking %.2f s, %llu repeated parts compared in %.2f s, %llu parts evicted from the delta cache\n", + static_cast(unwatchedChangedBytes) / (1024.0 * 1024.0), unwatchedCompareSeconds, static_cast(costs.compared), costs.compareSeconds, + static_cast(costs.evicted)); std::fprintf(stderr, "[frame-capture] %llu frames, %llu calls, %llu memory deltas (%.1f MiB), %.1f MiB raw, %.1f MiB stored in %s\n", static_cast(recordedFrames), static_cast(recordedCalls), static_cast(deltaGroups), static_cast(deltaBytes) / (1024.0 * 1024.0), static_cast(writer->RawBytes()) / (1024.0 * 1024.0), static_cast(writer->StoredBytes()) / (1024.0 * 1024.0), directory.string().c_str()); writer.reset(); + endGpuStores(); state = State::Done; } @@ -677,7 +884,7 @@ std::string FrameRecorder::header() const { text += ",\"start_boundary\":" + std::to_string(startBoundary) + ",\"frames\":" + std::to_string(recordedFrames); text += ",\"calls\":" + std::to_string(recordedCalls) + ",\"prologue_calls\":" + std::to_string(prologue.size()); text += ",\"ranges\":" + std::to_string(ranges.size()) + ",\"late_ranges\":" + std::to_string(lateRanges) + ",\"snapshot_bytes\":" + std::to_string(snapshotBytes) + ",\"unreadable_bytes\":" + std::to_string(unreadableBytes) + ",\"host_only_sample_bytes\":" + std::to_string(hostOnlySampleBytes); - text += ",\"memory_groups\":" + std::to_string(deltaGroups) + ",\"delta_bytes\":" + std::to_string(deltaBytes); + text += ",\"memory_groups\":" + std::to_string(deltaGroups) + ",\"delta_bytes\":" + std::to_string(deltaBytes) + ",\"gpu_store_bytes\":" + std::to_string(gpuStoreBytes) + ",\"shared_delta_bytes\":" + std::to_string(writer->SharedBytes()); text += ",\"capture_seconds\":" + std::to_string(std::chrono::duration(std::chrono::steady_clock::now() - startedAt).count()); text += ",\"env\":{"; bool first = true; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp index 03c4d7c0d4f2..ec67b2a97f30 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp @@ -1791,6 +1791,7 @@ struct WriteTracker { std::vector unstampedStores; void noteUnstampedStore(std::uint64_t address, std::uint64_t end) { + ForgetComparedPages(address, static_cast(end - address)); if (unstampedStores.empty()) unstampedStores.assign(UnstampedSlots, 0); const auto first = address / WriteBlockBytes; const auto last = (end - 1) / WriteBlockBytes; @@ -2712,17 +2713,39 @@ void SetLeftWatchCompare(bool compare) { comparedPages.clear(); } +static std::optional hashComparedPage(std::uint64_t page, std::uint64_t address, std::span bytes) { + if (page >= address && page + WritePageBytes <= address + bytes.size()) return HashPage(bytes.data() + (page - address)); + const auto* guest = reinterpret_cast(static_cast(page)); + if (!Accessible(guest, WritePageBytes)) return std::nullopt; + std::array merged; + std::memcpy(merged.data(), guest, WritePageBytes); + const auto from = std::max(page, address); + const auto to = std::min(page + WritePageBytes, address + bytes.size()); + std::memcpy(merged.data() + (from - page), bytes.data() + (from - address), static_cast(to - from)); + return HashPage(merged.data()); +} + void SeedComparedPages(std::uint64_t address, std::span bytes) { - if (!leftWatchCompare.load(std::memory_order_acquire)) return; - const auto first = (address + WritePageBytes - 1) & ~std::uint64_t{WritePageBytes - 1}; + if (!leftWatchCompare.load(std::memory_order_acquire) || bytes.empty()) return; const std::lock_guard lock(comparedMutex); - for (auto page = first; page + WritePageBytes <= address + bytes.size(); page += WritePageBytes) comparedPages[page] = {HashPage(bytes.data() + (page - address)), true}; + eachPage(address, bytes.size(), [&](std::uint64_t page) { + if (const auto hash = hashComparedPage(page, address, bytes)) comparedPages[page] = {*hash, true}; + }); } void UpdateComparedPages(std::uint64_t address, std::span bytes) { - const auto first = (address + WritePageBytes - 1) & ~std::uint64_t{WritePageBytes - 1}; + if (bytes.empty()) return; + const std::lock_guard lock(comparedMutex); + for (auto found = comparedPages.lower_bound(address & ~std::uint64_t{WritePageBytes - 1}); found != comparedPages.end() && found->first < address + bytes.size(); ++found) { + const auto hash = hashComparedPage(found->first, address, bytes); + found->second = {hash.value_or(0), hash.has_value()}; + } +} + +void ForgetComparedPages(std::uint64_t address, std::size_t bytes) { + if (!leftWatchCompare.load(std::memory_order_acquire) || bytes == 0 || bytes > std::numeric_limits::max() - address) return; const std::lock_guard lock(comparedMutex); - for (auto found = comparedPages.lower_bound(first); found != comparedPages.end() && found->first + WritePageBytes <= address + bytes.size(); ++found) found->second = {HashPage(bytes.data() + (found->first - address)), true}; + for (auto found = comparedPages.lower_bound(address & ~std::uint64_t{WritePageBytes - 1}); found != comparedPages.end() && found->first < address + bytes; ++found) found->second.known = false; } void ChangedComparedPages(std::uint64_t address, std::size_t bytes, std::vector>& changed) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp index 06333599db48..07617d71b1b5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Pm4.cpp @@ -1,6 +1,7 @@ #include "prx/libkernel/include/Api.hpp" #include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/FrameRecorder.hpp" #include "prx/libc/include/General.hpp" #include "prx/libc/include/PreciseWait.hpp" #include "RdnaDecoder/RdnaInstructionDecoder.hpp" @@ -194,10 +195,15 @@ std::vector dmaSourceBytes(std::span packet) { return copySource(GdsAddress() + packet[2], bytes, false); } +void driverStore(std::uint64_t destination, std::span bytes, std::size_t alignment = 1) { + GuestMemory::Write(destination, bytes, alignment); + FrameRecorder::NoteGpuStore(destination, bytes); +} + void copyMemory(std::uint64_t source, std::uint64_t destination, std::size_t bytes, bool immediate) { if (bytes == 0) return; GuestMemory::CheckRange(reinterpret_cast(destination), bytes, 1, true); - GuestMemory::Write(destination, copySource(source, bytes, immediate)); + driverStore(destination, copySource(source, bytes, immediate)); } constexpr std::uint32_t CopyDataRegisterSource = 0; @@ -1245,10 +1251,12 @@ void Execute(std::span packet, QueueState& queue) { if ((packet[3] >> 29u) == 6u) { prepare(); const bool set = (packet[3] & 0x100000u) != 0; + std::uint64_t stored = 1; GuestMemory::StoreOwnBytes(semaphore, sizeof(*word), [&] { if (set) shared.store(1, std::memory_order_release); - else shared.fetch_add(1, std::memory_order_acq_rel); + else stored = shared.fetch_add(1, std::memory_order_acq_rel) + 1; }); + FrameRecorder::NoteGpuStore(semaphore, std::as_bytes(std::span(&stored, 1))); return; } const auto start = std::chrono::steady_clock::now(); @@ -1264,8 +1272,10 @@ void Execute(std::span packet, QueueState& queue) { GuestMemory::StoreOwnBytes(semaphore, sizeof(*word), [&] { taken = shared.compare_exchange_strong(value, value - 1, std::memory_order_acq_rel); }); - if (taken) return; - continue; + if (!taken) continue; + const auto stored = value - 1; + FrameRecorder::NoteGpuStore(semaphore, std::as_bytes(std::span(&stored, 1))); + return; } PreciseSleepUs(50); if (!warned && std::chrono::steady_clock::now() - start > std::chrono::seconds(5)) { @@ -1281,7 +1291,7 @@ void Execute(std::span packet, QueueState& queue) { const auto destination = address(packet[3], packet[4]); if (dataSelect == 0 || destination == 0) return; const auto value = ReleaseMemValue(packet); - GuestMemory::Write(destination, std::as_bytes(std::span(&value, 1)).first(dataSelect == 1 ? 4 : 8), dataSelect == 1 ? 4 : 8); + driverStore(destination, std::as_bytes(std::span(&value, 1)).first(dataSelect == 1 ? 4 : 8), dataSelect == 1 ? 4 : 8); return; } case 0x51: { @@ -1302,7 +1312,7 @@ void Execute(std::span packet, QueueState& queue) { return; case 0x83: { const auto dump = DecodeConstantRamDump(packet); - GuestMemory::Write(dump.destination, std::as_bytes(queue.ConstantRam().subspan(dump.offset / 4, dump.words)), 4); + driverStore(dump.destination, std::as_bytes(queue.ConstantRam().subspan(dump.offset / 4, dump.words)), 4); return; } case 0x45: { @@ -1324,7 +1334,7 @@ void Execute(std::span packet, QueueState& queue) { } return; } - if (waitCompares(packet, false, value)) GuestMemory::Write(write.destination, std::as_bytes(std::span(&write.value, 1)), 4); + if (waitCompares(packet, false, value)) driverStore(write.destination, std::as_bytes(std::span(&write.value, 1)), 4); return; } case 0x37: { @@ -1335,8 +1345,8 @@ void Execute(std::span packet, QueueState& queue) { } const auto destination = address(packet[2], packet[3]); if ((packet[1] & 0x10000u) != 0) { - for (const auto& value : packet.subspan(4)) GuestMemory::Write(destination, std::as_bytes(std::span(&value, 1)), 4); - } else GuestMemory::Write(destination, std::as_bytes(packet.subspan(4)), 4); + for (const auto& value : packet.subspan(4)) driverStore(destination, std::as_bytes(std::span(&value, 1)), 4); + } else driverStore(destination, std::as_bytes(packet.subspan(4)), 4); return; } case 0x40: { @@ -1351,7 +1361,7 @@ void Execute(std::span packet, QueueState& queue) { const auto destination = CopyDataDestination(packet) == CopyDataSelectGds ? GdsAddress() + packet[4] : address(packet[4], packet[5]); const auto data = copyDataSource(packet, queue, CopyDataBytes(packet)); GuestMemory::CheckRange(reinterpret_cast(destination), data.size(), 1, true); - GuestMemory::Write(destination, data); + driverStore(destination, data); return; } case 0x28: return; @@ -1361,7 +1371,7 @@ void Execute(std::span packet, QueueState& queue) { auto data = dmaSourceBytes(packet); const auto destination = dmaDestination(packet) == DmaSelectGds ? GdsAddress() + packet[4] : address(packet[4], packet[5]); GuestMemory::CheckRange(reinterpret_cast(destination), bytes, 1, true); - GuestMemory::Write(destination, data); + driverStore(destination, data); return; } default: throw std::runtime_error("packet requires driver execution"); diff --git a/core/libs/prx/libSceAgcDriver/tests/FrameCapture.cpp b/core/libs/prx/libSceAgcDriver/tests/FrameCapture.cpp index 97cf6b9762df..f56b905174f7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/FrameCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/FrameCapture.cpp @@ -158,7 +158,7 @@ void testRoundTrip(const std::filesystem::path& directory) { const FrameCaptureReader reader(directory); check(!reader.Truncated(), "a finished capture reads as truncated"); - check(reader.Version() == 2, "a capture this build wrote reads as calls format " + std::to_string(reader.Version()) + ", not 2"); + check(reader.Version() == 3, "a capture this build wrote reads as calls format " + std::to_string(reader.Version()) + ", not 3"); check(reader.Header() == "{\"magic\":\"aps5-frame-capture 1\"}\n", "header does not round-trip"); check(reader.Calls().size() == calls.size(), "call count does not round-trip"); for (std::size_t index = 0; index < calls.size(); ++index) check(sameCall(reader.Calls()[index], calls[index]), "call " + std::to_string(index) + " does not round-trip"); @@ -202,14 +202,13 @@ void testTruncated(const std::filesystem::path& source, const std::filesystem::p check(reader.Chunks().back().kind != FrameMemoryKind::Delta, "a cut memory chunk is not dropped"); } -void testVersionOne(const std::filesystem::path& source, const std::filesystem::path& directory) { +void testOlderVersion(const std::filesystem::path& source, const std::filesystem::path& directory, std::string_view magic, std::uint32_t expected) { std::filesystem::remove_all(directory); std::filesystem::copy(source, directory, std::filesystem::copy_options::recursive); - constexpr std::string_view VersionOne = "aps5-frame-calls 1\n"; { std::fstream file(directory / FrameCaptureWriter::CallsName, std::ios::binary | std::ios::in | std::ios::out); - file.write(VersionOne.data(), static_cast(VersionOne.size())); - check(file.good(), "cannot write the calls format 1 magic"); + file.write(magic.data(), static_cast(magic.size())); + check(file.good(), "cannot write the calls format " + std::to_string(expected) + " magic"); } std::uint32_t version = 0; std::vector readBack; @@ -218,12 +217,12 @@ void testVersionOne(const std::filesystem::path& source, const std::filesystem:: version = reader.Version(); readBack = reader.Calls(); } catch (const std::runtime_error& error) { - check(false, std::string("a calls format 1 capture does not read: ") + error.what()); + check(false, "a calls format " + std::to_string(expected) + " capture does not read: " + error.what()); } - check(version == 1, "a calls format 1 capture reads as format " + std::to_string(version)); + check(version == expected, "a calls format " + std::to_string(expected) + " capture reads as format " + std::to_string(version)); const auto calls = sampleCalls(); - check(readBack.size() == calls.size(), "a calls format 1 capture reads " + std::to_string(readBack.size()) + " calls, not " + std::to_string(calls.size())); - for (std::size_t index = 0; index < calls.size(); ++index) check(sameCall(readBack[index], calls[index]), "call " + std::to_string(index) + " of a calls format 1 capture does not round-trip"); + check(readBack.size() == calls.size(), "a calls format " + std::to_string(expected) + " capture reads " + std::to_string(readBack.size()) + " calls, not " + std::to_string(calls.size())); + for (std::size_t index = 0; index < calls.size(); ++index) check(sameCall(readBack[index], calls[index]), "call " + std::to_string(index) + " of a calls format " + std::to_string(expected) + " capture does not round-trip"); } void testCorrupt(const std::filesystem::path& source, const std::filesystem::path& directory) { @@ -240,6 +239,167 @@ void testCorrupt(const std::filesystem::path& source, const std::filesystem::pat checkThrows([&] { FrameCaptureReader reader(directory); }, "a file without the magic does not throw"); } +std::vector filled(std::size_t bytes, std::uint8_t seed) { + std::vector result(bytes); + for (std::size_t at = 0; at < bytes; ++at) result[at] = static_cast((at * 13 + seed) & 0xff); + return result; +} + +std::vector deltaChunks(const FrameCaptureReader& reader) { + std::vector deltas; + for (const auto& chunk : reader.Chunks()) { + if (chunk.kind == FrameMemoryKind::Delta) deltas.push_back(chunk); + } + return deltas; +} + +struct DeltaWrite { + std::uint64_t address = 0; + const std::vector* bytes = nullptr; + std::size_t source = 0; +}; + +void checkDeltaWrites(const std::filesystem::path& directory, std::uint64_t cacheBudget, const std::vector& writes, std::uint64_t compared, std::uint64_t evicted, const std::string& what) { + std::uint64_t shared = 0; + { + FrameCaptureWriter writer(directory, 1, cacheBudget); + for (std::size_t index = 0; index < writes.size(); ++index) { + writer.WriteDelta(index + 1, index + 1, writes[index].address, *writes[index].bytes); + if (writes[index].source != index) shared += writes[index].bytes->size(); + } + const auto costs = writer.Costs(); + check(costs.compared == compared && costs.evicted == evicted, + what + ": the writer compared " + std::to_string(costs.compared) + " parts and evicted " + std::to_string(costs.evicted) + ", not " + std::to_string(compared) + " and " + std::to_string(evicted)); + check(writer.SharedBytes() == shared, what + ": the writer shares " + std::to_string(writer.SharedBytes()) + " bytes, not " + std::to_string(shared)); + writer.Finish("{}"); + } + const FrameCaptureReader reader(directory); + const auto deltas = deltaChunks(reader); + check(deltas.size() == writes.size(), what + ": the capture reads back " + std::to_string(deltas.size()) + " deltas, not " + std::to_string(writes.size())); + for (std::size_t index = 0; index < writes.size(); ++index) { + const auto name = what + ": delta " + std::to_string(index); + check(deltas[index].group == index + 1 && deltas[index].address == writes[index].address, name + " is out of order"); + check(deltas[index].offset == deltas[writes[index].source].offset, name + " does not share the payload of delta " + std::to_string(writes[index].source)); + for (std::size_t earlier = 0; writes[index].source == index && earlier < index; ++earlier) check(deltas[earlier].offset != deltas[index].offset, name + " shares the payload of delta " + std::to_string(earlier)); + check(reader.Read(deltas[index]) == *writes[index].bytes, name + " does not read back"); + } +} + +constexpr std::uint64_t DeltaAddress = 0x3000000000; + +void testSharedDeltas(const std::filesystem::path& directory) { + const auto first = filled(FrameCaptureWriter::BlockBytes, 1); + const auto second = filled(FrameCaptureWriter::BlockBytes, 2); + checkDeltaWrites(directory, FrameCaptureWriter::CachedDeltaBytes, + {{DeltaAddress, &first, 0}, {DeltaAddress, &first, 0}, {DeltaAddress, &second, 2}, {DeltaAddress + 4096, &second, 3}, {DeltaAddress, &second, 2}}, 3, 0, "shared"); +} + +void testChangedDeltas(const std::filesystem::path& directory) { + const auto first = filled(FrameCaptureWriter::BlockBytes, 3); + auto last = first; + last.back() ^= std::byte{1}; + checkDeltaWrites(directory, FrameCaptureWriter::CachedDeltaBytes, {{DeltaAddress, &first, 0}, {DeltaAddress, &last, 1}, {DeltaAddress, &first, 2}, {DeltaAddress, &first, 2}}, 3, 0, "changed last byte"); +} + +void testEvictedDeltas(const std::filesystem::path& directory) { + const auto a = filled(FrameCaptureWriter::BlockBytes, 5); + const auto b = filled(FrameCaptureWriter::BlockBytes, 6); + const auto c = filled(FrameCaptureWriter::BlockBytes, 7); + constexpr auto Step = FrameCaptureWriter::BlockBytes; + checkDeltaWrites(directory, 2 * FrameCaptureWriter::BlockBytes, + {{DeltaAddress, &a, 0}, + {DeltaAddress + Step, &b, 1}, + {DeltaAddress + 2 * Step, &c, 2}, + {DeltaAddress + 2 * Step, &c, 2}, + {DeltaAddress + Step, &b, 1}, + {DeltaAddress, &a, 5}, + {DeltaAddress + 2 * Step, &c, 6}, + {DeltaAddress, &a, 5}}, + 3, 3, "least recently used evicted"); +} + +void testOversizedDelta(const std::filesystem::path& directory) { + const auto small = filled(FrameCaptureWriter::BlockBytes, 8); + const auto large = filled(2 * FrameCaptureWriter::BlockBytes, 9); + checkDeltaWrites(directory, FrameCaptureWriter::BlockBytes, {{DeltaAddress, &small, 0}, {DeltaAddress + 0x100000, &large, 1}, {DeltaAddress + 0x100000, &large, 2}, {DeltaAddress, &small, 0}}, 1, 0, "larger than the cache"); +} + +void testResizedDeltas(const std::filesystem::path& directory) { + const auto whole = filled(FrameCaptureWriter::BlockBytes, 10); + const std::vector half(whole.begin(), whole.begin() + FrameCaptureWriter::BlockBytes / 2); + checkDeltaWrites(directory, FrameCaptureWriter::CachedDeltaBytes, {{DeltaAddress, &whole, 0}, {DeltaAddress, &half, 1}, {DeltaAddress, &whole, 0}, {DeltaAddress, &half, 1}}, 2, 0, "resized"); +} + +void testConcurrentDeltas(const std::filesystem::path& directory) { + constexpr std::size_t Threads = 8; + constexpr std::size_t Writes = 64; + constexpr std::size_t Addresses = 3; + const std::vector> patterns{filled(FrameCaptureWriter::BlockBytes, 11), filled(FrameCaptureWriter::BlockBytes, 12)}; + const auto pattern = [&](std::uint64_t group) -> const std::vector& { return patterns[(group / 6) % patterns.size()]; }; + const auto address = [](std::uint64_t group) { return DeltaAddress + (group / 2 % Addresses) * FrameCaptureWriter::BlockBytes; }; + { + FrameCaptureWriter writer(directory, 1, 2 * FrameCaptureWriter::BlockBytes); + std::vector threads; + for (std::size_t thread = 0; thread < Threads; ++thread) { + threads.emplace_back([&, thread] { + for (std::size_t index = 0; index < Writes; ++index) { + const std::uint64_t group = thread * Writes + index; + writer.WriteDelta(group, group, address(group), pattern(group)); + } + }); + } + for (auto& thread : threads) thread.join(); + check(writer.Costs().evicted != 0, "the concurrent writers never evicted a part from a cache smaller than the parts they wrote"); + writer.Finish("{}"); + } + const FrameCaptureReader reader(directory); + const auto deltas = deltaChunks(reader); + check(deltas.size() == Threads * Writes, "the concurrent capture reads back " + std::to_string(deltas.size()) + " deltas"); + for (const auto& delta : deltas) { + check(delta.address == address(delta.group) && reader.Read(delta) == pattern(delta.group), "concurrent delta of group " + std::to_string(delta.group) + " does not read back what was written"); + } +} + +void testMemoryFormatOne(const std::filesystem::path& source, const std::filesystem::path& directory) { + std::filesystem::remove_all(directory); + std::filesystem::copy(source, directory, std::filesystem::copy_options::recursive); + { + std::fstream file(directory / FrameCaptureWriter::MemoryName, std::ios::binary | std::ios::in | std::ios::out); + file.write(FrameCaptureWriter::MemoryMagicV1.data(), static_cast(FrameCaptureWriter::MemoryMagicV1.size())); + check(file.good(), "cannot write the memory format 1 magic"); + } + const FrameCaptureReader current(source); + const FrameCaptureReader older(directory); + check(older.Chunks().size() == current.Chunks().size(), "a memory format 1 capture reads a different number of chunks"); + for (std::size_t index = 0; index < older.Chunks().size(); ++index) { + const auto& chunk = older.Chunks()[index]; + check(chunk.kind == current.Chunks()[index].kind && chunk.address == current.Chunks()[index].address && chunk.offset == current.Chunks()[index].offset, "memory format 1 chunk " + std::to_string(index) + " does not read as written"); + if (chunk.kind == FrameMemoryKind::Delta) check(older.Read(chunk) == current.Read(current.Chunks()[index]), "a memory format 1 delta does not read back"); + } +} + +void writeLastShared(const std::filesystem::path& directory, std::uint64_t value) { + std::fstream file(directory / FrameCaptureWriter::MemoryName, std::ios::binary | std::ios::in | std::ios::out); + file.seekp(-static_cast(sizeof(value)), std::ios::end); + file.write(reinterpret_cast(&value), sizeof(value)); + check(file.good(), "cannot rewrite the shared payload field"); +} + +void testMalformedReference(const std::filesystem::path& source, const std::filesystem::path& directory) { + const FrameCaptureReader reader(source); + const auto deltas = deltaChunks(reader); + const auto& last = reader.Chunks().back(); + check(last.offset == deltas[2].offset && last.address == deltas[2].address, "the shared fixture does not end with a shared delta"); + const std::vector> cases{ + {deltas[0].offset + 1, "a shared offset inside a payload"}, {deltas[3].offset, "a shared payload of another address"}, {std::uint64_t{1} << 40, "a shared offset past the file"}}; + for (const auto& [value, what] : cases) { + std::filesystem::remove_all(directory); + std::filesystem::copy(source, directory, std::filesystem::copy_options::recursive); + writeLastShared(directory, value); + checkThrowsText([&] { FrameCaptureReader broken(directory); }, "frame capture: ", true, what + " is accepted"); + } +} + void testWriter(const std::filesystem::path& directory) { FrameCaptureWriter writer(directory); writer.Finish("{}"); @@ -400,9 +560,18 @@ int main(int argc, char** argv) { testReadAroundRanges(); testRoundTrip(root / "capture"); testTruncated(root / "capture", root / "truncated"); - testVersionOne(root / "capture", root / "version-one"); + testOlderVersion(root / "capture", root / "version-one", "aps5-frame-calls 1\n", 1); + testOlderVersion(root / "capture", root / "version-two", "aps5-frame-calls 2\n", 2); testCorrupt(root / "capture", root / "corrupt"); testWriter(root / "writer"); + testSharedDeltas(root / "shared"); + testChangedDeltas(root / "changed"); + testEvictedDeltas(root / "evicted"); + testOversizedDelta(root / "oversized"); + testResizedDeltas(root / "resized"); + testConcurrentDeltas(root / "concurrent"); + testMemoryFormatOne(root / "capture", root / "memory-one"); + testMalformedReference(root / "shared", root / "malformed"); std::filesystem::remove_all(root); std::puts("frame capture tests passed"); return 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/FrameCaptureFilter.cpp b/core/libs/prx/libSceAgcDriver/tests/FrameCaptureFilter.cpp index 72e002fe6a43..e44a9b559c0e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/FrameCaptureFilter.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/FrameCaptureFilter.cpp @@ -305,6 +305,25 @@ void testNormalizedSourceAlias(const std::filesystem::path& root) { } +void testFormatTwoWaits(const std::filesystem::path& root) { + const auto source = root / "format-two"; + const auto output = root / "format-two-filtered"; + { + AgcDriver::FrameCaptureWriter writer(source, 1, AgcDriver::FrameCaptureWriter::CachedDeltaBytes, 2); + AgcDriver::FrameCall memory; + memory.kind = AgcDriver::FrameCallKind::Memory; + memory.ordinal = 1; + memory.values = {7, 1, 0x11000}; + writer.WriteCall(memory); + writer.WriteDelta(7, 3, 0x11000, std::vector(64, std::byte{0x52})); + writer.Finish("{}"); + } + AgcDriverTools::FilterFrameCapture(source, output, {}); + const AgcDriver::FrameCaptureReader filtered(output); + check(filtered.Version() == 2, "filtering a calls format 2 capture wrote calls format " + std::to_string(filtered.Version()) + ", whose parked waits carry four values each"); + check(filtered.Calls().size() == 1 && filtered.Calls()[0].values == std::vector{7, 1, 0x11000}, "filtering changed the parked wait of a calls format 2 memory call"); +} + void testRangeMetadata(const std::filesystem::path& root) { const auto source = root / "source"; const auto output = root / "range-copy"; @@ -339,6 +358,7 @@ int main() { testTruncatedCapture(root); testNormalizedSourceAlias(root); testRangeMetadata(root); + testFormatTwoWaits(root); std::filesystem::remove_all(root); std::filesystem::create_directories(root); testCallFilter(root); diff --git a/core/libs/prx/libSceAgcDriver/tests/FrameReplay.cpp b/core/libs/prx/libSceAgcDriver/tests/FrameReplay.cpp index e0c067ab93b5..d751b3630c16 100644 --- a/core/libs/prx/libSceAgcDriver/tests/FrameReplay.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/FrameReplay.cpp @@ -36,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -45,6 +46,9 @@ #include #ifdef _WIN32 #include +#else +#include +#include #endif namespace AgcDriver::DriverDetail { @@ -598,9 +602,11 @@ class RewindCapture { call.thread = 1; call.accepted = submitted; call.completed = submitted - inFlight; + std::vector addresses; + for (const auto index : parked) addresses.push_back(address(index)); + std::sort(addresses.begin(), addresses.end()); call.values = {group, parked.size()}; - for (const auto index : parked) call.values.push_back(address(index)); - std::sort(call.values.begin() + 2, call.values.end()); + for (const auto parkedAt : addresses) call.values.insert(call.values.end(), {parkedAt, 0, 0, 0}); writer.WriteCall(call); } @@ -1281,7 +1287,113 @@ void testStoreAfterGatedCopy(const std::filesystem::path& tool) { check(replayed(tool, checkCapture(1), layout.firstTarget, DataBytes) == stored, "the replay applied the CPU store before the copy that preceded it"); } -void testCopyInFlightAtDelta(const std::filesystem::path& tool) { +void checkStoreAfterCopyBehindIdleWait(const std::filesystem::path& tool, bool rewound) { + const auto layout = allocate(); + const auto copied = pattern(7); + const auto stored = pattern(211); + std::memcpy(layout.source, copied.data(), copied.size()); + auto output = std::make_shared(); + AgcDriverRegisterVideoOutput_nid_postfix(Handle, output); + + flip(); + const auto gatedCopy = [&](CommandBuffer& buffer) { + sceAgcDcbDmaData(&buffer, 0, DmaMemory, 0, at(layout.firstTarget), DmaMemory, 0, at(layout.source), DataBytes, 0, 1, 0); + writeDone(buffer, layout.label); + }; + if (rewound) { + release(submitRewound(layout.firstCommands, [](CommandBuffer&) {}, gatedCopy)); + } else { + auto* const gate = layout.label + 1; + auto buffer = commands(layout.firstCommands); + sceAgcDcbWaitRegMem(&buffer, 0, 3, 0, 0, gate, Done, 0xffffffffu, 0); + gatedCopy(buffer); + Packet packet{layout.firstCommands, static_cast(buffer.cursor_up - layout.firstCommands), 0, {}}; + check(sceAgcDriverSubmitDcb(&packet) == 0, "submission failed"); + std::atomic_ref(*gate).store(Done, std::memory_order_release); + } + waitUntil([&] { return std::atomic_ref(*layout.label).load() == Done; }, "the gated copy did not run"); + std::memcpy(layout.firstTarget, stored.data(), stored.size()); + flip(); + flip(); + AgcDriverWaitIdle_nid_postfix(); + check(equal(layout.firstTarget, stored), "the driver did not finish the gated copy before the CPU store"); + check(replayed(tool, checkCapture(0), layout.firstTarget, DataBytes, " --no-release") == stored, rewound ? "the replay applied the CPU store before the copy in the tail of the REWIND that preceded it" : "the replay applied the CPU store before the gated copy that preceded it"); +} + +void testStoreAfterGatedCopyIdle(const std::filesystem::path& tool) { + checkStoreAfterCopyBehindIdleWait(tool, false); +} + +void testStoreAfterRewoundCopyIdle(const std::filesystem::path& tool) { + checkStoreAfterCopyBehindIdleWait(tool, true); +} + +void testStoreBeforeSecondWaitOnGate(const std::filesystem::path& tool) { + const auto layout = allocate(); + const auto copied = pattern(7); + const auto stored = pattern(211); + std::memcpy(layout.source, copied.data(), copied.size()); + auto output = std::make_shared(); + AgcDriverRegisterVideoOutput_nid_postfix(Handle, output); + + flip(); + auto* const gate = layout.label + 1; + auto buffer = commands(layout.firstCommands); + sceAgcDcbWaitRegMem(&buffer, 0, 3, 0, 0, gate, Done, 0xffffffffu, 0); + sceAgcDcbDmaData(&buffer, 0, DmaMemory, 0, at(layout.firstTarget), DmaMemory, 0, at(layout.source), DataBytes, 0, 1, 0); + writeDone(buffer, layout.label); + sceAgcDcbWaitRegMem(&buffer, 0, 3, 0, 0, gate, Done + 1, 0xffffffffu, 0); + Packet packet{layout.firstCommands, static_cast(buffer.cursor_up - layout.firstCommands), 0, {}}; + check(sceAgcDriverSubmitDcb(&packet) == 0, "submission failed"); + std::atomic_ref(*gate).store(Done, std::memory_order_release); + waitUntil([&] { return std::atomic_ref(*layout.label).load() == Done; }, "the gated copy did not run"); + std::memcpy(layout.firstTarget, stored.data(), stored.size()); + flip(); + std::atomic_ref(*gate).store(Done + 1, std::memory_order_release); + flip(); + AgcDriverWaitIdle_nid_postfix(); + check(equal(layout.firstTarget, stored), "the driver did not finish the gated copy before the CPU store"); + check(replayed(tool, checkCapture(1), layout.firstTarget, DataBytes, " --no-release") == stored, "the replay ran the copy behind the gate's first wait after restoring the CPU store the capture read while the queue waited on the gate's second value"); +} + +void testUnwatchedStoreBeforeReservation(const std::filesystem::path& tool) { + const auto layout = allocate(); + const auto copied = pattern(7); + const auto stored = pattern(211); + std::memcpy(layout.source, copied.data(), copied.size()); + AgcDriver::GuestMemory::Unwatch(at(layout.firstTarget), DataBytes); + check(!AgcDriver::GuestMemory::Watched(at(layout.firstTarget), DataBytes), "the copy target did not lose write-watch coverage"); + auto output = std::make_shared(); + AgcDriverRegisterVideoOutput_nid_postfix(Handle, output); + + flip(); + auto* const gate = layout.label + 1; + auto gated = commands(layout.firstCommands); + sceAgcDcbWaitRegMem(&gated, 0, 3, 0, 0, gate, Done, 0xffffffffu, 0); + sceAgcDcbDmaData(&gated, 0, DmaMemory, 0, at(layout.firstTarget), DmaMemory, 0, at(layout.source), DataBytes, 0, 1, 0); + writeDone(gated, layout.label); + Packet packet{layout.firstCommands, static_cast(gated.cursor_up - layout.firstCommands), 0, {}}; + check(sceAgcDriverSubmitDcb(&packet) == 0, "submission failed"); + std::atomic_ref(*gate).store(Done, std::memory_order_release); + waitUntil([&] { return std::atomic_ref(*layout.label).load() == Done; }, "the gated copy did not run"); + std::memcpy(layout.firstTarget, stored.data(), stored.size()); + const auto token = AgcDriverReserveEopFlip_nid_postfix(AgcDriver::FlipInfo{Handle, -1, 1, 0}); + check(token != 0, "the EOP flip was not reserved"); + auto reading = commands(layout.secondCommands); + sceAgcDcbDmaData(&reading, 0, DmaMemory, 0, at(layout.secondTarget), DmaMemory, 0, at(layout.firstTarget), DataBytes, 0, 1, 0); + const auto flipped = at(layout.label + 2); + const std::array eop{0xc0064900u, 0x06200504u, 0x42010000u, static_cast(flipped), static_cast(flipped >> 32u), Done, 0u, token}; + std::memcpy(reading.cursor_up, eop.data(), sizeof(eop)); + reading.cursor_up += eop.size(); + Packet flipping{layout.secondCommands, static_cast(reading.cursor_up - layout.secondCommands), 0, {}}; + check(sceAgcDriverSubmitDcb(&flipping) == 0, "the flipping submission failed"); + flip(); + AgcDriverWaitIdle_nid_postfix(); + check(equal(layout.secondTarget, stored), "the driver did not copy the CPU store"); + check(replayed(tool, checkCapture(0), layout.secondTarget, DataBytes, " --no-release") == stored, "the replay copied the gated copy's bytes, not the CPU store recorded before the EOP flip reservation"); +} + +void copyInFlightAtDelta(const std::filesystem::path& tool, bool held) { constexpr std::size_t CopyBytes = 128u << 20; constexpr std::size_t ChunkBytes = CopyBytes / 8; constexpr std::size_t Stored = 64; @@ -1300,6 +1412,18 @@ void testCopyInFlightAtDelta(const std::filesystem::path& tool) { sceAgcDcbDmaData(&buffer, 0, DmaMemory, 0, at(target + Stored + offset), DmaMemory, 0, at(source + offset), bytes, 0, 1, 0); } }, [&](CommandBuffer& buffer) { writeDone(buffer, layout.label); }); + if (held) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + const auto copying = [&] { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + const auto* recorder = AgcDriver::Graphics::Recorder::Active(); + return recorder != nullptr && recorder->PendingWriteOverlaps(at(target + Stored), 4096 - Stored); + }; + while (!copying()) { + if (std::chrono::steady_clock::now() >= deadline) throw Inconclusive("the GPU copy into the stored page never became pending"); + std::this_thread::yield(); + } + } std::memset(target, 0x5a, Stored); const auto gpuWaits = AgcDriver::Graphics::Recorder::ThreadHookWaits(); flip(); @@ -1314,6 +1438,14 @@ void testCopyInFlightAtDelta(const std::filesystem::path& tool) { if (!inFlight) throw Inconclusive("the GPU copy finished before the memory delta was read"); } +void testCopyInFlightAtDelta(const std::filesystem::path& tool) { + copyInFlightAtDelta(tool, false); +} + +void testStoreBesideHeldCopy(const std::filesystem::path& tool) { + copyInFlightAtDelta(tool, true); +} + void testComputeWaitBehindRewind(const std::filesystem::path& tool) { constexpr std::uint32_t ComputeQueue = 0x20; const auto layout = allocate(); @@ -1463,6 +1595,351 @@ void testRewindFilledAcrossChunks(const std::filesystem::path& tool) { check(replayed(tool, checkCapture(0), layout.label, 4) == std::vector{std::byte{Done}, std::byte{0}, std::byte{0}, std::byte{0}}, "the replay resumed the REWIND before the delta restored the buffer its tail jumps to"); } +bool deltaStoredBytes(const FrameCaptureReader& reader, const std::uint32_t* address) { + return std::any_of(reader.Chunks().begin(), reader.Chunks().end(), [&](const auto& chunk) { + if (chunk.kind != FrameMemoryKind::Delta || chunk.address >= at(address) + 4 || at(address) >= chunk.address + chunk.bytes) return false; + const auto bytes = reader.Read(chunk); + const auto first = std::max(chunk.address, at(address)); + const auto last = std::min(chunk.address + chunk.bytes, at(address) + 4); + return std::any_of(bytes.begin() + static_cast(first - chunk.address), bytes.begin() + static_cast(last - chunk.address), [](std::byte value) { return value != std::byte{0}; }); + }); +} + +void checkGpuStoreBehindRewind(const std::filesystem::path& tool, bool halfStored) { + constexpr std::uint32_t ComputeQueue = 0x20; + constexpr std::uint32_t Half = 0x5a5au; + const std::uint32_t releasedValue = halfStored ? Done | (Half << 16u) : Done; + constexpr std::uint32_t Filled = 0x5a5a5a5au; + constexpr std::size_t FillBytes = 0x3fff000u; + constexpr std::size_t Fills = 4; + const auto layout = allocate(); + const auto bulk = allocate(Fills * FillBytes); + const auto read = pattern(41); + std::memcpy(layout.source, read.data(), read.size()); + auto output = std::make_shared(); + AgcDriverRegisterVideoOutput_nid_postfix(Handle, output); + + flip(); + auto* const released = layout.label + 1; + auto* const title = layout.label + 2; + auto* const copied = layout.label + 3; + auto* const filled = reinterpret_cast(bulk.base + Fills * FillBytes) - 1; + auto graphics = commands(layout.firstCommands); + auto* const first = sceAgcDcbRewind(&graphics, 0) + 1; + for (std::size_t fill = 0; fill < Fills; ++fill) sceAgcDcbDmaData(&graphics, 0, DmaMemory, 0, at(bulk.base + fill * FillBytes), 2, 0, Filled, FillBytes, 0, 1, 0); + sceAgcDcbWaitRegMem(&graphics, 0, 3, 0, 0, filled, Filled, 0xffffffffu, 0); + sceAgcDcbDmaData(&graphics, 0, DmaMemory, 0, at(layout.firstTarget), DmaMemory, 0, at(layout.source), DataBytes, 0, 1, 0); + releaseMem(graphics, released); + if (halfStored) sceAgcDcbDmaData(&graphics, 0, DmaMemory, 0, at(released) + 2, 2, 0, Half, 2, 0, 1, 0); + auto* const second = sceAgcDcbRewind(&graphics, 0) + 1; + writeDone(graphics, layout.label); + Packet producer{layout.firstCommands, static_cast(graphics.cursor_up - layout.firstCommands), 0, {}}; + check(sceAgcDriverSubmitDcb(&producer) == 0, "graphics submission failed"); + auto compute = commands(layout.secondCommands); + sceAgcAcbWaitRegMem(&compute, 0, 3, 0, released, Done, 0xffffu, 0); + sceAgcAcbDmaData(&compute, DmaMemory, 0, at(layout.secondTarget), DmaMemory, 0, at(layout.firstTarget), DataBytes, 0, 1); + sceAgcAcbWriteData(&compute, ComputeMemory, 0, at(copied), &Done, 1, 0, 1); + Packet consumer{layout.secondCommands, static_cast(compute.cursor_up - layout.secondCommands), 0, {}}; + check(sceAgcDriverSubmitAcb(ComputeQueue, &consumer) == 0, "compute submission failed"); + std::atomic_ref(*title).store(Done, std::memory_order_release); + release(first); + waitUntil([&] { return std::atomic_ref(*copied).load(std::memory_order_acquire) == Done; }, "the compute queue did not copy after the label the graphics queue released"); + check(equal(layout.secondTarget, read), "the compute queue's copy after the label the graphics queue released did not land"); + flip(); + release(second); + flip(); + AgcDriverWaitIdle_nid_postfix(); + const auto capture = checkCapture(1); + const FrameCaptureReader reader(capture); + const auto delta = [&](const std::uint32_t* address) { + return std::any_of(reader.Chunks().begin(), reader.Chunks().end(), [&](const auto& chunk) { + if (chunk.kind != FrameMemoryKind::Delta || at(address) < chunk.address || chunk.address + chunk.bytes < at(address) + 4) return false; + const auto bytes = reader.Read(chunk); + std::uint32_t value = 0; + std::memcpy(&value, bytes.data() + (at(address) - chunk.address), sizeof(value)); + return value == Done; + }); + }; + check(std::atomic_ref(*released).load(std::memory_order_acquire) == releasedValue, "the graphics queue did not store the label the test expects"); + check(delta(title), "the memory delta lost the word the title wrote beside the label"); + check(!deltaStoredBytes(reader, released), "the memory delta holds bytes of the label the graphics queue's RELEASE_MEM and DMA_DATA wrote, so the replay restores them before the work that produces them"); + check(replayed(tool, capture, layout.secondTarget, DataBytes) == read, "the replay released the compute queue before the copy ahead of the label it waits on"); +} + +void testGpuStoreBehindRewind(const std::filesystem::path& tool) { + checkGpuStoreBehindRewind(tool, false); +} + +void testGpuStoreOverHalfLabel(const std::filesystem::path& tool) { + checkGpuStoreBehindRewind(tool, true); +} + +void checkUnwatchedTitleStores(const std::filesystem::path& tool, bool initiallyUnwatched, const std::function& prepare = {}) { + constexpr std::uint32_t Stored = 0x77u; + const auto bulk = allocate(); + check(AgcDriver::GuestMemory::Watched(at(bulk.base), 4096), "the fixture needs initially watched memory"); + if (prepare) prepare(bulk.base); + auto* const word = reinterpret_cast(bulk.base); + auto output = std::make_shared(); + AgcDriverRegisterVideoOutput_nid_postfix(Handle, output); + std::atomic_ref(*word).store(0, std::memory_order_release); + if (initiallyUnwatched) AgcDriver::GuestMemory::Unwatch(at(bulk.base), 4096); + flip(); + if (!initiallyUnwatched) AgcDriver::GuestMemory::Unwatch(at(bulk.base), 4096); + check(!AgcDriver::GuestMemory::Watched(at(bulk.base), 4096), "the test buffer did not lose write-watch coverage"); + std::atomic_ref(*word).store(Stored, std::memory_order_release); + flip(); + std::atomic_ref(*word).store(0, std::memory_order_release); + flip(); + AgcDriverWaitIdle_nid_postfix(); + const auto capture = checkCapture(0); + const FrameCaptureReader reader(capture); + if (prepare) { + check(std::any_of(reader.Chunks().begin(), reader.Chunks().end(), [&](const auto& chunk) { + return chunk.kind == FrameMemoryKind::Range && chunk.rangeKind == AgcDriver::FrameRangeKind::Section && chunk.address <= at(word) && at(word) + 4 <= chunk.address + chunk.bytes; + }), "the capture fixture did not record the word in shared section memory"); + } + std::uint64_t storedGroup = 0; + std::uint64_t restoredGroup = 0; + for (const auto& chunk : reader.Chunks()) { + if (chunk.kind != FrameMemoryKind::Delta || chunk.address > at(word) || at(word) + 4 > chunk.address + chunk.bytes) continue; + const auto bytes = reader.Read(chunk); + std::uint32_t value = 0; + std::memcpy(&value, bytes.data() + (at(word) - chunk.address), sizeof(value)); + if (value == Stored && storedGroup == 0) storedGroup = chunk.group; + if (value == 0 && storedGroup != 0 && chunk.group > storedGroup) restoredGroup = chunk.group; + } + check(storedGroup != 0, "the capture lost the intermediate CPU store into unwatched memory"); + check(restoredGroup > storedGroup, "the capture lost the CPU restore to its initial value in unwatched memory"); + const auto dumped = replayed(tool, capture, word, 4); + std::uint32_t value = 0; + std::memcpy(&value, dumped.data(), sizeof(value)); + check(value == 0, "the replay did not restore the unwatched word's initial value"); +} + +void testInitiallyUnwatchedTitleStores(const std::filesystem::path& tool) { + checkUnwatchedTitleStores(tool, true); +} + +void testLaterUnwatchedTitleStores(const std::filesystem::path& tool) { + checkUnwatchedTitleStores(tool, false); +} + +void onSharedSection(const std::function&)>& run) { + constexpr std::size_t Bytes = 65536; +#ifdef _WIN32 + struct Backing { + HANDLE section = nullptr; + std::byte* mapped = nullptr; + ~Backing() { + if (mapped != nullptr) GuestArena::GuestArenaReset_nid_postfix(mapped, 2 * Bytes); + if (section == nullptr) return; + GuestArena::GuestArenaForgetSection_nid_postfix(section); + CloseHandle(section); + } + } backing; + backing.section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_EXECUTE_READWRITE, 0, Bytes, nullptr); + check(backing.section != nullptr, "cannot create the capture fixture's shared backing"); + run([&](std::byte* base) { + backing.mapped = base; + AgcDriver::GuestMemory::Unwatch(at(base), 2 * Bytes); + GuestArena::GuestArenaReset_nid_postfix(base, BlockBytes); + GuestArena::GuestArenaMapDirect_nid_postfix(base, Bytes, backing.section, 0, PAGE_READWRITE); + GuestArena::GuestArenaMapDirect_nid_postfix(base + Bytes, Bytes, backing.section, 0, PAGE_READWRITE); + GuestArena::GuestArenaCompareWhenShared_nid_no_patch(reinterpret_cast(base), 2 * Bytes); + AgcDriver::GuestMemory::Unwatch(at(base), 2 * Bytes); + }); +#else + const auto closeFile = [](std::FILE* file) { std::fclose(file); }; + std::unique_ptr backing(std::tmpfile(), closeFile); + check(backing != nullptr && ftruncate(fileno(backing.get()), Bytes) == 0, "cannot create the capture fixture's shared backing"); + run([&](std::byte* base) { + AgcDriver::GuestMemory::Unwatch(at(base), 2 * Bytes); + check(mmap(base, Bytes, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fileno(backing.get()), 0) == base, "cannot map the capture fixture's shared backing"); + check(mmap(base + Bytes, Bytes, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fileno(backing.get()), 0) == base + Bytes, "cannot map the capture fixture's shared alias"); + }); +#endif +} + +void testSharedTitleStores(const std::filesystem::path& tool) { + onSharedSection([&](const std::function& prepare) { checkUnwatchedTitleStores(tool, true, prepare); }); +} + +void testUnchangedSectionStoredOnce(const std::filesystem::path& tool) { + constexpr std::uint32_t Stored = 0x5eu; + onSharedSection([&](const std::function& prepare) { + const auto layout = allocate(); + const auto bulk = allocate(); + prepare(bulk.base); + check(!AgcDriver::GuestMemory::Watched(at(bulk.base), 4096), "the fixture needs a multi-mapped section block without write-watch coverage, as a title's shared section has"); + auto* const word = reinterpret_cast(bulk.base); + auto output = std::make_shared(); + AgcDriverRegisterVideoOutput_nid_postfix(Handle, output); + std::atomic_ref(*word).store(0, std::memory_order_release); + flip(); + check(!AgcDriver::GuestMemory::Watched(at(bulk.base), 4096), "the multi-mapped section block was watched again once the capture started"); + copyFrame(layout.firstCommands, layout, layout.firstTarget); + std::atomic_ref(*word).store(Stored, std::memory_order_release); + flip(); + copyFrame(layout.secondCommands, layout, layout.secondTarget); + flip(); + AgcDriverWaitIdle_nid_postfix(); + const auto capture = checkCapture(0); + const FrameCaptureReader reader(capture); + std::vector samples; + for (const auto& chunk : reader.Chunks()) { + if (chunk.kind != FrameMemoryKind::Delta || chunk.address > at(word) || at(word) + 4 > chunk.address + chunk.bytes) continue; + const auto bytes = reader.Read(chunk); + std::uint32_t value = 0; + std::memcpy(&value, bytes.data() + (at(word) - chunk.address), sizeof(value)); + if (value == Stored) samples.push_back(chunk); + else check(samples.empty(), "a sample of the section block after the title's store lost it"); + } + check(samples.size() == 1, "the section block was recorded again after GPU work, though no store changed it"); + std::set payloads; + std::uint64_t shared = 0; + for (const auto& chunk : reader.Chunks()) { + if (chunk.kind == FrameMemoryKind::Delta && !payloads.insert(chunk.offset).second) shared += chunk.bytes; + } + const auto counted = reader.Header().find("\"shared_delta_bytes\":" + std::to_string(shared) + ","); + check(counted != std::string::npos, "the capture header does not count the " + std::to_string(shared) + " shared delta bytes: " + reader.Header()); + const auto dumped = replayed(tool, capture, word, 4); + std::uint32_t value = 0; + std::memcpy(&value, dumped.data(), sizeof(value)); + check(value == Stored, "the replay lost the store in the shared section block"); + }); +} + +void testPartlyWatchedBlockOnce(const std::filesystem::path& tool) { + constexpr std::uint32_t Watched = 0x31u; + constexpr std::uint32_t Unwatched = 0x32u; + const auto bulk = allocate(); + auto* const unwatched = reinterpret_cast(bulk.base); + auto* const watched = reinterpret_cast(bulk.base + 8192); + auto output = std::make_shared(); + AgcDriverRegisterVideoOutput_nid_postfix(Handle, output); + AgcDriver::GuestMemory::Unwatch(at(bulk.base), 4096); + check(!AgcDriver::GuestMemory::Watched(at(bulk.base), BlockBytes) && AgcDriver::GuestMemory::Watched(at(watched), 4), "the fixture needs a block that is only partly watched"); + flip(); + std::atomic_ref(*unwatched).store(Unwatched, std::memory_order_release); + std::atomic_ref(*watched).store(Watched, std::memory_order_release); + flip(); + flip(); + AgcDriverWaitIdle_nid_postfix(); + const auto capture = checkCapture(0); + const FrameCaptureReader reader(capture); + std::vector deltas; + for (const auto& chunk : reader.Chunks()) { + if (chunk.kind == FrameMemoryKind::Delta) deltas.push_back(chunk); + } + std::ranges::sort(deltas, [](const auto& left, const auto& right) { return std::pair{left.group, left.address} < std::pair{right.group, right.address}; }); + for (std::size_t index = 1; index < deltas.size(); ++index) { + const auto& previous = deltas[index - 1]; + check(previous.group != deltas[index].group || previous.address + previous.bytes <= deltas[index].address, "one memory delta group holds the same bytes twice at " + std::to_string(deltas[index].address)); + } + const auto dumped = replayed(tool, capture, bulk.base, 8196); + std::uint32_t first = 0; + std::uint32_t second = 0; + std::memcpy(&first, dumped.data(), sizeof(first)); + std::memcpy(&second, dumped.data() + 8192, sizeof(second)); + check(first == Unwatched && second == Watched, "the replay lost a store in the partly watched block"); +} + +void testGpuFillRestoredToCachedValue(const std::filesystem::path& tool) { + constexpr std::uint32_t Filled = 0x5a5a5a5au; + constexpr std::size_t FillBytes = 65536; + const auto layout = allocate(); + const auto bulk = allocate(); + auto* const word = reinterpret_cast(bulk.base); + auto output = std::make_shared(); + AgcDriverRegisterVideoOutput_nid_postfix(Handle, output); + flip(); + AgcDriver::GuestMemory::Unwatch(at(bulk.base), FillBytes); + flip(); + auto graphics = commands(layout.firstCommands); + sceAgcDcbDmaData(&graphics, 0, DmaMemory, 0, at(bulk.base), 2, 0, Filled, FillBytes, 0, 1, 0); + writeDone(graphics, layout.label); + Packet packet{layout.firstCommands, static_cast(graphics.cursor_up - layout.firstCommands), 0, {}}; + check(sceAgcDriverSubmitDcb(&packet) == 0, "graphics submission failed"); + AgcDriverWaitIdle_nid_postfix(); + check(*word == Filled, "the driver did not fill the previously sampled buffer"); + std::memset(bulk.base, 0, FillBytes); + flip(); + AgcDriverWaitIdle_nid_postfix(); + const auto dumped = replayed(tool, checkCapture(0), word, 4); + std::uint32_t value = 0; + std::memcpy(&value, dumped.data(), sizeof(value)); + check(value == 0, "the replay lost a CPU restore matching the cached bytes after an intervening GPU fill"); +} + +void testFillRewrittenByTitle(const std::filesystem::path& tool) { + constexpr std::uint32_t Filled = 0x5a5a5a5au; + constexpr std::uint32_t Stored = 0x77u; + constexpr std::size_t FillBytes = 512u * 1024u; + const auto layout = allocate(); + const auto bulk = allocate(); + auto* const word = reinterpret_cast(bulk.base + FillBytes / 2); + auto output = std::make_shared(); + AgcDriverRegisterVideoOutput_nid_postfix(Handle, output); + + flip(); + auto graphics = commands(layout.firstCommands); + sceAgcDcbDmaData(&graphics, 0, DmaMemory, 0, at(bulk.base), 2, 0, Filled, FillBytes, 0, 1, 0); + writeDone(graphics, layout.label); + Packet packet{layout.firstCommands, static_cast(graphics.cursor_up - layout.firstCommands), 0, {}}; + check(sceAgcDriverSubmitDcb(&packet) == 0, "graphics submission failed"); + AgcDriverWaitIdle_nid_postfix(); + check(*word == Filled, "the driver did not fill the buffer"); + std::atomic_ref(*word).store(Stored, std::memory_order_release); + flip(); + std::atomic_ref(*word).store(Filled, std::memory_order_release); + flip(); + AgcDriverWaitIdle_nid_postfix(); + const auto replayedWord = replayed(tool, checkCapture(0), word, 4); + std::uint32_t value = 0; + std::memcpy(&value, replayedWord.data(), sizeof(value)); + check(value == Filled, "the replay kept the title's earlier store over its later one, which wrote the value the fill had left"); +} + +void testFillWordHalfStored(const std::filesystem::path& tool) { + constexpr std::uint32_t Filled = 0x5a5a5a5au; + constexpr std::uint32_t Half = 0x1234u; + constexpr std::uint32_t Stored = 0x77u; + constexpr std::size_t FillBytes = 512u * 1024u; + const auto layout = allocate(); + const auto bulk = allocate(); + auto* const word = reinterpret_cast(bulk.base + FillBytes / 2); + auto* const title = word + 1; + auto output = std::make_shared(); + AgcDriverRegisterVideoOutput_nid_postfix(Handle, output); + + flip(); + auto graphics = commands(layout.firstCommands); + sceAgcDcbDmaData(&graphics, 0, DmaMemory, 0, at(bulk.base), 2, 0, Filled, FillBytes, 0, 1, 0); + sceAgcDcbDmaData(&graphics, 0, DmaMemory, 0, at(word) + 2, 2, 0, Half, 2, 0, 1, 0); + writeDone(graphics, layout.label); + Packet packet{layout.firstCommands, static_cast(graphics.cursor_up - layout.firstCommands), 0, {}}; + check(sceAgcDriverSubmitDcb(&packet) == 0, "graphics submission failed"); + AgcDriverWaitIdle_nid_postfix(); + const std::uint32_t expected = (Filled & 0xffffu) | (Half << 16u); + check(std::atomic_ref(*word).load(std::memory_order_acquire) == expected, "the driver did not fill the buffer and store half of the word"); + std::atomic_ref(*title).store(Stored, std::memory_order_release); + flip(); + flip(); + AgcDriverWaitIdle_nid_postfix(); + const auto capture = checkCapture(0); + const FrameCaptureReader reader(capture); + check(std::any_of(reader.Chunks().begin(), reader.Chunks().end(), [&](const auto& chunk) { + return chunk.kind == FrameMemoryKind::Delta && chunk.address <= at(title) && at(title) + 4 <= chunk.address + chunk.bytes; + }), "the memory delta lost the word the title wrote beside the filled word"); + check(!deltaStoredBytes(reader, word), "the memory delta holds bytes of a word the fill and a later 2-byte store wrote, so the replay restores them before that work"); + const auto replayedWords = replayed(tool, capture, word, 8); + std::array values{}; + std::memcpy(values.data(), replayedWords.data(), sizeof(values)); + check(values[0] == expected, "the replay did not reproduce the filled word with its stored half"); + check(values[1] == Stored, "the replay did not reproduce the word the title wrote beside the filled word"); +} + void testFenceReused(const std::filesystem::path& tool) { const auto layout = allocate(); const auto copied = pattern(53); @@ -1672,16 +2149,45 @@ void testSettledBesideReleasedTail() { AgcDriverWaitIdle_nid_postfix(); check(std::atomic_ref(*layout.label).load() == Done, "the driver did not run the released REWIND tail"); } + +void testFillClearedBeforeRange(const std::filesystem::path& tool) { + constexpr std::uint32_t Filled = 0x5a5a5a5au; + const auto layout = allocate(); + auto output = std::make_shared(); + AgcDriverRegisterVideoOutput_nid_postfix(Handle, output); + + flip(); + auto* const block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(BlockBytes, 65536)); + check(block != nullptr, "cannot allocate guest memory"); + GuestArena::GuestArenaCommit_nid_postfix(block, BlockBytes, 0x04, BlockBytes); + auto graphics = commands(layout.firstCommands); + sceAgcDcbDmaData(&graphics, 0, DmaMemory, 0, at(block), 2, 0, Filled, BlockBytes, 0, 1, 0); + writeDone(graphics, layout.label); + Packet packet{layout.firstCommands, static_cast(graphics.cursor_up - layout.firstCommands), 0, {}}; + check(sceAgcDriverSubmitDcb(&packet) == 0, "graphics submission failed"); + AgcDriverWaitIdle_nid_postfix(); + check(*reinterpret_cast(block) == Filled, "the driver did not fill the block"); + std::memset(block, 0, BlockBytes); + { + GuestAllocations::Mutation mutation; + mutation.Add(block, BlockBytes, true, true, true); + } + copy(layout.secondCommands, CommandBytes, block, layout.firstTarget, layout.label); + flip(); + flip(); + AgcDriverWaitIdle_nid_postfix(); + check(replayed(tool, checkCapture(0), layout.firstTarget, DataBytes) == std::vector(DataBytes), "the replay copied the GPU fill of a block the title cleared before its range was first recorded"); +} } int main(int argc, char** argv) { const std::string mode = argc == 3 ? argv[2] : ""; const std::map rewound{ - {"rewind_store", testStoreAfterGatedCopy}, {"rewind_copy", testCopyInFlightAtDelta}, {"rewind_compute", testComputeWaitBehindRewind}, {"rewind_release", testReleaseDuringDelta}, {"rewind_fill", testFilledRewindTail}, {"rewind_split", testRewindFilledAcrossChunks}, {"wait_label", testLabelFromLaterSubmission}, {"fence_reuse", testFenceReused}, {"busy_queue", testQueueBusyPastPacing}, {"rewind_page", testRewindPageRestored}, {"allocation_ranges", testRegisteredRangeBoundaries}, {"gpu_only", testGpuOnlyRange}}; + {"rewind_store", testStoreAfterGatedCopy}, {"store_idle", testStoreAfterGatedCopyIdle}, {"store_idle_rewind", testStoreAfterRewoundCopyIdle}, {"store_idle_unwatched", testUnwatchedStoreBeforeReservation}, {"store_second_wait", testStoreBeforeSecondWaitOnGate}, {"rewind_copy", testCopyInFlightAtDelta}, {"rewind_copy_held", testStoreBesideHeldCopy}, {"rewind_compute", testComputeWaitBehindRewind}, {"rewind_release", testReleaseDuringDelta}, {"rewind_fill", testFilledRewindTail}, {"rewind_split", testRewindFilledAcrossChunks}, {"wait_label", testLabelFromLaterSubmission}, {"gpu_store", testGpuStoreBehindRewind}, {"gpu_store_half", testGpuStoreOverHalfLabel}, {"gpu_fill", testFillRewrittenByTitle}, {"gpu_fill_half", testFillWordHalfStored}, {"gpu_restore_cached", testGpuFillRestoredToCachedValue}, {"unwatched_start", testInitiallyUnwatchedTitleStores}, {"unwatched_late", testLaterUnwatchedTitleStores}, {"unwatched_shared", testSharedTitleStores}, {"section_once", testUnchangedSectionStoredOnce}, {"partly_watched_once", testPartlyWatchedBlockOnce}, {"gpu_cleared", testFillClearedBeforeRange}, {"fence_reuse", testFenceReused}, {"busy_queue", testQueueBusyPastPacing}, {"rewind_page", testRewindPageRestored}, {"allocation_ranges", testRegisteredRangeBoundaries}, {"gpu_only", testGpuOnlyRange}}; const std::map restored{ {"rewind_chained", testChainedRewindGates}, {"rewind_page_start", testRewindControlAtPageStart}, {"rewind_zero_control", testZeroRewindControlRewritten}, {"rewind_zero_control_parked", testZeroRewindControlRestoredAtPark}, {"rewind_in_order", testEarlyReleaseRestoredInOrder}, {"rewind_kept_words", testRewindControlsKeptAnywhere}, {"multisample_depth", testMultisampleDepthPasses}, {"single_sample_depth", testSingleSampleDepthPasses}}; if (argc != 2 && !(argc == 3 && (mode == "concurrent" || mode == "subpage" || mode == "pipelines" || mode == "reservation_error" || mode == "rewind" || mode == "rewind_reuse" || mode == "rewind_shared_tail" || mode == "rewind_settled_tail" || rewound.contains(mode) || restored.contains(mode)))) { - std::fprintf(stderr, "usage: agc_driver_frame_replay_tests [concurrent|subpage|pipelines|reservation_error|rewind|rewind_store|rewind_copy|rewind_compute|rewind_release|rewind_fill|rewind_split|wait_label|fence_reuse|busy_queue|rewind_reuse|rewind_shared_tail|rewind_settled_tail|rewind_page|rewind_chained|rewind_page_start|rewind_zero_control|rewind_zero_control_parked|rewind_in_order|rewind_kept_words|multisample_depth|single_sample_depth|allocation_ranges|gpu_only]\n"); + std::fprintf(stderr, "usage: agc_driver_frame_replay_tests [concurrent|subpage|pipelines|reservation_error|rewind|rewind_store|store_idle|store_idle_rewind|store_idle_unwatched|store_second_wait|rewind_copy|rewind_compute|rewind_release|rewind_fill|rewind_split|wait_label|gpu_store|gpu_store_half|gpu_fill|gpu_fill_half|gpu_restore_cached|unwatched_start|unwatched_late|unwatched_shared|section_once|partly_watched_once|gpu_cleared|fence_reuse|busy_queue|rewind_reuse|rewind_shared_tail|rewind_settled_tail|rewind_page|rewind_chained|rewind_page_start|rewind_zero_control|rewind_zero_control_parked|rewind_in_order|rewind_kept_words|multisample_depth|single_sample_depth|allocation_ranges|gpu_only]\n"); return 2; } int status = 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/FrameReplayState.cpp b/core/libs/prx/libSceAgcDriver/tests/FrameReplayState.cpp index 77d389b62646..60c3bd60c39f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/FrameReplayState.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/FrameReplayState.cpp @@ -755,6 +755,59 @@ void testStoreAfterUnwatch(const std::filesystem::path& directory) { if (!failures.empty()) throw std::runtime_error(failures); } +void testGpuStoreRestoredUnwatched(const std::filesystem::path& directory) { + constexpr std::size_t Page = 4096; + constexpr std::uint32_t Stored = 0x600dcafeu; + auto* block = allocate(1u << 20); + std::fill_n(block, 1u << 20, std::byte{0}); + auto* commands = reinterpret_cast(block); + auto* page = block + 2 * FrameCaptureWriter::BlockBytes; + auto* label = reinterpret_cast(page); + AgcDriver::GuestMemory::Unwatch(address(page), Page); + check(!AgcDriver::GuestMemory::Watched(address(page), Page), "the page is in the write watch"); + auto* recorder = AgcDriver::FrameRecorder::Active(); + check(recorder != nullptr, "frame recorder is disabled"); + recorder->FrameBoundary(); + const std::array write{0xc0033700u, 0x00100200u, static_cast(address(label)), static_cast(address(label) >> 32u), Stored}; + std::memcpy(commands, write.data(), sizeof(write)); + Packet packet{commands, static_cast(write.size()), 0, {}}; + check(sceAgcDriverSubmitDcb(&packet) == 0, "the label write was not submitted"); + AgcDriverWaitIdle_nid_postfix(); + check(std::atomic_ref(*label).load(std::memory_order_acquire) == Stored, "the queue did not write the label"); + check(!AgcDriver::GuestMemory::Watched(address(page), Page), "the label write returned the page to the write watch"); + std::atomic_ref(*label).store(0, std::memory_order_release); + recorder->FrameBoundary(); + const FrameCaptureReader reader(directory); + check(lastDeltaByte(reader, page) == std::byte{0}, "the capture lost the title's restore of the bytes it recorded before a queue's store, so the replayed store survives"); +} + +void testUnalignedUnwatchedRange(const std::filesystem::path& directory) { + constexpr std::size_t Block = FrameCaptureWriter::BlockBytes; + constexpr std::size_t Page = 4096; + auto* block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Block, Block)); + check(block != nullptr, "guest reservation failed"); + GuestArena::GuestArenaCommit_nid_postfix(block, Block, 0x04, Block); + std::fill_n(block, Block, std::byte{0}); + AgcDriver::GuestMemory::Unwatch(address(block), Block); + check(!AgcDriver::GuestMemory::Watched(address(block), Block), "the range is write-watched"); + auto* range = block + 32; + { + GuestAllocations::Mutation mutation; + mutation.Add(range, 3 * Page, true, true, false); + } + auto* recorder = AgcDriver::FrameRecorder::Active(); + check(recorder != nullptr, "frame recorder is disabled"); + recorder->FrameBoundary(); + auto* head = block + 64; + auto* interior = block + Page + 8; + *head = std::byte{0x41}; + *interior = std::byte{0x42}; + recorder->FrameBoundary(); + const FrameCaptureReader reader(directory); + check(lastDeltaByte(reader, head) == std::byte{0x41}, "the capture lost a store to the first page of a range that starts inside it"); + check(lastDeltaByte(reader, interior) == std::byte{0x42}, "the capture lost a store to a whole page inside a range that starts inside a page"); +} + std::byte* comparedRacePage = nullptr; void unwatchComparedRacePage() { @@ -973,6 +1026,57 @@ void testGpuWriteBeforeDelta(const std::filesystem::path& directory) { if (stale != replayed.end()) throw std::runtime_error("the replay restored a memory delta while a GPU write over its range was still pending, and the next read landed that write over it: the page holds byte " + std::to_string(static_cast(*stale)) + ", not the 0 the capture recorded after the write"); } +void testUnwrittenDeltaBesideBusyQueue(const std::filesystem::path& directory) { + auto* block = allocate(1u << 20); + std::fill_n(block, 1u << 20, std::byte{0}); + auto* commands = reinterpret_cast(block); + auto* gate = reinterpret_cast(block + 4096); + auto* done = gate + 1; + const auto low = [](const void* pointer) { return static_cast(address(pointer)); }; + const auto high = [](const void* pointer) { return static_cast(address(pointer) >> 32u); }; + const std::array words{0xc0053c00u, 0x13u, low(gate), high(gate), 1u, 0xffffffffu, 4u, 0xc0033700u, 0x00100200u, low(done), high(done), 1u}; + std::memcpy(commands, words.data(), sizeof(words)); + auto* recorder = AgcDriver::FrameRecorder::Active(); + check(recorder != nullptr, "frame recorder is disabled"); + recorder->FrameBoundary(); + Packet packet{commands, static_cast(words.size()), 0, {}}; + check(sceAgcDriverSubmitDcb(&packet) == 0, "the gated label write was not submitted"); + const auto parked = [&] { + std::array waits{}; + const auto count = AgcDriverAwaitedWaits_nid_postfix(waits.data(), waits.size()); + return std::any_of(waits.begin(), waits.begin() + static_cast(count), [&](const auto& wait) { return wait.address == address(gate); }); + }; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (!parked()) { + check(std::chrono::steady_clock::now() < deadline, "the queue never waited on its gate"); + std::this_thread::yield(); + } + struct ActiveRecorder { + std::unique_ptr recorder; + void reset() { + AgcDriver::GuestMemory::SetFlushHook(nullptr); + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + recorder.reset(); + } + ~ActiveRecorder() { reset(); } + } active{std::make_unique(mockContext())}; + { + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + active.recorder->Activate(); + active.recorder->NotePendingWrite(address(gate), sizeof(std::uint32_t)); + } + AgcDriver::GuestMemory::SetFlushHook([](std::uint64_t, std::size_t) {}); + check(!AgcDriverSettled_nid_postfix(), "the queue counts as waiting on the title while a GPU write over its gate is pending, so the test cannot tell whether a delta waits for it"); + recorder->Suspend([] {}); + active.reset(); + std::atomic_ref(*gate).store(1, std::memory_order_release); + AgcDriverWaitIdle_nid_postfix(); + check(std::atomic_ref(*done).load(std::memory_order_acquire) == 1, "the queue did not pass its gate"); + recorder->FrameBoundary(); + const FrameCaptureReader reader(directory); + check(reader.Header().find("neither finished nor waited") == std::string::npos, "a memory delta with no written or unwatched block waited for GPU work it would not read, and the capture stopped"); +} + void testVersionOneRefused(const std::filesystem::path& directory) { constexpr std::size_t Size = FrameCaptureWriter::BlockBytes; constexpr std::string_view VersionOne = "aps5-frame-calls 1\n"; @@ -1004,6 +1108,74 @@ void testVersionOneRefused(const std::filesystem::path& directory) { check(std::all_of(bytes, bytes + Size, [](std::byte value) { return value == std::byte{0x55}; }), "the replay restored memory before refusing the calls format 1 capture"); } +void testMergedBlocks() { + using Blocks = std::vector>; + Blocks aligned{{0x20000, 0x30000}, {0x10000, 0x20000}, {0x18000, 0x28000}, {0x30000, 0x40000}}; + AgcDriver::FrameRecorder::MergeOverlappingBlocks(aligned); + check(aligned == Blocks{{0x10000, 0x30000}, {0x30000, 0x40000}}, "aligned overlapping blocks are not merged into their union, or touching blocks are"); + Blocks unaligned{{0x10000, 0x20000}, {0x1fffe, 0x20006}, {0x20002, 0x20010}, {0x20004, 0x20008}}; + AgcDriver::FrameRecorder::MergeOverlappingBlocks(unaligned); + check(unaligned == Blocks{{0x10000, 0x20000}, {0x1fffe, 0x20006}, {0x20002, 0x20010}, {0x20004, 0x20008}}, "a block with an unaligned edge was merged, so its GPU-stored words would be kept whole"); +} + +void testCapturedSpans() { + constexpr std::uint64_t Page = AgcDriver::FrameRecorder::HostPageBytes; + constexpr std::uint64_t Base = 0x7f0000000000; + AgcDriver::FrameRecorder::CapturedSpans captured; + captured.Add(Base, Base + 3 * Page); + captured.Add(Base + Page + 0x100, Base + Page + 0x200); + captured.Add(Base + 4 * Page - 0x80, Base + 4 * Page + 0x80); + captured.Add(Base + 4 * Page, Base + 5 * Page); + captured.Add(Base + 7 * Page, Base + 8 * Page); + captured.Add(Base + 8 * Page, Base + 9 * Page); + const auto covered = [&](std::uint64_t begin, std::uint64_t end) { + std::uint64_t bytes = 0; + captured.Covering(begin, end, [&](std::uint64_t first, std::uint64_t stop) { bytes += stop - first; }); + return bytes; + }; + check(covered(Base + Page, Base + 2 * Page) == Page, "a page inside a readable range was not covered once, so a smaller range starting inside it hid the rest or counted twice"); + check(covered(Base + Page + 0x300, Base + Page + 0x400) == 0x100, "bytes of a readable range after a smaller range it contains were missed"); + check(covered(Base + 4 * Page, Base + 5 * Page) == Page, "a host page overlapping the tail of a readable range was not covered once"); + check(covered(Base + 3 * Page, Base + 4 * Page) == 0x80, "the tail of a readable range ending inside a page was not covered"); + check(covered(Base + 6 * Page, Base + 10 * Page) == 2 * Page, "adjacent readable ranges were not covered once each"); + check(captured.spans.size() == 3, "overlapping or adjacent readable ranges were not merged into disjoint spans"); +} + +std::vector fillWords(std::initializer_list words) { + std::vector bytes(words.size() * 4); + std::size_t at = 0; + for (const auto word : words) { + std::memcpy(bytes.data() + at, &word, 4); + at += 4; + } + return bytes; +} + +void testUnalignedGpuFill() { + using Runs = std::vector>; + constexpr std::uint64_t Base = 0x100000; + constexpr std::array Pattern{0xa1a1a1a1u, 0xb2b2b2b2u, 0xc3c3c3c3u, 0xd4d4d4d4u}; + Runs runs; + { + AgcDriver::FrameRecorder::GpuStores stores; + stores.Fill(Base + 4, 20, Pattern); + const auto title = fillWords({0x11111111u, Pattern[0], Pattern[1], 0x22222222u, Pattern[3], Pattern[0], 0x33333333u, 0x44444444u}); + const auto driver = stores.KeepTitleWords(Base, title, runs, false); + check(driver == 16, "a 20-byte fill at an address that is not 16-aligned was not matched word by word from its own start"); + check(runs == Runs{{0, 4}, {12, 4}, {24, 8}}, "the title's words around and inside a 20-byte fill at an address that is not 16-aligned were not kept"); + } + { + AgcDriver::FrameRecorder::GpuStores stores; + stores.Fill(Base + 4, 20, Pattern); + const std::array stored{std::byte{0x5a}, std::byte{0x6b}}; + stores.Store(Base + 14, stored); + const auto title = fillWords({0x11111111u, Pattern[0], Pattern[1], 0x6b5ac3c3u, Pattern[3], Pattern[0], 0x33333333u}); + const auto driver = stores.KeepTitleWords(Base, title, runs, false); + check(driver == 20, "a store that split a 20-byte fill at an address that is not 16-aligned changed the pattern of the pieces it left"); + check(runs == Runs{{0, 4}, {24, 4}}, "a store that split a 20-byte fill at an address that is not 16-aligned kept driver words as the title's"); + } +} + void testEopTokens() { Frames frames; auto output = std::make_shared(frames); @@ -1204,6 +1376,40 @@ void testBlockingSubmission(const std::filesystem::path& directory) { AgcDriverUnregisterVideoOutput_nid_postfix(7, output); } +void testClippedHostShader(const std::filesystem::path& directory) { + constexpr std::size_t Page = AgcDriver::FrameRecorder::HostPageBytes; + constexpr std::size_t CodeBytes = 256; +#ifdef _WIN32 + auto* memory = static_cast(VirtualAlloc(nullptr, 2 * Page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); +#else + void* mapped = mmap(nullptr, 2 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + auto* memory = mapped != MAP_FAILED ? static_cast(mapped) : nullptr; +#endif + check(memory != nullptr, "host shader allocation failed"); + { + GuestAllocations::Mutation mutation; + mutation.Add(memory + 32, Page / 2, true, false, true); + } + auto* shader = reinterpret_cast(memory + 64); + auto* code = memory + 64 + sizeof(Shader); + auto* recorder = AgcDriver::FrameRecorder::Active(); + check(recorder != nullptr, "frame recorder is disabled"); + recorder->FrameBoundary(); + *shader = {}; + shader->file_header = 0x34333231u; + shader->version = 0x18u; + shader->header_size = sizeof(Shader); + shader->shader_size = CodeBytes; + shader->code = code; + std::fill_n(code, CodeBytes, std::byte{0x51}); + recorder->RegisterShader(shader); + std::fill_n(code, CodeBytes, std::byte{0x52}); + recorder->RegisterShader(shader); + recorder->FrameBoundary(); + const FrameCaptureReader reader(directory); + check(lastDeltaByte(reader, code) == std::byte{0x52}, "the capture lost a rewrite of host shader code in a page a captured range covers only in part"); +} + void testShaderCode(const std::filesystem::path& directory, bool host, std::string_view mode = {}) { const bool prologue = mode.starts_with("shader_prologue_"); const bool readOnly = mode.ends_with("readonly"); @@ -1308,6 +1514,286 @@ void testShaderCode(const std::filesystem::path& directory, bool host, std::stri check(listed && *listed == expected, "the offline shader listing read other code than the capture holds at the registration"); } +void testDeltaPaths(const std::filesystem::path& directory, std::string_view mode) { + constexpr std::size_t Block = FrameCaptureWriter::BlockBytes; + constexpr std::size_t PieceBytes = Block + Block / 2; + const bool host = mode != "shader_unaligned_restored"; + const bool rewritten = mode == "shader_host_rewritten"; + const std::size_t codeBytes = host ? 3 * Block : Block; + Shader* shader = nullptr; + std::byte* code = nullptr; + if (host) { + shader = reinterpret_cast(allocate(1u << 20)); + std::byte* memory = nullptr; +#ifdef _WIN32 + memory = static_cast(VirtualAlloc(nullptr, codeBytes + 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); +#elif defined(__linux__) + void* mapped = mmap(nullptr, codeBytes + 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + memory = mapped != MAP_FAILED ? static_cast(mapped) : nullptr; +#endif + check(memory != nullptr, "host shader allocation failed"); + GuestAllocations::Mutation mutation; + mutation.Add(memory, codeBytes + 4096, true, true, true); + code = memory + 256; + } else { + auto* block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(2 * Block, Block)); + check(block != nullptr, "guest reservation failed"); + GuestArena::GuestArenaRelease_nid_postfix(block, 2 * Block); + auto* piece = block + Block / 2; + GuestArena::GuestArenaCommit_nid_postfix(piece, PieceBytes, 0x04, PieceBytes); +#ifdef _WIN32 + AgcDriver::GuestMemory::Unwatch(address(piece), PieceBytes); +#endif + check(!AgcDriver::GuestMemory::Watched(address(piece), PieceBytes), "the unaligned shader range is write-watched"); + GuestAllocations::Mutation mutation; + mutation.Add(piece, PieceBytes, true, true, false); + shader = reinterpret_cast(piece); + code = piece + 256; + } + *shader = {}; + shader->file_header = 0x34333231u; + shader->version = 0x18u; + shader->header_size = sizeof(Shader); + shader->shader_size = codeBytes; + shader->code = code; + auto* recorder = AgcDriver::FrameRecorder::Active(); + check(recorder != nullptr, "frame recorder is disabled"); + recorder->FrameBoundary(); + const auto store = [&](unsigned seed) { + std::vector bytes(codeBytes); + for (std::size_t i = 0; i < bytes.size(); ++i) bytes[i] = static_cast(i * 31 + seed); + std::memcpy(code, bytes.data(), bytes.size()); + return bytes; + }; + const auto checked = rewritten ? FrameCallKind::RegisterShader : FrameCallKind::Flip; + const auto call = [&](FrameCallKind kind) { + if (kind == FrameCallKind::Flip) recorder->Flip(AgcDriver::FlipInfo{}, {}); + else recorder->RegisterShader(shader); + }; + const auto expected = store(17); + call(checked); + store(29); + call(rewritten ? FrameCallKind::Flip : FrameCallKind::RegisterShader); + store(17); + call(checked); + recorder->FrameBoundary(); + const FrameCaptureReader reader(directory); + CapturedMemory memory(reader); + std::map> groups; + for (const auto& chunk : reader.Chunks()) { + if (chunk.kind == FrameMemoryKind::Delta) groups[chunk.group].push_back(&chunk); + } + std::size_t seen = 0; + std::optional> replayed; + for (const auto& captured : reader.Calls()) { + if (captured.kind == checked && ++seen == 2) { + replayed = memory.Read(address(code), codeBytes); + break; + } + if (captured.kind != FrameCallKind::Memory) continue; + if (const auto found = groups.find(captured.values.at(0)); found != groups.end()) memory.Apply(found->second); + } + check(seen == 2, "the capture lost a call of the test"); + check(replayed && *replayed == expected, rewritten ? "the second registration replays the host code a flip's delta wrote, not the code the title registered again" : + host ? "after the second flip the replay keeps the host code a shader delta wrote, not the code the title restored" : + "after the second flip the replay keeps the code a shader delta wrote into an unaligned unwatched range, not the code the title restored"); +} + +void testRemappedRange(const std::filesystem::path& directory) { + constexpr std::size_t Block = FrameCaptureWriter::BlockBytes; + auto* recorder = AgcDriver::FrameRecorder::Active(); + check(recorder != nullptr, "frame recorder is disabled"); + recorder->FrameBoundary(); + auto* piece = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Block, Block)); + check(piece != nullptr, "guest reservation failed"); + GuestArena::GuestArenaCommit_nid_postfix(piece, Block, 0x04, Block); +#ifdef _WIN32 + AgcDriver::GuestMemory::Unwatch(address(piece), Block); +#endif + check(!AgcDriver::GuestMemory::Watched(address(piece), Block), "the remapped range is write-watched"); + const auto map = [&] { + GuestAllocations::Mutation mutation; + mutation.Add(piece, Block, true, true, false); + }; + const std::vector first(Block, std::byte{0x3a}); + const std::vector second(Block, std::byte{0xc5}); + std::memcpy(piece, first.data(), Block); + map(); + recorder->Flip(AgcDriver::FlipInfo{}, {}); + recorder->Flip(AgcDriver::FlipInfo{}, {}); + { + GuestAllocations::Mutation mutation; + mutation.Remove(piece); + } + map(); + std::memcpy(piece, second.data(), Block); + recorder->Flip(AgcDriver::FlipInfo{}, {}); + std::memcpy(piece, first.data(), Block); + recorder->Flip(AgcDriver::FlipInfo{}, {}); + recorder->FrameBoundary(); + const FrameCaptureReader reader(directory); + CapturedMemory memory(reader); + std::map> groups; + for (const auto& chunk : reader.Chunks()) { + if (chunk.kind == FrameMemoryKind::Delta) groups[chunk.group].push_back(&chunk); + } + std::vector>> replayed; + for (const auto& call : reader.Calls()) { + if (call.kind == FrameCallKind::Flip) replayed.push_back(memory.Read(address(piece), Block)); + if (call.kind != FrameCallKind::Memory) continue; + if (const auto found = groups.find(call.values.at(0)); found != groups.end()) memory.Apply(found->second); + } + check(replayed.size() == 4, "the capture lost a flip of the test"); + check(replayed[2] == second, "the replay does not see the bytes the title wrote into the range mapped again at the same address"); + check(replayed[3] == first, "after the title restored the bytes sampled before the range was mapped again, the replay keeps the bytes written after the remap"); +} + +void testHostShaderPageGpuStore(const std::filesystem::path& directory) { + constexpr std::size_t Page = AgcDriver::FrameRecorder::HostPageBytes; + constexpr std::size_t CodeBytes = 256; + constexpr std::uint32_t Stored = 0x600dcafeu; + auto* block = allocate(1u << 20); + auto* shader = reinterpret_cast(block); + auto* commands = reinterpret_cast(block + Page); +#ifdef _WIN32 + auto* host = static_cast(VirtualAlloc(nullptr, Page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); +#else + void* mapped = mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + auto* host = mapped != MAP_FAILED ? static_cast(mapped) : nullptr; +#endif + check(host != nullptr, "host shader allocation failed"); + { + GuestAllocations::Mutation mutation; + mutation.Add(host, Page, true, true, true); + } + auto* code = host + 256; + auto* label = reinterpret_cast(host + 2048); + *shader = {}; + shader->file_header = 0x34333231u; + shader->version = 0x18u; + shader->header_size = sizeof(Shader); + shader->shader_size = CodeBytes; + shader->code = code; + auto* recorder = AgcDriver::FrameRecorder::Active(); + check(recorder != nullptr, "frame recorder is disabled"); + recorder->FrameBoundary(); + const auto store = [&](unsigned seed) { + std::vector bytes(CodeBytes); + for (std::size_t i = 0; i < bytes.size(); ++i) bytes[i] = static_cast(i * 31 + seed); + std::memcpy(code, bytes.data(), bytes.size()); + return bytes; + }; + store(17); + recorder->RegisterShader(shader); + const std::array write{0xc0033700u, 0x00100200u, static_cast(address(label)), static_cast(address(label) >> 32u), Stored}; + std::memcpy(commands, write.data(), sizeof(write)); + Packet packet{commands, static_cast(write.size()), 0, {}}; + check(sceAgcDriverSubmitDcb(&packet) == 0, "the label write was not submitted"); + AgcDriverWaitIdle_nid_postfix(); + check(std::atomic_ref(*label).load(std::memory_order_acquire) == Stored, "the queue did not write the label"); + const auto expected = store(29); + recorder->RegisterShader(shader); + recorder->FrameBoundary(); + const FrameCaptureReader reader(directory); + CapturedMemory memory(reader); + std::map> groups; + for (const auto& chunk : reader.Chunks()) { + if (chunk.kind == FrameMemoryKind::Delta) groups[chunk.group].push_back(&chunk); + } + std::size_t registrations = 0; + std::optional> replayedCode; + std::optional> replayedLabel; + for (const auto& call : reader.Calls()) { + if (call.kind == FrameCallKind::RegisterShader && ++registrations == 2) { + replayedCode = memory.Read(address(code), CodeBytes); + replayedLabel = memory.Read(address(label), sizeof(std::uint32_t)); + break; + } + if (call.kind != FrameCallKind::Memory) continue; + if (const auto found = groups.find(call.values.at(0)); found != groups.end()) memory.Apply(found->second); + } + check(registrations == 2, "the capture lost a registration of the test"); + check(replayedCode && *replayedCode == expected, "the shader delta of a host page did not hold the code the title stored before the second registration"); + std::uint32_t value = 0; + std::memcpy(&value, replayedLabel->data(), sizeof(value)); + check(value != Stored, "the shader delta of a host page carried a label the GPU stored there, so a replay would see it before the work that writes it"); +} + +bool insideRanges(const FrameCaptureReader& reader, const FrameMemoryChunk& chunk) { + std::map ranges; + for (const auto& range : reader.Chunks()) { + if (range.kind == FrameMemoryKind::Range) ranges[range.address] = std::max(ranges[range.address], range.address + range.bytes); + } + auto cursor = chunk.address; + for (const auto& [begin, end] : ranges) { + if (begin <= cursor && cursor < end) cursor = end; + } + return cursor >= chunk.address + chunk.bytes; +} + +void testShaderBlockHole(const std::filesystem::path& directory) { + constexpr std::size_t Block = FrameCaptureWriter::BlockBytes; + constexpr std::size_t Page = 4096; + auto* block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(2 * Block, Block)); + check(block != nullptr, "guest reservation failed"); + GuestArena::GuestArenaRelease_nid_postfix(block, 2 * Block); + auto* tail = block + 8 * Page; + for (const auto& [piece, bytes] : {std::pair{block, 7 * Page}, std::pair{tail, Block - 8 * Page}}) { + GuestArena::GuestArenaCommit_nid_postfix(piece, bytes, 0x04, bytes); +#ifdef _WIN32 + AgcDriver::GuestMemory::Unwatch(address(piece), bytes); +#endif + GuestAllocations::Mutation mutation; + mutation.Add(piece, bytes, true, true, false); + } + auto* recorder = AgcDriver::FrameRecorder::Active(); + check(recorder != nullptr, "frame recorder is disabled"); + recorder->FrameBoundary(); + auto* shader = reinterpret_cast(tail + 0x2b0); + *shader = {}; + shader->file_header = 0x34333231u; + shader->version = 0x18u; + shader->header_size = sizeof(Shader); + recorder->RegisterShader(shader); + recorder->FrameBoundary(); + const FrameCaptureReader reader(directory); + bool shaderDelta = false; + for (const auto& chunk : reader.Chunks()) { + if (chunk.kind != FrameMemoryKind::Delta) continue; + check(insideRanges(reader, chunk), "a memory delta of the shader's block reaches a page that no range of the capture holds"); + shaderDelta = shaderDelta || (chunk.address <= address(shader) && address(shader) + sizeof(Shader) <= chunk.address + chunk.bytes); + } + check(shaderDelta, "the capture holds no memory delta with the registered shader"); +} + +void testDeltaOutsideRanges(const std::filesystem::path& directory) { + constexpr std::size_t Block = FrameCaptureWriter::BlockBytes; + constexpr std::size_t Page = 4096; + auto* block = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(Block, Block)); + check(block != nullptr, "guest reservation failed"); + GuestArena::GuestArenaRelease_nid_postfix(block, Block); + std::uintptr_t base = 0; + std::size_t arenaSize = 0; + GuestArena::GuestArenaRange_nid_postfix(&base, &arenaSize); + const std::vector delta(Block, std::byte{0x5a}); + FrameCaptureWriter writer(directory); + writer.WriteRange(address(block), 7 * Page, FrameRangeKind::Section, ReadWrite, FrameRangeAccess::Readable | FrameRangeAccess::Writable); + writer.WriteRange(address(block) + 8 * Page, Block - 8 * Page, FrameRangeKind::Section, ReadWrite, FrameRangeAccess::Readable | FrameRangeAccess::Writable); + writer.WriteDelta(2, 0, address(block), delta); + writer.WriteCall(memoryCall(2, 1)); + writer.Finish("{\"arena_base\":" + std::to_string(base) + "}"); + const FrameCaptureReader reader(directory); + std::string message; + try { + restoreMemory(reader); + } catch (const std::exception& error) { + message = error.what(); + } + char hole[48]; + std::snprintf(hole, sizeof(hole), "reaches 0x%llx", static_cast(address(block) + 7 * Page)); + check(message.find(hole) != std::string::npos, ("the replay accepted a memory delta across a page that no range of the capture maps: " + message).c_str()); +} + void writeInspectionCapture(const std::filesystem::path& directory) { constexpr std::uint64_t Commands = 0x1000000001ull; constexpr std::uint64_t Header = 0x2000000000ull; @@ -1528,6 +2014,8 @@ int main(int argc, char** argv) { else if (mode == "store_between_walks") testStoreBetweenWalks(directory); else if (mode == "store_after_unwatch") testStoreAfterUnwatch(directory); else if (mode == "compared_unwatch_race") testComparedUnwatchRace(); + else if (mode == "gpu_store_restored") testGpuStoreRestoredUnwatched(directory); + else if (mode == "unaligned_unwatched") testUnalignedUnwatchedRange(directory); else if (mode == "store_window") testStoreWindow(directory); else if (mode == "store_window_unwritten") testStoreWindowUnwritten(directory); else if (mode == "store_window_stopped") testStoreWindowStopped(directory); @@ -1535,13 +2023,23 @@ int main(int argc, char** argv) { else if (mode == "fresh_note") testFreshNote(directory); #endif else if (mode == "gpu_write_before_delta") testGpuWriteBeforeDelta(directory); + else if (mode == "unwritten_delta") testUnwrittenDeltaBesideBusyQueue(directory); else if (mode == "calls_v1") testVersionOneRefused(directory); else if (mode == "trace_window") testTraceWindow(directory); else if (mode == "tokens") testEopTokens(); + else if (mode == "merge_blocks") testMergedBlocks(); + else if (mode == "unaligned_gpu_fill") testUnalignedGpuFill(); + else if (mode == "captured_spans") testCapturedSpans(); + else if (mode == "remapped_range") testRemappedRange(directory); else if (mode == "reservations" || mode == "reservation_failure") testRepeatedReservations(directory, mode == "reservation_failure"); else if (mode == "blocking") testBlockingSubmission(directory); else if (mode == "environment") testColdPipelines(); else if (mode == "shader" || mode == "shader_host") testShaderCode(directory, mode == "shader_host"); + else if (mode == "shader_host_clipped") testClippedHostShader(directory); + else if (mode == "shader_host_rewritten" || mode == "shader_host_restored" || mode == "shader_unaligned_restored") testDeltaPaths(directory, mode); + else if (mode == "shader_host_gpu_store") testHostShaderPageGpuStore(directory); + else if (mode == "shader_hole") testShaderBlockHole(directory); + else if (mode == "delta_hole") testDeltaOutsideRanges(directory); else throw std::runtime_error("unknown test"); if (mode != "reservation_failure") AgcDriverShutdown_nid_postfix(); std::puts("frame replay state test passed"); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_frame_replay_state_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_frame_replay_state_tests.cmake index e89d4b1a1b17..6fbf0f168b96 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_frame_replay_state_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_frame_replay_state_tests.cmake @@ -16,12 +16,12 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() endforeach() - set(agcFrameReplayModes order tokens blocking reservations reservation_failure environment) + set(agcFrameReplayModes order tokens merge_blocks unaligned_gpu_fill captured_spans blocking reservations reservation_failure environment) if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux") - list(APPEND agcFrameReplayModes zero shader shader_host shader_prologue_code shader_prologue_header shader_prologue_readonly) + list(APPEND agcFrameReplayModes zero shader shader_host shader_host_clipped shader_host_rewritten shader_host_restored shader_unaligned_restored shader_host_gpu_store shader_hole delta_hole shader_prologue_code shader_prologue_header shader_prologue_readonly) endif() if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux") - list(APPEND agcFrameReplayModes unwatched once pending_result partly_covered late_clear store_between_walks store_after_unwatch gpu_write_before_delta calls_v1 store_window store_window_unwritten store_window_stopped compared_unwatch_race sub_page_resets partial_walk large_range flushed_owner untouched_gpu_owner) + list(APPEND agcFrameReplayModes unwatched remapped_range once pending_result partly_covered late_clear store_between_walks store_after_unwatch gpu_write_before_delta unwritten_delta calls_v1 store_window store_window_unwritten store_window_stopped compared_unwatch_race gpu_store_restored unaligned_unwatched sub_page_resets partial_walk large_range flushed_owner untouched_gpu_owner) endif() if(WIN32) list(APPEND agcFrameReplayModes fresh_note) @@ -37,7 +37,7 @@ if(BUILD_TESTING) if(mode STREQUAL "flushed_owner" OR mode STREQUAL "untouched_gpu_owner") set_tests_properties(agc_driver_frame_replay_${mode} PROPERTIES SKIP_RETURN_CODE 77) endif() - if(mode MATCHES "^(shader|once|pending_result|partly_covered|late_clear|store_between_walks|store_after_unwatch|fresh_note|store_window)") + if(mode MATCHES "^(shader|once|remapped_range|pending_result|partly_covered|late_clear|store_between_walks|store_after_unwatch|gpu_store_restored|unaligned_unwatched|fresh_note|store_window|unwritten_delta)") set_tests_properties(agc_driver_frame_replay_${mode} PROPERTIES ENVIRONMENT "APS5_FRAME_CAPTURE=${capture};APS5_FRAME_CAPTURE_AT_FLIP=1;APS5_FRAME_CAPTURE_FRAMES=1;APS5_FRAME_CAPTURE_MIN_FREE_BYTES=0") endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_frame_replay_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_frame_replay_tests.cmake index 6120ed804a25..d1f8c1141b51 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_frame_replay_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_frame_replay_tests.cmake @@ -98,7 +98,7 @@ if(BUILD_TESTING) "PATH=path_list_prepend:$") endif() endforeach() - foreach(mode IN ITEMS rewind_store rewind_copy rewind_compute rewind_release rewind_fill rewind_split wait_label fence_reuse busy_queue rewind_page allocation_ranges gpu_only) + foreach(mode IN ITEMS rewind_store store_idle store_idle_rewind store_idle_unwatched store_second_wait rewind_copy rewind_copy_held rewind_compute rewind_release rewind_fill rewind_split wait_label gpu_store gpu_store_half gpu_fill gpu_fill_half gpu_restore_cached unwatched_start unwatched_late unwatched_shared section_once partly_watched_once gpu_cleared fence_reuse busy_queue rewind_page allocation_ranges gpu_only) add_test(NAME agc_driver_frame_replay_${mode} COMMAND agc_driver_frame_replay_tests $ ${mode}) set_tests_properties(agc_driver_frame_replay_${mode} PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_FRAME_CAPTURE=${CMAKE_CURRENT_BINARY_DIR}/frame-replay-${mode}-capture;APS5_FRAME_CAPTURE_AT_FLIP=1;APS5_FRAME_CAPTURE_FRAMES=2;APS5_FRAME_CAPTURE_MIN_FREE_BYTES=0" diff --git a/core/libs/prx/libSceAgcDriver/tools/FrameCaptureFilter.cpp b/core/libs/prx/libSceAgcDriver/tools/FrameCaptureFilter.cpp index cff72b5c7997..ba02d438578e 100644 --- a/core/libs/prx/libSceAgcDriver/tools/FrameCaptureFilter.cpp +++ b/core/libs/prx/libSceAgcDriver/tools/FrameCaptureFilter.cpp @@ -124,7 +124,7 @@ void FilterFrameCapture(const std::filesystem::path& source, const std::filesyst requireFilter(!createError && createdDestination, "destination already exists or cannot be created: " + destination.string()); try { - AgcDriver::FrameCaptureWriter writer(destination); + AgcDriver::FrameCaptureWriter writer(destination, 1, AgcDriver::FrameCaptureWriter::CachedDeltaBytes, reader.Version()); for (std::size_t index = 0; index < reader.Calls().size(); ++index) { if (!plan.calls.contains(index)) writer.WriteCall(reader.Calls()[index]); } diff --git a/core/libs/prx/libSceAgcDriver/tools/FrameReplay.cpp b/core/libs/prx/libSceAgcDriver/tools/FrameReplay.cpp index 0ce5453786fd..46369627562c 100644 --- a/core/libs/prx/libSceAgcDriver/tools/FrameReplay.cpp +++ b/core/libs/prx/libSceAgcDriver/tools/FrameReplay.cpp @@ -159,6 +159,27 @@ std::uint64_t headerNumber(const std::string& header, std::string_view key) { return std::strtoull(header.c_str() + at + quoted.size(), nullptr, 10); } +void requireMemoryInRanges(const FrameCaptureReader& reader) { + std::map mapped; + for (const auto& chunk : reader.Chunks()) { + if (chunk.kind != FrameMemoryKind::Range) continue; + auto& end = mapped[chunk.address]; + end = std::max(end, chunk.address + chunk.bytes); + } + for (const auto& chunk : reader.Chunks()) { + if (chunk.kind != FrameMemoryKind::Snapshot && chunk.kind != FrameMemoryKind::Delta) continue; + const auto end = chunk.address + chunk.bytes; + auto cursor = chunk.address; + auto range = mapped.upper_bound(cursor); + if (range != mapped.begin()) --range; + for (; range != mapped.end() && range->first <= cursor && cursor < end; ++range) cursor = std::max(cursor, range->second); + if (cursor >= end) continue; + char where[96]; + std::snprintf(where, sizeof(where), " at 0x%llx (%llu bytes) reaches 0x%llx", static_cast(chunk.address), static_cast(chunk.bytes), static_cast(cursor)); + throw std::runtime_error(std::string("frame replay: the memory ") + (chunk.kind == FrameMemoryKind::Delta ? "delta of group " + std::to_string(chunk.group) : std::string("snapshot")) + where + ", which no range of the capture maps"); + } +} + void restore(const FrameCaptureReader& reader, const FrameMemoryChunk& chunk) { reader.Read(chunk, std::span(reinterpret_cast(static_cast(chunk.address)), static_cast(chunk.bytes))); } @@ -314,6 +335,7 @@ Skipped restoreMemory(const FrameCaptureReader& reader) { std::size_t size = 0; GuestArena::GuestArenaRange_nid_postfix(&base, &size); if (!reader.Header().empty() && headerNumber(reader.Header(), "arena_base") != base) throw std::runtime_error("frame replay: the guest arena is at a different address than in the capture"); + requireMemoryInRanges(reader); progress(); Skipped skipped; mapHostRanges(reader, skipped); @@ -884,11 +906,18 @@ struct Replay { bool atCapturedPark(const FrameCall& call) { std::array awaited{}; const auto count = AgcDriverAwaitedWaits_nid_postfix(awaited.data(), awaited.size()); - std::vector parked; - for (std::size_t slot = 0; slot < count; ++slot) parked.push_back(awaited[slot].address); + const std::size_t fields = reader.Version() >= 3 ? 4 : 1; + if (call.values.size() != 2 + fields * call.values[1]) throw std::runtime_error("frame replay: memory delta at call " + std::to_string(call.ordinal) + " lists " + std::to_string(call.values[1]) + " parked waits in " + std::to_string(call.values.size()) + " values"); + std::vector> parked; + for (std::size_t slot = 0; slot < count; ++slot) { + const auto& wait = awaited[slot]; + parked.push_back(fields == 4 && wait.bytes != 0 ? std::array{wait.address, wait.reference, wait.mask, wait.function | (std::uint64_t{wait.bytes} << 32u)} : std::array{wait.address, 0, 0, 0}); + } std::ranges::sort(parked); + std::vector flat; + for (const auto& wait : parked) flat.insert(flat.end(), wait.begin(), wait.begin() + static_cast(fields)); const auto [accepted, completed] = progress(); - return accepted - completed == call.accepted - call.completed && std::ranges::equal(parked, std::span(call.values).subspan(2)); + return accepted - completed == call.accepted - call.completed && std::ranges::equal(flat, std::span(call.values).subspan(2)); } void restoreAtCapturedPark(const FrameCall& call) { diff --git a/docs/dev/BUILD.md b/docs/dev/BUILD.md index 9a7f72e25114..a711bd900dbd 100644 --- a/docs/dev/BUILD.md +++ b/docs/dev/BUILD.md @@ -362,9 +362,9 @@ On Windows use `agc_pm4_replay.exe` and prepend `build/core/libs/libs/unpatched` ## Frame capture and replay -On Windows and Linux, set `APS5_FRAME_CAPTURE` to a directory to record a few frames of a title at the AGC driver boundary, then replay them with `agc_frame_replay` through any build of the driver that accepts their calls format, with no title running. From the start of the process the driver keeps every shader registration and ABI resolution, video output registration and EOP flip reservation. At the frame boundary picked by `APS5_FRAME_CAPTURE_AT_FLIP` (default 1), or by the appearance of the file `APS5_FRAME_CAPTURE_TRIGGER` names (a number in it replaces the frame count), it waits up to 10 s for the driver to go idle, trying again at the next boundary (up to 600) when it does not or as soon as a queue waits on memory only the title can store, and writes every committed allocation of the guest allocation registry that the title can read or the GPU can access, the title's image included, as zstd chunks without their all-zero 64 KiB blocks. A frame ends at a CPU flip, at a submission that flips (a flip packet, or the EOP release of a reserved flip token), or at the next submission, flip or flip reservation after a released REWIND tail flipped; the reservation itself only records its token. For the next `APS5_FRAME_CAPTURE_FRAMES` (10) frames it records each submission (queue, command buffer address and size), flip and suspend point with the thread that made it and the accepted and completed serials, each preceded by the guest pages the write tracker saw the CPU write, or found newly mapped while it collected around a GPU write, since the previous call that handed work to the GPU (`GuestMemory::CollectWrittenBlocks`, per 4 KiB where the tracker kept page stamps), and the pages outside the write watch whose contents changed since the delta that last recorded them (`GuestMemory::ChangedComparedPages`: a page is hashed from the snapshot when its range is unwatched at the start, just before it leaves the watch during the capture, or recorded whole at the next delta when it left without that hash, and it is compared until it is watched again), read through the driver's coherent path once the submissions already accepted have completed or every queue still busy is parked on a REWIND control word or `WAIT_REG_MEM` value the title has not stored yet, with no queued draw, unrecorded label or pending label write left (the parked queues then stay at their waits until the delta is read; a recorded submission, flip or suspend point reaches the driver before the recorder takes its next call, so that wait covers every call recorded before the delta); an allocation the registry gained after the snapshot is recorded there as a new range, with all its 64 KiB blocks when later deltas collect it (write-watched or private guest-arena memory), otherwise with its nonzero ones. A page in the range of a driver store from the CPU that is written during that store counts only when it then differs from its bytes before the store with the store's own bytes applied (another thread wrote it meanwhile), and always when the store does not give the bytes it stores: MEM_SEMAPHORE packets, buffer copies the driver runs on the CPU and compare-exchange write-backs (`WriteChangedIfHeld`). A submission ends a frame only when it flips itself, not when another thread's submission flipped while it was being submitted. Shader registrations and ABI resolutions only collect the blocks of the shader header and the arrays it points to, and the pages of the title's image only when their content changed. At the end it stores each display buffer the title presented, decoded, as a reference image. Without the guest write watch (`APS5_NO_WRITE_WATCH`, or no write watch on the host) the capture throws when it starts, since it could not record CPU stores. A capture is `calls.bin` (calls format 2), `memory.bin` and `capture.json` (commit, switches, sizes, warnings), and the recorder stops with a warning when its volume has less than 4 GiB free. A 20-frame capture in the Demon's Souls Nexus is 5.3 GiB of snapshot and 11.5 GiB of deltas before compression, 3.9 GiB on disk. +On Windows and Linux, set `APS5_FRAME_CAPTURE` to a directory to record a few frames of a title at the AGC driver boundary, then replay them with `agc_frame_replay` through any build of the driver that accepts their calls format, with no title running. From the start of the process the driver keeps every shader registration and ABI resolution, video output registration and EOP flip reservation. At the frame boundary picked by `APS5_FRAME_CAPTURE_AT_FLIP` (default 1), or by the appearance of the file `APS5_FRAME_CAPTURE_TRIGGER` names (a number in it replaces the frame count), it waits up to 10 s for the driver to go idle, trying again at the next boundary (up to 600) when it does not or as soon as a queue waits on memory only the title can store, and writes every committed allocation of the guest allocation registry that the title can read or the GPU can access, the title's image included, as zstd chunks without their all-zero 64 KiB blocks. A frame ends at a CPU flip, at a submission that flips (a flip packet, or the EOP release of a reserved flip token), or at the next submission, flip or flip reservation after a released REWIND tail flipped; the reservation itself only records its token. For the next `APS5_FRAME_CAPTURE_FRAMES` (10) frames it records each submission (queue, command buffer address and size), flip and suspend point with the thread that made it and the accepted and completed serials, each preceded by the guest pages the write tracker saw the CPU write, or found newly mapped while it collected around a GPU write, since the previous call that handed work to the GPU (`GuestMemory::CollectWrittenBlocks`, per 4 KiB where the tracker kept page stamps), and the pages outside the write watch whose contents changed since the delta that last recorded them (`GuestMemory::ChangedComparedPages`: in a range the deltas collect, write-watched, unwatched or writable, a page is hashed from the snapshot when it is outside the watch at the start, just before it leaves the watch during the capture, or recorded whole at the next delta when it left without that hash or a queue worker stored into it from a packet, and it is compared until it is watched again), read through the driver's coherent path once the submissions already accepted have completed or every queue still busy is parked on a REWIND control word or `WAIT_REG_MEM` value the title has not stored yet, with no queued draw, unrecorded label or pending label write left (the parked queues then stay at their waits until the delta is read; a recorded submission, flip or suspend point reaches the driver before the recorder takes its next call, so that wait covers every call recorded before the delta); an allocation the registry gained after the snapshot is recorded there as a new range, with all its 64 KiB blocks when later deltas collect it (write-watched or private guest-arena memory), otherwise with its nonzero ones. A page in the range of a driver store from the CPU that is written during that store counts only when it then differs from its bytes before the store with the store's own bytes applied (another thread wrote it meanwhile), and always when the store does not give the bytes it stores: MEM_SEMAPHORE packets, buffer copies the driver runs on the CPU and compare-exchange write-backs (`WriteChangedIfHeld`). A delta leaves out each word that still holds the last value a queue worker stored there from a packet (`gpu_store_bytes`), so a replayed queue does not see a label or fill before the work that writes it runs. A submission ends a frame only when it flips itself, not when another thread's submission flipped while it was being submitted. Shader registrations and ABI resolutions only collect the blocks of the shader header and the arrays it points to, and the pages of the title's image only when their content changed. At the end it stores each display buffer the title presented, decoded, as a reference image. Without the guest write watch (`APS5_NO_WRITE_WATCH`, or no write watch on the host) the capture throws when it starts, since it could not record CPU stores. A capture is `calls.bin` (calls format 3), `memory.bin` (memory format 2: a delta whose bytes equal the last delta recorded at its address and size shares that payload instead of storing it again, while the writer still holds that delta in its 512 MiB of most recently used deltas, counted as `shared_delta_bytes`; readers accept formats 1 and 2) and `capture.json` (commit, switches, sizes, warnings), and the recorder stops with a warning when its volume has less than 4 GiB free. A 20-frame capture in the Demon's Souls Nexus is 5.3 GiB of snapshot and 11.5 GiB of deltas before compression, 3.9 GiB on disk. -`agc_frame_replay [--no-pace] [--pace-timeout-ms ] [--no-release] [--release-after-ms ] [--no-synthesize] [--strict] [--repeat ] [--cold-pipelines] [--shaders] [--shader-code ] [--submits ] [--trace-serials] [--dump
::]... [--frames ]` maps the captured ranges at their addresses and registers them with their access (a range the replaying process already maps writable, such as the driver's fixed memory, is only refilled, and a non-GPU range it uses itself is skipped and counted), repeats the registrations, then replays the calls of each captured thread on a thread of its own, started in captured order. Before a call that hands work to the GPU it waits until no more submissions are in flight than when the title made it, and before a memory delta until no queue runs, each having finished or waiting on title memory (`--no-pace` turns this off). A call gives up waiting, and `--strict` fails, only once `--pace-timeout-ms` (10000) has passed and no queue is running, each having finished or parked on a wait, or after 10 minutes whatever the queues do: a queue still executing, such as one compiling pipelines on a cold shader cache, is progress. The drain after the last call ends the same way, after 10 s without a completion once no queue is running, and reports what the queues wait on every 10 s. A delta first flushes the driver's writes to the pages it restores, and the parked queues and the other threads' submissions wait until all of it is restored. It copies everything but the words that may gate a queue (the first word of each chunk, the word after each REWIND header and the words a queue is parked on), which it stores last (`kept_words` counts them). A delta also records the waits its queues were parked on when it was read; a replay that reaches it parked elsewhere, such as on a wait the delta's own stores release, applies it, waits until its queues park on those waits with the captured number of submissions in flight, and applies it again without the REWIND control words it sets, storing the clear ones atomically, so a title store that followed GPU work the delta released keeps its bytes (`park_restores` counts these). Titles release GPU waits from threads that never call the driver, so when the driver completes nothing for 3 ms, no queue is running and no memory delta is being paced or applied, the replay reads the waits its queues are blocked on (`AgcDriverAwaitedWaits`). A queue parked on a REWIND is released, once no queue runs, by applying the first later memory delta that sets its control word, with the delta's REWIND control words written last; for any other wait it writes the last earlier recorded CPU value that satisfies the compare, else a value derived from the reference (`--no-synthesize` turns this last step off). It releases one wait at a time and looks again only after another 3 ms with no queue running, so a queue released into work that a second waiting queue depends on runs before that queue is released. It prints one JSON line with the frame count and times, the submissions, the pacing wait, the released waits and how many were derived, the submissions that never completed and, for captures with reference images, the share of identical pixels and the largest channel difference of the replayed display buffers (`--frames` writes both images). Effects that depend on timing (temporal antialiasing, particles) make pixels differ, so expect a visual match rather than identical frames. The replay's device has no window, but it loads the title's Vulkan pipeline cache file (`vk-pipelines-*.bin` in the shader cache directory) as the windowed device does, so pipelines the title already compiled are not compiled again (`--cold-pipelines` starts with an empty one and clears an inherited `APS5_HEADLESS_PIPELINE_CACHE`; that variable is the driver switch). The title replayed its pipeline journal at boot, long before the captured frames, so after the registrations the replay waits for the driver's journal replay to finish before the first pass (`journal_s` in the JSON line). The first pass still compiles every shader and pipeline the frames use that neither cache holds, so `--repeat ` replays the frames n times in one process: before each later pass it resets guest memory in one driver transaction (`AgcDriverGuestMemoryTransaction`): the driver first waits until every accepted submission completed, then stops other threads from taking pending storage images to store and waits for the stores already taken, and holds its GPU lock until the reset ends, so no other thread stores, publishes or retires meanwhile. The transaction does not hold submissions back: its caller must stop every thread that submits first. It fails if a submission was accepted between that wait and its end, but only checks after its body, so it detects such a submission afterwards and misses one still copying its commands and unordered CPU flips, which are not counted. Overlapping transactions keep other threads from taking pending storage images until the last of them ends. Inside it the reset first lists the candidate pages of each captured range: the pages the write tracker saw written since the previous reset (CPU stores and the driver's own, per 64 KiB block; a block the write watch does not cover, or whose walk failed, is a candidate whole) and the pages of every resident owner whose results only the GPU holds (`AgcDriverGpuOwnedRanges`: the color, FMASK, CMASK, DCC and HTILE of multisampled color images drawn on the host, the planes of native depth owners written on the host, depth planes newer on the GPU and pending storage images). It retires the multisampled color images, native depth owners and depth surfaces over a candidate page (`AgcDriverRetireGpuOwners`, walking the driver's own owner lists: multisampled color images whole, native depth owners whole, depth surfaces with their stale planes discarded, and the HTILE reads and the HTILE clears waiting for their depth surface remembered over any part of those pages), so results the next pass rebuilds anyway are not stored first. Other images over those pages, sampled textures for example, are not retired: the rewrite is a guest write like any other, so they reload through the write generations at their next use. It then stores what must land in guest memory before the compare (recorded stores and pending storage images), adds the pages that store wrote to the candidates and retires the owners over them too, and compares only the candidate pages with the snapshot (zero where it holds nothing), page by page in windows of 4 MiB, on worker threads that take pieces of at most 64 MiB, so a range larger than one piece is split over several threads. A page that differs is rewritten from the same decoded window as soon as it is compared, and only those pages are rewritten, so caches over unchanged pages stay valid and an owner whose memory already matches is retired without a rewrite. The standalone replay has no other writer of guest memory during the reset: the threads that replay the captured calls and release GPU waits are joined, and every submission completed, before it starts; the reset fails if guest memory is mapped or unmapped during it. Each pass entry of the JSON line gives `rewritten_bytes` (of them `rewritten_owned_bytes` over GPU owners), `compared_bytes`, `flushed_bytes` (candidate pages the store added), `range_bytes`, `reset_ms`, `verify_ms` (the time `--verify-reset` took inside the transaction, not part of `reset_ms`), `reset_workers` (the threads that compared at least one page) and the owners retired (`retired_color`, `retired_depth_owners`, `retired_depth_surfaces`, `discarded_depth_planes`). `--verify-reset` makes the reset fail, before the transaction ends, when guest memory over a captured range differs from the capture, a resident owner with results only on the GPU remains over a captured range, or any resident owner remains over a candidate page; it walks the driver's resident owner lists (`AgcDriverResidentOwnersOver`), not the reset's owner inventory, but over the same plane footprints that retirement uses, so it catches an owner that retirement skipped or the inventory left out, not a footprint that is too small; the tests pin the footprints to plane ends they state themselves in `agc_graphics_profile_draw` and `agc_driver_multisample_retirement`. On Linux the replay needs the kernel write watch for every watched range and fails with the reason, including the errno of a failed registration, when it is missing (Linux 6.7 or newer); on Windows the arena is write-watched as a whole and a captured range outside it is compared whole at every reset. It then makes the reservations that were pending at the snapshot again (a token still reserved from the previous pass is kept), and the frame times then come from passes 2 to n, with each pass listed under `passes` with the bytes it rewrote (`rewritten_bytes`) of the captured ranges (`range_bytes`). Later passes replay the same frames, so driver caches keyed on values that change every frame in the title (ring addresses in user data, for example) can hit entries of an earlier pass; compare such changes on the first pass with warm disk caches instead. `--shaders` replays nothing and maps no guest memory: it reads the snapshot, applies the captured writes in call order and prints one JSON line per shader registration (code address, size, type, code hash and how many earlier registrations had the same code), then a summary; `--shader-code ` also writes each distinct code as `/type-.bin`. `--submits ` also reads captured memory without mapping guest addresses, applies writes in call order, and lists the first n submissions and flips of the captured frames with their queue and serials, the packets of each and the fields of its waits and releases. `--trace-serials` prints each submission, flip and suspend point with its call ordinal and command address as it is issued; with `APS5_TRACE_GPU` the driver prints the serial it accepts for each address and each completion, so a replay that stops completing can be followed to the call that made the submission. Replay times follow the GPU clock state: lock the clocks (`nvidia-smi -lgc`, `-lmc`) when comparing two drivers. +`agc_frame_replay [--no-pace] [--pace-timeout-ms ] [--no-release] [--release-after-ms ] [--no-synthesize] [--strict] [--repeat ] [--cold-pipelines] [--shaders] [--shader-code ] [--submits ] [--trace-serials] [--dump
::]... [--frames ]` maps the captured ranges at their addresses and registers them with their access (a range the replaying process already maps writable, such as the driver's fixed memory, is only refilled, and a non-GPU range it uses itself is skipped and counted), repeats the registrations, then replays the calls of each captured thread on a thread of its own, started in captured order. Every snapshot and memory delta must lie inside the captured ranges, as the recorder writes them: the replay refuses a capture with one that reaches memory no range maps before it restores any memory, so a capture an older recorder wrote that way has to be recorded again. Before a call that hands work to the GPU it waits until no more submissions are in flight than when the title made it, and before a memory delta until no queue runs, each having finished or waiting on title memory (`--no-pace` turns this off). A call gives up waiting, and `--strict` fails, only once `--pace-timeout-ms` (10000) has passed and no queue is running, each having finished or parked on a wait, or after 10 minutes whatever the queues do: a queue still executing, such as one compiling pipelines on a cold shader cache, is progress. The drain after the last call ends the same way, after 10 s without a completion once no queue is running, and reports what the queues wait on every 10 s. A delta first flushes the driver's writes to the pages it restores, and the parked queues and the other threads' submissions wait until all of it is restored. It copies everything but the words that may gate a queue (the first word of each chunk, the word after each REWIND header and the words a queue is parked on), which it stores last (`kept_words` counts them). A delta also records the waits its queues were parked on when it was read, each with its address, reference, mask, compare function and size (calls format 2 records only the addresses, so a queue on another wait at the same address counts as parked as captured there); a replay that reaches it parked elsewhere, such as on a wait the delta's own stores release, applies it, waits until its queues park on those waits with the captured number of submissions in flight, and applies it again without the REWIND control words it sets, storing the clear ones atomically, so a title store that followed GPU work the delta released keeps its bytes (`park_restores` counts these). Titles release GPU waits from threads that never call the driver, so when the driver completes nothing for 3 ms, no queue is running and no memory delta is being paced or applied, the replay reads the waits its queues are blocked on (`AgcDriverAwaitedWaits`). A queue parked on a REWIND is released, once no queue runs, by applying the first later memory delta that sets its control word, with the delta's REWIND control words written last; for any other wait it writes the last earlier recorded CPU value that satisfies the compare, else a value derived from the reference (`--no-synthesize` turns this last step off). It releases one wait at a time and looks again only after another 3 ms with no queue running, so a queue released into work that a second waiting queue depends on runs before that queue is released. It prints one JSON line with the frame count and times, the submissions, the pacing wait, the released waits and how many were derived, the submissions that never completed and, for captures with reference images, the share of identical pixels and the largest channel difference of the replayed display buffers (`--frames` writes both images). Effects that depend on timing (temporal antialiasing, particles) make pixels differ, so expect a visual match rather than identical frames. The replay's device has no window, but it loads the title's Vulkan pipeline cache file (`vk-pipelines-*.bin` in the shader cache directory) as the windowed device does, so pipelines the title already compiled are not compiled again (`--cold-pipelines` starts with an empty one and clears an inherited `APS5_HEADLESS_PIPELINE_CACHE`; that variable is the driver switch). The title replayed its pipeline journal at boot, long before the captured frames, so after the registrations the replay waits for the driver's journal replay to finish before the first pass (`journal_s` in the JSON line). The first pass still compiles every shader and pipeline the frames use that neither cache holds, so `--repeat ` replays the frames n times in one process: before each later pass it resets guest memory in one driver transaction (`AgcDriverGuestMemoryTransaction`): the driver first waits until every accepted submission completed, then stops other threads from taking pending storage images to store and waits for the stores already taken, and holds its GPU lock until the reset ends, so no other thread stores, publishes or retires meanwhile. The transaction does not hold submissions back: its caller must stop every thread that submits first. It fails if a submission was accepted between that wait and its end, but only checks after its body, so it detects such a submission afterwards and misses one still copying its commands and unordered CPU flips, which are not counted. Overlapping transactions keep other threads from taking pending storage images until the last of them ends. Inside it the reset first lists the candidate pages of each captured range: the pages the write tracker saw written since the previous reset (CPU stores and the driver's own, per 64 KiB block; a block the write watch does not cover, or whose walk failed, is a candidate whole) and the pages of every resident owner whose results only the GPU holds (`AgcDriverGpuOwnedRanges`: the color, FMASK, CMASK, DCC and HTILE of multisampled color images drawn on the host, the planes of native depth owners written on the host, depth planes newer on the GPU and pending storage images). It retires the multisampled color images, native depth owners and depth surfaces over a candidate page (`AgcDriverRetireGpuOwners`, walking the driver's own owner lists: multisampled color images whole, native depth owners whole, depth surfaces with their stale planes discarded, and the HTILE reads and the HTILE clears waiting for their depth surface remembered over any part of those pages), so results the next pass rebuilds anyway are not stored first. Other images over those pages, sampled textures for example, are not retired: the rewrite is a guest write like any other, so they reload through the write generations at their next use. It then stores what must land in guest memory before the compare (recorded stores and pending storage images), adds the pages that store wrote to the candidates and retires the owners over them too, and compares only the candidate pages with the snapshot (zero where it holds nothing), page by page in windows of 4 MiB, on worker threads that take pieces of at most 64 MiB, so a range larger than one piece is split over several threads. A page that differs is rewritten from the same decoded window as soon as it is compared, and only those pages are rewritten, so caches over unchanged pages stay valid and an owner whose memory already matches is retired without a rewrite. The standalone replay has no other writer of guest memory during the reset: the threads that replay the captured calls and release GPU waits are joined, and every submission completed, before it starts; the reset fails if guest memory is mapped or unmapped during it. Each pass entry of the JSON line gives `rewritten_bytes` (of them `rewritten_owned_bytes` over GPU owners), `compared_bytes`, `flushed_bytes` (candidate pages the store added), `range_bytes`, `reset_ms`, `verify_ms` (the time `--verify-reset` took inside the transaction, not part of `reset_ms`), `reset_workers` (the threads that compared at least one page) and the owners retired (`retired_color`, `retired_depth_owners`, `retired_depth_surfaces`, `discarded_depth_planes`). `--verify-reset` makes the reset fail, before the transaction ends, when guest memory over a captured range differs from the capture, a resident owner with results only on the GPU remains over a captured range, or any resident owner remains over a candidate page; it walks the driver's resident owner lists (`AgcDriverResidentOwnersOver`), not the reset's owner inventory, but over the same plane footprints that retirement uses, so it catches an owner that retirement skipped or the inventory left out, not a footprint that is too small; the tests pin the footprints to plane ends they state themselves in `agc_graphics_profile_draw` and `agc_driver_multisample_retirement`. On Linux the replay needs the kernel write watch for every watched range and fails with the reason, including the errno of a failed registration, when it is missing (Linux 6.7 or newer); on Windows the arena is write-watched as a whole and a captured range outside it is compared whole at every reset. It then makes the reservations that were pending at the snapshot again (a token still reserved from the previous pass is kept), and the frame times then come from passes 2 to n, with each pass listed under `passes` with the bytes it rewrote (`rewritten_bytes`) of the captured ranges (`range_bytes`). Later passes replay the same frames, so driver caches keyed on values that change every frame in the title (ring addresses in user data, for example) can hit entries of an earlier pass; compare such changes on the first pass with warm disk caches instead. `--shaders` replays nothing and maps no guest memory: it reads the snapshot, applies the captured writes in call order and prints one JSON line per shader registration (code address, size, type, code hash and how many earlier registrations had the same code), then a summary; `--shader-code ` also writes each distinct code as `/type-.bin`. `--submits ` also reads captured memory without mapping guest addresses, applies writes in call order, and lists the first n submissions and flips of the captured frames with their queue and serials, the packets of each and the fields of its waits and releases. `--trace-serials` prints each submission, flip and suspend point with its call ordinal and command address as it is issued; with `APS5_TRACE_GPU` the driver prints the serial it accepts for each address and each completion, so a replay that stops completing can be followed to the call that made the submission. Replay times follow the GPU clock state: lock the clocks (`nvidia-smi -lgc`, `-lmc`) when comparing two drivers. `agc_frame_replay` refuses a capture whose `calls.bin` is calls format 1 before it restores any memory: that format does not record whether GPU writes had landed before each memory delta was read, so record such a capture again. A delta first flushes the driver's writes to the pages it restores. @@ -378,7 +378,7 @@ the target bound again resolves to the captured colour in every sample. `agc_driver_frame_capture_rewind` makes the six EOP flips from REWIND tails and checks that they start the capture and that it holds the same three frames. `agc_driver_frame_capture_rewind_held` releases each REWIND only after its thread's next call returns and checks that no call waits at a busy frame boundary and that the capture starts at the first idle one. -Six tests with the driver's Vulkan device set a REWIND control word only after the next flip, so the delta before that flip is read while the REWIND waits, and check that the capture holds its frames: `agc_driver_frame_replay_rewind_store` overwrites the result of a copy gated by a `WAIT_REG_MEM` before the REWIND and checks that the replay keeps the CPU store, `agc_driver_frame_replay_rewind_copy` stores into the first page of a 128 MiB copy still running ahead of the REWIND and checks that the replayed delta holds the store and the copied bytes, and skips when the copy finished before the delta was read, `agc_driver_frame_replay_rewind_compute` parks a compute queue's `WAIT_REG_MEM` on a label the REWIND tail writes and checks that the replay runs the compute queue past it, `agc_driver_frame_replay_rewind_release` opens a queue's `WAIT_REG_MEM` gate from another thread 20 ms into a 256 MiB delta and checks that the delta holds the store, not the copy the queue makes after the gate, and `agc_driver_frame_replay_rewind_fill` submits a REWIND whose tail jumps to address 0 in the snapshot, fills the jump and sets the control word together, and checks that the replay runs the filled tail, and `agc_driver_frame_replay_rewind_split` fills the buffer a REWIND tail jumps to 64 MiB past the control word it sets in the same delta and checks that the replay resumes the REWIND only after both are restored. `agc_driver_frame_replay_rewind` parks a queue on a REWIND whose tail the CPU fills while it waits and checks that the strict replay runs the copy the tail chains to, `agc_driver_frame_replay_fence_reuse` releases and re-arms a fence between two recorded calls in each of two frames and checks that the strict replay runs both copies behind it, and `agc_driver_frame_replay_busy_queue` gates 64 MiB of graphics copies and a label on a fence a delta releases, parks a compute queue on that label, and checks that a replay with a 1 ms pacing timeout neither gives up nor releases the compute queue while the copies run. `agc_driver_frame_replay_wait_label` is the game-independent reproducer from #11157: a compute queue waits on a label, the CPU dirties an unrelated byte once the wait is registered, and a later graphics submission writes the label; it checks that the producer's submission does not wait for the capture and that the replay runs the compute queue past the label. +Six tests with the driver's Vulkan device set a REWIND control word only after the next flip, so the delta before that flip is read while the REWIND waits, and check that the capture holds its frames: `agc_driver_frame_replay_rewind_store` overwrites the result of a copy gated by a `WAIT_REG_MEM` before the REWIND and checks that the replay keeps the CPU store, `agc_driver_frame_replay_rewind_copy` stores into the first page of a 128 MiB copy still running ahead of the REWIND and checks that the replayed delta holds the store and the copied bytes, and skips when the copy finished before the delta was read, `agc_driver_frame_replay_rewind_compute` parks a compute queue's `WAIT_REG_MEM` on a label the REWIND tail writes and checks that the replay runs the compute queue past it, `agc_driver_frame_replay_rewind_release` opens a queue's `WAIT_REG_MEM` gate from another thread 20 ms into a 256 MiB delta and checks that the delta holds the store, not the copy the queue makes after the gate, and `agc_driver_frame_replay_rewind_fill` submits a REWIND whose tail jumps to address 0 in the snapshot, fills the jump and sets the control word together, and checks that the replay runs the filled tail, and `agc_driver_frame_replay_rewind_split` fills the buffer a REWIND tail jumps to 64 MiB past the control word it sets in the same delta and checks that the replay resumes the REWIND only after both are restored. `agc_driver_frame_replay_rewind` parks a queue on a REWIND whose tail the CPU fills while it waits and checks that the strict replay runs the copy the tail chains to, `agc_driver_frame_replay_fence_reuse` releases and re-arms a fence between two recorded calls in each of two frames and checks that the strict replay runs both copies behind it, and `agc_driver_frame_replay_busy_queue` gates 64 MiB of graphics copies and a label on a fence a delta releases, parks a compute queue on that label, and checks that a replay with a 1 ms pacing timeout neither gives up nor releases the compute queue while the copies run. `agc_driver_frame_replay_gpu_store` parks a compute queue on a label a graphics queue's `RELEASE_MEM` writes after 256 MiB of fills and a copy, stores beside the label from the CPU, and checks that the delta holds the CPU store but not the label and that the replayed compute queue copies only after the graphics copy, `agc_driver_frame_replay_gpu_fill` overwrites a word of a buffer the driver filled and then stores the fill value back, and checks that the replay keeps the later store, and `agc_driver_frame_replay_gpu_cleared` fills a block before its range is first recorded, clears it, and checks that a replayed copy reads the cleared block. `agc_driver_frame_replay_wait_label` is the game-independent reproducer from #11157: a compute queue waits on a label, the CPU dirties an unrelated byte once the wait is registered, and a later graphics submission writes the label; it checks that the producer's submission does not wait for the capture and that the replay runs the compute queue past the label. - `tools/frame_capture_minimize.py --capture C --replay R --filter F --output O --match-regex RE --expect-exit-code N` minimizes a frame capture while the replay failure that `--match-regex` identifies stays reproducible. `--max-trials`, `--confirm-runs`, `--replay-timeout` and `--temp-dir` bound the search. `tools/frame_capture_minimize.py` shrinks a frame capture from `--capture` while a replay failure stays reproducible. It runs `--replay` on the capture first, `--confirm-runs` times (at least 2), to make sure the failure reproduces, then tries removing calls and chunks of the capture with the `--filter` program and keeps a removal only when the replay still matches `--match-regex` in its output and exits with `--expect-exit-code`. It stops after `--max-trials` replays (default 1000); `--replay-arg` passes an extra argument to the replay (`{trial_dir}` expands to a fresh folder per run). The result is written to `--output`, which must not exist yet. diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index 791c619d2d58..7710240bcc6f 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -160,7 +160,7 @@ Eligible single-sample draws retain native finite bounds inside [0, 1] and use a - [Written staging window on discrete GPUs](../../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp) (libSceAgcDriver) - a written buffer element of a dispatch that is not swept is staged device-local up to 8 MiB on a discrete GPU (`Context::discreteGpu`) and up to 2 MiB otherwise; `APS5_WRITTEN_SHADOW_MAX_KIB` replaces either bound. The 8 MiB figure comes from one title on one NVIDIA Windows system (PPSA09911: a 2.5 and a 3.3 MiB skin-cache output written in place cost 55 ms of GPU time per frame, 1.8 ms of extra staging copies once staged); the point where the two copies of a larger element cost more than its in-place stores, and whether AMD or Linux drivers move it, has not been measured. The window is per element and per use, so a kernel that streams once through an element inside the window pays the copy-in and the copy-back on every dispatch. - [FS table calls on macOS](../../../core/libs/prx/libSceAgcDriver/Execution/include/Driver/DriverMemory.hpp) (libSceAgcDriver) - macOS keeps the console's 0xfe0000000 for itself, so the driver block, and the FS table at 0xfe0040000 inside it, moves to 0xee0000000 there; `sceAgc*StaticBuffer` and `AgcDriverStaticTable_nid_postfix` use the moved address. A shader that builds the table address from two `s_mov_b32` literals loaded it from 0xfe0040000, which macOS reserves, so those dispatches could not link; the driver now rewrites those two literals to the moved address, for the callee lookup and for the code the GPU runs (`RetargetTableCallPointer` in the shader recompiler), and `ComputeFsTableCalls` runs on macOS. A shader that takes the table address from user data instead of literals is not rewritten and still fails to link. #6160 lists titles that build this address. Closes when: a shader that takes the table address from user data is rewritten too - [Capture trace output](../../../core/libs/prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp) has no timeout for permanently blocked file I/O, so normal shutdown can wait for its writer. The pending queue holds up to 16 MiB, and the batch being written can hold another 16 MiB plus loss markers. Queue overflow drops new records until the next drain; markers and a shutdown total identify the incomplete trace. A failed write or flush disables tracing and reports an error to stderr, but the failed output may not receive its final markers. -- [Frame capture](../../../core/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp) (libSceAgcDriver) throws on macOS. Section views, aliases of one direct memory block and file views replay as separate private memory, so a store through one alias is not seen through another. CPU stores during the frames are recorded only in private memory on Windows (at the alias written) and in registered ranges and private anonymous memory on Linux (at every alias of direct memory mapped more than once). Pages outside the write watch are compared with their last recorded bytes at each memory delta, so GPU writes there are recorded too and replay over the replay's own. Title image pages are recorded only when changed and holding a shader header or its arrays. Linux omits no-access pages (Windows records them unreadable) and records file mapping pages past the file's end as unreadable. A capture starts only at a frame boundary where the driver idles within 10 s (up to 600 tries). +- [Frame capture](../../../core/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp) (libSceAgcDriver) throws on macOS. Section views, aliases of one direct memory block and file views replay as separate private memory, so a store through one alias is not seen through another. The write watch records CPU stores in private memory on Windows (at the alias written) and registered ranges and private anonymous memory on Linux (at every alias of direct memory mapped twice or more). Other writable pages are compared with their last recorded bytes at each delta, so GPU writes there, except a queue worker's packet stores, are recorded too and replay over the replay's own. Title image pages are recorded only when changed and holding a shader header or its arrays. Linux omits no-access pages (Windows records them unreadable) and records file mapping pages past the file's end as unreadable. A capture starts only at a frame boundary where the driver idles within 10 s (up to 600 tries). - [Frame capture registered ranges](../../../core/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp) do not record the original allocation base, allocation extent or backing identity. Capture retains registered-range boundaries, but replay creates an allocation per recorded range and restores memory before replaying device setup; it does not reproduce the title's mapping-time import history. - [Frame replay](../../../core/libs/prx/libSceAgcDriver/tools/FrameReplay.cpp) (libSceAgcDriver) orders the calls of different captured threads only by their start (a call starts once every earlier call has started), so the driver sees a schedule the title could have produced, not necessarily the one it did. CPU stores a title made from threads that never call the driver are known only by the next recorded call, so the replay applies them early or late when a GPU wait needs them and derives a value from the wait's reference when no recorded store satisfies it (`of_them_synthesized`). Pacing compares the number of submissions in flight, not what they hold. Prologue registrations of shaders whose memory the title reused after registering them fail and are counted (`stale_registrations`). The title's image range must be free in the replaying process, so the tool is linked at a high image base on Windows. - [Frame capture deltas](../../../core/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp) (libSceAgcDriver) - a capture stops when GPU work in flight at a delta neither completes nor parks every busy queue on a later CPU store within 10 s. @@ -170,6 +170,7 @@ Eligible single-sample draws retain native finite bounds inside [0, 1] and use a - [Workgroup count split](../../../core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp) (libSceAgcDriver) - a direct dispatch over `maxComputeWorkGroupCount` runs as `vkCmdDispatch` chunks, each bound to a pipeline variant whose workgroup offset specialization constants add the chunk's base to `WorkgroupId` and `GlobalInvocationId`. A variant is built when its chunk base is first recorded, not when the dispatch is prepared. A split of a shader with device-memory LDS throws: its slot base reads the chunk's `NumWorkgroups`, not the dispatch's. Chunks are ordered by a compute barrier, which the console does not have between workgroups of one dispatch. - [Experimental submission progress](../../../core/libs/prx/libSceAgcDriver/Execution/include/Driver/Queues/SubmissionProgress.hpp) (AGC driver) - the opt-in two-millisecond pacing budget is not derived from console hardware. Cross-title performance remains unvalidated; host scheduling can overshoot the timeout and pacing can reduce CPU/GPU overlap. - [GPU allocation recovery](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) (libSceAgcDriver) - recovery may free too little and still throw: caller-held sampled images, pending storage results and recorder references stay alive. Budgets remain floors rather than hard device limits. Image and buffer allocation failures trim idle buffers, then sampled and clean storage cache entries. A held cache lock is reused only for a new image's allocation after lookup iterators are no longer used; hit refreshes and flushes skip that cache. Other cache, resource and device locks are tried without waiting. +- [GPU stores in frame capture deltas](../../../core/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp) (libSceAgcDriver) - a memory delta leaves out a byte only while it still holds the last value a queue worker stored there from a packet (labels, `WRITE_DATA`, `COPY_DATA`, `DMA_DATA` up to 64 KiB, semaphores, constant RAM and sample dumps byte by byte; fills whose address and size are multiples of 4 by their 16-byte pattern; other fills stay in the delta), counted as `gpu_store_bytes`. Larger CPU-executed copies, GPU copies (`DMA_DATA` over 64 KiB or behind pending stores, copy kernels), dumped occlusion counters, timestamps of `RELEASE_MEM` packets the CPU executes, shader stores and render target write-backs stay in the delta, so a replay can see those values before the work that makes them runs. Closes when: copied and dumped values are read back once the GPU completes them, and the executed timestamp is carried into the label history. - [UINT color targets](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver) - whether the console's CB blends into integer targets is not measured, and what a raw 32-bit export into an 8- or 16-bit UINT channel stores is measured on Navi21 only (#11513), not on the console: `32_R` keeps the word's low bits, `32_GR` and `32_ABGR` clamp it as an unsigned integer, and `32_AR` gave no consistent result there, so it is passed unchanged and the attachment's conversion, which Vulkan leaves undefined, decides. Here a raw 32-bit export (`32_R`, `32_GR`, `32_AR`, `32_ABGR`) into a UINT target is passed as the exported bits through the `Uint` export packing, masked (`32_R`, the `UintMask8` and `UintMask16` packings) or clamped (`32_GR` and `32_ABGR`, `UintClamp8` and `UintClamp16`) to an 8- or 16-bit channel, and the target's blend is dropped; the execution test draws `32_R` into `R32_UINT`, `32_GR` into `R32G32_UINT` and `32_AR` and `32_ABGR` into `R32G32B32A32_UINT` (tiled and linear) and reads every written channel back bit for bit, draws words wider than the channel into 8- and 16-bit UINT targets, and draws through each masking and clamping packing into `R32_UINT` and `R32G32B32A32_UINT`. On lavapipe (Mesa, LLVM 20) a constant export of exactly 1.0 in the first channel and -0.0 in the second stores +0.0 in the second although the module declares `SignedZeroInfNanPreserve`, so the test leaves that pair out. The blend is dropped since Vulkan's framebuffer chapter says blending is only defined for floating-point, UNORM, SNORM and sRGB formats and Metal refuses both the float output and the blend on integer attachments (#9783). An `FP16_ABGR` export into a UINT target stores each half widened to a 32-bit float (a NaN with its quiet bit set) and read as an unsigned integer, clamped to the channel, so an 8- or 16-bit channel holds 0 for +0.0 and its maximum for any other half; two Navi21 GPUs (RDNA2) store this with RADV forced to `FP16_ABGR` (#11513), the console is not measured. The shader widens the half bits with integer operations and the `UintClamp8` and `UintClamp16` packings clamp them; the execution test draws halves read at run time into 32-, 16- and 8-bit UINT targets, and through each clamping packing into `R32_UINT`. An uncompressed `FP16_ABGR` export into a UINT target keeps its 32-bit words without a conversion to half, which is not measured. `UNORM16_ABGR`, `SNORM16_ABGR` and `SINT16_ABGR` exports into UINT targets throw. - [Scan-resistant sampled texture admission](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) (libSceAgcDriver) - while the sampled texture cache is over its budget but within a quarter over it, the first use of a texture it does not hold in a present is refused (used for its draw, then released, never cached) when its least recently used entry was used in the current or previous present, and a later use in the same present is refused when that entry was used in the current present. So a working set larger than the budget keeps a stable subset: a texture used more than once in a present still evicts an entry not yet used in that present, so a working set with interleaved multi-use textures rotates as on main, and the textures that arrive after the cache fills are created again at each use for as long as the least recently used entry is from the current present, including in the transition present after a scene change. Past a quarter over the budget the entries are evicted as before, so after the budget falls the cache can sit at up to 125% of the reduced budget until entries stop being used. Entries unused for two presents are evicted as before. A later use can evict an entry from the previous present and then be refused when the next least recently used entry is from the current present, so that entry is created again in the next present. The "current or previous present" window is an unmeasured threshold: it was chosen, not derived. Measured once, as one A-B-A series on one title (loading phase about 33000 textures per frame against a 5.4 GiB budget) on one RTX 4090, 3600 s each: 932 / 968 / 941 frames, evictions after frame 620 2.72M -> 1.17M, texture creations unchanged (about 5.8M). Nothing is measured on other titles or GPUs, and a title whose per-present working set only slightly exceeds the budget now re-creates the excess textures at every use. - [Texture cache budgets](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) (libSceAgcDriver) - the storage image cache gets what the reported heap budget leaves after the heap's other use, the live sampled textures and an eighth of the budget, capped at half of the budget and of the heap, at least 512 MiB; the sampled cache reserves the larger of `TextureCacheBudget` and the storage images held, and keeps at least 2 GiB; above the floors neither budget plus the other cache's bytes exceeds the budget less its eighth. Both read the heap at most once a second and trim at their next insert, so a burst can exceed the budget. The storage budget gives back the part of the sampled floor not in use. The eighth and the floors were checked only on PPSA11386 (10 GB GPU) and PPSA16064 (8 GB GPU); the halves come from PPSA25636 on one 8 GB GPU (a 3.5-4 GiB storage working set). A title whose storage working set exceeds its budget re-creates storage images at each use. @@ -259,6 +260,7 @@ Eligible single-sample draws retain native finite bounds inside [0, 1] and use a - [Pages under an import window](../../../core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp) whose protection an import resolves count as stored only when their bytes change. A same-value CPU store during that window cannot be distinguished from driver activity and does not win over pending results. On Windows, NVIDIA 617.42 marks every private MEM_WRITE_WATCH page after import until a GPU use completes. The driver behavior was measured on this driver; other drivers are unverified. Imports of at least 1 MiB wait for a four-byte read on the separate settle queue inside the window. Smaller imports stay compared until a deferred read completes; a later lookup returns their pages to write watching, stamping their blocks as CPU stores; the block's other pages keep their state. Blocks overlapping a live storage image, blocks of an import retired before rewatching, and imports without a settle queue stay compared. Shared-memory imports retain their separate-alias tracking. - [Driver stores during a frame capture](../../../core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp) (libSceAgcDriver) - MEM_SEMAPHORE packets, buffer copies that the driver runs on the CPU and compare-exchange write-backs (`WriteChangedIfHeld`) do not give the bytes they store, so while a capture records, every page they write is recorded in the next memory delta even when no other thread wrote it, and the replay writes the captured bytes there over what its own store wrote. How many delta bytes this adds and whether it changes replayed waits is not measured. When a driver store from the CPU gives its bytes, a store another thread makes during it that puts back bytes a GPU write into a watched host import changed during that store leaves the page equal to the store's copy, so that store is recorded only when another store since the previous memory delta gets the page listed; `main` also recorded it when the previous memory delta had found the page written. - [CPU stores during driver stores](../../../core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp) (libSceAgcDriver) - a CPU store another thread makes into a page that a driver store from the CPU covers (`Write`, `WriteChanged`, `StoreOwnBytes`, guest labels, MEM_SEMAPHORE packets and buffer copies run on the CPU) while that store runs counts as the driver's. `UnchangedSinceCollected`, the CPU flag of `ChangedBlocks` and `StoredOver` over bytes beside the driver's do not see it (`UnchangedSince` does), so a unit shadow publish or kept storage-image results can land over it, and a WAIT_REG_MEM can pass on a recorded label value that store replaced (a late label hit). While a frame capture records, `CollectWrittenBlocks` lists the page when it then differs from its bytes before the store with the store's own bytes applied, and always for MEM_SEMAPHORE packets and buffer copies. How often titles do this is not measured. +- [Restores outside the write watch during a frame capture](../../../core/libs/prx/libSceAgcDriver/Execution/src/FrameRecorder.cpp) (libSceAgcDriver) - a page outside the write watch is recorded when its bytes differ from the ones the delta that last recorded it read. A store the driver notes there (`StoreOwnBytes`, writes it marks after GPU work) makes the page unknown, so the next delta reads it. When a write the driver does not note changes such a page and the title then puts back the recorded bytes before the next delta, the page matches and the restore is not recorded, so the replay keeps that write. How often titles do this is not measured. - [Deferred host-import reads](../../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp) use the main queue with barriers ordering earlier and later writes around the reads. Submission does not wait on the CPU. An initial multisampled DCC import needing a range whose import still awaits its read submits it if needed and waits under the GPU mutex (`WatchedAfterSettle`, #9724). Imports of partial 64 KiB blocks are read the same way; that read or one on demand returns their pages as CPU stores unless a live, trimmed or parked compared import or storage image shares their blocks; one a recorder holds is unseen. The latency cost of placing batches behind main-queue work is unmeasured. The first-use test now checks that earlier main-queue reads finish before the import returns to write watching; the original two-queue canary measured driver marking while those reads were still in flight. The earlier-import canary still checks later use of another import of the same pages. - [Settled dma-buf imports](../../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp) (libSceAgcDriver): on Linux a dma-buf import of 1 MiB or more is read by a 4-byte copy on the settle queue right after it is made (`settleImport`), so the kernel maps its pages for the GPU there and not in the first submission that uses it (about 2 s for a 3 GiB import on RADV). The import's buffer is shared with the settle queue's family. An import made at map time settles on the guest thread that maps the range, inside its map call, so that thread waits while the kernel maps the pages: 0.47 to 2.2 s for the 3 GiB range of Hades (PPSA03355) and 0.49 to 4.3 s for the 4.5 GiB range of ASTRO BOT (PPSA21567) on RADV. Both titles map these ranges at start-up; a title that maps large ranges during gameplay stalls its mapping thread for as long. An import made from a submission settles under the GPU mutex, so its frame still pays for it; a smaller import, and every import on a device with no settle queue (one without a copy-capable queue besides the main one), pays in its first submission. A range imported through a host pointer, as lavapipe imports shared memory, is not settled - [Sparse dma-buf imports](../../../core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp) (libSceAgcDriver): on Linux a shared-backed range larger than one 64 MiB udmabuf buffer is imported as one sparse buffer bound to the 64 MiB buffers, on a queue of its own when the device has a second family that binds sparse memory. The path is decided before anything is imported, and a failure after that throws. A range whose offset in the backing file is not a multiple of 64 KiB starts its sparse buffer at the 64 KiB block below it (`HostImport::lead`). A range takes the single udmabuf import instead, which udmabuf's `size_limit_mb` refuses above 64 MiB by default so the range is copied, when the buffer's sparse block size is larger than 64 KiB (it is 64 KiB on RADV), when the sparse buffer does not accept every memory type a chunk import can have, when the backing file ends inside its last chunk, or when it is imported at map time on a device with no second family (the bind then needs the GPU mutex); the NVIDIA proprietary driver imports no dma-buf memory. A run list above 64 MiB is bound from the shared 64 MiB chunk imports in one sparse buffer, as a single run above 64 MiB is; one at or below 64 MiB, or one whose runs are not on the sparse block size, is one udmabuf of the list, which the kernel refuses above `size_limit_mb` (64 MiB by default) A single-run range of 32 MiB or less that crosses a chunk boundary is bound into a 64 MiB udmabuf buffer that starts 32 MiB into a chunk, not into a sparse buffer; a range of several runs or a single run above 32 MiB that is not inside one chunk takes the sparse path at any size. A range the sparse path declines (no GPU lock and no queue of its own, or a backing it cannot bind) is imported as a buffer object of its own, which amdgpu validates at every submission.