diff --git a/Common/GPU/Vulkan/VulkanMemory.cpp b/Common/GPU/Vulkan/VulkanMemory.cpp index b80adb269a..986f3b2c79 100644 --- a/Common/GPU/Vulkan/VulkanMemory.cpp +++ b/Common/GPU/Vulkan/VulkanMemory.cpp @@ -161,356 +161,3 @@ void VulkanPushBuffer::Unmap() { vkUnmapMemory(vulkan_->GetDevice(), buffers_[buf_].deviceMemory); writePtr_ = nullptr; } - -VulkanDeviceAllocator::VulkanDeviceAllocator(VulkanContext *vulkan, size_t minSlabSize, size_t maxSlabSize) - : vulkan_(vulkan), minSlabSize_(minSlabSize), maxSlabSize_(maxSlabSize) { - _assert_((minSlabSize_ & (SLAB_GRAIN_SIZE - 1)) == 0); -} - -VulkanDeviceAllocator::~VulkanDeviceAllocator() { - _assert_(destroyed_); - _assert_(slabs_.empty()); -} - -void VulkanDeviceAllocator::Destroy() { - for (Slab &slab : slabs_) { - // Did anyone forget to free? - for (auto pair : slab.allocSizes) { - int slabUsage = slab.usage[pair.first]; - // If it's not 2 (queued), there's a leak. - // If it's zero, it means allocSizes is somehow out of sync. - if (slabUsage == 1) { - ERROR_LOG(G3D, "VulkanDeviceAllocator detected memory leak of size %d", (int)pair.second); - } else { - _dbg_assert_msg_(slabUsage == 2, "Destroy: slabUsage has unexpected value %d", slabUsage); - } - } - - _assert_(slab.deviceMemory); - vulkan_->Delete().QueueDeleteDeviceMemory(slab.deviceMemory); - } - slabs_.clear(); - destroyed_ = true; -} - -size_t VulkanDeviceAllocator::Allocate(const VkMemoryRequirements &reqs, VkDeviceMemory *deviceMemory, const char *tag) { - _assert_(!destroyed_); - uint32_t memoryTypeIndex; - bool pass = vulkan_->MemoryTypeFromProperties(reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memoryTypeIndex); - if (!pass) { - ERROR_LOG(G3D, "Failed to pick an appropriate memory type (req: %08x)", reqs.memoryTypeBits); - return ALLOCATE_FAILED; - } - - size_t size = reqs.size; - - size_t align = reqs.alignment <= SLAB_GRAIN_SIZE ? 1 : (size_t)(reqs.alignment >> SLAB_GRAIN_SHIFT); - size_t blocks = (size_t)((size + SLAB_GRAIN_SIZE - 1) >> SLAB_GRAIN_SHIFT); - - const size_t numSlabs = slabs_.size(); - for (size_t i = 0; i < numSlabs; ++i) { - // We loop starting at the last successful allocation. - // This helps us "creep forward", and also spend less time allocating. - const size_t actualSlab = (lastSlab_ + i) % numSlabs; - Slab &slab = slabs_[actualSlab]; - if (slab.memoryTypeIndex != memoryTypeIndex) - continue; - size_t start = slab.nextFree; - - while (start < slab.usage.size()) { - start = (start + align - 1) & ~(align - 1); - if (AllocateFromSlab(slab, start, blocks, tag)) { - // Allocated? Great, let's return right away. - *deviceMemory = slab.deviceMemory; - lastSlab_ = actualSlab; - return start << SLAB_GRAIN_SHIFT; - } - } - } - - // Okay, we couldn't fit it into any existing slabs. We need a new one. - if (!AllocateSlab(size, memoryTypeIndex)) { - return ALLOCATE_FAILED; - } - - // Guaranteed to be the last one, unless it failed to allocate. - Slab &slab = slabs_[slabs_.size() - 1]; - size_t start = 0; - if (AllocateFromSlab(slab, start, blocks, tag)) { - *deviceMemory = slab.deviceMemory; - lastSlab_ = slabs_.size() - 1; - return start << SLAB_GRAIN_SHIFT; - } - - // Somehow... we're out of space. Darn. - return ALLOCATE_FAILED; -} - -bool VulkanDeviceAllocator::AllocateFromSlab(Slab &slab, size_t &start, size_t blocks, const char *tag) { - _assert_(!destroyed_); - - if (start + blocks > slab.usage.size()) { - start = slab.usage.size(); - return false; - } - - for (size_t i = 0; i < blocks; ++i) { - if (slab.usage[start + i]) { - // If we just ran into one, there's probably an allocation size. - auto it = slab.allocSizes.find(start + i); - if (it != slab.allocSizes.end()) { - start += i + it->second; - } else { - // We don't know how big it is, so just skip to the next one. - start += i + 1; - } - return false; - } - } - - // Okay, this run is good. Actually mark it. - for (size_t i = 0; i < blocks; ++i) { - slab.usage[start + i] = 1; - } - slab.nextFree = start + blocks; - if (slab.nextFree >= slab.usage.size()) { - slab.nextFree = 0; - } - - // Remember the size so we can free. - slab.allocSizes[start] = blocks; - slab.tags[start] = { time_now_d(), 0.0, tag }; - slab.totalUsage += blocks; - return true; -} - -int VulkanDeviceAllocator::ComputeUsagePercent() const { - int blockSum = 0; - int blocksUsed = 0; - for (size_t i = 0; i < slabs_.size(); i++) { - blockSum += (int)slabs_[i].usage.size(); - for (size_t j = 0; j < slabs_[i].usage.size(); j++) { - blocksUsed += slabs_[i].usage[j] != 0 ? 1 : 0; - } - } - return blockSum == 0 ? 0 : 100 * blocksUsed / blockSum; -} - -std::vector VulkanDeviceAllocator::GetSlabUsage(int slabIndex) const { - if (slabIndex < 0 || slabIndex >= (int)slabs_.size()) - return std::vector(); - const Slab &slab = slabs_[slabIndex]; - return slab.usage; -} - -void VulkanDeviceAllocator::DoTouch(VkDeviceMemory deviceMemory, size_t offset) { - size_t start = offset >> SLAB_GRAIN_SHIFT; - bool found = false; - for (Slab &slab : slabs_) { - if (slab.deviceMemory != deviceMemory) { - continue; - } - - auto it = slab.tags.find(start); - if (it != slab.tags.end()) { - it->second.touched = time_now_d(); - found = true; - } - } - - _assert_msg_(found, "Failed to find allocation to touch - use after free?"); -} - -void VulkanDeviceAllocator::Free(VkDeviceMemory deviceMemory, size_t offset) { - _assert_(!destroyed_); - - _assert_msg_(!slabs_.empty(), "No slabs - can't be anything to free! double-freed?"); - - // First, let's validate. This will allow stack traces to tell us when frees are bad. - size_t start = offset >> SLAB_GRAIN_SHIFT; - bool found = false; - for (Slab &slab : slabs_) { - if (slab.deviceMemory != deviceMemory) { - continue; - } - - auto it = slab.allocSizes.find(start); - _assert_msg_(it != slab.allocSizes.end(), "Double free?"); - // This means a double free, while queued to actually free. - _assert_msg_(slab.usage[start] == 1, "Double free when queued to free!"); - - // Mark it as "free in progress". - slab.usage[start] = 2; - found = true; - break; - } - - // Wrong deviceMemory even? Maybe it was already decimated, but that means a double-free. - _assert_msg_(found, "Failed to find allocation to free! Double-freed?"); - - // Okay, now enqueue. It's valid. - FreeInfo *info = new FreeInfo(this, deviceMemory, offset); - // Dispatches a call to ExecuteFree on the next delete round. - vulkan_->Delete().QueueCallback(&DispatchFree, info); -} - -void VulkanDeviceAllocator::ExecuteFree(FreeInfo *userdata) { - if (destroyed_) { - // We already freed this, and it's been validated. - delete userdata; - return; - } - - VkDeviceMemory deviceMemory = userdata->deviceMemory; - size_t offset = userdata->offset; - - // Revalidate in case something else got freed and made things inconsistent. - size_t start = offset >> SLAB_GRAIN_SHIFT; - bool found = false; - for (Slab &slab : slabs_) { - if (slab.deviceMemory != deviceMemory) { - continue; - } - - auto it = slab.allocSizes.find(start); - if (it != slab.allocSizes.end()) { - size_t size = it->second; - for (size_t i = 0; i < size; ++i) { - slab.usage[start + i] = 0; - } - slab.allocSizes.erase(it); - slab.totalUsage -= size; - - // Allow reusing. - if (slab.nextFree > start) { - slab.nextFree = start; - } - } else { - // Ack, a double free? - _assert_msg_(false, "Double free? Block missing at offset %d", (int)userdata->offset); - } - auto itTag = slab.tags.find(start); - if (itTag != slab.tags.end()) { - slab.tags.erase(itTag); - } - found = true; - break; - } - - // Wrong deviceMemory even? Maybe it was already decimated, but that means a double-free. - _assert_msg_(found, "ExecuteFree: Block not found (offset %d)", (int)offset); - delete userdata; -} - -bool VulkanDeviceAllocator::AllocateSlab(VkDeviceSize minBytes, int memoryTypeIndex) { - _assert_(!destroyed_); - if (!slabs_.empty() && minSlabSize_ < maxSlabSize_) { - // We're allocating an additional slab, so rachet up its size. - // TODO: Maybe should not do this when we are allocating a new slab due to memoryTypeIndex not matching? - minSlabSize_ <<= 1; - } - - VkMemoryAllocateInfo alloc{ VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; - alloc.allocationSize = minSlabSize_; - alloc.memoryTypeIndex = memoryTypeIndex; - - while (alloc.allocationSize < minBytes) { - alloc.allocationSize <<= 1; - } - - VkDeviceMemory deviceMemory; - VkResult res = vkAllocateMemory(vulkan_->GetDevice(), &alloc, NULL, &deviceMemory); - if (res != VK_SUCCESS) { - // If it's something else, we used it wrong? - _assert_(res == VK_ERROR_OUT_OF_HOST_MEMORY || res == VK_ERROR_OUT_OF_DEVICE_MEMORY || res == VK_ERROR_TOO_MANY_OBJECTS); - // Okay, so we ran out of memory. - return false; - } - - slabs_.resize(slabs_.size() + 1); - Slab &slab = slabs_[slabs_.size() - 1]; - slab.memoryTypeIndex = memoryTypeIndex; - slab.deviceMemory = deviceMemory; - slab.usage.resize((size_t)(alloc.allocationSize >> SLAB_GRAIN_SHIFT)); - - return true; -} - -void VulkanDeviceAllocator::ReportOldUsage() { - double now = time_now_d(); - static const double OLD_AGE = 10.0; - for (size_t i = 0; i < slabs_.size(); ++i) { - const auto &slab = slabs_[i]; - - bool hasOldAllocs = false; - for (auto &it : slab.tags) { - const auto info = it.second; - double touchedAge = now - info.touched; - if (touchedAge >= OLD_AGE) { - hasOldAllocs = true; - break; - } - } - - if (hasOldAllocs) { - NOTICE_LOG(G3D, "Slab %d usage:", (int)i); - for (auto &it : slab.tags) { - const auto info = it.second; - - double createAge = now - info.created; - double touchedAge = now - info.touched; - NOTICE_LOG(G3D, " * %s (created %fs ago, used %fs ago)", info.tag, createAge, touchedAge); - } - } - } -} - -void VulkanDeviceAllocator::Decimate() { - _assert_(!destroyed_); - bool foundFree = false; - - if (TRACK_TOUCH) { - ReportOldUsage(); - } - - for (size_t i = 0; i < slabs_.size(); ++i) { - // Go backwards. This way, we keep the largest free slab. - // We do this here (instead of the for) since size_t is unsigned. - size_t index = slabs_.size() - i - 1; - auto &slab = slabs_[index]; - - if (!slab.allocSizes.empty()) { - size_t usagePercent = 100 * slab.totalUsage / slab.usage.size(); - size_t freeNextPercent = 100 * slab.nextFree / slab.usage.size(); - - // This may mean we're going to leave an allocation hanging. Reset nextFree instead. - if (freeNextPercent >= 100 - usagePercent) { - size_t newFree = 0; - while (newFree < slab.usage.size()) { - auto it = slab.allocSizes.find(newFree); - if (it == slab.allocSizes.end()) { - break; - } - - newFree += it->second; - } - - slab.nextFree = newFree; - } - continue; - } - - if (!foundFree) { - // Let's allow one free slab, so we have room. - foundFree = true; - continue; - } - - // Okay, let's free this one up. - vulkan_->Delete().QueueDeleteDeviceMemory(slab.deviceMemory); - slabs_.erase(slabs_.begin() + index); - - // Let's check the next one, which is now in this same slot. - --i; - } -} diff --git a/Common/GPU/Vulkan/VulkanMemory.h b/Common/GPU/Vulkan/VulkanMemory.h index fc415681a0..c61ad0b874 100644 --- a/Common/GPU/Vulkan/VulkanMemory.h +++ b/Common/GPU/Vulkan/VulkanMemory.h @@ -126,103 +126,3 @@ private: uint8_t *writePtr_ = nullptr; VkBufferUsageFlags usage_; }; - -// VulkanDeviceAllocator -// -// Implements a slab based allocator that manages suballocations inside the slabs. -// Bitmaps are used to handle allocation state, with a 1KB grain. -class VulkanDeviceAllocator { -public: - // Slab sizes start at minSlabSize and double until maxSlabSize. - // Total slab count is unlimited, as long as there's free memory. - VulkanDeviceAllocator(VulkanContext *vulkan, size_t minSlabSize, size_t maxSlabSize); - ~VulkanDeviceAllocator(); - - // Requires all memory be free beforehand (including all pending deletes.) - void Destroy(); - - void Begin() { - Decimate(); - } - - void End() { - } - - // May return ALLOCATE_FAILED if the allocation fails. - // NOTE: Lifetime of the string tag points to must exceed that of the allocation. - size_t Allocate(const VkMemoryRequirements &reqs, VkDeviceMemory *deviceMemory, const char *tag); - - // Crashes on a double or misfree. - void Free(VkDeviceMemory deviceMemory, size_t offset); - - inline void Touch(VkDeviceMemory deviceMemory, size_t offset) { - if (TRACK_TOUCH) { - DoTouch(deviceMemory, offset); - } - } - - static const size_t ALLOCATE_FAILED = -1; - // Set to true to report potential leaks / long held textures. - static const bool TRACK_TOUCH = false; - - int GetSlabCount() const { return (int)slabs_.size(); } - int GetMinSlabSize() const { return (int)minSlabSize_; } - int GetMaxSlabSize() const { return (int)maxSlabSize_; } - - int ComputeUsagePercent() const; - std::vector GetSlabUsage(int slab) const; - -private: - static const size_t SLAB_GRAIN_SIZE = 1024; - static const uint8_t SLAB_GRAIN_SHIFT = 10; - static const uint32_t UNDEFINED_MEMORY_TYPE = -1; - - struct UsageInfo { - double created; - double touched; - const char *tag; - }; - - struct Slab { - VkDeviceMemory deviceMemory; - uint32_t memoryTypeIndex = UNDEFINED_MEMORY_TYPE; - std::vector usage; - std::unordered_map allocSizes; - std::unordered_map tags; - size_t nextFree; - size_t totalUsage; - - size_t Size() { - return usage.size() * SLAB_GRAIN_SIZE; - } - }; - - struct FreeInfo { - explicit FreeInfo(VulkanDeviceAllocator *a, VkDeviceMemory d, size_t o) - : allocator(a), deviceMemory(d), offset(o) { - } - - VulkanDeviceAllocator *allocator; - VkDeviceMemory deviceMemory; - size_t offset; - }; - - static void DispatchFree(void *userdata) { - auto freeInfo = static_cast(userdata); - freeInfo->allocator->ExecuteFree(freeInfo); // this deletes freeInfo - } - - bool AllocateSlab(VkDeviceSize minBytes, int memoryTypeIndex); - bool AllocateFromSlab(Slab &slab, size_t &start, size_t blocks, const char *tag); - void Decimate(); - void DoTouch(VkDeviceMemory deviceMemory, size_t offset); - void ExecuteFree(FreeInfo *userdata); - void ReportOldUsage(); - - VulkanContext *const vulkan_; - std::vector slabs_; - size_t lastSlab_ = 0; - size_t minSlabSize_; - const size_t maxSlabSize_; - bool destroyed_ = false; -}; diff --git a/GPU/Vulkan/DebugVisVulkan.cpp b/GPU/Vulkan/DebugVisVulkan.cpp index 83433ecbdf..25eeb44a1b 100644 --- a/GPU/Vulkan/DebugVisVulkan.cpp +++ b/GPU/Vulkan/DebugVisVulkan.cpp @@ -32,6 +32,8 @@ #undef DrawText void DrawAllocatorVis(UIContext *ui, GPUInterface *gpu) { + /* + if (!gpu) { return; } @@ -47,7 +49,6 @@ void DrawAllocatorVis(UIContext *ui, GPUInterface *gpu) { GPU_Vulkan *gpuVulkan = static_cast(gpu); VulkanDeviceAllocator *alloc = gpuVulkan->GetTextureCache()->GetAllocator(); - std::vector texturesToDelete; for (int i = 0; i < alloc->GetSlabCount(); i++) { std::vector usage = alloc->GetSlabUsage(i); @@ -98,6 +99,7 @@ void DrawAllocatorVis(UIContext *ui, GPUInterface *gpu) { for (auto iter : texturesToDelete) iter->Release(); + */ } void DrawGPUProfilerVis(UIContext *ui, GPUInterface *gpu) { diff --git a/GPU/Vulkan/TextureCacheVulkan.cpp b/GPU/Vulkan/TextureCacheVulkan.cpp index d534d12fa3..ec524d7e2a 100644 --- a/GPU/Vulkan/TextureCacheVulkan.cpp +++ b/GPU/Vulkan/TextureCacheVulkan.cpp @@ -204,17 +204,6 @@ void TextureCacheVulkan::DeviceLost() { Clear(true); - if (allocator_) { - allocator_->Destroy(); - - // We have to delete on queue, so this can free its queued deletions. - vulkan->Delete().QueueCallback([](void *ptr) { - auto allocator = static_cast(ptr); - delete allocator; - }, allocator_); - allocator_ = nullptr; - } - samplerCache_.DeviceLost(); if (samplerNearest_) @@ -234,7 +223,6 @@ void TextureCacheVulkan::DeviceRestore(Draw::DrawContext *draw) { _assert_(!allocator_); - allocator_ = new VulkanDeviceAllocator(vulkan, TEXCACHE_MIN_SLAB_SIZE, TEXCACHE_MAX_SLAB_SIZE); samplerCache_.DeviceRestore(vulkan); VkSamplerCreateInfo samp{ VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; @@ -341,15 +329,13 @@ void TextureCacheVulkan::StartFrame() { // Since textures are 2D maybe we should square this, but might get too non-aggressive. slabPressureLimit *= g_Config.iTexScalingLevel; } - Decimate(allocator_->GetSlabCount() > slabPressureLimit); + Decimate(false); // TODO: Use some indication from VMA. } - allocator_->Begin(); computeShaderManager_.BeginFrame(); } void TextureCacheVulkan::EndFrame() { - allocator_->End(); computeShaderManager_.EndFrame(); if (texelsScaledThisFrame_) { @@ -1058,8 +1044,7 @@ bool TextureCacheVulkan::GetCurrentTextureDebug(GPUDebugBuffer &buffer, int leve } void TextureCacheVulkan::GetStats(char *ptr, size_t size) { - snprintf(ptr, size, "Alloc: %d slabs\nSlab min/max: %d/%d\nAlloc usage: %d%%", - allocator_->GetSlabCount(), allocator_->GetMinSlabSize(), allocator_->GetMaxSlabSize(), allocator_->ComputeUsagePercent()); + snprintf(ptr, size, "N/A"); } std::vector TextureCacheVulkan::DebugGetSamplerIDs() const { diff --git a/GPU/Vulkan/TextureCacheVulkan.h b/GPU/Vulkan/TextureCacheVulkan.h index da228ffac4..bf3870e005 100644 --- a/GPU/Vulkan/TextureCacheVulkan.h +++ b/GPU/Vulkan/TextureCacheVulkan.h @@ -36,7 +36,6 @@ class DrawEngineVulkan; class VulkanContext; class VulkanTexture; class VulkanPushBuffer; -class VulkanDeviceAllocator; class SamplerCache { public: