Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
nvn/queue: replay completed nodes while the submit thread copies the …
…rest

Keep an open job at the head of its queue until its producer closes it. Publish sync snapshots at each boundary and retain program serials and texture descriptors until replay is done. Exercise the gap between prefix and suffix with a blocked producer and a second submission.
  • Loading branch information
seedds authored and atinseau committed Nov 19, 2026
commit d9bfca4e3a1c70d2aa12d86da8d90f75e24b9a5f
1 change: 1 addition & 0 deletions dm/games/0400C3F00006E000/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ Mac regression on the M4 Pro with macOS 27.2.1 and Xcode 27.2, 2026-11-19. Both

- [The split shader tables differ from a game profile's](../../../docs/reference/packing.md#the-split-shader-tables-differ-from-a-game-profiles).
- [Relative thread waits can hold back the replay clock](../../../docs/reference/threads.md#relative-thread-waits-can-hold-back-the-replay-clock): v0 stalled at frame 2 in `SleepThread` ([PR #2027](https://github.com/seedds/nxnative/pull/2027)). On 1.8.0 the main thread at `main+0x8ec38` waited indefinitely in `WaitForAddress` while a BaseProcExecutor worker was in `SleepThread` waiting for the replay clock. In the 60 s Mac smoke (Apple M6, macOS 27.2, Xcode 27.2, `DM_DETCLOCK=16666667 DM_DETCLOCK_PACE=1`), main `4b92e232` stalled at frame 20 and the fix reached frame 875. The candidate's frame median over seconds 55–60 was 17.55 ms. The clock-off main control reached the same texture CPU-fallback warning, and resident memory at frame 600 was 7,918 MB on that control and 7,735 MB on the candidate.
- [Submission streaming](../../../docs/reference/frame-rate.md#a-submission-copied-whole-before-its-first-commands-could-start) lets replay start at the first event wait while the game thread copies the rest of the race submission.
- [Pipeline look-ahead must leave future attachments unresolved](../../../docs/reference/shaders.md#pipeline-look-ahead-must-leave-future-attachments-unresolved): the direct Metal startup crash.
- [Cached dirty-range lookups with overlapping pools](../../../docs/reference/nvn-objects.md#cached-dirty-range-lookups-with-overlapping-pools): sparse-texture lookup locality motivated the cache; overlapping-pool missed writes are reproduced by CPU fixtures, not attributed to a particular gameplay image.
- [GPU timestamps per submission segment](../../../docs/reference/frame-rate.md#gpu-timestamps-per-submission-segment): dynamic resolution never stepped down with one time per submission; with the GPU's idle gaps counted it swung and distant detail flickered
Expand Down
15 changes: 13 additions & 2 deletions dm/gfx/nvn/nvn_mtl.m
Original file line number Diff line number Diff line change
Expand Up @@ -7132,12 +7132,23 @@ static void draw_gs_check(NvProg *pr) {
if (p->serial) serial_put(p->serial, o);
return o;
}
// The submit thread reads the switch under g_sub_mu and latches it for the job.
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);
}
// 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)
void mtl_prog_snapshot(prog_t *copy,const prog_t *source) {
prog_get(source); *copy=*source;
// Replay can resolve a program from the owned serial and shader keys.
void mtl_prog_snapshot_pin(prog_t *copy,const prog_t *source) {
*copy=*source;
if(!source->serial) MDIE("cannot retain a program without an initialization serial");
own_prog_pin(source->serial);
}
void mtl_prog_snapshot(prog_t *copy,const prog_t *source) {
prog_get(source);
mtl_prog_snapshot_pin(copy,source);
}

// ---------- Descriptor pool: texture ID / sampler ID → object ----------
// At registration the whole texture object is snapshotted (NVN semantics: the descriptor has been written into the pool); view: the MTLTexture for that ID (a view or the base texture, held via CFBridgingRetain) and the serial-table / guest-write generations at the time it was obtained
Expand Down
2 changes: 2 additions & 0 deletions dm/gfx/nvn/nvn_obj.h
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,8 @@ void nvn_ctl_lens(const void *control, uint32_t *nctl, uint32_t *ncode); // a
void mtl_reg_samp(int id, const samp_par *p);
void mtl_prog_release(prog_t *p);
void mtl_prog_unpin(prog_t *p); // submit lock held: release a queued descriptor or saved binding
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
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
Expand Down
19 changes: 16 additions & 3 deletions dm/gfx/nvn/nvn_owner.m
Original file line number Diff line number Diff line change
Expand Up @@ -558,20 +558,33 @@ own_dead_stats own_alias_dead_locked(uint32_t now, uint32_t idle, own_use_fn use
// A submitted descriptor and a queue binding hold the compiled program by its immutable initialization serial. Retaining it must not mint serial aliases:
// alias churn invalidates texture tables and changes composite-program keys
typedef struct { unsigned refs, retired; } prog_pin;
static nvn_hmap g_prog_pins = {.klen = 8}; // protected by the submission lock
// The pins have a lock of their own: a streamed submission pins on the game's thread without the submission lock (nvn_queue.inc). Release and unpin still run under the
// submission lock, which serial_del needs; they decide under the pin lock and drop the serial after it
static nvn_hmap g_prog_pins = {.klen = 8};
static os_unfair_lock g_prog_pin_lk = OS_UNFAIR_LOCK_INIT;
void mtl_prog_release(prog_t *p) {
if (!p->serial) return;
os_unfair_lock_lock(&g_prog_pin_lk);
prog_pin *pin = nvn_hm_get(&g_prog_pins, &p->serial);
if (pin) pin->retired = 1; else serial_del(p->serial);
if (pin) pin->retired = 1;
os_unfair_lock_unlock(&g_prog_pin_lk);
if (!pin) serial_del(p->serial);
}
void mtl_prog_unpin(prog_t *p) {
os_unfair_lock_lock(&g_prog_pin_lk);
prog_pin *pin = nvn_hm_get(&g_prog_pins, &p->serial);
if (pin && !--pin->refs) { nvn_hm_del(&g_prog_pins, &p->serial); if (pin->retired) serial_del(p->serial); free(pin); }
if (!pin || --pin->refs) { os_unfair_lock_unlock(&g_prog_pin_lk); return; }
nvn_hm_del(&g_prog_pins, &p->serial);
os_unfair_lock_unlock(&g_prog_pin_lk);
if (pin->retired) serial_del(p->serial);
free(pin);
}
void own_prog_pin(uint64_t serial) {
os_unfair_lock_lock(&g_prog_pin_lk);
prog_pin *pin = nvn_hm_get(&g_prog_pins, &serial);
if (!pin) { pin = calloc(1, sizeof *pin); if (!pin) ODIE("program retention allocation failed"); nvn_hm_put(&g_prog_pins, &serial, pin); }
pin->refs++;
os_unfair_lock_unlock(&g_prog_pin_lk);
}

own_alias_unheld own_alias_unheld_locked(void) {
Expand Down
75 changes: 58 additions & 17 deletions dm/gfx/nvn/nvn_queue.inc
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ typedef struct nq_node {
tex_t texture; double period; int crop[4];
} nq_node;
typedef struct nq_owned { struct nq_owned *next; unsigned kind; uint64_t data[]; } nq_owned;
typedef struct nq_job { struct nq_job *next; nq_node *first, *last; nq_receipt *receipt; nq_owned *owned; nvn_hmap objects; uint64_t frame, submitted; } nq_job; // submitted: guest ns of its nvnQueueSubmitCommands (mtl_sub_ready)
// An empty open job stays at the head of its queue until more nodes arrive.
typedef struct nq_job { struct nq_job *next; nq_node *first, *last; nq_receipt *receipt; nq_owned *owned; nvn_hmap objects; uint64_t frame, submitted;
nq_node *staged_first, *staged_last; int open, waits; } nq_job;
static void nq_job_free(nq_job *j) {
for(nq_owned *o=j->owned,*next;o;o=next) { next=o->next; if(o->kind==CAP_K_PROG) mtl_prog_unpin((prog_t *)o->data); else if(o->kind==CAP_K_TEX) mtl_tex_unpin(((tex_t *)o->data)->serial); free(o); }
free(j->objects.keys); free(j->objects.vals); free(j);
Expand All @@ -29,8 +31,12 @@ static int nq_snapshot_object(void *ctx,int kind,uint64_t *field,uint8_t *payloa
if(!o) {
size_t bytes=kind==CAP_K_PROG?sizeof(prog_t):sizeof(tex_t); o=calloc(1,sizeof *o+bytes); if(!o) die("queue descriptor allocation failed");
o->kind=kind; o->next=j->owned; j->owned=o;
if(kind==CAP_K_PROG) mtl_prog_snapshot((prog_t *)o->data,(const prog_t *)(uintptr_t)*field);
else { memcpy(o->data,(const void *)(uintptr_t)*field,bytes); mtl_tex_pin(((tex_t *)o->data)->serial); }
if(kind==CAP_K_PROG) {
prog_t *copy=(prog_t *)o->data;
const prog_t *source=(const prog_t *)(uintptr_t)*field;
if(j->open) mtl_prog_snapshot_pin(copy,source);
else mtl_prog_snapshot(copy,source);
} else { memcpy(o->data,(const void *)(uintptr_t)*field,bytes); mtl_tex_pin(((tex_t *)o->data)->serial); }
nvn_hm_put(&j->objects,key,o);
}
*field=(uintptr_t)o->data;return 1;
Expand Down Expand Up @@ -133,6 +139,7 @@ static void *nq_worker(void *unused) {
int mapped_event_wait=0;
for(q=nq_queues;q;q=q->next) {
j=q->first; if(!j) continue; n=j->first;
if(!n && j->open) continue; // a streamed submission still being copied: its next node is not published yet
if(!n) { nq_publish(j->receipt,q->physical); q->first=j->next; if(!q->first) q->last=NULL; nq_put(j->receipt);
pthread_mutex_unlock(&nq_mu); pthread_mutex_lock(&g_sub_mu); void *pool=objc_autoreleasePoolPush(); nq_job_free(j); objc_autoreleasePoolPop(pool); pthread_mutex_unlock(&g_sub_mu); pthread_mutex_lock(&nq_mu); goto scan_again; }
if(n->kind==NQ_EVENT && n->event) {
Expand Down Expand Up @@ -199,7 +206,29 @@ static void *nq_worker(void *unused) {
return NULL;
}
static void nq_start(void) { pthread_t t; if(pthread_create(&t,NULL,nq_worker,NULL)) die("NVN queue worker failed"); pthread_detach(t); }
static nq_node *nq_append(nq_job *j,unsigned kind) { nq_node *n=calloc(1,sizeof *n); if(!n) die("queue continuation allocation failed"); n->kind=kind; if(j->last) j->last->next=n; else j->first=n; j->last=n; return n; }
// Only the producer touches the staged list. The worker takes nodes from first / last.
static nq_node *nq_append(nq_job *j,unsigned kind) {
nq_node *n=calloc(1,sizeof *n); if(!n) die("queue continuation allocation failed");
n->kind=kind;
if(j->staged_last) j->staged_last->next=n; else j->staged_first=n;
j->staged_last=n;
j->waits|=kind==NQ_EVENT || kind==NQ_SYNC;
return n;
}
// Under nq_mu at a wait/fence boundary or at end of input: snapshot the syncs in
// command order before the worker can take any of these completed nodes.
static void nq_publish_staged(nq_job *j) {
if(!j->staged_first) return;
for(nq_node *n=j->staged_first;n;n=n->next) {
if(!n->sync_source) continue;
if(n->kind==NQ_FENCE) nq_set_sync((sync_t *)n->sync_source,n->receipt);
else nq_snapshot_sync(n,n->sync_source);
n->sync_source=NULL;
}
if(j->last) j->last->next=j->staged_first; else j->first=j->staged_first;
j->last=j->staged_last;
j->staged_first=j->staged_last=NULL;
}
// Grow geometrically so flattening a large submission does not reallocate its command records at every page.
static void nq_bytes(nq_node *n, const void *bytes, size_t length) {
if (length > SIZE_MAX - n->length) die("queue commands allocation overflow");
Expand All @@ -220,7 +249,7 @@ static void nq_signal_add(nq_node *n,nq_signal s) {
if(!(n->signal_count&(n->signal_count-1))) { n->signals=realloc(n->signals,(n->signal_count?2*n->signal_count:1)*sizeof *n->signals); if(!n->signals) die("queue signals allocation failed"); } // NOLINT(bugprone-suspicious-realloc-usage): allocation failure aborts
n->signals[n->signal_count++]=s;
}
static void nq_end(nq_job *j) { if(j->last && j->last->kind==NQ_COMMANDS && !j->last->closed) { op_hdr end={OP_END,8}; nq_bytes(j->last,&end,8); j->last->closed=1; } }
static void nq_end(nq_job *j) { if(j->staged_last && j->staged_last->kind==NQ_COMMANDS && !j->staged_last->closed) { op_hdr end={OP_END,8}; nq_bytes(j->staged_last,&end,8); j->staged_last->closed=1; } }
// One record of a recording, copied into the job (its object pointers snapshotted); waits and fences cut the job. A signal does not: its value is published when the commands
// it is among complete (mtl_sub_event), and a wait on it is ordered by that value or, while it is in flight, by the fence of those commands (nq_event_write), so the node keeps
// every signal it records. Each node is a Metal command buffer of its own, so a cut ends the open render pass: BioShock Infinite signals an event per occlusion query, and a cut
Expand All @@ -232,8 +261,14 @@ static void nq_record_one(nq_job *j,const uint8_t *p,op_hdr h) {
nq_end(j); nq_node *n=nq_append(j,h.op==OP_WAIT_EVENT?NQ_EVENT:h.op==OP_WAIT_SYNC?NQ_SYNC:NQ_FENCE);
if(h.op==OP_WAIT_EVENT) { memcpy(&n->event,a,8); memcpy(&n->mode,a+8,4); memcpy(&n->value,a+12,4); }
else { memcpy(&n->sync_source,a,8); if(h.op==OP_FENCE_SYNC) n->receipt=nq_new(); }
if(j->open) {
pthread_mutex_lock(&nq_mu);
nq_publish_staged(j);
pthread_cond_broadcast(&nq_cv);
pthread_mutex_unlock(&nq_mu);
}
} else {
nq_node *n=j->last; if(!n || n->kind!=NQ_COMMANDS || n->closed) n=nq_append(j,NQ_COMMANDS);
nq_node *n=j->staged_last; if(!n || n->kind!=NQ_COMMANDS || n->closed) n=nq_append(j,NQ_COMMANDS);
size_t offset=n->length; nq_bytes(n,p,h.size); if(!n->bytes) die("queue commands: a record of %u bytes",h.size);
if(h.op==OP_AS_BUILD) {
if(h.size<8+sizeof(p_as_build))die("invalid acceleration-structure command size");
Expand Down Expand Up @@ -265,21 +300,27 @@ static void nq_flatten(nq_job *j,const uint8_t *list) {
}
}
static void nq_enqueue(nq_queue *q,nq_job *j) { if(q->last) q->last->next=j; else q->first=j; q->last=j; nq_put(q->tail); q->tail=j->receipt; q->tail->refs++; pthread_cond_broadcast(&nq_cv); }
// Publish the job before copying so the worker can replay closed nodes while
// the game thread still owns the recording and copies its remaining commands.
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();
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); pthread_mutex_unlock(&g_sub_mu);
int waits=0; for(nq_node *node=j->first;node;node=node->next) waits|=node->kind==NQ_EVENT || node->kind==NQ_SYNC;
nvn_cap_queue(q->serial,waits);
pthread_mutex_lock(&nq_mu);
for(nq_node *node=j->first;node;node=node->next) if(node->sync_source) {
if(node->kind==NQ_FENCE) nq_set_sync((sync_t *)node->sync_source,node->receipt); else nq_snapshot_sync(node,node->sync_source);
node->sync_source=NULL;
int stream=mtl_sub_stream_on();
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);
}
nq_enqueue(nq_get(q),j); pthread_mutex_unlock(&nq_mu);
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);
nvn_cap_queue(q->serial,j->waits);
pthread_mutex_lock(&nq_mu); nq_publish_staged(j);
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);
}
// 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 All @@ -289,7 +330,7 @@ uint64_t nvn_queue_present(queue_t *q,const tex_t *t,double period,const int cro
j->receipt=nq_new(); j->frame=dm_nvn_frame_count(); { void mtl_present_recorded(uint64_t); mtl_present_recorded(j->frame); } // the game's own present count, for the screen wait (nvn_mtl.m)
nq_node *n=nq_append(j,NQ_PRESENT);
n->texture=*t; mtl_tex_pin(t->serial); n->period=period; if(crop) memcpy(n->crop,crop,sizeof n->crop);
pthread_mutex_lock(&nq_mu); j->receipt->refs++; uint64_t ticket=(uintptr_t)j->receipt;
pthread_mutex_lock(&nq_mu); nq_publish_staged(j); j->receipt->refs++; uint64_t ticket=(uintptr_t)j->receipt;
nq_enqueue(nq_get(q),j); pthread_mutex_unlock(&nq_mu); return ticket;
}
void nvn_queue_test_hold(int on) { pthread_mutex_lock(&nq_mu); nq_test_held=on; pthread_cond_broadcast(&nq_cv); pthread_mutex_unlock(&nq_mu); }
Expand Down Expand Up @@ -319,7 +360,7 @@ int nvn_sync_wait(const sync_t *s,uint64_t timeout) {
void nvn_queue_wait_sync(queue_t *q,const sync_t *s) {
nvn_cap_queue(q->serial,1);
pthread_once(&nq_once,nq_start); nq_job *j=calloc(1,sizeof *j); if(!j) die("queue wait allocation failed"); j->receipt=nq_new();
pthread_mutex_lock(&nq_mu); nq_snapshot_sync(nq_append(j,NQ_SYNC),s); nq_enqueue(nq_get(q),j); pthread_mutex_unlock(&nq_mu);
pthread_mutex_lock(&nq_mu); nq_snapshot_sync(nq_append(j,NQ_SYNC),s); nq_publish_staged(j); nq_enqueue(nq_get(q),j); pthread_mutex_unlock(&nq_mu);
}
void nvn_queue_finish(queue_t *q) { sync_t s={0}; nvn_queue_fence(q,&s); nvn_sync_wait(&s,UINT64_MAX); nvn_sync_release(&s);
pthread_mutex_lock(&nq_mu); nq_queue *p=nq_get(q); uint64_t present=p->present, copy=p->copy; pthread_mutex_unlock(&nq_mu);
Expand Down
Loading
Loading