Files
seeddsandThomas Liu 61e97458d2 nvn/latch: gate on GPU deadline and exit on late GPU or skipped ticks
On the 60 Hz display link at frame latency 1, games whose CPU present
arrives early (< room / 2) while their GPU rendering plus MetalFX
present exceeds update.targetTimestamp (~16.6 ms) locked to 30.0 fps
immediately after a drain into the late latch (Fire Emblem Fortune's
Weave on M5 Max and Xenoblade Chronicles: Definitive Edition on M5,
#3251): 300 latched presents across 300 callbacks with 0 timeouts at
33.34 ms p50, while DM_PRESENT_LATCH=0 held 60 fps.

CAMetalDisplayLink's targetTimestamp is the GPU completion deadline for
signalDrawable:, not just CPU commit. Missing it at latency 1 skips the
next 60 Hz callback (33.34 ms gap); while the game sleeps in
mtl_link_wait_ticks, the queue stays empty so the next callback latches
again into the same miss, and because CPU arrival stays inside the wait
(0 timeouts, age < 0), nvn_link_drain_next never saw a fallback.

Two general host fixes in nvn_link_drain.h, nvn_link_latch.h, and
nvn_mtl.m:
- Entry gate (nvn_link_latch_spare, link_gpu_lead): when NVN per-frame
  GPU completion timing (g_gpu[frame % GRING]) is available, include it
  plus smoothed present-pass GPU time (g_present_gpu_s) and require
  gpu_lead < room - tick / 8 alongside the CPU lead limit. Heavy scenes
  keep the queue's 1-frame slack instead of draining into a 30 fps lock,
  while light games and 33 ms ProMotion windows keep latching.
- Runtime exit (nvn_link_latch_check, present_now): check f.GPUEndTime
  against update.targetTimestamp in present_now's MTL4CommitOptions
  feedback handler (covering NVN, Vulkan, and GL) and watch for skipped
  callbacks right after a latched present (cb_gap > 1.35 * tick_period,
  < 0.25 s). Exit immediately on any late-GPU miss, a single skipped
  tick right after entering a drain, or 2 skipped ticks without
  LINK_LATCH_GIVE_UP clean latched ticks between them, skipping the
  wait for one tick to restore a standing frame and trigger backoff.

Checked on Apple M6 / macOS 27.2.1: t_link_latch (32/32), t_link_drain
(99/99), t_link_latch_cb (26/26, including NVN g_gpu gating, real Metal
4 GPUEndTime > targetTimestamp exit + backoff, and skipped-tick exit),
t_present_alloc (13/13), t_present_rescue (167/167), t_link_ticks
(95/95), dmhost build + --check-tables for 04007EF01F8AE000, test_docs
(7/7), and regress.py check --quick on Hades (0100535012974000: PASS,
60.8 -> 60.8 fps, latch enqueue-to-target-display 41.5 -> 24.5 ms with
live late-GPU exit/backoff). Open: reporter gameplay retests on
Fortune's Weave and Xenoblade Chronicles: Definitive Edition.

Part of #3251.

Co-authored-by: Thomas Liu <[email protected]>
2026-11-24 02:02:18 +08:00
..
Subsystem references and a symptom index: the failure catalogue of docs/agents/03-bringup.md and the per-title material of docs/agents/04-graphics.md (section 1's container list, section 6 and its "Seen in <game>" subsections) move into docs/reference/, one heading per mechanism: rewriter.md, memory.md, threads.md, services.md, movies.md, audio.md, frame-rate.md, nvn-objects.md, rendering.md (with the Vulkan and OpenGL layers), shaders.md and game-state.md, indexed by docs/reference/README.md. Each entry gives the symptom, the cause, the fix (file and function), the games it was found on (linked to their notes in dm/games/<id>/README.md) and any check, caveat or later change; one mechanism met on several games is one entry. docs/agents/symptoms.md lists every entry's symptom (an assertion, a [RED] line, an abort or crash site, a visible result) with a link to it, 350 lines, generated from the Symptom bullets. 03 keeps the loop and reading the log, and its Failure catalogue section now points to the references, the index and where a new finding goes; 04 keeps sections 1-5 and 7 (the container list is shaders.md's Containers by engine), and section 6 says where each kind of finding is. Facts in the old sections about one game only were checked against that game's note, where they already were. Statements the code no longer matches are marked as history beside the current value (movie output slots: MD_NOUT 64, MD_NOUT_AAC 32, MD_NOUT_VIDEO 16; APP_POOL is the profile key app_pool; Engage's layout is 5 / 4.375 GB; inline uniform updates are deferred by default; scaled copies are drawn), and Tears of the Kingdom joins the node-area entry's build list (issue #70). The game notes, docs/agents/README.md, 02 and 05 link to the exact entries, and so do the comments in nvn_mtl.m (nvnTextureCompare) and hle_audio.c (the RemoteIO buffer) and the provisional-profile note in profile_guess.py. 03 goes from 29,600 to 470 words, 04 from 34,400 to 3,500. Checked: every backticked span, module address, issue / PR number and 16-digit hash of AGENTS.md, development.md, dm/games/README.md and docs/agents/01-05 at 6a06877 (4,600 items) still appears in the repository's Markdown (the same five file patterns as before appear as the full names they stood for), every relative link and heading anchor in the repository's Markdown resolves, and the tool tests pass (the four that need capstone or lz4 in the T7 venv)
2026-10-25 12:31:58 +08:00
The host evaluates NVN conditional rendering for every game, and the profile key render_cond is gone: SetRenderEnable / SetRenderEnableConditional are always recorded and evaluated at replay (OP_RENDER_COND), every counter report is tracked (rc_note) and a timestamp report's counter field is 0, as on the GPU. Twelve profiles had the key (Tears of the Kingdom, Animal Crossing, Mario vs. Donkey Kong and others, whose scenes were black when the clears they skip ran); every other game drew its conditional blocks, which left Nintendo Switch Sports Resort's Select User grey with black outfits until it got the key. Two operand reads were wrong once every game evaluated: (1) an operand no report writes was read from memory at encode time, though a shader, copy or fill queued before the condition (in the submission, or one still running) writes it on the GPU first. Portal 2's D3D9 layer (NVIDIA's occlusion culling, IDirect3DDevice9::SetOcclusionShape, materialsystem.nro+0xc1130) has a shader write each mesh's visibility word (0xffff) into a 32 KB storage buffer bound read-write and draws the mesh under RENDER_IF_NOT_EQUAL on that pair: read before the shader ran, 0 / 0, and the vault's desk, microwave, fridge, lamp, TV, plant and blinds were dropped (its note's open bug). Such an operand is now known only when nothing queued writes its bytes (rc_value through rc_source, the check the uniform shadows make), else the block draws. (2) rc_source counted any page holding a report of the submission as written; a report writes its own 16 bytes, and every report has its entry now, so only those bytes count (hw_sub_hits): counted by page, Switch Sports' agl conditions read the CPU-written word 16 bytes after a timestamp record as unknown and 8 clears it skips ran (the court behind Select User wiped). dm/games/game.py ignores a leftover render_cond with a note (a derived profile in a build folder). Docs: the reference entry says the evaluation is the host's, new entry (A condition on a word the GPU writes), the keys table, docs_patches.py's binding row, the agents guide, profile_guess.py, TOTK's usage.tsv and the 22 game notes that named the key (each keyed game keeps its finding as a sentence); symptom index regenerated. Checked: t_render_enable_queue (62 checks: an operand a queued copy or buffer clear writes draws, one nothing writes is decided by memory, the word after a same-submission timestamp report is known; the first two fail with the memory read, the third with the page check), t_sbw (35: a record with no report is unknown while a GPU write anywhere still runs, read from memory once it landed), t_render_counter_overlap, the whole make -C dm/gfx/tests run list; test_game_profile, test_host_msl, test_nsp_*, test_patches, test_pso_offline, test_settings, test_ue_cvar, test_profile_guess, test_docs; lint_python (nothing new), lint_c tidy on the changed C files (at the baseline). Games, M6: Portal 2's vault with the conditions evaluated: its seven conditions unknown and drawn, the furniture there, no red line; Switch Sports' Select User: 8 clears skipped, 0 unknown, court and lit outfits as with the key before, 60 fps; regress.py check against f4b7e77c on Super Mario Odyssey (no key, occlusion queries in three rotating slots; 27,984 shaders, its old shader package split again first): CHANGED only by the red line gone, screenshots RGB 0.74 / 0.52, 58.9 / 59.4 fps. The new same-page test case failed three times in a row early on and then passed 81 runs (32 under parallel load), not explained. Not run: the other games that call conditions without the key (Wonder, Dark Souls, Big Brain Academy, TTYD, Kirby Air Riders, Star Fox, Fortune's Weave; their notes say not checked since), the iPhone.
2026-11-12 16:27:02 +08:00

Porting a Switch title: agent guide

These pages are for an agent asked to analyse a Switch NSP and port it with the native-execution approach of this repository and d2r-mobile: the game's own aarch64 code runs natively on Apple hardware, a rewriter patches only the instructions Apple's kernel cannot run, the host replaces Horizon system services, and NVN is reimplemented on Metal.

Everything here was learned on Diablo II: Resurrected (SDK ~12, NVN 53, the original target of d2r-mobile) and Super Mario Bros. Wonder (SDK 16.2.0, NVN 55, this repository; its update 1.2.1 uses SDK 16.2.12), then extended by Fire Emblem Engage (Unity, SDK 12.3.7), Metroid Dread (MercurySteam's engine, SDK 11.4.3) 13 Sentinels: Aegis Rim (Vanillaware's engine, SDK 11.4.3, the same sdk and movie module as Dread) Super Mario 3D World + Bowser's Fury (Nintendo EPD's sead / agl engine, SDK 10.4.0, NVN API 53) The Legend of Zelda: Breath of the Wild (EPD's sead / ksys engine, SDK 20.5.22, DT_RELR relocations, update 1.9.0), The Legend of Zelda: Link's Awakening (Grezzo's engine on NintendoWare, SDK 8.2.0, lower-left window origin) Hyrule Warriors: Age of Calamity (Koei Tecmo's KTGL, SDK 9.6.0, RDB archives, shaders as GLSLC outputs) Super Mario Galaxy (a Wii game on NERD's Hagi layer: recompiled PowerPC code, SDK 18.3.5, Vulkan with SPIR-V generated at run time, a 2.9 GB bss), Ace Attorney Investigations Collection (Unity 2022.3 IL2CPP, SDK 17.5.3: the C# file API through the SDK's C library), and the bring-up of Octopath Traveler 0 (Unreal Engine 5, SDK 19.3.13: an AES-encrypted pak, Oodle-compressed shaders that the game's own code decodes on the Mac, its allocator replaced by the host's). Where titles differed, each is given; the next title will differ again, so treat every number below as "measure it, don't assume it".

Page Covers
01-extract.md Keys, NSP → NCA → ExeFS / RomFS, update NSPs, the workspace layout
02-survey.md Static survey of a new title before touching the host: SDK version, imports vs. host hooks, SVCs, instructions to rewrite, NVN surface, data containers, Ghidra / REA setup
03-bringup.md Getting the host to boot the game: the run loop and how to read the log; the failures met so far are in the subsystem references, found through the symptom index
04-graphics.md NVN on Metal for a new title: finding every shader container, shader keys, binding layouts, bindless textures, depth mode, the diagnostic switches; what other titles needed is in the rendering, shaders and NVN objects references
05-debugging.md Recipes: crash reports, lldb scripts, Ghidra headless decompilation, objdump, memory growth, render-pass and texture dumps, on-device diagnostics, offline pipeline link checks
06-dev-loop.md The developer loop: which tool to build, run, debug, measure and check with, CI, and what a pull request needs by what it changes
symptoms.md One line per symptom met so far (an assertion, a [RED] line, an abort or crash site, a visible result) → the reference entry that explains it
game-patches.md Every piece of game-specific code: each game's rewriter patches, host rows keyed by its builds, the SDK cuts, and the profile keys that switch host behaviour, with each patch's binding (what it depends on now and the loosest it could depend on) and the gaps between them, the work list (generated by dm/tools/docs_patches.py)

Ground rules

  • Bring your own files. Keys, NSPs and anything extracted from them stay in the game's work folder ($W = <NSP folder>/<title>-work, next to the NSPs on the user's external drive; the home folder is nearly full), never in the repository, never in a commit, never printed. Print key names and lengths only.
  • Measure, then change. Each fix in this repository started from a concrete observation (a crash address and its decompilation, a census over all shaders, a memory profile). Write the evidence into the code comment next to the fix, the way the existing code does; the next title will need it.
  • Find the root cause; don't just work around it. A crash, hang or wrong picture is finished when its root cause is found and fixed there, not when it stops showing. Follow the bad value back to where it was written and the call back to the semantics the host gets wrong; a stub, skip, clamp, retry or timeout that only makes the symptom go away is a workaround, kept only when the root cause cannot be fixed and recorded as open (AGENTS.md).
  • One repository, one profile per title. nxnative (first called smbw-mobile) started as a copy of d2r-mobile's generic parts. Title- or SDK-specific constants live in the game profile dm/games/<id>/ (dm/games/README.md). That covers program ID, known builds, modules, address-space partition, NVN driver tables, the shader tables and the app identity. The code reads the profile through game_profile.h (host) or dm/games/game.py (tools). Behaviour that fits only one title's code is gated by that title's build ID (dm_main_build()), never left on for every title. Some things are still built into the translator: the texture / sampler handle bases and the depth mode (see 04). dmsh_build.py refuses a profile whose bases differ from the translator's.
  • Write code comments in English, and start log lines that mark something unimplemented or wrong with [RED] .
  • Test where it runs. The Mac host (dm/host/dmhost) is the development loop; the iOS app reuses the same host and graphics code. Never claim something works on iOS without running it there.

Checklist for a new title

  1. Run scripts/build_ipa_from_nsp.py on the title's NSP folder. With no profile for its title ID, it writes <NSP folder>/<title ID>_survey/survey.md:

    • modules and build IDs, SDK version and components, engine and graphics API markers;
    • RomFS containers;
    • the rewrite-site census and imports vs. host hooks.

    A 32-bit ARM program (main.npdm with the 64-bit instruction flag clear: Pikmin 3 Deluxe, New Super Mario Bros. U Deluxe) stops the survey with a red line: Apple silicon cannot run 32-bit ARM code, and the native-execution approach has no translator for it. The same check stops a 32-bit version of a game that has a profile (Mario Kart 8 Deluxe 1.0.0, reported in LNPANDY/NX2Apple#116) right after extraction, naming the registered versions to pack instead.

    It extracts only the code modules plus a RomFS list for the survey. Unless given --survey-only, it then writes a provisional profile into <NSP folder>/<title ID>_build/profile/<title ID>/, extracts the game, boots it on the Mac until its heap request when it has virtual address memory (the heap check) and packs a best-effort IPA. That profile is the starting point for step 3: the static keys follow rules checked against every profile, the rest are guesses or defaults (dm/games/README.md); the run-time keys (tex_flush_upload, core_preempt, …) are the bring-up's to find. For Mac runs, export DM_GAMES_DIR=<NSP folder>/<title ID>_build/profile until the profile moves into dm/games/.

  2. Extract base (and update, if in scope) — 01. Finish the survey — 02. Write down: SDK version, NVN API version, module list, imports the host lacks, SVCs, instruction census, NVN loader pattern, shader containers.

  3. Add a game profile dm/games/<title ID>/game.tsv, named after the base game's title ID (start from 010015100B514000/game.tsv: identity, build rows, modules; keep the memory / NVN values until they are measured) and build the host for it with make -C dm/host GAME=<id>.

  4. Run the rewriter and check its counts against insn_census.py.

  5. Boot on the Mac and iterate (03) until the game reaches its frame loop: look up each failure in the symptom index, which leads to its entry in the subsystem references.

  6. Extract and translate the shaders, find the binding layout by census, and get the first frame — 04.

  7. Check memory over a minute of running (footprint, the host's memory report line); fix growth before moving on.

  8. Input, audio, then the iOS bundle (d2r-mobile's dm/ios, RomFS inside the app).

  9. Test on a phone: an unsigned IPA the user sideloads, switches through env.txt, results through Documents/log.txt (05). Several bugs only showed there (the command-buffer byte and the audio buffer size, pipeline link failures in later levels in 04).

  10. For a game update: extract it over the base game, diff the imports, carry the per-build addresses over, and rebuild the shader tables for both versions (01).