From f684c7eb6130b17f43fd4bfbcf8b3a86bcd94947 Mon Sep 17 00:00:00 2001 From: Pedro Nascimento Date: Thu, 5 Nov 2026 22:21:22 -0300 Subject: [PATCH 1/2] Raw pool table words follow the pools at commit: a pool made after a raw shader was encoded no longer reads 0 An argument block holds the pool table that was current when it was encoded. A pool made after that, later in the submission or on another thread while it is encoded, is not in it, and a raw read of that pool gets 0, the failure that hung agl's task shaders. On the author's stack, loading Ocarina of Time's outdoor save, 5,729 of 154,107 table words in argument buffers held an older table than the current one by frame 5,100, and 2,582 held the current one behind the pools. As #1407 does in its stack, the words are noted as they are encoded (gmem_slot_note) and rewritten at each commit, whole or segment (gmem_commit_patch), before the GPU can read them. A new table is built when the pools changed, not refilled in place, as earlier segments may be reading the old one; the replaced one goes through the deferred release as before. The write log of these blocks lists pages, not table entries, so it needs nothing here. The memory report prints the words, those that held an older table and those that held the current one behind the pools. Whether this is what is left of the hang in #1326, minutes after a clean table growth, is open: nothing here reproduced it. t_gmem_words, 13 checks: an unchanged table leaves the words alone; a pool made after two words were noted is in the table they are pointed at, and a new table was built; an older table and one that lags the pools are rewritten and counted; a commit with no words changes nothing. With the rewrite removed, 2 checks fail. t_pool_chunks 75 checks pass; test_docs, test_gfx_tests_makefile, test_env_switches, docs_symptoms.py --check; lint_c.py tidy on nvn_mtl.m and t_gmem_words.m: 0 file/check pairs above the baseline. --- dm/gfx/nvn/nvn_mtl.m | 31 +++++++++++++++++-- dm/gfx/tests/Makefile | 5 ++++ dm/gfx/tests/t_gmem_words.m | 60 +++++++++++++++++++++++++++++++++++++ docs/agents/symptoms.md | 1 + docs/reference/shaders.md | 8 +++++ 5 files changed, 103 insertions(+), 2 deletions(-) create mode 100644 dm/gfx/tests/t_gmem_words.m diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index f73da6dac7..1e90cda207 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -895,6 +895,7 @@ void mtl_prepare(void) { if (!g_warm_started && prepare_on()) { mtl_init(); shmap_load(); } } static void sub_cut_begin(void); +static void gmem_commit_patch(void); // the raw pool table words of the arguments encoded so far follow the pools (gmem_slot_note) void mtl_sub_begin(void) { mtl_init(); g_sub_serial++; g_seg = 0; seg_clk_put(g_sclk); g_sclk = NULL; g_rc_npend = 0; g_rc_skip = 0; sub_cut_begin(); @@ -1723,6 +1724,7 @@ uint64_t mtl_sub_commit(void) { rp_flush(); ubd_land(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; } up_flush(); + gmem_commit_patch(); g_cut_copy = 0; treg_finish_submission(); // Late descriptor views retire behind this submission's fence. uint64_t fence = ++g_fence; @@ -3462,6 +3464,8 @@ void mtl_mem_stat(unsigned long long frame, unsigned long long rss_mb) { MLOG("GPU allocation growth by function: pass end %llu MB, pass begin %llu MB, pipeline fetch %llu MB, argument buffers %llu MB, texture fetch %llu MB", g_ap_fn[0] >> 20, g_ap_fn[1] >> 20, g_ap_fn[2] >> 20, g_ap_fn[3] >> 20, g_ap_fn[4] >> 20); } if (g_allocprof > 0) { int top[4] = {-1, -1, -1, -1}; for (int o = 0; o < 64; o++) for (int k = 0; k < 4; k++) if (top[k] < 0 || g_ap_bytes[o] > g_ap_bytes[top[k]]) { for (int j = 3; j > k; j--) top[j] = top[j - 1]; top[k] = o; break; } MLOG("GPU allocation growth by op: op%d %llu MB, op%d %llu MB, op%d %llu MB, op%d %llu MB", top[0], g_ap_bytes[top[0]] >> 20, top[1], g_ap_bytes[top[1]] >> 20, top[2], g_ap_bytes[top[2]] >> 20, top[3], g_ap_bytes[top[3]] >> 20); } + { void mtl_gmem_words(uint64_t *, uint64_t *, uint64_t *); uint64_t gw, go, gb; mtl_gmem_words(&gw, &go, &gb); + if (gw) MLOG("raw pool table words at commit: %llu, of them %llu held an older table than the current one and %llu the current one behind the pools", (unsigned long long)gw, (unsigned long long)go, (unsigned long long)gb); } } void mtl_pkg_stats(uint64_t *uploads, uint64_t *reuploads) { *uploads = g_pkg_uploads; *reuploads = g_pkg_reuploads; } uint64_t mtl_pkg_edge_skips(void) { return g_pkg_edge_skips; } @@ -8036,6 +8040,26 @@ static uint64_t gmem_map_gpu(void) { { 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); } return b.gpuAddress; } +// An argument block holds the pool table that was current when it was encoded. A pool made after that, later in the submission or on another thread while it is encoded, is not in it, and a raw +// read of that pool gets 0: the failure that hung agl's task shaders (docs/reference/shaders.md, More memory pools than the raw pool table had entries). The GPU has not read the blocks of the +// command buffer yet, so at each commit, whole or segment, their table words are pointed at a table of the pools as they are then (as #1407 does). A new table is built when the pools changed, +// not refilled in place, as earlier segments may be reading the old one. Counted in the memory report: the words, those that held an older table than the current one, and those that held the +// current one behind the pools. The write log of those blocks lists pages, not table entries, so it needs nothing +static uint64_t **g_gmem_slots; static int g_gmem_nslots, g_gmem_cslots; static uint64_t g_gmem_words, g_gmem_older, g_gmem_behind; +static void gmem_slot_note(uint64_t *w) { + if (g_gmem_nslots == g_gmem_cslots) { g_gmem_cslots = g_gmem_cslots ? 2 * g_gmem_cslots : 256; g_gmem_slots = realloc_or_die(g_gmem_slots, (size_t)g_gmem_cslots * sizeof *g_gmem_slots, "the raw pool table's word list"); } + g_gmem_slots[g_gmem_nslots++] = w; +} +void mtl_gmem_words(uint64_t *words, uint64_t *older, uint64_t *behind) { *words = g_gmem_words; *older = g_gmem_older; *behind = g_gmem_behind; } +static void gmem_commit_patch(void) { + int n = g_gmem_nslots; g_gmem_nslots = 0; if (!n || !g_gmem_buf) return; + uint64_t was = g_gmem_buf.gpuAddress; int lag = atomic_load(&g_pool_gen) != g_gmem_gen; + uint64_t cur = gmem_map_gpu(); + g_gmem_words += (uint64_t)n; + for (int i = 0; i < n; i++) { uint64_t *w = g_gmem_slots[i]; if (*w == cur) continue; + if (*w != was) g_gmem_older++; else if (lag) g_gmem_behind++; + *w = cur; } +} // 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 // write anywhere, they refused every shadow of the submission and of the next ones: Donkey Kong Bananza's tunnel ran at 70 ms a frame, 4,533 passes a frame ended to land deferred updates. // So each store also puts its guest page in a write log (DMSH_KIND_GMEM_LOG, a set of pages), each draw or dispatch with such stores gets its own log from a small pool, and the host @@ -8175,6 +8199,7 @@ static int encode_args_(id en, NvShader *sh, int nvn_stage, i return 1; } NSUInteger arg_len = sh->arg_len ? sh->arg_len : sh->ae.encodedLength; + int gmem_aid = -1; // the slot that holds the raw pool table (gmem_slot_note) uint64_t slots[NVN_REFL_MAXARG]; memset(slots, 0, arg_len < sizeof slots ? arg_len : sizeof slots); // only the bytes that are copied out (they used to be zeroed in full, before the reuse check too) #define USE(r, u) do { (void)(u); if (__builtin_expect(g_res_check_on, 0)) res_check((r), sh->key, reg); } while (0) // DM_NVN_PASSDUMP: on the first new encode per pass per stage, records the shader key (K) and the actual source of each binding (B: UBO address / length / first 4 floats, texture ID and serial, or "dummy") @@ -8362,7 +8387,7 @@ static int encode_args_(id en, NvShader *sh, int nvn_stage, i slots[aid] = (sh->c1buf ? sh->c1_gpu : zero_bank_gpu()) + (sh->c1buf ? sh->c1off : 0); USE(cb, MTLResourceUsageRead); } else if (b->kind == NVN_RB_GMEM) { // B: the memory pool table for addresses traced to no storage buffer (gmem_map_gpu) - slots[aid] = gmem_map_gpu(); + slots[aid] = gmem_map_gpu(); gmem_aid = aid; if (bl) PD("B %llu st%d gmem %s", g_stat_pass, nvn_stage, b->rw ? "rw" : "ro"); } else if (b->kind == NVN_RB_GMEML) { // B: the write log of those stores; their writes are noted as gml_take learned them slots[aid] = gml_take(); @@ -8439,7 +8464,8 @@ static int encode_args_(id en, NvShader *sh, int nvn_stage, i #undef USE os_unfair_lock_unlock(&g_rmu); id ab; size_t off = arena_alloc(arg_len, &ab); - memcpy(g_cur_arena->cpu + off, slots, arg_len); // the arena arena_alloc took it from (no contents message: see ubo_read) + memcpy(g_cur_arena->cpu + off, slots, arg_len); + if (gmem_aid >= 0) gmem_slot_note((uint64_t *)(void *)(g_cur_arena->cpu + off) + gmem_aid); // the arena arena_alloc took it from (no contents message: see ubo_read) bind_args(en, nvn_stage, metal_vertex, ab, g_cur_arena->gpu + off, off, sh->rf.abi); sh->ab_buf = ab; sh->ab_gpu = g_cur_arena->gpu + off; sh->ab_off = off; sh->ab_pass = g_pass.serial; sh->ab_binst = g_draw_binst; sh->ab_pgen = g_psnap_gen; g_args_dirty[nvn_stage] = 0; g_stat_args_enc++; @@ -12060,6 +12086,7 @@ static void sub_cut(void) { if (sc) { if (k < SEG_CLK_N) { atomic_store(&sc->t[k][0], gpu_s_guest_ns(cb.GPUStartTime)); atomic_store(&sc->t[k][1], gpu_s_guest_ns(cb.GPUEndTime)); } seg_clk_put(sc); } if (cb.error) { atomic_store(&g_last_commit_error, 1); static int k; if (k++ < 8) MLOG("[RED] segment command buffer execution error: %s", cb.error.description.UTF8String); res_top_once(cb.error); } }]; + gmem_commit_patch(); res_commit(); [g_cb endCommandBuffer]; rec_commit(g_cb, o); diff --git a/dm/gfx/tests/Makefile b/dm/gfx/tests/Makefile index 5288b37c2b..daa0fe52b8 100644 --- a/dm/gfx/tests/Makefile +++ b/dm/gfx/tests/Makefile @@ -155,6 +155,11 @@ 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) +t_gmem_words: t_gmem_words.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ t_gmem_words.m $(MTL_T_SRC) $(FW) +.PHONY: check_t_gmem_words +check_t_gmem_words: t_gmem_words + MTL_DEBUG_LAYER=1 ./t_gmem_words 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_words.m b/dm/gfx/tests/t_gmem_words.m new file mode 100644 index 0000000000..1b38a8a33e --- /dev/null +++ b/dm/gfx/tests/t_gmem_words.m @@ -0,0 +1,60 @@ +// The raw pool table words of the argument blocks encoded so far follow the pools at commit (nvn_mtl.m gmem_slot_note, gmem_commit_patch): a pool made after a block was encoded is in the +// table its word points at when the GPU reads it, a word behind the pools or holding an older table is rewritten and counted, and a word that is current is left alone. +#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) +// Whether the table the GPU address names has an entry that starts at the guest address (every table is the current one's or an older, still alive one) +static int table_has(uint64_t table_gpu, uint64_t guest) { + if (!g_gmem_buf || g_gmem_buf.gpuAddress != table_gpu) return 0; + const uint8_t *t = g_gmem_buf.contents; + for (unsigned k = 1; k < DMSH_GMEM_MAP_ENTRIES; k++) { uint64_t lo; memcpy(&lo, t + (size_t)k * DMSH_GMEM_MAP_ENTRY, sizeof lo); if (lo == guest) return 1; } + return 0; +} +int main(void) { @autoreleasepool { + mtl_init(); + const uint64_t MB = 1ull << 20; + uint8_t *mem = mmap(NULL, 64 * MB, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); if (mem == MAP_FAILED) abort(); + uint64_t a = (uint64_t)(uintptr_t)mem; + mtl_pool_add(mem, 4 * MB); + mtl_sub_begin(); + uint64_t t0 = gmem_map_gpu(); // the table two argument blocks were encoded with + uint64_t w0 = t0, w1 = t0, w2 = 0; + uint64_t words0, older0, behind0; mtl_gmem_words(&words0, &older0, &behind0); + gmem_slot_note(&w0); gmem_slot_note(&w1); + gmem_commit_patch(); + uint64_t words, older, behind; mtl_gmem_words(&words, &older, &behind); + CHECK("an unchanged table leaves the words alone", w0 == t0 && w1 == t0 && g_gmem_buf.gpuAddress == t0); + CHECK("two words counted, none out of date", words - words0 == 2 && older == older0 && behind == behind0); + mtl_pool_add(mem + 8 * MB, 4 * MB); // a pool made after the blocks were encoded + CHECK("the table the words hold lacks it", !table_has(t0, a + 8 * MB)); + gmem_slot_note(&w0); gmem_slot_note(&w1); + gmem_commit_patch(); + uint64_t t1 = g_gmem_buf.gpuAddress; + CHECK("a new table was built, not the old one refilled", t1 != t0); + CHECK("both words point at it", w0 == t1 && w1 == t1); + CHECK("it holds the pool made after they were encoded", table_has(t1, a + 8 * MB)); + mtl_gmem_words(&words, &older, &behind); + CHECK("two words counted as behind the pools", behind - behind0 == 2 && older == older0); + mtl_pool_add(mem + 16 * MB, 4 * MB); + uint64_t t2 = gmem_map_gpu(); // another block is encoded with the newer table, then the pools change again + mtl_pool_add(mem + 24 * MB, 4 * MB); + w2 = t1; // a block encoded with the older table + uint64_t w3 = t2; // and one with the table that now lags the pools + gmem_slot_note(&w2); gmem_slot_note(&w3); + gmem_commit_patch(); + uint64_t t3 = g_gmem_buf.gpuAddress; + CHECK("the words follow the last table", w2 == t3 && w3 == t3 && t3 != t2); + CHECK("it holds all four added pools", table_has(t3, a + 8 * MB) && table_has(t3, a + 16 * MB) && table_has(t3, a + 24 * MB)); + mtl_gmem_words(&words, &older, &behind); + CHECK("one word counted as older, one as behind", older - older0 == 1 && behind - behind0 == 3); + gmem_commit_patch(); // nothing noted since + CHECK("a commit with no words changes nothing", g_gmem_buf.gpuAddress == t3); + CHECK("submission completes", mtl_wait(mtl_sub_commit(), 5000000000ull)); + CHECK("GPU has no submission error", !mtl_last_commit_error()); + printf("t_gmem_words: %d checks, %d failed\n", checks, failed); return failed != 0; +} } diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index abd5629b9d..9ee093dbe2 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -908,6 +908,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - geometry preparation dominates rendering CPU even after geometry passes have been batched; primitive assembly and capture-index deduplication repeat for unchanged meshes. → [Prepared geometry indices reused after byte comparison](../reference/shaders.md#prepared-geometry-indices-reused-after-byte-comparison) - geometry vertex-capture passes consume substantial GPU time before geometry compute or depth rasterization. → [Geometry capture initializes only missing words](../reference/shaders.md#geometry-capture-initializes-only-missing-words) - Apple's performance HUD (`DM_METAL_HUD=1`) says `Compiled 2 shaders. Total compilation time is 102.70ms. Consider adopting MTL4Compiler for more fine grained compilations` during play, with a dip in the frame-rate graph at that moment, for example when a new room first issues a scissored clear. → [The host's own shaders compiled from source at run time](../reference/shaders.md#the-hosts-own-shaders-compiled-from-source-at-run-time) +- a raw global memory read of a memory pool made after the shader's arguments were encoded gets 0, though the pool exists when the GPU runs it; a task shader that reads both ends of a range this way loops `(0 - 1) >> 5` times and hangs the GPU. The memory report's `raw pool table words at commit` line counts the words that were out of date. → [Raw pool table words that predate the pools](../reference/shaders.md#raw-pool-table-words-that-predate-the-pools) ## Game state diff --git a/docs/reference/shaders.md b/docs/reference/shaders.md index 26f53d2d26..81616c8d0a 100644 --- a/docs/reference/shaders.md +++ b/docs/reference/shaders.md @@ -1830,3 +1830,11 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b - **Check:** `t_host_msl` loads every library, with a swizzled `newLibraryWithSource:` that counts 0 calls, and finds all 24 clear functions. `t_builtin`, `t_geometry` and `t_deswz_gpu` use the built libraries. - **Build inputs:** Mac libraries use `MACOS_MIN` from `dm/mac/min_os.mk`, matching the host's deployment target; otherwise a newer SDK emits libraries older supported Macs cannot load and the host falls back to runtime compilation. Every build rechecks the compiler, SDK, deployment target and source contents, reusing the header only when all match. Installing the Metal toolchain after a source-only build therefore regenerates the libraries without a clean build. - **Build callers:** the NSP packer and regression harness generate the Mac header before checking their cached host executables, and include it in the host fingerprint. The standalone iOS compile check generates the iPhone header before its dry run, as the app build does. A dry run alone does not generate either header. + +### Raw pool table words that predate the pools + +- **Symptom:** a raw global memory read of a memory pool made after the shader's arguments were encoded gets 0, though the pool exists when the GPU runs it; a task shader that reads both ends of a range this way loops `(0 - 1) >> 5` times and hangs the GPU. The memory report's `raw pool table words at commit` line counts the words that were out of date. +- **Cause:** an argument block holds the address of the pool table that was current when it was encoded (`gmem_map_gpu`). A pool made later in the same submission, or on another thread while it is encoded, is not in that table, and the table is rebuilt only for the next block that is encoded. A save load makes more than 4,000 pools in a burst, so many blocks are encoded with a table that lags. +- **Fix:** the words are noted as they are encoded (`gmem_slot_note`) and, at each commit of the command buffer, whole or segment, pointed at a table of the pools as they are then (`gmem_commit_patch`). A new table is built when the pools changed, not refilled in place, as earlier segments may be reading the old one; the replaced one goes through the deferred release. The write log of these blocks lists pages, not table entries, so it needs nothing. The idea is #1407's, which rewrites the words at commit in its own stack. +- **Found on:** The Legend of Zelda: Ocarina of Time (`0400486024DEC000`, profile in PR #1299): on the author's stack, loading the outdoor save, 5,729 of 154,107 words held an older table than the current one by frame 5,100 and 2,582 held the current one behind the pools. Whether this is what is left of the hang in issue #1326, minutes after a clean table growth, is open. +- **Check:** `t_gmem_words` (words noted, a pool made after them, an older table, a table that lags, a commit with no words). From 3037961af2d956a11db3acc181a8c7511e1f9635 Mon Sep 17 00:00:00 2001 From: Pedro Nascimento Date: Fri, 6 Nov 2026 02:36:35 -0300 Subject: [PATCH 2/2] t_gmem_words looks through the whole table, not its first 4,096 entries table_has walked DMSH_GMEM_MAP_ENTRIES entries. A table that grows with its pools (#1360) has more, and a pool past entry 4,095 would not have been found. It walks the buffer's length now, which is the same 4,096 entries on main. Pointed out by deanpektas27 on #1360. Checked: check_t_gmem_words, 13 checks, 0 failed. --- dm/gfx/tests/t_gmem_words.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dm/gfx/tests/t_gmem_words.m b/dm/gfx/tests/t_gmem_words.m index 1b38a8a33e..8d9b066f5e 100644 --- a/dm/gfx/tests/t_gmem_words.m +++ b/dm/gfx/tests/t_gmem_words.m @@ -12,7 +12,7 @@ void svc_thread_dump(void) {} static int table_has(uint64_t table_gpu, uint64_t guest) { if (!g_gmem_buf || g_gmem_buf.gpuAddress != table_gpu) return 0; const uint8_t *t = g_gmem_buf.contents; - for (unsigned k = 1; k < DMSH_GMEM_MAP_ENTRIES; k++) { uint64_t lo; memcpy(&lo, t + (size_t)k * DMSH_GMEM_MAP_ENTRY, sizeof lo); if (lo == guest) return 1; } + for (unsigned k = 1, n = (unsigned)(g_gmem_buf.length / DMSH_GMEM_MAP_ENTRY); k < n; k++) { uint64_t lo; memcpy(&lo, t + (size_t)k * DMSH_GMEM_MAP_ENTRY, sizeof lo); if (lo == guest) return 1; } return 0; } int main(void) { @autoreleasepool {