Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 21 additions & 4 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -17573,22 +17574,38 @@ 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<leonida::working_set::CpuRange> 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);
mapped += t->mapped;
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<unsigned long long>(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 "
Expand Down
72 changes: 72 additions & 0 deletions runtime/src/working_set.h
Original file line number Diff line number Diff line change
@@ -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 <algorithm>
#include <cstdint>
#include <vector>

#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <psapi.h>
#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<CpuRange>& 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<PSAPI_WORKING_SET_EX_INFORMATION> info(static_cast<std::size_t>(samples));
for (std::uint64_t i = 0; i < samples; ++i)
info[static_cast<std::size_t>(i)].VirtualAddress = reinterpret_cast<void*>(first + i * step * kPage);
if (!QueryWorkingSetEx(GetCurrentProcess(), info.data(),
static_cast<DWORD>(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
73 changes: 73 additions & 0 deletions runtime/test/working_set_test.cpp
Original file line number Diff line number Diff line change
@@ -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 <cstdio>
#include <cstring>

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<CpuRange> 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<unsigned char*>(VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
auto* untouched = static_cast<unsigned char*>(VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
auto* reserved = static_cast<unsigned char*>(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<std::uint64_t>(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;
}
Loading