Merge pull request #2401 from aslan2142/memory-breakdown-line

mem probe: a breakdown line of the runtime's Vulkan memory by consumer (RT-MEMORY-BREAKDOWN-AND-SPARSE-ARENA)
This commit is contained in:
Aslan2142
2026-11-26 20:43:42 +01:00
committed by GitHub
7 changed files with 376 additions and 7 deletions

View File

@ -4689,6 +4689,12 @@ if(TARGET Vulkan::Headers)
target_compile_options(arena_blocks_test PRIVATE /W4 /permissive- /utf-8)
endif()
add_test(NAME arena_blocks COMMAND arena_blocks_test)
# The mem probe's breakdown line: the tally by consumer, the owner scopes and the text (src/memory_breakdown.h).
add_executable(memory_breakdown_test test/memory_breakdown_test.cpp)
if(WIN32 AND MSVC)
target_compile_options(memory_breakdown_test PRIVATE /W4 /permissive- /utf-8)
endif()
add_test(NAME memory_breakdown COMMAND memory_breakdown_test)
# The address guard's page table (src/address_guard.h; docs/d3d12_vulkan.md, "Address guard").
add_executable(address_guard_test test/address_guard_test.cpp)
if(WIN32 AND MSVC)

View File

@ -358,6 +358,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
| `LEONIDA_INPUT_TRACE` | unset | `1` (diagnostic, the GameInput shim built without SDL3) logs the title's reading calls on the scripted pad: the first 128, then each one with a button down and every 1000th. Details in [docs/gameinput.md](../docs/gameinput.md#scripted-input-without-sdl3). |
| `LEONIDA_LOG_ALLOCINFO` | unset | *Diagnostic.* `1` logs every device slot 25 call (`GetResourceAllocationInfo`) with its thread, description and sizes (`shims/d3d12_xs_device.cpp`). |
| `LEONIDA_LOG_EXE_PIPELINES` | unset | *Diagnostic.* When set, one line per distinct graphics pipeline that uses a program translated from the executable's inline containers. |
| `LEONIDA_MEM_PROBE` | unset | *Diagnostic.* `<seconds>`: every that many seconds the memory probe (`src/mem_probe.h`) logs `[rt] mem-probe t=` (live pipelines, shader modules and `VkDeviceMemory` per memory type), `[rt] mem-probe breakdown t=` (the same allocated bytes by consumer: the arena with its reserved, bound and in-use MiB, geometry copies, title windows and shadows, upload heaps, staging, texture blocks, sampled textures, render targets and depth, and `other`, which add up to the allocated total; `src/memory_breakdown.h`) and `[rt] mem-probe smaps` (the process's resident memory by kind). |
| `LEONIDA_MEM_PROBE_CACHE` | unset | *Diagnostic.* `1` adds the pipeline cache's size to the memory probe's report; the driver serializes the whole cache to answer. |
| `LEONIDA_TEXTURE_PROBE` | unset | *Diagnostic.* Logs a `[rt] texture-probe` line for every shader resource view of a texture in the title's memory. |
| `LEONIDA_LOCAL_DIAGNOSTICS` | unset | *Diagnostic.* `1` turns on the boot diagnostics that write to stderr from the draw, clear, present and descriptor paths (the lines tagged `present-probe`, `fsdraw`, `heap-probe`, `desc-probe` and `PresentX diag`; `src/local_diagnostics.h`). They follow a frame of the title from its draws to the window and cost a lock and a line per draw, so they are off by default. The full-screen draw targets that `LEONIDA_CAPTURE_SOURCE` reads back are only collected with it. |

View File

@ -1,6 +1,7 @@
#pragma once
#include "d3d12_title_buffer_windows.h"
#include "../src/memory_breakdown.h"
#include "../src/title_geometry_watch.h"
#include <atomic>
#include <chrono>
@ -318,6 +319,7 @@ public:
VkDeviceSize va{};
bool at_cap = false;
const bool over_bytes = bytes_ >= limit || bytes > limit - bytes_;
leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::geometry);
if (over_bytes || !pool_.allocate(device, bytes, va, mapped, true, limit, &at_cap)) {
if (at_cap || over_bytes) {
refused_[key] = gen;

View File

@ -3087,7 +3087,8 @@ struct DeviceState {
std::uint8_t* mapped{};
if (arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) {
mapped = arena.mapped + offset;
} else if (stream_windows() && external_windows.allocate(*this, size, offset, mapped)) {
} else if (leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows);
stream_windows() && external_windows.allocate(*this, size, offset, mapped)) {
external_window_made.store(true, std::memory_order_release);
} else {
++title_window_refusals;
@ -8398,6 +8399,8 @@ public:
if (heap_.Type == D3D12_HEAP_TYPE_READBACK) host_preferred = VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD && device_.upload_in_vram)
host_preferred = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
leonida::memory_breakdown::Owner owner(host ? leonida::memory_breakdown::Consumer::upload
: leonida::memory_breakdown::current_owner());
memory_ = host ? device_.allocate(requirements,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
host_preferred, &memory_flags_, addressable || need_bda)
@ -8716,6 +8719,7 @@ public:
vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements);
// As an upload buffer (D3D-96): the CPU writes it at every submission and the GPU reads it, so VRAM through
// Resizable BAR where there is one, system memory otherwise.
leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows);
memory_ = device_.allocate(requirements,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
device_.upload_in_vram ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &memory_flags_,
@ -9251,6 +9255,7 @@ private:
vk.vkBindImageMemory, vk.vkDestroyImage, vk.vkFreeMemory, [&](VkDeviceSize size, std::uint32_t& type) {
auto page = pool_requirements;
page.size = size;
leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::image_blocks);
return device_.allocate(page, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, false, &type);
});
if (pooled_image_) memory_flags_ = device_.memory.memoryTypes[pooled_image_->page->type].propertyFlags;
@ -9853,8 +9858,12 @@ private:
};
VkMemoryRequirements requirements{};
vk.vkGetBufferMemoryRequirements(dev, staging.buffer, &requirements);
memory = device_.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
write ? 0 : VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
{
leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging);
memory = device_.allocate(requirements,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
write ? 0 : VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
}
if (!memory || vk.vkBindBufferMemory(dev, staging.buffer, memory, 0) != VK_SUCCESS ||
vk.vkMapMemory(dev, memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS)
return release(E_OUTOFMEMORY);
@ -14373,6 +14382,7 @@ public:
block.allocationSize = bytes;
block.memoryTypeIndex = type;
VkDeviceMemory out = VK_NULL_HANDLE;
leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::image_blocks);
return make(device, &block, nullptr, &out) == VK_SUCCESS ? out : VkDeviceMemory(VK_NULL_HANDLE);
},
[device = info.device, free = state_.context->vk.vkFreeMemory](VkDeviceMemory block) {
@ -14476,6 +14486,21 @@ public:
(unsigned long long)shadows, leonida::fsdraw::pipeline_count());
return std::string(text);
};
facts.share = [this] {
leonida::memory_breakdown::DeviceShare share;
DeviceState& d = state_;
if (d.arena.buffer) {
share.arena = true;
std::lock_guard lock(d.arena.mutex);
share.arena_reserved = d.arena.size;
share.arena_bound = d.arena.size; // one allocation behind the whole range
share.arena_in_use = d.arena.in_use;
for (std::size_t i = 0; i < share.arena_use.size(); ++i) share.arena_use[i] = d.arena.use_in_use[i];
}
std::lock_guard lock(d.descriptor_mutex); // the bindless set's lock (ExecuteCommandLists' flush)
if (const auto* bindless = d.bindless.get()) share.bindless_table_bytes = bindless->table_buffer_bytes();
return share;
};
leonida::mem_probe::start(std::move(facts));
}
if (info.conditional_rendering) {
@ -14512,6 +14537,7 @@ public:
state_.context->enable_copy_scratch(
get_device,
[this, index_scratch](const VkMemoryRequirements& requirements) {
leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging);
return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch);
},
scratch_extra, state_.families);
@ -14939,8 +14965,11 @@ public:
"device's %s\n",
static_cast<unsigned long long>(size.bytes >> 20),
static_cast<unsigned long long>(size.requested >> 20), leonida::arena_cap_name(size.capped));
arena.memory = state_.allocate(requirements, leonida::kArenaRequiredMemory, leonida::kArenaPreferredMemory,
nullptr, true, &arena.memory_type);
{
leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::arena);
arena.memory = state_.allocate(requirements, leonida::kArenaRequiredMemory,
leonida::kArenaPreferredMemory, nullptr, true, &arena.memory_type);
}
void* mapped = nullptr;
if (!arena.memory || vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) != VK_SUCCESS ||
vk.vkMapMemory(state_.info.device, arena.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) {

View File

@ -9,12 +9,18 @@
// other PE private memory (runtime + title heaps), PE images, PE sections, memory the Vulkan
// driver mapped for us, /dev/nvidia* mappings, other native (Unix-side) anonymous memory
// (driver heaps, glibc arenas), and files.
// [rt] mem-probe breakdown: the same allocations by consumer (src/memory_breakdown.h): the arena with its reserved,
// bound and in-use bytes, geometry copies, title windows and shadows, upload heaps, staging,
// texture blocks, sampled textures, render targets and depth, and other, which add up to the
// allocated bytes of the t= line.
// The Vulkan counts come from wrapping the runtime's own function table (install()); helpers that load their own
// pointers (depth24, predicate, xdxr, swapchain) are not counted: they create a handful of objects.
#include <windows.h>
#include <vulkan/vulkan.h>
#include "memory_breakdown.h"
#include <algorithm>
#include <atomic>
#include <cctype>
@ -40,6 +46,8 @@ struct Allocation {
bool imported = false;
std::uintptr_t mapped = 0;
std::uint64_t mapped_bytes = 0;
// Who asked for it (an Owner scope at the allocation), or what was bound to it later (bind_image_memory).
memory_breakdown::Consumer consumer = memory_breakdown::Consumer::other;
};
struct State {
@ -52,11 +60,15 @@ struct State {
PFN_vkCreateGraphicsPipelines create_graphics = nullptr;
PFN_vkCreateComputePipelines create_compute = nullptr;
PFN_vkDestroyPipeline destroy_pipeline = nullptr;
PFN_vkCreateImage create_image = nullptr;
PFN_vkDestroyImage destroy_image = nullptr;
PFN_vkBindImageMemory bind_image = nullptr;
std::mutex mutex;
std::unordered_map<VkDeviceMemory, Allocation> allocations;
std::unordered_map<VkShaderModule, std::uint64_t> modules;
std::unordered_map<VkPipeline, std::uint8_t> pipelines; // 0 graphics, 1 compute
std::unordered_map<VkImage, std::uint32_t> image_usage; // VkImageUsageFlags of each live image
std::uint64_t module_bytes = 0, modules_made = 0, module_bytes_made = 0;
std::uint64_t graphics_live = 0, compute_live = 0, graphics_made = 0, compute_made = 0;
std::uint64_t graphics_ns = 0, compute_ns = 0; // time inside vkCreate*Pipelines
@ -94,7 +106,8 @@ inline VKAPI_ATTR VkResult VKAPI_CALL allocate_memory(VkDevice device, const VkM
const VkResult result = s.allocate(device, info, callbacks, out);
if (result == VK_SUCCESS && out && *out) {
std::lock_guard lock(s.mutex);
s.allocations[*out] = {info->memoryTypeIndex, info->allocationSize, imported_memory(info), 0, 0};
s.allocations[*out] = {info->memoryTypeIndex, info->allocationSize, imported_memory(info), 0, 0,
memory_breakdown::current_owner()};
}
return result;
}
@ -132,6 +145,43 @@ inline VKAPI_ATTR void VKAPI_CALL unmap_memory(VkDevice device, VkDeviceMemory m
s.unmap(device, memory);
}
inline VKAPI_ATTR VkResult VKAPI_CALL create_image(VkDevice device, const VkImageCreateInfo* info,
const VkAllocationCallbacks* callbacks, VkImage* out) {
State& s = state();
const VkResult result = s.create_image(device, info, callbacks, out);
if (result == VK_SUCCESS && out && *out) {
std::lock_guard lock(s.mutex);
s.image_usage[*out] = info->usage;
}
return result;
}
inline VKAPI_ATTR void VKAPI_CALL destroy_image(VkDevice device, VkImage image, const VkAllocationCallbacks* callbacks) {
State& s = state();
if (image) {
std::lock_guard lock(s.mutex);
s.image_usage.erase(image);
}
s.destroy_image(device, image, callbacks);
}
// Memory nobody named that an image is bound to is that image's: a render target or depth buffer, or a sampled
// texture. A named block (the texture blocks) keeps its name, whatever is bound into it.
inline VKAPI_ATTR VkResult VKAPI_CALL bind_image_memory(VkDevice device, VkImage image, VkDeviceMemory memory,
VkDeviceSize offset) {
State& s = state();
const VkResult result = s.bind_image(device, image, memory, offset);
if (result == VK_SUCCESS) {
std::lock_guard lock(s.mutex);
const auto a = s.allocations.find(memory);
const auto u = s.image_usage.find(image);
if (a != s.allocations.end() && u != s.image_usage.end() &&
a->second.consumer == memory_breakdown::Consumer::other)
a->second.consumer = memory_breakdown::image_consumer(u->second);
}
return result;
}
inline VKAPI_ATTR VkResult VKAPI_CALL create_shader_module(VkDevice device, const VkShaderModuleCreateInfo* info,
const VkAllocationCallbacks* callbacks,
VkShaderModule* out) {
@ -246,7 +296,8 @@ void install(Functions& vk) {
if (s.installed++) return;
if (!vk.vkAllocateMemory || !vk.vkFreeMemory || !vk.vkMapMemory || !vk.vkUnmapMemory ||
!vk.vkCreateShaderModule || !vk.vkDestroyShaderModule || !vk.vkCreateGraphicsPipelines ||
!vk.vkCreateComputePipelines || !vk.vkDestroyPipeline)
!vk.vkCreateComputePipelines || !vk.vkDestroyPipeline || !vk.vkCreateImage || !vk.vkDestroyImage ||
!vk.vkBindImageMemory)
return;
s.started = GetTickCount64();
s.allocate = vk.vkAllocateMemory, vk.vkAllocateMemory = allocate_memory;
@ -258,6 +309,9 @@ void install(Functions& vk) {
s.create_graphics = vk.vkCreateGraphicsPipelines, vk.vkCreateGraphicsPipelines = create_graphics_pipelines;
s.create_compute = vk.vkCreateComputePipelines, vk.vkCreateComputePipelines = create_compute_pipelines;
s.destroy_pipeline = vk.vkDestroyPipeline, vk.vkDestroyPipeline = destroy_pipeline;
s.create_image = vk.vkCreateImage, vk.vkCreateImage = create_image;
s.destroy_image = vk.vkDestroyImage, vk.vkDestroyImage = destroy_image;
s.bind_image = vk.vkBindImageMemory, vk.vkBindImageMemory = bind_image_memory;
std::fprintf(stderr, "[rt] mem-probe: installed, every %u s\n", interval_seconds());
}
@ -451,6 +505,7 @@ inline std::string read_rollup() {
struct DeviceFacts {
std::function<std::string()> describe; // one text fragment
std::function<Ranges()> title_ranges; // the title's memory
std::function<memory_breakdown::DeviceShare()> share; // the arena and the bindless tables, for the breakdown
VkPhysicalDeviceMemoryProperties memory{};
};
@ -477,6 +532,7 @@ inline void sample(const DeviceFacts& facts) {
std::uint64_t type_count[VK_MAX_MEMORY_TYPES] = {}, type_bytes[VK_MAX_MEMORY_TYPES] = {};
std::uint64_t import_count[VK_MAX_MEMORY_TYPES] = {}, import_bytes[VK_MAX_MEMORY_TYPES] = {};
Ranges vk_mapped;
memory_breakdown::Tally tally;
std::uint64_t modules = 0, module_bytes = 0, modules_made = 0, module_bytes_made = 0;
std::uint64_t graphics = 0, compute = 0, graphics_made = 0, compute_made = 0, graphics_ns = 0, compute_ns = 0;
{
@ -491,6 +547,7 @@ inline void sample(const DeviceFacts& facts) {
type_bytes[i] += a.bytes;
}
if (a.mapped && !a.imported) vk_mapped.push_back({a.mapped, a.mapped + a.mapped_bytes});
tally.add(a.consumer, a.bytes, a.imported);
}
modules = s.modules.size();
module_bytes = s.module_bytes;
@ -527,6 +584,10 @@ inline void sample(const DeviceFacts& facts) {
(unsigned long long)compute_made, double(graphics_ns) / 1e9, double(compute_ns) / 1e9,
(unsigned long long)modules, mib(module_bytes), (unsigned long long)modules_made,
mib(module_bytes_made), memory_text.c_str(), facts.describe ? facts.describe().c_str() : "");
std::fprintf(stderr, "[rt] mem-probe breakdown t=%.0fs: %s\n", t,
memory_breakdown::format(tally, facts.share ? facts.share() : memory_breakdown::DeviceShare{},
module_bytes)
.c_str());
Ranges title = facts.title_ranges ? facts.title_ranges() : Ranges{};
std::sort(title.begin(), title.end());
Usage usage[b_count];

View File

@ -0,0 +1,152 @@
#pragma once
// The mem probe's breakdown line (src/mem_probe.h, LEONIDA_MEM_PROBE=<seconds>): the runtime's own vkAllocateMemory
// bytes split by the consumer that asked for them, so the parts add up to the total the probe's `mem-probe t=` line
// prints per memory type. Diagnostic only: nothing here changes what is allocated or where.
//
// A consumer is named in one of two ways:
// - by the caller: an Owner scope around the call that allocates (the arena, the geometry copies' and title
// windows' 4 MiB blocks, upload heaps, staging, the texture blocks). The probe's vkAllocateMemory wrapper reads
// the scope of the thread it runs on;
// - by what is bound to it: memory nobody named that a dedicated image is bound to is a render target or depth
// buffer when the image is an attachment, else a sampled texture (image_consumer()).
// Memory named neither way is "other", so the parts always sum to the total.
//
// Pure standard library (the usage bits are passed in as plain integers), so the tally and the text are tested
// without a GPU or Windows (memory_breakdown_test).
#include <array>
#include <cstdint>
#include <cstdio>
#include <string>
namespace leonida::memory_breakdown {
enum class Consumer : std::uint8_t {
other, // nobody named it and no image is bound to it
arena, // the GPU address arena's memory (docs/d3d12_vulkan.md section 3.3)
geometry, // geometry copies: GeometryViews' 4 MiB blocks (shims/d3d12_geometry_views.h)
windows, // title windows outside the arena and slot-133 shadow buffers with their own memory
upload, // upload and readback heap buffers with their own memory
staging, // texture staging and copy scratch
image_blocks, // blocks that hold many textures (ImageMemory, TitleImagePool)
sampled, // dedicated memory of a texture that is not an attachment
render_target, // dedicated memory of a colour or depth/stencil attachment
count
};
constexpr std::size_t kConsumers = std::size_t(Consumer::count);
inline const char* consumer_name(Consumer c) {
switch (c) {
case Consumer::other: return "other";
case Consumer::arena: return "arena";
case Consumer::geometry: return "geometry copies";
case Consumer::windows: return "title windows and shadows";
case Consumer::upload: return "upload heaps";
case Consumer::staging: return "staging";
case Consumer::image_blocks: return "texture blocks";
case Consumer::sampled: return "sampled textures";
case Consumer::render_target: return "render targets and depth";
default: return "?";
}
}
// VkImageUsageFlagBits values, as plain integers so this header needs no Vulkan headers.
constexpr std::uint32_t kColorAttachment = 0x10; // VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT
constexpr std::uint32_t kDepthStencilAttachment = 0x20; // VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT
// The consumer of memory an image of `usage` is bound to, when nobody named the memory.
inline Consumer image_consumer(std::uint32_t usage) {
return usage & (kColorAttachment | kDepthStencilAttachment) ? Consumer::render_target : Consumer::sampled;
}
// The consumer the calling thread allocates for. Set by an Owner scope; Consumer::other outside one.
inline Consumer& current_owner() {
thread_local Consumer owner = Consumer::other;
return owner;
}
// Names the consumer of the allocations this thread makes while the scope lives. Scopes nest: the inner one wins
// and the outer one is back when it ends.
class Owner {
public:
explicit Owner(Consumer consumer) : previous_(current_owner()) { current_owner() = consumer; }
~Owner() { current_owner() = previous_; }
Owner(const Owner&) = delete;
Owner& operator=(const Owner&) = delete;
private:
Consumer previous_;
};
// Live allocations per consumer. Imported memory (host pointers, the title's own pages) is system memory the runtime
// did not allocate, so it is kept apart, as the probe's total keeps it apart.
struct Tally {
std::array<std::uint64_t, kConsumers> bytes{}, count{};
std::uint64_t imported_bytes = 0, imported_count = 0;
void add(Consumer consumer, std::uint64_t size, bool imported) {
if (imported) {
imported_bytes += size;
++imported_count;
return;
}
const std::size_t i = std::size_t(consumer) < kConsumers ? std::size_t(consumer) : 0;
bytes[i] += size;
++count[i];
}
std::uint64_t total() const {
std::uint64_t sum = 0;
for (const std::uint64_t b : bytes) sum += b;
return sum;
}
};
// What the device knows about the arena and the tables outside the probe's wrapped allocations.
struct DeviceShare {
bool arena = false;
std::uint64_t arena_reserved = 0; // the arena's size: the address range shaders may name
std::uint64_t arena_bound = 0; // bytes of memory behind it
std::uint64_t arena_in_use = 0; // bytes allocations hold
// arena_in_use by kind, as DeviceState::ArenaUse: buffers, descriptor heaps, shader code, heaps
std::array<std::uint64_t, 4> arena_use{};
std::uint64_t bindless_table_bytes = 0; // allocated by BindlessSet through its own function table
};
inline double mib(std::uint64_t bytes) { return double(bytes) / 1048576.0; }
// The breakdown line's text after "[rt] mem-probe breakdown t=<s>: ". Every consumer is printed, zero or not, so a
// reader can line up two ticks; the figures are whole MiB.
inline std::string format(const Tally& tally, const DeviceShare& device, std::uint64_t module_bytes) {
std::string out;
char item[256];
std::snprintf(item, sizeof item, "allocated %.0f MiB =", mib(tally.total()));
out += item;
bool first = true;
for (std::size_t i = 1; i <= kConsumers; ++i) {
const std::size_t c = i % kConsumers; // "other" last
std::snprintf(item, sizeof item, "%s %s %.0f (%llu)", first ? "" : " +", consumer_name(Consumer(c)),
mib(tally.bytes[c]), (unsigned long long)tally.count[c]);
out += item;
first = false;
if (Consumer(c) == Consumer::arena && device.arena) {
std::snprintf(item, sizeof item,
" [reserved %.0f, bound %.0f, in use %.0f: buffers %.0f, descriptor heaps %.0f, shader code "
"%.0f, heaps %.0f]",
mib(device.arena_reserved), mib(device.arena_bound), mib(device.arena_in_use),
mib(device.arena_use[0]), mib(device.arena_use[1]), mib(device.arena_use[2]),
mib(device.arena_use[3]));
out += item;
}
}
std::snprintf(item, sizeof item,
"; imported %.0f MiB (%llu); not in the total: bindless tables %.0f MiB (own function table), shader "
"modules %.0f MiB SPIR-V, pipelines and swapchain images (the driver's)",
mib(tally.imported_bytes), (unsigned long long)tally.imported_count,
mib(device.bindless_table_bytes), mib(module_bytes));
out += item;
return out;
}
} // namespace leonida::memory_breakdown

View File

@ -0,0 +1,118 @@
// leonida::memory_breakdown (src/memory_breakdown.h): the mem probe's breakdown line. The tally of synthetic
// allocations by consumer adds up to the allocated total, an Owner scope names the allocations made under it and
// nests, an image's usage picks its kind, and the text names every part. No GPU, no device.
#include "../src/memory_breakdown.h"
#include <cstdint>
#include <cstdio>
#include <string>
#include <thread>
#define EXPECT(condition) do { \
if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
} while (0)
namespace {
namespace mb = leonida::memory_breakdown;
constexpr std::uint64_t kMiB = 1 << 20;
bool contains(const std::string& text, const char* part) { return text.find(part) != std::string::npos; }
// The parts add up to the total, imported memory stays out of it, and an unknown consumer counts as other.
int tally() {
mb::Tally t;
t.add(mb::Consumer::arena, 4095 * kMiB, false);
t.add(mb::Consumer::geometry, 4 * kMiB, false);
t.add(mb::Consumer::geometry, 4 * kMiB, false);
t.add(mb::Consumer::sampled, 3 * kMiB, false);
t.add(mb::Consumer::render_target, 8 * kMiB, false);
t.add(mb::Consumer::other, 1 * kMiB, false);
t.add(mb::Consumer::count, 2 * kMiB, false); // out of range: other
t.add(mb::Consumer::windows, 6 * kMiB, true); // imported: not allocated by us
EXPECT(t.total() == (4095 + 8 + 3 + 8 + 1 + 2) * kMiB);
EXPECT(t.bytes[std::size_t(mb::Consumer::geometry)] == 8 * kMiB);
EXPECT(t.count[std::size_t(mb::Consumer::geometry)] == 2);
EXPECT(t.bytes[std::size_t(mb::Consumer::other)] == 3 * kMiB);
EXPECT(t.count[std::size_t(mb::Consumer::other)] == 2);
EXPECT(t.bytes[std::size_t(mb::Consumer::windows)] == 0);
EXPECT(t.imported_bytes == 6 * kMiB && t.imported_count == 1);
std::uint64_t sum = 0;
for (std::size_t i = 0; i < mb::kConsumers; ++i) sum += t.bytes[i];
EXPECT(sum == t.total());
return 0;
}
// An Owner scope names this thread's allocations, nests, restores the outer name, and does not leak to other threads.
int owner_scopes() {
EXPECT(mb::current_owner() == mb::Consumer::other);
{
mb::Owner outer(mb::Consumer::geometry);
EXPECT(mb::current_owner() == mb::Consumer::geometry);
{
mb::Owner inner(mb::Consumer::staging);
EXPECT(mb::current_owner() == mb::Consumer::staging);
mb::Consumer seen = mb::Consumer::count;
std::thread([&] { seen = mb::current_owner(); }).join();
EXPECT(seen == mb::Consumer::other);
}
EXPECT(mb::current_owner() == mb::Consumer::geometry);
}
EXPECT(mb::current_owner() == mb::Consumer::other);
return 0;
}
// Colour and depth/stencil attachments are render targets; anything else bound alone is a sampled texture.
int image_kinds() {
const std::uint32_t sampled = 0x4, transfer_dst = 0x2, storage = 0x8;
EXPECT(mb::image_consumer(sampled | transfer_dst) == mb::Consumer::sampled);
EXPECT(mb::image_consumer(storage) == mb::Consumer::sampled);
EXPECT(mb::image_consumer(sampled | mb::kColorAttachment) == mb::Consumer::render_target);
EXPECT(mb::image_consumer(mb::kDepthStencilAttachment) == mb::Consumer::render_target);
return 0;
}
// The text: the total first, every consumer with its MiB and count, the arena's reserved/bound/in-use bytes, other
// last, and what lies outside the total.
int text() {
mb::Tally t;
t.add(mb::Consumer::arena, 4095 * kMiB, false);
t.add(mb::Consumer::geometry, 3867 * kMiB, false);
t.add(mb::Consumer::render_target, 1180 * kMiB, false);
t.add(mb::Consumer::other, 819 * kMiB, false);
t.add(mb::Consumer::other, 206 * kMiB, true);
mb::DeviceShare share;
share.arena = true;
share.arena_reserved = share.arena_bound = 4095 * kMiB;
share.arena_in_use = 757 * kMiB;
share.arena_use = {500 * kMiB, 171 * kMiB, 80 * kMiB, 6 * kMiB};
share.bindless_table_bytes = 2 * kMiB;
const std::string line = mb::format(t, share, 12 * kMiB);
std::fprintf(stderr, "%s\n", line.c_str());
EXPECT(line.rfind("allocated 9961 MiB = arena 4095 (1) [reserved 4095, bound 4095, in use 757: buffers 500, "
"descriptor heaps 171, shader code 80, heaps 6]",
0) == 0);
EXPECT(contains(line, " + geometry copies 3867 (1)"));
EXPECT(contains(line, " + title windows and shadows 0 (0)"));
EXPECT(contains(line, " + upload heaps 0 (0) + staging 0 (0) + texture blocks 0 (0) + sampled textures 0 (0)"));
EXPECT(contains(line, " + render targets and depth 1180 (1) + other 819 (1);"));
EXPECT(contains(line, "imported 206 MiB (1)"));
EXPECT(contains(line, "bindless tables 2 MiB"));
EXPECT(contains(line, "shader modules 12 MiB SPIR-V"));
// Without an arena the bracket is left out.
const std::string bare = mb::format(t, mb::DeviceShare{}, 0);
EXPECT(!contains(bare, "reserved"));
EXPECT(contains(bare, "arena 4095 (1) + geometry copies"));
return 0;
}
} // namespace
int main() {
if (int r = tally()) return r;
if (int r = owner_scopes()) return r;
if (int r = image_kinds()) return r;
if (int r = text()) return r;
std::fprintf(stderr, "memory_breakdown: ok\n");
return 0;
}