perf(agc): keep released host-type image memory in its own buffer pool tier (#23445)

* perf(agc): keep released host-type image memory in its own buffer pool tier
* fix(agc): keep only host-heap image memory in the host image pool
This commit is contained in:
JJenkx authored and GitHub committed 2026-12-04 13:13:48 +13:00
1 parent bed00d2f63
commit 4bb2f15eb2
5 files changed
+171 -8

No files matched your search

@@ -165,6 +165,8 @@ private:
void evictImageSlot(std::list<Slot*>::iterator order, std::vector<BufferAllocation>& evicted);
bool evictOldestImage(std::vector<BufferAllocation>& evicted);
bool imagePooled(VkDeviceSize bytes, std::uint32_t memoryType) const;
bool hostImagePooled(VkDeviceSize bytes, std::uint32_t memoryType) const;
static VkDeviceSize HostImageBudget();
bool heapOverBudget(std::uint32_t memoryType);
// The retained-slot bound of each tier (APS5_BUFFER_POOL_SLOTS, default `defaultSlots`), read once.
static std::size_t MaxSlots();
@@ -185,6 +187,8 @@ private:
Tier largeTier;
Tier deviceTier;
Tier smallDeviceTier;
Tier hostImageTier;
std::list<Slot*> hostImageOrder;
std::chrono::steady_clock::time_point heapRead{};
std::uint32_t heapOver = 0;
VkDeviceSize imageBudget = 0;
@@ -58,10 +58,11 @@ BufferPool::BufferPool(const Context& context) : maxSlots(std::max<std::size_t>(
physical = context.physical;
memoryProperties2 = context.memoryProperties2;
imageBudget = ImageBudget(deviceTier.budget);
hostImageTier.budget = HostImageBudget();
}
BufferPool::~BufferPool() {
for (auto* tier : {&smallTier, &largeTier, &deviceTier, &smallDeviceTier}) {
for (auto* tier : {&smallTier, &largeTier, &deviceTier, &smallDeviceTier, &hostImageTier}) {
for (const auto& [key, slots] : tier->free) {
for (const auto& slot : slots) destroy(slot.allocation, true);
}
@@ -149,6 +150,18 @@ VkDeviceSize BufferPool::ImageBudget(VkDeviceSize deviceBudget) {
return deviceBudget / 4u;
}
VkDeviceSize BufferPool::HostImageBudget() {
static const VkDeviceSize value = [] {
const char* text = std::getenv("APS5_HOST_IMAGE_POOL_MIB");
return (text != nullptr ? static_cast<VkDeviceSize>(std::strtoull(text, nullptr, 10)) : VkDeviceSize{1024}) << 20u;
}();
return value;
}
bool BufferPool::hostImagePooled(VkDeviceSize bytes, std::uint32_t memoryType) const {
return hostImageTier.budget != 0 && bytes != 0 && bytes <= hostImageTier.budget && memoryType < memoryProperties.memoryTypeCount && (memoryProperties.memoryTypes[memoryType].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == 0 && (memoryProperties.memoryHeaps[memoryProperties.memoryTypes[memoryType].heapIndex].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) == 0;
}
bool BufferPool::imagePooled(VkDeviceSize bytes, std::uint32_t memoryType) const {
return imageBudget != 0 && bytes != 0 && bytes <= imageBudget && bytes <= deviceTier.budget && memoryType < memoryProperties.memoryTypeCount && DeviceTiered(memoryProperties.memoryTypes[memoryType].propertyFlags);
}
@@ -192,6 +205,23 @@ VkDeviceMemory BufferPool::TakeImageMemory(const VkMemoryAllocateInfo& allocatio
return memory;
}
++imageMisses;
} else if (hostImagePooled(allocation.allocationSize, type)) {
std::lock_guard lock(mutex);
const auto found = hostImageTier.free.find({static_cast<std::size_t>(allocation.allocationSize), 0, memoryProperties.memoryTypes[type].propertyFlags, type});
if (found != hostImageTier.free.end() && !found->second.empty()) {
auto& slots = found->second;
const auto memory = slots.back().allocation.memory;
hostImageOrder.erase(slots.back().order);
slots.pop_back();
if (slots.empty()) hostImageTier.free.erase(found);
--hostImageTier.slots;
hostImageTier.retainedBytes -= allocation.allocationSize;
++hostImageTier.hits;
MemoryAccounting::Use(device, memory, operation);
if (allocatedType != nullptr) *allocatedType = type;
return memory;
}
++hostImageTier.misses;
}
return AllocateMemory(allocation, operation, hostType, allocatedType, newImage);
}
@@ -200,7 +230,44 @@ void BufferPool::PutImageMemory(VkDeviceMemory memory, VkDeviceSize bytes, std::
if (memory == VK_NULL_HANDLE) return;
imageMemoryReleasedBytes += bytes;
if (!imagePooled(bytes, memoryType)) {
MemoryAccounting::Free(freeMemory, device, memory);
if (!hostImagePooled(bytes, memoryType)) {
MemoryAccounting::Free(freeMemory, device, memory);
return;
}
BufferAllocation retained{VK_NULL_HANDLE, memory, nullptr, 0, bytes, static_cast<std::size_t>(bytes), 0, memoryProperties.memoryTypes[memoryType].propertyFlags};
retained.memoryType = memoryType;
std::vector<BufferAllocation> evicted;
try {
std::lock_guard lock(mutex);
while (!hostImageOrder.empty() && hostImageTier.retainedBytes + bytes > hostImageTier.budget) {
const Slot* oldest = hostImageOrder.front();
const SlotKey key{oldest->allocation.bytes, 0, oldest->allocation.properties, oldest->allocation.memoryType};
const auto found = hostImageTier.free.find(key);
evicted.push_back(oldest->allocation);
hostImageOrder.pop_front();
hostImageTier.retainedBytes -= oldest->allocation.allocationBytes;
found->second.pop_front();
if (found->second.empty()) hostImageTier.free.erase(found);
--hostImageTier.slots;
++hostImageTier.evictions;
}
const SlotKey key{retained.bytes, 0, retained.properties, memoryType};
auto& slots = hostImageTier.free[key];
slots.push_back({retained, ++clock, {}});
try {
slots.back().order = hostImageOrder.insert(hostImageOrder.end(), &slots.back());
} catch (...) {
slots.pop_back();
if (slots.empty()) hostImageTier.free.erase(key);
throw;
}
++hostImageTier.slots;
hostImageTier.retainedBytes += bytes;
MemoryAccounting::Retain(device, memory, bytes);
} catch (...) {
destroy(retained);
}
for (const auto& gone : evicted) destroy(gone, true);
return;
}
BufferAllocation allocation{VK_NULL_HANDLE, memory, nullptr, 0, bytes, static_cast<std::size_t>(bytes), 0, memoryProperties.memoryTypes[memoryType].propertyFlags};
@@ -568,9 +635,10 @@ VkDeviceSize BufferPool::trim() {
Tier retiredLarge;
Tier retiredDevice;
Tier retiredSmallDevice;
Tier retiredHostImage;
{
std::lock_guard lock(mutex);
for (const auto& [tier, retired] : {std::pair{&smallTier, &retiredSmall}, std::pair{&largeTier, &retiredLarge}, std::pair{&deviceTier, &retiredDevice}, std::pair{&smallDeviceTier, &retiredSmallDevice}}) {
for (const auto& [tier, retired] : {std::pair{&smallTier, &retiredSmall}, std::pair{&largeTier, &retiredLarge}, std::pair{&deviceTier, &retiredDevice}, std::pair{&smallDeviceTier, &retiredSmallDevice}, std::pair{&hostImageTier, &retiredHostImage}}) {
tier->free.swap(retired->free);
tier->evictions += tier->slots;
tier->retainedBytes = 0;
@@ -580,9 +648,10 @@ VkDeviceSize BufferPool::trim() {
imageBytes = 0;
imageSlots = 0;
imageOrder.clear();
hostImageOrder.clear();
}
VkDeviceSize bytes = 0;
for (const auto* tier : {&retiredSmall, &retiredLarge, &retiredDevice, &retiredSmallDevice}) {
for (const auto* tier : {&retiredSmall, &retiredLarge, &retiredDevice, &retiredSmallDevice, &retiredHostImage}) {
for (const auto& [key, slots] : tier->free) {
for (const auto& slot : slots) bytes += destroy(slot.allocation, true);
}
@@ -427,6 +427,82 @@ void AttachmentReclaim() {
Expect(mock.liveBytes == 0, "an attachment allocation leaked memory");
}
void HostImageReuse() {
mock = MockDevice{};
{
auto context = budgetContext();
reportedBudget = 100 * MiB;
reportedUsage = 200 * MiB;
VkMemoryAllocateInfo host{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
host.allocationSize = 8 * MiB;
host.memoryTypeIndex = 1;
const auto first = AllocateImageMemory(context, host, 3, "vkAllocateMemory storage texture");
ReleaseImageMemory(context, first, host.allocationSize, 1);
Expect(mock.memoryBytes.contains(first), "released host-type image memory was freed instead of kept for reuse");
VkMemoryAllocateInfo device = host;
device.memoryTypeIndex = 0;
const auto deviceMemory = AllocateImageMemory(context, device, 3, "vkAllocateMemory storage texture");
ReleaseImageMemory(context, deviceMemory, device.allocationSize, 0);
Expect(mock.memoryBytes.contains(first), "a release while the device-local heap was over its budget flushed the host-type image memory");
const auto attempts = mock.attempts;
const auto again = AllocateImageMemory(context, host, 3, "vkAllocateMemory storage texture");
Expect(again == first && mock.attempts == attempts, "host-type image memory of the same size and type was allocated again instead of reused");
host.allocationSize = 4 * MiB;
const auto other = AllocateImageMemory(context, host, 3, "vkAllocateMemory storage texture");
Expect(other != first && mock.memoryBytes.at(other) == 4 * MiB, "host-type image memory of another size was handed out for a 4 MiB request");
ReleaseImageMemory(context, other, 4 * MiB, 1);
ReleaseImageMemory(context, again, 8 * MiB, 1);
reportedBudget = 0;
reportedUsage = 0;
}
Expect(mock.liveBytes == 0, "host-type image memory the pool kept leaked when the pool was destroyed");
}
void HostImageBudget() {
mock = MockDevice{};
{
auto context = mockContext();
VkMemoryAllocateInfo host{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
host.memoryTypeIndex = 1;
host.allocationSize = 12 * MiB;
const auto older = AllocateImageMemory(context, host, 3, "vkAllocateMemory storage texture");
host.allocationSize = 8 * MiB;
const auto newer = AllocateImageMemory(context, host, 3, "vkAllocateMemory storage texture");
ReleaseImageMemory(context, older, 12 * MiB, 1);
ReleaseImageMemory(context, newer, 8 * MiB, 1);
Expect(!mock.memoryBytes.contains(older) && mock.memoryBytes.contains(newer), "the host image pool kept more than its 16 MiB budget or evicted the newer allocation");
host.allocationSize = 20 * MiB;
const auto large = AllocateImageMemory(context, host, 3, "vkAllocateMemory storage texture");
ReleaseImageMemory(context, large, 20 * MiB, 1);
Expect(!mock.memoryBytes.contains(large), "host-type image memory larger than the pool's budget was kept");
}
Expect(mock.liveBytes == 0, "the host image pool leaked memory");
}
void HostImageWithoutStaging() {
mock = MockDevice{};
{
auto context = budgetContext();
context.memory.memoryTypeCount = 3;
context.memory.memoryTypes[2] = {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | HostVisible, 0};
VkMemoryAllocateInfo info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
info.allocationSize = 8 * MiB;
info.memoryTypeIndex = 0;
const auto device = AllocateImageMemory(context, info, 7, "vkAllocateMemory storage texture");
ReleaseImageMemory(context, device, info.allocationSize, 0);
Expect(!mock.memoryBytes.contains(device), "released device-local image memory was kept by the host image pool with the staging pool off");
info.memoryTypeIndex = 2;
const auto visible = AllocateImageMemory(context, info, 7, "vkAllocateMemory storage texture");
ReleaseImageMemory(context, visible, info.allocationSize, 2);
Expect(!mock.memoryBytes.contains(visible), "released host-visible device-local image memory was kept by the host image pool");
info.memoryTypeIndex = 1;
const auto host = AllocateImageMemory(context, info, 7, "vkAllocateMemory storage texture");
ReleaseImageMemory(context, host, info.allocationSize, 1);
Expect(mock.memoryBytes.contains(host), "released host-type image memory was freed with the staging pool off");
}
Expect(mock.liveBytes == 0, "the host image pool leaked memory with the staging pool off");
}
void SizeClassesAndDirections() {
mock = MockDevice{};
auto context = mockContext();
@@ -1338,16 +1414,16 @@ void ImageMemoryReuse() {
const auto placed = AllocateImageMemory(context, host, 2u, "test image", &type);
Expect(type == 1 && mock.allocations == 3, "a host-visible image allocation is made");
ReleaseImageMemory(context, placed, 4 * MiB, 1);
Expect(mock.frees == 1 && context.bufferPool->RetainedImages() == 2, "a host-visible image allocation is freed when released");
Expect(mock.frees == 0 && context.bufferPool->RetainedImages() == 2 && mock.memoryBytes.contains(placed), "a host-visible image allocation is kept in its own tier when released");
const auto unsized = AllocateImageMemory(context, smaller, 1u, "test image", &type);
Expect(unsized == other && mock.allocations == 3 && context.bufferPool->RetainedImages() == 1, "an image of a retained size takes that allocation");
ReleaseImageMemory(context, unsized, 0, 0);
Expect(mock.frees == 2 && context.bufferPool->RetainedImages() == 1, "an allocation of unknown size is freed");
Expect(mock.frees == 1 && context.bufferPool->RetainedImages() == 1, "an allocation of unknown size is freed");
std::vector<VkDeviceMemory> many;
for (int i = 0; i < 33; ++i) many.push_back(AllocateImageMemory(context, allocation, 1u, "test image", &type));
Expect(many.front() == again && mock.allocations == 35, "a burst takes the retained allocation first and allocates the rest");
for (const auto memory : many) ReleaseImageMemory(context, memory, 4 * MiB, 0);
Expect(context.bufferPool->RetainedImages() == 32 && mock.frees == 3 && !mock.memoryBytes.contains(many.front()) && mock.memoryBytes.contains(many.back()), "retained image memory is evicted least recently used under its budget");
Expect(context.bufferPool->RetainedImages() == 32 && mock.frees == 2 && !mock.memoryBytes.contains(many.front()) && mock.memoryBytes.contains(many.back()), "retained image memory is evicted least recently used under its budget");
mock.results.push_back(VK_ERROR_OUT_OF_DEVICE_MEMORY);
auto third = allocation;
third.allocationSize = 3 * MiB;
@@ -1429,7 +1505,7 @@ void MemoryAccountingChecks() {
}
Expect(failed && MemoryAccounting::Read(context.device).allocations.size() == count, "a failed Vulkan allocation changed the live allocation count");
ReleaseImageMemory(context, host, 4 * MiB, 1);
Expect(MemoryAccounting::Read(context.device).allocations.size() == 1, "host fallback memory stayed counted after release");
Expect(MemoryAccounting::Read(context.device).allocations.size() == 2 && find(host).retained == 4 * MiB, "released host fallback memory kept for reuse was not counted as retained");
ReleaseImageMemory(context, reused, 4 * MiB, 0);
context.bufferPool.reset();
Expect(MemoryAccounting::Read(context.device).allocations.empty() && mock.liveBytes == 0, "image pool destruction left accounted memory");
@@ -1668,6 +1744,14 @@ int main(int argc, char** argv) {
MemoryAccountingBudgetSnapshot();
return failures == 0 ? 0 : 1;
}
if (argc == 2 && std::string_view(argv[1]) == "--host-image-budget") {
HostImageBudget();
return failures == 0 ? 0 : 1;
}
if (argc == 2 && std::string_view(argv[1]) == "--host-image-no-staging") {
HostImageWithoutStaging();
return failures == 0 ? 0 : 1;
}
if (argc == 2 && std::string_view(argv[1]) == "--small-device-retention") {
SmallDeviceRetention();
if (std::getenv("APS5_STAGING_POOL_MIB") == nullptr) {
@@ -1689,6 +1773,7 @@ int main(int argc, char** argv) {
SizeClassesAndDirections();
LargerClass();
ExactSizeReuse();
HostImageReuse();
TableFill();
TableLookups();
KeptUntilFence();
@@ -24,6 +24,10 @@ if(BUILD_TESTING)
add_test(NAME agc_buffer_pool_small_device_no_staging COMMAND agc_buffer_pool_tests --small-device-retention)
set_tests_properties(agc_buffer_pool_small_device_no_staging PROPERTIES ENVIRONMENT
"APS5_STAGING_POOL_MIB=0")
add_test(NAME agc_buffer_pool_host_image_budget COMMAND agc_buffer_pool_tests --host-image-budget)
set_tests_properties(agc_buffer_pool_host_image_budget PROPERTIES ENVIRONMENT "APS5_HOST_IMAGE_POOL_MIB=16")
add_test(NAME agc_buffer_pool_host_image_no_staging COMMAND agc_buffer_pool_tests --host-image-no-staging)
set_tests_properties(agc_buffer_pool_host_image_no_staging PROPERTIES ENVIRONMENT "APS5_STAGING_POOL_MIB=0")
add_test(NAME agc_memory_accounting_budget_snapshot COMMAND agc_buffer_pool_tests --memory-accounting-budget-snapshot)
set_tests_properties(agc_memory_accounting_budget_snapshot PROPERTIES ENVIRONMENT "APS5_TRACE_MEMORY_BUDGET=1"
PASS_REGULAR_EXPRESSION "storage heap=2 sampled_live=1073741824 storage_cached=2147483648 reserved=8321499136 available=2415919104 cap=5368709120 selected=2415919104"
+1
View File
@@ -267,6 +267,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti
| `APS5_SPARSE_FIXTURE_LAYOUT` | path | `core/libs/prx/libSceAgcDriver/tests/execution/UploadCacheReadOnlyFlush.cpp` | | file of page-aligned offset and length pairs used by the optional sparse Vulkan replay |
| `APS5_UPLOAD_CACHE_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp` | 512 | budget in MiB for the read-only guest buffer uploads reused across builds; `0` disables the cache |
| `APS5_IGNORE_DEPTH_TEST` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp` | | renders depth- and stencil-tested draws without a depth target as if the tests always passed |
| `APS5_HOST_IMAGE_POOL_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp` | `1024` | size in MiB of the released image memory in a host memory type (placed there because the device-local heap was over its budget) that the buffer pool keeps for reuse by memory type and exact size, least recently released first out; a device-local heap over its budget does not flush it; `0` frees such memory at once |
| `APS5_IMAGE_POOL_MIB` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/BufferPool.cpp` | | size in MiB of the released image memory the buffer pool keeps for reuse by memory type and size while the device-local heap is under its reported budget, including at most one empty image slab; a quarter of the device tier's budget by default; `0` frees released image memory at once |
| `APS5_INDEX_IN_PLACE_BEHIND_WRITER` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp` | | binds the index range of a draw without mesh stage or primitive restart in place from its host import behind a pending GPU writer, with a barrier before the draw, instead of waiting for the writer and copying the range; the draw then reads each vertex attribute from its whole buffer descriptor, as an indirect draw does, because its highest index is not known on the CPU; APS5_AB can toggle it; with APS5_PROFILE_DRAW it prints one `[index-behind-writer]` line per 10 s summed over every thread, counting each outcome of an attempt (taken, no writer, index limit, mesh stage, primitive restart, vertex offset, unit shadow, pending storage, label or store, copied writer, no import, refused, off) |
| `APS5_INDIRECT_VERTEX_MIB` | integer | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/IndirectDraw.cpp` | 64 | cap in MiB on a vertex attribute extent, above which a GPU-side indirect draw resolves on the CPU |