mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-25 06:20:08 -10:00
nvn/dispatch: order compute dispatches by the game's barriers (PR #2250)
Compute dispatches are ordered by the game's own barriers, for every game (PR #2250): dispatch_enc put a barrier before every dispatch in the shared copy encoder, so the GPU ran them one at a time, while NVN makes a dispatch's writes visible to later work only when the game issues nvnCommandBufferBarrier. Now a dispatch (dispatch_enc_cs) gets a barrier when the game issued one since the dispatch before it, or when one of the host's copies meets its ranges in either direction (uniform updates and uploads keep their order; copies are checked against what dispatches wrote and read, g_dw / g_dr); a dispatch with a binding whose reach is no memory range (an image, a buffer texture, a handle in a uniform slot, untraced global memory) and the host's own dispatches keep the full order on both sides. Kirby Air Riders' particle systems, about 230 dispatches a frame that share the buffers they write (91 % meet an earlier one's range, so ranges alone gain nothing): the encoder 6.6-9.8 → 0.4-1.2 ms, GPU p50 over alternating race phases 9.0 → 5.3 ms, the heaviest phase's frame p90 19.36 → 16.75 ms (PR author, M4 Pro, with PR #2254's loop guard). The PR made it a profile key for Kirby; it is the host default here, as the rule is NVN's: DM_NVN_DISPATCH_BARRIER=full brings back the barrier before every dispatch (diagnostic), ab alternates with the DM_AB phases. It replaces PR #1901's dispatch_overlap for Ocarina of Time. Also fixed on top of the PR: a new copy encoder empties the dispatch range sets (ranges from a closed encoder put needless barriers before its copies; t_dispatch_barrier's new case 6 fails without it), and bufsnap's copy is recorded as writing everything, so a later dispatch cannot overwrite what it still reads. The periodic [nvn] line counts dispatches after a game barrier, after a copy's range, in the full order and with none. Reference entry Compute dispatches that wait for each other (frame-rate.md), rendering.md's two dispatch entries point to it, Kirby's note lists it, env switch row, symptom index regenerated. Checked: t_dispatch_barrier in both orders with the encode thread on and off (27 / 31 checks), t_dispatch_own, t_copy_alias, t_tg_spill, t_cpu_tex, test_docs, test_env_switches, test_game_profile, lint_c.py tidy (at the baseline); regress.py check against 8a5c5e7e (M4 Pro): Mario Kart World PASS, 69,367 of about 1.02 M dispatches with no barrier, 59.8 / 60.0 fps, no new red line; OCTOPATH TRAVELER II PASS, but all its dispatches have a rangeless binding and keep the full order. Not run: Kirby Air Riders and Ocarina of Time in this form (no files / no route here), the iPhone
Co-authored-by: FifteenPen <[email protected]>
This commit is contained in:
1 parent
301cf6c9f9
commit
547c5db647
9 files changed
+192
-8
No files matched your search
@@ -37,6 +37,7 @@ Moving objects get their ambient light from eight values per object in a storage
|
||||
|
||||
## Found on this game
|
||||
|
||||
- [Compute dispatches that wait for each other](../../../docs/reference/frame-rate.md#compute-dispatches-that-wait-for-each-other): its particle systems.
|
||||
- [PMAP records in phx's PDAT archives](../../../docs/reference/shaders.md#pmap-records-in-phxs-pdat-archives): its shaders, and a loose NDSR file.
|
||||
- [A guard band cull in every vertex shader (0x80d)](../../../docs/reference/shaders.md#a-guard-band-cull-in-every-vertex-shader-0x80d).
|
||||
- [Ampere forms with a handle in a register](../../../docs/reference/shaders.md#ampere-forms-with-a-handle-in-a-register-and-sureds-other-operations): TMML (0xf69, 0x36a) in 4,776 pixel shaders.
|
||||
|
||||
@@ -1982,6 +1982,10 @@ static void power_line(uint64_t frame) {
|
||||
double nf = frame > pf ? (double)(frame - pf) : 1; // per frame: the fair comparison when one build holds the frame rate better than another
|
||||
LOG("[nvn] power up to frame %llu: CPU energy %.2f W, %.1f mJ per frame (%.1f fps); CPU %.0f%% (100 = one core), %.0f%% of it on performance cores; wakeups %.0f/s (out of platform idle %.0f); GPU %.1f ms/s; thermal %d; top yielders: %s", frame,
|
||||
(e - pe) / 1e9 / s, (e - pe) / 1e6 / nf, nf / s, (cpu - pcpu) / 1e7 / s, cpu > pcpu ? 100.0 * (double)(p - pp) / (double)(cpu - pcpu) : 0, (iw - piw) / s, (idw - ppw) / s, (g - pg) / 1e6 / s, dm_thermal_now(), yt);
|
||||
void mtl_dispatch_barrier_stats(uint64_t *, uint64_t *, uint64_t *, uint64_t *); static uint64_t pdg, pdc, pdu, pdn; uint64_t dg, dc, du, dn; mtl_dispatch_barrier_stats(&dg, &dc, &du, &dn);
|
||||
if (dg + dc + du + dn != pdg + pdc + pdu + pdn) LOG("[nvn] compute dispatches up to frame %llu: %llu after a barrier of the game's, %llu after a copy's range, %llu in the full order (a binding with no range), %llu with no barrier (DM_NVN_DISPATCH_BARRIER)", frame,
|
||||
(unsigned long long)(dg - pdg), (unsigned long long)(dc - pdc), (unsigned long long)(du - pdu), (unsigned long long)(dn - pdn));
|
||||
pdg = dg; pdc = dc; pdu = du; pdn = dn;
|
||||
char rs[400]; mtl_res_stats(rs, sizeof rs); static uint64_t pbs, pbf; uint64_t bs, bf; mtl_barrier_stats(&bs, &bf);
|
||||
uint64_t mtl_cut_count(void), mtl_copy_cut_count(void), mtl_blit_splits(void); void mtl_ubd_stats(uint64_t *, uint64_t *); static uint64_t pcut, pccut, pbsp, pud, puc; uint64_t cut = mtl_cut_count(), ccut = mtl_copy_cut_count(), bsp = mtl_blit_splits(), ud, uc; mtl_ubd_stats(&ud, &uc);
|
||||
void mtl_ubp_stats(uint64_t *, uint64_t *, uint64_t *); static uint64_t ppm, ppr, ppf; uint64_t pm, pr, pf_; mtl_ubp_stats(&pm, &pr, &pf_);
|
||||
|
||||
+64
-6
@@ -1699,11 +1699,13 @@ static void blit_note(void); // Per-pass dump: a copy / buffer update ended th
|
||||
// allocator gave out overlapping blocks, see hle_nvn.c zcull_size; NVN runs copies in order for any game)
|
||||
enum { BW_MAX = 64 };
|
||||
static uint64_t g_bw_lo[BW_MAX], g_bw_hi[BW_MAX], g_br_lo[BW_MAX], g_br_hi[BW_MAX]; static int g_bw_n, g_br_n, g_blit_ops; static uint64_t g_blit_barriers;
|
||||
enum { DW_MAX = 256 };
|
||||
static uint64_t g_dw_lo[DW_MAX], g_dw_hi[DW_MAX], g_dr_lo[DW_MAX], g_dr_hi[DW_MAX]; static int g_dw_n, g_dr_n, g_dsp_game_bar; // what dispatches ordered by the game's barriers wrote and read since the last barrier (dispatch_enc_cs), apart from the copies' sets: copies are ordered after them, dispatches only when the game asked (g_dsp_game_bar). Emptied by every barrier and by a new copy encoder; empty with DM_NVN_DISPATCH_BARRIER=full
|
||||
static uint64_t g_blit_splits; // copies / buffer updates / fills that ended an open draw pass (the residency set line; a pass ended this way stores and the next one reloads its attachments)
|
||||
uint64_t mtl_blit_splits(void) { return g_blit_splits; }
|
||||
static int enc_open(void);
|
||||
static int g_blit_ct; // the open copy encoder has the compute argument table set (dispatches share it, dispatch_enc)
|
||||
static id<MTL4ComputeCommandEncoder> blit_open(void) { if (!g_blit) { ser_gate(); g_blit = enc_b_begin(g_cb); [g_blit barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:blit_vis()]; gp_begin(g_blit, 'C', nil); g_bw_n = g_br_n = 0; g_blit_ops = 0; g_blit_ct = 0; } return g_blit; }
|
||||
static id<MTL4ComputeCommandEncoder> blit_open(void) { if (!g_blit) { ser_gate(); g_blit = enc_b_begin(g_cb); [g_blit barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:blit_vis()]; gp_begin(g_blit, 'C', nil); g_bw_n = g_br_n = g_dw_n = g_dr_n = 0; g_blit_ops = 0; g_blit_ct = 0; } return g_blit; }
|
||||
static void ubd_flush(void); static int g_nubd; // the inline updates deferred (see mtl_sub_update)
|
||||
static int g_ubd_landing;
|
||||
static id<MTL4ComputeCommandEncoder> blit_raw(void) {
|
||||
@@ -1718,11 +1720,13 @@ static void blit_barrier(void) {
|
||||
static int off = -1; if (off < 0) { const char *e = getenv("DM_NVN_BLIT_ORDER"); off = e && !strcmp(e, "0"); if (off) MLOG("DM_NVN_BLIT_ORDER=0: no barriers inside the copy encoder (diagnostic; brings back the fountain's vertical stripes)"); }
|
||||
// Only the stages a compute encoder has: MTLStageAll here fails Metal validation (macOS 27: "must be a valid combination of MTLStages for the current encoder type")
|
||||
if (!off) [g_blit barrierAfterEncoderStages:MTLStageDispatch | MTLStageBlit beforeEncoderStages:MTLStageDispatch | MTLStageBlit visibilityOptions:blit_vis()];
|
||||
g_bw_n = g_br_n = 0; g_blit_ops = 0; g_blit_barriers++;
|
||||
g_bw_n = g_br_n = g_dw_n = g_dr_n = 0; g_blit_ops = 0; g_blit_barriers++;
|
||||
}
|
||||
uint64_t mtl_blit_barriers(void) { return g_blit_barriers; }
|
||||
static int bw_hit(uint64_t lo, uint64_t hi) { for (int i = 0; i < g_bw_n; i++) if (lo < g_bw_hi[i] && g_bw_lo[i] < hi) return 1; return 0; }
|
||||
static int br_hit(uint64_t lo, uint64_t hi) { for (int i = 0; i < g_br_n; i++) if (lo < g_br_hi[i] && g_br_lo[i] < hi) return 1; return 0; }
|
||||
static int dw_hit(uint64_t lo, uint64_t hi) { for (int i = 0; i < g_dw_n; i++) if (lo < g_dw_hi[i] && g_dw_lo[i] < hi) return 1; return 0; }
|
||||
static int dr_hit(uint64_t lo, uint64_t hi) { for (int i = 0; i < g_dr_n; i++) if (lo < g_dr_hi[i] && g_dr_lo[i] < hi) return 1; return 0; }
|
||||
// buffer → buffer / fill: reads [rlo, rhi) (0, 0 when nothing is read), writes [wlo, whi)
|
||||
static uint64_t g_wr_epoch; // Bumped by every buffer write outside a render pass (copy / update / fill, texture → buffer, dispatch): indirect-draw conversions made before it are stale (ixc_run)
|
||||
static uint64_t g_mdx_epoch; // Bumped by GPU writes that can change an indirect-count multi-draw's records or count (copy, fill, texture → buffer, dispatch; see mdx_run)
|
||||
@@ -1756,7 +1760,7 @@ static id<MTL4ComputeCommandEncoder> blit_buf(uint64_t rlo, uint64_t rhi, uint64
|
||||
// their operations with everything before and after. Ordinary pools keep the
|
||||
// range-based batching, including separate Metal buffers over one CPU range.
|
||||
if (nvn_sparse_alias(rlo, rhi) || nvn_sparse_alias(wlo, whi)) { wlo = 0; whi = ~0ull; }
|
||||
if (g_blit_ops && (g_bw_n == BW_MAX || g_br_n == BW_MAX || (rhi > rlo && bw_hit(rlo, rhi)) || bw_hit(wlo, whi) || br_hit(wlo, whi))) blit_barrier();
|
||||
if (g_blit_ops && (g_bw_n == BW_MAX || g_br_n == BW_MAX || (rhi > rlo && (bw_hit(rlo, rhi) || dw_hit(rlo, rhi))) || bw_hit(wlo, whi) || br_hit(wlo, whi) || dw_hit(wlo, whi) || dr_hit(wlo, whi))) blit_barrier();
|
||||
g_bw_lo[g_bw_n] = wlo; g_bw_hi[g_bw_n++] = whi; g_blit_ops++; g_gp_copies++;
|
||||
if (rhi > rlo) { g_br_lo[g_br_n] = rlo; g_br_hi[g_br_n++] = rhi; }
|
||||
return e;
|
||||
@@ -14291,11 +14295,65 @@ static void bufsnap_after(NvShader *cs, id ce) {
|
||||
res_add(dst); res_commit();
|
||||
[(id<MTL4ComputeCommandEncoder>)ce barrierAfterEncoderStages:MTLStageDispatch | MTLStageBlit beforeEncoderStages:MTLStageDispatch | MTLStageBlit visibilityOptions:blit_vis()];
|
||||
[(id<MTL4ComputeCommandEncoder>)ce copyFromBuffer:(__bridge id<MTLBuffer>)mb sourceOffset:mo toBuffer:dst destinationOffset:0 size:n];
|
||||
g_blit_ops = 1; // the next copy or dispatch is ordered after it
|
||||
g_bw_lo[0] = 0; g_bw_hi[0] = ~0ull; g_bw_n = 1; g_br_n = 0; g_blit_ops = 1; // recorded as "everything written", as blit() does: the next copy or dispatch is ordered after it (a dispatch ordered by the game's barriers would otherwise overwrite what the copy still reads)
|
||||
NSString *key = @(cs->key);
|
||||
[g_commit_blocks addObject:^{ BOOL ok = [[NSData dataWithBytes:dst.contents length:n] writeToFile:path atomically:NO];
|
||||
MLOG("bufsnap after %s: %zu bytes %s %s", key.UTF8String, n, ok ? "saved to" : "could not be written to", path.UTF8String); }];
|
||||
}
|
||||
// Compute dispatches are ordered by the game's own barriers, as NVN orders them (DM_NVN_DISPATCH_BARRIER=full: each after everything before it in its encoder, as before; game, the
|
||||
// default; ab alternates the two with the DM_AB phases, for measurement). NVN makes a dispatch's writes visible to later work when the game asks with nvnCommandBufferBarrier; the full
|
||||
// order made the GPU run every dispatch of an encoder one at a time. Kirby Air Riders' particle systems are about 230 dispatches a frame in one encoder: 6.6-9.8 ms of GPU time at
|
||||
// about 30 us each, 0.4-1.2 ms ordered by the game's barriers, 0.15 ms with no barrier at all (DM_NVN_BLIT_ORDER=0, which also drops the ones the game asked for, and faults). Their
|
||||
// memory ranges cannot replace the game's barriers: the systems share the buffers they write, and 91 % of the dispatches met an earlier one's range. A dispatch gets a barrier when the
|
||||
// game issued one since the dispatch before it, when it reads a range a copy wrote or writes one a copy read or wrote since the last barrier (uniform updates, uploads: the host's own
|
||||
// order), or when its sets are full; what it writes and reads is kept apart from the copies' sets (g_dw, g_dr), so that later copies are ordered after it and later dispatches are not.
|
||||
// A dispatch with a binding whose reach is no range (an image, a buffer texture, a handle in a uniform slot, global memory traced to no storage buffer) keeps the full order on both
|
||||
// sides, as do the host's own dispatches (dispatch_enc). The driver's own segments are no guest memory. A draw pass ends the copy encoder and begins with its own barrier
|
||||
static int dbar_game(void) {
|
||||
static int v = -1;
|
||||
if (v < 0) { const char *e = getenv("DM_NVN_DISPATCH_BARRIER"); v = e && !strncmp(e, "ab", 2) ? sw_mode("DM_NVN_DISPATCH_BARRIER", 0) : !(e && !strcmp(e, "full"));
|
||||
if (!v) MLOG("DM_NVN_DISPATCH_BARRIER=full: every compute dispatch is ordered after everything before it in its encoder (diagnostic)"); }
|
||||
return sw_on(v);
|
||||
}
|
||||
static geo_access cs_access_of(NvShader *sh, uint64_t ind) { // the guest memory a dispatch reads and writes through its bindings and its indirect record; unknown when a binding's reach is no range
|
||||
geo_access a = {0};
|
||||
if (ind) geo_access_add(&a, ind, 12, 0);
|
||||
for (int i = 0; i < sh->rf.nb && !a.unknown; i++) {
|
||||
const nvn_rbind *b = &sh->rf.b[i];
|
||||
switch (b->kind) {
|
||||
case NVN_RB_CBUF: case NVN_RB_UBOP: case NVN_RB_SBUFP: {
|
||||
if (b->reg >= 16) { a.unknown = 1; break; }
|
||||
const p_bind_buf *u = b->kind == NVN_RB_SBUFP ? &S.ssbo[5][b->reg] : &S.ubo[5][b->reg];
|
||||
geo_access_add(&a, u->addr, b->kind == NVN_RB_CBUF ? cb_len(sh, b->reg, u->size) : u->size, b->kind == NVN_RB_SBUFP && b->rw && !(sh->sb_ro >> b->reg & 1));
|
||||
break; }
|
||||
case NVN_RB_SUPPORT: case NVN_RB_C1: case NVN_RB_DRV0: case NVN_RB_DRV2: case NVN_RB_CBSIZE: break;
|
||||
default: a.unknown = 1;
|
||||
}
|
||||
}
|
||||
return a;
|
||||
}
|
||||
static uint64_t g_dbar_game, g_dbar_copy, g_dbar_unknown, g_dbar_free;
|
||||
void mtl_dispatch_barrier_stats(uint64_t *game, uint64_t *copy, uint64_t *unknown, uint64_t *none) { // the periodic [nvn] line (hle_nvn.c)
|
||||
*game = g_dbar_game; *copy = g_dbar_copy; *unknown = g_dbar_unknown; *none = g_dbar_free; }
|
||||
static id<MTL4ComputeCommandEncoder> dispatch_enc_cs(NvShader *cs, uint64_t ind) {
|
||||
if (!dbar_game()) { g_dsp_game_bar = 0; return dispatch_enc(); }
|
||||
geo_access a = cs_access_of(cs, ind);
|
||||
if (a.unknown) { g_dbar_unknown++; g_dsp_game_bar = 0; return dispatch_enc(); }
|
||||
id<MTL4ComputeCommandEncoder> e = blit_open(); g_gp_disp++;
|
||||
int copy = g_dr_n + a.n > DW_MAX || g_dw_n + a.n > DW_MAX;
|
||||
for (int i = 0; i < a.n && !copy; i++) copy = bw_hit(a.r[i].lo, a.r[i].hi) || (a.r[i].write && br_hit(a.r[i].lo, a.r[i].hi));
|
||||
if (g_blit_ops && (g_dsp_game_bar || copy)) { if (g_dsp_game_bar) g_dbar_game++; else g_dbar_copy++; blit_barrier(); } else g_dbar_free++;
|
||||
g_dsp_game_bar = 0;
|
||||
for (int i = 0; i < a.n; i++) { // a range already in its set is not added again: the systems share their tables
|
||||
uint64_t *lo = a.r[i].write ? g_dw_lo : g_dr_lo, *hi = a.r[i].write ? g_dw_hi : g_dr_hi; int *n = a.r[i].write ? &g_dw_n : &g_dr_n, have = 0;
|
||||
for (int k = 0; k < *n && !have; k++) have = lo[k] == a.r[i].lo && hi[k] == a.r[i].hi;
|
||||
if (!have) { lo[*n] = a.r[i].lo; hi[(*n)++] = a.r[i].hi; }
|
||||
}
|
||||
g_blit_ops++;
|
||||
if (!g_blit_ct) { [e setArgumentTable:g_ct]; g_blit_ct = 1; }
|
||||
args_dirty_all();
|
||||
return e;
|
||||
}
|
||||
static void dispatch(const p_dispatch *dp) {
|
||||
zskip_clear();
|
||||
g_wr_epoch++; g_mdx_epoch++;
|
||||
@@ -14368,7 +14426,7 @@ static void dispatch(const p_dispatch *dp) {
|
||||
// or before dispatch_enc's copy-to-dispatch barrier: otherwise the upgrade opens a second encoder, or its copy races the dispatch (#1743).
|
||||
encode_args(nil, cs, 5, 0);
|
||||
if (own && g_blit) { enc_b_end(g_blit); g_blit = nil; }
|
||||
id<MTLComputeCommandEncoder> ce = own ? pg_compute() : (id<MTLComputeCommandEncoder>)dispatch_enc();
|
||||
id<MTLComputeCommandEncoder> ce = own ? pg_compute() : (id<MTLComputeCommandEncoder>)dispatch_enc_cs(cs, dp->ind);
|
||||
enc_c_pso(ce, ps);
|
||||
if (tg_groups) {
|
||||
__strong id<MTLBuffer> tb = nil; size_t to = arena_alloc((size_t)(tg_groups * cs->rf.tg_spill), &tb);
|
||||
@@ -15418,7 +15476,7 @@ void mtl_exec(const uint8_t *p) {
|
||||
PD("I %llu barrier bits %#x%s", g_stat_pass, bits, split ? ": ends the pass (shader writes)" : order ? " (render pass open; a later shader write is ordered after its draws)" : g_enc ? " (render pass open)" : "");
|
||||
if (split) { rp_end(); static int once; if (!once++) MLOG("a game barrier (bits %#x) after shader writes in a draw pass: the pass ends there (first case pass %llu)", bits, (unsigned long long)g_stat_pass); }
|
||||
else if (order) g_pass_order |= (bits & NVN_BARRIER_ORDER_PRIMITIVES_BIT ? 1 : 0) | (bits & (NVN_BARRIER_ORDER_FRAGMENTS_BIT | NVN_BARRIER_ORDER_FRAGMENTS_TILED_BIT) ? 2 : 0);
|
||||
if (bits) { g_game_barrier |= bits; g_fb_bar++; } break; } // g_fb_bar: snapshots taken before it are stale (see fb_prepare)
|
||||
if (bits) { g_game_barrier |= bits; g_fb_bar++; g_dsp_game_bar = 1; } break; } // g_fb_bar: snapshots taken before it are stale (see fb_prepare)
|
||||
case OP_SET_TEX_POOL: case OP_SET_SAMP_POOL: state_op(h.op, a); break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
@@ -244,6 +244,13 @@ check_t_dispatch_own: t_dispatch_own
|
||||
@set -e; for own in 0 1; do for enc in 0 1; do \
|
||||
DM_NVN_DISPATCH_OWN=$$own DM_NVN_ENC_THREAD=$$enc MTL_DEBUG_LAYER=1 ./t_dispatch_own; \
|
||||
done; done
|
||||
t_dispatch_barrier: t_dispatch_barrier.m $(MTL_T_DEP)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_dispatch_barrier.m $(MTL_T_SRC) $(FW)
|
||||
.PHONY: check_t_dispatch_barrier
|
||||
check_t_dispatch_barrier: t_dispatch_barrier
|
||||
@set -e; for mode in full game; do for enc in 0 1; do \
|
||||
DM_NVN_DISPATCH_BARRIER=$$mode DM_NVN_ENC_THREAD=$$enc MTL_DEBUG_LAYER=1 ./t_dispatch_barrier; \
|
||||
done; done
|
||||
t_vbuf: t_vbuf.m $(MTL_T_DEP)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_vbuf.m $(MTL_T_SRC) $(FW)
|
||||
.PHONY: check_t_vbuf
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// Compute dispatches ordered by the game's own barriers (nvn_mtl.m dispatch_enc_cs, the default): a barrier where the game issued one, where a copy's
|
||||
// range meets the dispatch's, and around a dispatch whose reach is no range; none between dispatches the game did not order. Run in both modes (DM_NVN_DISPATCH_BARRIER=full / game):
|
||||
// the results are the same, the barriers differ.
|
||||
#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); } } while (0)
|
||||
#define EXPECT(label, want, got) do { checks++; long long w_ = (long long)(want), g_ = (long long)(got); if (w_ != g_) { failed++; fprintf(stderr, "FAIL: %s: expected %lld, got %lld\n", label, w_, g_); } } while (0)
|
||||
enum { N = 64 };
|
||||
static NvShader *kernel(id<MTLLibrary> lib, NSString *name) {
|
||||
NvShader *cs = [NvShader new]; cs->stage = 5; cs->fn = [lib newFunctionWithName:name]; cs->ae = [cs->fn newArgumentEncoderWithBufferIndex:0];
|
||||
cs->rf.tg[0] = cs->rf.tg[1] = cs->rf.tg[2] = 1; cs->rf.nb = 2; cs->rf.drv_read[0] = 1;
|
||||
cs->rf.b[0] = (nvn_rbind){.kind=NVN_RB_SBUFP, .rw=1, .reg=0, .aid=0};
|
||||
cs->rf.b[1] = (nvn_rbind){.kind=NVN_RB_DRV0, .aid=1};
|
||||
return cs;
|
||||
}
|
||||
static void begin(void) { mtl_sub_begin(); state_reset(); memset(&R, 0, sizeof R); }
|
||||
static void end(const char *what) { uint64_t fence = mtl_sub_commit(); CHECK(mtl_wait(fence, 5000000000ull), what); mtl_drain(); CHECK(!mtl_last_commit_error(), "no GPU error"); }
|
||||
|
||||
int main(void) { @autoreleasepool {
|
||||
mtl_init();
|
||||
int game = dbar_game();
|
||||
NSError *error = nil;
|
||||
id<MTLLibrary> lib = [g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal;\n"
|
||||
"struct Args { device uint *buf [[id(0)]]; constant uint *c0 [[id(1)]]; };\n"
|
||||
"kernel void chain(constant Args &a [[buffer(0)]], uint3 p [[thread_position_in_grid]]) { if (!any(p != uint3(0))) a.buf[0] = a.buf[0] * 3u + 1u; }\n"
|
||||
"kernel void slot(constant Args &a [[buffer(0)]], uint3 p [[thread_position_in_grid]]) { if (!any(p != uint3(0))) a.buf[0] = a.buf[1] + 1u; }\n" options:nil error:&error];
|
||||
CHECK(lib != nil, "synthetic compute shaders compile"); if (!lib) return 1;
|
||||
prog_t pc = {.serial=970001}, ps = {.serial=970002};
|
||||
NvProg *chain = [NvProg new], *slot = [NvProg new]; chain->sh[5] = kernel(lib, @"chain"); slot->sh[5] = kernel(lib, @"slot");
|
||||
serial_put(pc.serial, chain); serial_put(ps.serial, slot);
|
||||
size_t page = (size_t)getpagesize(), size = 4 * page;
|
||||
uint8_t *mem = NULL, *commands = NULL;
|
||||
if (posix_memalign((void **)&mem, page, size) || posix_memalign((void **)&commands, page, size)) return 1;
|
||||
memset(mem, 0, size); memset(commands, 0, size); mtl_pool_add(mem, size); mtl_pool_add(commands, size);
|
||||
uint32_t *word = (uint32_t *)mem;
|
||||
p_dispatch one = {.x=1, .y=1, .z=1};
|
||||
size_t used = 0;
|
||||
#define EMIT(OP, X) do { size_t z = (8 + sizeof(X) + 7) & ~7ull; op_hdr h = {OP, (uint32_t)z}; memcpy(commands + used, &h, 8); memcpy(commands + used + 8, &(X), sizeof(X)); used += z; } while (0)
|
||||
#define RUN() do { op_hdr e_ = {OP_END, 8}; memcpy(commands + used, &e_, 8); uint64_t h_ = (uint64_t)commands; mtl_sub_index(&h_, 1); mtl_exec(commands); used = 0; } while (0)
|
||||
|
||||
// 1. A chain on one word, each dispatch behind the game's barrier: the sequential result in both modes
|
||||
{ word[0] = 5; uint32_t want = 5; for (int i = 0; i < N; i++) want = want * 3u + 1u;
|
||||
int32_t bits = NVN_BARRIER_ORDER_PRIMITIVES_BIT;
|
||||
for (int i = 0; i < N; i++) { if (i) EMIT(OP_BARRIER, bits); EMIT(OP_DISPATCH, one); }
|
||||
begin(); S.cprog = &pc; S.ssbo[5][0] = (p_bind_buf){.addr=(uint64_t)mem, .size=64};
|
||||
uint64_t b0 = mtl_blit_barriers(), g0 = g_dbar_game; RUN();
|
||||
EXPECT("a barrier before every dispatch the game ordered", N - 1, mtl_blit_barriers() - b0);
|
||||
if (game) EXPECT("counted as the game's own", N - 1, g_dbar_game - g0);
|
||||
end("the chain completes"); EXPECT("the chain runs in order", want, word[0]); }
|
||||
|
||||
// 2. Dispatches into slots of their own, no game barrier: none in game mode, one each in full mode
|
||||
{ for (int i = 0; i < N; i++) { word[16 * i] = 0; word[16 * i + 1] = (uint32_t)i; }
|
||||
begin(); S.cprog = &ps; uint64_t b0 = mtl_blit_barriers(), f0 = g_dbar_free;
|
||||
for (int i = 0; i < N; i++) { S.ssbo[5][0] = (p_bind_buf){.addr=(uint64_t)(mem + 64 * i), .size=64}; dispatch(&one); }
|
||||
EXPECT("barriers between dispatches the game did not order", game ? 0 : N - 1, mtl_blit_barriers() - b0);
|
||||
if (game) EXPECT("counted as none", N, g_dbar_free - f0);
|
||||
end("the slots complete"); int ok = 1; for (int i = 0; i < N; i++) ok &= word[16 * i] == (uint32_t)i + 1;
|
||||
CHECK(ok, "every slot's dispatch ran"); }
|
||||
|
||||
// 3. A fill, then a dispatch that reads it: ordered by the copy's range in both modes
|
||||
{ word[0] = 0;
|
||||
begin(); S.cprog = &pc; S.ssbo[5][0] = (p_bind_buf){.addr=(uint64_t)mem, .size=64};
|
||||
uint64_t b0 = mtl_blit_barriers(), c0 = g_dbar_copy;
|
||||
mtl_sub_fill((uint64_t)mem, 4, 7); dispatch(&one);
|
||||
EXPECT("a barrier between a fill and the dispatch that reads it", 1, mtl_blit_barriers() - b0);
|
||||
if (game) EXPECT("counted as a copy's range", 1, g_dbar_copy - c0);
|
||||
end("the fill and its dispatch complete"); EXPECT("the dispatch sees the fill", 7 * 3 + 1, word[0]); }
|
||||
|
||||
// 4. A dispatch, then a copy of what it wrote: the copy is ordered after it in both modes
|
||||
{ word[0] = 2; word[512] = 0;
|
||||
struct { uint64_t source, destination, bytes; } copy = {(uint64_t)mem, (uint64_t)(mem + 2048), 4};
|
||||
EMIT(OP_DISPATCH, one); EMIT(OP_COPY_B2B, copy);
|
||||
begin(); S.cprog = &pc; S.ssbo[5][0] = (p_bind_buf){.addr=(uint64_t)mem, .size=64};
|
||||
uint64_t b0 = mtl_blit_barriers(); RUN();
|
||||
EXPECT("a barrier between a dispatch and the copy that reads what it wrote", 1, mtl_blit_barriers() - b0);
|
||||
end("the dispatch and its copy complete"); EXPECT("the copy sees the dispatch", 2 * 3 + 1, word[512]); }
|
||||
|
||||
// 5. A binding whose reach is no range (no size): the full order on both sides, in both modes
|
||||
{ word[0] = 1;
|
||||
begin(); S.cprog = &pc; S.ssbo[5][0] = (p_bind_buf){.addr=(uint64_t)mem, .size=0};
|
||||
uint64_t b0 = mtl_blit_barriers(), u0 = g_dbar_unknown;
|
||||
dispatch(&one); dispatch(&one); S.ssbo[5][0].size = 64; dispatch(&one);
|
||||
EXPECT("barriers around dispatches with no range", 2, mtl_blit_barriers() - b0);
|
||||
if (game) EXPECT("counted as no range", 2, g_dbar_unknown - u0);
|
||||
end("the rangeless dispatches complete"); EXPECT("they run in order", ((1 * 3 + 1) * 3 + 1) * 3 + 1, word[0]); }
|
||||
|
||||
// 6. What a dispatch wrote orders nothing in the next copy encoder, which starts behind a full barrier of its own: two fills there, the second over the dispatch's range, get no barrier
|
||||
{ word[0] = 0;
|
||||
begin(); S.cprog = &pc; S.ssbo[5][0] = (p_bind_buf){.addr=(uint64_t)mem, .size=64}; dispatch(&one); end("the dispatch completes");
|
||||
begin(); uint64_t b0 = mtl_blit_barriers();
|
||||
mtl_sub_fill((uint64_t)(mem + 2048), 4, 1); mtl_sub_fill((uint64_t)mem, 4, 9);
|
||||
EXPECT("no barrier from a closed encoder's dispatch", 0, mtl_blit_barriers() - b0);
|
||||
end("the fills complete"); EXPECT("the second fill lands", 9, word[0]); }
|
||||
|
||||
mtl_pool_del(mem); mtl_pool_del(commands); mtl_drain();
|
||||
printf("t_dispatch_barrier (%s): %d checks, %d failed\n", game ? "game" : "full", checks, failed); return failed != 0;
|
||||
} }
|
||||
@@ -565,6 +565,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- 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)
|
||||
- a game with many small compute dispatches a frame spends most of its GPU time in one compute / copy encoder: `DM_NVN_GPUPROF` shows an encoder with hundreds of dispatches at about 30 µs each, and the frame rate drops where the dispatch count rises, with the submit thread and the render passes well inside the frame. → [Compute dispatches that wait for each other](../reference/frame-rate.md#compute-dispatches-that-wait-for-each-other)
|
||||
- after a loading screen the game's resolution stays at its lowest (Ocarina of Time: 683x384) for minutes while it holds 60 fps with GPU time well under the frame, and climbs back only slowly or not at all. → [Dynamic resolution at its floor while the GPU has time to spare](../reference/frame-rate.md#dynamic-resolution-at-its-floor-while-the-gpu-has-time-to-spare)
|
||||
- many passes a frame on the same attachments, with the residency set line showing `passes ended to land them for a read` in the thousands and `refused …: earlier submission running` matching it. Ocarina of Time: 10,463 per 300 frames, each ending the pass over a uniform block no GPU write touched. → [A full table of running GPU writes ends passes for nothing](../reference/frame-rate.md#a-full-table-of-running-gpu-writes-ends-passes-for-nothing)
|
||||
- the submit (replay) thread spends a large share of its time in `ubc_wait`, under `pthread_mutex_lock` / `pthread_cond_signal`, while the `dm-ub-copy` thread waits for the same mutex far longer than it copies; translation cost jumps several-fold on one host build and not on another with the same code. Ocarina of Time on one build: 192 of the replay thread's 392 busy samples in `ubc_wait`, the copy thread 168 samples waiting for the mutex and 19 copying, 221-333k instructions a draw (9 runs) and 23-57 ms of submit CPU a frame, against 38.9k and 7.1 ms with `DM_NVN_UB_COPY_THREAD=0`. Builds that did not convoy still had 0.3-0.9 % of the replay thread's busy samples there. → [The uniform copy thread's hand-off convoys on its mutex](../reference/frame-rate.md#the-uniform-copy-threads-hand-off-convoys-on-its-mutex)
|
||||
|
||||
@@ -147,6 +147,7 @@ DM_NVN_DEFER_AB diagnostic `=1` keeps the deferred pass merging (with `DM_NVN_TB
|
||||
DM_NVN_DEPTHOVR diagnostic `=<fragment shader key prefix>,…`: those draws compare depth with `ALWAYS`; with `DM_NVN_HILITE`, tells "the depth test rejects every fragment" from "nothing rasterizes"
|
||||
DM_NVN_DIRECT_UPLOAD switch 0 disables bounded direct RGBA16F array uploads and keeps staged copies; on by default for supported non-sparse textures.
|
||||
DM_NVN_DIRTYCHECK diagnostic `=1` fully hashes pool content on every use to find changes the dirty-page tracking missed
|
||||
DM_NVN_DISPATCH_BARRIER diagnostic `full`: every compute dispatch is ordered after everything before it in its encoder, as before; by default dispatches are ordered by the game's own barriers and by the copies around them (`nvn_mtl.m` `dbar_game`); `ab` alternates the two with the `DM_AB` phases, for measurement
|
||||
DM_NVN_DISPATCH_OWN switch `=1` gives every compute dispatch a compute encoder of its own with full barriers, as before (by default dispatches share the copy encoder); `DM_NVN_PASSGPU` does the same
|
||||
DM_NVN_DLSS_BILINEAR diagnostic `=1` draws every DLSS evaluation with the bilinear stand-in, to tell MetalFX's part in a GPU fault or stall
|
||||
DM_NVN_DUAL_WANT path `=<file>`: appends the key of each pixel shader a pipeline blends with its output 1 as the second source, while it has no dual-source entry point, to that file, once per key (the profile's `dual_want.tsv`)
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 19 and column 104.
|
@@ -593,6 +593,16 @@ Frame pacing: the host's frame step, engine frame limiters, present intervals an
|
||||
- **Open:** Ocarina of Time is the only profile with `draw_barriers game`; another game reaches this only with `DM_NVN_BARRIER=game`. About 37 full entry barriers a frame remain in Ocarina of Time, from `ORDER_PRIMITIVES` barriers and compute in between. An iPhone run with PR 1970 saw a flickering patch on a wall of the Deku Tree basement's torch room, with no baseline from that room: not reproduced or ruled out.
|
||||
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md#found-on-this-game).
|
||||
|
||||
### Compute dispatches that wait for each other
|
||||
|
||||
- **Symptom:** a game with many small compute dispatches a frame spends most of its GPU time in one compute / copy encoder: `DM_NVN_GPUPROF` shows an encoder with hundreds of dispatches at about 30 µs each, and the frame rate drops where the dispatch count rises, with the submit thread and the render passes well inside the frame.
|
||||
- **Cause:** every dispatch was ordered after everything before it in its encoder (`dispatch_enc`: a barrier before each, as for a texture copy), so the GPU ran them one at a time. NVN does not ask for that: a dispatch's writes are visible to later work when the game issues `nvnCommandBufferBarrier`, as for draw passes. The dispatches' memory ranges cannot replace the game's barriers: Kirby Air Riders' particle systems share the buffers they write, and 91 % of its dispatches met a range an earlier one wrote.
|
||||
- **Fix:** host-wide, dispatches are ordered as NVN orders them (`dispatch_enc_cs` in `nvn_mtl.m`). A dispatch gets a barrier when the game issued one since the dispatch before it, and when a copy's range meets its own (a dispatch after a copy that wrote what it reads, a copy after a dispatch that wrote or read what it touches: the host's own uniform updates and uploads keep their order). A dispatch whose reach is no memory range (an image, a buffer texture, a handle in a uniform slot, global memory traced to no storage buffer) and the host's own dispatches keep the full order on both sides. `DM_NVN_DISPATCH_BARRIER=full` brings back a barrier before every dispatch (diagnostic); `ab` alternates the two with the `DM_AB` phases. The periodic `[nvn] compute dispatches` line counts each kind.
|
||||
- **Measured** (PR author, M4 Pro, Kirby Air Riders' Air Ride races): of 600,000 dispatches 7 % had a barrier of the game's, 2 % a copy's, 6 % no range, and 85 % none; the particle encoder went from 6.6-9.8 ms to 0.4-1.2 ms a frame (about 230 dispatches, 30 → 2-6 µs each). Both orders in one race (`DM_AB=600 DM_NVN_DISPATCH_BARRIER=ab`, 450 measured frames a phase, 5 phases `full` and 4 `game`): GPU p50 8.2-11.5 ms (mean 9.0) → 4.1-6.2 ms (mean 5.3), p90 9.8-13.7 → 5.1-9.9 ms; in the heaviest phase the frame time was p50 17.27 / p90 19.36 ms with `full`, and 16.66 / 16.75 ms in every `game` phase. Those runs had [PR 2254](https://github.com/seedds/nxnative/pull/2254)'s loop guard: by its author, Kirby's particle shaders can hang the GPU without it, under either order.
|
||||
- **Checked:** `t_dispatch_barrier` (both modes: a chain behind the game's barriers gives the sequential result, dispatches the game did not order get no barrier, copies stay ordered both ways, a rangeless dispatch keeps the full order).
|
||||
- **Open:** a game that reads an earlier dispatch's writes with no barrier between them, which NVN does not order either, would now race; `DM_NVN_DISPATCH_BARRIER=full` tells. When it became the default, `regress.py check` against main ran two games (M4 Pro): Mario Kart World, 200 s, PASS, 69,367 of 1,023,394 dispatches with no barrier (182,609 after a game barrier, 45,983 after a copy's range, 725,435 in the full order), 59.8 / 60.0 fps, no new red line; OCTOPATH TRAVELER II, 440 s, PASS, but every one of its dispatches has a binding with no range, so it kept the full order. Kirby Air Riders and Ocarina of Time (which [PR 1901](https://github.com/seedds/nxnative/pull/1901) measured with a narrower form of this rule, GPU p50 about −0.8 ms) have not run with it in this form, nor has the iPhone. Age of Calamity puts a game barrier before each of its dispatches, so it keeps its order.
|
||||
- **Found on:** [Kirby Air Riders](../../dm/games/040077201BE50000/README.md).
|
||||
|
||||
### Dynamic resolution at its floor while the GPU has time to spare
|
||||
|
||||
- **Symptom:** after a loading screen the game's resolution stays at its lowest (Ocarina of Time: 683x384) for minutes while it holds 60 fps with GPU time well under the frame, and climbs back only slowly or not at all.
|
||||
|
||||
@@ -1313,7 +1313,7 @@ The replay on Metal (`dm/gfx/nvn/nvn_mtl.m`) and the Vulkan and OpenGL layers. E
|
||||
|
||||
- **Symptom:** tall blue / textured panels that flickered frame to frame: the fountain's vertex shader pushed the water surface to the top of the screen.
|
||||
- **Cause:** the host batches consecutive copies, fills and inline uniform updates (`UpdateUniformBuffer`) into one compute encoder, and Metal 4 does not order operations inside one encoder. Mario writes the same uniform slot twice in a row each frame (4 bytes of −1, then 16 bytes of wave coefficients); without an intra-encoder barrier the writes occasionally landed in reverse order, the fountain's GPU wave simulation (a 512×1 RGBA16F texture updated by render → copy back → splash pass every frame) ran with −1 as its self coefficient and diverged to ±65504.
|
||||
- **Fix:** `blit_buf` now inserts `barrierAfterEncoderStages` when an operation reads or writes a guest range an earlier operation in the same encoder wrote; texture copies always get one. Render passes have their own encoder with full barriers, so they were not affected; compute dispatches share the copy encoder and always get a barrier, as texture copies do (Hyrule Warriors: Age of Calamity, [Compute dispatches share the copy encoder](#compute-dispatches-share-the-copy-encoder)).
|
||||
- **Fix:** `blit_buf` now inserts `barrierAfterEncoderStages` when an operation reads or writes a guest range an earlier operation in the same encoder wrote; texture copies always get one. Render passes have their own encoder with full barriers, so they were not affected; compute dispatches share the copy encoder ([Compute dispatches share the copy encoder](#compute-dispatches-share-the-copy-encoder)) and are ordered against copies by the same ranges ([Compute dispatches that wait for each other](frame-rate.md#compute-dispatches-that-wait-for-each-other)).
|
||||
- **Check:** `DM_NVN_BLIT_ORDER=0` turns the barriers off to reproduce.
|
||||
- **Found on:** [Super Mario Bros. Wonder](../../dm/games/010015100B514000/README.md).
|
||||
|
||||
@@ -1387,7 +1387,7 @@ The replay on Metal (`dm/gfx/nvn/nvn_mtl.m`) and the Vulkan and OpenGL layers. E
|
||||
- **Cause:** each dispatch had a compute encoder of its own with full queue barriers on both sides, a GPU drain per dispatch: about 10 µs of GPU each on the Mac.
|
||||
- **Fix:** dispatches now go into the open copy encoder, each after a barrier inside it (as texture copies are, `blit`), with the compute argument table set once per encoder (`dispatch_enc`): about 1.3 µs each.
|
||||
- **Found on:** [Hyrule Warriors: Age of Calamity](../../dm/games/01002B00111A2000/README.md): after its first cutscene the first battle runs about 900–1,500 small dispatches a frame on the Mac (an iPhone log's call counts suggest more), each after a game barrier, at the same draws and passes; GPU 7.3 → 8.1 ms across the cutscene with the change.
|
||||
- **Note:** `DM_NVN_DISPATCH_OWN=1` (and `DM_NVN_PASSGPU`, which times each dispatch) gives each dispatch its own encoder again.
|
||||
- **Note:** `DM_NVN_DISPATCH_OWN=1` (and `DM_NVN_PASSGPU`, which times each dispatch) gives each dispatch its own encoder again. A barrier before every dispatch is now only where NVN asks for one: [Compute dispatches that wait for each other](frame-rate.md#compute-dispatches-that-wait-for-each-other).
|
||||
|
||||
### Compute bindings prepare texture copies before the dispatch encoder
|
||||
|
||||
|
||||
Reference in new issue
Block a user