From 4aa1096723a152e395efcc9d13d165da00f7246e Mon Sep 17 00:00:00 2001 From: Moriz82 <72836413+Moriz82@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:19:45 -0600 Subject: [PATCH] runtime: opt-in memory counters for the Vulkan device (RT-MEMORY-PROBE) A long boot can run out of memory, and nothing says whether it went to Vulkan allocations, pipelines, the GPU address arena or the process itself. LEONIDA_MEM_PROBE= wraps nine entries of the device's function table and writes, every and once more when the device is destroyed, the live pipelines by kind, the shader modules and their SPIR-V bytes, VkDeviceMemory per memory type (allocated and imported apart), the arena's use, and the working set and private bytes of the process. Under Wine on Linux it also sums the process's smaps per kind of mapping. The lines hold counts, sizes and file names. Unset, nothing is wrapped, no thread is started and nothing is written. The sampling thread ends with the device. Cross-built gta6rt and mem_probe_test. The test drives a stand-in function table: unset, the table is untouched and nothing is written; set, the entries are wrapped, all calls still reach the driver and the lines carry the expected counts. Both forms passed under Wine 11.22. d3d12_draw_test passed with the variable unset and set on an RTX 4070. AI-assisted (Claude Code). Co-authored-by: Plaaasma <47513553+Plaaasma@users.noreply.github.com> Co-Authored-By: Claude Fable 5.2 --- runtime/CMakeLists.txt | 12 ++ runtime/shims/d3d12_vulkan_device.cpp | 8 +- runtime/src/mem_probe.h | 63 +++++-- runtime/test/mem_probe_test.cpp | 249 ++++++++++++++++++++++++++ 4 files changed, 311 insertions(+), 21 deletions(-) create mode 100644 runtime/test/mem_probe_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 48c8af3602..fd4cf3c122 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2021,6 +2021,18 @@ if(TARGET Vulkan::Headers) add_test(NAME vk_host_at_aliasing COMMAND vk_host_at_aliasing_test) endif() # CPU-only: ScratchBuffers chunk alignment, retire/collect/forget, and spare cap (runtime/src/vulkan_scratch.h). + if(WIN32 AND BUILD_TESTING) + # LEONIDA_MEM_PROBE (src/mem_probe.h) on a stand-in function table: unset (nothing installed, nothing written) + # and set (--on: the entries wrapped, the counts and the lines). No GPU. + add_executable(mem_probe_test test/mem_probe_test.cpp) + target_link_libraries(mem_probe_test PRIVATE Vulkan::Headers) + target_compile_definitions(mem_probe_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + if(MSVC) + target_compile_options(mem_probe_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME mem_probe_off COMMAND mem_probe_test) + add_test(NAME mem_probe_on COMMAND mem_probe_test --on) + endif() add_executable(vulkan_scratch_test test/vulkan_scratch_test.cpp) target_link_libraries(vulkan_scratch_test PRIVATE Vulkan::Headers) if(MSVC) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 12494d201d..6179b3b845 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -9677,7 +9677,7 @@ class Device final for (auto queue : info.compute_queues) state_.context->add_diagnostic_queue(queue); for (auto queue : info.copy_queues) state_.context->add_diagnostic_queue(queue); } - leonida::mem_probe::install(state_.context->vk); // LOCAL DIAGNOSTIC: before anything allocates + const bool mem_probe_installed = leonida::mem_probe::install(state_.context->vk); if (info.device_fault_diagnostics && rt::compute_probe::enabled()) state_.context->set_input_probe([this](auto lists, auto sequence, auto queue) { rt::compute_probe::inspect(state_, lists, sequence, queue); @@ -9760,7 +9760,7 @@ class Device final } if (info.buffer_device_address && state_.context->loaded() && !create_arena()) std::fprintf(stderr, "[rt] d3d12: the GPU address arena could not be created\n"); - { // LOCAL DIAGNOSTIC: mem probe (LEONIDA_MEM_PROBE=) + if (mem_probe_installed) { leonida::mem_probe::DeviceFacts facts; facts.memory = state_.memory; facts.title_ranges = [] { return leonida::title_va_aliases().title_memory_ranges(); }; @@ -9806,7 +9806,7 @@ class Device final (unsigned long long)shadows, leonida::fsdraw::pipeline_count()); return std::string(text); }; - leonida::mem_probe::start(std::move(facts)); + mem_probe_ = leonida::mem_probe::start(std::move(facts)); } if (info.conditional_rendering) { const auto properties = reinterpret_cast( @@ -10257,6 +10257,7 @@ class Device final } ~Device() override { + mem_probe_.reset(); // The sampler reads state_. raw_images_.clear(); leonida::title_va_aliases().clear_hooks(&state_); { @@ -15148,6 +15149,7 @@ class Device final std::mutex native_pipeline_mutex_; std::unordered_map> native_pipelines_; DeviceState state_; + std::unique_ptr mem_probe_; struct RawImage { std::unique_ptr resource; std::vector fingerprints; diff --git a/runtime/src/mem_probe.h b/runtime/src/mem_probe.h index a36d38bfe3..0df6671929 100644 --- a/runtime/src/mem_probe.h +++ b/runtime/src/mem_probe.h @@ -19,12 +19,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -60,7 +62,7 @@ struct State { 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 - std::uint64_t installed = 0; + bool installed = false; ULONGLONG started = 0; }; @@ -239,15 +241,16 @@ inline VKAPI_ATTR void VKAPI_CALL destroy_pipeline(VkDevice device, VkPipeline p // Wraps the runtime's function table (leonida::VulkanDeviceFunctions). Once per process: the first device wins. template -void install(Functions& vk) { - if (!interval_seconds()) return; +bool install(Functions& vk) { + if (!interval_seconds()) return false; State& s = state(); std::lock_guard lock(s.mutex); - if (s.installed++) return; + if (s.installed) return false; if (!vk.vkAllocateMemory || !vk.vkFreeMemory || !vk.vkMapMemory || !vk.vkUnmapMemory || !vk.vkCreateShaderModule || !vk.vkDestroyShaderModule || !vk.vkCreateGraphicsPipelines || !vk.vkCreateComputePipelines || !vk.vkDestroyPipeline) - return; + return false; + s.installed = true; s.started = GetTickCount64(); s.allocate = vk.vkAllocateMemory, vk.vkAllocateMemory = allocate_memory; s.free = vk.vkFreeMemory, vk.vkFreeMemory = free_memory; @@ -259,6 +262,7 @@ void install(Functions& vk) { s.create_compute = vk.vkCreateComputePipelines, vk.vkCreateComputePipelines = create_compute_pipelines; s.destroy_pipeline = vk.vkDestroyPipeline, vk.vkDestroyPipeline = destroy_pipeline; std::fprintf(stderr, "[rt] mem-probe: installed, every %u s\n", interval_seconds()); + return true; } // ---- /proc/self/smaps, classified ---- @@ -552,19 +556,42 @@ inline void sample(const DeviceFacts& facts) { read_rollup().c_str()); } -// Starts the sampling thread (once). The thread runs until the process ends. -inline void start(DeviceFacts facts) { - const unsigned seconds = interval_seconds(); - if (!seconds) return; - static std::once_flag once; - std::call_once(once, [&] { - std::thread([facts = std::move(facts), seconds] { - for (;;) { - Sleep(seconds * 1000); - sample(facts); - } - }).detach(); - }); +// Own the sampler on the device whose state its callbacks read. +class Sampler { +public: + Sampler(DeviceFacts facts, unsigned seconds) + : thread_([this, facts = std::move(facts), seconds] { + std::unique_lock lock(mutex_); + while (!wake_.wait_for(lock, std::chrono::seconds(seconds), [this] { return stopping_; })) { + lock.unlock(); + sample(facts); + lock.lock(); + } + lock.unlock(); + sample(facts); + }) {} + ~Sampler() { + { + std::lock_guard lock(mutex_); + stopping_ = true; + } + wake_.notify_one(); + thread_.join(); + } + Sampler(const Sampler&) = delete; + Sampler& operator=(const Sampler&) = delete; + +private: + std::mutex mutex_; + std::condition_variable wake_; + bool stopping_ = false; + std::thread thread_; +}; + +inline std::unique_ptr start(DeviceFacts facts) { + if (const unsigned seconds = interval_seconds()) + return std::make_unique(std::move(facts), seconds); + return nullptr; } } // namespace leonida::mem_probe diff --git a/runtime/test/mem_probe_test.cpp b/runtime/test/mem_probe_test.cpp new file mode 100644 index 0000000000..120dfe9e6d --- /dev/null +++ b/runtime/test/mem_probe_test.cpp @@ -0,0 +1,249 @@ +// LEONIDA_MEM_PROBE (src/mem_probe.h), off and on, on a stand-in function table: no GPU, no game data. +// +// mem_probe_test the variable unset: the table is left alone, no thread starts, nothing is written +// mem_probe_test --on LEONIDA_MEM_PROBE=1: the nine entries are wrapped and still reach the driver, the counts +// follow what was made and destroyed, and the lines say so +// +// Both forms make the same calls through the table: three allocations (one imported), one freed, one mapped; two +// shader modules, one destroyed; three graphics pipelines and one compute pipeline, one graphics pipeline destroyed. +// stderr is sent to a file while they run. +#include "../src/mem_probe.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::printf("line %d: %s\n", __LINE__, #condition); std::fflush(stdout); return 1; } \ +} while (0) + +namespace { + +namespace probe = leonida::mem_probe; + +// The stand-in driver: every call is counted and hands out the next handle. +int g_calls = 0; +std::uint64_t g_next = 0x1000; +template +Handle next_handle() { return reinterpret_cast(static_cast(g_next += 0x10)); } + +VKAPI_ATTR VkResult VKAPI_CALL fake_allocate(VkDevice, const VkMemoryAllocateInfo*, const VkAllocationCallbacks*, + VkDeviceMemory* out) { + ++g_calls; + *out = next_handle(); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL fake_free(VkDevice, VkDeviceMemory, const VkAllocationCallbacks*) { ++g_calls; } +char g_mapped[4096]; +VKAPI_ATTR VkResult VKAPI_CALL fake_map(VkDevice, VkDeviceMemory, VkDeviceSize, VkDeviceSize, VkMemoryMapFlags, + void** data) { + ++g_calls; + *data = g_mapped; + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL fake_unmap(VkDevice, VkDeviceMemory) { ++g_calls; } +VKAPI_ATTR VkResult VKAPI_CALL fake_create_module(VkDevice, const VkShaderModuleCreateInfo*, + const VkAllocationCallbacks*, VkShaderModule* out) { + ++g_calls; + *out = next_handle(); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL fake_destroy_module(VkDevice, VkShaderModule, const VkAllocationCallbacks*) { ++g_calls; } +VKAPI_ATTR VkResult VKAPI_CALL fake_create_graphics(VkDevice, VkPipelineCache, std::uint32_t count, + const VkGraphicsPipelineCreateInfo*, const VkAllocationCallbacks*, + VkPipeline* out) { + ++g_calls; + for (std::uint32_t i = 0; i < count; ++i) out[i] = next_handle(); + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL fake_create_compute(VkDevice, VkPipelineCache, std::uint32_t count, + const VkComputePipelineCreateInfo*, const VkAllocationCallbacks*, + VkPipeline* out) { + ++g_calls; + for (std::uint32_t i = 0; i < count; ++i) out[i] = next_handle(); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL fake_destroy_pipeline(VkDevice, VkPipeline, const VkAllocationCallbacks*) { ++g_calls; } + +// The nine entries install() wraps, named as in leonida::VulkanDeviceFunctions. +struct Table { + PFN_vkAllocateMemory vkAllocateMemory = fake_allocate; + PFN_vkFreeMemory vkFreeMemory = fake_free; + PFN_vkMapMemory vkMapMemory = fake_map; + PFN_vkUnmapMemory vkUnmapMemory = fake_unmap; + PFN_vkCreateShaderModule vkCreateShaderModule = fake_create_module; + PFN_vkDestroyShaderModule vkDestroyShaderModule = fake_destroy_module; + PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines = fake_create_graphics; + PFN_vkCreateComputePipelines vkCreateComputePipelines = fake_create_compute; + PFN_vkDestroyPipeline vkDestroyPipeline = fake_destroy_pipeline; +}; + +bool untouched(const Table& t) { + return t.vkAllocateMemory == fake_allocate && t.vkFreeMemory == fake_free && t.vkMapMemory == fake_map && + t.vkUnmapMemory == fake_unmap && t.vkCreateShaderModule == fake_create_module && + t.vkDestroyShaderModule == fake_destroy_module && t.vkCreateGraphicsPipelines == fake_create_graphics && + t.vkCreateComputePipelines == fake_create_compute && t.vkDestroyPipeline == fake_destroy_pipeline; +} + +// Sends stderr to `path` while it lives; finish() restores it and returns what was written. +struct StderrCapture { + std::filesystem::path path; + int saved = -1; + bool redirected = false; + explicit StderrCapture(const std::filesystem::path& file) : path(file) { + std::fflush(stderr); + std::FILE* out = nullptr; + if (_wfopen_s(&out, path.c_str(), L"wb") != 0) out = nullptr; + saved = _dup(2); + if (out && saved >= 0) redirected = _dup2(_fileno(out), 2) == 0; + if (out) std::fclose(out); + } + std::string finish() { + std::fflush(stderr); + if (saved >= 0) { + _dup2(saved, 2); + _close(saved); + saved = -1; + } + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; + } + ~StderrCapture() { finish(); } +}; + +int count_of(const std::string& text, const std::string& needle) { + int count = 0; + for (std::size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++count; + return count; +} + +// The calls both forms make. The handles the stand-in driver gave must come back unchanged through the table. +int use_table(Table& vk) { + const VkDevice device = nullptr; + VkMemoryAllocateInfo info{}; + info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + VkDeviceMemory first = VK_NULL_HANDLE, second = VK_NULL_HANDLE, imported = VK_NULL_HANDLE; + info.allocationSize = 1u << 20; + info.memoryTypeIndex = 0; + EXPECT(vk.vkAllocateMemory(device, &info, nullptr, &first) == VK_SUCCESS && first); + info.allocationSize = 3u << 20; + EXPECT(vk.vkAllocateMemory(device, &info, nullptr, &second) == VK_SUCCESS && second && second != first); + VkImportMemoryHostPointerInfoEXT host{}; + host.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT; + info.pNext = &host; + info.allocationSize = 2u << 20; + info.memoryTypeIndex = 1; + EXPECT(vk.vkAllocateMemory(device, &info, nullptr, &imported) == VK_SUCCESS && imported); + void* mapped = nullptr; + EXPECT(vk.vkMapMemory(device, second, 0, VK_WHOLE_SIZE, 0, &mapped) == VK_SUCCESS && mapped == g_mapped); + vk.vkFreeMemory(device, first, nullptr); + + VkShaderModuleCreateInfo module_info{}; + module_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + VkShaderModule kept = VK_NULL_HANDLE, dropped = VK_NULL_HANDLE; + module_info.codeSize = 1u << 20; + EXPECT(vk.vkCreateShaderModule(device, &module_info, nullptr, &kept) == VK_SUCCESS && kept); + module_info.codeSize = 2u << 20; + EXPECT(vk.vkCreateShaderModule(device, &module_info, nullptr, &dropped) == VK_SUCCESS && dropped); + vk.vkDestroyShaderModule(device, dropped, nullptr); + + VkPipeline graphics[3] = {}, compute = VK_NULL_HANDLE; + const VkGraphicsPipelineCreateInfo graphics_info[3] = {}; + const VkComputePipelineCreateInfo compute_info{}; + EXPECT(vk.vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 3, graphics_info, nullptr, graphics) == VK_SUCCESS); + EXPECT(graphics[0] && graphics[1] && graphics[2]); + EXPECT(vk.vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &compute_info, nullptr, &compute) == VK_SUCCESS); + vk.vkDestroyPipeline(device, graphics[1], nullptr); + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + const bool on = argc == 2 && std::strcmp(argv[1], "--on") == 0; + if (argc > 1 && !on) { + std::printf("usage: mem_probe_test [--on]\n"); + return 2; + } + // Read at the first interval_seconds(). An empty value removes the variable, so the plain form does not depend + // on the environment it is started in. + EXPECT(_putenv_s("LEONIDA_MEM_PROBE", on ? "1" : "") == 0); + std::error_code ec; + const std::filesystem::path log_file = + std::filesystem::temp_directory_path(ec) / ("leonida_mem_probe_test_" + std::to_string(GetCurrentProcessId()) + ".txt"); + + probe::DeviceFacts facts; + facts.memory.memoryTypeCount = 2; + facts.memory.memoryTypes[0] = {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0}; + facts.memory.memoryTypes[1] = {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 1}; + facts.describe = [] { return std::string("arena 64 MiB"); }; + + Table table, second_table; + std::string log, later; + bool redirected = false, installed = false, installed_again = false, sampling = false; + int used = 1; + { + StderrCapture capture(log_file); + redirected = capture.redirected; + installed = probe::install(table); + installed_again = probe::install(second_table); // a second device of the process + used = use_table(table); + if (on && used == 0) probe::sample(facts); + { + const auto sampler = probe::start(facts); + sampling = sampler != nullptr; + Sleep(2500); // on: the sampler writes at 1 s and 2 s, and once more when it is stopped + } + log = capture.finish(); + } + { + StderrCapture capture(log_file); + Sleep(1500); // a stopped sampler writes nothing more + later = capture.finish(); + } + std::filesystem::remove(log_file, ec); + if (used != 0) return used; + EXPECT(redirected); + EXPECT(g_calls == 11); // every call reached the stand-in driver, wrapped or not + EXPECT(untouched(second_table) && !installed_again); + EXPECT(count_of(later, "mem-probe") == 0); + + probe::State& s = probe::state(); + if (!on) { + EXPECT(probe::interval_seconds() == 0); + EXPECT(!installed && untouched(table) && !sampling); + EXPECT(log.empty()); + EXPECT(s.allocations.empty() && s.modules.empty() && s.pipelines.empty() && !s.modules_made); + std::printf("probe off: 11 calls reached the driver through an untouched table, no thread, nothing written\n"); + return 0; + } + + EXPECT(probe::interval_seconds() == 1); + EXPECT(installed && sampling); + EXPECT(table.vkAllocateMemory == probe::allocate_memory && table.vkFreeMemory == probe::free_memory && + table.vkMapMemory == probe::map_memory && table.vkUnmapMemory == probe::unmap_memory && + table.vkCreateShaderModule == probe::create_shader_module && + table.vkDestroyShaderModule == probe::destroy_shader_module && + table.vkCreateGraphicsPipelines == probe::create_graphics_pipelines && + table.vkCreateComputePipelines == probe::create_compute_pipelines && + table.vkDestroyPipeline == probe::destroy_pipeline); + EXPECT(s.allocations.size() == 2 && s.modules.size() == 1 && s.pipelines.size() == 3); + EXPECT(s.graphics_live == 2 && s.compute_live == 1 && s.graphics_made == 3 && s.compute_made == 1); + EXPECT(s.module_bytes == (1u << 20) && s.modules_made == 2 && s.module_bytes_made == (3u << 20)); + EXPECT(count_of(log, "[rt] mem-probe: installed, every 1 s\n") == 1); + // One line from the direct sample(), the sampler's timed ones and its last: all say the same. + const int samples = count_of(log, "[rt] mem-probe t="); + EXPECT(samples >= 3 && samples <= 5); + EXPECT(count_of(log, "pipelines live graphics 2 compute 1 (made 3 / 1,") == samples); + EXPECT(count_of(log, "shader modules live 1, 1 MiB SPIR-V (made 2, 3 MiB)") == samples); + EXPECT(count_of(log, "type 0 DL heap 0: 1 x 3 MiB; type 1 HV+HC heap 1: 0 x 0 MiB " + "(+1 imported, 2 MiB); arena 64 MiB") == samples); + std::printf("probe on: 9 entries wrapped, 11 calls reached the driver, %d samples, thread stopped\n", samples); + return 0; +}