diff --git a/dm/gfx/nvn/dmsh_abi.h b/dm/gfx/nvn/dmsh_abi.h index e822bd1fb8..7752272051 100644 --- a/dm/gfx/nvn/dmsh_abi.h +++ b/dm/gfx/nvn/dmsh_abi.h @@ -78,7 +78,9 @@ // Raw global memory: the translator reserves that table as a storage buffer under this constant buffer slot, which no game has (Ryujinx GlobalToStorage.GmemMapCbSlot), finds the pool // holding an address by a binary search over the table's starts and accesses the address plus the pool's delta through a physical storage buffer pointer #define DMSH_GMEM_MAP_CB_SLOT 0xFF -#define DMSH_GMEM_MAP_ENTRIES 4096 // entries of the table (GlobalToStorage.GmemMapLog2 = 12), sorted by start: entry 0 is empty (start 0, end 0) and unused entries start at ~0 +// The table is sorted by start: entry 0 is empty (start 0, end 0) and unused entries start at ~0. The host gives it a power of two entries, as many as its pools need and at least +// DMSH_GMEM_MAP_ENTRIES, and writes that count into entry 0's delta (low word, GlobalToStorage.GmemMapCountWord), which the shader's binary search takes +#define DMSH_GMEM_MAP_ENTRIES 4096 // the least count of entries #define DMSH_GMEM_MAP_ENTRY 32 // bytes of an entry: start, end (exclusive) and delta (the pool's Metal GPU address minus its guest address), 64 bits each, then 8 bytes of padding // Where such a store or atomic lands is known only when the GPU runs it, so each one also puts its guest page (address >> 12) in a write log, reserved under the same slot at offset 1 // (Ryujinx GlobalToStorage.GmemLogCbOffset, GmemLogLog2): 32-bit words, word 0 set when a page found no free slot, then a hash set of 1 << DMSH_GMEM_LOG_LOG2 pages (0 = empty). diff --git a/dm/gfx/nvn/dmsh_chain.h b/dm/gfx/nvn/dmsh_chain.h index 327d943f7c..8238a1357a 100644 --- a/dm/gfx/nvn/dmsh_chain.h +++ b/dm/gfx/nvn/dmsh_chain.h @@ -1,3 +1,3 @@ // Generated file (dm/gfx/tools/dmsh_chain.py --header): the B shader library translation chain version this source tree expects (default options), one for every game; // the host loads only /b-/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change -#define DMSH_CHAIN "1d53805bef4f" +#define DMSH_CHAIN "6fe832f2db50" diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index 5fc025c6e3..82cbc911f0 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -8032,31 +8032,43 @@ static void bind_args(id en, int nvn_stage, int metal_vertex, // Layout (dmsh_abi.h DMSH_GMEM_MAP_*): sorted by start, entry 0 empty, then the pools as disjoint ranges (a pool overlapping an earlier one keeps only its part past that one's end: every // pool wraps the guest's own pages, so any pool holding an address gives its GPU address), unused entries starting at ~0. Rebuilt when the pools change; the replaced table goes through // deferred release, so submissions encoded with it keep it. Every pool is made resident, as the shader may reach any of them +// As many entries as the pools need: a power of two of at least DMSH_GMEM_MAP_ENTRIES, the count in entry 0's delta, where the shader's binary search starts. The table used to have +// 4,096 entries whatever the pools: loading a save in Ocarina of Time made up to 4,522 pools, the ones past the last entry were left out, and a task shader that read both ends of a +// range through them as 0 looped (0 - 1) >> 5 times, a GPU hang (docs/reference/shaders.md, More memory pools than the raw pool table had entries) +enum { GMEM_MAP_MAX = 1 << 20 }; // entries at most (a 32 MB table, if ever a game had that many pools); pools past them are still left out, with a red line static id g_gmem_buf; static uint64_t g_gmem_gen; static uint64_t gmem_map_gpu(void) { uint64_t gen = atomic_load(&g_pool_gen); if (g_gmem_buf && g_gmem_gen == gen) return g_gmem_buf.gpuAddress; - id b = [g_dev newBufferWithLength:DMSH_GMEM_MAP_ENTRIES * DMSH_GMEM_MAP_ENTRY options:MTLResourceStorageModeShared]; - uint8_t *t = (uint8_t *)b.contents; memset(t, 0, b.length); - for (int k = 1; k < DMSH_GMEM_MAP_ENTRIES; k++) memset(t + (size_t)k * DMSH_GMEM_MAP_ENTRY, 0xff, 8); - int n = 1, over = 0; uint64_t end = 0; + int n = 1, over = 0; uint64_t end = 0, over_lo = 0, over_bytes = 0; pthread_mutex_lock(&g_mu); for (int k = 0; k < g_nbig; k++) if (!g_big[k].full) { int n = big_new(&g_big[k], g_big[k].a, g_big[k].b, g_big[k].b, 0); if (n >= 0) g_big[k].full = n + 1; } // the pool table reaches all of a large pool gen = atomic_load(&g_pool_gen); pidx_sort(); + uint64_t (*rng)[3] = malloc(((size_t)g_npool + 1) * sizeof *rng); if (!rng) abort(); // the ranges (start, end, delta), taken under g_mu and written into the table after it for (int k = 0; k < g_npool; k++) { pool_ent *p = &g_pools[g_pidx[k]]; if (!p->res) { res_add(p->buf); p->res = 1; g_pool_res_n++; } uint64_t lo = MAX((uint64_t)p->lo, end), hi = p->hi; if (lo >= hi) continue; - if (n == DMSH_GMEM_MAP_ENTRIES) { over++; continue; } - uint64_t e[3] = {lo, hi, p->gpu - p->base}; memcpy(t + (size_t)n++ * DMSH_GMEM_MAP_ENTRY, e, sizeof e); end = hi; + if (n == GMEM_MAP_MAX) { if (!over++) over_lo = lo; over_bytes += hi - lo; continue; } + rng[n][0] = lo; rng[n][1] = hi; rng[n][2] = p->gpu - p->base; n++; end = hi; } pthread_mutex_unlock(&g_mu); - if (over) RED_ONCE(140, "raw global memory: %d more memory pools than the %d entries of the pool table; addresses in them are not reached", over, DMSH_GMEM_MAP_ENTRIES - 1); + unsigned cap = DMSH_GMEM_MAP_ENTRIES; while (cap < (unsigned)n) cap <<= 1; + id b = [g_dev newBufferWithLength:(NSUInteger)cap * DMSH_GMEM_MAP_ENTRY options:MTLResourceStorageModeShared]; + uint8_t *t = (uint8_t *)b.contents; memset(t, 0, b.length); + { uint32_t count = cap; memcpy(t + 4 * sizeof(uint32_t), &count, sizeof count); } // entry 0's delta: the count (entry 0 is never a pool: it ends at 0) + for (unsigned k = 1; k < cap; k++) memset(t + (size_t)k * DMSH_GMEM_MAP_ENTRY, 0xff, 8); + for (int k = 1; k < n; k++) memcpy(t + (size_t)k * DMSH_GMEM_MAP_ENTRY, rng[k], sizeof rng[k]); + free(rng); + if (over) RED_ONCE(140, "raw global memory: %d more pool ranges than the %d entries the pool table may have; addresses in them are not reached (the first at %#llx, %llu KB in all)", + over, GMEM_MAP_MAX - 1, (unsigned long long)over_lo, (unsigned long long)(over_bytes >> 10)); res_add(b); res_commit(); + unsigned old = g_gmem_buf ? (unsigned)(g_gmem_buf.length / DMSH_GMEM_MAP_ENTRY) : 0; if (g_gmem_buf) defer_obj_release(g_gmem_buf); g_gmem_buf = b; g_gmem_gen = gen; - { static int said; if (!said++) MLOG("raw global memory: pool table of %d ranges (pool generation %llu), rebuilt whenever a pool comes or goes", n - 1, (unsigned long long)gen); } + { static int said; if (!said++) MLOG("raw global memory: pool table of %d ranges in %u entries (pool generation %llu), rebuilt whenever a pool comes or goes", n - 1, cap, (unsigned long long)gen); } + if (old && cap > old) MLOG("raw global memory: the pool table grows to %u entries for %d ranges", cap, n - 1); return b.gpuAddress; } // Where those stores land is known only once the GPU has run them, while the host's uniform shadows and its CPU reads of guest memory must not miss a GPU write (sbw / gw). Counted as a diff --git a/dm/gfx/tests/Makefile b/dm/gfx/tests/Makefile index 8ac4d8634f..2f91f195f0 100644 --- a/dm/gfx/tests/Makefile +++ b/dm/gfx/tests/Makefile @@ -160,6 +160,14 @@ check_t_tex_fit_root: t_tex_fit_root MTL_DEBUG_LAYER=1 ./t_tex_fit_root t_pool_chunks: t_pool_chunks.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_pool_chunks.m $(MTL_T_SRC) $(FW) +# Raw global memory on the GPU through the host's pool table (t_gmem_raw.m), with the shader test_dmsh_ampere_mem.py translates (DMSH_TEST_XLATE, default the in-repo translator); +# skipped only when the translator does not run (its exit code 77) +t_gmem_raw: t_gmem_raw.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ t_gmem_raw.m $(MTL_T_SRC) $(FW) +.PHONY: check_t_gmem_raw +check_t_gmem_raw: t_gmem_raw + @set -e; work=$$(mktemp -d); trap 'rm -rf "$$work"' EXIT; rc=0; DMSH_TEST_XLATE=$${DMSH_TEST_XLATE:-$(CURDIR)/../tools/dmsh_xlate_bin/dmsh_xlate} python3 test_dmsh_ampere_mem.py --fixture "$$work" || rc=$$?; \ + if [ $$rc = 77 ]; then echo "t_gmem_raw: skipped, the translator does not run"; elif [ $$rc != 0 ]; then exit $$rc; else MTL_DEBUG_LAYER=1 ./t_gmem_raw "$$work/raw.metallib"; fi t_sparse_tiles: t_sparse_tiles.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_sparse_tiles.m ../../host/crash.c ../../host/hle_bigstack.c t_host_stubs.c $(filter-out ../nvn/nvn_mtl.m,$(GFX)) $(FW) t_readback: t_readback.m $(MTL_T_DEP) diff --git a/dm/gfx/tests/t_gmem_raw.m b/dm/gfx/tests/t_gmem_raw.m new file mode 100644 index 0000000000..607720930a --- /dev/null +++ b/dm/gfx/tests/t_gmem_raw.m @@ -0,0 +1,51 @@ +// A translated load at an address the shader read from memory (GlobalToStorage.TryGenerateRawStorageOp), run on the GPU against the host's own pool table (nvn_mtl.m gmem_map_gpu) with more +// pools than its least count: each probe must read its pool's word, including the pools past entry 4,096, and an address in no pool reads 0. The shader is test_dmsh_ampere_mem.py's +// RawGlobal one: it loads the address from words 0 and 1 of storage slot 0 and stores what it read at word 2. +// Usage: t_gmem_raw +#include "../nvn/nvn_mtl.m" +void *front_metal_layer(void) { return NULL; } +module_t *module_of(const void *p) { (void)p; return NULL; } +module_t *g_mod; int g_nmod; +void svc_thread_dump(void) {} +uint64_t now_ns(void) { return bp_now(); } +static int checks, failed; +#define CHECK(label, c) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s (line %d)\n", label, __LINE__); } } while (0) +int main(int argc, const char **argv) { @autoreleasepool { + if (argc != 2) { fprintf(stderr, "usage: t_gmem_raw \n"); return 2; } + mtl_init(); + enum { MANY = 5000, PG = 16384 }; + const uint64_t MB = 1ull << 20; + uint8_t *many = mmap(NULL, (size_t)MANY * 2 * PG, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0), *large = mmap(NULL, 64 * MB, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); + if (many == MAP_FAILED || large == MAP_FAILED) abort(); + for (int i = 0; i < MANY; i++) { uint8_t *p = many + (size_t)i * 2 * PG; mtl_pool_add(p, PG); uint32_t v = 0x10000u + (unsigned)i; memcpy(p + (size_t)(i * 8 % PG), &v, 4); } + mtl_pool_add(large, 64 * MB); { uint32_t v = 0xb16b00b5u; memcpy(large + 40 * MB + 12, &v, 4); } + mtl_sub_begin(); uint64_t map_gpu = gmem_map_gpu(); CHECK("submission completes", mtl_wait(mtl_sub_commit(), 5000000000ull)); + id map = g_gmem_buf; unsigned entries = (unsigned)(map.length / DMSH_GMEM_MAP_ENTRY); + CHECK("the table holds more than the least count", entries > DMSH_GMEM_MAP_ENTRIES && map_gpu == map.gpuAddress); + NSError *error = nil; + id lib = [g_dev newLibraryWithURL:[NSURL fileURLWithPath:@(argv[1])] error:&error]; if (!lib) { fprintf(stderr, "library: %s\n", error.description.UTF8String); return 1; } + id pso = [g_dev newComputePipelineStateWithFunction:[lib newFunctionWithName:@"main0"] error:&error]; if (!pso) { fprintf(stderr, "pipeline: %s\n", error.description.UTF8String); return 1; } + id slot = [g_dev newBufferWithLength:16 options:MTLResourceStorageModeShared], args = [g_dev newBufferWithLength:16 options:MTLResourceStorageModeShared]; + uint64_t *a = args.contents; a[0] = slot.gpuAddress; a[1] = map.gpuAddress; // the argument buffer: storage slot 0 [[id(0)]], the pool table [[id(1)]] + uint32_t (^probe)(uint64_t) = ^uint32_t(uint64_t addr) { + uint32_t *w = slot.contents; memcpy(w, &addr, 8); w[2] = 0xdeadbeefu; + id cb = q_cb(); id ce = [cb computeCommandEncoder]; + [ce setComputePipelineState:pso]; [ce setBuffer:args offset:0 atIndex:0]; + [ce useResource:slot usage:MTLResourceUsageRead | MTLResourceUsageWrite]; [ce useResource:map usage:MTLResourceUsageRead]; + [ce dispatchThreadgroups:MTLSizeMake(1, 1, 1) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)]; + [ce endEncoding]; [cb commit]; [cb waitUntilCompleted]; + CHECK("the dispatch completes", cb.status == MTLCommandBufferStatusCompleted); + return w[2]; + }; + int hits = 0, n = 0; + for (int i = 0; i < MANY; i += 97) { n++; uint64_t p = (uint64_t)(uintptr_t)(many + (size_t)i * 2 * PG); hits += probe(p + (uint64_t)(i * 8 % PG)) == 0x10000u + (unsigned)i; } + { int i = MANY - 1; n++; uint64_t p = (uint64_t)(uintptr_t)(many + (size_t)i * 2 * PG); hits += probe(p + (uint64_t)(i * 8 % PG)) == 0x10000u + (unsigned)i; } + CHECK("small pools: each probe reads its pool", hits == n); + { uint64_t last = (uint64_t)(uintptr_t)(many + (size_t)(MANY - 1) * 2 * PG); unsigned e = 0; + for (unsigned k = 1; k < entries; k++) if (((const uint64_t *)map.contents)[k * (DMSH_GMEM_MAP_ENTRY / 8)] == last) e = k; + CHECK("the last small pool lies past the least table", e >= DMSH_GMEM_MAP_ENTRIES); } + CHECK("a large pool", probe((uint64_t)(uintptr_t)large + 40 * MB + 12) == 0xb16b00b5u); + CHECK("an address in no pool reads 0", probe((uint64_t)(uintptr_t)many + PG + 8) == 0); + printf("t_gmem_raw: %d checks, %d failed (%u table entries, %d probes)\n", checks, failed, entries, n + 2); + return failed != 0; +}} diff --git a/dm/gfx/tests/t_pool_chunks.m b/dm/gfx/tests/t_pool_chunks.m index 943702f97e..55b4553f1c 100644 --- a/dm/gfx/tests/t_pool_chunks.m +++ b/dm/gfx/tests/t_pool_chunks.m @@ -1,6 +1,7 @@ // A large memory pool in chunks (nvn_mtl.m BIG_MIN): a lookup gets a zero-copy buffer that holds what it asked and starts at its stride, so only what lookups reach is wired. The buffers must // say the same memory as the guest address, a read of unknown extent must have BIG_UNKNOWN past it, a chunk asked for more is lengthened, a texture's upload wires no chunk (up_big_src), -// raw global memory's pool table covers the whole pool (big_full), the pool's removal takes every entry, and a smaller pool stays one buffer. +// raw global memory's pool table covers the whole pool (big_full), the pool's removal takes every entry, and a smaller pool stays one buffer. With more pools than the table's least +// count, the table grows and the shader's lookup (gmem_find: the translator's GlobalToStorage.TryGenerateRawStorageOp, on the CPU) still finds every one. #include "../nvn/nvn_mtl.m" void *front_metal_layer(void) { return NULL; } module_t *module_of(const void *p) { (void)p; return NULL; } @@ -9,6 +10,14 @@ void svc_thread_dump(void) {} uint64_t now_ns(void) { return bp_now(); } static int checks, failed; #define CHECK(label, c) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s (line %d)\n", label, __LINE__); } } while (0) +// The entry a translated shader takes for addr, as it does: the binary search over the count in entry 0's delta; 0 when no pool holds addr +static unsigned gmem_find(id map, uint64_t addr) { + const uint32_t *w = map.contents; enum { W = DMSH_GMEM_MAP_ENTRY / sizeof(uint32_t) }; + unsigned k = 0, step = w[4] >> 1; + do { unsigned c = k + step; uint64_t start; memcpy(&start, w + (size_t)c * W, sizeof start); if (start <= addr) k = c; step >>= 1; } while (step); + uint64_t end; memcpy(&end, w + (size_t)k * W + 2, sizeof end); + return addr < end ? k : 0; +} static void finish(void) { CHECK("submission completes", mtl_wait(mtl_sub_commit(), 5000000000ull)); CHECK("GPU has no submission error", !mtl_last_commit_error()); } // The lookup holds [a, a + n) in one buffer whose contents are the guest's memory there, and the GPU address agrees static id look(uint64_t a, uint64_t n) { @@ -86,6 +95,30 @@ int main(void) { @autoreleasepool { CHECK("only the small pool's entry is left of those added", g_npool == pools0 + 1); CHECK("the small pool still answers, its entry moved", look((uint64_t)(uintptr_t)small + 20, 16).length == 64 * MB); CHECK("the large pool's addresses do not", !mtl_gpu_addr(base + 100, 4, &mb, &mo, &gpu)); + // More pools than DMSH_GMEM_MAP_ENTRIES (Ocarina of Time loads its save with up to about 4,500): each still has an entry, found by the search + enum { MANY = 5000, PG = 16384 }; + uint8_t *many = mmap(NULL, (size_t)MANY * 2 * PG, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); if (many == MAP_FAILED) abort(); + for (int i = 0; i < MANY; i++) mtl_pool_add(many + (size_t)i * 2 * PG, PG); // a page apart: a range each + mtl_sub_begin(); CHECK("pool table rebuilt", gmem_map_gpu() != 0); finish(); + id map = g_gmem_buf; unsigned cap = (unsigned)(map.length / DMSH_GMEM_MAP_ENTRY); const uint32_t *mw = map.contents; + CHECK("the table grows to a power of two that holds every pool", cap >= MANY + 2 && !(cap & (cap - 1)) && cap < 2 * (MANY + 2) && mw[4] == cap); + int found = 0, beyond = 0, gaps = 0; unsigned last = 0; + for (int i = 0; i < MANY; i++) { + uint64_t p = (uint64_t)(uintptr_t)(many + (size_t)i * 2 * PG), a = p + (uint64_t)(i * 8 % PG); + unsigned e = gmem_find(map, a); void *pb; uint64_t po, pg; + const uint64_t *r = (const uint64_t *)map.contents + e * (DMSH_GMEM_MAP_ENTRY / sizeof(uint64_t)); + if (e && mtl_gpu_addr(a, 1, &pb, &po, &pg) && a + r[2] == pg) found++; + if (e >= DMSH_GMEM_MAP_ENTRIES) beyond++; + if (i == MANY - 1) last = e; + gaps += gmem_find(map, p + PG) == 0; // the page after the pool: no pool + } + CHECK("every pool's address reaches its memory", found == MANY); + CHECK("pools past the least table are found", beyond > 0 && last >= DMSH_GMEM_MAP_ENTRIES); + CHECK("an address in no pool finds none", gaps == MANY); + for (int i = 0; i < MANY; i++) mtl_pool_del(many + (size_t)i * 2 * PG); + mtl_drain(); + mtl_sub_begin(); gmem_map_gpu(); finish(); + CHECK("with the pools gone the table is the least again", g_gmem_buf.length / DMSH_GMEM_MAP_ENTRY == DMSH_GMEM_MAP_ENTRIES); mtl_pool_del(small); mtl_drain(); printf("t_pool_chunks: %d checks, %d failed\n", checks, failed); return failed != 0; }} diff --git a/dm/gfx/tests/test_dmsh_ampere_mem.py b/dm/gfx/tests/test_dmsh_ampere_mem.py index 98e8c7d3f1..13e226c5be 100644 --- a/dm/gfx/tests/test_dmsh_ampere_mem.py +++ b/dm/gfx/tests/test_dmsh_ampere_mem.py @@ -295,6 +295,48 @@ def sts(offset, rb): # STS.U32 [RZ + offset], Rb: keeps its result return inst(0x000fe80000000800, offset << 40 | rb << 32 | 0xff << 24 | 0x7388) +def ctrl(wb=7, wait=0, stall=2): # an instruction's control bits, high word: stall, yield, write barrier wb, no read barrier, waiting on the barriers in wait + return (stall | 1 << 4 | wb << 5 | 7 << 8 | wait << 11) << 41 + + +class RawGlobal(Translated): + """A load at an address the shader loaded from memory, which no storage buffer holds (GlobalToStorage.TryGenerateRawStorageOp): it goes through the host's pool table + (dmsh_abi.h DMSH_GMEM_MAP_*), a binary search over as many entries as entry 0 says (word 4), however many the pools need. t_gmem_raw runs it on the GPU against the host's table (--fixture)""" + ULDC = (0x000fe40000000a00, 0x0000100000067ab9) # ULDC.64 UR6, c[0][0x40]: storage slot 0 with this job's c0 layout (3 uniform buffers, 1 storage buffer) + ADDR_LO = (0x000fe2000f8e00ff, 0x00000006ff027e24) # IMAD.U32 R2, RZ, RZ, UR6 + ADDR_HI = (0x001fca000f8e00ff, 0x00000007ff037e24) # IMAD.U32 R3, RZ, RZ, UR7 + LDG_PTR = (ctrl(wb=2) | 0x1e1b00, 0x0000000002047381) # LDG.E.64 R4, [R2.64]: the address, from storage slot 0 + LDG_RAW = (ctrl(wb=3, wait=0b100) | 0x1e1900, 0x0000000004067381) # LDG.E R6, [R4.64]: at that address + STORE = (ctrl(wait=0b1000, stall=4) | 0x900, 0x0000080602007386) # STG.E [R2.64 + 8], R6: what it read, at word 2 of storage slot 0 + + def msl(self): + code = b''.join(inst(*c) for c in (self.ULDC, self.ADDR_LO, self.ADDR_HI, self.LDG_PTR, self.LDG_RAW, self.STORE)) + inst(*EXIT) + return self.translate(code, nvn2_cs=[3, 1, 0, 0x50, 0]) + + def has(self, msl, pattern): self.assertTrue(re.search(pattern, msl), f'no {pattern} in the raw access function') # not the whole source in the message + + def test_the_search_takes_the_tables_count(self): # a loop of log2(count) steps from word 4 of entry 0, not 12 steps over a table of 4,096 + msl = self.msl() + self.has(msl, r'= 0 \+ 4;') + self.has(msl, r'\bdo\s*\{[^}]*>> uint\(1\)[^}]*\} while \(') + self.assertFalse(re.search(r'\b2048u?\b', msl), 'an unrolled search over 4,096 entries') + + def test_the_bindings_are_the_ones_t_gmem_raw_fills(self): # storage slot 0 written at word 2 [[id(0)]], the pool table [[id(1)]] + msl = self.msl() + self.has(msl, r'device _\d+\* cp_s0 \[\[id\(0\)\]\];\s*(const )?device _\d+\* cp_s1 \[\[id\(1\)\]\];') + self.has(msl, r'cp_s0\)\._m0\[2\] = ') + + +def raw_fixture(out): + """/raw.metallib: RawGlobal's shader, compiled as the build compiles (dmsh_build.py MAC_METAL), for t_gmem_raw. Exit code 77 when the translator does not run""" + xlate = os.environ.get('DMSH_TEST_XLATE') + if not xlate or subprocess.run([xlate, '--source-sha'], capture_output=True).returncode: sys.exit(77) + msl = Path(out) / 'raw.metal'; msl.write_text(RawGlobal('test_the_search_takes_the_tables_count').msl()) + air = Path(out) / 'raw.air' + subprocess.run(['xcrun', '-sdk', 'macosx', 'metal', '-c', '-O1', '-fpreserve-invariance', str(msl), '-o', str(air)], check=True) + subprocess.run(['xcrun', '-sdk', 'macosx', 'metallib', str(air), '-o', str(Path(out) / 'raw.metallib')], check=True) + + class Shared(Translated): """Fire Emblem Fortune's Weave's Lighting compute shaders: the exposure histogram and its 64-bit average, in the game's own encodings""" STS_SCALED_4 = 0x000fe80000004800, 0x0000000302027388 # STS.U32 [R2 * 4], R3 (6d0f6db3f0d396a3 +0x80 with a value): R2 counts words. Read unscaled, bin b came back at about 4b @@ -506,4 +548,5 @@ def test_membar_orders_memory(self): if __name__ == '__main__': + if len(sys.argv) == 3 and sys.argv[1] == '--fixture': raw_fixture(sys.argv[2]); sys.exit(0) unittest.main() diff --git a/dm/gfx/tools/dmsh_chain.lock b/dm/gfx/tools/dmsh_chain.lock index a80beeb87b..64ade1b016 100644 --- a/dm/gfx/tools/dmsh_chain.lock +++ b/dm/gfx/tools/dmsh_chain.lock @@ -1,7 +1,7 @@ # Translation chain tool fingerprints (written by tool_lock.py --update-lock; regenerate after changing tools and commit it) -dmsh_xlate.dll b161a7de71127ccc -Ryujinx.Graphics.Shader.dll c1abc26f9d16ed8d -Ryujinx.Common.dll 64e7fef74fb5eb57 +dmsh_xlate.dll df697a0fcfd96322 +Ryujinx.Graphics.Shader.dll 0260821e5b61a6a2 +Ryujinx.Common.dll 71e13cfab7bbcf12 xlate_source 0bd66426675438a9 spirv-cross e37945d8e441d34d metal_macosx Apple metal version 32023.922 (metalfe-32023.922.4) diff --git a/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Common.dll b/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Common.dll index f93eb7b624..3df1276ffb 100644 Binary files a/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Common.dll and b/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Common.dll differ diff --git a/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Graphics.Shader.dll b/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Graphics.Shader.dll index e87ef76616..9d6f057472 100644 Binary files a/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Graphics.Shader.dll and b/dm/gfx/tools/dmsh_xlate_bin/Ryujinx.Graphics.Shader.dll differ diff --git a/dm/gfx/tools/dmsh_xlate_bin/Spv.Generator.dll b/dm/gfx/tools/dmsh_xlate_bin/Spv.Generator.dll index b50d073eb0..081683c286 100644 Binary files a/dm/gfx/tools/dmsh_xlate_bin/Spv.Generator.dll and b/dm/gfx/tools/dmsh_xlate_bin/Spv.Generator.dll differ diff --git a/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.dll b/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.dll index 485bebf23a..2fea387db4 100644 Binary files a/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.dll and b/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.dll differ diff --git a/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.pdb b/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.pdb index 203ab0d8bf..2599e12a3f 100644 Binary files a/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.pdb and b/dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate.pdb differ diff --git a/dm/third_party/ryujinx/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs b/dm/third_party/ryujinx/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs index 2fd44a5c1a..37a78b6f88 100644 --- a/dm/third_party/ryujinx/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs +++ b/dm/third_party/ryujinx/src/Ryujinx.Graphics.Shader/Translation/Optimizations/GlobalToStorage.cs @@ -780,10 +780,12 @@ private static bool TryGenerateMultiTargetStorageOp( } // nxnative: the memory pool table the host binds for raw global memory (dmsh_abi.h DMSH_GMEM_MAP_*): a storage buffer reserved under this sentinel constant buffer - // slot, which no constant buffer of the game has (dmsh_build.py turns it into DMSH_KIND_GMEM_MAP). 1 << GmemMapLog2 entries of GmemMapEntryWords words each, - // {start lo, start hi, end lo, end hi, delta lo, delta hi, 0, 0}, sorted by start; entry 0 is empty (start 0, end 0) and unused entries start at ~0 + // slot, which no constant buffer of the game has (dmsh_build.py turns it into DMSH_KIND_GMEM_MAP). Entries of GmemMapEntryWords words each, + // {start lo, start hi, end lo, end hi, delta lo, delta hi, 0, 0}, sorted by start; entry 0 is empty (start 0, end 0) and unused entries start at ~0. + // The host sizes the table to its pools: a power of two of entries, at least DMSH_GMEM_MAP_ENTRIES, the count in entry 0's delta low word (GmemMapCountWord), which no + // lookup uses. A fixed 4,096 entries left the pools past them out (Ocarina of Time loads its save with about 4,100 to 4,500 pools), and the shaders that read their addresses got zeros public const int GmemMapCbSlot = 0xff; - private const int GmemMapLog2 = 12; + private const int GmemMapCountWord = 4; private const int GmemMapEntryWords = 8; // nxnative: the write log (dmsh_abi.h DMSH_GMEM_LOG_*), reserved under the same sentinel slot at offset 1: the set of guest pages (address >> 12) the stores and atomics wrote, @@ -850,12 +852,17 @@ Operand MapWord(Operand entry, int word) return context.Load(StorageKind.StorageBuffer, mapBinding, Const(0), context.IAdd(entry, Const(word))); } - // The last entry whose start is at or below the address (entry 0 starts at 0, so there always is one) - Operand index = Const(0); + // The last entry whose start is at or below the address (entry 0 starts at 0, so there always is one): a binary search over the host's count of entries, a power of two, + // log2 of it steps. A count of 0 or 1 makes one step that stays at entry 0 (no pool) + Operand index = Local(); + Operand step = Local(); + context.Copy(index, Const(0)); + context.Copy(step, context.ShiftRightU32(MapWord(Const(0), GmemMapCountWord), Const(1))); + Operand lblSearch = Label(); + context.MarkLabel(lblSearch); - for (int step = 1 << (GmemMapLog2 - 1); step != 0; step >>= 1) { - Operand candidate = context.IAdd(index, Const(step)); + Operand candidate = context.IAdd(index, step); Operand entry = context.IMultiply(candidate, Const(GmemMapEntryWords)); Operand startLow = MapWord(entry, 0); Operand startHigh = MapWord(entry, 1); @@ -864,9 +871,12 @@ Operand MapWord(Operand entry, int word) context.ICompareLessUnsigned(startHigh, addrHigh), context.BitwiseAnd(context.ICompareEqual(startHigh, addrHigh), context.ICompareLessOrEqualUnsigned(startLow, addrLow))); - index = context.ConditionalSelect(atOrBelow, candidate, index); + context.Copy(index, context.ConditionalSelect(atOrBelow, candidate, index)); + context.Copy(step, context.ShiftRightU32(step, Const(1))); } + context.BranchIfTrue(lblSearch, context.ICompareNotEqual(step, Const(0))); + Operand found = context.IMultiply(index, Const(GmemMapEntryWords)); Operand endLow = MapWord(found, 2); Operand endHigh = MapWord(found, 3); diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index 8310034b2e..dc4602c554 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -856,6 +856,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - bindless handles read from a uniform buffer name the wrong texture when the game writes them earlier in the same submission. → [Handles in uniform buffers written earlier in the same submission](../reference/shaders.md#handles-in-uniform-buffers-written-earlier-in-the-same-submission) - a storage buffer reported with `cb_slot` 3, which had no NVN slot. → [Storage buffer addresses in the game's own uniform buffer](../reference/shaders.md#storage-buffer-addresses-in-the-games-own-uniform-buffer) - whatever a shader writes through a pointer it read from memory never happens. The build summary counted `Failed to find storage buffer for global memory operation "Store"`, and the shader's MSL had a store function with an empty body. In Donkey Kong Bananza the tunnel's walls and floor were black and only the loose rocks drew. → [Global memory at an address loaded from memory](../reference/shaders.md#global-memory-at-an-address-loaded-from-memory) +- `[RED] raw global memory: 1 more memory pools than the 4095 entries of the pool table; addresses in them are not reached`, then within a second `[RED] segment command buffer execution error` with `Caused GPU Hang Error (kIOGPUCommandBufferCallbackErrorHang)` and `InnocentVictim`. The game recovers after one to three hangs, or every later command buffer is `SubmissionsIgnored` and the picture stops for good. In a longer session without a hang, floors go missing in gameplay. → [More memory pools than the raw pool table had entries](../reference/shaders.md#more-memory-pools-than-the-raw-pool-table-had-entries) - `no resolved slot number`, the shader does not load; the translation has a 32-entry texture-pool array (`fp_t2d_cb0_40000000`, handle type Direct). → [Bindless handles through a loop phi](../reference/shaders.md#bindless-handles-through-a-loop-phi) - none in the log: texture reads come back 0. Particle meshes collapse to a point (their scale reads 0), so effects are missing or show as dark patches. The translator's own message (`Failed to find handle source for bindless access of type "textureBuffer"`) used to be dropped, because `dmsh_xlate`'s accessor had no `Log`; its messages now go into the shader's notes, marked `translator: `, and the build summary counts them apart from unanswered queries. → [Bindless reads whose handle phi also carries other values](../reference/shaders.md#bindless-reads-whose-handle-phi-also-carries-other-values) - the shaders' bindless arrays have no slot and used not to load; the translator falls back to a 32-entry array such as `array, 32> vp_tb_cb0_40000000`. → [Texture slots picked at run time](../reference/shaders.md#texture-slots-picked-at-run-time) diff --git a/docs/reference/shaders.md b/docs/reference/shaders.md index b99db561c7..3a8262621e 100644 --- a/docs/reference/shaders.md +++ b/docs/reference/shaders.md @@ -1351,6 +1351,15 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b - **Open:** the prediction is checked, not proven: a miss that does reach a shadow is reported (`[RED]`) after the frame, not prevented. The records' pointers come from memory, so the pools they will reach are not known ahead of the draw. - **Found on:** [Donkey Kong Bananza](../../dm/games/040074A01BF12000/README.md): its terrain, and agl's compute shader `49bc2268925e25b6` (one load); rebuilding the chain changed only these two of Donkey Kong Bananza's shaders. Vertex shader `588e242a52f5f7aa` (five stores) has one too, the same shader in [The Legend of Zelda: Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md) and [Super Mario Bros. Wonder](../../dm/games/010015100B514000/README.md), so likely one the SDK ships; neither drew it in its regression route. +### More memory pools than the raw pool table had entries + +- **Symptom:** `[RED] raw global memory: 1 more memory pools than the 4095 entries of the pool table; addresses in them are not reached`, then within a second `[RED] segment command buffer execution error` with `Caused GPU Hang Error (kIOGPUCommandBufferCallbackErrorHang)` and `InnocentVictim`. The game recovers after one to three hangs, or every later command buffer is `SubmissionsIgnored` and the picture stops for good. In a longer session without a hang, floors go missing in gameplay. +- **Cause:** the [raw global memory](#global-memory-at-an-address-loaded-from-memory) pool table had a fixed 4,096 entries (`GlobalToStorage.GmemMapLog2` = 12). The host left the pools past the last one out, the highest addresses, and a shader read 0 there. The lookup itself stays bounded (its search makes 12 steps and every index is inside the table), but zeros reach the game's own arithmetic. agl's task shader `99280b7b8aae78df` reads both ends of a range through raw loads, takes `min(end - start, 256)` and loops `(count - 1) >> 5` times. A count of 0 makes that 227 − 1 iterations. `DM_NVN_HANGLOG=1` put that shader and its sibling `47f9b38490dcf9a2`, with their mesh shaders, in both segments that hung. Each value a dropped access could return is one some game turns into a hang, so the fix keeps every pool in the table. +- **Fix:** general, in the chain. The host sizes the table to its pools: a power of two of at least 4,096 entries (`DMSH_GMEM_MAP_ENTRIES`), up to 220, with the count in entry 0's delta word (`GmemMapCountWord`). The translator's binary search loops `log2(count)` times from that count instead of 12 unrolled steps. The table is rebuilt when pools come or go, which also shrinks it. Past 220 ranges pools are still left out, with the red line, which now gives the first address and the size left out. The write log (a hash set of pages) does not depend on the table's size. +- **Cost:** 32 bytes an entry: 128 KB for up to 4,095 ranges as before, 256 KB at Ocarina of Time's 4,522. A lookup makes `log2(count)` steps, one more than before at 8,192 entries, plus one load of the count. The chain version changes for every game; shaders without raw global memory are unchanged. +- **Found on:** Ocarina of Time (Switch 2, `0400486024DEC000`, PR #1299): loading the Link's house autosave made 4,097 to 4,522 pools. Upstream issue #1265 (v131072 on an M4 with 16 GB): 2,131 ranges at boot, past 4,095 about eight minutes in and still growing, 88 pools left out, floors missing. Issue #1326 has the same red line in both logs (4,248 to 4,594 pools); its first run hung at 614 s as described here. Its second ended in GPU write faults at 15.5 GB of GPU allocations, which this entry does not explain. Issue #1347 reports that forcing the old size gives the hang. +- **Check:** `t_pool_chunks` (5,000 pools: a table that holds every pool, each address found as the shader finds it), `t_gmem_raw` (the translated load on the GPU against that table: pools past entry 4,095, 0 outside any pool), `test_dmsh_ampere_mem.py` (`RawGlobal`). + ### Bindless handles through a loop phi - **Symptom:** `no resolved slot number`, the shader does not load; the translation has a 32-entry texture-pool array (`fp_t2d_cb0_40000000`, handle type Direct).