Merge remote-tracking branch 'origin/dev' into pr/v110-patch-parity

This commit is contained in:
shenjack committed 2026-11-10 13:39:41 +08:00
commit ec62494bd9
31 files changed
+1297 -105

No files matched your search

+6 -5
View File
@@ -47,7 +47,7 @@ static const char *const known[] = {
"FULLSCREEN", "FXAA", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HDR", "HDR_GAME_NITS", "HDR_HUE",
"HDR_PEAK_NITS", "HDR_UI_NITS", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "KSPIN_US", "LANG", "LIB_PREBUILD",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "LSTICK_DEADZONE", "MEMORY", "MENU_LANG", "MENU_TEST",
"MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MODS_REBUILD", "MOTION", "MOUSE_AIM_SCALE", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_ASPECT", "MOVIE_HOST", "MOVIE_PACE",
"MEM_RESERVE_MIB", "MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MODS_REBUILD", "MOTION", "MOUSE_AIM_SCALE", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_ASPECT", "MOVIE_HOST", "MOVIE_PACE",
"MVOBJ_ALL", "MVOBJ_BANKS", "MVOBJ_EQUAL", "MVOBJ_EXACT", "MVOBJ_EXEC", "MVOBJ_NOC4", "MVOBJ_ONLY", "MVOBJ_TIMES", "MVPREV_CHECK", "MVPREV_GROW", "MVPREV_SKIP", "MVPREV_TRUST", "MV_CHECK",
"MV_SURVEY",
"ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_SCENE", "PCORE", "PCSS", "PCSS_K", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT",
@@ -59,8 +59,8 @@ static const char *const known[] = {
"SHADER_MEMO", "SHADOW_RANGE", "SHADOW_RES", "SHADOW_SCALE", "SHADOW_SNAP", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR",
"SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "STICK_SENS",
"SWKBD_ANSWER",
"SWKBD_TEST", "TEST_PAD", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_HEAP_EXTRA_MB", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "UB_OVERLAY", "UB_OVERLAY_OUT", "UPSCALER", "VB_USED", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64",
"VK_PRESENT", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VOLUME", "VRAM_HEADROOM", "VRAM_LIMIT_MIB", "VS_OUTS",
"SWKBD_TEST", "TEST_OOM", "TEST_PAD", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_BLOCK_MIB", "TEX_HEAP_EXTRA_MB", "TEX_MEMO", "TEX_RELEASED_MIB", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "UB_OVERLAY", "UB_OVERLAY_OUT", "UPSCALER", "VB_USED", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64",
"VK_PRESENT", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VMA_BLOCK_MIB", "VOLUME", "VRAM_HEADROOM", "VRAM_LIMIT_MIB", "VS_OUTS",
"WALK_KEY", "WALK_SCALE", "WB_EXACT", "WB_FENCE_LIMIT", "WB_MERGE", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_KEEP", "XLATE_PROCS",
"ZSTD_CHECK", "ZSTD_NATIVE",
};
@@ -99,7 +99,7 @@ static const struct { const char *key, *section; } sections[] = {
{"TIMER_1MS", "performance"}, {"PIPE_WAIT", "performance"}, {"PIPE_SKIP", "performance"},
{"LIB_PREBUILD", "performance"}, {"LIB_PREBUILD_THREADS", "performance"}, {"PIPE_PREBUILD", "performance"},
{"PREWARM_XLATE", "performance"}, {"GPL", "performance"}, {"ASTC", "performance"}, {"MEMORY", "performance"},
{"TEX_ALIAS", "performance"}, {"TEX_VRAM_PRESSURE", "performance"}, {"ASTC_BC", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"},
{"TEX_ALIAS", "performance"}, {"TEX_VRAM_PRESSURE", "performance"}, {"TEX_RELEASED_MIB", "performance"}, {"TEX_BLOCK_MIB", "performance"}, {"VMA_BLOCK_MIB", "performance"}, {"ASTC_BC", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"},
{"BIND_SKIP", "performance"}, {"SHADER_MEMO", "performance"}, {"PIPE_MEMO", "performance"}, {"TEX_MEMO", "performance"}, {"VB_USED", "performance"}, {"DESC_TEMPLATE", "performance"},
{"PUSH_SKIP", "performance"}, {"SPLIT_DRAWS", "performance"}, {"SPLIT_US", "performance"}, {"VK_VALIDATION", "performance"},
{"VK_DYN_VERTEX", "performance"}, {"VK_DYN_A2C", "performance"}, {"VK_SUBGROUP_PIN", "performance"},
@@ -173,7 +173,8 @@ static const CfgMeta metas[] = {
{"PIPE_PREBUILD", "1", "0|1", RESTART}, {"PREWARM_XLATE", "", "1..64", RESTART}, {"GPL", "1", "0|1", RESTART},
// textures and memory
{"ASTC", "auto", "auto|gpu|native|cpu", RESTART}, {"MEMORY", "auto", "auto|import|mirror|verify", RESTART},
{"TEX_ALIAS", "1", "0|1", RESTART}, {"TEX_VRAM_PRESSURE", "90", "0..100", RESTART}, {"ASTC_BC", "", "0|1", RESTART}, {"ZSTD_NATIVE", "1", "0|1", RESTART}, {"ZSTD_CHECK", "0", "0|1", RESTART},
{"TEX_ALIAS", "1", "0|1", RESTART}, {"TEX_VRAM_PRESSURE", "90", "0..100", RESTART},
{"TEX_RELEASED_MIB", "256", "0..65536", RESTART}, {"TEX_BLOCK_MIB", "64", "0..1024", RESTART}, {"VMA_BLOCK_MIB", "64", "0..1024", RESTART}, {"ASTC_BC", "", "0|1", RESTART}, {"ZSTD_NATIVE", "1", "0|1", RESTART}, {"ZSTD_CHECK", "0", "0|1", RESTART},
// render fixes
{"LOD_GUARD", "1", "0|1", RESTART}, {"FIX_C0", "1", "0|1", RESTART}, {"FIX_ZERO", "1", "0|1", RESTART},
{"BIND_SKIP", "1", "0|1", RESTART}, {"SHADER_MEMO", "1", "0|1", RESTART}, {"PIPE_MEMO", "1", "0|1", RESTART}, {"TEX_MEMO", "1", "0|1", RESTART},
+17
View File
@@ -175,6 +175,23 @@ int mem_guest_readable(uint64_t a, uint64_t n); // [a, a+n) can be re
// module or the committed heap answered from the layout,
// anything else by plat_mem_readable (an OS query)
// ---- short out-of-memory spells (oom.c)
enum { RT_OOM_COMMIT, RT_OOM_STAGING, RT_OOM_IMAGE, RT_OOM_CHUNK, RT_OOM_SITES };
extern volatile int32_t rt_oom_req; // set by rt_oom_request; vk_texture_new_submit takes it
void rt_oom_request(void); // asks the Vulkan back end to give memory back at its next
// submit (released textures, headroom blocks); any thread,
// any lock held
int rt_oom_wait(const char *what, uint64_t bytes, int (*retry)(void *arg), void *arg);
// after a failed allocation: requests a release, then calls
// retry every 10 ms for up to 30 s; 1 once retry returned 1,
// 0 after the wait (the caller ends the game). Logs the
// first 8 with the commit numbers
void *rt_realloc_wait(void *old, size_t n, const char *what); // realloc, NULL only after rt_oom_wait gave up
int rt_oom_forced(int site); // 1: fail this attempt at site (TOTK_TEST_OOM=<site>:<n>,
// sites commit, staging, image, chunk; or rt_oom_force)
void rt_oom_force(int site, int n); // probes: fail the next n attempts at site
int rt_oom_forced_left(int site); // forced failures still to come at site
// ---- modules (loader.c)
typedef struct {
const char *name; uint64_t base, size, text_end, data_off; // text_end, data_off: offsets from base
+70
View File
@@ -682,6 +682,25 @@ static int cmp_u64(const void *a, const void *b) {
return x < y ? -1 : x > y;
}
// A refused commit waits and retries (memory.c commit, oom.c rt_oom_wait): three forced refusals, then the page maps.
static void test_oom_commit(void) {
const RtGuestLayout *g = mem_layout();
uint64_t a = g->alias.base + g->alias.size - 0x10000;
rt_oom_force(RT_OOM_COMMIT, 3);
uint64_t t0 = plat_now_ms();
uint32_t r = mem_map_physical(a, 0x1000);
uint64_t ms = plat_now_ms() - t0;
CHECK(r == 0 && rt_oom_forced_left(RT_OOM_COMMIT) == 0 && ms >= 20,
"MapPhysicalMemory after 3 refused commits: result %#x, %d refusals left, %llu ms", r,
rt_oom_forced_left(RT_OOM_COMMIT), (unsigned long long)ms);
rt_oom_force(RT_OOM_COMMIT, 0);
if (r == 0) {
*(volatile uint64_t *)(uintptr_t)a = 1;
CHECK(mem_unmap_physical(a, 0x1000) == 0, "UnmapPhysicalMemory after the refused commits");
}
printf("oom: commit waited %llu ms through 3 refusals\n", (unsigned long long)ms);
}
static void test_platform(void) {
PlatThread *t = plat_thread_new(plat_worker, (void *)(intptr_t)1, "probe-kernel plat");
CHECK(t, "plat_thread_new");
@@ -719,6 +738,49 @@ static void test_platform(void) {
CHECK(over[N / 2] < 500000, "plat_sleep_ns(1 ms) median overshoot %.3f ms (want < 0.5)", over[N / 2] / 1e6);
}
// ---- crash report (main.c crash_handler): a child faults on a guest thread with known values in rbx and x19; the
// report must hold the host registers, the faulting instruction's bytes and the memory both values point at.
#define CRASH_CHILD_ENV "TOTK_PROBE_KERNEL_CRASH_CHILD"
static uint64_t crash_host_words[6] = {0, 0, 0x5ca1ab1e0c0de001ull, 0, 0, 0};
static uint64_t crash_guest_words[6] = {0, 0, 0x5ca1ab1e0c0de002ull, 0, 0, 0};
static void crash_child_main(Cpu *c) {
c->x[19] = (uint64_t)(uintptr_t)&crash_guest_words[2];
c->sp -= 0x100; // a frame on the guest stack, as a crashing function has
__asm__ volatile("movq %0, %%rbx\n\tmovq 0x10, %%rax" : : "r"(&crash_host_words[2]) : "rax", "rbx", "memory");
}
// The report line that holds needle, NULL when none does
static const char *report_line(const char *out, const char *needle, char *line, size_t cap) {
const char *p = strstr(out, needle);
if (!p) return NULL;
while (p > out && p[-1] != '\n') p--;
size_t n = strcspn(p, "\r\n");
snprintf(line, cap, "%.*s", (int)(n < cap ? n : cap - 1), p);
return line;
}
static void test_crash_report(void) {
static char out[65536];
char line[512], want[64];
int code = plat_run_self(CRASH_CHILD_ENV, "1", out, sizeof out, 30000);
CHECK(code == 71 && strstr(out, "FATAL: access violation") && strstr(out, "reading address 0x10"),
"crash child: exit code %d, no access violation at 0x10 reported", code);
snprintf(want, sizeof want, "rbx %016llx", (unsigned long long)(uintptr_t)&crash_host_words[2]);
CHECK(strstr(out, want), "crash report: no host register line with %s", want);
CHECK(report_line(out, "host code at rip-", line, sizeof line) && strstr(line, "| 48 8b 04 25 10 00 00 00"),
"crash report: the faulting instruction's bytes are missing");
const char *h = report_line(out, "*5ca1ab1e0c0de001", line, sizeof line);
CHECK(h && strstr(h, "rbx"), "crash report: no memory line for rbx (%s)", h ? h : "none");
const char *g = report_line(out, "*5ca1ab1e0c0de002", line, sizeof line);
CHECK(g && strstr(g, "x19"), "crash report: no memory line for x19 (%s)", g ? g : "none");
CHECK(strstr(out, "guest stack sp+0x00:"), "crash report: no guest stack words");
CHECK(report_line(out, " memory commit: this process ", line, sizeof line) && !strstr(line, "process -1 MB"),
"crash report: no memory commit line");
printf("crash report: exit code %d, host registers, code bytes, memory at rbx and x19, guest stack, commit %s\n", code,
failures ? "checked with failures" : "present");
}
int probe_kernel(void) {
a_lock_waiter = hostfn_register("probe-kernel lock waiter", lock_waiter);
a_cv_waiter = hostfn_register("probe-kernel condvar waiter", cv_waiter);
@@ -742,7 +804,15 @@ int probe_kernel(void) {
printf("probe-kernel: FAILED (no PLT stub for %s in main)\n", TICK_SYMBOL);
return 1;
}
const char *child = getenv(CRASH_CHILD_ENV);
if (child && *child) {
kern_run_on_guest_main(crash_child_main);
printf("crash child: returned without a fault\n");
return 1;
}
test_platform();
test_oom_commit();
test_crash_report();
kern_run_on_guest_main(probe_main);
RtStats s = rt_stats();
printf("stats: %llu SVCs, %llu threads, %llu host calls\n", (unsigned long long)s.svcs,
+88 -5
View File
@@ -21,7 +21,8 @@
//
// Also here: the runtime services the generated code calls besides rt_dispatch and rt_svc (rt_brk, rt_udf,
// rt_ticks, the function profiler hook), logging, SHA-256, and the crash reporter (a vectored exception handler that
// names the lifted function, the guest registers and the guest frame-pointer chain).
// names the lifted function, the host and guest registers, the machine code around the fault, the guest frame-pointer
// chain and the memory the registers point at).
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
@@ -188,8 +189,8 @@ static int by_host(const void *a, const void *b) {
}
// The lifted function that contains a host code address, by the nearest function start below it; 0 outside the lifted
// code.
static uint64_t lifted_function(uintptr_t rip) {
// code. *host, when given, gets the function's host start.
static uint64_t lifted_function_at(uintptr_t rip, uintptr_t *host) {
if (!fn_rev) {
static RtModule mods[MAX_MODULES];
int n = rt_linked_modules(mods, MAX_MODULES);
@@ -211,11 +212,78 @@ static uint64_t lifted_function(uintptr_t rip) {
if (fn_rev[mid].host <= rip) lo = mid + 1;
else hi = mid;
}
if (lo && host) *host = fn_rev[lo - 1].host;
return lo ? fn_rev[lo - 1].guest : 0;
}
static uint64_t lifted_function(uintptr_t rip) { return lifted_function_at(rip, NULL); }
static int readable(uint64_t a, uint64_t n) { return plat_mem_readable(a, n); }
// The machine code around the faulting instruction: 32 bytes before rip, then 32 from rip. The user's totk.exe is built
// on their machine, so its offsets need not match ours; these bytes and the offset into the lifted function find the
// same instruction in a local build of that version, and with it the guest instruction and the operands' registers.
static void crash_code_bytes(uintptr_t rip) {
uint8_t b[64];
int before = 32;
if (!plat_mem_read(rip - 32, b, sizeof b)) {
before = 0; // rip near the start of a mapping: the bytes from rip only
if (!plat_mem_read(rip, b + 32, 32)) return;
}
rt_logf(" host code at rip-%d:", before);
for (int i = 32 - before; i < 64; i++) rt_logf("%s%02x", i == 32 ? " | " : " ", b[i]);
rt_log_raw("\n", 1);
}
// 64 bytes around each register value that points at readable memory, as 8-byte words from 16 bytes below the value,
// the word holding the value marked with *. Host and guest registers that land on the same window share a line. A
// guest pointer is a host address here (the guest address space is mapped one to one), so both kinds are read alike.
// The guest registers come from the Cpu, which the lifted code writes back only at calls and returns, so the host
// registers carry the faulting function's live values.
typedef struct { uint64_t start; char names[56]; uint64_t w[8]; } CrashWin;
static void crash_win_add(CrashWin *wins, int *n, int cap, const char *name, uint64_t v) {
if (v < 0x10000 || v > 0x00007fffffffffffull) return; // small integers and non-canonical values
uint64_t start = (v & ~7ull) - 16;
for (int i = 0; i < *n; i++)
if (wins[i].start == start) {
size_t len = strlen(wins[i].names);
if (len + strlen(name) + 2 < sizeof wins[i].names)
snprintf(wins[i].names + len, sizeof wins[i].names - len, " %s", name);
return;
}
if (*n == cap || !plat_mem_read(start, wins[*n].w, sizeof wins[*n].w)) return;
wins[*n].start = start;
snprintf(wins[*n].names, sizeof wins[*n].names, "%s", name);
(*n)++;
}
static void crash_memory(const PlatCrash *x, const Cpu *c) {
static CrashWin wins[64]; // the crash handler runs once (busy flag), so static storage needs no allocation
static const char *const gpr_names[16] = PLAT_GPR_NAMES;
int n = 0;
char name[8];
if (x->has_regs)
for (int i = 0; i < 16; i++) crash_win_add(wins, &n, 64, gpr_names[i], x->gpr[i]);
if (c) {
for (int i = 0; i < 31; i++) snprintf(name, sizeof name, "x%d", i), crash_win_add(wins, &n, 64, name, c->x[i]);
crash_win_add(wins, &n, 64, "sp", c->sp);
}
if (!n) return;
rt_logf(" memory at the register values (8-byte words from value-16, * the value's word):\n");
for (int i = 0; i < n; i++) {
rt_logf(" %016llx %-12s", (unsigned long long)wins[i].start, wins[i].names);
for (int k = 0; k < 8; k++) rt_logf(" %s%016llx", k == 2 ? "*" : "", (unsigned long long)wins[i].w[k]);
rt_log_raw("\n", 1);
}
// The guest stack above sp: the crashing function's spills and locals, and the callers' saved registers
uint64_t s[16];
if (c && plat_mem_read(c->sp, s, sizeof s))
for (int i = 0; i < 16; i += 4)
rt_logf(" guest stack sp+0x%02x: %016llx %016llx %016llx %016llx\n", i * 8, (unsigned long long)s[i],
(unsigned long long)s[i + 1], (unsigned long long)s[i + 2], (unsigned long long)s[i + 3]);
}
static void crash_handler(const PlatCrash *x) {
static volatile int32_t busy;
if (plat_xchg32(&busy, 1)) plat_exit(71);
@@ -230,8 +298,22 @@ static void crash_handler(const PlatCrash *x) {
rt_log_raw("\n", 1);
if (x->cxx_type)
rt_logf(" C++ type %s%s%s\n", x->cxx_type, x->cxx_what ? ", what(): " : "", x->cxx_what ? x->cxx_what : "");
uint64_t f = x->module ? 0 : lifted_function(rip);
if (f) rt_logf(" in lifted function f_%llx = %s\n", (unsigned long long)f, ldr_describe(f, d, sizeof d));
// A driver that runs out of memory faults or throws (std::bad_alloc) instead of returning an error: the commit
// tells that apart from a driver bug, as rt_fatal's line does for our own failed allocations.
double proc, used, limit;
plat_commit_info(&proc, &used, &limit);
rt_logf(" memory commit: this process %.0f MB, the system %.0f of %.0f MB\n", proc, used, limit);
uintptr_t fstart = 0;
uint64_t f = x->module ? 0 : lifted_function_at(rip, &fstart);
if (f)
rt_logf(" in lifted function f_%llx = %s, host +%#llx into it\n", (unsigned long long)f,
ldr_describe(f, d, sizeof d), (unsigned long long)(rip - fstart));
if (x->has_regs) {
static const char *const gpr_names[16] = PLAT_GPR_NAMES;
for (int i = 0; i < 16; i++)
rt_logf(" %-3s %016llx%s", gpr_names[i], (unsigned long long)x->gpr[i], i % 4 == 3 ? "\n" : "");
crash_code_bytes(rip);
}
// abort and invalid parameter: where the host code called it; a fault in another module: the driver code and the
// host calls that led into it
uintptr_t exe = plat_exe_base();
@@ -266,6 +348,7 @@ static void crash_handler(const PlatCrash *x) {
} else {
rt_logf(" not on a guest thread\n");
}
crash_memory(x, c);
kern_free_cores_note();
fflush(stderr);
plat_exit(71);
+21 -4
View File
@@ -175,12 +175,29 @@ static int thaw_fault(uint64_t a) {
}
// Mapping changes thaw the regions they touch and run under frz_lock, so no freeze sees them half done.
static void commit(uint64_t a, uint64_t n, const char *what) {
typedef struct { uint64_t a, n; } CommitTry;
static int commit_try(void *arg) {
const CommitTry *t = arg;
if (rt_oom_forced(RT_OOM_COMMIT)) return 0;
plat_mutex_lock(&frz_lock);
thaw_range_locked(a, n, 3);
int ok = !n || plat_mem_commit(a, n);
thaw_range_locked(t->a, t->n, 3);
int ok = !t->n || plat_mem_commit(t->a, t->n);
plat_mutex_unlock(&frz_lock);
if (!ok) rt_fatal("memory: commit %s %#llx+%#llx failed", what, (unsigned long long)a, (unsigned long long)n);
return ok;
}
// A refused commit waits for memory (rt_oom_wait): the system's commit ran out for a moment (a page file growing, the
// driver's device memory charged to this process), and the Vulkan back end gives memory back at its next submit. The
// wait holds the caller's lock (lock or klock: only memory SVCs and kernel-region allocations wait behind it) but not
// frz_lock, which write faults on frozen regions need. Every caller waits, the boot's ones too: there a refusal has the
// same cause, and the wait only delays an end the game would reach anyway.
static void commit(uint64_t a, uint64_t n, const char *what) {
CommitTry t = {a, n};
if (commit_try(&t)) return;
char w[64];
snprintf(w, sizeof w, "memory: commit of %s at %#llx", what, (unsigned long long)a);
if (!rt_oom_wait(w, n, commit_try, &t))
rt_fatal("memory: commit %s %#llx+%#llx failed", what, (unsigned long long)a, (unsigned long long)n);
}
static void decommit(uint64_t a, uint64_t n, const char *what) {
+1
View File
@@ -148,6 +148,7 @@ static void *realloc_wait(void *old, size_t n, const char *what) {
if (p) return p;
pool_drain();
big_drain();
rt_oom_request(); // the Vulkan back end gives memory back at its next submit (oom.c)
static uint32_t reports;
int report = __atomic_fetch_add(&reports, 1, __ATOMIC_RELAXED) < 8;
if (report) {
+106
View File
@@ -0,0 +1,106 @@
// Short out-of-memory spells: a failed allocation waits for memory instead of ending the game.
//
// Windows refuses commit beyond the current limit while it grows a system-managed page file, and on some drivers device
// memory counts as process commit (vk_memory.c vk_mem_host_probe), so for a moment every allocation of the process can
// fail and the same request succeeds a little later. The failure sites (memory.c commit, vk_memory.c vk_staging,
// vk_texture.c create_tex, vk_exec_draw.c transient chunks, nvn_api_cmd.c realloc_wait) ask the Vulkan back end to give
// memory back (rt_oom_request: released textures and headroom blocks, at its next submit, where its locks are free) and
// retry for up to OOM_WAIT_MS before they end the game.
//
// TOTK_TEST_OOM=<site>:<n>[,<site>:<n>...] (sites commit, staging, image, chunk) fails the first n attempts at a site, so
// the wait can be tested without running out of memory; the probes arm it with rt_oom_force.
#include <stdlib.h>
#include <string.h>
#include "cfg.h"
#include "host.h"
#include "platform/platform.h"
#define OOM_WAIT_MS 30000u
#define OOM_STEP_MS 10u
#define OOM_REPORTS 8
#define OOM_REQUEST_EVERY 100 // retries between two release requests: a second, since a release only frees what is old enough
volatile int32_t rt_oom_req;
static const char *const site_name[RT_OOM_SITES] = {"commit", "staging", "image", "chunk"};
static volatile int32_t force_left[RT_OOM_SITES];
static volatile int32_t forced_parsed;
static PlatOnce force_once = PLAT_ONCE_INIT;
static void force_parse(void *arg) {
(void)arg;
const char *s = cfg_get("TOTK_TEST_OOM");
while (s && *s) {
const char *colon = strchr(s, ':'), *end = strchr(s, ',');
if (!end) end = s + strlen(s);
if (colon && colon < end) {
for (int i = 0; i < RT_OOM_SITES; i++)
if ((size_t)(colon - s) == strlen(site_name[i]) && !strncmp(s, site_name[i], (size_t)(colon - s))) {
int n = atoi(colon + 1);
__atomic_store_n(&force_left[i], n > 0 ? n : 0, __ATOMIC_RELAXED);
rt_log("oom: TOTK_TEST_OOM fails the first %d %s attempts", n, site_name[i]);
}
}
s = *end ? end + 1 : end;
}
__atomic_store_n(&forced_parsed, 1, __ATOMIC_RELEASE);
}
int rt_oom_forced(int site) {
if (!__atomic_load_n(&forced_parsed, __ATOMIC_ACQUIRE)) plat_once(&force_once, force_parse, NULL);
if (__atomic_load_n(&force_left[site], __ATOMIC_RELAXED) <= 0) return 0;
return plat_dec32(&force_left[site]) >= 0;
}
void rt_oom_force(int site, int n) {
if (!__atomic_load_n(&forced_parsed, __ATOMIC_ACQUIRE)) plat_once(&force_once, force_parse, NULL);
__atomic_store_n(&force_left[site], n, __ATOMIC_RELAXED);
}
int rt_oom_forced_left(int site) {
int n = __atomic_load_n(&force_left[site], __ATOMIC_RELAXED);
return n > 0 ? n : 0;
}
void rt_oom_request(void) { __atomic_store_n(&rt_oom_req, 1, __ATOMIC_RELEASE); }
int rt_oom_wait(const char *what, uint64_t bytes, int (*retry)(void *arg), void *arg) {
rt_oom_request();
static volatile int32_t reports;
int report = plat_inc32(&reports) <= OOM_REPORTS;
double proc, used, limit;
if (report) {
plat_commit_info(&proc, &used, &limit);
rt_log("%s of %llu bytes failed (memory commit: this process %.0f MB, the system %.0f of %.0f MB); waiting up "
"to %u s for memory", what, (unsigned long long)bytes, proc, used, limit, OOM_WAIT_MS / 1000);
}
uint64_t t0 = plat_now_ms();
for (int n = 1; plat_now_ms() - t0 < OOM_WAIT_MS; n++) {
plat_sleep_ms(OOM_STEP_MS);
if (retry(arg)) {
if (report)
rt_log("%s of %llu bytes succeeded after %llu ms", what, (unsigned long long)bytes,
(unsigned long long)(plat_now_ms() - t0));
return 1;
}
if (n % OOM_REQUEST_EVERY == 0) rt_oom_request();
}
plat_commit_info(&proc, &used, &limit);
rt_log("%s of %llu bytes still failed after %u s (memory commit: this process %.0f MB, the system %.0f of %.0f MB)",
what, (unsigned long long)bytes, OOM_WAIT_MS / 1000, proc, used, limit);
return 0;
}
typedef struct { void *old, *p; size_t n; } Realloc;
static int realloc_try(void *arg) {
Realloc *r = arg;
return (r->p = realloc(r->old, r->n)) != NULL;
}
void *rt_realloc_wait(void *old, size_t n, const char *what) {
void *p = realloc(old, n);
if (p || !n) return p;
Realloc r = {old, NULL, n};
return rt_oom_wait(what, n, realloc_try, &r) ? r.p : NULL;
}
+15
View File
@@ -957,6 +957,10 @@ static void fault_handler(int sig, siginfo_t *si, void *uc) {
}
if (sig == SIGSEGV || sig == SIGBUS)
c.access = (err & 16) ? 8 : (err & 2) ? 1 : 0, c.addr = (uint64_t)(uintptr_t)si->si_addr;
static const int gr[16] = {REG_RAX, REG_RCX, REG_RDX, REG_RBX, REG_RSP, REG_RBP, REG_RSI, REG_RDI,
REG_R8, REG_R9, REG_R10, REG_R11, REG_R12, REG_R13, REG_R14, REG_R15};
for (int i = 0; i < 16; i++) c.gpr[i] = (uint64_t)u->uc_mcontext.gregs[gr[i]];
c.has_regs = 1;
crash_fn(&c);
}
signal(sig, SIG_DFL); // returns into the faulting instruction, which faults again with the default action
@@ -1669,6 +1673,17 @@ void plat_commit_info(double *proc_mb, double *used_mb, double *limit_mb) {
if (private_bytes) *proc_mb = (double)(private_bytes >> 20);
}
void plat_mem_room(uint64_t *commit_room, uint64_t *phys_room) {
*commit_room = *phys_room = UINT64_MAX;
char line[128];
unsigned long long k;
FILE *f = fopen("/proc/meminfo", "r");
if (!f) return;
while (fgets(line, sizeof line, f))
if (sscanf(line, "MemAvailable: %llu kB", &k) == 1) *phys_room = (uint64_t)k << 10;
fclose(f);
}
// ---- child processes
struct PlatChild {
+7
View File
@@ -249,7 +249,11 @@ typedef struct {
const char *module; // the module holding rip: NULL for this executable, "" for none (a jump to address 0)
const char *cxx_type; // a C++ exception from MSVC-built code: the thrown type's decorated name (.?AV...@@)
const char *cxx_what; // and what() when the type derives from std::exception; NULL when unknown
int has_regs; // gpr holds the faulting thread's registers (a fault; not abort or invalid parameter)
uint64_t gpr[16]; // rax rcx rdx rbx rsp rbp rsi rdi r8..r15, in the x86 encoding order
} PlatCrash;
#define PLAT_GPR_NAMES {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", \
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"}
void plat_crash_hook(void (*fn)(const PlatCrash *c));
int plat_mem_read(uint64_t addr, void *out, size_t n); // copies n bytes, 0 instead of faulting on unmapped memory
int plat_screen_size(int *w, int *h); // the primary display's current mode in pixels; 0 unknown
@@ -429,6 +433,9 @@ void plat_mem_info(float *used_mb, float *total_mb, float *proc_mb);
// Commit charge in MB: this process's private bytes, the system's commit in use and its limit (RAM plus page files).
// An allocation fails when the system's reaches the limit, however much physical memory is free. -1 when unknown.
void plat_commit_info(double *proc_mb, double *used_mb, double *limit_mb);
// What the system can still give, in bytes: commit (Windows: limit minus charge; Linux, which overcommits: UINT64_MAX)
// and physical memory available without paging. UINT64_MAX when unknown.
void plat_mem_room(uint64_t *commit_room, uint64_t *phys_room);
// This process's memory in bytes: resident (the working set) and private (Windows: committed private bytes; Linux: the
// resident anonymous pages). 0 when unknown.
void plat_process_memory(uint64_t *resident, uint64_t *private_bytes);
+16
View File
@@ -736,6 +736,14 @@ void plat_mem_fault_hook(int (*fn)(uint64_t addr)) {
static void (*crash_fn)(const PlatCrash *c);
// The faulting thread's general registers, for the report to tie the faulting instruction to its operands.
static void regs_of(const CONTEXT *x, PlatCrash *c) {
const DWORD64 r[16] = {x->Rax, x->Rcx, x->Rdx, x->Rbx, x->Rsp, x->Rbp, x->Rsi, x->Rdi,
x->R8, x->R9, x->R10, x->R11, x->R12, x->R13, x->R14, x->R15};
for (int i = 0; i < 16; i++) c->gpr[i] = r[i];
c->has_regs = 1;
}
static LONG WINAPI crash_filter(EXCEPTION_POINTERS *ep);
static LONG CALLBACK crash_veh(EXCEPTION_POINTERS *ep) {
@@ -758,6 +766,7 @@ static LONG CALLBACK crash_veh(EXCEPTION_POINTERS *ep) {
PlatCrash c = {what, (uint32_t)code, rip, rip - (uintptr_t)mi.lpBaseOfDll, -1, 0};
if (code == EXCEPTION_ACCESS_VIOLATION && ep->ExceptionRecord->NumberParameters >= 2)
c.access = (int)ep->ExceptionRecord->ExceptionInformation[0], c.addr = ep->ExceptionRecord->ExceptionInformation[1];
regs_of(ep->ContextRecord, &c);
crash_fn(&c);
return EXCEPTION_CONTINUE_SEARCH;
}
@@ -895,6 +904,7 @@ static LONG WINAPI crash_filter(EXCEPTION_POINTERS *ep) {
(uint32_t)code, rip, 0, -1, 0};
if (code == EXCEPTION_ACCESS_VIOLATION && er->NumberParameters >= 2)
c.access = (int)er->ExceptionInformation[0], c.addr = er->ExceptionInformation[1];
regs_of(ep->ContextRecord, &c);
void *base = NULL;
RtlPcToFileHeader((void *)rip, &base);
uintptr_t exe = (uintptr_t)GetModuleHandleW(NULL);
@@ -1774,6 +1784,12 @@ void plat_commit_info(double *proc_mb, double *used_mb, double *limit_mb) {
*proc_mb = (double)(pmc.PrivateUsage >> 20);
}
void plat_mem_room(uint64_t *commit_room, uint64_t *phys_room) {
*commit_room = *phys_room = UINT64_MAX;
MEMORYSTATUSEX ms = {.dwLength = sizeof ms};
if (GlobalMemoryStatusEx(&ms)) *commit_room = ms.ullAvailPageFile, *phys_room = ms.ullAvailPhys;
}
void plat_process_memory(uint64_t *resident, uint64_t *private_bytes) {
PROCESS_MEMORY_COUNTERS_EX pm = {.cb = sizeof pm};
*resident = *private_bytes = 0;
+25 -7
View File
@@ -14,10 +14,11 @@
// 64-bit word, +40 the renderer (1.2.1) or display configuration (1.4.3) the patched code stores there.
// +56 the camera's aspect ratio as a float when the output is not 16:9 (set aspect), +60 the field-of-view factor
// (set fov, res_fov_live).
// 1.4.3 scales the scene it reads by output width / 1920 (a 2560x1440 output renders its 1600x900 scene at 2128x1200;
// MacNativeGames measured the same), so its page holds the wanted size divided by that factor and the game's 5/6 needs
// no scene patch. 1.2.1 renders the size it reads (1600x900 on a 2560x1440 output): its page holds the wanted size, and
// the scene set is on whenever the output differs from 1920x1080.
// 1.4.3 scales the scene it reads by canvas width / the console mode's base width, 1920 docked and 1280 handheld (a
// 2560x1440 output renders its 1600x900 scene at 2128x1200 docked; MacNativeGames measured the same), so its page holds
// the wanted size divided by that factor (scene_scale) and the game's 5/6 needs no scene patch. 1.2.1 renders the size
// it reads (1600x900 on a 2560x1440 output): its page holds the wanted size, and the scene set is on whenever the
// output differs from 1920x1080.
//
// Heap: agl's DynamicTextureAllocator is one fixed heap, "DynamicTextureAllocatorMem" in
// System/HeapSize/Product.Nin_NX_NVN.HeapDef.byml.zs (113664 KiB, carved from "Graphics", 201728 KiB). At 2560x1440
@@ -40,6 +41,7 @@
#include "cfg.h"
#include "host.h"
#include "mods.h"
#include "ov.h"
#include "platform/platform.h"
#define BASE_W 1920
@@ -209,6 +211,17 @@ uint64_t res_heap_extra_kib(void) {
return kib + ((shadow_kib() + 1023) & ~1023ull); // whole MiB
}
// 1.4.3's factor between the scene size it reads from the page and the one it renders. The game's scene setter
// (main+0x585e48 and the code before it) multiplies the page's size by the canvas width (display configuration +0x10)
// over the current console mode's base width (+0xf4 of the mode's entry, mode 1 handheld: main+0x2dac1c stores
// GetOperationMode != 1 at +0x546). The base is 1280 handheld and 1920 docked. The canvas is the output whenever the
// scene patch is on: docked the game's own canvas is 1920, handheld res_init switches the output patch on (a 1280 base
// with the game's 1280x720 handheld canvas would render R.ow / 1280 times the scene). 1.2.1 renders the size it reads.
static double scene_scale(void) {
if (!RT_V143) return 1.0;
return (double)R.ow / (ov_handheld() ? 1280 : BASE_W);
}
uint64_t res_heap_extra_bytes(void) { return ((res_heap_extra_kib() << 10) + 0x1fffff) & ~0x1fffffull; }
// TOTK_TEX_HEAP_EXTRA_MB (0 to 4096): more room in "TextureHeap" and its parent "ゲームグラフィックス", the heap the
@@ -485,15 +498,20 @@ void res_init(void) {
return;
}
uint8_t *page = rt_patch_page();
double k = RT_V143 ? (double)R.ow / BASE_W : 1.0; // 1.4.3's own scaling of the scene with the output width
double k = scene_scale();
int scene_on = R.scene_set || (!RT_V143 && (R.ow != BASE_W || R.oh != BASE_H));
// Handheld, 1.4.3 draws a 1280x720 canvas unless the output patch is on, whatever the output setting (measured: a
// 1920x1080 output with the patch off composed the frame at 1280x720 and only the swapchain was 1920x1080). With
// the scene patch on the output patch is switched on too, so the canvas is the output size that scene_scale and
// the heap size (res_heap_extra_kib) assume.
int output_on = R.ow != BASE_W || R.oh != BASE_H || (RT_V143 && scene_on && ov_handheld());
float sc[2] = {(float)(R.sw / k), (float)(R.sh / k)};
uint64_t out = pack(R.ow, R.oh), none = 0;
memcpy(page + 16, sc, sizeof sc);
memcpy(page + 32, &out, 8);
memcpy(page + 40, &none, 8);
memcpy(page + 48, &out, 8);
rt_patch_switch(output, R.ow != BASE_W || R.oh != BASE_H);
rt_patch_switch(output, output_on);
rt_patch_switch(scene, scene_on);
R.on = 1;
if (R.live) g_fnprof = 1; // until the game sets its render size: res_fn_hit, or res_present gives up
@@ -614,7 +632,7 @@ int res_dlss_mode(const char *m) {
unsigned w, h;
scene_for(k ? k : R.base_k, &w, &h);
if (w == R.sw && h == R.sh) return 0;
double s = RT_V143 ? (double)R.ow / BASE_W : 1.0;
double s = scene_scale();
float sc[2] = {(float)(w / s), (float)(h / s)};
memcpy((uint8_t *)rt_patch_page() + 16, sc, sizeof sc);
R.sw = w, R.sh = h;
+19 -1
View File
@@ -44,6 +44,7 @@ typedef struct VkCtx {
// VK_FEEDBACK_RESTART (the pass ends and restarts behind the full barrier).
int feedback; // VK_FEEDBACK_*
uint32_t min_imported_host_alignment; // VK_EXT_external_memory_host
VkDeviceSize vma_block; // VMA's block size for heaps over 1 GiB (TOTK_VMA_BLOCK_MIB, vk_device.c)
int device_index; // index in vkEnumeratePhysicalDevices
} VkCtx;
enum { VK_FEEDBACK_OFF, VK_FEEDBACK_RESTART, VK_FEEDBACK_LAYOUT };
@@ -300,13 +301,24 @@ int vk_mem_class_of(uint64_t addr); // VK_MCLS_* of the pool at ad
void vk_mem_census(uint64_t frame); // at each present: pool census and traffic, logged at frame 1800 and,
// with TOTK_TRACE=perf, every 1800 frames
// VRAM in use and its budget, summed over the DEVICE_LOCAL heaps. exact 1: VK_EXT_memory_budget (the whole process),
// 0: this allocator's own allocations against the heap sizes. 0 when unknown.
// 0: this allocator's own allocations against the heap sizes. 0 when unknown. Where device memory takes host memory
// (vk_mem_host_room) the budget is at most the use plus that room.
int vk_mem_vram(uint64_t *used, uint64_t *budget, int *exact);
// Bytes the system can still give device memory beyond a reserve (TOTK_MEM_RESERVE_MIB) where device memory takes host
// memory: a UMA GPU (commit and physical memory), or a discrete GPU whose device-local memory took process commit in
// vk_mem_host_probe (commit). UINT64_MAX elsewhere.
uint64_t vk_mem_host_room(void);
void vk_mem_host_probe(void); // vk_device.c, after the device: measures that for a discrete GPU, once
int vk_mem_uma(void); // 1: the device class is uma (vk_mem_class_log), its memory is RAM
// VRAM headroom (vk_headroom.c): the VMA callbacks that see new device memory, and the thread that allocates the next
// block of each memory type in use ahead of the render thread.
const VmaDeviceMemoryCallbacks *vk_headroom_callbacks(void);
void vk_headroom_start(void);
void vk_headroom_stop(void); // before vmaDestroyAllocator
// The texture pool (vk_memory.c vk_texture_image) gets its next block ahead too; pool NULL frees the anchor in it.
void vk_headroom_pool(VmaPool pool, uint32_t type, VkDeviceSize block);
void vk_headroom_release(void); // after a failed allocation: frees the spare blocks and keeps none for a while;
// any thread that holds no VMA lock (takes only the headroom lock)
int vk_mem_resolve(uint64_t addr, uint64_t size, VkMemSpan *out); // 1 when all of [addr, addr+size) is backed
// Changes whenever vk_mem_resolve plus VK_MEM_USE may give another span for an address: a pool added, finalized or
// mapped, a mirror created, refused or forgotten, a submission started.
@@ -342,6 +354,8 @@ void vk_defer_buffer(VkBuffer buf, VmaAllocation alloc);
void vk_defer_free(void *p);
// Device-local scratch for the upload batch (storage, transfer src and dst), from a pool of its own (vk_memory.c).
VkResult vk_scratch_buffer(VkDeviceSize size, VkBuffer *buf, VmaAllocation *alloc);
// A game texture's image with memory of its own: the texture pool, or a dedicated allocation (vk_memory.c).
VkResult vk_texture_image(const VkImageCreateInfo *ci, VkImage *img, VmaAllocation *alloc);
// Staging and scratch bytes the open upload batch holds until it completes. Large texture loads submit the batch early
// (vk_texture.c UPLOAD_HELD_MAX) so the GPU starts on it and its buffers come back before the pools need new blocks.
VkDeviceSize vk_upload_held(void);
@@ -395,6 +409,10 @@ int vk_mem_span_live(const VkMemSpan *sp);
void vk_mem_note_fence(uint64_t timeline_value);
void vk_mem_fault_log(void); // vk_device_fault_report: the deferred-free state, lock-free
void vk_mem_collect(void); // frees what has completed
// After a failed allocation, on a thread that may hold the texture lock and the upload lock (cmd_lock) but no VMA
// lock: frees the headroom blocks and the completed upload batches and deferred objects, and requests the release
// of released textures at the next submit (rt_oom_request).
void vk_oom_release(void);
typedef struct { uint64_t imported_pools, physical_pools, virtual_pools, import_failures, upload_batches; } VkMemStats;
void vk_mem_stats(VkMemStats *s);
void vk_mem_shutdown(void); // before vk_shutdown: waits idle, frees every memory and texture object
+6 -4
View File
@@ -300,17 +300,19 @@ static int create_pipeline(VkCtx *c) {
// TOTK_ASTC_BC=1: the BC3 encoder, when the device samples BC3 (every desktop GPU does); 0 leaves ASTC as RGBA8.
// Unset: on when the largest device-local heap is under 5 GiB. There RGBA8 ASTC, four times the size of BC3, fills
// video memory (a GTX 1650 4 GiB went from 10-23 to 3-12 ms of GPU time a frame, issue #87); BC3 loses some precision
// (normal maps), so GPUs with more memory keep RGBA8.
// (normal maps), so GPUs with more memory keep RGBA8. A UMA GPU's heap is the machine's RAM however large it reads
// (10.6 GiB on an ROG Ally X, 14.9 GiB on a Radeon 880M), so there BC3 is on too: on the RX 9070, BC3 took 737 MiB off
// VMA's device-local allocations after a minute in the field, at the same GPU time.
static int create_bc_pipeline(VkCtx *c) {
const char *e = cfg_get("TOTK_ASTC_BC");
VkDeviceSize vram = 0;
for (uint32_t h = 0; h < c->mem_props.memoryHeapCount && h < VK_MAX_MEMORY_HEAPS; h++)
if (c->mem_props.memoryHeaps[h].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT && c->mem_props.memoryHeaps[h].size > vram)
vram = c->mem_props.memoryHeaps[h].size;
int on = e && *e ? *e != '0' : vram < (5ull << 30);
int on = e && *e ? *e != '0' : vram < (5ull << 30) || vk_mem_uma();
if (!(e && *e))
rt_log("vk: TOTK_ASTC_BC unset: BC3 %s (largest device-local heap %llu MiB)", on ? "on" : "off",
(unsigned long long)(vram >> 20));
rt_log("vk: TOTK_ASTC_BC unset: BC3 %s (largest device-local heap %llu MiB%s)", on ? "on" : "off",
(unsigned long long)(vram >> 20), vk_mem_uma() ? ", uma: system memory" : "");
if (!on) return 0;
VkFormatProperties p;
vkGetPhysicalDeviceFormatProperties(c->phys, VK_FORMAT_BC3_SRGB_BLOCK, &p);
+9 -2
View File
@@ -429,8 +429,14 @@ static int create_device(void) {
g_vk.min_imported_host_alignment = (uint32_t)emh.minImportedHostPointerAlignment;
vk_caps_init(&g_vk);
// Blocks of 64 MiB instead of VMA's 256 (TOTK_VMA_BLOCK_MIB, 0 = VMA's). Since the textures moved to their own pool
// (vk_memory.c vk_texture_image), the default device-local blocks hold mirrors and other buffers: on the RX 9070
// after 10 minutes in the field one 256 MiB block held 53 MiB of them, and the headroom thread kept half a block of
// each device-local type ahead (128 MiB each). Larger buffers than half a block get memory of their own.
g_vk.vma_block = (VkDeviceSize)cfg_int("TOTK_VMA_BLOCK_MIB") << 20;
if (!g_vk.vma_block) g_vk.vma_block = 256ull << 20; // VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE
VmaAllocatorCreateInfo ai = {.physicalDevice = g_vk.phys, .device = g_vk.device, .instance = g_vk.instance,
.vulkanApiVersion = VK_API_VERSION_1_3,
.vulkanApiVersion = VK_API_VERSION_1_3, .preferredLargeHeapBlockSize = g_vk.vma_block,
.flags = (g_vk.has_buffer_device_address ? VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT : 0) |
(g_vk.has_memory_budget ? VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT : 0),
.pDeviceMemoryCallbacks = vk_headroom_callbacks()};
@@ -475,7 +481,8 @@ int vk_init(void) {
plat_mutex_lock(&g_lock);
if (!g_ready) {
memset(&g_vk, 0, sizeof g_vk);
if (create_instance() && pick_device() && create_device()) g_ready = 1, vk_upload_pools_init(), vk_headroom_start(), vk_dlaa_init();
if (create_instance() && pick_device() && create_device())
g_ready = 1, vk_mem_host_probe(), vk_upload_pools_init(), vk_headroom_start(), vk_dlaa_init();
else destroy_all();
}
int ok = g_ready;
+21 -4
View File
@@ -363,6 +363,16 @@ static CbRes *cb_res(VkExec *ex) {
return D->cur;
}
typedef struct { const VkBufferCreateInfo *bi; const VmaAllocationCreateInfo *ai; Chunk *c; VmaAllocationInfo info;
VkResult r; } ChunkTry;
static int chunk_try(void *arg) {
ChunkTry *t = arg;
vk_mem_collect(); // the fence thread's collect waits while the caller holds cmd_lock
t->r = rt_oom_forced(RT_OOM_CHUNK) ? VK_ERROR_OUT_OF_DEVICE_MEMORY
: vmaCreateBuffer(vk_ctx()->vma, t->bi, t->ai, &t->c->buf, &t->c->alloc, &t->info);
return t->r == VK_SUCCESS;
}
static uint8_t *scratch(VkExec *ex, uint64_t size, VkBuffer *buf, VkDeviceSize *off) {
CbRes *r = cb_res(ex);
size = (size + 255) & ~255ull;
@@ -396,10 +406,17 @@ static uint8_t *scratch(VkExec *ex, uint64_t size, VkBuffer *buf, VkDeviceSize *
VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST,
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT,
.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT};
VmaAllocationInfo info;
VkResult res = vmaCreateBuffer(vk_ctx()->vma, &bi, &ai, &c->buf, &c->alloc, &info);
if (res != VK_SUCCESS) rt_fatal("vk: transient buffer of %llu bytes failed (%d)", (unsigned long long)n, (int)res);
c->map = info.pMappedData, c->size = n, c->used = 0;
// Out of memory: the recording waits for memory (rt_oom_wait) with what it holds (the texture lock at most,
// which vk_oom_release takes before cmd_lock); new chunks are made only when the spare ones ran out.
ChunkTry ct = {.bi = &bi, .ai = &ai, .c = c};
ct.r = rt_oom_forced(RT_OOM_CHUNK) ? VK_ERROR_OUT_OF_DEVICE_MEMORY
: vmaCreateBuffer(vk_ctx()->vma, &bi, &ai, &c->buf, &c->alloc, &ct.info);
if (ct.r == VK_ERROR_OUT_OF_HOST_MEMORY || ct.r == VK_ERROR_OUT_OF_DEVICE_MEMORY) {
vk_oom_release();
rt_oom_wait("vk: transient buffer", n, chunk_try, &ct);
}
if (ct.r != VK_SUCCESS) rt_fatal("vk: transient buffer of %llu bytes failed (%d)", (unsigned long long)n, (int)ct.r);
c->map = ct.info.pMappedData, c->size = n, c->used = 0;
r->nchunks++;
}
*buf = c->buf;
+11
View File
@@ -968,6 +968,9 @@ int probe_vkexec(void) {
const GfxBackend *b = &gfx_vulkan_backend;
uint64_t heap = 0;
CHECK(mem_set_heap_size(16ull << 20, &heap) == 0 && heap, "SetHeapSize 16 MiB");
// Out-of-memory waits (oom.c): the first two staging buffers, the first texture image and the first draw-data chunk
// fail; every part below passes through the wait or the retry that follows.
rt_oom_force(RT_OOM_STAGING, 2), rt_oom_force(RT_OOM_IMAGE, 1), rt_oom_force(RT_OOM_CHUNK, 1);
uint8_t *guest = (uint8_t *)(uintptr_t)heap;
uint64_t first = 0, last = 0;
int w = 0, h = 0, inside = 0, xfer_bytes = 0;
@@ -989,6 +992,12 @@ int probe_vkexec(void) {
vk_exec_xfer_shutdown();
vk_backend_shutdown();
long errors = vk_validation_errors_total();
int oom_left[3] = {rt_oom_forced_left(RT_OOM_STAGING), rt_oom_forced_left(RT_OOM_IMAGE), rt_oom_forced_left(RT_OOM_CHUNK)};
if (!bad && !errors && (oom_left[0] || oom_left[1] || oom_left[2])) {
printf("probe-vkexec: FAILED (forced allocation failures never reached: staging %d, image %d, chunk %d)\n",
oom_left[0], oom_left[1], oom_left[2]);
return 1;
}
if (bad || errors) {
printf("probe-vkexec: FAILED (%s, %ld validation errors)\n",
sync_bad ? "a sync check failed" : draw_bad ? "a draw check failed" : bad ? "a clear or xfer check failed" : "checks passed", errors);
@@ -1034,5 +1043,7 @@ int probe_vkexec(void) {
"finished mark is the last pass, ring records exact); the report reads:\n%s\n", marks_text);
printf("probe-vkexec: empty pool part passed (a zero-byte pool at the start of another: no Vulkan objects, lookups "
"there find the other pool before and after its Finalize)\n");
printf("probe-vkexec: out-of-memory part passed (2 failed staging buffers waited for, 1 failed texture image retried, "
"1 failed draw-data chunk waited for)\n");
return 0;
}
+67 -19
View File
@@ -12,7 +12,9 @@
// a block per memory type is held back.
// Under VRAM pressure no headroom is kept: the spare block counts against the budget that decides whether a pool gets
// its VRAM mirror (vk_memory.c), so while use plus two blocks passes 85% of the budget the anchor goes and nothing new
// is allocated.
// is allocated. The same holds when the system runs short of memory (room), and for HR_HOLD_MS after an allocation
// failed anywhere (vk_headroom_release).
// The texture pool (vk_memory.c vk_texture_image) is kept ahead the same way, with its own anchor of half its block.
// TOTK_VRAM_HEADROOM=0 turns it off.
#include "cfg.h"
@@ -22,6 +24,7 @@
#define HR_PERIOD_MS 500
#define HR_SMALL_HEAP (1ull << 30) // VMA_SMALL_HEAP_MAX_SIZE: smaller heaps use blocks of a heap eighth
#define HR_HOLD_MS 30000u
static struct {
int on, stop;
@@ -33,6 +36,11 @@ static struct {
volatile int64_t made; // blocks this thread brought in
volatile int64_t other; // device memory of 32 MiB or more other threads allocated (VMA blocks, large dedicated)
VmaAllocation anchor[64]; // per memory type: the half block that keeps the newest spare block from being deleted
VmaPool pool; // the texture pool, its memory type and block size, and its anchor
uint32_t pool_type;
VkDeviceSize pool_block;
VmaAllocation pool_anchor;
volatile uint64_t hold_until; // plat_now_ms before which no spare block is kept (vk_headroom_release)
} H;
static void VKAPI_PTR on_allocate(VmaAllocator a, uint32_t type, VkDeviceMemory m, VkDeviceSize size, void *user) {
@@ -55,29 +63,36 @@ const VmaDeviceMemoryCallbacks *vk_headroom_callbacks(void) {
static VkDeviceSize block_size(const VkCtx *c, uint32_t type) {
VkDeviceSize heap = c->mem_props.memoryHeaps[c->mem_props.memoryTypes[type].heapIndex].size;
return heap <= HR_SMALL_HEAP ? heap / 8 : 256ull << 20; // VMA's default preferredLargeHeapBlockSize
return heap <= HR_SMALL_HEAP ? heap / 8 : c->vma_block; // VMA's preferredLargeHeapBlockSize
}
// The spare block is memory the game does not use yet; where device memory takes host memory it is kept only while the
// system has four blocks to spare beyond the reserve (vk_mem_host_room). On the RX 9070 the spare blocks held 1.4 GB
// of commit.
static int room(const VkCtx *c, uint32_t type, VkDeviceSize block) {
VmaBudget b[VK_MAX_MEMORY_HEAPS];
vmaGetHeapBudgets(c->vma, b);
const VmaBudget *h = &b[c->mem_props.memoryTypes[type].heapIndex];
return h->budget && h->usage + 2 * block <= h->budget / 100 * 85;
return h->budget && h->usage + 2 * block <= h->budget / 100 * 85 && vk_mem_host_room() >= 4 * block;
}
static void drop_anchor(const VkCtx *c, uint32_t type) {
if (H.anchor[type]) vmaFreeMemory(c->vma, H.anchor[type]);
H.anchor[type] = NULL;
static void drop_anchor(const VkCtx *c, VmaAllocation *anchor) {
if (*anchor) vmaFreeMemory(c->vma, *anchor);
*anchor = NULL;
}
static void top_up(const VkCtx *c, uint32_t type) {
VkDeviceSize block = block_size(c, type);
if (!room(c, type, block)) {
drop_anchor(c, type);
// pool NULL: the default pool of the type
static void top_up(const VkCtx *c, uint32_t type, VmaPool pool, VkDeviceSize block, VmaAllocation *anchor) {
// Device-local types only: textures and mirrors grow there. Host memory types are woken by the staging pool's own
// blocks (vk_memory.c vk_staging), while their default pool held 4 MiB: on the RX 9070 the spare blocks of types 1
// and 3 held 512 MiB of commit for nothing.
if (!(c->mem_props.memoryTypes[type].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ||
plat_now_ms() < __atomic_load_n(&H.hold_until, __ATOMIC_RELAXED) || !room(c, type, block)) {
drop_anchor(c, anchor);
return;
}
VkMemoryRequirements req = {.size = block / 2, .alignment = 256, .memoryTypeBits = 1u << type};
VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_UNKNOWN};
VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_UNKNOWN, .pool = pool};
VmaAllocation a;
int64_t before = H.made;
if (vmaAllocateMemory(c->vma, &req, &ai, &a, NULL) != VK_SUCCESS) return;
@@ -85,12 +100,13 @@ static void top_up(const VkCtx *c, uint32_t type) {
vmaFreeMemory(c->vma, a);
return;
}
drop_anchor(c, type);
H.anchor[type] = a;
drop_anchor(c, anchor);
*anchor = a;
static volatile int32_t logged;
if (plat_inc32(&logged) <= 32)
rt_log("vk: headroom: a %.0f MiB block of memory type %u allocated ahead (%lld so far; %lld allocations of 32 MiB "
"or more on other threads)", (double)block / 1048576.0, type, (long long)H.made, (long long)H.other);
rt_log("vk: headroom: a %.0f MiB block of memory type %u%s allocated ahead (%lld so far; %lld allocations of "
"32 MiB or more on other threads)", (double)block / 1048576.0, type, pool ? " (texture pool)" : "",
(long long)H.made, (long long)H.other);
}
static void headroom_main(void *arg) {
@@ -105,10 +121,15 @@ static void headroom_main(void *arg) {
plat_mutex_lock(&H.lock);
const VkCtx *c = H.stop ? NULL : vk_ctx();
for (uint32_t t = 0; c && t < c->mem_props.memoryTypeCount && t < 64; t++)
if (watch >> t & 1) top_up(c, t);
if (watch >> t & 1) {
top_up(c, t, NULL, block_size(c, t), &H.anchor[t]);
if (H.pool && t == H.pool_type) top_up(c, t, H.pool, H.pool_block, &H.pool_anchor);
}
int stop = H.stop;
if (stop && (c = vk_ctx()))
for (uint32_t t = 0; t < 64; t++) drop_anchor(c, t);
if (stop && (c = vk_ctx())) {
for (uint32_t t = 0; t < 64; t++) drop_anchor(c, &H.anchor[t]);
drop_anchor(c, &H.pool_anchor);
}
plat_mutex_unlock(&H.lock);
if (stop) return;
}
@@ -120,11 +141,38 @@ void vk_headroom_stop(void) {
plat_mutex_lock(&H.lock);
H.stop = 1;
const VkCtx *c = vk_ctx();
for (uint32_t t = 0; c && t < 64; t++) drop_anchor(c, t);
for (uint32_t t = 0; c && t < 64; t++) drop_anchor(c, &H.anchor[t]);
if (c) drop_anchor(c, &H.pool_anchor);
plat_mutex_unlock(&H.lock);
plat_event_set(&H.ev);
}
void vk_headroom_pool(VmaPool pool, uint32_t type, VkDeviceSize block) {
if (!H.started) return;
plat_mutex_lock(&H.lock);
const VkCtx *c = vk_ctx();
if (c) drop_anchor(c, &H.pool_anchor);
H.pool = pool, H.pool_type = type, H.pool_block = block;
plat_mutex_unlock(&H.lock);
}
// After a failed allocation: the spare blocks go at once (an empty VMA block takes the next allocation of its type or
// is given back), and none is kept for HR_HOLD_MS. H.lock is held only around VMA calls, so the caller may hold any lock
// of ours, just no VMA lock.
void vk_headroom_release(void) {
__atomic_store_n(&H.hold_until, plat_now_ms() + HR_HOLD_MS, __ATOMIC_RELAXED);
if (!H.started) return;
int n = 0;
plat_mutex_lock(&H.lock);
const VkCtx *c = H.stop ? NULL : vk_ctx();
for (uint32_t t = 0; c && t < 64; t++)
if (H.anchor[t]) drop_anchor(c, &H.anchor[t]), n++;
if (c && H.pool_anchor) drop_anchor(c, &H.pool_anchor), n++;
plat_mutex_unlock(&H.lock);
static volatile int32_t logged;
if (n && plat_inc32(&logged) <= 8) rt_log("vk: headroom: %d spare blocks freed after a failed allocation", n);
}
void vk_headroom_start(void) {
if (!H.on || H.started) return;
plat_mutex_init(&H.lock);
+203 -5
View File
@@ -571,6 +571,25 @@ void vk_mem_census(uint64_t frame) {
n_import_failures, (unsigned long long)count[POOL_PHYS], total[POOL_PHYS] / 1048576.0,
(unsigned long long)count[POOL_VIRT], total[POOL_VIRT] / 1048576.0,
(unsigned long long)__atomic_load_n(&n_cross_defer, __ATOMIC_RELAXED));
// The baseline for the commit a crash report prints: a crash far above it points at growth during play.
double proc, used, limit;
plat_commit_info(&proc, &used, &limit);
uint64_t room = vk_mem_host_room();
rt_log("mem: commit at frame %llu: this process %.0f MB, the system %.0f of %.0f MB; room for device memory %s%.0f MiB",
(unsigned long long)frame, proc, used, limit, room == UINT64_MAX ? "not counted " : "",
room == UINT64_MAX ? 0.0 : room / 1048576.0);
// Per heap, what VMA holds (blocks, and the allocations inside them) beside what the driver counts for the process:
// usage above VMA's blocks is the driver's own memory (pipelines, command buffers, descriptor pools).
VkCtx *vc = vk_ctx();
if (vc && vc->vma) {
VmaBudget vb[VK_MAX_MEMORY_HEAPS];
vmaGetHeapBudgets(vc->vma, vb);
for (uint32_t h = 0; h < vc->mem_props.memoryHeapCount && h < VK_MAX_MEMORY_HEAPS; h++)
rt_log("mem: heap %u (flags %#x) at frame %llu: vma %u blocks %.0f MiB, %u allocations %.0f MiB; driver usage "
"%.0f of %.0f MiB", h, vc->mem_props.memoryHeaps[h].flags, (unsigned long long)frame,
vb[h].statistics.blockCount, vb[h].statistics.blockBytes / 1048576.0, vb[h].statistics.allocationCount,
vb[h].statistics.allocationBytes / 1048576.0, vb[h].usage / 1048576.0, vb[h].budget / 1048576.0);
}
static const char *const kinds[] = {"", "import", "physical", "virtual"};
for (int j = 0; j < ng; j++) {
char f[160];
@@ -602,6 +621,79 @@ static uint64_t vram_limit(void) {
return (uint64_t)limit;
}
// Device memory that takes host memory. A UMA GPU's memory is the machine's RAM. On Windows the AMD driver charges
// device-local allocations to the process commit one to one (RX 9070: VRAM use and private bytes grew by the same
// 1164, 256 and 256 MiB), so on a 16 GB machine the commit limit is reached while the VRAM budget shows gigabytes free,
// and the driver then fails inside a call (#285: std::bad_alloc in amdvlk64.dll under gpl_link). Whether a discrete
// GPU's driver does so is measured once (vk_mem_host_probe), not assumed per vendor: an RTX 5080 log (#398) showed
// 10.4 GB of process commit at frame 1200, about what the RX 9070 holds with its VRAM counted. Linux overcommits, so
// there only a UMA GPU's physical memory counts (plat_mem_room).
enum { HB_NONE, HB_COMMIT, HB_UMA, HB_PROBE };
static int host_backed;
static uint64_t room_reserve;
static volatile uint64_t room_cached, room_ms;
uint64_t vk_mem_host_room(void) {
if (!host_backed) return UINT64_MAX;
uint64_t now = plat_now_ms(), at = __atomic_load_n(&room_ms, __ATOMIC_ACQUIRE);
if (at && now - at < 250) return __atomic_load_n(&room_cached, __ATOMIC_RELAXED); // a query costs a system call
uint64_t commit, phys;
plat_mem_room(&commit, &phys);
uint64_t r = host_backed == HB_UMA && phys < commit ? phys : commit;
r = r == UINT64_MAX ? r : r > room_reserve ? r - room_reserve : 0;
__atomic_store_n(&room_cached, r, __ATOMIC_RELAXED);
__atomic_store_n(&room_ms, now | 1, __ATOMIC_RELEASE);
return r;
}
int vk_mem_uma(void) { return host_backed == HB_UMA; }
// A discrete GPU: one device-local allocation of HB_PROBE_SIZE, and the process commit before and after it. The driver
// charges it at allocation or not at all as far as this sees; one that charged only at first use would read as not
// counted, as before the probe. Another thread's allocation in between could only add, and half the size is the line.
#define HB_PROBE_SIZE (128ull << 20)
void vk_mem_host_probe(void) {
VkCtx *c = vk_ctx();
if (!c || host_backed != HB_PROBE) return;
host_backed = HB_NONE;
uint64_t commit, phys;
plat_mem_room(&commit, &phys);
if (commit == UINT64_MAX) return; // no commit limit (Linux)
uint32_t type = UINT32_MAX;
for (uint32_t i = 0; i < c->mem_props.memoryTypeCount && type == UINT32_MAX; i++)
if ((c->mem_props.memoryTypes[i].propertyFlags & (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) ==
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
type = i;
VkMemoryAllocateInfo ai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = HB_PROBE_SIZE,
.memoryTypeIndex = type};
uint64_t r0, p0, r1, p1;
VkDeviceMemory m;
plat_process_memory(&r0, &p0);
if (type == UINT32_MAX || !p0 || vkAllocateMemory(c->device, &ai, NULL, &m) != VK_SUCCESS) {
rt_log("mem: device memory against system memory: not measured (no device-local type or allocation failed): not counted");
return;
}
plat_process_memory(&r1, &p1);
vkFreeMemory(c->device, m, NULL);
int64_t d = (int64_t)(p1 - p0);
host_backed = d >= (int64_t)HB_PROBE_SIZE / 2 ? HB_COMMIT : HB_NONE;
rt_log("mem: device memory against system memory: %s (a %llu MiB device-local allocation took %.0f MiB of process "
"commit), reserve %llu MiB (TOTK_MEM_RESERVE_MIB)", host_backed == HB_COMMIT ? "commit" : "not counted",
(unsigned long long)(HB_PROBE_SIZE >> 20), d / 1048576.0, (unsigned long long)(room_reserve >> 20));
}
// The budget is at most the use plus what the system can still give, so the paths that react to VRAM pressure (the
// mirror refusal, released textures, the headroom block) react to a system short of memory too.
static void host_cap(uint64_t used, uint64_t *budget) {
uint64_t room = vk_mem_host_room();
if (room == UINT64_MAX || used + room >= *budget) return;
*budget = used + room ? used + room : 1;
static volatile int32_t logged;
if (!plat_xchg32(&logged, 1))
rt_log("mem: system memory limits the device-local budget: %.0f MiB in use, %.0f MiB more beyond a reserve of "
"%.0f MiB (logged once)", used / 1048576.0, room / 1048576.0, room_reserve / 1048576.0);
}
int vk_mem_vram(uint64_t *used, uint64_t *budget, int *exact) {
VkCtx *c = vk_ctx();
*used = *budget = 0, *exact = 0;
@@ -617,6 +709,7 @@ int vk_mem_vram(uint64_t *used, uint64_t *budget, int *exact) {
*used += b.heapUsage[h], *budget += b.heapBudget[h];
*exact = 1;
if (limit && *budget > limit) *budget = limit;
if (*budget) host_cap(*used, budget);
return *budget != 0;
}
VmaBudget vb[VK_MAX_MEMORY_HEAPS];
@@ -625,6 +718,7 @@ int vk_mem_vram(uint64_t *used, uint64_t *budget, int *exact) {
if (mp->memoryHeaps[h].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT)
*used += vb[h].statistics.blockBytes, *budget += mp->memoryHeaps[h].size;
if (limit && *budget > limit) *budget = limit;
if (*budget) host_cap(*used, budget);
return *budget != 0;
}
@@ -2226,6 +2320,9 @@ void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDevic
else if (host_heap < 0) cls = "uma", why = "every heap is device-local";
else cls = "discrete", why = "device-local heap separate from host memory";
int discrete = cls[0] == 'd';
host_backed = !discrete ? HB_UMA : HB_PROBE; // a discrete GPU is measured once the device exists
const char *rs = cfg_get("TOTK_MEM_RESERVE_MIB");
room_reserve = (rs && *rs ? strtoull(rs, NULL, 10) : 1536) << 20; // Windows, other programs, our own heap
char line[2048];
size_t k = (size_t)snprintf(line, sizeof line, "mem: class %s (%s; device type %d %s, %s)", cls, why, t, tn, p->deviceName);
for (uint32_t h = 0; h < m->memoryHeapCount; h++)
@@ -2245,6 +2342,9 @@ void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDevic
f & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT ? " LAZY" : "");
}
rt_log("%s", line);
if (host_backed == HB_UMA)
rt_log("mem: device memory against system memory: commit and physical memory (uma), reserve %llu MiB "
"(TOTK_MEM_RESERVE_MIB)", (unsigned long long)(room_reserve >> 20));
mirror_mode(discrete);
}
@@ -2382,6 +2482,20 @@ void vk_upload_end(void) { plat_rmutex_unlock(&cmd_lock); }
static VmaPool stg_pool;
static int stg_pool_tried;
typedef struct { const VkBufferCreateInfo *bi; const VmaAllocationCreateInfo *aci; VkBuffer b; VmaAllocation a;
VmaAllocationInfo info; VkResult r; } StgTry;
static int staging_try(void *arg) {
StgTry *t = arg;
vk_mem_collect(); // upload batches and deferred objects the GPU finished meanwhile
t->r = rt_oom_forced(RT_OOM_STAGING) ? VK_ERROR_OUT_OF_DEVICE_MEMORY
: vmaCreateBuffer(vk_ctx()->vma, t->bi, t->aci, &t->b, &t->a, &t->info);
return t->r == VK_SUCCESS;
}
// A failed staging buffer waits for memory (rt_oom_wait) before it ends the game: the headroom blocks go and the GPU's
// finished batches are freed at once, released textures at the next submit (vk_oom_release). The caller may hold the
// texture lock and cmd_lock (vk_upload_begin), both of which vk_oom_release may take after them, and no VMA lock. The open
// batch is not submitted: its caller records into it after this returns.
void *vk_staging(VkDeviceSize size, VkBuffer *buf, VmaAllocation *alloc) {
VkCtx *c = vk_ctx();
VkBufferCreateInfo bi = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = size ? size : 16,
@@ -2405,11 +2519,22 @@ void *vk_staging(VkDeviceSize size, VkBuffer *buf, VmaAllocation *alloc) {
plat_rmutex_unlock(&cmd_lock);
}
if (stg_pool && bi.size <= STG_BLOCK / 2) aci.pool = stg_pool;
VmaAllocationInfo info;
VkBuffer b;
VmaAllocation a;
VkResult r = vmaCreateBuffer(c->vma, &bi, &aci, &b, &a, &info);
if (r != VK_SUCCESS) rt_fatal("vk: staging buffer of %llu bytes failed (%d)", (unsigned long long)size, (int)r);
StgTry st = {.bi = &bi, .aci = &aci};
st.r = rt_oom_forced(RT_OOM_STAGING) ? VK_ERROR_OUT_OF_DEVICE_MEMORY
: vmaCreateBuffer(c->vma, &bi, &aci, &st.b, &st.a, &st.info);
if (st.r != VK_SUCCESS) {
VkResult first = st.r;
if (first == VK_ERROR_OUT_OF_HOST_MEMORY || first == VK_ERROR_OUT_OF_DEVICE_MEMORY) {
vk_oom_release();
rt_oom_wait("vk: staging buffer", bi.size, staging_try, &st);
}
if (st.r != VK_SUCCESS)
rt_fatal("vk: staging buffer of %llu bytes failed (%d, first %d)", (unsigned long long)size, (int)st.r,
(int)first);
}
VkBuffer b = st.b;
VmaAllocation a = st.a;
VmaAllocationInfo info = st.info;
*buf = b;
if (alloc) *alloc = a; // the caller destroys it (vmaDestroyBuffer) after vk_upload_flush(1)
else {
@@ -2464,6 +2589,66 @@ VkResult vk_scratch_buffer(VkDeviceSize size, VkBuffer *buf, VmaAllocation *allo
VkDeviceSize vk_upload_held(void) { return open_active ? open_b.held : 0; }
// Own memory of the game's textures (vk_texture.c create_tex): a pool of its own with blocks of TOTK_TEX_BLOCK_MIB
// (default 64; 0 puts textures back in the default pools). In the default pools textures shared 256 MiB blocks with the
// mirrors and other buffers, and a block went back to the driver only once all of them were gone: on the RX 9070,
// after 4.5 minutes of roaming the field, 3 of the 9 device-local blocks were 13-27% full, held by 87-223 small
// textures and buffers each, and the full ones had hundreds of free gaps under 1 MiB, so blocks held 800 MiB more than
// their allocations. Where device memory takes process commit (vk_mem_host_probe) that commit backs nothing. A smaller
// block, holding textures only, empties sooner and wastes less when it does not. With the pool the same 10-minute route
// ended with 807 MiB of blocks beyond their allocations instead of 1037, the texture pool's 22 blocks mostly 75-100%
// full, and the slow frames did not grow.
// An image of a quarter block or more gets memory of its own (a dedicated allocation) that goes back to the driver
// with the image; so do images the driver prefers that for, and images the pool's memory type does not take. VMA
// checks neither for a custom pool (VmaAllocator_T::AllocateMemory takes the pool's type as it is), so the image's
// requirements are read here first.
static VmaPool tex_pool;
static uint32_t tex_type;
static VkDeviceSize tex_block;
static int tex_pool_tried;
static void tex_pool_init(VkCtx *c, const VkImageCreateInfo *ci) {
plat_once(&cmd_once, cmd_init, NULL);
plat_rmutex_lock(&cmd_lock);
if (!tex_pool_tried) {
tex_block = (VkDeviceSize)cfg_int("TOTK_TEX_BLOCK_MIB") << 20; // schema default 64
VmaAllocationCreateInfo aci = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE};
VmaPoolCreateInfo pi = {.blockSize = tex_block};
if (tex_block && vmaFindMemoryTypeIndexForImageInfo(c->vma, ci, &aci, &tex_type) == VK_SUCCESS) {
pi.memoryTypeIndex = tex_type;
if (vmaCreatePool(c->vma, &pi, &tex_pool) != VK_SUCCESS) tex_pool = NULL;
}
if (tex_pool) {
vk_headroom_pool(tex_pool, tex_type, tex_block);
rt_log("vk: texture pool: blocks of %llu MiB in memory type %u; images of %llu MiB or more get memory of "
"their own (TOTK_TEX_BLOCK_MIB)", (unsigned long long)(tex_block >> 20), tex_type,
(unsigned long long)(tex_block >> 22));
} else {
rt_log("vk: texture pool %s: textures go to the default pools (TOTK_TEX_BLOCK_MIB)",
tex_block ? "unavailable" : "off");
}
__atomic_store_n(&tex_pool_tried, 1, __ATOMIC_RELEASE);
}
plat_rmutex_unlock(&cmd_lock);
}
VkResult vk_texture_image(const VkImageCreateInfo *ci, VkImage *img, VmaAllocation *alloc) {
VkCtx *c = vk_ctx();
VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE};
if (!__atomic_load_n(&tex_pool_tried, __ATOMIC_ACQUIRE)) tex_pool_init(c, ci);
if (tex_pool) {
VkDeviceImageMemoryRequirements q = {.sType = VK_STRUCTURE_TYPE_DEVICE_IMAGE_MEMORY_REQUIREMENTS, .pCreateInfo = ci};
VkMemoryDedicatedRequirements dr = {.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS};
VkMemoryRequirements2 mr = {.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2, .pNext = &dr};
vkGetDeviceImageMemoryRequirements(c->device, &q, &mr);
if (dr.requiresDedicatedAllocation || dr.prefersDedicatedAllocation || mr.memoryRequirements.size >= tex_block / 4)
ai.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
else if (mr.memoryRequirements.memoryTypeBits >> tex_type & 1)
ai = (VmaAllocationCreateInfo){.usage = VMA_MEMORY_USAGE_UNKNOWN, .pool = tex_pool}; // the pool's type
}
return vmaCreateImage(c->vma, ci, &ai, img, alloc, NULL);
}
// At device creation: the staging and scratch pools with their kept blocks, made through a first small buffer each
// (freed at once), so the first world frame does not allocate them (staging was first used there once the GPU took
// the early texture uploads).
@@ -2588,6 +2773,15 @@ void vk_mem_collect(void) {
plat_rmutex_unlock(&cmd_lock);
}
// Lock order: the texture lock, then cmd_lock (create_tex records under the first), then the headroom lock, which is
// held only around VMA calls. A caller holding cmd_lock takes it again (recursive) and keeps the fence thread's own
// collect (vk_sync.c) out meanwhile, so this collects for it.
void vk_oom_release(void) {
rt_oom_request();
vk_headroom_release();
vk_mem_collect();
}
void vk_mem_stats(VkMemStats *s) {
memset(s, 0, sizeof *s);
plat_mutex_lock_shared(&pool_lock);
@@ -2630,6 +2824,10 @@ void vk_mem_shutdown(void) {
if (scr_pool) vmaDestroyPool(c->vma, scr_pool); // deferred scratch buffers went with collect_locked above
scr_pool = NULL;
scr_pool_tried = 0;
vk_headroom_pool(NULL, 0, 0); // frees the headroom's anchor in the texture pool
if (tex_pool) vmaDestroyPool(c->vma, tex_pool); // textures went with vk_texture_shutdown, deferred ones above
tex_pool = NULL;
tex_pool_tried = 0;
plat_rmutex_unlock(&cmd_lock);
plat_mutex_lock(&pool_lock);
for (int i = 0; i < pool_index.n; i++) destroy_rec(c, pool_index.e[i].buf);
+89 -25
View File
@@ -64,6 +64,7 @@ typedef struct Tex {
uint32_t wt_n; // WriteTexels into the storage since the last upload
struct Tex *rel_prev, *rel_next; // while released: the list of released entries, oldest first
uint64_t rel_ms; // while released: when (coarse_ms)
uint64_t rel_bytes; // while released: its own memory, counted in rel_bytes_total
uint64_t use_seq; // order of the last creation or take-back among all entries
uint64_t rel_seq; // while released: use_seq of the newest entry placed before this release; an entry
// with a later use_seq on overlapping storage replaced this one's bytes
@@ -95,6 +96,7 @@ static SampSlot *sslots;
static int nsslots;
static nvn_hmap samplers = {.klen = sizeof(samp_par)};
static int nreleased;
static uint64_t rel_bytes_total; // own memory of the released entries
static Tex *rel_head, *rel_tail; // released entries in release order (sweep_released drops from the head)
static uint64_t n_uploads, n_reuploads;
// Re-uploads since the last perf line (tex_lock): all, and those of textures a WriteTexels wrote since their last upload.
@@ -457,8 +459,19 @@ static Tex *create_tex(const tex_t *t, const TexKey *k, int defer_init) {
}
}
if (!img) {
VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE};
VkResult r = vmaCreateImage(c->vma, &ci, &ai, &img, &e->alloc, NULL);
VkResult r = rt_oom_forced(RT_OOM_IMAGE) ? VK_ERROR_OUT_OF_DEVICE_MEMORY
: vk_texture_image(&ci, &img, &e->alloc);
// Out of memory: one more try after the headroom blocks and the finished deferred objects are freed
// (vk_oom_release, which takes cmd_lock after the texture lock held here); released textures go at the next
// submit. No wait: the texture is asked for again at its next use, while a wait would hold the texture lock.
if (r == VK_ERROR_OUT_OF_HOST_MEMORY || r == VK_ERROR_OUT_OF_DEVICE_MEMORY) {
static volatile int32_t n_retried;
vk_oom_release();
VkResult again = vk_texture_image(&ci, &img, &e->alloc);
log_limited(&n_retried, "image creation failed (%d), tried again after a memory release: %s (%ux%ux%u fmt %#x)",
(int)r, again == VK_SUCCESS ? "created" : "failed again", w, h, depth, d->format);
r = again;
}
if (r != VK_SUCCESS) {
log_limited(&n_failed, "image creation failed (%d): nvn fmt %#x %ux%ux%u target %d levels %u layers %u", (int)r,
d->format, w, h, depth, d->target, levels, layers);
@@ -538,7 +551,11 @@ static void own_remove(Tex *e) {
plat_mutex_unlock(&owned_lock);
}
static uint64_t own_bytes(const Tex *e);
static void rel_append(Tex *e) {
e->rel_bytes = own_bytes(e);
rel_bytes_total += e->rel_bytes;
e->rel_next = NULL;
e->rel_prev = rel_tail;
if (rel_tail) rel_tail->rel_next = e;
@@ -547,6 +564,8 @@ static void rel_append(Tex *e) {
}
static void rel_unlink(Tex *e) {
rel_bytes_total -= e->rel_bytes;
e->rel_bytes = 0;
if (e->rel_prev) e->rel_prev->rel_next = e->rel_next;
else rel_head = e->rel_next;
if (e->rel_next) e->rel_next->rel_prev = e->rel_prev;
@@ -644,12 +663,19 @@ static void sweep_released(void) {
// CLEAN_AGE_MS: without the wait a fight re-created about 500 of them per 10 s. Any other render target lives only in its
// image: dropping one that was merely old brought the texture back empty (black flashes in a Depths boss fight, ~170
// "left uninitialised" aliases a minute).
//
// TOTK_TEX_RELEASED_MIB (default 256; 0 = no cap): the same drops run while the released entries hold more own memory than
// that, under pressure or not. A 10-minute field run on the RX 9070 kept 818 MiB of them, 730 MiB with their storage
// taken by a later texture, while 23579 of 23660 take-backs came within a second and none after 120 s. With the
// cap the same route ended with 216 MiB of them, 1.1 GB less process commit and 1 GB less in VMA blocks; 15 dropped
// textures were created again, and the slow frames stayed the same.
#define PRESSURE_STEP 32
#define CLEAN_AGE_MS 5000u
#define DEAD_AGE_MS 30000u
#define DEAD_QUIET_SUBMITS 600u
#define DEAD_RETRY_QUERIES 8 // budget queries to skip after a search that found nothing
static int vram_pressure = -1;
static uint64_t released_cap;
static uint64_t n_pressure_drops, n_pressure_overwritten;
static int tex_by_addr(const void *a, const void *b) {
@@ -703,16 +729,19 @@ static int dead_candidate(const Tex *e) {
// Drops overwritten entries until `need` bytes are free or the step is used up. The sort runs only under pressure, while
// an old enough entry exists, and rests for a while when it finds nothing to drop. Returns the bytes freed.
static uint64_t pressure_search_ns; // longest search since the last mem: released line
static uint64_t drop_overwritten(uint64_t need, int *dropped) {
// step: PRESSURE_STEP, or OOM_STEP from oom_release, which neither waits out nor starts the rest.
#define OOM_STEP 256
static uint64_t drop_overwritten(uint64_t need, int *dropped, int step) {
static int rest;
if (rest > 0) { rest--; return 0; }
int urgent = step > PRESSURE_STEP;
if (rest > 0 && !urgent) { rest--; return 0; }
if (!rel_head || coarse_ms - rel_head->rel_ms < DEAD_AGE_MS) return 0;
uint64_t t0 = plat_now_ns(), freed = 0;
AddrIndex x;
if (!addr_index(&x)) return 0;
Tex *cand[PRESSURE_STEP];
Tex *cand[OOM_STEP];
int nc = 0;
for (Tex *e = rel_head; e && nc < PRESSURE_STEP && coarse_ms - e->rel_ms >= DEAD_AGE_MS; e = e->rel_next) {
for (Tex *e = rel_head; e && nc < step && coarse_ms - e->rel_ms >= DEAD_AGE_MS; e = e->rel_next) {
if (!dead_candidate(e)) continue;
int lo = 0, hi = x.n; // the first entry at e's address, then e among those
while (lo < hi) {
@@ -730,35 +759,62 @@ static uint64_t drop_overwritten(uint64_t need, int *dropped) {
destroy_tex(cand[i]);
(*dropped)++, n_pressure_drops++, n_pressure_overwritten++;
}
if (!nc) rest = DEAD_RETRY_QUERIES;
if (!nc && !urgent) rest = DEAD_RETRY_QUERIES;
uint64_t ns = plat_now_ns() - t0;
if (ns > pressure_search_ns) pressure_search_ns = ns;
return freed;
}
// Clean released entries, oldest first: mirrored ones the GPU never wrote, which come back from their storage.
static uint64_t drop_clean(uint64_t need, uint64_t freed, int *dropped, int step) {
for (Tex *e = rel_head, *next; e && freed < need && *dropped < step && coarse_ms - e->rel_ms >= CLEAN_AGE_MS; e = next) {
next = e->rel_next;
if (!e->pub.mirrored || e->pub.gpu_owned || e->gpu_dirty) continue;
freed += own_bytes(e);
dropped_note(e);
destroy_tex(e);
(*dropped)++, n_pressure_drops++;
}
return freed;
}
static void sweep_pressure(void) { // tex_lock held
if (vram_pressure < 0) {
const char *s = cfg_get("TOTK_TEX_VRAM_PRESSURE");
vram_pressure = s && *s ? atoi(s) : 90;
if (vram_pressure < 0 || vram_pressure > 100) vram_pressure = 90;
rt_log("vk: released textures under VRAM pressure: %s%d%%", vram_pressure ? "dropped above " : "off", vram_pressure);
const char *m = cfg_get("TOTK_TEX_RELEASED_MIB");
released_cap = (m && *m ? strtoull(m, NULL, 10) : 256) << 20;
rt_log("vk: released textures under VRAM pressure: %s%d%%; above %llu MiB of them: %s (TOTK_TEX_RELEASED_MIB)",
vram_pressure ? "dropped above " : "off", vram_pressure, (unsigned long long)(released_cap >> 20),
released_cap ? "dropped" : "no cap");
}
if (!vram_pressure || !rel_head || submit_epoch & 7) return; // the budget query every 8 submits
if (!rel_head || submit_epoch & 7) return; // the budget query every 8 submits
uint64_t need = released_cap && rel_bytes_total > released_cap ? rel_bytes_total - released_cap : 0;
uint64_t used, budget;
int exact;
if (!vk_mem_vram(&used, &budget, &exact)) return;
uint64_t line = budget / 100 * (uint64_t)vram_pressure;
if (used <= line) return;
int dropped = 0;
uint64_t need = used - line, freed = drop_overwritten(need, &dropped);
for (Tex *e = rel_head, *next; e && freed < need && dropped < PRESSURE_STEP && coarse_ms - e->rel_ms >= CLEAN_AGE_MS; e = next) {
next = e->rel_next;
if (!e->pub.mirrored || e->pub.gpu_owned || e->gpu_dirty) continue;
freed += own_bytes(e);
dropped_note(e);
destroy_tex(e);
dropped++, n_pressure_drops++;
if (vram_pressure && vk_mem_vram(&used, &budget, &exact)) {
uint64_t line = budget / 100 * (uint64_t)vram_pressure;
if (used > line && used - line > need) need = used - line;
}
if (!need) return;
int dropped = 0;
uint64_t freed = drop_overwritten(need, &dropped, PRESSURE_STEP);
drop_clean(need, freed, &dropped, PRESSURE_STEP);
}
// rt_oom_request (an allocation failed somewhere, oom.c): the same two kinds as sweep_pressure, as many as OOM_STEP
// whatever the budget says, and the headroom blocks. Never GPU-written content that lives only in its image. The memory
// comes back once the submission being recorded is done (destroy_tex defers the images). Texture lock held.
static void oom_release(void) {
int dropped = 0;
uint64_t freed = drop_overwritten(UINT64_MAX, &dropped, OOM_STEP);
int overwritten = dropped;
freed = drop_clean(UINT64_MAX, freed, &dropped, OOM_STEP);
vk_headroom_release();
static volatile int32_t n_logged;
log_limited(&n_logged, "out of memory: %d released textures dropped (%d overwritten, %d clean), %.0f MiB, %d kept",
dropped, overwritten, dropped - overwritten, freed / 1048576.0, nreleased);
}
// ---------------------------------------------------------------- uploads
@@ -1714,6 +1770,8 @@ void vk_texture_new_submit(void) {
if (!++submit_epoch) submit_epoch = 1;
coarse_ms = plat_now_ms();
sweep_pressure();
if (__atomic_load_n(&rt_oom_req, __ATOMIC_RELAXED) && __atomic_exchange_n(&rt_oom_req, 0, __ATOMIC_ACQUIRE))
oom_release();
static uint64_t log_at;
uint64_t f = __atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED) / 60;
if ((rt_trace & RT_TRACE_PERF) && f != log_at && tex_alias > 0) {
@@ -1740,8 +1798,9 @@ void vk_texture_new_submit(void) {
(unsigned long long)f * 60, (unsigned long long)ck, (unsigned long long)n_checks, (unsigned long long)calls,
(unsigned long long)untr);
n_checks = 0;
rt_log("perf: frame %llu: released textures kept %d, dropped under VRAM pressure %llu (%llu overwritten)",
(unsigned long long)f * 60, nreleased, (unsigned long long)n_pressure_drops,
rt_log("perf: frame %llu: released textures kept %d (%.0f MiB), dropped under VRAM pressure or the cap %llu "
"(%llu overwritten)", (unsigned long long)f * 60, nreleased, rel_bytes_total / 1048576.0,
(unsigned long long)n_pressure_drops,
(unsigned long long)n_pressure_overwritten);
n_pressure_drops = n_pressure_overwritten = 0;
}
@@ -2037,7 +2096,12 @@ static void write_back_n(Tex **v, int n) {
if (np) vk_upload_flush(1);
for (int i = 0; i < np; i++) {
WbPart *q = &p[i];
uint8_t *buf = malloc(q->g.img * (size_t)q->g.nz);
size_t bytes = q->g.img * (size_t)q->g.nz;
uint8_t *buf = malloc(bytes);
if (!buf) { // waits for memory with the texture lock held, after the release that needs no submit
vk_oom_release();
buf = rt_realloc_wait(NULL, bytes, "vk: texture write-back buffer");
}
if (!buf) rt_fatal("vk: out of memory for a texture write-back");
texels_read_take(q->e, &q->g, &q->t, buf);
storage_texels(&q->e->t, &q->g, &q->r, buf, 1);
@@ -2533,7 +2597,7 @@ void vk_texture_shutdown(void) {
by_addr = (nvn_hmap){.klen = 8};
samplers = (nvn_hmap){.klen = sizeof(samp_par)};
free(tslots), free(sslots);
tslots = NULL, sslots = NULL, ntslots = nsslots = 0, nreleased = 0;
tslots = NULL, sslots = NULL, ntslots = nsslots = 0, nreleased = 0, rel_bytes_total = 0;
rel_head = rel_tail = NULL;
if (sinfo) memset(sinfo, 0, sizeof *sinfo << 20), memset(sepoch, 0, sizeof *sepoch << 20); // no slot is registered: tokens 0
unlock();