Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
OoT-30 C-4: a submission copies its command lists without the submiss…
…ion lock, so the game's thread no longer waits for the queue replay of the one before

Item C-4 asked whether the game's main thread (200-400 ms/s of CPU in the owner's slow windows, 2-4 ms of yields a frame) waits on the host. It does: a `sample` on the Mac (the owner's save, Temple of Time) has the main thread 16.5% in __psynch_mutexwait, 12.4% inside nvn_queue_submit -> pthread_mutex_lock. A submission copied its command lists (nq_flatten) under g_sub_mu, which the queue replay thread holds for the whole translation of each submission (nq_worker), so with 22-30 submissions a frame the game's thread waited for each one the replay had in hand; on an iPhone, with 11-24 ms of replay a frame in busy scenes, the frame was the main thread's work plus the replay's. The rest of the main thread's time is its own: guest code and its waits on the game's own workers (the yields; ModuleSystemWorker).

The copy needed the lock only for the first submission's prepare step and for a program no replay had resolved (prog_get is the replay's), and the program pins it shared with the replay had no lock of their own.
- nvn_queue_submit: no submission lock for the copy; the prepare step runs under it once (mtl_prepared).
- nq_snapshot_object: a program the serial table holds is pinned and copied without it (mtl_prog_snapshot_live, own_prog_pin_live); only one not resolved yet takes the lock to be resolved, as before.
- nvn_owner.m: the program pins have a lock of their own (g_pin_mu), taken before g_smu wherever both are held.

Tests: check_t_queue_lifetime 43 x2 (a submission whose program is resolved returns while the lock is held, and draws; an unresolved program is left to the lock: new, fails before), t_gfx_suspend 20 (updated deliberately: both submissions now return while the prepare step holds the lock instead of the second waiting for it; nothing commits before the resume, as before), t_nvn 325, t_serial_owner 176, check_t_alias_takeover 48, test_docs.
Docs: frame-rate.md "The game's submissions waited for the queue replay's lock", nvn-objects.md (the prepare-step entry's check), symptom index, game note.
(cherry picked from commit f923323)

Rebased onto main b633687, where submission streaming (5588e99, PR #2996)
already copies a streamed submission without the submission lock, pins its
programs by serial without resolving them (mtl_prog_snapshot_pin) and gives
the program pins their own lock (g_prog_pin_lk). What C-4 still changes:
nvn_queue_submit no longer takes the lock at the start of a streamed
submission once the prepare step is done (mtl_prepared), so the game's thread
no longer waits there for the node the replay has in hand; mtl_sub_stream_on
sets its switch up once (pthread_once), as its first read may now come
without the lock. Dropped as superseded: mtl_prog_snapshot_live,
own_prog_pin_live and g_pin_mu (nvn_owner.h and nvn_owner.m are main's).
The whole-submission path (DM_NVN_SUB_STREAM=0, frame capture) keeps main's
locking. t_queue_lifetime's case runs when streaming is on and no longer
checks the dropped function; the frame-rate.md entry says what streaming
already did.
  • Loading branch information
seedds authored and stan69b committed Nov 24, 2026
commit 9cc710ea8d02f93c0bf2b784bc4c3536e281c7a3
1 change: 1 addition & 0 deletions dm/games/0400486024DEC000/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,7 @@ Its 37 kernels that correct samples, NDSR's network among them, gave about 0.25
- [Predicted keys' bases looked up on the submit thread](../../../docs/reference/frame-rate.md#predicted-keys-bases-looked-up-on-the-submit-thread): resolved in host tests; iPhone testing was waived for landing, with the phone performance benefit unverified. The earlier iPhone play spent up to 3.5 s per 300 frames in predictions on first visits to Hyrule Field and Castle Town (batch OoT-30, C-3).
- [A draw that came during another thread's archive lookup compiled its base](../../../docs/reference/frame-rate.md#a-draw-that-came-during-another-threads-archive-lookup-compiled-its-base): resolved in the host's lookup-wait fixture; iPhone testing with corrected background lookups was waived for landing ([PR #2770](https://github.com/seedds/nxnative/pull/2770), [PR #2677](https://github.com/seedds/nxnative/pull/2677)), with the phone performance benefit unverified. The earlier stacked build had 0.3–1.8-second draw waits on an iPhone 17; the Mac measurements do not establish a significant gain.
- [A storage takeover looked at a spared entry once per 64 KB cell](../../../docs/reference/frame-rate.md#a-storage-takeover-looked-at-a-spared-entry-once-per-64-kb-cell): resolved; 6% of the submit thread's busy time on a Mac in the Temple of Time (batch OoT-30, C-1).
- [The game's submissions waited for the queue replay's lock](../../../docs/reference/frame-rate.md#the-games-submissions-waited-for-the-queue-replays-lock): resolved; the main thread waited in `nvnQueueSubmitCommands` for the replay of the submission before (batch OoT-30, C-4).
- [A texture written while it is drawn read whole at every use](../../../docs/reference/frame-rate.md#a-texture-written-while-it-is-drawn-read-whole-at-every-use): resolved, frames of 31–59 ms on entering Hyrule Castle Town, a 1800x1380x8 R16 array (38.5 MB) and three block-compressed textures re-uploaded 31–52 times while the loader wrote them, the array 16–17 times whole; 16–17 re-uploads after, the array's 7–9 at 4.7–14.2 MB, one frame of 25 ms at most.
- [A pipeline a hybrid draw stood in for listed only once built](../../../docs/reference/shaders.md#a-pipeline-a-hybrid-draw-stood-in-for-listed-only-once-built): on an iPhone 18 Pro Max, found by HookLink, the pipelines Castle Town asked for last were not in `pso_user.tsv` for the next start; they are listed when first asked for (`DM_PSO_DEMAND_RECORD=0` restores the old order). Synthetic hybrid-lookup tests now cover pending compilation, canonical persistence/reload, completion deduplication and recording limits; the iPhone timing claim is not locally reproduced.
- [One Pro Controller read as two players](../../../docs/reference/services.md#one-pro-controller-read-as-two-players): resolved, no music in Kokiri Forest gameplay and its cutscenes; the controller applet opened over and over and the game kept its music suspended while it had focus.
Expand Down
11 changes: 7 additions & 4 deletions dm/gfx/nvn/nvn_mtl.m
Original file line number Diff line number Diff line change
Expand Up @@ -1997,6 +1997,7 @@ void mtl_prepare(void) {
guest_clock_freeze_for(3, 0);
}
}
int mtl_prepared(void) { return __atomic_load_n(&g_warm_started, __ATOMIC_ACQUIRE) || !prepare_on(); }
static void sub_cut_begin(void); static void ts_sub_begin(void), ts_boundary(void); static int ts_on(void);
static void tu_tick(void);
static void gmem_commit_patch(void); // the raw pool table words of the arguments encoded so far follow the pools (gmem_slot_note)
Expand Down Expand Up @@ -8475,11 +8476,13 @@ static uint8_t prog_stage_mask(const prog_t *p) {
if (ser) smc[h] = (smc_ent){ser, gen, m};
return m;
}
// The submit thread reads the switch under g_sub_mu and latches it for the job.
// The submit thread reads the switch once per submission and latches it for the job. A streamed submission takes no submission lock once the prepare step is done
// (nvn_queue.inc nvn_queue_submit), so the switch is set up once, whichever thread submits first
static int g_sub_stream_mode;
static void sub_stream_init(void) { g_sub_stream_mode = getenv("DM_NVN_CAPTURE") ? 0 : sw_mode("DM_NVN_SUB_STREAM", 1); }
int mtl_sub_stream_on(void) {
static int mode = -1;
if (mode < 0) mode = getenv("DM_NVN_CAPTURE") ? 0 : sw_mode("DM_NVN_SUB_STREAM", 1);
return sw_on(mode);
static pthread_once_t once = PTHREAD_ONCE_INIT; pthread_once(&once, sub_stream_init);
return sw_on(g_sub_stream_mode);
}
// A submitted descriptor and a queue binding pin the program by its serial (own_prog_pin; mtl_prog_release and mtl_prog_unpin are nvn_owner.m's)
// Replay can resolve a program from the owned serial and shader keys.
Expand Down
1 change: 1 addition & 0 deletions dm/gfx/nvn/nvn_obj.h
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,7 @@ void mtl_prog_unpin(prog_t *p); // submit lock held: release a queued descriptor
int mtl_sub_stream_on(void);
void mtl_prog_snapshot_pin(prog_t *copy, const prog_t *source); // retain the serial without resolving the program on the submit thread
void mtl_prog_snapshot(prog_t *copy, const prog_t *source); // submit lock held: retain compiled shaders behind owned metadata
int mtl_prepared(void); // the first submission's prepare step (mtl_prepare) has nothing left to do
void mtl_prog_prefetch(const prog_t *p); // loads a new program's shader libraries in the background (nvn_mtl.m)
void mtl_prog_forget(const prog_t *p); // program finalize, submit lock held: drop it from every queue's bindings
// New serial (> 0, globally increasing)
Expand Down
18 changes: 13 additions & 5 deletions dm/gfx/nvn/nvn_queue.inc
Original file line number Diff line number Diff line change
Expand Up @@ -330,13 +330,21 @@ static void nq_enqueue(nq_queue *q,nq_job *j) { if(q->last) q->last->next=j; els
void nvn_queue_submit(queue_t *q,int count,const uint64_t *handles) {
pthread_once(&nq_once,nq_start); nq_job *j=calloc(1,sizeof *j); if(!j) die("queue job allocation failed"); j->receipt=nq_new();
j->objects.klen=16; j->frame=dm_nvn_frame_count(); j->submitted=guest_ns();
// No scheduler lock while copying descriptors or resolving shader libraries.
dm_host_mutex_lock(&g_sub_mu); void *pool=objc_autoreleasePoolPush(); dm_host_work++; mtl_prepare(); dm_host_work--; nq_cost cost=nq_cost_begin();
int stream=mtl_sub_stream_on();
// No scheduler lock while copying descriptors or resolving shader libraries. A streamed submission takes no submission lock either once the first submission's prepare
// step is done: the queue replay thread holds it for the whole translation of each node (nq_worker), and the game's thread, which took it only to queue the job, waited
// for each one the replay had in hand. Ocarina of Time submits 22-30 times a frame: its main thread spent 16% of its time in that wait on a Mac (12% inside this
// function), and on an iPhone, where the replay took 11-24 ms a frame, the frame was the main thread's work plus the replay's instead of the longer of the two
// (OoT-30 C-4). Nothing of the copy needs the lock: a streamed job pins its programs by serial without resolving them (nq_snapshot_object), the pins have their own
// locks, and the job is queued in order under nq_mu. The whole-submission path (DM_NVN_SUB_STREAM=0, frame capture) still copies under the lock
int stream=mtl_sub_stream_on(), locked=!stream || !mtl_prepared();
if(locked) dm_host_mutex_lock(&g_sub_mu);
void *pool=objc_autoreleasePoolPush();
if(locked) { dm_host_work++; mtl_prepare(); dm_host_work--; }
nq_cost cost=nq_cost_begin();
if(stream) {
j->open=1;
pthread_mutex_lock(&nq_mu); nq_enqueue(nq_get(q),j); pthread_mutex_unlock(&nq_mu);
pthread_mutex_unlock(&g_sub_mu);
if(locked) { pthread_mutex_unlock(&g_sub_mu); locked=0; }
}
for(int i=0;i<count;i++) nq_flatten(j,(const uint8_t *)(uintptr_t)handles[i]); nq_end(j);
nq_cost_end(cost); objc_autoreleasePoolPop(pool);
Expand All @@ -345,7 +353,7 @@ void nvn_queue_submit(queue_t *q,int count,const uint64_t *handles) {
if(stream) { j->open=0; pthread_cond_broadcast(&nq_cv); }
else nq_enqueue(nq_get(q),j);
pthread_mutex_unlock(&nq_mu);
if(!stream) pthread_mutex_unlock(&g_sub_mu);
if(locked) pthread_mutex_unlock(&g_sub_mu);
}
// The window retains this logical receipt until it reacquires or finalizes that image.
// Only replay turns it into a physical display ticket; present never waits on the guest thread.
Expand Down
10 changes: 5 additions & 5 deletions dm/gfx/tests/t_gfx_suspend.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// CPU-only lifecycle regression: the real NVN submit entry and graphics gate, with the prepare step (mtl_prepare) held by semaphores and the Metal replay and drain stubbed.
// Going to the background while the first submission prepares must not wait for it, and a second submission queued behind it must not hold the suspend either (docs/reference/nvn-objects.md,
// "Going to the background during the prepare step")
// "Going to the background during the prepare step"). A streamed submission copies its command list without the submit lock (nvn_queue.inc nvn_queue_submit): both return while the prepare step
// holds it, and neither is in-flight graphics work until the replay runs them after the resume
#include <pthread.h>
#include <stdatomic.h>
#include <dispatch/dispatch.h>
Expand Down Expand Up @@ -116,9 +117,9 @@ int main(void) {
CHECK("the prepare step runs outside the graphics gate", inflight_in_prepare == 0);
CHECK("the prepare step is host work for the guest scheduler", host_work_in_prepare > 0);
pthread_create(&second, NULL, submit, (void *)1);
if (!reached(second_waiting, "a second submission waits for the submit lock")) return 1;
CHECK("a queued submission is not in-flight graphics work", inflight_at_serial_wait == 0);
CHECK("a contended submit lock is host work for the guest scheduler", host_work_at_serial_wait > 0);
if (!reached(returned, "a submission returns while the prepare step holds the submit lock") || !reached(returned, "a second submission returns as well")) return 1;
CHECK("a queued submission is not in-flight graphics work", g_inflight_api == 0);
(void)second_waiting; (void)inflight_at_serial_wait; (void)host_work_at_serial_wait; // the contended-lock hook (observed_mutex_lock): no submission takes the lock now
if (failures) return 1; // the suspend below would wait forever
pthread_create(&background, NULL, suspend_graphics, NULL);
if (!reached(suspended, "suspend completes while the prepare step holds the submit lock")) return 1;
Expand All @@ -131,7 +132,6 @@ int main(void) {
CHECK("queued work stays outside the GPU while suspended", dispatch_semaphore_wait(committed, dispatch_time(DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC)) != 0);
CHECK("no submission commits while graphics are suspended", atomic_load(&commits) == 0);
dm_gfx_suspend(0);
if (!reached(returned, "a submission returns after resume") || !reached(returned, "both submissions return after resume")) return 1;
pthread_join(first, NULL); pthread_join(second, NULL);
if (!reached(committed, "first queued submission commits after resume") || !reached(committed, "second queued submission commits after resume")) return 1;
CHECK("both submissions commit", atomic_load(&commits) == 2);
Expand Down
15 changes: 15 additions & 0 deletions dm/gfx/tests/t_queue_lifetime.m
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,21 @@ int main(void) { @autoreleasepool {
CHECK(pixels(0, 0, 0, 255), "an ordinary upload still reads the live buffer in command order");
}

if (mtl_sub_stream_on()) { // The queue replay thread holds the submission lock for the whole translation of each node: the game's next streamed submit queues its job
// and copies its command list without waiting for it (nvn_queue.inc nvn_queue_submit, OoT-30 C-4).
puts("CASE a submission while the replay holds the submission lock");
NVNcommandHandle h = record(&target, &stable_red, 0, 1, 0); memset(memory + OUTPUT, 0x5a, BYTES);
dispatch_semaphore_t s = dispatch_semaphore_create(0);
pthread_mutex_lock(&g_sub_mu);
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ P(nvnQueueSubmitCommands)(&queues[0], 1, &h); dispatch_semaphore_signal(s); });
long blocked = dispatch_semaphore_wait(s, dispatch_time(DISPATCH_TIME_NOW, 2000000000ll));
pthread_mutex_unlock(&g_sub_mu);
if (blocked) dispatch_semaphore_wait(s, DISPATCH_TIME_FOREVER);
CHECK(!blocked, "a streamed submission does not wait for the submission lock");
P(nvnSyncInitialize)(&sync, &device); P(nvnQueueFenceSync)(&queues[0], &sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0); finish(&sync);
CHECK(pixels(0, 255, 0, 0), "and draws with that program once the replay runs it");
}

P(nvnQueueFinish)(&queues[0]); P(nvnQueueFinish)(&queues[1]);
P(nvnProgramFinalize)(&reused); P(nvnProgramFinalize)(&stable_red); P(nvnProgramFinalize)(&stable_green);
P(nvnTextureFinalize)(&target); P(nvnTextureFinalize)(&replacement); P(nvnCommandBufferFinalize)(&command);
Expand Down
1 change: 1 addition & 0 deletions docs/agents/symptoms.md
Original file line number Diff line number Diff line change
Expand Up @@ -790,6 +790,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- the acquire thread's declared computation is too low for a frame acquired in several calls (a third or half of the frame's CPU time), or, after the game acquires from another thread, the new thread gets no policy of its own, its computation is inflated to the cap, or the old thread keeps the frame's deadline. → [A time-constraint computation sampled per acquire or across acquire threads](../reference/frame-rate.md#a-time-constraint-computation-sampled-per-acquire-or-across-acquire-threads)
- a freeze of tens of seconds as one `[longframe]` (`whole frame 51828.5 ms, submit+present 11.5 ms`) with the GPU idle. The 300-frame window that holds it shows a low share on performance cores (`13% of it on performance cores`), the main thread holding the CPU, and `real-time policy in effect`. → [A lone acquire thread kept its time-constraint policy through a long CPU burst](../reference/frame-rate.md#a-lone-acquire-thread-kept-its-time-constraint-policy-through-a-long-cpu-burst)
- a `sample` of the queue replay thread shows `own_alias_publish` → `alias_take_over` → `nvn_hm_get` and `memcmp` under the passes' first draws (`draw_` → `rt_dims` → `tex_mtl_at`): 3% of the thread's samples, 6% of its busy time, in a scene where the game makes its render targets again as new texture objects. → [A storage takeover looked at a spared entry once per 64 KB cell](../reference/frame-rate.md#a-storage-takeover-looked-at-a-spared-entry-once-per-64-kb-cell)
- the game's thread that submits (the main thread in Ocarina of Time) spends much of its time in `nvnQueueSubmitCommands` while the queue replay thread translates: a `sample` shows it in `nvn_queue_submit` → `pthread_mutex_lock` (12% of the main thread on a Mac, 16% in mutex waits), and on an iPhone, where the replay takes 11-24 ms a frame in busy scenes, frames take about the main thread's work plus the replay's instead of the longer of the two. → [The game's submissions waited for the queue replay's lock](../reference/frame-rate.md#the-games-submissions-waited-for-the-queue-replays-lock)
- a movie or full-screen compute pass far slower than the same work should be, nearly all of it GPU time: `GPU p50` near the frame time with `submit+present` under 1 ms. `[RED] raw global memory: a write log ran out of slots` on older chains. With `DM_NVN_GPUPROF` a relaxed timestamp can put the time before the compute encoder's reported start, so the encoder itself looks short and the gap before it is what is long. → [A shader that writes a whole frame through raw global memory](../reference/frame-rate.md#a-shader-that-writes-a-whole-frame-through-raw-global-memory)
- a game with dynamic resolution stays at its full size while the GPU runs far over budget: `GPU p50` above the frame time target, frame times locked to 2 vsyncs, and the same pass sizes frame after frame in `DM_NVN_GPUPROF`. → [Dynamic resolution that never moves, and draw passes that wait for each other](../reference/frame-rate.md#dynamic-resolution-that-never-moves-and-draw-passes-that-wait-for-each-other)
- a game with `draw_barriers game` gets no benefit from it: the 300-frame log line `draw-pass entry barriers full N / saved 0`, every draw pass behind a full barrier, and in a Metal System Trace many small idle gaps between consecutive render encoders of one command buffer (Ocarina of Time on an M1 Max: 141 a frame, 2.3 ms in all). → [Draw passes that wait for each other again while images share memory](../reference/frame-rate.md#draw-passes-that-wait-for-each-other-again-while-images-share-memory)
Expand Down
8 changes: 8 additions & 0 deletions docs/reference/frame-rate.md
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,14 @@ Frame pacing: the host's frame step, engine frame limiters, present intervals an
- **Found on:** [Ocarina of Time](../../dm/games/0400486024DEC000/README.md#found-on-this-game), Mac, the owner's save in the Temple of Time (batch OoT-30, item C-1).
- **Check:** `make -C dm/gfx/tests GAME=<id> check_t_alias_takeover`: a spared entry that lies in every cell of the new texture is looked at once (fails before the fix).

### The game's submissions waited for the queue replay's lock

- **Symptom:** the game's thread that submits (the main thread in Ocarina of Time) spends much of its time in `nvnQueueSubmitCommands` while the queue replay thread translates: a `sample` shows it in `nvn_queue_submit` → `pthread_mutex_lock` (12% of the main thread on a Mac, 16% in mutex waits), and on an iPhone, where the replay takes 11-24 ms a frame in busy scenes, frames take about the main thread's work plus the replay's instead of the longer of the two.
- **Cause:** the queue replay thread holds the submission lock `g_sub_mu` for the whole translation of each node (`nq_worker`: `mtl_exec`, `mtl_sub_commit`). A submission copied its command lists into a queue job (`nq_flatten`: the records, snapshots of the programs and textures they name) under that lock; since submission streaming ([A submission copied whole before its first commands could start](#a-submission-copied-whole-before-its-first-commands-could-start)) a streamed submission copies without it, but still took it at the start to run the prepare step and queue its open job. Either way, with 22-30 submissions a frame the game's thread waited for each node the replay had in hand.
- **Fix:** general, in the host (`nvn_queue.inc` `nvn_queue_submit`): a streamed submission takes the submission lock only until the first submission's prepare step is done (`mtl_prepared`). Nothing else of it needs the lock: it queues its open job under `nq_mu`, pins its programs by serial without resolving them (`mtl_prog_snapshot_pin`; the replay resolves them) and its textures under the pins' own locks. The stream switch is set up once (`mtl_sub_stream_on`, `pthread_once`), as its first read may now come without the lock. `DM_NVN_SUB_STREAM=0` and frame capture still copy the whole submission under the lock.
- **Found on:** [Ocarina of Time](../../dm/games/0400486024DEC000/README.md#found-on-this-game), Mac (`sample` of the owner's save in the Temple of Time, before submission streaming; batch OoT-30, item C-4); the owner's iPhone play showed the main thread at 200-400 ms/s of CPU and frames of 50-60 ms with 16-20 ms of GPU in Castle Town. Open: a CPU-limited comparison against main with streaming.
- **Check:** `make -C dm/gfx/tests GAME=<id> check_t_queue_lifetime`: with the submission lock held (a replay mid-translation), a streamed submission returns, and draws with its program once the replay runs (fails before the fix). `t_gfx_suspend`: both submissions return while the prepare step holds the lock.

### A shader that writes a whole frame through raw global memory

- **Symptom:** a movie or full-screen compute pass far slower than the same work should be, nearly all of it GPU time: `GPU p50` near the frame time with `submit+present` under 1 ms. `[RED] raw global memory: a write log ran out of slots` on older chains. With `DM_NVN_GPUPROF` a relaxed timestamp can put the time before the compute encoder's reported start, so the encoder itself looks short and the gap before it is what is long.
Expand Down
Loading