From a157107714b58f7a1d1baf3e5946d546a8c9bded Mon Sep 17 00:00:00 2001 From: seedds Date: Sun, 8 Nov 2026 19:52:03 -0500 Subject: [PATCH] Track bounded compute buffer dependencies in the copy encoder --- dm/games/0400486024DEC000/README.md | 7 +++ dm/gfx/nvn/nvn_mtl.m | 73 ++++++++++++++++++++++++++++- dm/gfx/tests/Makefile | 8 ++++ dm/gfx/tests/t_cs_ranges.m | 71 ++++++++++++++++++++++++++++ docs/agents/symptoms.md | 1 + docs/env_switches.tsv | 1 + docs/reference/rendering.md | 9 ++++ 7 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 dm/gfx/tests/t_cs_ranges.m diff --git a/dm/games/0400486024DEC000/README.md b/dm/games/0400486024DEC000/README.md index d880588ffe..c53ef7ae61 100644 --- a/dm/games/0400486024DEC000/README.md +++ b/dm/games/0400486024DEC000/README.md @@ -188,3 +188,10 @@ From an empty save: at about 45 s `A` (title), `A` (New Game), then the movie. F - [AV1 movies stop an M1 iPad with SIGILL in dav1d](../../../docs/reference/movies.md#av1-movies-stop-an-m1-ipad-with-sigill-in-dav1d): the title movie on an M1 iPad Pro. - [`devicectl` copies a large RomFS image through the Mac's memory](../../../docs/reference/packing.md#devicectl-copies-a-large-romfs-image-through-the-macs-memory): the 26.2 GB image's pushes to an iPad filled a 16 GB Mac's swap and failed; now sent over AFC. - [`devicectl`'s `--remove-existing-content` empties the app's whole container](../../../docs/reference/packing.md#devicectls---remove-existing-content-empties-the-apps-whole-container): the first complete copy of the image, deleted by the DLC step after it. + + +### Bounded compute ordering (experimental) + +Found on this game: [independent buffer dispatch ordering](../../../docs/reference/rendering.md#independent-buffer-dispatches-serialize-inside-the-copy-encoder). Extracted from the playability campaign as an opt-in host-only change. Historical crowded-Market ABBA measurement, same host/shaders/save/window and matching 1578 MHz GPU / 4512 MHz CPU medians: the later stable-workload cycle reduces GPU mean 10.580 to 10.395 ms (1.75%). An earlier cycle changes workload and is not the principal result. A separate reverse-order process comparison measured 93.6 to 94.9 FPS and GPU median 10.72 to 10.45 ms, but frame p99 worsened from 13.00 to 14.55 ms. The preceding 93.7/87.0 FPS pair was clock-confounded and does not establish a regression or gain. These are historical measurements on the combined experimental branch, not measurements of this extraction on current main. + +Evidence from the November 8 chat was cross-checked against `compute-range-review.json`, `heavy-market/predicated-cs-ranges-ab-02/ab-review.json`, `compute-range-full-gfx-result.json` and `compute-range-regress/report.md` in the campaign diagnostics. The original full graphics suite and local Ocarina regression passed; capped regression FPS was 59.5 for both variants, not high-rate evidence. The extracted change passes 6,986 focused checks per encoder mode, but renewed gameplay, other games, iOS and stable 120 FPS remain unvalidated. Image quality settings are unchanged. diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index 3966c65760..960acda99e 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -13334,6 +13334,77 @@ static int dispatch_own(void) { args_dirty_all(); return e; } +// Buffer-only dispatches can share the copy encoder without a barrier when +// their complete guest-memory access sets are disjoint. Any unbounded access, +// sparse alias, image/texture binding or indirect dispatch keeps full ordering. +static int cs_range_add(csh_rng *ranges, int *count, uint64_t address, uint64_t size) { + if (!address || !size || size > UINT64_MAX - address || *count == BW_MAX + || nvn_sparse_alias(address, address + size)) return 0; + // An unresolved binding uses shared dummy storage in encode_args; two + // distinct guest addresses would then alias. Keep full ordering instead. + void *buffer; uint64_t offset; + if (!mtl_addr(address, size, &buffer, &offset)) return 0; + ranges[(*count)++] = (csh_rng){address, address + size}; + return 1; +} +static int cs_buffer_ranges(NvShader *cs, const p_dispatch *dp, csh_rng *reads, int *nr, csh_rng *writes, int *nw) { + if (!cs || cs->builtin || dp->ind || cs->rf.tg_spill) return 0; + uint32_t seen_u = 0, seen_s = 0; + for (int i = 0; i < cs->rf.nb; i++) { + const nvn_rbind *binding = &cs->rf.b[i]; unsigned reg = binding->reg; + switch (binding->kind) { + case NVN_RB_CBUF: case NVN_RB_UBOP: + if (reg >= 16) return 0; + if (seen_u & (1u << reg)) break; + seen_u |= 1u << reg; + if (!cs_range_add(reads, nr, S.ubo[5][reg].addr, S.ubo[5][reg].size)) return 0; + break; + case NVN_RB_SBUFP: + if (reg >= 16) return 0; + // Always include reads; a read_write declaration does not prove + // a pure store. Repeated declarations retain the union of writes. + if (!(seen_s & (1u << reg))) { + seen_s |= 1u << reg; + if (!cs_range_add(reads, nr, S.ssbo[5][reg].addr, S.ssbo[5][reg].size)) return 0; + } + if (binding->rw && !(cs->sb_ro & (1u << reg)) + && !cs_range_add(writes, nw, S.ssbo[5][reg].addr, S.ssbo[5][reg].size)) return 0; + break; + case NVN_RB_SUPPORT: case NVN_RB_C1: case NVN_RB_DRV0: case NVN_RB_DRV2: + break; // immutable or per-dispatch host-owned argument storage + default: return 0; + } + } + return 1; +} +static id dispatch_buffer_enc(NvShader *cs, const p_dispatch *dp) { + static int mode = -1; + if (mode < 0) mode = sw_mode("DM_NVN_CS_RANGES", 0); + if (!sw_on(mode)) return dispatch_enc(); + csh_rng reads[BW_MAX], writes[BW_MAX]; int nr = 0, nw = 0; + static uint64_t considered, eligible, skipped, reported_frame; + considered++; + if (!cs_buffer_ranges(cs, dp, reads, &nr, writes, &nw)) return dispatch_enc(); + eligible++; + g_blit_alias = 1; + id encoder = blit_open(); g_gp_disp++; + int conflict = g_bw_n + nw > BW_MAX || g_br_n + nr > BW_MAX; + for (int i = 0; i < nr && !conflict; i++) conflict = bw_hit(reads[i].lo, reads[i].hi); + for (int i = 0; i < nw && !conflict; i++) conflict = bw_hit(writes[i].lo, writes[i].hi) || br_hit(writes[i].lo, writes[i].hi); + if (g_blit_ops && conflict) blit_barrier(); + else if (g_blit_ops) skipped++; + for (int i = 0; i < nr; i++) { g_br_lo[g_br_n] = reads[i].lo; g_br_hi[g_br_n++] = reads[i].hi; } + for (int i = 0; i < nw; i++) { g_bw_lo[g_bw_n] = writes[i].lo; g_bw_hi[g_bw_n++] = writes[i].hi; } + g_blit_ops++; + if (!g_blit_ct) { [encoder setArgumentTable:g_ct]; g_blit_ct = 1; } + args_dirty_all(); + uint64_t frame = atomic_load(&g_cur_frame); + if (frame && frame % 600 == 0 && frame != reported_frame) { + reported_frame = frame; + MLOG("compute range ordering: %llu considered, %llu bounded, %llu independent barriers skipped", (unsigned long long)considered, (unsigned long long)eligible, (unsigned long long)skipped); + } + return encoder; +} static void dispatch(const p_dispatch *dp) { zskip_clear(); g_wr_epoch++; g_mdx_epoch++; @@ -13402,7 +13473,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 ce = own ? pg_compute() : (id)dispatch_enc(); + id ce = own ? pg_compute() : (id)dispatch_buffer_enc(cs, dp); enc_c_pso(ce, ps); if (tg_groups) { __strong id tb = nil; size_t to = arena_alloc((size_t)(tg_groups * cs->rf.tg_spill), &tb); diff --git a/dm/gfx/tests/Makefile b/dm/gfx/tests/Makefile index cb90d91410..92d9835985 100644 --- a/dm/gfx/tests/Makefile +++ b/dm/gfx/tests/Makefile @@ -572,3 +572,11 @@ t_tg_spill: t_tg_spill.m $(MTL_T_DEP) check_t_tg_spill: t_tg_spill MTL_DEBUG_LAYER=1 DM_NVN_DISPATCH_OWN=0 ./$< MTL_DEBUG_LAYER=1 DM_NVN_DISPATCH_OWN=1 ./$< + +# Bounded buffer dispatch dependencies, direct and deferred encoding. +t_cs_ranges: t_cs_ranges.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ $< $(MTL_T_SRC) $(FW) +.PHONY: check_t_cs_ranges +check_t_cs_ranges: t_cs_ranges + MTL_DEBUG_LAYER=1 ./t_cs_ranges + DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_cs_ranges diff --git a/dm/gfx/tests/t_cs_ranges.m b/dm/gfx/tests/t_cs_ranges.m new file mode 100644 index 0000000000..e6d991f835 --- /dev/null +++ b/dm/gfx/tests/t_cs_ranges.m @@ -0,0 +1,71 @@ +// Buffer dispatch ordering: real dependent GPU results plus fallback/capacity checks. +#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) +static void issue(NvShader *shader, id ps, id mem, unsigned src, unsigned dst) { + uint64_t a=(uint64_t)mem.contents; + S.ubo[5][0]=(p_bind_buf){.addr=a+src*4,.size=4}; + S.ssbo[5][0]=(p_bind_buf){.addr=a+dst*4,.size=4}; + p_dispatch dp={.x=1,.y=1,.z=1}; + id e=dispatch_buffer_enc(shader,&dp); + enc_c_pso(e,ps);enc_c_args(e,mem.gpuAddress+src*4,0);enc_c_args(e,mem.gpuAddress+dst*4,1); + enc_c_dispatch(e,MTLSizeMake(1,1,1),MTLSizeMake(1,1,1)); +} +int main(void) { @autoreleasepool { + setenv("DM_NVN_CS_RANGES","1",1);mtl_init(); + NSError *error=nil; + id lib=[g_dev newLibraryWithSource:@"#include \nusing namespace metal; kernel void step(device const uint* a [[buffer(0)]],device uint* b [[buffer(1)]]) { b[0]=a[0]+1; }" options:nil error:&error]; + id fn=[lib newFunctionWithName:@"step"]; + CHECK(fn!=nil,"test kernel compiles");if(!fn)return 1; + id ps=[g_dev newComputePipelineStateWithFunction:fn error:&error]; + void *guest=NULL; + CHECK(!posix_memalign(&guest,getpagesize(),65536),"guest allocation");if(!guest)return 1; + memset(guest,0,65536);mtl_pool_add(guest,65536); + void *mapped=NULL;uint64_t offset=0; + CHECK(mtl_addr((uint64_t)guest,4096,&mapped,&offset)&&offset==0,"registered guest pool resolves"); + id mem=(__bridge id)mapped; + CHECK(ps&&mem,"pipeline and memory allocated");if(!ps||!mem)return 1;res_add(mem); + NvShader *shader=[NvShader new];shader->rf.nb=2; + shader->rf.b[0]=(nvn_rbind){.kind=NVN_RB_CBUF,.reg=0}; + shader->rf.b[1]=(nvn_rbind){.kind=NVN_RB_SBUFP,.reg=0,.rw=1}; + for(int round=0;round<64;round++) { + uint32_t *v=mem.contents;memset(v,0,4096);v[0]=round;v[8]=100+round; + mtl_sub_begin();uint64_t barriers=g_blit_barriers; + issue(shader,ps,mem,0,1);issue(shader,ps,mem,8,9); + CHECK(g_blit_barriers==barriers,"disjoint dispatches need no internal barrier"); + issue(shader,ps,mem,1,2);CHECK(g_blit_barriers==barriers+1,"read after write orders producer"); + issue(shader,ps,mem,8,1);CHECK(g_blit_barriers==barriers+2,"write after read orders reader"); + issue(shader,ps,mem,0,1);CHECK(g_blit_barriers==barriers+3,"overlapping writes ordered"); + // Fill the access ledger with disjoint reads/writes, forcing capacity flushes. + for(unsigned i=16;i<216;i+=2)issue(shader,ps,mem,0,i); + CHECK(g_br_n<=BW_MAX&&g_bw_n<=BW_MAX,"bounded ledger stays within capacity"); + uint64_t a=(uint64_t)mem.contents; + enc_b_copy_buffer(blit_buf(a,a+4,a+1200,a+1204),mem,0,mem,1200,4); + issue(shader,ps,mem,300,301); + enc_b_copy_buffer(blit_buf(a+1204,a+1208,a+1208,a+1212),mem,1204,mem,1208,4); + issue(shader,ps,mem,302,303); + // An unbounded declaration forces the conservative path, with the same + // actual kernel so its dependent result remains an independent oracle. + shader->rf.b[1].kind=NVN_RB_GMEM;issue(shader,ps,mem,303,304); + shader->rf.b[1].kind=NVN_RB_SBUFP;issue(shader,ps,mem,304,305); + CHECK(mtl_wait(mtl_sub_commit(),5000000000ull),"submission completes"); + CHECK(v[301]==(uint32_t)round+1&&v[303]==(uint32_t)round+2&&v[305]==(uint32_t)round+4,"copy dispatch and unknown fallback transitions preserve GPU results"); + CHECK(!mtl_last_commit_error(),"Metal reports no execution error"); + CHECK(v[1]==(uint32_t)round+1&&v[2]==(uint32_t)round+2&&v[9]==(uint32_t)round+101,"GPU results preserve dependency order"); + for(unsigned i=16;i<216;i+=2)CHECK(v[i]==(uint32_t)round+1,"capacity flush preserves output"); + } + csh_rng r[BW_MAX],w[BW_MAX];int nr=0,nw=0;p_dispatch dp={0}; + S.ssbo[5][0].size=0;CHECK(!cs_buffer_ranges(shader,&dp,r,&nr,w,&nw),"unknown buffer size rejected"); + S.ssbo[5][0].size=4;dp.ind=1;nr=nw=0;CHECK(!cs_buffer_ranges(shader,&dp,r,&nr,w,&nw),"indirect dispatch rejected"); + dp.ind=0;shader->rf.b[1].kind=NVN_RB_GMEM;nr=nw=0;CHECK(!cs_buffer_ranges(shader,&dp,r,&nr,w,&nw),"raw global memory rejected"); + shader->rf.b[1].kind=NVN_RB_IMG;nr=nw=0;CHECK(!cs_buffer_ranges(shader,&dp,r,&nr,w,&nw),"image access rejected"); + nr=0;CHECK(!cs_range_add(r,&nr,UINT64_MAX-2,4),"wrapped range rejected"); + nr=0;CHECK(!cs_range_add(r,&nr,0x12340000,4),"unmapped address cannot masquerade as independent dummy storage"); + mtl_pool_del(guest);mtl_drain();mem=nil;free(guest); + printf("compute range ordering: %d checks, %d failed\n",checks,failed);return failed!=0; +} } diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index 1d11014f6f..51d0f535ab 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -808,6 +808,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - read-only depth/stencil attachments are written back after every pass, and the periodic unwritten-store savings counter remains zero with the default configuration. → [Unwritten attachment stores without lookahead](../reference/rendering.md#unwritten-attachment-stores-without-lookahead) - portrait gameplay overlaps the touch controls, touch coordinates land outside the game picture, or a TV's picture renders at 4K again after a layout pass. → [iOS layouts: portrait, a half-folded Duo, iPad windows](../reference/rendering.md#ios-layouts-portrait-a-half-folded-duo-ipad-windows) - with *Picture shape* at 1.43:1 (`DM_SCREEN_ASPECT`) the game renders 1920x1344, but on an iPhone Duo in Fit (the default) the picture comes out smaller than the 16:9 one, with black bars on all four sides; it fills the screen only in Fill. On the Mac a click lands off the point under the pointer (it was mapped on a 16:9 rectangle of the window). → [The picture laid out in the shape the game presents](../reference/rendering.md#the-picture-laid-out-in-the-shape-the-game-presents) +- buffer-only compute dispatches serialize even when their complete read/write ranges are disjoint. → [Independent buffer dispatches serialize inside the copy encoder](../reference/rendering.md#independent-buffer-dispatches-serialize-inside-the-copy-encoder) ## Shaders diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv index a1e62374ae..10b481f4c3 100644 --- a/docs/env_switches.tsv +++ b/docs/env_switches.tsv @@ -128,6 +128,7 @@ DM_NVN_COUNT diagnostic `1` counts every NVN call (the counting trampolines) and DM_NVN_CPUPROF diagnostic 1 records CPU wall/time/instruction totals by renderer operation; off by default. DM_NVN_CSH_PRESCAN diagnostic `0` runs the compute-hoist scan at every pass's first draw even when no dispatch follows (as before; for timing) DM_NVN_CS_HOIST switch `0` makes a compute dispatch between the draws of a pass end it (on by default: the dispatch runs ahead of the pass when that changes nothing the draws before it read) +DM_NVN_CS_RANGES diagnostic Opt-in bounded buffer compute ordering; 1 enables, ab alternates. DM_NVN_CUT switch `=`: the replay commits its command buffer every that many draws, between passes (default 64; `0` one command buffer per submission, except the cut after a buffer-to-texture copy) DM_NVN_CUT_BUSY switch `=0`: a segment boundary commits whatever the GPU is doing (the default commits only when earlier work has reported back, keeping the boundary's GPU timestamp otherwise) DM_NVN_DEFER switch `0` turns off the deferred pass merging of the TBDR optimizations (which run only with `DM_NVN_TBDR=1`) diff --git a/docs/reference/rendering.md b/docs/reference/rendering.md index 4d1e13f15d..1dabc5fbfa 100644 --- a/docs/reference/rendering.md +++ b/docs/reference/rendering.md @@ -1657,3 +1657,12 @@ Digimon Story Cyber Sleuth: Complete Edition (Media.Vision's MVGL engine, SDK 6. - **Fix:** the present reports the shape of the frame it draws ([the layer's](#a-crop-only-picks-texels-the-picture-has-the-layers-shape)) whenever its width / height changes (`nvn_mtl.m` `present_now` → `front.h` `front_picture_shape`; every graphics API presents there). The iOS front end lays the game's view out in that shape (`DmLayout.h` takes it as a parameter: the overlay, the split, Fill and the TV alike), so a 1.43:1 picture fills a 1.43:1 screen in Fit and touches are normalized on the picture as drawn; the Mac maps the mouse on the picture's own rectangle. A 16:9 game reports 16:9 and keeps its layout, and a size change of the same shape (1280x720 handheld, 1920x1080 docked) is not reported. - **Check:** the [Duo harness](../../dm/ios/tests/duo/README.md) tests the taller picture in Fit, in Fill and on a wider screen, and the production root view following a reported shape and returning to 16:9. Not yet run on a device. - **Found on:** [Breath of the Wild](../../dm/games/01007EF00011E000/README.md#screen-shape-dm_screen_aspect-current) and [Animal Crossing: New Horizons](../../dm/games/01006F8002326000/README.md#screen-shape-dm_screen_aspect-current) with `DM_SCREEN_ASPECT=1.43`. + + +### Independent buffer dispatches serialize inside the copy encoder + +- **Symptom:** buffer-only compute dispatches serialize even when their complete read/write ranges are disjoint. +- **Cause:** the shared copy/compute encoder treats every dispatch as an unbounded write. +- **Fix:** opt-in `DM_NVN_CS_RANGES=1` tracks resolved uniform/storage-buffer ranges and preserves RAW, WAR and WAW dependencies with copies and dispatches. Unknown bindings, indirect dispatch, image access, sparse aliases, unresolved dummy-buffer bindings and capacity exhaustion retain conservative ordering. `ab` uses the existing A/B phases. +- **Check:** `check_t_cs_ranges` passes 6,986 checks in each encoding mode under Metal validation on upstream `e3ad8255`. Historical game measurements predate this extraction; no new full gameplay regression is claimed. +- **Found on:** [Ocarina of Time](../../dm/games/0400486024DEC000/README.md#bounded-compute-ordering-experimental).