"""A report word the sets hold already is not noted again (gpu/vk/cpuwordsseen.h; vk_memory.cpp memory_cpu_owned; no game, no GPU). (Triforce, 11-26.) Every word of every counter report the replay writes into guest memory is noted (memory_cpu_owned), so that a mirror's write-back leaves it out (the one-frame dark flashes of 11-07). The same words come every frame, and each was pushed again, sorted again and searched for in both sets at every part's end (cpu_words_merge). A table of the words the sets hold (the full address and the sets' generation in each entry) answers that at the note now. This compiles the header with vk_memory.cpp's own sorted_merge, cpu_words_merge, memory_cpu_owned and cut_cpu_words cut from the source, and - asks the table at random against a std::set: it never calls a word known that was not marked since the last forget(), whatever shares its entry, and two words that share an entry only push each other out; - runs one fixed run of notes and write-back cuts three times, with the table off (the code as it was), on, and checking: the same report words frame after frame (some given unaligned), new ones mixed in, words that share a table entry with them, bursts past 65,536 words (the sets are forgotten) and the same words again after it. At every cut the two sets together are the words a std::set model holds and the cut runs are the same in all three, and the check counts no mismatch; - counts what reaches the merge over frames that only repeat: every word without the table; with it nothing, but for the few report words another word pushed out of their table entry the frame before, once; - builds the same file from the source with the table's forget() taken out of the clear: that build must give other runs than the model, and its check must count mismatches (so the cases mean something). And reads the source: the sets are cleared in one place and the table forgets there; the three sets are named only in their declaration and the four functions the program above compiles (the comments left out), so no other code can take a word out of them; the table is asked, marked and forgotten only by memory_cpu_owned under cpu_words_mu (only its atomic counters are read elsewhere); the switch is read once (a value other than 1, 0 or check logged) and the lab knob at each note, the status line has the counters and the switches table has the row. python -I -B tests/test_cpuwordsseen.py [--cxx clang++] """ import argparse import os import re import subprocess import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] VK = ROOT / "gpu" / "vk" RUN_ALL_ARGS = ["--cxx", "{cxx}"] def check(ok, why): if not ok: raise SystemExit("FAIL: " + why) def block(text, marker): check(marker in text, "vk_memory.cpp has no " + marker) start = text.index(marker) end = text.index("{", start + len(marker) - 1) + 1 depth = 1 while depth: depth += (text[end] == "{") - (text[end] == "}") end += 1 return text[start:end] def code_only(text): """text with its // and /* */ comments blanked (newlines kept, so offsets and lines stay); string and character literals are left as they are""" out, i, n = list(text), 0, len(text) while i < n: c = text[i] if c in "\"'": j = i + 1 while j < n and text[j] != c and text[j] != "\n": j += 2 if text[j] == "\\" else 1 i = j + 1 elif text.startswith("//", i): j = text.find("\n", i) j = n if j < 0 else j out[i:j] = " " * (j - i) i = j elif text.startswith("/*", i): j = text.find("*/", i + 2) j = n if j < 0 else j + 2 out[i:j] = [ch if ch == "\n" else " " for ch in text[i:j]] i = j else: i += 1 return "".join(out) # (where the three sets may be named: their declaration and the four functions PROGRAM compiles and runs) SET_DECL = "std::vector cpu_words, cpu_words_recent, cpu_words_new;" SET_USERS = ("void cpu_words_merge() {", "void memory_cpu_owned(uint64_t guest, uint64_t size) {", "void cut_cpu_words(") def stray_set_uses(mem): """The lines that name cpu_words, cpu_words_recent or cpu_words_new outside SET_DECL and SET_USERS' blocks. An allowlist, not a list of the calls that remove words: a member call, std::erase_if, std::swap on either side, std::move or a reference taken elsewhere are all caught, and every edit inside the blocks is run by the program""" code = code_only(mem) spans = [(code.index(SET_DECL), code.index(SET_DECL) + len(SET_DECL))] for marker in SET_USERS: start = mem.index(marker) spans.append((start, start + len(block(mem, marker)))) return sorted({code.count("\n", 0, m.start()) + 1 for m in re.finditer(r"\bcpu_words(_recent|_new)?\b", code) if not any(a <= m.start() < b for a, b in spans)}) PROGRAM = r""" #include #include #include #include #include #include #include #include #include "cpuwordsseen.h" static int fails = 0; #define CHECK(ok) do { if (!(ok)) { if (fails++ < 20) std::printf("FAIL:%d %s\n", __LINE__, #ok); } } while (0) struct Pool { uint64_t lo; }; struct VkBufferCopy { uint64_t srcOffset, dstOffset, size; }; std::mutex cpu_words_mu; bool wb_notes_off() { return false; } // (the mirrors are on here) std::vector cpu_words, cpu_words_recent, cpu_words_new; cpu_words_seen::Table cpu_words_table; static int g_mode = cpu_words_seen::ON; int cpu_words_seen_mode() { return g_mode; } // (vk_memory.cpp's reads the switch and the lab knob) /* ACTUAL */ static uint64_t rnd_state; static uint64_t rnd() { rnd_state ^= rnd_state << 13, rnd_state ^= rnd_state >> 7, rnd_state ^= rnd_state << 17; return rnd_state; } using cpu_words_seen::Table; // another word in w's entry of the table static uint64_t shares_entry(uint64_t w) { for (uint64_t c = w + 8;; c += 8) if (Table::slot(c) == Table::slot(w)) return c; } // ---- the table alone, against a set ---- static void table_against_a_set() { static Table t; std::set marked; rnd_state = 0x9E3779B97F4A7C15ull; long known = 0, pushed_out = 0; for (int i = 0; i < 3000000; i++) { // (300,000 words over 131,072 entries: most entries are shared; half the asks are of 2,000 words that repeat) const uint64_t w = 0x2000000000ull + (rnd() % 2 ? rnd() % 2000 : rnd() % 300000) * 8; if (rnd() % 400000 == 0) t.forget(), marked.clear(); if (t.known(w)) { known++; CHECK(marked.count(w) == 1); // (never known without being held) } else { pushed_out += marked.count(w); t.mark(w), marked.insert(w); CHECK(t.known(w)); } } CHECK(known > 500000 && pushed_out > 1000); // two words in one entry: each pushes the other out, neither is taken for the other const uint64_t a = 0x80001000, b = shares_entry(a); CHECK(a != b && Table::slot(a) == Table::slot(b)); t.forget(); CHECK(!t.known(a) && !t.known(b)); t.mark(a); CHECK(t.known(a) && !t.known(b)); t.mark(b); CHECK(t.known(b) && !t.known(a)); t.forget(); CHECK(!t.known(a) && !t.known(b)); // (the forget takes every word at once) CHECK(!t.known(0)); // (an entry never written is no word, address 0 neither) // the switch using namespace cpu_words_seen; CHECK(mode(nullptr) == ON && mode("") == ON && mode("1") == ON && mode("0") == OFF && mode("check") == CHECK_BOTH); CHECK(mode("on") == ON && mode("true") == ON && mode("2") == ON && mode("Check") == ON); // (any other value: as unset) CHECK(mode_now(ON, false) == ON && mode_now(ON, true) == OFF && mode_now(CHECK_BOTH, false) == CHECK_BOTH && mode_now(CHECK_BOTH, true) == OFF && mode_now(OFF, false) == OFF); CHECK(kSlots >= 65536 * 2); // (the sets hold up to 65,536 words) // push(): off pushes everything and marks nothing; on pushes a word once; checking pushes all and counts static Table p; std::vector none, big{a}; CHECK(push(p, OFF, a, none, none, none) && !p.known(a) && p.st_noted.load() == 0); CHECK(push(p, ON, a, none, none, none) && p.known(a)); CHECK(!push(p, ON, a, big, none, none) && p.st_noted.load() == 2 && p.st_known.load() == 1); CHECK(push(p, CHECK_BOTH, a, big, none, none) && p.st_mismatch.load() == 0); // (held in the big set) CHECK(push(p, CHECK_BOTH, a, none, big, none) && p.st_mismatch.load() == 0); // (in the recent one) CHECK(push(p, CHECK_BOTH, a, none, none, big) && p.st_mismatch.load() == 0); // (noted since the merge) CHECK(push(p, CHECK_BOTH, a, none, none, none) && p.st_mismatch.load() == 1); // (known to the table, held nowhere) CHECK(p.st_known.load() == 5); // (off with a word the table knows: the lab knob's phases come after phases that marked words, and must push them all // as before, counting nothing) CHECK(p.known(a) && push(p, OFF, a, none, none, none) && p.st_noted.load() == 6 && p.st_known.load() == 5); } // ---- memory_cpu_owned and cut_cpu_words: one fixed run, the table off, on and checking ---- struct Result { std::vector log; // (at every cut: the sets' size and hash, the cut runs' hash) std::vector reached; // (what reached the merge in each frame that only repeated) uint64_t noted = 0, known = 0, forgets = 0, mismatch = 0; int model_differs = 0; }; static uint64_t hash(uint64_t h, uint64_t v) { return (h ^ v) * 1099511628211ull; } static Result run(int mode) { Result r; g_mode = mode; cpu_words.clear(), cpu_words_recent.clear(), cpu_words_new.clear(); cpu_words_table.forget(); // (a run starts with empty sets) const uint64_t noted0 = cpu_words_table.st_noted.load(), known0 = cpu_words_table.st_known.load(), forgets0 = cpu_words_table.st_forgets.load(), mismatch0 = cpu_words_table.st_mismatch.load(); rnd_state = 0x1234567887654321ull; const Pool pool{0x80000000}; const uint64_t reports = pool.lo + 0x10000; // (250 reports of 16 bytes: 500 words) std::set model; // memory_cpu_owned as it was, on a set: both sets forgotten at a note that finds more than 65,536 words held auto note = [&](uint64_t guest, uint64_t size) { if (model.size() > 65536) model.clear(); for (uint64_t a = guest & ~7ull; a < guest + size; a += 8) model.insert(a); memory_cpu_owned(guest, size); }; auto cut = [&] { std::vector runs; for (int k = 0; k < 6; k++) { const uint64_t at = rnd() % 0x30000, len = 1 + rnd() % 0x4000; runs.push_back({at, at, len}); } runs.push_back({0x10000 - 12, 0x10000 - 12, 500 * 8 + 40}); // (over all the reports, from inside a word before them) cut_cpu_words(pool, runs); CHECK(cpu_words_new.empty()); std::vector both(cpu_words); both.insert(both.end(), cpu_words_recent.begin(), cpu_words_recent.end()); std::sort(both.begin(), both.end()); if (std::adjacent_find(both.begin(), both.end()) != both.end() || both.size() != model.size() || !std::equal(both.begin(), both.end(), model.begin())) r.model_differs++; uint64_t h = 1469598103934665603ull; for (uint64_t w : both) h = hash(h, w); r.log.push_back(both.size()), r.log.push_back(h); h = 1469598103934665603ull; for (const VkBufferCopy& c : runs) h = hash(hash(hash(h, c.srcOffset), c.dstOffset), c.size); r.log.push_back(runs.size()), r.log.push_back(h); }; for (int frame = 0; frame < 100; frame++) { const bool only_repeats = frame % 10 >= 6 && frame % 10 <= 8; // (three frames in ten with nothing new) const size_t new0 = cpu_words_new.size(); for (int i = 0; i < 250; i++) { // (the same reports every frame; one in sixteen given from inside its first word, which takes a third word in) if (i % 16 == 5 && !only_repeats) note(reports + 16 * (uint64_t)i + 4, 16); else note(reports + 16 * (uint64_t)i, 16); if (only_repeats) continue; if (rnd() % 8 == 0) note(pool.lo + (rnd() % 0x6000) * 8, 16); // (reports at new addresses) if (rnd() % 16 == 0) note(shares_entry(reports + 16 * (rnd() % 250)), 8); // (a word in a report word's entry) if (rnd() % 97 == 0) cut(); // (a part's end with write-backs) } if (only_repeats) r.reached.push_back(cpu_words_new.size() - new0); cut(); if (frame % 25 == 12) // (a burst of new words: the sets pass 65,536 and are forgotten, and the reports come again) for (int k = 0; k < 9000; k++) { note(0x90000000ull + (uint64_t)frame * 0x1000000 + (uint64_t)k * 64, 64); if (k % 1000 == 999) note(reports, 500 * 8), cut(); } } r.noted = cpu_words_table.st_noted.load() - noted0, r.known = cpu_words_table.st_known.load() - known0; r.forgets = cpu_words_table.st_forgets.load() - forgets0, r.mismatch = cpu_words_table.st_mismatch.load() - mismatch0; return r; } int main(int argc, char** argv) { const std::string test = argc == 2 ? argv[1] : ""; using namespace cpu_words_seen; if (test == "table") { table_against_a_set(); } else if (test == "runs") { const Result off = run(OFF), on = run(ON), both = run(CHECK_BOTH); CHECK(off.model_differs == 0 && on.model_differs == 0 && both.model_differs == 0); CHECK(off.log.size() > 400 && off.log == on.log && off.log == both.log); CHECK(off.noted == 0 && off.known == 0 && off.forgets == 4); // (off: the table is not asked; the sets were forgotten in each burst) CHECK(on.forgets == off.forgets && both.forgets == off.forgets); CHECK(on.noted > 300000 && on.known > 60000 && on.mismatch == 0); // (the bursts' words are new; the reports' are known) CHECK(both.noted == on.noted && both.mismatch == 0); CHECK(off.reached.size() == 30 && on.reached.size() == 30); for (size_t i = 0; i < off.reached.size() && i < on.reached.size(); i++) { CHECK(off.reached[i] == 500); // (as it was: every word again) // (the first of each three comes after a frame with words in report words' entries: the reports pushed out // of the table are noted once more, and take their entries back; then nothing reaches the merge) if (i % 3 == 0) CHECK(on.reached[i] > 0 && on.reached[i] < 60); else CHECK(on.reached[i] == 0); } std::printf("noted %llu known %llu forgets %llu\n", (unsigned long long)on.noted, (unsigned long long)on.known, (unsigned long long)on.forgets); } else if (test == "stale") { // (for the build without the forget: what the table on, and the check, make of it) const Result on = run(ON), both = run(CHECK_BOTH); std::printf("differs %d mismatch %llu\n", on.model_differs, (unsigned long long)both.mismatch); return 0; } else { std::printf("a known case\n"); return 1; } return fails != 0; } """ def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--cxx", default="clang++") args = parser.parse_args() check((VK / "cpuwordsseen.h").is_file(), "gpu/vk/cpuwordsseen.h is missing: report words are noted again every frame") head = (VK / "cpuwordsseen.h").read_text(encoding="utf-8") mem = (VK / "vk_memory.cpp").read_text(encoding="utf-8") # the rule: an entry is the whole address and the generation, and both are compared check("#pragma once" in head and "namespace cpu_words_seen {" in head, "cpuwordsseen.h is not the rule header") check("uint64_t word, stamp;" in head and "return x.stamp == forgets + 1 && x.word == word;" in head, "a table entry is not known by its whole address and the sets' generation") check("RX_VK_CPU_WORDS_SEEN" in head and "nowordsseen" in head, "the header does not name its switch and its lab knob") # the hook: one clear of the sets, the table forgets there; asked and written only inside memory_cpu_owned's lock check('#include "cpuwordsseen.h"' in mem, "vk_memory.cpp does not include cpuwordsseen.h") owned = block(mem, "void memory_cpu_owned(uint64_t guest, uint64_t size) {") clear = "cpu_words.clear(), cpu_words_recent.clear(), cpu_words_table.forget();" check(mem.count("cpu_words.clear()") == 1 and clear in owned, "the sets are cleared without the table forgetting, or in a second place") check(mem.count("cpu_words_table.forget()") == 1, "the table forgets somewhere else too") check(mem.count("cpu_words_recent.clear()") == 2 and "sorted_merge(cpu_words, cpu_words_recent.data(), cpu_words_recent.data() + cpu_words_recent.size());\n cpu_words_recent.clear();" in block(mem, "void cpu_words_merge() {"), "the recent set is emptied other than into the big one") # (no word leaves a set any other way: the sets are named nowhere else, and inside the blocks the words noted since the # merge are emptied once, at the merge's end, and thinned once, to their unique words) stray = stray_set_uses(mem) check(not stray, "vk_memory.cpp names the report word sets outside their declaration and %s (lines %s): a word may leave " "them without the table forgetting" % (", ".join(m.split("(")[0][5:] for m in SET_USERS), stray)) check(stray_set_uses(mem + "\nvoid stray() {\n std::lock_guard lk(cpu_words_mu);\n cpu_words_new.clear();\n}\n") and stray_set_uses(mem + "\nvoid stray(std::vector& x) { std::swap(x, cpu_words); }\n"), "the scan does not catch a set emptied in another function") merge = block(mem, "void cpu_words_merge() {") code = code_only(mem) check(code.count("cpu_words_new.clear()") == 1 and "cpu_words_new.clear()" in code_only(merge), "the words noted since the merge are emptied somewhere else than at the merge's end") unique = [l for l in code.split("\n") if "cpu_words_new.erase(" in l] check(len(unique) == 1 and "std::unique(cpu_words_new.begin(), cpu_words_new.end())" in unique[0], "the words noted since the merge are erased other than to their unique words") push = "if (cpu_words_seen::push(cpu_words_table, seen, a, cpu_words, cpu_words_recent, cpu_words_new)) cpu_words_new.push_back(a);" lock = "std::lock_guard lk(cpu_words_mu);" check(mem.count("cpu_words_seen::push(") == 1 and push in owned and owned.index(lock) < owned.index(clear) < owned.index(push), "memory_cpu_owned does not ask the table for each word, under its lock, after the clear") rest = code.replace("cpu_words_seen::Table cpu_words_table;", "", 1).replace(clear, "", 1).replace(push, "", 1) for st in ("st_noted", "st_known", "st_forgets", "st_mismatch"): rest = rest.replace("cpu_words_table." + st + ".load(std::memory_order_relaxed)", "", 1) check("cpu_words_table" not in rest, "the table is used other than by memory_cpu_owned's push and forget under " "cpu_words_mu (only its atomic counters are read elsewhere)") check("cpu_words_new.push_back(" not in mem.replace(push, ""), "a word is noted past the table") check("const int seen = cpu_words_seen_mode();" in owned, "memory_cpu_owned does not read the switch's mode at each note") # the switch read once and logged when not the default; the lab knob at each note mode = block(mem, "int cpu_words_seen_mode() {") check(mem.count('getenv("RX_VK_CPU_WORDS_SEEN")') == 1 and "static const int env = [] {" in mode and 'const char* e = getenv("RX_VK_CPU_WORDS_SEEN");' in mode and "const int m = cpu_words_seen::mode(e);" in mode and "if (m != cpu_words_seen::ON) logf(" in mode, "RX_VK_CPU_WORDS_SEEN is not read once into a static and logged when not the default") check('else if (e && e[0] && strcmp(e, "1"))' in mode and "RX_VK_CPU_WORDS_SEEN=%s not known" in mode, "an RX_VK_CPU_WORDS_SEEN value other than 1, 0 or check is not logged") check('return cpu_words_seen::mode_now(env, lab_ab::on("nowordsseen"));' in mode, "the lab knob nowordsseen is not read at each note") # the counters, in the mirror syncs' line end = block(mem, "void memory_end_submission(VkCommandBuffer cmd) {") check("report words: %llu asked of the table, %llu known to it and not noted again (noted all the same with =check), the " "sets forgotten %llu times, %llu check mismatches since the start (RX_VK_CPU_WORDS_SEEN)" in re.sub(r'"\s*\n\s*"', "", end), "the mirror syncs' line does not carry the report words' counters") for st in ("st_noted", "st_known", "st_forgets", "st_mismatch"): check("cpu_words_table." + st + ".load(std::memory_order_relaxed)" in end, "the status line does not read " + st) row = [l for l in (ROOT / "docs" / "development.md").read_text(encoding="utf-8").split("\n") if l.startswith("| `RX_VK_CPU_WORDS_SEEN=0`")] check(len(row) == 1 and "`nowordsseen`" in row[0] and "`RX_VK_CPU_WORDS_SEEN=check`" in row[0] and "gpu/vk/cpuwordsseen.h" in row[0] and "tests/test_cpuwordsseen.py" in row[0], "docs/development.md's switches table has no row for RX_VK_CPU_WORDS_SEEN") cut = "\n".join(block(mem, m) for m in ("void sorted_merge(", "void cpu_words_merge() {", "void memory_cpu_owned(uint64_t guest, uint64_t size) {", "void cut_cpu_words(")) stale = cut.replace(", cpu_words_table.forget();", ";") # (the sets cleared, the table left as it was) check(stale != cut, "the forget is not where the test takes it out") env = {k: v for k, v in os.environ.items() if not k.startswith("RX_VK_")} with tempfile.TemporaryDirectory(prefix="cpuwordsseen-") as tmp: exes = {} for name, code in (("now", cut), ("stale", stale)): src, exe = Path(tmp) / (name + ".cpp"), Path(tmp) / (name + ".exe") src.write_text(PROGRAM.replace("/* ACTUAL */", code), encoding="utf-8", newline="\n") subprocess.run([args.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-I", str(VK), str(src), "-o", str(exe)], check=True) exes[name] = str(exe) def run(name, case): return subprocess.run([exes[name], case], env=env, capture_output=True, text=True, timeout=600) r = run("now", "table") check(r.returncode == 0, "the table against a set:\n" + r.stdout + r.stderr) r = run("now", "runs") check(r.returncode == 0, "the runs with the table off, on and checking:\n" + r.stdout + r.stderr) counts = r.stdout.strip() r = run("now", "stale") check(r.returncode == 0 and r.stdout.strip() == "differs 0 mismatch 0", "the code as it is: " + r.stdout + r.stderr) r = run("stale", "stale") check(r.returncode == 0 and r.stdout.startswith("differs "), "the build without the forget:\n" + r.stdout + r.stderr) differs, mismatch = int(r.stdout.split()[1]), int(r.stdout.split()[3]) check(differs > 0 and mismatch > 0, "without the forget the runs are still right and the check counts nothing: the cases check nothing (" + r.stdout.strip() + ")") print("PASS: a report word the sets hold is not noted again (" + counts + "); the sets and the cut runs are what they were, " "over table entries shared and the sets forgotten; a table that does not forget is caught") if __name__ == "__main__": main()