From 18cd1cf07f0b446627127a5865e649c6d589066b Mon Sep 17 00:00:00 2001 From: LunaDL <91587464+EnzoDLofi@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:04:16 -0400 Subject: [PATCH] Fix: reclaim DD-FG scratch resources on rebuild (#3456) * Prepare FrameGen for instance-owned scratch lifecycle * Make DD-FG rebuild and teardown completion-aware * Restore DD-FG namespace boundary * Isolate DD-FG scratch state and reclaim resources on rebuild * Declare per-instance scratch builder before recording code * Make DD-FG ring teardown report unsafe GPU completion * Retain DD-FG input ring until GPU completion is confirmed * Add DD-FG lifecycle and resource-isolation tests * Cover DD-FG teardown and rebuild failure cases * Document DD-FG scratch ownership and teardown semantics * Guard DD-FG teardown when GPU completion cannot be queried * docs: clarify DD-FG device-loss teardown * fix: define DD-FG scratch state before resize * fix: define DD-FG scratch state before resize * fix(ddfg): wait for the GPU before replacing the input ring on resize * Fix DD-FG ring cleanup after device loss * Propagate DD-FG device-loss status * Retain DD-FG resources when GPU completion is unknown * Retain DD-FG resources when GPU completion is unknown * Retain DD-FG resources when GPU completion is unknown * Retain DD-FG resources when GPU completion is unknown * Retain DD-FG resources when GPU completion is unknown * Retry DD-FG cleanup after an idle-wait failure * Test DD-FG cleanup retry after GPU wait failure --------- Co-authored-by: maxjivi05 --- .../main/cpp/framegen/ddfg/ddfg_engine.cpp | 82 +++++- app/src/main/cpp/framegen/ddfg/ddfg_engine.h | 4 +- app/src/main/cpp/framegen/ddfg/framegen.cpp | 142 +++++++++-- app/src/main/cpp/framegen/ddfg/framegen.hpp | 18 +- .../main/cpp/framegen/ddfg/record_impl.inc | 184 +++++++------- .../cpp/waylandcomp/src/framegen_engine.cpp | 28 ++- docs/development/dd-fg.md | 28 +++ tools/tests/ddfg_flow_levels_harness.cpp | 235 ++++++++++++++++-- tools/tests/test_ddfg_flow_levels.py | 33 +++ 9 files changed, 602 insertions(+), 152 deletions(-) diff --git a/app/src/main/cpp/framegen/ddfg/ddfg_engine.cpp b/app/src/main/cpp/framegen/ddfg/ddfg_engine.cpp index 6e87890b3f..034f2c4d55 100644 --- a/app/src/main/cpp/framegen/ddfg/ddfg_engine.cpp +++ b/app/src/main/cpp/framegen/ddfg/ddfg_engine.cpp @@ -27,7 +27,31 @@ VkImageMemoryBarrier bar(VkImage img, VkImageLayout from, VkImageLayout to, } Engine::Engine() = default; -Engine::~Engine() { destroyRing(); fg_.destroy(); } +Engine::~Engine() { (void)destroy(); } + +bool Engine::destroy() { + if (!fg_.destroy()) { + DDFG_LOGE("native: retaining the input ring because GPU completion is unknown"); + return false; + } + if (!destroyRing(true)) { + DDFG_LOGE("native: could not release the input ring during teardown"); + return false; + } + dev_ = VK_NULL_HANDLE; + unavailable_ = true; + return true; +} + +void Engine::abandon() { + fg_.abandon(); + ring_[0] = Slot{}; + ring_[1] = Slot{}; + dev_ = VK_NULL_HANDLE; + queue_ = VK_NULL_HANDLE; + phys_ = VK_NULL_HANDLE; + unavailable_ = true; +} bool Engine::init(const VkTable& table, VkPhysicalDevice phys, VkDevice dev, uint32_t queueFamily, VkQueue queue) { @@ -59,15 +83,29 @@ bool Engine::prepare(uint32_t w, uint32_t h, VkFormat fmt) { if (unavailable_ || w == 0 || h == 0 || fmt == VK_FORMAT_UNDEFINED) return false; if (builtW_ == w && builtH_ == h && builtFmt_ == fmt && fg_.valid()) return true; - - if (!fg_.onResize(VkExtent2D{w, h}, fmt, false)) { + const bool formatChanged = fmt != builtFmt_; + if (!fg_.onResize(VkExtent2D{w, h}, fmt, formatChanged)) { DDFG_LOGE("native: onResize %ux%u failed; frame generation unavailable", w, h); unavailable_ = true; return false; } - destroyRing(); + bool deviceLost = false; + if (!destroyRing(false, &deviceLost)) { + DDFG_LOGE("native: could not safely release the previous input ring"); + unavailable_ = true; + return false; + } + if (deviceLost) { + DDFG_LOGE("native: device lost while releasing the input ring"); + unavailable_ = true; + return false; + } for (Slot& s : ring_) { - if (!makeSlot(s, w, h, fmt)) { destroyRing(); unavailable_ = true; return false; } + if (!makeSlot(s, w, h, fmt)) { + destroyRing(true); + unavailable_ = true; + return false; + } } builtW_ = w; builtH_ = h; builtFmt_ = fmt; history_ = 0; curr_ = 0; frames_ = 0; @@ -178,11 +216,37 @@ void Engine::destroySlot(Slot& s) { s = Slot{}; } -void Engine::destroyRing() { - if (dev_ == VK_NULL_HANDLE || !dd_.DeviceWaitIdle) return; - if (ring_[0].img || ring_[1].img) dd_.DeviceWaitIdle(dev_); - destroySlot(ring_[0]); destroySlot(ring_[1]); +bool Engine::destroyRing(bool deviceIdleConfirmed, bool* deviceLost) { + if (deviceLost) *deviceLost = false; + const bool hasResources = ring_[0].img || ring_[0].mem || ring_[0].view || + ring_[1].img || ring_[1].mem || ring_[1].view; + if (!hasResources) { + history_ = 0; + return true; + } + if (dev_ == VK_NULL_HANDLE) { + DDFG_LOGE("native: cannot release the input ring without a valid device"); + return false; + } + if (!deviceIdleConfirmed) { + if (!dd_.DeviceWaitIdle) { + DDFG_LOGE("native: cannot release the input ring without vkDeviceWaitIdle"); + return false; + } + const VkResult result = dd_.DeviceWaitIdle(dev_); + if (result == VK_ERROR_DEVICE_LOST) { + if (deviceLost) *deviceLost = true; + unavailable_ = true; + } else if (result != VK_SUCCESS) { + DDFG_LOGE("native: DeviceWaitIdle failed (%d); retaining the input ring", (int)result); + unavailable_ = true; + return false; + } + } + destroySlot(ring_[0]); + destroySlot(ring_[1]); history_ = 0; + return true; } } diff --git a/app/src/main/cpp/framegen/ddfg/ddfg_engine.h b/app/src/main/cpp/framegen/ddfg/ddfg_engine.h index 55c1ef8fa0..aff10a9033 100644 --- a/app/src/main/cpp/framegen/ddfg/ddfg_engine.h +++ b/app/src/main/cpp/framegen/ddfg/ddfg_engine.h @@ -36,13 +36,15 @@ public: uint32_t width, uint32_t height); void reset(); + bool destroy(); + void abandon(); private: struct Slot { VkImage img = VK_NULL_HANDLE; VkDeviceMemory mem = VK_NULL_HANDLE; VkImageView view = VK_NULL_HANDLE; bool valid = false; }; bool makeSlot(Slot& s, uint32_t w, uint32_t h, VkFormat fmt); void destroySlot(Slot& s); - void destroyRing(); + bool destroyRing(bool deviceIdleConfirmed = false, bool* deviceLost = nullptr); uint32_t memType(uint32_t bits, VkMemoryPropertyFlags props) const; DeviceDispatch dd_{}; diff --git a/app/src/main/cpp/framegen/ddfg/framegen.cpp b/app/src/main/cpp/framegen/ddfg/framegen.cpp index 330f83a7cf..20cc5e2d4a 100644 --- a/app/src/main/cpp/framegen/ddfg/framegen.cpp +++ b/app/src/main/cpp/framegen/ddfg/framegen.cpp @@ -7,6 +7,31 @@ namespace ddfg { +struct ScratchState { + VkDevice ownerDevice = VK_NULL_HANDLE; + VkBuffer synthUbo[ddfg::FrameGen::kSynthSlots]{}; + VkDeviceMemory synthUboMem[ddfg::FrameGen::kSynthSlots]{}; + void* synthUboPtr[ddfg::FrameGen::kSynthSlots]{}; + std::vector flowUbo; std::vector flowUboMem; std::vector flowUboPtr; + VkBuffer expandUbo = VK_NULL_HANDLE; VkDeviceMemory expandUboMem = VK_NULL_HANDLE; void* expandUboPtr = nullptr; + VkBuffer flowRegUbo = VK_NULL_HANDLE; VkDeviceMemory flowRegUboMem = VK_NULL_HANDLE; void* flowRegUboPtr = nullptr; + VkBuffer gmUbo[ddfg::FrameGen::kGmSlots]{}; + VkDeviceMemory gmUboMem[ddfg::FrameGen::kGmSlots]{}; + void* gmUboPtr[ddfg::FrameGen::kGmSlots]{}; + VkDescriptorSet sLumaCurr = VK_NULL_HANDLE, sLumaPrev = VK_NULL_HANDLE; + std::vector sDownA, sDownB, sFlow; + VkDescriptorSet sExpand[ddfg::FrameGen::kGmSlots]{}; + VkDescriptorSet sFlowReg0 = VK_NULL_HANDLE, sFlowRegAB = VK_NULL_HANDLE, sFlowRegBA = VK_NULL_HANDLE; + VkDescriptorSet sSynth[ddfg::FrameGen::kSynthSlots]{}; + VkDescriptorSet sGmReduce[ddfg::FrameGen::kGmSlots]{}; + std::vector sGmPrewarp[ddfg::FrameGen::kGmSlots]; + VkExtent2D builtFor{0,0}; + uint64_t builtGeneration = 0; + bool built = false; + bool flowInited = false; + bool flowReady = false; +}; + #define VKOK(x) do { if ((x) != VK_SUCCESS) { DDFG_LOGE("vk fail: %s", #x); return false; } } while (0) uint32_t FrameGen::findMemType(uint32_t bits, VkMemoryPropertyFlags props) const { @@ -108,6 +133,10 @@ static bool buildSetLayout(const DeviceDispatch* dd, VkDevice dev, bool FrameGen::init(const DeviceDispatch* dd, const InstanceDispatch* id, VkPhysicalDevice phys, VkDevice dev, uint32_t queueFamily, VkQueue queue) { + if (device_ || completionUnknown_ || deviceLost_) { + DDFG_LOGE("framegen: refusing to initialize an instance that still owns device resources"); + return false; + } dd_ = dd; id_ = id; phys_ = phys; device_ = dev; queueFamily_ = queueFamily; queue_ = queue; id_->GetPhysicalDeviceMemoryProperties(phys_, &memProps_); @@ -166,16 +195,19 @@ static VkExtent2D levelExtent(VkExtent2D e, int l) { } bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) { - - - if (!force && ready_ && extent.width == extent_.width && extent.height == extent_.height) return true; - if (ready_) { - const VkResult idleResult = dd_->DeviceWaitIdle(device_); - if (idleResult != VK_SUCCESS) { - DDFG_LOGE("framegen resize: DeviceWaitIdle failed (%d); keeping existing images", (int)idleResult); - return false; - } + if (completionUnknown_ || deviceLost_) return false; + if (!device_) { + DDFG_LOGE("framegen: cannot resize before device initialization"); + return false; } + if (!force && ready_ && extent.width == extent_.width && extent.height == extent_.height) return true; + if (ready_ && !waitIdle("resize")) return false; + if (scratch_ && scratch_->ownerDevice != VK_NULL_HANDLE && !destroyScratchResources()) { + DDFG_LOGE("framegen resize: scratch cleanup failed; retaining the previous image set"); + return false; + } + + ready_ = false; ++imageGeneration_; for (auto& i : pyrA_) destroyImage(i); pyrA_.clear(); for (auto& i : pyrB_) destroyImage(i); pyrB_.clear(); @@ -183,7 +215,17 @@ bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) { for (auto& i : flowLvl_) destroyImage(i); flowLvl_.clear(); destroyImage(flowExpA_); destroyImage(flowExpB_); destroyImage(flowRegA_); destroyImage(flowRegB_); - extent_ = extent; ready_ = false; + extent_ = extent; + + for (int i = 0; i < 6; ++i) gmRun_[i] = 0.0; + for (int s = 0; s < kGmSlots; ++s) { + gmSlotValid_[s] = false; + for (int i = 0; i < 6; ++i) gmLinAt_[s][i] = 0.0; + } + gmHaveEst_ = false; + gmEngaged_ = false; + gmStableCount_ = 0; + gmLastTransPx_ = 0.0f; const VkImageUsageFlags lumaUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT; const VkImageUsageFlags flowUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; @@ -234,21 +276,37 @@ void FrameGen::initializeImage(VkCommandBuffer cmd, VkImage img, VkImageLayout t } -void FrameGen::destroy() { - if (!device_) return; - const VkResult idleResult = dd_->DeviceWaitIdle(device_); - if (idleResult != VK_SUCCESS && idleResult != VK_ERROR_DEVICE_LOST) { - DDFG_LOGE("framegen destroy: DeviceWaitIdle failed (%d); preserving resources for safe retry", (int)idleResult); - return; - } - if (idleResult == VK_ERROR_DEVICE_LOST) { - // A lost device cannot become idle again. Still explicitly destroy its - // child objects; skip descriptor-pool reset and release scratch ownership. - DDFG_LOGE("framegen destroy: device lost; releasing owned resources without waiting"); - destroyScratchResources(false); - } else { - destroyScratchResources(); +bool FrameGen::destroy() { + if (!device_) return true; + if (!deviceLost_) { + // A previous wait failure leaves completion unknown, but a later + // teardown attempt may safely retry the wait before releasing resources. + if (!dd_ || !dd_->DeviceWaitIdle) { + ready_ = false; + completionUnknown_ = true; + DDFG_LOGE("framegen destroy: vkDeviceWaitIdle is unavailable; preserving GPU resources"); + return false; + } + const VkResult idleResult = dd_->DeviceWaitIdle(device_); + if (idleResult == VK_SUCCESS) completionUnknown_ = false; + if (idleResult != VK_SUCCESS) { + ready_ = false; + if (idleResult == VK_ERROR_DEVICE_LOST) { + deviceLost_ = true; + DDFG_LOGE("framegen destroy: device lost; releasing owned resources without waiting"); + } else { + completionUnknown_ = true; + DDFG_LOGE("framegen destroy: DeviceWaitIdle failed (%d); preserving resources because GPU completion is unknown", + (int)idleResult); + return false; + } + } } + + ready_ = false; + if (descPool_) dd_->DestroyDescriptorPool(device_, descPool_, nullptr); + descPool_ = VK_NULL_HANDLE; + releaseScratch(); for (auto& i : pyrA_) destroyImage(i); pyrA_.clear(); for (auto& i : pyrB_) destroyImage(i); pyrB_.clear(); for (auto& i : pyrAs_) destroyImage(i); pyrAs_.clear(); @@ -260,15 +318,45 @@ void FrameGen::destroy() { destroyPipe(pGmReduce_); destroyPipe(pGmPrewarp_); destroyPipe(pFlowReg_); for (int s = 0; s < kGmSlots; ++s) { - if (gmSsboMem_[s]) dd_->UnmapMemory(device_, gmSsboMem_[s]); + if (gmSsboPtr_[s] && gmSsboMem_[s]) dd_->UnmapMemory(device_, gmSsboMem_[s]); if (gmSsbo_[s]) dd_->DestroyBuffer(device_, gmSsbo_[s], nullptr); if (gmSsboMem_[s]) dd_->FreeMemory(device_, gmSsboMem_[s], nullptr); gmSsbo_[s] = VK_NULL_HANDLE; gmSsboMem_[s] = VK_NULL_HANDLE; gmSsboPtr_[s] = nullptr; } gmBuffersReady_ = false; - if (descPool_) dd_->DestroyDescriptorPool(device_, descPool_, nullptr); if (linear_) dd_->DestroySampler(device_, linear_, nullptr); - descPool_ = VK_NULL_HANDLE; linear_ = VK_NULL_HANDLE; device_ = VK_NULL_HANDLE; ready_ = false; + linear_ = VK_NULL_HANDLE; + device_ = VK_NULL_HANDLE; + ready_ = false; + deviceLost_ = false; + return true; +} + +void FrameGen::abandon() { + device_ = VK_NULL_HANDLE; + dd_ = nullptr; + id_ = nullptr; + phys_ = VK_NULL_HANDLE; + queue_ = VK_NULL_HANDLE; + linear_ = VK_NULL_HANDLE; + descPool_ = VK_NULL_HANDLE; + scratch_.reset(); + pyrA_.clear(); pyrB_.clear(); pyrAs_.clear(); flowLvl_.clear(); + flowExpA_ = Img{}; flowExpB_ = Img{}; + flowRegA_ = Img{}; flowRegB_ = Img{}; + pLuma_ = Pipe{}; pDown_ = Pipe{}; pFlow_ = Pipe{}; pFlowM4_ = Pipe{}; + pExpand_ = Pipe{}; pExpandM4_ = Pipe{}; pSynth_ = Pipe{}; + pGmReduce_ = Pipe{}; pGmPrewarp_ = Pipe{}; pFlowReg_ = Pipe{}; + for (int s = 0; s < kGmSlots; ++s) { + gmSsbo_[s] = VK_NULL_HANDLE; + gmSsboMem_[s] = VK_NULL_HANDLE; + gmSsboPtr_[s] = nullptr; + gmSlotValid_[s] = false; + } + gmBuffersReady_ = false; + ready_ = false; + completionUnknown_ = false; + deviceLost_ = false; } } diff --git a/app/src/main/cpp/framegen/ddfg/framegen.hpp b/app/src/main/cpp/framegen/ddfg/framegen.hpp index d40518dd1d..bba77480c7 100644 --- a/app/src/main/cpp/framegen/ddfg/framegen.hpp +++ b/app/src/main/cpp/framegen/ddfg/framegen.hpp @@ -1,12 +1,20 @@ #pragma once #include "vk_dispatch.hpp" #include "config.hpp" +#include #include namespace ddfg { +struct ScratchState; + class FrameGen { public: + FrameGen(); + ~FrameGen(); + FrameGen(const FrameGen&) = delete; + FrameGen& operator=(const FrameGen&) = delete; + bool init(const DeviceDispatch* dd, const InstanceDispatch* id, VkPhysicalDevice phys, VkDevice dev, uint32_t queueFamily, VkQueue queue); void configure(const Config& c); @@ -14,7 +22,8 @@ public: void record(VkCommandBuffer cmd, VkImageView prevView, VkImageView currView, VkImageView outView, float alpha, uint32_t gmSlot = 0, uint32_t synthSlot = 0, bool reuseFlow = false); - void destroy(); + bool destroy(); + void abandon(); bool valid() const { return device_ != VK_NULL_HANDLE && ready_; } const Config& config() const { return cfg_; } @@ -64,7 +73,9 @@ private: void destroyPipe(Pipe& p); void barrier(VkCommandBuffer cmd, VkImage img, VkImageLayout from, VkImageLayout to); void initializeImage(VkCommandBuffer cmd, VkImage img, VkImageLayout to); - void destroyScratchResources(bool resetPool = true); + bool waitIdle(const char* operation); + bool destroyScratchResources(bool resetPool = true); + void releaseScratch(); const DeviceDispatch* dd_ = nullptr; const InstanceDispatch* id_ = nullptr; @@ -80,7 +91,10 @@ private: VkExtent2D extent_{}; uint64_t imageGeneration_ = 0; bool ready_ = false; + bool completionUnknown_ = false; + bool deviceLost_ = false; int flowFinest_ = kFlowFinestDefault; + std::unique_ptr scratch_; Pipe pLuma_, pDown_, pFlow_, pFlowM4_, pExpand_, pExpandM4_, pSynth_; Pipe pGmReduce_, pGmPrewarp_; diff --git a/app/src/main/cpp/framegen/ddfg/record_impl.inc b/app/src/main/cpp/framegen/ddfg/record_impl.inc index 1d9e71df8c..3922db391b 100644 --- a/app/src/main/cpp/framegen/ddfg/record_impl.inc +++ b/app/src/main/cpp/framegen/ddfg/record_impl.inc @@ -1,33 +1,7 @@ -namespace { -struct ScratchState { - VkDevice ownerDevice = VK_NULL_HANDLE; - VkBuffer synthUbo[ddfg::FrameGen::kSynthSlots]{}; - VkDeviceMemory synthUboMem[ddfg::FrameGen::kSynthSlots]{}; - void* synthUboPtr[ddfg::FrameGen::kSynthSlots]{}; - std::vector flowUbo; std::vector flowUboMem; std::vector flowUboPtr; - VkBuffer expandUbo = VK_NULL_HANDLE; VkDeviceMemory expandUboMem = VK_NULL_HANDLE; void* expandUboPtr = nullptr; - VkBuffer flowRegUbo = VK_NULL_HANDLE; VkDeviceMemory flowRegUboMem = VK_NULL_HANDLE; void* flowRegUboPtr = nullptr; - VkBuffer gmUbo[ddfg::FrameGen::kGmSlots]{}; - VkDeviceMemory gmUboMem[ddfg::FrameGen::kGmSlots]{}; - void* gmUboPtr[ddfg::FrameGen::kGmSlots]{}; - VkDescriptorSet sLumaCurr = VK_NULL_HANDLE, sLumaPrev = VK_NULL_HANDLE; - std::vector sDownA, sDownB, sFlow; - VkDescriptorSet sExpand[ddfg::FrameGen::kGmSlots]{}; - - - - VkDescriptorSet sFlowReg0 = VK_NULL_HANDLE, sFlowRegAB = VK_NULL_HANDLE, sFlowRegBA = VK_NULL_HANDLE; - VkDescriptorSet sSynth[ddfg::FrameGen::kSynthSlots]{}; - VkDescriptorSet sGmReduce[ddfg::FrameGen::kGmSlots]{}; - std::vector sGmPrewarp[ddfg::FrameGen::kGmSlots]; - VkExtent2D builtFor{0,0}; - uint64_t builtGeneration = 0; - bool built = false; - bool flowInited = false; - bool flowReady = false; -}; -ScratchState g_scratch; +namespace ddfg { +FrameGen::FrameGen() : scratch_(std::make_unique()) {} +FrameGen::~FrameGen() { (void)destroy(); } } static bool makeUbo(const ddfg::DeviceDispatch* dd, VkDevice dev, @@ -144,7 +118,7 @@ static void mulAff(const double A[3][3], const double B[3][3], double out[3][3]) namespace ddfg { -static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, +static bool ensureScratch(ScratchState& S, FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, const VkPhysicalDeviceMemoryProperties& mp, VkDescriptorPool pool, VkSampler samp, VkExtent2D ext, std::vector& pyrA, std::vector& pyrB, @@ -157,30 +131,72 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, FrameGen::Img& flowRegA, FrameGen::Img& flowRegB, VkBuffer* gmSsbo, int kLevels, const Config& cfg, uint64_t imageGeneration); -static void destroyScratch(const DeviceDispatch* dd, VkDevice dev, VkDescriptorPool pool, - bool resetPool = true) { - if (g_scratch.ownerDevice != VK_NULL_HANDLE && g_scratch.ownerDevice != dev) return; +bool FrameGen::waitIdle(const char* operation) { + if (completionUnknown_ || deviceLost_ || !device_) return false; + if (!dd_ || !dd_->DeviceWaitIdle) { + completionUnknown_ = true; + ready_ = false; + DDFG_LOGE("framegen: %s cannot confirm GPU completion; this instance is stopped and its resources are retained", + operation); + return false; + } + const VkResult result = dd_->DeviceWaitIdle(device_); + if (result == VK_SUCCESS) return true; + ready_ = false; + if (result == VK_ERROR_DEVICE_LOST) { + deviceLost_ = true; + DDFG_LOGE("framegen: %s reported device loss; cleanup will skip further waits", operation); + } else { + completionUnknown_ = true; + DDFG_LOGE("framegen: %s vkDeviceWaitIdle failed (%d); this instance is stopped and its GPU resources retained", + operation, (int)result); + } + return false; +} + +bool FrameGen::destroyScratchResources(bool resetPool) { + if (!scratch_) return true; + if (resetPool && descPool_ && !deviceLost_) { + if (!dd_ || !dd_->ResetDescriptorPool) { + ready_ = false; + DDFG_LOGE("framegen: descriptor-pool reset is unavailable; retaining scratch resources"); + return false; + } + const VkResult result = dd_->ResetDescriptorPool(device_, descPool_, 0); + if (result != VK_SUCCESS) { + ready_ = false; + if (result == VK_ERROR_DEVICE_LOST) deviceLost_ = true; + DDFG_LOGE("framegen: descriptor-pool reset failed (%d); retaining scratch resources", + (int)result); + return false; + } + } + releaseScratch(); + return true; +} + +void FrameGen::releaseScratch() { + if (!scratch_) return; + auto& S = *scratch_; auto freeUbo = [&](VkBuffer& b, VkDeviceMemory& m, void*& p) { - if (m) dd->UnmapMemory(dev, m); - if (b) dd->DestroyBuffer(dev, b, nullptr); - if (m) dd->FreeMemory(dev, m, nullptr); - b = VK_NULL_HANDLE; m = VK_NULL_HANDLE; p = nullptr; + if (p && m) dd_->UnmapMemory(device_, m); + if (b) dd_->DestroyBuffer(device_, b, nullptr); + if (m) dd_->FreeMemory(device_, m, nullptr); + b = VK_NULL_HANDLE; + m = VK_NULL_HANDLE; + p = nullptr; }; - auto& S = g_scratch; for (int s = 0; s < FrameGen::kSynthSlots; ++s) freeUbo(S.synthUbo[s], S.synthUboMem[s], S.synthUboPtr[s]); - freeUbo(S.expandUbo, S.expandUboMem, S.expandUboPtr); + freeUbo(S.expandUbo, S.expandUboMem, S.expandUboPtr); freeUbo(S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr); for (size_t i = 0; i < S.flowUbo.size(); ++i) freeUbo(S.flowUbo[i], S.flowUboMem[i], S.flowUboPtr[i]); for (int s = 0; s < FrameGen::kGmSlots; ++s) freeUbo(S.gmUbo[s], S.gmUboMem[s], S.gmUboPtr[s]); - if (resetPool && pool && dd->ResetDescriptorPool) dd->ResetDescriptorPool(dev, pool, 0); S = ScratchState{}; } -void FrameGen::destroyScratchResources(bool resetPool) { - destroyScratch(dd_, device_, descPool_, resetPool); -} void FrameGen::configure(const Config& c) { + if (completionUnknown_ || deviceLost_) return; Config nextCfg = c; nextCfg.sanitize(); int want = flowFinestForPreset(nextCfg.perfPreset); @@ -203,16 +219,12 @@ void FrameGen::configure(const Config& c) { return; } - // Keep the previous configuration and image set if the device cannot idle. - const VkResult idleResult = dd_->DeviceWaitIdle(device_); - if (idleResult != VK_SUCCESS) { - DDFG_LOGE("framegen configure: DeviceWaitIdle failed (%d); keeping previous configuration and images", - (int)idleResult); + if (!waitIdle("live preset rebuild")) return; + if (scratch_ && scratch_->ownerDevice != VK_NULL_HANDLE && !destroyScratchResources()) { + DDFG_LOGE("perf-preset live rebuild: scratch cleanup failed; keeping the previous configuration"); return; } - // The device is idle, so reset motion history before rebuilding. This - // also leaves the predictor reset if onResize fails. for (int i = 0; i < 6; ++i) gmRun_[i] = 0.0; for (int s = 0; s < kGmSlots; ++s) { gmSlotValid_[s] = false; @@ -223,20 +235,17 @@ void FrameGen::configure(const Config& c) { gmStableCount_ = 0; gmLastTransPx_ = 0.0f; - // Prevent onResize from issuing a second wait. - destroyScratch(dd_, device_, descPool_); cfg_ = nextCfg; flowFinest_ = want; ready_ = false; if (!onResize(extent_, VK_FORMAT_UNDEFINED, true)) { ready_ = false; - DDFG_LOGE("perf-preset live rebuild: onResize FAILED at %ux%u - FG disabled until next resize", + DDFG_LOGE("perf-preset live rebuild: onResize FAILED at %ux%u - frame generation unavailable", extent_.width, extent_.height); return; } DDFG_LOGI("perf-preset live rebuild DONE (kFlowFinest=%d, flow predictor reset)", flowFinest_); } - bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) { ++gmFrames_; if (!gmBuffersReady_ || cfg_.gmMode == 2 ) { @@ -306,35 +315,33 @@ bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) { void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView currView, VkImageView outView, float alpha, uint32_t gmSlot, uint32_t synthSlot, bool reuseFlow) { if (!valid()) return; + auto& S = *scratch_; if (gmSlot >= (uint32_t)kGmSlots) gmSlot = 0; if (synthSlot >= (uint32_t)kSynthSlots) synthSlot = 0; const bool m4 = (cfg_.model == 4); const Pipe& flowP = m4 ? pFlowM4_ : pFlow_; const Pipe& expandP = m4 ? pExpandM4_ : pExpand_; - if (!g_scratch.built || g_scratch.builtFor.width != extent_.width || - g_scratch.builtFor.height != extent_.height || - g_scratch.builtGeneration != imageGeneration_) { - if (g_scratch.built) { - const VkResult idleResult = dd_->DeviceWaitIdle(device_); - if (idleResult != VK_SUCCESS) { - DDFG_LOGE("framegen record: DeviceWaitIdle failed (%d); skipping scratch rebuild", (int)idleResult); - return; - } - destroyScratch(dd_, device_, descPool_); + if (!S.built || S.builtFor.width != extent_.width || + S.builtFor.height != extent_.height || + S.builtGeneration != imageGeneration_) { + if (S.built && !waitIdle("scratch rebuild")) return; + if (S.ownerDevice != VK_NULL_HANDLE && !destroyScratchResources()) { + DDFG_LOGE("framegen record: scratch cleanup failed; skipping this frame"); + return; } - if (!ensureScratch(this, dd_, device_, memProps_, descPool_, linear_, extent_, + if (!ensureScratch(S, this, dd_, device_, memProps_, descPool_, linear_, extent_, pyrA_, pyrB_, pyrAs_, flowLvl_, flowExpA_, flowExpB_, pLuma_, pDown_, flowP, expandP, pSynth_, pGmReduce_, pGmPrewarp_, pFlowReg_, flowRegA_, flowRegB_, gmSsbo_, kLevels, cfg_, imageGeneration_)) return; } - if (g_scratch.ownerDevice != device_) return; - if (reuseFlow && !g_scratch.flowReady) return; + if (S.ownerDevice != device_) return; + if (reuseFlow && !S.flowReady) return; if (!reuseFlow) { bool gmEngaged = updateGlobalMotion(gmSlot, extent_); - if (g_scratch.gmUboPtr[gmSlot]) { + if (S.gmUboPtr[gmSlot]) { GMUBO g{}; g.lin[0]=(float)gmRun_[0]; g.lin[1]=(float)gmRun_[1]; g.lin[2]=(float)gmRun_[2]; g.lin[3]=(float)gmRun_[3]; g.linT[0]=(float)gmRun_[4]; g.linT[1]=(float)gmRun_[5]; g.linT[2]=gmEngaged?1.0f:0.0f; g.linT[3]=0.0f; @@ -342,7 +349,7 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur g.app[0]=(float)gmRun_[0]; g.app[1]=(float)gmRun_[1]; g.app[2]=(float)gmRun_[2]; g.app[3]=(float)gmRun_[3]; g.appT[0]=(float)gmRun_[4]; g.appT[1]=(float)gmRun_[5]; } - std::memcpy(g_scratch.gmUboPtr[gmSlot], &g, sizeof(g)); + std::memcpy(S.gmUboPtr[gmSlot], &g, sizeof(g)); } { static int lastEng = -1; @@ -353,7 +360,7 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur } } - const VkDescriptorSet lumaSets[] = {g_scratch.sLumaCurr, g_scratch.sLumaPrev}; + const VkDescriptorSet lumaSets[] = {S.sLumaCurr, S.sLumaPrev}; const uint32_t lumaBindings[] = {32, 32}; const VkDescriptorType lumaTypes[] = { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER}; @@ -367,9 +374,9 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur SynthUBO su{cfg_.flowScale, alpha, cfg_.beta, cfg_.lambda, cfg_.epsilon, cfg_.photoScale, 0, 0, cfg_.hudX0, cfg_.hudY0, cfg_.hudX1, cfg_.hudY1}; - if (g_scratch.synthUboPtr[synthSlot]) std::memcpy(g_scratch.synthUboPtr[synthSlot], &su, sizeof(su)); + if (S.synthUboPtr[synthSlot]) std::memcpy(S.synthUboPtr[synthSlot], &su, sizeof(su)); - const VkDescriptorSet synthSet = g_scratch.sSynth[synthSlot]; + const VkDescriptorSet synthSet = S.sSynth[synthSlot]; const VkDescriptorSet synthSets[] = {synthSet, synthSet, synthSet}; const uint32_t synthBindings[] = {32, 33, 48}; const VkDescriptorType synthTypes[] = { @@ -468,17 +475,17 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &b); } - disp(pLuma_, g_scratch.sLumaCurr, levelExtent(extent_, 0)); - disp(pLuma_, g_scratch.sLumaPrev, levelExtent(extent_, 0)); + disp(pLuma_, S.sLumaCurr, levelExtent(extent_, 0)); + disp(pLuma_, S.sLumaPrev, levelExtent(extent_, 0)); barPair(pyrA_[0], pyrB_[0]); for (int l = 1; l < kLevels; ++l) { - disp(pDown_, g_scratch.sDownA[l - 1], levelExtent(extent_, l)); - disp(pDown_, g_scratch.sDownB[l - 1], levelExtent(extent_, l)); + disp(pDown_, S.sDownA[l - 1], levelExtent(extent_, l)); + disp(pDown_, S.sDownB[l - 1], levelExtent(extent_, l)); barPair(pyrA_[l], pyrB_[l]); } - if (gmBuffersReady_ && g_scratch.sGmReduce[gmSlot]) { + if (gmBuffersReady_ && S.sGmReduce[gmSlot]) { dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.pipeline); - dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.layout, 0, 1, &g_scratch.sGmReduce[gmSlot], 0, nullptr); + dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.layout, 0, 1, &S.sGmReduce[gmSlot], 0, nullptr); dd_->CmdDispatch(cmd, (uint32_t)(kGmThreads / 64), 1, 1); VkMemoryBarrier mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; mb.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; mb.dstAccessMask = VK_ACCESS_HOST_READ_BIT; @@ -486,27 +493,27 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur 0, 1, &mb, 0, nullptr, 0, nullptr); } for (int l = flowFinest_; l < kLevels; ++l) { - disp(pGmPrewarp_, g_scratch.sGmPrewarp[gmSlot][l], levelExtent(extent_, l)); + disp(pGmPrewarp_, S.sGmPrewarp[gmSlot][l], levelExtent(extent_, l)); bar(pyrAs_[l]); } for (int l = kLevels - 1; l >= flowFinest_; --l) { - disp(flowP, g_scratch.sFlow[l], levelExtent(extent_, l)); + disp(flowP, S.sFlow[l], levelExtent(extent_, l)); bar(flowLvl_[l]); } if (frEngaged) { const int F = flowFinest_; const VkExtent2D fe = levelExtent(extent_, F); - if (g_scratch.flowRegUboPtr) { + if (S.flowRegUboPtr) { FlowRegUBO fu{cfg_.frDt, cfg_.frLambda, cfg_.frEdge, cfg_.frEps}; - std::memcpy(g_scratch.flowRegUboPtr, &fu, sizeof(fu)); + std::memcpy(S.flowRegUboPtr, &fu, sizeof(fu)); } FrameGen::Img* last = nullptr; for (int it = 0; it < cfg_.frIters; ++it) { VkDescriptorSet set; FrameGen::Img* outImg; - if (it == 0) { set = g_scratch.sFlowReg0; outImg = &flowRegA_; } - else if (it % 2 == 1) { set = g_scratch.sFlowRegAB; outImg = &flowRegB_; } - else { set = g_scratch.sFlowRegBA; outImg = &flowRegA_; } + if (it == 0) { set = S.sFlowReg0; outImg = &flowRegA_; } + else if (it % 2 == 1) { set = S.sFlowRegAB; outImg = &flowRegB_; } + else { set = S.sFlowRegBA; outImg = &flowRegA_; } dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pFlowReg_.pipeline); dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pFlowReg_.layout, 0, 1, &set, 0, nullptr); dd_->CmdDispatch(cmd, (fe.width + 15) / 16, (fe.height + 15) / 16, 1); @@ -540,14 +547,14 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur } } - disp(expandP, g_scratch.sExpand[gmSlot], levelExtent(extent_, 0)); + disp(expandP, S.sExpand[gmSlot], levelExtent(extent_, 0)); barPair(flowExpA_, flowExpB_); - g_scratch.flowReady = true; + S.flowReady = true; } disp(pSynth_, synthSet, levelExtent(extent_, 0)); } -static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, +static bool ensureScratch(ScratchState& S, FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, const VkPhysicalDeviceMemoryProperties& mp, VkDescriptorPool pool, VkSampler samp, VkExtent2D ext, std::vector& pyrA, std::vector& pyrB, @@ -559,7 +566,6 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, const FrameGen::Pipe& pGmPrewarp, const FrameGen::Pipe& pFlowReg, FrameGen::Img& flowRegA, FrameGen::Img& flowRegB, VkBuffer* gmSsbo, int kLevels, const Config& cfg, uint64_t imageGeneration) { - auto& S = g_scratch; if (S.ownerDevice != VK_NULL_HANDLE && S.ownerDevice != dev) return false; S = ScratchState{}; S.ownerDevice = dev; diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp b/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp index 014c7c7ec8..ed16dd4c88 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp @@ -31,6 +31,7 @@ bool g_probed = false, g_ready = false; std::unique_ptr g_lsfg; std::unique_ptr g_ddfg; +std::vector> g_retained_ddfg; int g_kind = -1; char g_build[96] = ""; @@ -128,7 +129,14 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica void fge_device_lost(void) { g_lsfg.reset(); - g_ddfg.reset(); + if (g_ddfg) { + if (g_ddfg->destroy()) g_ddfg.reset(); + else g_retained_ddfg.push_back(std::move(g_ddfg)); + } + // The device is being torn down. Unknown-completion resources must not be + // passed to Vulkan destruction calls; the VkDevice teardown reclaims them. + for (auto& engine : g_retained_ddfg) engine->abandon(); + g_retained_ddfg.clear(); g_kind = -1; g_dev = VK_NULL_HANDLE; g_queue = VK_NULL_HANDLE; @@ -193,9 +201,21 @@ int fge_start(int kind, const char *cache_path) { } void fge_stop(void) { - if ((g_lsfg || g_ddfg) && g_table.DeviceWaitIdle && g_dev) g_table.DeviceWaitIdle(g_dev); - g_lsfg.reset(); - g_ddfg.reset(); + if (g_lsfg) { + if (g_table.DeviceWaitIdle && g_dev) g_table.DeviceWaitIdle(g_dev); + g_lsfg.reset(); + } + for (auto it = g_retained_ddfg.begin(); it != g_retained_ddfg.end();) { + if ((*it)->destroy()) it = g_retained_ddfg.erase(it); + else ++it; + } + if (g_ddfg) { + if (g_ddfg->destroy()) g_ddfg.reset(); + else { + ELOGE("ddfg-native: retaining engine until GPU completion is known or device teardown"); + g_retained_ddfg.push_back(std::move(g_ddfg)); + } + } g_kind = -1; } diff --git a/docs/development/dd-fg.md b/docs/development/dd-fg.md index 81cb43a9ea..1275b18758 100644 --- a/docs/development/dd-fg.md +++ b/docs/development/dd-fg.md @@ -27,6 +27,28 @@ bytes for dimensions at least four pixels: These are pixel payloads, not driver allocation sizes or measured FPS gains. +## Scratch ownership and rebuilds + +Each `FrameGen` instance owns its scratch buffers, mappings and descriptor sets. +A size or live-preset rebuild first confirms GPU completion and resets that +instance's descriptor pool, then releases the old scratch and image resources. +Motion/history validity is reset with the rebuilt images. Repeated preparation +at the same size and ordinary frame recording do not add device-idle waits. + +Healthy destruction releases the descriptor pool, mapped scratch buffers and +images. The native engine releases its input ring only after the chain confirms +completion, so an input image is not destroyed before the wait. + +If `vkDeviceWaitIdle` fails with an error other than +`VK_ERROR_DEVICE_LOST`, the affected instance becomes unusable: further +recording and rebuilding stop, and its Vulkan resources and input ring are +intentionally retained because GPU completion is unknown. Device loss follows +a separate teardown path: `FrameGen::destroy()` releases its owned resources +without another wait and returns true, allowing the Engine to release the +input ring. This is local DD-FG containment, not compositor-wide GPU recovery. +A descriptor-pool reset failure also stops that resize without releasing the +resources, but healthy teardown can still release them. + ## Validation Run `python3 -m unittest discover -s tools/tests -p 'test_ddfg_flow_levels.py'`. @@ -35,4 +57,10 @@ selected through the usual SDK/NDK environment variables. It compiles the actual DD-FG chain against a mock Vulkan dispatch table and checks resource counts, dispatch order and sizes, valid descriptor bindings, both models, every preset, 2x/3x/4x generation, small/odd extents, resize and live preset changes. +The same harness enforces descriptor-pool capacity, accounts for all live +resources, and models pending GPU work to reject early cleanup. Lifecycle cases +cover repeated rebuilds, same-size restarts, two simultaneous instances, +automatic/idempotent destruction, partial resize allocation, failed GPU waits, +and failed descriptor-pool resets. The actual native `Engine` is included to +check the input-ring destruction order. It does not execute shaders on a GPU or replace on-device validation. diff --git a/tools/tests/ddfg_flow_levels_harness.cpp b/tools/tests/ddfg_flow_levels_harness.cpp index e5cf7bf701..4c8fdb30d4 100644 --- a/tools/tests/ddfg_flow_levels_harness.cpp +++ b/tools/tests/ddfg_flow_levels_harness.cpp @@ -1,4 +1,5 @@ #include "framegen.hpp" +#include "ddfg_engine.h" #include #include #include @@ -25,12 +26,19 @@ std::map buffers; std::map allocations; std::map buffer_memory; std::map> descriptors; +std::map set_pools; +std::map pool_capacities; std::map pipelines; std::map image_ids; std::map buffer_ids; std::vector dispatches; +std::vector external_views; uintptr_t serial = 100; -unsigned buffer_creates, set_creates; +unsigned buffer_creates, set_creates, pipeline_creates, idle_calls, image_creates, fail_image_at; +bool gpu_pending; +VkResult idle_result = VK_SUCCESS, reset_result = VK_SUCCESS; +const ddfg::DeviceDispatch *engine_dispatch; +const ddfg::InstanceDispatch *engine_instance; VkPipeline bound_pipeline; VkDescriptorSet bound_set; uint64_t command_hash = 14695981039346656037ull; @@ -61,6 +69,7 @@ template void VKAPI_CALL destroy(VkDevice, T, const VkAllocationCallbac VkResult VKAPI_CALL create_image(VkDevice, const VkImageCreateInfo *info, const VkAllocationCallbacks *, VkImage *out) { + if (++image_creates == fail_image_at) return VK_ERROR_OUT_OF_DEVICE_MEMORY; *out = handle(); images[*out] = {info->extent, info->format, info->usage}; return VK_SUCCESS; @@ -73,9 +82,11 @@ VkResult VKAPI_CALL create_view(VkDevice, const VkImageViewCreateInfo *info, return VK_SUCCESS; } void VKAPI_CALL destroy_image(VkDevice, VkImage image, const VkAllocationCallbacks *) { + assert(!gpu_pending); assert(images.erase(image) == 1); } void VKAPI_CALL destroy_view(VkDevice, VkImageView view, const VkAllocationCallbacks *) { + assert(!gpu_pending); assert(views.erase(view) == 1); } VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo *info, @@ -86,6 +97,7 @@ VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo *info, return VK_SUCCESS; } void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks *) { + assert(!gpu_pending); assert(buffers.erase(buffer) == 1); buffer_memory.erase(buffer); } @@ -104,6 +116,7 @@ VkResult VKAPI_CALL allocate(VkDevice, const VkMemoryAllocateInfo *info, return VK_SUCCESS; } void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks *) { + assert(!gpu_pending); assert(allocations.erase(memory) == 1); } VkResult VKAPI_CALL bind_image(VkDevice, VkImage image, VkDeviceMemory memory, VkDeviceSize) { @@ -123,8 +136,14 @@ VkResult VKAPI_CALL map_memory(VkDevice, VkDeviceMemory memory, VkDeviceSize off *out = allocation.data.get(); return VK_SUCCESS; } -void VKAPI_CALL unmap(VkDevice, VkDeviceMemory memory) { assert(allocations.count(memory)); } -VkResult VKAPI_CALL idle(VkDevice) { return VK_SUCCESS; } +void VKAPI_CALL unmap(VkDevice, VkDeviceMemory memory) { + assert(!gpu_pending && allocations.count(memory)); +} +VkResult VKAPI_CALL idle(VkDevice) { + idle_calls++; + if (idle_result == VK_SUCCESS) gpu_pending = false; + return idle_result; +} void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProperties *out) { *out = {}; out->memoryTypeCount = 1; @@ -132,15 +151,42 @@ void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProper VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; } VkResult VKAPI_CALL allocate_sets(VkDevice, const VkDescriptorSetAllocateInfo *info, VkDescriptorSet *out) { + const auto used = std::count_if(set_pools.begin(), set_pools.end(), [&](const auto &entry) { + return entry.second == info->descriptorPool; + }); + if (used + info->descriptorSetCount > pool_capacities.at(info->descriptorPool)) + return VK_ERROR_OUT_OF_POOL_MEMORY; for (uint32_t i = 0; i < info->descriptorSetCount; i++) { out[i] = handle(); descriptors[out[i]] = {}; + set_pools[out[i]] = info->descriptorPool; set_creates++; } return VK_SUCCESS; } -VkResult VKAPI_CALL reset_pool(VkDevice, VkDescriptorPool, VkDescriptorPoolResetFlags) { - descriptors.clear(); +VkResult VKAPI_CALL create_pool(VkDevice, const VkDescriptorPoolCreateInfo *info, + const VkAllocationCallbacks *, VkDescriptorPool *out) { + *out = handle(); + pool_capacities[*out] = info->maxSets; + return VK_SUCCESS; +} +void drop_sets(VkDescriptorPool pool) { + assert(!gpu_pending); + for (auto it = set_pools.begin(); it != set_pools.end();) { + if (it->second == pool) { + descriptors.erase(it->first); + it = set_pools.erase(it); + } else ++it; + } +} +void VKAPI_CALL destroy_pool(VkDevice, VkDescriptorPool pool, const VkAllocationCallbacks *) { + drop_sets(pool); + assert(pool_capacities.erase(pool) == 1); +} +VkResult VKAPI_CALL reset_pool(VkDevice, VkDescriptorPool pool, VkDescriptorPoolResetFlags) { + assert(!gpu_pending); + if (reset_result != VK_SUCCESS) return reset_result; + drop_sets(pool); return VK_SUCCESS; } void VKAPI_CALL update_sets(VkDevice, uint32_t count, const VkWriteDescriptorSet *writes, @@ -164,12 +210,15 @@ VkResult VKAPI_CALL create_pipelines(VkDevice, VkPipelineCache, uint32_t count, const VkComputePipelineCreateInfo *, const VkAllocationCallbacks *, VkPipeline *out) { for (uint32_t i = 0; i < count; i++) { - const auto index = static_cast(pipelines.size()); + const auto index = pipeline_creates++ % 10; out[i] = handle(); pipelines[out[i]] = index; } return VK_SUCCESS; } +void VKAPI_CALL destroy_pipeline(VkDevice, VkPipeline pipeline, const VkAllocationCallbacks *) { + assert(!gpu_pending && pipelines.erase(pipeline) == 1); +} void VKAPI_CALL bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline pipeline) { assert(pipelines.count(pipeline)); bound_pipeline = pipeline; @@ -248,10 +297,20 @@ VkImageView external_image(uint32_t width, uint32_t height) { images[image] = {{width, height, 1}, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT}; views[view] = image; + external_views.push_back(view); return view; } +void clear_external_images() { + for (auto view : external_views) { + images.erase(views.at(view)); + views.erase(view); + } + external_views.clear(); +} + void record(ddfg::FrameGen &fg, int model, uint32_t width, uint32_t height, unsigned generations) { + gpu_pending = false; const auto previous = external_image(width, height), current = external_image(width, height); const auto first = dispatches.size(); for (unsigned i = 0; i < generations; i++) @@ -275,14 +334,29 @@ void record(ddfg::FrameGen &fg, int model, uint32_t width, uint32_t height, unsi const auto &actual = dispatches[first + i], &want = expected[i]; assert(actual.pipeline == want.pipeline && actual.x == want.x && actual.y == want.y && actual.z == want.z); } - for (auto it = views.begin(); it != views.end();) { - if (images.at(it->second).format == VK_FORMAT_R8G8B8A8_UNORM) { - images.erase(it->second); - it = views.erase(it); - } else ++it; - } + clear_external_images(); + gpu_pending = true; } +void check_empty() { + assert(images.empty() && views.empty() && buffers.empty() && allocations.empty()); + assert(descriptors.empty() && set_pools.empty() && pool_capacities.empty() && pipelines.empty()); +} + +void check_working_set(const ddfg::FrameGen &fg) { + assert(images.size() == static_cast(32 - 2 * fg.flowFinest())); + assert(buffers.size() == static_cast(18 - fg.flowFinest())); + assert(descriptors.size() == static_cast(54 - 4 * fg.flowFinest())); + assert(allocations.size() == images.size() + buffers.size()); +} + +} + +struct VkTable {}; +bool ddfgVkdInit(const VkTable &, ddfg::DeviceDispatch &dd, ddfg::InstanceDispatch &id) { + dd = *engine_dispatch; + id = *engine_instance; + return true; } int main(int argc, char **argv) { @@ -312,25 +386,145 @@ int main(int argc, char **argv) { dd.DestroyDescriptorSetLayout = destroy; dd.CreatePipelineLayout = create; dd.DestroyPipelineLayout = destroy; - dd.CreateDescriptorPool = create; - dd.DestroyDescriptorPool = destroy; dd.ResetDescriptorPool = reset_pool; + dd.CreateDescriptorPool = create_pool; + dd.DestroyDescriptorPool = destroy_pool; dd.ResetDescriptorPool = reset_pool; dd.AllocateDescriptorSets = allocate_sets; dd.UpdateDescriptorSets = update_sets; - dd.CreateComputePipelines = create_pipelines; dd.DestroyPipeline = destroy; + dd.CreateComputePipelines = create_pipelines; dd.DestroyPipeline = destroy_pipeline; dd.CmdBindPipeline = bind_pipeline; dd.CmdBindDescriptorSets = bind_sets; dd.CmdDispatch = dispatch; dd.CmdPipelineBarrier = barrier; dd.CmdClearColorImage = clear_image; dd.CmdCopyImage = copy_image; - ddfg::FrameGen fg; - assert(fg.init(&dd, &id, reinterpret_cast(1), reinterpret_cast(2), - 0, reinterpret_cast(3))); + engine_dispatch = ⅆ + engine_instance = &id; ddfg::Config cfg; cfg.enabled = true; cfg.model = model; cfg.perfPreset = preset; cfg.flowScale = 0.6f; - fg.configure(cfg); - assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM)); + auto initialize = [&](ddfg::FrameGen &fg) { + assert(fg.init(&dd, &id, reinterpret_cast(1), reinterpret_cast(2), + 0, reinterpret_cast(3))); + fg.configure(cfg); + assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM)); + }; + if (mode == "steady" || mode == "automatic") { + const auto waits = idle_calls; + { + ddfg::FrameGen fg; + initialize(fg); + for (unsigned repeat = 0; repeat < repeats; repeat++) { + record(fg, model, width, height, generations); + assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM)); + assert(idle_calls == waits); + check_working_set(fg); + } + if (mode == "steady") { + fg.destroy(); + fg.destroy(); + assert(idle_calls == waits + 1); + } + } + check_empty(); + assert(idle_calls == waits + 1); + std::puts("PASS lifecycle=steady-and-idempotent-destruction"); + return 0; + } + if (mode == "restart" || mode == "instances") { + for (unsigned repeat = 0; repeat < repeats; repeat++) { + ddfg::FrameGen first; + initialize(first); + record(first, model, width, height, generations); + check_working_set(first); + if (mode == "instances") { + gpu_pending = false; + ddfg::FrameGen second; + initialize(second); + record(second, model, width, height, generations); + first.destroy(); + record(second, model, width, height, generations); + check_working_set(second); + second.destroy(); + } else first.destroy(); + check_empty(); + } + std::puts("PASS lifecycle=restart-and-instance-isolation"); + return 0; + } + if (mode == "engine" || mode == "engine-failure") { + { + ddfg::Engine engine; + assert(engine.init(VkTable{}, reinterpret_cast(1), + reinterpret_cast(2), 0, reinterpret_cast(3))); + engine.configure(generations + 1, model, preset, 0.6f); + assert(engine.prepare(width, height, VK_FORMAT_R8G8B8A8_UNORM)); + for (unsigned frame = 0; frame < 3; frame++) { + gpu_pending = false; + const auto source = external_image(width, height); + const auto output = external_image(width, height); + const auto count = engine.plan(generations); + engine.process(reinterpret_cast(1), views.at(source), width, height, count); + for (unsigned generation = 0; generation < count; generation++) + engine.generateInto(reinterpret_cast(1), generation, count, + views.at(output), output, width, height); + clear_external_images(); + gpu_pending = true; + } + if (mode == "engine-failure") { + idle_result = VK_ERROR_OUT_OF_DEVICE_MEMORY; + assert(!engine.prepare(width + 17, height + 9, VK_FORMAT_R8G8B8A8_UNORM)); + assert(engine.unavailable() && !engine.valid()); + } + } + if (mode == "engine") check_empty(); + else assert(gpu_pending && !images.empty() && !buffers.empty() && !descriptors.empty()); + std::puts("PASS lifecycle=engine-ownership"); + return 0; + } + if (mode == "idle-failure" || mode == "destroy-failure" || mode == "reset-failure" || mode == "partial") { + { + ddfg::FrameGen fg; + initialize(fg); + record(fg, model, width, height, generations); + const auto prior_buffers = buffers.size(), prior_images = images.size(), prior_sets = descriptors.size(); + if (mode == "partial") { + fail_image_at = image_creates + 2; + assert(!fg.onResize({width + 17, height + 9}, VK_FORMAT_R8G8B8A8_UNORM)); + assert(!fg.valid()); + } else { + if (mode == "reset-failure") reset_result = VK_ERROR_OUT_OF_HOST_MEMORY; + else idle_result = VK_ERROR_OUT_OF_DEVICE_MEMORY; + if (mode == "destroy-failure") fg.destroy(); + else assert(!fg.onResize({width + 17, height + 9}, VK_FORMAT_R8G8B8A8_UNORM)); + assert(!fg.valid()); + assert(buffers.size() == prior_buffers && images.size() == prior_images && + descriptors.size() == prior_sets); + const auto prior_dispatches = dispatches.size(); + const auto prior_waits = idle_calls; + fg.record(reinterpret_cast(1), VK_NULL_HANDLE, VK_NULL_HANDLE, VK_NULL_HANDLE, 0.5f); + assert(dispatches.size() == prior_dispatches); + if (mode != "reset-failure") { + assert(!fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM)); + cfg.perfPreset = (preset + 1) % 3; + fg.configure(cfg); + if (mode == "destroy-failure") { + idle_result = VK_SUCCESS; + assert(fg.destroy()); + } else { + fg.destroy(); + assert(idle_calls == prior_waits + 1); + } + } + } + } + if (mode == "reset-failure" || mode == "partial" || mode == "destroy-failure") check_empty(); + else assert(gpu_pending && !images.empty() && !buffers.empty() && !descriptors.empty()); + std::puts("PASS lifecycle=failure-containment"); + return 0; + } + ddfg::FrameGen fg; + initialize(fg); assert(mode == "resources" || mode == "record" || mode == "resize" || mode == "preset"); for (unsigned repeat = 0; repeat < repeats; repeat++) { const auto old_buffers = buffer_creates, old_sets = set_creates; if (mode != "record") check_images(width, height, fg.flowFinest()); record(fg, model, width, height, generations); if (mode != "record") { + check_working_set(fg); assert(buffer_creates - old_buffers == static_cast(15 - fg.flowFinest())); assert(set_creates - old_sets == static_cast(54 - 4 * fg.flowFinest())); } @@ -356,4 +550,5 @@ int main(int argc, char **argv) { dispatches.size(), static_cast(command_hash)); fg.destroy(); assert(images.empty() && views.empty()); + if (mode != "record") check_empty(); } diff --git a/tools/tests/test_ddfg_flow_levels.py b/tools/tests/test_ddfg_flow_levels.py index d5efd6355d..eb5f5a0186 100644 --- a/tools/tests/test_ddfg_flow_levels.py +++ b/tools/tests/test_ddfg_flow_levels.py @@ -40,6 +40,7 @@ class DdfgFlowLevelsTest(unittest.TestCase): "-Wno-missing-field-initializers", "-Wno-misleading-indentation", "-I" + str(work / "include"), "-I" + str(CHAIN), str(ROOT / "tools/tests/ddfg_flow_levels_harness.cpp"), str(CHAIN / "framegen.cpp"), + str(CHAIN / "ddfg_engine.cpp"), "-o", str(cls.binary), ], capture_output=True, text=True, timeout=120) if build.returncode: @@ -97,6 +98,38 @@ class DdfgFlowLevelsTest(unittest.TestCase): with self.subTest(model=model): self.run_case("preset", model=model, generations=3, repeats=4) + def test_many_resizes_do_not_accumulate_scratch_resources(self): + for model in (3, 4): + for preset in range(3): + with self.subTest(model=model, preset=preset): + self.run_case("resize", model=model, preset=preset, generations=3, repeats=16) + + def test_same_size_engine_restarts_use_fresh_scratch(self): + self.run_case("restart", generations=3, repeats=8) + + def test_instances_do_not_share_or_destroy_each_others_scratch(self): + self.run_case("instances", generations=3, repeats=3) + + def test_engine_teardown_waits_before_destroying_its_input_ring(self): + self.run_case("engine", generations=3) + + def test_failed_gpu_wait_stops_recording_and_retains_resources(self): + for mode in ("idle-failure", "destroy-failure", "engine-failure"): + with self.subTest(mode=mode): + self.run_case(mode, generations=3) + + def test_descriptor_pool_reset_failure_does_not_free_live_scratch(self): + self.run_case("reset-failure", generations=3) + + def test_partial_resize_allocation_is_cleaned_up(self): + self.run_case("partial", generations=3) + + def test_steady_frames_and_same_size_prepare_add_no_gpu_waits(self): + self.run_case("steady", generations=3, repeats=10) + + def test_scope_exit_releases_resources_without_an_explicit_destroy(self): + self.run_case("automatic", generations=3, repeats=3) + if __name__ == "__main__": unittest.main()