From 9c4b4d701cf41430ee84577b599100c64f0c8c1d Mon Sep 17 00:00:00 2001 From: Nicolas Abosch <88494836+nicolasabosch@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:36:25 -0300 Subject: [PATCH 1/2] fix(agc): write profiling reports off GPU workers --- core/libs/prx/libSceAgcDriver/CMakeLists.txt | 14 ++ .../Execution/include/ProfileOutput.hpp | 145 ++++++++++++++++++ .../Dispatch/DispatchCacheStatistics.cpp | 9 +- .../src/Driver/Dispatch/DispatchTiming.cpp | 3 +- .../src/Driver/Packets/PacketFlush.cpp | 3 +- .../Execution/src/GuestMemory.cpp | 25 +-- .../Execution/src/VulkanDevice.cpp | 27 ++-- .../Graphics/src/BufferPool.cpp | 3 +- .../Graphics/src/GuestBufferMemory.cpp | 19 +-- .../libSceAgcDriver/Graphics/src/Recorder.cpp | 27 ++-- .../Graphics/src/ShaderResources.cpp | 15 +- .../libSceAgcDriver/tests/ProfileOutput.cpp | 121 +++++++++++++++ 12 files changed, 350 insertions(+), 61 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/ProfileOutput.cpp diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 90d971f7a..f0b6ceb8a 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -200,6 +200,20 @@ target_link_libraries(libSceAgcDriver PRIVATE set_target_properties(libSceAgcDriver PROPERTIES CXX_EXTENSIONS OFF) configure_windows_unwind(libSceAgcDriver) + +if(BUILD_TESTING) + add_test_executable(agc_profile_output_tests tests/ProfileOutput.cpp) + target_include_directories(agc_profile_output_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(agc_profile_output_tests PRIVATE libc) + configure_windows_unwind(agc_profile_output_tests) + add_test(NAME agc_profile_output COMMAND agc_profile_output_tests) + set_tests_properties(agc_profile_output PROPERTIES TIMEOUT 20) + if(WIN32) + set_tests_properties(agc_profile_output PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() + if(WIN32) set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/Execution/src/GuestMemory.cpp PROPERTIES COMPILE_DEFINITIONS _WIN32_WINNT=0x0602) endif() diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp new file mode 100644 index 000000000..9c714409e --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp @@ -0,0 +1,145 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver { + +class ProfileOutput { +public: + explicit ProfileOutput(std::function writer, std::size_t capacity = 4 * 1024 * 1024) : writer(std::move(writer)), capacity(capacity) { + if (!this->writer || capacity == 0) throw std::invalid_argument("invalid profile output writer or capacity"); + worker = std::thread([this] { run(); }); + } + + ~ProfileOutput() { + { + std::lock_guard lock(mutex); + stopping = true; + } + changed.notify_one(); + worker.join(); + } + + bool Write(std::string text) { + { + std::lock_guard lock(mutex); + if (failure) std::rethrow_exception(failure); + if (stopping) throw std::runtime_error("profile output is stopping"); + if (text.empty()) return true; + if (text.size() > capacity - bytes) { + ++dropped; + changed.notify_one(); + return false; + } + const auto size = text.size(); + pending.push_back(std::move(text)); + bytes += size; + } + changed.notify_one(); + return true; + } + + template + void Print(const char* format, TArgs... args) { + std::array local{}; + const auto size = std::snprintf(local.data(), local.size(), format, args...); + if (size < 0) throw std::runtime_error("profile output formatting failed"); + if (static_cast(size) < local.size()) { + Write(std::string(local.data(), size)); + } else if (static_cast(size) > capacity) { + std::lock_guard lock(mutex); + if (failure) std::rethrow_exception(failure); + ++dropped; + changed.notify_one(); + } else { + std::vector text(static_cast(size) + 1); + if (std::snprintf(text.data(), text.size(), format, args...) != size) throw std::runtime_error("profile output formatting changed"); + Write(std::string(text.data(), size)); + } + } + + void Flush() { + std::unique_lock lock(mutex); + idle.wait(lock, [&] { return failure || (pending.empty() && !writing && dropped == 0); }); + if (failure) std::rethrow_exception(failure); + } + +private: + void run() noexcept { + try { + for (;;) { + std::string batch; + std::size_t consumed = 0; + { + std::unique_lock lock(mutex); + changed.wait(lock, [&] { return stopping || !pending.empty() || dropped != 0; }); + if (stopping && pending.empty() && dropped == 0) return; + while (!pending.empty() && (batch.empty() || batch.size() + pending.front().size() <= 65536)) { + consumed += pending.front().size(); + batch += pending.front(); + pending.pop_front(); + } + if (dropped != 0) { + batch += "[profile-output] dropped " + std::to_string(dropped) + " chunks because the diagnostic writer fell behind\n"; + dropped = 0; + } + writing = true; + } + writer(batch); + { + std::lock_guard lock(mutex); + bytes -= consumed; + writing = false; + } + idle.notify_all(); + } + } catch (...) { + { + std::lock_guard lock(mutex); + failure = std::current_exception(); + writing = false; + } + idle.notify_all(); + } + } + + std::function writer; + const std::size_t capacity; + std::mutex mutex; + std::condition_variable changed; + std::condition_variable idle; + std::deque pending; + std::size_t bytes = 0; + std::size_t dropped = 0; + bool writing = false; + bool stopping = false; + std::exception_ptr failure; + std::thread worker; +}; + +inline ProfileOutput& ProfileOutput_nid_no_patch() { + static ProfileOutput output([](std::string_view text) { + if (std::fwrite(text.data(), 1, text.size(), stderr) != text.size() || std::fflush(stderr) != 0) + throw std::runtime_error("profile output write failed"); + }); + return output; +} + +template +void ProfilePrint_nid_no_patch(const char* format, TArgs... args) { + ProfileOutput_nid_no_patch().Print(format, args...); +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCacheStatistics.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCacheStatistics.cpp index d2fe53c1e..dae236316 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCacheStatistics.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchCacheStatistics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "Optimization/ResourceProgram.hpp" @@ -42,7 +43,7 @@ void Driver::classifyDiffering(std::uint64_t program, std::uint64_t key, const D void Driver::reportDispatchCache(EntryCounters& counters) { const auto count = [](std::uint64_t value) { return static_cast(value); }; const auto validated = counters.lookups - counters.absent; - std::fprintf(stderr, "[dispatch-cache] %llu lookups (10 s): %llu no entry, %llu validated by value in %.1f us each: %llu equal, %llu differing, %llu page not mapped, %llu queued label, %llu image being stored, %llu publish generation moved, %llu pending serial moved, %llu forget serial moved (%llu pending images stored first, %llu pending runs synced first, %llu equal entries inserted before a forget; gate retried %llu: %llu equal, %llu moved again); runs per entry %.1f validated / %.1f inserted; %llu misses found the entry replaced meanwhile; %llu inserts (%llu captures not kept: unstable), %llu evictions in total, %zu entries, %llu LRU moves\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast(validated) : 0.0, count(counters.equal), count(counters.differing), count(counters.inaccessible), count(counters.queuedLabel), count(counters.flushingImage), count(counters.publishMoved), count(counters.pendingMoved), count(counters.forgetMoved), count(counters.imagesFlushed), count(counters.runsSynced), count(counters.forgetSinceInsert), count(counters.retriesEqual + counters.retriesMoved), count(counters.retriesEqual), count(counters.retriesMoved), validated != 0 ? static_cast(counters.runsValidated) / static_cast(validated) : 0.0, counters.inserts != 0 ? static_cast(counters.runsInserted) / static_cast(counters.inserts) : 0.0, count(counters.replaced), count(counters.inserts), count(counters.unstable), count(dispatchCacheEvictions), dispatchCache.size(), count(counters.touches)); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch-cache] %llu lookups (10 s): %llu no entry, %llu validated by value in %.1f us each: %llu equal, %llu differing, %llu page not mapped, %llu queued label, %llu image being stored, %llu publish generation moved, %llu pending serial moved, %llu forget serial moved (%llu pending images stored first, %llu pending runs synced first, %llu equal entries inserted before a forget; gate retried %llu: %llu equal, %llu moved again); runs per entry %.1f validated / %.1f inserted; %llu misses found the entry replaced meanwhile; %llu inserts (%llu captures not kept: unstable), %llu evictions in total, %zu entries, %llu LRU moves\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast(validated) : 0.0, count(counters.equal), count(counters.differing), count(counters.inaccessible), count(counters.queuedLabel), count(counters.flushingImage), count(counters.publishMoved), count(counters.pendingMoved), count(counters.forgetMoved), count(counters.imagesFlushed), count(counters.runsSynced), count(counters.forgetSinceInsert), count(counters.retriesEqual + counters.retriesMoved), count(counters.retriesEqual), count(counters.retriesMoved), validated != 0 ? static_cast(counters.runsValidated) / static_cast(validated) : 0.0, counters.inserts != 0 ? static_cast(counters.runsInserted) / static_cast(counters.inserts) : 0.0, count(counters.replaced), count(counters.inserts), count(counters.unstable), count(dispatchCacheEvictions), dispatchCache.size(), count(counters.touches)); std::vector> programs(counters.differingByProgram.begin(), counters.differingByProgram.end()); std::sort(programs.begin(), programs.end(), [](const auto& a, const auto& b) { return a.second > b.second; }); std::string top; @@ -51,21 +52,21 @@ void Driver::reportDispatchCache(EntryCounters& counters) { std::snprintf(text, sizeof(text), " 0x%llx x%llu", static_cast(programs[i].first), count(programs[i].second)); top += text; } - std::fprintf(stderr, "[dispatch-cache] differing by class (10 s, %llu classified): address-only %llu, data-only %llu, walk %llu, mixed %llu (runs changed %llu); matched one of the last 3 value sets %llu; differing words %llu in total (misses with 1 / 2-4 / 5-16 / >16 words: %llu / %llu / %llu / %llu), %zu distinct positions (first %zu, last %zu); top programs by differing:%s\n", count(counters.differingClassified), count(counters.differingAddress), count(counters.differingData), count(counters.differingWalk), count(counters.differingMixed), count(counters.differingRunsChanged), count(counters.differingMatchedPrior), count(counters.differingWords), count(counters.differingWordBuckets[0]), count(counters.differingWordBuckets[1]), count(counters.differingWordBuckets[2]), count(counters.differingWordBuckets[3]), counters.differingPositions.size(), counters.differingPositions.empty() ? std::size_t{0} : counters.differingFirstPosition, counters.differingLastPosition, top.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch-cache] differing by class (10 s, %llu classified): address-only %llu, data-only %llu, walk %llu, mixed %llu (runs changed %llu); matched one of the last 3 value sets %llu; differing words %llu in total (misses with 1 / 2-4 / 5-16 / >16 words: %llu / %llu / %llu / %llu), %zu distinct positions (first %zu, last %zu); top programs by differing:%s\n", count(counters.differingClassified), count(counters.differingAddress), count(counters.differingData), count(counters.differingWalk), count(counters.differingMixed), count(counters.differingRunsChanged), count(counters.differingMatchedPrior), count(counters.differingWords), count(counters.differingWordBuckets[0]), count(counters.differingWordBuckets[1]), count(counters.differingWordBuckets[2]), count(counters.differingWordBuckets[3]), counters.differingPositions.size(), counters.differingPositions.empty() ? std::size_t{0} : counters.differingFirstPosition, counters.differingLastPosition, top.c_str()); std::string ranks; for (std::size_t rank = 0; rank < dispatchVariants(); ++rank) { char text[32]; std::snprintf(text, sizeof(text), "%s%llu", rank == 0 ? "" : " / ", count(counters.variantHitsByRank[rank])); ranks += text; } - std::fprintf(stderr, "[dispatch-cache] variants (10 s, k = %zu): hits by rank 1..k %s; %.2f variants compared per validation; %llu inserted into an entry, %llu evicted beyond k; %.2f variants per entry (%llu over %zu entries, ~%.1f MiB)\n", dispatchVariants(), ranks.c_str(), validated != 0 ? static_cast(counters.variantsCompared) / static_cast(validated) : 0.0, count(counters.variantsInserted), count(counters.variantsEvicted), dispatchCache.empty() ? 0.0 : static_cast(dispatchCacheVariants) / static_cast(dispatchCache.size()), count(dispatchCacheVariants), dispatchCache.size(), static_cast(dispatchCacheVariantBytes) / (1024.0 * 1024.0)); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch-cache] variants (10 s, k = %zu): hits by rank 1..k %s; %.2f variants compared per validation; %llu inserted into an entry, %llu evicted beyond k; %.2f variants per entry (%llu over %zu entries, ~%.1f MiB)\n", dispatchVariants(), ranks.c_str(), validated != 0 ? static_cast(counters.variantsCompared) / static_cast(validated) : 0.0, count(counters.variantsInserted), count(counters.variantsEvicted), dispatchCache.empty() ? 0.0 : static_cast(dispatchCacheVariants) / static_cast(dispatchCache.size()), count(dispatchCacheVariants), dispatchCache.size(), static_cast(dispatchCacheVariantBytes) / (1024.0 * 1024.0)); std::string dataRanks; for (std::size_t rank = 0; rank < dispatchVariants(); ++rank) { char text[32]; std::snprintf(text, sizeof(text), "%s%llu", rank == 0 ? "" : " / ", count(counters.dataHitsByRank[rank])); dataRanks += text; } - std::fprintf(stderr, "[dispatch-cache] data hits (10 s): %llu (%llu words refreshed; by rank 1..k %s; %llu data variants missed on pending runs), verified %llu; inserts with data positions %llu of %llu (%.1f positions each), leaves skipped: unmapped %llu, mismatched %llu, aliased %llu\n", count(counters.dataHits), count(counters.dataWordsRefreshed), dataRanks.c_str(), count(dataPendingMisses.exchange(0, std::memory_order_relaxed)), count(counters.dataVerified), count(counters.dataInserts), count(counters.inserts), counters.dataInserts != 0 ? static_cast(counters.dataPositionsInserted) / static_cast(counters.dataInserts) : 0.0, count(counters.dataLeavesUnmapped), count(counters.dataLeavesMismatched), count(counters.dataLeavesAliased)); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch-cache] data hits (10 s): %llu (%llu words refreshed; by rank 1..k %s; %llu data variants missed on pending runs), verified %llu; inserts with data positions %llu of %llu (%.1f positions each), leaves skipped: unmapped %llu, mismatched %llu, aliased %llu\n", count(counters.dataHits), count(counters.dataWordsRefreshed), dataRanks.c_str(), count(dataPendingMisses.exchange(0, std::memory_order_relaxed)), count(counters.dataVerified), count(counters.dataInserts), count(counters.inserts), counters.dataInserts != 0 ? static_cast(counters.dataPositionsInserted) / static_cast(counters.dataInserts) : 0.0, count(counters.dataLeavesUnmapped), count(counters.dataLeavesMismatched), count(counters.dataLeavesAliased)); counters = EntryCounters{}; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchTiming.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchTiming.cpp index ecfdfb711..b887acd81 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchTiming.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchTiming.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Dispatch/DispatchTiming.hpp" @@ -25,7 +26,7 @@ void Driver::addDriverPhases(DispatchClass which, const std::array(line.validations) : 0.0; - std::fprintf(stderr, "[dispatch] driver phases %s (10 s, %llu dispatches, %llu cache hits), us per dispatch:%s, total %.1f (%.1f ms); validate %.1f us per validation (%llu validations; GPU waits inside it %.1f us per validation apart)\n", DispatchClassNames[cls], static_cast(line.dispatches), static_cast(line.hits), report.c_str(), total * 1000 / static_cast(line.dispatches), total, line.ms[PhaseValidate] * perValidation, static_cast(line.validations), line.ms[PhaseValidateWait] * perValidation); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch] driver phases %s (10 s, %llu dispatches, %llu cache hits), us per dispatch:%s, total %.1f (%.1f ms); validate %.1f us per validation (%llu validations; GPU waits inside it %.1f us per validation apart)\n", DispatchClassNames[cls], static_cast(line.dispatches), static_cast(line.hits), report.c_str(), total * 1000 / static_cast(line.dispatches), total, line.ms[PhaseValidate] * perValidation, static_cast(line.validations), line.ms[PhaseValidateWait] * perValidation); line = {}; } } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp index 0729d6a79..33863d1b2 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketFlush.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/SynchronizationStatistics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/DeferredLabels.hpp" @@ -98,7 +99,7 @@ void Driver::flushBetweenPackets(std::uint32_t queue, std::uint32_t header, bool lastReport = reportNow; const auto stores = Graphics::Recorder::StoreCounts(); const auto failed = [](TrySite site) { return static_cast(triesFailed[site].load()); }; - std::fprintf(stderr, "[labels] batch flushes between packets: %llu at the next packet, %llu by deadline, %llu by size cap (%llu well overdue, waited for the mutex); %llu boundary reaps; record tries skipped (self-locking next) %llu; failed tries: label %llu, flush %llu, reap %llu, poll %llu, idle %llu, capture %llu, poll-record %llu; at the packet's own lock: %llu label groups (%.0f ms), %llu submits (%.0f ms incl. queue 0's reaps), left to it by a failed try: %llu groups, %llu submits; after a capture: %llu groups recorded by a try, %llu packets redone for a queued label over the capture; %llu suspend points; stores: %llu in %llu runs (%llu joined, %llu replaced, %llu WAW barriers, %llu joins refused; %llu runs recorded at submit, %llu in place before a writer or reader); DCC key stores: %llu queued in %llu runs (%llu before a writer, %llu joined a queued range); queued labels: %llu noted (%llu over a recorded entry), %llu same-queue wait hits, %llu groups recorded from a poll loop, %llu from the flush hook (%llu hook accesses, %llu inside a completion skipped)\n", static_cast(packetFlushes.load()), static_cast(deadlineFlushes.load()), static_cast(capFlushes.load()), static_cast(overdueLocks.load()), static_cast(boundaryReaps.load()), static_cast(recordTriesSkipped.load()), failed(TryLabel), failed(TryFlush), failed(TryReap), failed(TryPoll), failed(TryIdle), failed(TryCapture), failed(TryPollRecord), static_cast(packetLockRecords.load()), packetLockRecordUs.load() / 1000.0, static_cast(packetLockSubmits.load()), packetLockSubmitUs.load() / 1000.0, static_cast(packetLockDeferred.load()), static_cast(packetSubmitDeferred.load()), static_cast(captureTryRecords.load()), static_cast(captureRetries.load()), static_cast(suspendPoints.load()), static_cast(stores.stores), static_cast(stores.runs), static_cast(stores.joined), static_cast(stores.replaced), static_cast(stores.wawBarriers), static_cast(stores.joinsRefused), static_cast(stores.runsAtSubmit), static_cast(stores.runsForced), static_cast(stores.keyStores), static_cast(stores.keyStoreRuns), static_cast(stores.keyStoreRunsForWriter), static_cast(stores.keyStoresJoined), static_cast(stores.queuedNoted), static_cast(stores.queuedOverRecorded), static_cast(stores.queuedHits), static_cast(pollLabelRecords.load()), static_cast(hookLabelRecords.load()), static_cast(stores.queuedHookRecords), static_cast(stores.queuedHookInCompletion)); + AgcDriver::ProfilePrint_nid_no_patch("[labels] batch flushes between packets: %llu at the next packet, %llu by deadline, %llu by size cap (%llu well overdue, waited for the mutex); %llu boundary reaps; record tries skipped (self-locking next) %llu; failed tries: label %llu, flush %llu, reap %llu, poll %llu, idle %llu, capture %llu, poll-record %llu; at the packet's own lock: %llu label groups (%.0f ms), %llu submits (%.0f ms incl. queue 0's reaps), left to it by a failed try: %llu groups, %llu submits; after a capture: %llu groups recorded by a try, %llu packets redone for a queued label over the capture; %llu suspend points; stores: %llu in %llu runs (%llu joined, %llu replaced, %llu WAW barriers, %llu joins refused; %llu runs recorded at submit, %llu in place before a writer or reader); DCC key stores: %llu queued in %llu runs (%llu before a writer, %llu joined a queued range); queued labels: %llu noted (%llu over a recorded entry), %llu same-queue wait hits, %llu groups recorded from a poll loop, %llu from the flush hook (%llu hook accesses, %llu inside a completion skipped)\n", static_cast(packetFlushes.load()), static_cast(deadlineFlushes.load()), static_cast(capFlushes.load()), static_cast(overdueLocks.load()), static_cast(boundaryReaps.load()), static_cast(recordTriesSkipped.load()), failed(TryLabel), failed(TryFlush), failed(TryReap), failed(TryPoll), failed(TryIdle), failed(TryCapture), failed(TryPollRecord), static_cast(packetLockRecords.load()), packetLockRecordUs.load() / 1000.0, static_cast(packetLockSubmits.load()), packetLockSubmitUs.load() / 1000.0, static_cast(packetLockDeferred.load()), static_cast(packetSubmitDeferred.load()), static_cast(captureTryRecords.load()), static_cast(captureRetries.load()), static_cast(suspendPoints.load()), static_cast(stores.stores), static_cast(stores.runs), static_cast(stores.joined), static_cast(stores.replaced), static_cast(stores.wawBarriers), static_cast(stores.joinsRefused), static_cast(stores.runsAtSubmit), static_cast(stores.runsForced), static_cast(stores.keyStores), static_cast(stores.keyStoreRuns), static_cast(stores.keyStoreRunsForWriter), static_cast(stores.keyStoresJoined), static_cast(stores.queuedNoted), static_cast(stores.queuedOverRecorded), static_cast(stores.queuedHits), static_cast(pollLabelRecords.load()), static_cast(hookLabelRecords.load()), static_cast(stores.queuedHookRecords), static_cast(stores.queuedHookInCompletion)); } } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp index 291369842..8bea6b6a1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "ThreadOwned.hpp" #include "prx/libc/include/GuestAllocations.hpp" @@ -292,30 +293,30 @@ public: auto last = state.lastReport.load(); if (nowMs - last < 10000 || !state.lastReport.compare_exchange_strong(last, nowMs)) return; const auto totals = FoldMemoryCounters(); - std::fprintf(stderr, "[guestmem]"); + AgcDriver::ProfilePrint_nid_no_patch("[guestmem]"); for (std::size_t i = 0; i < MemoryCounterCount; ++i) { - std::fprintf(stderr, " %s %llu calls %.0f MiB %.1f s", MemoryCounterNames[i], static_cast(totals[i][0]), totals[i][1] / 1048576.0, totals[i][2] / 1e9); + AgcDriver::ProfilePrint_nid_no_patch(" %s %llu calls %.0f MiB %.1f s", MemoryCounterNames[i], static_cast(totals[i][0]), totals[i][1] / 1048576.0, totals[i][2] / 1e9); } - std::fprintf(stderr, " collect-memo hits %llu, collect epochs %llu", static_cast(collectMemoHits.load()), static_cast(collectEpochBumps.load())); - std::fprintf(stderr, " collect-dirty %llu tracker waits %llu / %llu", static_cast(collectDirty.load()), static_cast(trackerWaits.load()), static_cast(trackerAcquisitions.load())); - std::fprintf(stderr, " | arena 0x%llx+0x%llx image 0x%llx+0x%llx forgets %llu (%.0f MiB)", static_cast(PagesBase()), static_cast(PagesSize()), static_cast(ImagePagesBase()), static_cast(ImagePagesSize()), static_cast(forgetCalls.load()), forgetBytes.load() / 1048576.0); + AgcDriver::ProfilePrint_nid_no_patch(" collect-memo hits %llu, collect epochs %llu", static_cast(collectMemoHits.load()), static_cast(collectEpochBumps.load())); + AgcDriver::ProfilePrint_nid_no_patch(" collect-dirty %llu tracker waits %llu / %llu", static_cast(collectDirty.load()), static_cast(trackerWaits.load()), static_cast(trackerAcquisitions.load())); + AgcDriver::ProfilePrint_nid_no_patch(" | arena 0x%llx+0x%llx image 0x%llx+0x%llx forgets %llu (%.0f MiB)", static_cast(PagesBase()), static_cast(PagesSize()), static_cast(ImagePagesBase()), static_cast(ImagePagesSize()), static_cast(forgetCalls.load()), forgetBytes.load() / 1048576.0); { std::lock_guard lock(state.callersMutex); - std::fprintf(stderr, " | read callers:"); + AgcDriver::ProfilePrint_nid_no_patch(" | read callers:"); for (const auto& [caller, count] : state.callers) { - if (count != 0) std::fprintf(stderr, " +0x%llx=%llu", caller, static_cast(count)); + if (count != 0) AgcDriver::ProfilePrint_nid_no_patch(" +0x%llx=%llu", caller, static_cast(count)); } - std::fprintf(stderr, " | write callers:"); + AgcDriver::ProfilePrint_nid_no_patch(" | write callers:"); for (const auto& [caller, count] : state.writeCallers) { - if (count != 0) std::fprintf(stderr, " +0x%llx=%llu", caller, static_cast(count)); + if (count != 0) AgcDriver::ProfilePrint_nid_no_patch(" +0x%llx=%llu", caller, static_cast(count)); } } - std::fprintf(stderr, " | read sites:"); + AgcDriver::ProfilePrint_nid_no_patch(" | read sites:"); for (std::size_t site = 0; site < static_cast(ReadSite::Count); ++site) { const auto count = readSiteSamples[site].load(std::memory_order_relaxed); - if (count != 0) std::fprintf(stderr, " %s=%llu", ReadSiteName(static_cast(site)), static_cast(count)); + if (count != 0) AgcDriver::ProfilePrint_nid_no_patch(" %s=%llu", ReadSiteName(static_cast(site)), static_cast(count)); } - std::fprintf(stderr, "\n"); + AgcDriver::ProfilePrint_nid_no_patch("\n"); } private: MemoryCounterKind kind; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 5f2479057..5cadb337f 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/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "BdaAbi.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" @@ -1327,7 +1328,7 @@ bool VulkanDevice::FillBuffer(std::uint64_t address, std::size_t bytes, std::spa const auto now = std::chrono::steady_clock::now(); if (now - lastReport > std::chrono::seconds(10)) { lastReport = now; - std::fprintf(stderr, "[fill-sync] fills: %llu synced (%llu with a completion label pending) waited %.0f ms, %llu ordered by barrier, %llu with no pending write; phases ms: decide %.0f record %.0f notes %.0f; %llu uniform, %llu pattern (%llu doubling steps in place; pattern buffers reused %llu, made %llu)\n", static_cast(synced), static_cast(labelSynced), syncedMs, static_cast(ordered), static_cast(fills - synced - ordered), decideMs, recordMs, notesMs, static_cast(uniformFills), static_cast(patternFills), static_cast(doublingSteps), static_cast(patternBuffersReused), static_cast(patternBuffersMade)); + AgcDriver::ProfilePrint_nid_no_patch("[fill-sync] fills: %llu synced (%llu with a completion label pending) waited %.0f ms, %llu ordered by barrier, %llu with no pending write; phases ms: decide %.0f record %.0f notes %.0f; %llu uniform, %llu pattern (%llu doubling steps in place; pattern buffers reused %llu, made %llu)\n", static_cast(synced), static_cast(labelSynced), syncedMs, static_cast(ordered), static_cast(fills - synced - ordered), decideMs, recordMs, notesMs, static_cast(uniformFills), static_cast(patternFills), static_cast(doublingSteps), static_cast(patternBuffersReused), static_cast(patternBuffersMade)); } } auto phaseStart = fillStart; @@ -1958,7 +1959,7 @@ bool VulkanDevice::PresentDisplayBuffer(const DisplayBuffer& buffer) { } if (profile && std::chrono::steady_clock::now() - lastReport > std::chrono::seconds(10)) { 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)); + AgcDriver::ProfilePrint_nid_no_patch("[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)); VkClearColorValue uniform{}; @@ -2685,7 +2686,7 @@ void reportRecipes() { const auto precheckUs = perHit(counters.precheckNs); const auto proofUs = perHit(counters.proofNs); const auto recordUs = perHit(counters.recordNs); - std::fprintf(stderr, "[recipe] %s (10 s): hits %llu; pre-check misses: %s; proofs: %s; rebuilds: %s; presyncs from the recipe %llu (recomputed %llu, waited %llu); data refreshes recorded %llu / skipped by hash %llu (%llu decided by words: data hits); restarts %llu, attaches %llu; us per hit: pre-check %.1f, proof %.1f, record %.1f; verified %llu (object replaced %llu)\n", kind == 0 ? "dispatch" : kind == 1 ? "indirect" : "draw", hits, misses.c_str(), proofs.c_str(), rebuilds.c_str(), take(counters.presyncsFromRecipe), take(counters.presyncsRecomputed), take(counters.presyncWaits), take(counters.dataRefreshed), take(counters.dataSkipped), take(counters.refreshByWords), take(counters.restarts), take(counters.attaches), precheckUs, proofUs, recordUs, take(counters.verified), take(counters.verifyReplaced)); + AgcDriver::ProfilePrint_nid_no_patch("[recipe] %s (10 s): hits %llu; pre-check misses: %s; proofs: %s; rebuilds: %s; presyncs from the recipe %llu (recomputed %llu, waited %llu); data refreshes recorded %llu / skipped by hash %llu (%llu decided by words: data hits); restarts %llu, attaches %llu; us per hit: pre-check %.1f, proof %.1f, record %.1f; verified %llu (object replaced %llu)\n", kind == 0 ? "dispatch" : kind == 1 ? "indirect" : "draw", hits, misses.c_str(), proofs.c_str(), rebuilds.c_str(), take(counters.presyncsFromRecipe), take(counters.presyncsRecomputed), take(counters.presyncWaits), take(counters.dataRefreshed), take(counters.dataSkipped), take(counters.refreshByWords), take(counters.restarts), take(counters.attaches), precheckUs, proofUs, recordUs, take(counters.verified), take(counters.verifyReplaced)); } } @@ -2715,7 +2716,7 @@ struct DispatchTimer { add(which, ms); phaseStart = now; // Slow phases are reported as they finish, so a dispatch that never completes shows where it is. - if (ms > 1000) std::fprintf(stderr, "[dispatch] %s took %.0f ms (%zu words, program 0x%llx)\n", DispatchRowName(which), ms, spirvWords, static_cast(programAddress)); + if (ms > 1000) AgcDriver::ProfilePrint_nid_no_patch("[dispatch] %s took %.0f ms (%zu words, program 0x%llx)\n", DispatchRowName(which), ms, spirvWords, static_cast(programAddress)); } void restart() { phaseStart = std::chrono::steady_clock::now(); } // The call's phases as text, only when wanted: a slow call, or a new [indirect] maximum. @@ -2738,7 +2739,7 @@ struct DispatchTimer { for (std::size_t row = 0; row < DispatchPhaseCount; ++row) { if (d.phaseTotals[row] != 0) report += " " + std::string(DispatchRowName(row)) + "=" + std::to_string(static_cast(d.phaseTotals[row] / 1000)) + "s"; } - std::fprintf(stderr, "[dispatch] %llu dispatches, phase totals:%s\n", static_cast(d.profiledDispatches), report.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("[dispatch] %llu dispatches, phase totals:%s\n", static_cast(d.profiledDispatches), report.c_str()); } // The call's end: the proc lookups it made, the slow-call report, the [indirect] hold // accounting (`indirectHold`: the call was an indirect dispatch, CPU-resolved or not) and line. @@ -2748,7 +2749,7 @@ struct DispatchTimer { d.procLookups += Graphics::DeviceProcLookups() - lookupsBefore; const auto now = std::chrono::steady_clock::now(); const auto totalMs = std::chrono::duration(now - start).count(); - if (totalMs > 100) std::fprintf(stderr, "[dispatch] %s %zu words:%s\n", groupsText, spirvWords, formatCall().c_str()); + if (totalMs > 100) AgcDriver::ProfilePrint_nid_no_patch("[dispatch] %s %zu words:%s\n", groupsText, spirvWords, formatCall().c_str()); if (!indirectHold) return; auto& hold = d.indirectHold; ++hold.count; @@ -2767,7 +2768,7 @@ struct DispatchTimer { else std::snprintf(text, sizeof(text), " %s %.0f ms", DispatchRowName(i), hold.phaseMs[i]); report += text; } - std::fprintf(stderr, "[indirect] %llu indirect dispatches spent %.0f ms inside the device call (10 s; max %.1f ms:%s), by phase (the 'resources: ...' rows split 'resources'; 'hook waits' overlaps them; 'images: ...' rows are the lookups by outcome, count x ms, inside 'B images'):%s; copied-writer lists scanned per decision: dispatch avg %.1f (max %zu), draw avg %.1f\n", static_cast(hold.count), hold.totalMs, hold.maxMs, hold.maxPhases.c_str(), report.c_str(), hold.count != 0 ? static_cast(hold.writersScanned) / hold.count : 0.0, hold.maxWriters, hold.count != 0 ? static_cast(hold.drawWritersScanned) / hold.count : 0.0); + AgcDriver::ProfilePrint_nid_no_patch("[indirect] %llu indirect dispatches spent %.0f ms inside the device call (10 s; max %.1f ms:%s), by phase (the 'resources: ...' rows split 'resources'; 'hook waits' overlaps them; 'images: ...' rows are the lookups by outcome, count x ms, inside 'B images'):%s; copied-writer lists scanned per decision: dispatch avg %.1f (max %zu), draw avg %.1f\n", static_cast(hold.count), hold.totalMs, hold.maxMs, hold.maxPhases.c_str(), report.c_str(), hold.count != 0 ? static_cast(hold.writersScanned) / hold.count : 0.0, hold.maxWriters, hold.count != 0 ? static_cast(hold.drawWritersScanned) / hold.count : 0.0); hold.phaseMs = {}; hold.phaseCounts = {}; hold.count = 0; @@ -2902,7 +2903,7 @@ std::uint64_t VulkanDevice::presync(std::span(std::chrono::steady_clock::now().time_since_epoch()).count(); auto last = counters.lastReport.load(); - if (nowMs - last >= 10000 && counters.lastReport.compare_exchange_strong(last, nowMs)) std::fprintf(stderr, "[presync] %llu dispatches checked, %llu pre-syncs waited %.0f ms (cumulative)\n", static_cast(counters.checked.load()), static_cast(counters.presyncs.load()), counters.waitedUs.load() / 1000.0); + if (nowMs - last >= 10000 && counters.lastReport.compare_exchange_strong(last, nowMs)) AgcDriver::ProfilePrint_nid_no_patch("[presync] %llu dispatches checked, %llu pre-syncs waited %.0f ms (cumulative)\n", static_cast(counters.checked.load()), static_cast(counters.presyncs.load()), counters.waitedUs.load() / 1000.0); } return serial; } @@ -3361,8 +3362,8 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec } if (profile && std::chrono::steady_clock::now() - d.cacheReport > std::chrono::seconds(10)) { d.cacheReport = std::chrono::steady_clock::now(); - std::fprintf(stderr, "[rescache] %llu hits, %llu misses, %llu invalidated, %zu entries (dispatch + draw); template hits: %llu refreshed the data buffers (revalidate %.1f ms), %llu had the same words; Find calls %llu, Touch calls %llu\n", static_cast(d.cacheHits), static_cast(d.cacheMisses), static_cast(d.cacheInvalidated), state->resourceCache.Size(), static_cast(d.templateRefreshed), d.templateRevalidateMs, static_cast(d.templateSameWords), static_cast(ResourceCache::Finds()), static_cast(ResourceCache::Touches())); - std::fprintf(stderr, "[vk] deviceProc lookups inside the device call: %llu (%.2f per dispatch); pre-dispatch barriers recorded %llu, skipped %llu\n", static_cast(d.procLookups), d.profiledDispatches != 0 ? static_cast(d.procLookups) / static_cast(d.profiledDispatches) : 0.0, static_cast(d.preBarriersRecorded), static_cast(d.preBarriersSkipped)); + AgcDriver::ProfilePrint_nid_no_patch("[rescache] %llu hits, %llu misses, %llu invalidated, %zu entries (dispatch + draw); template hits: %llu refreshed the data buffers (revalidate %.1f ms), %llu had the same words; Find calls %llu, Touch calls %llu\n", static_cast(d.cacheHits), static_cast(d.cacheMisses), static_cast(d.cacheInvalidated), state->resourceCache.Size(), static_cast(d.templateRefreshed), d.templateRevalidateMs, static_cast(d.templateSameWords), static_cast(ResourceCache::Finds()), static_cast(ResourceCache::Touches())); + AgcDriver::ProfilePrint_nid_no_patch("[vk] deviceProc lookups inside the device call: %llu (%.2f per dispatch); pre-dispatch barriers recorded %llu, skipped %llu\n", static_cast(d.procLookups), d.profiledDispatches != 0 ? static_cast(d.procLookups) / static_cast(d.profiledDispatches) : 0.0, static_cast(d.preBarriersRecorded), static_cast(d.preBarriersSkipped)); reportRecipes(); } timing.Mark("shader_resources"); @@ -3449,9 +3450,9 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec lastReport = now; std::vector> hot(byProgram.begin(), byProgram.end()); std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return a.second.ms > b.second.ms; }); - std::fprintf(stderr, "[address-sync] %llu address-based dispatch syncs waited %.1f s in total; by program (10 s):", static_cast(syncs), waitedMs / 1000); - for (std::size_t i = 0; i < hot.size() && i < 8; ++i) std::fprintf(stderr, " 0x%llx x%llu %.0fms", static_cast(hot[i].first), static_cast(hot[i].second.count), hot[i].second.ms); - std::fprintf(stderr, "\n"); + AgcDriver::ProfilePrint_nid_no_patch("[address-sync] %llu address-based dispatch syncs waited %.1f s in total; by program (10 s):", static_cast(syncs), waitedMs / 1000); + for (std::size_t i = 0; i < hot.size() && i < 8; ++i) AgcDriver::ProfilePrint_nid_no_patch(" 0x%llx x%llu %.0fms", static_cast(hot[i].first), static_cast(hot[i].second.count), hot[i].second.ms); + AgcDriver::ProfilePrint_nid_no_patch("\n"); byProgram.clear(); } } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp index cdd541e0f..bdee4b50f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Graphics/include/BufferPool.hpp" #include #include @@ -68,7 +69,7 @@ std::optional BufferPool::Take(std::size_t bytes, VkBufferUsag const auto now = std::chrono::steady_clock::now(); if (now - lastReport > std::chrono::seconds(10)) { lastReport = now; - std::fprintf(stderr, "[bufferpool] small: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB); large: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB)%s; device: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB of %llu)\n", static_cast(smallTier.hits), static_cast(smallTier.misses), static_cast(smallTier.evictions), smallTier.slots, smallTier.retainedBytes / 1048576.0, static_cast(largeTier.hits), static_cast(largeTier.misses), static_cast(largeTier.evictions), largeTier.slots, largeTier.retainedBytes / 1048576.0, sharedTiers() ? " (shared)" : "", static_cast(deviceTier.hits), static_cast(deviceTier.misses), static_cast(deviceTier.evictions), deviceTier.slots, deviceTier.retainedBytes / 1048576.0, static_cast(deviceTier.budget >> 20u)); + AgcDriver::ProfilePrint_nid_no_patch("[bufferpool] small: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB); large: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB)%s; device: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB of %llu)\n", static_cast(smallTier.hits), static_cast(smallTier.misses), static_cast(smallTier.evictions), smallTier.slots, smallTier.retainedBytes / 1048576.0, static_cast(largeTier.hits), static_cast(largeTier.misses), static_cast(largeTier.evictions), largeTier.slots, largeTier.retainedBytes / 1048576.0, sharedTiers() ? " (shared)" : "", static_cast(deviceTier.hits), static_cast(deviceTier.misses), static_cast(deviceTier.evictions), deviceTier.slots, deviceTier.retainedBytes / 1048576.0, static_cast(deviceTier.budget >> 20u)); } } auto& tier = tierFor(capacity, properties); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index a8d9ed9ca..bb16630cc 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "ThreadOwned.hpp" #include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" @@ -818,7 +819,7 @@ void reportMirrors() { } heapBytes = state.heapBytes; } - std::fprintf(stderr, "[buffers] image mirrors: %zu ranges (%.1f MiB, %zu writable, %zu heap %.1f MiB), %llu address-based builds served, %llu descriptor sub-ranges bound, %llu rebuilds, %llu refreshes: %llu blocks compared, %llu copied, %llu refresh syncs; heap refills %llu, unwatched heaps %llu\n", count, bytes / 1048576.0, writable, heaps, heapBytes / 1048576.0, static_cast(state.builds), static_cast(state.subranges), static_cast(state.rebuilds), static_cast(state.refreshes), static_cast(state.blocksCompared), static_cast(state.blocksCopied), static_cast(state.syncs), static_cast(state.heapRefills), static_cast(state.heapUnwatched)); + AgcDriver::ProfilePrint_nid_no_patch("[buffers] image mirrors: %zu ranges (%.1f MiB, %zu writable, %zu heap %.1f MiB), %llu address-based builds served, %llu descriptor sub-ranges bound, %llu rebuilds, %llu refreshes: %llu blocks compared, %llu copied, %llu refresh syncs; heap refills %llu, unwatched heaps %llu\n", count, bytes / 1048576.0, writable, heaps, heapBytes / 1048576.0, static_cast(state.builds), static_cast(state.subranges), static_cast(state.rebuilds), static_cast(state.refreshes), static_cast(state.blocksCompared), static_cast(state.blocksCopied), static_cast(state.syncs), static_cast(state.heapRefills), static_cast(state.heapUnwatched)); } // Deferred lease release. The lease an address-based build takes (AcquireRegistered) is dropped by its @@ -962,7 +963,7 @@ void CountLeaseOutcome(bool synced, std::uint64_t batchSerial) { const auto& stats = state.stats; const auto table = BdaResources::TableCacheCounters(); const auto& snapshots = Snapshots(); - std::fprintf(stderr, "[address-sync] leases: %llu released at completion, %llu synced at once; %llu pin-contention waits by guest threads (%llu finished the lease batch, %llu drained the recorder, %llu cache-only drops) %.1f s; BDA table cache %llu hits / %llu misses (%zu tables held); snapshot compares: %llu skipped (live-backed region), %llu made\n", static_cast(stats.deferred), static_cast(stats.synced), static_cast(stats.contentionWaits), static_cast(stats.contentionSyncs), static_cast(stats.contentionDrains), static_cast(stats.cacheDrops), stats.contentionMs / 1000, static_cast(table.hits), static_cast(table.misses), table.held, static_cast(snapshots.skipped.load(std::memory_order_relaxed)), static_cast(snapshots.checked.load(std::memory_order_relaxed))); + AgcDriver::ProfilePrint_nid_no_patch("[address-sync] leases: %llu released at completion, %llu synced at once; %llu pin-contention waits by guest threads (%llu finished the lease batch, %llu drained the recorder, %llu cache-only drops) %.1f s; BDA table cache %llu hits / %llu misses (%zu tables held); snapshot compares: %llu skipped (live-backed region), %llu made\n", static_cast(stats.deferred), static_cast(stats.synced), static_cast(stats.contentionWaits), static_cast(stats.contentionSyncs), static_cast(stats.contentionDrains), static_cast(stats.cacheDrops), stats.contentionMs / 1000, static_cast(table.hits), static_cast(table.misses), table.held, static_cast(snapshots.skipped.load(std::memory_order_relaxed)), static_cast(snapshots.checked.load(std::memory_order_relaxed))); } LeaseStats LeaseCounters() { @@ -1166,7 +1167,7 @@ void GuestBufferMemory::CountAddressBuild(double snapshotsUs) { const auto delta = [](std::uint64_t now, std::uint64_t before) { return static_cast(now - before); }; const auto space = AddressSpaceCounters(); const auto& spaceSeen = totals.spaceSeen; - std::fprintf(stderr, "[address] %llu address-based builds (10 s), us per build: lease %.0f, imports pass %.0f, mirror prepare %.0f, compare %.0f (%.0f blocks, %.1f copied), snapshots %.0f; space hits %llu / rebuilds: generation %llu, epoch %llu, device %llu, waiter drop %llu, first %llu; unpublished %llu, dissolved: overlap %llu, imports %llu%s; [bda-table] hits %llu / misses %llu (space tables %llu), first entry: expired %llu, hash differs low %llu / heap %llu, same hash %llu, none held %llu\n", static_cast(totals.builds), per(totals.sums.leaseUs), per(totals.sums.importsUs), per(totals.sums.mirrorsUs), per(totals.sums.compareUs), per(static_cast(totals.sums.blocksCompared)), per(static_cast(totals.sums.blocksCopied)), per(totals.snapshotsUs), delta(space.hits, spaceSeen.hits), delta(space.rebuiltGeneration, spaceSeen.rebuiltGeneration), delta(space.rebuiltEpoch, spaceSeen.rebuiltEpoch), delta(space.rebuiltDevice, spaceSeen.rebuiltDevice), delta(space.rebuiltWaiterDrop, spaceSeen.rebuiltWaiterDrop), delta(space.rebuiltFirst, spaceSeen.rebuiltFirst), delta(space.unpublished, spaceSeen.unpublished), delta(space.dissolvedOverlap, spaceSeen.dissolvedOverlap), delta(space.dissolvedImports, spaceSeen.dissolvedImports), space.enabled ? "" : " (cache off)", delta(table.hits, seen.hits), delta(table.misses, seen.misses), delta(table.spaceTables, seen.spaceTables), delta(table.firstExpired, seen.firstExpired), delta(table.firstDiffersLow, seen.firstDiffersLow), delta(table.firstDiffersHeap, seen.firstDiffersHeap), delta(table.firstSameHash, seen.firstSameHash), delta(table.firstEmpty, seen.firstEmpty)); + AgcDriver::ProfilePrint_nid_no_patch("[address] %llu address-based builds (10 s), us per build: lease %.0f, imports pass %.0f, mirror prepare %.0f, compare %.0f (%.0f blocks, %.1f copied), snapshots %.0f; space hits %llu / rebuilds: generation %llu, epoch %llu, device %llu, waiter drop %llu, first %llu; unpublished %llu, dissolved: overlap %llu, imports %llu%s; [bda-table] hits %llu / misses %llu (space tables %llu), first entry: expired %llu, hash differs low %llu / heap %llu, same hash %llu, none held %llu\n", static_cast(totals.builds), per(totals.sums.leaseUs), per(totals.sums.importsUs), per(totals.sums.mirrorsUs), per(totals.sums.compareUs), per(static_cast(totals.sums.blocksCompared)), per(static_cast(totals.sums.blocksCopied)), per(totals.snapshotsUs), delta(space.hits, spaceSeen.hits), delta(space.rebuiltGeneration, spaceSeen.rebuiltGeneration), delta(space.rebuiltEpoch, spaceSeen.rebuiltEpoch), delta(space.rebuiltDevice, spaceSeen.rebuiltDevice), delta(space.rebuiltWaiterDrop, spaceSeen.rebuiltWaiterDrop), delta(space.rebuiltFirst, spaceSeen.rebuiltFirst), delta(space.unpublished, spaceSeen.unpublished), delta(space.dissolvedOverlap, spaceSeen.dissolvedOverlap), delta(space.dissolvedImports, spaceSeen.dissolvedImports), space.enabled ? "" : " (cache off)", delta(table.hits, seen.hits), delta(table.misses, seen.misses), delta(table.spaceTables, seen.spaceTables), delta(table.firstExpired, seen.firstExpired), delta(table.firstDiffersLow, seen.firstDiffersLow), delta(table.firstDiffersHeap, seen.firstDiffersHeap), delta(table.firstSameHash, seen.firstSameHash), delta(table.firstEmpty, seen.firstEmpty)); totals.tableSeen = table; totals.spaceSeen = space; totals.builds = 0; @@ -1691,7 +1692,7 @@ void reportStaging() { const auto staged = stats.staged.load(); const auto in = stats.stagedInBytes.load(); const auto out = stats.stagedOutBytes.load(); - std::fprintf(stderr, "[buffers] staging: %llu regions staged device-local (%llu with atomics, %llu of reused builds), %.0f KiB copied in, %.0f KiB copied back, %llu without copy-back, %llu shadows refused; last 10 s: %llu regions, %.0f KiB in, %.0f KiB back\n", static_cast(staged), static_cast(stats.stagedAtomic.load()), static_cast(stats.stagedReused.load()), in / 1024.0, out / 1024.0, static_cast(stats.stagedLost.load()), static_cast(stats.stagingRefused.load()), static_cast(staged - lastStaged), (in - lastIn) / 1024.0, (out - lastOut) / 1024.0); + AgcDriver::ProfilePrint_nid_no_patch("[buffers] staging: %llu regions staged device-local (%llu with atomics, %llu of reused builds), %.0f KiB copied in, %.0f KiB copied back, %llu without copy-back, %llu shadows refused; last 10 s: %llu regions, %.0f KiB in, %.0f KiB back\n", static_cast(staged), static_cast(stats.stagedAtomic.load()), static_cast(stats.stagedReused.load()), in / 1024.0, out / 1024.0, static_cast(stats.stagedLost.load()), static_cast(stats.stagingRefused.load()), static_cast(staged - lastStaged), (in - lastIn) / 1024.0, (out - lastOut) / 1024.0); lastStaged = staged; lastIn = in; lastOut = out; @@ -2028,7 +2029,7 @@ void GuestBufferMemory::UploadFinish(bool addressable) { const auto uploads = uploadsProfiled.fetch_add(1, std::memory_order_relaxed) + 1; if (uploads % 2000 == 0) { const auto& copies = Copies(); - std::fprintf(stderr, "[buffers] %llu uploads: import lookup %.0f ms, buffer allocation %.0f ms, guest read %.0f ms; copies on the GPU: %llu regions (%.0f KiB) copied out of imports, %llu written sub-ranges (%.0f KiB) copied back, %llu staging stores by the CPU at write-back\n", static_cast(uploads), importUs.load(std::memory_order_relaxed) / 1000.0, allocateUs.load(std::memory_order_relaxed) / 1000.0, readUs.load(std::memory_order_relaxed) / 1000.0, static_cast(copies.gpuCopies.load(std::memory_order_relaxed)), copies.gpuCopyBytes.load(std::memory_order_relaxed) / 1024.0, static_cast(copies.gpuCopyBacks.load(std::memory_order_relaxed)), copies.gpuCopyBackBytes.load(std::memory_order_relaxed) / 1024.0, static_cast(copies.stagingStores.load(std::memory_order_relaxed))); + AgcDriver::ProfilePrint_nid_no_patch("[buffers] %llu uploads: import lookup %.0f ms, buffer allocation %.0f ms, guest read %.0f ms; copies on the GPU: %llu regions (%.0f KiB) copied out of imports, %llu written sub-ranges (%.0f KiB) copied back, %llu staging stores by the CPU at write-back\n", static_cast(uploads), importUs.load(std::memory_order_relaxed) / 1000.0, allocateUs.load(std::memory_order_relaxed) / 1000.0, readUs.load(std::memory_order_relaxed) / 1000.0, static_cast(copies.gpuCopies.load(std::memory_order_relaxed)), copies.gpuCopyBytes.load(std::memory_order_relaxed) / 1024.0, static_cast(copies.gpuCopyBacks.load(std::memory_order_relaxed)), copies.gpuCopyBackBytes.load(std::memory_order_relaxed) / 1024.0, static_cast(copies.stagingStores.load(std::memory_order_relaxed))); } const auto ms = std::chrono::duration(std::chrono::steady_clock::now() - started).count(); if (ms > 50) { @@ -2040,7 +2041,7 @@ void GuestBufferMemory::UploadFinish(bool addressable) { largest = std::max(largest, region.end - region.begin); if (region.buffer != nullptr) copied += region.end - region.begin; } - std::fprintf(stderr, "[resources] guest upload of %zu regions, %.1f MiB (largest %.1f MiB, copied %.1f MiB, addressable %d) took %.0f ms to finish\n", regions.size(), total / 1048576.0, largest / 1048576.0, copied / 1048576.0, addressable ? 1 : 0, ms); + AgcDriver::ProfilePrint_nid_no_patch("[resources] guest upload of %zu regions, %.1f MiB (largest %.1f MiB, copied %.1f MiB, addressable %d) took %.0f ms to finish\n", regions.size(), total / 1048576.0, largest / 1048576.0, copied / 1048576.0, addressable ? 1 : 0, ms); } // Debug aid: APS5_TRACE_BIGBUF lists every copied region of at least 1 MiB. static const bool traceBig = std::getenv("APS5_TRACE_BIGBUF") != nullptr; @@ -2080,9 +2081,9 @@ void GuestBufferMemory::copyRegion(Region& region, bool addressable) { if (++uploads % 1000 == 0) { // 'misaligned in imports' are the ones the GPU did not copy: over APS5_GPU_COPY_MAX_KIB, // sparse, APS5_CPU_COPIES, no recorder, or an import gone by UploadFinish. - std::fprintf(stderr, "[buffers] %llu copied regions on the CPU: %llu snapshots (%.0f MiB), %llu misaligned in imports (%.0f MiB), %llu outside imports (%.0f MiB):", static_cast(uploads), static_cast(snapshotOnly), snapshotBytes / 1048576.0, static_cast(misaligned), misalignedBytes / 1048576.0, static_cast(noImport), noImportBytes / 1048576.0); - for (const auto& [granule, counts] : outside) std::fprintf(stderr, " 0x%llx0000000:%llu/%.0fMiB", static_cast(granule), static_cast(counts.first), counts.second / 1048576.0); - std::fprintf(stderr, "\n"); + AgcDriver::ProfilePrint_nid_no_patch("[buffers] %llu copied regions on the CPU: %llu snapshots (%.0f MiB), %llu misaligned in imports (%.0f MiB), %llu outside imports (%.0f MiB):", static_cast(uploads), static_cast(snapshotOnly), snapshotBytes / 1048576.0, static_cast(misaligned), misalignedBytes / 1048576.0, static_cast(noImport), noImportBytes / 1048576.0); + for (const auto& [granule, counts] : outside) AgcDriver::ProfilePrint_nid_no_patch(" 0x%llx0000000:%llu/%.0fMiB", static_cast(granule), static_cast(counts.first), counts.second / 1048576.0); + AgcDriver::ProfilePrint_nid_no_patch("\n"); } } const auto allocateStart = std::chrono::steady_clock::now(); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index bb8f5fb2b..439fd70de 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/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -779,7 +780,7 @@ void ReportHookSyncs(HookSyncStats& stats) { std::snprintf(text, sizeof(text), " [0x%x %s %s +0x%llx/+0x%llx/+0x%llx/+0x%llx/+0x%llx/+0x%llx: %llu/%.0fms u%llu/%llu/%llu c%llu s%llu %.0fK/%.0fK]", key.queue, PacketName(key.opcode).c_str(), GuestMemory::ReadSiteName(key.site), key.frames[0], key.frames[1], key.frames[2], key.frames[3], key.frames[4], key.frames[5], count(totals.count), totals.waitedMs, count(k.unchangedOpen), count(k.unchangedPending), count(k.unchangedSignaled), count(k.changed), count(k.stores), totals.rangeBytes / 1024.0 / totals.count, totals.accessBytes / 1024.0 / totals.count); report += text; } - std::fprintf(stderr, "%s\n", report.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("%s\n", report.c_str()); stats = HookSyncStats{}; } @@ -900,7 +901,7 @@ void ReportRecordedStoreSyncs(RecordedStoreStats& stats) { std::snprintf(text, sizeof(text), " [0x%x %s %s +0x%llx/+0x%llx/+0x%llx: %llu/%.0fms k%llu y%llu/n%llu c%llu/u%llu d%llu/l%llu]", key.queue, PacketName(key.opcode).c_str(), GuestMemory::ReadSiteName(key.site), key.frames[0], key.frames[1], key.frames[2], count(k.count), k.waitedMs, count(k.skipped), count(k.cpuWrittenYes), count(k.cpuWrittenNo), count(k.changed), count(k.unchanged), count(k.imagesDead), count(k.imagesLive)); report += text; } - std::fprintf(stderr, "%s\n", report.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("%s\n", report.c_str()); stats.byKey.clear(); stats.totals = {}; } @@ -1718,7 +1719,7 @@ void reportBarriers() { std::snprintf(text, sizeof(text), " %s %llu", CommandClassNames[i], static_cast(mergedCount)); mergedLine += text; } - std::fprintf(stderr, "[barriers] %llu recorded (10 s) by class:%s; merged %llu:%s", static_cast(total), line.c_str(), static_cast(merged), mergedLine.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("[barriers] %llu recorded (10 s) by class:%s; merged %llu:%s", static_cast(total), line.c_str(), static_cast(merged), mergedLine.c_str()); if (Recorder::BarrierValidate()) { std::uint64_t emitted = 0, skipped = 0; std::string classes, kinds; @@ -1737,9 +1738,9 @@ void reportBarriers() { std::snprintf(text, sizeof(text), " %s %llu", HazardNames[i], static_cast(validateKinds[i].exchange(0, std::memory_order_relaxed))); kinds += text; } - std::fprintf(stderr, "; validate: would emit %llu (%s) + %llu batch ends, would skip %llu; emitted/skipped by class:%s", static_cast(emitted), kinds.c_str() + 1, static_cast(validateBatchEnds.exchange(0, std::memory_order_relaxed)), static_cast(skipped), classes.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("; validate: would emit %llu (%s) + %llu batch ends, would skip %llu; emitted/skipped by class:%s", static_cast(emitted), kinds.c_str() + 1, static_cast(validateBatchEnds.exchange(0, std::memory_order_relaxed)), static_cast(skipped), classes.c_str()); } - std::fputc('\n', stderr); + AgcDriver::ProfilePrint_nid_no_patch("\n"); } } @@ -2147,9 +2148,9 @@ void Recorder::readGpuTiming(Batch& batch) { } std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return a.second.ms > b.second.ms; }); // The first field stays the program sum: the measure scripts match on it. - std::fprintf(stderr, "[gputime] %.0f ms of GPU time in %llu batches over 10 s (batch %.0f ms first to last command; classes %.0f ms, all ranges %.0f ms, untimed %.0f ms outside every range; %llu presents; %llu ranges dropped at the %u cap); by program:", timingProgramMs, static_cast(timingBatches), timingBatchMs, timingClassMs, timingUnionMs, timingBatchMs - timingUnionMs, static_cast(presents), static_cast(timingDropped.exchange(0, std::memory_order_relaxed)), MaxTimedRanges); - for (std::size_t i = 0; i < hot.size() && i < 12; ++i) std::fprintf(stderr, " 0x%llx x%llu %.0fms", static_cast(hot[i].first), static_cast(hot[i].second.count), hot[i].second.ms); - std::fprintf(stderr, "; by class:%s\n", classes.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("[gputime] %.0f ms of GPU time in %llu batches over 10 s (batch %.0f ms first to last command; classes %.0f ms, all ranges %.0f ms, untimed %.0f ms outside every range; %llu presents; %llu ranges dropped at the %u cap); by program:", timingProgramMs, static_cast(timingBatches), timingBatchMs, timingClassMs, timingUnionMs, timingBatchMs - timingUnionMs, static_cast(presents), static_cast(timingDropped.exchange(0, std::memory_order_relaxed)), MaxTimedRanges); + for (std::size_t i = 0; i < hot.size() && i < 12; ++i) AgcDriver::ProfilePrint_nid_no_patch(" 0x%llx x%llu %.0fms", static_cast(hot[i].first), static_cast(hot[i].second.count), hot[i].second.ms); + AgcDriver::ProfilePrint_nid_no_patch("; by class:%s\n", classes.c_str()); timingByKey.clear(); timingProgramMs = timingClassMs = timingUnionMs = timingBatchMs = 0; timingBatches = 0; @@ -2996,7 +2997,7 @@ void ReportSyncWaits(SyncWaitStats& stats) { else std::snprintf(text, sizeof(text), " 0x%x %llu", queue, static_cast(count)); report += text; } - std::fprintf(stderr, "%s\n", report.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("%s\n", report.c_str()); stats = SyncWaitStats{}; } @@ -3202,11 +3203,11 @@ void Recorder::finish(std::unique_ptr batch, bool wait, int source) { if (now - lastReport > std::chrono::seconds(10)) { lastReport = now; const auto& h = holdCounters; - std::fprintf(stderr, "[recorder] %llu syncs waited %.1f s for the GPU in total (sources, count/wait: idle %llu/%.1fs, pending write %llu/%.1fs, recorded store %llu/%.1fs, address-based %llu/%.1fs, other %llu/%.1fs); hook %llu calls, %llu locked; %llu targeted syncs left %llu batches in flight; snapshot %llu rebuilds %.0f ms, %llu notes covered; %llu unlocked timeline waits %.1f s; %llu submissions, %zu label entries, %llu completion labels pending; fence waits by thread (count/wait):%s; top sync sites (source@caller syncs/batches/wait):%s; under holds (cumulative): %llu completions ran %.0f ms (kept objects released %.0f ms), pending-write syncs from completions: %llu skipped, %llu waited %.0f ms; %llu reaps (%llu with work) retired %llu batches in %.0f ms; hook waits unlocked %llu / %.0f ms GPU (pending write %llu / %.0f ms, recorded store %llu / %.0f ms) + %.0f ms relock (%llu found the recorder torn down), locked %llu; deferred releases: on the release thread %llu batches (%llu objects) in %.0f ms, inline %llu batches (%llu objects) in %.0f ms (%llu batches over the queue bound of %zu), queue max %llu batches, %llu pending\n",static_cast(waits), waitedMs / 1000, static_cast(syncCounts[0]), syncWaitedMs[0] / 1000, static_cast(syncCounts[1]), syncWaitedMs[1] / 1000, static_cast(syncCounts[2]), syncWaitedMs[2] / 1000, static_cast(syncCounts[3]), syncWaitedMs[3] / 1000, static_cast(syncCounts[4]), syncWaitedMs[4] / 1000, static_cast(hookCalls.load()), static_cast(hookLocks.load()), static_cast(targetedSyncs.load()), static_cast(batchesLeftInFlight.load()), static_cast(snapshotRebuilds), snapshotRebuildMs, static_cast(snapshotCovered), static_cast(unlockedWaits.load()), unlockedWaitedUs.load() / 1e6, static_cast(recorder.submissions), recorder.PendingLabels(), static_cast(completionLabels.load()), ThreadSyncReport().c_str(), SyncSiteReport().c_str(), static_cast(h.completions), h.completionMs, h.keptReleaseMs, static_cast(h.completionSyncsSkipped), static_cast(h.completionSyncsWaited), h.completionSyncWaitMs, static_cast(h.reaps), static_cast(h.reapsWithWork), static_cast(h.reapBatches), h.reapMs, static_cast(h.hookUnlockedWaits), h.hookUnlockedWaitMs, static_cast(h.hookUnlockedWaitsBySource[1]), h.hookUnlockedWaitMsBySource[1], static_cast(h.hookUnlockedWaitsBySource[2]), h.hookUnlockedWaitMsBySource[2], h.hookRelockMs, static_cast(h.hookUnlockedTornDown), static_cast(h.hookLockedWaits), static_cast(threadReleases.load()), static_cast(threadObjects.load()), threadReleaseUs.load() / 1000.0, static_cast(inlineReleases.load()), static_cast(inlineObjects.load()), inlineReleaseUs.load() / 1000.0, static_cast(inlineOverBound.load()), ReleaseQueueBound(), static_cast(releaseQueueMax.load()), static_cast(deferredPending.load())); - std::fprintf(stderr, "[recorder] completion label stores: %llu run, %llu skipped (no CPU write-back overlapped them); %llu counted pending at a write-back; %llu write-backs over a tracked label; %llu write-back completions pending\n", static_cast(completionStoresRun.load()), static_cast(completionStoresSkipped.load()), static_cast(completionLabelsCountedLate.load()), static_cast(writeBacksOverLabels.load()), static_cast(writeBackCompletions.load())); - std::fprintf(stderr, "[recorder] submits %llu, vkQueueSubmit mean %.1f us, max %.1f us\n", static_cast(submitCount), submitCount != 0 ? submitUs / static_cast(submitCount) : 0.0, submitMaxUs); + AgcDriver::ProfilePrint_nid_no_patch("[recorder] %llu syncs waited %.1f s for the GPU in total (sources, count/wait: idle %llu/%.1fs, pending write %llu/%.1fs, recorded store %llu/%.1fs, address-based %llu/%.1fs, other %llu/%.1fs); hook %llu calls, %llu locked; %llu targeted syncs left %llu batches in flight; snapshot %llu rebuilds %.0f ms, %llu notes covered; %llu unlocked timeline waits %.1f s; %llu submissions, %zu label entries, %llu completion labels pending; fence waits by thread (count/wait):%s; top sync sites (source@caller syncs/batches/wait):%s; under holds (cumulative): %llu completions ran %.0f ms (kept objects released %.0f ms), pending-write syncs from completions: %llu skipped, %llu waited %.0f ms; %llu reaps (%llu with work) retired %llu batches in %.0f ms; hook waits unlocked %llu / %.0f ms GPU (pending write %llu / %.0f ms, recorded store %llu / %.0f ms) + %.0f ms relock (%llu found the recorder torn down), locked %llu; deferred releases: on the release thread %llu batches (%llu objects) in %.0f ms, inline %llu batches (%llu objects) in %.0f ms (%llu batches over the queue bound of %zu), queue max %llu batches, %llu pending\n",static_cast(waits), waitedMs / 1000, static_cast(syncCounts[0]), syncWaitedMs[0] / 1000, static_cast(syncCounts[1]), syncWaitedMs[1] / 1000, static_cast(syncCounts[2]), syncWaitedMs[2] / 1000, static_cast(syncCounts[3]), syncWaitedMs[3] / 1000, static_cast(syncCounts[4]), syncWaitedMs[4] / 1000, static_cast(hookCalls.load()), static_cast(hookLocks.load()), static_cast(targetedSyncs.load()), static_cast(batchesLeftInFlight.load()), static_cast(snapshotRebuilds), snapshotRebuildMs, static_cast(snapshotCovered), static_cast(unlockedWaits.load()), unlockedWaitedUs.load() / 1e6, static_cast(recorder.submissions), recorder.PendingLabels(), static_cast(completionLabels.load()), ThreadSyncReport().c_str(), SyncSiteReport().c_str(), static_cast(h.completions), h.completionMs, h.keptReleaseMs, static_cast(h.completionSyncsSkipped), static_cast(h.completionSyncsWaited), h.completionSyncWaitMs, static_cast(h.reaps), static_cast(h.reapsWithWork), static_cast(h.reapBatches), h.reapMs, static_cast(h.hookUnlockedWaits), h.hookUnlockedWaitMs, static_cast(h.hookUnlockedWaitsBySource[1]), h.hookUnlockedWaitMsBySource[1], static_cast(h.hookUnlockedWaitsBySource[2]), h.hookUnlockedWaitMsBySource[2], h.hookRelockMs, static_cast(h.hookUnlockedTornDown), static_cast(h.hookLockedWaits), static_cast(threadReleases.load()), static_cast(threadObjects.load()), threadReleaseUs.load() / 1000.0, static_cast(inlineReleases.load()), static_cast(inlineObjects.load()), inlineReleaseUs.load() / 1000.0, static_cast(inlineOverBound.load()), ReleaseQueueBound(), static_cast(releaseQueueMax.load()), static_cast(deferredPending.load())); + AgcDriver::ProfilePrint_nid_no_patch("[recorder] completion label stores: %llu run, %llu skipped (no CPU write-back overlapped them); %llu counted pending at a write-back; %llu write-backs over a tracked label; %llu write-back completions pending\n", static_cast(completionStoresRun.load()), static_cast(completionStoresSkipped.load()), static_cast(completionLabelsCountedLate.load()), static_cast(writeBacksOverLabels.load()), static_cast(writeBackCompletions.load())); + AgcDriver::ProfilePrint_nid_no_patch("[recorder] submits %llu, vkQueueSubmit mean %.1f us, max %.1f us\n", static_cast(submitCount), submitCount != 0 ? submitUs / static_cast(submitCount) : 0.0, submitMaxUs); const auto reads = Recorder::ReadCounts(); - std::fprintf(stderr, "[recorder] in-place reads: %llu noted, %llu queries, hits by reader: dispatch element %llu, gpu copy %llu, address-based %llu, indirect %llu, storage upload %llu, copy source %llu; %llu hits on signaled batches ignored\n", static_cast(reads.noted), static_cast(reads.queries), static_cast(reads.hits[0]), static_cast(reads.hits[1]), static_cast(reads.hits[2]), static_cast(reads.hits[3]), static_cast(reads.hits[4]), static_cast(reads.hits[5]), static_cast(reads.staleIgnored)); + AgcDriver::ProfilePrint_nid_no_patch("[recorder] in-place reads: %llu noted, %llu queries, hits by reader: dispatch element %llu, gpu copy %llu, address-based %llu, indirect %llu, storage upload %llu, copy source %llu; %llu hits on signaled batches ignored\n", static_cast(reads.noted), static_cast(reads.queries), static_cast(reads.hits[0]), static_cast(reads.hits[1]), static_cast(reads.hits[2]), static_cast(reads.hits[3]), static_cast(reads.hits[4]), static_cast(reads.hits[5]), static_cast(reads.staleIgnored)); } } } report{profile, source, waitStart, *this, signaledAtStart}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index c1fff993b..d6d69c35f 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/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "ThreadOwned.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" @@ -170,7 +171,7 @@ void reportTextureCounters() { auto last = counters.lastReport.load(); if (nowMs - last < 10000 || !counters.lastReport.compare_exchange_strong(last, nowMs)) return; const auto count = [](const std::atomic& value) { return static_cast(value.load(std::memory_order_relaxed)); }; - std::fprintf(stderr, "[textures] sampled created: %llu from storage images, %llu snapshots (%llu snapshot reads over recorded writes inside cachedTexture, %llu storage-path fallbacks); stage-A records %llu: %llu fast hits, %llu full lookups; storage images %llu hits, %llu created, %llu own-object refreshes\n", count(counters.fromStorage), count(counters.snapshots), count(counters.pendingReads), count(counters.storageFallbacks), count(counters.records), count(counters.fastHits), count(counters.fastMisses), count(counters.storageHits), count(counters.storageCreated), count(counters.ownRefreshes)); + AgcDriver::ProfilePrint_nid_no_patch("[textures] sampled created: %llu from storage images, %llu snapshots (%llu snapshot reads over recorded writes inside cachedTexture, %llu storage-path fallbacks); stage-A records %llu: %llu fast hits, %llu full lookups; storage images %llu hits, %llu created, %llu own-object refreshes\n", count(counters.fromStorage), count(counters.snapshots), count(counters.pendingReads), count(counters.storageFallbacks), count(counters.records), count(counters.fastHits), count(counters.fastMisses), count(counters.storageHits), count(counters.storageCreated), count(counters.ownRefreshes)); } // What the sampled-texture lookups on this thread proved their returned objects current against, @@ -836,7 +837,7 @@ struct ThreadBuildProfile { builds = 0; std::string report; for (std::size_t i = 0; i < BuildPhaseCount; ++i) report += " " + std::string(BuildPhaseNames[i]) + "=" + std::to_string(static_cast(profile.ms[i])) + "ms"; - std::fprintf(stderr, "[resources] %llu builds, phase totals:%s\n", static_cast(profile.builds), report.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("[resources] %llu builds, phase totals:%s\n", static_cast(profile.builds), report.c_str()); } }; @@ -872,7 +873,7 @@ double ShaderResources::phase(BuildPhase which) { const auto now = std::chrono::steady_clock::now(); const auto ms = std::chrono::duration(now - phaseStart).count(); addBuildPhase(which, ms); - if (ms > 50) std::fprintf(stderr, "[resources] %s took %.0f ms (%zu textures, %zu storage images, %zu buffers, bda %d)\n", BuildPhaseNames[static_cast(which)], ms, textures.size(), storageTextures.size(), allocations.size(), usesBda ? 1 : 0); + if (ms > 50) AgcDriver::ProfilePrint_nid_no_patch("[resources] %s took %.0f ms (%zu textures, %zu storage images, %zu buffers, bda %d)\n", BuildPhaseNames[static_cast(which)], ms, textures.size(), storageTextures.size(), allocations.size(), usesBda ? 1 : 0); phaseStart = now; return ms; } @@ -1161,7 +1162,7 @@ void ShaderResources::reportDescriptorCaches() const { const auto descriptors = context.descriptorCache != nullptr ? context.descriptorCache->Counters() : DescriptorCache::Stats{}; const auto samplerHits = context.samplerCache != nullptr ? context.samplerCache->Hits() : 0; const auto samplerMisses = context.samplerCache != nullptr ? context.samplerCache->Misses() : 0; - std::fprintf(stderr, "[descriptors] layouts %llu hits / %llu created, sets %llu from %llu pools, samplers %llu hits / %llu created\n", static_cast(descriptors.layoutHits), static_cast(descriptors.layoutMisses), static_cast(descriptors.sets), static_cast(descriptors.pools), static_cast(samplerHits), static_cast(samplerMisses)); + AgcDriver::ProfilePrint_nid_no_patch("[descriptors] layouts %llu hits / %llu created, sets %llu from %llu pools, samplers %llu hits / %llu created\n", static_cast(descriptors.layoutHits), static_cast(descriptors.layoutMisses), static_cast(descriptors.sets), static_cast(descriptors.pools), static_cast(samplerHits), static_cast(samplerMisses)); } std::vector ShaderResources::ContentKey(const CompiledShader& shader, bool dataWords, bool movableBuffers) { @@ -1344,7 +1345,7 @@ void countRevalidate(bool fast, bool ok, std::chrono::steady_clock::time_point s const auto reasons = byReason(profile.fastFails, FastFailNames); const auto fullReasons = byReason(profile.fullByReason, FastFailNames); const auto fallbacks = byReason(profile.ownFallbacks, OwnRefreshFallbackNames); - std::fprintf(stderr, "[rescache] revalidate %llu calls %.1f ms: fast %llu, full %llu, failed %llu; fast-fail by reason:%s; full walks: T1 refreshed %llu (%llu storage images, %llu view sources, %llu views served by their own pending source, %llu overlaps left by the refresh accepted), full by reason:%s, T1 fallback by reason:%s, proofs verified %llu; fast-fail pending image: own 0 (the query excepts the own object), foreign %llu, snapshot %llu, T1 eligible %llu; keys proven: %llu sampled, %llu storage; epoch gate: %llu registry scans skipped, %llu import loops skipped\n", static_cast(profile.calls.load()), profile.nanoseconds.load() / 1e6, static_cast(profile.fast.load()), static_cast(profile.full.load()), static_cast(profile.failed.load()), reasons.c_str(), static_cast(profile.ownRefreshed.load()), static_cast(profile.ownStorageRefreshes.load()), static_cast(profile.ownViewRefreshes.load()), static_cast(profile.ownSourceViews.load()), static_cast(profile.refreshedOverlaps.load()), fullReasons.c_str(), fallbacks.c_str(), static_cast(profile.proofsVerified.load()), static_cast(profile.pendingForeign.load()), static_cast(profile.pendingSnapshot.load()), static_cast(profile.pendingT1Eligible.load()), static_cast(profile.keysProven.load()), static_cast(profile.storageKeysProven.load()), static_cast(profile.serialSkips.load()), static_cast(profile.importSkips.load())); + AgcDriver::ProfilePrint_nid_no_patch("[rescache] revalidate %llu calls %.1f ms: fast %llu, full %llu, failed %llu; fast-fail by reason:%s; full walks: T1 refreshed %llu (%llu storage images, %llu view sources, %llu views served by their own pending source, %llu overlaps left by the refresh accepted), full by reason:%s, T1 fallback by reason:%s, proofs verified %llu; fast-fail pending image: own 0 (the query excepts the own object), foreign %llu, snapshot %llu, T1 eligible %llu; keys proven: %llu sampled, %llu storage; epoch gate: %llu registry scans skipped, %llu import loops skipped\n", static_cast(profile.calls.load()), profile.nanoseconds.load() / 1e6, static_cast(profile.fast.load()), static_cast(profile.full.load()), static_cast(profile.failed.load()), reasons.c_str(), static_cast(profile.ownRefreshed.load()), static_cast(profile.ownStorageRefreshes.load()), static_cast(profile.ownViewRefreshes.load()), static_cast(profile.ownSourceViews.load()), static_cast(profile.refreshedOverlaps.load()), fullReasons.c_str(), fallbacks.c_str(), static_cast(profile.proofsVerified.load()), static_cast(profile.pendingForeign.load()), static_cast(profile.pendingSnapshot.load()), static_cast(profile.pendingT1Eligible.load()), static_cast(profile.keysProven.load()), static_cast(profile.storageKeysProven.load()), static_cast(profile.serialSkips.load()), static_cast(profile.importSkips.load())); } // APS5_NO_EPOCH_REVALIDATE=1: the per-element registry, cache and stamp checks and the per-region @@ -1991,7 +1992,7 @@ void ResourceCache::noteMiss(const Key& key) { } std::snprintf(item, sizeof(item), "; layout %llu, draw target/index %llu, same key %llu (not inserted or evicted), first seen %llu", static_cast(churn.layout), static_cast(churn.drawWords), static_cast(churn.sameKey), static_cast(churn.firstSeen)); line += item; - std::fprintf(stderr, "%s\n", line.c_str()); + AgcDriver::ProfilePrint_nid_no_patch("%s\n", line.c_str()); }; report("dispatch", churn.dispatch); report("draws", churn.draws); @@ -2828,7 +2829,7 @@ void ShaderResources::MarkGpuWrites(Recorder& recorder) { if (nowMs - last < 10000 || !counters.lastReport.compare_exchange_strong(last, nowMs)) return; const auto elements = counters.elements.load(); const auto readOnly = counters.readOnly.load(); - std::fprintf(stderr, "[buffers] descriptor elements bound: %llu total, %llu written, %llu read-only; %llu pending-write notes skipped\n", static_cast(elements), static_cast(elements - readOnly), static_cast(readOnly), static_cast(counters.notesSkipped.load())); + AgcDriver::ProfilePrint_nid_no_patch("[buffers] descriptor elements bound: %llu total, %llu written, %llu read-only; %llu pending-write notes skipped\n", static_cast(elements), static_cast(elements - readOnly), static_cast(readOnly), static_cast(counters.notesSkipped.load())); } void ShaderResources::WriteBackBuffers() { diff --git a/core/libs/prx/libSceAgcDriver/tests/ProfileOutput.cpp b/core/libs/prx/libSceAgcDriver/tests/ProfileOutput.cpp new file mode 100644 index 000000000..5ac7e3ee0 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/ProfileOutput.cpp @@ -0,0 +1,121 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" +#include +#include +#include +#include +#include + +namespace { + +void Check(bool condition, const char* message) { + if (!condition) throw std::runtime_error(message); +} + +void FormatAndDrain() { + std::string written; + const std::string longLine(6000, 'x'); + { + AgcDriver::ProfileOutput output([&](std::string_view text) { written += text; }); + output.Print("%s %.2f %llu\n", "shader", 1.25, 42ull); + output.Print("%s\n", longLine.c_str()); + } + Check(written == "shader 1.25 42\n" + longLine + "\n", "formatting or shutdown drain changed the output"); +} + +void SlowWriter() { + std::mutex mutex; + std::condition_variable release; + bool released = false; + std::promise entered; + bool first = true; + std::string written; + AgcDriver::ProfileOutput output([&](std::string_view text) { + if (first) { + first = false; + entered.set_value(); + std::unique_lock lock(mutex); + release.wait(lock, [&] { return released; }); + } + written += text; + }, 16); + std::future producer; + struct Release { + std::mutex& mutex; + std::condition_variable& changed; + bool& released; + ~Release() { + { + std::lock_guard lock(mutex); + released = true; + } + changed.notify_one(); + } + } cleanup{mutex, release, released}; + Check(output.Write("12345678"), "first write was rejected"); + Check(entered.get_future().wait_for(std::chrono::seconds(2)) == std::future_status::ready, "writer did not start"); + producer = std::async(std::launch::async, [&] { return output.Write("abcdefgh"); }); + Check(producer.wait_for(std::chrono::seconds(2)) == std::future_status::ready, "producer blocked behind the diagnostic writer"); + Check(producer.get(), "write within the bound was rejected"); + Check(!output.Write("z"), "queue bound did not include the in-flight output"); + { + std::lock_guard lock(mutex); + released = true; + } + release.notify_one(); + output.Flush(); + Check(written.starts_with("12345678abcdefgh"), "accepted chunks changed order"); + Check(written.find("[profile-output] dropped 1 chunks") != std::string::npos, "bounded overflow was not reported"); +} + +void ConcurrentWriters() { + std::string written; + AgcDriver::ProfileOutput output([&](std::string_view text) { written += text; }); + std::vector producers; + for (int thread = 0; thread < 8; ++thread) { + producers.emplace_back([&, thread] { + for (int item = 0; item < 100; ++item) output.Print("%d:%d\n", thread, item); + }); + } + for (auto& producer : producers) producer.join(); + output.Flush(); + std::istringstream stream(written); + std::vector lines; + for (std::string line; std::getline(stream, line);) lines.push_back(line); + std::sort(lines.begin(), lines.end()); + Check(lines.size() == 800 && std::adjacent_find(lines.begin(), lines.end()) == lines.end(), "concurrent writes lost or duplicated chunks"); + for (int thread = 0; thread < 8; ++thread) { + for (int item = 0; item < 100; ++item) + Check(std::binary_search(lines.begin(), lines.end(), std::to_string(thread) + ":" + std::to_string(item)), "concurrent formatting changed a chunk"); + } +} + +void WriterFailure() { + AgcDriver::ProfileOutput output([](std::string_view) { throw std::runtime_error("test writer failure"); }); + output.Write("test"); + for (int operation = 0; operation < 2; ++operation) { + bool failed = false; + try { + if (operation == 0) output.Flush(); + else output.Write("next"); + } catch (const std::runtime_error& error) { + failed = std::string(error.what()) == "test writer failure"; + } + Check(failed, "writer failure was not propagated"); + } +} + +} + +int main() { + try { + FormatAndDrain(); + SlowWriter(); + ConcurrentWriters(); + WriterFailure(); + std::cout << "profile output tests passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} From 4a43d433e04714007c44184cd9887eac9088979e Mon Sep 17 00:00:00 2001 From: Nicolas Abosch <88494836+nicolasabosch@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:41:00 -0300 Subject: [PATCH 2/2] fix(agc): defer remaining periodic profiling reports --- .../Execution/src/Driver/Dispatch/Dispatch.cpp | 3 ++- .../Execution/src/Driver/Draw/DrawCacheStatistics.cpp | 5 +++-- .../libSceAgcDriver/Execution/src/Driver/Draw/DrawTiming.cpp | 3 ++- .../Execution/src/Driver/Memory/CaptureDiagnostics.cpp | 3 ++- .../Execution/src/Driver/Packets/PacketExecution.cpp | 3 ++- .../Execution/src/Driver/Packets/PacketTiming.cpp | 5 +++-- .../libSceAgcDriver/Execution/src/Driver/Presentation.cpp | 3 ++- .../src/Driver/Synchronization/SynchronizationStatistics.cpp | 3 ++- core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp | 4 ++-- core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp | 3 ++- core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp | 3 ++- core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp | 3 ++- 12 files changed, 26 insertions(+), 15 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp index 25c05fb21..8be671d55 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/Dispatch.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp" @@ -360,7 +361,7 @@ void Driver::dispatch(QueueState& queue, std::span packet, pending.ms = phaseMs; pending.tailAt = phaseLap; } - if (profile && ++dispatches % 100 == 0) std::fprintf(stderr, "[gpu] %llu dispatches (%llu dispatch cache hits, %llu evictions, %llu recompile cache hits): capture %.1f s, cache key %.1f s, recompile %.1f s, device %.1f s\n", static_cast(dispatches), static_cast(dispatchCacheHits), static_cast(dispatchCacheEvictions), static_cast(cacheHits), captureMs / 1000, keyMs / 1000, recompileMs / 1000, deviceMs / 1000); + if (profile && ++dispatches % 100 == 0) AgcDriver::ProfilePrint_nid_no_patch( "[gpu] %llu dispatches (%llu dispatch cache hits, %llu evictions, %llu recompile cache hits): capture %.1f s, cache key %.1f s, recompile %.1f s, device %.1f s\n", static_cast(dispatches), static_cast(dispatchCacheHits), static_cast(dispatchCacheEvictions), static_cast(cacheHits), captureMs / 1000, keyMs / 1000, recompileMs / 1000, deviceMs / 1000); } } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCacheStatistics.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCacheStatistics.cpp index 6282bc2a7..9d82d8550 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCacheStatistics.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCacheStatistics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" namespace AgcDriver::DriverDetail { @@ -12,8 +13,8 @@ void Driver::reportDrawCache(DrawEntryCounters& counters) { std::snprintf(text, sizeof(text), "%s%llu", rank == 0 ? "" : " / ", count(counters.variantHitsByRank[rank])); ranks += text; } - std::fprintf(stderr, "[draw-cache] %llu lookups (10 s): %llu no entry, %llu validated in %.1f us each (key, lookup and every stage): %llu hits (every stage equal; stage hits by variant rank 1..k %s), misses by reason: front stage differing %llu, fragment differing %llu, other stage differing %llu, layout (push offset) %llu, gate %llu, stage count %llu; %llu stage validations (%llu equal, %.2f variants compared each); %llu inserts (%llu variants inserted, %llu evicted beyond k, %llu already present, %llu unstable), %zu entries (%llu variants, ~%.1f MiB), %llu evictions in total, %llu LRU moves; verify: %llu hits captured again, %llu stages differed\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast(validated) : 0.0, count(counters.hits), ranks.c_str(), miss(DrawMiss::FrontDiffering), miss(DrawMiss::FragmentDiffering), miss(DrawMiss::OtherDiffering), miss(DrawMiss::Layout), miss(DrawMiss::Gate), miss(DrawMiss::Stages), count(counters.stageValidations), count(counters.stageEqual), counters.stageValidations != 0 ? static_cast(counters.variantsCompared) / static_cast(counters.stageValidations) : 0.0, count(counters.inserts), count(counters.variantsInserted), count(counters.variantsEvicted), count(counters.present), count(counters.unstable), drawCache.size(), count(drawCacheVariants), static_cast(drawCacheVariantBytes) / (1024.0 * 1024.0), count(drawCacheEvictions), count(counters.touches), count(counters.verifyHits), count(counters.verifyMismatches)); - std::fprintf(stderr, "[draw-cache] register key (10 s): %llu lookups, %llu hits, key build %.1f us each; decode skipped %llu, partial (state/pixel/programs from the entry) %llu; facade log != table %llu; verify: %llu decodes compared, %llu differed\n", count(counters.registerKeyLookups), count(counters.registerKeyHits), counters.registerKeyLookups != 0 ? counters.keyUs / static_cast(counters.registerKeyLookups) : 0.0, count(counters.decodeSkipped), count(counters.decodePartial), count(counters.facadeMismatches), count(counters.verifyDecodes), count(counters.verifyDecodeMismatches)); + AgcDriver::ProfilePrint_nid_no_patch( "[draw-cache] %llu lookups (10 s): %llu no entry, %llu validated in %.1f us each (key, lookup and every stage): %llu hits (every stage equal; stage hits by variant rank 1..k %s), misses by reason: front stage differing %llu, fragment differing %llu, other stage differing %llu, layout (push offset) %llu, gate %llu, stage count %llu; %llu stage validations (%llu equal, %.2f variants compared each); %llu inserts (%llu variants inserted, %llu evicted beyond k, %llu already present, %llu unstable), %zu entries (%llu variants, ~%.1f MiB), %llu evictions in total, %llu LRU moves; verify: %llu hits captured again, %llu stages differed\n", count(counters.lookups), count(counters.absent), count(validated), validated != 0 ? counters.validateUs / static_cast(validated) : 0.0, count(counters.hits), ranks.c_str(), miss(DrawMiss::FrontDiffering), miss(DrawMiss::FragmentDiffering), miss(DrawMiss::OtherDiffering), miss(DrawMiss::Layout), miss(DrawMiss::Gate), miss(DrawMiss::Stages), count(counters.stageValidations), count(counters.stageEqual), counters.stageValidations != 0 ? static_cast(counters.variantsCompared) / static_cast(counters.stageValidations) : 0.0, count(counters.inserts), count(counters.variantsInserted), count(counters.variantsEvicted), count(counters.present), count(counters.unstable), drawCache.size(), count(drawCacheVariants), static_cast(drawCacheVariantBytes) / (1024.0 * 1024.0), count(drawCacheEvictions), count(counters.touches), count(counters.verifyHits), count(counters.verifyMismatches)); + AgcDriver::ProfilePrint_nid_no_patch( "[draw-cache] register key (10 s): %llu lookups, %llu hits, key build %.1f us each; decode skipped %llu, partial (state/pixel/programs from the entry) %llu; facade log != table %llu; verify: %llu decodes compared, %llu differed\n", count(counters.registerKeyLookups), count(counters.registerKeyHits), counters.registerKeyLookups != 0 ? counters.keyUs / static_cast(counters.registerKeyLookups) : 0.0, count(counters.decodeSkipped), count(counters.decodePartial), count(counters.facadeMismatches), count(counters.verifyDecodes), count(counters.verifyDecodeMismatches)); counters = DrawEntryCounters{}; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawTiming.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawTiming.cpp index bd973c611..bfc4731ce 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawTiming.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawTiming.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawTiming.hpp" @@ -26,7 +27,7 @@ void Driver::addDrawPhases(const std::array& ms, b report += text; total += totals.ms[i]; } - std::fprintf(stderr, "[draw] driver phases (10 s, %llu draw packets, %llu drawn, %llu captures), us per packet:%s, total %.1f (%.1f ms; Graphics::Draw %.1f ms, skipped %.1f ms)\n", static_cast(totals.packets), static_cast(totals.drawn), static_cast(totals.captures), report.c_str(), total * 1000 / static_cast(totals.packets), total, totals.ms[DrawRowGraphics], totals.ms[DrawRowSkipped]); + AgcDriver::ProfilePrint_nid_no_patch( "[draw] driver phases (10 s, %llu draw packets, %llu drawn, %llu captures), us per packet:%s, total %.1f (%.1f ms; Graphics::Draw %.1f ms, skipped %.1f ms)\n", static_cast(totals.packets), static_cast(totals.drawn), static_cast(totals.captures), report.c_str(), total * 1000 / static_cast(totals.packets), total, totals.ms[DrawRowGraphics], totals.ms[DrawRowSkipped]); totals.ms = {}; totals.packets = totals.drawn = totals.captures = 0; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/CaptureDiagnostics.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/CaptureDiagnostics.cpp index 10c4b53ff..ddab9c7aa 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/CaptureDiagnostics.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/CaptureDiagnostics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" namespace AgcDriver::DriverDetail { @@ -30,7 +31,7 @@ void Driver::reportValidation(ValidateCounters& counters) { if (evidence.streak >= writeEvidenceAfter()) ++eligible; } } - std::fprintf(stderr, "[validate] dispatch-cache compares over pending GPU writes (10 s): %llu; missed without the sync %llu, skipped the sync %llu, synced %llu waiting %.0f ms (no dispatch writer %llu, foreign writer %llu, larger range %llu, label %llu, evidence short %llu, writer changed %llu, sampled %llu, image %llu, shadow %llu, off %llu); known-value reads %llu; verify: %llu would-skip compares synced anyway (%.0f ms), %llu mismatches, %llu misses a sync made hits; dwords observed over waits: %llu unchanged, %llu changed (regions not observed: %llu after no GPU wait, %llu not compared); %zu tracked, %zu with a streak\n", count(counters.pending), count(counters.unsyncedMisses), count(counters.skipped), count(counters.syncedNoWriter + counters.syncedForeign + counters.syncedLargeRange + counters.syncedLabel + counters.syncedEvidence + counters.syncedWriterChanged + counters.syncedSample + counters.syncedImage + counters.syncedShadow + counters.syncedOff), counters.syncedWaitMs, count(counters.syncedNoWriter), count(counters.syncedForeign), count(counters.syncedLargeRange), count(counters.syncedLabel), count(counters.syncedEvidence), count(counters.syncedWriterChanged), count(counters.syncedSample), count(counters.syncedImage), count(counters.syncedShadow), count(counters.syncedOff), count(counters.knownValue), count(counters.verified), counters.verifiedWaitMs, count(counters.mismatches), count(counters.verifiedMissesHit), count(observedUnchanged.exchange(0)), count(observedChanged.exchange(0)), count(observationsNoWait.exchange(0)), count(observationsNotReached.exchange(0)), tracked, eligible); + AgcDriver::ProfilePrint_nid_no_patch( "[validate] dispatch-cache compares over pending GPU writes (10 s): %llu; missed without the sync %llu, skipped the sync %llu, synced %llu waiting %.0f ms (no dispatch writer %llu, foreign writer %llu, larger range %llu, label %llu, evidence short %llu, writer changed %llu, sampled %llu, image %llu, shadow %llu, off %llu); known-value reads %llu; verify: %llu would-skip compares synced anyway (%.0f ms), %llu mismatches, %llu misses a sync made hits; dwords observed over waits: %llu unchanged, %llu changed (regions not observed: %llu after no GPU wait, %llu not compared); %zu tracked, %zu with a streak\n", count(counters.pending), count(counters.unsyncedMisses), count(counters.skipped), count(counters.syncedNoWriter + counters.syncedForeign + counters.syncedLargeRange + counters.syncedLabel + counters.syncedEvidence + counters.syncedWriterChanged + counters.syncedSample + counters.syncedImage + counters.syncedShadow + counters.syncedOff), counters.syncedWaitMs, count(counters.syncedNoWriter), count(counters.syncedForeign), count(counters.syncedLargeRange), count(counters.syncedLabel), count(counters.syncedEvidence), count(counters.syncedWriterChanged), count(counters.syncedSample), count(counters.syncedImage), count(counters.syncedShadow), count(counters.syncedOff), count(counters.knownValue), count(counters.verified), counters.verifiedWaitMs, count(counters.mismatches), count(counters.verifiedMissesHit), count(observedUnchanged.exchange(0)), count(observedChanged.exchange(0)), count(observationsNoWait.exchange(0)), count(observationsNotReached.exchange(0)), tracked, eligible); counters = ValidateCounters{}; } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp index 3c5dcd148..af3361308 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketExecution.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "ThreadOwned.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" @@ -24,7 +25,7 @@ void Driver::timed(double WorkerProfile::*bucket, TWork&& work) { static const bool report = std::getenv("APS5_PROFILE_DRAW") != nullptr; if (report && end - profile.reported > std::chrono::seconds(10)) { profile.reported = end; - std::fprintf(stderr, "[gpu] worker at %.0f s: dispatch %.1f s, draw %.1f s, wait %.1f s\n", std::chrono::duration(end - profile.start).count(), profile.dispatchMs / 1000, profile.drawMs / 1000, profile.waitMs / 1000); + AgcDriver::ProfilePrint_nid_no_patch( "[gpu] worker at %.0f s: dispatch %.1f s, draw %.1f s, wait %.1f s\n", std::chrono::duration(end - profile.start).count(), profile.dispatchMs / 1000, profile.drawMs / 1000, profile.waitMs / 1000); } } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketTiming.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketTiming.cpp index 5c6e70eff..40461f1a5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketTiming.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/PacketTiming.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Packets/PacketTiming.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/SynchronizationStatistics.hpp" @@ -40,9 +41,9 @@ PacketTimer::~PacketTimer() { outcomes += text; } auto& poll = Driver::pollStats(); - std::fprintf(stderr, "[poll] queue 0x%x (10 s): ticks %llu, table hits %llu, tries %llu / failed %llu, submits %llu, reaps %llu (%llu with work; by reason: behind completion %llu / other %llu), refusals: %s %llu, %s %llu, %s %llu, %s %llu, %s %llu; longest try hold %.1f us, try holds %.1f ms\n", queue, static_cast(poll.ticks), static_cast(poll.tableHits), static_cast(poll.tries), static_cast(poll.triesFailed), static_cast(poll.submits), static_cast(poll.reaps), static_cast(poll.reapsWithWork), static_cast(poll.reapsBehindCompletion), static_cast(poll.reapsOther), LabelRefusalNames[1], static_cast(poll.refusals[1]), LabelRefusalNames[2], static_cast(poll.refusals[2]), LabelRefusalNames[3], static_cast(poll.refusals[3]), LabelRefusalNames[4], static_cast(poll.refusals[4]), LabelRefusalNames[5], static_cast(poll.refusals[5]), poll.longestTryHoldUs, poll.tryHoldUs / 1000.0); + AgcDriver::ProfilePrint_nid_no_patch( "[poll] queue 0x%x (10 s): ticks %llu, table hits %llu, tries %llu / failed %llu, submits %llu, reaps %llu (%llu with work; by reason: behind completion %llu / other %llu), refusals: %s %llu, %s %llu, %s %llu, %s %llu, %s %llu; longest try hold %.1f us, try holds %.1f ms\n", queue, static_cast(poll.ticks), static_cast(poll.tableHits), static_cast(poll.tries), static_cast(poll.triesFailed), static_cast(poll.submits), static_cast(poll.reaps), static_cast(poll.reapsWithWork), static_cast(poll.reapsBehindCompletion), static_cast(poll.reapsOther), LabelRefusalNames[1], static_cast(poll.refusals[1]), LabelRefusalNames[2], static_cast(poll.refusals[2]), LabelRefusalNames[3], static_cast(poll.refusals[3]), LabelRefusalNames[4], static_cast(poll.refusals[4]), LabelRefusalNames[5], static_cast(poll.refusals[5]), poll.longestTryHoldUs, poll.tryHoldUs / 1000.0); poll = PollStats{}; - std::fprintf(stderr, "[packets] queue 0x%x %llu submissions, time by packet (10 s):%s, flush %.0fms; DISPATCH_DIRECT by outcome:%s; per submission (%llu submitted): validate %.1f us, copy %.1f us, dequeue %.1f us, complete %.1f us; suspend points %llu x %.1f us, %llu skipped (nothing open); end submits %llu made, %llu skipped, %llu notifies skipped; waits satisfied: at entry %llu, from recorder %llu (%llu while polling, same queue %llu, %llu without the GPU mutex, %llu late-trusted), polled %llu (%llu entered without the GPU mutex, %llu entry tries failed; late candidates %llu: refused cpu-store %llu, overwritten %llu, unclosed %llu, queued %llu), timed out %llu; poll submits %llu, poll reaps %llu; epoch bumps: submissions %llu, waits %llu, drains %llu, reaps %llu, packets %llu\n", queue, static_cast(profile.submissions), report.c_str(), profile.flushMs, outcomes.c_str(), static_cast(submitted), validateUs, copyUs, dequeueUs, completeUs, static_cast(suspends), suspendUs, static_cast(costs.suspendsSkipped.exchange(0)), static_cast(costs.endSubmits.exchange(0)), static_cast(costs.endSkipped.exchange(0)), static_cast(costs.notifiesSkipped.exchange(0)), static_cast(waits.atEntry), static_cast(waits.fromRecorder + waits.fromRecorderPolling), static_cast(waits.fromRecorderPolling), static_cast(waits.fromRecorderSameQueue), static_cast(waits.fromRecorderUnlocked), static_cast(waits.fromRecorderLate), static_cast(waits.polled), static_cast(waits.entriesUnlocked), static_cast(waits.entryTriesFailed), static_cast(late.candidates - lateSeen.candidates), static_cast(waits.lateRefusedCpuStore), static_cast(late.overwritten - lateSeen.overwritten), static_cast(late.unclosed - lateSeen.unclosed), static_cast(late.queued - lateSeen.queued), static_cast(waits.timedOut), static_cast(waits.pollSubmits), static_cast(waits.pollReaps), static_cast(epochs.submissions), static_cast(epochs.waits), static_cast(epochs.drains), static_cast(epochs.reaps), static_cast(epochs.packets)); + AgcDriver::ProfilePrint_nid_no_patch( "[packets] queue 0x%x %llu submissions, time by packet (10 s):%s, flush %.0fms; DISPATCH_DIRECT by outcome:%s; per submission (%llu submitted): validate %.1f us, copy %.1f us, dequeue %.1f us, complete %.1f us; suspend points %llu x %.1f us, %llu skipped (nothing open); end submits %llu made, %llu skipped, %llu notifies skipped; waits satisfied: at entry %llu, from recorder %llu (%llu while polling, same queue %llu, %llu without the GPU mutex, %llu late-trusted), polled %llu (%llu entered without the GPU mutex, %llu entry tries failed; late candidates %llu: refused cpu-store %llu, overwritten %llu, unclosed %llu, queued %llu), timed out %llu; poll submits %llu, poll reaps %llu; epoch bumps: submissions %llu, waits %llu, drains %llu, reaps %llu, packets %llu\n", queue, static_cast(profile.submissions), report.c_str(), profile.flushMs, outcomes.c_str(), static_cast(submitted), validateUs, copyUs, dequeueUs, completeUs, static_cast(suspends), suspendUs, static_cast(costs.suspendsSkipped.exchange(0)), static_cast(costs.endSubmits.exchange(0)), static_cast(costs.endSkipped.exchange(0)), static_cast(costs.notifiesSkipped.exchange(0)), static_cast(waits.atEntry), static_cast(waits.fromRecorder + waits.fromRecorderPolling), static_cast(waits.fromRecorderPolling), static_cast(waits.fromRecorderSameQueue), static_cast(waits.fromRecorderUnlocked), static_cast(waits.fromRecorderLate), static_cast(waits.polled), static_cast(waits.entriesUnlocked), static_cast(waits.entryTriesFailed), static_cast(late.candidates - lateSeen.candidates), static_cast(waits.lateRefusedCpuStore), static_cast(late.overwritten - lateSeen.overwritten), static_cast(late.unclosed - lateSeen.unclosed), static_cast(late.queued - lateSeen.queued), static_cast(waits.timedOut), static_cast(waits.pollSubmits), static_cast(waits.pollReaps), static_cast(epochs.submissions), static_cast(epochs.waits), static_cast(epochs.drains), static_cast(epochs.reaps), static_cast(epochs.packets)); lateSeen = late; waits = WaitOutcomes{}; epochs = EpochBumps{}; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Presentation.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Presentation.cpp index 994626128..e42553239 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Presentation.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Presentation.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Queues/WorkerAffinity.hpp" @@ -150,7 +151,7 @@ void Driver::reportPresents(double waitedMs, std::size_t inFlight) { const auto flips = flipsCounted.load() - previousFlips; const double perFlip = flips != 0 ? 1.0 / static_cast(flips) : 0.0; const auto serial = flipSerial.load(); - std::fprintf(stderr, "[present] %llu presents over 10 s (%zu may trail on the GPU); %s p50 %.2f ms, p90 %.2f ms, max %.2f ms over %zu; per present: GPU busy %.1f ms, idle gaps %.1f ms (%llu batches without a completion record); per flip: %.1f batches recorded (%.1f unsignaled at the flip); per present: %.1f batches ahead of the blit, %.1f after it; after the flip packet: last submit %.1f ms, blit submit %.1f ms; in-place reads overwritten before execution: %llu of %llu checked\n", static_cast(presents), inFlight, inFlight != 0 ? "inflight_wait" : "render_fence_wait", percentile(0.5), percentile(0.9), waits.empty() ? 0.0 : waits.back(), waits.size(), (counts.gpuBusyMs - previous.gpuBusyMs) * perPresent, (counts.gpuGapMs - previous.gpuGapMs) * perPresent, static_cast(counts.gpuUnread - previous.gpuUnread), static_cast(serial - windowSerial) * perFlip, static_cast(flipBatchesUnsignaled.load() - previousUnsignaled) * perFlip, static_cast(counts.batchesAheadOfBlit - previous.batchesAheadOfBlit) * perPresent, static_cast(counts.batchesAfterFlip - previous.batchesAfterFlip) * perPresent, (counts.lastSubmitAfterFlipMs - previous.lastSubmitAfterFlipMs) * perPresent, (counts.blitSubmitAfterFlipMs - previous.blitSubmitAfterFlipMs) * perPresent, static_cast(counts.readsOverwritten - previous.readsOverwritten), static_cast(counts.readsChecked - previous.readsChecked)); + AgcDriver::ProfilePrint_nid_no_patch( "[present] %llu presents over 10 s (%zu may trail on the GPU); %s p50 %.2f ms, p90 %.2f ms, max %.2f ms over %zu; per present: GPU busy %.1f ms, idle gaps %.1f ms (%llu batches without a completion record); per flip: %.1f batches recorded (%.1f unsignaled at the flip); per present: %.1f batches ahead of the blit, %.1f after it; after the flip packet: last submit %.1f ms, blit submit %.1f ms; in-place reads overwritten before execution: %llu of %llu checked\n", static_cast(presents), inFlight, inFlight != 0 ? "inflight_wait" : "render_fence_wait", percentile(0.5), percentile(0.9), waits.empty() ? 0.0 : waits.back(), waits.size(), (counts.gpuBusyMs - previous.gpuBusyMs) * perPresent, (counts.gpuGapMs - previous.gpuGapMs) * perPresent, static_cast(counts.gpuUnread - previous.gpuUnread), static_cast(serial - windowSerial) * perFlip, static_cast(flipBatchesUnsignaled.load() - previousUnsignaled) * perFlip, static_cast(counts.batchesAheadOfBlit - previous.batchesAheadOfBlit) * perPresent, static_cast(counts.batchesAfterFlip - previous.batchesAfterFlip) * perPresent, (counts.lastSubmitAfterFlipMs - previous.lastSubmitAfterFlipMs) * perPresent, (counts.blitSubmitAfterFlipMs - previous.blitSubmitAfterFlipMs) * perPresent, static_cast(counts.readsOverwritten - previous.readsOverwritten), static_cast(counts.readsChecked - previous.readsChecked)); previous = counts; previousFlips = flipsCounted.load(); previousUnsignaled = flipBatchesUnsignaled.load(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/SynchronizationStatistics.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/SynchronizationStatistics.cpp index 07304acfe..dfb31f4b7 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/SynchronizationStatistics.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/SynchronizationStatistics.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Synchronization/SynchronizationStatistics.hpp" #include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" @@ -38,7 +39,7 @@ SubmissionCosts& submissionCosts(std::uint32_t queue) { void reportSync() { std::string report; for (const auto& [code, count] : drainCounts) report += " " + (code == 0xffffu ? std::string("flip") : Pm4::Name(code << 8u)) + "=" + std::to_string(count); - std::fprintf(stderr, "[sync] %llu device drains by packet:%s (%llu waited without the GPU mutex); %llu labels written on the GPU, %llu deferred behind completions, %llu deferred not imported, %llu no-op, fallbacks: idle %llu, completions %llu, not imported %llu, undecodable %llu; %llu labels queued per worker, recorded in %llu groups, %llu recorded at once; stores: %llu recorded on the GPU, %llu behind completions, %llu on the CPU (idle), %llu synced (drained)\n", static_cast(drainTotal), report.c_str(), static_cast(unlockedDrains.load()), static_cast(gpuLabels.load()), static_cast(completionLabels.load()), static_cast(notImportedLabels.load()), static_cast(noOpLabels.load()), static_cast(labelFallbacks[1].load()), static_cast(labelFallbacks[2].load()), static_cast(labelFallbacks[3].load()), static_cast(labelFallbacks[4].load()), static_cast(queuedLabels.load()), static_cast(labelGroups.load()), static_cast(immediateLabels.load()), static_cast(storesOnGpu.load()), static_cast(storesBehindCompletions.load()), static_cast(storesOnCpu.load()), static_cast(storesDrained.load())); + AgcDriver::ProfilePrint_nid_no_patch("[sync] %llu device drains by packet:%s (%llu waited without the GPU mutex); %llu labels written on the GPU, %llu deferred behind completions, %llu deferred not imported, %llu no-op, fallbacks: idle %llu, completions %llu, not imported %llu, undecodable %llu; %llu labels queued per worker, recorded in %llu groups, %llu recorded at once; stores: %llu recorded on the GPU, %llu behind completions, %llu on the CPU (idle), %llu synced (drained)\n", static_cast(drainTotal), report.c_str(), static_cast(unlockedDrains.load()), static_cast(gpuLabels.load()), static_cast(completionLabels.load()), static_cast(notImportedLabels.load()), static_cast(noOpLabels.load()), static_cast(labelFallbacks[1].load()), static_cast(labelFallbacks[2].load()), static_cast(labelFallbacks[3].load()), static_cast(labelFallbacks[4].load()), static_cast(queuedLabels.load()), static_cast(labelGroups.load()), static_cast(immediateLabels.load()), static_cast(storesOnGpu.load()), static_cast(storesBehindCompletions.load()), static_cast(storesOnCpu.load()), static_cast(storesDrained.load())); } void countLabelOutcome(int reason) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp index 8bea6b6a1..a9427ddc0 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp @@ -1505,8 +1505,8 @@ void GpuMutexType::lock() { char counts[160]; std::snprintf(counts, sizeof(counts), "; lock() %llu / try %llu / try failed %llu; locked GPU waits %llu / %.0f ms", static_cast(stats.acquisitions), static_cast(stats.tries), static_cast(stats.triesFailed), static_cast(stats.lockedGpuWaits), stats.lockedGpuWaitMs); holds += counts; - if (stats.tag == 0xffffffffu) std::fprintf(stderr, "[lock] %s waited %.0f ms for the GPU mutex in %llu of %llu acquisitions (%.0f s); by site (acquisitions/waits, waited):%s%s\n", stats.holderColumn == PresenterColumn ? "presenter" : "untagged thread", stats.waitedMs, static_cast(stats.waits), static_cast(stats.acquisitions), interval, sites.c_str(), holds.c_str()); - else std::fprintf(stderr, "[lock] queue 0x%x waited %.0f ms for the GPU mutex in %llu of %llu acquisitions (%.0f s); by site (acquisitions/waits, waited):%s%s\n", stats.tag, stats.waitedMs, static_cast(stats.waits), static_cast(stats.acquisitions), interval, sites.c_str(), holds.c_str()); + if (stats.tag == 0xffffffffu) AgcDriver::ProfilePrint_nid_no_patch("[lock] %s waited %.0f ms for the GPU mutex in %llu of %llu acquisitions (%.0f s); by site (acquisitions/waits, waited):%s%s\n", stats.holderColumn == PresenterColumn ? "presenter" : "untagged thread", stats.waitedMs, static_cast(stats.waits), static_cast(stats.acquisitions), interval, sites.c_str(), holds.c_str()); + else AgcDriver::ProfilePrint_nid_no_patch("[lock] queue 0x%x waited %.0f ms for the GPU mutex in %llu of %llu acquisitions (%.0f s); by site (acquisitions/waits, waited):%s%s\n", stats.tag, stats.waitedMs, static_cast(stats.waits), static_cast(stats.acquisitions), interval, sites.c_str(), holds.c_str()); stats.waitedMs = 0; stats.waits = 0; stats.acquisitions = 0; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp index 78bc557d7..f624288af 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/ShaderMemory.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "Optimization/RequestMemoryView.hpp" @@ -240,7 +241,7 @@ std::shared_ptr ShaderMemory::Capture(c const auto specializationNs = ShaderRecompiler::ResourceMaterializer::SpecializationNanoseconds(); const auto hookNs = totals.hookWaitNanoseconds.load(); const auto walkNs = captureNs > resolveNs + pageNs + wordNs + specializationNs ? captureNs - resolveNs - pageNs - wordNs - specializationNs : 0; - std::fprintf(stderr, "[capture] %llu captures: %llu word reads, %llu pages fetched (%llu read word by word over pending GPU writes: %llu words waited %.2f s, %llu read raw on evidence, %llu verified with %llu mismatches, %llu served from known values, %llu hook reads not observed: no GPU wait), capture (plan lookup + materialize) %.1f s, %llu KiB registered code this capture; sub-phases (s, us per capture): source resolve %.2f/%.1f, walk %.2f/%.1f, specialization (every materialize) %.2f/%.1f, page reads %.2f/%.1f, word reads %.2f/%.1f, hook GPU waits inside %.2f/%.1f; source handle memo %llu hits, %llu resolves\n", static_cast(totals.captures.load()), static_cast(totals.reads.load()), static_cast(totals.pages.load()), static_cast(totals.pagesWordwise.load()), static_cast(totals.wordWaits.load()), totals.wordWaitNanoseconds.load() / 1e9, static_cast(totals.wordsRaw.load()), static_cast(totals.wordsVerified.load()), static_cast(totals.wordMismatches.load()), static_cast(totals.wordsKnown.load()), static_cast(totals.observationsSkipped.load()), captureNs / 1e9, static_cast(initialBytes / 1024), resolveNs / 1e9, resolveNs / captures / 1e3, walkNs / 1e9, walkNs / captures / 1e3, specializationNs / 1e9, specializationNs / captures / 1e3, pageNs / 1e9, pageNs / captures / 1e3, wordNs / 1e9, wordNs / captures / 1e3, hookNs / 1e9, hookNs / captures / 1e3, static_cast(totals.handleHits.load()), static_cast(totals.handleMisses.load())); + AgcDriver::ProfilePrint_nid_no_patch( "[capture] %llu captures: %llu word reads, %llu pages fetched (%llu read word by word over pending GPU writes: %llu words waited %.2f s, %llu read raw on evidence, %llu verified with %llu mismatches, %llu served from known values, %llu hook reads not observed: no GPU wait), capture (plan lookup + materialize) %.1f s, %llu KiB registered code this capture; sub-phases (s, us per capture): source resolve %.2f/%.1f, walk %.2f/%.1f, specialization (every materialize) %.2f/%.1f, page reads %.2f/%.1f, word reads %.2f/%.1f, hook GPU waits inside %.2f/%.1f; source handle memo %llu hits, %llu resolves\n", static_cast(totals.captures.load()), static_cast(totals.reads.load()), static_cast(totals.pages.load()), static_cast(totals.pagesWordwise.load()), static_cast(totals.wordWaits.load()), totals.wordWaitNanoseconds.load() / 1e9, static_cast(totals.wordsRaw.load()), static_cast(totals.wordsVerified.load()), static_cast(totals.wordMismatches.load()), static_cast(totals.wordsKnown.load()), static_cast(totals.observationsSkipped.load()), captureNs / 1e9, static_cast(initialBytes / 1024), resolveNs / 1e9, resolveNs / captures / 1e3, walkNs / 1e9, walkNs / captures / 1e3, specializationNs / 1e9, specializationNs / captures / 1e3, pageNs / 1e9, pageNs / captures / 1e3, wordNs / 1e9, wordNs / captures / 1e3, hookNs / 1e9, hookNs / captures / 1e3, static_cast(totals.handleHits.load()), static_cast(totals.handleMisses.load())); } } return capture; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index 3d56df8c9..e77279db5 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -1,3 +1,4 @@ +#include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" #include "prx/libSceAgcDriver/Graphics/include/VertexInput.hpp" #include @@ -499,7 +500,7 @@ void reportPipelines(PipelineStore& store) { if (now - store.lastReport < std::chrono::seconds(10)) return; store.lastReport = now; const auto lookups = store.hits + store.misses + store.uncached; - std::fprintf(stderr, "[pipecache] %llu lookups over 10 s: %llu hits (%.0f%%), %llu misses, %llu private (no variant id), %llu evicted, %zu cached\n", static_cast(lookups), static_cast(store.hits), lookups != 0 ? 100.0 * static_cast(store.hits) / static_cast(lookups) : 0.0, static_cast(store.misses), static_cast(store.uncached), static_cast(store.evicted), store.entries.size()); + AgcDriver::ProfilePrint_nid_no_patch( "[pipecache] %llu lookups over 10 s: %llu hits (%.0f%%), %llu misses, %llu private (no variant id), %llu evicted, %zu cached\n", static_cast(lookups), static_cast(store.hits), lookups != 0 ? 100.0 * static_cast(store.hits) / static_cast(lookups) : 0.0, static_cast(store.misses), static_cast(store.uncached), static_cast(store.evicted), store.entries.size()); store.hits = store.misses = store.uncached = store.evicted = 0; } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp index 2bb762263..a6e017329 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/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libc/include/General.hpp" @@ -125,7 +126,7 @@ void reportStorageTraffic(StorageTraffic& traffic) { const auto take = [](std::atomic& counter) { return static_cast(counter.exchange(0, std::memory_order_relaxed)); }; const auto partialUploadCount = take(partialUploads), partialWriteBackCount = take(partialWriteBacks); const auto uploadMiB = take(partialUploadBytes) / 1048576.0, writeBackMiB = take(partialWriteBackBytes) / 1048576.0; - std::fprintf(stderr, "[storage] uploads by path (count/MiB, 10 s):%s; %llu write-backs GPU-direct, %llu stored nothing; block units: partial uploads %llu/%.1f, partial write-backs %llu/%.1f, %llu widened to every pending unit, units dropped %llu, superseded %llu, dropped unregistered %llu, kept over a key flip %llu%s, pretest skipped %llu, evicted stale %llu\n", line.c_str(), static_cast(traffic.directWriteBacks), take(emptyWriteBacks), partialUploadCount, uploadMiB, partialWriteBackCount, writeBackMiB, take(coalescedWriteBacks), take(unitsDropped), take(unitsSuperseded), take(unregisteredDropped), take(keyFlipKept), ShadowReport().c_str(), take(pretestSkipped), take(staleEvicted)); + AgcDriver::ProfilePrint_nid_no_patch( "[storage] uploads by path (count/MiB, 10 s):%s; %llu write-backs GPU-direct, %llu stored nothing; block units: partial uploads %llu/%.1f, partial write-backs %llu/%.1f, %llu widened to every pending unit, units dropped %llu, superseded %llu, dropped unregistered %llu, kept over a key flip %llu%s, pretest skipped %llu, evicted stale %llu\n", line.c_str(), static_cast(traffic.directWriteBacks), take(emptyWriteBacks), partialUploadCount, uploadMiB, partialWriteBackCount, writeBackMiB, take(coalescedWriteBacks), take(unitsDropped), take(unitsSuperseded), take(unregisteredDropped), take(keyFlipKept), ShadowReport().c_str(), take(pretestSkipped), take(staleEvicted)); traffic.writeBacks.clear(); traffic.uploadReasons.clear(); traffic.directWriteBacks = 0;