From b830eda76a6cff93e43bd8415cc1e025c25753cf Mon Sep 17 00:00:00 2001 From: seedds Date: Sun, 15 Nov 2026 10:23:34 +0100 Subject: [PATCH] OoT-sleep C-1: a non-compiling pipeline call waits for another thread's archive lookup of the same base, not only returns nil, so a draw that comes during a background lookup takes its stand-in instead of compiling its base on the submit thread pso_build_ex with compile 0 (a draw asking whether its base or its pulling base is made or archived, a prewarm task) returned nil at once when another thread held that base's job, so that it would never wait for the Metal compiler. A job's owner first only looks in the archives, which takes milliseconds, and a non-compiling owner does nothing else. A draw that came during such a lookup of its pulling base found no stand-in; its own base was already known missing, so it compiled that base on the submit thread. The prediction's background base lookups (pso_bg_look, PR #2677) make the race happen every time: they look up the bases of the draws that come next in the same submission, milliseconds before those draws. On the owner's iPhone 17 play of 2026-11-14 the builds with them had single draws waiting 0.3-1.8 s on first visits ("draws that waited: pulling base not made yet" 1 / 861 ms, 2 / 1,081 ms, 8 / 1,786 ms per 300 frames, while the background lookups found every base: 21 of 21), against 1 / 95 ms on the build without them. - PbaseBuild.looked / found: the owner leaves looked once it has looked in the archives (or skipped them for a base known missing), with the base it found, before the compaction's capture and before any compile. - A compile 0 call that finds another thread's job waits on looked and takes found; when the lookup found nothing it returns nil as before, without waiting for the compile. Mac, M4, Ocarina of Time v131072, an unattended route from a Kakariko save (out to Hyrule Field and back), a first visit (no recorded pipeline list), the archive holding only the pair prebuild's pulling bases (as the phone's bundled archive), hosts on the phone tree (be8db251 + #2677's commits), one run each: draws that waited 214 / 32.0 s without the fix, 216 / 29.5 s with it. On the Mac an archive lookup takes well under a millisecond, so the race's window is small there and the waits left are draws whose pulling base no archive holds; the race shows on the phone, where a lookup takes about 10 ms. Not run: the phone (no phone in this batch). Checked: t_pso_look_wait 9 checks, new (fails without the fix: the call during a 200 ms lookup returned nil at once); t_pso_pending 66, t_pso_stall 73, t_pso_archive 362, t_pso_depth_stencil 301, t_pso_prewarm 64, t_pso_warm 123, t_pso_bundle 83, t_pso_msaa 34; test_docs; lint_c.py tidy (nothing above the baseline). regress.py: not run. The only game this Mac can run it on is Ocarina of Time, which has no smoke route, so the check is its shader chain alone, which this change does not touch; the route runs above booted the game with the change. New reference entry: docs/reference/frame-rate.md, "A draw that came during another thread's archive lookup compiled its base"; symptom index updated. (cherry picked from commit 51a1de473f5aac98cc4e37a59d435a9f7171b441) --- dm/gfx/nvn/nvn_mtl.m | 15 ++++-- dm/gfx/tests/Makefile | 3 ++ dm/gfx/tests/t_pso_look_wait.m | 93 ++++++++++++++++++++++++++++++++++ docs/agents/symptoms.md | 1 + docs/reference/frame-rate.md | 8 +++ 5 files changed, 117 insertions(+), 3 deletions(-) create mode 100644 dm/gfx/tests/t_pso_look_wait.m diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index 8c0f7665d4..edcce9a330 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -9276,7 +9276,8 @@ static id arch_lookup(MTL4PipelineDescriptor *d, int plain, int *from_run) { static nvn_hmap g_pbase_miss = {.klen = sizeof(pbase_key)}; // Only callers for the same base wait on this group; unrelated bases compile in parallel. // compiled: its owner asked the compiler (a compile 0 owner only looks in the archive, and a waiter that needs the base builds it itself when that found none). -@interface PbaseBuild : NSObject { @public dispatch_group_t done; id ps; NSError *error; int compiled; } @end +// looked: left once the owner has looked in the archives (or skipped them for a base known missing), found: the base that found, set before; a compile 0 waiter waits on it +@interface PbaseBuild : NSObject { @public dispatch_group_t done, looked; id ps, found; NSError *error; int compiled; } @end @implementation PbaseBuild @end static nvn_hmap g_pbase_pending = {.klen = sizeof(pbase_key)}; static os_unfair_lock g_pbase_lock = OS_UNFAIR_LOCK_INIT; @@ -10139,11 +10140,18 @@ static void pbase_key_of(MTLRenderPipelineDescriptor *d, int off, pbase_key *k) known = hm_get_id(&g_pbase_miss, &bk) != nil; if (known && !compile) { os_unfair_lock_unlock(&g_pbase_lock); return nil; } job = hm_get_id(&g_pbase_pending, &bk); - if (!job) { job = [PbaseBuild new]; job->done = dispatch_group_create(); dispatch_group_enter(job->done); hm_put_id(&g_pbase_pending, &bk, job); owner = 1; } + if (!job) { + job = [PbaseBuild new]; job->done = dispatch_group_create(); job->looked = dispatch_group_create(); + dispatch_group_enter(job->done); dispatch_group_enter(job->looked); hm_put_id(&g_pbase_pending, &bk, job); owner = 1; + } } os_unfair_lock_unlock(&g_pbase_lock); if (!job || owner) break; - if (!compile) return nil; // another thread is taking or building it: no wait for the Metal compiler + // Another thread is taking or building it. A compile 0 call waits for that thread's archive lookup (milliseconds) and takes the base it found, never for its compile. + // Returning nil at once, as before, sent a draw that came while a background worker (pso_bg_look, hy_base_kick) looked up its pulling base to no stand-in and then + // to a compile of its own base on the submit thread: Ocarina of Time on an iPhone 17, first visits to Hyrule Field and Kakariko, one draw 0.3-1.8 s ("draws that waited: + // pulling base not made yet"), while every lookup the workers made found its base + if (!compile) { dispatch_group_wait(job->looked, DISPATCH_TIME_FOREVER); base = job->found; if (base) break; return nil; } dispatch_group_wait(job->done, DISPATCH_TIME_FOREVER); base = job->ps; if (base) break; if (job->compiled) { if (e) *e = job->error; return nil; } @@ -10156,6 +10164,7 @@ static void pbase_key_of(MTLRenderPipelineDescriptor *d, int off, pbase_key *k) int from_run = 0; base = known ? nil : arch_lookup(b, vd, &from_run); uint64_t t1 = bp_now(); if (base) { g_pb_archived++; g_pt_hit_n++; g_pt_hit_ns += t1 - t0; } + job->found = base; dispatch_group_leave(job->looked); // before the compaction's capture below, which compiles if (base && from_run && g_compact_enabled && atomic_load(&g_warm_running)) { // Metal can crash in materializeAirNTFromOnlineForSlice when serializing archive imports mixed with fresh bases (#342). // Work around that framework bug by capturing the original shader functions, without lookupArchives. The normal compiler cache still applies. diff --git a/dm/gfx/tests/Makefile b/dm/gfx/tests/Makefile index 7b1305a109..c3ebca3c1e 100644 --- a/dm/gfx/tests/Makefile +++ b/dm/gfx/tests/Makefile @@ -373,6 +373,9 @@ t_ubc_wait: t_ubc_wait.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_ubc_wait.m $(MTL_T_SRC) $(FW) t_pso_pending: t_pso_pending.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_pso_pending.m $(MTL_T_SRC) $(FW) +t_pso_look_wait: t_pso_look_wait.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ t_pso_look_wait.m $(MTL_T_SRC) $(FW) +check_t_pso_look_wait: RUN_ENV = MTL_DEBUG_LAYER=1 t_shmap_warm: t_shmap_warm.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_shmap_warm.m $(MTL_T_SRC) $(FW) t_pso_depth_stencil: t_pso_depth_stencil.m $(MTL_T_DEP) diff --git a/dm/gfx/tests/t_pso_look_wait.m b/dm/gfx/tests/t_pso_look_wait.m new file mode 100644 index 0000000000..664c9359f2 --- /dev/null +++ b/dm/gfx/tests/t_pso_look_wait.m @@ -0,0 +1,93 @@ +// A compile 0 call of pso_build_ex (nvn_mtl.m) for a base another thread holds: it waits for that thread's archive lookup, which takes milliseconds, and takes the base +// it found; it never waits for that thread's compile. Before, it returned nil at once, so a draw that came while a background worker looked up its pulling base found no +// stand-in and compiled its own base on the submit thread instead (Ocarina of Time on an iPhone 17, first visits: one draw waited 0.3-1.8 s). +// The other thread is played here by hand: a job planted in g_pbase_pending, finished from a dispatch_after block. Real Metal 4 compiles of synthetic shaders, no archive. +#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(c, label) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s\n", label); } else printf("ok: %s\n", label); } while (0) + +static NvProg *program(float z) { + NSError *error = nil; + NSString *src = [NSString stringWithFormat:@"#include \nusing namespace metal;\n" + "vertex float4 v(uint n[[vertex_id]]) { float2 p[3]={float2(-1,-1),float2(3,-1),float2(-1,3)}; return float4(p[n],%f,1); }\n" + "fragment float4 f() { return float4(1,0,0,1); }\n", z]; + id lib = [g_dev newLibraryWithSource:src options:nil error:&error]; + if (!lib) { fprintf(stderr, "%s\n", error.localizedDescription.UTF8String); exit(1); } + NvProg *p = [NvProg new]; + p->sh[0] = [NvShader new]; p->sh[1] = [NvShader new]; + snprintf(p->sh[0]->key, sizeof p->sh[0]->key, "lw%.2f-vs", z); snprintf(p->sh[1]->key, sizeof p->sh[1]->key, "lw%.2f-fs", z); p->sh[1]->stage = 1; + p->sh[0]->fn = fn4_note([lib newFunctionWithName:@"v"], lib, @"v", nil); + p->sh[1]->fn = fn4_note([lib newFunctionWithName:@"f"], lib, @"f", nil); + p->sh[1]->rf.color_known = 1; p->sh[1]->rf.color_mask = 1; + return p; +} +// The descriptor of p's pipeline for one colour attachment, and its base's key +static MTLRenderPipelineDescriptor *desc(NvProg *p, pso_key *k, pbase_key *bk) { + state_reset(); pso_key_fill(k, p->sh[0], p->sh[1], (uint32_t[8]){70}, 0, 0, 1, 0); + MTLRenderPipelineDescriptor *d = pso_desc(k, p->sh[0], p->sh[1], nil, 0); + pbase_key_of(d, !k->border, bk); + return d; +} +// A job for bk as another thread's would be while it looks in the archive +static PbaseBuild *plant(const pbase_key *bk) { + PbaseBuild *job = [PbaseBuild new]; job->done = dispatch_group_create(); job->looked = dispatch_group_create(); + dispatch_group_enter(job->done); dispatch_group_enter(job->looked); + os_unfair_lock_lock(&g_pbase_lock); hm_put_id(&g_pbase_pending, bk, job); os_unfair_lock_unlock(&g_pbase_lock); + return job; +} +static void finish(PbaseBuild *job, const pbase_key *bk, id base) { // what the owner does at the end + os_unfair_lock_lock(&g_pbase_lock); + job->ps = base; if (base) hm_put_id(&g_pbase, bk, base); + hm_rel(nvn_hm_del(&g_pbase_pending, bk)); dispatch_group_leave(job->done); + os_unfair_lock_unlock(&g_pbase_lock); +} + +int main(void) { @autoreleasepool { + setenv("DM_PSO_ARCHIVE", "off", 1); setenv("DM_PSO_MANIFEST", "off", 1); setenv("DM_PSO_USER", "/dev/null", 1); + setenv("DM_PSO_PREBUILD", "0", 1); setenv("DM_NVN_PREDICT", "0", 1); setenv("DM_PSO_MTL4", "1", 1); + mtl_init(); pso4_init(); + if (!g_comp4) { printf("no Metal 4 bases on this system: nothing to check\n"); return 0; } + dispatch_queue_t other = dispatch_queue_create("t.owner", DISPATCH_QUEUE_SERIAL); + + // 1. The other thread's lookup finds the base after 200 ms: the compile 0 call waits for it and specializes it, with no compile of its own + { NvProg *p = program(.25f); pso_key k; pbase_key bk; MTLRenderPipelineDescriptor *d = desc(p, &k, &bk); + NSError *e = nil; id base = nil; + { MTL4RenderPipelineDescriptor *b = pso_desc4(d, 1, !k.border); base = [g_comp4 newRenderPipelineStateWithDescriptor:b compilerTaskOptions:nil error:&e]; } + CHECK(base != nil, "the base builds"); + PbaseBuild *job = plant(&bk); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC), other, ^{ job->found = base; dispatch_group_leave(job->looked); finish(job, &bk, base); }); + uint64_t built = g_pb_built, t0 = bp_now(); + id ps = pso_build_ex(d, !k.border, &e, 0); + double ms = (bp_now() - t0) / 1e6; + CHECK(ps != nil, "a compile 0 call for a base being looked up takes the base the lookup found"); + CHECK(ms >= 150, "it waited for the lookup"); + CHECK(g_pb_built == built, "it compiled nothing"); + dispatch_sync(other, ^{}); + } + // 2. The other thread's lookup finds nothing after 100 ms and then compiles for 2 s: the compile 0 call returns nil after the lookup, not after the compile + { NvProg *p = program(.5f); pso_key k; pbase_key bk; MTLRenderPipelineDescriptor *d = desc(p, &k, &bk); + PbaseBuild *job = plant(&bk); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 100 * NSEC_PER_MSEC), other, ^{ dispatch_group_leave(job->looked); usleep(2000000); finish(job, &bk, nil); }); + NSError *e = nil; uint64_t t0 = bp_now(); + id ps = pso_build_ex(d, !k.border, &e, 0); + double ms = (bp_now() - t0) / 1e6; + CHECK(ps == nil, "a compile 0 call whose base the lookup did not find returns nil"); + CHECK(ms < 1000, "it does not wait for the other thread's compile"); + dispatch_sync(other, ^{}); + } + // 3. A compile 0 owner (no other thread): an archive miss still returns nil and marks the base missing; a later compile 0 call returns nil at once + { NvProg *p = program(.75f); pso_key k; pbase_key bk; MTLRenderPipelineDescriptor *d = desc(p, &k, &bk); + NSError *e = nil; + CHECK(pso_build_ex(d, !k.border, &e, 0) == nil, "a compile 0 owner with no archive finds nothing"); + os_unfair_lock_lock(&g_pbase_lock); int miss = hm_get_id(&g_pbase_miss, &bk) != nil, pend = hm_get_id(&g_pbase_pending, &bk) != nil; os_unfair_lock_unlock(&g_pbase_lock); + CHECK(miss && !pend, "the base is marked missing and its job is gone"); + CHECK(pso_build_ex(d, !k.border, &e, 1) != nil, "a compiling call then builds it"); + } + printf("lookup waits: %d checks, %d failed\n", checks, failed); + return failed != 0; +} } diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index 591b1511d1..66ca7a1e4c 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -663,6 +663,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - a busy scene runs far below what its GPU time allows, with the main thread busy for most of each second. The `pipelines up to frame` line shows archive lookups that found none in the thousands per 300 frames, at about 3 ms each, many draws with a hybrid pipeline, and `in flight 384`. Ocarina of Time's castle town market: 9,208 searches, 30.5 s in 300 frames, CPU translation 114 ms a frame. → [Archive searches repeated while the build table is full](../reference/frame-rate.md#archive-searches-repeated-while-the-build-table-is-full) - frames of 50–170 ms on entering an area, in every run again, although the prewarm lists and the pipeline archive hold everything the area draws. The long-frame line shows `new pipelines 0` or `1` with tens of milliseconds, and the `pipelines up to frame` line shows that time under `predictions`, with a hundred or more `archive lookups found` at about 1 ms each and as many `pulling pipelines made`, against one or two `draws with a hybrid pipeline`. Ocarina of Time's castle town: one prediction made 160 stand-ins in 104 ms, three predictions 244 in 191 ms. → [Pulling stand-ins made for predicted keys that are never drawn](../reference/frame-rate.md#pulling-stand-ins-made-for-predicted-keys-that-are-never-drawn) - while an area's pipelines are still being built and many draws use a pulling stand-in, the submit thread spends 1 ms or more a frame in predictions: the `pipelines up to frame` line shows thousands of `predictions` per 300 frames, against tens of thousands of `draws with a hybrid pipeline`, while `builds admitted` stays low. → [Predictions replayed every submission of an area's stand-in warm-up](../reference/frame-rate.md#predictions-replayed-every-submission-of-an-areas-stand-in-warm-up) +- on a first visit, single frames of 0.3–2 s while the pipeline archive holds the area's pulling bases. The `pipelines up to frame` line shows one to eight `draws that waited: pulling base not made yet` with hundreds of milliseconds each, few `draws with a hybrid pipeline`, and its background lookups finding every base they looked for (`base lookups handed to the background 21 (found 21)`). Ocarina of Time on an iPhone 17, entering Kakariko Village and Hyrule Castle: 1 / 861 ms, 2 / 1,081 ms, 8 / 1,786 ms in one 300-frame window each, against 1 / 95 ms on the build without the background lookups. → [A draw that came during another thread's archive lookup compiled its base](../reference/frame-rate.md#a-draw-that-came-during-another-threads-archive-lookup-compiled-its-base) - frames of 30–150 ms as an area loads, with `new pipelines 0` and a long-frame line such as `texture uploads 31 first + 6 re-uploads, 235.0 MB / 23.7 ms`. With `DM_NVN_REUPLOADS=1` the same large texture is re-uploaded many times within a few frames, several times with the same `submission` number, each for a few written pages (`pages written since its upload: 7 of 2466`). → [A texture written while it is drawn read whole at every use](../reference/frame-rate.md#a-texture-written-while-it-is-drawn-read-whole-at-every-use) - in a `sample` of the queue's thread (`NVN queue replay`), `mtl_sub_commit` has much time of its own and in `gw_put`, though a submission writes few pages. A game that makes many small submissions a frame pays it each time: Ocarina of Time makes about 30. → [A submission's commit read the whole storage-write page set](../reference/frame-rate.md#a-submissions-commit-read-the-whole-storage-write-page-set) - the submit thread spends time in `-[AGXTexture newTextureViewWithPixelFormat:…]` under `tex_by_id` and `img_binding` (a `sample` of the process) in a scene that does not change, and the `texture views by texture (vc_get)` line of the memory report counts views made at about half the rate of views reused, while the number of textures holding views stays flat. Ocarina of Time on the Kokiri Forest deck: 121,284 views made against 454,107 reused by frame 5,700, about 40 a frame. → [Texture views made again for render targets initialized again every frame](../reference/frame-rate.md#texture-views-made-again-for-render-targets-initialized-again-every-frame) diff --git a/docs/reference/frame-rate.md b/docs/reference/frame-rate.md index 46c4f9e831..b19e112c88 100644 --- a/docs/reference/frame-rate.md +++ b/docs/reference/frame-rate.md @@ -825,6 +825,14 @@ Frame pacing: the host's frame step, engine frame limiters, present intervals an - **Check:** `make -C dm/gfx/tests GAME= check_t_pso_pending` (the trigger: a stand-in draw whose build is under way starts nothing, the first new miss starts the submission's one prediction) and `check_t_pso_depth_stencil` (with a stand-in for a draw's key the prediction hands over only its attachment-free variant; fails without the fix). Ocarina of Time v131072, village arrival from `save_ref`, frames 5,100–8,100, M6 Mac, instrumented hosts, two runs a side, against the host before: predictions 12,706 / 5,564 → 269 / 312, their time 3.77 / 2.76 s → 0.65 / 0.75 s (what is left is the first sight of new keys), builds admitted 84 / 85 → 71 / 87, draws that waited 347 / 343 → 352 / 367, submit CPU 7.89 / 7.97 → 5.69 / 6.18 ms a frame. The stand-in check alone: predictions as before, none of the stand-in keys' time. - **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md#frame-rate), reported with measurements by a contributor ([issue #2438](https://github.com/seedds/nxnative/issues/2438): the market's warm-up, 1.0–1.5 ms a frame of submit CPU in the prediction after a stand-in draw, which their runs showed admitting nothing; the runs here show it admitting builds, so it is kept at new misses rather than left out). +### A draw that came during another thread's archive lookup compiled its base + +- **Symptom:** on a first visit, single frames of 0.3–2 s while the pipeline archive holds the area's pulling bases. The `pipelines up to frame` line shows one to eight `draws that waited: pulling base not made yet` with hundreds of milliseconds each, few `draws with a hybrid pipeline`, and its background lookups finding every base they looked for (`base lookups handed to the background 21 (found 21)`). Ocarina of Time on an iPhone 17, entering Kakariko Village and Hyrule Castle: 1 / 861 ms, 2 / 1,081 ms, 8 / 1,786 ms in one 300-frame window each, against 1 / 95 ms on the build without the background lookups. +- **Cause:** a call of `pso_build_ex` that does not compile (`compile` 0: a draw asking whether its base or its pulling base is made or archived, a prewarm task) returned nil at once when another thread held that base's job in `g_pbase_pending`, so that it would never wait for the Metal compiler. But a job's owner first only looks in the archives, which takes milliseconds, and a non-compiling owner does nothing else. A draw that came during such a lookup of its pulling base therefore found no stand-in. Its own base was already known missing, so the draw then compiled it on the submit thread: about a second on the phone. The background lookups of the prediction (`pso_bg_look`) make this race happen every time: they look up the bases of the draws that come next in the same submission, a few milliseconds before those draws. +- **Fix:** general, in the host (`nvn_mtl.m`, `pso_build_ex`, `PbaseBuild.looked`): the owner of a base's job leaves a second group, `looked`, once it has looked in the archives (or skipped them for a base known missing), with the base it found in `found`. It leaves the group before the compaction's capture and before any compile. A non-compiling call that finds another thread's job waits on `looked` and takes `found`. If the lookup found nothing it returns nil as before, without waiting for the compile. The wait is one archive lookup at most. +- **Check:** `make -C dm/gfx/tests GAME= check_t_pso_look_wait`: a non-compiling call during another thread's 200 ms lookup takes the base the lookup found and compiles nothing (fails without the fix: it returned nil at once); during a lookup that finds nothing, followed by a 2 s compile, it returns nil after the lookup, not after the compile; a non-compiling owner still marks a missing base. +- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md#frame-rate), the owner's play of 2026-11-14 on an iPhone 17 (builds with the prediction's background lookups: 2 fps in Hyrule Castle). + ### A texture written while it is drawn read whole at every use - **Symptom:** frames of 30–150 ms as an area loads, with `new pipelines 0` and a long-frame line such as `texture uploads 31 first + 6 re-uploads, 235.0 MB / 23.7 ms`. With `DM_NVN_REUPLOADS=1` the same large texture is re-uploaded many times within a few frames, several times with the same `submission` number, each for a few written pages (`pages written since its upload: 7 of 2466`).