Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4079,6 +4079,7 @@ Graphics::Context VulkanDevice::buildContext() const {
context.sampleLocationGridSizes = state->sampleLocationGridSizes;
context.shaderStencilExport = state->shaderStencilExport;
context.memoryProperties2 =state->memoryBudget ? state->InstanceFunction<PFN_vkGetPhysicalDeviceMemoryProperties2>("vkGetPhysicalDeviceMemoryProperties2") : nullptr;
context.integratedGpu = state->properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
context.singlePassStorage = state->storageImageWithoutFormat;
context.cacheReclaim = Graphics::ReleaseTextureCaches;
return context;
Expand Down
14 changes: 14 additions & 0 deletions core/libs/prx/libSceAgcDriver/Graphics/include/BufferPool.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#include "prx/libSceAgcDriver/Graphics/include/Context.hpp"
#include <chrono>
#include "prx/libSceAgcDriver/Execution/include/Mutex.hpp"
#include "prx/libSceAgcDriver/Graphics/include/VramBudget.hpp"
#include <array>
#include <cstdint>
#include <deque>
#include <list>
Expand Down Expand Up @@ -79,6 +81,9 @@ class BufferPool {
SlabSlot TakeSlot(const Context& context, std::uint32_t memoryType, std::size_t capacity, bool addressable);
VkDeviceSize PutSlot(VkDeviceMemory memory, VkDeviceSize offset) noexcept;
std::size_t SlabBlocks();
VramBudget& Vram() { return vram; }
void ReadHeapBudget();
static constexpr std::chrono::milliseconds DemandWindow{1000};

private:
struct SlabBlock {
Expand Down Expand Up @@ -176,6 +181,15 @@ class BufferPool {
AgcDriver::Mutex slabMutex;
std::unordered_map<std::uint64_t, Slab> slabs;
std::unordered_map<VkDeviceMemory, std::unique_ptr<SlabBlock>> slabBlocks;
VramBudget vram;
std::uint64_t vramDropped = 0;
VkDeviceSize vramDroppedBytes = 0;
std::array<VkDeviceSize, 8> demand{};
std::int64_t demandSlot = -1;
std::uint64_t vramChurn = 0;
bool vramDropping = false;
void noteDemand(VkDeviceSize bytes);
VkDeviceSize demandFloor() const;
static constexpr VkDeviceSize budget = 512ull * 1024 * 1024;
// The small tier's own budget (slots of at most half a MiB each): pinned host memory the large
// tier's budget does not count.
Expand Down
16 changes: 13 additions & 3 deletions core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,16 @@ inline std::uint64_t& DeviceProcLookups() {

inline constexpr std::size_t EmptyBufferBytes = 16;

struct HostPlacementCounts {
std::atomic<std::uint64_t> count{0};
std::atomic<std::uint64_t> bytes{0};
};

inline HostPlacementCounts& HostPlacements() {
static HostPlacementCounts counts;
return counts;
}

struct Context {
VkDevice device;
VkPhysicalDevice physical;
Expand Down Expand Up @@ -195,6 +205,7 @@ struct Context {
std::mutex* settleQueueMutex = nullptr;
PFN_vkGetPhysicalDeviceMemoryProperties2 memoryProperties2 = nullptr;
VkDeviceSize (*cacheReclaim)(VkDeviceSize bytes, bool newImage) = nullptr;
bool integratedGpu = false;
RenderCache* renderCache = nullptr;
DrawQueue* drawQueue = nullptr;
GraphicsPipelineCache* graphicsPipelines = nullptr;
Expand Down Expand Up @@ -344,9 +355,8 @@ struct Context {
if (budget == 0 || (usage < budget && bytes <= budget - usage)) return type;
const auto host = HostMemoryType(mask);
if (!host) return type;
static std::atomic<std::uint64_t> placements{0}, placedBytes{0};
const auto count = placements.fetch_add(1) + 1;
const auto total = placedBytes.fetch_add(bytes) + bytes;
const auto count = HostPlacements().count.fetch_add(1) + 1;
const auto total = HostPlacements().bytes.fetch_add(bytes) + bytes;
if (count <= 5 || (count & (count - 1)) == 0) std::fprintf(stderr, "[gpu] %s: device-local heap %u uses %llu of its %llu MiB budget, %llu bytes placed in host memory type %u; %llu such allocations, %llu MiB\n", what, heap, static_cast<unsigned long long>(usage >> 20u), static_cast<unsigned long long>(budget >> 20u), static_cast<unsigned long long>(bytes), *host, static_cast<unsigned long long>(count), static_cast<unsigned long long>(total >> 20u));
return *host;
}
Expand Down
43 changes: 43 additions & 0 deletions core/libs/prx/libSceAgcDriver/Graphics/include/VramBudget.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_VRAMBUDGET_HPP
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_VRAMBUDGET_HPP

#include "prx/libSceAgcDriver/Graphics/include/Context.hpp"
#include <cstdint>
#include <optional>

namespace AgcDriver::Graphics {

struct VramReport {
std::uint32_t heap = 0;
VkDeviceSize heapBytes = 0;
VkDeviceSize budget = 0;
VkDeviceSize usage = 0;
VkDeviceSize target = 0;
};

class VramBudget {
public:
explicit VramBudget(const Context& context);
VramBudget(const VramBudget&) = delete;
VramBudget& operator=(const VramBudget&) = delete;
static VkDeviceSize TargetFor(VkDeviceSize size, VkDeviceSize available);
bool Enabled() const { return heap.has_value(); }
void Read(const VkPhysicalDeviceMemoryBudgetPropertiesEXT& reported);
VkDeviceSize Excess() const;
void Released(VkDeviceSize bytes);
VramReport Report() const;

private:
VkDeviceSize target() const;
std::optional<std::uint32_t> heap;
VkDeviceSize heapBytes = 0;
VkDeviceSize limit = 0;
bool announced = false;
VkDeviceSize budget = 0;
VkDeviceSize usage = 0;
VkDeviceSize released = 0;
};

}

#endif
80 changes: 75 additions & 5 deletions core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,15 @@ bool systemMemoryHeap(const VkPhysicalDeviceMemoryProperties& memory, std::uint3

constexpr VkBufferUsageFlags deviceUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;

VkDeviceSize releasedBytes(const std::vector<BufferAllocation>& allocations) {
VkDeviceSize bytes = 0;
for (const auto& allocation : allocations) bytes += allocation.slab ? 0 : allocation.allocationBytes;
return bytes;
}

BufferPool::BufferPool(const Context& context) : maxSlots(std::max<std::size_t>(1, std::min<std::size_t>(MaxSlots(), context.limits.maxMemoryAllocationCount / 6u))), cacheReclaim(context.cacheReclaim), device(context.device), unmap(context.Function<PFN_vkUnmapMemory>("vkUnmapMemory")), destroyBuffer(context.Function<PFN_vkDestroyBuffer>("vkDestroyBuffer")), freeMemory(context.Function<PFN_vkFreeMemory>("vkFreeMemory")), allocateMemory(context.Function<PFN_vkAllocateMemory>("vkAllocateMemory")), mapMemory(context.Function<PFN_vkMapMemory>("vkMapMemory")), physical(context.physical), memoryProperties(context.memory), memoryProperties2(context.memoryProperties2) {
}

BufferPool::BufferPool(const Context& context) : maxSlots(std::max<std::size_t>(1, std::min<std::size_t>(MaxSlots(), context.limits.maxMemoryAllocationCount / 6u))), cacheReclaim(context.cacheReclaim), device(context.device), unmap(context.Function<PFN_vkUnmapMemory>("vkUnmapMemory")), destroyBuffer(context.Function<PFN_vkDestroyBuffer>("vkDestroyBuffer")), freeMemory(context.Function<PFN_vkFreeMemory>("vkFreeMemory")), allocateMemory(context.Function<PFN_vkAllocateMemory>("vkAllocateMemory")), mapMemory(context.Function<PFN_vkMapMemory>("vkMapMemory")), physical(context.physical), memoryProperties(context.memory), memoryProperties2(context.memoryProperties2), vram(context) {
smallTier.budget = smallBudget;
largeTier.budget = budget;
deviceTier.budget = deviceBudget(context);
Expand Down Expand Up @@ -91,9 +97,8 @@ VkDeviceMemory BufferPool::AllocateMemory(const VkMemoryAllocateInfo& allocation
++attempts;
if (result == VK_SUCCESS) {
if (allocatedType != nullptr) *allocatedType = *hostType;
static std::atomic<std::uint64_t> placements{0}, placedBytes{0};
const auto count = placements.fetch_add(1, std::memory_order_relaxed) + 1;
const auto total = placedBytes.fetch_add(allocation.allocationSize, std::memory_order_relaxed) + allocation.allocationSize;
const auto count = HostPlacements().count.fetch_add(1, std::memory_order_relaxed) + 1;
const auto total = HostPlacements().bytes.fetch_add(allocation.allocationSize, std::memory_order_relaxed) + allocation.allocationSize;
if (count <= 5 || (count & (count - 1)) == 0) std::fprintf(stderr, "[bufferpool] %s: memory type %u is out of device memory for %llu bytes after reclaiming %llu and releasing %llu; placed in host memory type %u until it is released; %llu such allocations, %llu MiB\n", operation, allocation.memoryTypeIndex, static_cast<unsigned long long>(allocation.allocationSize), static_cast<unsigned long long>(reclaimed), static_cast<unsigned long long>(released), *hostType, static_cast<unsigned long long>(count), static_cast<unsigned long long>(total >> 20u));
return memory;
}
Expand Down Expand Up @@ -143,9 +148,16 @@ bool BufferPool::heapOverBudget() {
for (std::uint32_t heap = 0; heap < memoryProperties.memoryHeapCount && heap < VK_MAX_MEMORY_HEAPS; ++heap) {
if ((memoryProperties.memoryHeaps[heap].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0 && reported.heapBudget[heap] != 0 && reported.heapUsage[heap] > reported.heapBudget[heap]) heapOver = true;
}
vram.Read(reported);
return heapOver;
}

void BufferPool::ReadHeapBudget() {
std::lock_guard lock(mutex);
heapRead = {};
heapOverBudget();
}

VkDeviceMemory BufferPool::TakeImageMemory(const VkMemoryAllocateInfo& allocation, const char* operation, std::optional<std::uint32_t> hostType, std::uint32_t* allocatedType, bool newImage) {
const auto type = allocation.memoryTypeIndex;
if (imagePooled(allocation.allocationSize, type)) {
Expand Down Expand Up @@ -205,6 +217,7 @@ void BufferPool::PutImageMemory(VkDeviceMemory memory, VkDeviceSize bytes, std::
++imageSlots;
imageBytes += bytes;
}
vram.Released(releasedBytes(evicted));
} catch (...) {
destroy(allocation);
}
Expand Down Expand Up @@ -401,14 +414,20 @@ std::optional<BufferAllocation> BufferPool::Take(std::size_t bytes, VkBufferUsag
if (now - lastReport > std::chrono::seconds(10)) {
lastReport = now;
AgcDriver::ProfilePrint_nid_no_patch("[bufferpool] small: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB); large: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB)%s; device: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB of %llu); images: %llu hits, %llu misses, %llu evictions, %zu retained (%.0f MiB of %llu)\n", static_cast<unsigned long long>(smallTier.hits), static_cast<unsigned long long>(smallTier.misses), static_cast<unsigned long long>(smallTier.evictions), smallTier.slots, smallTier.retainedBytes / 1048576.0, static_cast<unsigned long long>(largeTier.hits), static_cast<unsigned long long>(largeTier.misses), static_cast<unsigned long long>(largeTier.evictions), largeTier.slots, largeTier.retainedBytes / 1048576.0, sharedTiers() ? " (shared)" : "", static_cast<unsigned long long>(deviceTier.hits), static_cast<unsigned long long>(deviceTier.misses), static_cast<unsigned long long>(deviceTier.evictions), deviceTier.slots, deviceTier.retainedBytes / 1048576.0, static_cast<unsigned long long>(deviceTier.budget >> 20u), static_cast<unsigned long long>(imageHits), static_cast<unsigned long long>(imageMisses), static_cast<unsigned long long>(imageEvictions), imageSlots, imageBytes / 1048576.0, static_cast<unsigned long long>(imageBudget >> 20u));
if (vram.Enabled()) {
const auto report = vram.Report();
AgcDriver::ProfilePrint_nid_no_patch("[vram] heap %u: budget %llu MiB, usage %llu MiB, target %llu MiB; %llu released device buffers (%.0f MiB) not pooled over the target, demand floor %.0f MiB, %llu device allocations while dropping; %llu allocations (%llu MiB) placed in host memory\n", report.heap, static_cast<unsigned long long>(report.budget >> 20u), static_cast<unsigned long long>(report.usage >> 20u), static_cast<unsigned long long>(report.target >> 20u), static_cast<unsigned long long>(vramDropped), vramDroppedBytes / 1048576.0, demandFloor() / 1048576.0, static_cast<unsigned long long>(vramChurn), static_cast<unsigned long long>(HostPlacements().count.load()), static_cast<unsigned long long>(HostPlacements().bytes.load() >> 20u));
}
}
}
auto& tier = tierFor(capacity, properties);
if (&tier == &deviceTier) noteDemand(capacity);
const auto largest = &tier == &deviceTier && !exactSizes() && bytes <= std::numeric_limits<std::size_t>::max() / 2 ? std::max(capacity, bytes * 2) : capacity;
auto found = tier.free.end();
for (auto size = capacity; size <= largest && found == tier.free.end(); size = NextCapacity(size)) found = tier.free.find({size, usage, properties});
if (found == tier.free.end() || found->second.empty()) {
++tier.misses;
if (&tier == &deviceTier && vramDropping) ++vramChurn;
return std::nullopt;
}
auto result = found->second.back().allocation;
Expand Down Expand Up @@ -498,6 +517,7 @@ VkDeviceSize BufferPool::ReclaimIdleDevice(VkDeviceSize bytes, std::chrono::stea
--deviceTier.slots;
++deviceTier.evictions;
}
vram.Released(selected);
}
VkDeviceSize released = 0;
for (const auto& allocation : evicted) released += destroy(allocation);
Expand Down Expand Up @@ -533,6 +553,11 @@ VkDeviceSize BufferPool::trim() {
imageBytes = 0;
imageSlots = 0;
imageOrder.clear();
VkDeviceSize retiredBytes = 0;
for (const auto& [key, slots] : retiredDevice.free) {
for (const auto& slot : slots) retiredBytes += slot.allocation.slab ? 0 : slot.allocation.allocationBytes;
}
vram.Released(retiredBytes);
}
VkDeviceSize bytes = 0;
for (const auto* tier : {&retiredSmall, &retiredLarge, &retiredDevice}) {
Expand Down Expand Up @@ -566,20 +591,65 @@ void BufferPool::Put(const BufferAllocation& allocation) noexcept {
try {
std::lock_guard lock(mutex);
auto& tier = tierFor(allocation.bytes, allocation.properties);
if (allocation.allocationBytes > tier.budget) {
const bool device = &tier == &deviceTier;
VkDeviceSize excess = 0;
if (device && vram.Enabled()) {
heapOverBudget();
excess = vram.Excess();
}
while (excess != 0 && imageSlots != 0 && evictOldestImage(evicted)) {
const auto bytes = evicted.back().allocationBytes;
excess -= std::min(excess, bytes);
++vramDropped;
vramDroppedBytes += bytes;
}
const auto floor = device ? std::min(demandFloor(), vram.Report().heapBytes / 16u) : 0;
if (excess != 0 && tier.retainedBytes + allocation.allocationBytes <= floor) excess = 0;
if (device) vramDropping = excess != 0;
if (excess != 0) {
const auto images = evicted.size();
auto dropped = allocation.allocationBytes;
while (tier.slots != 0 && dropped < excess && tier.retainedBytes > floor) {
evictOldest(tier, evicted);
dropped += evicted.back().allocationBytes;
}
evicted.push_back(allocation);
vramDropped += evicted.size() - images;
vramDroppedBytes += dropped;
} else if (allocation.allocationBytes > tier.budget) {
evicted.push_back(allocation);
} else {
while (tier.slots != 0 && (tier.retainedBytes + allocation.allocationBytes > tier.budget || tier.slots >= maxSlots)) evictOldest(tier, evicted);
tier.free[{allocation.bytes, allocation.usage, allocation.properties}].push_back({allocation, ++clock, {}});
++tier.slots;
tier.retainedBytes += allocation.allocationBytes;
}
if (device) vram.Released(releasedBytes(evicted));
} catch (...) {
destroy(allocation);
}
for (const auto& gone : evicted) destroy(gone);
}

void BufferPool::noteDemand(VkDeviceSize bytes) {
const auto now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
const auto slot = now / (DemandWindow.count() / static_cast<std::int64_t>(demand.size()));
if (slot != demandSlot) {
if (demandSlot < 0 || slot - demandSlot >= static_cast<std::int64_t>(demand.size())) demand.fill(0);
else for (auto next = demandSlot + 1; next <= slot; ++next) demand[static_cast<std::size_t>(next) % demand.size()] = 0;
demandSlot = slot;
}
demand[static_cast<std::size_t>(slot) % demand.size()] += bytes;
}

VkDeviceSize BufferPool::demandFloor() const {
const auto now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
const auto oldest = now / (DemandWindow.count() / static_cast<std::int64_t>(demand.size())) - static_cast<std::int64_t>(demand.size()) + 1;
VkDeviceSize total = 0;
for (auto slot = std::max<std::int64_t>({oldest, demandSlot - static_cast<std::int64_t>(demand.size()) + 1, 0}); slot <= demandSlot; ++slot) total += demand[static_cast<std::size_t>(slot) % demand.size()];
return total;
}

std::shared_ptr<BufferPool> GetBufferPool(const Context& context) {
if (!context.bufferPool) context.bufferPool = std::make_shared<BufferPool>(context);
return context.bufferPool;
Expand Down
74 changes: 74 additions & 0 deletions core/libs/prx/libSceAgcDriver/Graphics/src/VramBudget.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#include "prx/libSceAgcDriver/Graphics/include/VramBudget.hpp"
#include <algorithm>
#include <cstdio>
#include <cstdlib>

namespace AgcDriver::Graphics {

namespace {

constexpr VkDeviceSize MiB = VkDeviceSize{1} << 20u;

VkDeviceSize mibSetting(const char* name) {
const char* value = std::getenv(name);
return value != nullptr ? static_cast<VkDeviceSize>(std::strtoull(value, nullptr, 10)) * MiB : 0;
}

bool disabled() {
static const bool off = std::getenv("APS5_NO_VRAM_BUDGET") != nullptr;
return off;
}

}

VramBudget::VramBudget(const Context& context) {
if (disabled() || context.integratedGpu || context.memoryProperties2 == nullptr || context.physical == VK_NULL_HANDLE) return;
for (std::uint32_t index = 0; index < context.memory.memoryHeapCount && index < VK_MAX_MEMORY_HEAPS; ++index) {
const auto& candidate = context.memory.memoryHeaps[index];
if ((candidate.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0 && (!heap || candidate.size > heapBytes)) {
heap = index;
heapBytes = candidate.size;
}
}
if (!heap || heapBytes == 0) {
heap.reset();
return;
}
static const VkDeviceSize forcedLimit = mibSetting("APS5_VRAM_BUDGET_MIB");
limit = forcedLimit != 0 ? std::min(forcedLimit, heapBytes) : heapBytes;
}

VkDeviceSize VramBudget::TargetFor(VkDeviceSize size, VkDeviceSize available) {
return std::max<VkDeviceSize>(available, std::min<VkDeviceSize>(size / 4u, 1024 * MiB));
}

VkDeviceSize VramBudget::target() const {
return TargetFor(heapBytes, budget != 0 ? std::min(budget, limit) : limit);
}

void VramBudget::Read(const VkPhysicalDeviceMemoryBudgetPropertiesEXT& reported) {
if (!heap) return;
released = 0;
budget = reported.heapBudget[*heap];
usage = reported.heapUsage[*heap];
if (announced) return;
announced = true;
std::fprintf(stderr, "[vram] device-local heap %u of %llu MiB: VK_EXT_memory_budget budget %llu MiB, usage %llu MiB; over %llu MiB the device pool keeps only what was taken from it in the last second\n", *heap, static_cast<unsigned long long>(heapBytes / MiB), static_cast<unsigned long long>(budget / MiB), static_cast<unsigned long long>(usage / MiB), static_cast<unsigned long long>(target() / MiB));
}

VkDeviceSize VramBudget::Excess() const {
if (!heap) return 0;
const auto used = usage - std::min(usage, released);
const auto bound = target();
return used > bound ? used - bound : 0;
}

void VramBudget::Released(VkDeviceSize bytes) {
if (heap) released += bytes;
}

VramReport VramBudget::Report() const {
return {heap.value_or(0), heapBytes, budget, usage, target()};
}

}
2 changes: 1 addition & 1 deletion core/libs/prx/libSceAgcDriver/PostCompile.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ add_custom_command(

foreach(agcTarget IN ITEMS libSceAgcDriver agc_driver_visual_test)
if(TARGET ${agcTarget})
target_sources(${agcTarget} PRIVATE Graphics/src/BufferPool.cpp)
target_sources(${agcTarget} PRIVATE Graphics/src/BufferPool.cpp Graphics/src/VramBudget.cpp)
endif()
endforeach()

Expand Down
Loading
Loading