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
4 changes: 4 additions & 0 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -3656,6 +3656,10 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv
copies. On a device without `VK_EXT_host_image_copy` every colour title image, linear placements too, takes the
staged upload: the refresh before a submission has no other way to fill one, and without it the title's textures
stayed zero (a flat green intro movie). An allocation failure retries the original host-copyable image.
The staging buffers are a ring of four slots, each as large as the largest texture it has carried; a slot
over `LEONIDA_TITLE_UPLOAD_KEEP_MB` (4) idle for `LEONIDA_TITLE_UPLOAD_IDLE_MS` (2000) after its transfer completed
is freed by the periodic texture pass, which never waits for it (`src/title_upload_trim.h`). The mem probe counts
them as staging and its texture line says how many were freed.
`LEONIDA_TITLE_IMAGE_STAGING=0`
restores the original placement policy. With `LEONIDA_MEM_PROBE`, each title image class logs its
Vulkan memory type mask, mask without host transfer, and selected type.
Expand Down
6 changes: 6 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4864,6 +4864,12 @@ if(TARGET Vulkan::Headers)
target_compile_options(memory_breakdown_test PRIVATE /W4 /permissive- /utf-8)
endif()
add_test(NAME memory_breakdown COMMAND memory_breakdown_test)
# When the title-texture upload ring gives an idle slot's buffer back (src/title_upload_trim.h).
add_executable(title_upload_trim_test test/title_upload_trim_test.cpp)
if(WIN32 AND MSVC)
target_compile_options(title_upload_trim_test PRIVATE /W4 /permissive- /utf-8)
endif()
add_test(NAME title_upload_trim COMMAND title_upload_trim_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)
Expand Down
2 changes: 2 additions & 0 deletions runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,8 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
| `LEONIDA_TITLE_TEXTURE_PERIOD_MS` | `16` | The shortest time between two passes over the textures filled from the title's memory. |
| `LEONIDA_TITLE_TEXTURE_CHECK_KB` | `4096` | How many KiB of those textures one pass hashes to find changed ones. |
| `LEONIDA_TITLE_TEXTURE_FILL_MB` | `32` | How many MiB of changed textures one pass fills again; the rest waits for the next pass. |
| `LEONIDA_TITLE_UPLOAD_IDLE_MS` | `2000` | How long a slot of the title-texture upload ring (the host-visible buffers whole textures are detiled into) stays unused before its buffer is freed, once its transfer has completed. `0` keeps every slot's buffer until the device goes, as before. |
| `LEONIDA_TITLE_UPLOAD_KEEP_MB` | `4` | A slot of that ring this size or smaller is never freed, so steady small uploads do not allocate each time. |
| `LEONIDA_TEXTURE_HASH_BUDGET_US` | `400` | Microseconds a pass may spend hashing before it stops at a texture boundary. `0` leaves the byte budget alone to bound it. |
| `LEONIDA_TEXTURE_SWEEP_BUDGET_US` | `400` | Microseconds a pass may spend on residency checks and uploads between textures. |
| `LEONIDA_TITLE_BUFFERS_MB` | `512` | The most memory, in MiB, of buffers made over the title's own memory for vertex and index views that name it. |
Expand Down
69 changes: 64 additions & 5 deletions runtime/shims/d3d12_title_image_upload.h
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
#pragma once

#include "xg_xs_layout.h"
#include "../src/memory_breakdown.h"
#include "../src/title_upload_trim.h"
#include "../src/vulkan_backend.h"

#include <atomic>
#include <chrono>

namespace rt::d3d12 {

// A ring of upload buffers and command buffers per device, used under the title-texture registry lock.
Expand All @@ -15,12 +20,31 @@ namespace rt::d3d12 {
// resized or freed only after its last transfer completed (the slot's timeline value). The image needs no CPU wait:
// later submissions on the queue are ordered after the transfer, other queues wait for it on the GPU, and a retired
// image is destroyed through the deferred queue, after later submissions retire.
//
// A slot keeps its buffer between writes, but not for ever: trim() gives back a large one that has been idle for a
// while and whose transfer has completed (src/title_upload_trim.h). Its memory counts as staging in the mem probe's
// breakdown line.
class TitleImageUpload {
public:
VkDeviceSize capacity() const {
VkDeviceSize total = 0;
for (const auto& slot : slots_) total += slot.capacity;
return total;
// Readable without the lock (the mem probe's line): the bytes the slots hold, and how many buffers trim() freed.
VkDeviceSize capacity() const { return capacity_.load(std::memory_order_relaxed); }
std::uint64_t trimmed() const { return trimmed_.load(std::memory_order_relaxed); }

// Under the lock write() takes, never waiting for the GPU: releases each slot that title_upload_trim says to.
// Called from the periodic title-texture pass, so a burst of large uploads does not hold its buffers after it.
template<class Device>
void trim(Device& d) {
const auto& settings = trim_settings();
if (!settings.enabled()) return;
const std::uint64_t now = now_ns();
for (auto& slot : slots_) {
if (!slot.capacity) continue;
if (leonida::title_upload_trim::release(slot.capacity, slot.last_used_ns, now, transfer_done(d, slot),
settings)) {
release_buffer(d, slot);
trimmed_.fetch_add(1, std::memory_order_relaxed);
}
}
}

template<class Device>
Expand Down Expand Up @@ -70,6 +94,8 @@ class TitleImageUpload {
}
Slot& slot = slots_[next_];
if (!prepare(d, slot, bytes)) return false;
// Only a large upload keeps the slot's buffer: a small one fits the buffer trim() would leave behind.
if (leonida::title_upload_trim::counts_as_use(bytes, trim_settings())) slot.last_used_ns = now_ns();
next_ = (next_ + 1) % kSlots;
for (const auto& copy : regions_) {
const auto level = copy.imageSubresource.mipLevel;
Expand Down Expand Up @@ -119,8 +145,34 @@ class TitleImageUpload {
VkDeviceSize capacity = 0;
VkCommandBuffer command{};
std::uint64_t value = 0; // the ready_ value its last transfer signals; 0: none submitted
std::uint64_t last_used_ns = 0; // when write() last carried an upload over the size kept (steady clock)
};

static const leonida::title_upload_trim::Settings& trim_settings() {
static const leonida::title_upload_trim::Settings settings = leonida::title_upload_trim::settings_from_env();
return settings;
}

static std::uint64_t now_ns() {
return std::uint64_t(std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count());
}

// Whether the slot's last transfer has completed, without waiting: a counter value it has reached. A value that
// cannot be read counts as not done, so the buffer stays.
template<class Device>
bool transfer_done(Device& d, Slot& slot) {
if (!slot.value) return true;
if (!ready_) return false;
auto& vk = d.context->vk;
std::uint64_t reached = 0;
if (!vk.vkGetSemaphoreCounterValue ||
vk.vkGetSemaphoreCounterValue(d.info.device, ready_, &reached) != VK_SUCCESS || reached < slot.value)
return false;
slot.value = 0;
return true;
}

// Waits (outside every lock but the registry's) until the slot's last transfer has completed.
template<class Device>
bool wait_slot(Device& d, Slot& slot) {
Expand Down Expand Up @@ -154,6 +206,7 @@ class TitleImageUpload {
slot.buffer = VK_NULL_HANDLE;
slot.memory = VK_NULL_HANDLE;
slot.mapped = nullptr;
capacity_.fetch_sub(slot.capacity, std::memory_order_relaxed);
slot.capacity = 0;
}

Expand Down Expand Up @@ -194,7 +247,10 @@ class TitleImageUpload {
if (vk.vkCreateBuffer(dev, &buffer, nullptr, &slot.buffer) != VK_SUCCESS) return false;
VkMemoryRequirements req{};
vk.vkGetBufferMemoryRequirements(dev, slot.buffer, &req);
slot.memory = d.allocate(req, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0);
{
leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging);
slot.memory = d.allocate(req, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0);
}
void* map = nullptr;
if (!slot.memory || vk.vkBindBufferMemory(dev, slot.buffer, slot.memory, 0) != VK_SUCCESS ||
vk.vkMapMemory(dev, slot.memory, 0, VK_WHOLE_SIZE, 0, &map) != VK_SUCCESS) {
Expand All @@ -203,6 +259,7 @@ class TitleImageUpload {
}
slot.mapped = static_cast<std::uint8_t*>(map);
slot.capacity = size;
capacity_.fetch_add(size, std::memory_order_relaxed);
return true;
}

Expand Down Expand Up @@ -251,6 +308,8 @@ class TitleImageUpload {
std::uint64_t value_ = 0;
std::vector<VkQueue> consumers_;
std::vector<VkBufferImageCopy> regions_;
std::atomic<VkDeviceSize> capacity_{0};
std::atomic<std::uint64_t> trimmed_{0};
};

} // namespace rt::d3d12
12 changes: 10 additions & 2 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16512,6 +16512,12 @@ class Device final
std::unique_lock lock(state_.title_texture_mutex, std::try_to_lock);
if (!lock.owns_lock()) return; // a slot-70 view is filling one; next time
title_refreshed_.store(ticks, std::memory_order_relaxed);
{
// Give back the upload ring's large idle buffers (d3d12_title_image_upload.h). try_lock: a fill holding it
// is using the ring now, and this pass never waits for it.
std::unique_lock upload(state_.title_upload_mutex, std::try_to_lock);
if (upload.owns_lock()) state_.title_upload.trim(state_);
}
std::optional<InTitleTextures> inside(std::in_place);
TitleTextureStats& stats = title_stats_;
++stats.passes;
Expand Down Expand Up @@ -17585,10 +17591,12 @@ class Device final
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 "
"(%llu released idle)\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,
static_cast<unsigned long long>(state_.title_upload.trimmed()));
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
87 changes: 87 additions & 0 deletions runtime/src/title_upload_trim.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#pragma once

// When the title-texture upload ring (shims/d3d12_title_image_upload.h) gives an idle slot's buffer back. Each of its
// four slots grows to the largest whole-image upload that went through it and kept that capacity for the rest of the
// run, in host-visible memory (system RAM on a discrete GPU): after a burst of large textures, such as a cutscene's,
// up to four of the largest stayed allocated. A slot is now released once it has been idle for a while and its last
// transfer has completed; a small one is kept, so steady small uploads do not allocate again each time.
//
// LEONIDA_TITLE_UPLOAD_IDLE_MS how long a slot stays unused before it is released (default 2000; 0: never, the
// behaviour before this)
// LEONIDA_TITLE_UPLOAD_KEEP_MB a slot this size or smaller is never released (default 4)
//
// Pure standard library, so the rule is tested without a GPU (title_upload_trim_test).

#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <string>

namespace leonida::title_upload_trim {

struct Settings {
std::uint64_t idle_ns = 2000ull * 1000 * 1000;
std::uint64_t keep_bytes = 4ull << 20;
bool enabled() const { return idle_ns != 0; }
};

// A whole decimal number, or `fallback` for a missing, empty or malformed value.
inline std::uint64_t parse_u64(const char* text, std::uint64_t fallback) {
if (!text || !*text) return fallback;
std::uint64_t value = 0;
for (const char* p = text; *p; ++p) {
if (*p < '0' || *p > '9') return fallback;
const std::uint64_t digit = std::uint64_t(*p - '0');
if (value > (UINT64_MAX - digit) / 10) return fallback;
value = value * 10 + digit;
}
return value;
}

// The two variables' values (null when unset).
inline Settings settings_from(const char* idle_ms, const char* keep_mb) {
Settings s;
const std::uint64_t ms = parse_u64(idle_ms, 2000);
s.idle_ns = ms > UINT64_MAX / 1000000 ? UINT64_MAX : ms * 1000000;
const std::uint64_t mb = parse_u64(keep_mb, 4);
s.keep_bytes = mb > (UINT64_MAX >> 20) ? UINT64_MAX : mb << 20;
return s;
}

// A variable's value as an owned copy ("" when unset): getenv's result may be overwritten by the next getenv, and
// the Windows CRT deprecates getenv for _dupenv_s.
inline std::string env_copy(const char* name) {
#if defined(_WIN32)
char* value = nullptr;
std::size_t length = 0;
if (_dupenv_s(&value, &length, name) != 0 || !value) return {};
std::string copy(value);
std::free(value);
return copy;
#else
const char* value = std::getenv(name);
return value ? std::string(value) : std::string();
#endif
}

// The settings from the environment; an unset variable is "", which gives its default.
inline Settings settings_from_env() {
const std::string idle = env_copy("LEONIDA_TITLE_UPLOAD_IDLE_MS");
const std::string keep = env_copy("LEONIDA_TITLE_UPLOAD_KEEP_MB");
return settings_from(idle.c_str(), keep.c_str());
}

// Whether an upload of `bytes` counts as a use of its slot's large buffer. Only an upload over the size kept does:
// small ones the slot also carries would otherwise keep a buffer left over from a burst of large textures for ever
// (they go round the four slots, so every slot gets one now and then).
inline bool counts_as_use(std::uint64_t bytes, const Settings& s) { return bytes > s.keep_bytes; }

// Whether a slot's buffer is released now. `capacity`: its bytes (0: nothing to release); `last_used_ns`: when a
// write last used it; `transfer_done`: its last transfer has completed (known without waiting).
inline bool release(std::uint64_t capacity, std::uint64_t last_used_ns, std::uint64_t now_ns, bool transfer_done,
const Settings& s) {
if (!s.enabled() || !capacity || capacity <= s.keep_bytes || !transfer_done) return false;
return now_ns >= last_used_ns && now_ns - last_used_ns >= s.idle_ns;
}

} // namespace leonida::title_upload_trim
112 changes: 112 additions & 0 deletions runtime/test/title_upload_trim_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// leonida::title_upload_trim (src/title_upload_trim.h): when the title-texture upload ring releases an idle slot's
// buffer. A large idle slot whose transfer is done goes; a busy, recent, small or empty one stays; 0 ms turns it off;
// malformed settings fall back to the defaults. No GPU, no device.
#include "../src/title_upload_trim.h"

#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <initializer_list>

#define EXPECT(condition) do { \
if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
} while (0)

namespace {

namespace tt = leonida::title_upload_trim;
constexpr std::uint64_t kMiB = 1 << 20;
constexpr std::uint64_t kMs = 1000 * 1000;

int defaults() {
const tt::Settings s = tt::settings_from(nullptr, nullptr);
EXPECT(s.enabled());
EXPECT(s.idle_ns == 2000 * kMs);
EXPECT(s.keep_bytes == 4 * kMiB);
return 0;
}

int rule() {
const tt::Settings s = tt::settings_from(nullptr, nullptr);
const std::uint64_t t0 = 10'000 * kMs;
// 64 MiB, done, idle exactly the limit and past it: released.
EXPECT(tt::release(64 * kMiB, t0, t0 + 2000 * kMs, true, s));
EXPECT(tt::release(64 * kMiB, t0, t0 + 60'000 * kMs, true, s));
// Idle for less than the limit: kept.
EXPECT(!tt::release(64 * kMiB, t0, t0 + 1999 * kMs, true, s));
// Its transfer is still running: kept however long ago it was used.
EXPECT(!tt::release(64 * kMiB, t0, t0 + 60'000 * kMs, false, s));
// At or under the size kept: kept; one byte over: released.
EXPECT(!tt::release(4 * kMiB, t0, t0 + 60'000 * kMs, true, s));
EXPECT(tt::release(4 * kMiB + 1, t0, t0 + 60'000 * kMs, true, s));
// Nothing allocated: nothing to release.
EXPECT(!tt::release(0, t0, t0 + 60'000 * kMs, true, s));
// A clock that reads earlier than the last use (another thread stamped it after `now` was read): kept.
EXPECT(!tt::release(64 * kMiB, t0, t0 - 1, true, s));
return 0;
}

int settings() {
// 0 ms: never released, the behaviour before the trim.
const tt::Settings off = tt::settings_from("0", nullptr);
EXPECT(!off.enabled());
EXPECT(!tt::release(1024 * kMiB, 0, UINT64_MAX, true, off));
// Values are read as given.
const tt::Settings s = tt::settings_from("500", "0");
EXPECT(s.idle_ns == 500 * kMs);
EXPECT(s.keep_bytes == 0);
EXPECT(tt::release(1, 0, 500 * kMs, true, s));
// Malformed or empty: the defaults.
for (const char* bad : {"", "-1", "2s", "1e3", " 5", "99999999999999999999999"}) {
const tt::Settings d = tt::settings_from(bad, bad);
EXPECT(d.idle_ns == 2000 * kMs);
EXPECT(d.keep_bytes == 4 * kMiB);
}
// Large but valid values saturate instead of wrapping.
const tt::Settings big = tt::settings_from("18446744073709551615", "18446744073709551615");
EXPECT(big.idle_ns == UINT64_MAX);
EXPECT(big.keep_bytes == UINT64_MAX);
EXPECT(!tt::release(1024 * kMiB, 0, UINT64_MAX - 1, true, big));
return 0;
}

// Only an upload over the size kept stamps the slot: small uploads going round the ring must not keep a large
// buffer alive (lixonik's review of #2463).
int uses() {
const tt::Settings s = tt::settings_from(nullptr, nullptr);
EXPECT(!tt::counts_as_use(1, s));
EXPECT(!tt::counts_as_use(4 * kMiB, s));
EXPECT(tt::counts_as_use(4 * kMiB + 1, s));
EXPECT(tt::counts_as_use(64 * kMiB, s));
// A 64 MiB slot last stamped by a large upload, then carrying 1 MiB uploads every 0.5 s: they do not stamp it,
// so 2 s after the large one it is released.
const std::uint64_t large_at = 1000 * kMs;
std::uint64_t last = large_at;
for (std::uint64_t t = large_at + 500 * kMs; t <= large_at + 2000 * kMs; t += 500 * kMs)
if (tt::counts_as_use(1 * kMiB, s)) last = t;
EXPECT(tt::release(64 * kMiB, last, large_at + 2000 * kMs, true, s));
return 0;
}

// Both variables are read, each copied before the next getenv.
int environment() {
#if defined(_WIN32)
_putenv_s("LEONIDA_TITLE_UPLOAD_IDLE_MS", "750");
_putenv_s("LEONIDA_TITLE_UPLOAD_KEEP_MB", "16");
#else
setenv("LEONIDA_TITLE_UPLOAD_IDLE_MS", "750", 1);
setenv("LEONIDA_TITLE_UPLOAD_KEEP_MB", "16", 1);
#endif
const tt::Settings s = tt::settings_from_env();
EXPECT(s.idle_ns == 750 * kMs);
EXPECT(s.keep_bytes == 16 * kMiB);
return 0;
}

} // namespace

int main() {
if (defaults() || rule() || settings() || uses() || environment()) return 1;
std::puts("title_upload_trim_test: ok");
return 0;
}
Loading