upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorAslan2142 <jan.trencansky@protonmail.com>2026-11-26 20:43:42 +0100
committerGitHub <noreply@github.com>2026-11-26 20:43:42 +0100
commitfac8b4bb903b6988bd616e8874e77fa026858ffb (patch)
treede62c97ea795078ad9e199fdfacb53092d3eff8c /runtime/src
parent2d43417d49fdd8f2d8241f75ea8fd0cdd8811137 (diff)
parentaaff77b831a5167b4b255fe92b7cde4add593b98 (diff)
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)
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/mem_probe.h65
-rw-r--r--runtime/src/memory_breakdown.h152
2 files changed, 215 insertions, 2 deletions
diff --git a/runtime/src/mem_probe.h b/runtime/src/mem_probe.h
index a36d38bfe..f8c573da4 100644
--- a/runtime/src/mem_probe.h
+++ b/runtime/src/mem_probe.h
@@ -9,12 +9,18 @@
9// other PE private memory (runtime + title heaps), PE images, PE sections, memory the Vulkan 9// other PE private memory (runtime + title heaps), PE images, PE sections, memory the Vulkan
10// driver mapped for us, /dev/nvidia* mappings, other native (Unix-side) anonymous memory 10// driver mapped for us, /dev/nvidia* mappings, other native (Unix-side) anonymous memory
11// (driver heaps, glibc arenas), and files. 11// (driver heaps, glibc arenas), and files.
12// [rt] mem-probe breakdown: the same allocations by consumer (src/memory_breakdown.h): the arena with its reserved,
13// bound and in-use bytes, geometry copies, title windows and shadows, upload heaps, staging,
14// texture blocks, sampled textures, render targets and depth, and other, which add up to the
15// allocated bytes of the t= line.
12// The Vulkan counts come from wrapping the runtime's own function table (install()); helpers that load their own 16// The Vulkan counts come from wrapping the runtime's own function table (install()); helpers that load their own
13// pointers (depth24, predicate, xdxr, swapchain) are not counted: they create a handful of objects. 17// pointers (depth24, predicate, xdxr, swapchain) are not counted: they create a handful of objects.
14 18
15#include <windows.h> 19#include <windows.h>
16#include <vulkan/vulkan.h> 20#include <vulkan/vulkan.h>
17 21
22#include "memory_breakdown.h"
23
18#include <algorithm> 24#include <algorithm>
19#include <atomic> 25#include <atomic>
20#include <cctype> 26#include <cctype>
@@ -40,6 +46,8 @@ struct Allocation {
40 bool imported = false; 46 bool imported = false;
41 std::uintptr_t mapped = 0; 47 std::uintptr_t mapped = 0;
42 std::uint64_t mapped_bytes = 0; 48 std::uint64_t mapped_bytes = 0;
49 // Who asked for it (an Owner scope at the allocation), or what was bound to it later (bind_image_memory).
50 memory_breakdown::Consumer consumer = memory_breakdown::Consumer::other;
43}; 51};
44 52
45struct State { 53struct State {
@@ -52,11 +60,15 @@ struct State {
52 PFN_vkCreateGraphicsPipelines create_graphics = nullptr; 60 PFN_vkCreateGraphicsPipelines create_graphics = nullptr;
53 PFN_vkCreateComputePipelines create_compute = nullptr; 61 PFN_vkCreateComputePipelines create_compute = nullptr;
54 PFN_vkDestroyPipeline destroy_pipeline = nullptr; 62 PFN_vkDestroyPipeline destroy_pipeline = nullptr;
63 PFN_vkCreateImage create_image = nullptr;
64 PFN_vkDestroyImage destroy_image = nullptr;
65 PFN_vkBindImageMemory bind_image = nullptr;
55 66
56 std::mutex mutex; 67 std::mutex mutex;
57 std::unordered_map<VkDeviceMemory, Allocation> allocations; 68 std::unordered_map<VkDeviceMemory, Allocation> allocations;
58 std::unordered_map<VkShaderModule, std::uint64_t> modules; 69 std::unordered_map<VkShaderModule, std::uint64_t> modules;
59 std::unordered_map<VkPipeline, std::uint8_t> pipelines; // 0 graphics, 1 compute 70 std::unordered_map<VkPipeline, std::uint8_t> pipelines; // 0 graphics, 1 compute
71 std::unordered_map<VkImage, std::uint32_t> image_usage; // VkImageUsageFlags of each live image
60 std::uint64_t module_bytes = 0, modules_made = 0, module_bytes_made = 0; 72 std::uint64_t module_bytes = 0, modules_made = 0, module_bytes_made = 0;
61 std::uint64_t graphics_live = 0, compute_live = 0, graphics_made = 0, compute_made = 0; 73 std::uint64_t graphics_live = 0, compute_live = 0, graphics_made = 0, compute_made = 0;
62 std::uint64_t graphics_ns = 0, compute_ns = 0; // time inside vkCreate*Pipelines 74 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
94 const VkResult result = s.allocate(device, info, callbacks, out); 106 const VkResult result = s.allocate(device, info, callbacks, out);
95 if (result == VK_SUCCESS && out && *out) { 107 if (result == VK_SUCCESS && out && *out) {
96 std::lock_guard lock(s.mutex); 108 std::lock_guard lock(s.mutex);
97 s.allocations[*out] = {info->memoryTypeIndex, info->allocationSize, imported_memory(info), 0, 0}; 109 s.allocations[*out] = {info->memoryTypeIndex, info->allocationSize, imported_memory(info), 0, 0,
110 memory_breakdown::current_owner()};
98 } 111 }
99 return result; 112 return result;
100} 113}
@@ -132,6 +145,43 @@ inline VKAPI_ATTR void VKAPI_CALL unmap_memory(VkDevice device, VkDeviceMemory m
132 s.unmap(device, memory); 145 s.unmap(device, memory);
133} 146}
134 147
148inline VKAPI_ATTR VkResult VKAPI_CALL create_image(VkDevice device, const VkImageCreateInfo* info,
149 const VkAllocationCallbacks* callbacks, VkImage* out) {
150 State& s = state();
151 const VkResult result = s.create_image(device, info, callbacks, out);
152 if (result == VK_SUCCESS && out && *out) {
153 std::lock_guard lock(s.mutex);
154 s.image_usage[*out] = info->usage;
155 }
156 return result;
157}
158
159inline VKAPI_ATTR void VKAPI_CALL destroy_image(VkDevice device, VkImage image, const VkAllocationCallbacks* callbacks) {
160 State& s = state();
161 if (image) {
162 std::lock_guard lock(s.mutex);
163 s.image_usage.erase(image);
164 }
165 s.destroy_image(device, image, callbacks);
166}
167
168// Memory nobody named that an image is bound to is that image's: a render target or depth buffer, or a sampled
169// texture. A named block (the texture blocks) keeps its name, whatever is bound into it.
170inline VKAPI_ATTR VkResult VKAPI_CALL bind_image_memory(VkDevice device, VkImage image, VkDeviceMemory memory,
171 VkDeviceSize offset) {
172 State& s = state();
173 const VkResult result = s.bind_image(device, image, memory, offset);
174 if (result == VK_SUCCESS) {
175 std::lock_guard lock(s.mutex);
176 const auto a = s.allocations.find(memory);
177 const auto u = s.image_usage.find(image);
178 if (a != s.allocations.end() && u != s.image_usage.end() &&
179 a->second.consumer == memory_breakdown::Consumer::other)
180 a->second.consumer = memory_breakdown::image_consumer(u->second);
181 }
182 return result;
183}
184
135inline VKAPI_ATTR VkResult VKAPI_CALL create_shader_module(VkDevice device, const VkShaderModuleCreateInfo* info, 185inline VKAPI_ATTR VkResult VKAPI_CALL create_shader_module(VkDevice device, const VkShaderModuleCreateInfo* info,
136 const VkAllocationCallbacks* callbacks, 186 const VkAllocationCallbacks* callbacks,
137 VkShaderModule* out) { 187 VkShaderModule* out) {
@@ -246,7 +296,8 @@ void install(Functions& vk) {
246 if (s.installed++) return; 296 if (s.installed++) return;
247 if (!vk.vkAllocateMemory || !vk.vkFreeMemory || !vk.vkMapMemory || !vk.vkUnmapMemory || 297 if (!vk.vkAllocateMemory || !vk.vkFreeMemory || !vk.vkMapMemory || !vk.vkUnmapMemory ||
248 !vk.vkCreateShaderModule || !vk.vkDestroyShaderModule || !vk.vkCreateGraphicsPipelines || 298 !vk.vkCreateShaderModule || !vk.vkDestroyShaderModule || !vk.vkCreateGraphicsPipelines ||
249 !vk.vkCreateComputePipelines || !vk.vkDestroyPipeline) 299 !vk.vkCreateComputePipelines || !vk.vkDestroyPipeline || !vk.vkCreateImage || !vk.vkDestroyImage ||
300 !vk.vkBindImageMemory)
250 return; 301 return;
251 s.started = GetTickCount64(); 302 s.started = GetTickCount64();
252 s.allocate = vk.vkAllocateMemory, vk.vkAllocateMemory = allocate_memory; 303 s.allocate = vk.vkAllocateMemory, vk.vkAllocateMemory = allocate_memory;
@@ -258,6 +309,9 @@ void install(Functions& vk) {
258 s.create_graphics = vk.vkCreateGraphicsPipelines, vk.vkCreateGraphicsPipelines = create_graphics_pipelines; 309 s.create_graphics = vk.vkCreateGraphicsPipelines, vk.vkCreateGraphicsPipelines = create_graphics_pipelines;
259 s.create_compute = vk.vkCreateComputePipelines, vk.vkCreateComputePipelines = create_compute_pipelines; 310 s.create_compute = vk.vkCreateComputePipelines, vk.vkCreateComputePipelines = create_compute_pipelines;
260 s.destroy_pipeline = vk.vkDestroyPipeline, vk.vkDestroyPipeline = destroy_pipeline; 311 s.destroy_pipeline = vk.vkDestroyPipeline, vk.vkDestroyPipeline = destroy_pipeline;
312 s.create_image = vk.vkCreateImage, vk.vkCreateImage = create_image;
313 s.destroy_image = vk.vkDestroyImage, vk.vkDestroyImage = destroy_image;
314 s.bind_image = vk.vkBindImageMemory, vk.vkBindImageMemory = bind_image_memory;
261 std::fprintf(stderr, "[rt] mem-probe: installed, every %u s\n", interval_seconds()); 315 std::fprintf(stderr, "[rt] mem-probe: installed, every %u s\n", interval_seconds());
262} 316}
263 317
@@ -451,6 +505,7 @@ inline std::string read_rollup() {
451struct DeviceFacts { 505struct DeviceFacts {
452 std::function<std::string()> describe; // one text fragment 506 std::function<std::string()> describe; // one text fragment
453 std::function<Ranges()> title_ranges; // the title's memory 507 std::function<Ranges()> title_ranges; // the title's memory
508 std::function<memory_breakdown::DeviceShare()> share; // the arena and the bindless tables, for the breakdown
454 VkPhysicalDeviceMemoryProperties memory{}; 509 VkPhysicalDeviceMemoryProperties memory{};
455}; 510};
456 511
@@ -477,6 +532,7 @@ inline void sample(const DeviceFacts& facts) {
477 std::uint64_t type_count[VK_MAX_MEMORY_TYPES] = {}, type_bytes[VK_MAX_MEMORY_TYPES] = {}; 532 std::uint64_t type_count[VK_MAX_MEMORY_TYPES] = {}, type_bytes[VK_MAX_MEMORY_TYPES] = {};
478 std::uint64_t import_count[VK_MAX_MEMORY_TYPES] = {}, import_bytes[VK_MAX_MEMORY_TYPES] = {}; 533 std::uint64_t import_count[VK_MAX_MEMORY_TYPES] = {}, import_bytes[VK_MAX_MEMORY_TYPES] = {};
479 Ranges vk_mapped; 534 Ranges vk_mapped;
535 memory_breakdown::Tally tally;
480 std::uint64_t modules = 0, module_bytes = 0, modules_made = 0, module_bytes_made = 0; 536 std::uint64_t modules = 0, module_bytes = 0, modules_made = 0, module_bytes_made = 0;
481 std::uint64_t graphics = 0, compute = 0, graphics_made = 0, compute_made = 0, graphics_ns = 0, compute_ns = 0; 537 std::uint64_t graphics = 0, compute = 0, graphics_made = 0, compute_made = 0, graphics_ns = 0, compute_ns = 0;
482 { 538 {
@@ -491,6 +547,7 @@ inline void sample(const DeviceFacts& facts) {
491 type_bytes[i] += a.bytes; 547 type_bytes[i] += a.bytes;
492 } 548 }
493 if (a.mapped && !a.imported) vk_mapped.push_back({a.mapped, a.mapped + a.mapped_bytes}); 549 if (a.mapped && !a.imported) vk_mapped.push_back({a.mapped, a.mapped + a.mapped_bytes});
550 tally.add(a.consumer, a.bytes, a.imported);
494 } 551 }
495 modules = s.modules.size(); 552 modules = s.modules.size();
496 module_bytes = s.module_bytes; 553 module_bytes = s.module_bytes;
@@ -527,6 +584,10 @@ inline void sample(const DeviceFacts& facts) {
527 (unsigned long long)compute_made, double(graphics_ns) / 1e9, double(compute_ns) / 1e9, 584 (unsigned long long)compute_made, double(graphics_ns) / 1e9, double(compute_ns) / 1e9,
528 (unsigned long long)modules, mib(module_bytes), (unsigned long long)modules_made, 585 (unsigned long long)modules, mib(module_bytes), (unsigned long long)modules_made,
529 mib(module_bytes_made), memory_text.c_str(), facts.describe ? facts.describe().c_str() : ""); 586 mib(module_bytes_made), memory_text.c_str(), facts.describe ? facts.describe().c_str() : "");
587 std::fprintf(stderr, "[rt] mem-probe breakdown t=%.0fs: %s\n", t,
588 memory_breakdown::format(tally, facts.share ? facts.share() : memory_breakdown::DeviceShare{},
589 module_bytes)
590 .c_str());
530 Ranges title = facts.title_ranges ? facts.title_ranges() : Ranges{}; 591 Ranges title = facts.title_ranges ? facts.title_ranges() : Ranges{};
531 std::sort(title.begin(), title.end()); 592 std::sort(title.begin(), title.end());
532 Usage usage[b_count]; 593 Usage usage[b_count];
diff --git a/runtime/src/memory_breakdown.h b/runtime/src/memory_breakdown.h
new file mode 100644
index 000000000..7e2ae7057
--- /dev/null
+++ b/runtime/src/memory_breakdown.h
@@ -0,0 +1,152 @@
1#pragma once
2
3// The mem probe's breakdown line (src/mem_probe.h, LEONIDA_MEM_PROBE=<seconds>): the runtime's own vkAllocateMemory
4// bytes split by the consumer that asked for them, so the parts add up to the total the probe's `mem-probe t=` line
5// prints per memory type. Diagnostic only: nothing here changes what is allocated or where.
6//
7// A consumer is named in one of two ways:
8// - by the caller: an Owner scope around the call that allocates (the arena, the geometry copies' and title
9// windows' 4 MiB blocks, upload heaps, staging, the texture blocks). The probe's vkAllocateMemory wrapper reads
10// the scope of the thread it runs on;
11// - by what is bound to it: memory nobody named that a dedicated image is bound to is a render target or depth
12// buffer when the image is an attachment, else a sampled texture (image_consumer()).
13// Memory named neither way is "other", so the parts always sum to the total.
14//
15// Pure standard library (the usage bits are passed in as plain integers), so the tally and the text are tested
16// without a GPU or Windows (memory_breakdown_test).
17
18#include <array>
19#include <cstdint>
20#include <cstdio>
21#include <string>
22
23namespace leonida::memory_breakdown {
24
25enum class Consumer : std::uint8_t {
26 other, // nobody named it and no image is bound to it
27 arena, // the GPU address arena's memory (docs/d3d12_vulkan.md section 3.3)
28 geometry, // geometry copies: GeometryViews' 4 MiB blocks (shims/d3d12_geometry_views.h)
29 windows, // title windows outside the arena and slot-133 shadow buffers with their own memory
30 upload, // upload and readback heap buffers with their own memory
31 staging, // texture staging and copy scratch
32 image_blocks, // blocks that hold many textures (ImageMemory, TitleImagePool)
33 sampled, // dedicated memory of a texture that is not an attachment
34 render_target, // dedicated memory of a colour or depth/stencil attachment
35 count
36};
37
38constexpr std::size_t kConsumers = std::size_t(Consumer::count);
39
40inline const char* consumer_name(Consumer c) {
41 switch (c) {
42 case Consumer::other: return "other";
43 case Consumer::arena: return "arena";
44 case Consumer::geometry: return "geometry copies";
45 case Consumer::windows: return "title windows and shadows";
46 case Consumer::upload: return "upload heaps";
47 case Consumer::staging: return "staging";
48 case Consumer::image_blocks: return "texture blocks";
49 case Consumer::sampled: return "sampled textures";
50 case Consumer::render_target: return "render targets and depth";
51 default: return "?";
52 }
53}
54
55// VkImageUsageFlagBits values, as plain integers so this header needs no Vulkan headers.
56constexpr std::uint32_t kColorAttachment = 0x10; // VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT
57constexpr std::uint32_t kDepthStencilAttachment = 0x20; // VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT
58
59// The consumer of memory an image of `usage` is bound to, when nobody named the memory.
60inline Consumer image_consumer(std::uint32_t usage) {
61 return usage & (kColorAttachment | kDepthStencilAttachment) ? Consumer::render_target : Consumer::sampled;
62}
63
64// The consumer the calling thread allocates for. Set by an Owner scope; Consumer::other outside one.
65inline Consumer& current_owner() {
66 thread_local Consumer owner = Consumer::other;
67 return owner;
68}
69
70// Names the consumer of the allocations this thread makes while the scope lives. Scopes nest: the inner one wins
71// and the outer one is back when it ends.
72class Owner {
73public:
74 explicit Owner(Consumer consumer) : previous_(current_owner()) { current_owner() = consumer; }
75 ~Owner() { current_owner() = previous_; }
76 Owner(const Owner&) = delete;
77 Owner& operator=(const Owner&) = delete;
78
79private:
80 Consumer previous_;
81};
82
83// Live allocations per consumer. Imported memory (host pointers, the title's own pages) is system memory the runtime
84// did not allocate, so it is kept apart, as the probe's total keeps it apart.
85struct Tally {
86 std::array<std::uint64_t, kConsumers> bytes{}, count{};
87 std::uint64_t imported_bytes = 0, imported_count = 0;
88
89 void add(Consumer consumer, std::uint64_t size, bool imported) {
90 if (imported) {
91 imported_bytes += size;
92 ++imported_count;
93 return;
94 }
95 const std::size_t i = std::size_t(consumer) < kConsumers ? std::size_t(consumer) : 0;
96 bytes[i] += size;
97 ++count[i];
98 }
99 std::uint64_t total() const {
100 std::uint64_t sum = 0;
101 for (const std::uint64_t b : bytes) sum += b;
102 return sum;
103 }
104};
105
106// What the device knows about the arena and the tables outside the probe's wrapped allocations.
107struct DeviceShare {
108 bool arena = false;
109 std::uint64_t arena_reserved = 0; // the arena's size: the address range shaders may name
110 std::uint64_t arena_bound = 0; // bytes of memory behind it
111 std::uint64_t arena_in_use = 0; // bytes allocations hold
112 // arena_in_use by kind, as DeviceState::ArenaUse: buffers, descriptor heaps, shader code, heaps
113 std::array<std::uint64_t, 4> arena_use{};
114 std::uint64_t bindless_table_bytes = 0; // allocated by BindlessSet through its own function table
115};
116
117inline double mib(std::uint64_t bytes) { return double(bytes) / 1048576.0; }
118
119// The breakdown line's text after "[rt] mem-probe breakdown t=<s>: ". Every consumer is printed, zero or not, so a
120// reader can line up two ticks; the figures are whole MiB.
121inline std::string format(const Tally& tally, const DeviceShare& device, std::uint64_t module_bytes) {
122 std::string out;
123 char item[256];
124 std::snprintf(item, sizeof item, "allocated %.0f MiB =", mib(tally.total()));
125 out += item;
126 bool first = true;
127 for (std::size_t i = 1; i <= kConsumers; ++i) {
128 const std::size_t c = i % kConsumers; // "other" last
129 std::snprintf(item, sizeof item, "%s %s %.0f (%llu)", first ? "" : " +", consumer_name(Consumer(c)),
130 mib(tally.bytes[c]), (unsigned long long)tally.count[c]);
131 out += item;
132 first = false;
133 if (Consumer(c) == Consumer::arena && device.arena) {
134 std::snprintf(item, sizeof item,
135 " [reserved %.0f, bound %.0f, in use %.0f: buffers %.0f, descriptor heaps %.0f, shader code "
136 "%.0f, heaps %.0f]",
137 mib(device.arena_reserved), mib(device.arena_bound), mib(device.arena_in_use),
138 mib(device.arena_use[0]), mib(device.arena_use[1]), mib(device.arena_use[2]),
139 mib(device.arena_use[3]));
140 out += item;
141 }
142 }
143 std::snprintf(item, sizeof item,
144 "; imported %.0f MiB (%llu); not in the total: bindless tables %.0f MiB (own function table), shader "
145 "modules %.0f MiB SPIR-V, pipelines and swapchain images (the driver's)",
146 mib(tally.imported_bytes), (unsigned long long)tally.imported_count,
147 mib(device.bindless_table_bytes), mib(module_bytes));
148 out += item;
149 return out;
150}
151
152} // namespace leonida::memory_breakdown