Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 84 additions & 10 deletions dm/gfx/nvn/nvn_mtl.m

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions dm/gfx/tests/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,13 @@ t_srgb_alias: t_srgb_alias.m $(MTL_T_DEP)
check_t_srgb_alias: RUN_ENV = MTL_DEBUG_LAYER=1
t_image_alias: t_image_alias.m $(MTL_T_DEP)
clang $(CFLAGS) -fobjc-arc -o $@ t_image_alias.m $(MTL_T_SRC) $(FW)
t_alias_retire: t_alias_retire.m $(MTL_T_DEP)
clang $(CFLAGS) -fobjc-arc -o $@ t_alias_retire.m $(MTL_T_SRC) $(FW)
.PHONY: check_t_alias_retire
check_t_alias_retire: t_alias_retire
DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_alias_retire
DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_alias_retire
MTL_DEBUG_LAYER=1 ./t_alias_retire off
.PHONY: check_t_image_alias
check_t_image_alias: t_image_alias
DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_image_alias
Expand Down
58 changes: 58 additions & 0 deletions dm/gfx/tests/t_alias_retire.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Shared textures no live texture object resolves to are retired when GPU memory runs short (nvn_mtl.m alias_retire_idle): the budget is DM_NVN_WS_MB, set tiny here.
// A texture a live object holds stays, an idle unreferenced one goes, a finalized descriptor over it then resolves to nothing, and a live object over it gets a new texture.
// "./t_alias_retire off" runs with DM_NVN_ALIAS_RETIRE=0: nothing is retired.
#include "../nvn/nvn_mtl.m"
void *front_metal_layer(void) { return NULL; }
module_t *module_of(const void *p) { (void)p; return NULL; }
module_t *g_mod; int g_nmod;
void svc_thread_dump(void) {}
uint64_t now_ns(void) { return bp_now(); }
static int checks, failed;
#define CHECK(c, label) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s\n", label); } } while (0)

enum { POOL = 16 << 20 };
static tex_t target(pool_t *pool, uint64_t serial, int64_t off, unsigned w) {
tex_t t = {.magic = MAGIC('T','E','X',0), .serial = serial, .pool = pool, .off = off, .mem = pool->mem + off};
t.d = (nvn_texdesc){.target = NVN_TEXTURE_TARGET_2D, .format = NVN_FORMAT_RGBA8, .flags = NVN_TEXTURE_FLAGS_COMPRESSIBLE, .width = w, .height = w, .depth = 1, .levels = 1, .samples = 1};
nvn_tex_layout(&t.d, &t.L); mtl_tex_init(&t); return t;

Check failure on line 17 in dm/gfx/tests/t_alias_retire.m

View workflow job for this annotation

GitHub Actions / clang-tidy (ratchet)

Address of stack memory associated with local variable 't' is still referred to by the global variable 'g_tex_live' upon returning to the caller. This will be a dangling reference [clang-analyzer-core.StackAddressEscape] (1 in this file, the baseline has 0)
}
static void submissions(int n) { for (int i = 0; i < n; i++) { mtl_sub_commit(); mtl_drain(); mtl_sub_begin(); } dispatch_sync(g_feedback_q, ^{}); defer_drain(); }
static int in_table(id<MTLTexture> t) { pthread_mutex_lock(&g_smu); int r = alias_has(t); pthread_mutex_unlock(&g_smu); return r; }

int main(int argc, char **argv) { @autoreleasepool {
int off = argc > 1 && !strcmp(argv[1], "off");
setenv("DM_NVN_WS_MB", "1", 1); // any residency set is past 85 % of it
if (off) setenv("DM_NVN_ALIAS_RETIRE", "0", 1);
setenv("DM_NVN_POOL_HEAP", "0", 1); // a pool heap, if the build has one, would hold these textures' memory whatever the retirement does
mtl_init();
uint8_t *mem = aligned_alloc(1 << 16, POOL); memset(mem, 0, POOL);
mtl_pool_add(mem, POOL);
pool_t pool = {.magic = MAGIC('P','O','O','L'), .flags = NVN_MEMORY_POOL_FLAGS_CPU_NO_ACCESS | NVN_MEMORY_POOL_FLAGS_GPU_CACHED, .mem = mem, .size = POOL};
@autoreleasepool {
mtl_sub_begin();
tex_t kept = target(&pool, 996000, 0, 256), left = target(&pool, 996001, 4 << 20, 256);
id<MTLTexture> mk = tex_mtl(&kept), ml = tex_mtl(&left);
CHECK(mk && ml && in_table(mk) && in_table(ml), "both render targets are shared textures");
mtl_tex_release(&left); // finalized: no live object resolves to it any more, as a scene the game left
submissions(ALIAS_RETIRE + 2 * ALIAS_RETIRE_EVERY);
CHECK(in_table(mk), "a texture a live object holds stays");
if (off) {
CHECK(in_table(ml), "DM_NVN_ALIAS_RETIRE=0: an idle unreferenced texture stays");
} else {
CHECK(!in_table(ml), "an idle texture no live object resolves to is retired when memory runs short");
CHECK(g_alias_idle >= 1, "the memory report counts it");
tex_t stale = left; stale.serial = 996001; // the finalized descriptor, as a texture pool walk resolves it
CHECK(tex_mtl(&stale) == nil, "a finalized descriptor over a retired texture resolves to nothing, not a new texture");
tex_t again = target(&pool, 996002, 4 << 20, 256); // a live object over the retired storage and description
id<MTLTexture> ma = tex_mtl(&again);
CHECK(ma && ma != ml && in_table(ma), "a live object over a retired texture gets a new shared texture");
mtl_tex_release(&again);
}
mtl_tex_release(&kept); mk = nil; ml = nil;
mtl_alias_drop_pool(&pool);
submissions(2);
mtl_sub_commit(); mtl_drain();
}
free(mem);
printf("t_alias_retire%s: %d checks, %d failed\n", off ? " (off)" : "", checks, failed); return failed != 0;
} }
2 changes: 1 addition & 1 deletion dm/gfx/tests/t_direct_upload.m
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ static void run(int target,unsigned width,unsigned height,unsigned layers,unsign
if(!round&&direct){
tex_t initial=t;initial.has_layout=0;initial.serial+=100000;
id<MTLTexture> control=[g_dev newTextureWithDescriptor:tex_desc(&initial,0)];res_add(control);uint64_t n=g_direct_uploads;
mtl_sub_begin();CHECK("initial fill retains its original texture",tex_init_fill(&initial,control));finish();CHECK("initial fill does not require new write/view usage",g_direct_uploads==n);defer_obj_release(control);
mtl_sub_begin();CHECK("initial fill retains its original texture",tex_init_fill(&initial,control,0));finish();CHECK("initial fill does not require new write/view usage",g_direct_uploads==n);defer_obj_release(control);
}
memset(readback.contents,0xcd,readback.length);id<MTLCommandBuffer> cb=q_cb();id<MTLBlitCommandEncoder> ce=[cb blitCommandEncoder];off=0;
for(unsigned l=0;l<levels;l++)for(unsigned a=0;a<layers;a++) {
Expand Down
2 changes: 1 addition & 1 deletion dm/gfx/tests/t_view_swizzle.m
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ static void init_fill_case(int tid, int format, int pool_flags) {
CHECK(nvn_swizzle(&t.d, 0, 0, pixels, 4, t.mem) == 0, "guest texels swizzled");
g_sub_thread = pthread_self(); atomic_store(&g_sub_thread_set, 1);
id<MTLTexture> base = [g_dev newTextureWithDescriptor:tex_desc(&t, 0)];
CHECK(tex_init_fill(&t, base), "initial fill from the pool");
CHECK(tex_init_fill(&t, base, 0), "initial fill from the pool");
up_flush(); mtl_finish_gpu();
serial_put(t.serial, base); mtl_reg_tex(tid, &t, NULL);
os_unfair_lock_lock(&g_rmu); id<MTLTexture> view = tex_by_id(tid); os_unfair_lock_unlock(&g_rmu);
Expand Down
1 change: 1 addition & 0 deletions docs/agents/symptoms.md
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- ≈13 MB/frame leak. → [Transient render targets shared by storage](../reference/rendering.md#transient-render-targets-shared-by-storage)
- a model has correct geometry, base colour and normals but appears as a black silhouette; deferred lighting's material-ID depth texture stays zero. → [IMAGE usage does not split texture storage](../reference/rendering.md#image-usage-does-not-split-texture-storage)
- GPU memory grows with every image shown; the memory line's `shared textures` count keeps rising. → [Shared-storage entries taken over by a new texture](../reference/rendering.md#shared-storage-entries-taken-over-by-a-new-texture)
- at a scene change the GPU's memory climbs by several GB within seconds and stays; on a Mac whose working set it passes, the GPU faults (`kIOGPUCommandBufferCallbackErrorPageFault`) or hangs and macOS ignores every later submission, or the submit thread blocks in the kernel with the Mac frozen. The memory report shows thousands of shared textures "unreferenced". → [Shared textures of a scene the game left, retired when GPU memory runs short](../reference/rendering.md#shared-textures-of-a-scene-the-game-left-retired-when-gpu-memory-runs-short)
- GPU memory grows as resolution changes or rooms load, although almost every retained texture still has a live NVN descriptor; reclaiming unused sharing-table entries cannot recover it. → [Live resolution variants share physical image storage](../reference/rendering.md#live-resolution-variants-share-physical-image-storage)
- the whole picture came out darker and more saturated on the Mac and the iPhone: comparing with a Switch screenshot, every channel at every level equalled the Switch value decoded from sRGB once more (0.55 → 0.26, 0.75 → 0.52). → [Render-target views that change the format](../reference/rendering.md#render-target-views-that-change-the-format)
- a movie (or another picture the game converts each frame) does not show: the screen keeps the last 3D frame while the decoder delivers every picture. A pass dump shows a pass writing one serial and the composite sampling another serial of the same size, the two Metal formats `RGBA8Unorm` (70) and `RGBA8Unorm_sRGB` (71). → [Textures of an sRGB / linear pair over the same storage](../reference/rendering.md#textures-of-an-srgb--linear-pair-over-the-same-storage)
Expand Down
2 changes: 2 additions & 0 deletions docs/env_switches.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ DM_NICK switch The account nickname the game sees (default `Player`)
DM_NRO switch `0` turns off loading of the NRO modules the game's NRR files register (on by default): every `nn::ro::LoadModule` then fails
DM_NRO_CAPTURE diagnostic folder: a `nn::ro::LoadModule` with no rewritten copy writes the image to `<folder>/<SHA-256>.nro` and ends the run (the NSP script's capture of an NRO the game decodes at run time)
DM_NRO_DIR path folder of NROs the shader split reads like `main`, and in which it finds a CRA archive's file table (the NSP script sets it for a captured NRO)
DM_NVN_ALIAS_RETIRE switch `0` keeps shared textures until their storage is taken over or their pool goes, as before; by default, while the residency set holds more than 85 % of the working set, shared textures no live texture object has resolved to in 64 submissions are retired, the longest idle first, down to 75 % (`alias_retire_idle`)
DM_NVN_ALLOCPROF diagnostic `=1` charges Metal allocation growth to each replayed op type and function, and logs command allocator sizes and each new texture (serial, size, format, storage)
DM_NVN_API switch `=<major>.<minor>` overrides the NVN API version `nvnDeviceGetInteger` reports (by default decided by the SDK version or the profile's `device_api`: 55.15 for SDK 11 and later, 53.313 before)
DM_NVN_BARRIER switch How draw passes are ordered: `full` (default) waits for all earlier GPU work, `game` only for the previous pass's fragment stage unless the game set a barrier, `ab` alternates with the `DM_AB` phases
Expand Down Expand Up @@ -219,6 +220,7 @@ DM_NVN_VSDUMP_FROM diagnostic First presented frame eligible for a post-vertex c
DM_NVN_VSDUMP_KEY diagnostic Vertex key to capture, or `*` for all eligible vertex shaders; storage-writing shaders are excluded
DM_NVN_VSDUMP_MAX diagnostic Maximum post-vertex captures (default 1, or 256 for the wildcard key)
DM_NVN_WAITS diagnostic `=1` turns on the wait ledger: every place a host or game thread waits on the CPU for the GPU or the encode thread, counted per frame
DM_NVN_WS_MB diagnostic `=<MB>` replaces Metal's recommended working set in the host's memory budget (shared texture retirement, `restop`): a smaller Mac's budget tried on a larger one (a 16 GB Mac recommends about 10,700 MB)
DM_NVN_XV switch `0` turns off the cross-submission attachment validity ledger, which skips write-backs of colour attachments cleared before their next use (on by default, only with `DM_NVN_TBDR` on)
DM_NVN_ZBLOCK diagnostic `=1` logs (`[zb]`) the all-zero blocks per level of each ASTC texture uploaded on the CPU (magenta when drawn); `=<folder>` also writes the raw storage of the first one per format and size
DM_NVN_ZSKIP switch `0` turns off the zero-source skip, which drops a draw whose fragment shader is proven to write 0 over targets already 0 (on by default, only with `DM_NVN_TBDR` on)
Expand Down
13 changes: 13 additions & 0 deletions docs/reference/rendering.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,19 @@ The replay on Metal (`dm/gfx/nvn/nvn_mtl.m`) and the Vulkan and OpenGL layers. E
- **Found on:** [STEINS;GATE RE:BOOT](../../dm/games/01008BC024FDE000/README.md) (ASTC 4x4 images up to 4096 wide, RGBA8 render targets, R8 masks): from a quick save, 297 entries and 1.29 GB of GPU memory at frame 6,600; 468 entries and 1.58 GB 24,000 frames into a new game. With the fix: 97 entries and 0.93 GB at frame 6,600; 15 minutes of story from the quick save (53,700 frames) stayed at 1.08–1.15 GB of GPU memory and 1.02–1.13 GB resident, and a new game from boot stays at 0.97–1.03 GB from its first story scene to frame 27,300 (with the 16-submission guard).
- **Check:** Captain Toad: Treasure Tracker's opening course, rendered with agl's transient targets, keeps its 26 entries and takes none over, with the same memory and frame times as before.

### Shared textures of a scene the game left, retired when GPU memory runs short

- **Symptom:** at a scene change the GPU's memory climbs by several GB within seconds and stays; on a Mac whose working set it passes, the GPU faults (`kIOGPUCommandBufferCallbackErrorPageFault`) or hangs and macOS ignores every later submission, or the submit thread blocks in the kernel with the Mac frozen. The memory report shows thousands of shared textures "unreferenced".
- **Cause:** a game may leave the descriptors of the textures it finalized registered in its texture pool, and every pool walk resolves them, which keeps their shared textures (`g_alias`) and refreshed their last-use stamp. Nothing else let them go: a shared texture leaves the table when its pool is finalized or another texture takes over its storage, and a game that keeps its pools and loads the next scene elsewhere in them does neither.
- **Fix:** `alias_retire_idle` in `nvn_mtl.m`, at the start of each submission. When the residency set holds more than 85 % of the working set, it retires shared textures that no live texture object (or a view one holds) resolves to and that no lookup for a live object has used for 64 submissions. It retires the longest idle first, until the set is down to 75 %.
- Only lookups for live objects count as use (`g_alias_lseen`). Reclaiming by any lookup would keep every texture a stale descriptor names, and reclaiming by lookup idleness alone would retire targets in use.
- A finalized descriptor over a retired key resolves to nothing (the pool table's dummy). Making those again brought the old scenes back by the thousand, too new to retire.
- A live object over a retired key gets a new texture filled from its storage (`tex_init_fill`).
- `DM_NVN_ALIAS_RETIRE=0` turns it off. `DM_NVN_WS_MB` sets another working set for it, to try a smaller Mac's budget on a larger one (a 16 GB Mac recommends about 10.7 GB).
- **Limits:** only shared textures (the sharing table) are retired, and only under memory pressure, so a game within its budget is unchanged. A finalized descriptor a shader still samples after its texture was retired reads the dummy. A game that keeps drawing with finalized descriptors for long would need the texture kept, which this cannot tell from a stale one.
- **Check:** `make -C dm/gfx/tests GAME=<id> check_t_alias_retire` runs under Metal validation with direct and deferred encoding, and with the switch off. A held texture stays, an idle unreferenced one is retired, its finalized descriptor resolves to nothing, and a live object over it gets a new texture.
- **Found on:** The Legend of Zelda: Ocarina of Time (Switch 2, `0400486024DEC000` v131072, profile in [#1299](https://github.com/seedds/nxnative/pull/1299)) on a 24 GB M5 Pro, after the talk with Saria in Kokiri Forest. 2,000 to 2,500 shared textures lost their live object at once, and textures went from 5 GB to 10 to 16 GB with the residency set past the 18.2 GB working set. With the retirement, textures stayed about 6 GB over repeated replays of the scene (`DM_NVN_ALIAS_RETIRE=0`: 16.6 GB of textures and a freeze). With `DM_NVN_WS_MB=10700` the game stayed within a 16 GB Mac's budget.

### Live resolution variants share physical image storage

- **Symptom:** GPU memory grows as resolution changes or rooms load, although almost every retained texture still has a live NVN descriptor; reclaiming unused sharing-table entries cannot recover it.
Expand Down
Loading