From 1baeb120d71775ae9b4896ffb2e8a3fce4805fba Mon Sep 17 00:00:00 2001 From: Roan de Graaf Date: Thu, 12 Nov 2026 15:00:42 +0100 Subject: [PATCH 1/2] nvn/views: cache texture views by Metal texture behind the serial cache Texture views are also cached by the Metal texture they are made of, behind the cache by the game's texture object: a view asked for through a new texture object over the same storage, or through the ID of a finalized one, is the one made before (vb_get / vb_put; an entry leaves when the host retires the Metal texture through defer_obj_at, or after 120 frames unused; textures uploaded from guest memory stay out). 0400486024DEC000 makes its render targets on new texture objects every frame and made 77 views a frame of 39 Metal textures that stayed, 0.9 ms of the replay thread while the GPU waits for it at each frame's start: none in three consecutive frames now, the replay's CPU 7.1-7.9 -> 6.1-6.3 ms a frame. In a GPU-bound village scene (about 2,910 draws) 52.6-52.7 -> 53.0-53.2 fps with the view cache alone, 54.4-54.6 with enc_thread on in its profile as well (Apple M4 Pro, headless, three runs a side, measured on ced36121). The field scene first measured (52.2-53.4 -> 56.5-56.9 fps on 8db5dd45) holds 60 fps on later bases with or without the change. t_view_cache checks the reuse, the retire, the ageing and the uploaded textures through tex_by_id. Rebased on main: the game note keeps main's draw_barriers row and loses render_cond (removed on main); all Metal texture releases, including the resource owner's (own_hook_drop), still go through defer_obj_at, where vb_drop sits. t_view_cache asks the resource owner (own_alias_each_locked) whether a texture is shared, as the sharing table moved there. --- dm/games/0400486024DEC000/README.md | 4 + dm/games/0400486024DEC000/game.tsv | 3 + dm/gfx/nvn/nvn_mtl.m | 49 ++++++++++- dm/gfx/tests/Makefile | 3 + dm/gfx/tests/t_view_cache.m | 131 ++++++++++++++++++++++++++++ docs/agents/symptoms.md | 1 + docs/reference/frame-rate.md | 10 +++ 7 files changed, 198 insertions(+), 3 deletions(-) create mode 100644 dm/gfx/tests/t_view_cache.m diff --git a/dm/games/0400486024DEC000/README.md b/dm/games/0400486024DEC000/README.md index 1487d7b177..919340d885 100644 --- a/dm/games/0400486024DEC000/README.md +++ b/dm/games/0400486024DEC000/README.md @@ -11,6 +11,7 @@ A Switch 2 game: update v131072, SDK 22.2.8 (`Ounce`). Nintendo EPD's engine (se | `sys_resource 0x3000000` | `game.tsv` | 48 MB, as the NPDM declares | | Dynamic-resolution stub | [`patches.py`](patches.py) (frame step rule, `others`) | full resolution unless the launcher's Dynamic resolution is on ([Dynamic resolution](#dynamic-resolution)) | | `draw_barriers game` | `game.tsv` | about 180 full barriers a frame NVN does not ask for: GPU 25 → 18 ms at full resolution. From 7f50222 until the fix in [Draw passes that wait for each other again while images share memory](../../../docs/reference/frame-rate.md#draw-passes-that-wait-for-each-other-again-while-images-share-memory) it had no effect, since the dynamic resolution's family heaps turned it off; with the fix, M1 Max gameplay GPU 22.2 → 20.3 ms; no change on an M2 Air or an M4 Pro | +| `enc_thread on` | `game.tsv` | the game parks each frame's submissions behind an event its CPU signals when the frame before has left the GPU, so the GPU starts every frame dry and waits for the replay; with encoding on its own thread 56.5–56.9 against 55.3–55.8 fps in a GPU-bound scene ([Frame rate](#frame-rate)). | | `tex_flush_upload on`, `tex_dirty_upload on` | `game.tsv` | as Tears of the Kingdom: the CPU writes the terrain tiles' height (R32F), blend and hole (RGBA8) maps into textures after creating them. Without the keys those textures stay zero: flat blue holes in the ground around the path with grass floating in them, and grey stone where the console shows dirt | | `shader_groups`, `shader_note` | `game.tsv` | shaders grouped as `/Shader/`, `/Effect/`, `/Lib/`, `/UI/` | | `pad_layout full` | `game.tsv` | a 3D field and both sticks | @@ -32,6 +33,8 @@ One [NUP container](../../../docs/development.md#the-packing-script-in-detail) o Measured on an M6 Mac with 16 GB, headless, on one walk with camera turns (`walk.sh` in the work folder). - Current on an M5 Pro MacBook Pro (16-inch, 20-core GPU, 24 GB, macOS 27.2, 2026-11-09), `kokiri-deck` from a deck autosave with the full library of chain `dedc9391c30b`, at full resolution (Dynamic resolution off), two runs a variant: in a window a locked 60 fps (59.8–60.0, frame p99 16.8–19.4 ms, GPU p50 10.2 ms). In fullscreen on its ProMotion screen it held 40 fps (39.6–40.1) at the same GPU time, with every present a 120 Hz refresh late and every other link tick skipped: [The 60 Hz link at 40 fps in fullscreen on a ProMotion screen](../../../docs/reference/frame-rate.md#the-60-hz-link-at-40-fps-in-fullscreen-on-a-promotion-screen). With the 120 Hz link there, 58.8–59.6 fps, frame p99 25.3 ms; with the screen held at its fixed 60 Hz mode, 60.0 fps, frame p99 16.9 ms, which fullscreen now switches to. MetalFX present upscaling to the 3456-wide fullscreen cost no measurable GPU time (59.4–59.7 fps). Resident about 10 GB, GPU allocated 11.2–11.4 GB; the prepare step took 7.3 s on a first start. +- Current on an M4 Pro (20-core GPU, 24 GB, macOS 27.2, 2026-11-10, chain `cb2e91c138e3`, full resolution, `DM_FPS_HOLD=off`), headless from a save on the castle town drawbridge looking over Hyrule Field (about 2,720 draws a frame): the game's own GPU time is 14.5–15.0 ms a frame, and it ran at 52.2–53.4 fps, not 60; 56.5–56.9 fps since the two changes below. + - GPU idle at each frame's start. The game submits the whole next frame, about 23 submissions on several queues, some 8 ms before the current frame's GPU work ends; queue 1's first piece waits for an event the CPU signals 0.2 ms after the frame's fence. The replay thread sits idle those 8 ms and translates only from the signal on, the whole frame in about 6 ms, while the GPU's first 5 ms of light passes wait for it. Per frame the game had no command buffer on the GPU for 2.03–2.19 ms, nearly all of it before a buffer committed after the GPU ran dry. Measured steps, headless, three runs a side unless said: `enc_thread on` 2.1 → 1.3–1.6 ms; [texture views by Metal texture](../../../docs/reference/frame-rate.md#texture-views-made-again-every-frame-for-render-targets-on-new-texture-objects) 1.4–1.8 → 1.16–1.20 ms (two runs), the replay's CPU 7.1–7.9 → 6.1–6.3 ms a frame. Frame rate in the same scene: 52.2–53.4 fps before both, 55.3–55.8 with the view cache, 56.5–56.9 with both. Disproved: smaller segments (`DM_NVN_CUT=16` / `8`) move the wait and leave its total (1.84–1.91 ms; 1.30–1.39 with the encode thread); the replay thread not waiting for the encode thread at each submission's end changed nothing once the views were cached (1.24–1.25 against 1.16–1.20 ms). Not tried: translating the parked submissions before the signal. The wait is there so that the frame before has landed (its occlusion results, which the replay reads, and the lighting buffer the CPU clears), so a replay ahead of it would read stale memory. Open: 1.2 ms of idle a frame, the replay's remaining cost (pool tables 0.5 ms a frame in `pool_gpu`'s copies, argument encoding, mesh task draws). - Current: the title and menu, a movie behind them, are a locked 60 fps (p50 16.67 ms, GPU span 15.6 ms). - Resolved: the title movie and the cutscene movies stuttered in small regular jerks at that steady 60 fps on a Mac that decodes AV1 with dav1d (M1, M2). The frames were on time and the movie's pictures were not: the player's `advance` (`main+0x3b61ea0`) found no new picture in 546 and 569 of about 2,900 frames of the title on an M2 Pro, and showed the last one again. Two causes, both general: [packets decoded inside the submission](../../../docs/reference/movies.md#nncodec-packets-decoded-inside-the-submission), on the player's one reader thread, which also gives the shown pictures back, and [dav1d one frame at a time](../../../docs/reference/movies.md#dav1d-decoded-one-frame-at-a-time) (15.4 ms a packet in the movie's heaviest five seconds, 122 ms the longest). After: 0 or 1 in 2,567 to 3,036 frames a run (eight runs of 54 s, headless, `DM_PROBE=main:3b61ed8,main:3b61f80` counting the failed and the good calls), and `DecodeAsync` returns in 0.1 ms at the median and 1.1 ms at the 99th percentile, from 1.9 and 120 ms. Open: not run on an M1 or M2 with four performance cores, nor on an iPad; a Mac with a hardware AV1 decoder (M3 on) decodes with VideoToolbox, where only the first cause applied, not measured. - Game speed: the game steps its time by a frame ratio, its base rate (60, or 30) / its int frame rate, whatever the frame took (`main+0x6e6cc4` on v131072), so frames longer than a vsync played in slow motion (seen by the user on a slower Mac; [issue 1375](https://github.com/seedds/nxnative/issues/1375)'s M1 Max ran the title at about 28 fps). With `fps_target 60` the ratio is the host's frame step × base / 60 ([A fixed frame step plays in slow motion on a slow Mac](../../../docs/reference/frame-rate.md#a-fixed-frame-step-plays-in-slow-motion-on-a-slow-mac)), a stub placed by its function's fingerprint ([`patches.py`](patches.py)). Mac runs on the M6 (2026-11-08, a test host on the libraries of chain `3ee493b2c3a4`): the user's play sessions held 60 fps with 2- and 3-vsync holds while areas loaded, game time 1.000 of real time by the host's count. That count is the stub's own; no run on a Mac slow enough to show the slow motion before and after. @@ -138,6 +141,7 @@ Its 37 kernels that correct samples, NDSR's network among them, gave about 0.25 - [The blend helper's output reference on iOS](../../../docs/reference/shaders.md#the-blend-helpers-output-reference-on-ios): resolved, 22,296 of 42,848 Mac shaders failed to compile on macOS 26 ([GitHub issue #2272](https://github.com/seedds/nxnative/issues/2272)); the Mac compile now names the host's minimum macOS. - [A NaN colour under a zero blend weight](../../../docs/reference/shaders.md#a-nan-colour-under-a-zero-blend-weight): resolved, white clouds over the ground mist between Kokiri Forest and Hyrule Field and over the ferns at the camera in Kokiri Forest ([issue #1839](https://github.com/seedds/nxnative/issues/1839)). The mist shader `5ad65c0eefd09c7f` writes NaN at alpha 0 where its layer has density 0; NVIDIA's blender, with the option NVN's driver sets, adds nothing there, Apple's stored the NaN. - [A first start builds every base of the prewarm list before the first frame](../../../docs/reference/rendering.md#a-first-start-builds-every-base-of-the-prewarm-list-before-the-first-frame): the 450-475 s first-start prepare on an M5 Max; the Mac app now bundles the list's pipelines (`--prebake`, on by default) and it took 4.3 s. +- [Texture views made again every frame for render targets on new texture objects](../../../docs/reference/frame-rate.md#texture-views-made-again-every-frame-for-render-targets-on-new-texture-objects): 77 Metal texture views a frame of 39 textures that stayed, 0.9 ms of the replay thread at each frame's start, where the GPU waits for it; 52.2–53.4 → 55.3–55.8 fps in a GPU-bound Hyrule Field scene. - [The 60 Hz link at 40 fps in fullscreen on a ProMotion screen](../../../docs/reference/frame-rate.md#the-60-hz-link-at-40-fps-in-fullscreen-on-a-promotion-screen): 40 fps in fullscreen on an M5 Pro MacBook Pro with the GPU at 10 ms of the 16.7, every present one 120 Hz refresh late and every other display-link tick skipped; the screen's fixed 60 Hz mode held 60.0 fps there and fullscreen now switches to it, with the 120 Hz link (59 fps) for screens with no such mode. - [The shader package and the shader map come from different splits](../../../docs/reference/packing.md#the-shader-package-and-the-shader-map-come-from-different-splits): resolved, a black screen with sound in a build through NX2Apple ([issue #1841](https://github.com/seedds/nxnative/issues/1841)); the present pass was translated from a terrain shader's record. Records now carry their keys, and the shader build finds them by key. - [Native mesh pipelines compiled at their first draw](../../../docs/reference/shaders.md#native-mesh-pipelines-compiled-at-their-first-draw): resolved. The foliage, shadows and enemies drawn with task and mesh shaders stalled at their first draw on a cold Metal cache (59.5 s of builds at the Kokiri Forest entry on an M5 Max, one frame of 42.9 s), as nothing recorded or kept their pipelines; `pso_manifest.tsv` now carries 164 `M` rows (Kokiri Forest, Hyrule Field, Castle Town, Hyrule Castle, and 41 from later play, Death Mountain Trail among it), and with the prepare step they are built before the first frame. Pipelines outside the list still stall once, then go into `pso_user.tsv`. With the first 123 alone, a cold first start (empty Metal cache and pipeline archive, M4 Pro) on a Death Mountain Trail save built 9 and 10 at their first draw in two runs, 2.7 and 4.2 s, frames of 1,775 and 1,657 ms; with all 164, none, worst frame 25.6 and 18.5 ms, the prepare step 29.6 and 29.3 s → 32.1 and 31.0 s. diff --git a/dm/games/0400486024DEC000/game.tsv b/dm/games/0400486024DEC000/game.tsv index 45ccc5ed9e..8cd0591bec 100644 --- a/dm/games/0400486024DEC000/game.tsv +++ b/dm/games/0400486024DEC000/game.tsv @@ -46,3 +46,6 @@ draw_barriers game # As Tears of the Kingdom: the terrain's height, blend and hole maps are written by the CPU into textures after they are created. Without these keys they stay zero: holes in the ground and the wrong materials tex_flush_upload on tex_dirty_upload on +# The game submits a frame's commands behind an event its CPU signals once the frame before has left the GPU, so the GPU starts each frame with nothing queued and waits for the +# replay: with Metal encoding on its own thread a GPU-bound Hyrule Field scene went 55.3-55.8 -> 56.5-56.9 fps (Apple M4 Pro, three runs a side, interleaved) +enc_thread on diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index ca824c221c..bd654bee8b 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -496,10 +496,12 @@ @implementation NvDeferredRelease @end // Previously only the former existed: when the view cache was invalidated, a texture that 'is still the current storage of some serial' was also removed from the residency set. Invalidation used to happen only when the base texture was really replaced, so it was never hit; // after the transparency chain's in-place composite swapped the storage of two textures, each of the two live textures was removed once this way, and afterwards they are used as attachments and sampled every frame as usual - the GPU accesses non-resident memory. static void defer_kick(void); +static void vb_drop(const void *base); // Most objects wait for the next submission's fence. A caller that knows no submission still to come can reach the object passes an earlier one (mtl_pool_del); a fence the GPU has // already passed is then drained at once (defer_kick), as no feedback handler is left to do it static void defer_obj_at(id obj, int keep_resident, uint64_t fence) { if (!obj) return; + if (!keep_resident) vb_drop((__bridge const void *)obj); NvDeferredRelease *d = [NvDeferredRelease new]; d->object = obj; d->fence = fence; d->keep_resident = keep_resident; pthread_mutex_lock(&g_deferred_mu); if (!g_deferred) g_deferred = [NSMutableArray array]; @@ -6433,8 +6435,48 @@ static void vc_put(uint64_t ser, const void *pool, const vc_key *k, idview[i]) { defer_obj_unref((__bridge id)s->view[i]); CFRelease(s->view[i]); } s->k[i] = *k; s->view[i] = (void *)CFBridgingRetain(v); g_vc_new++; } +// Views by the Metal texture they are made of, behind the cache by texture above, whose entries go with the game's texture object. A game that makes its render targets on new +// texture objects every frame over storage that stays, or finalizes the objects and keeps their IDs, missed that cache for every view every frame: Ocarina of Time made 77 views +// a frame of 39 Metal textures that were the same ones each frame, 0.9 ms of the replay thread. A view holds its parent, so an entry goes when the host retires the Metal texture +// (defer_obj_at: its recycled heap waits for the texture to be freed, rh_take) or has gone VB_AGE frames unused. Not for textures uploaded from guest memory: a finalized one +// is uploaded again as a new Metal texture, and its views would hold every upload. Its own lock, taken last +enum { VB_AGE = 120, VB_MAX = 4096 }; +typedef struct { vc_key k[VC_WAYS]; void *view[VC_WAYS]; unsigned next; uint64_t used; } vb_set; // view: retained +static nvn_hmap g_vb = {.klen = 8}; // Metal texture → vb_set +static os_unfair_lock g_vb_lk = OS_UNFAIR_LOCK_INIT; static uint64_t g_vb_swept; static _Atomic uint64_t g_vb_hit; +static void vb_set_free(void *p) { vb_set *s = p; for (int i = 0; i < VC_WAYS; i++) if (s->view[i]) { defer_obj_unref((__bridge id)s->view[i]); CFRelease(s->view[i]); } free(s); } +static void vb_drop(const void *base) { + if (!g_vb.n) return; + os_unfair_lock_lock(&g_vb_lk); vb_set *s = nvn_hm_del(&g_vb, &base); os_unfair_lock_unlock(&g_vb_lk); + if (s) vb_set_free(s); +} +static id vb_get(id base, const vc_key *k, uint64_t frame) { + const void *b = (__bridge const void *)base; id v = nil; + os_unfair_lock_lock(&g_vb_lk); + vb_set *s = nvn_hm_get(&g_vb, &b); + for (int i = 0; s && i < VC_WAYS; i++) if (s->view[i] && !memcmp(&s->k[i], k, sizeof *k)) { v = (__bridge id)s->view[i]; s->used = frame; break; } + os_unfair_lock_unlock(&g_vb_lk); + if (v) atomic_fetch_add(&g_vb_hit, 1); + return v; +} +static void vb_put(id base, const vc_key *k, id v, uint64_t frame) { + const void *b = (__bridge const void *)base; void *old = NULL, **gone = NULL; unsigned ngone = 0; + os_unfair_lock_lock(&g_vb_lk); + if (frame >= g_vb_swept + VB_AGE || g_vb.n >= VB_MAX) { // entries unused for VB_AGE frames, or all of them at the cap + g_vb_swept = frame; gone = malloc(sizeof *gone * (g_vb.n ? g_vb.n : 1)); + for (uint32_t i = 0; gone && i < g_vb.cap;) { vb_set *e = g_vb.vals[i]; + if (e && (e->used + VB_AGE < frame || g_vb.n >= VB_MAX)) { const void *key; memcpy(&key, g_vb.keys + (size_t)i * 8, 8); nvn_hm_del(&g_vb, &key); gone[ngone++] = e; } else i++; } // a delete moves later entries back into slot i + } + vb_set *s = nvn_hm_get(&g_vb, &b); + if (!s && (s = calloc(1, sizeof *s))) nvn_hm_put(&g_vb, &b, s); + if (s) { unsigned i = s->next++ % VC_WAYS; old = s->view[i]; s->k[i] = *k; s->view[i] = (void *)CFBridgingRetain(v); s->used = frame; } + os_unfair_lock_unlock(&g_vb_lk); + if (old) { defer_obj_unref((__bridge id)old); CFRelease(old); } + for (unsigned i = 0; i < ngone; i++) vb_set_free(gone[i]); + free(gone); +} void mtl_vc_drop(uint64_t ser) { os_unfair_lock_lock(&g_rmu); vc_set *s = nvn_hm_del(&g_vc, &ser); if (s) vc_set_free(s); os_unfair_lock_unlock(&g_rmu); } -void mtl_vc_stats(unsigned *n, uint64_t *hit, uint64_t *made) { os_unfair_lock_lock(&g_rmu); *n = g_vc.n; *hit = g_vc_hit; *made = g_vc_new; os_unfair_lock_unlock(&g_rmu); } +void mtl_vc_stats(unsigned *n, uint64_t *hit, uint64_t *made) { os_unfair_lock_lock(&g_rmu); *n = g_vc.n; *hit = g_vc_hit + atomic_load(&g_vb_hit); *made = g_vc_new; os_unfair_lock_unlock(&g_rmu); } static void tb2_gone_clear(void); static void vc_drop_pool(const void *pool) { // caller holds g_rmu tb2_gone_clear(); @@ -6754,11 +6796,12 @@ static int treg_swizzle(const treg_t *r, MTLPixelFormat base_pf, int in_place, u if (fits) { s0 *= 6; ns *= 6; } else tt = MTLTextureType2DArray; } vc_key k; memset(&k, 0, sizeof k); k.pf = pf; k.tt = (uint8_t)tt; k.l0 = (uint32_t)l0; k.nl = (uint32_t)nl; k.s0 = (uint32_t)s0; k.ns = (uint32_t)ns; memcpy(k.sw, sw, 4); - if (!(v = vc_get(rp->t.serial, &k, base))) { + uint64_t vb_f = atomic_load(&g_cur_frame); int vb_on = !rp->view_pkg; + if (!(v = vc_get(rp->t.serial, &k, base)) && !(vb_on && (v = vb_get(base, &k, vb_f)))) { v = need_sw ? [base newTextureViewWithPixelFormat:(MTLPixelFormat)pf textureType:tt levels:NSMakeRange(l0, nl) slices:NSMakeRange(s0, ns) swizzle:MTLTextureSwizzleChannelsMake(sw[0], sw[1], sw[2], sw[3])] : [base newTextureViewWithPixelFormat:(MTLPixelFormat)pf textureType:tt levels:NSMakeRange(l0, nl) slices:NSMakeRange(s0, ns)]; if (!v) { RED_ONCE(11, "cannot create texture view id %d", tid); v = base; } - else vc_put(rp->t.serial, rp->t.pool, &k, v); + else { vc_put(rp->t.serial, rp->t.pool, &k, v); if (vb_on) vb_put(base, &k, v, vb_f); } } } if (rp->retired && rp->transient_sub != g_sub_serial) { diff --git a/dm/gfx/tests/Makefile b/dm/gfx/tests/Makefile index f2d290f841..bdde30b2e8 100644 --- a/dm/gfx/tests/Makefile +++ b/dm/gfx/tests/Makefile @@ -492,6 +492,9 @@ t_serial_owner: t_serial_owner.m ../nvn/nvn_owner.m ../nvn/nvn_owner.h ../nvn/nv t_partial_upload: t_partial_upload.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_partial_upload.m $(MTL_T_SRC) $(FW) check_t_partial_upload: RUN_ENV = MTL_DEBUG_LAYER=1 +t_view_cache: t_view_cache.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ t_view_cache.m $(MTL_T_SRC) $(FW) +check_t_view_cache: RUN_ENV = MTL_DEBUG_LAYER=1 t_srgb_alias: t_srgb_alias.m $(MTL_T_DEP) clang $(CFLAGS) -fobjc-arc -o $@ t_srgb_alias.m $(MTL_T_SRC) $(FW) check_t_srgb_alias: RUN_ENV = MTL_DEBUG_LAYER=1 diff --git a/dm/gfx/tests/t_view_cache.m b/dm/gfx/tests/t_view_cache.m new file mode 100644 index 0000000000..fc7afe2e9a --- /dev/null +++ b/dm/gfx/tests/t_view_cache.m @@ -0,0 +1,131 @@ +// Texture views by the Metal texture they are made of (vb_get / vb_put in nvn_mtl.m), behind the cache by texture object, through the production lookup (tex_by_id): a view asked +// for again through a new texture object over the same storage, or through an ID whose object was finalized, is the one made before; an entry goes when the host retires the Metal +// texture (here: another description takes its storage, alias_take_over) and when it has gone VB_AGE frames unused; a texture uploaded from guest memory stays out of the cache. +// Ocarina of Time made 77 views a frame of 39 Metal textures that stayed (docs/reference/frame-rate.md) +#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 (line %d)\n", label, __LINE__); } } while (0) + +static tex_t tex(uint64_t serial, NVNformat format, int w) { + tex_t t = {.magic = MAGIC('T','E','X',0), .serial = serial}; + t.d = (nvn_texdesc){.target = NVN_TEXTURE_TARGET_2D, .format = format, .width = w, .height = w, .depth = 1, .levels = 1, .samples = 1}; + nvn_tex_layout(&t.d, &t.L); + return t; +} +static view_t swizzle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { view_t v = {0}; v.set_swizzle = 1; v.swz[0] = r; v.swz[1] = g; v.swz[2] = b; v.swz[3] = a; return v; } +static id view_of(int tid) { os_unfair_lock_lock(&g_rmu); id v = tex_by_id(tid); os_unfair_lock_unlock(&g_rmu); return v; } +static int cached(id base) { const void *b = (__bridge const void *)base; os_unfair_lock_lock(&g_vb_lk); int r = nvn_hm_get(&g_vb, &b) != NULL; os_unfair_lock_unlock(&g_vb_lk); return r; } +static int shared(id t) { __block int r = 0; pthread_mutex_lock(&g_smu); own_alias_each_locked(^(const alias_key *k, id o) { (void)k; r |= o == t; }); pthread_mutex_unlock(&g_smu); return r; } +static uint64_t reused(void) { unsigned n; uint64_t hit, made; mtl_vc_stats(&n, &hit, &made); return hit; } +static uint64_t made(void) { unsigned n; uint64_t hit, m; mtl_vc_stats(&n, &hit, &m); return m; } +static void next_submission(void) { CHECK(mtl_wait(mtl_sub_commit(), 5000000000ull), "submission completes"); mtl_sub_begin(); } +enum { SW_R = MTLTextureSwizzleRed, SW_1 = MTLTextureSwizzleOne, SW_0 = MTLTextureSwizzleZero }; + +static void new_object_reuses_view(void) { + tex_t a = tex(93001, NVN_FORMAT_R32F, 64), b = tex(93002, NVN_FORMAT_R32F, 64); + view_t rrr1 = swizzle(SW_R, SW_R, SW_R, SW_1), r001 = swizzle(SW_R, SW_0, SW_0, SW_0); + mtl_tex_init(&a); mtl_reg_tex(1, &a, &rrr1); + id ta = tex_mtl(&a); + uint64_t hit0 = reused(), made0 = made(), vb0 = atomic_load(&g_vb_hit); + id v1 = view_of(1); + CHECK(ta && v1 && v1 != ta && v1.parentTexture == ta, "a swizzled descriptor gets a view of the object's Metal texture"); + CHECK(cached(ta) && made() == made0 + 1 && reused() == hit0, "the first ask makes the view and enters it by Metal texture"); + mtl_tex_release(&a); + CHECK(!g_treg[1].view && !nvn_hm_get(&g_vc, &a.serial), "finalizing the object drops its descriptor's view and its entry by texture object"); + CHECK(view_of(1) == v1 && atomic_load(&g_vb_hit) == vb0 + 1, "the ID of a finalized object gets the view made before"); + mtl_tex_init(&b); mtl_reg_tex(1, &b, &rrr1); + CHECK(tex_mtl(&b) == ta, "a new object over the same storage resolves to the same Metal texture"); + CHECK(view_of(1) == v1 && atomic_load(&g_vb_hit) == vb0 + 2, "and gets the view made before"); + CHECK(made() == made0 + 1 && reused() == hit0 + 2, "no view made for either, and both counted as reused"); + mtl_reg_tex(2, &b, &r001); + id v2 = view_of(2); + CHECK(v2 && v2 != v1 && v2.parentTexture == ta && made() == made0 + 2 && atomic_load(&g_vb_hit) == vb0 + 2, "another swizzle of the same texture is another view"); + mtl_tex_release(&b); tex_t c = tex(93003, NVN_FORMAT_R32F, 64); mtl_tex_init(&c); + mtl_reg_tex(1, &c, &rrr1); mtl_reg_tex(2, &c, &r001); + CHECK(view_of(1) == v1 && view_of(2) == v2 && atomic_load(&g_vb_hit) == vb0 + 4, "a texture holds several views, each found by its own parameters"); + defer_obj_unref(ta); + CHECK(cached(ta), "dropping one reference to the texture (defer_obj_unref) leaves its views"); + mtl_reg_tex(1, NULL, NULL); mtl_reg_tex(2, NULL, NULL); mtl_tex_release(&c); +} +static void retired_texture_leaves(void) { + tex_t a = tex(93011, NVN_FORMAT_R32F, 128), other = tex(93012, NVN_FORMAT_RG16F, 128), again = tex(93013, NVN_FORMAT_R32F, 128); + view_t rrr1 = swizzle(SW_R, SW_R, SW_R, SW_1); + mtl_tex_init(&a); mtl_reg_tex(3, &a, &rrr1); + id ta = tex_mtl(&a), v1 = view_of(3); + CHECK(ta && v1.parentTexture == ta && cached(ta), "a view entered by Metal texture"); + mtl_reg_tex(3, NULL, NULL); mtl_tex_release(&a); + for (int i = 0; i <= ALIAS_IDLE; i++) next_submission(); + CHECK(cached(ta) && shared(ta), "the entry stays while the host keeps the texture for its storage"); + mtl_tex_init(&other); + CHECK(tex_mtl(&other) && !shared(ta), "another description takes the storage and the host retires the texture"); + CHECK(!cached(ta), "a retired texture's views go with it"); + uint64_t vb0 = atomic_load(&g_vb_hit), made0 = made(); + mtl_tex_init(&again); mtl_reg_tex(3, &again, &rrr1); + id tn = tex_mtl(&again), v2 = view_of(3); + CHECK(tn && tn != ta && v2 && v2 != v1 && v2.parentTexture == tn, "the next object over the storage gets a view of its own Metal texture"); + CHECK(atomic_load(&g_vb_hit) == vb0 && made() == made0 + 1, "made, not reused"); + mtl_reg_tex(3, NULL, NULL); mtl_tex_release(&other); mtl_tex_release(&again); +} +static void unused_entry_ages_out(uint64_t f0) { + tex_t used = tex(93021, NVN_FORMAT_R32F, 32), used2 = tex(93022, NVN_FORMAT_R32F, 32), idle = tex(93023, NVN_FORMAT_R32F, 16), idle2 = tex(93024, NVN_FORMAT_R32F, 16), late = tex(93025, NVN_FORMAT_R32F, 8); + view_t rrr1 = swizzle(SW_R, SW_R, SW_R, SW_1); + mtl_set_frame(f0); + mtl_tex_init(&used); mtl_tex_init(&idle); mtl_reg_tex(4, &used, &rrr1); mtl_reg_tex(5, &idle, &rrr1); + id tu = tex_mtl(&used), ti = tex_mtl(&idle), vu = view_of(4), vi = view_of(5); + CHECK(tu && ti && tu != ti && cached(tu) && cached(ti), "two textures' views entered in the same frame"); + mtl_tex_release(&used); mtl_tex_release(&idle); + mtl_set_frame(f0 + VB_AGE); + mtl_tex_init(&late); mtl_reg_tex(6, &late, &rrr1); + CHECK(view_of(6) && cached(ti), "an entry unused for exactly VB_AGE frames stays"); + mtl_tex_init(&used2); mtl_reg_tex(4, &used2, &rrr1); + CHECK(view_of(4) == vu, "one of the two is asked for again in that frame, through a new object"); + mtl_set_frame(f0 + 2 * VB_AGE); + view_t r001 = swizzle(SW_R, SW_0, SW_0, SW_0); mtl_reg_tex(6, &late, &r001); + id tl = tex_mtl(&late); + CHECK(view_of(6) && cached(tl), "a view made later enters the cache"); + CHECK(!cached(ti), "the entry unused for more than VB_AGE frames is gone"); + CHECK(cached(tu), "the one used since stays"); + uint64_t vb0 = atomic_load(&g_vb_hit); + mtl_tex_init(&idle2); mtl_reg_tex(5, &idle2, &rrr1); + id vi2 = view_of(5); + CHECK(tex_mtl(&idle2) == ti && vi2 && vi2 != vi && vi2.parentTexture == ti && atomic_load(&g_vb_hit) == vb0, "its texture's next view is made again"); + mtl_reg_tex(4, NULL, NULL); mtl_reg_tex(5, NULL, NULL); mtl_reg_tex(6, NULL, NULL); + mtl_tex_release(&used2); mtl_tex_release(&idle2); mtl_tex_release(&late); +} +// As tex_mtl leaves a texture uploaded from guest memory: an NvPkg in the serial table, clean since its upload, which two texture objects over the same bytes share (pkg_shared) +static void uploaded_stays_out(void) { + static uint8_t pixels[64]; + tex_t a = tex(93031, NVN_FORMAT_RGBA8, 4), b = tex(93032, NVN_FORMAT_RGBA8, 4); + a.has_layout = b.has_layout = 1; a.mem = b.mem = pixels; + MTLTextureDescriptor *d = tex_desc(&a, 1); d.storageMode = MTLStorageModeShared; + id base = [g_dev newTextureWithDescriptor:d]; + [base replaceRegion:MTLRegionMake2D(0, 0, 4, 4) mipmapLevel:0 withBytes:pixels bytesPerRow:16]; + NvPkg *pk = [NvPkg new]; pk->tex = base; pk->span = pixels; pk->seen = nvn_dirty_now(); + serial_put(a.serial, pk); serial_put(b.serial, pk); + view_t bgra = swizzle(MTLTextureSwizzleBlue, MTLTextureSwizzleGreen, MTLTextureSwizzleRed, MTLTextureSwizzleAlpha); + os_unfair_lock_lock(&g_vb_lk); uint32_t n0 = g_vb.n; os_unfair_lock_unlock(&g_vb_lk); + uint64_t vb0 = atomic_load(&g_vb_hit); + mtl_reg_tex(7, &a, &bgra); mtl_reg_tex(8, &b, &bgra); + id va = view_of(7), vb = view_of(8); + CHECK(base && va && va != base && va.parentTexture == base && g_treg[7].view_pkg, "an uploaded texture's swizzled descriptor gets a view of the upload"); + CHECK(vb && vb.parentTexture == base && vb != va, "another object over the same upload gets a view of its own"); + os_unfair_lock_lock(&g_vb_lk); uint32_t n1 = g_vb.n; os_unfair_lock_unlock(&g_vb_lk); + CHECK(!cached(base) && n1 == n0 && atomic_load(&g_vb_hit) == vb0, "an uploaded texture's views are neither entered by Metal texture nor found there"); + mtl_reg_tex(7, NULL, NULL); mtl_reg_tex(8, NULL, NULL); serial_del(a.serial); serial_del(b.serial); +} + +int main(void) { @autoreleasepool { + mtl_init(); mtl_sub_begin(); + mtl_set_frame(1000); + new_object_reuses_view(); + retired_texture_leaves(); + unused_entry_ages_out(2000); + uploaded_stays_out(); + next_submission(); defer_drain(); + printf("t_view_cache: %d checks, %d failed\n", checks, failed); return failed != 0; +} } diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index 2df94ddc79..c827f11832 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -573,6 +573,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - 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) - a game that reads textures through a pool (Shaders report which textures they read through a pool) renders far below its maximum dynamic resolution: Ocarina of Time's main pass at 763x429 with the GPU at 17 ms a frame. → [A host's own store in a fragment shader moves its depth test](../reference/frame-rate.md#a-hosts-own-store-in-a-fragment-shader-moves-its-depth-test) - passes that read textures through a pool (Shaders report which textures they read through a pool) cost far more GPU time than their texture reads explain, most on an iPad: Ocarina of Time's colour pass about 13 ms on an iPad Pro M5, 6 times the Mac's, while its prepass cost 1.3 times. → [Pool marks queue on one word when they test it with an atomic load](../reference/frame-rate.md#pool-marks-queue-on-one-word-when-they-test-it-with-an-atomic-load) +- a GPU-bound game whose GPU still sits idle at the start of each frame, waiting for the replay; in a CPU sample of the replay thread, `newTextureViewWithPixelFormat:` under `tex_by_id` ← `pool_entry` ← `encode_args` (5 % of the thread, 0.9 ms a frame), and the log's `texture views by texture` line counting dozens of views made per frame for as long as the game runs. → [Texture views made again every frame for render targets on new texture objects](../reference/frame-rate.md#texture-views-made-again-every-frame-for-render-targets-on-new-texture-objects) - a busy scene runs far below what its GPU time allows, with the main thread busy for most of each second. The `pipelines up to frame` line shows archive lookups that found none in the thousands per 300 frames, at about 3 ms each, many draws with a hybrid pipeline, and `in flight 384`. Ocarina of Time's castle town market: 9,208 searches, 30.5 s in 300 frames, CPU translation 114 ms a frame. → [Archive searches repeated while the build table is full](../reference/frame-rate.md#archive-searches-repeated-while-the-build-table-is-full) - frames of 50–170 ms on entering an area, in every run again, although the prewarm lists and the pipeline archive hold everything the area draws. The long-frame line shows `new pipelines 0` or `1` with tens of milliseconds, and the `pipelines up to frame` line shows that time under `predictions`, with a hundred or more `archive lookups found` at about 1 ms each and as many `pulling pipelines made`, against one or two `draws with a hybrid pipeline`. Ocarina of Time's castle town: one prediction made 160 stand-ins in 104 ms, three predictions 244 in 191 ms. → [Pulling stand-ins made for predicted keys that are never drawn](../reference/frame-rate.md#pulling-stand-ins-made-for-predicted-keys-that-are-never-drawn) - frames of 30–150 ms as an area loads, with `new pipelines 0` and a long-frame line such as `texture uploads 31 first + 6 re-uploads, 235.0 MB / 23.7 ms`. With `DM_NVN_REUPLOADS=1` the same large texture is re-uploaded many times within a few frames, several times with the same `submission` number, each for a few written pages (`pages written since its upload: 7 of 2466`). → [A texture written while it is drawn read whole at every use](../reference/frame-rate.md#a-texture-written-while-it-is-drawn-read-whole-at-every-use) diff --git a/docs/reference/frame-rate.md b/docs/reference/frame-rate.md index 69f0b16947..4f82adbc00 100644 --- a/docs/reference/frame-rate.md +++ b/docs/reference/frame-rate.md @@ -647,6 +647,16 @@ Frame pacing: the host's frame step, engine frame limiters, present intervals an - **Result on Ocarina of Time, an M6:** no measurable change. Its 4,758 marked pixel shaders were rebuilt with each load over the same library (chain `f9f01e4f9994`), and the game was measured standing on the Kokiri Forest deck, 40 s a run. GPU p50 was 14.38 ms with either load (5 runs plain, 13.99–14.88; 4 atomic, 14.28–15.34). The pictures matched within run-to-run noise. The gain the contributor measured is on an iPad Pro M5 and is not checked here. - **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md), reported with the iPad figures by a contributor in [discussion #1789](https://github.com/seedds/nxnative/discussions/1789). +### Texture views made again every frame for render targets on new texture objects + +- **Symptom:** a GPU-bound game whose GPU still sits idle at the start of each frame, waiting for the replay; in a CPU sample of the replay thread, `newTextureViewWithPixelFormat:` under `tex_by_id` ← `pool_entry` ← `encode_args` (5 % of the thread, 0.9 ms a frame), and the log's `texture views by texture` line counting dozens of views made per frame for as long as the game runs. +- **Cause:** a view that only swizzles or reformats a texture is cached by the game's texture object (`vc_get`, by serial), and the entry goes when that object is finalized. A game that makes its render targets on new texture objects every frame over storage that stays, or finalizes the objects and keeps their texture IDs registered, never hits it, though the host resolves those objects to the same Metal textures frame after frame. Ocarina of Time: 77 views a frame of 39 Metal textures (depth, R11G11B10, R8 and R32F targets read through their format's swizzle), every one made again each frame. +- **Fix:** general: a second cache by the Metal texture itself, behind the first (`vb_get` / `vb_put` in `nvn_mtl.m`). A view holds its parent, so an entry goes when the host retires the Metal texture (`defer_obj_at`, so a recycled render-target heap is not kept waiting) or has gone 120 frames unused. Textures uploaded from guest memory stay out of it: a finalized one is uploaded again as a new Metal texture, and its views would hold every upload. +- **Measured:** Ocarina of Time on an M4 Pro, headless in a GPU-bound Hyrule Field scene: no view made in three consecutive frames (77 a frame before), 1,392–1,479 made in a whole 95 s run against 8,177; the replay's CPU 7.1–7.9 → 6.1–6.3 ms a frame (71–76 M → 59–61 M instructions); the time with no command buffer of the game on the GPU 1.4–1.8 → 1.16–1.20 ms a frame; 52.2–53.4 → 55.3–55.8 fps with encoding on the replay thread (three runs a side), pictures alike. +- **Check:** `make -C dm/gfx/tests GAME= check_t_view_cache` (a new texture object over the same storage, and the ID of a finalized one, get the view made before; the entry goes with a retired Metal texture and after 120 frames unused; an uploaded texture's views stay out), and `check_t_cpu_tex` (the descriptor and view lifetimes it checks hold). +- **Not checked:** other games (no `scripts/regress.py check` run: Ocarina of Time was the only game built on the Mac it was measured on); iOS. +- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md#frame-rate). + ### Archive searches repeated while the build table is full - **Symptom:** a busy scene runs far below what its GPU time allows, with the main thread busy for most of each second. The `pipelines up to frame` line shows archive lookups that found none in the thousands per 300 frames, at about 3 ms each, many draws with a hybrid pipeline, and `in flight 384`. Ocarina of Time's castle town market: 9,208 searches, 30.5 s in 300 frames, CPU translation 114 ms a frame. From 9e2d2626df90524a62bcd73dee5c77dccb3ed629 Mon Sep 17 00:00:00 2001 From: Roan de Graaf Date: Thu, 12 Nov 2026 15:01:16 +0100 Subject: [PATCH 2/2] nvn/queue: translate a frame parked on a CPU event before its signal replay_ahead: a queue parked on an event the game's CPU signals is translated before the signal, and the encode thread keeps what that sends to the Metal queue (commits, upload batches, event signals, queue blocks) in order until the wait is satisfied, so the GPU gets the work when and in the order the game gives it (nvn_queue.inc nq_worker, nvn_rec.h hold_*; profile key replay_ahead, DM_NVN_REPLAY_AHEAD; off by default, needs enc_thread). Only an event word the CPU has signalled 30 times and no command ever has is taken; the submit thread stops for the signal at any wait for held work, before a present and at a condition whose report is in flight; a thread that has waited for held work for 200 ms gets it to the GPU with a red line. On for 0400486024DEC000, which parks each frame's 23 submissions behind such an event: a GPU-bound scene of 2,940 draws 55.5-57.1 -> 59.6-59.8 fps, frame p50 17.2-17.7 -> 16.5-16.6 ms, the GPU work the same (Apple M4 Pro, headless, four and five runs in turn). t_replay_ahead checks the hold, the order, a plain-store signal, an event commands signal, and the limit Rebased on main: game.py takes the replay_ahead key beside main's notice that render_cond is ignored (the key and DM_GAME_RENDER_COND are gone on main); the profile keys table keeps main's draw_barriers row. The hold's waits (mtl_wait_at, up_wait_zero, rc_value, mtl_sub_begin) apply unchanged; main added no other GPU wait in nvn_mtl.m since. --- dm/games/0400486024DEC000/README.md | 3 + dm/games/0400486024DEC000/game.tsv | 3 + dm/games/README.md | 1 + dm/games/game.py | 4 + dm/gfx/nvn/hle_nvn.c | 1 + dm/gfx/nvn/nvn_mtl.h | 8 ++ dm/gfx/nvn/nvn_mtl.m | 37 ++++++- dm/gfx/nvn/nvn_queue.inc | 36 ++++++- dm/gfx/nvn/nvn_rec.h | 113 ++++++++++++++++++--- dm/gfx/tests/Makefile | 10 ++ dm/gfx/tests/t_replay_ahead.m | 146 ++++++++++++++++++++++++++++ docs/agents/symptoms.md | 1 + docs/env_switches.tsv | 1 + docs/reference/frame-rate.md | 15 +++ 14 files changed, 358 insertions(+), 21 deletions(-) create mode 100644 dm/gfx/tests/t_replay_ahead.m diff --git a/dm/games/0400486024DEC000/README.md b/dm/games/0400486024DEC000/README.md index 919340d885..48c5db4c28 100644 --- a/dm/games/0400486024DEC000/README.md +++ b/dm/games/0400486024DEC000/README.md @@ -12,6 +12,7 @@ A Switch 2 game: update v131072, SDK 22.2.8 (`Ounce`). Nintendo EPD's engine (se | Dynamic-resolution stub | [`patches.py`](patches.py) (frame step rule, `others`) | full resolution unless the launcher's Dynamic resolution is on ([Dynamic resolution](#dynamic-resolution)) | | `draw_barriers game` | `game.tsv` | about 180 full barriers a frame NVN does not ask for: GPU 25 → 18 ms at full resolution. From 7f50222 until the fix in [Draw passes that wait for each other again while images share memory](../../../docs/reference/frame-rate.md#draw-passes-that-wait-for-each-other-again-while-images-share-memory) it had no effect, since the dynamic resolution's family heaps turned it off; with the fix, M1 Max gameplay GPU 22.2 → 20.3 ms; no change on an M2 Air or an M4 Pro | | `enc_thread on` | `game.tsv` | the game parks each frame's submissions behind an event its CPU signals when the frame before has left the GPU, so the GPU starts every frame dry and waits for the replay; with encoding on its own thread 56.5–56.9 against 55.3–55.8 fps in a GPU-bound scene ([Frame rate](#frame-rate)). | +| `replay_ahead on` | `game.tsv` | the same event: the parked frame is translated before the signal and its commits held until it, so the GPU starts the frame with work queued (Kakariko Village 55.5-57.1 → 59.6-59.8 fps) | | `tex_flush_upload on`, `tex_dirty_upload on` | `game.tsv` | as Tears of the Kingdom: the CPU writes the terrain tiles' height (R32F), blend and hole (RGBA8) maps into textures after creating them. Without the keys those textures stay zero: flat blue holes in the ground around the path with grass floating in them, and grey stone where the console shows dirt | | `shader_groups`, `shader_note` | `game.tsv` | shaders grouped as `/Shader/`, `/Effect/`, `/Lib/`, `/UI/` | | `pad_layout full` | `game.tsv` | a 3D field and both sticks | @@ -35,6 +36,7 @@ Measured on an M6 Mac with 16 GB, headless, on one walk with camera turns (`walk - Current on an M5 Pro MacBook Pro (16-inch, 20-core GPU, 24 GB, macOS 27.2, 2026-11-09), `kokiri-deck` from a deck autosave with the full library of chain `dedc9391c30b`, at full resolution (Dynamic resolution off), two runs a variant: in a window a locked 60 fps (59.8–60.0, frame p99 16.8–19.4 ms, GPU p50 10.2 ms). In fullscreen on its ProMotion screen it held 40 fps (39.6–40.1) at the same GPU time, with every present a 120 Hz refresh late and every other link tick skipped: [The 60 Hz link at 40 fps in fullscreen on a ProMotion screen](../../../docs/reference/frame-rate.md#the-60-hz-link-at-40-fps-in-fullscreen-on-a-promotion-screen). With the 120 Hz link there, 58.8–59.6 fps, frame p99 25.3 ms; with the screen held at its fixed 60 Hz mode, 60.0 fps, frame p99 16.9 ms, which fullscreen now switches to. MetalFX present upscaling to the 3456-wide fullscreen cost no measurable GPU time (59.4–59.7 fps). Resident about 10 GB, GPU allocated 11.2–11.4 GB; the prepare step took 7.3 s on a first start. - Current on an M4 Pro (20-core GPU, 24 GB, macOS 27.2, 2026-11-10, chain `cb2e91c138e3`, full resolution, `DM_FPS_HOLD=off`), headless from a save on the castle town drawbridge looking over Hyrule Field (about 2,720 draws a frame): the game's own GPU time is 14.5–15.0 ms a frame, and it ran at 52.2–53.4 fps, not 60; 56.5–56.9 fps since the two changes below. - GPU idle at each frame's start. The game submits the whole next frame, about 23 submissions on several queues, some 8 ms before the current frame's GPU work ends; queue 1's first piece waits for an event the CPU signals 0.2 ms after the frame's fence. The replay thread sits idle those 8 ms and translates only from the signal on, the whole frame in about 6 ms, while the GPU's first 5 ms of light passes wait for it. Per frame the game had no command buffer on the GPU for 2.03–2.19 ms, nearly all of it before a buffer committed after the GPU ran dry. Measured steps, headless, three runs a side unless said: `enc_thread on` 2.1 → 1.3–1.6 ms; [texture views by Metal texture](../../../docs/reference/frame-rate.md#texture-views-made-again-every-frame-for-render-targets-on-new-texture-objects) 1.4–1.8 → 1.16–1.20 ms (two runs), the replay's CPU 7.1–7.9 → 6.1–6.3 ms a frame. Frame rate in the same scene: 52.2–53.4 fps before both, 55.3–55.8 with the view cache, 56.5–56.9 with both. Disproved: smaller segments (`DM_NVN_CUT=16` / `8`) move the wait and leave its total (1.84–1.91 ms; 1.30–1.39 with the encode thread); the replay thread not waiting for the encode thread at each submission's end changed nothing once the views were cached (1.24–1.25 against 1.16–1.20 ms). Not tried: translating the parked submissions before the signal. The wait is there so that the frame before has landed (its occlusion results, which the replay reads, and the lighting buffer the CPU clears), so a replay ahead of it would read stale memory. Open: 1.2 ms of idle a frame, the replay's remaining cost (pool tables 0.5 ms a frame in `pool_gpu`'s copies, argument encoding, mesh task draws). + - Current: `replay_ahead` translates the parked frame before the signal and holds its commits until it ([The GPU waits at a frame's start for commands the game queued long before](../../../docs/reference/frame-rate.md#the-gpu-waits-at-a-frames-start-for-commands-the-game-queued-long-before)). Kakariko Village, a GPU-bound scene of about 2,940 draws (2026-11-11, headless from a save in the village, `DM_FPS_HOLD=off`, runs in turn against `DM_NVN_REPLAY_AHEAD=0`): 59.6-59.8 fps against 55.5-57.1 (five and four runs; one more a side fell out with long frames), frame p50 16.5-16.6 against 17.2-17.7 ms, the same GPU work (15.3-15.5 ms a frame); 48.0-53.7 against 41.8-46.1 fps with a terminal and WindowServer drawing 150-290 ms/s. Passing the event's wait outright, so that the next frame is also committed before the signal, removed the same idle (2.31 → 0.25 ms a frame) but lets the GPU run commands the game holds back, and was not kept. Open: not judged by eye in a window, nor on the 120 Hz link. - Current: the title and menu, a movie behind them, are a locked 60 fps (p50 16.67 ms, GPU span 15.6 ms). - Resolved: the title movie and the cutscene movies stuttered in small regular jerks at that steady 60 fps on a Mac that decodes AV1 with dav1d (M1, M2). The frames were on time and the movie's pictures were not: the player's `advance` (`main+0x3b61ea0`) found no new picture in 546 and 569 of about 2,900 frames of the title on an M2 Pro, and showed the last one again. Two causes, both general: [packets decoded inside the submission](../../../docs/reference/movies.md#nncodec-packets-decoded-inside-the-submission), on the player's one reader thread, which also gives the shown pictures back, and [dav1d one frame at a time](../../../docs/reference/movies.md#dav1d-decoded-one-frame-at-a-time) (15.4 ms a packet in the movie's heaviest five seconds, 122 ms the longest). After: 0 or 1 in 2,567 to 3,036 frames a run (eight runs of 54 s, headless, `DM_PROBE=main:3b61ed8,main:3b61f80` counting the failed and the good calls), and `DecodeAsync` returns in 0.1 ms at the median and 1.1 ms at the 99th percentile, from 1.9 and 120 ms. Open: not run on an M1 or M2 with four performance cores, nor on an iPad; a Mac with a hardware AV1 decoder (M3 on) decodes with VideoToolbox, where only the first cause applied, not measured. - Game speed: the game steps its time by a frame ratio, its base rate (60, or 30) / its int frame rate, whatever the frame took (`main+0x6e6cc4` on v131072), so frames longer than a vsync played in slow motion (seen by the user on a slower Mac; [issue 1375](https://github.com/seedds/nxnative/issues/1375)'s M1 Max ran the title at about 28 fps). With `fps_target 60` the ratio is the host's frame step × base / 60 ([A fixed frame step plays in slow motion on a slow Mac](../../../docs/reference/frame-rate.md#a-fixed-frame-step-plays-in-slow-motion-on-a-slow-mac)), a stub placed by its function's fingerprint ([`patches.py`](patches.py)). Mac runs on the M6 (2026-11-08, a test host on the libraries of chain `3ee493b2c3a4`): the user's play sessions held 60 fps with 2- and 3-vsync holds while areas loaded, game time 1.000 of real time by the host's count. That count is the stub's own; no run on a Mac slow enough to show the slow motion before and after. @@ -227,6 +229,7 @@ Its 37 kernels that correct samples, NDSR's network among them, gave about 0.25 - [Finalizing a copy of a texture object](../../../docs/reference/nvn-objects.md#finalizing-a-copy-of-a-texture-object) - [Dynamic resolution that never moves, and draw passes that wait for each other](../../../docs/reference/frame-rate.md#dynamic-resolution-that-never-moves-and-draw-passes-that-wait-for-each-other) - [Dynamic resolution at its floor while the GPU has time to spare](../../../docs/reference/frame-rate.md#dynamic-resolution-at-its-floor-while-the-gpu-has-time-to-spare): a stale frame-start timestamp, and event waits that idled the GPU +- [The GPU waits at a frame's start for commands the game queued long before](../../../docs/reference/frame-rate.md#the-gpu-waits-at-a-frames-start-for-commands-the-game-queued-long-before): the frame's 23 submissions parked behind the event its CPU signals after the frame before, translated only from the signal on; `replay_ahead` translates them ahead and holds their commits (Kakariko Village 55.5-57.1 → 59.6-59.8 fps). - [A full table of running GPU writes ends passes for nothing](../../../docs/reference/frame-rate.md#a-full-table-of-running-gpu-writes-ends-passes-for-nothing) - [Float atomics in storage memory](../../../docs/reference/shaders.md#float-atomics-in-storage-memory) - [textureGatherOffsets and a loop over its offsets](../../../docs/reference/shaders.md#texturegatheroffsets-and-a-loop-over-its-offsets) diff --git a/dm/games/0400486024DEC000/game.tsv b/dm/games/0400486024DEC000/game.tsv index 8cd0591bec..bc45b04a2d 100644 --- a/dm/games/0400486024DEC000/game.tsv +++ b/dm/games/0400486024DEC000/game.tsv @@ -49,3 +49,6 @@ tex_dirty_upload on # The game submits a frame's commands behind an event its CPU signals once the frame before has left the GPU, so the GPU starts each frame with nothing queued and waits for the # replay: with Metal encoding on its own thread a GPU-bound Hyrule Field scene went 55.3-55.8 -> 56.5-56.9 fps (Apple M4 Pro, three runs a side, interleaved) enc_thread on +# The same event again: with the encode thread the replay still began translating at the signal. Translating the parked queue before it, its commits held until the signal, in +# Kakariko Village (headless, DM_FPS_HOLD=off, Apple M4 Pro, 2026-11-11): 55.5-57.1 -> 59.6-59.8 fps, frame p50 17.2-17.7 -> 16.5-16.6 ms, the GPU work and the draws the same +replay_ahead on diff --git a/dm/games/README.md b/dm/games/README.md index 4888adcaef..cf2216899d 100644 --- a/dm/games/README.md +++ b/dm/games/README.md @@ -254,6 +254,7 @@ One row per profile; the notes are each profile's `README.md`. | `tex_dirty_upload` | `on` / `off` (the default), needs `tex_flush_upload`: a registered texture whose pages the CPU writes after `nvnTextureInitialize` without any NVN flush is uploaded as well (its pages are write-protected at registration, checked on first use; `nvn_ft_written` in `hle_nvn.c`). Tears of the Kingdom fills its ASTC terrain material arrays this way; without it the cave is magenta. FINAL FANTASY TACTICS - The Ivalice Chronicles loads its UI textures straight into CPU-uncached pools, which need no flush, after creating them; without both keys its screen stays black. The Great Ace Attorney Chronicles copies every texture into a CPU-cached pool after creating it and never flushes (its `main` has no cache maintenance at all): black too. The Legend of Zelda: Ocarina of Time writes its terrain tiles' height, blend and hole maps this way, and without the keys has holes in the ground | | `tex_dyn_slots` | `on` / `off` (the default): a shader whose buffer-texture handle the translator could not trace to one slot gets Ryujinx's fallback arrays (`__cb0_40000000`: 32 buffer textures and samplers indexed by the handle's texture / sampler ID; any other sampled texture indexes the whole pool without a key, [Texture handles from game memory index the pools](../../docs/reference/shaders.md#texture-handles-from-game-memory-index-the-pools)). With the key the replay puts slot indices in that shader's c2 texture and sampler tables (texture slot r → r, sampler slot r → r << 20) and binds slot k at element k, so the shader's own arithmetic picks the binding (`NVN_RB_TEXD` / `NVN_RB_SAMPD` in `nvn_mtl.m`). Right only where the handle comes from c2's tables: Octopath Traveler 0's 61 such vertex shaders read separate texture slots 0-10 and samplers 0-4 there and nothing else (FINAL FANTASY RESONANCE's 2,077 the texture table words 0x168-0x1c0 and sampler table words 0x568-0x590). Off, such shaders do not load. Not part of the shader chain version | | `draw_barriers` | `full` (the default) / `game`: how draw passes are ordered. `full`: each waits for all earlier GPU work. `game`: by the game's own barriers (NVN asks for one before results of rendering are read), so a pass's vertex work overlaps the previous pass's fragments. Ocarina of Time's GPU time 25 → 18 ms, about 180 full barriers a frame halved. Only a barrier that orders primitives or indirect data waits for all earlier work; a fragment-only one keeps the overlap. Only vertex-stage reads of the previous pass's output without a barrier change order. `DM_NVN_BARRIER` overrides it | +| `replay_ahead` | `off` (the default) / `on`: a queue parked on an event the game's CPU signals is translated before the signal, its commits held until then; needs `enc_thread` ([The GPU waits at a frame's start for commands the game queued long before](../../docs/reference/frame-rate.md#the-gpu-waits-at-a-frames-start-for-commands-the-game-queued-long-before); `DM_NVN_REPLAY_AHEAD` overrides) | | `vconv_range` | `on` / `off` (the default): vertex attributes the replay converts on the CPU (integer shader inputs fed float-type formats and the like, `vconv_bind` in `nvn_mtl.m`) are converted only over the vertices each draw reads (first / count, or the smallest and largest index of a direct indexed draw, kept while the index pages stay unwritten) instead of the whole bound range. Age of Calamity binds whole mesh pools: in a battle that was millions of vertices a frame. Indirect draws, per-instance streams and indices with a GPU write queued on them keep the whole range. `DM_NVN_VCONV_CHECK=1` scans the indices again at every reuse and reports differences; `DM_NVN_VCONV_RANGE=0` / `1` overrides it | | `shader_key_skip` | `+` (none by default): control-section bytes every shader key hashes as zeros, in `shader_split.py` (`key_ctl`) and the host (`hle_nvn.c` `keys_hash`), for an engine that shares one control section among shaders that differ only there. Batman: Arkham Knight: `0x770+0x78`, GLSLC's compile information (+0x778..+0x791 and +0x7d0..+0x7e7); without it the game asks for shaders the map does not have, each the control section of one record with the code area of another. It must stay clear of `+0x700..+0x75f`, which the tools read; it is a shader chain input, as every `shader_*` key | | `shader_groups`, `shader_note` | `shader_split.py` source groups and the map header note (Engage: `engine` for `data.unity3d` and `Resources/`, `assets` for the Addressables bundles). Both are shader inputs, the note too: changing either one, even by a word, builds every shader of the game again. Keep them as they are when a provisional profile moves into `dm/games` | diff --git a/dm/games/game.py b/dm/games/game.py index b7c198fd62..9d2da628ca 100644 --- a/dm/games/game.py +++ b/dm/games/game.py @@ -192,6 +192,9 @@ def header_one(g): sys.exit(f'{g.id}: shader_key_skip takes + within the first 0x880 bytes of the control section, past its header (+0x30) and clear of +0x700..+0x75f: {sks}') sko, skl = (int(m[1], 0), int(m[2], 0)) if m else (0, 0) if g.get('render_cond', ''): print(f'{g.id}: render_cond is ignored: the host evaluates NVN conditional rendering for every game', file=sys.stderr) # a profile written before the key went (a build folder's derived one) + rah = g.get('replay_ahead', 'off') # a queue parked on an event the game's CPU signals is translated meanwhile, its commits held until the signal (nvn_queue.inc nq_worker, nvn_rec.h hold_*; DM_NVN_REPLAY_AHEAD overrides; needs enc_thread): on / off + if rah not in ('on', 'off'): sys.exit(f'{g.id}: replay_ahead must be on or off: {rah}') + if rah == 'on' and et != 'on': sys.exit(f'{g.id}: replay_ahead needs enc_thread on (the encode thread holds the commits)') tfu = g.get('tex_flush_upload', 'off') # textures written by the CPU into a pool and published with nvnMemoryPoolFlushMappedRange are uploaded like packaged ones (hle_nvn.c): on / off if tfu not in ('on', 'off'): sys.exit(f'{g.id}: tex_flush_upload must be on or off: {tfu}') tdu = g.get('tex_dirty_upload', 'off') # with tex_flush_upload: a registered texture the CPU writes after init without any flush is uploaded too (dirty pages, hle_nvn.c nvn_ft_written): on / off @@ -255,6 +258,7 @@ def header_one(g): f'#define DM_GAME_PERF_BOOST {int(pm == "boost")}', f'#define DM_GAME_TEX_FLUSH_UPLOAD {int(tfu == "on")}', f'#define DM_GAME_SHADER_KEY_SKIP_OFF {sko:#x}', f'#define DM_GAME_SHADER_KEY_SKIP_LEN {skl:#x}', + f'#define DM_GAME_REPLAY_AHEAD {int(rah == "on")}', f'#define DM_GAME_TEX_DIRTY_UPLOAD {int(tdu == "on")}', f'#define DM_GAME_TEX_DYN_SLOTS {int(tds == "on")}', f'#define DM_GAME_DRAW_BARRIERS_GAME {int(dbr == "game")}', diff --git a/dm/gfx/nvn/hle_nvn.c b/dm/gfx/nvn/hle_nvn.c index a4d838a0d1..bc28adbeeb 100644 --- a/dm/gfx/nvn/hle_nvn.c +++ b/dm/gfx/nvn/hle_nvn.c @@ -1723,6 +1723,7 @@ __attribute__((weak)) void dm_gl_drain(void) {} // dm/gfx/gl/hle_gl.m: the sam void dm_gfx_suspend(int on) { pthread_mutex_lock(&g_susp_mu); g_susp = on != 0; + if (on) mtl_hold_drain(); // a submit thread stopped at held work is in flight: its hold ends first (nvn_rec.h) if (on) while (g_inflight_api) pthread_cond_wait(&g_susp_cv, &g_susp_mu); else pthread_cond_broadcast(&g_susp_cv); pthread_mutex_unlock(&g_susp_mu); diff --git a/dm/gfx/nvn/nvn_mtl.h b/dm/gfx/nvn/nvn_mtl.h index fb9fb002d7..3feac0a6ab 100644 --- a/dm/gfx/nvn/nvn_mtl.h +++ b/dm/gfx/nvn/nvn_mtl.h @@ -46,6 +46,14 @@ void mtl_sub_counter(uint64_t addr, uint32_t type); // Wri uint64_t mtl_sub_commit(void); uint64_t mtl_completed_fence(void); // Completed physical submissions, including CPU-visible post effects +int mtl_replay_ahead(void); // profile key replay_ahead / DM_NVN_REPLAY_AHEAD, with the encode thread +int mtl_hold_begin(volatile uint32_t *word, unsigned mode, uint32_t value); // submit thread, between submissions: 1 when what reaches the queue from now on is held until the wait is satisfied +int mtl_hold_active(void); +void mtl_hold_signal(volatile uint32_t *word, uint32_t value); // any thread: this event word was signalled and holds value +void mtl_hold_force(volatile uint32_t *word); // any thread: commands that signal this word were submitted; a hold on it cannot be satisfied +void mtl_hold_drain(void); // any thread: the host drains (a suspend); a hold ends now +void mtl_hold_wait(void); // submit thread: returns once the hold has ended +void mtl_hold_satisfied(void); // any thread: the held wait was satisfied (a signal latched before the hold began) uint64_t mtl_last_fence(void); // Fence value of the most recent submit (0 = never submitted) int mtl_wait(uint64_t fence, uint64_t timeout_ns); // Returns 1 when the GPU has completed up to fence, 0 on timeout int mtl_wait_acq(uint64_t fence, uint64_t timeout_ns); // the same for a sync WindowAcquireTexture handed out (its own line in the wait ledger, DM_NVN_WAITS) diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index bd654bee8b..b6bb6f5f9e 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -1160,6 +1160,10 @@ static int rc_gpu_unknown(rc_report *r, uint64_t done) { static int rc_value(uint64_t addr, uint64_t *v) { // 0 = unknown at encode time rc_report *r=rc_find(addr); uint64_t done=atomic_load_explicit(&g_rc_complete,memory_order_acquire); + // Replay ahead (nvn_rec.h) reaches a condition before the GPU has run the report it reads, and an unknown condition draws its block: Ocarina of Time's Kakariko Village had + // 360-480 more draws a frame (2,930 to 3,290-3,410). The translation waits here for the game's signal, as it does without the hold; what it has translated by then goes to + // the GPU at the signal. Waiting for the report's fence as well cost more than it saved (57.4 to 55.2 fps, the translation stalled 0.8 times a frame) + if (r && !r->conservative && r->fence>done && atomic_load(&g_hold_on) && on_sub_thread()) { hold_block(1); g_rc_ahead_waits++; done=atomic_load_explicit(&g_rc_complete,memory_order_acquire); } if (r) { if (r->conservative) return 0; if (rc_gpu_unknown(r,done)) return 0; @@ -1454,6 +1458,7 @@ void mtl_prepare(void) { } static void sub_cut_begin(void); static void ts_sub_begin(void), ts_boundary(void); static int ts_on(void); static void gmem_commit_patch(void); // the raw pool table words of the arguments encoded so far follow the pools (gmem_slot_note) +#define POST_RING 128 // mtl_sub_commit's ring of completion records, one a fence void mtl_sub_begin(void) { mtl_init(); g_sub_serial++; g_seg = 0; if (g_pkg_kept) { g_pkg_kept = 0; nvn_dirty_touch(); } seg_clk_put(g_sclk); g_sclk = NULL; @@ -1464,6 +1469,7 @@ void mtl_sub_begin(void) { mtl_prepare(); // done by then in the submit entry; the replay tool (nvn_replay) reaches it here warm_claim(); if (g_cb) MDIE("submit re-entered"); + if (atomic_load(&g_hold_on) && g_fence - g_done >= POST_RING - 16) hold_block(0); // a hold's fences complete only after it: the post ring (mtl_sub_commit) must not come round to one if (!atomic_load(&g_sub_thread_set) || !pthread_equal(g_sub_thread, pthread_self())) nvn_dirty_own_thread(); g_sub_thread = pthread_self(); atomic_store(&g_sub_thread_set, 1); atomic_store(&g_last_commit_error, 0); @@ -2389,7 +2395,6 @@ int mtl_gpu_span(uint64_t f, uint64_t *t0, uint64_t *t1) { // A submission's CPU-side writes at its end (events, samples-passed and counter reports): run once, by its feedback handler or, when a game's SyncWait wakes on the // GPU's own signal of the fence first, by that waiter (DM_NVN_FAST_WAKE, on by default): the feedback handler comes 0.26 ms after the GPU end on an M2 Max typedef struct { _Atomic uint64_t fence; _Atomic int claimed; int n; post_op *ops; seg_clk *sc; uint32_t seg_last; uint64_t t_commit; } post_rec; // t_commit: guest ns when it was committed -#define POST_RING 128 static post_rec g_postr[POST_RING]; static pthread_mutex_t g_post_mu = PTHREAD_MUTEX_INITIALIZER; // A successful claim holds the lock until post_run finishes. Ownership alone @@ -2496,9 +2501,10 @@ uint64_t mtl_sub_commit(void) { if (g_gp_state == 1 && !gp_active()) { int gn = g_gp_n; gp_lab *gl = malloc(sizeof(gp_lab) * (gn ? gn : 1)); memcpy(gl, g_gp_lab, sizeof(gp_lab) * gn); uint64_t gf = g_gp_frame; g_gp_state = 2; atomic_store(&g_gp_busy, 1); [o addFeedbackHandler:^(id f) { (void)f; gp_report(gn, gl, gf); }]; } [g_cb endCommandBuffer]; + if (atomic_load(&g_hold_on)) rec_queue_block(^{ pthread_mutex_lock(&g_post_mu); if (atomic_load(&pr->fence) == fence) pr->t_commit = guest_ns(); pthread_mutex_unlock(&g_post_mu); }); // a held commit: its time is when the queue gets it rec_commit(g_cb, o); g_cbgen++; // the stores it holds come before any later upload batch (gsb_held) if (!lost_test) rec_signal(g_ev, fence); - rec_drain(); + rec_drain_soft(); g_alloc_fence[g_alloc_cur] = fence; g_cb = nil; atomic_store(&g_sub_on, 0); // after ++g_fence and the last encoding: a buffer retired from now on waits for this fence at most @@ -2509,6 +2515,21 @@ uint64_t mtl_sub_commit(void) { } uint64_t mtl_completed_fence(void) { return atomic_load_explicit(&g_done,memory_order_acquire); } +// Replay ahead (profile key replay_ahead, DM_NVN_REPLAY_AHEAD overrides; needs the encode thread): nvn_queue.inc nq_worker translates a queue parked on an event the game's CPU +// signals, and nvn_rec.h keeps what that sends to the Metal queue until the wait is satisfied +int mtl_replay_ahead(void) { + static int v = -1; + if (v < 0) { const char *e = getenv("DM_NVN_REPLAY_AHEAD"); v = (e ? atoi(e) != 0 : DM_GAME_REPLAY_AHEAD) && rec_on(); + if (v) MLOG("replay ahead: a queue parked on an event the game signals is translated meanwhile, its commits held until the signal (DM_NVN_REPLAY_AHEAD=0 turns it off)"); } + return v; +} +int mtl_hold_begin(volatile uint32_t *word, unsigned mode, uint32_t value) { return mtl_replay_ahead() && !g_cb && hold_begin(word, mode, value, g_fence + 1); } +int mtl_hold_active(void) { return atomic_load_explicit(&g_hold_on, memory_order_acquire); } +void mtl_hold_signal(volatile uint32_t *word, uint32_t value) { uint32_t gen = atomic_load(&g_hold_gen); if (atomic_load_explicit(&g_hold_on, memory_order_acquire) && g_hold_word == word && hold_pred(value)) hold_poke(NULL, gen); } // value: the word as the signal left it, so a later reset does not hide it +void mtl_hold_force(volatile uint32_t *word) { uint32_t gen = atomic_load(&g_hold_gen); if (atomic_load_explicit(&g_hold_on, memory_order_acquire) && g_hold_word == word) hold_poke("commands that signal its event were submitted behind it", gen); } +void mtl_hold_drain(void) { hold_poke(HOLD_DRAIN, atomic_load(&g_hold_gen)); } +void mtl_hold_wait(void) { if (on_sub_thread()) hold_block(1); } +void mtl_hold_satisfied(void) { hold_poke(NULL, atomic_load(&g_hold_gen)); } uint64_t mtl_last_fence(void) { return g_fence; } int mtl_last_commit_error(void) { return atomic_load(&g_last_commit_error); } @@ -2518,7 +2539,16 @@ uint64_t mtl_sub_commit(void) { static void post_early(uint64_t fence) { post_complete(fence, 0, 0); } +static int mtl_wait_at_(uint64_t fence, uint64_t timeout_ns, int site); static int mtl_wait_at(uint64_t fence, uint64_t timeout_ns, int site) { + if (g_done >= fence) { if (ws_on()) ws_put(site, 0, 0); return 1; } + if (atomic_load(&g_hold_on) && fence >= g_hold_first) { // held work reaches the GPU first (nvn_rec.h): the submit thread stops for the signal; another thread waits as for parked work, and the hold's limit runs + if (on_sub_thread()) hold_block(0); + else hold_stuck(); // a poll counts: the game may ask again until it lands, and signal only then + } + return mtl_wait_at_(fence, timeout_ns, site); +} +static int mtl_wait_at_(uint64_t fence, uint64_t timeout_ns, int site) { if (g_done >= fence) { if (ws_on()) ws_put(site, 0, 0); return 1; } uint64_t w0 = ws_t0(); if ((site == WS_SYNC || site == WS_SYNC_NEWEST || site == WS_ACQ) && fast_wake() && g_ev && fence <= g_fence) { // the game's own wait: wake on the GPU's signal (rec_signal(g_ev, fence) after each submission) @@ -2575,7 +2605,7 @@ static void mtl_finish_gpu_at(int site) { void mtl_finish(void) { mtl_finish_gpu_at(WS_FINISH); } static void present_drop_for_suspend(void); static void snap_drain(void); -void mtl_drain(void) { present_drop_for_suspend(); mtl_present_flush(); snap_drain(); mtl_init(); id cb = q_cb(); [cb commit]; [cb waitUntilCompleted]; mtl_finish_gpu(); } +void mtl_drain(void) { mtl_hold_drain(); present_drop_for_suspend(); mtl_present_flush(); snap_drain(); mtl_init(); id cb = q_cb(); [cb commit]; [cb waitUntilCompleted]; mtl_finish_gpu(); } // ================= Render replay ================= #include "../../host/front.h" @@ -2928,6 +2958,7 @@ static int tex_atomic_alias(id base) { static void up_wake(void) { pthread_mutex_lock(&g_up_wmu); pthread_cond_broadcast(&g_up_wcv); pthread_mutex_unlock(&g_up_wmu); } static void up_wait_zero(_Atomic int *v, int site) { if (!atomic_load(v)) { if (ws_on()) ws_put(site, 0, 0); return; } + if (atomic_load(&g_hold_on) && on_sub_thread()) hold_block(0); // the batch may be a held commit (nvn_rec.h) uint64_t w0 = ws_t0(); pthread_mutex_lock(&g_up_wmu); while (atomic_load(v)) { struct timespec dl; clock_gettime(CLOCK_REALTIME, &dl); dl.tv_nsec += 10000000; if (dl.tv_nsec >= 1000000000) { dl.tv_sec++; dl.tv_nsec -= 1000000000; } pthread_cond_timedwait(&g_up_wcv, &g_up_wmu, &dl); } diff --git a/dm/gfx/nvn/nvn_queue.inc b/dm/gfx/nvn/nvn_queue.inc index bdb2beb5f0..08f7757d8f 100644 --- a/dm/gfx/nvn/nvn_queue.inc +++ b/dm/gfx/nvn/nvn_queue.inc @@ -11,7 +11,7 @@ typedef struct nq_signal { volatile uint32_t *event; unsigned mode; uint32_t val typedef struct nq_node { struct nq_node *next; uint8_t *bytes; size_t length, capacity; - unsigned kind, mode, closed, waiting; volatile uint32_t *event; uint32_t value; + unsigned kind, mode, closed, waiting, ahead; volatile uint32_t *event; uint32_t value; // ahead: an event wait passed under a hold (mtl_hold_begin) uint64_t wait_fence, event_predecessor, wait_since; unsigned wait_kind, wait_said; const sync_t *sync_source; nq_receipt *receipt; nq_signal *signals; unsigned signal_count; // NQ_COMMANDS: every event signal it records, in order (nq_event_issued at its commit) tex_t texture; double period; int crop[4]; @@ -79,8 +79,25 @@ void nvn_queue_gpu_progress(void) { while(*p) { nq_event_write *w=*p; if(w->fence<=done) { *p=w->next; free(w); } else p=&w->next; } pthread_cond_broadcast(&nq_cv); pthread_mutex_unlock(&nq_mu); } +// Who signals each event word: the game's CPU (nvnEventSignal) or its commands. Replay ahead takes only a wait on a word the CPU has signalled NQ_AHEAD_SIGNALS times and no +// command ever has, a frame gate's pattern: commands that signal the awaited word would be translated behind the wait and held with it, so the signal could not come +// (t_wait_event: a consumer parked on an event the CPU had reset, released by a producer submitted later on another queue). The count is evidence, not proof: such commands +// submitted behind a hold end it at once, in red (mtl_hold_force), and the word is never taken again. A hold that ran into its limit (nvn_rec.h HOLD_MAX_NS: a slow signal +// at an area load, or a thread the signal depends on) leaves the word out for NQ_AHEAD_SIGNALS signals more +enum { NQ_AHEAD_SIGNALS = 30 }; +typedef struct nq_event_src { struct nq_event_src *next; volatile uint32_t *word; unsigned cpu, gpu; } nq_event_src; +static nq_event_src *nq_event_srcs; +static int nq_event_cpu(volatile uint32_t *word) { for(nq_event_src *e=nq_event_srcs;e;e=e->next) if(e->word==word) return e->cpu>=NQ_AHEAD_SIGNALS && !e->gpu; return 0; } +static nq_event_src *nq_event_src_get(volatile uint32_t *word) { + nq_event_src *e=nq_event_srcs; while(e && e->word!=word) e=e->next; + if(!e) { e=calloc(1,sizeof *e); if(!e) die("event source allocation failed"); e->word=word; e->next=nq_event_srcs; nq_event_srcs=e; } + return e; +} +static void nq_event_src_note(volatile uint32_t *word,int cpu) { nq_event_src *e=nq_event_src_get(word); if(cpu) { if(e->cpucpu++; } else e->gpu=1; } +void nvn_queue_ahead_refuse(volatile uint32_t *word) { pthread_mutex_lock(&nq_mu); nq_event_src_get(word)->cpu=0; pthread_mutex_unlock(&nq_mu); } // a hold on it had to be forced (nvn_rec.h hold_check): its signals are counted again static void nq_event_publish(volatile uint32_t *word,unsigned mode,uint32_t value,uint64_t gpu_fence) { pthread_mutex_lock(&nq_mu); + nq_event_src_note(word,!gpu_fence); if(mode==1) atomic_fetch_add_explicit((_Atomic uint32_t *)word,value,memory_order_release); else atomic_store_explicit((_Atomic uint32_t *)word,value,memory_order_release); atomic_thread_fence(memory_order_seq_cst); @@ -89,7 +106,9 @@ static void nq_event_publish(volatile uint32_t *word,unsigned mode,uint32_t valu nq_node *n=q->first->first; if(n->kind==NQ_EVENT && n->waiting && n->event==word && (gpu_fence ? gpu_fence>=n->event_predecessor : nq_event_pending(word)<=mtl_completed_fence()) && nq_predicate(atomic_load_explicit((_Atomic uint32_t *)word,memory_order_acquire),n->mode,n->value)) { n->event=NULL; n->wait_fence=gpu_fence; } } + uint32_t left=atomic_load_explicit((_Atomic uint32_t *)word,memory_order_acquire); pthread_cond_broadcast(&nq_cv); pthread_mutex_unlock(&nq_mu); + mtl_hold_signal(word,left); } void nvn_event_publish(volatile uint32_t *word,unsigned mode,uint32_t value) { nq_event_publish(word,mode,value,0); } void nvn_event_publish_gpu(volatile uint32_t *word,unsigned mode,uint32_t value,uint64_t fence) { nq_event_publish(word,mode,value,fence); } @@ -118,11 +137,12 @@ static void *nq_worker(void *unused) { for(;;) { scan_again:; if(nq_test_held) { pthread_cond_wait(&nq_cv,&nq_mu); continue; } - int mapped_event_wait=0; + int mapped_event_wait=0; nq_node *ahead=NULL; for(q=nq_queues;q;q=q->next) { j=q->first; if(!j) continue; n=j->first; if(!n) { nq_publish(j->receipt,q->physical); q->first=j->next; if(!q->first) q->last=NULL; nq_put(j->receipt); pthread_mutex_unlock(&nq_mu); pthread_mutex_lock(&g_sub_mu); void *pool=objc_autoreleasePoolPush(); nq_job_free(j); objc_autoreleasePoolPop(pool); pthread_mutex_unlock(&g_sub_mu); pthread_mutex_lock(&nq_mu); goto scan_again; } + if(n->kind==NQ_EVENT && n->event && n->ahead) { if(mtl_hold_active()) break; n->ahead=0; } // its hold ended otherwise than by the signal: the wait stands again if(n->kind==NQ_EVENT && n->event) { uint64_t predecessor=nq_event_pending(n->event); if(!n->waiting) n->event_predecessor=predecessor; @@ -136,6 +156,7 @@ static void *nq_worker(void *unused) { else if(t-n->wait_since>5000000000ull && !n->wait_said) { static _Atomic int said; n->wait_said=1; if(atomic_fetch_add(&said,1)<8) LOG("[RED] queue %llu: an event wait has held it %.1f s: word %p is %#x, waiting for %s %#x; a GPU write of it is %s",(unsigned long long)q->serial,(t-n->wait_since)/1e9,(void *)n->event, atomic_load_explicit((_Atomic uint32_t *)n->event,memory_order_acquire),n->mode==0?"equal to":"at least",n->value,predecessor>mtl_completed_fence()?"queued, not completed":"not queued"); } + if(!ahead && predecessor<=mtl_completed_fence() && (n->next || j->next) && nq_event_cpu(n->event)) ahead=n; n->waiting=1; mapped_event_wait=1; continue; } } if(n->kind==NQ_SYNC) { @@ -151,6 +172,13 @@ static void *nq_worker(void *unused) { break; } if(q) break; + // Every queue waits, one of them only for the game's CPU: its commands are translated meanwhile, and what they send to the Metal queue is held until that wait is + // satisfied (nvn_rec.h hold_*). The node stays this queue's first while the lock is dropped: only this thread takes nodes + if(ahead && mtl_replay_ahead() && !mtl_hold_active()) { + volatile uint32_t *word=ahead->event; unsigned mode=ahead->mode; uint32_t value=ahead->value; + pthread_mutex_unlock(&nq_mu); dm_host_mutex_lock(&g_sub_mu); int held=mtl_hold_begin(word,mode,value); pthread_mutex_unlock(&g_sub_mu); pthread_mutex_lock(&nq_mu); + if(held) { ahead->ahead=1; if(!ahead->event) mtl_hold_satisfied(); goto scan_again; } + } // NVN events can also be changed by plain stores through mapped pool memory. // A bounded notification poll only while such a word is awaited complements API/callback wakes. if(mapped_event_wait) { struct timespec tick={0,1000000}; pthread_cond_timedwait_relative_np(&nq_cv,&nq_mu,&tick); } @@ -169,6 +197,7 @@ static void *nq_worker(void *unused) { gfx_enter(); nq_cost cost=nq_cost_begin(); if(frame!=j->frame) { frame=j->frame; mtl_set_frame(frame); } mtl_queue_activate(q->serial); mtl_set_queue_origin_lower_left(q->origin); + if(n->kind==NQ_PRESENT) mtl_hold_wait(); // a present goes to the display once the work before it has reached the GPU if(n->kind==NQ_COMMANDS) { uint64_t handle=(uintptr_t)n->bytes; nvn_cap_submit(1,&handle); @@ -231,7 +260,8 @@ static void nq_flatten(nq_job *j,const uint8_t *list) { if(v&CTL_LAST) return; } } -static void nq_enqueue(nq_queue *q,nq_job *j) { if(q->last) q->last->next=j; else q->first=j; q->last=j; nq_put(q->tail); q->tail=j->receipt; q->tail->refs++; pthread_cond_broadcast(&nq_cv); } +static void nq_enqueue(nq_queue *q,nq_job *j) { for(nq_node *n=j->first;n;n=n->next) for(unsigned i=0;isignal_count;i++) { nq_event_src_note(n->signals[i].event,0); mtl_hold_force(n->signals[i].event); } // before any wait on it can be taken ahead; a hold on it now could not be satisfied + if(q->last) q->last->next=j; else q->first=j; q->last=j; nq_put(q->tail); q->tail=j->receipt; q->tail->refs++; pthread_cond_broadcast(&nq_cv); } 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(); diff --git a/dm/gfx/nvn/nvn_rec.h b/dm/gfx/nvn/nvn_rec.h index 5d6cc32f1a..8f4ce1dc1d 100644 --- a/dm/gfx/nvn/nvn_rec.h +++ b/dm/gfx/nvn/nvn_rec.h @@ -128,6 +128,51 @@ static void rec_note_wait(_Atomic uint64_t *p, uint64_t v) { pthread_mutex_lock(&g_note_mu); while (atomic_load(p) < v) pthread_cond_wait(&g_note_cv, &g_note_mu); pthread_mutex_unlock(&g_note_mu); } +// ---------- Held commits (profile key replay_ahead, DM_NVN_REPLAY_AHEAD) ---------- +// A queue parked on an event the game's CPU signals has its commands translated and encoded meanwhile (nvn_queue.inc nq_worker), while everything that reaches the Metal queue +// (commits, event signals, queue blocks) is kept here in order and made when the event's wait is satisfied: the GPU gets the work when and in the order the game gives it, and +// only the host's translation moves ahead of the signal. The encode thread keeps and makes them; the submit thread stops at anything that waits for held work (hold_block). +// A parked queue with nobody waiting for it stays held as long as the game leaves it parked. Once the submit thread has stopped at a wait for held work (it holds the +// submission lock there) or another thread has waited for or polled a held fence, the signal may depend on that thread: HOLD_MAX_NS after the first of them (hold_stuck) the +// held operations are made at once and a red line says so, as the commands then run before the game's signal; nvn_queue.inc takes no wait on that event for a while +enum { HOLD_MAX_NS = 200000000 }; +static _Atomic uint64_t g_hold_stuck; // when the first such wait of this hold began (ns), 0 with none; cleared only as the hold ends +static _Atomic uint32_t g_hold_gen; // counts holds: a request made for one hold does not end the next +static _Atomic int g_hold_on; static _Atomic uint64_t g_hold_req; // req: the hold it is for << 2 | 1 the wait is satisfied (hold_poke), 2 forced, 3 the host drains (a suspend, the exit) +static _Atomic uint32_t g_hold_recs; // queue records made under this hold (submit thread) +static volatile uint32_t *g_hold_word; static unsigned g_hold_mode; static uint32_t g_hold_value; +static uint64_t g_hold_t0, g_hold_first; // when it began (ns); the first fence it holds +static NSMutableArray *g_hold_ops; // the encode thread's +static pthread_mutex_t g_hold_mu = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_hold_cv = PTHREAD_COND_INITIALIZER; +static uint64_t g_hold_n, g_hold_ops_n, g_hold_forced, g_hold_drained, g_hold_blocks, g_hold_block_recs, g_hold_ns; // statistics +static const char *volatile g_hold_force_why; +static uint64_t g_rc_ahead_waits; // nvn_mtl.m rc_value +static const char HOLD_DRAIN[] = "drain"; // hold_poke: the host's own drain, where the game does not run on +static int on_sub_thread(void); +void nvn_queue_ahead_refuse(volatile uint32_t *word); // nvn_queue.inc +static void hold_stuck(void) { uint64_t z = 0; atomic_compare_exchange_strong(&g_hold_stuck, &z, clock_gettime_nsec_np(CLOCK_UPTIME_RAW)); } // a thread waits for held work from now +static int hold_pred(uint32_t c) { return g_hold_mode == 0 ? c == g_hold_value : (uint32_t)(c - g_hold_value) < 0x80000000u; } +static int hold_ready(void) { uint32_t c = atomic_load_explicit((_Atomic uint32_t *)g_hold_word, memory_order_acquire); return g_hold_mode == 0 ? c == g_hold_value : (uint32_t)(c - g_hold_value) < 0x80000000u; } +// The encode thread: 1 while queue operations are to be kept; makes them all once the wait is satisfied +static int hold_check(void) { + if (!atomic_load_explicit(&g_hold_on, memory_order_acquire)) return 0; + uint64_t rq = atomic_load(&g_hold_req); int req = rq >> 2 == atomic_load(&g_hold_gen) ? (int)(rq & 3) : 0; + uint64_t now = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + if (!req && hold_ready()) req = 1; + uint64_t stuck = atomic_load(&g_hold_stuck); + if (!req && stuck && now > stuck && now - stuck > HOLD_MAX_NS) { req = 2; g_hold_force_why = "a thread had waited for them for 200 ms with no signal"; } + if (!req) return 1; + for (void (^op)(void) in g_hold_ops) op(); + g_hold_n++; g_hold_ops_n += g_hold_ops.count; g_hold_ns += now - g_hold_t0; [g_hold_ops removeAllObjects]; + if (req == 3) g_hold_drained++; + if (req == 2) { nvn_queue_ahead_refuse(g_hold_word); if (!g_hold_forced++) MLOG("[RED] replay ahead: held commands were handed to the GPU before the game's signal (%s); further ones are counted", g_hold_force_why ?: "?"); } + if (g_hold_n % 3000 == 0) MLOG("replay ahead: %llu holds, %.1f queue operations and %.2f ms a hold, %llu forced, %llu ended by a drain of the host's, submit thread stopped %llu times before the signal (%.1f queue operations recorded by then); of them at a condition whose report was in flight %llu", (unsigned long long)g_hold_n, (double)g_hold_ops_n / g_hold_n, g_hold_ns / 1e6 / g_hold_n, (unsigned long long)g_hold_forced, (unsigned long long)g_hold_drained, (unsigned long long)g_hold_blocks, g_hold_blocks ? (double)g_hold_block_recs / g_hold_blocks : 0.0, (unsigned long long)g_rc_ahead_waits); + pthread_mutex_lock(&g_hold_mu); atomic_store(&g_hold_stuck, 0); atomic_store_explicit(&g_hold_on, 0, memory_order_release); pthread_cond_broadcast(&g_hold_cv); pthread_mutex_unlock(&g_hold_mu); + return 0; +} +static int hold_req_now(void) { uint64_t rq = atomic_load(&g_hold_req); return rq >> 2 == atomic_load(&g_hold_gen) && (rq & 3); } +static void hold_op(void (^op)(void)) { if (hold_check()) { if (!g_hold_ops) g_hold_ops = [NSMutableArray new]; [g_hold_ops addObject:[op copy]]; } else op(); } + // ---------- The encode thread ---------- static id g_rx_cb, g_rx_enc; // the encode thread's real command buffer and open encoder static void rec_exec(const rec_t *r) { @@ -139,14 +184,15 @@ static void rec_exec(const rec_t *r) { case RO_CB_BLOCK: ((void (^)(id))rec_id(a[0]))(g_rx_cb); break; case RO_COMMIT: case RO_COMMIT_REAL: { if (r->op == RO_COMMIT) ubc_wait(a[2]); // the uniform shadows this command buffer reads - id buffers[] = {r->op == RO_COMMIT ? g_rx_cb : rec_id(a[1])}; MTL4CommitOptions *o = rec_id(a[0]); - pthread_mutex_lock(&g_res_mu); - if (o) [g_q4 commit:buffers count:1 options:o]; else [g_q4 commit:buffers count:1]; - pthread_mutex_unlock(&g_res_mu); + id cb = r->op == RO_COMMIT ? g_rx_cb : rec_id(a[1]); MTL4CommitOptions *o = rec_id(a[0]); + hold_op(^{ id buffers[] = {cb}; + pthread_mutex_lock(&g_res_mu); + if (o) [g_q4 commit:buffers count:1 options:o]; else [g_q4 commit:buffers count:1]; + pthread_mutex_unlock(&g_res_mu); }); if (r->op == RO_COMMIT) g_rx_cb = nil; break; } - case RO_SIGNAL: [g_q4 signalEvent:rec_id(a[0]) value:a[1]]; break; - case RO_Q_BLOCK: ((void (^)(void))rec_id(a[0]))(); break; + case RO_SIGNAL: { id ev = rec_id(a[0]); uint64_t v = a[1]; hold_op(^{ [g_q4 signalEvent:ev value:v]; }); break; } + case RO_Q_BLOCK: hold_op((void (^)(void))rec_id(a[0])); break; case RO_RE_BEGIN: g_rx_enc = [(id)g_rx_cb renderCommandEncoderWithDescriptor:rec_id(a[0])]; break; case RO_CE_BEGIN: g_rx_enc = [(id)g_rx_cb computeCommandEncoder]; break; case RO_END: [(id)e endEncoding]; g_rx_enc = nil; break; @@ -199,7 +245,8 @@ static void rec_exec(const rec_t *r) { case RO_LABEL: [(id)e setLabel:rec_id(a[0])]; break; case RO_R_TS: [(id)e writeTimestampWithGranularity:a[1] afterStage:a[2] intoHeap:rec_id(a[0]) atIndex:a[3]]; break; case RO_C_TS: [(id)e writeTimestampWithGranularity:a[1] intoHeap:rec_id(a[0]) atIndex:a[2]]; break; - case RO_NOTE: { _Atomic uint64_t *p = (_Atomic uint64_t *)(uintptr_t)a[0]; pthread_mutex_lock(&g_note_mu); if (a[1] > atomic_load(p)) atomic_store(p, a[1]); pthread_cond_broadcast(&g_note_cv); pthread_mutex_unlock(&g_note_mu); break; } + case RO_NOTE: { _Atomic uint64_t *p = (_Atomic uint64_t *)(uintptr_t)a[0]; uint64_t v = a[1]; // kept with the queue operations it follows: it says they are made + hold_op(^{ pthread_mutex_lock(&g_note_mu); if (v > atomic_load(p)) atomic_store(p, v); pthread_cond_broadcast(&g_note_cv); pthread_mutex_unlock(&g_note_mu); }); break; } default: MDIE("deferred encoding: unknown record %u", r->op); } for (uint32_t i = 0; i < r->nobj; i++) if (a[i]) CFRelease((CFTypeRef)(uintptr_t)a[i]); @@ -209,10 +256,19 @@ static void *rec_thread(void *arg) { pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0); for (;;) { pthread_mutex_lock(&g_rb_mu); - while (!g_rb_head) { g_rb_sleeping = 1; pthread_cond_wait(&g_rb_work, &g_rb_mu); g_rb_sleeping = 0; } + while (!g_rb_head) { + if (atomic_load(&g_hold_on)) { // held operations wait for the game's signal: hold_poke wakes this thread, and a store into a mapped event word is found by the poll + pthread_mutex_unlock(&g_rb_mu); int held; @autoreleasepool { held = hold_check(); } pthread_mutex_lock(&g_rb_mu); + if (g_rb_head) break; + if (held) { struct timespec tick = {0, clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - g_hold_t0 < 50000000ull ? 500000 : 5000000}; g_rb_sleeping = 1; // a frame gate is signalled within milliseconds; a queue parked for long is polled less + if (!g_rb_head && !hold_req_now()) pthread_cond_timedwait_relative_np(&g_rb_work, &g_rb_mu, &tick); g_rb_sleeping = 0; } + continue; + } + g_rb_sleeping = 1; pthread_cond_wait(&g_rb_work, &g_rb_mu); g_rb_sleeping = 0; + } rec_blk *b = g_rb_head; g_rb_head = b->next; if (!g_rb_head) g_rb_tail = NULL; g_rb_busy = 1; pthread_mutex_unlock(&g_rb_mu); - @autoreleasepool { for (int i = 0; i < b->n; i++) rec_exec(&b->r[i]); } + @autoreleasepool { for (int i = 0; i < b->n; i++) { if (atomic_load_explicit(&g_hold_on, memory_order_relaxed) && g_hold_ops.count) hold_check(); rec_exec(&b->r[i]); } } pthread_mutex_lock(&g_rb_mu); b->n = 0; b->next = g_rb_free; g_rb_free = b; g_rb_busy = 0; if (!g_rb_head) pthread_cond_broadcast(&g_rb_idle); @@ -242,8 +298,26 @@ static rec_t *rec_put(uint32_t op, uint32_t nobj) { } rec_t *r = &g_rb_cur->r[g_rb_cur->n++]; r->op = op; r->nobj = nobj; return r; } -// Hand over what is recorded and wait until the encode thread has made every call -static void rec_drain(void) { +// The submit thread, at a wait for work a hold keeps from the GPU: the hold ends first, with the game's signal +static void hold_block(int any) { // any: also with nothing held yet (the caller waits for what the game's signal follows, not for held work) + if (!atomic_load(&g_hold_on) || (!any && !atomic_load(&g_hold_recs))) return; + rec_publish(); g_hold_blocks++; g_hold_block_recs += atomic_load(&g_hold_recs); + hold_stuck(); + pthread_mutex_lock(&g_hold_mu); while (atomic_load(&g_hold_on)) pthread_cond_wait(&g_hold_cv, &g_hold_mu); pthread_mutex_unlock(&g_hold_mu); +} +// Any thread: the wait (word, as read under the queue lock) is satisfied, or with why the held work must reach the GPU now. gen: the hold the caller saw +static void hold_poke(const char *why, uint32_t gen) { + if (!atomic_load(&g_hold_on) || atomic_load(&g_hold_gen) != gen) return; + uint64_t req = (uint64_t)gen << 2 | (!why ? 1 : why == HOLD_DRAIN ? 3 : 2), old = atomic_load(&g_hold_req); + do { if (old >> 2 == gen && (old & 3)) return; } while (!atomic_compare_exchange_weak(&g_hold_req, &old, req)); // the first request for this hold stands + if (why && why != HOLD_DRAIN) g_hold_force_why = why; + pthread_mutex_lock(&g_rb_mu); if (g_rb_sleeping) pthread_cond_signal(&g_rb_work); pthread_mutex_unlock(&g_rb_mu); +} +// Hand over what is recorded and wait until the encode thread has made every call. A caller that goes on to wait for the GPU or to use another queue needs the queue to have +// everything (hard): held operations are made first, which waits for the game's signal. The end of a submission only needs the calls made (rec_drain_soft) +static void rec_drain_soft(void); +static void rec_drain(void) { if (on_sub_thread()) hold_block(0); rec_drain_soft(); } +static void rec_drain_soft(void) { if (!g_rb_started) return; rec_publish(); uint64_t w0 = ws_t0(); int blocked = 0; @@ -366,18 +440,27 @@ static void rec_cb_block(id cb, void (^block)(id)) { static id rec_table(id t) { if (!rec_on() || !t) return t; DmRecTable *s = [DmRecTable new]; s->real = t; return s; } // The replay's main command buffer: committed once the uniform shadows queued so far are made (ubc_wait) static void rec_commit(id cb, MTL4CommitOptions *o) { - if ([cb isKindOfClass:[DmRecCB class]]) { rec_t *r = rec_put(RO_COMMIT, 1); r->a[0] = rec_obj(o); r->a[2] = ubc_head(); return; } + if ([cb isKindOfClass:[DmRecCB class]]) { rec_t *r = rec_put(RO_COMMIT, 1); r->a[0] = rec_obj(o); r->a[2] = ubc_head(); atomic_fetch_add(&g_hold_recs, 1); return; } ubc_wait(ubc_head()); id buffers[] = {cb}; if (o) [g_q4 commit:buffers count:1 options:o]; else [g_q4 commit:buffers count:1]; } // An upload batch: its place in the queue is after what is recorded so far (it reads no uniform shadow) static void rec_commit_upload(id cb, MTL4CommitOptions *o) { - if (rec_on() && g_rb_started) { rec_t *r = rec_put(RO_COMMIT_REAL, 2); r->a[0] = rec_obj(o); r->a[1] = rec_obj(cb); return; } + if (rec_on() && g_rb_started) { rec_t *r = rec_put(RO_COMMIT_REAL, 2); r->a[0] = rec_obj(o); r->a[1] = rec_obj(cb); atomic_fetch_add(&g_hold_recs, 1); return; } id buffers[] = {cb}; if (o) [g_q4 commit:buffers count:1 options:o]; else [g_q4 commit:buffers count:1]; } // A queue operation (a sparse texture's mapping update, nvn_mtl.m sparse_*): on the encoding thread in its place among the recorded commits, so it reaches the queue before the upload batch // committed after it and after the command buffers committed before it -static void rec_queue_block(void (^block)(void)) { if (rec_on() && g_rb_started) rec_put(RO_Q_BLOCK, 1)->a[0] = rec_obj([block copy]); else block(); } -static void rec_signal(id ev, uint64_t v) { if (rec_on() && g_rb_started) { rec_t *r = rec_put(RO_SIGNAL, 1); r->a[0] = rec_obj(ev); r->a[1] = v; } else [g_q4 signalEvent:ev value:v]; } +static void rec_queue_block(void (^block)(void)) { if (rec_on() && g_rb_started) { rec_put(RO_Q_BLOCK, 1)->a[0] = rec_obj([block copy]); atomic_fetch_add(&g_hold_recs, 1); } else block(); } +static void rec_signal(id ev, uint64_t v) { if (rec_on() && g_rb_started) { rec_t *r = rec_put(RO_SIGNAL, 1); r->a[0] = rec_obj(ev); r->a[1] = v; atomic_fetch_add(&g_hold_recs, 1); } else [g_q4 signalEvent:ev value:v]; } +// The submit thread, idle between submissions (nvn_mtl.m mtl_hold_begin): from here on what reaches the queue is kept until the wait (word, mode, value) is satisfied +static int hold_begin(volatile uint32_t *word, unsigned mode, uint32_t value, uint64_t first_fence) { + if (!rec_on() || !g_rb_started || atomic_load(&g_hold_on)) return 0; + rec_drain_soft(); + g_hold_word = word; g_hold_mode = mode; g_hold_value = value; g_hold_first = first_fence; g_hold_t0 = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + atomic_store(&g_hold_recs, 0); atomic_store(&g_hold_stuck, 0); atomic_fetch_add(&g_hold_gen, 1); atomic_store_explicit(&g_hold_on, 1, memory_order_release); + pthread_mutex_lock(&g_rb_mu); if (g_rb_sleeping) pthread_cond_signal(&g_rb_work); pthread_mutex_unlock(&g_rb_mu); // the encode thread polls from now, also with nothing recorded + return 1; +} diff --git a/dm/gfx/tests/Makefile b/dm/gfx/tests/Makefile index bdde30b2e8..0fe5345f75 100644 --- a/dm/gfx/tests/Makefile +++ b/dm/gfx/tests/Makefile @@ -603,13 +603,23 @@ 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) +# A queue parked on an event the game's CPU signals: translated meanwhile, nothing of it on the GPU before the signal (nvn_rec.h hold_*, DM_NVN_REPLAY_AHEAD) +t_replay_ahead: t_replay_ahead.m $(MTL_T_DEP) + clang $(CFLAGS) -fobjc-arc -o $@ t_replay_ahead.m $(filter-out ../nvn/hle_nvn.c,$(MTL_T_SRC)) $(FW) +.PHONY: check_t_replay_ahead +check_t_replay_ahead: t_replay_ahead + MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 DM_NVN_REPLAY_AHEAD=0 ./$< + MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 DM_NVN_REPLAY_AHEAD=1 ./$< + .PHONY: check_t_wait_event check_t_queue_lifetime 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 ./$< + MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 DM_NVN_REPLAY_AHEAD=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 ./$< + MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 DM_NVN_REPLAY_AHEAD=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) diff --git a/dm/gfx/tests/t_replay_ahead.m b/dm/gfx/tests/t_replay_ahead.m new file mode 100644 index 0000000000..5a1b052ded --- /dev/null +++ b/dm/gfx/tests/t_replay_ahead.m @@ -0,0 +1,146 @@ +// Replay ahead (DM_NVN_REPLAY_AHEAD, nvn_rec.h hold_*): a queue parked on an event the game's CPU signals is translated meanwhile, and nothing of it reaches the GPU before the signal. +#define nvn_game_fps nvn_game_fps_mtl_default +#include "../nvn/nvn_mtl.m" +#undef nvn_game_fps +#define g_ft g_ft_hle +#include "../nvn/hle_nvn.c" +#undef g_ft +#define P(name) ((NVNT_##name)nvn_lookup(#name)) +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, failures; +#define CHECK(c, name) do { int check_ok = !!(c); checks++; failures += !check_ok; printf("%s: %s\n", check_ok ? "PASS" : "FAIL", name); } while (0) +static void require(int ok, const char *name) { CHECK(ok, name); if (!ok) exit(2); } +enum { W = 8, H = 8, BYTES = W * H * 4, POOL_BYTES = 1 << 20, TEX_A = 0x80000, OUTPUT = 0xa0000, EVENT = 0xa1000, GPU_EVENT = 0xa2000 }; +static NVNdevice device; static NVNqueue queues[2]; static NVNmemoryPool pool; static NVNcommandBuffer command; +static NVNevent event, gpu_event; static NVNtexture target; static uint8_t *memory; static NVNbufferAddress output; +static const NVNcopyRegion region = {0, 0, 0, W, H, 1}; + +static int landed(NVNsync *sync, uint64_t timeout) { + NVNsyncWaitResult r = P(nvnSyncWait)(sync, timeout); + return r == NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED || r == NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED; +} +static void submit(int queue, NVNcommandHandle handle, NVNsync *sync) { + P(nvnSyncInitialize)(sync, &device); P(nvnQueueSubmitCommands)(&queues[queue], 1, &handle); + P(nvnQueueFenceSync)(&queues[queue], sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0); +} +static int pixels(unsigned r, unsigned g, unsigned b) { + const uint8_t want[] = {r, g, b, 255}; + for (int i = 0; i < W * H; i++) if (memcmp(memory + OUTPUT + i * 4, want, 4)) return 0; + return 1; +} +static int untouched(void) { for (int i = 0; i < BYTES; i++) if (memory[OUTPUT + i] != 0x5a) return 0; return 1; } +// A clear to the colour and its copy into the readback buffer, behind a wait on ev (NULL: none), signalling sig afterwards (NULL: none) +static NVNcommandHandle record(NVNevent *ev, const float *colour, NVNevent *sig) { + P(nvnCommandBufferBeginRecording)(&command); + if (ev) P(nvnCommandBufferWaitEvent)(&command, ev, NVN_EVENT_WAIT_MODE_EQUAL, 1); + const NVNtexture *colors[] = {&target}; const float viewport[] = {0, 0, W, H}; + P(nvnCommandBufferSetRenderTargets)(&command, 1, colors, NULL, NULL, NULL); + P(nvnCommandBufferSetViewports)(&command, 0, 1, viewport); P(nvnCommandBufferSetScissor)(&command, 0, 0, W, H); + P(nvnCommandBufferClearColor)(&command, 0, colour, 15); + P(nvnCommandBufferCopyTextureToBuffer)(&command, &target, NULL, ®ion, output, 0); + if (sig) P(nvnCommandBufferSignalEvent)(&command, sig, NVN_EVENT_SIGNAL_MODE_WRITE, NVN_EVENT_SIGNAL_LOCATION_BOTTOM, 0, 1); + return P(nvnCommandBufferEndRecording)(&command); +} +static int wait_until(int (^cond)(void), int ms) { for (int i = 0; i < ms * 10; i++) { if (cond()) return 1; usleep(100); } return cond(); } +int main(void) { @autoreleasepool { + if (setvbuf(stdout, NULL, _IONBF, 0)) abort(); mtl_init(); + int on = mtl_replay_ahead(); + printf("replay ahead %s\n", on ? "on" : "off"); + NVNdeviceBuilder db = {0}; P(nvnDeviceBuilderSetDefaults)(&db); require(P(nvnDeviceInitialize)(&device, &db), "device initialized"); + for (int i = 0; i < 2; i++) { NVNqueueBuilder qb = {0}; P(nvnQueueBuilderSetDefaults)(&qb); P(nvnQueueBuilderSetDevice)(&qb, &device); require(P(nvnQueueInitialize)(&queues[i], &qb), "queue initialized"); } + require(!posix_memalign((void **)&memory, getpagesize(), POOL_BYTES), "pool storage allocated"); memset(memory, 0, POOL_BYTES); + NVNmemoryPoolBuilder pb = {0}; P(nvnMemoryPoolBuilderSetDefaults)(&pb); P(nvnMemoryPoolBuilderSetDevice)(&pb, &device); + P(nvnMemoryPoolBuilderSetStorage)(&pb, memory, POOL_BYTES); P(nvnMemoryPoolBuilderSetFlags)(&pb, 0x24); require(P(nvnMemoryPoolInitialize)(&pool, &pb), "pool initialized"); + NVNbufferBuilder bb = {0}; NVNbuffer buffer; P(nvnBufferBuilderSetDefaults)(&bb); P(nvnBufferBuilderSetDevice)(&bb, &device); + P(nvnBufferBuilderSetStorage)(&bb, &pool, OUTPUT, BYTES); require(P(nvnBufferInitialize)(&buffer, &bb), "readback buffer initialized"); output = P(nvnBufferGetAddress)(&buffer); + NVNeventBuilder eb = {0}; P(nvnEventBuilderSetDefaults)(&eb); P(nvnEventBuilderSetStorage)(&eb, &pool, EVENT); require(P(nvnEventInitialize)(&event, &eb), "event initialized"); + P(nvnEventBuilderSetStorage)(&eb, &pool, GPU_EVENT); require(P(nvnEventInitialize)(&gpu_event, &eb), "second event initialized"); + require(P(nvnCommandBufferInitialize)(&command, &device), "command buffer initialized"); P(nvnCommandBufferAddCommandMemory)(&command, &pool, 0, TEX_A); + NVNtextureBuilder tb = {0}; P(nvnTextureBuilderSetDefaults)(&tb); P(nvnTextureBuilderSetDevice)(&tb, &device); + P(nvnTextureBuilderSetTarget)(&tb, NVN_TEXTURE_TARGET_2D); P(nvnTextureBuilderSetSize2D)(&tb, W, H); + P(nvnTextureBuilderSetFormat)(&tb, NVN_FORMAT_RGBA8); P(nvnTextureBuilderSetStorage)(&tb, &pool, TEX_A); require(P(nvnTextureInitialize)(&target, &tb), "texture initialized"); + const float red[] = {1, 0, 0, 1}, green[] = {0, 1, 0, 1}, blue[] = {0, 0, 1, 1}; + NVNsync sync, sync2; + submit(0, record(NULL, red, NULL), &sync); require(landed(&sync, 5000000000ull), "an ungated submission lands"); P(nvnSyncFinalize)(&sync); + CHECK(pixels(255, 0, 0), "it cleared to red"); + + for (int i = 0; i < 40; i++) P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, i & 1); // the game's CPU has signalled it many times, its commands never (nvn_queue.inc NQ_AHEAD_SIGNALS) + puts("CASE a queue parked on a CPU-signalled event"); + P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 0); memset(memory + OUTPUT, 0x5a, BYTES); + uint64_t holds = g_hold_n; + submit(0, record(&event, green, NULL), &sync); + if (on) { + CHECK(wait_until(^{ return (int)(atomic_load(&g_hold_on) && atomic_load(&g_hold_recs) >= 2); }, 2000), "its commands are translated before the signal: a commit and its fence signal are held"); + } else CHECK(!atomic_load(&g_hold_on), "no hold with the switch off"); + CHECK(!landed(&sync, 100000000ull), "the submission has not run 100 ms later"); + CHECK(untouched(), "the GPU wrote nothing of it"); + CHECK(!on || atomic_load(&g_hold_on), "a wait that gives up within the limit leaves the hold"); + P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 1); + require(landed(&sync, 5000000000ull), "it lands after the signal"); P(nvnSyncFinalize)(&sync); + CHECK(pixels(0, 255, 0), "and cleared to green"); + CHECK(!atomic_load(&g_hold_on) && g_hold_n == holds + (on ? 1 : 0) && !g_hold_forced, on ? "one hold, ended by the signal" : "no hold was counted"); + + puts("CASE work submitted behind the held queue keeps its order"); + P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 0); memset(memory + OUTPUT, 0x5a, BYTES); + submit(0, record(&event, green, NULL), &sync); submit(0, record(NULL, blue, NULL), &sync2); + CHECK(!landed(&sync2, 100000000ull) && untouched(), "the later submission of the same queue waits behind the parked one"); + P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 1); + require(landed(&sync2, 5000000000ull) && landed(&sync, 0), "both land after the signal"); P(nvnSyncFinalize)(&sync); P(nvnSyncFinalize)(&sync2); + CHECK(pixels(0, 0, 255), "the later one ran last: blue"); + + puts("CASE a signal by a plain store into the event's word"); + P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 0); memset(memory + OUTPUT, 0x5a, BYTES); holds = g_hold_n; + submit(0, record(&event, red, NULL), &sync); + CHECK(!on || wait_until(^{ return (int)(atomic_load(&g_hold_on) && atomic_load(&g_hold_recs) >= 2); }, 2000), "held again"); + CHECK(untouched(), "nothing on the GPU yet"); + atomic_store_explicit((_Atomic uint32_t *)(memory + EVENT), 1, memory_order_release); // no API call: the encode thread's poll and the queue worker's find it + require(landed(&sync, 5000000000ull), "it lands after the store"); P(nvnSyncFinalize)(&sync); + CHECK(pixels(255, 0, 0) && g_hold_n == holds + (on ? 1 : 0) && !g_hold_forced, "red, and the hold ended unforced"); + + puts("CASE an event the GPU signals is not held past"); + for (int i = 0; i < 40; i++) P(nvnEventSignal)(&gpu_event, NVN_EVENT_SIGNAL_MODE_WRITE, i & 1); // as many CPU signals as the other: only the commands' signal keeps it out + // gpu_event was last written by commands: its wait parks as before, and the commands that signal it run + P(nvnEventSignal)(&gpu_event, NVN_EVENT_SIGNAL_MODE_WRITE, 0); + submit(1, record(NULL, red, &gpu_event), &sync); require(landed(&sync, 5000000000ull), "the signalling commands land"); P(nvnSyncFinalize)(&sync); + holds = g_hold_n; memset(memory + OUTPUT, 0x5a, BYTES); + P(nvnCommandBufferBeginRecording)(&command); P(nvnCommandBufferSignalEvent)(&command, &gpu_event, NVN_EVENT_SIGNAL_MODE_WRITE, NVN_EVENT_SIGNAL_LOCATION_BOTTOM, 0, 0); + NVNcommandHandle reset = P(nvnCommandBufferEndRecording)(&command); + submit(1, reset, &sync); require(landed(&sync, 5000000000ull), "commands reset the event"); P(nvnSyncFinalize)(&sync); + submit(0, record(&gpu_event, green, NULL), &sync); + CHECK(!landed(&sync, 100000000ull) && untouched() && !atomic_load(&g_hold_on), "a wait on it parks its queue with no hold"); + submit(1, record(NULL, red, &gpu_event), &sync2); + require(landed(&sync, 5000000000ull) && landed(&sync2, 5000000000ull), "the other queue's commands signal it and both land"); P(nvnSyncFinalize)(&sync); P(nvnSyncFinalize)(&sync2); + CHECK(pixels(0, 255, 0) && g_hold_n == holds, "the waiting queue ran after its signal, with no hold"); + + puts("CASE a thread stuck on held work"); + P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 0); memset(memory + OUTPUT, 0x5a, BYTES); + uint64_t forced = g_hold_forced; + submit(0, record(&event, red, NULL), &sync); + if (on) { + CHECK(landed(&sync, 2000000000ull), "a wait of more than 200 ms for a held fence gets the work to the GPU"); + CHECK(g_hold_forced == forced + 1, "counted as forced"); + } else CHECK(!landed(&sync, 400000000ull), "without the switch the queue stays parked"); + P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 1); + require(landed(&sync, 5000000000ull), "the queue is free again"); P(nvnSyncFinalize)(&sync); + + puts("CASE the event of a forced hold is left out for a while"); + P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 0); memset(memory + OUTPUT, 0x5a, BYTES); holds = g_hold_n; + submit(0, record(&event, green, NULL), &sync); + CHECK(!landed(&sync, 100000000ull) && untouched() && !atomic_load(&g_hold_on), "its next wait parks with no hold"); + P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 1); + require(landed(&sync, 5000000000ull), "and lands after the signal"); P(nvnSyncFinalize)(&sync); + for (int i = 0; i < 40; i++) P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, i & 1); + P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 0); memset(memory + OUTPUT, 0x5a, BYTES); + submit(0, record(&event, blue, NULL), &sync); + CHECK(!on || wait_until(^{ return (int)atomic_load(&g_hold_on); }, 2000), "after 30 more signals of the CPU's it is taken again"); + P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 1); + require(landed(&sync, 5000000000ull), "the last submission lands"); P(nvnSyncFinalize)(&sync); + CHECK(pixels(0, 0, 255), "blue"); + + printf("%d checks, %d failures\n", checks, failures); + return failures != 0; +} } diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index c827f11832..e660f53dc6 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -556,6 +556,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - in a replay profile, `_platform_memcmp` is most of the time spent in serial lookups (`tex_mtl` through `g_by_serial`). → [Hash-table lookups of 8-byte keys](../reference/frame-rate.md#hash-table-lookups-of-8-byte-keys) - the GPU sits idle each frame while the host translates the submission (a game that does not submit frame N+1 until frame N's GPU work is done). → [Submissions handed to the GPU in segments](../reference/frame-rate.md#submissions-handed-to-the-gpu-in-segments) - one frame in 50 or so takes 25-40 ms in a scene where the frame normally fits, with the host on time: `@sync_ms` is high, `@sub_wall_ms` is not, and the frame before has a GPU span (`@gpu_end_ms - @gpu_beg_ms`) of 25-40 ms while the summed `@gpu_ms` has not moved. Runs fall into two states, and on the same code one can have 5 long frames and the next 60. A bad run also shows 186 % CPU against 133 %, and the previous frame still running when the next starts (p50 4 ms, p90 10 ms, against about 0 in a good run). → [The GPU idles with the next command buffer already committed](../reference/frame-rate.md#the-gpu-idles-with-the-next-command-buffer-already-committed) +- a GPU-bound scene some frames a second under its rate with the GPU's own work under a vsync: per frame the game has no command buffer on the GPU for 1-2 ms, nearly all of it before the frame's first one (`DM_NVN_GPUPROF`: the gap in front of the frame's first render pass; `DM_NVN_TSV`: `@gpu_end_ms - @gpu_beg_ms` 2 ms over the summed `@gpu_ms`), while the replay thread sat idle for milliseconds just before. → [The GPU waits at a frame's start for commands the game queued long before](../reference/frame-rate.md#the-gpu-waits-at-a-frames-start-for-commands-the-game-queued-long-before) - the submit thread's CPU samples half in `__CFBasicHashFindBucket_Linear` under `CFSetContainsValue` (from `tex_mtl_` and `tex_by_id`), a few hundred thousand to over a million instructions of translation per draw, the submission growing with the game's CPU-written textures. → [The set of CPU-written textures hashed by serial](../reference/frame-rate.md#the-set-of-cpu-written-textures-hashed-by-serial) - several milliseconds of CPU translation and geometry preparation separate one frame's GPU end from the next frame's GPU start, even though the frame already contains complete geometry passes. → [Geometry boundaries submit prepared work early](../reference/frame-rate.md#geometry-boundaries-submit-prepared-work-early) - CPU submission spikes during texture updates, with the residency log showing tens of MB of new private staging allocations per frame. → [Reusing upload staging after a slot completes](../reference/frame-rate.md#reusing-upload-staging-after-a-slot-completes) diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv index e23e305512..8e59945ce1 100644 --- a/docs/env_switches.tsv +++ b/docs/env_switches.tsv @@ -198,6 +198,7 @@ DM_NVN_PRESENT_FINISH diagnostic `=1` makes each present return once the GPU has DM_NVN_PROF diagnostic `=1` wraps the implemented NVN functions in a timing wrapper and collects the time each takes during recording DM_NVN_PROGTRACE diagnostic `=` logs matching ProgramSetShaders calls and their guest backtraces DM_NVN_REGLUM diagnostic `=x0,y0,x1,y1:` (normalized coordinates): on every present records the present number, time, mean luminance and a grayscale thumbnail of that region, to check animation speed against frame rate +DM_NVN_REPLAY_AHEAD switch `1` translates a queue parked on an event the game's CPU signals before the signal, the encode thread keeping its commits until then (with `DM_NVN_ENC_THREAD=1`); `0` translates from the signal on (the default unless the profile sets replay_ahead: Ocarina of Time does) DM_NVN_REPORT_EXACT switch `0` refuses a partly covered uniform shadow over the whole 4 KB page of a counter report of a running submission, as before; by default only over the report's own 16 bytes, which the host writes when that submission completes DM_NVN_REUPLOADS diagnostic `=1` logs the first 400 re-uploads of textures taken from their storage: shape, size, how much was read from guest memory and how many images were copied from the texture it replaces, the frame and the submission, the pages written since the upload and where the first lies, and the GPU copies into it since then DM_NVN_RP_AREA switch `0` makes passes on targets of 16 M pixels or more cover the whole target, as before; by default a draw pass that loads what it keeps stops at the far corner of its scissor when that is at most half the target diff --git a/docs/reference/frame-rate.md b/docs/reference/frame-rate.md index 4f82adbc00..b457df84cd 100644 --- a/docs/reference/frame-rate.md +++ b/docs/reference/frame-rate.md @@ -512,6 +512,21 @@ Frame pacing: the host's frame step, engine frame limiters, present intervals an - **Check:** `make -C dm/gfx/tests GAME= check_t_feedback` (`cut_boundary_case`: two reports of one command buffer, either side of a boundary, read two times from the boundary's GPU timestamps; the tests' guest clock is their `now_ns`, as the host's is with no pause, and `bp_now`, which most tests give as `now_ns`, is the host's Mach clock, as Metal's timestamps are. With stubs that returned 0 both reports took the time their completion handler wrote them, the same in about half the runs). Ocarina of Time on its walk, settled, per 2,700 frames: over 25 ms 51-75 in the bad state and 3-6 in the rare good one before; 0-8 in all 7 runs after, the last 2 on the landed code; over 33 ms 12-58 before and 0-2 after; frame p95 18.9-21 ms to 17.8-18.9 ms; in a window p95 17.8 ms, 3 over 25 ms. The heavy stretch holds 16.65-16.8 ms by lowering its resolution, as before. - **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md#found-on-this-game). +### The GPU waits at a frame's start for commands the game queued long before + +- **Symptom:** a GPU-bound scene some frames a second under its rate with the GPU's own work under a vsync: per frame the game has no command buffer on the GPU for 1-2 ms, nearly all of it before the frame's first one (`DM_NVN_GPUPROF`: the gap in front of the frame's first render pass; `DM_NVN_TSV`: `@gpu_end_ms - @gpu_beg_ms` 2 ms over the summed `@gpu_ms`), while the replay thread sat idle for milliseconds just before. +- **Cause:** the game submits a frame's commands behind an event (`nvnCommandBufferWaitEvent`) that its CPU signals once the frame before has left the GPU. The queue worker parks that queue and every queue ordered behind it until the signal, then translates the frame from its first command. The GPU has nothing queued then, and the frame's first passes are light, so it waits for the translation. +- **Fix:** the profile key `replay_ahead` (`DM_NVN_REPLAY_AHEAD` overrides it; it needs the encode thread, `enc_thread`). When every queue waits and one of them only for an event of this kind, `nq_worker` (`nvn_queue.inc`) passes the wait and goes on translating, and the encode thread keeps everything that would reach the Metal queue, in order: command buffer commits, upload batches, event signals, queue blocks (`nvn_rec.h` `hold_*`). When the wait is satisfied it makes them all. The GPU gets the work when and in the order the game gives it; only the host's translation moves ahead of the signal. + - Which waits: an event word the game's CPU has signalled 30 times and no command ever has (`NQ_AHEAD_SIGNALS`). Commands that signal the awaited word would be translated behind the wait and held with it. The count is evidence, not proof: such commands submitted behind a hold end it at once, with the red line below, and the word is never taken again. + - The submit thread stops for the signal wherever it would wait for held work: a fence of a held submission, an upload slot, a drain before another queue is used, and before a present, which commits to the queue itself. It also stops before the hold's fences would come round the ring of 128 completion records. + - A condition (`render_cond`) whose report is still in flight stops it too. Drawn as unknown instead, the scene below had 360-480 more draws a frame. Waiting for the report's fence as well cost more than it saved (57.4 to 55.2 fps). + - A held commit's time for the game's GPU reports is when the queue gets it, not when it was translated. + - A parked queue nobody waits for stays held as long as the game leaves it. Once the submit thread has stopped at held work, or another thread has waited for or polled a held fence, the signal may depend on that thread: 200 ms after the first of them with no signal, the held work goes to the GPU and a red line says so (`replay ahead: held commands were handed to the GPU before the game's signal`), and the event's signals are counted from 0 again before it is taken. The host's own drain (a suspend, the exit) ends a hold without the line. +- **Not covered by a test:** the submit thread stopped inside a submission (a condition, an upload slot) and woken by the signal, a second queue translated under a hold, the host's drain, and the commit time a held submission reports; the game's runs below go through the first two every frame. +- **Open:** what the replay reads from guest memory while it translates, it now reads before the signal: uniform blocks are read by the GPU from the pools, but copies the host makes at translation (indirect records, pool tables, uploads of textures the CPU wrote) would miss a write the game makes between its submission and its signal. No check counts such writes yet, which is why the key is off unless a profile sets it. +- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md#found-on-this-game), which parks about 23 submissions a frame behind one such event. Kakariko Village, headless from a save, `DM_FPS_HOLD=off`, Apple M4 Pro, runs in turn on one build (`DM_NVN_REPLAY_AHEAD=0` against the profile's `on`): 55.5-57.1 fps without (four runs) and 59.6-59.8 with (five), frame p50 17.2-17.7 → 16.5-16.6 ms, the GPU span's p50 17.2-17.5 → 16.2-16.4 ms, the summed GPU time the same (15.3-15.5 ms). One more run a side fell out with long frames, as runs here do when another app draws: 45.8 fps without (frame p95 33 ms), 54.3 with (p95 29 ms, its p50 16.5 ms). On an earlier build of the change, with a terminal and WindowServer drawing 150-290 ms/s throughout, 41.8-46.1 → 48.0-53.7 fps (three runs a side). Draws a frame 2,900-2,940 → 2,970-2,990, the conditions met in the first moments after the signal. A hold lasts 0.7-5 ms and keeps 4-25 queue operations; in a seventh to two fifths of the frames the translation stops at a condition before the signal. No forced hold in any run, the save's own area load among them; the end shots alike by eye. +- **Check:** `make -C dm/gfx/tests GAME= check_t_replay_ahead` (a parked queue's commands are translated and kept, nothing of them on the GPU before the signal; a later submission of the queue keeps its order; a signal by a plain store ends the hold; a wait on an event commands signal parks with no hold; a thread stuck on held work for 200 ms gets it to the GPU, counted, and that event is left out until its CPU has signalled it 30 times more), and `check_t_wait_event` and `check_t_queue_lifetime`, which also run with the switch on. + ### The set of CPU-written textures hashed by serial - **Symptom:** the submit thread's CPU samples half in `__CFBasicHashFindBucket_Linear` under `CFSetContainsValue` (from `tex_mtl_` and `tex_by_id`), a few hundred thousand to over a million instructions of translation per draw, the submission growing with the game's CPU-written textures.