mirror of
https://git.triforceproject.com/triforce/source
synced 2026-12-02 05:48:50 -04:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dad28e2d4b |
107
gpu/vk/ram_census.h
Normal file
107
gpu/vk/ram_census.h
Normal file
@@ -0,0 +1,107 @@
|
||||
// (Triforce, 12-01) The RAM census, RX_VK_RAM_CENSUS=1 (off unless set): what the GPU does with the game's memory that
|
||||
// the renderer imports.
|
||||
//
|
||||
// An import (vk_memory.cpp import_pool) hands a range of the game's memory to the driver as host memory; the driver locks
|
||||
// those pages, so Windows can never trim them out of RAM or page them out. In the 11-30 play log 8,256 MB of the game's
|
||||
// 10,240 MB in RAM were imported. This census says, for every import, how much of it the GPU reaches and how:
|
||||
// - kBindNarrow: a buffer binding of at most 16 MB reached the page (vertex, index, uniform, storage, indirect...)
|
||||
// - kBindWide: only a wider binding did (a whole pool bound for a few bytes: an upper bound of what it reads)
|
||||
// - kBindWrite: a binding the GPU writes through reached it
|
||||
// - kTexSampled: the storage of a texture the renderer made to sample (the image in VRAM is made from these bytes)
|
||||
// - kTexTarget: the storage of a render target or a texture the GPU draws into
|
||||
// A page is 64 KB of guest address (addresses below 1 TB, the native pools'; a virtual pool's texture is marked page by page
|
||||
// through its mapping). The bits are never cleared, so the census holds everything since the start of the run.
|
||||
// Once in a while (the memory line's thread, every 600 presents) triforce_ram_census.txt beside the exe gets one line an import
|
||||
// and the totals, and the log one summary line. Costs only with the switch on: a load of `on` at each binding otherwise.
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <memory>
|
||||
|
||||
namespace ram_census {
|
||||
|
||||
enum Kind : int { kBindNarrow, kBindWide, kBindWrite, kTexSampled, kTexTarget, kKinds };
|
||||
inline constexpr int kPageShift = 16;
|
||||
inline constexpr uint64_t kPages = 1ull << (40 - kPageShift); // (2^24 pages: 2 MB of bits a kind)
|
||||
inline constexpr uint64_t kWords = kPages / 64;
|
||||
inline constexpr uint64_t kNarrowMax = 16ull << 20;
|
||||
|
||||
inline bool on() {
|
||||
static const bool v = [] {
|
||||
const char* e = getenv("RX_VK_RAM_CENSUS");
|
||||
return e && atoi(e) != 0;
|
||||
}();
|
||||
return v;
|
||||
}
|
||||
|
||||
struct Maps {
|
||||
std::unique_ptr<std::atomic<uint64_t>[]> bits[kKinds];
|
||||
Maps() {
|
||||
for (auto& b : bits) {
|
||||
b.reset(new std::atomic<uint64_t>[kWords]);
|
||||
for (uint64_t i = 0; i < kWords; i++) b[i].store(0, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
};
|
||||
inline Maps& maps() {
|
||||
static Maps m;
|
||||
return m;
|
||||
}
|
||||
|
||||
/// Mark the pages of guest [lo, lo + size) as `k` (a word whose bits are all set already is not written)
|
||||
inline void mark(Kind k, uint64_t lo, uint64_t size) {
|
||||
if (!size || lo >= (1ull << 40)) return;
|
||||
uint64_t hi = lo + size;
|
||||
if (hi > (1ull << 40)) hi = 1ull << 40;
|
||||
const uint64_t p0 = lo >> kPageShift, p1 = (hi - 1) >> kPageShift;
|
||||
std::atomic<uint64_t>* b = maps().bits[k].get();
|
||||
for (uint64_t w = p0 / 64; w <= p1 / 64; w++) {
|
||||
const uint64_t first = w * 64, last = first + 63;
|
||||
const uint64_t a = p0 > first ? p0 - first : 0, z = p1 < last ? p1 - first : 63;
|
||||
const uint64_t mask = (z == 63 ? ~0ull : ((1ull << (z + 1)) - 1)) & ~((1ull << a) - 1);
|
||||
if ((b[w].load(std::memory_order_relaxed) & mask) != mask) b[w].fetch_or(mask, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
inline bool test(Kind k, uint64_t page) {
|
||||
return (maps().bits[k][page / 64].load(std::memory_order_relaxed) >> (page % 64)) & 1;
|
||||
}
|
||||
|
||||
/// A buffer binding of guest [lo, lo + size)
|
||||
inline void bind(uint64_t lo, uint64_t size, bool written) {
|
||||
mark(size <= kNarrowMax ? kBindNarrow : kBindWide, lo, size);
|
||||
if (written) mark(kBindWrite, lo, size);
|
||||
}
|
||||
|
||||
/// The bytes of [lo, hi) by what reached them: the classes the census file and the line give
|
||||
struct Count {
|
||||
uint64_t total = 0;
|
||||
uint64_t narrow = 0; // a narrow binding reached it (whatever else did)
|
||||
uint64_t wide_only = 0; // only a wide binding reached it, no texture
|
||||
uint64_t tex_only = 0; // a sampled texture's storage, no binding
|
||||
uint64_t target_only = 0; // a render target's storage, no binding
|
||||
uint64_t tex_and_wide = 0; // a texture's storage that only a wide binding also reached
|
||||
uint64_t written = 0; // a binding the GPU writes through reached it
|
||||
uint64_t none = 0; // nothing: no binding, no texture
|
||||
};
|
||||
inline void count(uint64_t lo, uint64_t hi, Count* c) {
|
||||
if (lo >= (1ull << 40)) return;
|
||||
if (hi > (1ull << 40)) hi = 1ull << 40;
|
||||
for (uint64_t page = lo >> kPageShift; (page << kPageShift) < hi; page++) {
|
||||
const uint64_t a = std::max(lo, page << kPageShift), z = std::min(hi, (page + 1) << kPageShift);
|
||||
const uint64_t n = z - a;
|
||||
c->total += n;
|
||||
const bool nar = test(kBindNarrow, page), wide = test(kBindWide, page), ts = test(kTexSampled, page),
|
||||
tt = test(kTexTarget, page);
|
||||
if (test(kBindWrite, page)) c->written += n;
|
||||
if (nar) c->narrow += n;
|
||||
else if (wide && (ts || tt)) c->tex_and_wide += n;
|
||||
else if (wide) c->wide_only += n;
|
||||
else if (ts) c->tex_only += n;
|
||||
else if (tt) c->target_only += n;
|
||||
else c->none += n;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ram_census
|
||||
@@ -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)
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
#include <filesystem>#include <vector>
|
||||
|
||||
#include "vk_texture.h"
|
||||
#include "ram_census.h" // ((Triforce, 12-01) RX_VK_RAM_CENSUS)
|
||||
#include "vk_menu.h"
|
||||
#include "vk_draw.h"
|
||||
#include "vk_programs.h" // ((Triforce) the programs' life log: programs_slow_upload
|
||||
@@ -3560,6 +3561,14 @@ Texture* create(const Key& key, const nvn_tex* t, VkFormat vf, bool astc, int bw
|
||||
x.gpu = t->gpu, x.d = t->d, x.L = t->L, x.nvn_format = t->d.format;
|
||||
x.guest = host->gpu_guest(t->gpu);
|
||||
x.guest_size = t->L.size;
|
||||
if (ram_census::on()) { // ((Triforce, 12-01) the RAM census: this texture's storage, ram_census.h)
|
||||
const ram_census::Kind k = as_target ? ram_census::kTexTarget : ram_census::kTexSampled;
|
||||
if (t->gpu < (1ull << 40)) ram_census::mark(k, t->gpu, t->L.size);
|
||||
else
|
||||
for (uint64_t off = 0; off < t->L.size; off += 1ull << ram_census::kPageShift)
|
||||
if (const uint64_t g = host->gpu_guest(t->gpu + off))
|
||||
ram_census::mark(k, g, std::min<uint64_t>(t->L.size - off, 1ull << ram_census::kPageShift));
|
||||
}
|
||||
x.astc = astc, x.block_w = bw, x.block_h = bh, x.bpb = bpb;
|
||||
int from = 0;
|
||||
vf = widened(vf, &from);
|
||||
|
||||
160
host/hos_mem.c
160
host/hos_mem.c
@@ -62,6 +62,12 @@ void hos_mem_init(uint64_t image_end) {
|
||||
hos_program_size = image_end - hos_image_base;
|
||||
hos_commit(HOS_SYSTEM_BASE, HOS_SYSTEM_END - HOS_SYSTEM_BASE);
|
||||
hos_mem_census_start(); /* (Triforce: the census line and the give-back, mkw_glue.c) */
|
||||
#if defined(_WIN32)
|
||||
{ /* ((Triforce, 12-01) the page file against the game's peak, a warning when it is too small: mkw_glue.c) */
|
||||
void hos_pagefile_check(void);
|
||||
hos_pagefile_check();
|
||||
}
|
||||
#endif
|
||||
low_hole[0][0] = 0x00100000ULL, low_hole[0][1] = HOS_SYSTEM_BASE;
|
||||
low_hole[1][0] = (image_end + 0xFFFFFULL) & ~0xFFFFFULL, low_hole[1][1] = HOS_HEAP_BASE;
|
||||
/* Retail Switch gives an application 3285 MB. HOS_MEMORY_MB overrides it: TOTK sizes its heap from this
|
||||
@@ -849,6 +855,160 @@ static int census_release(uint64_t lo, uint64_t hi) {
|
||||
CENSUS_UNLOCK();
|
||||
return ok;
|
||||
}
|
||||
/* ---- ((Triforce, 12-01) The zero pages of freed imports given back (HOS_MEM_ZERO_BACK, on; =0 off) -----------------------------
|
||||
An import (gpu/vk/vk_memory.cpp import_pool) commits its whole range and reads every page of it first, also the pages the game
|
||||
never had: its GPU pools lie in the heap (committed as it is touched) and in regions, and an import takes 4 to 16 MB chunks and
|
||||
whole pools around what a binding or a texture needs. After the import went those pages stayed committed, zeros, in RAM until
|
||||
Windows trimmed them and in the commit charge for good: 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 (the census line's "handed out"), on a tour 25 GB of commit at the peak, past what a
|
||||
16 GB PC with its page file can give (#bug-tracker: crashes and stutter on 16 GB PCs).
|
||||
Here the census's thread takes the freed ranges from the renderer (rx_freed_ranges) and, a MB at a time with the renderer's
|
||||
import locks held (rx_guest_release: no import holds the MB, none can start meanwhile), gives back each 64 KB block that is
|
||||
committed read-write and all zeros. A zero page given back is the same page to the game: its next touch commits it again,
|
||||
zeroed (mkw_glue.c commit_on_touch), whoever had been handed it. The race with the game's own writes:
|
||||
- the block is read first without any lock (most blocks with data end there);
|
||||
- then marked busy (zero_busy_lo/hi), made read-only, read again, and decommitted only if still all zeros, else made
|
||||
read-write again. A write after the read-only flip faults: commit_on_touch waits until the block is no longer busy and
|
||||
has the write tried again (on a reserved page then: committed, zeroed; on a read-write one: done);
|
||||
- the kernel does not fault pages in, so the calls that hand guest memory to it (file reads and writes) hold kio_lock shared
|
||||
from their touch to their end (hos_guest_kio_begin/end), and a block is given back only when kio_lock is free at once
|
||||
(never waited for: the renderer's pool lock is held here).
|
||||
Below 4 GB and in large pages nothing is given back (as census_release). Only with the heap committed as it is touched
|
||||
(hos_heap_on_touch, Windows): the first touch is what brings a page back. */
|
||||
#if defined(_WIN32)
|
||||
static SRWLOCK kio_lock = SRWLOCK_INIT;
|
||||
static volatile uint64_t zero_busy_lo, zero_busy_hi;
|
||||
static uint64_t zero_given, zero_scanned, zero_busy_io, zero_had_data, zero_refused;
|
||||
void hos_guest_kio_begin(uint64_t addr, uint64_t size) {
|
||||
AcquireSRWLockShared(&kio_lock);
|
||||
hos_guest_touch(addr, size);
|
||||
}
|
||||
void hos_guest_kio_end(void) { ReleaseSRWLockShared(&kio_lock); }
|
||||
/* The handler's part (mkw_glue.c commit_on_touch): 1 when guest lies in the block being given back; it returns once the block
|
||||
is done (given back or read-write again), and the access is to be tried again */
|
||||
int hos_zero_wait(uint64_t guest) {
|
||||
if (!(guest >= __atomic_load_n(&zero_busy_lo, __ATOMIC_SEQ_CST) && guest < __atomic_load_n(&zero_busy_hi, __ATOMIC_SEQ_CST)))
|
||||
return 0;
|
||||
while (guest >= __atomic_load_n(&zero_busy_lo, __ATOMIC_SEQ_CST) && guest < __atomic_load_n(&zero_busy_hi, __ATOMIC_SEQ_CST))
|
||||
YieldProcessor();
|
||||
return 1;
|
||||
}
|
||||
static int block_zero(const uint8_t *p) {
|
||||
const uint64_t *q = (const uint64_t *)p;
|
||||
for (int i = 0; i < 0x10000 / 8; i += 8)
|
||||
if (q[i] | q[i + 1] | q[i + 2] | q[i + 3] | q[i + 4] | q[i + 5] | q[i + 6] | q[i + 7]) return 0;
|
||||
return 1;
|
||||
}
|
||||
/* rx_guest_release's callback for [lo, hi) (a MB at most): the zero blocks given back; 1 when any was */
|
||||
static int zero_release(uint64_t lo, uint64_t hi) {
|
||||
extern uint64_t hos_large_lo, hos_large_hi;
|
||||
if (hos_large_hi && lo < hos_large_hi && hi > hos_large_lo) return 0;
|
||||
if (lo < (1ULL << 32)) return 0;
|
||||
/* (which pages are in RAM and read-write: QueryWorkingSetEx, one call for the MB. Not VirtualQuery: it walks every page of
|
||||
the committed region it is asked in, and the game's are GBs: 132,681 asks of it made a pass of 57 s of kernel time in the
|
||||
first lab tour, the pools' lock and the address space's held through it, the replay and the game's frees stalled for
|
||||
seconds. A page not in RAM is left: it costs no RAM now) */
|
||||
typedef struct { void *va; ULONG_PTR attr; } Wsx;
|
||||
typedef BOOL(WINAPI * QueryWs)(HANDLE, PVOID, DWORD);
|
||||
static QueryWs query;
|
||||
if (!query) query = (QueryWs)(void *)GetProcAddress(GetModuleHandleA("kernel32.dll"), "K32QueryWorkingSetEx");
|
||||
lo &= ~0xFFFFULL;
|
||||
if (!query || hi <= lo || hi - lo > (1ULL << 20)) return 0;
|
||||
static Wsx q[256]; /* (the census's thread alone) */
|
||||
const int npages = (int)((hi - lo) >> 12);
|
||||
for (int i = 0; i < npages; i++) q[i].va = (void *)GP(lo + ((uint64_t)i << 12)), q[i].attr = 0;
|
||||
if (!query(GetCurrentProcess(), q, (DWORD)(npages * sizeof *q))) return 0;
|
||||
uint64_t given = 0;
|
||||
for (uint64_t b = lo; b + 0x10000 <= hi; b += 0x10000) {
|
||||
const int first = (int)((b - lo) >> 12);
|
||||
int usable = 1;
|
||||
for (int i = first; i < first + 16 && usable; i++) {
|
||||
const ULONG_PTR a = q[i].attr;
|
||||
/* (Valid bit 0, Win32Protection bits 4-14, Shared bit 15, Locked bit 22) */
|
||||
usable = (a & 1) && ((a >> 4) & 0x7FF) == PAGE_READWRITE && !(a & (1u << 15)) && !(a & (1u << 22));
|
||||
}
|
||||
if (!usable) continue;
|
||||
zero_scanned++;
|
||||
if (!block_zero(GP(b))) { zero_had_data++; continue; }
|
||||
if (!TryAcquireSRWLockExclusive(&kio_lock)) { zero_busy_io++; continue; }
|
||||
__atomic_store_n(&zero_busy_lo, b, __ATOMIC_SEQ_CST);
|
||||
__atomic_store_n(&zero_busy_hi, b + 0x10000, __ATOMIC_SEQ_CST);
|
||||
DWORD old = 0;
|
||||
int done = 0;
|
||||
if (VirtualProtect(GP(b), 0x10000, PAGE_READONLY, &old)) {
|
||||
if (block_zero(GP(b)) && VirtualFree(GP(b), 0x10000, MEM_DECOMMIT)) done = 1;
|
||||
else VirtualProtect(GP(b), 0x10000, PAGE_READWRITE, &old), zero_refused++;
|
||||
}
|
||||
__atomic_store_n(&zero_busy_hi, 0, __ATOMIC_SEQ_CST);
|
||||
__atomic_store_n(&zero_busy_lo, 0, __ATOMIC_SEQ_CST);
|
||||
ReleaseSRWLockExclusive(&kio_lock);
|
||||
if (done) {
|
||||
CENSUS_LOCK();
|
||||
gc_change(&census, GC_HELD, b, b + 0x10000, 0);
|
||||
gc_change(&census, GC_KEPT, b, b + 0x10000, 0);
|
||||
CENSUS_UNLOCK();
|
||||
given += 0x10000;
|
||||
}
|
||||
}
|
||||
zero_given += given;
|
||||
return given > 0;
|
||||
}
|
||||
/* A pass (the census's thread): the ranges freed since the last one taken in, then up to max_bytes of them looked at, a MB at a
|
||||
time. The bytes given back this pass */
|
||||
int64_t hos_mem_zero_give_back(uint64_t max_bytes) {
|
||||
static int on = -1;
|
||||
if (on < 0) {
|
||||
const char *e = getenv("HOS_MEM_ZERO_BACK");
|
||||
on = !(e && atoi(e) == 0) && hos_heap_on_touch && hos_mem_census_on();
|
||||
hos_log("mem: the zero pages of freed imports given back: %s (HOS_MEM_ZERO_BACK=0: off)",
|
||||
on ? "on" : hos_heap_on_touch ? "off" : "off (the heap is committed whole)");
|
||||
}
|
||||
if (!on) return 0;
|
||||
int rx_freed_ranges(uint64_t (*out)[2], int max); /* (rx_backend.c) */
|
||||
int rx_guest_release(uint64_t lo, uint64_t hi, int (*release)(uint64_t lo, uint64_t hi));
|
||||
static uint64_t (*todo)[2];
|
||||
static int ntodo, captodo;
|
||||
uint64_t got[256][2];
|
||||
for (int n; (n = rx_freed_ranges(got, 256)) > 0;) {
|
||||
if (ntodo + n > captodo) {
|
||||
const int cap = (ntodo + n) * 2;
|
||||
uint64_t(*grown)[2] = (uint64_t(*)[2])realloc(todo, (size_t)cap * sizeof *todo);
|
||||
if (!grown) break;
|
||||
todo = grown, captodo = cap;
|
||||
}
|
||||
for (int i = 0; i < n; i++) todo[ntodo][0] = got[i][0] & ~0xFFFFULL, todo[ntodo][1] = got[i][1], ntodo++;
|
||||
if (n < 256) break;
|
||||
}
|
||||
const uint64_t given0 = zero_given;
|
||||
uint64_t looked = 0;
|
||||
const int64_t stall0 = stall_host_begin();
|
||||
const int64_t t0 = hos_now_ns();
|
||||
while (ntodo > 0 && looked < max_bytes && hos_now_ns() - t0 < 40000000) { /* (40 ms a pass at most: the rest next pass) */
|
||||
uint64_t *r = todo[ntodo - 1];
|
||||
const uint64_t lo = r[0], hi = r[1] - r[0] > (1ULL << 20) ? r[0] + (1ULL << 20) : r[1];
|
||||
const int io = hos_guest_io_begin(GP(lo), hi - lo); /* (the lazy write-back's pages there paid first, as census_offer) */
|
||||
rx_guest_release(lo, hi, zero_release);
|
||||
hos_guest_io_end(io);
|
||||
looked += hi - lo;
|
||||
if (hi >= r[1]) ntodo--;
|
||||
else r[0] = hi;
|
||||
}
|
||||
stall_host_end(STALL_HOST_GIVE_BACK, stall0, zero_given - given0);
|
||||
const uint64_t given = zero_given - given0;
|
||||
static int said;
|
||||
if (given && (said++ < 40 || said % 64 == 0))
|
||||
hos_log("mem: %llu MB of zero pages under freed imports given back (%llu MB in all; %llu MB looked at, %d ranges left; blocks: "
|
||||
"%llu scanned, %llu with data, %llu skipped beside a file call, %llu written meanwhile)", (unsigned long long)(given >> 20),
|
||||
(unsigned long long)(zero_given >> 20), (unsigned long long)(looked >> 20), ntodo, (unsigned long long)zero_scanned,
|
||||
(unsigned long long)zero_had_data, (unsigned long long)zero_busy_io, (unsigned long long)zero_refused);
|
||||
return (int64_t)given;
|
||||
}
|
||||
#else
|
||||
void hos_guest_kio_begin(uint64_t addr, uint64_t size) { hos_guest_touch(addr, size); }
|
||||
void hos_guest_kio_end(void) {}
|
||||
int hos_zero_wait(uint64_t guest) { (void)guest; return 0; }
|
||||
int64_t hos_mem_zero_give_back(uint64_t max_bytes) { (void)max_bytes; return 0; }
|
||||
#endif
|
||||
/* One kept run offered: the lazy write-back's pages there paid first (as FreeMemoryPages does), then the renderer asked */
|
||||
static int census_offer(void *ctx, uint64_t lo, uint64_t hi) {
|
||||
(void)ctx;
|
||||
|
||||
@@ -188,6 +188,89 @@ DWORD WINAPI hos_out_of_memory_box(LPVOID unused) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---- ((Triforce, 12-01) The page file checked at the start (pagefile_rule.h has why and the rule) ---------------------------
|
||||
A line in the log every start; and when the commit limit can never reach what the game needs, a warning that says what to
|
||||
change, once for the page file's settings as they are (triforce_pagefile_warned.txt beside the game: shown again only when
|
||||
they change). On a thread of its own: the start waits for nothing. HOS_PAGEFILE_CHECK=0: neither; =2: the warning whatever the
|
||||
rule says (to see it) */
|
||||
#if defined(_WIN32)
|
||||
#include "pagefile_rule.h"
|
||||
static char pagefile_box_text[1400];
|
||||
static DWORD WINAPI pagefile_box(LPVOID unused) {
|
||||
(void)unused;
|
||||
MessageBoxA(NULL, pagefile_box_text, "Triforce: your page file is too small", MB_OK | MB_ICONWARNING | MB_TOPMOST);
|
||||
return 0;
|
||||
}
|
||||
static DWORD WINAPI pagefile_check_main(LPVOID unused) {
|
||||
(void)unused;
|
||||
const char *e = getenv("HOS_PAGEFILE_CHECK");
|
||||
const int mode = e ? atoi(e) : 1;
|
||||
if (mode == 0) return 0;
|
||||
char multi[2048];
|
||||
DWORD size = sizeof multi - 2;
|
||||
memset(multi, 0, sizeof multi);
|
||||
const LONG r = RegGetValueA(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Memory Management",
|
||||
"PagingFiles", RRF_RT_REG_MULTI_SZ, NULL, multi, &size);
|
||||
const PfSettings s = pf_parse(r == ERROR_SUCCESS ? multi : "", r == ERROR_SUCCESS ? (size_t)size : 0);
|
||||
MEMORYSTATUSEX ms;
|
||||
ms.dwLength = sizeof ms;
|
||||
if (!GlobalMemoryStatusEx(&ms)) return 0;
|
||||
const double gb = 1024.0 * 1024.0 * 1024.0;
|
||||
const double ram = (double)ms.ullTotalPhys / gb, limit = (double)ms.ullTotalPageFile / gb,
|
||||
in_use = (double)(ms.ullTotalPageFile - ms.ullAvailPageFile) / gb;
|
||||
double disk = 0;
|
||||
if (s.kind == PF_KIND_MANAGED && s.drive) {
|
||||
char root[4] = {s.drive, ':', '\\', 0};
|
||||
ULARGE_INTEGER avail;
|
||||
if (GetDiskFreeSpaceExA(root, &avail, NULL, NULL)) disk = (double)avail.QuadPart / gb;
|
||||
}
|
||||
const PfVerdict v = pf_decide(&s, ram, limit, in_use, disk);
|
||||
static const char *kinds[] = {"none", "managed by Windows", "a fixed size"};
|
||||
hos_log("mem: page file: %s%s%c%s (%s %.1f GB); RAM %.1f GB, commit limit %.1f GB now, %.1f GB in use before the game; the "
|
||||
"limit can reach %.1f GB, the game needs %.1f GB: %s (HOS_PAGEFILE_CHECK)", kinds[s.kind], s.drive ? " on " : "",
|
||||
s.drive ? s.drive : ' ', s.drive ? ":" : "", s.kind == PF_KIND_MANAGED ? "its drive has free" : "at most",
|
||||
s.kind == PF_KIND_FIXED ? s.fixed_max_gb : s.kind == PF_KIND_MANAGED ? disk : 0.0,
|
||||
ram, limit, in_use, v.reach_gb, v.need_gb,
|
||||
v.verdict == PF_OK ? "enough" : v.verdict == PF_SHORT_NONE ? "SHORT, no page file" : v.verdict == PF_SHORT_FIXED ?
|
||||
"SHORT, the fixed page file is too small" : "SHORT, the page file's drive is nearly full");
|
||||
if (v.verdict == PF_OK && mode != 2) return 0;
|
||||
/* (once for these settings: the kind, the drive, the fixed size and the RAM) */
|
||||
char sig[96], path[MAX_PATH + 40], had[96] = "";
|
||||
snprintf(sig, sizeof sig, "%d %c %.0f %.0f %d", s.kind, s.drive ? s.drive : '-', s.fixed_max_gb, ram, v.verdict);
|
||||
const DWORD n = hos_game_path_a(path, MAX_PATH);
|
||||
if (n && n < MAX_PATH) {
|
||||
char *slash = strrchr(path, '\\');
|
||||
if (slash) strcpy(slash + 1, "triforce_pagefile_warned.txt");
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (f) {
|
||||
const size_t k = fread(had, 1, sizeof had - 1, f);
|
||||
had[k] = 0;
|
||||
fclose(f);
|
||||
}
|
||||
if (!strcmp(had, sig) && mode != 2) {
|
||||
hos_log("mem: page file: warned before for these settings (delete triforce_pagefile_warned.txt to see it again)");
|
||||
return 0;
|
||||
}
|
||||
if ((f = fopen(path, "wb"))) fputs(sig, f), fclose(f);
|
||||
}
|
||||
const char *what = v.verdict == PF_SHORT_NONE ? "Windows has no page file"
|
||||
: v.verdict == PF_SHORT_FIXED ? "Windows' page file is set to a fixed size that is too small"
|
||||
: "the drive that holds Windows' page file is nearly full, so the page file cannot grow";
|
||||
snprintf(pagefile_box_text, sizeof pagefile_box_text,
|
||||
"Triforce can use up to about %.0f GB of memory (RAM plus the page file) at its peak, and %s: this PC can reach "
|
||||
"%.0f GB, it needs about %.0f GB. When it runs out, the game closes.\n\n"
|
||||
"To fix it: open Windows' Settings > System > About > Advanced system settings > Performance: Settings > "
|
||||
"Advanced > Virtual memory: Change, tick \"Automatically manage paging file size for all drives\", then restart "
|
||||
"the PC.%s\n\n"
|
||||
"This warning is shown once for these settings.",
|
||||
24.0, what, v.reach_gb, v.need_gb,
|
||||
v.verdict == PF_SHORT_DISK ? " Also free up space on that drive (at least 20 GB)." : "");
|
||||
CloseHandle(CreateThread(NULL, 0, pagefile_box, NULL, 0, NULL));
|
||||
return 0;
|
||||
}
|
||||
void hos_pagefile_check(void) { CloseHandle(CreateThread(NULL, 0, pagefile_check_main, NULL, 0, NULL)); }
|
||||
#endif
|
||||
|
||||
static LONG CALLBACK commit_on_touch(EXCEPTION_POINTERS *info) {
|
||||
EXCEPTION_RECORD *rec = info->ExceptionRecord;
|
||||
if (rec->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || rec->NumberParameters < 2) return EXCEPTION_CONTINUE_SEARCH;
|
||||
@@ -195,6 +278,12 @@ static LONG CALLBACK commit_on_touch(EXCEPTION_POINTERS *info) {
|
||||
if (p < A64_MEM || p >= A64_MEM + HOS_GUEST_SPACE) return EXCEPTION_CONTINUE_SEARCH;
|
||||
const uint64_t guest = (uint64_t)(p - A64_MEM);
|
||||
if (guest < 0x100000) return EXCEPTION_CONTINUE_SEARCH; /* (a null pointer: the game's own fault) */
|
||||
/* ((Triforce, 12-01) a block of zeros being given back (hos_mem.c zero_release) is read-only for a moment: the write waits
|
||||
for it, then is tried again */
|
||||
{
|
||||
int hos_zero_wait(uint64_t guest);
|
||||
if (hos_zero_wait(guest)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
MEMORY_BASIC_INFORMATION mbi;
|
||||
if (!VirtualQuery(p, &mbi, sizeof mbi)) return EXCEPTION_CONTINUE_SEARCH;
|
||||
#ifdef _WIN32
|
||||
@@ -1335,6 +1424,10 @@ static DWORD WINAPI census_main(void *unused) {
|
||||
}
|
||||
}
|
||||
}
|
||||
{ /* ((Triforce, 12-01) the zero pages under freed imports (hos_mem.c), every pass whatever the RAM */
|
||||
int64_t hos_mem_zero_give_back(uint64_t max_bytes);
|
||||
hos_mem_zero_give_back(512ULL << 20);
|
||||
}
|
||||
if (!census_line) continue;
|
||||
hos_mem_census(&c);
|
||||
char line[1024];
|
||||
@@ -1351,7 +1444,7 @@ void hos_mem_census_start(void) {
|
||||
census_line = !(e && atoi(e) <= 0);
|
||||
census_every = e && atoi(e) > 0 ? atoi(e) : 5;
|
||||
census_give_back = g ? atoi(g) : 0;
|
||||
if (!census_line && census_give_back <= 0) return;
|
||||
if (!census_line && census_give_back <= 0) return; /* ((Triforce, 12-01) the zero give-back runs on this thread too) */
|
||||
char every[32] = "off";
|
||||
if (census_line) snprintf(every, sizeof every, "every %d s", census_every);
|
||||
hos_log("mem: census %s; give-back %s (HOS_MEM_CENSUS, HOS_MEM_GIVE_BACK)", every,
|
||||
|
||||
@@ -2341,10 +2341,12 @@ HLE(_ZN2nn5audio16AppendWaveBufferEPNS0_9VoiceTypeEPKNS0_10WaveBufferE) {
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (f) {
|
||||
fwrite(v->coefs, 1, 32, f);
|
||||
hos_guest_touch(w.buffer, (uint64_t)w.size); /* ((Triforce, 11-21, MEM-09) fwrite hands it to the kernel) */
|
||||
void hos_guest_kio_begin(uint64_t addr, uint64_t size), hos_guest_kio_end(void);
|
||||
hos_guest_kio_begin(w.buffer, (uint64_t)w.size); /* ((Triforce, 11-21, MEM-09; 12-01) fwrite hands it to the kernel) */
|
||||
const int io = hos_guest_io_begin(GP(w.buffer), (uint64_t)w.size); /* (Triforce: rx_backend.c) */
|
||||
fwrite(GP(w.buffer), 1, (size_t)w.size, f);
|
||||
hos_guest_io_end(io);
|
||||
hos_guest_kio_end();
|
||||
fclose(f);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -740,7 +740,8 @@ static uint64_t read_at(Ctx *c, uint64_t id, int64_t off, uint64_t buf, uint64_t
|
||||
const int64_t stall0 = stall_host_begin(); /* ((Triforce, OS-51) the read itself, not the wait for the core after it) */
|
||||
/* ((Triforce, 11-21, MEM-09) the kernel's ReadFile does not fault pages in: heap pages nothing touched yet (committed
|
||||
as they are touched now, heap_commit.h) are touched for it first) */
|
||||
hos_guest_touch(buf, size);
|
||||
void hos_guest_kio_begin(uint64_t addr, uint64_t size), hos_guest_kio_end(void);
|
||||
hos_guest_kio_begin(buf, size); /* ((Triforce, 12-01) and no zero block given back under the read: hos_mem.c) */
|
||||
const int io = hos_guest_io_begin(GP(buf), size); /* (Triforce: the kernel writes there: rx_backend.c) */
|
||||
while (done < size) {
|
||||
OVERLAPPED ov = {0};
|
||||
@@ -752,6 +753,7 @@ static uint64_t read_at(Ctx *c, uint64_t id, int64_t off, uint64_t buf, uint64_t
|
||||
done += got;
|
||||
}
|
||||
hos_guest_io_end(io);
|
||||
hos_guest_kio_end();
|
||||
stall_host_end(STALL_HOST_READ, stall0, done);
|
||||
if (away) hos_vcore_back();
|
||||
HOS_WRITTEN(GP(buf), (size_t)done); /* (into guest memory: the GPU may read it) */
|
||||
@@ -808,10 +810,12 @@ HLE(_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE) {
|
||||
it. HOS_WRITE_KEEP_CORE=1: the core held through writes and flushes, as before */
|
||||
const int away = fs_write_keep_core() ? 0 : hos_vcore_away();
|
||||
const int64_t stall0 = stall_host_begin(); /* ((Triforce, OS-51) the host's part of a long frame: stall_host.h) */
|
||||
hos_guest_touch(ARG(2), ARG(3)); /* ((Triforce, 11-21, MEM-09) as the read: touched before the kernel reads them) */
|
||||
void hos_guest_kio_begin(uint64_t addr, uint64_t size), hos_guest_kio_end(void);
|
||||
hos_guest_kio_begin(ARG(2), ARG(3)); /* ((Triforce, 11-21, MEM-09) as the read: touched before the kernel reads them) */
|
||||
const int io = hos_guest_io_begin(GP(ARG(2)), ARG(3)); /* (Triforce: the kernel reads there: rx_backend.c) */
|
||||
WriteFile(fh->h, GP(ARG(2)), (DWORD)ARG(3), &put, &ov);
|
||||
hos_guest_io_end(io);
|
||||
hos_guest_kio_end();
|
||||
stall_host_end(STALL_HOST_WRITE, stall0, put);
|
||||
if (away) hos_vcore_back();
|
||||
}
|
||||
|
||||
97
host/pagefile_rule.h
Normal file
97
host/pagefile_rule.h
Normal file
@@ -0,0 +1,97 @@
|
||||
/* (Triforce, 12-01) Whether this PC's commit limit (RAM + page file) can ever hold the game: the page file's settings read at
|
||||
the start, and a warning when they cannot (mkw_glue.c hos_pagefile_check). Apart from Windows so that
|
||||
tests/test_pagefile_rule.py runs it on many made-up PCs.
|
||||
|
||||
Why: 16 GB players crash when Windows runs out of commit ("Windows is out of memory", mkw_glue.c hos_out_of_memory_box, shown
|
||||
only once it has happened). Eleven 16 GB players' logs of 11-19 had commit limits of 29 to 58 GB, set by their page files,
|
||||
and five of them were within 1.5 GB of theirs. The game itself takes some 23.5-24.5 GB of commit at its peak on a lab tour of
|
||||
eleven areas (12-01, v0.9.0 + the RAM work: the game's own memory ~9.4 GB, the graphics memory's charge ~8.4, the renderer's
|
||||
~5.6), and none of that could be cut without hitches. A page file Windows manages grows as it is needed, up to three times
|
||||
the RAM, while its drive has room; a fixed one never passes its maximum; none at all leaves the RAM alone.
|
||||
|
||||
The rule: the most the limit can reach (RAM + the page file at its largest: a fixed one's maximum; a managed one's size now
|
||||
grown by what its drive has free, keeping 2 GB, up to three times the RAM, or 4 GB on a small PC) against what is needed (the
|
||||
commit in use before the game, plus the game's peak and a margin: 26 GB; never under 36 GB). Short: a warning, which names
|
||||
what to change. */
|
||||
#ifndef PAGEFILE_RULE_H
|
||||
#define PAGEFILE_RULE_H
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
enum { PF_KIND_NONE = 0, PF_KIND_MANAGED = 1, PF_KIND_FIXED = 2 };
|
||||
enum { PF_OK = 0, PF_SHORT_NONE = 1, PF_SHORT_FIXED = 2, PF_SHORT_DISK = 3 };
|
||||
|
||||
typedef struct {
|
||||
int kind; /* PF_KIND_*: managed wins when one file of several is managed */
|
||||
char drive; /* the managed file's drive letter ('C'), or the first fixed file's; 0 when none */
|
||||
double fixed_max_gb; /* the fixed files' maximum sizes, summed */
|
||||
} PfSettings;
|
||||
|
||||
/* The registry's PagingFiles value (REG_MULTI_SZ: strings one after another, each ended by a 0, an empty one at the end), n
|
||||
bytes: "?:\pagefile.sys" (every drive, Windows manages it), "C:\pagefile.sys 0 0" (managed, on C:), "C:\pagefile.sys 4096 8192"
|
||||
(fixed: initial and maximum in MB), or nothing (no page file) */
|
||||
static inline PfSettings pf_parse(const char *multi, size_t n) {
|
||||
PfSettings s = {PF_KIND_NONE, 0, 0.0};
|
||||
size_t at = 0;
|
||||
while (multi && at < n && multi[at]) {
|
||||
const char *e = multi + at;
|
||||
size_t len = 0;
|
||||
while (at + len < n && e[len]) len++;
|
||||
char one[300];
|
||||
const size_t k = len < sizeof one - 1 ? len : sizeof one - 1;
|
||||
memcpy(one, e, k);
|
||||
one[k] = 0;
|
||||
at += len + 1;
|
||||
if (k < 2) continue;
|
||||
char *sp = strchr(one, ' ');
|
||||
long long init = 0, max = 0;
|
||||
int sizes = 0;
|
||||
if (sp) {
|
||||
char *end = NULL;
|
||||
init = strtoll(sp + 1, &end, 10);
|
||||
if (end && *end == ' ') max = strtoll(end + 1, NULL, 10), sizes = 1;
|
||||
}
|
||||
const char d = one[0] >= 'a' && one[0] <= 'z' ? (char)(one[0] - 32) : one[0];
|
||||
if (one[0] == '?' || !sizes || (init == 0 && max == 0)) { /* (managed: every drive, or a drive with no sizes) */
|
||||
s.kind = PF_KIND_MANAGED;
|
||||
s.drive = one[0] == '?' ? 'C' : d;
|
||||
} else if (s.kind != PF_KIND_MANAGED) {
|
||||
if (s.kind == PF_KIND_NONE) s.drive = d;
|
||||
s.kind = PF_KIND_FIXED;
|
||||
s.fixed_max_gb += (double)(max > init ? max : init) / 1024.0;
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
double reach_gb; /* the most the commit limit can reach */
|
||||
double need_gb; /* what the game needs it to reach */
|
||||
int verdict; /* PF_OK, or why it is short */
|
||||
} PfVerdict;
|
||||
|
||||
/* ram_gb: the PC's RAM; limit_gb: the commit limit now (RAM + the page file as it is now); in_use_gb: the commit in use now,
|
||||
before the game's own; disk_free_gb: free space on the managed file's drive (unused otherwise) */
|
||||
static inline PfVerdict pf_decide(const PfSettings *s, double ram_gb, double limit_gb, double in_use_gb, double disk_free_gb) {
|
||||
PfVerdict v;
|
||||
const double now_file = limit_gb > ram_gb ? limit_gb - ram_gb : 0.0;
|
||||
if (s->kind == PF_KIND_MANAGED) {
|
||||
const double cap = ram_gb * 3 > 4 ? ram_gb * 3 : 4;
|
||||
double grown = now_file + (disk_free_gb > 2 ? disk_free_gb - 2 : 0);
|
||||
if (grown > cap) grown = cap;
|
||||
if (grown < now_file) grown = now_file;
|
||||
v.reach_gb = ram_gb + grown;
|
||||
} else if (s->kind == PF_KIND_FIXED) {
|
||||
v.reach_gb = ram_gb + (s->fixed_max_gb > now_file ? s->fixed_max_gb : now_file);
|
||||
} else {
|
||||
v.reach_gb = limit_gb > ram_gb ? limit_gb : ram_gb;
|
||||
}
|
||||
v.need_gb = in_use_gb + 26 > 36 ? in_use_gb + 26 : 36;
|
||||
v.verdict = v.reach_gb >= v.need_gb ? PF_OK
|
||||
: s->kind == PF_KIND_NONE ? PF_SHORT_NONE
|
||||
: s->kind == PF_KIND_FIXED ? PF_SHORT_FIXED : PF_SHORT_DISK;
|
||||
return v;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -766,6 +766,19 @@ int rx_guest_release(uint64_t lo, uint64_t hi, int (*release)(uint64_t lo, uint6
|
||||
if (away) hos_vcore_back();
|
||||
return r == 1 ? 1 : 0;
|
||||
}
|
||||
/* ((Triforce, 12-01) The ranges of guest memory whose Vulkan imports were freed since the last ask (the back end's
|
||||
mkwvk_freed_ranges, found by name): hos_mem.c hos_mem_zero_give_back looks there for pages to give back. The count, 0 when
|
||||
there is no such back end */
|
||||
int rx_freed_ranges(uint64_t (*out)[2], int max) {
|
||||
if (!vk || max <= 0) return 0;
|
||||
static int (*volatile fn)(uint64_t (*)[2], int);
|
||||
static volatile int looked;
|
||||
if (!looked) {
|
||||
fn = (int (*)(uint64_t (*)[2], int))(void *)GetProcAddress(vk_module, "mkwvk_freed_ranges");
|
||||
looked = 1;
|
||||
}
|
||||
return fn ? fn(out, max) : 0;
|
||||
}
|
||||
/* (Triforce) The census's second line (mkw_glue.c census_main): the Vulkan back end's big holders of memory, as text (its
|
||||
mkwvk_memory_holders, found by name). Its length, 0 when there is none */
|
||||
int rx_memory_holders(char *out, size_t n) {
|
||||
|
||||
@@ -96,6 +96,13 @@ def main():
|
||||
"the heap is left reserved on Linux too, or committed whole on Windows")
|
||||
|
||||
touch = block(glue, "static LONG CALLBACK commit_on_touch(")
|
||||
# ((Triforce, 12-01) a write into a block of zeros being given back (hos_mem.c zero_release) waits for it and is tried again,
|
||||
# first thing after the guest checks: checked here, then left out of the order below)
|
||||
zero_wait = (" {\n int hos_zero_wait(uint64_t guest);\n if (hos_zero_wait(guest)) return EXCEPTION_CONTINUE_EXECUTION;\n"
|
||||
" }\n")
|
||||
touch = touch.replace("\r\n", "\n")
|
||||
check(zero_wait in touch, "commit_on_touch does not wait out a block of zeros being given back (hos_zero_wait)")
|
||||
touch = touch.replace(zero_wait, "")
|
||||
in_order(touch, ["if (!VirtualQuery(p, &mbi, sizeof mbi)) return EXCEPTION_CONTINUE_SEARCH;", "#ifdef _WIN32",
|
||||
"if (heap_touch_again(mbi.State == MEM_COMMIT, mbi.Protect == PAGE_READWRITE, rec->ExceptionInformation[0]))",
|
||||
"return EXCEPTION_CONTINUE_EXECUTION;", "#endif",
|
||||
@@ -130,11 +137,11 @@ def main():
|
||||
"SetMemoryHeapSize does not say the heap is committed as it is touched: the kernel calls' buffers are not touched")
|
||||
|
||||
read = block(fs, "static uint64_t read_at(")
|
||||
in_order(read, ["const int away = hos_vcore_away();", "hos_guest_touch(buf, size);", "const int io = hos_guest_io_begin(GP(buf), size);",
|
||||
in_order(read, ["const int away = hos_vcore_away();", "hos_guest_kio_begin(buf, size);", "const int io = hos_guest_io_begin(GP(buf), size);",
|
||||
"ReadFile(fh->h, GP(buf + done)"],
|
||||
"read_at does not touch its buffer before the kernel's read (with no virtual core held)")
|
||||
write = block(fs, "HLE(_ZN2nn2fs9WriteFileENS0_10FileHandleElPKvmRKNS0_11WriteOptionE)")
|
||||
in_order(write, ["hos_guest_touch(ARG(2), ARG(3));", "const int io = hos_guest_io_begin(GP(ARG(2)), ARG(3));", "WriteFile(fh->h, GP(ARG(2))"],
|
||||
in_order(write, ["hos_guest_kio_begin(ARG(2), ARG(3));", "const int io = hos_guest_io_begin(GP(ARG(2)), ARG(3));", "WriteFile(fh->h, GP(ARG(2))"],
|
||||
"WriteFile does not touch its buffer before the kernel's write")
|
||||
check("void hos_guest_touch(uint64_t addr, uint64_t size);" in (HOST / "hos.h").read_text(encoding="utf-8"),
|
||||
"hos.h does not declare hos_guest_touch")
|
||||
|
||||
97
tests/test_pagefile_rule.py
Normal file
97
tests/test_pagefile_rule.py
Normal file
@@ -0,0 +1,97 @@
|
||||
"""The page-file check at the start (host/pagefile_rule.h, mkw_glue.c hos_pagefile_check; no game).
|
||||
|
||||
(Triforce, 12-01.) 16 GB players crash when RAM + page file run out; the game takes ~24 GB of commit at its peak. This compiles
|
||||
pagefile_rule.h alone and runs its parse of the registry's PagingFiles value and its verdict on made-up PCs: no page file,
|
||||
fixed ones small and large, a managed one with a full or a roomy drive; and reads mkw_glue.c for the check's call, its
|
||||
once-per-settings note and its switch.
|
||||
|
||||
python -I -B tests/test_pagefile_rule.py [--cc clang]
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HOST = ROOT / "host"
|
||||
RUN_ALL_ARGS = ["--cc", "clang"]
|
||||
|
||||
PROG = r'''
|
||||
#include <stdio.h>
|
||||
#include "pagefile_rule.h"
|
||||
static void parse(const char *name, const char *m, size_t n) {
|
||||
PfSettings s = pf_parse(m, n);
|
||||
printf("parse %s %d %c %.2f\n", name, s.kind, s.drive ? s.drive : '-', s.fixed_max_gb);
|
||||
}
|
||||
static void decide(const char *name, int kind, double fixed, double ram, double limit, double in_use, double disk) {
|
||||
PfSettings s = {kind, 'C', fixed};
|
||||
PfVerdict v = pf_decide(&s, ram, limit, in_use, disk);
|
||||
printf("decide %s %d %.1f %.1f\n", name, v.verdict, v.reach_gb, v.need_gb);
|
||||
}
|
||||
int main(void) {
|
||||
parse("auto", "?:\\pagefile.sys\0\0", 17);
|
||||
parse("managed_d", "D:\\pagefile.sys 0 0\0\0", 21);
|
||||
parse("fixed", "C:\\pagefile.sys 4096 8192\0\0", 27);
|
||||
parse("fixed2", "C:\\pagefile.sys 2048 2048\0E:\\pagefile.sys 1024 4096\0\0", 54);
|
||||
parse("none", "\0\0", 2);
|
||||
parse("empty", "", 0);
|
||||
parse("mixed", "C:\\pagefile.sys 1024 2048\0D:\\pagefile.sys 0 0\0\0", 47);
|
||||
decide("16_none", 0, 0, 16, 16, 6, 100);
|
||||
decide("16_fixed8", 2, 8, 16, 24, 6, 100);
|
||||
decide("16_fixed24", 2, 24, 16, 20, 6, 100);
|
||||
decide("16_managed_roomy", 1, 0, 16, 19, 6, 200);
|
||||
decide("16_managed_full", 1, 0, 16, 19, 6, 3);
|
||||
decide("32_none", 0, 0, 32, 32, 8, 100);
|
||||
decide("32_managed", 1, 0, 32, 57, 28, 300);
|
||||
decide("16_busy_managed", 1, 0, 16, 30, 14, 10);
|
||||
return 0;
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def check(ok, why):
|
||||
if not ok:
|
||||
raise SystemExit("FAIL: " + why)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--cc", default="clang")
|
||||
a = ap.parse_args()
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src = Path(d) / "t.c"
|
||||
exe = Path(d) / "t.exe"
|
||||
src.write_text(PROG)
|
||||
subprocess.run([a.cc, "-std=c11", "-Wall", "-Werror", "-I", str(HOST), str(src), "-o", str(exe)], check=True)
|
||||
out = subprocess.run([str(exe)], capture_output=True, text=True, check=True).stdout.split("\n")
|
||||
r = {}
|
||||
for line in out:
|
||||
f = line.split()
|
||||
if f:
|
||||
r[(f[0], f[1])] = f[2:]
|
||||
check(r[("parse", "auto")][:2] == ["1", "C"], "?:\\pagefile.sys is managed, on C: %s" % r[("parse", "auto")])
|
||||
check(r[("parse", "managed_d")][:2] == ["1", "D"], "a drive with 0 0 is managed there")
|
||||
check(r[("parse", "fixed")] == ["2", "C", "8.00"], "fixed 4096..8192 MB: 8 GB at most %s" % r[("parse", "fixed")])
|
||||
check(r[("parse", "fixed2")] == ["2", "C", "6.00"], "two fixed files: their maximums summed %s" % r[("parse", "fixed2")])
|
||||
check(r[("parse", "none")][0] == "0" and r[("parse", "empty")][0] == "0", "no strings: no page file")
|
||||
check(r[("parse", "mixed")][:2] == ["1", "D"], "one managed file of several: managed")
|
||||
v = {k[1]: (int(x[0]), float(x[1]), float(x[2])) for k, x in r.items() if k[0] == "decide"}
|
||||
check(v["16_none"][0] == 1, "16 GB with no page file: short (none)")
|
||||
check(v["16_fixed8"][0] == 2 and v["16_fixed8"][1] == 24.0, "16 GB + 8 GB fixed: reach 24, short (fixed)")
|
||||
check(v["16_fixed24"][0] == 0 and v["16_fixed24"][1] == 40.0, "16 GB + 24 GB fixed: reach 40, enough")
|
||||
check(v["16_managed_roomy"][0] == 0 and v["16_managed_roomy"][1] == 64.0, "managed, roomy drive: up to 3x RAM")
|
||||
check(v["16_managed_full"][0] == 3, "managed on a full drive: short (disk)")
|
||||
check(v["32_none"][0] == 1, "32 GB with no page file: short (needs 36)")
|
||||
check(v["32_managed"][0] == 0 and v["32_managed"][2] == 54.0, "this PC: enough; need = in use 28 + 26")
|
||||
check(v["16_busy_managed"][0] == 3 and v["16_busy_managed"][2] == 40.0, "busy 16 GB PC, 10 GB free disk: short (disk)")
|
||||
glue = (HOST / "mkw_glue.c").read_text(encoding="utf-8")
|
||||
check("pf_decide(" in glue and "pf_parse(" in glue, "mkw_glue.c runs the rule")
|
||||
check("triforce_pagefile_warned.txt" in glue, "the warning once per page-file settings")
|
||||
check("HOS_PAGEFILE_CHECK" in glue, "the switch")
|
||||
mem = (HOST / "hos_mem.c").read_text(encoding="utf-8")
|
||||
check("hos_pagefile_check()" in mem, "called at the start (hos_mem_init)")
|
||||
print("ok: page-file rule")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user