"""The descriptor templates' wide per-thread table (gpu/vk/tpltable.h; vk_draw.cpp set_template, push_template; no game, no GPU). (Triforce, 11-26, the GPU audit's C31, its part (a).) A program's set template and push template were found through a per-thread table of 8 entries by the program's address; a frame pushes the descriptors of far more programs than 8, so most lookups took the global tpl_mu and searched a std::unordered_map (0.8% of the Presentation Thread's time at Lake Hylia, 1.1% in the Market). The table is now 512 sets of 2 entries by a multiplicative hash of the address and the template's kind; the entries, the layout check and the locked path behind a miss are what they were. Compiles a driver against the header: the switch's values (another value by its leading number); 64 programs taken in turn miss once each and never again (the 8-entry table by the old index misses on most lookups); 300 programs a fixed 0x2c0 apart miss on a few lookups in a hundred at most, but a fixed stride is not a frame (at this one the hash spreads them evenly, at 0x110 apart nearly every lookup misses); 300 programs at scattered addresses miss on about 12 lookups in a hundred after the first round (printed; the bound, 20, only catches a table that stopped spreading keys; busy frames took the lock on about 10% in a play test); a program's three kinds are three entries; an entry put again is replaced in place; a third key in a set puts the oldest out, and what is put out is not found again; an empty table finds nothing; the table is 16 KB. Reads the source: - vk_draw.cpp: the header included; RX_VK_TPL_TABLE read once (tpl_table_env), logged when not the default and when not a value it knows, the lab's knob notpltable over it (tpl_table_mode); set_template and push_template look in the table before tpl_mu, keep the layout check on what they find, put what the locked path gave, and keep the 8 entries for the switch's 0; the check mode asks the map under the lock and logs a difference by the check's name; the counters are in the frame statistics' line, labelled by the switch (not the lab's phase) and saying that under the check every find took the lock too; - vk_shader.h, vk_shader.cpp (stamp files): untouched by the name; - the switches table has the row, with the check's values, the busy frames' share of locked lookups and when a thread's table is made and freed. python -I -B tests/test_tpltable.py [--cxx clang++] """ import argparse import subprocess import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] RUN_ALL_ARGS = ["--cxx", "{cxx}"] DRIVER = r''' #include "tpltable.h" #include #include #include using namespace mkwvk::tpltable; static int checks, fails; static void want(const char* what, bool ok) { checks++; if (!ok) fails++, printf("FAIL %s\n", what); } // the callers' use of the table: found, or the locked path (counted) and put static int locked; static const void* lookup(Table& tab, uintptr_t key, const void* t) { if (const void* got = tab.find(key)) return got; locked++; tab.put(key, t); return t; } // the 8 entries before, by the old index struct Old { uintptr_t p; const void* t; }; static const void* lookup_old(Old* last, uintptr_t p, const void* t) { Old& l = last[old_slot(p)]; if (l.p == p && l.t) return l.t; locked++; l = {p, t}; return t; } int main() { want("the switch: on unless set otherwise", mode(nullptr) == kWide && mode("1") == kWide && mode("") == kWide && mode("x") == kWide); want("the switch: 0 is the 8 entries, 2 the check", mode("0") == kOld && mode("2") == kCheck && mode("3") == kWide); want("the switch: check is the check too", mode("check") == kCheck && mode("checked") == kWide && mode("Check") == kWide); want("the switch: another value by its leading number, a 0 only when it starts the value", mode("02") == kCheck && mode("+2") == kCheck && mode("2x") == kCheck && mode("00") == kOld && mode("0x") == kOld && mode(" 0") == kWide && mode("-0") == kWide && mode("1x") == kWide); want("the old index is what it was", old_slot(0x1000) == 0 && old_slot(0x1040) == 1 && old_slot(0x11c0) == 7 && old_slot(0x1200) == 0 && kOldSlots == 8); want("512 sets of 2, 16 bytes an entry", kSets == 512 && kWays == 2 && sizeof(Entry) == 16 && sizeof(Table) == 16 * 1024); auto tab = std::make_unique(); static int tpl[4096]; // (the templates: any distinct addresses) want("an empty table finds nothing", !tab->find(key_of((const void*)0x1e4a5c00040, kSet))); // 64 programs 0x1c0 apart (a heap's spacing for one size), taken in turn three times std::vector progs; for (int i = 0; i < 64; i++) progs.push_back((uintptr_t)0x1e4a5c00040 + (uintptr_t)i * 0x1c0); locked = 0; bool right = true; for (int round = 0; round < 3; round++) for (int i = 0; i < 64; i++) right &= lookup(*tab, key_of((const void*)progs[i], kPushGraphics), &tpl[i]) == &tpl[i]; want("64 programs in turn: each its own template", right); want("64 programs in turn: one locked lookup each, none after the first round", locked == 64); Old last[kOldSlots] = {}; locked = 0; for (int round = 0; round < 3; round++) for (int i = 0; i < 64; i++) right &= lookup_old(last, progs[i], &tpl[i]) == &tpl[i]; want("the 8 entries before: locked on most lookups", right && locked > 150); // 300 programs 0x2c0 apart, three rounds. A fixed stride is not a frame's programs: at this stride (and at 0x1c0) the // multiplicative hash spreads them evenly over the sets and none locks again, at 0x110 or 0x130 apart nearly every lookup // locks. The scattered case below is nearer a frame tab = std::make_unique
(); locked = 0; for (int round = 0; round < 3; round++) for (int i = 0; i < 300; i++) { const uintptr_t p = (uintptr_t)0x2b7f0a31000 + (uintptr_t)i * 0x2c0; right &= lookup(*tab, key_of((const void*)p, kPushGraphics), &tpl[i]) == &tpl[i]; } want("300 programs: every lookup its own template", right); want("300 programs: under 5 in 100 lookups locked after the first round", locked >= 300 && locked - 300 < 600 * 5 / 100); printf(" (300 programs, 900 lookups: %d locked after the first round)\n", locked - 300); // 300 programs at scattered addresses (a fixed generator), three rounds: a set keeps two keys, first in, first out, so a set // that three or more keys fall in misses on each of them every round. About 12 in 100 lookups after the first round lock // here; busy frames' statistics in a play test showed about 10% (21% at worst). The bound only catches a table that // stopped spreading keys; it is no promise for a frame std::vector scattered; uint64_t seed = 0x243f6a8885a308d3ull; for (int i = 0; i < 300; i++) { seed = seed * 6364136223846793005ull + 1442695040888963407ull; scattered.push_back((uintptr_t)0x20000000000 + (uintptr_t)(seed >> 32) * 0x40); } tab = std::make_unique
(); locked = 0; for (int round = 0; round < 3; round++) for (int i = 0; i < 300; i++) right &= lookup(*tab, key_of((const void*)scattered[i], kPushGraphics), &tpl[i]) == &tpl[i]; want("300 scattered programs: every lookup its own template", right); want("300 scattered programs: some locked after the first round, under 20 in 100", locked > 300 && locked - 300 < 600 * 20 / 100); printf(" (300 scattered programs, 900 lookups: %d locked after the first round)\n", locked - 300); // a program's kinds are entries of their own tab = std::make_unique
(); const void* prog = (const void*)0x1e4a5c00040; want("the kinds make three keys", key_of(prog, kSet) != key_of(prog, kPushGraphics) && key_of(prog, kPushGraphics) != key_of(prog, kPushCompute) && key_of(prog, kSet) != key_of(prog, kPushCompute) && kPushCompute == kPushGraphics + 1); tab->put(key_of(prog, kSet), &tpl[0]), tab->put(key_of(prog, kPushGraphics), &tpl[1]), tab->put(key_of(prog, kPushCompute), &tpl[2]); want("each kind finds its own", tab->find(key_of(prog, kSet)) == &tpl[0] && tab->find(key_of(prog, kPushGraphics)) == &tpl[1] && tab->find(key_of(prog, kPushCompute)) == &tpl[2]); // an entry put again is replaced where it is; a third key in a set puts the oldest out, for good tab = std::make_unique
(); const uintptr_t a = key_of(prog, kPushGraphics); std::vector same; // (other keys of a's set) for (uintptr_t p = 0x1e4a5c00040 + 0x40; same.size() < 3; p += 0x40) if (set_of(key_of((const void*)p, kPushGraphics)) == set_of(a)) same.push_back(key_of((const void*)p, kPushGraphics)); tab->put(a, &tpl[10]); tab->put(same[0], &tpl[11]); want("two keys of a set are both found", tab->find(a) == &tpl[10] && tab->find(same[0]) == &tpl[11]); tab->put(a, &tpl[12]); // (its template made again: the locked path gave another) want("put again: the new template, the neighbour kept", tab->find(a) == &tpl[12] && tab->find(same[0]) == &tpl[11]); int held = 0; for (const Entry& e : tab->e) held += e.key == a; want("put again: one entry for the key", held == 1); tab->put(same[1], &tpl[13]); want("a third key: the newest stays with one of the two", tab->find(same[1]) == &tpl[13] && (tab->find(a) == &tpl[12]) + (tab->find(same[0]) == &tpl[11]) == 1); tab->put(same[2], &tpl[14]); want("a fourth: the first two are out, and nothing old is found for them", !tab->find(a) && !tab->find(same[0]) && tab->find(same[1]) == &tpl[13] && tab->find(same[2]) == &tpl[14]); int used = 0; for (const Entry& e : tab->e) used += e.key != 0; want("and no other set was written", used == 2); if (fails) printf("tpltable: FAILED (%d of %d checks)\n", fails, checks); else printf("tpltable: all %d checks passed\n", checks); return fails != 0; } ''' def block(text, marker): start = text.index(marker) at = text.index("{", start) + 1 depth = 1 while depth: depth += (text[at] == "{") - (text[at] == "}") at += 1 return text[start:at] def need(ok, why): if not ok: raise SystemExit("FAIL: " + why) def ordered(text, parts, why): last = 0 for p in parts: k = text.find(p, last) need(k >= 0, why + " (missing, or out of order: " + p + ")") last = k + len(p) def check_source(): draw = (ROOT / "gpu/vk/vk_draw.cpp").read_text(encoding="utf-8") need('#include "tpltable.h"' in draw, "vk_draw.cpp does not include tpltable.h") need("TLS_OBJECT(tpl_wide, tpltable::Table)" in draw, "vk_draw.cpp has no per-thread wide table (TLS_OBJECT(tpl_wide, tpltable::Table))") need("static_assert(alignof(Program) >= 4" in draw, "nothing says a program's address leaves the kind's two bits free") need("int tpl_table_env() {" in draw, "vk_draw.cpp has no tpl_table_env (the switch read once, apart from the lab's knob)") env = block(draw, "int tpl_table_env() {") ordered(env, ["static const int env", 'getenv("RX_VK_TPL_TABLE")', "tpltable::mode(asked)", "logf(", "is not 0, 1, 2 or check", "return env;"], "the switch is not RX_VK_TPL_TABLE read once and logged, an unknown value told") mode = block(draw, "int tpl_table_mode() {") need("tpl_table_env()" in mode and 'return lab_ab::on("notpltable") ? tpltable::kOld : env;' in mode and "getenv" not in mode, "the table in force is not the switch's with the lab's notpltable knob over it") for name, kind, valid in [("const SetTemplate* set_template(", "tpltable::kSet", "t->layout == p.set_layout"), ("const SetTemplate* push_template(", "tpltable::kPushGraphics + k", "t->pipe_layout == p.layout")]: body = block(draw, name) ordered(body, ["const int wide = tpl_table_mode();", "tpltable::key_of(&p, " + kind + ")", "tpltable::old_slot((uintptr_t)&p)", "if (wide) {", "tpl_wide().find(key)", "if (t && " + valid + ") {", "count_add(st_tpl_fast, 1);", "if (wide == tpltable::kCheck) tpl_check(", "return t;", "} else if (l.p == &p && l.t && l." + valid + ") {", "count_add(st_tpl_locked, 1);", "std::lock_guard lk(tpl_mu);", "if (wide) tpl_wide().put(key, t.get());", "else l = {&p, t.get()};", "return t.get();"], "%s does not look in the wide table before tpl_mu with the layout check, count, and put what the lock gave" % name.strip("(")) need(body.count("std::lock_guard lk(tpl_mu);") == 1, name + " takes tpl_mu elsewhere") check = block(draw, "void tpl_check(") ordered(check, ["std::lock_guard lk(tpl_mu);", "map.find(&p)", "count_add(st_tpl_checked, 1);", "count_add(st_tpl_bad, 1);", '"vk: descriptor template check: '], "the check mode does not ask the map under the lock, count what came out otherwise and log it by its name (not by one value)") report = block(draw, "void desc_report(double frames) {") need("a frame's descriptor templates:" in report and "st_tpl_fast.load()" in report and "st_tpl_locked.load()" in report and "st_tpl_checked.load()" in report and "st_tpl_bad.load()" in report, "the frame statistics have no line of the templates' lookups") need("const int tm = tpl_table_env();" in report and "tpl_table_mode()" not in report and "each one found took the lock too" in report, "the templates' line is not labelled by the switch, or does not say the check takes the lock at every find") # (stamp files: this change is a side table, nothing on Program) for stamp in ["gpu/vk/vk_shader.h", "gpu/vk/vk_shader.cpp"]: need("tpltable" not in (ROOT / stamp).read_text(encoding="utf-8"), stamp + ", a stamp file, names tpltable") docs = (ROOT / "docs/development.md").read_text(encoding="utf-8") row = [line for line in docs.splitlines() if line.startswith("| `RX_VK_TPL_TABLE=0`")] need(len(row) == 1 and "`gpu/vk/tpltable.h`" in row[0] and "`notpltable`" in row[0] and "a frame's descriptor templates" in row[0] and "`RX_VK_TPL_TABLE=2`" in row[0], "docs/development.md: the switches table has no RX_VK_TPL_TABLE row") need(row[0].startswith("| `RX_VK_TPL_TABLE=0` or `2` (`check`) |"), "docs/development.md: the RX_VK_TPL_TABLE row's head lacks the check") for part, why in [("about 10% of them", "that busy frames still take the lock on about 10% of lookups"), ("8 entries a kind of template", "that there were 8 entries a kind of template"), ("made at its first lookup and freed when the thread ends", "when a thread's table is made and freed"), ("`RX_VK_TPL_TABLE=2` or `check`", "check as a value of the check"), ("so every lookup takes it", "that the check takes the lock at every lookup"), ("the table's template is still the one used", "which template the check uses"), ("labelled by the switch", "what labels the counters' line")]: need(part in row[0], "docs/development.md: the RX_VK_TPL_TABLE row does not say " + why) def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--cxx", default="clang++") args = parser.parse_args() need((ROOT / "gpu/vk/tpltable.h").is_file(), "gpu/vk/tpltable.h is not there: the templates' table is the 8 entries behind tpl_mu") with tempfile.TemporaryDirectory(prefix="tpltable-") as tmp: cpp, exe = Path(tmp) / "tpltable_test.cpp", Path(tmp) / "tpltable.exe" cpp.write_text(DRIVER, encoding="utf-8") subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(cpp), "-o", str(exe)], check=True) r = subprocess.run([str(exe)], capture_output=True, text=True) print(r.stdout.rstrip()) if r.returncode: raise SystemExit("FAIL: the template table's checks failed") check_source() print("PASS: the descriptor templates are found in a per-thread table of 512 sets of 2; RX_VK_TPL_TABLE=0 is the 8 entries as before") if __name__ == "__main__": main()