diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3084bf06b8..37ee0db363 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3642,7 +3642,12 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv slice can be reused. Large images, dedicated-only images, and failed pool allocations use individual memory allocations. `LEONIDA_TITLE_IMAGE_POOL=0` selects individual allocation for every image. With `LEONIDA_MEM_PROBE` enabled, the texture census also reports logical Vulkan backing bytes for the registered - slot-70 and slot-133 images and the portion on non-device-local types. + slot-70 and slot-133 images and the portion on non-device-local types. It also reports the unique CPU memory + behind images filled from title memory and estimates how much of it is resident in RAM (#1702). The census + merges overlapping CPU address ranges before sampling one page in 16 with `QueryWorkingSetEx` + (`runtime/src/working_set.h`). Images the GPU writes (render targets, depth, unordered access) are left out. The + merge is by virtual address, so the log line says "CPU virtual bytes": two distinct views of one physical backing + (the same frames mapped at two addresses) count twice, in the total and in the resident part. - A refresh pass visits a snapshot of the title-image registry, taken under its mutex, instead of walking the registry itself. Filling a texture can submit, a submission destroys a retired image, and that image's destructor erases its registry entry. Windows' mutex is recursive for its owner, so the erase lands inside the pass, and a walk diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 9c433257d3..215ed9b6ec 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -39,6 +39,17 @@ if(MSVC) target_link_options(root_signature_test PRIVATE /OPT:NOREF) endif() +# The memory probe merges CPU ranges on every platform. Windows also tests the working-set query on real pages. +add_executable(working_set_test test/working_set_test.cpp) +if(WIN32) + target_compile_definitions(working_set_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_link_libraries(working_set_test PRIVATE psapi) +endif() +if(MSVC) + target_compile_options(working_set_test PRIVATE /W4 /permissive- /utf-8) +endif() +add_test(NAME working_set COMMAND working_set_test) + option(LEONIDA_BUILD_WINDOWS_RUNTIME "Build the Windows runtime, its shims and their tests" ${WIN32}) if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) # Custom CMAKE_CXX_FLAGS can replace MSVC's default /EHsc. Require C++ stack unwinding so error diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index de623b6040..24c0268642 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -44,6 +44,7 @@ #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" +#include "../src/working_set.h" #include "../src/vulkan_mesh_limits.h" #include "../src/resource_tiling.h" #include "../src/cached_pso.h" @@ -17573,6 +17574,9 @@ class Device final refused += (refused.empty() ? "" : "; ") + why + " " + std::to_string(n); std::size_t owned = 0, slot133 = 0, mapped = 0, filled = 0; VkDeviceSize owned_bytes = 0, placed_bytes = 0, host_heap_bytes = 0; + // With the probe on, collect the CPU ranges that filled the images. Aliases may share a range. + std::vector sources; + const bool probe = leonida::mem_probe::interval_seconds() != 0; for (const auto& [address, t] : state_.title_textures) { (t->owned ? owned : slot133) += 1; if (!t->owned && t->resource && t->unbound_bytes) t->set_resource(t->resource); @@ -17580,15 +17584,28 @@ class Device final filled += t->fills > 0; (t->owned ? owned_bytes : placed_bytes) += t->backing_bytes; if (!t->device_local) host_heap_bytes += t->backing_bytes; + if (probe && t->fills && !t->gpu_written && t->layout_known && t->cpu && t->layout.layout.size && + t->layout.layout.size <= UINT64_MAX - t->cpu) { + sources.push_back({t->cpu, t->cpu + t->layout.layout.size}); + } } - if (leonida::mem_probe::interval_seconds()) + if (probe) { + leonida::working_set::merge_cpu_ranges(sources); + std::uint64_t source_bytes = 0, resident_source_bytes = 0; + for (const auto& [begin, end] : sources) { + source_bytes += end - begin; + resident_source_bytes += leonida::working_set::resident_bytes(begin, end - begin); + } log_title_image_uses(state_.title_textures, retired_title_textures_.size(), retired_backing_, state_.zero_image_bytes.load()); - if (leonida::mem_probe::interval_seconds()) std::fprintf(stderr, "[rt] mem-probe: registered image backing: %.1f MiB from slot 70, %.1f MiB from slot " - "133, %.1f MiB total on non-device-local types; staged fills %llu, %.3f s, buffer %.1f MiB\n", + "133, %.1f MiB total on non-device-local types; staged fills %llu, %.3f s, buffer %.1f MiB; " + "CPU virtual bytes behind filled images %.1f MiB, %.1f MiB of it resident in RAM (two views " + "of one backing count twice)\n", double(owned_bytes) / 1048576.0, double(placed_bytes) / 1048576.0, double(host_heap_bytes) / 1048576.0, static_cast(s.staged_fills), - double(s.staged_ns) / 1e9, double(state_.title_upload.capacity()) / 1048576.0); + double(s.staged_ns) / 1e9, double(state_.title_upload.capacity()) / 1048576.0, + double(source_bytes) / 1048576.0, double(resident_source_bytes) / 1048576.0); + } std::fprintf(stderr, "[rt] d3d12: title textures (%s): %llu slot-70 texture views (%zu kinds), %llu of slot-133 textures, " "%llu of images made for them (%llu made, %llu over memory not readable yet, %llu retired), %llu " diff --git a/runtime/src/working_set.h b/runtime/src/working_set.h new file mode 100644 index 0000000000..de98210cf2 --- /dev/null +++ b/runtime/src/working_set.h @@ -0,0 +1,72 @@ +#pragma once + +// How much of a range of this process's memory is resident in RAM, sampled with QueryWorkingSetEx (psapi): one 4 KiB +// page in every `step`, one call per range. Used by the memory probe to show how much of the title memory behind a +// GPU copy is also held in RAM, which is the duplicate docs/d3d12_vulkan.md and #1702 describe. An estimate, not an +// exact count: a range smaller than `step` pages is read from its first page only. Pages that are not committed, or +// not mapped at all, read as not resident. + +#include +#include +#include + +#ifdef _WIN32 +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include +#endif + +namespace leonida::working_set { + +constexpr std::uint64_t kPage = 4096; + +struct CpuRange { + std::uint64_t begin; + std::uint64_t end; +}; + +// Texture aliases and overlapping views can refer to the same CPU bytes. Count their union, by virtual address: two +// distinct virtual views of one physical backing (a placeholder mapped twice, a GPU-only alias paired with a CPU view) +// do not overlap here, so their bytes count twice, and so does their residency. +inline void merge_cpu_ranges(std::vector& ranges) { + std::sort(ranges.begin(), ranges.end(), [](const CpuRange& a, const CpuRange& b) { return a.begin < b.begin; }); + std::size_t count = 0; + for (const CpuRange range : ranges) { + if (range.begin >= range.end) continue; + if (count && range.begin <= ranges[count - 1].end) { + ranges[count - 1].end = std::max(ranges[count - 1].end, range.end); + } else { + ranges[count++] = range; + } + } + ranges.resize(count); +} + +// Estimated resident bytes of [base, base + size): the share of sampled pages that are valid in the working set, +// times size. 0 for an empty range or where the query is not available. +inline std::uint64_t resident_bytes(std::uint64_t base, std::uint64_t size, unsigned step = 16) { +#ifdef _WIN32 + if (!size || !step) return 0; + const std::uint64_t first = base & ~(kPage - 1); + const std::uint64_t pages = (base + size - first + kPage - 1) / kPage; + const std::uint64_t samples = (pages + step - 1) / step; + std::vector info(static_cast(samples)); + for (std::uint64_t i = 0; i < samples; ++i) + info[static_cast(i)].VirtualAddress = reinterpret_cast(first + i * step * kPage); + if (!QueryWorkingSetEx(GetCurrentProcess(), info.data(), + static_cast(info.size() * sizeof(PSAPI_WORKING_SET_EX_INFORMATION)))) + return 0; + std::uint64_t valid = 0; + for (const auto& e : info) valid += e.VirtualAttributes.Valid; + return size * valid / samples; +#else + (void)base; + (void)size; + (void)step; + return 0; +#endif +} + +} // namespace leonida::working_set diff --git a/runtime/test/working_set_test.cpp b/runtime/test/working_set_test.cpp new file mode 100644 index 0000000000..0c500bda6b --- /dev/null +++ b/runtime/test/working_set_test.cpp @@ -0,0 +1,73 @@ +// src/working_set.h: the memory probe's estimate of how much of a range is resident in RAM. Synthetic memory only. +#include "../src/working_set.h" + +#include +#include + +namespace { +int failures = 0; +void check(bool ok, const char* what) { + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what); + ++failures; + } +} +void check_cpu_ranges() { + using namespace leonida::working_set; + constexpr std::uint64_t start = 0x100000; + constexpr std::uint64_t size = 128 << 10; + std::vector ranges{{start, start + size}, {start, start + size}}; + merge_cpu_ranges(ranges); + check(ranges.size() == 1 && ranges[0].begin == start && ranges[0].end == start + size, + "two aliases count as 128 KiB of unique CPU memory"); + + ranges = {{50, 60}, {25, 40}, {10, 30}, {20, 22}, {40, 45}, {80, 80}}; + merge_cpu_ranges(ranges); + check(ranges.size() == 2 && ranges[0].begin == 10 && ranges[0].end == 45 && + ranges[1].begin == 50 && ranges[1].end == 60, + "overlapping, nested and adjacent ranges merge without filling gaps"); +} + +#ifdef _WIN32 +void check_resident_ranges() { + using leonida::working_set::resident_bytes; + constexpr SIZE_T size = 8u << 20; + auto* touched = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + auto* untouched = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + auto* reserved = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_NOACCESS)); + check(touched && untouched && reserved, "allocations"); + if (!touched || !untouched || !reserved) { + if (touched) VirtualFree(touched, 0, MEM_RELEASE); + if (untouched) VirtualFree(untouched, 0, MEM_RELEASE); + if (reserved) VirtualFree(reserved, 0, MEM_RELEASE); + return; + } + std::memset(touched, 1, size); + const auto base = [](const void* p) { return reinterpret_cast(p); }; + + check(resident_bytes(base(touched), size) == size, "written pages are resident"); + check(resident_bytes(base(untouched), size) == 0, "committed pages never touched are not resident"); + check(resident_bytes(base(reserved), size) == 0, "reserved pages are not resident"); + check(resident_bytes(base(touched), 0) == 0, "an empty range"); + // Half of a range written: the estimate is half of its size (every 16th page sampled, 2,048 pages). + std::memset(untouched, 1, size / 2); + check(resident_bytes(base(untouched), size) == size / 2, "half written, half resident"); + // VirtualUnlock on a range that is not locked removes it from the working set (Win32 VirtualUnlock remarks). + VirtualUnlock(touched, size); + check(resident_bytes(base(touched), size) < size / 4, "pages dropped from the working set are not resident"); + + VirtualFree(touched, 0, MEM_RELEASE); + VirtualFree(untouched, 0, MEM_RELEASE); + VirtualFree(reserved, 0, MEM_RELEASE); + std::printf("working_set: written, untouched, reserved, half-written and trimmed ranges\n"); +} +#endif +} // namespace + +int main() { + check_cpu_ranges(); +#ifdef _WIN32 + check_resident_ranges(); +#endif + return failures ? 1 : 0; +}