Skip to content
Open
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
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
64 changes: 64 additions & 0 deletions dm/gfx/nvn/hle_nvn.c
Original file line number Diff line number Diff line change
Expand Up @@ -2602,7 +2602,71 @@ static void power_line(uint64_t frame) {
else { char yt[192], rs[400], tc[400]; dm_yield_top(yt, sizeof yt); mtl_res_stats(rs, sizeof rs); dm_thread_cpu(tc, sizeof tc, 1); } // the first call only takes the baselines
pt = t; pe = e; pcpu = cpu; pp = p; piw = iw; ppw = idw; pg = g; pf = frame; mtl_bw(&pld, &pst, &pfu); pudc = mtl_udc_saved_bytes();
}
// DM_PCSAMPLE=<name>[,<name>...][:<µs>[:<seconds>[:<first frame>]]] (diagnostic, every platform): a host thread samples the threads whose pthread name contains one of the names
// every <µs> (1000) for <seconds> (60) from frame <first frame> (900) on: each one found running is suspended, its pc, lr and up to 10 frame-pointer frames read, and resumed.
// The samples go to pcsample.txt in the working folder (the app's Documents on iOS, beside log.txt), one line each, "<name index> <pc> <lr> <frames...>" in hex, after a header
// with this image's load address, so `atos -o <the binary> -l <address>` names them on the Mac. It is how the submit thread's CPU per draw was profiled on an iPhone, where neither
// `sample` nor a debugger may attach (OoT-30 C-1). A suspend and resume cost the sampled thread some microseconds: at 1000 µs about 1% of its time
#include <dlfcn.h>
static char g_pcs_names[8][48]; static int g_pcs_n;
static void *pcs_main(void *arg) {
(void)arg; pthread_setname_np("dm-pcsample");
const char *e = getenv("DM_PCSAMPLE"); char spec[512]; snprintf(spec, sizeof spec, "%s", e);
long us = 1000, secs = 60, first = 900; char *c = strchr(spec, ':');
if (c) { *c++ = 0; us = atol(c); char *c2 = strchr(c, ':'); if (c2) { secs = atol(c2 + 1); char *c3 = strchr(c2 + 1, ':'); if (c3) first = atol(c3 + 1); } }
if (us < 100) us = 100;
for (char *t = strtok(spec, ","); t && g_pcs_n < 8; t = strtok(NULL, ",")) snprintf(g_pcs_names[g_pcs_n++], sizeof g_pcs_names[0], "%s", t);
while (atomic_load_explicit(&g_frame, memory_order_relaxed) < (uint64_t)first) usleep(100000);
FILE *f = fopen("pcsample.txt", "w"); if (!f) { LOG("[RED] DM_PCSAMPLE: cannot write pcsample.txt"); return NULL; }
Dl_info di = {0}; dladdr((void *)pcs_main, &di);
fprintf(f, "# DM_PCSAMPLE image %s load address %#llx; interval %ld us from frame %llu; names", di.dli_fname ? di.dli_fname : "?", (unsigned long long)(uintptr_t)di.dli_fbase, us, (unsigned long long)atomic_load(&g_frame));
for (int i = 0; i < g_pcs_n; i++) fprintf(f, " %d=%s", i, g_pcs_names[i]);
fputc('\n', f);
for (int i = 0; i < g_nmod; i++) fprintf(f, "# guest module %s %#llx %#llx\n", g_mod[i].name, (unsigned long long)(uintptr_t)g_mod[i].base, (unsigned long long)g_mod[i].text_end); // the game's code: base and text length
enum { PT = 16 }; thread_act_t port[PT]; int who[PT], np = 0; uint64_t t0 = clock_gettime_nsec_np(CLOCK_UPTIME_RAW), tl = 0, taken = 0, idle = 0;
mach_port_t self = mach_thread_self();
for (;;) {
uint64_t now = clock_gettime_nsec_np(CLOCK_UPTIME_RAW);
if (now - t0 > (uint64_t)secs * 1000000000ull) break;
if (now - tl > 1000000000ull) { // the threads, again every second (a named thread may start late)
for (int i = 0; i < np; i++) mach_port_deallocate(mach_task_self(), port[i]);
np = 0; tl = now; thread_act_array_t ths; mach_msg_type_number_t nth = 0;
if (task_threads(mach_task_self(), &ths, &nth) == KERN_SUCCESS) {
for (mach_msg_type_number_t i = 0; i < nth; i++) {
int w = -1; pthread_t pt = ths[i] != self ? pthread_from_mach_thread_np(ths[i]) : NULL; char nm[64] = "";
if (pt && !pthread_getname_np(pt, nm, sizeof nm)) for (int k = 0; k < g_pcs_n && w < 0; k++) if (strstr(nm, g_pcs_names[k])) w = k;
if (w >= 0 && np < PT) { port[np] = ths[i]; who[np++] = w; } else mach_port_deallocate(mach_task_self(), ths[i]);
}
vm_deallocate(mach_task_self(), (vm_address_t)ths, nth * sizeof *ths);
}
}
for (int i = 0; i < np; i++) {
thread_basic_info_data_t bi; mach_msg_type_number_t bc = THREAD_BASIC_INFO_COUNT;
if (thread_info(port[i], THREAD_BASIC_INFO, (thread_info_t)&bi, &bc) != KERN_SUCCESS || bi.run_state != TH_STATE_RUNNING) { idle++; continue; }
if (thread_suspend(port[i]) != KERN_SUCCESS) continue;
arm_thread_state64_t st; mach_msg_type_number_t n = ARM_THREAD_STATE64_COUNT; uint64_t fr[12]; int nf = 0;
if (thread_get_state(port[i], ARM_THREAD_STATE64, (thread_state_t)&st, &n) == KERN_SUCCESS) {
fr[nf++] = __darwin_arm_thread_state64_get_pc(st); fr[nf++] = __darwin_arm_thread_state64_get_lr(st);
uint64_t fp = __darwin_arm_thread_state64_get_fp(st), w2[2]; vm_size_t g = 0;
while (nf < 12 && fp && !vm_read_overwrite(mach_task_self(), fp, 16, (vm_address_t)w2, &g) && g == 16 && w2[0] > fp) { fr[nf++] = w2[1]; fp = w2[0]; }
}
thread_resume(port[i]);
if (!nf) continue;
fprintf(f, "%d", who[i]); for (int k = 0; k < nf; k++) fprintf(f, " %llx", (unsigned long long)fr[k]); fputc('\n', f); taken++;
}
usleep((useconds_t)us);
}
for (int i = 0; i < np; i++) mach_port_deallocate(mach_task_self(), port[i]);
mach_port_deallocate(mach_task_self(), self);
fclose(f); LOG("[nvn] DM_PCSAMPLE: %llu samples of running threads (%llu found waiting) written to pcsample.txt", (unsigned long long)taken, (unsigned long long)idle);
return NULL;
}
static void pcs_start(void) {
static int once; const char *e = getenv("DM_PCSAMPLE"); if (once || !e || !*e) return; once = 1;
pthread_t th; if (!pthread_create(&th, NULL, pcs_main, NULL)) { pthread_detach(th); LOG("[nvn] DM_PCSAMPLE=%s: sampling those threads into pcsample.txt", e); }
}
static void tsummary(uint64_t frame) {
pcs_start();
char line[1024]; size_t o = 0;
for (int k = 0; k < 6; k++) {
unsigned n = g_tn[k] < TWIN ? g_tn[k] : TWIN; if (!n) continue;
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
9 changes: 8 additions & 1 deletion dm/gfx/tests/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -922,13 +922,20 @@ t_wait_event: t_wait_event.m $(MTL_T_DEP)
t_queue_lifetime: t_queue_lifetime.m $(MTL_T_DEP)
clang $(CFLAGS) -fobjc-arc -o $@ t_queue_lifetime.m $(filter-out ../nvn/hle_nvn.c,$(MTL_T_SRC)) $(FW)

.PHONY: check_t_wait_event check_t_queue_lifetime
# Under ASan: a streamed submission's descriptor copies run without the submission lock, and a program pinned that way once fell through to the texture copy (a heap overread)
t_queue_lifetime_asan: t_queue_lifetime.m $(MTL_T_DEP)
clang $(CFLAGS) -fsanitize=address,undefined -fno-omit-frame-pointer -fobjc-arc -o $@ t_queue_lifetime.m $(filter-out ../nvn/hle_nvn.c,$(MTL_T_SRC)) $(FW)

.PHONY: check_t_wait_event check_t_queue_lifetime check_t_queue_lifetime_asan
check_t_wait_event: t_wait_event
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=0 ./$<
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 ./$<
check_t_queue_lifetime: t_queue_lifetime
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=0 ./$<
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 ./$<
check_t_queue_lifetime_asan: t_queue_lifetime_asan
ASAN_OPTIONS=halt_on_error=1 UBSAN_OPTIONS=halt_on_error=1 MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=0 ./$<
ASAN_OPTIONS=halt_on_error=1 UBSAN_OPTIONS=halt_on_error=1 MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 ./$<

t_render_enable_queue: t_render_enable_queue.m $(MTL_T_DEP)
clang $(CFLAGS) -fobjc-arc -o $@ t_render_enable_queue.m $(filter-out ../nvn/hle_nvn.c,$(MTL_T_SRC)) $(FW)
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
16 changes: 16 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,22 @@ 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). Its program is pinned by serial, never copied as a texture
// (check_t_queue_lifetime_asan)
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
Loading
Loading