debug(agc): detect gpu input buffer changes between recording and execution

This commit is contained in:
boykopovar
2026-09-28 13:27:14 +03:00
parent 73e031a4dd
commit 76f1d48e60
7 changed files with 186 additions and 1 deletions
@@ -0,0 +1,95 @@
#pragma once
#include <array>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <mutex>
#include <stdexcept>
#include <string>
#include <thread>
namespace AgcDriver {
class CaptureTrace {
public:
static bool Enabled() {
static const bool enabled = std::getenv("APS5_CAPTURE_TRACE") != nullptr;
return enabled;
}
template<typename... TArgs>
static void Log(const char* format, TArgs... args) {
if (!Enabled()) return;
std::array<char, 2048> line{};
const auto size = std::snprintf(line.data(), line.size(), format, args...);
if (size < 0 || static_cast<std::size_t>(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<std::size_t>(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::microseconds>(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<std::streamsize>(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;
};
}
@@ -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<unsigned long long>(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<unsigned long long>(frameSerial), static_cast<unsigned long long>(submission.serial), cursor, static_cast<unsigned long long>(batchesAtFlip), static_cast<unsigned long long>(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<unsigned long long>(submission.serial), submission.queue, cursor, static_cast<unsigned long long>(color), readRegister(queue.context, 0x8e), static_cast<int>(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<unsigned long long>(color), readRegister(queue.context, 0x8e));
}
} catch (const std::exception& error) {
CaptureTrace::Log("draw-error submission=%llu offset=%zu reason=%.256s", static_cast<unsigned long long>(submission.serial), cursor, error.what());
skipped(error.what());
countSkip(Graphics::DrawSkip::Thrown);
}
@@ -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<unsigned long long>(residentPresents), static_cast<unsigned long long>(refreshedPresents), static_cast<unsigned long long>(notPending), static_cast<unsigned long long>(unsuitable), static_cast<unsigned long long>(gpuDumps));
}
CaptureTrace::Log("present dump=%d address=%llx width=%u height=%u resident=%d generation=%llu", dumpFrame ? state->nextDumpIndex : -1, static_cast<unsigned long long>(buffer.address), buffer.width, buffer.height, resident != nullptr, static_cast<unsigned long long>(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<unsigned long long>(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;
@@ -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<std::byte> expected;
VkBuffer source;
VkDeviceSize sourceOffset;
};
static unsigned long long nextDraw = 0;
const auto draw = ++nextDraw;
const auto batch = static_cast<unsigned long long>(recorder.Submissions() + 1);
std::vector<Sample> 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<std::size_t>(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<unsigned long long>(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<std::byte>(bytes), imported->buffer, begin - imported->base};
std::memcpy(sample.expected.data(), reinterpret_cast<const void*>(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<unsigned long long>(target), samples.size(), total);
if (samples.empty()) return;
auto readback = std::make_shared<Buffer>(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<PFN_vkCmdCopyBuffer>("vkCmdCopyBuffer");
for (const auto& sample : samples) {
const VkBufferCopy region{sample.sourceOffset, sample.offset, sample.expected.size()};
copy(commands, sample.source, readback->Handle(), 1, &region);
}
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<unsigned long long>(sample.address), index, std::to_integer<unsigned>(sample.expected[index]), std::to_integer<unsigned>(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<unsigned long long>(target), static_cast<unsigned long long>(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<const CompiledShader> 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;
@@ -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<void()> 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<unsigned long long>(submissions + 1), static_cast<unsigned long long>(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<unsigned long long>(submissions + 1), static_cast<unsigned long long>(address), bytes, static_cast<int>(kind));
if (bytes == 0 || !ReadTrackingEnabled()) return;
ensureOpen();
open->reads.push_back({address, address + bytes, kind});
@@ -2025,6 +2028,7 @@ void Recorder::NotePendingReads(std::span<const std::pair<std::uint64_t, std::ui
if (ranges.empty() || !ReadTrackingEnabled()) return;
ensureOpen();
for (const auto& [begin, end] : ranges) {
CaptureTrace::Log("buffer-read batch=%llu address=%llx bytes=%llu kind=%d", static_cast<unsigned long long>(submissions + 1), static_cast<unsigned long long>(begin), static_cast<unsigned long long>(end - begin), static_cast<int>(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<unsigned long long>(serial), batch->reads.size(), batch->writes.size());
VkTimelineSemaphoreSubmitInfoKHR timelineInfo{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO_KHR};
timelineInfo.signalSemaphoreValueCount = 1;
timelineInfo.pSignalSemaphoreValues = &serial;
@@ -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 <algorithm>
@@ -260,6 +261,7 @@ std::shared_ptr<StorageTexture> sampledStorageSource(const Context& context, con
// `guestBytes` is the surface size when the caller described the surface already (0: described here).
std::shared_ptr<Texture> cachedTexture(const Context& context, std::span<const std::uint32_t> 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<unsigned long long>(resource.baseAddress), resource.width, resource.height, static_cast<unsigned long long>(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{};
@@ -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<unsigned long long>(descriptor.baseAddress), static_cast<unsigned long long>(guestBytes), static_cast<unsigned long long>(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<unsigned long long>(descriptor.baseAddress), layer, static_cast<unsigned long long>(layerGeneration[layer]), layer < stampedBlocks.size() && stampedBlocks[layer] != 0, static_cast<int>(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<bool>* layers) {
CaptureTrace::Log("upload image=%llx bytes=%llu generation=%llu reason=%s partial=%d", static_cast<unsigned long long>(descriptor.baseAddress), static_cast<unsigned long long>(guestBytes), static_cast<unsigned long long>(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<unsigned long long>(descriptor.baseAddress), first, count, static_cast<unsigned long long>(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<bool>& layers) {
CaptureTrace::Log("writeback image=%llx generation=%llu reason=%s units=%zu", static_cast<unsigned long long>(descriptor.baseAddress), static_cast<unsigned long long>(generation), flushReason, static_cast<std::size_t>(std::count(layers.begin(), layers.end(), true)));
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
PhaseTimer timer;
struct Account {