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
2 changes: 2 additions & 0 deletions dm/games/0400486024DEC000/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ A Switch 2 game: update v131072, SDK 22.2.8 (`Ounce`). Nintendo EPD's engine (se

One [NUP container](../../../docs/development.md#the-packing-script-in-detail) of 25.6 GB: `scripts/pack_nup.py` unpacks it to `extract/v131072/`. The RomFS keeps most files as zstd with dictionaries from `Pack/ZsDic.pack.zs`. The movies are AV1.

The NUP at hand has three damaged files: `Tex/CmnTex_Map_Soil_FairyFountain_Floor_D_Nrm.bntx.zs`, `Tex/Rock_WaterTemple_Gate_M_01_Nrm.bntx.zs` and `Tex/RBake_Scene_GanonStage_G_2_1_d0_t0.bntx.zs` begin with 12 KB of zeros (the container's SHA-256 of them matches, so they were so when it was packed; whether a retail copy has them is not known; the other 102,182 `.zs` files begin with a zstd frame). The first kept the Kokiri Forest fairy fountain model from ever loading: the `OptimizeChangeBanc` thread asked for it ~22 times a second all session (one core) and a `ParallelDecompThread` decompressed its 2.4 MB each time (~0.75 core). The profile key `romfs_substitute` serves them as the game's 1x1 flat normal map (the Ganon stage bake as its neighbour cell's): Mac CPU 412% → 180%, frame p95 21.9 → 18.8 ms ([A `.zs` file that is not a zstd stream](../../../docs/reference/packing.md#a-zs-file-that-is-not-a-zstd-stream)).

## Shaders

- About 42,850 in [`shader_map.tsv`](shader_map.tsv), including 500 mesh and 20 task shaders in the BNSH programs ([Task and mesh shaders in BNSH](../../../docs/reference/shaders.md#task-and-mesh-shaders-in-bnsh-and-indirect-mesh-draws)), and the movie library's in an NDVE pack ([`nn::ndve`](../../../docs/reference/shaders.md#nnndves-movie-enhancement-file)).
Expand Down
7 changes: 7 additions & 0 deletions dm/games/0400486024DEC000/game.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ modules main subsdk0 sdk
romfs_marker Pack/ZsDic.pack.zs
zip_store .zs:.bwav:.webm:.metallib

# In the NUP at hand three RomFS files begin with 12 KB of zeros (the container's SHA-256 of them matches, so they were so when it was packed; whether a retail copy has them is not known), so they cannot be decompressed. Served as stored, the fairy
# fountain model that uses the first never loaded and the OptimizeChangeBanc thread (main+0xf7a0) asked for it again ~22 times a second all session: one core, plus ~0.75 core of
# ParallelDecompThread decompressing the 2.4 MB model each time (Mac CPU 365%, iPad 400-460%). "Not found" fails the model the same way. Served as the game's own 1x1 flat normal map, the
# model loads once and both threads go idle (Mac CPU 412% -> 180%, frame p95 21.9 -> 18.8 ms). The Ganon stage bake is served as its neighbour cell's (not checked in game). A copy without the damage
# needs none of this: the host substitutes only a .zs file that is not a zstd stream (hle_fs.c img_serve)
romfs_substitute Tex/CmnTex_Map_Soil_FairyFountain_Floor_D_Nrm.bntx.zs=Tex/Dummy_Flat_Normal_CmnTex_Chara_DetailMap_Nrm.bntx.zs Tex/Rock_WaterTemple_Gate_M_01_Nrm.bntx.zs=Tex/Dummy_Flat_Normal_CmnTex_Chara_DetailMap_Nrm.bntx.zs Tex/RBake_Scene_GanonStage_G_2_1_d0_t0.bntx.zs=Tex/RBake_Scene_GanonStage_G_2_2_d0_t0.bntx.zs

# ---- Memory ----
# The Switch 2 leaves games 9 GB of its 12 GB (Donkey Kong Bananza's figure). The NPDM declares 48 MB of system resource, so virtual address memory is on.
# nninitStartup asks SetHeapSize 0x18ce00000 (6.2 GB) with the 9 GB pool, as Mario Kart World. 256 MB in front + 4 GB alias region + 256 MB stack region + 8 GB heap region: a starting split, to be measured
Expand Down
1 change: 1 addition & 0 deletions dm/games/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ One row per profile; the notes are each profile's `README.md`.
| `gpu_timestamps` | What a timestamp report (`nvnCommandBufferReportCounter`) records: `submission` (the default) = the time the whole submission completed, the same for every report in it; `segment` = the GPU start (`TIMESTAMP_TOP`) or end (the other types) of the segment the report was encoded in (the host commits a submission in segments of 64 draws, `sub_cut` in `nvn_mtl.m`), so two reports of one submission bracket the GPU time between them, as on hardware. Breath of the Wild needs `segment`: its frame-interval controller and its dynamic resolution read the GPU time between the frame's first and last report, and with one time for both they read 0 (the game kept 60 fps in slow motion when the GPU could not keep up). `DM_NVN_GPU_TS=segment` / `submission` overrides it, also from `Documents/env.txt` |
| `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 vertex-stage reads of the previous pass's output without a barrier change order. `DM_NVN_BARRIER` overrides it |
| `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 |
| `romfs_substitute` | `<path>=<substitute path>` pairs, RomFS paths without a leading `/` (none by default): a RomFS image file named `*.zs` that does not begin with a zstd frame (damaged) is served as the other image file (`hle_fs.c` `img_serve`; `DM_ROMFS_SUBST` replaces the list); one without a substitute is answered "not found". Ocarina of Time: three textures of the NUP at hand begin with 12 KB of zeros; the fairy fountain's normal map, served as the game's 1x1 flat normal, ends the OptimizeChangeBanc reload loop (one core all session). |
| `shader_key_skip` | `<offset>+<length>` (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` |

Expand Down
3 changes: 3 additions & 0 deletions dm/games/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,8 @@ def header_one(g):
if dbr not in ('full', 'game'): sys.exit(f'{g.id}: draw_barriers must be full or game: {dbr}')
gts = g.get('gpu_timestamps', 'submission') # counter timestamps (nvn_mtl.m rep_ticks): submission = one time per submission, segment = the GPU start / end of the segment holding the report
if gts not in ('submission', 'segment'): sys.exit(f'{g.id}: gpu_timestamps must be submission or segment: {gts}')
rsub = ' '.join(g.get('romfs_substitute', '').split()) # damaged RomFS files (a .zs that is not a zstd stream) served as another image file (hle_fs.c img_serve; DM_ROMFS_SUBST overrides): <path>=<substitute path> ...
if any(w.count('=') != 1 or w.startswith(('=', '/')) or w.endswith('=') or '=/' in w for w in rsub.split()): sys.exit(f'{g.id}: romfs_substitute takes <path>=<substitute path> pairs, RomFS paths without a leading /: {rsub}')
om = g.get('op_mode', 'console') # the operation mode reported at start (hle_oe.c dm_opmode; DM_OPMODE overrides): console = docked, handheld = touch screen in use (Super Mario Galaxy's pointer)
if om not in ('console', 'handheld'): sys.exit(f'{g.id}: op_mode must be console or handheld: {om}')
if pl == 'touch' and om != 'handheld': sys.exit(f'{g.id}: pad_layout touch needs op_mode handheld (the touch screen reaches the game only in handheld mode)')
Expand Down Expand Up @@ -265,6 +267,7 @@ def header_one(g):
f'#define DM_GAME_DRAW_BARRIERS_GAME {int(dbr == "game")}',
f'#define DM_GAME_UPSCALER_KEYS {q(",".join(ups))}', f'#define DM_GAME_UPSCALER_N {len(ups)}',
f'#define DM_GAME_VCONV_RANGE {int(vcr == "on")}',
f'#define DM_GAME_ROMFS_SUBST {q(rsub)}',
*([f'#define DM_GAME_NVN_API_MAJOR {api.split(".")[0]}', f'#define DM_GAME_NVN_API_MINOR {api.split(".")[1]}'] if g.get('device_api', '') else []), # without the key: by the SDK version (hle_nvn.c nvn_api)
'']
return '\n'.join(L)
Expand Down
59 changes: 58 additions & 1 deletion dm/host/hle_fs.c
Original file line number Diff line number Diff line change
Expand Up @@ -784,6 +784,62 @@ HLE_FORCE("_ZN2nn2fs7UnmountEPKc", "fsp-srv; host mounts are permanent, a no-op;
}

// ---------- Files ----------
// A RomFS image file named *.zs that does not begin with a zstd frame (or a skippable frame) cannot be decompressed. Such a file is served as the substitute the profile key
// romfs_substitute names for it (<damaged path>=<substitute path> pairs, image paths without the mount; DM_ROMFS_SUBST replaces the profile's list), else answered "path not found", as a file
// the dump lacks; one [RED] line names it. Ocarina of Time (Switch 2), the NUP at hand: Tex/CmnTex_Map_Soil_FairyFountain_Floor_D_Nrm.bntx.zs, Tex/Rock_WaterTemple_Gate_M_01_Nrm.bntx.zs and
// Tex/RBake_Scene_GanonStage_G_2_1_d0_t0.bntx.zs begin with 12 KB of zeros (the container's SHA-256 of them matches: they were so when it was packed; whether a retail copy has them is not known). Served as stored, the fairy fountain model that uses
// the first (Model/Land_FairyFountain_Base_A.Land_FairyFountain_Base_A_01.bfres) failed to load, and the OptimizeChangeBanc thread (main+0xf7a0) asked for it again about 22 times a second for
// the whole session: its pass over the 852 entries of the area never ended "all done", so it never went back to its 16 ms sleep (one core, ~980 ms/s, on the Mac and the iPad), and a
// ParallelDecompThread decompressed the 2.4 MB model each time (~750 ms/s). "Not found" fails the model the same way (the game then asks for the .bntx, also missing); the game's own 1x1 flat
// normal map (Tex/Dummy_Flat_Normal_CmnTex_Chara_DetailMap_Nrm.bntx.zs) in its place loads the model once, and both threads go idle: Mac CPU 412% -> 180% (medians of 5-minute runs).
// Checked once per entry, at its first open or entry type (4 bytes); DM_ROMFS_ZSTD_CHECK=0 serves such files as stored
#define IMG_ENT_ZCHECKED 4 // in memory only: the zstd head check has run for this entry
#define IMG_ENT_BADZSTD 8 // in memory only: ... and found no zstd frame at the start
#ifndef DM_GAME_ROMFS_SUBST
#define DM_GAME_ROMFS_SUBST ""
#endif
static int64_t img_subst(mount_t *m, const char *path, const char **donor, int *dlen) { // the substitute entry for a damaged path (-1: none named, or not in the image)
const char *c = strchr(path, ':'), *rest = c ? c + 1 : path, *s = getenv("DM_ROMFS_SUBST");
while (*rest == '/') rest++;
if (!s) s = DM_GAME_ROMFS_SUBST;
size_t rl = strlen(rest);
while (*s) {
while (*s == ' ' || *s == '\t') s++;
const char *end = s + strcspn(s, " \t"), *eq = memchr(s, '=', (size_t)(end - s));
if (eq && (size_t)(eq - s) == rl && !memcmp(s, rest, rl)) {
char d[1024]; snprintf(d, sizeof d, "/%.*s", (int)(end - eq - 1), eq + 1);
if (donor) { *donor = eq + 1; *dlen = (int)(end - eq - 1); }
int64_t k = img_find(m->img, d);
return k > 0 && m->img->e[k].type ? k : -1;
}
s = end;
}
return -1;
}
// The entry to serve for entry k: k itself, a damaged file's substitute, or -1 (answered "not found")
static int64_t img_serve(mount_t *m, int64_t k, const char *path) {
img_ent *ent = &m->img->e[k];
const char *nm = m->img->names + ent->name;
if (!ent->type || ent->nlen <= 3 || memcmp(nm + ent->nlen - 3, ".zs", 3)) return k; // other files keep their flags as they are
uint8_t f = __atomic_load_n(&ent->flags, __ATOMIC_ACQUIRE);
if (f & IMG_ENT_ZCHECKED) return f & IMG_ENT_BADZSTD ? img_subst(m, path, NULL, NULL) : k;
static int on = -1; if (on < 0) { const char *e = getenv("DM_ROMFS_ZSTD_CHECK"); on = !(e && *e == '0'); }
int bad = 0; int64_t r = k;
if (on && ent->b >= 4) {
uint8_t h[4];
if (romfs_image_read(m->img->fd, h, 4, (off_t)ent->a)) {
uint32_t mg = (uint32_t)h[0] | (uint32_t)h[1] << 8 | (uint32_t)h[2] << 16 | (uint32_t)h[3] << 24;
bad = mg != 0xFD2FB528u && (mg & 0xFFFFFFF0u) != 0x184D2A50u;
if (bad) {
const char *d = NULL; int dl = 0; r = img_subst(m, path, &d, &dl);
if (r >= 0) LOG("[RED] fs %s is not a zstd stream (begins %02x %02x %02x %02x; damaged): served as %.*s (romfs_substitute)", path, h[0], h[1], h[2], h[3], dl, d);
else LOG("[RED] fs %s is not a zstd stream (begins %02x %02x %02x %02x; damaged): answered \"not found\"%s (DM_ROMFS_ZSTD_CHECK=0 serves it as stored)", path, h[0], h[1], h[2], h[3], d ? ", its substitute is not in the image" : "");
}
}
}
__atomic_fetch_or(&ent->flags, (uint8_t)(IMG_ENT_ZCHECKED | (bad ? IMG_ENT_BADZSTD : 0)), __ATOMIC_RELEASE);
return r;
}
HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Result, h_fs_OpenFile, uint64_t *out, const char *path, int mode) { dm_thread_service_request();
int mi; int64_t k;
if (img_path(path, &mi, &k)) {
Expand All @@ -793,6 +849,7 @@ HLE_FORCE("_ZN2nn2fs8OpenFileEPNS0_10FileHandleEPKci", "fsp-srv → open(2)", Re
img_ent *ent = &g_mnt[mi].img->e[k]; // a damaged file is named once, at its first open
if ((ent->flags & IMG_ENT_DAMAGED) && !(__atomic_fetch_or(&ent->flags, IMG_ENT_REPORTED, __ATOMIC_RELAXED) & IMG_ENT_REPORTED))
LOG("[RED] fs %s failed the NCA's hash check when it was extracted (a damaged NSP, --allow-damaged); its bytes may be wrong", path);
if ((k = img_serve(&g_mnt[mi], k, path)) < 0) return RES_PATH_NOT_FOUND;
*out = FH_OUT(IMG_HANDLE(mi, k));
if (g_flag.fs) LOG("fs open [%.2fs] %s mode=%d → image entry %lld", (now_ns() - g_t0_ns) / 1e9, path, mode, (long long)k);
return RES_OK;
Expand Down Expand Up @@ -982,7 +1039,7 @@ HLE_FORCE("_ZN2nn2fs10RenameFileEPKcS2_", "fsp-srv → rename(2)", Result, h_fs_
HLE_FORCE("_ZN2nn2fs15RenameDirectoryEPKcS2_", "fsp-srv → rename(2) of a directory", Result, h_fs_RenameDir, const char *from, const char *to) { dm_thread_service_request(); return rename_entry(from, to); }
HLE_FORCE("_ZN2nn2fs12GetEntryTypeEPNS0_18DirectoryEntryTypeEPKc", "fsp-srv → stat(2)", Result, h_fs_GetEntryType, int32_t *out, const char *path) { dm_thread_service_request();
int mi; int64_t k;
if (img_path(path, &mi, &k)) { if (k < 0) return err_res("stat", path); *out = g_mnt[mi].img->e[k].type ? ENT_FILE : ENT_DIR; return RES_OK; }
if (img_path(path, &mi, &k)) { if (k < 0) return err_res("stat", path); if (img_serve(&g_mnt[mi], k, path) < 0) return RES_PATH_NOT_FOUND; *out = g_mnt[mi].img->e[k].type ? ENT_FILE : ENT_DIR; return RES_OK; } // a damaged .zs without a substitute is "not found" here too (img_serve)
HP(path); struct stat st;
if (stat(hp, &st)) return err_res("stat", hp);
*out = S_ISDIR(st.st_mode) ? ENT_DIR : ENT_FILE; return RES_OK;
Expand Down
8 changes: 5 additions & 3 deletions dm/host/probe.c
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ void crash_set_trap_hook(int (*fn)(ucontext_t *uc));
// The trampoline borrows x16: place probes only at function entries or at points where x16 is dead; the original instruction must not be PC-relative (adr/adrp/b/bl/ldr literal/cbz...).
#define MAX_PROBE 16
typedef void (*probe_fn)(ucontext_t *uc);
static struct { uint64_t at; uint32_t *slot; unsigned hits; char name[40]; long dump, dpost; probe_fn fn; int freg; long foff; uint64_t fval; int hreg; } g_probe[MAX_PROBE]; // dpost: @*xN+off+dpost
static struct { uint64_t at; uint32_t *slot; unsigned hits, seen; char name[40]; long dump, dpost; probe_fn fn; int freg; long foff; uint64_t fval; int hreg; } g_probe[MAX_PROBE]; // dpost: @*xN+off+dpost

// !xN: treat xN as a sead::ExpHeap and print its free and used blocks (block size at block +0x18, alignment pad at +0x12). Settings (docs/agents/05-debugging.md):
// DM_PROBE_HEAP=<name>,<start>,<size>,<free list>,<used list> layout by sead version (hex; node offset at list +0x14), default SMBW 0,28,30,b0,c8 (no name), BotW 28,38,40,e0,f8;
Expand Down Expand Up @@ -78,7 +78,7 @@ static void probe_heapwalk(uint64_t h) {
} // dump: on hit print 16 bytes at [x0+dump] (-1 = do not print); fn: dedicated handler (replaces the default print)
static int g_nprobe;
static uint64_t g_probe_frame_first, g_probe_frame_last = UINT64_MAX;
static unsigned g_probe_limit;
static unsigned g_probe_limit, g_probe_every; // DM_PROBE_LIMIT printed hits per probe; DM_PROBE_EVERY=N every hit counts, every N-th prints (#N is then the true hit count: rates)
uint64_t dm_guest_frame(void);
static void probe_str(uint64_t p) {
char buf[80]; vm_size_t got = 0;
Expand Down Expand Up @@ -112,6 +112,7 @@ static int probe_hit(ucontext_t *uc) { // Registered by probe_install with the
for (int i = 0; i < g_nprobe; i++) if (g_probe[i].at == pc) {
if (g_probe[i].fn) { g_probe[i].hits++; g_probe[i].fn(uc); uc->uc_mcontext->__ss.__pc = (uint64_t)g_probe[i].slot; return 1; }
uint64_t frame = dm_guest_frame();
if (g_probe_every && frame >= g_probe_frame_first && frame <= g_probe_frame_last && ++g_probe[i].seen % g_probe_every) { uc->uc_mcontext->__ss.__pc = (uint64_t)g_probe[i].slot; return 1; }
if (frame < g_probe_frame_first || frame > g_probe_frame_last || (g_probe_limit && g_probe[i].hits >= g_probe_limit)) {
uc->uc_mcontext->__ss.__pc = (uint64_t)g_probe[i].slot; return 1;
}
Expand All @@ -126,7 +127,7 @@ static int probe_hit(ucontext_t *uc) { // Registered by probe_install with the
}
probe_dump_once();
flockfile(stderr); // One block per hit when threads hit at once
{ extern uint64_t g_t0_ns; uint64_t now_ns(void); uint32_t thr_cur_handle(void); fprintf(stderr, "[dm] PROBE %s #%u [%.4fs] F=%llu T=%x", g_probe[i].name, ++g_probe[i].hits, (now_ns() - g_t0_ns) / 1e9, (unsigned long long)frame, thr_cur_handle()); }
{ extern uint64_t g_t0_ns; uint64_t now_ns(void); uint32_t thr_cur_handle(void); ++g_probe[i].hits; fprintf(stderr, "[dm] PROBE %s #%u [%.4fs] F=%llu T=%x", g_probe[i].name, g_probe_every ? g_probe[i].seen : g_probe[i].hits, (now_ns() - g_t0_ns) / 1e9, (unsigned long long)frame, thr_cur_handle()); }
for (int r = 0; r < 8; r++) { uint64_t v = uc->uc_mcontext->__ss.__x[r]; fprintf(stderr, " x%d=%#llx", r, v); probe_str(v); }
for (int r = 19; r < 24; r++) fprintf(stderr, " x%d=%#llx", r, uc->uc_mcontext->__ss.__x[r]);
if (getenv("DM_PROBE_ALL")) for (int r = 8; r < 19; r++) fprintf(stderr, " x%d=%#llx", r, uc->uc_mcontext->__ss.__x[r]); // also print x8–x18
Expand Down Expand Up @@ -381,6 +382,7 @@ void probe_install(void) {
}
const char *limit = getenv("DM_PROBE_LIMIT");
if (limit) g_probe_limit = (unsigned)strtoul(limit, NULL, 10);
if ((limit = getenv("DM_PROBE_EVERY"))) g_probe_every = (unsigned)strtoul(limit, NULL, 10);
const char *e = getenv("DM_PROBE");
if (e) {
char spec[512]; strlcpy(spec, e, sizeof spec);
Expand Down
Loading
Loading