Triforce v0.9.1

The 16 GB update: idle memory unlocked and handed back to Windows while playing, empty pages under freed locks returned, and a page-file check at launch that warns before a too-small page file can crash the game.
This commit is contained in:
ruckus7382sfgsgdf
2026-12-01 17:47:00 -06:00
parent 822ee913bc
commit dad28e2d4b
11 changed files with 802 additions and 7 deletions

View File

@@ -57,6 +57,7 @@
#include "table_stream.h" // ((Triforce, 11-22, SYNC-04) the page table's changes streamed into 64 KiB transfers, RX_VK_TABLE_STREAM)
#include "range_walk.h" // ((Triforce, 11-22, MEM-42) a loop's pages asked of a sorted range list by a forward cursor, RX_VK_RANGE_WALK)
#include "piece_idle.h" // ((Triforce, 11-22, MEM-26's first step) what the mirrors' pieces hold that no game pool covers: counted
#include "ram_census.h" // ((Triforce, 12-01) what the GPU does with the imported memory, RX_VK_RAM_CENSUS=1
#include "late_inline.h" // ((Triforce, 11-22, MEM-80) the late pages' partial rule alone, RX_VK_LATE_INLINE
#include "retired_give_back.h" // ((Triforce, 11-22, MEM-21) a retired pool's import given back after a wait, RX_VK_KEEP_RETIRED=wait
#include "msync_pass.h" // ((Triforce, 11-21, MEM-48) a mirror sync's pages from the captures in one compute dispatch
@@ -114,6 +115,8 @@ struct Pool {
uint64_t up_value = 0;
uint8_t up_kinds = 0;
uint64_t last_value = 0; // (the newest submission that bound it: its mirror is in use until that one is done)
uint64_t bound_value = 0; // ((Triforce, 12-01) the newest submission a BUFFER binding reached it in: not a texture's upload
// (gpu_buffer), which stamps last_value alone. 0: never bound so far (imports_idle_give_back)
uint64_t imported_value = 0; // (Triforce: the recording being made when this import went into the table: imports_give_back)
uint64_t direct_write_epoch = 0; // (the part that last wrote it in guest memory, before it had a mirror)
uint64_t retired_value = 0; // (retired: the submission that may still use it)
@@ -199,6 +202,17 @@ struct GuestPool {
std::vector<GuestPool> guest_pools; // by lo, from the host
std::atomic<uint64_t> guest_pools_gen{1}; // (bumped when that table is replaced: a span cached without the lock goes stale)
std::map<uint64_t, Pool> imported; // by lo, made on first use
// ((Triforce, 12-01) the ranges whose imports' memory was freed, for the host's give-back of the zero pages in them
// (host/hos_mem.c hos_mem_zero_give_back, through mkwvk_freed_ranges below). An import commits its whole range and reads every
// page of it first (import_pool), and those pages stayed committed after it went: in the 12-01 lab runs the game's window held
// 9.3-9.8 GB committed where the game had been handed ~5.0-5.2 GB. freed_mu alone; at most 65,536 ranges waiting)
std::mutex freed_mu;
std::vector<std::pair<uint64_t, uint64_t>> freed_ranges;
void freed_note(uint64_t lo, uint64_t hi) {
if (hi <= lo || hi > (1ull << 40)) return;
std::lock_guard lk(freed_mu);
if (freed_ranges.size() < 65536) freed_ranges.push_back({lo, hi});
}
Pool* last_pool = nullptr; // (the last pool_of hit: draws in a row bind buffers of the same pools)
extern Pool* pool_cache[4096];
void retire_pool(std::map<uint64_t, Pool>::iterator it);
@@ -5571,6 +5585,7 @@ void bg_drain() {
destroy_import_buffer(p.buffer);
vkFreeMemory(dev.device, p.memory, nullptr);
for (VkDeviceMemory m : p.pieces) vkFreeMemory(dev.device, m, nullptr);
freed_note(p.lo, p.hi); // ((Triforce, 12-01) the host's zero give-back; an import over it refuses it)
continue;
}
bool overlap = false; // (amd-fix: a chunk imported ahead that an import made since covers in part: the pools stay disjoint)
@@ -5595,6 +5610,7 @@ void bg_drain() {
destroy_import_buffer(p.buffer);
vkFreeMemory(dev.device, p.memory, nullptr);
for (VkDeviceMemory m : p.pieces) vkFreeMemory(dev.device, m, nullptr);
freed_note(p.lo, p.hi); // ((Triforce, 12-01) the host's zero give-back)
continue;
}
if (imp != imported.end()) retire_pool(imp);
@@ -5951,7 +5967,8 @@ Pool* pool_lookup(uint64_t guest, uint64_t size) {
for (uint64_t k : overlapped) { // (the pools it took in)
auto o = imported.find(k);
if (o != imported.end()) // (their mirrors' contents come with them)
p.gpu_only |= o->second.gpu_only, p.gpu_written |= o->second.gpu_written, retire_pool(o);
p.gpu_only |= o->second.gpu_only, p.gpu_written |= o->second.gpu_written,
p.bound_value = std::max(p.bound_value, o->second.bound_value), retire_pool(o); // ((Triforce, 12-01) bound_value too)
}
p.imported_value = mem_rec_value;
imp = imported.emplace(p.lo, p).first;
@@ -7576,6 +7593,66 @@ static void bind_span_report() { // (every 600 submissions)
l_hits = h, l_misses = m, l_fills = f;
}
// ((Triforce, 12-01) the RAM census, RX_VK_RAM_CENSUS=1 (ram_census.h): every import and what the GPU did with its pages, into
// triforce_ram_census.txt beside the exe, and one log line of the totals over the imports' union. The memory line's thread)
void ram_census_report() {
if (!ram_census::on()) return;
struct Imp { uint64_t lo, hi; uint8_t mstate; bool mpieces, retired, gpu_only; };
std::vector<Imp> imps;
{
std::lock_guard lk(pools_mu);
imps.reserve(imported.size());
for (const auto& [lo, p] : imported)
imps.push_back({p.lo, p.hi, (uint8_t)p.mstate, p.mpieces, p.retired_value != 0, p.gpu_only});
}
static int n_report = 0;
n_report++;
char exe[MAX_PATH];
const DWORD n = game_module_path(exe, MAX_PATH);
std::string dir(exe, n);
const std::string path = dir.substr(0, dir.find_last_of("\/") + 1) + "triforce_ram_census.txt";
FILE* out = fopen(path.c_str(), "w");
auto mb = [](uint64_t b) { return (double)b / (1 << 20); };
if (out)
fprintf(out, "# RAM census %d (RX_VK_RAM_CENSUS): one import a line, MB: lo hi total narrow wide_only tex_only target_only "
"tex_and_wide written none mirror(0 none 1 wanted 2 on 3 refused) pieces retired gpu_only\n", n_report);
for (const Imp& i : imps) {
ram_census::Count c;
ram_census::count(i.lo, i.hi, &c);
if (out)
fprintf(out, "%#llx %#llx %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f %d %d %d %d\n", (unsigned long long)i.lo,
(unsigned long long)i.hi, mb(c.total), mb(c.narrow), mb(c.wide_only), mb(c.tex_only), mb(c.target_only),
mb(c.tex_and_wide), mb(c.written), mb(c.none), i.mstate, i.mpieces, i.retired, i.gpu_only);
}
// (the totals over the union: imports may overlap)
std::vector<std::pair<uint64_t, uint64_t>> u;
for (const Imp& i : imps) u.push_back({i.lo, i.hi});
std::sort(u.begin(), u.end());
std::vector<std::pair<uint64_t, uint64_t>> m;
for (const auto& r : u)
if (!m.empty() && r.first <= m.back().second) m.back().second = std::max(m.back().second, r.second);
else m.push_back(r);
ram_census::Count t;
for (const auto& r : m) ram_census::count(r.first, r.second, &t);
// (and every page a texture or a binding reached, imported or not)
uint64_t all[ram_census::kKinds] = {};
for (int k = 0; k < ram_census::kKinds; k++) {
const auto* b = ram_census::maps().bits[k].get();
for (uint64_t w = 0; w < ram_census::kWords; w++) all[k] += (uint64_t)std::popcount(b[w].load(std::memory_order_relaxed));
}
char line[640];
snprintf(line, sizeof line,
"vk: RAM census %d: %zu imports, %.0f MB in their union (%zu runs): a narrow binding reached %.0f, only wide ones %.0f, "
"textures' storage alone %.0f, render targets' alone %.0f, textures' that only a wide binding reached %.0f, nothing %.0f; "
"GPU-written %.0f. Every page reached, imported or not (MB): narrow bindings %llu, wide %llu, written %llu, "
"textures %llu, targets %llu",
n_report, imps.size(), mb(t.total), m.size(), mb(t.narrow), mb(t.wide_only), mb(t.tex_only), mb(t.target_only),
mb(t.tex_and_wide), mb(t.none), mb(t.written), (unsigned long long)(all[0] >> 4), (unsigned long long)(all[1] >> 4),
(unsigned long long)(all[2] >> 4), (unsigned long long)(all[3] >> 4), (unsigned long long)(all[4] >> 4));
logf("%s", line);
if (out) fprintf(out, "# %s\n", line), fclose(out);
}
BufferRef gpu_buffer_bind(uint64_t gpu, uint64_t size, bool written) {
if (written) texture_gpu_wrote(gpu, size), st_binds_written.fetch_add(1, std::memory_order_relaxed);
// ((Triforce, 11-27) not again for RX_VK_BIND_SPAN=check's whole way of a span's hit: the outer call noted it)
@@ -7589,6 +7666,7 @@ BufferRef gpu_buffer_bind(uint64_t gpu, uint64_t size, bool written) {
guest = host->gpu_guest(gpu);
}
if (deferred_late_n.load(std::memory_order_relaxed)) late_deferred_bound(guest, size); // (Triforce: a page put off, bound now)
if (ram_census::on()) ram_census::bind(guest, size, written); // ((Triforce, 12-01) the RAM census, ram_census.h)
if (written && trace_on() && trace_range(guest & ~4095ull)) // ((Triforce, 11-26, diagnostics) the writer's binding
logf("vk: trace write bind %#llx +%#llx: recording %llu, segment %llu, recordings submitted %llu, at %.3f ms", (unsigned long long)guest,
(unsigned long long)size, (unsigned long long)mem_rec_value, (unsigned long long)texture_segment(),
@@ -7647,6 +7725,7 @@ BufferRef gpu_buffer_bind(uint64_t gpu, uint64_t size, bool written) {
Pool* p = tl.p;
const uint64_t off = guest - p->lo;
if (p->last_value < mem_rec_value) p->last_value = mem_rec_value;
if (p->bound_value < mem_rec_value) p->bound_value = mem_rec_value; // ((Triforce, 12-01) imports_idle_give_back)
__atomic_fetch_add(&p->binds, 1u, __ATOMIC_RELAXED);
if (mirror_heat_on()) __atomic_fetch_add(&p->heat, Pool::heat_of(size), __ATOMIC_RELAXED); // ((Triforce) mirrors_by_heat)
if (mirror_use_on()) mirror_use_note(p, off, size);
@@ -7699,6 +7778,7 @@ BufferRef gpu_buffer_bind(uint64_t gpu, uint64_t size, bool written) {
if (!p) return {};
tl = {p, pools_gen.load(std::memory_order_relaxed)};
if (p->last_value < mem_rec_value) p->last_value = mem_rec_value;
if (p->bound_value < mem_rec_value) p->bound_value = mem_rec_value; // ((Triforce, 12-01) imports_idle_give_back)
__atomic_fetch_add(&p->binds, 1u, __ATOMIC_RELAXED);
if (mirror_heat_on()) __atomic_fetch_add(&p->heat, Pool::heat_of(size), __ATOMIC_RELAXED); // ((Triforce) mirrors_by_heat)
const uint64_t off = guest - p->lo;
@@ -7993,6 +8073,7 @@ void reap_mirrors() { // (pools_mu held)
destroy_import_buffer(dead_imports.front().buffer);
vkFreeMemory(dev.device, dead_imports.front().memory, nullptr);
for (VkDeviceMemory m : dead_imports.front().pieces) vkFreeMemory(dev.device, m, nullptr);
freed_note(dead_imports.front().lo, dead_imports.front().hi); // ((Triforce, 12-01) the host's zero give-back)
st_retired_imports_freed++, st_retired_import_bytes_freed += dead_imports.front().bytes;
dead_import_bytes -= std::min(dead_import_bytes, dead_imports.front().bytes); // ((Triforce, 11-22, MEM-21))
dead_imports.pop_front();
@@ -8484,14 +8565,77 @@ int64_t st_imports_evicted = 0;
uint64_t st_import_bytes_evicted = 0;
constexpr uint64_t kImportIdle = 600;
// ---- ((Triforce, 12-01) imports given back when idle, whatever the RAM: RX_VK_IMPORT_IDLE (on; =0 off). An import is the game's
// memory locked in RAM by the driver: Windows can neither trim it nor page it out. The RAM census of 12-01 (ram_census.h, his
// save, walking): 5,712 MB imported, of which the GPU's buffer bindings reached 690 MB; texture storage alone 1,285 MB (read
// once, at the texture's upload: the GPU unswizzle's gpu_buffer), nothing at all 3,737 MB (whole pools imported for a texture
// and ranges imported ahead from earlier runs). The rule above gives imports back only past 85% of the system heap's budget
// (about half the PC's RAM): on a 16 GB PC some 6 GB stay locked while the PC pages everything else. Here, every 16
// submissions, an import without a mirror that is done on the GPU goes back
// - never reached by a buffer binding (bound_value 0: a texture's storage, a range imported ahead), once nothing has used it
// for RX_VK_IMPORT_IDLE_UNBOUND submissions (2400, ~3-4 s of play at ~8 recordings a frame);
// - bound, once no binding has reached it for RX_VK_IMPORT_IDLE_BOUND submissions (21600, ~30 s).
// It is imported again at its next use, as one the rule above gave back. (Caveat, the same as above: shaders reaching a pool only
// through the page table are not seen; such a pool reads zeros until it is bound again) ----
int64_t st_idle_given = 0;
uint64_t st_idle_given_bytes = 0, st_idle_given_unbound = 0;
void imports_idle_give_back() { // (pools_mu held)
static const bool on = !(getenv("RX_VK_IMPORT_IDLE") && atoi(getenv("RX_VK_IMPORT_IDLE")) == 0);
static const uint64_t idle_unbound = getenv("RX_VK_IMPORT_IDLE_UNBOUND") ? (uint64_t)std::max(1, atoi(getenv("RX_VK_IMPORT_IDLE_UNBOUND"))) : 2400;
static const uint64_t idle_bound = getenv("RX_VK_IMPORT_IDLE_BOUND") ? (uint64_t)std::max(1, atoi(getenv("RX_VK_IMPORT_IDLE_BOUND"))) : 21600;
static uint64_t calls = 0;
if (!on || ++calls % 16) return;
static bool told = false;
if (!told) {
told = true;
logf("vk: imports given back when idle: never bound past %llu submissions, bound past %llu (RX_VK_IMPORT_IDLE=0: off)",
(unsigned long long)idle_unbound, (unsigned long long)idle_bound);
}
int n = 0, unbound = 0;
uint64_t freed = 0;
for (auto it = imported.begin(); it != imported.end();) {
Pool& p = it->second;
const bool no_mirror = p.mstate == Pool::MIRROR_NONE || p.mstate == Pool::MIRROR_REFUSED;
const uint64_t used = std::max(p.last_value, p.imported_value);
const bool idle = p.bound_value ? mem_rec_value > std::max(used, p.bound_value) + idle_bound
: mem_rec_value > used + idle_unbound;
if (!no_mirror || p.last_value > mem_completed || !idle || n >= 64) {
++it;
continue;
}
const auto next = std::next(it);
lazy_settle(p.lo, p.hi, wb_lazy::BY_GIVEUP);
guest_pages_set(p.lo, p.hi, 0);
p.retired_value = mem_rec_value; // (freed once this recording is done: imports_give_back)
freed += p.hi - p.lo;
unbound += !p.bound_value;
n++;
evicted_pools.push_back(imported.extract(it));
it = next;
}
if (!n) return;
pools_gen++;
last_pool = nullptr;
std::fill(std::begin(pool_cache), std::end(pool_cache), nullptr);
if (mirror_on()) publish_cap_ranges();
st_idle_given += n, st_idle_given_bytes += freed, st_idle_given_unbound += unbound;
static int logged;
if (logged++ < 40 || logged % 64 == 0)
logf("vk: %d idle imports given back (%llu MB, %d never bound); %lld (%llu MB, %llu never bound) in all, %zu imported now",
n, (unsigned long long)(freed >> 20), unbound, (long long)st_idle_given, (unsigned long long)(st_idle_given_bytes >> 20),
(unsigned long long)st_idle_given_unbound, imported.size());
}
void imports_give_back() { // (pools_mu held)
while (!evicted_pools.empty() && evicted_pools.front().mapped().retired_value <= mem_completed) {
Pool& p = evicted_pools.front().mapped();
destroy_import_buffer(p.buffer);
vkFreeMemory(dev.device, p.memory, nullptr);
for (VkDeviceMemory m : p.pieces) vkFreeMemory(dev.device, m, nullptr); // (a pool imported as several dma-bufs)
freed_note(p.lo, p.hi); // ((Triforce, 12-01) the host's zero give-back)
evicted_pools.pop_front();
}
imports_idle_give_back(); // ((Triforce, 12-01) whatever the RAM, above)
// (hookshot) Off by default on Windows, as giving retired imports back is (RX_VK_KEEP_RETIRED, retired_imports_give_back:
// device losses on Intel Arc and AMD right after imports went back): RX_VK_IMPORT_HIGH=85 turns it on there
// (Triforce, 2026-11-11) On by default on Windows too where the memory handling is on (memory_trial_on: NVIDIA cards, which
@@ -10200,6 +10344,35 @@ bool sample_parts(mem_parts::Parts* p, LineCost* c) {
void memory_parts_line() {
static const bool on = !(getenv("RX_VK_MEM_PARTS") && atoi(getenv("RX_VK_MEM_PARTS")) == 0);
if (!on) return;
#ifdef _WIN32
{ // ((Triforce, 12-01, lab only) RX_VK_TEST_TRIM_AT=<s>[,<s>...]: the process's working set emptied once at each of those seconds
// of the run (K32EmptyWorkingSet), so that the lines after it show what play brings back in: the floor a PC short of RAM
// must hold. What the driver locks (imports) cannot leave: the line's working set never goes below it)
static const char* at = getenv("RX_VK_TEST_TRIM_AT");
static const auto t0 = std::chrono::steady_clock::now();
static int done = 0;
if (at) {
const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
int k = 0;
for (const char* c = at; *c;) {
const double want = atof(c);
if (k == done && sec >= want) {
uint64_t ws0 = 0, pv = 0, ws1 = 0;
memory_process(&ws0, &pv);
K32EmptyWorkingSet(GetCurrentProcess());
memory_process(&ws1, &pv);
logf("vk: lab: the working set emptied at %.0f s (RX_VK_TEST_TRIM_AT): %llu -> %llu MB", sec,
(unsigned long long)(ws0 >> 20), (unsigned long long)(ws1 >> 20));
done++;
break;
}
k++;
while (*c && *c != ',') c++;
if (*c == ',') c++;
}
}
}
#endif
const auto t0 = std::chrono::steady_clock::now();
mem_parts::Parts p;
LineCost c;
@@ -10241,6 +10414,7 @@ void memory_line_ask() {
}
try {
memory_parts_line();
ram_census_report(); // ((Triforce, 12-01) RX_VK_RAM_CENSUS only)
} catch (const std::exception& e) {
logf("vk: the memory line failed: %s", e.what());
}
@@ -10368,6 +10542,28 @@ void memory_ram_watch(uint64_t presents) {
/// can take the pages between the question and the decommit ("decommitted pages under an import faulted the device"; the owner's
/// test11 and test12, tests/test_bg_import_held.py). -1: held, not given back; else release's answer (1 given back, 0 refused: a
/// page handed out again meanwhile). tests/test_guest_release.py
/// ((Triforce, 12-01) The freed ranges waiting (freed_note), joined where they touch, at most max of them into out; the rest wait
/// for the next ask. The count given
int freed_take(uint64_t (*out)[2], int max) {
std::vector<std::pair<uint64_t, uint64_t>> all;
{
std::lock_guard lk(freed_mu);
all.swap(freed_ranges);
}
if (all.empty() || max <= 0) return 0;
std::sort(all.begin(), all.end());
std::vector<std::pair<uint64_t, uint64_t>> m;
for (const auto& r : all)
if (!m.empty() && r.first <= m.back().second) m.back().second = std::max(m.back().second, r.second);
else m.push_back(r);
int n = 0;
for (; n < (int)m.size() && n < max; n++) out[n][0] = m[n].first, out[n][1] = m[n].second;
if (n < (int)m.size()) {
std::lock_guard lk(freed_mu);
freed_ranges.insert(freed_ranges.end(), m.begin() + n, m.end());
}
return n;
}
int guest_release_unimported(uint64_t lo, uint64_t hi, int (*release)(uint64_t, uint64_t)) {
std::lock_guard lk(pools_mu);
auto it = imported.lower_bound(hi); // (pools by lo: those starting below hi, the last ones checked first)
@@ -10461,6 +10657,16 @@ __attribute__((visibility("default")))
int mkwvk_guest_release(uint64_t lo, uint64_t hi, int (*release)(uint64_t, uint64_t)) {
return release && hi > lo ? mkwvk::guest_release_unimported(lo, hi, release) : 0;
}
// ((Triforce, 12-01) host/rx_backend.c's rx_freed_ranges, found by name: the ranges whose imports were freed (freed_take)
extern "C"
#ifdef _WIN32
__declspec(dllexport)
#else
__attribute__((visibility("default")))
#endif
int mkwvk_freed_ranges(uint64_t (*out)[2], int max) {
return out ? mkwvk::freed_take(out, max) : 0;
}
extern "C"
#ifdef _WIN32
__declspec(dllexport)