From 76f1d48e60686cfea7c924fb4340f93f3123bc7e Mon Sep 17 00:00:00 2001 From: boykopovar Date: Mon, 28 Sep 2026 13:27:14 +0300 Subject: [PATCH] debug(agc): detect gpu input buffer changes between recording and execution --- .../Execution/include/CaptureTrace.hpp | 95 +++++++++++++++++++ .../libSceAgcDriver/Execution/src/Driver.cpp | 5 + .../Execution/src/VulkanDevice.cpp | 3 + .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 71 +++++++++++++- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 5 + .../Graphics/src/ShaderResources.cpp | 2 + .../libSceAgcDriver/Graphics/src/Texture.cpp | 6 ++ 7 files changed, 186 insertions(+), 1 deletion(-) create mode 100644 core/libs/prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp new file mode 100644 index 000000000..56dd9215f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp @@ -0,0 +1,95 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver { + +class CaptureTrace { +public: + static bool Enabled() { + static const bool enabled = std::getenv("APS5_CAPTURE_TRACE") != nullptr; + return enabled; + } + + template + static void Log(const char* format, TArgs... args) { + if (!Enabled()) return; + std::array line{}; + const auto size = std::snprintf(line.data(), line.size(), format, args...); + if (size < 0 || static_cast(size) >= line.size()) throw std::runtime_error("Capture trace event exceeds 2047 bytes"); + static CaptureTrace& trace = instance(); + trace.append(std::string(line.data(), static_cast(size))); + } + +private: + static CaptureTrace& instance() { + static CaptureTrace trace; + return trace; + } + + CaptureTrace() { + output.exceptions(std::ios::badbit | std::ios::failbit); + output.open("capture-trace.log", std::ios::binary); + worker = std::thread([this] { run(); }); + } + + ~CaptureTrace() { + { + std::lock_guard lock(mutex); + stopping = true; + } + changed.notify_one(); + worker.join(); + } + + void append(std::string line) { + const auto elapsed = std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count(); + std::lock_guard lock(mutex); + if (pending.size() + line.size() + 64 > 16 * 1024 * 1024) throw std::runtime_error("Capture trace queue exceeded 16 MiB"); + pending += std::to_string(++sequence) + " " + std::to_string(elapsed) + "us " + line + "\n"; + if (line.starts_with("blit ")) flushRequested = true; + if (pending.size() >= 65536 || flushRequested) changed.notify_one(); + } + + void run() { + try { + for (;;) { + std::string batch; + { + std::unique_lock lock(mutex); + changed.wait_for(lock, std::chrono::milliseconds(100), [this] { return stopping || flushRequested || pending.size() >= 65536; }); + if (stopping && pending.empty()) return; + batch.swap(pending); + flushRequested = false; + } + if (batch.empty()) continue; + output.write(batch.data(), static_cast(batch.size())); + output.flush(); + } + } catch (const std::exception& error) { + std::fprintf(stderr, "Capture trace failed: %s\n", error.what()); + std::terminate(); + } + } + + std::ofstream output; + std::mutex mutex; + std::condition_variable changed; + std::string pending; + std::thread worker; + std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); + unsigned long long sequence = 0; + bool stopping = false; + bool flushRequested = false; +}; + +} diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver.cpp index 4af28bfd6..e02a1ac14 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -5621,6 +5622,7 @@ private: const auto opcode = (header >> 8u) & 0xffu; // Names this packet for the flush hook's sync attribution ([hooksync]); the flip is 0xffff. GuestMemory::SetCurrentPacket(header == FlipPacketHeader ? 0xffffu : opcode, submission.queue); + CaptureTrace::Log("packet submission=%llu queue=%x offset=%zu header=%08x words=%zu", static_cast(submission.serial), submission.queue, cursor, header, packet.size()); // Pending labels and full batches go to the GPU before this packet's own work starts // (see flushBetweenPackets); labels themselves only check the deadline, so a label // group shares one submission. Timed on its own, before the packet's timer starts. @@ -5930,6 +5932,7 @@ private: frame->IncludeSubmission(submission.serial, now, now, now, true); frame->SetFlip(submission.serial, cursor, now, now); frame->NoteFlipBatches(batchesAtFlip, unsignaledAtFlip); + CaptureTrace::Log("flip frame=%llu submission=%llu offset=%zu batch=%llu unsignaled=%llu", static_cast(frameSerial), static_cast(submission.serial), cursor, static_cast(batchesAtFlip), static_cast(unsignaledAtFlip)); submission.flips.at(cursor)->GpuReady(frame); } else if (opcode == 0x15) { timed(&WorkerProfile::dispatchMs, [&] { tolerate("dispatch", [&] { dispatch(queue, packet, submission); }); }); @@ -5994,6 +5997,7 @@ private: std::string rejected; const auto verdict = draw(queue, packet, submission, rejected); drawn = verdict == DrawVerdict::Drawn; + CaptureTrace::Log("draw submission=%llu queue=%x offset=%zu target=%llx mask=%x verdict=%d reason=%.256s", static_cast(submission.serial), submission.queue, cursor, static_cast(color), readRegister(queue.context, 0x8e), static_cast(verdict), rejected.c_str()); if (verdict == DrawVerdict::Rejected) { skipped(rejected); countSkip(Graphics::DrawSkip::Prechecked); @@ -6003,6 +6007,7 @@ private: std::fprintf(stderr, "[draw] target 0x%llx mask 0x%x ok\n",static_cast(color), readRegister(queue.context, 0x8e)); } } catch (const std::exception& error) { + CaptureTrace::Log("draw-error submission=%llu offset=%zu reason=%.256s", static_cast(submission.serial), cursor, error.what()); skipped(error.what()); countSkip(Graphics::DrawSkip::Thrown); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 7513ee855..83bd0b373 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "BdaAbi.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" @@ -1755,6 +1756,7 @@ bool VulkanDevice::PresentDisplayBuffer(const DisplayBuffer& buffer) { lastReport = std::chrono::steady_clock::now(); std::fprintf(stderr, "[flip] %llu presents from the resident image (%llu refreshed first), through guest memory: %llu not pending, %llu unsuitable; %llu GPU frame dumps\n", static_cast(residentPresents), static_cast(refreshedPresents), static_cast(notPending), static_cast(unsuitable), static_cast(gpuDumps)); } + CaptureTrace::Log("present dump=%d address=%llx width=%u height=%u resident=%d generation=%llu", dumpFrame ? state->nextDumpIndex : -1, static_cast(buffer.address), buffer.width, buffer.height, resident != nullptr, static_cast(resident ? resident->Generation() : 0)); if (!present(buffer.width, buffer.height, true, {}, &buffer, resident, filter, dumpFrame)) { // A dropped frame (swapchain out of date) keeps the dump numbering contiguous. if (dumpFrame) --dumps.dumped; @@ -1837,6 +1839,7 @@ bool VulkanDevice::present(std::uint32_t width, std::uint32_t height, bool opaqu SubmitRecorded(false); std::chrono::steady_clock::time_point lastSubmittedAt{}; const std::uint64_t batchesAtBlit = state->recorder ? state->recorder->NewestSubmitted(&lastSubmittedAt) : 0; + CaptureTrace::Log("blit dump=%d batch=%llu slot=%zu image=%u direct=%d", dumpFrame ? state->nextDumpIndex : -1, static_cast(batchesAtBlit), state->presentCursor, index, direct); timing.Mark("pixel_upload"); APS5_LOG_OUT_DEBUG("present source=%s bytes=%zu", pixels.empty() ? "clear" : "pixels", pixels.size()); auto commands = slot.commands; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index b90d4969a..3fd283069 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -8,6 +8,7 @@ #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libc/include/General.hpp" #include "Optimization/include/Optimization/ShaderStageInputInfo.hpp" @@ -998,6 +999,72 @@ struct RecordedDraw { // attachments with nothing recorded between them share one pass; the host-write and host-read // barriers are implicit in the submission and the fence. Then the kept objects, the completion // work and, for a waited-for draw, the recorder sync. +bool CaptureInputsEnabled() { + static const bool enabled = std::getenv("APS5_CAPTURE_INPUTS") != nullptr; + Require(!enabled || CaptureTrace::Enabled(), "APS5_CAPTURE_INPUTS requires APS5_CAPTURE_TRACE"); + return enabled; +} + +void captureInputs(const Context& context, Recorder& recorder, VkCommandBuffer commands, const ShaderResources& resources, std::uint64_t target) { + struct Sample { + std::uint64_t address; + std::size_t offset; + std::vector expected; + VkBuffer source; + VkDeviceSize sourceOffset; + }; + static unsigned long long nextDraw = 0; + const auto draw = ++nextDraw; + const auto batch = static_cast(recorder.Submissions() + 1); + std::vector samples; + std::size_t total = 0; + for (const auto& [begin, end] : resources.InPlaceReads()) { + Require(end >= begin, "invalid capture input range"); + const auto bytes = static_cast(end - begin); + if (bytes == 0 || bytes > 512) continue; + if (resources.WritesOverlap(begin, bytes) || recorder.PendingWriteOverlaps(begin, bytes)) { + CaptureTrace::Log("input-skip draw=%llu batch=%llu address=%llx bytes=%zu reason=gpu-writer", draw, batch, static_cast(begin), bytes); + continue; + } + const auto* imported = HostImportFor(context, begin, bytes); + Require(imported != nullptr, "capture input has no host import"); + Require(begin % 4 == 0 && bytes % 4 == 0, "capture input is not aligned for a Vulkan buffer copy"); + Require(total + bytes <= 65536, "capture inputs exceed 64 KiB per draw"); + Sample sample{begin, total, std::vector(bytes), imported->buffer, begin - imported->base}; + std::memcpy(sample.expected.data(), reinterpret_cast(begin), bytes); + total += bytes; + samples.push_back(std::move(sample)); + } + CaptureTrace::Log("input-capture draw=%llu batch=%llu target=%llx ranges=%zu bytes=%zu", draw, batch, static_cast(target), samples.size(), total); + if (samples.empty()) return; + auto readback = std::make_shared(context, total, VK_BUFFER_USAGE_TRANSFER_DST_BIT); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); + const auto copy = context.Function("vkCmdCopyBuffer"); + for (const auto& sample : samples) { + const VkBufferCopy region{sample.sourceOffset, sample.offset, sample.expected.size()}; + copy(commands, sample.source, readback->Handle(), 1, ®ion); + } + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_HOST_READ_BIT | VK_ACCESS_SHADER_READ_BIT); + recorder.OnComplete([draw, batch, target, readback, samples = std::move(samples)] { + const auto actual = readback->Bytes(); + std::size_t differences = 0; + for (const auto& sample : samples) { + std::size_t changed = 0; + for (std::size_t index = 0; index < sample.expected.size(); ++index) { + const auto gpu = actual[sample.offset + index]; + if (sample.expected[index] == gpu) continue; + if (changed < 16) CaptureTrace::Log("input-byte draw=%llu batch=%llu address=%llx offset=%zu cpu=%02x gpu=%02x", draw, batch, static_cast(sample.address), index, std::to_integer(sample.expected[index]), std::to_integer(gpu)); + ++changed; + } + if (changed != 0) { + ++differences; + CaptureTrace::Log("input-mismatch draw=%llu batch=%llu target=%llx address=%llx bytes=%zu changed=%zu", draw, batch, static_cast(target), static_cast(sample.address), sample.expected.size(), changed); + } + } + CaptureTrace::Log("input-result draw=%llu batch=%llu ranges=%zu mismatched=%zu", draw, batch, samples.size(), differences); + }); +} + void recordDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span shaders, DrawInputs& inputs, RecordedDraw& record, DrawOutcome& outcome, DrawTimer& timer, double& ownWaitedMs) { auto* recorder = record.recorder; auto& resources = *record.resources; @@ -1030,10 +1097,12 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam if (recorder->HasQueuedKeyStores() && (resources.HoldsLease() || recorder->AnyQueuedKeyStore(touches))) recorder->FlushKeyStores(); // A queued label store over such memory likewise (Recorder::RecordStore). if (recorder->HasQueuedStores() && (resources.HoldsLease() || recorder->AnyQueuedStore(touches))) recorder->FlushStores(); - const bool continued = !readsTarget && !gpuIndirect && recorder->ContinuesRenderPass(passKey); + const bool capture = CaptureInputsEnabled(); + const bool continued = !capture && !readsTarget && !gpuIndirect && recorder->ContinuesRenderPass(passKey); outcome.passContinued = continued; outcome.passBegun = !continued; const auto commands = continued ? recorder->CommandsInRenderPass() : recorder->Commands(); + if (capture) captureInputs(context, *recorder, commands, resources, record.targets.empty() || record.targets.front() == nullptr ? 0 : record.targets.front()->Descriptor().baseAddress); // The draw's [gputime] class range: from its first barrier to the pass's trailing barrier (a // continued draw lies inside its pass's range). const auto drawTiming = !continued ? recorder->BeginGpuTiming(CommandClass::Draw) : Recorder::NoTiming; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index d9184240f..f796220fd 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" @@ -1894,6 +1895,7 @@ void Recorder::OnComplete(std::function action) { } bool Recorder::noteWrite(std::uint64_t address, std::size_t bytes, bool ownLabel) { + CaptureTrace::Log("buffer-write batch=%llu address=%llx bytes=%zu label=%d", static_cast(submissions + 1), static_cast(address), bytes, ownLabel); if (bytes == 0) return false; ensureOpen(); const auto end = address + bytes; @@ -2015,6 +2017,7 @@ bool Recorder::ReadTracking() { } void Recorder::NotePendingRead(std::uint64_t address, std::size_t bytes, ReadKind kind) { + CaptureTrace::Log("buffer-read batch=%llu address=%llx bytes=%zu kind=%d", static_cast(submissions + 1), static_cast(address), bytes, static_cast(kind)); if (bytes == 0 || !ReadTrackingEnabled()) return; ensureOpen(); open->reads.push_back({address, address + bytes, kind}); @@ -2025,6 +2028,7 @@ void Recorder::NotePendingReads(std::span(submissions + 1), static_cast(begin), static_cast(end - begin), static_cast(kind)); if (end > begin) open->reads.push_back({begin, end, kind}); } readsNoted.fetch_add(ranges.size(), std::memory_order_relaxed); @@ -2345,6 +2349,7 @@ void Recorder::Submit() { submission.pCommandBuffers = &batch->commands; // The timeline reaches this batch's serial when it completes (see WaitSerial). const std::uint64_t serial = submissions + 1; + CaptureTrace::Log("submit batch=%llu reads=%zu writes=%zu", static_cast(serial), batch->reads.size(), batch->writes.size()); VkTimelineSemaphoreSubmitInfoKHR timelineInfo{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO_KHR}; timelineInfo.signalSemaphoreValueCount = 1; timelineInfo.pSignalSemaphoreValues = &serial; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index f55e3ebf6..35c605c26 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include @@ -260,6 +261,7 @@ std::shared_ptr sampledStorageSource(const Context& context, con // `guestBytes` is the surface size when the caller described the surface already (0: described here). std::shared_ptr cachedTexture(const Context& context, std::span words, const GuestTextureResource& resource, VkComponentMapping components, std::uint64_t guestBytes = 0) { + CaptureTrace::Log("sampled-lookup address=%llx width=%u height=%u dcc=%llx", static_cast(resource.baseAddress), resource.width, resource.height, static_cast(resource.dccAddress)); static const bool disabled = std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr; const bool profile = LookupOutcomes::Profiled(); const auto start = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index da0d220ee..74f55c1a8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libc/include/General.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" @@ -1062,6 +1063,7 @@ bool StorageTexture::Refresh() { if (profile) LookupOutcomes::Add(stamped ? LookupOutcomes::RefreshUnchanged : LookupOutcomes::RefreshCompared, start); return true; } + CaptureTrace::Log("refresh image=%llx bytes=%llu generation=%llu dirty=%d keysChanged=%d cpuWrote=%d", static_cast(descriptor.baseAddress), static_cast(guestBytes), static_cast(generation), dirty, keysChanged, cpuWrote); // Debug aid: APS5_TRACE_UPLOAD names why a storage image is uploaded again. static const bool traceUpload = std::getenv("APS5_TRACE_UPLOAD") != nullptr; if (traceUpload) { @@ -1115,6 +1117,7 @@ bool StorageTexture::Refresh() { if (changed[layer]) { pendingResults = true; if (blockUnits && droppable(layer)) { + CaptureTrace::Log("drop-unit image=%llx unit=%u generation=%llu stamped=%d keys=%d", static_cast(descriptor.baseAddress), layer, static_cast(layerGeneration[layer]), layer < stampedBlocks.size() && stampedBlocks[layer] != 0, static_cast(keys)); layerPending[layer] = false; dropped = true; continue; @@ -1167,6 +1170,7 @@ void traceKeyStore(const char* path, const GuestTextureResource& descriptor, std } void StorageTexture::upload(const std::vector* layers) { + CaptureTrace::Log("upload image=%llx bytes=%llu generation=%llu reason=%s partial=%d", static_cast(descriptor.baseAddress), static_cast(guestBytes), static_cast(generation), uploadReason, layers != nullptr); const bool profile = LookupOutcomes::Profiled(); const auto start = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; const auto elementBytes = BytesPerElement(descriptor.format); @@ -1812,6 +1816,7 @@ void StorageTexture::refreshGeneration() { } void StorageTexture::markLayersPending(std::uint32_t first, std::uint32_t count) { + CaptureTrace::Log("image-write image=%llx first=%u count=%u generation=%llu", static_cast(descriptor.baseAddress), first, count, static_cast(generation)); static const bool eager = std::getenv("APS5_EAGER_WRITEBACK") != nullptr || std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr; for (std::uint32_t layer = first; layer < first + count; ++layer) layerPending[layer] = true; // Results of this image now cover the alias's results borrowed into these units: this image @@ -2818,6 +2823,7 @@ void StorageTexture::writeBack(std::uint64_t address, std::size_t bytes) { } void StorageTexture::writeBackLayers(const std::vector& layers) { + CaptureTrace::Log("writeback image=%llx generation=%llu reason=%s units=%zu", static_cast(descriptor.baseAddress), static_cast(generation), flushReason, static_cast(std::count(layers.begin(), layers.end(), true))); static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; PhaseTimer timer; struct Account {