#include #include "prx/libSceAgcDriver/Execution/include/AsyncLog.hpp" #include "prx/libc/include/HostThread.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileOutput.hpp" #include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" #include "prx/libSceAgcDriver/Execution/include/ProfileCounter.hpp" #include "prx/libc/include/HostThreadLocal.hpp" #include "prx/libc/include/HostThreadSlot.hpp" #include "prx/libSceAgcDriver/Execution/include/ThreadScratch.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Graphics/include/DrawStageTimingKeys.hpp" #include "prx/libSceAgcDriver/Graphics/include/BdaResources.hpp" #include "prx/libSceAgcDriver/Graphics/include/ReferenceStorage.hpp" #include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp" #include "prx/libkernel/Time/include/SleepWake.hpp" #include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" #include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp" #include "prx/libSceAgcDriver/Graphics/include/ParallelCompare.hpp" #include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" #include "prx/libSceAgcDriver/Graphics/include/DeferredDestruction.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/SubmissionSnapshots.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/MeshArguments_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/StagingCopyBack_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/StagingCopyBackBound_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/SampleCounter_spv.h" #include "prx/libSceAgcDriver/Graphics/shaders/SampleDumps_spv.h" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceOverlay.hpp" #include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp" #include "prx/libSceAgcDriver/Execution/include/Pm4Opcodes.hpp" #include "prx/libc/include/CpuTopology.hpp" #include "prx/libc/include/RunReport.hpp" #include "prx/libc/include/GuestAllocations.hpp" #include "prx/libc/include/GuestArena.hpp" #include "prx/libSceAgcDriver/Graphics/shaders/DispatchArguments_spv.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "prx/libc/include/general/AtomicSharedPtr.hpp" namespace AgcDriver::Graphics { namespace { Recorder* activeRecorder = nullptr; bool DrawProfiled() { static const bool profiled = std::getenv("APS5_PROFILE_DRAW") != nullptr; return profiled; } std::uint64_t syncCounts[5] = {}; // Fence wait time by sync source (APS5_PROFILE_DRAW), and the source CountSync announced for the // Sync/SyncThrough that follows it on this thread. double syncWaitedMs[5] = {}; thread_local int announcedSource = 4; // The call site CountSync named for that sync (nullptr: none; the sync's own return address is // taken then), and the fence-wait table per (source, site) it feeds (APS5_PROFILE_DRAW, under the // GpuMutex like finish()): which caller's syncs wait, when the source alone does not say (source // 0 is every WaitIdle and drain). `activeSyncSite` is the entry of the sync in progress on this // thread (an index: a nested sync from a completion replaces and restores it), so finish() charges // each batch's wait to it. thread_local const void* announcedSite = nullptr; struct SyncSiteWaits { int source; const void* site; std::uint64_t syncs; std::uint64_t batches; double waitedMs; }; std::vector syncSites; constexpr std::size_t NoSyncSite = static_cast(-1); constexpr std::size_t SyncSiteLimit = 48; thread_local std::size_t activeSyncSite = NoSyncSite; bool SyncSitesProfiled() { // APS5_NO_SYNC_SITES=1 leaves only the per-source and per-thread counts. static const bool profiled = std::getenv("APS5_PROFILE_DRAW") != nullptr && std::getenv("APS5_NO_SYNC_SITES") == nullptr; return profiled; } // Begins a sync's attribution: returns the previous active entry for the caller to restore, after // counting the sync under (source, site). Beyond the table's limit every further site shares the // last entry (a nullptr site), so the table stays small. std::size_t BeginSyncSite(int source, const void* site) { const auto previous = activeSyncSite; if (!SyncSitesProfiled()) return previous; auto it = std::find_if(syncSites.begin(), syncSites.end(), [&](const SyncSiteWaits& entry) { return entry.source == source && entry.site == site; }); if (it == syncSites.end()) { if (syncSites.size() >= SyncSiteLimit) { it = std::find_if(syncSites.begin(), syncSites.end(), [&](const SyncSiteWaits& entry) { return entry.source == source && entry.site == nullptr; }); if (it == syncSites.end()) it = syncSites.insert(syncSites.end(), SyncSiteWaits{source, nullptr, 0, 0, 0}); } else { it = syncSites.insert(syncSites.end(), SyncSiteWaits{source, site, 0, 0, 0}); } } ++it->syncs; activeSyncSite = static_cast(it - syncSites.begin()); return previous; } void CountSiteWait(double ms) { if (activeSyncSite == NoSyncSite || activeSyncSite >= syncSites.size()) return; auto& entry = syncSites[activeSyncSite]; ++entry.batches; entry.waitedMs += ms; } // The sites by wait, longest first, as "source@+offset syncs/batches/wait" (offsets symbolize with // nm against the driver's image like the [guestmem] callers; +0x0 is the overflow entry). std::string SyncSiteReport() { static const char* const names[5] = {"idle", "pending-write", "recorded-store", "address-based", "other"}; std::vector order; for (const auto& entry : syncSites) order.push_back(&entry); std::sort(order.begin(), order.end(), [](const SyncSiteWaits* a, const SyncSiteWaits* b) { return a->waitedMs > b->waitedMs; }); std::string report; for (std::size_t i = 0; i < order.size() && i < 8; ++i) { char text[96]; std::snprintf(text, sizeof(text), " %s@+0x%llx %llu/%llu/%.1fs", names[order[i]->source], order[i]->site != nullptr ? GuestMemory::CodeOffset(order[i]->site) : 0ull, static_cast(order[i]->syncs), static_cast(order[i]->batches), order[i]->waitedMs / 1000); report += text; } return report; } // Fence waits by thread and source (APS5_PROFILE_DRAW), keyed by the thread's GpuMutex queue tag: // a sync waits for the GPU under the mutex, so which worker's syncs (and which kind) hold it against // queue 0 has to be visible. Its own mutex: the table is read while the report line is printed. struct ThreadSyncs { std::uint32_t tag; std::array counts; std::array waitedMs; }; std::vector threadSyncs; AgcDriver::Mutex threadSyncsMutex; // This thread's fence and timeline waits in total (Recorder::ThreadWaitedMs): a caller times a span // of its own work and reads the difference to learn how much of it was waiting for the GPU. struct ThreadWaitedSlot {}; void CountThreadSync(int source, double ms) { HostThreadSlot::Set(HostThreadSlot::Get() + ms); const auto tag = GuestMemory::GpuLockThreadTag(); std::lock_guard lock(threadSyncsMutex); auto it = std::find_if(threadSyncs.begin(), threadSyncs.end(), [&](const ThreadSyncs& thread) { return thread.tag == tag; }); if (it == threadSyncs.end()) it = threadSyncs.insert(threadSyncs.end(), ThreadSyncs{tag, {}, {}}); ++it->counts[source]; it->waitedMs[source] += ms; } std::string ThreadSyncReport() { static const char* const names[5] = {"idle", "pending-write", "recorded-store", "address-based", "other"}; std::string report; std::lock_guard lock(threadSyncsMutex); for (const auto& thread : threadSyncs) { char text[64]; if (thread.tag == 0xffffffffu) std::snprintf(text, sizeof(text), " untagged:"); else std::snprintf(text, sizeof(text), " queue 0x%x:", thread.tag); report += text; for (int source = 0; source < 5; ++source) { if (thread.counts[source] == 0) continue; std::snprintf(text, sizeof(text), " %s %llu/%.1fs", names[source], static_cast(thread.counts[source]), thread.waitedMs[source] / 1000); report += text; } } return report; } // Unlocked timeline waits (WaitSerial): count and time, for the [recorder] line. std::atomic unlockedWaits{0}, unlockedWaitedUs{0}; // vkQueueSubmit calls and their time (APS5_PROFILE_DRAW; Submit runs under the GpuMutex). std::uint64_t submitCount = 0; double submitUs = 0, submitMaxUs = 0; // Threads inside a timeline wait with the GpuMutex released (WaitSerial, syncThroughUnlocked): a // recorder's teardown, after its Sync() made every wait satisfiable, waits until they left the // semaphore before destroying it. Counted per recorder id (a small fixed array; the waiter cannot // touch a recorder that may be dying, so it is keyed by the id it copied out), so a replaced // device's old recorder does not spin on the new device's in-flight waits. constexpr std::size_t WaiterSlots = 16; std::atomic unlockedWaiters[WaiterSlots]{}; std::atomic& WaitersOf(std::uint64_t id) { return unlockedWaiters[id % WaiterSlots]; } // Recorders alive, by id (own mutex, taken under the GpuMutex or with nothing held): a thread that // released the GpuMutex around a wait learns whether its recorder still exists before touching it. AgcDriver::Mutex liveRecordersMutex; std::vector liveRecorders; std::atomic nextRecorderId{1}; std::atomic samplesPassed{0}; constexpr std::uint32_t SampleFoldCapacity = 64; constexpr std::uint32_t SampleCounterPushBytes = 28; constexpr std::uint32_t SegmentSlots = 128; constexpr std::uint32_t SegmentFoldCapacity = 1024; constexpr std::uint32_t DumpFoldCapacity = 1024; constexpr std::uint32_t SampleDumpBytes = 15 * 16 + 8; constexpr VkDeviceSize DumpListOffset = 16 + 8 * SegmentFoldCapacity; constexpr std::uint32_t SampleDumpPushBytes = 40; std::atomic dumpsQueued{0}, dumpsQueuedInPass{0}, dumpsAtOnce{0}, segmentsClosed{0}, dumpFolds{0}; struct SamplePoolCache { VkDevice device; PFN_vkDestroyQueryPool destroy; AgcDriver::Mutex mutex; std::vector free; bool closed = false; void put(VkQueryPool pool) { { std::lock_guard lock(mutex); if (!closed && free.size() < 256) { free.push_back(pool); return; } } destroy(device, pool, nullptr); } VkQueryPool take() { std::lock_guard lock(mutex); if (free.empty()) return VK_NULL_HANDLE; const auto pool = free.back(); free.pop_back(); return pool; } void close() { std::lock_guard lock(mutex); closed = true; for (const auto pool : free) destroy(device, pool, nullptr); free.clear(); } }; struct SamplePool { SamplePool(std::shared_ptr cache, VkQueryPool pool) : cache(std::move(cache)), pool(pool) {} SamplePool(const SamplePool&) = delete; SamplePool& operator=(const SamplePool&) = delete; ~SamplePool() { cache->put(pool); } std::shared_ptr cache; VkQueryPool pool; }; bool RecorderAlive(std::uint64_t id) { std::lock_guard lock(liveRecordersMutex); return std::find(liveRecorders.begin(), liveRecorders.end(), id) != liveRecorders.end(); } // Completion actions in progress on this thread (finish()): a pending-write sync the flush hook // makes from inside one (a copied buffer's write-back store) is skipped, see SyncThrough. struct CompletionDepthSlot {}; int completionDepth() { return HostThreadSlot::Get(); } // This thread's hook syncs that waited for an unsignaled target (Recorder::ThreadHookWaits). thread_local std::uint64_t hookRealWaits = 0; } bool Recorder::Alive(std::uint64_t id) { return RecorderAlive(id); } bool Recorder::InCompletion() { return completionDepth() != 0; } namespace { // APS5_NO_HOOK_COMPLETION_GUARD=1: the flush hook records the accessing worker's queued labels // even from inside a completion action, as before (see FlushForAccess). bool HookCompletionGuard() { static const bool guard = std::getenv("APS5_NO_HOOK_COMPLETION_GUARD") == nullptr; return guard; } // APS5_COMPLETION_STORE_SYNC=1: a store made by a completion action waits for later batches that // note its range, as before (the wait runs under whichever hold reaped the batch). bool CompletionStoreSyncs() { static const bool enabled = std::getenv("APS5_COMPLETION_STORE_SYNC") != nullptr; return enabled; } // APS5_HOOK_LOCKED_WAIT=1: the flush hook's pending-write wait stays under the GpuMutex as before. bool HookLockedWait() { static const bool locked = std::getenv("APS5_HOOK_LOCKED_WAIT") != nullptr; return locked; } // APS5_HOOK_FULL_SYNC=1: the flush hook's recorded-store wait is a full Sync() under the GpuMutex // (every batch in flight) as before, instead of SyncThrough's targeted, unlocked wait (H1). bool HookFullSync() { static const bool hookFullSync = std::getenv("APS5_HOOK_FULL_SYNC") != nullptr; return hookFullSync; } // APS5_HOOK_FLUSH_CPU_BLOCKS=0: an access whose every 64 KiB block the CPU wrote since the // overlapping pending images' generations flushes them as before, instead of the C4 skip (H2: // StorageTexture::AccessKeptByCpu). bool HookFlushCpuBlocks() { static const bool hookFlushCpuBlocks = [] { const char* text = std::getenv("APS5_HOOK_FLUSH_CPU_BLOCKS"); return text != nullptr && text[0] == '0'; }(); return hookFlushCpuBlocks; } // What the holds spend on the recorder (APS5_PROFILE_DRAW, all under the GpuMutex, printed at the // end of the [recorder] line): completions and their time (of which releasing the kept objects), // pending-write syncs from inside completions (skipped, or waited with the kill switch), reaps and // the batches they retired, and the flush hook's unlocked waits (with those that found the // recorder torn down when they retook the mutex, and those that had to wait locked). struct HoldCounters { std::uint64_t completions = 0; double completionMs = 0; double keptReleaseMs = 0; std::uint64_t completionSyncsSkipped = 0; std::uint64_t completionSyncsWaited = 0; double completionSyncWaitMs = 0; std::uint64_t reaps = 0; std::uint64_t reapsWithWork = 0; std::uint64_t reapBatches = 0; double reapMs = 0; std::uint64_t hookUnlockedWaits = 0; // The GPU wait alone (timeline wait with the mutex released) and, separately, the relock's // own wait for the GpuMutex (also counted by the [lock] line under 'hook'), so the two // remaining costs, GPU latency and hold contention, stay apart. double hookUnlockedWaitMs = 0; double hookRelockMs = 0; // The same by sync source (1 pending write, 2 recorded store). std::array hookUnlockedWaitsBySource{}; std::array hookUnlockedWaitMsBySource{}; std::uint64_t hookUnlockedTornDown = 0; // Genuine nested hooks (depth >= 2 outside a completion action) that had to wait locked. std::uint64_t hookLockedWaits = 0; }; HoldCounters holdCounters; // Deferred release of a finished batch's kept objects (and its completion actions, whose captures // hold some of the same objects): finish() moves them to this list of the finishing thread instead // of destroying them under the mutex, and the GpuMutex unlock hook (ReleaseDeferredKeeps, set by // the constructor) hands the list to the release thread once the thread gave up its outermost // hold. Destroying a ShaderResources with its buffers, descriptor set, textures and pipelines cost // ~1.5 ms per reap with work, inside whichever hold reaped ('kept objects released', 15.9 s per // 200 s run), and most reaps are queue 0's own (ReapRecorded before its dispatches), so a release // on the unlocking thread would still be the frame's time. The destructors touch only their own // caches' mutexes and the device, never the recorder or GpuMutex, so they need no hold and no // particular thread (every Vulkan object is externally synchronized per object, and its cache's // mutex covers its pool); they need the device alive, which ~Recorder guarantees by draining its // own thread's list, stopping and joining the release thread (it drains the queue before it // leaves) and waiting for every release still in progress on another thread (`deferredPending`: // counted up under the mutex, down after each batch's objects are gone) before the device goes. // The queue is bounded (APS5_RELEASE_QUEUE_MAX batches, default 256): a thread whose hand-off // would exceed it destroys its batches itself, as it did before the release thread, so memory // cannot grow behind a release thread that falls behind. // APS5_RELEASE_UNDER_LOCK=1 destroys them in finish() as before; APS5_RELEASE_ON_UNLOCK=1 destroys // them on the unlocking thread (no release thread). struct DeferredBatch { std::vector> kept; std::vector> completions; }; struct DeferredBatchesTag {}; auto& DeferredBatches() { return HostThreadLocal, DeferredBatchesTag>(); } struct DeferredBytesTag {}; auto& DeferredBytes() { return HostThreadLocal(); } std::vector TakeDeferred() { auto taken = std::move(DeferredBatches()); DeferredBatches().clear(); DeferredBytes() = 0; return taken; } std::atomic deferredPending{0}; std::atomic threadReleases{0}, threadObjects{0}, threadReleaseUs{0}; std::atomic inlineReleases{0}, inlineObjects{0}, inlineReleaseUs{0}, inlineOverBound{0}; std::atomic releaseQueueMax{0}; bool ReleaseUnderLock() { static const bool locked = std::getenv("APS5_RELEASE_UNDER_LOCK") != nullptr; return locked; } bool ReleaseOnUnlock() { static const bool onUnlock = std::getenv("APS5_RELEASE_ON_UNLOCK") != nullptr; return onUnlock; } std::size_t ReleaseQueueBound() { static const std::size_t bound = [] { const char* value = std::getenv("APS5_RELEASE_QUEUE_MAX"); const auto parsed = value != nullptr ? std::strtoull(value, nullptr, 10) : 0ull; return parsed != 0 ? static_cast(parsed) : std::size_t{256}; }(); return bound; } // Destroys deferred batches, on the release thread (`onThread`) or on the thread that deferred // them, and counts each batch off `deferredPending` only once its objects are gone: ~Recorder // waits for that count. void DestroyDeferred(std::vector releasing, bool onThread) { if (releasing.empty()) return; const bool profile = DrawProfiled(); const auto start = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; const auto count = releasing.size(); std::uint64_t objects = 0; for (auto& batch : releasing) { objects += batch.kept.size(); // The completions first (their captures hold some of the objects), then the objects. batch.completions.clear(); batch.kept.clear(); deferredPending.fetch_sub(1, std::memory_order_acq_rel); } releasing.clear(); if (profile) { const auto us = static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count()); (onThread ? threadReleases : inlineReleases).fetch_add(count, std::memory_order_relaxed); (onThread ? threadObjects : inlineObjects).fetch_add(objects, std::memory_order_relaxed); (onThread ? threadReleaseUs : inlineReleaseUs).fetch_add(us, std::memory_order_relaxed); } } // The release thread's queue: one for the process. The thread is started at the first hand-off and // stopped and joined by ~Recorder (JoinReleaseThread), after which the next hand-off starts it // again (a device replacement makes a new recorder). The queue object is leaked so that a static // destructor never races the thread: at process exit the thread is idle on its condition variable // (every ~Recorder joined it) or, when no ~Recorder ran, mid-release like any worker thread. Nothing // is done under `mutex` but the hand-off and the take; `joinMutex` serializes joiners and orders // before `mutex`; neither is ever taken by a kept object's destructor. struct ReleaseQueue { std::mutex mutex; std::condition_variable wake; std::vector items; std::thread thread; bool started = false; // Set by a joiner under `mutex` until the thread was joined: the thread leaves once the queue // is empty, and hand-offs meanwhile destroy inline (nothing may be queued without a taker). bool stop = false; AgcDriver::Mutex joinMutex; }; ReleaseQueue& ReleaseThreadQueue() { static ReleaseQueue* const queue = new ReleaseQueue; return *queue; } void ReleaseThreadMain() { CpuTopology::PinHelperThread("release thread"); auto& queue = ReleaseThreadQueue(); std::unique_lock lock(queue.mutex); for (;;) { queue.wake.wait(lock, [&] { return !queue.items.empty() || queue.stop; }); if (queue.items.empty()) return; auto items = std::move(queue.items); queue.items.clear(); lock.unlock(); DestroyDeferred(std::move(items), true); lock.lock(); } } // Stops the release thread once it emptied the queue and joins it (~Recorder, before its device // goes). Hand-offs made while the thread stops destroy inline, so nothing can sit in the queue // without a taker; a later hand-off starts the thread again. void JoinReleaseThread() { auto& queue = ReleaseThreadQueue(); std::lock_guard joining(queue.joinMutex); std::thread worker; { std::lock_guard lock(queue.mutex); if (!queue.started) return; queue.stop = true; worker = std::move(queue.thread); } queue.wake.notify_all(); worker.join(); std::lock_guard lock(queue.mutex); queue.started = false; queue.stop = false; } // The unlock hook: hands what this thread deferred to the release thread, or destroys it here // (APS5_RELEASE_ON_UNLOCK=1, the queue is full or stopping, or the hand-off cannot be made). void ReleaseDeferredKeeps() { if (DeferredBatches().empty()) return; // Taken off the thread's list first: a destructor that took and released the mutex (none is // known to) would re-enter here and must find nothing. auto releasing = TakeDeferred(); if (ReleaseOnUnlock()) { DestroyDeferred(std::move(releasing), false); return; } auto& queue = ReleaseThreadQueue(); const bool profile = DrawProfiled(); bool handedOff = false; bool overBound = false; try { std::lock_guard lock(queue.mutex); if (queue.items.size() + releasing.size() > ReleaseQueueBound()) { overBound = true; } else if (!queue.stop) { // The thread before the items: items queued with no thread to take them would keep // `deferredPending` up and ~Recorder waiting forever. if (!queue.started) { queue.thread = Libc::StartHostThread(&ReleaseThreadMain); queue.started = true; } // The allocation before any move: a failure here leaves `releasing` intact for the // fallback below, and the moves cannot throw. queue.items.reserve(queue.items.size() + releasing.size()); for (auto& batch : releasing) queue.items.push_back(std::move(batch)); handedOff = true; if (profile) { const auto queued = static_cast(queue.items.size()); auto seen = releaseQueueMax.load(std::memory_order_relaxed); while (queued > seen && !releaseQueueMax.compare_exchange_weak(seen, queued, std::memory_order_relaxed)) { } } } } catch (...) { } if (!handedOff) { if (profile && overBound) inlineOverBound.fetch_add(releasing.size(), std::memory_order_relaxed); DestroyDeferred(std::move(releasing), false); return; } queue.wake.notify_one(); } // Lock-free state of the active recorder's open batch, read by the queue workers between packets // and inside WAIT_REG_MEM polls (see the static readers in Recorder.hpp). Written under the mutex. constexpr std::int64_t NoPendingLabel = std::numeric_limits::min(); constexpr BarrierMask PassEndBarrier{VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT}; constexpr BarrierMask LabelLeadingBarrier{VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT}; std::atomic pendingLabelSince{NoPendingLabel}; std::atomic writeGeneration{0}; std::atomic publishGeneration{0}; std::atomic completionLabels{0}; std::atomic completionStores{0}; std::atomic writeBackCompletions{0}; std::atomic completionStoresSkipped{0}; std::atomic completionStoresRun{0}; std::atomic commandBuffersFreed{0}; std::atomic fencesKept{0}; // Write-backs noted over a tracked label dword (NoteWrittenBack): a CPU store over a GPU label. std::atomic writeBacksOverLabels{0}; // Completion labels that entered the pending count at a write-back (see NoteWrittenBack). std::atomic completionLabelsCountedLate{0}; std::atomic workSinceSubmit{0}; // APS5_COUNT_ALL_COMPLETION_LABELS=1: a completion label also stored on the GPU counts as pending // from its registration, as before (see Recorder::AfterCompletions). bool CountAllCompletionLabels() { static const bool all = std::getenv("APS5_COUNT_ALL_COMPLETION_LABELS") != nullptr; return all; } // APS5_NO_PROC_TABLE=1: the recorder resolves its Vulkan entry points per call, as before. bool ProcTable() { static const bool table = std::getenv("APS5_NO_PROC_TABLE") == nullptr; return table; } // The pending-label table's own mutex: every mutation of a recorder's `labels` holds it (under the // GPU mutex), so a WAIT_REG_MEM looks a label up with this small lock alone (Recorder::LookupLabel) // instead of queueing behind a dispatch. `labelTableOwner` is the active recorder while it lives, // set and cleared under this mutex, so a lookup never touches a table being destroyed. Nothing // under this mutex takes the GPU mutex (no lock-order cycle). AgcDriver::Mutex labelTableMutex; std::atomic injectedSubmitFailures{0}; Recorder* labelTableOwner = nullptr; // The ranges of the calling worker's queued labels (NoteQueuedLabel, cleared by // ForgetQueuedLabels): the flush hook, on the same thread, has them recorded before an access that // overlaps one, through the function the driver installed. struct QueuedLabelRangesTag {}; auto& QueuedLabelRanges() { return ThreadScratch>, QueuedLabelRangesTag>(); } struct QueuedLabelsOnThreadTag {}; using QueuedLabelsOnThread = HostThreadSlot; std::atomic queuedLabelRecorder{nullptr}; // The dwords (with their stamps) this thread noted since its last CloseLabelGroup (see Recorder::CloseLabelGroup). struct LabelGroupDwordsTag {}; auto& LabelGroupDwords() { return HostThreadLocal>, LabelGroupDwordsTag>(); } // Late-rule counters (Recorder::LateCounts), per thread: lookups run on the waiting worker. thread_local Recorder::LateStatistics lateCounts{}; // APS5_LABEL_TRUST_LATE=1 trusts entries with stamp <= afterStamp under the late rule; off by // default until the frame-rate collapse it produced at the video stage (lt_on: 119 -> 25 presents // per 10 s with 0 late-trusted waits) is understood. bool LateTrustEnabled() { static const bool enabled = [] { const char* value = std::getenv("APS5_LABEL_TRUST_LATE"); return value != nullptr && std::strcmp(value, "0") != 0; }(); return enabled; } // Store-run and queued-label counters (Recorder::StoreCounts), relaxed: they are only reported. std::atomic storeCount{0}, storeRuns{0}, storesJoined{0}, storesReplaced{0}, storeWawBarriers{0}, storeJoinsRefused{0}; std::atomic keyStoreCount{0}, keyStoreRuns{0}, keyStoreRunsForWriter{0}, keyStoresJoined{0}; // Debug aid: APS5_DCC_KEYS_EACH=1 records every DCC key store at once (see Recorder::QueueKeyStore). bool KeyStoresEach() { static const bool each = std::getenv("APS5_DCC_KEYS_EACH") != nullptr; return each; } std::atomic queuedLabelsNoted{0}, queuedLabelsOverRecorded{0}, queuedLabelHits{0}, queuedLabelHookRecords{0}, queuedLabelHookInCompletion{0}; // Read-tracking counters (Recorder::ReadCounts), relaxed: they are only reported. constexpr std::size_t ReadKinds = static_cast(Recorder::ReadKind::Count); ProfileCounter readsNoted, readQueries, readStaleIgnored; ProfileCounter readHits[ReadKinds]; bool ReadTrackingEnabled() { // APS5_COPY_READ_TRACKING=0: no in-place reads are noted; the copy HLE's CPU path then requires // an idle recorder (VulkanDevice::CopyBuffer), never less. static const bool enabled = [] { const char* value = std::getenv("APS5_COPY_READ_TRACKING"); return value == nullptr || std::strcmp(value, "0") != 0; }(); return enabled; } bool LabelRunsEnabled() { // Debug aid: APS5_NO_LABEL_RUNS=1 records every store between a barrier pair of its own // (APS5_NO_LABEL_BATCHING=1 turns off every label-batching change of Driver.cpp too). static const bool enabled = std::getenv("APS5_NO_LABEL_RUNS") == nullptr && std::getenv("APS5_NO_LABEL_BATCHING") == nullptr; return enabled; } // One store run per batch, recorded at Submit (see Recorder::RecordStore). Debug aid: // APS5_LABEL_RUNS_INLINE=1 records the stores at once and closes the run at the next command. bool LabelRunsPerBatch() { static const bool perBatch = LabelRunsEnabled() && std::getenv("APS5_LABEL_RUNS_INLINE") == nullptr; return perBatch; } std::atomic storeRunsAtSubmit{0}, storeRunsForced{0}; // APS5_NO_JOIN_WAW_CHECK=1: a contiguous store joins the pending one without the check against // the run's recorded stores, as before (see RecordStore). bool JoinWawCheck() { static const bool check = std::getenv("APS5_NO_JOIN_WAW_CHECK") == nullptr; return check; } // APS5_NO_SEPARATE_QUEUED_LABELS=1: a queued label enters the recorded table and replaces a // recorded entry of its dword, as before (see NoteQueuedLabel). bool SeparateQueuedLabels() { static const bool separate = std::getenv("APS5_NO_SEPARATE_QUEUED_LABELS") == nullptr; return separate; } bool QueuedLabelOverlaps(std::uint64_t address, std::size_t bytes) { const auto end = address + bytes; for (const auto& [begin, finish] : QueuedLabelRanges()) { if (address < finish && begin < end) return true; } return false; } // Flush hook statistics: calls, calls whose snapshot check overlapped (the GpuMutex was taken), // targeted syncs and the batches they left in flight. std::atomic hookCalls{0}, hookLocks{0}, targetedSyncs{0}, batchesLeftInFlight{0}; // Snapshot maintenance (under the GpuMutex): notes whose range the snapshot already covered (no // rebuild), rebuilds, and the time the rebuilds took (APS5_PROFILE_DRAW), so their cost is visible. std::uint64_t snapshotCovered = 0, snapshotRebuilds = 0; double snapshotRebuildMs = 0; using WriteRanges = Recorder::WriteRanges; // The sorted, merged union of the guest ranges every unfinished batch will write. Rebuilt under // GuestMemory::GpuMutex (the only writer) and read by the flush hook without it: the lock is the // graphics worker's main stall, so a no-overlap access must not wait for another queue's device // work. A range leaves the snapshot only after its batch's completions (CPU write-backs) ran, so a // reader that sees no overlap either precedes the note (the queues are unordered then, as on the // GPU) or follows the write-back. AtomicSharedPtr pendingWrites; bool HookSnapshotEnabled() { // Debug aid: APS5_NO_HOOK_SNAPSHOT=1 takes the GpuMutex on every access as before. static const bool enabled = std::getenv("APS5_NO_HOOK_SNAPSHOT") == nullptr; return enabled; } bool SnapshotOverlaps(const WriteRanges* snapshot, std::uint64_t address, std::size_t bytes) { if (bytes == 0 || snapshot == nullptr || snapshot->empty()) return false; // Merged ranges are ordered by both bounds: the first one ending past the access decides. const auto it = std::partition_point(snapshot->begin(), snapshot->end(), [&](const auto& range) { return range.second <= address; }); return it != snapshot->end() && it->first < address + bytes; } bool SnapshotOverlaps(std::uint64_t address, std::size_t bytes) { if (bytes == 0) return false; const auto snapshot = pendingWrites.load(std::memory_order_acquire); return SnapshotOverlaps(snapshot.get(), address, bytes); } bool HookClearAccess() { static const bool enabled = std::getenv("APS5_NO_HOOK_CLEAR_ACCESS") == nullptr; return enabled; } struct ThreadWriteRanges { std::uint64_t generation = ~std::uint64_t{0}; std::shared_ptr ranges; }; struct ThreadWriteRangesTag {}; bool ThreadSnapshotOverlaps(std::uint64_t address, std::size_t bytes) { auto& copy = ThreadScratch(); const auto generation = publishGeneration.load(std::memory_order_acquire); if (copy.generation != generation) { copy.ranges = pendingWrites.load(std::memory_order_acquire); copy.generation = generation; } return SnapshotOverlaps(copy.ranges.get(), address, bytes); } struct ClearAccessesTag {}; using ClearAccesses = HostThreadSlot; bool ClearAccess(std::uint64_t address, std::size_t bytes) { return StorageTexture::PendingClearOnThread(address, bytes) && LiveUnitsClear(address, bytes) && !ThreadSnapshotOverlaps(address, bytes); } // Whether one merged range of the snapshot contains [address, end) entirely. bool SnapshotCovers(const WriteRanges* snapshot, std::uint64_t address, std::uint64_t end) { if (snapshot == nullptr || snapshot->empty()) return false; const auto it = std::partition_point(snapshot->begin(), snapshot->end(), [&](const auto& range) { return range.second <= address; }); return it != snapshot->end() && it->first <= address && end <= it->second; } bool SnapshotCovers(std::uint64_t address, std::uint64_t end) { const auto snapshot = pendingWrites.load(std::memory_order_acquire); return SnapshotCovers(snapshot.get(), address, end); } // Attribution of the pending-write syncs the hook makes (the [hooksync] line every 10 s, under // APS5_PROFILE_DRAW; APS5_NO_HOOKSYNC_PROFILE=1 leaves only the plain counts). Every sync is charged // to the packet the accessing thread executes and the read site it named (or, when it named none, // its return addresses), together with the noted range it hit, the batch that noted it and the // time waited. A small read (up to 64 KiB) has its bytes compared before and after the wait: a // sync whose bytes come out unchanged although its target batch had not run yet was not needed // for that read (the noted range was larger than what the GPU wrote, or the GPU wrote the same // values), which separates false overlaps from real producer/consumer dependencies; see // HookSyncOutcomes for the cases that prove nothing. All state lives under the GpuMutex, which // the hook holds. // Debug aid: APS5_NO_SYNC_THROUGH=1 makes every pending-write sync a full Sync (SyncThrough and // the attribution's DescribePendingWrite read the same switch). bool SyncThroughEnabled() { static const bool enabled = std::getenv("APS5_NO_SYNC_THROUGH") == nullptr; return enabled; } // Six frames: whether the hook's constructor and FlushGpuWrites are inlined into the GuestMemory // entry decides at which frame the driver caller sits, so enough are kept to see its own caller. constexpr std::size_t HookSyncFrames = 6; struct HookSyncKey { std::uint32_t queue; std::uint32_t opcode; GuestMemory::ReadSite site; std::array frames; bool operator<(const HookSyncKey& other) const { return std::tie(queue, opcode, site, frames) < std::tie(other.queue, other.opcode, other.site, other.frames); } }; // Whether the bytes of a small access changed over the wait, split by the state of the target // batch: only an unchanged access whose target had not run yet (open, or in flight with its fence // unsignaled) shows the sync was not needed; against a signaled fence the copy made before the // wait already held the GPU's values, so unchanged proves nothing. A store (ReadSite::Store) is // counted apart: its sync orders a CPU write after the GPU's, whatever the bytes do. struct HookSyncOutcomes { std::uint64_t unchangedOpen = 0; std::uint64_t unchangedPending = 0; std::uint64_t unchangedSignaled = 0; std::uint64_t changed = 0; std::uint64_t stores = 0; std::uint64_t unchecked = 0; }; struct HookSyncTotals { std::uint64_t count = 0; HookSyncOutcomes outcomes; std::uint64_t rangeBytes = 0; std::uint64_t accessBytes = 0; double waitedMs = 0; }; // Size buckets for the noted ranges and the accesses: <=4K, <=64K, <=1M, <=16M, <=256M, larger. constexpr std::size_t SizeBuckets = 6; constexpr const char* SizeBucketNames[SizeBuckets] = {"<=4K", "<=64K", "<=1M", "<=16M", "<=256M", ">256M"}; std::size_t SizeBucket(std::uint64_t bytes) { if (bytes <= 4096) return 0; if (bytes <= 65536) return 1; if (bytes <= (1u << 20u)) return 2; if (bytes <= (16u << 20u)) return 3; if (bytes <= (256u << 20u)) return 4; return 5; } struct HookSyncStats { std::map byKey; std::uint64_t count = 0, openTargets = 0, signaledTargets = 0, batchesFinished = 0; HookSyncOutcomes outcomes; double waitedMs = 0; std::array rangeBuckets{}; std::array accessBuckets{}; std::chrono::steady_clock::time_point lastReport = std::chrono::steady_clock::now(); }; HookSyncStats& HookSyncs() { static HookSyncStats stats; return stats; } bool HookSyncProfiled() { static const bool profiled = std::getenv("APS5_PROFILE_DRAW") != nullptr && std::getenv("APS5_NO_HOOKSYNC_PROFILE") == nullptr; return profiled; } std::string PacketName(std::uint32_t opcode) { if (opcode == GuestMemory::NoPacket) return "no-packet"; if (opcode == 0xffffu) return "flip"; // 0xfffd is reserved for the deferred-label stores (recordDeferredLabels), once its owner // brackets them with SetCurrentPacket; until then they are charged to the following packet. if (opcode == 0xfffdu) return "deferred-labels"; for (const auto& entry : Pm4::Opcodes) { if (entry.value == opcode) return std::string(entry.name); } char text[24]; std::snprintf(text, sizeof(text), "op 0x%x", opcode); return text; } void ReportHookSyncs(HookSyncStats& stats) { std::vector> hot; hot.reserve(stats.byKey.size()); for (const auto& [key, totals] : stats.byKey) hot.emplace_back(&key, &totals); std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return a.second->waitedMs > b.second->waitedMs; }); std::string report; char text[512]; const auto count = [](std::uint64_t value) { return static_cast(value); }; const auto& o = stats.outcomes; std::snprintf(text, sizeof(text), "[hooksync] %llu pending-write syncs waited %.0f ms (10 s); read bytes after the wait: unchanged %llu (target open %llu, in flight unsignaled %llu, signaled %llu), changed %llu; stores %llu, unchecked %llu; targets: %llu open, %llu already signaled, %llu batches finished; noted range:", count(stats.count), stats.waitedMs, count(o.unchangedOpen + o.unchangedPending + o.unchangedSignaled), count(o.unchangedOpen), count(o.unchangedPending), count(o.unchangedSignaled), count(o.changed), count(o.stores), count(o.unchecked), count(stats.openTargets), count(stats.signaledTargets), count(stats.batchesFinished)); report += text; for (std::size_t i = 0; i < SizeBuckets; ++i) { if (stats.rangeBuckets[i] == 0) continue; std::snprintf(text, sizeof(text), " %s %llu", SizeBucketNames[i], static_cast(stats.rangeBuckets[i])); report += text; } report += "; access:"; for (std::size_t i = 0; i < SizeBuckets; ++i) { if (stats.accessBuckets[i] == 0) continue; std::snprintf(text, sizeof(text), " %s %llu", SizeBucketNames[i], static_cast(stats.accessBuckets[i])); report += text; } report += "; top by wait (queue packet site frames: count/ms, unchanged open/unsignaled/signaled, changed, stores, avg range/access):"; for (std::size_t i = 0; i < hot.size() && i < 10; ++i) { const auto& key = *hot[i].first; const auto& totals = *hot[i].second; const auto& k = totals.outcomes; 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; } AgcDriver::ProfilePrint_nid_no_patch("%s\n", report.c_str()); stats = HookSyncStats{}; } // Wraps one pending-write sync (constructed before it, under the GpuMutex): gathers what the sync // waits for and, in the destructor, the time it took and whether the bytes changed. class HookSyncScope { public: HookSyncScope(const Recorder& recorder, std::uint64_t address, std::size_t bytes) : enabled(HookSyncProfiled()), address(address), bytes(bytes) { if (!enabled) return; info = recorder.DescribePendingWrite(address, bytes); const auto packet = GuestMemory::CurrentPacket(); key = HookSyncKey{packet.queue, packet.opcode, GuestMemory::CurrentReadSite(), {}}; // Frame 0 is the hook's caller (the GuestMemory entry, or the driver code when the entry // was inlined); the driver code that made the access is one of the next frames. GuestMemory::CaptureCallerOffsets(key.frames, 1); // The access's bytes are copied raw: a Read here would re-enter the hook. The same access // check the accessing code makes guards the copy; a range that fails it is left unchecked. // A store's bytes are not compared (counted as a store instead). if (!GuestMemory::WritesGuestMemory(key.site) && bytes <= CompareLimit && GuestMemory::Accessible(reinterpret_cast(address), bytes)) { before.resize(bytes); std::memcpy(before.data(), reinterpret_cast(address), bytes); } start = std::chrono::steady_clock::now(); } ~HookSyncScope() { if (!enabled) return; const auto now = std::chrono::steady_clock::now(); const auto ms = std::chrono::duration(now - start).count(); auto& stats = HookSyncs(); auto& totals = stats.byKey[key]; ++totals.count; totals.waitedMs += ms; totals.accessBytes += bytes; ++stats.count; stats.waitedMs += ms; stats.accessBuckets[SizeBucket(bytes)] += 1; if (info.has_value()) { const auto rangeBytes = info->rangeEnd - info->rangeBegin; totals.rangeBytes += rangeBytes; stats.rangeBuckets[SizeBucket(rangeBytes)] += 1; if (info->open) ++stats.openTargets; if (info->signaled) ++stats.signaledTargets; stats.batchesFinished += info->batchesToFinish; } // One outcome per sync, on both the key's and the interval's counters. const auto outcome = [&]() -> std::uint64_t HookSyncOutcomes::* { if (GuestMemory::WritesGuestMemory(key.site)) return &HookSyncOutcomes::stores; if (before.empty() || !GuestMemory::Accessible(reinterpret_cast(address), bytes)) return &HookSyncOutcomes::unchecked; if (std::memcmp(before.data(), reinterpret_cast(address), bytes) != 0) return &HookSyncOutcomes::changed; // A target already signaled (or no target found: the batch is finishing) had run // before the copy, so its unchanged bytes are not evidence of a false overlap. if (!info.has_value() || info->signaled) return &HookSyncOutcomes::unchangedSignaled; return info->open ? &HookSyncOutcomes::unchangedOpen : &HookSyncOutcomes::unchangedPending; }(); ++(totals.outcomes.*outcome); ++(stats.outcomes.*outcome); if (now - stats.lastReport > std::chrono::seconds(10)) ReportHookSyncs(stats); } HookSyncScope(const HookSyncScope&) = delete; HookSyncScope& operator=(const HookSyncScope&) = delete; private: static constexpr std::size_t CompareLimit = 65536; bool enabled; std::uint64_t address; std::size_t bytes; std::optional info; HookSyncKey key{}; std::vector before; std::chrono::steady_clock::time_point start; }; // Attribution of the hook's recorded-store syncs (source 2: a pending image's write-back or a unit // publish was recorded for the access and SyncThrough waits for it), the [hooksync] recorded-store // line every 10 s under the same switch as HookSyncScope: per (queue, packet, read site), the syncs, // their wait, the batches in flight at the sync, the C4 classification of the access (every 64 KiB // block CPU-written since the overlapping images' generations: the store would not change a byte // the CPU reads), whether the bytes changed over the wait, whether the images overlapped had a // consumer proof within StorageTexture::DeadImagePresents presents, and the accesses the C4 skip // took instead of a flush (with the images that left the registry there as an empty write-back // would have left them). The skips are counted without the GpuMutex (their own mutex); the syncs // under it. struct RecordedStoreTotals { std::uint64_t count = 0; double waitedMs = 0; std::uint64_t batchesFinished = 0; std::uint64_t cpuWrittenYes = 0, cpuWrittenNo = 0, unclassified = 0, publishOnly = 0; std::uint64_t changed = 0, unchanged = 0, unchecked = 0; std::uint64_t imagesDead = 0, imagesLive = 0; std::uint64_t skipped = 0, flushed = 0, evicted = 0; }; struct RecordedStoreStats { AgcDriver::Mutex mutex; std::map byKey; RecordedStoreTotals totals; std::chrono::steady_clock::time_point lastReport = std::chrono::steady_clock::now(); }; RecordedStoreStats& RecordedStoreSyncs() { static RecordedStoreStats stats; return stats; } void ReportRecordedStoreSyncs(RecordedStoreStats& stats) { std::vector> hot; for (const auto& [key, totals] : stats.byKey) hot.emplace_back(&key, &totals); std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return std::tie(a.second->waitedMs, a.second->skipped) > std::tie(b.second->waitedMs, b.second->skipped); }); const auto count = [](std::uint64_t value) { return static_cast(value); }; const auto& t = stats.totals; const auto skips = StorageTexture::TakeHookSkipCounts(); char text[640]; std::snprintf(text, sizeof(text), "[hooksync] recorded-store syncs (10 s): %llu waited %.0f ms, %llu batches in flight at them; skipped (cpu-written blocks) %llu / flushed %llu / evicted stale %llu; flushed later after a skip %llu (by the same site %llu); C4 every block CPU-written: yes %llu / no %llu / unclassified %llu (publish only %llu); bytes after the wait: changed %llu, unchanged %llu, unchecked %llu; images overlapped: dead %llu / live %llu (no consumer proof for %llu presents); by queue packet site (count/ms, skipped, cpu-written yes/no, changed/unchanged, dead/live):", count(t.count), t.waitedMs, count(t.batchesFinished), count(t.skipped), count(t.flushed), count(t.evicted), count(skips.flushedAfterSkip), count(skips.flushedAfterSkipSameSite), count(t.cpuWrittenYes), count(t.cpuWrittenNo), count(t.unclassified), count(t.publishOnly), count(t.changed), count(t.unchanged), count(t.unchecked), count(t.imagesDead), count(t.imagesLive), count(StorageTexture::DeadImagePresents)); std::string report = text; for (std::size_t i = 0; i < hot.size() && i < 10; ++i) { const auto& key = *hot[i].first; const auto& k = *hot[i].second; 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; } AgcDriver::ProfilePrint_nid_no_patch("%s\n", report.c_str()); stats.byKey.clear(); stats.totals = {}; } // The key of the access the hook handles now: always inlined into FlushForAccess so that frame 0 // is the hook's caller for the skip counters and the sync scope alike, whatever the inliner does // with the scope's constructor. [[gnu::always_inline]] inline HookSyncKey RecordedStoreKey() { const auto packet = GuestMemory::CurrentPacket(); HookSyncKey key{packet.queue, packet.opcode, GuestMemory::CurrentReadSite(), {}}; GuestMemory::CaptureCallerOffsets(key.frames, 1); return key; } void CountRecordedStoreSkip(const HookSyncKey& key, std::size_t evicted) { auto& stats = RecordedStoreSyncs(); std::lock_guard lock(stats.mutex); for (auto* totals : {&stats.byKey[key], &stats.totals}) { ++totals->skipped; totals->evicted += evicted; } const auto now = std::chrono::steady_clock::now(); if (now - stats.lastReport > std::chrono::seconds(10)) { stats.lastReport = now; ReportRecordedStoreSyncs(stats); } } class RecordedStoreSyncScope { public: RecordedStoreSyncScope(const Recorder& recorder, std::uint64_t address, std::size_t bytes, const StorageTexture::AccessClassification& classification, bool stored, const HookSyncKey& key) : enabled(HookSyncProfiled()), address(address), bytes(bytes), classification(classification), stored(stored), key(key) { if (!enabled) return; batchesInFlight = recorder.InFlightBatches(); if (!GuestMemory::WritesGuestMemory(key.site) && bytes <= CompareLimit && GuestMemory::Accessible(reinterpret_cast(address), bytes)) { before.resize(bytes); std::memcpy(before.data(), reinterpret_cast(address), bytes); } start = std::chrono::steady_clock::now(); } ~RecordedStoreSyncScope() { if (!enabled) return; const auto now = std::chrono::steady_clock::now(); const auto ms = std::chrono::duration(now - start).count(); auto& stats = RecordedStoreSyncs(); std::lock_guard lock(stats.mutex); const auto add = [&](RecordedStoreTotals& totals) { ++totals.count; totals.waitedMs += ms; totals.batchesFinished += batchesInFlight; if (stored) ++totals.flushed; if (classification.images == 0) ++totals.publishOnly; else if (!classification.checked) ++totals.unclassified; else ++(classification.allCpuWritten ? totals.cpuWrittenYes : totals.cpuWrittenNo); totals.imagesDead += classification.dead; totals.imagesLive += classification.live; if (before.empty() || !GuestMemory::Accessible(reinterpret_cast(address), bytes)) ++totals.unchecked; else if (std::memcmp(before.data(), reinterpret_cast(address), bytes) != 0) ++totals.changed; else ++totals.unchanged; }; add(stats.byKey[key]); add(stats.totals); if (now - stats.lastReport > std::chrono::seconds(10)) { stats.lastReport = now; ReportRecordedStoreSyncs(stats); } } RecordedStoreSyncScope(const RecordedStoreSyncScope&) = delete; RecordedStoreSyncScope& operator=(const RecordedStoreSyncScope&) = delete; private: static constexpr std::size_t CompareLimit = 65536; bool enabled; std::uint64_t address; std::size_t bytes; StorageTexture::AccessClassification classification; bool stored; HookSyncKey key; std::size_t batchesInFlight = 0; std::vector before; std::chrono::steady_clock::time_point start; }; // GuestMemory flush hook: a CPU access to memory that recorded GPU work will write waits for that // work first; then storage image results pending for the range are stored. The recorder is only // dereferenced under the GpuMutex (it is destroyed with its device under that lock). void FlushForAccess(std::uint64_t address, std::size_t bytes) { if (DrawProfiled()) hookCalls.fetch_add(1, std::memory_order_relaxed); // A label this worker queued but has not recorded writes the range: in queue order the label // precedes this access, so the group is recorded first (it then notes the range as a pending // write of the open batch, and the check below syncs on it like any recorded store). Not from // inside a completion action (a write-back store made while a batch is reaped): the record // would reap nested in the reap in progress, landing later batches' write-backs before the // rest of this one's, and this queue's queued label follows every batch of its own in flight // anyway, so the write-back landing first is the order the hardware gives. if (QueuedLabelsOnThread::Get() && QueuedLabelOverlaps(address, bytes)) { if (completionDepth() != 0 && HookCompletionGuard()) { queuedLabelHookInCompletion.fetch_add(1, std::memory_order_relaxed); } else if (auto* record = queuedLabelRecorder.load(std::memory_order_acquire); record != nullptr) { queuedLabelHookRecords.fetch_add(1, std::memory_order_relaxed); record(); } } if (HookClearAccess() && HookSnapshotEnabled() && !HookFlushCpuBlocks() && ClearAccess(address, bytes) && !(GuestMemory::CurrentReadSite() == GuestMemory::ReadSite::HostWrite && AnyPublishInProgress())) { ClearAccesses::Set(ClearAccesses::Get() + 1); return; } if (!HookSnapshotEnabled() || SnapshotOverlaps(address, bytes)) { hookLocks.fetch_add(1, std::memory_order_relaxed); GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Hook); std::lock_guard gpu(GuestMemory::GpuMutex()); if (auto* recorder = Recorder::Active(); recorder != nullptr && recorder->PendingWriteOverlaps(address, bytes)) { const HookSyncScope attribution(*recorder, address, bytes); Recorder::CountSync(1); // The wait runs without the mutex when this acquisition is the outermost one (a stage-A // read, a game thread); the recorder is not dereferenced after the call. recorder->SyncThrough(address, bytes, true); } } const auto site = GuestMemory::CurrentReadSite(); const auto scope = site != GuestMemory::ReadSite::Store ? PublishScope::Whole : PublishScope::PartialUnits; const bool waited = completionDepth() != 0; bool published = false; // The classification is made before the store (the store changes what it measures); profile only. StorageTexture::AccessClassification classification{}; if (HookSyncProfiled()) StorageTexture::ClassifyAccess(address, bytes, classification); // C4: an access whose every 64 KiB block the CPU wrote since the overlapping images' generations // reads the same bytes with or without their store (the store keeps those blocks), so the // images stay pending (short of the layers the store would have left empty-handed anyway) and // only the unit shadows over the range are published; with no image over the range that // publish is all FlushPending would do (one registry scan, not two). bool stored = false; std::size_t images = 0, evicted = 0; const bool deferred = StorageTexture::DeferToMirror(address, bytes); const bool kept = !deferred && !HookFlushCpuBlocks() && StorageTexture::AccessKeptByCpu(address, bytes, &images, &evicted); if (deferred || kept || (images == 0 && !HookFlushCpuBlocks())) { stored = StorageTexture::WaitForFlushing(address, bytes); published = StorageTexture::PublishShadowsOnly(address, bytes, scope, "memory access", waited); if (kept && HookSyncProfiled()) CountRecordedStoreSkip(RecordedStoreKey(), evicted); } else { stored = StorageTexture::FlushPending(address, bytes, nullptr, "memory access", scope, &published, waited); } const bool publishInProgress = site == GuestMemory::ReadSite::HostWrite && AnyPublishInProgress(); if (stored || published || publishInProgress || (completionDepth() == 0 && SnapshotOverlaps(address, bytes))) { // Stores into imported memory were only recorded; the CPU is about to read them. The wait // targets the batch holding them (the open one: SyncThrough submits it) and runs with the // mutex released when this acquisition is the outermost; a nested hook waits locked through // that batch ([lock] 'locked GPU waits'). Inside a completion action the store must land // before the completing batch's CPU write-back (an older result under a newer one), which // only the full Sync() gives there. GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Hook); std::lock_guard gpu(GuestMemory::GpuMutex()); if (auto* recorder = Recorder::Active(); recorder != nullptr) { const RecordedStoreSyncScope attribution(*recorder, address, bytes, classification, stored, HookSyncProfiled() ? RecordedStoreKey() : HookSyncKey{}); Recorder::CountSync(2); if (HookFullSync() || completionDepth() != 0) recorder->Sync(); else recorder->SyncThrough(address, bytes, true); } } } } static bool CheckpointMarkersEnabled() { static const bool enabled = std::getenv("APS5_GPU_CHECKPOINTS") != nullptr; return enabled; } struct CheckpointMarkerDevice { VkDevice device = VK_NULL_HANDLE; PFN_vkCmdWriteBufferMarkerAMD write = nullptr; PFN_vkDestroyBuffer destroyBuffer = nullptr; PFN_vkFreeMemory freeMemory = nullptr; PFN_vkUnmapMemory unmapMemory = nullptr; VkBuffer buffer = VK_NULL_HANDLE; VkDeviceMemory memory = VK_NULL_HANDLE; const void* mapping = nullptr; }; static CheckpointMarkerDevice& CheckpointMarkerState() { static CheckpointMarkerDevice state; return state; } static bool PrepareCheckpointMarker(const Context& context) { if (!CheckpointMarkersEnabled()) return false; auto& state = CheckpointMarkerState(); if (state.device == context.device && state.buffer != VK_NULL_HANDLE) return state.write != nullptr; if (state.device != VK_NULL_HANDLE && state.device != context.device) return false; if (context.device == VK_NULL_HANDLE || context.deviceProc == nullptr) return false; auto write = reinterpret_cast(CommandThunk("vkCmdWriteBufferMarkerAMD", context.deviceProc(context.device, "vkCmdWriteBufferMarkerAMD"), context.device)); if (write == nullptr) return false; auto destroyBuffer = reinterpret_cast(context.deviceProc(context.device, "vkDestroyBuffer")); auto freeMemory = reinterpret_cast(context.deviceProc(context.device, "vkFreeMemory")); auto unmapMemory = reinterpret_cast(context.deviceProc(context.device, "vkUnmapMemory")); if (destroyBuffer == nullptr || freeMemory == nullptr || unmapMemory == nullptr) return false; if (state.buffer == VK_NULL_HANDLE) { auto createBuffer = reinterpret_cast(context.deviceProc(context.device, "vkCreateBuffer")); auto getRequirements = reinterpret_cast(context.deviceProc(context.device, "vkGetBufferMemoryRequirements")); auto allocateMemory = reinterpret_cast(context.deviceProc(context.device, "vkAllocateMemory")); auto bindMemory = reinterpret_cast(context.deviceProc(context.device, "vkBindBufferMemory")); auto mapMemory = reinterpret_cast(context.deviceProc(context.device, "vkMapMemory")); if (createBuffer == nullptr || getRequirements == nullptr || allocateMemory == nullptr || bindMemory == nullptr || mapMemory == nullptr) return false; VkBufferCreateInfo bufferInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bufferInfo.size = 2 * sizeof(std::uint32_t); bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VkBuffer buffer = VK_NULL_HANDLE; if (createBuffer(context.device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS || buffer == VK_NULL_HANDLE) return false; VkMemoryRequirements requirements{}; getRequirements(context.device, buffer, &requirements); std::uint32_t memoryType = context.memory.memoryTypeCount; const VkMemoryPropertyFlags flags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; for (std::uint32_t i = 0; i < context.memory.memoryTypeCount; ++i) { if ((requirements.memoryTypeBits & (1u << i)) != 0 && (context.memory.memoryTypes[i].propertyFlags & flags) == flags) { memoryType = i; break; } } if (memoryType >= context.memory.memoryTypeCount) { auto destroyBuffer = reinterpret_cast(context.deviceProc(context.device, "vkDestroyBuffer")); if (destroyBuffer != nullptr) destroyBuffer(context.device, buffer, nullptr); return false; } VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; allocation.allocationSize = requirements.size; allocation.memoryTypeIndex = memoryType; VkDeviceMemory memory = VK_NULL_HANDLE; if (allocateMemory(context.device, &allocation, nullptr, &memory) != VK_SUCCESS || memory == VK_NULL_HANDLE) { auto destroyBuffer = reinterpret_cast(context.deviceProc(context.device, "vkDestroyBuffer")); if (destroyBuffer != nullptr) destroyBuffer(context.device, buffer, nullptr); return false; } if (bindMemory(context.device, buffer, memory, 0) != VK_SUCCESS) { auto destroyBuffer = reinterpret_cast(context.deviceProc(context.device, "vkDestroyBuffer")); auto freeMemory = reinterpret_cast(context.deviceProc(context.device, "vkFreeMemory")); if (destroyBuffer != nullptr) destroyBuffer(context.device, buffer, nullptr); if (freeMemory != nullptr) freeMemory(context.device, memory, nullptr); return false; } void* mapping = nullptr; if (mapMemory(context.device, memory, 0, bufferInfo.size, 0, &mapping) != VK_SUCCESS || mapping == nullptr) { auto destroyBuffer = reinterpret_cast(context.deviceProc(context.device, "vkDestroyBuffer")); auto freeMemory = reinterpret_cast(context.deviceProc(context.device, "vkFreeMemory")); if (destroyBuffer != nullptr) destroyBuffer(context.device, buffer, nullptr); if (freeMemory != nullptr) freeMemory(context.device, memory, nullptr); return false; } std::memset(mapping, 0, bufferInfo.size); state.buffer = buffer; state.memory = memory; state.mapping = mapping; } state.device = context.device; state.write = write; state.destroyBuffer = destroyBuffer; state.freeMemory = freeMemory; state.unmapMemory = unmapMemory; return state.write != nullptr && state.buffer != VK_NULL_HANDLE; } constexpr VkDeviceSize CheckpointMarkerSerialOffset = 0; constexpr VkDeviceSize CheckpointMarkerTokenOffset = sizeof(std::uint32_t); void WriteCheckpointMarker(const Context& context, VkCommandBuffer commands, std::uint64_t token, std::uint32_t queue) { if (!CheckpointMarkersEnabled()) return; if (queue != 0) return; if (commands == VK_NULL_HANDLE || token == 0) return; try { if (!PrepareCheckpointMarker(context)) return; auto& state = CheckpointMarkerState(); state.write(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, state.buffer, CheckpointMarkerTokenOffset, static_cast(token)); } catch (...) { } } void WriteNvCheckpointToken(const Context& context, VkCommandBuffer commands, std::uint64_t token, std::uint32_t queue) { if (!CheckpointMarkersEnabled()) return; if (queue != 0) return; if (commands == VK_NULL_HANDLE || token == 0) return; try { if (context.device == VK_NULL_HANDLE || context.deviceProc == nullptr) return; auto setCheckpoint = reinterpret_cast(CommandThunk("vkCmdSetCheckpointNV", context.deviceProc(context.device, "vkCmdSetCheckpointNV"), context.device)); if (setCheckpoint == nullptr) return; EmitNvCheckpointToken(commands, static_cast(token), setCheckpoint); } catch (...) { } } void WriteCheckpointSerial(const Context& context, VkCommandBuffer commands, std::uint64_t serial, std::uint32_t queue) { if (!CheckpointMarkersEnabled()) return; if (queue != 0) return; if (commands == VK_NULL_HANDLE || serial == 0) return; try { if (!PrepareCheckpointMarker(context)) return; auto& state = CheckpointMarkerState(); state.write(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, state.buffer, CheckpointMarkerSerialOffset, static_cast(serial)); } catch (...) { } } std::uint32_t LastCheckpointMarkerSerial() noexcept { const void* mapping = CheckpointMarkerState().mapping; if (mapping == nullptr) return 0; std::uint32_t serial = 0; std::memcpy(&serial, static_cast(mapping) + CheckpointMarkerSerialOffset, sizeof(serial)); return serial; } std::uint32_t LastCheckpointMarkerToken() noexcept { const void* mapping = CheckpointMarkerState().mapping; if (mapping == nullptr) return 0; std::uint32_t token = 0; std::memcpy(&token, static_cast(mapping) + CheckpointMarkerTokenOffset, sizeof(token)); return token; } void WriteCheckpointSentinel(const Context& context, VkCommandBuffer commands) { if (!CheckpointMarkersEnabled()) return; if (commands == VK_NULL_HANDLE) return; try { if (!PrepareCheckpointMarker(context)) return; auto& state = CheckpointMarkerState(); state.write(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, state.buffer, CheckpointMarkerSerialOffset, 0); state.write(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, state.buffer, CheckpointMarkerTokenOffset, 0); } catch (...) { } } void ResetCheckpointSnapshots() noexcept { AgcDriver::SubmissionSnapshots::DeviceSnapshots().Reset(); } void TeardownCheckpointMarkers() noexcept { ResetCheckpointSnapshots(); auto& state = CheckpointMarkerState(); if (state.device == VK_NULL_HANDLE) return; try { if (state.mapping != nullptr && state.unmapMemory != nullptr) state.unmapMemory(state.device, state.memory); if (state.buffer != VK_NULL_HANDLE && state.destroyBuffer != nullptr) state.destroyBuffer(state.device, state.buffer, nullptr); if (state.memory != VK_NULL_HANDLE && state.freeMemory != nullptr) state.freeMemory(state.device, state.memory, nullptr); } catch (...) { } state = CheckpointMarkerDevice{}; } struct Recorder::ProgressWatcher { std::atomic submitted{0}; std::atomic stop{false}; std::atomic wakes{0}; std::thread thread; ProgressWatcher(VkDevice device, VkSemaphore timeline, PFN_vkWaitSemaphoresKHR waitSemaphores, PFN_vkGetSemaphoreCounterValueKHR counterValue) { thread = std::thread([this, device, timeline, waitSemaphores, counterValue] { CpuTopology::PinHelperThread("GPU progress watcher"); std::uint64_t seen = 0; for (;;) { const auto token = wakes.load(std::memory_order_acquire); if (stop.load(std::memory_order_acquire)) return; if (submitted.load(std::memory_order_acquire) <= seen) { wakes.wait(token, std::memory_order_acquire); continue; } const std::uint64_t target = seen + 1; VkSemaphoreWaitInfoKHR info{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO_KHR}; info.semaphoreCount = 1; info.pSemaphores = &timeline; info.pValues = ⌖ const auto result = waitSemaphores(device, &info, 50'000'000ull); if (result == VK_TIMEOUT) continue; if (result != VK_SUCCESS) { std::fprintf(stderr, "[gpu] progress watcher: vkWaitSemaphoresKHR failed (%d), watcher stops\n", static_cast(result)); return; } std::uint64_t value = target; if (counterValue(device, timeline, &value) != VK_SUCCESS) value = target; seen = std::max(target, value); KernelWakeSleepers_nid_no_patch(); } }); } void Submitted(std::uint64_t serial) { submitted.store(serial, std::memory_order_release); wakes.fetch_add(1, std::memory_order_release); wakes.notify_one(); } ~ProgressWatcher() { stop.store(true, std::memory_order_release); wakes.fetch_add(1, std::memory_order_release); wakes.notify_one(); thread.join(); } }; Recorder::Recorder(const Context& context, bool timelineSemaphores, bool deferredBatches, std::uint32_t queueFamily, WorkBudget::Limits limits) : context(context), id(nextRecorderId.fetch_add(1)), budget(limits), queueFamily(queueFamily) { if (deferredBatches && context.deviceProc != nullptr) { ResolveCommandFunctions(realCommands, context.device, context.deviceProc); executor = makeExecutor(); deferring = true; } if (context.deviceProc != nullptr) { if (!deferring) ResolveCommandFunctions(realCommands, context.device, context.deviceProc); realResolved = true; overlayListed(); } { std::lock_guard lock(liveRecordersMutex); liveRecorders.push_back(id); } // Idempotent: the same hook for every recorder (the deferred lists are per thread, not per recorder). GuestMemory::SetGpuUnlockHook(&ReleaseDeferredKeeps); if (ProcTable() && context.deviceProc != nullptr) { getFenceStatus = context.Function("vkGetFenceStatus"); resetFences = context.Function("vkResetFences"); waitForFences = context.Function("vkWaitForFences"); cmdUpdateBuffer = context.Function("vkCmdUpdateBuffer"); beginCommandBuffer = context.Function("vkBeginCommandBuffer"); endCommandBuffer = context.Function("vkEndCommandBuffer"); queueSubmit = context.Function("vkQueueSubmit"); cmdPipelineBarrier = context.Function("vkCmdPipelineBarrier"); cmdBeginQuery = context.Function("vkCmdBeginQuery"); cmdEndQuery = context.Function("vkCmdEndQuery"); cmdResetQueryPool = context.Function("vkCmdResetQueryPool"); cmdCopyQueryPoolResults = context.Function("vkCmdCopyQueryPoolResults"); cmdPushConstants = context.Function("vkCmdPushConstants"); cmdDispatch = context.Function("vkCmdDispatch"); } if (!timelineSemaphores) return; // The timeline starts at 0 and every Submit signals its serial (1, 2, ...): a value that only // grows, so a thread waiting for it outside the mutex can never observe a reset or a reused // handle (the batch fences are pooled and reset in release()). A failure here only disables the // unlocked waits; the locked Sync path still works. VkSemaphoreTypeCreateInfoKHR type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR}; type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR; type.initialValue = 0; VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; const auto result = context.Function("vkCreateSemaphore")(context.device, &info, nullptr, &timeline); if (result != VK_SUCCESS) { std::fprintf(stderr, "[gpu] timeline semaphore creation failed (Vulkan result %d); drains wait under the GPU mutex\n", static_cast(result)); timeline = VK_NULL_HANDLE; return; } fenceless = std::getenv("APS5_BATCH_FENCES") == nullptr; if (ProcTable() && context.deviceProc != nullptr) { getSemaphoreCounterValue = context.Function("vkGetSemaphoreCounterValueKHR"); } } Recorder::~Recorder() { for (;;) { try { Sync(); break; } catch (const std::exception& error) { std::fprintf(stderr, "[gpu] recorder teardown: %s\n", error.what()); if (inFlight.empty()) break; } } ForgetHtileMasks_nid_no_patch(id); latch.Shutdown(); if (executor != nullptr) executor->Shutdown(); progressWatcher.reset(); holdKept.clear(); if (activeRecorder == this) { activeRecorder = nullptr; pendingWrites.store(nullptr, std::memory_order_release); publishGeneration.fetch_add(1, std::memory_order_release); pendingLabelSince.store(NoPendingLabel, std::memory_order_release); completionLabels.store(0, std::memory_order_release); completionStores.store(0, std::memory_order_release); writeBackCompletions.store(0, std::memory_order_release); workSinceSubmit.store(0, std::memory_order_release); } { // A thread that released the mutex around a wait on this recorder re-checks the id when it // retakes the mutex and touches nothing then. That check is only sound while the device // (and so this destructor) is torn down under the GpuMutex, as the driver's drain and // failure paths do; a worker dropping the last device reference after releasing its lock // would run this without the mutex, concurrently with a relocked waiter. std::lock_guard lock(liveRecordersMutex); liveRecorders.erase(std::remove(liveRecorders.begin(), liveRecorders.end(), id), liveRecorders.end()); } // Sync() above completed every batch, so every timeline wait in progress on this recorder // returns now; the semaphore is destroyed only once they all left it. while (WaitersOf(id).load(std::memory_order_acquire) != 0) std::this_thread::yield(); // The kept objects of every batch this thread finished (Sync() above included) belong to the // device that is going away: destroyed now, here (no hand-off: nothing should stay in flight // behind this thread); the release thread is then stopped and joined (it drains its queue // first, holding no mutex this thread holds: the destructors take only their caches' own // mutexes, which order after the GpuMutex), and the releases still in progress inline on // other threads (an unlock hook that found the queue stopping or full) are waited for before // the caller destroys the device. The count is global: a newer recorder's batches (device // replacement) are waited for too, which only prolongs the spin. if (!DeferredBatches().empty()) DestroyDeferred(TakeDeferred(), false); JoinReleaseThread(); while (deferredPending.load(std::memory_order_acquire) != 0) std::this_thread::yield(); { // Unlocked lookups stop before `labels` is destroyed (after this body). std::lock_guard tableLock(labelTableMutex); if (labelTableOwner == this) labelTableOwner = nullptr; } if (meshArgumentPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, meshArgumentPipeline, nullptr); if (meshArgumentLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, meshArgumentLayout, nullptr); if (changedCopyPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, changedCopyPipeline, nullptr); if (changedCopyLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, changedCopyLayout, nullptr); if (boundChangedCopyPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, boundChangedCopyPipeline, nullptr); if (boundChangedCopyLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, boundChangedCopyLayout, nullptr); if (boundChangedCopySetLayout != VK_NULL_HANDLE) context.Function("vkDestroyDescriptorSetLayout")(context.device, boundChangedCopySetLayout, nullptr); if (sampleCounterState > 0) { samplesPassed.store(SamplesTotal(), std::memory_order_release); if (samplePools != nullptr) std::static_pointer_cast(samplePools)->close(); if (segmentPools != nullptr) std::static_pointer_cast(segmentPools)->close(); context.Function("vkDestroyPipeline")(context.device, samplePipeline, nullptr); context.Function("vkDestroyPipelineLayout")(context.device, sampleLayout, nullptr); context.Function("vkDestroyPipeline")(context.device, dumpPipeline, nullptr); context.Function("vkDestroyPipelineLayout")(context.device, dumpLayout, nullptr); sampleCounter.reset(); } if (dispatchArgumentPipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, dispatchArgumentPipeline, nullptr); if (dispatchArgumentLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, dispatchArgumentLayout, nullptr); for (const auto fence : spare) context.Function("vkDestroyFence")(context.device, fence, nullptr); spare.clear(); for (const auto pool : sparePools) context.Function("vkDestroyQueryPool")(context.device, pool, nullptr); sparePools.clear(); // Sync() above waited for every batch, so no submission still signals the timeline. if (timeline != VK_NULL_HANDLE) context.Function("vkDestroySemaphore")(context.device, timeline, nullptr); timeline = VK_NULL_HANDLE; executor.reset(); } std::optional Recorder::PendingLabelSince() { const auto since = pendingLabelSince.load(std::memory_order_acquire); if (since == NoPendingLabel) return std::nullopt; return std::chrono::steady_clock::time_point(std::chrono::steady_clock::duration(since)); } std::uint64_t Recorder::WriteGeneration() { return writeGeneration.load(std::memory_order_acquire); } std::uint64_t Recorder::PublishGeneration() { return publishGeneration.load(std::memory_order_acquire); } std::uint64_t Recorder::PendingCompletionLabels() { return completionLabels.load(std::memory_order_acquire); } std::uint64_t Recorder::PendingCompletionStores() { return completionStores.load(std::memory_order_acquire); } std::uint64_t Recorder::PendingWriteBackCompletions() { return writeBackCompletions.load(std::memory_order_acquire); } std::uint64_t Recorder::RecordedWorkSinceSubmit() { return workSinceSubmit.load(std::memory_order_relaxed); } bool Recorder::NoteGuestWork(VkCommandBuffer commands) { if (open == nullptr || open->commands != commands) return false; open->guestWork = true; return true; } void Recorder::CountRecordedWork() { workSinceSubmit.fetch_add(1, std::memory_order_relaxed); } namespace { bool sameBits(float left, float right) { return std::bit_cast(left) == std::bit_cast(right); } template bool sameBits(const std::array& left, const std::array& right) { for (std::size_t index = 0; index < Count; ++index) { if (!sameBits(left[index], right[index])) return false; } return true; } bool sameBits(const VkViewport& left, const VkViewport& right) { return sameBits(left.x, right.x) && sameBits(left.y, right.y) && sameBits(left.width, right.width) && sameBits(left.height, right.height) && sameBits(left.minDepth, right.minDepth) && sameBits(left.maxDepth, right.maxDepth); } bool sameBits(const VkRect2D& left, const VkRect2D& right) { return left.offset.x == right.offset.x && left.offset.y == right.offset.y && left.extent.width == right.extent.width && left.extent.height == right.extent.height; } } std::uint32_t CommandState::DynamicSlots(std::span states) { std::uint32_t slots = 0; for (const auto state : states) { switch (state) { case VK_DYNAMIC_STATE_VIEWPORT: slots |= Mask(Viewport); break; case VK_DYNAMIC_STATE_SCISSOR: slots |= Mask(Scissor); break; case VK_DYNAMIC_STATE_DEPTH_BIAS: slots |= Mask(DepthBias); break; case VK_DYNAMIC_STATE_DEPTH_BOUNDS: slots |= Mask(DepthBounds); break; case VK_DYNAMIC_STATE_CULL_MODE: slots |= Mask(CullMode); break; case VK_DYNAMIC_STATE_FRONT_FACE: slots |= Mask(FrontFace); break; case VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE: slots |= Mask(DepthTest); break; case VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE: slots |= Mask(DepthWrite); break; case VK_DYNAMIC_STATE_DEPTH_COMPARE_OP: slots |= Mask(DepthCompare); break; case VK_DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE: slots |= Mask(DepthBoundsTest); break; case VK_DYNAMIC_STATE_STENCIL_TEST_ENABLE: slots |= Mask(StencilTest); break; case VK_DYNAMIC_STATE_STENCIL_OP: slots |= Mask(StencilOpFront) | Mask(StencilOpBack); break; case VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK: slots |= Mask(CompareMaskFront) | Mask(CompareMaskBack); break; case VK_DYNAMIC_STATE_STENCIL_WRITE_MASK: slots |= Mask(WriteMaskFront) | Mask(WriteMaskBack); break; case VK_DYNAMIC_STATE_STENCIL_REFERENCE: slots |= Mask(ReferenceFront) | Mask(ReferenceBack); break; case VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT: slots |= Mask(ColorWriteMask); break; case VK_DYNAMIC_STATE_DEPTH_BIAS_ENABLE: slots |= Mask(DepthBiasEnable); break; default: throw std::runtime_error("AGC graphics: a pipeline declares a dynamic state the command tracker does not follow"); } } return slots; } void CommandState::Begin(VkCommandBuffer recording, bool suppress, const CommandFunctions* table) { commands = recording; functions = table; trackable = suppress ? ~0u : 0u; Invalidate(); } void CommandState::Invalidate() noexcept { valid = 0; overwritten = 0; dynamicSlots = 0; pipeline = VK_NULL_HANDLE; pipelineKnown = false; } template void CommandState::apply(Slot slot, TValue CommandState::*field, const TValue& value, TEqual equal, TEmit emit) { if (Known(slot) && equal(this->*field, value)) return; emit(); this->*field = value; wrote(Mask(slot)); } template void CommandState::applyFaces(Slot first, VkStencilFaceFlags faces, std::array CommandState::*field, const TValue& value, TEmit emit) { VkStencilFaceFlags needed = 0; for (std::uint32_t face = 0; face < 2; ++face) { const VkStencilFaceFlags bit = 1u << face; if ((faces & bit) == 0) continue; if (!Known(static_cast(first + face)) || !((this->*field)[face] == value)) needed |= bit; } if (needed == 0) return; emit(needed); for (std::uint32_t face = 0; face < 2; ++face) { if ((needed & (1u << face)) == 0) continue; (this->*field)[face] = value; wrote(Mask(static_cast(first + face))); } } void CommandState::BindPipeline(const Context& context, VkPipeline bound, std::uint32_t slots) { if (pipelineKnown && pipeline == bound && dynamicSlots == slots && (overwritten & ~slots) == 0) return; context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdBindPipeline, &DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline")(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, bound); pipeline = bound; pipelineKnown = trackable != 0 && bound != VK_NULL_HANDLE; dynamicSlots = slots; valid &= slots; overwritten = 0; } void CommandState::SetViewport(const Context& context, const VkViewport& value) { apply(Viewport, &CommandState::viewport, value, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetViewport, &DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &value); }); } void CommandState::SetScissor(const Context& context, const VkRect2D& value) { apply(Scissor, &CommandState::scissor, value, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetScissor, &DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &value); }); } void CommandState::SetViewports(const Context& context, std::span viewports, std::span scissors) { Require(!viewports.empty() && viewports.size() == scissors.size(), "every viewport needs a scissor"); const auto count = static_cast(viewports.size()); context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetViewport, &DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, count, viewports.data()); context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetScissor, &DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, count, scissors.data()); viewport = viewports.front(); scissor = scissors.front(); wrote(Mask(Viewport) | Mask(Scissor)); } void CommandState::SetDepthBias(const Context& context, float constant, float clamp, float slope) { const std::array bias{constant, clamp, slope}; apply(DepthBias, &CommandState::depthBias, bias, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthBias, &DeviceFunctions::cmdSetDepthBias, "vkCmdSetDepthBias")(commands, constant, clamp, slope); }); } void CommandState::SetDepthBounds(const Context& context, float minimum, float maximum) { const std::array bounds{minimum, maximum}; apply(DepthBounds, &CommandState::depthBounds, bounds, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthBounds, &DeviceFunctions::cmdSetDepthBounds, "vkCmdSetDepthBounds")(commands, minimum, maximum); }); } void CommandState::SetCullMode(const Context& context, VkCullModeFlags mode) { apply(CullMode, &CommandState::cullMode, mode, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetCullModeEXT, &DeviceFunctions::cmdSetCullMode, "vkCmdSetCullModeEXT")(commands, mode); }); } void CommandState::SetFrontFace(const Context& context, VkFrontFace face) { apply(FrontFace, &CommandState::frontFace, face, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetFrontFaceEXT, &DeviceFunctions::cmdSetFrontFace, "vkCmdSetFrontFaceEXT")(commands, face); }); } void CommandState::SetDepthTestEnable(const Context& context, VkBool32 enable) { apply(DepthTest, &CommandState::depthTest, enable, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthTestEnableEXT, &DeviceFunctions::cmdSetDepthTestEnable, "vkCmdSetDepthTestEnableEXT")(commands, enable); }); } void CommandState::SetDepthBiasEnable(const Context& context, VkBool32 enable) { apply(DepthBiasEnable, &CommandState::depthBiasEnable, enable, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthBiasEnableEXT, &DeviceFunctions::cmdSetDepthBiasEnable, "vkCmdSetDepthBiasEnableEXT")(commands, enable); }); } void CommandState::SetDepthWriteEnable(const Context& context, VkBool32 enable) { apply(DepthWrite, &CommandState::depthWrite, enable, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthWriteEnableEXT, &DeviceFunctions::cmdSetDepthWriteEnable, "vkCmdSetDepthWriteEnableEXT")(commands, enable); }); } void CommandState::SetDepthCompareOp(const Context& context, VkCompareOp compare) { apply(DepthCompare, &CommandState::depthCompare, compare, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthCompareOpEXT, &DeviceFunctions::cmdSetDepthCompareOp, "vkCmdSetDepthCompareOpEXT")(commands, compare); }); } void CommandState::SetDepthBoundsTestEnable(const Context& context, VkBool32 enable) { apply(DepthBoundsTest, &CommandState::depthBoundsTest, enable, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthBoundsTestEnableEXT, &DeviceFunctions::cmdSetDepthBoundsTestEnable, "vkCmdSetDepthBoundsTestEnableEXT")(commands, enable); }); } void CommandState::SetStencilTestEnable(const Context& context, VkBool32 enable) { apply(StencilTest, &CommandState::stencilTest, enable, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetStencilTestEnableEXT, &DeviceFunctions::cmdSetStencilTestEnable, "vkCmdSetStencilTestEnableEXT")(commands, enable); }); } void CommandState::SetStencilOp(const Context& context, VkStencilFaceFlags faces, VkStencilOp failOp, VkStencilOp passOp, VkStencilOp depthFailOp, VkCompareOp compareOp) { applyFaces(StencilOpFront, faces, &CommandState::stencilOps, StencilOps{failOp, passOp, depthFailOp, compareOp}, [&](VkStencilFaceFlags needed) { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetStencilOpEXT, &DeviceFunctions::cmdSetStencilOp, "vkCmdSetStencilOpEXT")(commands, needed, failOp, passOp, depthFailOp, compareOp); }); } void CommandState::SetStencilCompareMask(const Context& context, VkStencilFaceFlags faces, std::uint32_t mask) { applyFaces(CompareMaskFront, faces, &CommandState::compareMasks, mask, [&](VkStencilFaceFlags needed) { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetStencilCompareMask, &DeviceFunctions::cmdSetStencilCompareMask, "vkCmdSetStencilCompareMask")(commands, needed, mask); }); } void CommandState::SetStencilWriteMask(const Context& context, VkStencilFaceFlags faces, std::uint32_t mask) { applyFaces(WriteMaskFront, faces, &CommandState::writeMasks, mask, [&](VkStencilFaceFlags needed) { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetStencilWriteMask, &DeviceFunctions::cmdSetStencilWriteMask, "vkCmdSetStencilWriteMask")(commands, needed, mask); }); } void CommandState::SetStencilReference(const Context& context, VkStencilFaceFlags faces, std::uint32_t reference) { applyFaces(ReferenceFront, faces, &CommandState::references, reference, [&](VkStencilFaceFlags needed) { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetStencilReference, &DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, needed, reference); }); } void CommandState::SetColorWriteMasks(const Context& context, std::span masks) { ColorWriteMasks value{}; Require(!masks.empty() && masks.size() <= value.masks.size(), "color write masks exceed the color attachments"); value.count = static_cast(masks.size()); std::ranges::copy(masks, value.masks.begin()); const auto covered = [](const ColorWriteMasks& known, const ColorWriteMasks& wanted) { return wanted.count <= known.count && std::equal(wanted.masks.begin(), wanted.masks.begin() + wanted.count, known.masks.begin()); }; apply(ColorWriteMask, &CommandState::colorWriteMasks, value, covered, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetColorWriteMaskEXT, &DeviceFunctions::cmdSetColorWriteMask, "vkCmdSetColorWriteMaskEXT")(commands, 0, value.count, masks.data()); }); } CommandState& Recorder::GraphicsState() { Require(open != nullptr, "no batch is open for graphics state"); return open->graphicsState; } Recorder* Recorder::Active() { return activeRecorder; } void Recorder::Activate() { activeRecorder = this; { std::lock_guard tableLock(labelTableMutex); labelTableOwner = this; } GuestMemory::SetFlushHook(&FlushForAccess); } std::optional Recorder::LookupLabel(std::uint64_t address, std::size_t bytes, std::uint64_t afterStamp, LabelRefusal* refusal) { std::lock_guard tableLock(labelTableMutex); if (labelTableOwner == nullptr) return std::nullopt; return labelTableOwner->lookupLabel(address, bytes, afterStamp, refusal); } bool Recorder::WideLabelIn(std::uint64_t address, std::size_t bytes) { std::lock_guard tableLock(labelTableMutex); return labelTableOwner != nullptr && labelTableOwner->wideLabelInLocked(address, bytes); } bool Recorder::wideLabelInLocked(std::uint64_t address, std::size_t bytes) const { if (wideLabels.empty() || bytes == 0) return false; const auto end = address + bytes; for (auto it = wideLabels.lower_bound(address >= wideLabelBytes ? address - wideLabelBytes + 1 : 0); it != wideLabels.end() && it->first < end; ++it) { if (it->second.end > address) return true; } return false; } bool Recorder::LookupStoredBytes(std::uint64_t address, std::span bytes) { std::lock_guard tableLock(labelTableMutex); return labelTableOwner != nullptr && labelTableOwner->storedBytesLocked(address, bytes); } bool Recorder::storedBytesLocked(std::uint64_t address, std::span bytes) const { if (bytes.empty() || bytes.size() % 4 != 0 || address % 4 != 0 || address > std::numeric_limits::max() - bytes.size()) return false; const auto end = address + bytes.size(); if (const auto queued = queuedLabels.lower_bound(address); queued != queuedLabels.end() && queued->first < end) return false; const auto dwords = bytes.size() / 4; std::vector*> newest(dwords, nullptr); for (auto it = wideLabels.lower_bound(address >= wideLabelBytes ? address - wideLabelBytes + 1 : 0); it != wideLabels.end() && it->first < end; ++it) { if (it->second.end <= address) continue; const auto from = std::max(it->first, address); const auto to = std::min(it->second.end, end); for (auto dword = (from - address) / 4; dword < (to - address + 3) / 4; ++dword) { if (newest[dword] == nullptr || newest[dword]->second.sequence < it->second.sequence) newest[dword] = &*it; } } std::vector composed(bytes.size()); for (std::size_t dword = 0; dword < dwords; ++dword) { const auto at = address + dword * 4; if (const auto found = labels.find(at); found != labels.end()) { const auto& entry = found->second; if (entry.batch == nullptr || entry.batch->submitStarted.load(std::memory_order_acquire) || entry.overwritten || entry.behindCompletion) return false; std::memcpy(composed.data() + dword * 4, &entry.value, 4); continue; } const auto* wide = newest[dword]; if (wide == nullptr || at < wide->first || wide->second.end - at < 4 || wide->second.overwritten || wide->second.batch == nullptr || wide->second.batch->submitStarted.load(std::memory_order_acquire)) return false; std::memcpy(composed.data() + dword * 4, wide->second.bytes.data() + (at - wide->first), 4); } std::copy(composed.begin(), composed.end(), bytes.begin()); return true; } Recorder::OwnLabel Recorder::UnlandedOwnLabel(std::uint64_t address, std::size_t bytes, std::uint32_t queue) { std::lock_guard tableLock(labelTableMutex); if (labelTableOwner == nullptr) return {}; return labelTableOwner->unlandedOwnLabel(address, bytes, queue); } Recorder::OwnLabel Recorder::unlandedOwnLabel(std::uint64_t address, std::size_t bytes, std::uint32_t queue) const { OwnLabel own; if ((labels.empty() && queuedLabels.empty()) || (bytes != 4 && bytes != 8) || address % 4 != 0) return own; for (std::size_t offset = 0; offset < bytes; offset += 4) { const auto dword = address + offset; const LabelEntry* entry = nullptr; if (const auto found = labels.find(dword); found != labels.end()) entry = &found->second; if (const auto queued = queuedLabels.find(dword); queued != queuedLabels.end() && (entry == nullptr || queued->second.stamp > entry->stamp)) entry = &queued->second; if (entry == nullptr || entry->queue != queue || entry->overwritten) continue; own.value |= static_cast(entry->value) << (offset * 8u); own.mask |= 0xffffffffull << (offset * 8u); } return own; } std::optional Recorder::LookupLabelValue(std::uint64_t address, std::size_t bytes, std::uint64_t afterStamp) { const auto hit = LookupLabel(address, bytes, afterStamp); if (!hit.has_value()) return std::nullopt; return hit->value; } bool Recorder::LateTrust() { return LateTrustEnabled(); } Recorder::LateStatistics Recorder::LateCounts() { return lateCounts; } void Recorder::CloseLabelGroup(std::uint64_t trackerGeneration) { if (LabelGroupDwords().empty()) return; auto group = std::move(LabelGroupDwords()); LabelGroupDwords().clear(); if (trackerGeneration == 0) return; std::lock_guard tableLock(labelTableMutex); if (labelTableOwner == nullptr) return; auto& recorded = labelTableOwner->labels; for (const auto& [dword, stamp] : group) { // Only an entry still ours (stamps are unique): a later note of the dword has its own group. // And only while its batch is unsubmitted: a submitted one (a drain or APS5_LABEL_SUBMIT_NOW // inside the group) may have landed the value already, and a CPU store between that and // this close is not newer than the generation. const auto found = recorded.find(dword); if (found != recorded.end() && found->second.stamp == stamp && found->second.batch != nullptr && !found->second.batch->submitted) found->second.generation = trackerGeneration; } // A poller that refused the group as unclosed re-consults the table on the next generation. writeGeneration.fetch_add(1, std::memory_order_release); } void Recorder::NoteQueuedLabel(std::uint64_t address, std::span bytes, std::uint64_t stamp, std::uint32_t queue) { if (bytes.size() < 4 || address % 4 != 0) return; // The range before the table: the hook covers the group whether or not a table exists to // enter it in (no owner: the callback records it outright, by a CPU store when need be). QueuedLabelRanges().emplace_back(address, address + bytes.size()); QueuedLabelsOnThread::Set(true); queuedLabelsNoted.fetch_add(1, std::memory_order_relaxed); std::lock_guard tableLock(labelTableMutex); if (labelTableOwner == nullptr) return; auto& recorded = labelTableOwner->labels; auto& table = SeparateQueuedLabels() ? labelTableOwner->queuedLabels : recorded; for (std::size_t offset = 0; offset + 4 <= bytes.size(); offset += 4) { std::uint32_t value = 0; std::memcpy(&value, bytes.data() + offset, 4); if (const auto found = recorded.find(address + offset); found != recorded.end() && found->second.batch != nullptr) queuedLabelsOverRecorded.fetch_add(1, std::memory_order_relaxed); table.insert_or_assign(address + offset, LabelEntry{value, queue, stamp, nullptr}); } labelTableOwner->recordedLabels.store(recorded.size(), std::memory_order_relaxed); } void Recorder::ForgetQueuedLabels() { if (!QueuedLabelsOnThread::Get()) return; auto ranges = std::move(QueuedLabelRanges()); QueuedLabelRanges().clear(); QueuedLabelsOnThread::Set(false); std::lock_guard tableLock(labelTableMutex); if (labelTableOwner == nullptr) return; auto& recorded = labelTableOwner->labels; auto& queued = labelTableOwner->queuedLabels; const auto tag = GuestMemory::GpuLockThreadTag(); for (const auto& [begin, end] : ranges) { for (auto dword = begin; dword + 4 <= end; dword += 4) { if (const auto own = queued.find(dword); own != queued.end() && own->second.queue == tag) queued.erase(own); const auto found = recorded.find(dword); if (found != recorded.end() && found->second.batch == nullptr) recorded.erase(found); } } labelTableOwner->recordedLabels.store(recorded.size(), std::memory_order_relaxed); } std::uint64_t Recorder::ThreadClearAccesses() { return ClearAccesses::Get(); } bool Recorder::QueuedLabelsPending() { std::lock_guard tableLock(labelTableMutex); if (labelTableOwner == nullptr) return false; const auto& recorded = labelTableOwner->labels; return !labelTableOwner->queuedLabels.empty() || std::any_of(recorded.begin(), recorded.end(), [](const auto& entry) { return entry.second.batch == nullptr; }); } void Recorder::SetQueuedLabelRecorder(void (*recorder)()) { queuedLabelRecorder.store(recorder, std::memory_order_release); } Recorder::StoreStatistics Recorder::StoreCounts() { return StoreStatistics{storeCount.load(std::memory_order_relaxed), storeRuns.load(std::memory_order_relaxed), storesJoined.load(std::memory_order_relaxed), storesReplaced.load(std::memory_order_relaxed), storeWawBarriers.load(std::memory_order_relaxed), storeJoinsRefused.load(std::memory_order_relaxed), queuedLabelsNoted.load(std::memory_order_relaxed), queuedLabelsOverRecorded.load(std::memory_order_relaxed), queuedLabelHits.load(std::memory_order_relaxed), queuedLabelHookRecords.load(std::memory_order_relaxed), queuedLabelHookInCompletion.load(std::memory_order_relaxed), keyStoreCount.load(std::memory_order_relaxed), keyStoreRuns.load(std::memory_order_relaxed), keyStoreRunsForWriter.load(std::memory_order_relaxed), keyStoresJoined.load(std::memory_order_relaxed), storeRunsAtSubmit.load(std::memory_order_relaxed), storeRunsForced.load(std::memory_order_relaxed)}; } std::uint64_t Recorder::ThreadHookWaits() { return hookRealWaits; } namespace { struct DispatchOrder { std::uint32_t queueKey = 0; bool unordered = false; }; thread_local DispatchOrder nextDispatchOrder; std::atomic overlapDeferred{0}, overlapJoined{0}, overlapFlushed{0}; } bool Recorder::DispatchOverlapEnabled() { static const bool enabled = std::getenv("APS5_NO_DISPATCH_OVERLAP") == nullptr; return enabled; } void Recorder::SetDispatchOrder(std::uint32_t queueKey, bool unordered) { nextDispatchOrder = {queueKey, unordered}; } std::uint32_t Recorder::PeekUnorderedDispatch() { return nextDispatchOrder.unordered ? nextDispatchOrder.queueKey : 0u; } std::uint32_t Recorder::TakeDispatchOrder(bool& unordered) { const auto order = std::exchange(nextDispatchOrder, DispatchOrder{}); unordered = order.unordered; return order.queueKey; } Recorder::OverlapStatistics Recorder::OverlapCounts() { return OverlapStatistics{overlapDeferred.load(std::memory_order_relaxed), overlapJoined.load(std::memory_order_relaxed), overlapFlushed.load(std::memory_order_relaxed)}; } void Recorder::flushDeferredDispatch() { if (open == nullptr || open->deferredDispatchQueue == 0) return; open->deferredDispatchQueue = 0; open->deferredRun.clear(); open->runAccess.clear(); auto after = std::move(open->afterRun); open->afterRun.clear(); constexpr VkAccessFlags dispatchedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; recordBarrier(live(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, dispatchedAccess); CountBarriers(CommandClass::DispatchTrailing); open->coveredAccess = dispatchedAccess; overlapFlushed.fetch_add(1, std::memory_order_relaxed); std::exception_ptr failure; for (auto& work : after) { try { work(*this); } catch (...) { if (failure == nullptr) failure = std::current_exception(); } } if (failure != nullptr) std::rethrow_exception(failure); } bool Recorder::runConflict(std::span accesses) const { for (const auto& access : accesses) { for (const auto& member : open->runAccess) { if (((access[2] ^ member[2]) & RunAccessImage) != 0) continue; if (!(access[0] < member[1] && member[0] < access[1])) continue; if (((access[2] | member[2]) & RunAccessWritten) != 0) return true; } } return false; } bool Recorder::joinsRun(std::uint32_t queueKey, std::span owners, std::span accesses) const { if (queueKey == 0 || open == nullptr || open->deferredDispatchQueue != queueKey || open->renderPass.open || open->run.open) return false; const auto taken = [&](const void* owner) { return std::find(open->deferredRun.begin(), open->deferredRun.end(), owner) != open->deferredRun.end(); }; return std::none_of(owners.begin(), owners.end(), taken) && !runConflict(accesses); } VkCommandBuffer Recorder::RunCommands(std::uint32_t queueKey, const void* owner, std::span accesses, bool& inRun, VkAccessFlags* coveredAccess, std::source_location where) { GuestMemory::AssertGpuLockHeld("Recorder::RunCommands"); inRun = joinsRun(queueKey, std::span(&owner, 1), accesses); if (!inRun) return Commands(coveredAccess); if (coveredAccess != nullptr) *coveredAccess = 0; return live(); } void Recorder::AfterRun(std::function work) { Require(RunOpen(), "work after a dispatch run without an open run"); open->afterRun.push_back(std::move(work)); } bool Recorder::CloseRunOwing(const void* owner) { GuestMemory::AssertGpuLockHeld("Recorder::CloseRunOwing"); if (!RunOpen() || std::find(open->deferredRun.begin(), open->deferredRun.end(), owner) == open->deferredRun.end()) return false; flushDeferredDispatch(); return true; } VkCommandBuffer Recorder::OverlapCommands(std::uint32_t queueKey, std::span owners, std::span accesses, VkAccessFlags* coveredAccess, bool& overlapped, std::source_location where) { GuestMemory::AssertGpuLockHeld("Recorder::OverlapCommands"); overlapped = joinsRun(queueKey, owners, accesses); if (!overlapped) return Commands(coveredAccess); if (coveredAccess != nullptr) *coveredAccess = 0; return live(); } void Recorder::DeferDispatchBarrier(std::uint32_t queueKey, std::span owners, std::span accesses) { Require(open != nullptr && queueKey != 0, "a deferred dispatch barrier has no batch"); if (open->deferredDispatchQueue == 0) { open->deferredRun.clear(); open->runAccess.clear(); } else { overlapJoined.fetch_add(1, std::memory_order_relaxed); } open->deferredRun.insert(open->deferredRun.end(), owners.begin(), owners.end()); open->runAccess.insert(open->runAccess.end(), accesses.begin(), accesses.end()); open->deferredDispatchQueue = queueKey; open->coveredAccess = 0; overlapDeferred.fetch_add(1, std::memory_order_relaxed); } bool Recorder::SnapshotWriteOverlaps(std::uint64_t address, std::size_t bytes) { return AgcDriver::Graphics::SnapshotOverlaps(address, bytes); } std::shared_ptr Recorder::PendingWriteSnapshot() { return pendingWrites.load(std::memory_order_acquire); } bool Recorder::SnapshotOverlaps(const WriteRanges* snapshot, std::uint64_t address, std::size_t bytes) { return AgcDriver::Graphics::SnapshotOverlaps(snapshot, address, bytes); } void Recorder::CountSync(int source, const void* site) { if (source < 0 || source >= 5) return; ++syncCounts[source]; announcedSource = source; announcedSite = site; } void Recorder::AnnounceSyncSite(const void* site) { announcedSite = site; } double Recorder::ThreadWaitedMs() { return HostThreadSlot::Get(); } std::uint64_t Recorder::ReapsWithWork() { return holdCounters.reapsWithWork; } VkCommandBuffer Recorder::Commands(VkAccessFlags* coveredAccess, std::source_location where) { ensureOpen(); flushDeferredDispatch(); // Work recorded after a draw's render pass or an inline store run must see their writes: the // pass's end and the run's trailing barrier go in first (a per-batch run waits for Submit, or // for a caller whose ranges overlap a queued store: FlushStores). if (open->renderPass.open) endOpenRenderPass(PassBreak::Command, true, where); if (open->run.open && !LabelRunsPerBatch()) closeStoreRun(); if (coveredAccess != nullptr) *coveredAccess = open->coveredAccess; open->coveredAccess = 0; return live(); } void Recorder::MarkCovered(VkAccessFlags access) { if (open != nullptr) open->coveredAccess = access; } Recorder::DrawPassStart Recorder::StartDrawPass(std::uint64_t key, bool forced, bool fenced, const PassAccess& access) { ensureOpen(); flushDeferredDispatch(); auto& pass = open->renderPass; if (!pass.open || forced || (countingSamples && segmentMode() && !segmentSlotReady(*open))) { const auto reason = !pass.open ? pass.closedBy : forced ? PassBreak::Forced : PassBreak::Segment; const auto commands = Commands(); open->passHazards.Clear(); open->passHazards.BeginPass(); return {commands, false, true, reason}; } const auto hazard = open->passHazards.Check(access, pass.key == key); if (hazard == PassHazard::None && pass.key == key) { PerformanceTrace::Amount("Graphics.RenderPass.Continued", 1); return {open->commands, true, false, PassBreak::Continued}; } const auto reason = PassBreakFor(hazard); const bool merge = MergeBarriers() && !fenced && !pass.fenced && !pass.afterPass && pass.afterEnd.empty(); const bool elide = merge && hazard == PassHazard::None; endOpenRenderPass(reason, !merge); const auto commands = Commands(); if (!elide) open->passHazards.Clear(); open->passHazards.BeginPass(); return {commands, false, !elide, reason}; } void Recorder::LeaveRenderPassOpen(std::uint64_t key, std::uint32_t timing, bool fenced, const PassAccess& access, std::function afterPass) { Require(open != nullptr, "no batch is open for the render pass"); auto& pass = open->renderPass; if (!pass.open) { pass.timing = timing; pass.afterPass = std::move(afterPass); } pass.open = true; pass.key = key; pass.fenced = pass.fenced || fenced; open->passHazards.Add(access); } void Recorder::AfterRenderPass(std::function work) { Require(RenderPassOpen(), "work after a render pass without an open render pass"); open->renderPass.afterEnd.push_back(std::move(work)); } void Recorder::SealPassWriteOnly() { if (open != nullptr) open->passHazards.SealWriteOnly(); } bool Recorder::RenderPassOpen() const { return open != nullptr && open->renderPass.open; } void Recorder::endOpenRenderPass(PassBreak by, bool barrier, std::source_location where) { ++passGeneration; auto& pass = open->renderPass; if (open->segmentActive) endSegment(*open); EndRenderPass(context, live()); // The pass's attachment and shader writes are visible to everything recorded after it (the // host sees them at the batch's fence). if (barrier) { recordBarrier(live(), PassEndBarrier.srcStage, PassEndBarrier.dstStage, PassEndBarrier.srcAccess, PassEndBarrier.dstAccess); CountBarriers(CommandClass::Draw); } if (pass.afterPass) { pass.afterPass(open->graphicsState); } EndGpuTiming(pass.timing); open->coveredAccess = barrier ? VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : 0; open->hostReadOwed = true; auto after = std::move(pass.afterEnd); pass = {}; pass.closedBy = by; PerformanceTrace::Amount(PassBreakScopeNames[static_cast(by)], 1); std::exception_ptr failure; for (auto& work : after) { try { work(*this); } catch (...) { if (failure == nullptr) failure = std::current_exception(); } } if (failure != nullptr) std::rethrow_exception(failure); } void Recorder::QueueKeyStore(VkBuffer buffer, VkDeviceSize first, VkDeviceSize last, std::shared_ptr seed, std::uint64_t begin, std::uint64_t end) { ensureOpen(); // A queued label store over the keys lands first (program order: the key store is later). FlushStoresOverlapping(begin, static_cast(end - begin)); keyStoreCount.fetch_add(1, std::memory_order_relaxed); if (seed != nullptr) open->kept.push_back(seed); // The same range queued twice lands once: nothing wrote over it in between, or the writer // would have recorded the first store first. for (const auto& store : open->keyStores) { if (store.buffer == buffer && store.first == first && store.last == last) { keyStoresJoined.fetch_add(1, std::memory_order_relaxed); return; } } open->keyStores.push_back({buffer, first, last, std::move(seed), begin, end}); if (KeyStoresEach()) recordKeyStores(false); } bool Recorder::QueuedKeyStoreOverlaps(std::uint64_t address, std::size_t bytes) const { if (open == nullptr || bytes == 0) return false; const auto end = address + bytes; return std::any_of(open->keyStores.begin(), open->keyStores.end(), [&](const Batch::KeyStore& store) { return address < store.end && store.begin < end; }); } bool Recorder::AnyQueuedKeyStore(const std::function& overlaps) const { if (open == nullptr) return false; return std::any_of(open->keyStores.begin(), open->keyStores.end(), [&](const Batch::KeyStore& store) { return overlaps(store.begin, store.end); }); } void Recorder::FlushKeyStores() { if (open == nullptr || open->keyStores.empty()) return; recordKeyStores(true); } void Recorder::recordKeyStores(bool forWriter) { auto stores = std::move(open->keyStores); open->keyStores.clear(); if (stores.empty()) return; const auto commands = Commands(); const auto timing = beginTiming(ClassKey(CommandClass::DccKeyStore)); // Ordered behind every earlier recorded read or write of the ranges (the title's DCC clear or // decompress kernel storing keys through a V#), and visible to the work after and to the host. recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT); const auto fill = context.Resolved(&DeviceFunctions::cmdFillBuffer, "vkCmdFillBuffer"); const auto copy = context.Resolved(&DeviceFunctions::cmdCopyBuffer, "vkCmdCopyBuffer"); std::uint64_t bytes = 0; for (const auto& store : stores) { const VkDeviceSize fillBegin = std::min((store.first + 3) & ~VkDeviceSize{3}, store.last); const VkDeviceSize fillEnd = std::max(store.last & ~VkDeviceSize{3}, fillBegin); if (fillEnd > fillBegin) fill(commands, store.buffer, fillBegin, fillEnd - fillBegin, 0xffffffffu); if (store.seed != nullptr) { VkBufferCopy copies[2]; std::uint32_t copyCount = 0; if (fillBegin > store.first) copies[copyCount++] = {0, store.first, fillBegin - store.first}; if (store.last > fillEnd) copies[copyCount++] = {0, fillEnd, store.last - fillEnd}; if (copyCount != 0) copy(commands, static_cast(store.seed.get())->Handle(), store.buffer, copyCount, copies); } bytes += store.last - store.first; } recordBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); CountBarriers(CommandClass::DccKeyStore, 2); EndGpuTiming(timing, bytes); open->coveredAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; keyStoreRuns.fetch_add(1, std::memory_order_relaxed); if (forWriter) keyStoreRunsForWriter.fetch_add(1, std::memory_order_relaxed); } bool Recorder::defers() const { static const bool recordInline = [] { const char* value = std::getenv("APS5_RECORD_INLINE"); return value != nullptr && std::strcmp(value, "0") != 0; }(); return deferring && !recordInline && !RuntimeSwitches::Set(RuntimeSwitch::DirectBatches); } VkCommandBuffer Recorder::allocateBegun() { VkCommandBufferAllocateInfo allocation{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; allocation.commandPool = context.pool; allocation.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocation.commandBufferCount = 1; VkCommandBuffer commands = VK_NULL_HANDLE; Check(context.Function("vkAllocateCommandBuffers")(context.device, &allocation, &commands), "vkAllocateCommandBuffers recorder"); VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; const auto result = function(beginCommandBuffer, "vkBeginCommandBuffer")(commands, &begin); if (result != VK_SUCCESS) { context.Function("vkFreeCommandBuffers")(context.device, context.pool, 1, &commands); Check(result, "vkBeginCommandBuffer recorder"); } return commands; } VkCommandBuffer Recorder::Begin(CommandStream& stream) { if (open == nullptr || open->stream.get() != &stream) throw std::logic_error("AGC graphics: a stream that is not the open batch's asked for a command buffer"); open->real = allocateBegun(); demotedBatches.fetch_add(1, std::memory_order_relaxed); return open->real; } void Recorder::poisonOpen() noexcept { if (open == nullptr || open->stream == nullptr || open->stream->Materialized() != VK_NULL_HANDLE || open->stream->Poisoned()) return; open->stream->Poison(std::make_exception_ptr(std::runtime_error("AGC graphics: a draw threw while recording into a deferred batch, so the batch holds part of it"))); } std::unique_ptr Recorder::makeExecutor() { ReplayEntryPoints entry; entry.device = context.device; entry.createPool = context.Function("vkCreateCommandPool"); entry.destroyPool = context.Function("vkDestroyCommandPool"); entry.allocate = context.Function("vkAllocateCommandBuffers"); entry.free = context.Function("vkFreeCommandBuffers"); entry.begin = context.Function("vkBeginCommandBuffer"); entry.end = context.Function("vkEndCommandBuffer"); static const bool thread = [] { const char* value = std::getenv("APS5_ENCODE_THREAD"); return value != nullptr && std::strcmp(value, "0") != 0; }(); if (!thread) return std::make_unique(BorrowReplayPool(entry, context.pool)); const auto family = queueFamily; return std::make_unique([entry, family] { return CreateReplayPool(entry, family); }); } Recorder::StreamStatistics Recorder::StreamCounts() const { StreamStatistics counts; counts.deferred = deferredBatches.load(std::memory_order_relaxed); counts.direct = directBatches.load(std::memory_order_relaxed); counts.refused = budget.Refusals(); counts.demoted = demotedBatches.load(std::memory_order_relaxed); counts.poisoned = poisonedBatches.load(std::memory_order_relaxed); counts.replayed = replayedBatches.load(std::memory_order_relaxed); counts.replayFailed = failedReplays.load(std::memory_order_relaxed); return counts; } void Recorder::noteDemotion(const Demotion& demotion) { if (demotion.command == nullptr) return; std::string key = demotion.command; if (demotion.chained != VK_STRUCTURE_TYPE_MAX_ENUM) key += "/" + std::to_string(static_cast(demotion.chained)); std::lock_guard lock(demotionMutex); ++demotions[key]; } std::string Recorder::StreamReport() const { const auto counts = StreamCounts(); std::string demoted; for (const auto& [key, count] : Demotions()) demoted += " " + key + " " + std::to_string(count); char line[512]; std::snprintf(line, sizeof(line), "[recorder] batches: %llu deferred, %llu direct (%llu refused by admission), %llu demoted (by command/sType:%s), %llu poisoned; %llu replayed, %llu replays failed\n", static_cast(counts.deferred), static_cast(counts.direct), static_cast(counts.refused), static_cast(counts.demoted), demoted.empty() ? " none" : demoted.c_str(), static_cast(counts.poisoned), static_cast(counts.replayed), static_cast(counts.replayFailed)); return line; } std::vector> Recorder::Demotions() const { std::lock_guard lock(demotionMutex); return {demotions.begin(), demotions.end()}; } void Recorder::overlayListed() { directCommands = realCommands; streamedCommands = StreamedCommands(); const auto* table = context.Table(); if (table == nullptr) return; listedFunctions = *table; context.OverlayCommands(directCommands, realCommands); context.OverlayCommands(streamedCommands, realCommands); directCommands.listed = table; streamedCommands.listed = table; } void Recorder::ensureOpen() { GuestMemory::AssertGpuLockHeld("Recorder::Commands"); if (open == nullptr) { if (realResolved && !context.OverlayMatches(listedFunctions)) overlayListed(); ++passGeneration; auto batch = std::make_unique(); batch->sampleBatch = ++sampleBatches; try { batch->pool = context.pool; if (defers() && budget.TryOpen()) { try { batch->stream = std::make_unique(realCommands, &budget, static_cast(this)); } catch (...) { budget.Retired(0); throw; } batch->commands = batch->stream->Handle(); batch->functions = &streamedCommands; deferredBatches.fetch_add(1, std::memory_order_relaxed); } else { batch->real = allocateBegun(); batch->commands = batch->real; batch->functions = realResolved ? &directCommands : nullptr; directBatches.fetch_add(1, std::memory_order_relaxed); } if (!fenceless) { if (!spare.empty()) { batch->fence = spare.back(); spare.pop_back(); } else { VkFenceCreateInfo info{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; Check(context.Function("vkCreateFence")(context.device, &info, nullptr, &batch->fence), "vkCreateFence recorder"); } } static const bool suppress = std::getenv("APS5_NO_STATE_SUPPRESSION") == nullptr; batch->graphicsState.Begin(batch->commands, suppress, batch->functions); } catch (...) { release(*batch); throw; } batch->queue = GuestMemory::GpuLockThreadTag(); if (countingSamples && !segmentMode()) beginSamples(*batch); dropStaleHoldKept(); batch->kept.insert(batch->kept.end(), holdKept.begin(), holdKept.end()); open = std::move(batch); retentionCount = 0; if (++retentionEpoch == 0) { for (auto& slot : retention) slot = {}; ++retentionEpoch; } open->predictedSerial = sealedThrough + 1; try { if (open->queue == 0) WriteCheckpointSerial(context, live(), open->predictedSerial, open->queue); else WriteCheckpointSentinel(context, live()); } catch (...) { } if (PerformanceTrace::Recording()) { static std::atomic traceIds{0}; open->traceId = traceIds.fetch_add(1, std::memory_order_relaxed) + 1; } TraceBatchTag = open->traceId; // The whole-batch range: its start stamp waits for the previous batches like any // bottom-of-pipe stamp, so it marks when this batch's execution began. if (BatchStampsEnabled()) open->batchTiming = beginTiming(BatchTimingKey); } } void Recorder::RecordStore(VkBuffer buffer, VkDeviceSize offset, std::span bytes, std::uint64_t address) { if (bytes.empty()) return; ensureOpen(); flushDeferredDispatch(); auto& run = open->run; const VkDeviceSize end = offset + bytes.size(); storeCount.fetch_add(1, std::memory_order_relaxed); if (LabelRunsPerBatch()) { // Queued for the batch's run: a store inside the last queued one replaces its bytes, a // contiguous one joins it (a joined range overlapping an earlier queued store takes the // WAW barrier when the run is recorded, so no join is refused). if (run.queued.empty()) storeRuns.fetch_add(1, std::memory_order_relaxed); else if (auto& last = run.queued.back(); last.buffer == buffer) { const VkDeviceSize lastEnd = last.offset + last.bytes.size(); if (offset >= last.offset && end <= lastEnd) { std::memcpy(last.bytes.data() + (offset - last.offset), bytes.data(), bytes.size()); storesReplaced.fetch_add(1, std::memory_order_relaxed); return; } if (offset == lastEnd && last.bytes.size() + bytes.size() <= 65536) { last.bytes.insert(last.bytes.end(), bytes.begin(), bytes.end()); storesJoined.fetch_add(1, std::memory_order_relaxed); return; } } run.queued.push_back({buffer, offset, std::vector(bytes.begin(), bytes.end()), address}); return; } // A label says the work before it is done: the queued key stores (results of that work) land // ahead of every store of the run. if (!open->keyStores.empty()) recordKeyStores(true); if (open->renderPass.open) endOpenRenderPass(PassBreak::Label); open->coveredAccess = 0; // Two transfers to the same bytes have no order of their own within the run. const auto overlapsRecorded = [&] { return std::any_of(run.recorded.begin(), run.recorded.end(), [&](const auto& store) { return std::get<0>(store) == buffer && offset < std::get<2>(store) && std::get<1>(store) < end; }); }; if (!run.open) { run.timing = beginTiming(ClassKey(CommandClass::LabelRun)); run.storedBytes = 0; // The run's leading barrier: every earlier write of the range (a shader's, a transfer's, a // color attachment's) lands before the stores of the run. recordBarrier(live(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); CountBarriers(CommandClass::LabelRun); run.open = true; storeRuns.fetch_add(1, std::memory_order_relaxed); } else if (run.buffer == buffer && !run.bytes.empty()) { const VkDeviceSize pendingEnd = run.offset + run.bytes.size(); if (offset >= run.offset && end <= pendingEnd) { std::memcpy(run.bytes.data() + (offset - run.offset), bytes.data(), bytes.size()); storesReplaced.fetch_add(1, std::memory_order_relaxed); return; } if (offset == pendingEnd && run.bytes.size() + bytes.size() <= 65536) { // A joined store shares the pending vkCmdUpdateBuffer, which no barrier precedes: one // that overlaps a store the run already recorded takes the WAW barrier below instead. if (!JoinWawCheck() || !overlapsRecorded()) { run.bytes.insert(run.bytes.end(), bytes.begin(), bytes.end()); storesJoined.fetch_add(1, std::memory_order_relaxed); return; } storeJoinsRefused.fetch_add(1, std::memory_order_relaxed); } } flushPendingStore(); const bool waw = overlapsRecorded(); if (waw) { recordBarrier(live(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); CountBarriers(CommandClass::LabelRun); storeWawBarriers.fetch_add(1, std::memory_order_relaxed); } run.buffer = buffer; run.offset = offset; run.bytes.assign(bytes.begin(), bytes.end()); if (!LabelRunsEnabled()) closeStoreRun(); } void Recorder::recordBarrier(VkCommandBuffer commands, VkPipelineStageFlags sourceStage, VkPipelineStageFlags destinationStage, VkAccessFlags sourceAccess, VkAccessFlags destinationAccess) const { if (cmdPipelineBarrier == nullptr) { RecordMemoryBarrier(context, commands, sourceStage, destinationStage, sourceAccess, destinationAccess); return; } const VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, sourceAccess, destinationAccess}; cmdPipelineBarrier(commands, sourceStage, destinationStage, 0, 1, &barrier, 0, nullptr, 0, nullptr); } void Recorder::flushPendingStore() { auto& run = open->run; if (run.bytes.empty()) return; function(cmdUpdateBuffer, "vkCmdUpdateBuffer")(live(), run.buffer, run.offset, run.bytes.size(), run.bytes.data()); run.recorded.emplace_back(run.buffer, run.offset, run.offset + run.bytes.size()); run.storedBytes += run.bytes.size(); run.bytes.clear(); } bool Recorder::closeStoreRun(bool atSubmit) { flushDeferredDispatch(); auto& run = open->run; if (LabelRunsPerBatch()) { auto stores = std::move(run.queued); run.queued.clear(); open->queuedDumps = 0; if (stores.empty()) return false; // A label says the work before it is done: the queued key stores (results of that work) // land ahead of every store of the run, and the pass a draw left open ends. if (!open->keyStores.empty()) recordKeyStores(true); const bool passEndLast = open->renderPass.open && !open->renderPass.afterPass && open->renderPass.afterEnd.empty(); if (open->renderPass.open) endOpenRenderPass(PassBreak::Label); const auto commands = live(); run.timing = beginTiming(ClassKey(CommandClass::LabelRun)); if (BarrierValidate()) { std::vector> ranges; for (const auto& store : stores) ranges.emplace_back(store.address, store.End()); NoteAccess(CommandClass::LabelRun, Access{{}, ranges, {}, VK_PIPELINE_STAGE_TRANSFER_BIT}); } // At Submit every result of the batch reaches the host before the stores (the title's // pollers read results after the label); in place, later work sees the stores as well. std::uint32_t barriers = 2; if (atSubmit) { recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); } else if (passEndLast && BarrierBatch() && Covers(PassEndBarrier, LabelLeadingBarrier)) { CountMerged(CommandClass::LabelRun); barriers = 1; } else { recordBarrier(commands, LabelLeadingBarrier.srcStage, LabelLeadingBarrier.dstStage, LabelLeadingBarrier.srcAccess, LabelLeadingBarrier.dstAccess); } std::uint64_t storedBytes = 0; const auto update = function(cmdUpdateBuffer, "vkCmdUpdateBuffer"); std::vector writes; writes.reserve(stores.size()); for (const auto& store : stores) writes.push_back({store.address, store.End(), store.dumpTarget != 0}); if (const auto order = QueuedWriteOrder(writes); !std::is_sorted(order.begin(), order.end())) { std::vector ordered; std::vector orderedWrites; ordered.reserve(stores.size()); orderedWrites.reserve(writes.size()); for (const auto index : order) { ordered.push_back(std::move(stores[index])); orderedWrites.push_back(writes[index]); } stores = std::move(ordered); writes = std::move(orderedWrites); } const bool dumps = std::any_of(writes.begin(), writes.end(), [](const QueuedWrite& write) { return write.computed; }); if (dumps) recordQueuedDumps(commands, stores); std::size_t first = 0; std::uint32_t dumpIndex = 0, consumed = 0; for (const auto end : QueuedWriteGroups(writes)) { if (first != 0) { recordBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); ++barriers; run.recorded.clear(); } for (std::size_t i = first; i < end; ++i) { const auto& store = stores[i]; if (store.dumpTarget != 0) continue; const VkDeviceSize storeEnd = store.offset + store.bytes.size(); if (std::any_of(run.recorded.begin(), run.recorded.end(), [&](const auto& earlier) { return std::get<0>(earlier) == store.buffer && store.offset < std::get<2>(earlier) && std::get<1>(earlier) < storeEnd; })) { recordBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); ++barriers; storeWawBarriers.fetch_add(1, std::memory_order_relaxed); } else if (i != first) { recordBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); ++barriers; } update(commands, store.buffer, store.offset, store.bytes.size(), store.bytes.data()); run.recorded.emplace_back(store.buffer, store.offset, storeEnd); storedBytes += store.bytes.size(); } const auto before = dumpIndex; foldQueuedDumps(commands, stores, first, end, dumpIndex, consumed); if (dumpIndex != before) barriers += 3; first = end; } if (dumps) { retireSegments(consumed); dumpFolds.fetch_add(1, std::memory_order_relaxed); } const VkPipelineStageFlags written = VK_PIPELINE_STAGE_TRANSFER_BIT | (dumps ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT : 0u); const VkAccessFlags writtenAccess = VK_ACCESS_TRANSFER_WRITE_BIT | (dumps ? VK_ACCESS_SHADER_WRITE_BIT : 0u); if (atSubmit) { recordBarrier(commands, written, VK_PIPELINE_STAGE_HOST_BIT, writtenAccess, VK_ACCESS_HOST_READ_BIT); open->coveredAccess = 0; storeRunsAtSubmit.fetch_add(1, std::memory_order_relaxed); } else { recordBarrier(commands, written, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, writtenAccess, VK_ACCESS_HOST_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); open->coveredAccess = VK_ACCESS_HOST_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; storeRunsForced.fetch_add(1, std::memory_order_relaxed); } CountBarriers(CommandClass::LabelRun, barriers); EndGpuTiming(run.timing, storedBytes); run.timing = NoTiming; run.recorded.clear(); return atSubmit; } flushPendingStore(); // The run's stores are visible to the host and to everything recorded after them. recordBarrier(live(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); CountBarriers(CommandClass::LabelRun); EndGpuTiming(run.timing, run.storedBytes); run.timing = NoTiming; open->coveredAccess = VK_ACCESS_HOST_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; run.open = false; run.buffer = VK_NULL_HANDLE; run.recorded.clear(); return false; } bool Recorder::QueuedStoreOverlaps(std::uint64_t address, std::size_t bytes) const { if (open == nullptr || bytes == 0) return false; const auto end = address + bytes; return std::any_of(open->run.queued.begin(), open->run.queued.end(), [&](const Batch::StoreRun::Queued& store) { return address < store.End() && store.address < end; }); } bool Recorder::AnyQueuedStore(const std::function& overlaps) const { if (open == nullptr) return false; return std::any_of(open->run.queued.begin(), open->run.queued.end(), [&](const Batch::StoreRun::Queued& store) { return overlaps(store.address, store.End()); }); } void Recorder::FlushStores() { if (open == nullptr || open->run.queued.empty()) return; closeStoreRun(false); } namespace { constexpr std::uint32_t MaxTimedRanges = 512; constexpr std::size_t CommandClasses = static_cast(Recorder::CommandClass::Count); constexpr const char* CommandClassNames[CommandClasses] = {"dispatch-lead", "dispatch-trail", "indirect-args", "label-run", "fill", "fill-clear", "copy", "staging-in", "staging-out", "draw", "storage-upload", "storage-writeback", "dcc-clear", "dcc-keys", "present-blit", "shadow-publish", "template-refresh", "input-mirror", "mirror-publish"}; constexpr const char* BarrierScopes[CommandClasses] = {"Graphics.Barrier.dispatch-lead", "Graphics.Barrier.dispatch-trail", "Graphics.Barrier.indirect-args", "Graphics.Barrier.label-run", "Graphics.Barrier.fill", "Graphics.Barrier.fill-clear", "Graphics.Barrier.copy", "Graphics.Barrier.staging-in", "Graphics.Barrier.staging-out", "Graphics.Barrier.draw", "Graphics.Barrier.storage-upload", "Graphics.Barrier.storage-writeback", "Graphics.Barrier.dcc-clear", "Graphics.Barrier.dcc-keys", "Graphics.Barrier.present-blit", "Graphics.Barrier.shadow-publish", "Graphics.Barrier.template-refresh", "Graphics.Barrier.input-mirror", "Graphics.Barrier.mirror-publish"}; constexpr const char* BarrierMergedScopes[CommandClasses] = {"Graphics.BarrierMerged.dispatch-lead", "Graphics.BarrierMerged.dispatch-trail", "Graphics.BarrierMerged.indirect-args", "Graphics.BarrierMerged.label-run", "Graphics.BarrierMerged.fill", "Graphics.BarrierMerged.fill-clear", "Graphics.BarrierMerged.copy", "Graphics.BarrierMerged.staging-in", "Graphics.BarrierMerged.staging-out", "Graphics.BarrierMerged.draw", "Graphics.BarrierMerged.storage-upload", "Graphics.BarrierMerged.storage-writeback", "Graphics.BarrierMerged.dcc-clear", "Graphics.BarrierMerged.dcc-keys", "Graphics.BarrierMerged.present-blit", "Graphics.BarrierMerged.shadow-publish", "Graphics.BarrierMerged.template-refresh", "Graphics.BarrierMerged.input-mirror", "Graphics.BarrierMerged.mirror-publish"}; // [barriers] counters by class (relaxed: only reported) and the [gputime] totals, which the // presenter's thread adds to without the GPU mutex (AddGpuTiming). std::atomic classBarriers[CommandClasses]{}; std::atomic classMerged[CommandClasses]{}; // The hazard tracker's counts (APS5_BARRIER_VALIDATE=1): simulated barriers by class and by // hazard kind, leading barriers it would have skipped by class, batch-end barriers, and the // APS5_TRACE_BARRIERS budget left. constexpr std::size_t HazardKinds = 5; constexpr const char* HazardNames[HazardKinds] = {"raw", "waw", "war", "image", "conservative"}; std::atomic validateEmitted[CommandClasses]{}, validateSkipped[CommandClasses]{}, validateKinds[HazardKinds]{}; std::atomic validateBatchEnds{0}; std::atomic traceBarriersLeft{[] { const char* text = std::getenv("APS5_TRACE_BARRIERS"); return text != nullptr ? static_cast(std::strtoll(text, nullptr, 10)) : std::int64_t{0}; }()}; std::atomic timingPresents{0}; std::atomic presentSerial{0}; std::atomic settledFrames{0}; std::atomic settledFrameBusyNs{0}; std::atomic batchStampsRequested{false}; std::atomic timingDropped{0}; struct TimingTotals { std::uint64_t count = 0; double ms = 0; std::uint64_t bytes = 0; }; AgcDriver::Mutex timingMutex; std::map timingByKey; double timingProgramMs = 0, timingClassMs = 0, timingUnionMs = 0, timingBatchMs = 0; std::uint64_t timingBatches = 0; bool DrawOrGpuProfiled() { static const bool profiled = std::getenv("APS5_PROFILE_DRAW") != nullptr || Recorder::GpuTimingEnabled(); return profiled; } void reportBarriers() { if (!DrawOrGpuProfiled()) return; static auto lastReport = std::chrono::steady_clock::now(); const auto now = std::chrono::steady_clock::now(); if (now - lastReport < std::chrono::seconds(10)) return; lastReport = now; std::uint64_t total = 0, merged = 0; std::string line, mergedLine; for (std::size_t i = 0; i < CommandClasses; ++i) { const auto count = classBarriers[i].exchange(0, std::memory_order_relaxed); total += count; char text[64]; std::snprintf(text, sizeof(text), " %s %llu", CommandClassNames[i], static_cast(count)); line += text; const auto mergedCount = classMerged[i].exchange(0, std::memory_order_relaxed); if (mergedCount == 0) continue; merged += mergedCount; std::snprintf(text, sizeof(text), " %s %llu", CommandClassNames[i], static_cast(mergedCount)); mergedLine += text; } 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; for (std::size_t i = 0; i < CommandClasses; ++i) { const auto emittedCount = validateEmitted[i].exchange(0, std::memory_order_relaxed); const auto skippedCount = validateSkipped[i].exchange(0, std::memory_order_relaxed); emitted += emittedCount; skipped += skippedCount; if (emittedCount == 0 && skippedCount == 0) continue; char text[96]; std::snprintf(text, sizeof(text), " %s %llu/%llu", CommandClassNames[i], static_cast(emittedCount), static_cast(skippedCount)); classes += text; } for (std::size_t i = 0; i < HazardKinds; ++i) { char text[64]; std::snprintf(text, sizeof(text), " %s %llu", HazardNames[i], static_cast(validateKinds[i].exchange(0, std::memory_order_relaxed))); kinds += text; } 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()); } AgcDriver::ProfilePrint_nid_no_patch("\n"); AgcDriver::ProfilePrint_nid_no_patch("[samples] occlusion dumps (cumulative): %llu queued (%llu inside an open pass), %llu recorded at once; %llu segments closed; %llu folds of queued dumps\n", static_cast(dumpsQueued.load(std::memory_order_relaxed)), static_cast(dumpsQueuedInPass.load(std::memory_order_relaxed)), static_cast(dumpsAtOnce.load(std::memory_order_relaxed)), static_cast(segmentsClosed.load(std::memory_order_relaxed)), static_cast(dumpFolds.load(std::memory_order_relaxed))); } } bool Recorder::GpuTimingEnabled() { static const bool enabled = std::getenv("APS5_PROFILE_GPU") != nullptr; return enabled; } bool Recorder::BatchStampsEnabled() { return GpuTimingEnabled() || DrawProfiled() || PerformanceTrace::Configured() || batchStampsRequested.load(std::memory_order_relaxed); } void Recorder::CountBarriers(CommandClass which, std::uint32_t count) { const auto index = static_cast(which); PerformanceTrace::Amount(BarrierScopes[index], count); if (!DrawOrGpuProfiled()) return; classBarriers[index].fetch_add(count, std::memory_order_relaxed); } bool Recorder::MergeBarriers() { static const bool merge = std::getenv("APS5_FULL_BARRIERS") == nullptr && std::getenv("APS5_NO_BARRIER_ELISION") == nullptr; return merge; } bool Recorder::BarrierBatch() { return MergeBarriers() && !RuntimeSwitches::Set(RuntimeSwitch::NoBarrierBatch); } bool Recorder::ElideCovered(CommandClass which, const BarrierMask& wanted, VkAccessFlags covered) { if (!BarrierBatch() || !OrderedByTrailing(covered, wanted)) return false; CountMerged(which); return true; } void Recorder::CountMerged(CommandClass which) { PerformanceTrace::Amount(BarrierMergedScopes[static_cast(which)], 1); if (!DrawOrGpuProfiled()) return; classMerged[static_cast(which)].fetch_add(1, std::memory_order_relaxed); } bool Recorder::BarrierValidate() { static const bool validate = std::getenv("APS5_BARRIER_VALIDATE") != nullptr; return validate; } void Recorder::NoteAccess(CommandClass which, const Access& access) { if (!BarrierValidate()) return; ensureOpen(); auto& tracker = open->tracker; const auto overlapsAny = [](const auto& ranges, const std::pair& range) { return std::any_of(ranges.begin(), ranges.end(), [&](const auto& other) { return range.first < other.end && other.begin < range.second; }); }; std::size_t kind = HazardKinds; if (access.conservative) kind = 4; for (const auto& range : access.reads) { if (kind != HazardKinds) break; if (overlapsAny(tracker.writes, range)) kind = 0; } for (const auto& range : access.writes) { if (kind != HazardKinds) break; if (overlapsAny(tracker.writes, range)) kind = 1; else if (overlapsAny(tracker.reads, range)) kind = 2; } for (const auto& [image, written] : access.images) { if (kind != HazardKinds) break; if (std::any_of(tracker.images.begin(), tracker.images.end(), [&](const auto& seen) { return seen.image == image && (seen.written || written); })) kind = 3; } const auto index = static_cast(which); if (kind != HazardKinds) { validateEmitted[index].fetch_add(1, std::memory_order_relaxed); validateKinds[kind].fetch_add(1, std::memory_order_relaxed); tracker.reads.clear(); tracker.writes.clear(); tracker.images.clear(); } else { validateSkipped[index].fetch_add(1, std::memory_order_relaxed); if (traceBarriersLeft.load(std::memory_order_relaxed) > 0 && traceBarriersLeft.fetch_sub(1, std::memory_order_relaxed) > 0) { const auto first = [](const auto& ranges) { return ranges.empty() ? std::pair{0, 0} : std::pair{ranges.front().first, ranges.front().second}; }; const auto reads = first(access.reads); const auto writes = first(access.writes); std::fprintf(stderr, "[barriers] would skip %s: reads %zu (first 0x%llx+0x%llx), writes %zu (first 0x%llx+0x%llx), images %zu; since the last barrier: %zu reads, %zu writes, %zu images\n", CommandClassNames[index], access.reads.size(), static_cast(reads.first), static_cast(reads.second - reads.first), access.writes.size(), static_cast(writes.first), static_cast(writes.second - writes.first), access.images.size(), tracker.reads.size(), tracker.writes.size(), tracker.images.size()); } } for (const auto& [begin, end] : access.reads) tracker.reads.push_back({begin, end, access.stages}); for (const auto& [begin, end] : access.writes) tracker.writes.push_back({begin, end, access.stages}); for (const auto& [image, written] : access.images) tracker.images.push_back({image, written, access.stages}); } void Recorder::CountPresent() { timingPresents.fetch_add(1, std::memory_order_relaxed); presentSerial.fetch_add(1, std::memory_order_relaxed); ReferenceStorage::Shared().ReleaseIdle(); } std::uint64_t Recorder::Presents() { return presentSerial.load(std::memory_order_relaxed); } void Recorder::NoteFrameGpuBusy(double milliseconds) { settledFrameBusyNs.fetch_add(static_cast(milliseconds * 1e6), std::memory_order_relaxed); settledFrames.fetch_add(1, std::memory_order_release); } std::pair Recorder::FrameGpuBusy() { const auto frames = settledFrames.load(std::memory_order_acquire); return {frames, static_cast(settledFrameBusyNs.load(std::memory_order_relaxed)) / 1e6}; } void Recorder::RequestBatchStamps() { batchStampsRequested.store(true, std::memory_order_relaxed); } void Recorder::AddGpuTiming(CommandClass which, double nanoseconds, std::uint64_t bytes) { std::lock_guard lock(timingMutex); auto& totals = timingByKey[ClassKey(which)]; ++totals.count; totals.ms += nanoseconds / 1e6; totals.bytes += bytes; timingClassMs += nanoseconds / 1e6; } std::uint32_t Recorder::BeginGpuTiming(std::uint64_t key) { if (!GpuTimingEnabled()) return NoTiming; ensureOpen(); if (open->queries == VK_NULL_HANDLE && open->renderPass.open) return NoTiming; return beginTiming(key); } std::string Recorder::TimingKeyLabel(std::uint64_t key) { char text[32]; if (DrawStageTimingEnabled() && (key & (DrawTimingFlag | DrawStageTimingFlag)) == (DrawTimingFlag | DrawStageTimingFlag)) { std::snprintf(text, sizeof(text), "drawset 0x%llx", static_cast(key & ~(DrawTimingFlag | DrawStageTimingFlag))); return text; } std::snprintf(text, sizeof(text), (key & DrawTimingFlag) != 0 ? "draw 0x%llx" : "0x%llx", static_cast(key & ~DrawTimingFlag)); return text; } bool Recorder::DrawStageTimingEnabled() { static const bool enabled = std::getenv("APS5_PROFILE_GPU_DRAW_STAGES") != nullptr; return enabled; } std::uint64_t Recorder::DrawStageTimingKey(std::span> stages) { static auto* keys = new DrawStageTimingKeys; const auto [key, inserted] = keys->Intern(stages); if (inserted) { char text[96]; std::snprintf(text, sizeof(text), "[drawstages] drawset 0x%llx", static_cast(key)); std::string line = text; for (const auto& [stage, variant] : stages) { std::snprintf(text, sizeof(text), " %u:0x%llx", stage, static_cast(variant)); line += text; } line += '\n'; AgcDriver::ProfilePrint_nid_no_patch("%s", line.c_str()); } return key | DrawTimingFlag | DrawStageTimingFlag; } std::uint32_t Recorder::BeginInPassGpuTiming(std::uint64_t key) { if (!GpuTimingEnabled() || open == nullptr || open->queries == VK_NULL_HANDLE) return NoTiming; return beginTiming(key); } std::uint32_t Recorder::beginTiming(std::uint64_t key) { const bool full = GpuTimingEnabled(); if (!full && !(key == BatchTimingKey && BatchStampsEnabled())) return NoTiming; const auto commands = live(); const std::uint32_t queryCount = full ? MaxTimedRanges * 2 : 2; if (open->queries == VK_NULL_HANDLE) { if (!full && !sparePools.empty()) { open->queries = sparePools.back(); sparePools.pop_back(); } else { VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; info.queryType = VK_QUERY_TYPE_TIMESTAMP; info.queryCount = queryCount; if (context.Function("vkCreateQueryPool")(context.device, &info, nullptr, &open->queries) != VK_SUCCESS) { open->queries = VK_NULL_HANDLE; return NoTiming; } } function(cmdResetQueryPool, "vkCmdResetQueryPool")(commands, open->queries, 0, queryCount); } if (open->timedKeys.size() >= queryCount / 2) { timingDropped.fetch_add(1, std::memory_order_relaxed); return NoTiming; } const auto index = static_cast(open->timedKeys.size()); open->timedKeys.push_back(key); open->timedBytes.push_back(0); // Both stamps wait for everything before them to complete, so the range is the timed work alone // (a top-of-pipe stamp is not held back by the barrier that precedes the work). context.Function("vkCmdWriteTimestamp")(commands, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, open->queries, index * 2); return index; } void Recorder::EndGpuTiming(std::uint32_t index, std::uint64_t bytes) { if (index == NoTiming || open == nullptr || open->queries == VK_NULL_HANDLE) return; if (index < open->timedBytes.size()) open->timedBytes[index] += bytes; context.Function("vkCmdWriteTimestamp")(live(), VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, open->queries, index * 2 + 1); } bool Recorder::RecordDispatchArguments(VkCommandBuffer commands, VkDeviceAddress source, VkDeviceAddress arguments, const std::array* threadGroup) { constexpr std::uint32_t PushBytes = 48; if (dispatchArgumentState == 0) { dispatchArgumentState = -1; VkShaderModule module = VK_NULL_HANDLE; try { const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes}; VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layoutInfo.pushConstantRangeCount = 1; layoutInfo.pPushConstantRanges = &push; Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &dispatchArgumentLayout), "vkCreatePipelineLayout dispatch arguments"); module = CreateShaderModule(context, DISPATCH_ARGUMENTS_SPV, sizeof(DISPATCH_ARGUMENTS_SPV), "vkCreateShaderModule dispatch arguments"); VkComputePipelineCreateInfo pipelineInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; pipelineInfo.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; pipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; pipelineInfo.stage.module = module; pipelineInfo.stage.pName = "main"; pipelineInfo.layout = dispatchArgumentLayout; Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &dispatchArgumentPipeline), "vkCreateComputePipelines dispatch arguments"); context.Function("vkDestroyShaderModule")(context.device, module, nullptr); dispatchArgumentState = 1; } catch (const std::exception& error) { if (module != VK_NULL_HANDLE) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); std::fprintf(stderr, "[gpu] indirect dispatches read their group counts unchecked: %s\n", error.what()); } } if (dispatchArgumentState < 0) return false; recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); context.BindComputePipeline(commands, dispatchArgumentPipeline); const auto* limit = context.limits.maxComputeWorkGroupCount; struct { VkDeviceAddress source; VkDeviceAddress arguments; std::array limits; std::array group; } parameters{source, arguments, {limit[0], limit[1], limit[2], threadGroup != nullptr ? 1u : 0u}, {1u, 1u, 1u, 0u}}; if (threadGroup != nullptr) std::copy(threadGroup->begin(), threadGroup->end(), parameters.group.begin()); static_assert(sizeof(parameters) == PushBytes); function(cmdPushConstants, "vkCmdPushConstants")(commands, dispatchArgumentLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, 1, 1, 1); const VkPipelineStageFlags readers = VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | (threadGroup != nullptr ? VK_PIPELINE_STAGE_TRANSFER_BIT : 0u); const VkAccessFlags reads = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | (threadGroup != nullptr ? VK_ACCESS_TRANSFER_READ_BIT : 0u); recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, readers, VK_ACCESS_SHADER_WRITE_BIT, reads); CountBarriers(CommandClass::DispatchLeading, 2); return true; } void Recorder::CountSamples() { GuestMemory::AssertGpuLockHeld("Recorder::CountSamples"); gpuSampleCounter(); countingSamples = true; if (segmentMode() || open == nullptr || open->samples != VK_NULL_HANDLE) return; if (open->renderPass.open) endOpenRenderPass(PassBreak::Samples); beginSamples(*open); } std::uint64_t Recorder::SamplesTotal() { if (sampleCounterState <= 0) return samplesPassed.load(std::memory_order_acquire); if (segmentMode() && !Idle()) Sync(); std::uint64_t total = 0; std::memcpy(&total, sampleCounter->Bytes().data(), sizeof(total)); for (const auto& segment : pendingSamples) { std::uint64_t samples = 0; Check(context.Function("vkGetQueryPoolResults")(context.device, segment.handle, segment.slot, 1, sizeof(samples), &samples, sizeof(samples), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT), "vkGetQueryPoolResults occlusion"); total += samples; } pendingSamples.clear(); std::memcpy(sampleCounter->Bytes().data(), &total, sizeof(total)); return total; } void Recorder::NoteSampledDraw(VkCommandBuffer commands) { if (open == nullptr) return; if (segmentMode()) { if (countingSamples && open->commands == commands && !open->segmentActive) beginSegment(*open); return; } if (open->sampleActive) open->samplesDrawn = true; } void Recorder::NoteDrawTraceToken(std::uint64_t token) noexcept { if (token == 0 || open == nullptr) return; try { auto inserted = open->drawTraceTokenSet.insert(token); if (!inserted.second) return; try { open->drawTraceTokens.push_back(token); } catch (...) { open->drawTraceTokenSet.erase(inserted.first); throw; } } catch (...) { AgcDriver::CaptureTrace::Log("draw-token-note-failed token=%llu", static_cast(token)); } } void Recorder::NoteFaultToken(AgcDriver::FaultToken token) noexcept { if (token == 0 || open == nullptr) return; if (open->firstToken == 0) open->firstToken = token; open->lastToken = token; } bool Recorder::gpuSampleCounter() { if (sampleCounterState != 0) return sampleCounterState > 0; sampleCounterState = -1; if (!context.bufferDeviceAddress) return false; VkShaderModule module = VK_NULL_HANDLE; try { sampleCounter = std::make_unique(context, DumpListOffset + 16 * DumpFoldCapacity, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); std::memset(sampleCounter->Bytes().data(), 0, sampleCounter->Bytes().size()); const auto initial = samplesPassed.load(std::memory_order_acquire); std::memcpy(sampleCounter->Bytes().data(), &initial, sizeof(initial)); const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes}; VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layoutInfo.pushConstantRangeCount = 1; layoutInfo.pPushConstantRanges = &push; Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &sampleLayout), "vkCreatePipelineLayout sample counter"); module = CreateShaderModule(context, SAMPLE_COUNTER_SPV, sizeof(SAMPLE_COUNTER_SPV), "vkCreateShaderModule sample counter"); VkComputePipelineCreateInfo pipelineInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; pipelineInfo.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; pipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; pipelineInfo.stage.module = module; pipelineInfo.stage.pName = "main"; pipelineInfo.layout = sampleLayout; { auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &samplePipeline), "vkCreateComputePipelines sample counter"); } context.Function("vkDestroyShaderModule")(context.device, module, nullptr); module = VK_NULL_HANDLE; const VkPushConstantRange dumpPush{VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes}; layoutInfo.pPushConstantRanges = &dumpPush; Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &dumpLayout), "vkCreatePipelineLayout sample dumps"); module = CreateShaderModule(context, SAMPLE_DUMPS_SPV, sizeof(SAMPLE_DUMPS_SPV), "vkCreateShaderModule sample dumps"); pipelineInfo.stage.module = module; pipelineInfo.layout = dumpLayout; { auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &dumpPipeline), "vkCreateComputePipelines sample dumps"); } context.Function("vkDestroyShaderModule")(context.device, module, nullptr); module = VK_NULL_HANDLE; } catch (const std::exception& error) { if (module != VK_NULL_HANDLE) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); if (samplePipeline != VK_NULL_HANDLE) context.Function("vkDestroyPipeline")(context.device, samplePipeline, nullptr); if (dumpLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, dumpLayout, nullptr); if (sampleLayout != VK_NULL_HANDLE) context.Function("vkDestroyPipelineLayout")(context.device, sampleLayout, nullptr); samplePipeline = VK_NULL_HANDLE; dumpLayout = VK_NULL_HANDLE; sampleLayout = VK_NULL_HANDLE; sampleCounter.reset(); std::fprintf(stderr, "[gpu] occlusion counter dumps drain the device: %s\n", error.what()); return false; } sampleCounterState = 1; return true; } std::uint64_t Recorder::Batch::StoreRun::Queued::End() const { return address + (dumpTarget != 0 ? SampleDumpBytes : bytes.size()); } std::vector Recorder::QueuedWriteOrder(std::span writes) { std::vector order(writes.size()); for (std::size_t i = 0; i < order.size(); ++i) order[i] = i; std::vector coveredLater(writes.size()), overLater(writes.size()); std::map later; for (auto i = writes.size(); i-- > 0;) { const auto& write = writes[i]; if (!write.computed) { const auto after = later.upper_bound(write.begin); coveredLater[i] = after != later.begin() && std::prev(after)->second >= write.end; const auto last = later.lower_bound(write.end); overLater[i] = last != later.begin() && std::prev(last)->second > write.begin; continue; } auto begin = write.begin, end = write.end; auto at = later.lower_bound(begin); if (at != later.begin() && std::prev(at)->second >= begin) --at; while (at != later.end() && at->first <= end) { begin = std::min(begin, at->first); end = std::max(end, at->second); at = later.erase(at); } later.emplace(begin, end); } std::vector before, dumps, after; std::vector> earlier, delayed; for (std::size_t i = 0; i < writes.size(); ++i) { const auto& write = writes[i]; const auto over = [&](const std::vector>& ranges) { return std::any_of(ranges.begin(), ranges.end(), [&](const auto& range) { return write.begin < range.second && range.first < write.end; }); }; if (write.computed) { dumps.push_back(i); earlier.emplace_back(write.begin, write.end); } else if (dumps.empty()) { before.push_back(i); } else if (overLater[i]) { if (over(delayed) || (!coveredLater[i] && over(earlier))) return order; before.push_back(i); } else { after.push_back(i); delayed.emplace_back(write.begin, write.end); } } order = std::move(before); order.insert(order.end(), dumps.begin(), dumps.end()); order.insert(order.end(), after.begin(), after.end()); return order; } std::vector Recorder::QueuedWriteGroups(std::span writes) { std::vector ends; std::vector> computed; for (std::size_t i = 0; i < writes.size(); ++i) { const auto& write = writes[i]; if (!write.computed && !computed.empty()) { ends.push_back(i); computed.clear(); } if (write.computed) computed.emplace_back(write.begin, write.end); } if (!writes.empty()) ends.push_back(writes.size()); return ends; } bool Recorder::segmentMode() const { return sampleCounterState > 0; } bool Recorder::QueuesSampleDumps() const { return segmentMode() && LabelRunsPerBatch(); } Recorder::SampleDumpStatistics Recorder::SampleDumpCounts() { return SampleDumpStatistics{dumpsQueued.load(std::memory_order_relaxed), dumpsQueuedInPass.load(std::memory_order_relaxed), dumpsAtOnce.load(std::memory_order_relaxed), segmentsClosed.load(std::memory_order_relaxed), dumpFolds.load(std::memory_order_relaxed)}; } bool Recorder::segmentSlotReady(const Batch& batch) const { return batch.segmentActive || (batch.segments != VK_NULL_HANDLE && batch.segmentNext < SegmentSlots); } void Recorder::PrepareSampleSlot() { GuestMemory::AssertGpuLockHeld("Recorder::PrepareSampleSlot"); if (!countingSamples || !segmentMode()) return; ensureOpen(); flushDeferredDispatch(); Require(!open->renderPass.open, "a sample slot is prepared inside a render pass"); if (!segmentSlotReady(*open)) takeSegmentPool(*open); } void Recorder::EndPassSamples() { if (open != nullptr && open->segmentActive) endSegment(*open); } void Recorder::RecordUncounted(const std::function& record) { Commands(); if (open->segmentActive) endSegment(*open); const bool counted = open->sampleActive; if (counted) { open->endedSamples.reserve(open->endedSamples.size() + 1); endSamples(*open); open->endedSamples.push_back(open->samples); open->samples = VK_NULL_HANDLE; } record(open->graphicsState); if (counted) beginSamples(*open); } void Recorder::takeSegmentPool(Batch& batch) { auto cache = std::static_pointer_cast(segmentPools); if (cache == nullptr) { cache = std::make_shared(); cache->device = context.device; cache->destroy = context.Function("vkDestroyQueryPool"); segmentPools = cache; } if (batch.segmentPool != nullptr) batch.kept.push_back(std::move(batch.segmentPool)); batch.segmentPool.reset(); batch.segments = cache->take(); if (batch.segments == VK_NULL_HANDLE) { VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; info.queryType = VK_QUERY_TYPE_OCCLUSION; info.queryCount = SegmentSlots; Check(context.Function("vkCreateQueryPool")(context.device, &info, nullptr, &batch.segments), "vkCreateQueryPool occlusion segments"); } try { batch.segmentPool = std::make_shared(cache, batch.segments); } catch (...) { cache->put(batch.segments); batch.segments = VK_NULL_HANDLE; throw; } batch.segmentNext = 0; function(cmdResetQueryPool, "vkCmdResetQueryPool")(batch.commands, batch.segments, 0, SegmentSlots); } void Recorder::beginSegment(Batch& batch) { Require(batch.segments != VK_NULL_HANDLE && batch.segmentNext < SegmentSlots, "an occlusion segment begins without a reset query slot"); batch.segmentSlot = batch.segmentNext++; const auto flags = context.occlusionQueryPrecise ? VK_QUERY_CONTROL_PRECISE_BIT : 0u; function(cmdBeginQuery, "vkCmdBeginQuery")(batch.commands, batch.segments, batch.segmentSlot, flags); batch.segmentActive = true; } void Recorder::endSegment(Batch& batch) { function(cmdEndQuery, "vkCmdEndQuery")(batch.commands, batch.segments, batch.segmentSlot); batch.segmentActive = false; reserveSampleRestore(batch); pendingSamples.push_back({batch.segmentPool, batch.segments, batch.segmentSlot, batch.sampleBatch}); segmentsClosed.fetch_add(1, std::memory_order_relaxed); } void Recorder::copySegments(VkCommandBuffer commands, std::uint32_t count) { Require(count <= pendingSamples.size() && count <= SegmentFoldCapacity, "occlusion segments exceed the fold capacity"); const auto copy = function(cmdCopyQueryPoolResults, "vkCmdCopyQueryPoolResults"); for (std::uint32_t i = 0; i < count;) { const auto& first = pendingSamples[i]; std::uint32_t run = 1; while (i + run < count && pendingSamples[i + run].handle == first.handle && pendingSamples[i + run].slot == first.slot + run) ++run; copy(commands, first.handle, first.slot, run, sampleCounter->Handle(), 16 + 8 * static_cast(i), 8, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); i += run; } } void Recorder::reserveSampleRestore(const Batch& batch) { const auto needed = pendingSamples.size() + batch.foldedSamples.size() + 1; if (needed > pendingSamples.capacity()) pendingSamples.reserve(std::max(needed, 2 * pendingSamples.capacity())); } void Recorder::retireSegments(std::uint32_t count) { open->foldedSamples.insert(open->foldedSamples.end(), std::make_move_iterator(pendingSamples.begin()), std::make_move_iterator(pendingSamples.begin() + count)); pendingSamples.erase(pendingSamples.begin(), pendingSamples.begin() + count); } void Recorder::recordQueuedDumps(VkCommandBuffer commands, std::span writes) { std::uint32_t segments = 0; std::vector list; for (const auto& write : writes) { if (write.dumpTarget == 0) continue; segments = write.dumpSegments; list.insert(list.end(), {static_cast(write.dumpTarget), static_cast(write.dumpTarget >> 32u), write.dumpSegments, write.dumpBlocks}); } Require(list.size() <= 4u * DumpFoldCapacity, "queued occlusion dumps exceed the fold capacity"); copySegments(commands, segments); function(cmdUpdateBuffer, "vkCmdUpdateBuffer")(commands, sampleCounter->Handle(), DumpListOffset, list.size() * sizeof(std::uint32_t), list.data()); } void Recorder::dispatchDumps(VkCommandBuffer commands, std::uint32_t firstDump, std::uint32_t dumps, std::uint32_t firstSegment, std::uint32_t lastSegment) { recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); context.BindComputePipeline(commands, dumpPipeline); struct { VkDeviceAddress counter; VkDeviceAddress list; std::uint32_t firstDump; std::uint32_t dumps; std::uint32_t firstSegment; std::uint32_t lastSegment; std::uint32_t phase; } parameters{sampleCounter->DeviceAddress(), sampleCounter->DeviceAddress() + DumpListOffset, firstDump, dumps, firstSegment, lastSegment, 0u}; static_assert(sizeof(parameters) == SampleDumpPushBytes); const auto push = function(cmdPushConstants, "vkCmdPushConstants"); const auto dispatch = function(cmdDispatch, "vkCmdDispatch"); push(commands, dumpLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes, ¶meters); dispatch(commands, 1, 1, 1); if (dumps == 0) return; const auto publish = [&](std::uint32_t phase) { recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); parameters.phase = phase; push(commands, dumpLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleDumpPushBytes, ¶meters); dispatch(commands, 1, 1, 1); }; publish(1u); publish(2u); } void Recorder::foldQueuedDumps(VkCommandBuffer commands, std::span writes, std::size_t first, std::size_t end, std::uint32_t& dumpIndex, std::uint32_t& consumed) { std::uint32_t count = 0, segments = consumed; for (std::size_t i = first; i < end; ++i) { if (writes[i].dumpTarget == 0) continue; ++count; segments = writes[i].dumpSegments; } if (count == 0) return; dispatchDumps(commands, dumpIndex, count, consumed, segments); dumpIndex += count; consumed = segments; } void Recorder::foldSegments() { const auto commands = live(); const auto count = static_cast(std::min(pendingSamples.size(), SegmentFoldCapacity)); recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); copySegments(commands, count); dispatchDumps(commands, 0, 0, 0, count); recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); CountBarriers(CommandClass::Copy, 3); retireSegments(count); } void Recorder::endSamples(Batch& batch) { if (!batch.sampleActive) return; function(cmdEndQuery, "vkCmdEndQuery")(batch.commands, batch.samples, 0); batch.sampleActive = false; if (sampleCounterState > 0 && batch.samplesDrawn) { reserveSampleRestore(batch); pendingSamples.push_back({batch.samplePool, batch.samples, 0, batch.sampleBatch}); } batch.samplesDrawn = false; } void Recorder::foldSamples(Batch& batch, VkDeviceAddress target, std::uint32_t blocks) { const auto commands = batch.commands; const auto copy = function(cmdCopyQueryPoolResults, "vkCmdCopyQueryPoolResults"); const auto push = function(cmdPushConstants, "vkCmdPushConstants"); const auto dispatch = function(cmdDispatch, "vkCmdDispatch"); const auto bindCompute = context.ComputeBinding(); std::size_t done = 0; do { const auto count = static_cast(std::min(SampleFoldCapacity, pendingSamples.size() - done)); if (done != 0) { recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); } for (std::uint32_t i = 0; i < count; ++i) { const auto& segment = pendingSamples[done + i]; copy(commands, segment.handle, segment.slot, 1, sampleCounter->Handle(), 16 + 8 * i, 8, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); if (segment.pool != nullptr) batch.kept.push_back(segment.pool); } done += count; const bool last = done == pendingSamples.size(); recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); bindCompute(commands, samplePipeline); struct { VkDeviceAddress counter; VkDeviceAddress target; std::uint32_t count; std::uint32_t store; std::uint32_t blocks; } parameters{sampleCounter->DeviceAddress(), target, count, last && target != 0 ? 1u : 0u, blocks}; static_assert(offsetof(decltype(parameters), blocks) + sizeof(parameters.blocks) == SampleCounterPushBytes); push(commands, sampleLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes, ¶meters); dispatch(commands, 1, 1, 1); if (parameters.store == 1u) { const auto publish = [&](std::uint32_t store) { recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT); parameters.store = store; push(commands, sampleLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, SampleCounterPushBytes, ¶meters); dispatch(commands, 1, 1, 1); }; publish(3u); publish(2u); } } while (done < pendingSamples.size()); recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_HOST_READ_BIT); CountBarriers(CommandClass::Copy, target != 0 ? 4u : 2u); batch.foldedSamples.insert(batch.foldedSamples.end(), std::make_move_iterator(pendingSamples.begin()), std::make_move_iterator(pendingSamples.end())); pendingSamples.clear(); } bool Recorder::DumpSamples(VkDeviceAddress target, std::uint64_t address, std::uint32_t blocks) { GuestMemory::AssertGpuLockHeld("Recorder::DumpSamples"); if (target == 0 || !gpuSampleCounter()) return false; countingSamples = true; flushDeferredDispatch(); if (segmentMode()) { ensureOpen(); if (address != 0 && LabelRunsPerBatch() && pendingSamples.size() < SegmentFoldCapacity && open->queuedDumps < DumpFoldCapacity) { if (open->segmentActive) endSegment(*open); if (open->renderPass.open) dumpsQueuedInPass.fetch_add(1, std::memory_order_relaxed); if (open->run.queued.empty()) storeRuns.fetch_add(1, std::memory_order_relaxed); auto& queued = open->run.queued.emplace_back(); queued.address = address; queued.dumpTarget = target; queued.dumpSegments = static_cast(pendingSamples.size()); queued.dumpBlocks = blocks; ++open->queuedDumps; dumpsQueued.fetch_add(1, std::memory_order_relaxed); return true; } FlushStores(); Commands(); foldSamples(*open, target, blocks); dumpsAtOnce.fetch_add(1, std::memory_order_relaxed); return true; } Commands(); endSamples(*open); foldSamples(*open, target, blocks); if (open->samplePool != nullptr) open->kept.push_back(std::move(open->samplePool)); open->samplePool.reset(); open->samples = VK_NULL_HANDLE; beginSamples(*open); return true; } bool Recorder::RecordMeshArguments(VkCommandBuffer commands, VkDeviceAddress record, VkDeviceAddress arguments, std::span rules) { constexpr std::uint32_t PushBytes = 48; if (meshArgumentState == 0) { meshArgumentState = -1; VkShaderModule module = VK_NULL_HANDLE; try { const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes}; VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layoutInfo.pushConstantRangeCount = 1; layoutInfo.pPushConstantRanges = &push; Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &meshArgumentLayout), "vkCreatePipelineLayout mesh arguments"); module = CreateShaderModule(context, MESH_ARGUMENTS_SPV, sizeof(MESH_ARGUMENTS_SPV), "vkCreateShaderModule mesh arguments"); VkComputePipelineCreateInfo pipelineInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; pipelineInfo.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; pipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; pipelineInfo.stage.module = module; pipelineInfo.stage.pName = "main"; pipelineInfo.layout = meshArgumentLayout; { auto pipelineCacheLock = context.LockPipelineCacheForUse(); Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &meshArgumentPipeline), "vkCreateComputePipelines mesh arguments"); } context.Function("vkDestroyShaderModule")(context.device, module, nullptr); meshArgumentState = 1; } catch (const std::exception& error) { if (module != VK_NULL_HANDLE) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); std::fprintf(stderr, "[gpu] mesh indirect draws read their records on the CPU: %s\n", error.what()); } } if (meshArgumentState < 0) return false; recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); context.BindComputePipeline(commands, meshArgumentPipeline); struct { VkDeviceAddress record; VkDeviceAddress arguments; std::array rules; } parameters{record, arguments, {rules[0], rules[1], rules[2], rules[3], rules[4], rules[5], rules[6], rules[7]}}; static_assert(sizeof(parameters) == PushBytes); function(cmdPushConstants, "vkCmdPushConstants")(commands, meshArgumentLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, 1, 1, 1); recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_MESH_SHADER_BIT_EXT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_SHADER_READ_BIT); CountBarriers(CommandClass::Draw, 2); return true; } bool Recorder::RecordChangedCopy(VkCommandBuffer commands, VkDeviceAddress result, VkDeviceAddress snapshot, VkDeviceAddress target, std::uint32_t dwords, VkDeviceAddress counter) { constexpr std::uint32_t PushBytes = 40; constexpr std::uint32_t GroupSize = 64; if (changedCopyState == 0) { changedCopyState = -1; VkShaderModule module = VK_NULL_HANDLE; try { const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes}; VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layoutInfo.pushConstantRangeCount = 1; layoutInfo.pPushConstantRanges = &push; Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &changedCopyLayout), "vkCreatePipelineLayout changed copy"); module = CreateShaderModule(context, STAGING_COPY_BACK_SPV, sizeof(STAGING_COPY_BACK_SPV), "vkCreateShaderModule changed copy"); VkComputePipelineCreateInfo pipelineInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; pipelineInfo.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; pipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; pipelineInfo.stage.module = module; pipelineInfo.stage.pName = "main"; pipelineInfo.layout = changedCopyLayout; Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &changedCopyPipeline), "vkCreateComputePipelines changed copy"); context.Function("vkDestroyShaderModule")(context.device, module, nullptr); changedCopyState = 1; } catch (const std::exception& error) { if (module != VK_NULL_HANDLE) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); std::fprintf(stderr, "[gpu] staged write-backs copy their whole ranges: %s\n", error.what()); } } if (changedCopyState < 0) return false; static const bool alwaysCopy = std::getenv("APS5_CHANGED_COPY_ALWAYS") != nullptr; context.BindComputePipeline(commands, changedCopyPipeline); const auto dispatchLimit = static_cast(std::min(std::uint64_t{context.limits.maxComputeWorkGroupCount[0]} * GroupSize, std::numeric_limits::max() - GroupSize)); const auto perDispatch = dispatchLimit >= GroupSize ? dispatchLimit - dispatchLimit % GroupSize : dispatchLimit; for (std::uint32_t done = 0; done < dwords;) { const auto count = std::min(dwords - done, perDispatch); struct { VkDeviceAddress result; VkDeviceAddress snapshot; VkDeviceAddress target; VkDeviceAddress counter; std::uint32_t count; std::uint32_t always; } parameters{result + VkDeviceAddress{done} * 4u, snapshot + VkDeviceAddress{done} * 4u, target + VkDeviceAddress{done} * 4u, counter, count, alwaysCopy ? 1u : 0u}; static_assert(sizeof(parameters) == PushBytes); function(cmdPushConstants, "vkCmdPushConstants")(commands, changedCopyLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, PushBytes, ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, (count + GroupSize - 1) / GroupSize, 1, 1); done += count; } return true; } bool Recorder::RecordBoundChangedCopy(VkCommandBuffer commands, BoundWords result, BoundWords snapshot, BoundWords target, std::uint32_t dwords, VkBuffer counter) { constexpr std::uint32_t GroupSize = 64; struct Parameters { std::uint32_t resultBase; std::uint32_t snapshotBase; std::uint32_t targetBase; std::uint32_t count; std::uint32_t always; std::uint32_t counting; }; if (!context.pushDescriptors) return false; if (boundChangedCopyState == 0) { boundChangedCopyState = -1; VkShaderModule module = VK_NULL_HANDLE; try { std::array bindings{}; for (std::uint32_t binding = 0; binding < bindings.size(); ++binding) bindings[binding] = {binding, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; VkDescriptorSetLayoutCreateInfo setInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; setInfo.flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR; setInfo.bindingCount = static_cast(bindings.size()); setInfo.pBindings = bindings.data(); Check(context.Function("vkCreateDescriptorSetLayout")(context.device, &setInfo, nullptr, &boundChangedCopySetLayout), "vkCreateDescriptorSetLayout bound changed copy"); const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Parameters)}; VkPipelineLayoutCreateInfo layoutInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; layoutInfo.setLayoutCount = 1; layoutInfo.pSetLayouts = &boundChangedCopySetLayout; layoutInfo.pushConstantRangeCount = 1; layoutInfo.pPushConstantRanges = &push; Check(context.Function("vkCreatePipelineLayout")(context.device, &layoutInfo, nullptr, &boundChangedCopyLayout), "vkCreatePipelineLayout bound changed copy"); VkShaderModuleCreateInfo moduleInfo{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; moduleInfo.codeSize = sizeof(STAGING_COPY_BACK_BOUND_SPV); moduleInfo.pCode = STAGING_COPY_BACK_BOUND_SPV; Check(context.Function("vkCreateShaderModule")(context.device, &moduleInfo, nullptr, &module), "vkCreateShaderModule bound changed copy"); VkComputePipelineCreateInfo pipelineInfo{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; pipelineInfo.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; pipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; pipelineInfo.stage.module = module; pipelineInfo.stage.pName = "main"; pipelineInfo.layout = boundChangedCopyLayout; Check(context.Function("vkCreateComputePipelines")(context.device, context.pipelineCache, 1, &pipelineInfo, nullptr, &boundChangedCopyPipeline), "vkCreateComputePipelines bound changed copy"); context.Function("vkDestroyShaderModule")(context.device, module, nullptr); boundChangedCopyState = 1; } catch (const std::exception& error) { if (module != VK_NULL_HANDLE) context.Function("vkDestroyShaderModule")(context.device, module, nullptr); std::fprintf(stderr, "[gpu] staged write-backs do not bind their buffers: %s\n", error.what()); } } if (boundChangedCopyState < 0) return false; const auto alignment = std::max(context.limits.minStorageBufferOffsetAlignment, sizeof(std::uint32_t)); if (context.limits.maxStorageBufferRange <= alignment) return false; static const bool alwaysCopy = std::getenv("APS5_CHANGED_COPY_ALWAYS") != nullptr; const auto dispatchLimit = static_cast(std::min({std::uint64_t{context.limits.maxComputeWorkGroupCount[0]} * GroupSize, (context.limits.maxStorageBufferRange - alignment) / sizeof(std::uint32_t), std::numeric_limits::max() - GroupSize})); const auto perDispatch = dispatchLimit >= GroupSize ? dispatchLimit - dispatchLimit % GroupSize : dispatchLimit; context.BindComputePipeline(commands, boundChangedCopyPipeline); for (std::uint32_t done = 0; done < dwords;) { const auto count = std::min(dwords - done, perDispatch); const auto span = VkDeviceSize{count} * sizeof(std::uint32_t); std::array infos{}; std::array bases{}; const std::array words{result, snapshot, target}; for (std::size_t index = 0; index < words.size(); ++index) { const auto offset = words[index].offset + VkDeviceSize{done} * sizeof(std::uint32_t); const auto bound = offset / alignment * alignment; infos[index] = {words[index].buffer, bound, offset - bound + span}; bases[index] = static_cast((offset - bound) / sizeof(std::uint32_t)); } infos[3] = counter != VK_NULL_HANDLE ? VkDescriptorBufferInfo{counter, 0, sizeof(std::uint32_t)} : infos[0]; std::array writes{}; for (std::uint32_t binding = 0; binding < writes.size(); ++binding) { writes[binding] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; writes[binding].dstBinding = binding; writes[binding].descriptorCount = 1; writes[binding].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; writes[binding].pBufferInfo = &infos[binding]; } context.Function("vkCmdPushDescriptorSetKHR")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, boundChangedCopyLayout, 0, static_cast(writes.size()), writes.data()); const Parameters parameters{bases[0], bases[1], bases[2], count, alwaysCopy ? 1u : 0u, counter != VK_NULL_HANDLE ? 1u : 0u}; function(cmdPushConstants, "vkCmdPushConstants")(commands, boundChangedCopyLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(parameters), ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, (count + GroupSize - 1) / GroupSize, 1, 1); done += count; } return true; } void Recorder::beginSamples(Batch& batch) { auto cache = std::static_pointer_cast(samplePools); if (sampleCounterState > 0 && cache == nullptr) { cache = std::make_shared(); cache->device = context.device; cache->destroy = context.Function("vkDestroyQueryPool"); samplePools = cache; } batch.samples = sampleCounterState > 0 ? cache->take() : VK_NULL_HANDLE; if (batch.samples == VK_NULL_HANDLE) { VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; info.queryType = VK_QUERY_TYPE_OCCLUSION; info.queryCount = 1; Check(context.Function("vkCreateQueryPool")(context.device, &info, nullptr, &batch.samples), "vkCreateQueryPool occlusion"); } if (sampleCounterState > 0) { try { batch.samplePool = std::make_shared(cache, batch.samples); } catch (...) { cache->put(batch.samples); batch.samples = VK_NULL_HANDLE; throw; } } function(cmdResetQueryPool, "vkCmdResetQueryPool")(batch.commands, batch.samples, 0, 1); function(cmdBeginQuery, "vkCmdBeginQuery")(batch.commands, batch.samples, 0, context.occlusionQueryPrecise ? VK_QUERY_CONTROL_PRECISE_BIT : 0u); batch.sampleActive = true; batch.samplesDrawn = false; } void Recorder::readSamples(Batch& batch) { if (sampleCounterState > 0) return; if (batch.samples == VK_NULL_HANDLE || !batch.submitted) return; std::uint64_t total = 0; for (const auto pool : batch.endedSamples) { std::uint64_t samples = 0; Check(context.Function("vkGetQueryPoolResults")(context.device, pool, 0, 1, sizeof(samples), &samples, sizeof(samples), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT), "vkGetQueryPoolResults occlusion"); total += samples; } std::uint64_t samples = 0; Check(context.Function("vkGetQueryPoolResults")(context.device, batch.samples, 0, 1, sizeof(samples), &samples, sizeof(samples), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT), "vkGetQueryPoolResults occlusion"); samplesPassed.fetch_add(total + samples, std::memory_order_acq_rel); } void Recorder::readGpuTiming(Batch& batch) { if (batch.queries == VK_NULL_HANDLE || batch.timedKeys.empty()) return; std::vector stamps(batch.timedKeys.size() * 2); const auto result = context.Function("vkGetQueryPoolResults")(context.device, batch.queries, 0, static_cast(stamps.size()), stamps.size() * sizeof(std::uint64_t), stamps.data(), sizeof(std::uint64_t), VK_QUERY_RESULT_64_BIT); if (result != VK_SUCCESS) return; const auto period = context.limits.timestampPeriod; if (!GpuTimingEnabled()) { if (batch.batchTiming == 0 && stamps[1] >= stamps[0]) { batch.gpuStartNs = static_cast(stamps[0]) * period; batch.gpuEndNs = static_cast(stamps[1]) * period; PerformanceTrace::GpuRange("batch", batch.gpuStartNs, batch.gpuEndNs, batch.traceId); } return; } static auto lastReport = std::chrono::steady_clock::now(); // The union of the timed ranges (class ranges nest program ranges: a copy's transfer inside // its class range) against the batch span gives what no range covers. std::vector> intervals; intervals.reserve(batch.timedKeys.size()); std::unique_lock lock(timingMutex); for (std::size_t i = 0; i < batch.timedKeys.size(); ++i) { const auto ns = static_cast(stamps[i * 2 + 1] - stamps[i * 2]) * period; if (i == batch.batchTiming) { // The whole batch: apart from the per-program totals it contains. batch.gpuStartNs = static_cast(stamps[i * 2]) * period; batch.gpuEndNs = static_cast(stamps[i * 2 + 1]) * period; PerformanceTrace::GpuRange("batch", batch.gpuStartNs, batch.gpuEndNs, batch.traceId); timingBatchMs += ns / 1e6; AgcDriver::PerformanceCounters::AddGpuNanoseconds(static_cast(ns)); continue; } const auto key = batch.timedKeys[i]; if (key >= ClassKey(CommandClass::DispatchLeading) && key < ClassKey(CommandClass::Count)) PerformanceTrace::GpuRange(CommandClassNames[key - ClassKey(CommandClass::DispatchLeading)], static_cast(stamps[i * 2]) * period, static_cast(stamps[i * 2 + 1]) * period, batch.traceId); auto& totals = timingByKey[key]; ++totals.count; totals.ms += ns / 1e6; totals.bytes += batch.timedBytes[i]; (key >= ClassKey(CommandClass::DispatchLeading) && key < ClassKey(CommandClass::Count) ? timingClassMs : timingProgramMs) += ns / 1e6; intervals.emplace_back(stamps[i * 2], stamps[i * 2 + 1]); } std::sort(intervals.begin(), intervals.end()); std::uint64_t coveredTicks = 0, unionEnd = 0; for (const auto& [begin, end] : intervals) { const auto from = std::max(begin, unionEnd); if (end > from) coveredTicks += end - from; unionEnd = std::max(unionEnd, end); } timingUnionMs += static_cast(coveredTicks) * period / 1e6; ++timingBatches; const auto now = std::chrono::steady_clock::now(); if (now - lastReport < std::chrono::seconds(10)) return; lastReport = now; const auto presents = timingPresents.exchange(0, std::memory_order_relaxed); const double perPresent = presents != 0 ? 1.0 / static_cast(presents) : 0.0; std::vector> hot; std::string classes; for (const auto& [key, totals] : timingByKey) { if (key >= ClassKey(CommandClass::DispatchLeading) && key < ClassKey(CommandClass::Count)) { char text[160]; std::snprintf(text, sizeof(text), " %s x%llu %.1fms %.1fMiB (per present x%.1f %.2fms %.2fMiB)", CommandClassNames[key - ClassKey(CommandClass::DispatchLeading)], static_cast(totals.count), totals.ms, totals.bytes / 1048576.0, static_cast(totals.count) * perPresent, totals.ms * perPresent, totals.bytes / 1048576.0 * perPresent); classes += text; } else { hot.emplace_back(key, totals); } } 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. 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(" %s x%llu %.0fms", Recorder::TimingKeyLabel(hot[i].first).c_str(), 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; lock.unlock(); reportBarriers(); } bool Recorder::FlipReadCheck() { static const bool enabled = std::getenv("APS5_FLIP_READ_CHECK") != nullptr; return enabled; } std::vector Recorder::CompletedBatches(std::uint64_t afterSerial, std::uint64_t throughSerial, std::size_t& missing) const { std::vector found; missing = 0; if (throughSerial <= afterSerial) return found; std::lock_guard lock(completedMutex); for (auto serial = afterSerial + 1; serial <= throughSerial; ++serial) { const auto& entry = completed[serial % completed.size()]; if (entry.serial == serial) found.push_back(entry); else ++missing; } return found; } std::uint64_t Recorder::NewestSubmitted(std::chrono::steady_clock::time_point* submittedAt) const { std::lock_guard lock(completedMutex); if (submittedAt != nullptr) *submittedAt = newestSubmittedAt; return newestSubmitted; } std::size_t Recorder::UnsignaledBatches() const { return static_cast(std::count_if(inFlight.begin(), inFlight.end(), [&](const auto& batch) { return !signaled(*batch); })); } std::shared_ptr Recorder::UploadScratchBuffer(UploadScratch kind, std::size_t bytes) { Require(kind < UploadScratch::Count && bytes != 0, "invalid texture upload scratch request"); ensureOpen(); auto& scratch = open->uploadScratch[static_cast(kind)]; if (scratch == nullptr || scratch->Size() < bytes) { const VkBufferUsageFlags usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (kind == UploadScratch::Tiled ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT); scratch = std::make_shared(context, bytes, usage); Keep(scratch, bytes); } return scratch; } void Recorder::ReserveRetention(std::size_t additional) { ensureOpen(); if (additional > open->kept.max_size() - open->kept.size()) throw std::length_error("recorded owner count exceeds the batch capacity"); prepareRetention(additional); const auto needed = open->kept.size() + additional; if (needed <= open->kept.capacity()) return; const auto grown = open->kept.capacity() <= open->kept.max_size() / 2 ? open->kept.capacity() * 2 : open->kept.max_size(); open->kept.reserve(std::max(needed, grown)); } void Recorder::prepareRetention(std::size_t additional) { if (additional > retention.max_size() / 2 - retentionCount) throw std::length_error("recorded owner lookup exceeds the batch capacity"); const auto needed = (retentionCount + additional) * 2; if (needed <= retention.size()) return; auto capacity = std::max(64, retention.size()); while (capacity < needed) { if (capacity > retention.max_size() / 2) throw std::length_error("recorded owner lookup exceeds the batch capacity"); capacity *= 2; } std::vector grown(capacity); const auto mask = grown.size() - 1; for (const auto& slot : retention) { if (slot.epoch != retentionEpoch) continue; auto index = retentionHash(slot.object) & mask; while (grown[index].epoch == retentionEpoch) index = (index + 1) & mask; grown[index] = slot; } retention.swap(grown); } void Recorder::Keep(std::shared_ptr object, std::size_t bytes) { ensureOpen(); open->kept.push_back(std::move(object)); open->keptBytes += bytes; } void Recorder::KeepThroughHold(std::shared_ptr object) { GuestMemory::AssertGpuLockHeld("Recorder::KeepThroughHold"); if (const auto hold = GuestMemory::GpuHoldSerial(); hold != holdKeptSerial) { holdKept.clear(); holdKeptSerial = hold; } Keep(object); holdKept.push_back(std::move(object)); } void Recorder::dropStaleHoldKept() { if (!holdKept.empty() && holdKeptSerial != GuestMemory::GpuHoldSerial() && GuestMemory::GpuMutex().HeldByThisThread()) holdKept.clear(); } void Recorder::KeepBytes(const void* owner, std::size_t bytes) { if (owner == nullptr || bytes == 0) return; ensureOpen(); if (open->keptOwners.insert(owner).second) open->keptBytes += bytes; } void Recorder::BoundKeptBytes() { if (!GuestMemory::GpuMutex().HeldByThisThread()) return; if (open != nullptr && open->keptBytes >= KeptBytesBudget) Submit(); if (DeferredBytes() != 0 && inFlightKeptBytes + DeferredBytes() > 2 * KeptBytesBudget) DestroyDeferred(TakeDeferred(), false); while (!inFlight.empty() && inFlightKeptBytes > 2 * KeptBytesBudget) { auto batch = std::move(inFlight.front()); inFlight.pop_front(); finish(std::move(batch), true, 4, true); } } namespace { std::size_t SnapshotPool(Recorder::SnapshotUse use) { return use == Recorder::SnapshotUse::Storage ? 0 : 1; } } void Recorder::dropDrawInputMirror(std::map::iterator entry) { if (entry->second.mirror == nullptr) return; drawSnapshotPools[SnapshotPool(std::get<1>(entry->first))].bytes -= std::get<2>(entry->first); drawInputMirrorBytes -= std::get<2>(entry->first); entry->second.mirror.reset(); } void Recorder::eraseDrawSnapshot(std::map::iterator entry) { dropDrawInputMirror(entry); auto& pool = drawSnapshotPools[SnapshotPool(std::get<1>(entry->first))]; pool.bytes -= std::get<2>(entry->first); pool.recency.erase(entry->second.recent); if (!entry->second.owned.words.empty()) --ownedDrawInputs; drawSnapshots.erase(entry); } bool Recorder::DrawInputMirrors() { static const bool enabled = std::getenv("APS5_NO_INPUT_MIRRORS") == nullptr; return enabled; } std::pair Recorder::DrawInputBytes() const { return {drawSnapshotPools[SnapshotPool(SnapshotUse::Vertex)].bytes, drawInputMirrorBytes}; } std::shared_ptr Recorder::mirrorDrawInput(std::map::iterator entry) { const auto bytes = std::get<2>(entry->first); auto& pool = drawSnapshotPools[SnapshotPool(std::get<1>(entry->first))]; if (bytes > DrawInputMirrorBudget || 2 * bytes > DrawInputBudget || !context.HostMemoryType(~0u)) return {}; const auto host = entry->second.buffer; const auto copied = host->Bytes().size(); auto mirror = Buffer::WithinDeviceLocalHeadroom(context, copied, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); if (mirror == nullptr) return {}; for (auto oldest = pool.recency.begin(); drawInputMirrorBytes + bytes > DrawInputMirrorBudget && oldest != pool.recency.end(); ++oldest) { if (*oldest != entry->first) dropDrawInputMirror(drawSnapshots.find(*oldest)); } while (pool.bytes + bytes > DrawInputBudget && pool.recency.front() != entry->first) eraseDrawSnapshot(drawSnapshots.find(pool.recency.front())); const auto commands = Commands(); const auto timing = BeginGpuTiming(CommandClass::InputMirror); CopyBuffer(context, commands, host->Handle(), 0, mirror->Handle(), 0, copied); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDEX_READ_BIT); CountBarriers(CommandClass::InputMirror); EndGpuTiming(timing, copied); Keep(host); Keep(mirror); pool.bytes += bytes; drawInputMirrorBytes += bytes; return mirror; } Recorder::UploadSlice Recorder::DrawUpload(std::size_t bytes) { const VkDeviceSize alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 16); auto offset = (drawUploadUsed + alignment - 1) & ~(alignment - 1); if (drawUpload == nullptr || offset + bytes > drawUpload->Bytes().size()) { drawUpload = std::make_shared(context, std::max(DrawUploadChunk, bytes), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT); offset = 0; } drawUploadUsed = offset + bytes; return {drawUpload, offset, drawUpload->Bytes().data() + offset}; } void Recorder::retireUnwrittenSnapshots(const std::array& stamp) { if (stamp == unwrittenStamp) return; unwrittenSnapshots.clear(); unwrittenBytes = 0; unwrittenStamp = stamp; } std::shared_ptr Recorder::UnwrittenDrawSnapshot(std::uint64_t address, std::size_t bytes, const std::array& stamp, VkDeviceSize* offset) { retireUnwrittenSnapshots(stamp); const auto found = unwrittenSnapshots.find(address); if (found == unwrittenSnapshots.end() || found->second.bytes != bytes) return {}; if (offset != nullptr) *offset = found->second.offset; return found->second.buffer; } void Recorder::NoteUnwrittenDrawSnapshot(std::uint64_t address, std::size_t bytes, const std::array& stamp, std::shared_ptr buffer, VkDeviceSize offset) { retireUnwrittenSnapshots(stamp); if (const auto found = unwrittenSnapshots.find(address); found != unwrittenSnapshots.end()) { unwrittenBytes -= found->second.bytes; unwrittenSnapshots.erase(found); } if (unwrittenSnapshots.size() >= UnwrittenSnapshotEntries || bytes > DrawSnapshotBudget - unwrittenBytes) return; unwrittenSnapshots.emplace(address, UnwrittenSnapshot{bytes, std::move(buffer), offset}); unwrittenBytes += bytes; } bool Recorder::ShorterDrawSnapshotKept(std::uint64_t address, std::size_t bytes, SnapshotUse use) const { const auto registry = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); for (auto entry = drawSnapshots.lower_bound({address, use, 0}); entry != drawSnapshots.end() && std::get<0>(entry->first) == address && std::get<1>(entry->first) == use && std::get<2>(entry->first) < bytes; ++entry) { const auto kept = std::get<2>(entry->first); const auto from = entry->second.from; if (entry->second.owned.words.empty() && entry->second.registryGeneration == registry && GuestMemory::UnchangedSince(address + from, kept - from, entry->second.generation)) return true; } return false; } bool Recorder::GuestWritesPendingIn(std::uint64_t address, std::size_t bytes) const { return PendingWriteOverlaps(address, bytes) || PendingLabelIn(address, bytes) || QueuedStoreOverlaps(address, bytes) || (QueuedLabelsOnThread::Get() && QueuedLabelOverlaps(address, bytes)); } std::shared_ptr Recorder::ReusableDrawSnapshot(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived, std::uint64_t generation, VkDeviceSize* offset, std::size_t from, std::uint32_t* lowest, bool mirrored) { Require(from == 0 || (use == SnapshotUse::Vertex && from < bytes), "only a vertex snapshot starts past its address"); auto found = use == SnapshotUse::Vertex ? drawSnapshots.lower_bound({address, use, bytes}) : drawSnapshots.find({address, use, bytes}); if (found == drawSnapshots.end() || std::get<0>(found->first) != address || std::get<1>(found->first) != use) { if (use != SnapshotUse::Storage || offset == nullptr) return {}; return containingDrawSnapshot(address, bytes, offset); } if (offset != nullptr) *offset = 0; if (!found->second.owned.words.empty()) { eraseDrawSnapshot(found); return {}; } const bool sameRegistry = found->second.registryGeneration == GuestAllocations::GuestAllocationsGeneration_nid_postfix(); const auto guestBytes = use == SnapshotUse::PaddedVertex ? static_cast(found->second.derived) : bytes; const auto held = std::max(from, found->second.from); if (!sameRegistry || (held < guestBytes && !GuestMemory::UnchangedSince(address + held, guestBytes - held, found->second.generation))) { if (!sameRegistry || generation == 0 || use != SnapshotUse::Storage || !refreshDrawSnapshot(found->second, address, bytes)) { eraseDrawSnapshot(found); return {}; } found->second.generation = generation; } if (found->second.from > from) { const auto start = from - std::min(from, std::get<2>(found->first) - found->second.from); GuestMemory::Read(address + start, found->second.buffer->Bytes().subspan(start, found->second.from - start), 1); found->second.from = start; dropDrawInputMirror(found); } auto& recency = drawSnapshotPools[SnapshotPool(use)].recency; recency.splice(recency.end(), recency, found->second.recent); if (derived != nullptr) *derived = found->second.derived; if (lowest != nullptr) *lowest = found->second.lowest; if (!mirrored || use == SnapshotUse::Storage || !DrawInputMirrors()) return found->second.buffer; if (found->second.mirror == nullptr) found->second.mirror = mirrorDrawInput(found); return found->second.mirror != nullptr ? found->second.mirror : found->second.buffer; } std::shared_ptr Recorder::containingDrawSnapshot(std::uint64_t address, std::size_t bytes, VkDeviceSize* offset) { const VkDeviceSize alignment = std::max(context.limits.minStorageBufferOffsetAlignment, 4); const auto registry = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); auto entry = drawSnapshots.upper_bound({address, SnapshotUse::Storage, std::numeric_limits::max()}); for (std::size_t probe = 0; probe < ContainingSnapshotProbes && entry != drawSnapshots.begin(); ++probe) { --entry; const auto& [start, use, held] = entry->first; if (use != SnapshotUse::Storage || start + held < address + bytes || (address - start) % alignment != 0) continue; if (entry->second.registryGeneration != registry || !GuestMemory::UnchangedSince(address, bytes, entry->second.generation)) continue; auto& recency = drawSnapshotPools[SnapshotPool(use)].recency; recency.splice(recency.end(), recency, entry->second.recent); *offset = address - start; return entry->second.buffer; } return {}; } bool Recorder::refreshDrawSnapshot(DrawSnapshot& entry, std::uint64_t address, std::size_t bytes) { const auto held = entry.buffer->Bytes(); if (held.size() != bytes || bytes == 0) return false; constexpr std::uint64_t block = 65536; const auto aligned = address / block * block; const auto end = address + bytes; const auto count = static_cast((end - 1) / block - address / block + 1); struct Scratch { std::vector generations; std::vector changed; std::vector> differing; std::vector spans; std::vector equal; }; auto& scratch = HostThreadLocal(); auto& generations = scratch.generations; auto& changed = scratch.changed; auto& differing = scratch.differing; auto& spans = scratch.spans; auto& equal = scratch.equal; generations.assign(count, entry.generation); changed.assign(count, GuestMemory::BlockWritten); differing.clear(); spans.clear(); const bool sole = entry.buffer.use_count() == 1; GuestMemory::ChangedBlocks(address, bytes, generations, changed); for (std::size_t k = 0; k < count; ++k) { if (changed[k] == GuestMemory::BlockUnchanged) continue; const auto from = std::max(address, aligned + k * block); const auto to = std::min(end, aligned + (k + 1) * block); const auto offset = static_cast(from - address); spans.push_back({held.data() + offset, reinterpret_cast(from), static_cast(to - from)}); } equal.assign(spans.size(), 0); CompareSpans(spans, equal); for (std::size_t k = 0; k < spans.size(); ++k) { if (equal[k] != 0) continue; const auto offset = static_cast(static_cast(spans[k].first) - held.data()); const auto length = spans[k].bytes; if (!sole) return false; if (!differing.empty() && differing.back().first + differing.back().second == offset) differing.back().second += length; else differing.emplace_back(offset, length); } for (const auto& [offset, length] : differing) std::memcpy(held.data() + offset, reinterpret_cast(address + offset), length); return true; } static void OwnedDrawTraceCount(const char* name, std::uint64_t amount = 1) { PerformanceTrace::CountOwnedDraw(name, amount); } void Recorder::KeepDrawSnapshot(std::uint64_t address, std::size_t bytes, std::uint64_t generation, std::uint64_t registryGeneration, std::shared_ptr buffer, SnapshotUse use, std::uint32_t derived, std::size_t from, std::uint32_t lowest, bool ownedInsertion) { Require(from == 0 || (use == SnapshotUse::Vertex && from < bytes), "only a vertex snapshot starts past its address"); const bool storage = use == SnapshotUse::Storage; const auto budget = storage ? DrawSnapshotBudget : DrawInputBudget; const auto maxEntries = storage ? DrawSnapshotEntries : DrawInputEntries; auto& pool = drawSnapshotPools[SnapshotPool(use)]; if (generation == 0 || bytes > budget) return; if (use == SnapshotUse::Vertex) { for (auto it = drawSnapshots.lower_bound({address, use, 0}); it != drawSnapshots.end() && std::get<0>(it->first) == address && std::get<1>(it->first) == use && std::get<2>(it->first) <= bytes;) eraseDrawSnapshot(it++); } else if (const auto found = drawSnapshots.find({address, use, bytes}); found != drawSnapshots.end()) { eraseDrawSnapshot(found); } while (!pool.recency.empty() && (pool.bytes + bytes > budget || pool.recency.size() >= maxEntries)) { const auto victim = drawSnapshots.find(pool.recency.front()); if (!storage) { const bool ownedVictim = !victim->second.owned.words.empty(); OwnedDrawTraceCount(ownedVictim ? "OwnedDraw.evicted_owned" : "OwnedDraw.evicted_other"); if (ownedInsertion) OwnedDrawTraceCount(ownedVictim ? "OwnedDraw.evicted_owned_by_owned" : "OwnedDraw.evicted_other_by_owned"); } eraseDrawSnapshot(victim); } const DrawSnapshotKey key{address, use, bytes}; pool.recency.push_back(key); try { drawSnapshots.emplace(key, DrawSnapshot{generation, registryGeneration, std::prev(pool.recency.end()), std::move(buffer), derived, from, lowest, nullptr}); } catch (...) { pool.recency.pop_back(); throw; } pool.bytes += bytes; } Recorder::OwnedDrawInputProof Recorder::ArmOwnedDrawInput(std::uint64_t address, std::size_t bytes) const { GuestMemory::AssertGpuLockHeld("arm owned draw input"); OwnedDrawTraceCount("OwnedDraw.arm_attempt"); if (bytes == 0 || bytes > DrawInputBudget || bytes > std::numeric_limits::max() - address || !GuestMemory::WriteWatched() || PendingWriteOverlaps(address, bytes)) { OwnedDrawTraceCount("OwnedDraw.arm_refused"); return {}; } OwnedDrawInputProof proof; proof.words.resize((address + bytes - 1) / 65536 - address / 65536 + 1); OwnedDrawTraceCount("OwnedDraw.arm_blocks_requested", proof.words.size()); if (!GuestArena::GuestArenaArmOwned_nid_no_patch(static_cast(address), bytes, proof.words.data(), proof.words.size(), 1)) { OwnedDrawTraceCount("OwnedDraw.arm_refused"); return {}; } proof.registry = GuestAllocations::GuestAllocationsGeneration_nid_postfix(); proof.forget = GuestMemory::ForgetSerial(); proof.since = GuestMemory::TrackerGeneration(); proof.note = NewestWriteNote(address, bytes); if (proof.since == 0 || (proof.forget & 1u) != 0) { OwnedDrawTraceCount("OwnedDraw.arm_refused"); return {}; } OwnedDrawTraceCount("OwnedDraw.arm_success"); return proof; } bool Recorder::ownedDrawInputHolds(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof) const { GuestMemory::AssertGpuLockHeld("check owned draw input"); OwnedDrawTraceCount("OwnedDraw.proof_check"); if (proof.words.empty() || proof.since == 0 || (proof.forget & 1u) != 0 || !GuestMemory::WriteWatched()) return false; if (proof.registry != GuestAllocations::GuestAllocationsGeneration_nid_postfix() || proof.forget != GuestMemory::ForgetSerial()) return false; if (PendingWriteOverlaps(address, bytes) || proof.note != NewestWriteNote(address, bytes) || GuestMemory::NewestStamp(address, bytes) > proof.since) return false; OwnedDrawTraceCount("OwnedDraw.arena_check"); OwnedDrawTraceCount("OwnedDraw.check_blocks_requested", proof.words.size()); return GuestArena::GuestArenaOwnedUnchanged_nid_no_patch(static_cast(address), bytes, proof.words.data(), proof.words.size()); } std::shared_ptr Recorder::ReusableOwnedDrawInput(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint32_t* derived, std::size_t from, std::uint32_t* lowest) { GuestMemory::AssertGpuLockHeld("reuse owned draw input"); Require(use != SnapshotUse::Storage, "an owned draw input is a vertex or index buffer"); const auto found = drawSnapshots.find({address, use, bytes}); if (found == drawSnapshots.end() || found->second.owned.words.empty() || found->second.from > from) return {}; if (!ownedDrawInputHolds(address, bytes, found->second.owned)) { OwnedDrawTraceCount("OwnedDraw.invalidated"); eraseDrawSnapshot(found); return {}; } static const bool verify = std::getenv("APS5_VERIFY_OWNED_DRAW_INPUTS") != nullptr; if (verify) { const auto held = found->second.from; const bool equal = GuestMemory::EqualsCommittedUnsynced(address + held, found->second.buffer->Bytes().subspan(held)); if (!ownedDrawInputHolds(address, bytes, found->second.owned)) { eraseDrawSnapshot(found); return {}; } Require(equal, "an owned draw input differs while its proof holds"); } auto& recency = drawSnapshotPools[SnapshotPool(use)].recency; recency.splice(recency.end(), recency, found->second.recent); if (derived != nullptr) *derived = found->second.derived; if (lowest != nullptr) *lowest = found->second.lowest; OwnedDrawTraceCount("OwnedDraw.reused"); return found->second.buffer; } void Recorder::KeepOwnedDrawInput(std::uint64_t address, std::size_t bytes, const OwnedDrawInputProof& proof, std::shared_ptr buffer, SnapshotUse use, std::uint32_t derived, std::size_t from, std::uint32_t lowest) { Require(use != SnapshotUse::Storage, "an owned draw input is a vertex or index buffer"); if (buffer == nullptr || buffer->Bytes().size() != bytes || !ownedDrawInputHolds(address, bytes, proof)) return; auto kept = proof; KeepDrawSnapshot(address, bytes, proof.since, proof.registry, std::move(buffer), use, derived, from, lowest, true); if (const auto found = drawSnapshots.find({address, use, bytes}); found != drawSnapshots.end()) { found->second.owned = std::move(kept); ++ownedDrawInputs; } } bool Recorder::KnownHighestIndex(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::optional& highest, std::uint32_t* lowest) { const auto found = indexRanges.find({address, use, bytes}); if (found == indexRanges.end()) return false; if (found->second.registryGeneration != GuestAllocations::GuestAllocationsGeneration_nid_postfix() || !GuestMemory::UnchangedSince(address, bytes, found->second.generation)) { indexRangeRecency.erase(found->second.recent); indexRanges.erase(found); return false; } indexRangeRecency.splice(indexRangeRecency.end(), indexRangeRecency, found->second.recent); highest = found->second.highest; if (lowest != nullptr) *lowest = found->second.lowest; return true; } void Recorder::KeepHighestIndex(std::uint64_t address, std::size_t bytes, SnapshotUse use, std::uint64_t generation, std::uint64_t registryGeneration, std::optional highest, std::uint32_t lowest) { Require(use != SnapshotUse::Storage && use != SnapshotUse::Vertex, "a highest index belongs to an index buffer"); if (generation == 0) return; const DrawSnapshotKey key{address, use, bytes}; if (const auto found = indexRanges.find(key); found != indexRanges.end()) { indexRangeRecency.erase(found->second.recent); indexRanges.erase(found); } while (indexRanges.size() >= IndexRangeEntries) { indexRanges.erase(indexRangeRecency.front()); indexRangeRecency.pop_front(); } indexRangeRecency.push_back(key); try { indexRanges.emplace(key, IndexRange{generation, registryGeneration, std::prev(indexRangeRecency.end()), highest, lowest}); } catch (...) { indexRangeRecency.pop_back(); throw; } } void Recorder::OnComplete(std::function action) { ensureOpen(); open->completions.push_back(std::move(action)); ++open->writeBackCompletionCount; writeBackCompletions.fetch_add(1, std::memory_order_acq_rel); } void Recorder::OnWriteComplete(std::uint64_t address, std::size_t bytes, std::function action) { const auto end = address + bytes; Batch* holder = open != nullptr && overlaps(*open, address, end) ? open.get() : nullptr; for (auto batch = inFlight.rbegin(); holder == nullptr && batch != inFlight.rend(); ++batch) { if (overlaps(**batch, address, end)) holder = batch->get(); } if (holder == nullptr) { action(); return; } holder->completions.push_back(std::move(action)); ++holder->writeBackCompletionCount; writeBackCompletions.fetch_add(1, std::memory_order_acq_rel); } bool Recorder::noteWrite(std::uint64_t address, std::size_t bytes, bool ownLabel, int value, std::int64_t word) { CaptureTrace::Log("buffer-write batch=%llu address=%llx bytes=%zu label=%d", static_cast(sealedThrough + 1), static_cast(address), bytes, ownLabel); if (bytes == 0) return false; GuestMemory::ForgetKnownZero(address, bytes); ensureOpen(); const auto end = address + bytes; open->writes.emplace_back(address, end); open->writeNotes.push_back(++writeNoteCount); if (published != nullptr && !SnapshotCovers(published.get(), address, end)) published = nullptr; open->writeValues.push_back(static_cast(value)); open->writeWords.push_back(word); if (!ownLabel) markOverwritten(address, end); // A poller waiting on this range learns that the open batch may now hold its producer. if (activeRecorder == this) writeGeneration.fetch_add(1, std::memory_order_release); // Consecutive dispatches write the same output buffers: a range the snapshot already contains // leaves the published union unchanged, so the O(N log N) rebuild is skipped. if (SnapshotCovers(address, end)) { ++snapshotCovered; return false; } return true; } void Recorder::noteWriteOn(Batch& batch, std::uint64_t address, std::size_t bytes, bool ownLabel) { if (bytes == 0) return; if (&batch != open.get()) GuestMemory::ForgetKnownZero(address, bytes); if (&batch == open.get()) { if (!noteWrite(address, bytes, ownLabel)) return; const std::array ranges{std::pair{address, address + bytes}}; publishPendingWrites(ranges); std::atomic_thread_fence(std::memory_order_seq_cst); return; } // An in-flight batch: its range joins the snapshot at once (the completion that stores it runs // when the batch finishes, and the hook must sync for a CPU read until then). The generation // moves as well, so a poller re-consults the label table for a completion label. batch.writes.emplace_back(address, address + bytes); batch.writeNotes.push_back(++writeNoteCount); if (published != nullptr && !SnapshotCovers(published.get(), address, address + bytes)) published = nullptr; batch.writeValues.push_back(-1); batch.writeWords.push_back(-1); if (!ownLabel) markOverwritten(address, address + bytes); if (activeRecorder == this) writeGeneration.fetch_add(1, std::memory_order_release); if (!SnapshotCovers(address, address + bytes)) { const std::array ranges{std::pair{address, address + bytes}}; publishPendingWrites(ranges); } std::atomic_thread_fence(std::memory_order_seq_cst); } void Recorder::markOverwritten(std::uint64_t address, std::uint64_t end) { if (recordedLabels.load(std::memory_order_relaxed) == 0 && recordedWideLabels.load(std::memory_order_relaxed) == 0) return; std::lock_guard tableLock(labelTableMutex); // A dword overlaps the range when it starts before the end and ends after the start. for (auto it = labels.lower_bound(address >= 3 ? address - 3 : 0); it != labels.end() && it->first < end; ++it) it->second.overwritten = true; for (auto it = wideLabels.lower_bound(address >= wideLabelBytes ? address - wideLabelBytes + 1 : 0); it != wideLabels.end() && it->first < end; ++it) { if (it->second.end > address) it->second.overwritten = true; } } void Recorder::NotePendingWrite(std::uint64_t address, std::size_t bytes) { if (!noteWrite(address, bytes)) return; const std::array ranges{std::pair{address, address + bytes}}; publishPendingWrites(ranges); // The note precedes this thread's vkQueueSubmit and the label another queue polls for; the // fence makes that order hold without relying on x86 store ordering. std::atomic_thread_fence(std::memory_order_seq_cst); } void Recorder::NotePendingFill(std::uint64_t address, std::size_t bytes, std::uint8_t value) { if (!noteWrite(address, bytes, false, value, value * std::int64_t{0x01010101})) return; const std::array ranges{std::pair{address, address + bytes}}; publishPendingWrites(ranges); std::atomic_thread_fence(std::memory_order_seq_cst); } void Recorder::NotePendingWordFill(std::uint64_t address, std::size_t bytes, std::uint32_t word) { const int value = word == (word & 0xffu) * 0x01010101u ? static_cast(word & 0xffu) : -1; if (!noteWrite(address, bytes, false, value, word)) return; const std::array ranges{std::pair{address, address + bytes}}; publishPendingWrites(ranges); std::atomic_thread_fence(std::memory_order_seq_cst); } void Recorder::NotePendingWrites(std::span> ranges) { notePendingRanges(ranges, -1); } void Recorder::NotePendingReach(std::span> ranges) { notePendingRanges(ranges, ReachValue); } void Recorder::notePendingRanges(std::span> ranges, int value) { bool publish = false; for (const auto& [begin, end] : ranges) { if (end > begin && noteWrite(begin, static_cast(end - begin), false, value)) publish = true; } if (!publish) return; publishPendingWrites(ranges); std::atomic_thread_fence(std::memory_order_seq_cst); } void Recorder::NoteStampedWrites(std::span> ranges) { const auto first = writeNoteCount + 1; NotePendingWrites(ranges); if (open == nullptr) return; for (auto note = first; note <= writeNoteCount; ++note) open->stampedNotes.push_back(note); } void Recorder::publishPendingWrites(std::span> additions) const { if (activeRecorder != this) { publishedWriteRangesValid = false; return; } const auto started = DrawProfiled() ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; const auto previous = pendingWrites.load(std::memory_order_acquire); const auto owned = publishedWriteRanges.lock(); const bool extend = !additions.empty() && previous != nullptr && previous == owned && publishedWriteRangesValid && std::all_of(additions.begin(), additions.end(), [](const auto& range) { return range.second > range.first; }); publishedWriteRangesValid = false; auto merged = std::make_shared(); if (extend && additions.size() == 1) { auto range = additions.front(); const auto first = std::partition_point(previous->begin(), previous->end(), [&](const auto& entry) { return entry.second < range.first; }); auto last = first; while (last != previous->end() && last->first <= range.second) { range.first = std::min(range.first, last->first); range.second = std::max(range.second, last->second); ++last; } merged->reserve(previous->size() - static_cast(last - first) + 1); merged->insert(merged->end(), previous->begin(), first); merged->push_back(range); merged->insert(merged->end(), last, previous->end()); } else { if (extend) { merged->reserve(previous->size() + additions.size()); merged->insert(merged->end(), previous->begin(), previous->end()); merged->insert(merged->end(), additions.begin(), additions.end()); } else { if (open != nullptr) merged->insert(merged->end(), open->writes.begin(), open->writes.end()); for (const auto& batch : inFlight) merged->insert(merged->end(), batch->writes.begin(), batch->writes.end()); for (const auto* batch : finishing) merged->insert(merged->end(), batch->writes.begin(), batch->writes.end()); } std::sort(merged->begin(), merged->end()); std::size_t out = 0; for (const auto& [begin, end] : *merged) { if (out != 0 && begin <= (*merged)[out - 1].second) (*merged)[out - 1].second = std::max((*merged)[out - 1].second, end); else (*merged)[out++] = {begin, end}; } merged->resize(out); } publishedWriteRangesValid = std::all_of(merged->begin(), merged->end(), [](const auto& range) { return range.second > range.first; }); publishedWriteRanges = merged; published = merged; pendingWrites.store(std::move(merged), std::memory_order_release); publishGeneration.fetch_add(1, std::memory_order_release); ++snapshotRebuilds; if (DrawProfiled()) snapshotRebuildMs += std::chrono::duration(std::chrono::steady_clock::now() - started).count(); } bool Recorder::overlaps(const Batch& batch, std::uint64_t address, std::uint64_t end) { for (const auto& [begin, finish] : batch.writes) { if (address < finish && begin < end) return true; } return false; } bool Recorder::PendingWriteOverlaps(std::uint64_t address, std::size_t bytes) const { if (bytes == 0) return false; if (published != nullptr && !SnapshotOverlaps(published.get(), address, bytes)) return false; const auto end = address + bytes; if (open != nullptr && overlaps(*open, address, end)) return true; for (const auto& batch : inFlight) { if (overlaps(*batch, address, end)) return true; } return false; } bool Recorder::PendingStoreOverlaps(std::uint64_t address, std::size_t bytes) const { if (bytes == 0) return false; if (published != nullptr && !SnapshotOverlaps(published.get(), address, bytes)) return false; const auto end = address + bytes; const auto stores = [&](const Batch& batch) { for (std::size_t index = 0; index < batch.writes.size(); ++index) { if (batch.writeValues[index] != ReachValue && address < batch.writes[index].second && batch.writes[index].first < end) return true; } return false; }; if (open != nullptr && stores(*open)) return true; return std::any_of(inFlight.begin(), inFlight.end(), [&](const auto& batch) { return stores(*batch); }); } bool Recorder::OpenWriteOverlaps(std::uint64_t address, std::size_t bytes) const { return bytes != 0 && open != nullptr && overlaps(*open, address, address + bytes); } std::uint64_t Recorder::PendingWriterSerial(std::uint64_t address, std::size_t bytes) const { if (bytes == 0) return 0; const auto end = address + bytes; const auto writes = [&](const Batch& batch) { return overlaps(batch, address, end) || readOverlap(batch, address, end, ReadKind::AddressBased).has_value(); }; if (open != nullptr && writes(*open)) return OpenSerial(); for (auto it = inFlight.rbegin(); it != inFlight.rend(); ++it) { if (writes(**it)) return (*it)->serial; } return 0; } std::uint64_t Recorder::PendingWriterSerial(std::uint64_t address, std::size_t bytes, std::span exceptNotes) const { if (exceptNotes.empty()) return PendingWriterSerial(address, bytes); if (bytes == 0) return 0; const auto end = address + bytes; const auto writes = [&](const Batch& batch) { for (std::size_t index = 0; index < batch.writes.size(); ++index) { const auto& [begin, finish] = batch.writes[index]; if (address >= finish || begin >= end) continue; if (index < batch.writeNotes.size() && std::find(exceptNotes.begin(), exceptNotes.end(), batch.writeNotes[index]) != exceptNotes.end()) continue; return true; } return readOverlap(batch, address, end, ReadKind::AddressBased).has_value(); }; if (open != nullptr && writes(*open)) return OpenSerial(); for (auto it = inFlight.rbegin(); it != inFlight.rend(); ++it) { if (writes(**it)) return (*it)->serial; } return 0; } std::uint64_t Recorder::PendingLeaseSerial(std::uint64_t address, std::size_t bytes) const { if (bytes == 0) return 0; const auto end = address + bytes; const auto leases = [&](const Batch& batch) { return readOverlap(batch, address, end, ReadKind::AddressBased).has_value(); }; if (open != nullptr && leases(*open)) return OpenSerial(); for (auto it = inFlight.rbegin(); it != inFlight.rend(); ++it) { if (leases(**it)) return (*it)->serial; } return 0; } bool Recorder::signaled(const Batch& batch) const { return batch.submitted && gpuDone(batch); } std::uint64_t Recorder::readTimeline() const { std::uint64_t value = 0; if (function(getSemaphoreCounterValue, "vkGetSemaphoreCounterValueKHR")(context.device, timeline, &value) == VK_SUCCESS && value > reachedSerial) reachedSerial = value; return reachedSerial; } bool Recorder::gpuDone(const Batch& batch) const { if (!fenceless) return fenceStatus(batch.fence) == VK_SUCCESS; return batch.serial != 0 && (batch.serial <= reachedSerial || batch.serial <= readTimeline()); } bool Recorder::PendingWriteSettled(std::uint64_t address, std::size_t bytes) const { if (bytes == 0) return true; const auto end = address + bytes; if (open != nullptr && overlaps(*open, address, end)) return false; for (const auto& batch : inFlight) { if (overlaps(*batch, address, end) && !signaled(*batch)) return false; } return true; } std::vector Recorder::StampedNotesSince(std::uint64_t note) const { std::vector notes; const auto collect = [&](const Batch& batch) { for (const auto stamped : batch.stampedNotes) { if (stamped > note) notes.push_back(stamped); } }; for (const auto& batch : inFlight) collect(*batch); if (open != nullptr) collect(*open); return notes; } std::uint64_t Recorder::LastWriteNote(std::uint64_t address, std::size_t bytes) const { if (open == nullptr || open->writes.empty() || open->writeNotes.size() != open->writes.size()) return 0; if (open->writes.back() != std::pair{address, address + bytes}) return 0; return open->writeNotes.back() == writeNoteCount ? writeNoteCount : 0; } std::uint64_t Recorder::NewestWriteNote(std::uint64_t address, std::size_t bytes) const { return newestNote(address, bytes, true); } std::uint64_t Recorder::NewestStoreNote(std::uint64_t address, std::size_t bytes) const { return newestNote(address, bytes, false); } std::uint64_t Recorder::newestNote(std::uint64_t address, std::size_t bytes, bool reach) const { if (bytes == 0) return 0; const auto end = address + bytes; std::uint64_t newest = 0; const auto scan = [&](const Batch& batch) { for (std::size_t i = 0; i < batch.writes.size(); ++i) { if ((reach || batch.writeValues[i] != ReachValue) && address < batch.writes[i].second && batch.writes[i].first < end) newest = std::max(newest, batch.writeNotes[i]); } }; if (open != nullptr) scan(*open); for (const auto& batch : inFlight) scan(*batch); return newest; } std::vector Recorder::PendingWritesOver(std::uint64_t address, std::size_t bytes) const { std::vector found; if (bytes == 0) return found; const auto end = address + bytes; const auto scan = [&](const Batch& batch) { for (std::size_t i = 0; i < batch.writes.size(); ++i) { if (address < batch.writes[i].second && batch.writes[i].first < end) found.push_back({batch.writes[i].first, batch.writes[i].second, batch.writeNotes[i], batch.writeValues[i], batch.writeWords[i]}); } }; if (open != nullptr) scan(*open); for (const auto& batch : inFlight) scan(*batch); return found; } void Recorder::PendingWriteRanges(std::vector>& ranges) const { ranges.clear(); if (open != nullptr) ranges.insert(ranges.end(), open->writes.begin(), open->writes.end()); for (const auto& batch : inFlight) ranges.insert(ranges.end(), batch->writes.begin(), batch->writes.end()); } bool Recorder::ReadTracking() { return ReadTrackingEnabled(); } void Recorder::NotePendingRead(std::uint64_t address, std::size_t bytes, ReadKind kind) { CaptureTrace::Log("buffer-read batch=%llu address=%llx bytes=%zu kind=%d", static_cast(sealedThrough + 1), static_cast(address), bytes, static_cast(kind)); if (bytes == 0 || !ReadTrackingEnabled()) return; ensureOpen(); open->reads.push_back({address, address + bytes, kind}); readsNoted.Add(1); } void Recorder::NotePendingReads(std::span> ranges, ReadKind kind) { if (ranges.empty() || !ReadTrackingEnabled()) return; ensureOpen(); for (const auto& [begin, end] : ranges) { CaptureTrace::Log("buffer-read batch=%llu address=%llx bytes=%llu kind=%d", static_cast(sealedThrough + 1), static_cast(begin), static_cast(end - begin), static_cast(kind)); if (end > begin) open->reads.push_back({begin, end, kind}); } readsNoted.Add(ranges.size()); } bool Recorder::ValidReadList(const ReadList& ranges) { for (std::size_t index = 0; index < ranges.size(); ++index) { if (ranges[index].second <= ranges[index].first) return false; if (index != 0 && ranges[index].first < ranges[index - 1].second) return false; } return true; } void Recorder::NotePendingReadList(std::shared_ptr ranges, ReadKind kind) { if (ranges == nullptr || ranges->empty() || !ReadTrackingEnabled()) return; if (CaptureTrace::Enabled() || FlipReadCheck()) { NotePendingReads(*ranges, kind); return; } ensureOpen(); readsNoted.Add(ranges->size()); for (const auto& note : open->readLists) { if (note.ranges == ranges && note.kind == kind) return; } open->readLists.push_back({std::move(ranges), open->reads.size(), kind}); } std::optional Recorder::readOverlap(const Batch& batch, std::uint64_t address, std::uint64_t end, std::optional only) { const auto listOverlaps = [&](const Batch::ReadListNote& note) { if (only.has_value() && note.kind != *only) return false; const auto& list = *note.ranges; const auto found = std::partition_point(list.begin(), list.end(), [&](const auto& range) { return range.second <= address; }); return found != list.end() && found->first < end; }; std::size_t next = 0; for (std::size_t index = 0; index < batch.reads.size(); ++index) { for (; next < batch.readLists.size() && batch.readLists[next].position == index; ++next) { if (listOverlaps(batch.readLists[next])) return batch.readLists[next].kind; } const auto& read = batch.reads[index]; if ((!only.has_value() || read.kind == *only) && address < read.end && read.begin < end) return read.kind; } for (; next < batch.readLists.size(); ++next) { if (listOverlaps(batch.readLists[next])) return batch.readLists[next].kind; } return std::nullopt; } std::vector> Recorder::notedReads(const Batch& batch) { std::vector> result; std::size_t next = 0; const auto expand = [&](std::size_t position) { for (; next < batch.readLists.size() && batch.readLists[next].position == position; ++next) result.insert(result.end(), batch.readLists[next].ranges->begin(), batch.readLists[next].ranges->end()); }; for (std::size_t index = 0; index < batch.reads.size(); ++index) { expand(index); result.emplace_back(batch.reads[index].begin, batch.reads[index].end); } expand(batch.reads.size()); return result; } bool Recorder::PendingReadOverlaps(std::uint64_t address, std::size_t bytes, bool ignoreSignaled) const { if (bytes == 0) return false; readQueries.Add(1); const auto end = address + bytes; if (open != nullptr) { if (const auto kind = readOverlap(*open, address, end)) { readHits[static_cast(*kind)].Add(1); return true; } } // Newest first: the batch most likely still running decides without a status query per batch. for (auto it = inFlight.rbegin(); it != inFlight.rend(); ++it) { const auto kind = readOverlap(**it, address, end); if (!kind.has_value()) continue; if (ignoreSignaled && signaled(**it)) { readStaleIgnored.Add(1); continue; } readHits[static_cast(*kind)].Add(1); return true; } return false; } std::optional Recorder::DescribePendingRead(std::uint64_t address, std::size_t bytes) const { if (bytes == 0) return std::nullopt; const auto end = address + bytes; if (open != nullptr) { if (const auto kind = readOverlap(*open, address, end)) return PendingReadInfo{sealedThrough + 1, open->queue, *kind, true, false}; } for (auto it = inFlight.rbegin(); it != inFlight.rend(); ++it) { if (const auto kind = readOverlap(**it, address, end)) return PendingReadInfo{(*it)->serial, (*it)->queue, *kind, false, signaled(**it)}; } return std::nullopt; } Recorder::ReadStatistics Recorder::ReadCounts() { ReadStatistics counts{readsNoted.Sum(), readQueries.Sum(), readStaleIgnored.Sum(), {}}; for (std::size_t kind = 0; kind < ReadKinds; ++kind) counts.hits[kind] = readHits[kind].Sum(); return counts; } std::optional Recorder::DescribePendingWrite(std::uint64_t address, std::size_t bytes) const { if (bytes == 0) return std::nullopt; const auto end = address + bytes; // The same choice SyncThrough makes: the open batch forces a full Sync, otherwise the newest // overlapping in-flight batch is the target. Of that batch's ranges the first overlapping one // is reported (a dispatch notes each written V# once, so it is the range the access hit). const auto firstOverlap = [&](const Batch& batch) -> const std::pair* { for (const auto& range : batch.writes) { if (address < range.second && range.first < end) return ⦥ } return nullptr; }; // With SyncThrough disabled every hit is a full Sync: the open batch (if any) is submitted and // everything in flight finishes, whichever batch noted the range. const bool syncAll = !SyncThroughEnabled(); const auto allBatches = inFlight.size() + (open != nullptr ? 1 : 0); if (open != nullptr) { if (const auto* range = firstOverlap(*open)) return PendingWriteInfo{sealedThrough + 1, true, false, range->first, range->second, inFlight.size() + 1}; } std::size_t finished = inFlight.size(); for (auto it = inFlight.rbegin(); it != inFlight.rend(); ++it, --finished) { const auto* range = firstOverlap(**it); if (range == nullptr) continue; // In flight means submitted, so the fence is live; signaled = the GPU already ran it. const bool signaled = gpuDone(**it); if (syncAll) return PendingWriteInfo{submissions + (open != nullptr ? 1 : 0), open != nullptr, signaled, range->first, range->second, allBatches}; return PendingWriteInfo{(*it)->serial, false, signaled, range->first, range->second, finished}; } return std::nullopt; } bool Recorder::HasCompletions() const { if (open != nullptr && !open->completions.empty()) return true; for (const auto& batch : inFlight) { if (!batch->completions.empty()) return true; } return false; } void Recorder::noteLabelOn(Batch& batch, std::uint64_t address, std::span bytes, std::uint64_t stamp, std::uint32_t queue, bool behindCompletion) { // One entry per dword; a label overlapping older entries (a 4-byte store inside an 8-byte one or // the reverse) replaces exactly the dwords it stores, so a lookup composes what memory will hold. std::lock_guard tableLock(labelTableMutex); for (std::size_t offset = 0; offset + 4 <= bytes.size(); offset += 4) { std::uint32_t value = 0; std::memcpy(&value, bytes.data() + offset, 4); const auto dword = address + offset; labels.insert_or_assign(dword, LabelEntry{value, queue, stamp, &batch, 0, false, behindCompletion}); batch.labelDwords.push_back(dword); LabelGroupDwords().emplace_back(dword, stamp); } recordedLabels.store(labels.size(), std::memory_order_relaxed); } void Recorder::markBehindCompletion(const Batch& batch, std::uint64_t begin, std::uint64_t end) { std::lock_guard tableLock(labelTableMutex); for (auto it = labels.lower_bound(begin); it != labels.end() && it->first < end; ++it) { if (it->second.batch == &batch) it->second.behindCompletion = true; } } void Recorder::NoteLabel(std::uint64_t address, std::span bytes, std::uint64_t stamp, std::uint32_t queue) { ensureOpen(); // The table entry before the write note: the note bumps the write generation a poller // watches, and a poller that sees the bump then finds the label without the GPU mutex. const bool tabled = bytes.size() <= LabelTableBytes; if (tabled) { noteLabelOn(*open, address, bytes, stamp, queue); } else { std::lock_guard tableLock(labelTableMutex); labels.erase(labels.lower_bound(address), labels.lower_bound(address + bytes.size())); recordedLabels.store(labels.size(), std::memory_order_relaxed); open->wideLabels.push_back(wideLabels.emplace(address, WideLabel{address + bytes.size(), {bytes.begin(), bytes.end()}, ++wideLabelSequence, false, open.get()})); wideLabelBytes = std::max(wideLabelBytes, bytes.size()); recordedWideLabels.store(wideLabels.size(), std::memory_order_relaxed); } markLabel(*open); noteWriteOn(*open, address, bytes.size(), true); } std::optional Recorder::PendingLabel(std::uint64_t address, std::size_t bytes, std::uint64_t afterStamp, LabelRefusal* refusal) const { // Under the GPU mutex; the table mutex is taken too so this one path serves both lock regimes. std::lock_guard tableLock(labelTableMutex); return lookupLabel(address, bytes, afterStamp, refusal); } std::size_t Recorder::PendingLabels() const { std::lock_guard tableLock(labelTableMutex); return labels.size(); } bool Recorder::PendingLabelIn(std::uint64_t address, std::size_t bytes) const { std::lock_guard tableLock(labelTableMutex); if (bytes == 0) return false; const auto end = address + bytes; if (const auto first = labels.lower_bound(address); first != labels.end() && first->first < end) return true; if (wideLabelInLocked(address, bytes)) return true; // A queued label of another queue is unordered against the caller on hardware (nothing that // queue recorded could have satisfied a wait yet); it is still reported, since the table mutex // is held anyway and a caller deciding a CPU store wants the conservative answer. if (const auto first = queuedLabels.lower_bound(address); first != queuedLabels.end() && first->first < end) return true; return false; } bool Recorder::CompletionLabelIn(std::uint64_t address, std::size_t bytes) const { std::lock_guard tableLock(labelTableMutex); if (bytes == 0) return false; const auto end = address + bytes; for (auto it = labels.lower_bound(address); it != labels.end() && it->first < end; ++it) { if (it->second.behindCompletion) return true; } if (const auto first = queuedLabels.lower_bound(address); first != queuedLabels.end() && first->first < end) return true; return false; } std::optional Recorder::lookupLabel(std::uint64_t address, std::size_t bytes, std::uint64_t afterStamp, LabelRefusal* refusal) const { if (refusal != nullptr) *refusal = LabelRefusal::None; if ((labels.empty() && queuedLabels.empty()) || (bytes != 4 && bytes != 8) || address % 4 != 0) return std::nullopt; LabelHit hit{0, 0, 0, false, std::numeric_limits::max()}; bool queued = false; bool candidate = false; const auto tag = GuestMemory::GpuLockThreadTag(); const auto refuse = [&](LabelRefusal reason, std::uint64_t LateStatistics::*counter, const LabelEntry& entry) { if (refusal != nullptr) *refusal = entry.behindCompletion ? LabelRefusal::BehindCompletion : reason; if (counter != nullptr) ++(lateCounts.*counter); return std::nullopt; }; for (std::size_t offset = 0; offset < bytes; offset += 4) { const auto dword = address + offset; const LabelEntry* entry = nullptr; // A queued label is only good for its own queue's wait (see NoteQueuedLabel), where it is // that queue's newest store of the dword; everyone else sees the recorded entry. if (const auto own = queuedLabels.find(dword); own != queuedLabels.end() && own->second.queue == tag) { entry = &own->second; queued = true; } else if (const auto found = labels.find(dword); found != labels.end()) { entry = &found->second; if (entry->batch == nullptr) { if (entry->queue != tag) return std::nullopt; queued = true; } } if (entry == nullptr) return std::nullopt; if (entry->stamp <= afterStamp) { // The late rule (see NoteLabel): counted in both modes, so a control run shows the population. if (!candidate) ++lateCounts.candidates; candidate = true; if (!LateTrustEnabled()) return refuse(LabelRefusal::TrustOff, nullptr, *entry); if (entry->batch == nullptr) return refuse(LabelRefusal::Queued, &LateStatistics::queued, *entry); if (entry->overwritten) return refuse(LabelRefusal::Overwritten, &LateStatistics::overwritten, *entry); if (entry->generation == 0) return refuse(LabelRefusal::Unclosed, &LateStatistics::unclosed, *entry); hit.late = true; hit.generation = std::min(hit.generation, entry->generation); } hit.value |= static_cast(entry->value) << (offset * 8u); if (offset == 0) { hit.queue = entry->queue; hit.stamp = entry->stamp; } } if (!hit.late) hit.generation = 0; if (queued) queuedLabelHits.fetch_add(1, std::memory_order_relaxed); return hit; } bool Recorder::unsignaled(std::uint64_t serial) const { for (const auto& batch : inFlight) { if (batch->serial == serial) return !gpuDone(*batch); } return false; } void Recorder::AfterCompletions(std::uint64_t address, std::span bytes, std::uint64_t stamp, std::uint32_t queue, bool storedOnGpu) { Require(open != nullptr || !inFlight.empty(), "no batch to append a completion label to"); Batch& batch = open != nullptr ? *open : *inFlight.back(); std::vector copy(bytes.begin(), bytes.end()); // The store bypasses the flush hook: it runs inside finish() under the mutex, and the hook would // find this very range noted (or a later label to it) and sync re-entrantly. Stamped like every // driver store so a collect memoized for the packet sees it. static const bool always = std::getenv("APS5_LABEL_STORE_ALWAYS") != nullptr; const auto sequence = [&] { std::lock_guard ringLock(writtenBackMutex); return writtenBackSequence; }(); batch.completions.push_back([this, address, copy = std::move(copy), sequence, storedOnGpu] { if (storedOnGpu && !always && !writtenBackSince(sequence, address, address + copy.size())) { completionStoresSkipped.fetch_add(1, std::memory_order_relaxed); return; } completionStoresRun.fetch_add(1, std::memory_order_relaxed); GuestMemory::CheckRange(reinterpret_cast(address), copy.size(), 4, true); GuestMemory::StoreOwnBytes(address, copy); }); // Counted per batch and counted down when the batch finishes, on every exit path of finish() // (a label whose range became unmapped is reported there, and a lost device throws before the // completions run): a label that will never land must not leave the workers reaping forever. // One stored on the GPU already needs no reap unless a write-back overlaps it (the store above // is skipped otherwise), so it enters the count at that write-back (NoteWrittenBack). const bool behindCompletion = !(storedOnGpu && !always && !CountAllCompletionLabels()); if (!behindCompletion) { batch.completionLabelRanges.push_back({address, address + bytes.size(), false}); } else { ++batch.completionLabelCount; completionLabels.fetch_add(1, std::memory_order_acq_rel); ++batch.completionStoreCount; completionStores.fetch_add(1, std::memory_order_acq_rel); GuestMemory::BreakProofs(); } // The table entry before the write note: the note bumps the generation a poller watches, and a // poller that sees the bump then finds the label without the GPU mutex. noteLabelOn(batch, address, bytes, stamp, queue, behindCompletion); noteWriteOn(batch, address, bytes.size(), true); if (!batch.submitted) markLabel(batch); } bool Recorder::AfterRecordedWork(std::function action) { if (Idle()) return false; Batch& batch = open != nullptr ? *open : !sealedBatches.empty() ? *sealedBatches.back() : *inFlight.back(); batch.completions.push_back(std::move(action)); ++batch.completionLabelCount; completionLabels.fetch_add(1, std::memory_order_acq_rel); if (!batch.submitted) markLabel(batch); return true; } void Recorder::markLabel(Batch& batch) { if (batch.labelSince == NoPendingLabel) batch.labelSince = std::chrono::steady_clock::now().time_since_epoch().count(); if (activeRecorder == this && pendingLabelSince.load(std::memory_order_relaxed) == NoPendingLabel) pendingLabelSince.store(batch.labelSince, std::memory_order_release); } void Recorder::refreshLabelMark() noexcept { if (activeRecorder != this) return; auto since = NoPendingLabel; const auto older = [&](std::int64_t mark) { if (mark != NoPendingLabel && (since == NoPendingLabel || mark < since)) since = mark; }; for (const auto& batch : sealedBatches) older(batch->labelSince); if (open != nullptr) older(open->labelSince); pendingLabelSince.store(since, std::memory_order_release); } void Recorder::NoteWrittenBack(std::uint64_t address, std::size_t bytes) { Recorder* recorder = activeRecorder; if (recorder == nullptr || bytes == 0) return; GuestMemory::AssertGpuLockHeld("Recorder::NoteWrittenBack"); const auto end = address + bytes; { std::lock_guard ringLock(recorder->writtenBackMutex); recorder->writtenBack.push_back({++recorder->writtenBackSequence, address, end}); while (recorder->writtenBack.size() > 16384) recorder->writtenBack.pop_front(); } if (recorder->recordedLabels.load(std::memory_order_relaxed) != 0 && recorder->PendingLabelIn(address, bytes)) writeBacksOverLabels.fetch_add(1, std::memory_order_relaxed); // The GPU-stored completion labels this write-back overlaps now need their completion store, // so they enter the pending count (once each; finish() subtracts the batch's count). Batches // in `finishing` run their own completions in the same finish(), so only open and in-flight // ones are scanned. const auto count = [&](Batch& batch) { for (auto& label : batch.completionLabelRanges) { if (label.counted || label.begin >= end || address >= label.end) continue; label.counted = true; ++batch.completionLabelCount; completionLabels.fetch_add(1, std::memory_order_acq_rel); GuestMemory::BreakProofs(); completionLabelsCountedLate.fetch_add(1, std::memory_order_relaxed); ++batch.completionStoreCount; completionStores.fetch_add(1, std::memory_order_acq_rel); recorder->markBehindCompletion(batch, label.begin, label.end); } }; if (recorder->open != nullptr) count(*recorder->open); for (auto& batch : recorder->inFlight) count(*batch); } bool Recorder::writtenBackSince(std::uint64_t sequence, std::uint64_t begin, std::uint64_t end) { std::lock_guard ringLock(writtenBackMutex); if (writtenBack.empty() || writtenBack.back()[0] <= sequence) return false; if (writtenBack.front()[0] > sequence + 1) return true; for (auto it = writtenBack.rbegin(); it != writtenBack.rend() && (*it)[0] > sequence; ++it) { if ((*it)[1] < end && begin < (*it)[2]) return true; } return false; } void Recorder::HoldNextSubmit(VkSemaphore semaphore, std::uint64_t value) { submitHold = semaphore; submitHoldValue = value; } bool Recorder::SubmitHeld() const { return submitHold != VK_NULL_HANDLE || (heldSerial != 0 && unsignaled(heldSerial)); } void Recorder::FailNextSubmitsForTest(unsigned count) { injectedSubmitFailures.store(count, std::memory_order_relaxed); } void Recorder::Submit() { PerformanceTimer frameTiming("Recorder.Submit"); // The work count is cleared even when nothing is open: the driver counts a dispatch after its // call returns (outside the mutex), so a submit by another thread in between leaves a stale // count behind, and the callers that act on it would otherwise take the mutex for nothing at // every packet or submission end until a real batch is next submitted. if (activeRecorder == this) workSinceSubmit.store(0, std::memory_order_relaxed); if (sealedBatches.empty()) { if (auto batch = sealOpen()) queue(std::move(batch)); return; } std::exception_ptr failure; try { Seal(); } catch (...) { failure = std::current_exception(); } while (!sealedBatches.empty()) { try { QueueSealed(); } catch (...) { if (failure == nullptr) failure = std::current_exception(); } } if (failure != nullptr) std::rethrow_exception(failure); } std::uint64_t Recorder::Seal() { auto batch = sealOpen(); if (batch == nullptr) return 0; const auto serial = batch->sealedSerial; sealedBatches.push_back(std::move(batch)); return serial; } std::unique_ptr Recorder::sealOpen() { dropStaleHoldKept(); if (open == nullptr) return nullptr; GuestMemory::AssertGpuLockHeld("Recorder::Seal"); struct DiscardUnsealed { Recorder& recorder; std::unique_ptr& batch; ~DiscardUnsealed() { if (batch != nullptr) recorder.discard(std::move(batch)); } }; if (open->stream != nullptr && open->stream->Poisoned()) { auto failed = std::move(open); const DiscardUnsealed discardFailed{*this, failed}; poisonedBatches.fetch_add(1, std::memory_order_relaxed); std::rethrow_exception(failed->stream->Reason()); } if (latch.Failed() || latch.DeviceLost()) { auto failed = std::move(open); const DiscardUnsealed discardFailed{*this, failed}; latch.ThrowFor(sealedThrough + 1); } flushDeferredDispatch(); if (!open->keyStores.empty()) recordKeyStores(false); if (open->renderPass.open) endOpenRenderPass(PassBreak::NewBatch); const bool segments = segmentMode(); if (!segments) { endSamples(*open); if (pendingSamples.size() >= SampleFoldCapacity) foldSamples(*open, 0); } const bool hostReadCovered = (open->run.open || !open->run.queued.empty()) && closeStoreRun(true); if (segments && pendingSamples.size() >= SampleFoldCapacity) foldSegments(); if (BarrierValidate()) validateBatchEnds.fetch_add(1, std::memory_order_relaxed); if (open->hostReadOwed && !hostReadCovered) { // A fence makes nothing visible to the host: a lean draw's writes (no download barrier of // its own) get the batch's one here. recordBarrier(live(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); CountBarriers(CommandClass::Draw); } EndGpuTiming(open->batchTiming); if (!GpuTimingEnabled()) reportBarriers(); if (FlipReadCheck()) { // A CPU write into a noted read after this collect (and so possibly before the GPU read // it) fails UnchangedSince at the presenter's check (VulkanDevice RetirePresents). for (const auto& [begin, end] : notedReads(*open)) open->readGeneration = std::max(open->readGeneration, GuestMemory::CollectWrites(begin, end - begin)); } auto batch = std::move(open); const DiscardUnsealed discardUnsealed{*this, batch}; if (batch->stream != nullptr && batch->stream->Poisoned()) { poisonedBatches.fetch_add(1, std::memory_order_relaxed); std::rethrow_exception(batch->stream->Reason()); } const std::uint64_t serial = ++sealedThrough; try { batch->sealedSerial = serial; if (batch->stream != nullptr && batch->stream->Materialized() == VK_NULL_HANDLE) { batch->sealed = std::make_shared(serial, *batch->stream, realCommands, latch, &budget); executor->Execute(batch->sealed); } else { if (batch->stream != nullptr) noteDemotion(batch->stream->DemotedBy()); Check(function(endCommandBuffer, "vkEndCommandBuffer")(batch->real), "vkEndCommandBuffer recorder"); } } catch (...) { if (latch.FailedSerial() > serial) sealedThrough = serial - 1; throw; } batch->hold = std::exchange(submitHold, VK_NULL_HANDLE); batch->holdValue = submitHoldValue; return std::move(batch); } void Recorder::unqueued(std::unique_ptr batch, std::exception_ptr reason) noexcept { const auto serial = batch->sealedSerial; if (!latch.DeviceLost() && latch.FailedSerial() > serial) { if (sealedThrough == serial && open == nullptr) { sealedThrough = serial - 1; if (submitHold == VK_NULL_HANDLE) { submitHold = batch->hold; submitHoldValue = batch->holdValue; } } else { latch.Fail(serial, reason); } } discard(std::move(batch)); } std::uint64_t Recorder::QueueSealed() { PerformanceTimer frameTiming("Recorder.QueueSealed"); if (sealedBatches.empty()) return 0; GuestMemory::AssertGpuLockHeld("Recorder::QueueSealed"); auto batch = std::move(sealedBatches.front()); sealedBatches.pop_front(); return queue(std::move(batch)); } std::uint64_t Recorder::queue(std::unique_ptr batch) { const std::uint64_t serial = batch->sealedSerial; VkCommandBuffer submitted = batch->real; std::string tokensStr; try { if (latch.DeviceLost() || latch.FailedSerial() < serial) latch.ThrowFor(serial); if (serial != submissions + 1) throw std::logic_error("AGC graphics: sealed batch " + std::to_string(serial) + " was queued after batch " + std::to_string(submissions)); if (batch->sealed != nullptr) { try { submitted = batch->sealed->Await(); } catch (...) { failedReplays.fetch_add(1, std::memory_order_relaxed); throw; } replayedBatches.fetch_add(1, std::memory_order_relaxed); batch->stream->ReleaseMemory(); } if (injectedSubmitFailures.load(std::memory_order_relaxed) != 0 && injectedSubmitFailures.fetch_sub(1, std::memory_order_relaxed) != 0) throw std::runtime_error("vkQueueSubmit recorder: injected failure"); if (CheckpointMarkersEnabled() && batch->queue == 0 && batch->predictedSerial != 0) { Require(batch->predictedSerial == serial, "Recorder::Submit submit serial mismatch"); try { if (const auto snapshot = GuestBufferMemory::TrySnapshotAddressSpace(); snapshot.has_value()) AgcDriver::SubmissionSnapshots::DeviceSnapshots().NoteSubmit(serial, snapshot->first, snapshot->second, AgcDriver::SubmitBracket{serial, CompletedThrough(), batch->firstToken, batch->lastToken}); } catch (...) { } } tokensStr = "["; for (std::size_t i = 0; i < batch->drawTraceTokens.size(); ++i) { if (i > 0) tokensStr += ","; tokensStr += std::to_string(batch->drawTraceTokens[i]); } tokensStr += "]"; CaptureTrace::Log("submit batch=%llu tokens=%s", static_cast(serial), tokensStr.c_str()); DestroyDeferredAtIdle(context); } catch (...) { unqueued(std::move(batch), std::current_exception()); throw; } struct DiscardUnsubmitted { Recorder& recorder; std::unique_ptr& batch; ~DiscardUnsubmitted() { if (batch != nullptr && !batch->submitted) recorder.discard(std::move(batch)); } }; const DiscardUnsubmitted discardUnsubmitted{*this, batch}; VkSubmitInfo submission{VK_STRUCTURE_TYPE_SUBMIT_INFO}; submission.commandBufferCount = 1; submission.pCommandBuffers = &submitted; VkTimelineSemaphoreSubmitInfoKHR timelineInfo{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO_KHR}; const VkSemaphore hold = batch->hold; const std::uint64_t holdValue = batch->holdValue; VkPipelineStageFlags holdStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; if (hold != VK_NULL_HANDLE) { submission.waitSemaphoreCount = 1; submission.pWaitSemaphores = &hold; submission.pWaitDstStageMask = &holdStage; timelineInfo.waitSemaphoreValueCount = 1; timelineInfo.pWaitSemaphoreValues = &holdValue; } if (timeline != VK_NULL_HANDLE) { timelineInfo.signalSemaphoreValueCount = 1; timelineInfo.pSignalSemaphoreValues = &serial; submission.signalSemaphoreCount = 1; submission.pSignalSemaphores = &timeline; } if (hold != VK_NULL_HANDLE || timeline != VK_NULL_HANDLE) submission.pNext = &timelineInfo; const auto submitStart = std::chrono::steady_clock::now(); batch->submitStarted.store(true, std::memory_order_release); const auto result = function(queueSubmit, "vkQueueSubmit")(context.queue, 1, &submission, batch->fence); const bool queuedNothing = result != VK_SUCCESS && result != VK_ERROR_DEVICE_LOST; if (batch->sealed != nullptr && !queuedNothing) batch->sealed->Returned(result); std::exception_ptr refused; if (result != VK_SUCCESS) { try { Check(result, "vkQueueSubmit recorder"); } catch (...) { refused = std::current_exception(); } if (batch->sealed == nullptr && result == VK_ERROR_DEVICE_LOST) latch.LoseDevice(refused); } if (result == VK_ERROR_DEVICE_LOST) { const auto idle = context.Function("vkDeviceWaitIdle")(context.device); if (idle != VK_SUCCESS && idle != VK_ERROR_DEVICE_LOST) std::terminate(); if (batch->sealed != nullptr) batch->sealed->DeviceIdleAfterLoss(); } if (queuedNothing) unqueued(std::move(batch), refused); if (refused != nullptr) std::rethrow_exception(refused); if (batch->guestWork) LibcRunReportMilestone_nid_no_patch(2); batch->submitted = true; batch->serial = ++submissions; if (hold != VK_NULL_HANDLE) heldSerial = batch->serial; batch->submittedAt = std::chrono::steady_clock::now(); CaptureTrace::Log("submit-confirmed batch=%llu tokens=%s", static_cast(batch->serial), tokensStr.c_str()); if (DrawProfiled()) { const auto us = std::chrono::duration(batch->submittedAt - submitStart).count(); ++submitCount; submitUs += us; submitMaxUs = std::max(submitMaxUs, us); if (auto* frame = PerformanceContext::Current()) frame->Add(frame->Get("Recorder", "submit"), batch->submittedAt - submitStart); } { std::lock_guard lock(completedMutex); newestSubmitted = batch->serial; newestSubmittedAt = batch->submittedAt; } if (timeline != VK_NULL_HANDLE) { if (!progressWatcher) { progressWatcher = std::make_unique(context.device, timeline, context.Function("vkWaitSemaphoresKHR"), context.Function("vkGetSemaphoreCounterValueKHR")); } progressWatcher->Submitted(batch->serial); } inFlight.push_back(std::move(batch)); inFlightKeptBytes += inFlight.back()->keptBytes; refreshLabelMark(); return serial; } std::uint64_t Recorder::SubmitAndEpoch() { Submit(); return inFlight.empty() ? 0 : submissions; } std::uint64_t Recorder::OpenBatchSerial() { return open != nullptr ? sealedThrough + 1 : 0; } namespace { // One thread's registration as a timeline waiter (see `unlockedWaiters`): constructed while the // caller still holds the mutex (or the device), so a teardown that starts after the mutex is // released sees it and keeps the semaphore until the wait returned. struct UnlockedWaiter { std::atomic& count; explicit UnlockedWaiter(std::uint64_t recorderId) : count(WaitersOf(recorderId)) { count.fetch_add(1, std::memory_order_acq_rel); } ~UnlockedWaiter() { count.fetch_sub(1, std::memory_order_acq_rel); } UnlockedWaiter(const UnlockedWaiter&) = delete; UnlockedWaiter& operator=(const UnlockedWaiter&) = delete; }; // Restores the thread's active sync-site entry on every exit path (a Check throw on a lost device // included), so the next sync on the thread is not attributed to this one's site. struct RestoreSyncSite { std::size_t site; ~RestoreSyncSite() { activeSyncSite = site; } }; // The timeline wait itself, on handles copied out of the recorder: the caller holds no mutex, and // the recorder may be torn down meanwhile (its destructor waits for the registered waiters to // leave after completing every batch, so the handles stay valid until this returns). constexpr std::uint64_t TimelineSliceNanos = 100'000'000ull; constexpr unsigned TimelineSlicesPerReport = 50; VkResult WaitTimelineSlice(VkDevice device, VkSemaphore timeline, PFN_vkWaitSemaphoresKHR waitSemaphores, std::uint64_t serial, std::uint64_t nanos) { VkSemaphoreWaitInfoKHR wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO_KHR}; wait.semaphoreCount = 1; wait.pSemaphores = &timeline; wait.pValues = &serial; return waitSemaphores(device, &wait, nanos); } std::exception_ptr LatchStops(const FailureLatch& latch, std::uint64_t serial) noexcept { try { latch.ThrowFor(serial); } catch (...) { return std::current_exception(); } return nullptr; } VkResult WaitTimeline(VkDevice device, VkSemaphore timeline, PFN_vkWaitSemaphoresKHR waitSemaphores, std::uint64_t serial, const FailureLatch& latch, std::exception_ptr& stopped) { auto result = WaitTimelineSlice(device, timeline, waitSemaphores, serial, TimelineSliceNanos); for (unsigned slices = 1; result == VK_TIMEOUT; ++slices) { if (stopped = LatchStops(latch, serial); stopped != nullptr) return VK_TIMEOUT; // As for the fence wait in finish(): a hung batch is reported every 5 s. if (slices % TimelineSlicesPerReport == 0) std::fprintf(stderr, "[gpu] recorded batch %llu still running on the GPU after %u s (timeline wait)\n", static_cast(serial), slices / 10); result = WaitTimelineSlice(device, timeline, waitSemaphores, serial, TimelineSliceNanos); } return result; } } void Recorder::WaitSerial(std::uint64_t serial) { PerformanceTimer frameTiming("Recorder.WaitSerial"); if (timeline == VK_NULL_HANDLE || serial == 0) return; static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; const auto start = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; const UnlockedWaiter waiter{id}; std::exception_ptr stopped; const auto result = WaitTimeline(context.device, timeline, context.Function("vkWaitSemaphoresKHR"), serial, latch, stopped); if (profile) { unlockedWaits.fetch_add(1, std::memory_order_relaxed); unlockedWaitedUs.fetch_add(static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count()), std::memory_order_relaxed); } if (stopped != nullptr) std::rethrow_exception(stopped); Check(result, "vkWaitSemaphoresKHR recorder"); } bool Recorder::WaitSerialFor(std::uint64_t serial, std::uint64_t timeoutNanos) { PerformanceTimer frameTiming("Recorder.WaitSerialFor"); if (timeline == VK_NULL_HANDLE || serial == 0) return false; const UnlockedWaiter waiter{id}; const auto waitSemaphores = context.Function("vkWaitSemaphoresKHR"); auto left = timeoutNanos; auto result = WaitTimelineSlice(context.device, timeline, waitSemaphores, serial, std::min(left, TimelineSliceNanos)); while (result == VK_TIMEOUT) { if (const auto stopped = LatchStops(latch, serial); stopped != nullptr) std::rethrow_exception(stopped); left -= std::min(left, TimelineSliceNanos); if (left == 0) return false; result = WaitTimelineSlice(context.device, timeline, waitSemaphores, serial, std::min(left, TimelineSliceNanos)); } Check(result, "vkWaitSemaphoresKHR submission progress"); return true; } void Recorder::FinishUpTo(std::uint64_t serial) { // A drain: the wait already happened (unlocked), the fences are signaled, so the source-0 wait // recorded here is the bookkeeping only (a caller that did not wait first, WaitForLeases, shows // up in the site table by its own address). ++syncCounts[0]; announcedSource = 4; const void* site = std::exchange(announcedSite, nullptr); const auto previousSite = inFlight.empty() || inFlight.front()->serial > serial ? activeSyncSite : BeginSyncSite(0, site != nullptr ? site : __builtin_return_address(0)); while (!inFlight.empty() && inFlight.front()->serial <= serial) { auto batch = std::move(inFlight.front()); inFlight.pop_front(); finish(std::move(batch), true, 0); } activeSyncSite = previousSite; } void Recorder::Sync() { PerformanceTimer frameTiming("Recorder.Sync"); const auto source = std::exchange(announcedSource, 4); const void* site = std::exchange(announcedSite, nullptr); std::exception_ptr failure; try { Submit(); } catch (...) { failure = std::current_exception(); } // Counted only when something is waited for: an idle recorder's Sync is free and would only // swamp the site table with the callers that check nothing first. const auto previousSite = inFlight.empty() ? activeSyncSite : BeginSyncSite(source, site != nullptr ? site : __builtin_return_address(0)); while (!inFlight.empty()) { auto batch = std::move(inFlight.front()); inFlight.pop_front(); try { finish(std::move(batch), true, source); } catch (...) { if (failure == nullptr) failure = std::current_exception(); break; } } activeSyncSite = previousSite; if (failure != nullptr) std::rethrow_exception(failure); } void Recorder::FlushDeferredReleases() { holdKept.clear(); ReleaseDeferredKeeps(); } void Recorder::SyncThrough(std::uint64_t address, std::size_t bytes, bool waitUnlocked) { if (bytes == 0) return; const auto end = address + bytes; if (completionDepth() != 0 && !CompletionStoreSyncs()) { // A store made by a completion action (a copied buffer's write-back, GuestBufferMemory:: // WriteBack) reached the flush hook, and a batch still in flight notes the range. Every // batch in flight now was recorded after the completing one (finish runs front to back), // so in program order this store precedes their writes: landing it before them is the // order the hardware gives; waiting for them first (what the hook would do) lands the // completing batch's bytes over the later batch's, which is wrong, and does so under the // hold of whoever reaped (the [hooksync] 'store' entries, up to tens of ms per reap). The // later batch's own ordering against this write-back is its recorder's business at record // time (FillBuffer and DispatchIndirect consult copiedWriters; a later copied writer's // write-back runs after this one in finish order; a label behind completions lands after). announcedSource = 4; announcedSite = nullptr; ++holdCounters.completionSyncsSkipped; return; } if (completionDepth() != 0) ++holdCounters.completionSyncsWaited; const auto completionWaitStart = completionDepth() != 0 && DrawProfiled() ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; struct CompletionWait { std::chrono::steady_clock::time_point start; ~CompletionWait() { if (start != std::chrono::steady_clock::time_point{}) holdCounters.completionSyncWaitMs += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); } } completionWait{completionWaitStart}; if (waitUnlocked) { // The hook's wait without the mutex: its own acquisition is the outermost on this thread. const auto source = announcedSource; const void* site = announcedSite != nullptr ? announcedSite : __builtin_return_address(0); if (syncThroughUnlocked(address, end, source, site)) return; // A completion-store wait (kill switch above) is already counted as 'waited'. if (completionDepth() == 0) ++holdCounters.hookLockedWaits; } if (!SyncThroughEnabled() || (open != nullptr && overlaps(*open, address, end))) { // The announced site (or this call's caller) names the sync, not this function. if (announcedSite == nullptr) announcedSite = __builtin_return_address(0); // The open batch's work has not run; without one the newest in flight is the target. if (open != nullptr || (!inFlight.empty() && unsignaled(inFlight.back()->serial))) ++hookRealWaits; Sync(); return; } const auto source = std::exchange(announcedSource, 4); const void* site = std::exchange(announcedSite, nullptr); std::uint64_t targetSerial = 0; for (auto it = inFlight.rbegin(); it != inFlight.rend(); ++it) { if (overlaps(**it, address, end)) { targetSerial = (*it)->serial; break; } } if (targetSerial == 0) return; if (unsignaled(targetSerial)) ++hookRealWaits; targetedSyncs.fetch_add(1, std::memory_order_relaxed); const RestoreSyncSite restoreSite{BeginSyncSite(source, site != nullptr ? site : __builtin_return_address(0))}; // Batches are in flight in serial order. A completion's own guest access can sync re-entrantly // and finish the target first (and a new batch may reuse its allocation, so the serial, not the // pointer, identifies it); the loop stops then, and later batches stay in flight either way. while (!inFlight.empty() && inFlight.front()->serial <= targetSerial) { auto batch = std::move(inFlight.front()); inFlight.pop_front(); finish(std::move(batch), true, source); } batchesLeftInFlight.fetch_add(inFlight.size(), std::memory_order_relaxed); } namespace { // What the unlocked hook waits waited for, per read site (the [syncwait] line every 10 s under // APS5_PROFILE_DRAW): the batches up to the target, how many of them the GPU had not finished when // the wait began, and whether the target was the newest submission. APS5_TRACE_CAPSYNC=1 prints // every such wait ([capsync] sync lines). struct SyncWaitSite { std::uint64_t count = 0; std::uint64_t batchesToTarget = 0; std::uint64_t unsignaledAtStart = 0; std::uint64_t newest = 0; double waitedMs = 0; // The target batch's submit -> wait-end latency: what the wait's length is made of when the // batches ahead of it carry little GPU work (submission latency, not throughput). double targetAgeMs = 0; }; struct SyncWaitStats { std::array(GuestMemory::ReadSite::Count)> bySite{}; // Batches up to the targets, by the queue that opened them: whether a wait for one queue's // producer is really a wait for the other queues' batches ahead of it on the one timeline. std::map aheadByQueue; std::chrono::steady_clock::time_point lastReport = std::chrono::steady_clock::now(); }; SyncWaitStats& SyncWaits() { static SyncWaitStats stats; return stats; } bool TraceCapSync() { static const bool trace = std::getenv("APS5_TRACE_CAPSYNC") != nullptr; return trace; } void ReportSyncWaits(SyncWaitStats& stats) { std::string report = "[syncwait] unlocked hook waits by read site (10 s; count/GPU wait, avg batches up to the target, avg of them unsignaled at the start, target was the newest submission, avg target submit-to-signal ms):"; for (std::size_t site = 0; site < stats.bySite.size(); ++site) { const auto& entry = stats.bySite[site]; if (entry.count == 0) continue; char text[160]; std::snprintf(text, sizeof(text), " %s %llu/%.0fms %.1f %.1f %.0f%% %.1f", GuestMemory::ReadSiteName(static_cast(site)), static_cast(entry.count), entry.waitedMs, static_cast(entry.batchesToTarget) / entry.count, static_cast(entry.unsignaledAtStart) / entry.count, entry.newest * 100.0 / entry.count, entry.targetAgeMs / entry.count); report += text; } report += "; batches ahead by queue:"; for (const auto& [queue, count] : stats.aheadByQueue) { char text[48]; if (queue == 0xffffffffu) std::snprintf(text, sizeof(text), " untagged %llu", static_cast(count)); else std::snprintf(text, sizeof(text), " 0x%x %llu", queue, static_cast(count)); report += text; } AgcDriver::ProfilePrint_nid_no_patch("%s\n", report.c_str()); stats = SyncWaitStats{}; } } bool Recorder::syncThroughUnlocked(std::uint64_t address, std::uint64_t end, int source, const void* site) { // Only for the outermost acquisition: a nested hook (inside a dispatch's hold) must not give // up the caller's mutex, and a thread that waits here holds nothing the relock could invert // (the hook took the mutex from a depth of 0 with the same locks held). if (HookLockedWait() || timeline == VK_NULL_HANDLE || GuestMemory::GpuMutex().DepthOnThisThread() != 1) return false; // The target as SyncThrough chooses it: the open batch (submitted here, so the GPU can reach // it) makes everything the target, else the newest overlapping in-flight batch; with // SyncThrough disabled everything is the target as well. std::uint64_t targetSerial = 0; if (!SyncThroughEnabled() || (open != nullptr && overlaps(*open, address, end))) { Submit(); targetSerial = submissions; } else { for (auto it = inFlight.rbegin(); it != inFlight.rend(); ++it) { if (overlaps(**it, address, end)) { targetSerial = (*it)->serial; break; } } } announcedSource = 4; announcedSite = nullptr; if (targetSerial == 0) return true; if (unsignaled(targetSerial)) ++hookRealWaits; // Everything the wait needs is copied out: the recorder may be torn down while the mutex is // released (its destructor completes every batch and waits for the semaphore to be left, see // WaitTimeline), after which `this` must not be touched. The id re-check below relies on the // teardown running under the GpuMutex (the driver's drain and failure paths reset the device // under it; a worker dropping its last device reference outside its lock would not). const auto myId = id; const auto& waitLatch = latch; const auto device = context.device; const auto semaphore = timeline; const auto waitSemaphores = context.Function("vkWaitSemaphoresKHR"); // The site entry is taken under the mutex (the table is only touched under it; entries are // appended, never removed, so the index stays valid across the release). const RestoreSyncSite restoreSite{BeginSyncSite(source, site)}; const bool profile = DrawProfiled(); const bool trace = TraceCapSync(); const auto readSite = GuestMemory::CurrentReadSite(); const auto newestSerial = submissions; std::size_t batchesToTarget = 0, unsignaledAtStart = 0, targetRanges = 0; std::pair hit{0, 0}; std::chrono::steady_clock::time_point targetSubmittedAt{}; std::map aheadByQueue; if (profile || trace) { for (const auto& batch : inFlight) { if (batch->serial > targetSerial) break; ++batchesToTarget; ++aheadByQueue[batch->queue]; if (!gpuDone(*batch)) ++unsignaledAtStart; if (batch->serial != targetSerial) continue; targetSubmittedAt = batch->submittedAt; targetRanges = batch->writes.size(); for (const auto& range : batch->writes) { if (address < range.second && range.first < end) { hit = range; break; } } } } const auto start = profile || trace ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; auto waited = start; auto& mutex = GuestMemory::GpuMutex(); VkResult result = VK_SUCCESS; std::exception_ptr stopped; { // Registered before the release: a teardown can only start once the mutex is free. const UnlockedWaiter waiter{myId}; mutex.unlock(); result = WaitTimeline(device, semaphore, waitSemaphores, targetSerial, waitLatch, stopped); // Read before the relock: the GPU wait, not the wait for the mutex behind it. if (profile || trace) waited = std::chrono::steady_clock::now(); } GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Hook); mutex.lock(); const auto ms = std::chrono::duration(waited - start).count(); if (profile) { // The GPU wait is charged like a locked wait, so the per-source, per-thread and per-site // totals of the [recorder] line keep their meaning; the unlocked count says how many were // not held. The relock's wait for the mutex is kept apart (the [lock] line also counts it // under 'hook' waits, for a cross-check). syncWaitedMs[source] += ms; CountThreadSync(source, ms); CountSiteWait(ms); ++holdCounters.hookUnlockedWaits; holdCounters.hookUnlockedWaitMs += ms; if (source >= 0 && source < 5) { ++holdCounters.hookUnlockedWaitsBySource[source]; holdCounters.hookUnlockedWaitMsBySource[source] += ms; } holdCounters.hookRelockMs += std::chrono::duration(std::chrono::steady_clock::now() - waited).count(); auto& stats = SyncWaits(); auto& siteStats = stats.bySite[static_cast(readSite)]; ++siteStats.count; siteStats.waitedMs += ms; siteStats.batchesToTarget += batchesToTarget; siteStats.unsignaledAtStart += unsignaledAtStart; if (targetSerial == newestSerial) ++siteStats.newest; if (targetSubmittedAt != std::chrono::steady_clock::time_point{}) siteStats.targetAgeMs += std::chrono::duration(waited - targetSubmittedAt).count(); for (const auto& [queue, count] : aheadByQueue) stats.aheadByQueue[queue] += count; if (std::chrono::steady_clock::now() - stats.lastReport > std::chrono::seconds(10)) ReportSyncWaits(stats); } if (trace) { static std::atomic lines{0}; if (lines.fetch_add(1) < 600) { const auto packet = GuestMemory::CurrentPacket(); std::fprintf(stderr, "[capsync] sync q0x%x %s %s 0x%llx+0x%llx: target %llu (newest %llu), %zu batches up to it (%zu unsignaled at the start), target noted %zu ranges, hit 0x%llx+0x%llx, GPU wait %.1f ms\n", packet.queue, PacketName(packet.opcode).c_str(), GuestMemory::ReadSiteName(readSite), static_cast(address), static_cast(end - address), static_cast(targetSerial), static_cast(newestSerial), batchesToTarget, unsignaledAtStart, targetRanges, static_cast(hit.first), static_cast(hit.second - hit.first), ms); } } if (!RecorderAlive(myId)) { // Torn down meanwhile: its destructor's Sync() ran every completion, nothing is pending. ++holdCounters.hookUnlockedTornDown; if (stopped != nullptr) std::rethrow_exception(stopped); Check(result, "vkWaitSemaphoresKHR recorder"); return true; } if (stopped != nullptr) std::rethrow_exception(stopped); Check(result, "vkWaitSemaphoresKHR recorder"); // The completions up to the target, under the mutex again; the fences are signaled, so the // waits inside finish() return at once (charged to the same site entry). Another thread may // have finished some meanwhile. targetedSyncs.fetch_add(1, std::memory_order_relaxed); while (!inFlight.empty() && inFlight.front()->serial <= targetSerial) { auto batch = std::move(inFlight.front()); inFlight.pop_front(); finish(std::move(batch), true, source); } batchesLeftInFlight.fetch_add(inFlight.size(), std::memory_order_relaxed); return true; } bool Recorder::Reap() { PerformanceTimer frameTiming("Recorder.Reap"); dropStaleHoldKept(); const bool profile = DrawProfiled(); const auto start = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; std::uint64_t retired = 0; if (fenceless && !inFlight.empty() && inFlight.back()->serial > reachedSerial) readTimeline(); while (!inFlight.empty()) { if (fenceless ? inFlight.front()->serial > reachedSerial : fenceStatus(inFlight.front()->fence) != VK_SUCCESS) break; auto batch = std::move(inFlight.front()); inFlight.pop_front(); finish(std::move(batch), false, 4); ++retired; } if (profile) { ++holdCounters.reaps; if (retired != 0) ++holdCounters.reapsWithWork; holdCounters.reapBatches += retired; holdCounters.reapMs += std::chrono::duration(std::chrono::steady_clock::now() - start).count(); } return inFlight.empty(); } void Recorder::finish(std::unique_ptr batch, bool wait, int source, bool releaseNow) { inFlightKeptBytes -= batch->keptBytes; // The batch's writes stay published until its completions ran, on every exit path. struct Finishing { Recorder& recorder; const Batch* batch; ~Finishing() { auto& list = recorder.finishing; list.erase(std::remove(list.begin(), list.end(), batch), list.end()); // The batch's completion labels have landed, or never will (fence failure below). if (batch->completionLabelCount != 0) completionLabels.fetch_sub(batch->completionLabelCount, std::memory_order_acq_rel); if (batch->completionStoreCount != 0) completionStores.fetch_sub(batch->completionStoreCount, std::memory_order_acq_rel); if (batch->writeBackCompletionCount != 0) writeBackCompletions.fetch_sub(batch->writeBackCompletionCount, std::memory_order_acq_rel); // This also runs while the fence-failure throw unwinds: an allocation failure in the // rebuild keeps the previous snapshot, which is a superset (a stale entry only causes a // false hit, never a miss) rather than terminating. try { recorder.publishPendingWrites(); } catch (...) { } try { BdaResources::NoteFinished(recorder.context.device, batch->serial); } catch (...) { } } } finishingScope{*this, batch.get()}; finishing.push_back(batch.get()); if (wait) { // APS5_PROFILE_DRAW: how long the CPU waits for recorded GPU work, reported every 10 s. static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; static double waitedMs = 0; static std::uint64_t waits = 0; static auto lastReport = std::chrono::steady_clock::now(); const auto waitStart = std::chrono::steady_clock::now(); // A fence still unsignaled here makes this a real GPU wait under the mutex (finish runs // under it): the [lock] line's 'locked GPU waits'. const bool signaledAtStart = !profile || gpuDone(*batch); struct Report { bool enabled; int source; std::chrono::steady_clock::time_point start; const Recorder& recorder; bool signaledAtStart; ~Report() { if (!enabled) return; const auto now = std::chrono::steady_clock::now(); const auto ms = std::chrono::duration(now - start).count(); waitedMs += ms; syncWaitedMs[source] += ms; ++waits; CountThreadSync(source, ms); CountSiteWait(ms); if (!signaledAtStart) GuestMemory::NoteLockedGpuWait(ms); if (now - lastReport > std::chrono::seconds(10)) { lastReport = now; const auto& h = holdCounters; 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; command buffers freed at batch release %llu, fences kept for reuse %llu\n", static_cast(submitCount), submitCount != 0 ? submitUs / static_cast(submitCount) : 0.0, submitMaxUs, static_cast(commandBuffersFreed.load()), static_cast(fencesKept.load())); if (recorder.deferring) AgcDriver::ProfilePrint_nid_no_patch("%s", recorder.StreamReport().c_str()); const auto reads = Recorder::ReadCounts(); 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, draw input %llu, address-based read-only %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.hits[6]), static_cast(reads.hits[7]), static_cast(reads.staleIgnored)); } } } report{profile, source, waitStart, *this, signaledAtStart}; std::exception_ptr stopped; const auto waitTimeline = [&] { VkResult reached = VK_SUCCESS; if (batch->serial > reachedSerial && batch->serial > readTimeline()) { reached = WaitTimeline(context.device, timeline, context.Function("vkWaitSemaphoresKHR"), batch->serial, latch, stopped); if (stopped != nullptr) return VK_ERROR_DEVICE_LOST; } if (reached == VK_SUCCESS) reachedSerial = std::max(reachedSerial, batch->serial); return reached; }; const auto waitFences = function(waitForFences, "vkWaitForFences"); auto result = fenceless ? waitTimeline() : waitFences(context.device, 1, &batch->fence, VK_TRUE, 5'000'000'000ull); for (int waited = 5; result == VK_TIMEOUT; waited += 5) { // A batch still running after 5 s is reported (every 5 s) so a GPU-side hang is visible. std::fprintf(stderr, "[gpu] recorded batch still running on the GPU after %d s\n", waited); result = waitFences(context.device, 1, &batch->fence, VK_TRUE, 5'000'000'000ull); } if (result != VK_SUCCESS && result != VK_ERROR_DEVICE_LOST) { const auto idle = context.Function("vkDeviceWaitIdle")(context.device); Check(idle, "vkDeviceWaitIdle after recorder fence failure"); } if (batch->sealed != nullptr) batch->sealed->GpuDone(); if (result != VK_SUCCESS) { release(*batch); if (stopped != nullptr) std::rethrow_exception(stopped); Check(result, fenceless ? "vkWaitSemaphoresKHR recorder" : "vkWaitForFences recorder"); } } else if (batch->sealed != nullptr) { batch->sealed->GpuDone(); } readGpuTiming(*batch); readSamples(*batch); if (batch->serial != 0) { std::lock_guard ringLock(completedMutex); auto& entry = completed[batch->serial % completed.size()]; entry.serial = batch->serial; entry.gpuStartNs = batch->gpuStartNs; entry.gpuEndNs = batch->gpuEndNs; entry.submittedAt = batch->submittedAt; entry.fenceSeenAt = std::chrono::steady_clock::now(); entry.readGeneration = batch->readGeneration; entry.reads.clear(); if (FlipReadCheck()) { entry.reads = notedReads(*batch); } } // Completions store GPU results to guest memory; a failing one is reported, the rest still run. // Timed (APS5_PROFILE_DRAW) with the release of the kept objects: both run under whichever hold // reaped or synced the batch. Inside them the flush hook makes no pending-write wait (SyncThrough). const bool profile = DrawProfiled(); const auto completionStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; { struct InCompletion { InCompletion() { HostThreadSlot::Set(completionDepth() + 1); } ~InCompletion() { HostThreadSlot::Set(completionDepth() - 1); } } inCompletion; for (auto& action : batch->completions) { try { action(); } catch (const BdaUnalignedAccess& error) { static std::mutex failuresMutex; static std::unordered_map failures; constexpr std::uint64_t kDeferredFailureFirst = 8, kDeferredFailureEvery = 1024; const auto count = [&] { std::lock_guard lock(failuresMutex); return ++failures[error.instruction]; }(); if (count <= kDeferredFailureFirst) std::fprintf(stderr, "[gpu] deferred write-back failed: %s\n", error.what()); else if (count % kDeferredFailureEvery == 0) std::fprintf(stderr, "[gpu] deferred write-back failed with an unaligned BDA access at pc 0x%x %llu times so far; latest: %s\n", error.instruction, static_cast(count), error.what()); } catch (const std::exception& error) { AgcDriver::LogCoalescedStderr_nid_no_patch("[gpu] deferred write-back failed: %s\n", error.what()); } } } if (!batch->completions.empty()) KernelWakeSleepers_nid_no_patch(); if (profile) holdCounters.completions += batch->completions.size(); const auto keptStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; // Deferred only from inside a hold: the unlock that releases the list is this thread's own, and // a caller finishing batches without the mutex (a test) might never make one. if (releaseNow || ReleaseUnderLock() || !GuestMemory::GpuMutex().HeldByThisThread()) { batch->completions.clear(); batch->kept.clear(); } else { // To this thread's unlock (see ReleaseDeferredKeeps); the completions go with the objects, // their captures hold the same ones. The push comes first: a failed one (the list's growth) // destroys the batch's objects here, under the mutex, counts nothing the destructor would // wait for and must not escape (the rest of finish() releases the fence and command buffer). try { DeferredBatches().push_back({std::move(batch->kept), std::move(batch->completions)}); deferredPending.fetch_add(1, std::memory_order_acq_rel); DeferredBytes() += batch->keptBytes; } catch (...) { } batch->completions.clear(); batch->kept.clear(); } if (profile) { const auto now = std::chrono::steady_clock::now(); holdCounters.keptReleaseMs += std::chrono::duration(now - keptStart).count(); holdCounters.completionMs += std::chrono::duration(now - completionStart).count(); } // The batch's label entries leave the table (a later label to the same dword already replaced // its entry and belongs to another batch). Correctness never depended on this removal. removeLabels(*batch); release(*batch); } void Recorder::discard(std::unique_ptr batch) noexcept { if (batch->sealed != nullptr && !batch->sealed->SubmitReturned()) batch->sealed->NotSubmitted(); std::erase_if(pendingSamples, [&](const SampleSegment& sample) { return sample.batch == batch->sampleBatch; }); std::erase_if(batch->foldedSamples, [&](const SampleSegment& sample) { return sample.batch == batch->sampleBatch; }); if (pendingSamples.size() + batch->foldedSamples.size() <= pendingSamples.capacity()) { pendingSamples.insert(pendingSamples.begin(), std::make_move_iterator(batch->foldedSamples.begin()), std::make_move_iterator(batch->foldedSamples.end())); } else { std::fprintf(stderr, "[samples] %zu occlusion samples folded by a discarded batch are lost: no capacity was reserved to restore them\n", batch->foldedSamples.size()); } removeLabels(*batch); if (batch->completionLabelCount != 0) completionLabels.fetch_sub(batch->completionLabelCount, std::memory_order_acq_rel); if (batch->completionStoreCount != 0) completionStores.fetch_sub(batch->completionStoreCount, std::memory_order_acq_rel); if (batch->writeBackCompletionCount != 0) writeBackCompletions.fetch_sub(batch->writeBackCompletionCount, std::memory_order_acq_rel); refreshLabelMark(); release(*batch); try { publishPendingWrites(); } catch (...) { } } void Recorder::removeLabels(Batch& batch) { if (!batch.labelDwords.empty() || !batch.wideLabels.empty()) { std::lock_guard tableLock(labelTableMutex); for (const auto dword : batch.labelDwords) { const auto found = labels.find(dword); if (found != labels.end() && found->second.batch == &batch) labels.erase(found); } for (const auto entry : batch.wideLabels) wideLabels.erase(entry); recordedLabels.store(labels.size(), std::memory_order_relaxed); recordedWideLabels.store(wideLabels.size(), std::memory_order_relaxed); } batch.labelDwords.clear(); batch.wideLabels.clear(); } void Recorder::release(Batch& batch) noexcept { if (batch.queries != VK_NULL_HANDLE) { if (!GpuTimingEnabled() && sparePools.size() < 64) { try { sparePools.push_back(batch.queries); batch.queries = VK_NULL_HANDLE; } catch (...) { } } if (batch.queries != VK_NULL_HANDLE) context.Function("vkDestroyQueryPool")(context.device, batch.queries, nullptr); } batch.queries = VK_NULL_HANDLE; if (batch.samples != VK_NULL_HANDLE && batch.samplePool == nullptr) context.Function("vkDestroyQueryPool")(context.device, batch.samples, nullptr); batch.samples = VK_NULL_HANDLE; batch.samplePool.reset(); for (const auto pool : batch.endedSamples) context.Function("vkDestroyQueryPool")(context.device, pool, nullptr); batch.endedSamples.clear(); batch.segments = VK_NULL_HANDLE; batch.segmentPool.reset(); static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; if (batch.real != VK_NULL_HANDLE) { context.Function("vkFreeCommandBuffers")(context.device, batch.pool != VK_NULL_HANDLE ? batch.pool : context.pool, 1, &batch.real); if (profile) commandBuffersFreed.fetch_add(1, std::memory_order_relaxed); } batch.real = VK_NULL_HANDLE; if (batch.sealed != nullptr) { if (batch.sealed->Commands() != VK_NULL_HANDLE) { executor->Retire(batch.sealed->Commands(), batch.sealed->Worker()); if (profile) commandBuffersFreed.fetch_add(1, std::memory_order_relaxed); } batch.sealed.reset(); } else if (batch.stream != nullptr) { budget.Retired(batch.stream->Charged()); } batch.stream.reset(); batch.commands = VK_NULL_HANDLE; if (batch.fence != VK_NULL_HANDLE && spare.size() < 64 && function(resetFences, "vkResetFences")(context.device, 1, &batch.fence) == VK_SUCCESS) { try { spare.push_back(batch.fence); batch.fence = VK_NULL_HANDLE; if (profile) fencesKept.fetch_add(1, std::memory_order_relaxed); return; } catch (const std::bad_alloc&) { } } if (batch.fence != VK_NULL_HANDLE) context.Function("vkDestroyFence")(context.device, batch.fence, nullptr); batch.fence = VK_NULL_HANDLE; } }