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
51 changes: 42 additions & 9 deletions dm/gfx/nvn/hle_nvn.c
Original file line number Diff line number Diff line change
Expand Up @@ -2119,7 +2119,7 @@ _Static_assert(DM_QUIT_ARCH_MS == MTL_QUIT_ARCH_MS, "a graceful exit gives the p
// comes before the gate: a second submission waiting for it must not count as in flight, or the suspend waits for it while the first waits to enter the closed gate holding the lock
static void sleep_until_ns(uint64_t dl);
static void nvn_acq_ref(uint64_t handle);
static uint64_t nvn_acq_unref_take_ticket(uint64_t handle);
static uint64_t nvn_acq_unref_take_ticket(uint64_t handle, uint64_t *next);
static void nvn_acq_snapshot(uint64_t handle, uint64_t *gpu_fence, uint64_t *ticket);
#include "nvn_queue.inc"
NVN(nvnQueueSubmitCommands, void, NVNqueue *q, int n, const NVNcommandHandle *h) {
Expand Down Expand Up @@ -2259,6 +2259,7 @@ struct acq_wait {
uint64_t avail; // snapshotted o->avail[*idx] at acquire time
uint64_t ticket; // snapshotted o->ticket[*idx] at acquire time (owned until completed, finalized, or freed)
uint64_t gpu_fence; // mtl_last_fence() at acquire time
uint64_t next; // ticket (a reference of its own) of the present after this image's last one: Horizon hands the image back once that one is on screen (acq_next_ticket)
unsigned refs; // held by win->pending_acq, sync_t (fenced == 4), and active waiters
int paced; // 1 once pacing (link / sleep / screen / detclock / snap) has completed
int done; // 0 = pending, 1 = wait in progress, 2 = completed or abandoned
Expand All @@ -2280,12 +2281,13 @@ static void nvn_acq_ref(uint64_t handle) {
aw->refs++;
pthread_mutex_unlock(&acq_mu);
}
static uint64_t nvn_acq_unref_take_ticket(uint64_t handle) {
static uint64_t nvn_acq_unref_take_ticket(uint64_t handle, uint64_t *next) {
*next = 0;
if (!handle) return 0;
acq_wait_t *aw = (acq_wait_t *)(uintptr_t)handle;
uint64_t tk = 0;
pthread_mutex_lock(&acq_mu);
if (!--aw->refs) { tk = aw->ticket; free(aw); }
if (!--aw->refs) { tk = aw->ticket; *next = aw->next; free(aw); }
pthread_mutex_unlock(&acq_mu);
return tk;
}
Expand All @@ -2298,8 +2300,9 @@ static void nvn_acq_snapshot(uint64_t handle, uint64_t *gpu_fence, uint64_t *tic
pthread_mutex_unlock(&acq_mu);
}
static void acq_wait_unref(acq_wait_t *aw) {
uint64_t tk = nvn_acq_unref_take_ticket((uintptr_t)aw);
uint64_t nx, tk = nvn_acq_unref_take_ticket((uintptr_t)aw, &nx);
if (tk) nvn_queue_present_release(tk);
if (nx) nvn_queue_present_release(nx);
}
static int acq_pace_ready(const win_t *o, uint64_t at) {
if (!dm_detclock_enabled()) {
Expand Down Expand Up @@ -2415,10 +2418,11 @@ static int acq_wait_run(acq_wait_t *aw, uint64_t timeout_ns, int *waited, uint64

if (!o) {
pthread_mutex_lock(&acq_mu);
uint64_t drop = aw->ticket; aw->ticket = 0; aw->done = 2;
uint64_t drop = aw->ticket, dnx = aw->next; aw->ticket = 0; aw->next = 0; aw->done = 2;
pthread_cond_broadcast(&acq_cv);
pthread_mutex_unlock(&acq_mu);
if (drop) nvn_queue_present_release(drop);
if (dnx) nvn_queue_present_release(dnx);
return 1;
}
if (!timeout_ns && ((!paced && !acq_pace_ready(o, at)) || (tk && !nvn_queue_present_ready(tk)))) {
Expand Down Expand Up @@ -2446,16 +2450,39 @@ static int acq_wait_run(acq_wait_t *aw, uint64_t timeout_ns, int *waited, uint64
ok = nvn_queue_present_wait_timeout(tk, rem);
if (ok) atomic_fetch_add(&g_pq_wait_ns, now_ns() - w0);
}
pthread_mutex_lock(&acq_mu); uint64_t nx = aw->next; pthread_mutex_unlock(&acq_mu);
if (ok && nx) {
if (!nvn_queue_present_ready(nx)) *waited = 1;
uint64_t rem = timeout_ns == UINT64_MAX ? UINT64_MAX : !timeout_ns ? 0 : now_ns() >= deadline ? 0 : deadline - now_ns();
uint64_t w0 = now_ns();
ok = nvn_queue_present_gpu_wait_timeout(nx, rem);
if (ok) atomic_fetch_add(&g_pq_wait_ns, now_ns() - w0);
}

uint64_t release_tk = 0;
uint64_t release_tk = 0, release_nx = 0;
pthread_mutex_lock(&acq_mu);
if (ok) { release_tk = aw->ticket; aw->ticket = 0; aw->win = NULL; aw->done = 2; }
if (ok) { release_tk = aw->ticket; aw->ticket = 0; release_nx = aw->next; aw->next = 0; aw->win = NULL; aw->done = 2; }
else aw->done = 0;
pthread_cond_broadcast(&acq_cv);
pthread_mutex_unlock(&acq_mu);
if (release_tk) nvn_queue_present_release(release_tk);
if (release_nx) nvn_queue_present_release(release_nx);
return ok;
}
// The present after image idx's most recent one, with a reference of its own (0: none yet). Horizon gives an image back once the compositor has taken the next present
// in its place, so the GPU has finished that later frame: games pace their CPU-written per-frame data by the acquire's sync alone. Xenoblade Chronicles: Definitive Edition's
// Switch 2 Edition (two images) waits only on that sync and writes the constants of frame N + 1 into the slot frame N - 1 read; given back when its own present's copy had
// run (frame N - 2), the image let the game overwrite them while the GPU still drew frame N - 1, and its exposure and fog read the next frame's values (NaN frames in the intro).
// Lock order nq_mu -> acq_mu (the receipt's count is the queue's)
static uint64_t acq_next_ticket(win_t *o, int idx) {
uint64_t t = 0;
if (idx < 0 || idx >= 4) return 0;
pthread_mutex_lock(&nq_mu); pthread_mutex_lock(&acq_mu);
if (o->pseq[idx]) for (int i = 0; i < 4; i++) if (i != idx && o->pseq[i] == o->pseq[idx] + 1 && o->ticket[i]) { t = o->ticket[i]; nvn_queue_present_ref_locked(t); break; }
pthread_mutex_unlock(&acq_mu); pthread_mutex_unlock(&nq_mu);
return t;
}
static int acq_next_on(void) { static int on = -1; if (on < 0) { const char *e = getenv("DM_NVN_ACQ_NEXT"); on = !e || atoi(e) != 0; if (!on) LOG("DM_NVN_ACQ_NEXT=0: an acquired image is handed back once its own present has run, as before"); } return on; }
NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsync *s, int *idx) {
win_t *o = (win_t *)w;
if (o->offscreen) { // nothing shows its frames, so nothing holds a texture: free once the commands before this point are done
Expand Down Expand Up @@ -2483,10 +2510,12 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
if (*idx >= 0 && *idx < 4) { at = o->avail[*idx]; tk = o->ticket[*idx]; o->ticket[*idx] = 0; }
pthread_mutex_unlock(&acq_mu);

uint64_t nx = acq_next_on() ? acq_next_ticket(o, *idx) : 0;
if (!s) {
int dummy = 0;
acq_pace_do(o, at, UINT64_MAX, UINT64_MAX, &dummy);
if (tk) { uint64_t w0 = now_ns(); nvn_queue_present_wait(tk); nvn_queue_present_release(tk); atomic_fetch_add(&g_pq_wait_ns, now_ns() - w0); }
if (nx) { uint64_t w0 = now_ns(); nvn_queue_present_gpu_wait_timeout(nx, UINT64_MAX); nvn_queue_present_release(nx); atomic_fetch_add(&g_pq_wait_ns, now_ns() - w0); }
return NVN_WINDOW_ACQUIRE_TEXTURE_RESULT_SUCCESS;
}

Expand All @@ -2495,6 +2524,7 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
aw->win = o;
aw->avail = at;
aw->ticket = tk;
aw->next = nx;
aw->gpu_fence = mtl_last_fence();
aw->refs = 2; // 1 for win->pending_acq, 1 for sync_t
pthread_mutex_lock(&acq_mu);
Expand All @@ -2506,14 +2536,15 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
// The older API (NVN 53, Super Mario 3D World + Bowser's Fury): the queue waits for the texture on the GPU and no sync object is handed out. The host replays in submission order, so later commands already come after earlier presents; the same as WindowAcquireTexture without a sync object
NVN(nvnWindowFinalize, void, NVNwindow *w) {
win_t *o = (win_t *)w;
uint64_t drop[5] = {0}; int nd = 0;
uint64_t drop[6] = {0}; int nd = 0;
pthread_mutex_lock(&acq_mu);
acq_wait_t *aw = (acq_wait_t *)o->pending_acq;
if (aw) {
while (aw->done == 1) pthread_cond_wait(&acq_cv, &acq_mu);
if (aw->done == 0) {
aw->done = 2; aw->win = NULL;
if (aw->ticket) { drop[nd++] = aw->ticket; aw->ticket = 0; }
if (aw->next) { drop[nd++] = aw->next; aw->next = 0; }
pthread_cond_broadcast(&acq_cv);
}
o->pending_acq = NULL;
Expand Down Expand Up @@ -3366,8 +3397,10 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
const tex_t *t = CTX(o->tex[idx]); int lc[4]; const int *crop = present_crop(o->crop, (int)t->d.width, (int)t->d.height, lc);
uint64_t new_tk = nvn_queue_present((queue_t *)q, t, present_period(o) / 1e9, crop);
pthread_mutex_lock(&acq_mu);
uint64_t old_tk = o->ticket[idx];
uint64_t old_tk = o->ticket[idx], last = 0;
o->ticket[idx] = new_tk;
for (int i = 0; i < 4; i++) if (o->pseq[i] > last) last = o->pseq[i];
o->pseq[idx] = last + 1;
pthread_mutex_unlock(&acq_mu);
if (old_tk) nvn_queue_present_release(old_tk);
}
Expand Down
2 changes: 1 addition & 1 deletion dm/gfx/nvn/nvn_obj.h
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ typedef struct { uint32_t magic; volatile uint32_t *val; const pool_t *pool; int
typedef struct { NVNdevice *dev; void *native; int32_t ntex, interval; NVNtexture *tex[4]; int32_t nactive; } win_builder_t;
FITS(win_builder_t, NVNwindowBuilder);
// avail[i]: time at which swapchain image i can be acquired again (ns, monotonic clock) = its display time + one present period; pace: target time of this window's present pacer
typedef struct { uint32_t magic; void *native; int32_t ntex, interval, next, crop[4], offscreen; NVNtexture *tex[4]; uint64_t presents, avail[4], pace, ticket[4]; int32_t nactive, follow; void *pending_acq; } win_t; // ticket[i]: ticket of the most recent present of image i; nactive as in win_builder_t; follow: see nvn_pace_follow; pending_acq: deferred acquire wait not yet consumed
typedef struct { uint32_t magic; void *native; int32_t ntex, interval, next, crop[4], offscreen; NVNtexture *tex[4]; uint64_t presents, avail[4], pace, ticket[4]; int32_t nactive, follow; void *pending_acq; uint64_t pseq[4]; } win_t; // pseq[i]: order of image i's most recent present (1 = the first); ticket[i]: ticket of the most recent present of image i; nactive as in win_builder_t; follow: see nvn_pace_follow; pending_acq: deferred acquire wait not yet consumed
FITS(win_t, NVNwindow);

// Command buffer: commands are written into the command memory given by the game (AddCommandMemory), and the list that strings a recording's pieces together into its control memory
Expand Down
12 changes: 11 additions & 1 deletion dm/gfx/nvn/nvn_queue.inc
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ static nq_receipt *nq_new(void) { nq_receipt *r=calloc(1,sizeof *r); if(!r) die(
static void nq_put(nq_receipt *r) { if(r && !--r->refs) free(r); }
static void nq_release_sync_locked(sync_t *s) {
if (s->fenced == 3) nq_put((nq_receipt *)(uintptr_t)s->fence);
else if (s->fenced == 4) { uint64_t tk = nvn_acq_unref_take_ticket(s->fence); if (tk) nq_put((nq_receipt *)(uintptr_t)tk); }
else if (s->fenced == 4) { uint64_t nx, tk = nvn_acq_unref_take_ticket(s->fence, &nx); if (tk) nq_put((nq_receipt *)(uintptr_t)tk); if (nx) nq_put((nq_receipt *)(uintptr_t)nx); }
s->fenced = 0; s->fence = 0;
}
static void nq_set_sync(sync_t *s,nq_receipt *r) { nq_release_sync_locked(s); r->refs++; s->fence=(uintptr_t)r; s->fenced=3; }
Expand Down Expand Up @@ -383,6 +383,16 @@ uint64_t nvn_queue_present(queue_t *q,const tex_t *t,double period,const int cro
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); }
int nvn_queue_present_wait_timeout(uint64_t ticket, uint64_t timeout_ns);
void nvn_queue_present_ref_locked(uint64_t ticket) { if(ticket) ((nq_receipt *)(uintptr_t)ticket)->refs++; }
// A present's GPU work done: its job replayed (the receipt published) and the GPU past the fence it ended at. Every submission before the present is in that fence
int nvn_queue_present_gpu_wait_timeout(uint64_t ticket, uint64_t timeout_ns) {
if(!ticket) return 1; nq_receipt *r=(nq_receipt *)(uintptr_t)ticket; uint64_t start=now_ns();
if(!nvn_queue_present_wait_timeout(ticket,timeout_ns)) return 0;
pthread_mutex_lock(&nq_mu); uint64_t f=r->fence; pthread_mutex_unlock(&nq_mu);
uint64_t el=now_ns()-start, rem=timeout_ns==UINT64_MAX?UINT64_MAX:el>=timeout_ns?0:timeout_ns-el;
return !f || mtl_wait_acq(f,rem);
}
void nvn_queue_present_release(uint64_t ticket) {
if(!ticket) return; pthread_mutex_lock(&nq_mu); nq_put((nq_receipt *)(uintptr_t)ticket); pthread_mutex_unlock(&nq_mu);
}
Expand Down
24 changes: 24 additions & 0 deletions dm/gfx/tests/t_nvn.c
Original file line number Diff line number Diff line change
Expand Up @@ -1456,6 +1456,30 @@ int main(void) {
P(nvnEventSignal)(&ev, NVN_EVENT_SIGNAL_MODE_WRITE, 1);
P(nvnQueueFinish)(&q);

// An image comes back once the present after its last one has run (hle_nvn.c acq_next_ticket): with two images, acquiring A again waits for B's present, which the
// queue holds behind an unsignaled event. Before, A came back when its own earlier present had run, and Xenoblade Chronicles: Definitive Edition overwrote the
// constants of the frame the GPU was still drawing
{
ev_mem[0] = 0;
int ia = -1, ib = -1, ic = -1;
P(nvnWindowAcquireTexture)(&win, &s_acq, &ia); P(nvnSyncWait)(&s_acq, UINT64_MAX);
P(nvnQueuePresentTexture)(&q, &win, ia);
P(nvnWindowAcquireTexture)(&win, &s_acq, &ib); P(nvnSyncWait)(&s_acq, UINT64_MAX);
P(nvnCommandBufferBeginRecording)(&cb);
P(nvnCommandBufferWaitEvent)(&cb, &ev, NVN_EVENT_WAIT_MODE_EQUAL, 1);
NVNcommandHandle h_hold = P(nvnCommandBufferEndRecording)(&cb);
P(nvnQueueSubmitCommands)(&q, 1, &h_hold);
P(nvnQueuePresentTexture)(&q, &win, ib);
P(nvnWindowAcquireTexture)(&win, &s_acq, &ic);
EXPECT("the image presented before the held one comes back next", ia, ic);
EXPECT("its acquire waits for the held present after it (timeout)", NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED, P(nvnSyncWait)(&s_acq, 300000000ull));
P(nvnEventSignal)(&ev, NVN_EVENT_SIGNAL_MODE_WRITE, 1);
NVNsyncWaitResult r_next = P(nvnSyncWait)(&s_acq, 5000000000ull);
EXPECT("once the held present has run, the acquire is signaled", 1, r_next == NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED || r_next == NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED);
P(nvnQueuePresentTexture)(&q, &win, ic);
P(nvnQueueFinish)(&q);
}

// QueueWaitSync without CPU SyncWait, drained by next acquire
int qidx0 = -1, qidx1 = -1;
P(nvnWindowAcquireTexture)(&win, &s_acq, &qidx0);
Expand Down
1 change: 1 addition & 0 deletions docs/agents/symptoms.md
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- `DM_PRESENT_LINK=1` and `DM_PRESENT_LINK=2` both select the 30 Hz link at a 30 fps target in variable-refresh fullscreen. → [An explicit display link is ignored at 30 fps](../reference/frame-rate.md#an-explicit-display-link-is-ignored-at-30-fps)
- input lag of one frame more than the display link needs, from the first late frame on and for the rest of the run: the `display link up to tick` line's `game enqueue to target display p50` sits one link tick above its value before the hiccup (60 fps in a window: 65.4 ms, then 82.0 ms; a 30 fps cap in a window: 115.4 ms from the first 300 frames on), with no dropped and no empty ticks. → [A frame standing in the present queue after a late frame](../reference/frame-rate.md#a-frame-standing-in-the-present-queue-after-a-late-frame)
- a game with its own dynamic present-interval controller (such as `sead::GameFrameworkNx`) locks at 30 fps (`the game sets present interval 1 → 2`) after a single slow frame and never returns to 60 fps even when the scene takes much less than 16.7 ms. → [Blocking inside nvnWindowAcquireTexture inflates a game's measured CPU frame time](../reference/frame-rate.md#blocking-inside-nvnwindowacquiretexture-inflates-a-games-measured-cpu-frame-time)
- whole frames of one flat colour (blue, purple) with the subtitles drawn over them, horizontal streaks, and a correct frame only now and then, worse where the GPU frame is long. `DM_NVN_MAGSCAN` finds NaN in the scene targets and the 1x1 exposure texture; with `DM_NVN_PRESENT_FINISH=1` there is none. → [An acquired image comes back once the present after it has run](../reference/frame-rate.md#an-acquired-image-comes-back-once-the-present-after-it-has-run)
- autorelease work takes a measurable share of replay time, with temporary arena-buffer ownership traffic a few times per draw. → [Arena buffer ownership on allocation](../reference/frame-rate.md#arena-buffer-ownership-on-allocation)
- a game runs at about 10 fps with little GPU work: the submit thread waits for a command allocator (`mtl_sub_begin` → `mtl_wait_at`), the GPU sits idle between encoders for hundreds of ms (`DM_NVN_GPUPROF`), the Metal 4 `SubmissionQueue` thread spends nearly all its time in `iokit_user_client_trap` (almost all system time), and the `memory up to frame` line shows a residency set of 10,000 objects or more. → [Dedicated c1 constants as slices of a bank](../reference/frame-rate.md#dedicated-c1-constants-as-slices-of-a-bank)
- the submit thread waits for the GPU at the start of a submission (`mtl_sub_begin` → `mtl_wait_at`), many times a frame, in a game that makes many small submissions a frame; the `translation detail` line's `GPU waits so far` climbs with all 8 allocator pools in use. → [One command allocator for each of a frame's submissions](../reference/frame-rate.md#one-command-allocator-for-each-of-a-frames-submissions)
Expand Down
1 change: 1 addition & 0 deletions docs/env_switches.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ DM_NICK switch The account nickname the game sees (default `Player`)
DM_NRO switch `0` turns off loading of the NRO modules the game's NRR files register (on by default): every `nn::ro::LoadModule` then fails
DM_NRO_CAPTURE diagnostic folder: a `nn::ro::LoadModule` with no rewritten copy writes the image to `<folder>/<SHA-256>.nro` and ends the run (the NSP script's capture of an NRO the game decodes at run time)
DM_NRO_DIR path folder of NROs the shader split reads like `main`, and in which it finds a CRA archive's file table (the NSP script sets it for a captured NRO)
DM_NVN_ACQ_NEXT switch `0` gives an acquired window image back once its own last present has run, as before; by default only once the present after it has run too, as Horizon does (`hle_nvn.c` `acq_next_ticket`)
DM_NVN_ALLOCPROF diagnostic `=1` charges Metal allocation growth to each replayed op type and function, and logs command allocator sizes and each new texture (serial, size, format, storage); `=2` also gives each main submission a fresh command allocator and reports command memory by operation, by encoder, by submission size and the indirect-count multi-draws encoded
DM_NVN_ANISO player `=<2..16>`: a floor on the anisotropy of NVN surface texture samplers (linear filter with mips; not nearest, comparison, min / max reduction or single-LOD samplers), keeping any higher game value; `0` or unset leaves the game's own value as on the console (`nvn_aniso.h`). Mac NVN launcher setting
DM_NVN_API switch `=<major>.<minor>` overrides the NVN API version `nvnDeviceGetInteger` reports (by default decided by the SDK version or the profile's `device_api`: 55.15 for SDK 11 and later, 53.313 before)
Expand Down
Loading
Loading