NVN recordings take no more command memory than the driver's commands: a recording's end, its links and its calls are in control memory, as in NVN, and what games record per mesh takes compact forms the queue expands at submit, so a typical mesh draw takes 88 bytes where the driver takes 132 and the host took 112 (PR #1609)

Engines that size a model's prerecorded commands by measuring scratch recordings against a fixed resource budget ran out of it with the host's records: Super Mario Bros. Wonder's Nintendo Switch 2 Edition (NpcCommonerA 0x5424 of 0x5000) and Drag x Drive (5 s after boot), BufferInitialize with no pool, then a crash in nvnMemoryPoolGetFlags. PR #1609 shrank one-draw recordings to 4-byte tickets behind a profile key; this fixes the cause for every game instead.

- Control memory: each recording's control list is 8-byte entries in the game's control memory (pieces of records, links to more control memory); the handle is the list. Command memory holds only records: no END, no JUMP, no CALL, nothing past what GetCommandMemoryUsed reported. GetControlMemoryUsed / Free count the entries; the game's out-of-control-memory callback is called (Cuphead refills from it), and the host lends blocks when it gives none.
- CallCommands copies the called list's pieces into the caller, as the driver copies a command set's GPU FIFO entries: Donkey Kong Bananza resets its control arena twice per command arena, and while a call pointed at the called list the caller replayed overwritten entries (FATAL invalid NVN command size in about one 100 s run in six). CopyCommands copies the records.
- Compact records (nvn_obj.h OPC_*): draws, viewports, stencil values, handle binds, uniform / storage / vertex buffer binds, vertex state, small states, barrier, primitive restart, scissor, with small arguments in the header's upper 24 bits. The queue's flatten (and nvn_rec_linear) expands each into the canonical records, so replay, capture and the replay walkers see no new op.
- Sized against the driver's own commands: dm/tools/nvn_native_sizes.py finds the NVN driver in a game's sdk (names, implementations, the command buffer layout from its getters) and runs each call in Unicorn. NVN1 (Fire Emblem: Three Houses, Cuphead, Minecraft Dungeons II) and NVN2 (Ocarina of Time, Donkey Kong Bananza) agree; five calls stay above the driver's at the 8-byte header's floor (depth-stencil state, BindTexture kept for Luigi's Mansion 3's in-place patch, storage buffer, blend color, scissor). Table in docs/reference/memory.md.

Checked: t_nvn 290/290 (51 calls recorded compact and canonical expand byte for byte; calls replay after the called list's control memory is overwritten, copies after both of the source's memories are; a list linked across control blocks), the gfx suite, lint. Minecraft Dungeons II on the Mac: the same picture in Squid Coast as before (its early stall at frame 120-140 happens on the old host too). Donkey Kong Bananza on the Mac (no shader libraries for this chain): three 100 s runs without a crash, command bytes per frame 127 -> 88 KB. Not run: the Wonder Edition and Drag x Drive (not on this Mac), iOS, Ocarina of Time (its pipeline preparation outlasts a run here).

Co-authored-by: ishtiaq156 <[email protected]>
This commit is contained in:
seeddsandishtiaq156 committed 2026-11-10 18:16:31 +08:00
1 parent 629dd75297
commit f02d0474cf
17 files changed
+953 -187

No files matched your search

+2 -2
View File
@@ -54,7 +54,7 @@ Game-specific findings. The general host changes they led to are listed under [F
## Command memory
- **Resolved (issue #61): `CRASH sig=10` in `mtl_exec` after minutes of play**, the fault address equal to `x19` and shaped like `0x1000000003`. The game gives each model's prerecorded lists fixed slots of the size a recording of that list measured (`GetCommandMemoryUsed`), slot k at base + size × k, and passes `AddCommandMemory` max(size, 512) (`main+0xbb120`); its memory callback is empty. A JUMP the host wrote after a 496-byte list reached 8 bytes into the next slot. The host now never writes past what `GetCommandMemoryUsed` reported (`OP_RESERVE`, [Prerecorded lists in slots of their measured size](../../../docs/reference/nvn-objects.md#prerecorded-lists-in-slots-of-their-measured-size)).
- **Resolved (issue #61): `CRASH sig=10` in `mtl_exec` after minutes of play**, the fault address equal to `x19` and shaped like `0x1000000003`. The game gives each model's prerecorded lists fixed slots of the size a recording of that list measured (`GetCommandMemoryUsed`), slot k at base + size × k, and passes `AddCommandMemory` max(size, 512) (`main+0xbb120`); its memory callback is empty. A JUMP the host wrote after a 496-byte list reached 8 bytes into the next slot. The host now never writes past what `GetCommandMemoryUsed` reported: command memory holds only the records, and a recording's end and links are in control memory ([Prerecorded lists in slots of their measured size](../../../docs/reference/nvn-objects.md#prerecorded-lists-in-slots-of-their-measured-size)).
## Services
@@ -134,7 +134,7 @@ General host changes first needed here; each applies to every game:
- **Mid-pass, partial-mask and partial-scissor clears** drawn as a triangle (`clear_color_tri` / `clear_ds_tri`), **8-bit indices widened on the GPU** when written in the same submission (`wide_run`), **`ReadTexels` from guest memory on any thread** with `nvn_ft_poll` marking textures written after first use, **attachment-less passes** (`bare_dims`): same section.
- **Rewriter:** out-of-line atomic retry blocks (`retry_block` / `site_retry_window`, 8 sites) and jump tables relative to an `adr` (`jump_adr_offsets`, `main+0x393bb0`): [Out-of-line retry blocks of atomic updates](../../../docs/reference/rewriter.md#out-of-line-retry-blocks-of-atomic-updates), [Offset tables relative to an adr](../../../docs/reference/rewriter.md#offset-tables-relative-to-an-adr).
- **Resolved: black screen at boot since `9a56ecf` (issue #247), handoffs that waited for the whole core:** [Same-core wake handoffs](../../../docs/reference/threads.md#same-core-wake-handoffs). Each wake's handoff waited for every runnable higher-priority thread pinned to the caller's core. `BootupBackgroundWorkThread` (priority 58) then waited 200–290 ms at a time for `ARes Loading 1`, `Presentation Thread` and `BaseProcExecutor`, threads its wake had not made runnable. Checked on the Mac with update 1.4.3 and no shader libraries for chain `8393d85a4eae` (draws skipped), the issue #70 route for 180 s. On `82ab25b` the scene stayed empty (`84 functions 771 calls` a frame, no texture uploaded), and handoffs waited 250,008 ms in total. With handoffs limited to the threads the wake made runnable, they waited 1,221 ms, and the run matched `9feac2f` (before the change) frame by frame: 11 first uploads in both, 14,500–20,500 calls a frame. Gameplay with shaders has not been rechecked.
- **Slotted command lists** (`OP_RESERVE`, `t_nvn` "slotted lists"): [Prerecorded lists in slots of their measured size](../../../docs/reference/nvn-objects.md#prerecorded-lists-in-slots-of-their-measured-size).
- **Slotted command lists** (`t_nvn` "slotted lists"): [Prerecorded lists in slots of their measured size](../../../docs/reference/nvn-objects.md#prerecorded-lists-in-slots-of-their-measured-size).
- **Resolved in the NSP script's extractor: a cartridge dump with the update on it** (1G+1U XCI, [PR #311](https://github.com/seedds/nxnative/pull/311)): [A cartridge dump with its update on it extracts the update as the base game](../../../docs/reference/packing.md#a-cartridge-dump-with-its-update-on-it-extracts-the-update-as-the-base-game).
- **Resolved in the NSP script: a base NSP without a ticket or a title ID in its name** ([LNPANDY/NX2Apple#177](https://github.com/LNPANDY/NX2Apple/issues/177)) is identified by its meta NCA: [An NSP without a ticket or a title ID in its name](../../../docs/reference/packing.md#an-nsp-without-a-ticket-or-a-title-id-in-its-name-stops-with-no-nsp-with-a-readable-title-id).
+1
View File
@@ -74,6 +74,7 @@ Each step below stopped the boot before its fix:
## Found on this game
- Calls copy the called list's pieces: its control memory comes from one arena reset twice per arena of command memory, so a call that pointed at the called list replayed overwritten entries: [A recording's end and links are in control memory](../../../docs/reference/nvn-objects.md#a-recordings-end-and-links-are-in-control-memory).
- [Early fragment tests from the control section](../../../docs/reference/shaders.md#early-fragment-tests-from-the-control-section): 2,855 of its 13,546 pixel shaders set the NVN2 flag (control +0x5b), none of them writes depth; before, no NVN2 shader got the attribute.
- [A control section's words read as a BAHS entry](../../../docs/reference/shaders.md#a-control-sections-words-read-as-a-bahs-entry): checked, 2026-11-10 ([issue #1613](https://github.com/seedds/nxnative/issues/1613)). The update v458752, split again without the DLC (whose tables are derived), gives all four tables byte for byte as the profile has them: no false entry, and the NSP script's table check passes.
- [A prebuild pool sized from the Super cores](../../../docs/reference/shaders.md#a-prebuild-pool-sized-from-the-super-cores): the pipeline prebuild of its 21,225 shader pairs, M5 Pro, 393-452 s on 4 workers against 187-272 s on Metal's 14 (resolved).
+333 -56
View File
@@ -900,13 +900,15 @@ NVN(nvnQueueFinish, void, NVNqueue *q) { nvn_queue_finish((queue_t *)q); }
// ---------- Command buffer: record into the game's command memory, perform CPU-visible side effects at submit ----------
#define CB(c) ((cmd_t *)(c))
// Room kept at the segment end after every record but the END: one JUMP. The END needs none (nothing follows it), and every other record is at least 16 bytes, so a JUMP
// only ever stands where a record was to go: linking never writes past the bytes the recording takes in one piece, which is what GetCommandMemoryUsed reports and games size
// command memory by. Tears of the Kingdom (GitHub issue #61) gives each model's prerecorded lists fixed slots of the size a recording of that list measured, slot k at
// base + size × k, and passes AddCommandMemory max(size, 512) (main+0xbb120). With 24 bytes kept for "a JUMP or an END", a 496-byte list's END did not fit in 512,
// went to a host segment, and the 16-byte JUMP at 488 reached 8 bytes into the next slot; recording that slot wrote its first record over the JUMP's target, and the
// replay jumped to 0x1000000003 (that CALL record's header) after 8 to 30 minutes of play
#define OP_RESERVE 16
// Command memory holds only the records; what strings them together is in the game's control memory (nvn_obj.h ctl_e), as NVN keeps a recording's end, the links between its
// pieces of command memory and its calls of other recordings in control memory (the device reports control memory aligned to 8 bytes, item 0x14, and at least 256 of it, 0x16).
// So nothing is ever written past what GetCommandMemoryUsed reported, which games size and place their command memory by:
// - Tears of the Kingdom (GitHub issue #61) gives each model's prerecorded lists fixed slots of the size a recording of that list measured, slot k at base + size × k, and passes
// AddCommandMemory max(size, 512) (main+0xbb120). A JUMP written after the last record that fit reached 8 bytes into the next slot, whose first record overwrote its target,
// and the replay jumped to 0x1000000003 (that CALL record's header) after 8 to 30 minutes of play.
// - Engines that measure scratch recordings to size a model's prerecorded commands against a fixed resource budget (Breath of the Wild, Super Mario Bros. Wonder and its Nintendo
// Switch 2 Edition, Drag x Drive) counted 8 bytes of END per recording, and 16 per call and per link, that the driver puts in control memory (docs/reference/memory.md,
// "Model heaps sized by the host's command record sizes").
NVN(nvnCommandBufferInitialize, NVNboolean, NVNcommandBuffer *c, NVNdevice *d) {
memset(c, 0, sizeof(cmd_t)); CB(c)->magic = MAGIC('C', 'M', 'D', 'B'); CB(c)->dev = d; return 1;
@@ -917,27 +919,28 @@ NVN(nvnCommandBufferSetMemoryCallbackData, void, NVNcommandBuffer *c, void *d) {
static uint8_t *align8(uint8_t *p) { return (uint8_t *)(((uintptr_t)p + 7) & ~(uintptr_t)7); }
// Diagnostic DM_NVN_CMDSTAT=1: every 300 frames log one line of command recording usage -- how many bytes / records were recorded per frame, how large a command memory segment the game gives each time, how many out-of-memory callbacks per frame, how many host-supplied segments,
// and the count and bytes of each command type (to find "how much larger our records are than real-device commands"). Counts only; does not change recording / replay
static struct { int on; uint64_t bytes, recs, grants, grant_bytes, grant_min, grant_max, cbs, hostseg, op_n[64], op_b[64], frame0, waste; } g_cs = { .on = -1 };
static struct { int on; uint64_t bytes, recs, grants, grant_bytes, grant_min, grant_max, cbs, hostseg, op_n[256], op_b[256], frame0, waste; } g_cs = { .on = -1 };
static pthread_mutex_t g_cs_mu = PTHREAD_MUTEX_INITIALIZER;
uint64_t dm_nvn_frame_count(void);
static int cs_on(void) { if (g_cs.on < 0) g_cs.on = getenv("DM_NVN_CMDSTAT") != NULL; return g_cs.on; }
static void cs_op(uint32_t op, uint32_t size) { if (!cs_on() || op >= 64) return; pthread_mutex_lock(&g_cs_mu); g_cs.op_n[op]++; g_cs.op_b[op] += size; pthread_mutex_unlock(&g_cs_mu); }
static void cs_op(uint32_t op, uint32_t size) { op &= 0xff; if (!cs_on()) return; pthread_mutex_lock(&g_cs_mu); g_cs.op_n[op]++; g_cs.op_b[op] += size; pthread_mutex_unlock(&g_cs_mu); }
static void cs_dump(void) { // Called once per frame (at present)
if (!cs_on()) return; uint64_t f = dm_nvn_frame_count(); if (f - g_cs.frame0 < 300) return;
pthread_mutex_lock(&g_cs_mu); double n = (double)(f - g_cs.frame0); char top[700]; int k = 0; uint8_t used[64] = {0};
for (int r = 0; r < 8; r++) { int bi = -1; for (int i = 0; i < 64; i++) if (!used[i] && g_cs.op_b[i] && (bi < 0 || g_cs.op_b[i] > g_cs.op_b[bi])) bi = i; if (bi < 0) break; used[bi] = 1;
pthread_mutex_lock(&g_cs_mu); double n = (double)(f - g_cs.frame0); char top[700]; int k = 0; uint8_t used[256] = {0};
for (int r = 0; r < 8; r++) { int bi = -1; for (int i = 0; i < 256; i++) if (!used[i] && g_cs.op_b[i] && (bi < 0 || g_cs.op_b[i] > g_cs.op_b[bi])) bi = i; if (bi < 0) break; used[bi] = 1;
k += snprintf(top + k, sizeof top - k, " op %d: %.0f × %.0f bytes = %.1f KB;", bi, g_cs.op_n[bi] / n, (double)g_cs.op_b[bi] / (double)g_cs.op_n[bi], g_cs.op_b[bi] / n / 1024.0); }
LOG("[nvn] command memory up to frame %llu: recorded per frame %.1f KB / %.0f records; segments from the game per frame %.2f, mean %.1f KB each (min %.1f / max %.1f); out-of-memory callbacks per frame %.2f; host-lent segments per frame %.3f; segment tails dropped on a switch per frame %.1f KB | per frame%s",
(unsigned long long)f, g_cs.bytes / n / 1024.0, g_cs.recs / n, g_cs.grants / n, g_cs.grants ? g_cs.grant_bytes / (double)g_cs.grants / 1024.0 : 0, g_cs.grant_min / 1024.0, g_cs.grant_max / 1024.0, g_cs.cbs / n, g_cs.hostseg / n, g_cs.waste / n / 1024.0, top);
int on = g_cs.on; memset(&g_cs, 0, sizeof g_cs); g_cs.on = on; g_cs.frame0 = f; pthread_mutex_unlock(&g_cs_mu);
}
static void put_hdr(uint8_t *p, uint32_t op, uint32_t size) { op_hdr h = {op, size}; memcpy(p, &h, sizeof h); if (op) cs_op(op, size); }
// New segment: if the recording in progress has records, write a JUMP at the end of the old segment to link it. A recording with none yet starts in the new segment
// (its first record is its handle), and the bytes at the old write position are not its own: after an END that took the last bytes there is no room there at all
static void ctl_chunk_close(cmd_t *o);
// New segment: the records the recording in progress has in the old segment become one piece of its control list (written at its next record: ctl_push), and its next record
// opens a piece in the new one
static void cmd_new_segment(cmd_t *o, uint8_t *mem, size_t n) {
uint8_t *start = align8(mem), *end = mem + n;
if (o->recording == 1 && o->cur) { if (cs_on() && o->end > o->cur) { pthread_mutex_lock(&g_cs_mu); g_cs.waste += (uint64_t)(o->end - o->cur); pthread_mutex_unlock(&g_cs_mu); } put_hdr(o->cur, OP_JUMP, 16); memcpy(o->cur + 8, &start, 8);
o->used += 16; } // the JUMP also occupies guest memory of this recording: count it in used, so the game packing the next recording right behind by used does not overwrite it
if (o->recording == 1 && o->cur && cs_on() && o->end > o->cur) { pthread_mutex_lock(&g_cs_mu); g_cs.waste += (uint64_t)(o->end - o->cur); pthread_mutex_unlock(&g_cs_mu); }
if (o->recording) ctl_chunk_close(o);
o->cur = start; o->end = end;
}
// Host-supplied segment when the game's own command memory runs out: when the game's out-of-memory callback cannot allocate from its command memory pool, it calls AddCommandMemory with an empty pool (p = NULL, n = 0)
@@ -946,9 +949,9 @@ static void cmd_new_segment(cmd_t *o, uint8_t *mem, size_t n) {
// (Do not use the whole game chunk as the range: SMBW sub-allocates many recordings out of one big chunk, and a later grant inside that chunk freed segments still in use.)
// Reclaim follows the game's command memory chunks, not a frame count: the game caches recorded command handles and CALLs them every frame until it re-records them itself (SMBW's object setup handles);
// once a handle was recorded into a host segment, the old "reclaim 8 frames after lending" rewrote the segment while the game still CALLed it (with overflow forced on the Mac, the replay read garbage commands: RGBA16F used as a depth format for a pipeline).
// A segment hangs off one recording through the JUMP at the end of its guest part: that recording occupies [BEGIN, end of JUMP) in guest memory, and the game only gives those bytes out again once they are dead
// (when it re-records that material in place; packing the next recording right behind by used never touches them, since used includes the JUMP). So a segment remembers that guest range and is reclaimed when the game gives out memory
// overlapping it; segments overflowing from a host segment keep the same range.
// A segment hangs off the recording that overflowed into it: that recording occupies [its first record, the write position at the overflow) in guest memory, and the game only gives
// those bytes out again once they are dead (when it re-records that material in place; packing the next recording right behind by used never touches them). So a segment remembers
// that guest range and is reclaimed when the game gives out memory overlapping it; segments overflowing from a host segment keep the same range.
// The segment pool grows on demand (SMBW opening course: many small command buffers each overflow once per frame, and the old fixed 64 segments × 1 MB ran out within 8 frames); abort only beyond HOSTSEG_CAP in total.
// A segment is HOSTSEG_SZ, with two exceptions (hostseg_size): an empty pool with a length of at most HOSTSEG_SMALL outside a recording gets that much rounded up to HOSTSEG_SMALL
// (Super Mario Odyssey hands out many such 512-byte grants before recording; at 256 KB each, and with no recording to reclaim them by, they reached the cap entering the Wooded
@@ -965,16 +968,17 @@ static hostseg_t *g_hostseg; static int g_nhostseg, g_caphostseg; static uint64_
static pthread_mutex_t g_hostseg_mu = PTHREAD_MUTEX_INITIALIZER;
static size_t hostseg_size(const cmd_t *o, int empty_pool, size_t want) {
if (empty_pool) return want && want <= HOSTSEG_SMALL && !o->recording ? HOSTSEG_SMALL : HOSTSEG_SZ;
return want + 16 > HOSTSEG_SZ ? (want + 16 + 0xfff) & ~(size_t)0xfff : HOSTSEG_SZ; // 16: room for the next JUMP (want holds OP_RESERVE already, this is slack for the alignment)
return want > HOSTSEG_SZ ? (want + 0xfff) & ~(size_t)0xfff : HOSTSEG_SZ;
}
// Take a segment of n bytes: origin = the current recording's guest bytes [BEGIN, end of JUMP); if the write pointer is already in a host segment (overflowing again), keep that segment's origin
// Take a segment of n bytes: origin = the current recording's guest bytes [first record, write position), at least the byte at the write position; if the write pointer is already in
// a host segment (overflowing again), keep that segment's origin
static uint8_t *hostseg_take(const cmd_t *o, size_t n) {
static unsigned total; uint64_t f = dm_nvn_frame_count(); uint8_t *m = NULL;
uintptr_t lo = 0, hi = 0, cur = o ? (uintptr_t)o->cur : 0;
pthread_mutex_lock(&g_hostseg_mu);
int in_seg = 0; // by the segment's end too: a small segment can end where another one starts
for (int i = 0; i < g_nhostseg && cur; i++) if (cur >= (uintptr_t)g_hostseg[i].mem && o->end == g_hostseg[i].mem + g_hostseg[i].n) { lo = g_hostseg[i].org_lo; hi = g_hostseg[i].org_hi; in_seg = 1; break; }
if (!in_seg && o && o->recording && o->cur) { lo = o->recording == 1 && o->begin && (uintptr_t)o->begin <= cur ? (uintptr_t)o->begin : cur; hi = cur + 16; }
if (!in_seg && o && o->recording && o->cur) { lo = o->recording == 1 && o->begin && (uintptr_t)o->begin <= cur ? (uintptr_t)o->begin : cur; hi = cur > lo ? cur : lo + 1; }
for (int i = 0; i < g_nhostseg && !m; i++)
if (!g_hostseg[i].busy && g_hostseg[i].n == n) { g_hostseg[i] = (hostseg_t){ g_hostseg[i].mem, n, f, 1, lo, hi }; m = g_hostseg[i].mem; }
if (!m && g_hostseg_bytes + n <= HOSTSEG_CAP && (m = malloc(n))) {
@@ -1004,47 +1008,157 @@ NVN(nvnCommandBufferAddCommandMemory, void, NVNcommandBuffer *c, const NVNmemory
cmd_new_segment(CB(c), pl->mem + off, n);
CB(c)->used = 0; // GetCommandMemoryUsed counts from the start of the memory the game last added, across recordings (see there)
}
NVN(nvnCommandBufferAddControlMemory, void, NVNcommandBuffer *c, void *m, size_t n) {
(void)m;
CB(c)->ctl_size = n; // The host's recordings contain no control-memory entries; the entire last block remains free.
// Control memory: each recording's control list (nvn_obj.h ctl_e). A non-final entry is written only with 8 bytes left after it, so a list cut off by new control memory can always
// be linked on (CTL_LINK) from where it stopped, whether the game added the memory from its callback or on its own.
static void ctl_set(cmd_t *o, uint8_t *m, size_t n) {
uint8_t *a = m ? align8(m) : NULL; size_t pad = (size_t)(a - m); n = a && n > pad ? (n - pad) & ~(size_t)7 : 0;
if (n > 0xfffffff8u) n = 0xfffffff8u;
if (o->ctl_list && o->ctl_mem) {
if (n < 8) return; // nothing to link to: the list goes on in the old block's reserved bytes, and the next entry asks for memory again
uint64_t e = ctl_e(CTL_LINK, a, 0); memcpy(o->ctl_mem + o->ctl_used, &e, 8);
}
o->ctl_mem = a; o->ctl_size = (uint32_t)n; o->ctl_used = 0;
}
// Get space for one record and keep `keep` bytes after it (OP_RESERVE, 0 for the END); if not enough, call back into the game per the NVN convention to add command memory
static uint8_t *cmd_alloc_keep(cmd_t *o, uint32_t size, uint32_t keep) {
// Control memory the host lends when the game's callback gives none (or none is set): never reclaimed, as nothing tells when the game is done with the handles listed in it. On hardware
// recording stops there, so a game only gets here if the host needs more control memory than the driver would
#define CTLSEG_SZ (64u << 10)
static uint8_t *ctlseg_take(void) {
static uint64_t bytes; static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mu); uint64_t b = bytes += CTLSEG_SZ; pthread_mutex_unlock(&mu);
if (b > (256u << 20)) die("NVN control memory: the game gives none and host-lent control memory reached 256 MB");
uint8_t *m = malloc(CTLSEG_SZ); if (!m) die("NVN control memory: cannot lend a block");
if (b == CTLSEG_SZ || b % (16u << 20) == 0) LOG("[nvn] the game gave no control memory when asked, the host lends a block (%llu KB so far)", (unsigned long long)(b >> 10));
return m;
}
static void ctl_put(cmd_t *o, uint64_t e) {
uint32_t need = e & CTL_LAST ? 8 : 16;
for (int tries = 0; !o->ctl_mem || o->ctl_size - o->ctl_used < need; tries++) {
if (!o->cb || tries == 2) { ctl_set(o, ctlseg_take(), CTLSEG_SZ); break; }
o->cb((NVNcommandBuffer *)o, NVN_COMMAND_BUFFER_MEMORY_EVENT_OUT_OF_CONTROL_MEMORY, need, o->cb_data);
}
uint8_t *p = o->ctl_mem + o->ctl_used; memcpy(p, &e, 8); o->ctl_used += 8;
if (!o->ctl_list) o->ctl_list = p; // the list's first entry is the recording's handle
}
// Entries wait in ctl_q: the newest until the next one shows whether it is the last; one closed by a segment switch until host code writes it (ctl_flush), not inside AddCommandMemory
static void ctl_push(cmd_t *o, uint64_t e) {
if (o->ctl_q[1]) { ctl_put(o, o->ctl_q[0]); o->ctl_q[0] = o->ctl_q[1]; o->ctl_q[1] = 0; }
o->ctl_q[o->ctl_q[0] ? 1 : 0] = e;
}
static void ctl_flush(cmd_t *o) { if (o->ctl_q[1]) { ctl_put(o, o->ctl_q[0]); o->ctl_q[0] = o->ctl_q[1]; o->ctl_q[1] = 0; } }
static void ctl_chunk_close(cmd_t *o) {
if (o->chunk && o->cur > o->chunk) ctl_push(o, ctl_e(CTL_CHUNK, o->chunk, (uint64_t)(o->cur - o->chunk)));
o->chunk = NULL;
}
NVN(nvnCommandBufferAddControlMemory, void, NVNcommandBuffer *c, void *m, size_t n) { ctl_set(CB(c), m, n); }
// Get space for one record; if not enough, call back into the game per the NVN convention to add command memory. The record joins the recording's open piece of the control list
static uint8_t *cmd_alloc(cmd_t *o, uint32_t size) {
size = (size + 7) & ~7u;
for (int tries = 0; !o->cur || o->cur + size + keep > o->end; tries++) {
for (int tries = 0; !o->cur || o->cur + size > o->end; tries++) {
// The game's callback cannot supply enough (newer-SDK games hand out small chunks sized for real-device commands, or disable the callback and manage memory themselves): continue recording in a host segment instead of aborting
if (!o->cb || tries == 2) {
static int once; if (!once++) LOG("[nvn] command memory: the game's callback did not add enough (cb=%p, need %u bytes), using a host-lent segment", (void *)o->cb, size + keep);
size_t sz = hostseg_size(o, 0, size + keep); cmd_new_segment(o, hostseg_take(o, sz), sz); break;
static int once; if (!once++) LOG("[nvn] command memory: the game's callback did not add enough (cb=%p, need %u bytes), using a host-lent segment", (void *)o->cb, size);
size_t sz = hostseg_size(o, 0, size); cmd_new_segment(o, hostseg_take(o, sz), sz); break;
}
if (cs_on()) { pthread_mutex_lock(&g_cs_mu); g_cs.cbs++; pthread_mutex_unlock(&g_cs_mu); }
{ static int cblog = -1; if (cblog < 0) cblog = getenv("DM_NVN_CBLOG") != NULL; static uint64_t ncb;
if (cblog && (++ncb <= 40 || ncb % 1000 == 0)) LOG("[nvn] command memory callback #%llu cmd=%p need %u (used in this segment %ld)", (unsigned long long)ncb, (void *)o, size + keep, o->cur && o->end ? (long)(o->cur - (o->end - 1)) : -1L); }
o->cb((NVNcommandBuffer *)o, NVN_COMMAND_BUFFER_MEMORY_EVENT_OUT_OF_COMMAND_MEMORY, size + keep, o->cb_data);
if (cblog && (++ncb <= 40 || ncb % 1000 == 0)) LOG("[nvn] command memory callback #%llu cmd=%p need %u (used in this segment %ld)", (unsigned long long)ncb, (void *)o, size, o->cur && o->end ? (long)(o->cur - (o->end - 1)) : -1L); }
o->cb((NVNcommandBuffer *)o, NVN_COMMAND_BUFFER_MEMORY_EVENT_OUT_OF_COMMAND_MEMORY, size, o->cb_data);
}
if (cs_on()) { pthread_mutex_lock(&g_cs_mu); g_cs.bytes += size; g_cs.recs++; pthread_mutex_unlock(&g_cs_mu); }
uint8_t *p = o->cur; o->cur += size; o->used += size; put_hdr(p, 0, size);
if (o->recording == 2) { o->begin = p; o->recording = 1; } // The recording's first record is its handle
if (o->recording == 2) { o->begin = p; o->recording = 1; }
if (o->recording) {
if (o->chunk && (uint64_t)(o->cur - o->chunk) > CTL_CHUNK_MAX) { if (p > o->chunk) ctl_push(o, ctl_e(CTL_CHUNK, o->chunk, (uint64_t)(p - o->chunk))); o->chunk = NULL; }
if (size > CTL_CHUNK_MAX) ctl_push(o, ctl_e(CTL_CHUNK, p, CTL_ONE)); // a record longer than a piece can say gets an entry of its own
else if (!o->chunk) o->chunk = p;
ctl_flush(o);
}
return p;
}
static uint8_t *cmd_alloc(cmd_t *o, uint32_t size) { return cmd_alloc_keep(o, size, OP_RESERVE); }
// A recording starts with its first command, as in NVN: no BEGIN record, so an empty recording takes only its END. Games size command memory by GetCommandMemoryUsed
// (nvn_obj.h draw_rec): Breath of the Wild sums one scratch recording per mesh and per shape and render pass into each model's prerecorded commands, and with an
// A recording starts with its first command, as in NVN: no BEGIN record, and an empty recording takes no command memory, only its control entry. Games size command memory by
// GetCommandMemoryUsed (nvn_obj.h draw_rec): Breath of the Wild sums one scratch recording per mesh and per shape and render pass into each model's prerecorded commands, and with an
// 8-byte BEGIN on each of several hundred recordings a model came out a 4 KB page over its resource size table entry
NVN(nvnCommandBufferBeginRecording, void, NVNcommandBuffer *c) {
cmd_t *o = CB(c);
if (o->recording) LOG("[RED] BeginRecording re-entered");
o->recording = 2; // 2: recording, no command yet (cmd_alloc sets begin)
o->chunk = NULL; o->ctl_list = NULL; o->ctl_q[0] = o->ctl_q[1] = 0;
}
// The recording's last entry carries CTL_LAST; an empty recording's list is one empty piece. The handle is the list's first entry
NVN(nvnCommandBufferEndRecording, NVNcommandHandle, NVNcommandBuffer *c) {
cmd_t *o = CB(c);
uint8_t *p = cmd_alloc_keep(o, 8, 0); put_hdr(p, OP_END, 8); // nothing follows: the END may take the segment's last bytes
o->recording = 0;
return (NVNcommandHandle)o->begin;
ctl_chunk_close(o);
if (!o->ctl_q[0]) o->ctl_q[0] = ctl_e(CTL_CHUNK, NULL, 0);
ctl_flush(o); ctl_put(o, o->ctl_q[0] | CTL_LAST); o->ctl_q[0] = 0;
uint8_t *h = o->ctl_list; o->ctl_list = NULL; o->recording = 0;
return (NVNcommandHandle)h;
}
NVN(nvnCommandBufferIsRecording, NVNboolean, const NVNcommandBuffer *c) { return ((const cmd_t *)c)->recording != 0; }
// The pieces of a recording's control list in order (CTL_CHUNK entries, following links); NULL past the last. A handle that is not a list gives a red line and no pieces
typedef struct { const uint8_t *e; int done; } ctl_iter;
static int ctl_next(ctl_iter *it, uint64_t *out) {
for (int links = 0; !it->done && links < 1024; links++) {
uint64_t v; memcpy(&v, it->e, 8);
if (ctl_kind(v) == CTL_LINK) { it->e = ctl_addr(v); continue; }
if (ctl_kind(v) != CTL_CHUNK) { LOG("[RED] NVN command list: control entry %#llx at %p is no piece", (unsigned long long)v, (const void *)it->e); it->done = 1; return 0; }
it->e += 8; it->done = !!(v & CTL_LAST); *out = v & ~CTL_LAST; return 1;
}
if (!it->done) { LOG("[RED] NVN command list: more than 1024 links in a row at %p", (const void *)it->e); it->done = 1; }
return 0;
}
static int ctl_handle_ok(NVNcommandHandle h) {
if (h && !(h & 7) && !(h >> 47)) return 1;
LOG("[RED] CallCommands / CopyCommands: handle %#llx is no command list", (unsigned long long)h); return 0;
}
// CallCommands: the called recording's pieces join the caller's list (its records run in place at submit, so its command memory must stay as it was until then; its control
// memory need not). It takes no command memory
NVN(nvnCommandBufferCallCommands, void, NVNcommandBuffer *c, int n, const NVNcommandHandle *h) {
cmd_t *o = CB(c);
if (!o->recording) { LOG("[RED] CallCommands outside a recording"); return; }
for (int i = 0; i < n; i++) {
if (!ctl_handle_ok(h[i])) continue;
ctl_chunk_close(o);
ctl_iter it = { (const uint8_t *)(uintptr_t)h[i], 0 }; uint64_t v;
while (ctl_next(&it, &v)) if (ctl_len(v)) { ctl_push(o, v); ctl_flush(o); }
}
}
// CopyCommands: the called recording's records are copied into the caller's command memory, as the driver copies the GPU commands; the source may be recorded over at once
NVN(nvnCommandBufferCopyCommands, void, NVNcommandBuffer *c, int n, const NVNcommandHandle *h) {
for (int i = 0; i < n; i++) { uint8_t *p = cmd_alloc(CB(c), 16); put_hdr(p, OP_CALL, 16); memcpy(p + 8, &h[i], 8); }
cmd_t *o = CB(c);
if (!o->recording) { LOG("[RED] CopyCommands outside a recording"); return; }
for (int i = 0; i < n; i++) {
if (!ctl_handle_ok(h[i])) continue;
ctl_iter it = { (const uint8_t *)(uintptr_t)h[i], 0 }; uint64_t v;
while (ctl_next(&it, &v))
for (const uint8_t *p = ctl_addr(v), *pe = p + ctl_chunk_bytes(v); p < pe; ) {
op_hdr r; memcpy(&r, p, sizeof r);
if (r.size < 8 || (r.size & 7) || r.size > (size_t)(pe - p)) { LOG("[RED] CopyCommands: a corrupt record at %p in the source", (const void *)p); break; }
uint8_t *d = cmd_alloc(o, r.size); memcpy(d, p, r.size); cs_op(r.op, r.size); p += r.size;
}
}
}
static size_t rec_expand(const uint8_t *rec_, uint8_t *out);
// Its records in order, ending in OP_END
uint8_t *nvn_rec_linear(uint64_t handle, size_t *len) {
size_t n = 0, cap = 4096; uint8_t *buf = malloc(cap);
if (!buf) die("NVN command list: out of memory for a linear copy");
ctl_iter it = { (const uint8_t *)(uintptr_t)handle, 0 }; uint64_t v;
for (;;) {
size_t k = ctl_next(&it, &v) ? ctl_chunk_bytes(v) : 0, want = n + k + 8;
if (want > cap) { uint8_t *nb = realloc(buf, cap = want * 2); if (!nb) die("NVN command list: out of memory for a linear copy"); buf = nb; }
if (!k) { if (it.done) break; continue; }
for (const uint8_t *p = ctl_addr(v), *pe = p + k; p < pe; ) { // compact records expanded, as the queue's flatten does
op_hdr h; memcpy(&h, p, 8);
if (h.size < 8 || (h.size & 7) || h.size > (size_t)(pe - p)) die("NVN command list: a corrupt record at %p", (const void *)p);
uint8_t x[REC_EXPAND_MAX] __attribute__((aligned(8))); const uint8_t *src = p; size_t m = h.size;
if (rec_compact(h.op)) { m = rec_expand(p, x); src = x; }
if (n + m + 8 > cap) { uint8_t *nb = realloc(buf, cap = (n + m + 8) * 2); if (!nb) die("NVN command list: out of memory for a linear copy"); buf = nb; }
memcpy(buf + n, src, m); n += m; p += h.size;
}
}
put_hdr(buf + n, OP_END, 8); n += 8;
if (len) *len = n;
return buf;
}
NVN(nvnCommandBufferWaitEvent, void, NVNcommandBuffer *c, const NVNevent *e, NVNeventWaitMode mode, uint32_t value) {
uint8_t *p=cmd_alloc(CB(c),24); put_hdr(p,OP_WAIT_EVENT,24); volatile uint32_t *word=((const ev_t *)e)->val; uint32_t m=mode;
@@ -1094,9 +1208,115 @@ static void *rec(NVNcommandBuffer *c, uint32_t op, size_t payload) {
// Binding records with arrays are allocated by the actual count: prefix fields + n elements (the replay side reads only the first n). Previously they were recorded at fixed length for the maximum count (bind vertex buffers 272 bytes, bind textures / samplers 280 bytes,
// while there are usually only 1–2 in practice), and the empty tail took 40–50% of the command bytes per frame; the advanced stats page of the level 88 sorceress recorded 12.5 MB per frame, using up the game's own command memory pool (about 105 segments x 128 KB per frame)
#define RECN(c, OP, T, ARR, N) ((T *)rec((c), (OP), offsetof(T, ARR) + sizeof(((T *)0)->ARR[0]) * (size_t)(N)))
// Compact records (nvn_obj.h OPC_*): what a game records per mesh and per pass, in no more bytes than the driver's command where the 8-byte header allows. Measured against the NVN2
// driver of Ocarina of Time's sdk, run in an emulator on a command buffer of its own layout (bytes of command memory, driver / canonical host record → compact):
// DrawArrays 16 / 32 → 16, DrawElements 24 / 40 → 24, DrawElementsBaseVertex 48-72 / 40 → 24, DrawArraysInstanced 24 / 32 → 24, DrawElementsInstanced 48 / 40 → 32,
// DrawElementsIndirect 36 / 64 → 24, SetViewports (one) 36 / 400 → 24, SetStencilRef 8 / 32 → 8, BindImage 20 / 40 → 16, BindTextures (two) 28 / 48 → 16,
// BindStorageBuffer 20 / 32 → 24, BindUniformBuffers (two) 24 / 48 → 32, BindVertexBuffers (two) 40 / 48 → 32, BindVertexAttribState (four) 24 / 32 → 24,
// BindVertexStreamState (two) 24 / 32 → 24.
// Not compact, as their canonical record is at the header's floor or must keep its layout: BindTexture (24, its handle 16 bytes in for engines that patch it, see there; driver 16),
// BindUniformBuffer (24; 20), BindDepthStencilState (16 + 8; 8), BindColorState (16; 12), SetScissor (24; 12), SetPrimitiveRestart (16; 12), SetBlendColor (24; 20).
// Tests set g_rec_compact to 0 to record the canonical forms and compare them with the expanded compact ones
static int g_rec_compact = 1;
static uint8_t *crec(NVNcommandBuffer *c, uint32_t opc, uint32_t args, size_t payload) {
uint32_t sz = (uint32_t)((8 + payload + 7) & ~(size_t)7);
uint8_t *p = cmd_alloc(CB(c), sz); put_hdr(p, opc | args << 8, sz); memset(p + 8, 0, sz - 8);
return p + 8;
}
static void put32(uint8_t **q, uint32_t v) { memcpy(*q, &v, 4); *q += 4; }
static void put64(uint8_t **q, uint64_t v) { memcpy(*q, &v, 8); *q += 8; }
// Draws carry the indirect / multi-draw fields (ind onwards) only when they use them: a plain indexed draw record is 0x28 bytes instead of 0x40 (nvn_obj.h draw_rec)
static void rec_draw(NVNcommandBuffer *c, p_draw d) { size_t n = d.ind || d.mdi_cnt ? sizeof d : offsetof(p_draw, ind); memcpy(rec(c, OP_DRAW, n), &d, n); }
static void rec_draw_idx(NVNcommandBuffer *c, p_draw_idx d) { size_t n = d.ind || d.mdi_cnt ? sizeof d : offsetof(p_draw_idx, ind); memcpy(rec(c, OP_DRAW_IDX, n), &d, n); }
static void rec_draw(NVNcommandBuffer *c, p_draw d) {
if (g_rec_compact && !d.mdi_cnt && (uint32_t)d.prim < 0x100) {
uint8_t *q;
if (d.ind) { q = crec(c, OPC_DRAW_IND, (uint32_t)d.prim, 8); put64(&q, d.ind); return; }
if (d.instances == 1 && !d.base_instance) { q = crec(c, OPC_DRAW, (uint32_t)d.prim, 8); put32(&q, (uint32_t)d.first); put32(&q, (uint32_t)d.count); return; }
q = crec(c, OPC_DRAW_INST, (uint32_t)d.prim, 16); put32(&q, (uint32_t)d.first); put32(&q, (uint32_t)d.count); put32(&q, (uint32_t)d.base_instance); put32(&q, (uint32_t)d.instances); return;
}
size_t n = d.ind || d.mdi_cnt ? sizeof d : offsetof(p_draw, ind); memcpy(rec(c, OP_DRAW, n), &d, n);
}
static void rec_draw_idx(NVNcommandBuffer *c, p_draw_idx d) {
if (g_rec_compact && !d.mdi_cnt && (uint32_t)d.prim < 0x100 && (uint32_t)d.itype < 0x100) {
uint32_t a = (uint32_t)d.prim | (uint32_t)d.itype << 8; uint8_t *q;
if (d.ind) { if (d.count || d.base_vertex || d.base_instance || d.instances != 1) goto full; q = crec(c, OPC_DRAW_IDX_IND, a, 16); put64(&q, d.ibuf); put64(&q, d.ind); return; }
if (d.instances == 1 && !d.base_instance) { q = crec(c, OPC_DRAW_IDX, a, 16); put32(&q, (uint32_t)d.count); put32(&q, (uint32_t)d.base_vertex); put64(&q, d.ibuf); return; }
q = crec(c, OPC_DRAW_IDX_INST, a, 24); put32(&q, (uint32_t)d.count); put32(&q, (uint32_t)d.base_vertex); put32(&q, (uint32_t)d.base_instance); put32(&q, (uint32_t)d.instances); put64(&q, d.ibuf); return;
}
full:;
size_t n = d.ind || d.mdi_cnt ? sizeof d : offsetof(p_draw_idx, ind); memcpy(rec(c, OP_DRAW_IDX, n), &d, n);
}
// A compact record's canonical records, written to out (at least REC_EXPAND_MAX bytes); returns their bytes
static uint8_t *xrec(uint8_t *out, size_t *n, uint32_t op, size_t payload) {
uint32_t sz = (uint32_t)((8 + payload + 7) & ~(size_t)7); uint8_t *p = out + *n;
if (*n + sz > REC_EXPAND_MAX) die("NVN compact record: its expansion exceeds REC_EXPAND_MAX");
op_hdr h = {op, sz}; memcpy(p, &h, 8); memset(p + 8, 0, sz - 8); *n += sz; return p + 8;
}
static uint32_t get32(const uint8_t **q) { uint32_t v; memcpy(&v, *q, 4); *q += 4; return v; }
static uint64_t get64(const uint8_t **q) { uint64_t v; memcpy(&v, *q, 8); *q += 8; return v; }
static size_t rec_expand(const uint8_t *rec_, uint8_t *out) {
op_hdr h; memcpy(&h, rec_, 8); uint32_t a = h.op >> 8; const uint8_t *q = rec_ + 8; size_t n = 0;
switch (h.op & 0xff) {
case OPC_DRAW: case OPC_DRAW_INST: case OPC_DRAW_IND: {
p_draw d = { .prim = (int32_t)(a & 0xff), .instances = 1 };
if ((h.op & 0xff) == OPC_DRAW_IND) d.ind = get64(&q);
else { d.first = (int32_t)get32(&q); d.count = (int32_t)get32(&q); if ((h.op & 0xff) == OPC_DRAW_INST) { d.base_instance = (int32_t)get32(&q); d.instances = (int32_t)get32(&q); } }
size_t k = d.ind ? sizeof d : offsetof(p_draw, ind); memcpy(xrec(out, &n, OP_DRAW, k), &d, k); break; }
case OPC_DRAW_IDX: case OPC_DRAW_IDX_INST: case OPC_DRAW_IDX_IND: {
p_draw_idx d = { .prim = (int32_t)(a & 0xff), .itype = (int32_t)(a >> 8 & 0xff), .instances = 1 };
if ((h.op & 0xff) == OPC_DRAW_IDX_IND) { d.ibuf = get64(&q); d.ind = get64(&q); }
else { d.count = (int32_t)get32(&q); d.base_vertex = (int32_t)get32(&q); if ((h.op & 0xff) == OPC_DRAW_IDX_INST) { d.base_instance = (int32_t)get32(&q); d.instances = (int32_t)get32(&q); } d.ibuf = get64(&q); }
size_t k = d.ind ? sizeof d : offsetof(p_draw_idx, ind); memcpy(xrec(out, &n, OP_DRAW_IDX, k), &d, k); break; }
case OPC_VIEWPORTS: {
p_viewports *r = (p_viewports *)xrec(out, &n, OP_VIEWPORTS, sizeof *r); r->first = (int32_t)(a & 0xff); r->n = (int32_t)(a >> 8 & 0xff);
for (int i = 0; i < r->n; i++) { memcpy(r->v[i], q, 16); q += 16; }
break; }
case OPC_STENCIL: {
p_stencil s = { .face = (int32_t)(a & 3), .which = (int32_t)(a >> 2 & 3) }; int32_t v = (int32_t)(a >> 4);
if (s.which == 0) s.value_mask = v; else if (s.which == 1) s.mask = v; else s.ref = v;
memcpy(xrec(out, &n, OP_STENCIL, sizeof s), &s, sizeof s); break; }
case OPC_HANDLES: {
int cnt = (int)(a >> 17 & 0x3f);
p_bind_handles *r = (p_bind_handles *)xrec(out, &n, a & 0x3f, offsetof(p_bind_handles, h) + 8 * (size_t)cnt);
r->stage = (int32_t)(a >> 6 & 7); r->first = (int32_t)(a >> 9 & 0xff); r->n = cnt;
for (int i = 0; i < cnt; i++) r->h[i] = get32(&q);
break; }
case OPC_BUFS: {
uint32_t op = a & 0x3f, st = a >> 6 & 7, first = a >> 9 & 0xff, cnt = a >> 17 & 0x3f;
for (uint32_t i = 0; i < cnt; i++) {
uint64_t addr = get64(&q); uint32_t size = get32(&q);
if (op == OP_BIND_UBO_SMALL) *(p_bind_ubo_small *)xrec(out, &n, op, sizeof(p_bind_ubo_small)) = (p_bind_ubo_small){(uint16_t)st, (uint16_t)(first + i), size, addr};
else *(p_bind_buf *)xrec(out, &n, op, sizeof(p_bind_buf)) = (p_bind_buf){(int32_t)st, (int32_t)(first + i), addr, size};
}
break; }
case OPC_VBUFS: {
int cnt = (int)(a >> 8 & 0xff);
p_bind_vbuf *r = (p_bind_vbuf *)xrec(out, &n, OP_BIND_VBUF, offsetof(p_bind_vbuf, r) + sizeof(NVNbufferRange) * (size_t)cnt); r->first = (int32_t)(a & 0xff); r->n = cnt;
for (int i = 0; i < cnt; i++) { r->r[i].address = get64(&q); r->r[i].size = get32(&q); }
break; }
case OPC_VATTR: {
int cnt = (int)(a & 0xff);
p_bind_vattr *r = (p_bind_vattr *)xrec(out, &n, OP_BIND_VATTR, offsetof(p_bind_vattr, st) + 4 * (size_t)cnt); r->n = cnt; memcpy(r->st, q, 4 * (size_t)cnt);
break; }
case OPC_VSTREAM: {
int cnt = (int)(a & 0xff);
p_bind_vstream *r = (p_bind_vstream *)xrec(out, &n, OP_BIND_VSTREAM, offsetof(p_bind_vstream, st) + 8 * (size_t)cnt); r->n = cnt; memcpy(r->st, q, 8 * (size_t)cnt);
break; }
case OPC_UBO: {
uint32_t st = a & 7, first = a >> 3 & 0xf, cnt = a >> 7 & 0x1f;
for (uint32_t i = 0; i < cnt; i++) { uint64_t v = get64(&q); *(p_bind_ubo_small *)xrec(out, &n, OP_BIND_UBO_SMALL, sizeof(p_bind_ubo_small)) = (p_bind_ubo_small){(uint16_t)st, (uint16_t)(first + i), (uint32_t)(v >> 40), (v & ((UINT64_C(1) << 40) - 1)) << 8}; }
break; }
case OPC_STATE: case OPC_STATE8: {
size_t k = (h.op & 0xff) == OPC_STATE ? 4 : 8;
p_bind_state *r = (p_bind_state *)xrec(out, &n, OP_BIND_STATE, offsetof(p_bind_state, bytes) + k); r->kind = (int32_t)(a & 7);
if (k == 4) { uint32_t v = a >> 3; memcpy(r->bytes, &v, 4); } else memcpy(r->bytes, q, 8);
break; }
case OPC_BARRIER: { int32_t b = (int32_t)a; memcpy(xrec(out, &n, OP_BARRIER, 8), &b, 4); break; }
case OPC_PRIM_RESTART: *(p_prim_restart *)xrec(out, &n, OP_PRIM_RESTART, sizeof(p_prim_restart)) = (p_prim_restart){a & 1, a & 2 ? UINT32_MAX : a >> 2}; break;
case OPC_SCISSOR: { uint16_t v[4]; memcpy(v, q, 8); *(p_scissor *)xrec(out, &n, OP_SCISSOR, sizeof(p_scissor)) = (p_scissor){v[0], v[1], v[2], v[3]}; break; }
default: die("NVN command list: unknown compact record %#x", h.op);
}
return n;
}
static void copy_view(view_t *dst, uint8_t *has, const NVNtextureView *v) { *has = v != NULL; if (v) *dst = *(const view_t *)v; }
// Records with textures snapshot the texture objects (0x80 bytes each, after the record struct) and replay reads the snapshots: an NVN command no longer depends on the API object once recorded, and the game may finalize, free or reuse it before submitting.
// Unity (Engage) does so when it changes scenes; only the object pointer used to be recorded, and replay read other data (a texture 1869367126 high, a Metal assertion abort).
@@ -1144,15 +1364,24 @@ NVN(nvnCommandBufferClearDepthStencil, void, NVNcommandBuffer *c, float depth, u
}
NVN(nvnCommandBufferSetViewports, void, NVNcommandBuffer *c, int first, int n, const float *v) {
if (n < 0 || first + n > 16) { LOG("[RED] SetViewports first=%d n=%d", first, n); return; }
if (g_rec_compact && first >= 0) { uint8_t *q = crec(c, OPC_VIEWPORTS, (uint32_t)first | (uint32_t)n << 8, 16 * (size_t)n); memcpy(q, v, 16 * (size_t)n); return; }
p_viewports *r = REC(c, OP_VIEWPORTS, p_viewports); r->first = first; r->n = n;
for (int i = 0; i < n; i++) memcpy(r->v[i], v + 4 * i, 16);
}
NVN(nvnCommandBufferSetScissor, void, NVNcommandBuffer *c, int x, int y, int w, int h) { *REC(c, OP_SCISSOR, p_scissor) = (p_scissor){x, y, w, h}; }
NVN(nvnCommandBufferSetScissor, void, NVNcommandBuffer *c, int x, int y, int w, int h) {
if (g_rec_compact && (unsigned)x < 0x10000 && (unsigned)y < 0x10000 && (unsigned)w < 0x10000 && (unsigned)h < 0x10000) {
uint16_t v[4] = {(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}; memcpy(crec(c, OPC_SCISSOR, 0, 8), v, 8); return;
}
*REC(c, OP_SCISSOR, p_scissor) = (p_scissor){x, y, w, h};
}
NVN(nvnCommandBufferSetDepthRange, void, NVNcommandBuffer *c, float n, float f) { *REC(c, OP_DEPTH_RANGE, p_depth_range) = (p_depth_range){n, f}; }
NVN(nvnCommandBufferBindProgram, void, NVNcommandBuffer *c, const NVNprogram *p, int stages) {
*REC(c, OP_BIND_PROGRAM, p_bind_program) = (p_bind_program){(const prog_t *)p, stages};
}
static void bind_state(NVNcommandBuffer *c, int kind, const void *st, size_t n) { p_bind_state *r = rec(c, OP_BIND_STATE, offsetof(p_bind_state, bytes) + n); r->kind = kind; memcpy(r->bytes, st, n); } // only the state's own bytes (nvn_obj.h p_bind_state)
static void bind_state(NVNcommandBuffer *c, int kind, const void *st, size_t n) {
if (g_rec_compact && (unsigned)kind < 8 && n == 4) { uint32_t v; memcpy(&v, st, 4); if (v < (1u << 21)) { crec(c, OPC_STATE, (uint32_t)kind | v << 3, 0); return; } }
if (g_rec_compact && (unsigned)kind < 8 && n == 8) { memcpy(crec(c, OPC_STATE8, (uint32_t)kind, 8), st, 8); return; }
p_bind_state *r = rec(c, OP_BIND_STATE, offsetof(p_bind_state, bytes) + n); r->kind = kind; memcpy(r->bytes, st, n); } // only the state's own bytes (nvn_obj.h p_bind_state)
NVN(nvnCommandBufferBindBlendState, void, NVNcommandBuffer *c, const NVNblendState *st) { bind_state(c, 0, st, sizeof(blend_st)); }
NVN(nvnCommandBufferBindColorState, void, NVNcommandBuffer *c, const NVNcolorState *st) { bind_state(c, 1, st, sizeof(color_st)); }
NVN(nvnCommandBufferBindChannelMaskState, void, NVNcommandBuffer *c, const NVNchannelMaskState *st) { bind_state(c, 2, st, sizeof(chmask_st)); }
@@ -1162,10 +1391,12 @@ NVN(nvnCommandBufferBindDepthStencilState, void, NVNcommandBuffer *c, const NVNd
NVN(nvnCommandBufferBindVertexAttribState, void, NVNcommandBuffer *c, int n, const NVNvertexAttribState *st) {
// 32 on NVN2 (16 on NVN): Yoshi and the Mysterious Book's Unreal Engine 5.4 binds 17, the last on its own stream, and refusing the bind left the scene's draws without vertex layouts: a black scene
if (n < 0 || n > 32) { LOG("[RED] BindVertexAttribState n=%d", n); return; }
if (g_rec_compact) { memcpy(crec(c, OPC_VATTR, (uint32_t)n, 4 * (size_t)n), st, 4 * (size_t)n); return; }
p_bind_vattr *r = RECN(c, OP_BIND_VATTR, p_bind_vattr, st, n); r->first = 0; r->n = n; memcpy(r->st, st, 4 * n);
}
NVN(nvnCommandBufferBindVertexStreamState, void, NVNcommandBuffer *c, int n, const NVNvertexStreamState *st) {
if (n < 0 || n > 16) { LOG("[RED] BindVertexStreamState n=%d", n); return; }
if (g_rec_compact) { memcpy(crec(c, OPC_VSTREAM, (uint32_t)n, 8 * (size_t)n), st, 8 * (size_t)n); return; }
p_bind_vstream *r = RECN(c, OP_BIND_VSTREAM, p_bind_vstream, st, n); r->first = 0; r->n = n; memcpy(r->st, st, 8 * n);
}
NVN(nvnCommandBufferBindVertexBuffers, void, NVNcommandBuffer *c, int first, int n, const NVNbufferRange *rg) {
@@ -1175,17 +1406,37 @@ NVN(nvnCommandBufferBindVertexBuffers, void, NVNcommandBuffer *c, int first, int
if (n == 1 && (unsigned)first < 16 && rg[0].size <= UINT32_MAX) {
*REC(c, OP_BIND_VBUF1, p_bind_vbuf1) = (p_bind_vbuf1){(uint32_t)first, (uint32_t)rg[0].size, rg[0].address}; return;
}
int fit = g_rec_compact && first >= 0; for (int i = 0; i < n && fit; i++) fit = rg[i].size <= UINT32_MAX;
if (fit) { uint8_t *q = crec(c, OPC_VBUFS, (uint32_t)first | (uint32_t)n << 8, 12 * (size_t)n); for (int i = 0; i < n; i++) { put64(&q, rg[i].address); put32(&q, (uint32_t)rg[i].size); } return; }
p_bind_vbuf *r = RECN(c, OP_BIND_VBUF, p_bind_vbuf, r, n); r->first = first; r->n = n; memcpy(r->r, rg, sizeof *rg * n);
}
// NVN2's task and mesh stages (6, 7) keep their bindings in the tessellation stages' places (3, 4): a program has mesh shaders or tessellation, never both, and the replay keeps six stages
static inline NVNshaderStage st_host(NVNshaderStage st) { return (unsigned)st == 6 ? 3 : (unsigned)st == 7 ? 4 : st; }
// Uniform bindings with a 256-aligned address (the device's uniform buffer alignment) and a size below 2^18 (NVN's limit is 64 KB) take 8 bytes each after one header (OPC_UBO)
static int rec_ubo(NVNcommandBuffer *c, int st, int first, int n, const NVNbufferRange *rg) {
if (!g_rec_compact || (unsigned)st >= 6 || first < 0 || n < 1 || first + n > 16) return 0;
for (int i = 0; i < n; i++) if ((rg[i].address & 0xff) || rg[i].address >> 48 || rg[i].size >= (1u << 18)) return 0;
uint8_t *q = crec(c, OPC_UBO, (uint32_t)st | (uint32_t)first << 3 | (uint32_t)n << 7, 8 * (size_t)n);
for (int i = 0; i < n; i++) put64(&q, rg[i].address >> 8 | (uint64_t)rg[i].size << 40);
return 1;
}
NVN(nvnCommandBufferBindUniformBuffer, void, NVNcommandBuffer *c, NVNshaderStage st, int i, NVNbufferAddress a, size_t n) { st = st_host(st);
NVNbufferRange r = {a, n}; if (rec_ubo(c, st, i, 1, &r)) return;
if ((unsigned)st < 6 && (unsigned)i < 16 && n <= UINT32_MAX) {
*REC(c, OP_BIND_UBO_SMALL, p_bind_ubo_small) = (p_bind_ubo_small){(uint16_t)st, (uint16_t)i, (uint32_t)n, a}; return;
}
*REC(c, OP_BIND_UBO, p_bind_buf) = (p_bind_buf){st, i, a, n};
}
// Several uniform or storage buffer bindings in one compact record (OPC_BUFS), when each fits its canonical record's compact form
static int rec_bufs(NVNcommandBuffer *c, uint32_t op, int st, int first, int n, const NVNbufferRange *rg, int slots) {
if (!g_rec_compact || n < 1 || n > 63 || (unsigned)st >= 8 || first < 0 || first + n > slots || first > 0xff) return 0;
for (int i = 0; i < n; i++) if (rg[i].size > UINT32_MAX) return 0;
uint8_t *q = crec(c, OPC_BUFS, op | (uint32_t)st << 6 | (uint32_t)first << 9 | (uint32_t)n << 17, 12 * (size_t)n);
for (int i = 0; i < n; i++) { put64(&q, rg[i].address); put32(&q, (uint32_t)rg[i].size); }
return 1;
}
NVN(nvnCommandBufferBindUniformBuffers, void, NVNcommandBuffer *c, NVNshaderStage st, int first, int n, const NVNbufferRange *rg) { st = st_host(st);
if (n >= 2 && (unsigned)st < 6 && (rec_ubo(c, st, first, n, rg) || rec_bufs(c, OP_BIND_UBO_SMALL, st, first, n, rg, 16))) return;
for (int i = 0; i < n; i++) h_nvnCommandBufferBindUniformBuffer(c, st, first + i, rg[i].address, rg[i].size);
}
static void ssbo_slot_check(int st, int i) { // the replay keeps 16 storage buffer slots a stage (NVN's limit); a higher one is not bound
@@ -1193,14 +1444,21 @@ static void ssbo_slot_check(int st, int i) { // the replay keeps 16 storage bu
}
NVN(nvnCommandBufferBindStorageBuffer, void, NVNcommandBuffer *c, NVNshaderStage st, int i, NVNbufferAddress a, size_t n) { st = st_host(st);
ssbo_slot_check(st, i);
NVNbufferRange r = {a, n}; if (rec_bufs(c, OP_BIND_SSBO, st, i, 1, &r, 256)) return;
*REC(c, OP_BIND_SSBO, p_bind_buf) = (p_bind_buf){st, i, a, n};
}
NVN(nvnCommandBufferBindStorageBuffers, void, NVNcommandBuffer *c, NVNshaderStage st, int first, int n, const NVNbufferRange *rg) { st = st_host(st);
for (int i = 0; i < n; i++) { ssbo_slot_check(st, first + i); *REC(c, OP_BIND_SSBO, p_bind_buf) = (p_bind_buf){st, first + i, rg[i].address, rg[i].size}; }
for (int i = 0; i < n; i++) ssbo_slot_check(st, first + i);
if (rec_bufs(c, OP_BIND_SSBO, st, first, n, rg, 256)) return;
for (int i = 0; i < n; i++) *REC(c, OP_BIND_SSBO, p_bind_buf) = (p_bind_buf){st, first + i, rg[i].address, rg[i].size};
}
static p_bind_handles *bind_handles(NVNcommandBuffer *c, int op, int st, int first, int n, const uint64_t *h) {
// compact: as one OPC_HANDLES record (the handles' final values; BindTexturesDeferred edits its record afterwards, so it takes the canonical one)
static p_bind_handles *bind_handles_ex(NVNcommandBuffer *c, int op, int st, int first, int n, const uint64_t *h, int compact) {
if (n < 0 || n > 32) { LOG("[RED] bind handle count %d", n); return NULL; }
p_bind_handles *r = RECN(c, op, p_bind_handles, h, n); r->stage = st; r->first = first; r->n = n; r->defer = 0; r->src = 0;
p_bind_handles tmp, *r;
if (compact && g_rec_compact && (unsigned)st < 8 && first >= 0 && first <= 0xff && n >= 1) r = &tmp;
else r = RECN(c, op, p_bind_handles, h, n);
r->stage = st; r->first = first; r->n = n; r->defer = 0; r->src = 0;
// The driver writes each handle into the c2 table as a 32-bit word (texture ID in bits 0-19, sampler ID in bits 20-31), so the GPU never sees the upper half of the 64-bit handle.
// EA SPORTS FC 27 binds separate textures with bit 32 set (0x1000001d1): read whole, its sampler ID was 4096, beyond any pool, where the GPU reads sampler 0
for (int i = 0; i < n; i++) r->h[i] = (uint32_t)h[i];
@@ -1212,8 +1470,14 @@ static p_bind_handles *bind_handles(NVNcommandBuffer *c, int op, int st, int fir
else { if (tid) tid += (uint64_t)tb; if (sid && op == OP_BIND_TEX) sid += (uint64_t)sb; r->h[i] = tid | sid << 20; }
}
}
if (r == &tmp) {
uint8_t *q = crec(c, OPC_HANDLES, (uint32_t)op | (uint32_t)st << 6 | (uint32_t)first << 9 | (uint32_t)n << 17, 4 * (size_t)n);
for (int i = 0; i < n; i++) put32(&q, (uint32_t)r->h[i]);
return NULL;
}
return r;
}
static p_bind_handles *bind_handles(NVNcommandBuffer *c, int op, int st, int first, int n, const uint64_t *h) { return bind_handles_ex(c, op, st, first, n, h, 1); }
// Image (writable texture): handle = texture pool index (GetImageHandle returns it as-is; RegisterImage writes the same table as RegisterTexture)
NVN(nvnCommandBufferBindImages, void, NVNcommandBuffer *c, NVNshaderStage st, int first, int n, const NVNimageHandle *h) { st = st_host(st);
bind_handles(c, OP_BIND_IMG, st, first, n, (const uint64_t *)h);
@@ -1229,9 +1493,14 @@ NVN(nvnCommandBufferBindSeparateSamplers, void, NVNcommandBuffer *c, NVNshaderSt
NVN(nvnCommandBufferBindSeparateSampler, void, NVNcommandBuffer *c, NVNshaderStage st, int i, NVNseparateSamplerHandle h) { st = st_host(st);
bind_handles(c, OP_BIND_SAMP, st, i, 1, &h.value);
}
NVN(nvnCommandBufferSetStencilValueMask, void, NVNcommandBuffer *c, NVNface f, int m) { *REC(c, OP_STENCIL, p_stencil) = (p_stencil){f, m, 0, 0, 0}; }
NVN(nvnCommandBufferSetStencilMask, void, NVNcommandBuffer *c, NVNface f, int m) { *REC(c, OP_STENCIL, p_stencil) = (p_stencil){f, 0, m, 0, 1}; }
NVN(nvnCommandBufferSetStencilRef, void, NVNcommandBuffer *c, NVNface f, int v) { *REC(c, OP_STENCIL, p_stencil) = (p_stencil){f, 0, 0, v, 2}; }
// which: 0 value mask, 1 write mask, 2 reference value (p_stencil)
static void rec_stencil(NVNcommandBuffer *c, NVNface f, int which, int v) {
if (g_rec_compact && (unsigned)f < 4 && (unsigned)v < (1u << 20)) { crec(c, OPC_STENCIL, (uint32_t)f | (uint32_t)which << 2 | (uint32_t)v << 4, 0); return; }
*REC(c, OP_STENCIL, p_stencil) = (p_stencil){f, which == 0 ? v : 0, which == 1 ? v : 0, which == 2 ? v : 0, which};
}
NVN(nvnCommandBufferSetStencilValueMask, void, NVNcommandBuffer *c, NVNface f, int m) { rec_stencil(c, f, 0, m); }
NVN(nvnCommandBufferSetStencilMask, void, NVNcommandBuffer *c, NVNface f, int m) { rec_stencil(c, f, 1, m); }
NVN(nvnCommandBufferSetStencilRef, void, NVNcommandBuffer *c, NVNface f, int v) { rec_stencil(c, f, 2, v); }
NVN(nvnCommandBufferSetPolygonOffsetClamp, void, NVNcommandBuffer *c, float fa, float un, float cl) {
*REC(c, OP_POLY_OFFSET, p_poly_offset) = (p_poly_offset){fa, un, cl};
}
@@ -1260,7 +1529,10 @@ NVN(nvnCommandBufferDispatchCompute, void, NVNcommandBuffer *c, int x, int y, in
NVN(nvnCommandBufferDispatchComputeIndirect, void, NVNcommandBuffer *c, NVNbufferAddress ind) {
*REC(c, OP_DISPATCH, p_dispatch) = (p_dispatch){0, 0, 0, (uint64_t)__builtin_return_address(0), ind};
}
NVN(nvnCommandBufferBarrier, void, NVNcommandBuffer *c, int bits) { *(int32_t *)rec(c, OP_BARRIER, 8) = bits; }
NVN(nvnCommandBufferBarrier, void, NVNcommandBuffer *c, int bits) {
if (g_rec_compact && (unsigned)bits < (1u << 24)) { crec(c, OPC_BARRIER, (uint32_t)bits, 0); return; }
*(int32_t *)rec(c, OP_BARRIER, 8) = bits;
}
NVN(nvnCommandBufferSetTexturePool, void, NVNcommandBuffer *c, const NVNtexturePool *p) { REC(c, OP_SET_TEX_POOL, p_set_pool)->pool = (const dpool_t *)p; CB(c)->tex_base = dpool_base(g_tpb, g_ntpb, p); }
NVN(nvnCommandBufferSetSamplerPool, void, NVNcommandBuffer *c, const NVNsamplerPool *p) { REC(c, OP_SET_SAMP_POOL, p_set_pool)->pool = (const dpool_t *)p; CB(c)->samp_base = dpool_base(g_spb, g_nspb, p); }
@@ -2629,7 +2901,7 @@ NVN_NOPROTO(nvnWindowBuilderGetNumActiveTextures, int, const NVNwindowBuilder *b
NVN_NOPROTO(nvnWindowSetNumActiveTextures, void, NVNwindow *w, int n) { win_t *o = (win_t *)w; o->nactive = active_count(n, o->ntex, "WindowSetNumActiveTextures"); }
NVN_NOPROTO(nvnWindowGetNumActiveTextures, int, const NVNwindow *w) { return window_active((const win_t *)w); }
// Command buffer memory usage: record bytes written in this recording (accumulated across segments; the host does not use control memory, always 0); the memory callback switch is ignored.
// Command buffer memory usage: record bytes written in this recording (accumulated across segments; control entries are counted by GetControlMemoryUsed); the memory callback switch is ignored.
// It used to be cur - begin: once a recording overflowed into a host segment, cur is in host memory (an address below the guest begin) and it returned 0. SMBW asks for this value after recording each material setup handle,
// and on 0 (with control memory also 0) treats the recording as empty and marks the handle invalid (from main+0x4bb6c it clears bit 0 of the material entry +0x50); later draws no longer CALL it and inherit the previous object's vertex buffers / textures:
// on the iPhone a batch of draws on odd frames of the opening course fetched vertices out of bounds, giving huge triangles and NaN (black band, black-edged glow, grey stripes). Without overflow the accumulated value equals cur - begin.
@@ -2638,8 +2910,10 @@ NVN_NOPROTO(nvnWindowGetNumActiveTextures, int, const NVNwindow *w) { return win
// signals. Counted per recording, the position stayed at one frame's size (about 18 KB), the ring never freed past it, and after the first 16 MB (about 15 s) the callback waited for ring space forever
NVN(nvnCommandBufferGetCommandMemoryUsed, size_t, const NVNcommandBuffer *c) { const cmd_t *m = (const cmd_t *)c;
return m->begin ? (size_t)m->used : 0; }
NVN(nvnCommandBufferGetControlMemoryUsed, size_t, const NVNcommandBuffer *c) { (void)c; return 0; }
NVN(nvnCommandBufferGetControlMemoryFree, size_t, const NVNcommandBuffer *c) { return ((const cmd_t *)c)->ctl_size; }
// Control memory: the entries written into the last block, and those still waiting to be written (ctl_q)
static size_t ctl_used_now(const cmd_t *o) { size_t u = o->ctl_used + 8u * (size_t)(!!o->ctl_q[0] + !!o->ctl_q[1]); return u < o->ctl_size ? u : o->ctl_size; }
NVN(nvnCommandBufferGetControlMemoryUsed, size_t, const NVNcommandBuffer *c) { return ctl_used_now((const cmd_t *)c); }
NVN(nvnCommandBufferGetControlMemoryFree, size_t, const NVNcommandBuffer *c) { const cmd_t *o = (const cmd_t *)c; return o->ctl_size - ctl_used_now(o); }
NVN(nvnCommandBufferGetControlMemorySize, size_t, const NVNcommandBuffer *c) { return ((const cmd_t *)c)->ctl_size; }
// Free bytes of the command memory (DRAGON QUEST XI S, Unreal Engine 4.18): what is left in the current segment
NVN(nvnCommandBufferGetCommandMemoryFree, size_t, const NVNcommandBuffer *c) { const cmd_t *m = (const cmd_t *)c; return m->cur && m->end > m->cur ? (size_t)(m->end - m->cur) : 0; }
@@ -2814,7 +3088,6 @@ NVN_NOPROTO(nvnProgramSetSampleShading, NVNboolean, NVNprogram *p, int mode) { (
// Singular / combined forms → plural / separate forms; state the replay layer does not have yet (conditional render, depth bounds, ...) is logged once and drawing continues (better to over-draw than to drop).
#include "../tex/nvn_deswizzle.h"
NVN(nvnCommandBufferCallCommands, void, NVNcommandBuffer *c, int n, const NVNcommandHandle *h) { h_nvnCommandBufferCopyCommands(c, n, h); } // the replay layer treats CALL and COPY alike
// Combined texture handle (texture id | sampler id << 20) is recorded into the texture slot as is: the replay layer takes the texture from the low 20 bits and the sampler from the high bits (nvn_mtl.m NVN_RB_SAMPT)
// One combined handle: recorded as the hardware lays the command out, the handle 16 bytes in, where Luigi's Mansion 3 patches it after recording (nvn_obj.h p_bind_tex1)
NVN(nvnCommandBufferBindTexture, void, NVNcommandBuffer *c, NVNshaderStage st, int i, NVNtextureHandle h) { st = st_host(st);
@@ -2828,7 +3101,7 @@ NVN(nvnCommandBufferBindTextures, void, NVNcommandBuffer *c, NVNshaderStage st,
// passing the address of the handle field in the texture sampler object with a count of 1; command blocks are recorded once and submitted repeatedly, and the handle is written / replaced afterwards. The host used to copy the handles at recording (mostly 0),
// so every texture of the deferred lighting composite became the dummy texture 0 and the whole 3D picture was black. The address is recorded and the replay layer reads it when it reads the record (bh_fresh)
NVN_NOPROTO(nvnCommandBufferBindTexturesDeferred, void, NVNcommandBuffer *c, NVNshaderStage st, int first, int n, const NVNtextureHandle *h) { st = st_host(st);
p_bind_handles *r = bind_handles(c, OP_BIND_TEX, st, first, n, (const uint64_t *)h);
p_bind_handles *r = bind_handles_ex(c, OP_BIND_TEX, st, first, n, (const uint64_t *)h, 0);
if (r && h) { r->defer = 1; r->src = (uint64_t)(uintptr_t)h; }
if (CB(c)->tex_base || CB(c)->samp_base) ONCE_LOG("[RED] deferred-bound handles are read only at replay: the numbering base of this command buffer's bound descriptor pools is not added (pools %d / %d)", CB(c)->tex_base, CB(c)->samp_base);
}
@@ -3013,7 +3286,11 @@ NVN(nvnCommandBufferSetViewportSwizzles, void, NVNcommandBuffer *c, int first, i
NVN(nvnCommandBufferSetAlphaRef, void, NVNcommandBuffer *c, float r) { REC(c, OP_ALPHA_REF, p_alpha_ref)->ref = r; }
NVN(nvnCommandBufferSetLineWidth, void, NVNcommandBuffer *c, float w) { (void)c; if (w != 1.0f) ONCE_LOG("SetLineWidth %.2f: Metal has only 1-pixel lines", w); }
NVN(nvnCommandBufferSetPointSize, void, NVNcommandBuffer *c, float s) { (void)c; (void)s; ONCE_LOG("SetPointSize: the point size comes from the shader"); }
NVN(nvnCommandBufferSetPrimitiveRestart, void, NVNcommandBuffer *c, uint32_t en, int idx) { *REC(c, OP_PRIM_RESTART, p_prim_restart) = (p_prim_restart){(en & 0xff) != 0, (uint32_t)idx}; }
NVN(nvnCommandBufferSetPrimitiveRestart, void, NVNcommandBuffer *c, uint32_t en, int idx) {
uint32_t on = (en & 0xff) != 0, ix = (uint32_t)idx;
if (g_rec_compact && (ix == UINT32_MAX || ix < (1u << 22))) { crec(c, OPC_PRIM_RESTART, on | (ix == UINT32_MAX) << 1 | (ix == UINT32_MAX ? 0 : ix << 2), 0); return; }
*REC(c, OP_PRIM_RESTART, p_prim_restart) = (p_prim_restart){on, ix};
}
// Rasterizer discard: draws run their vertex stage only (with transform feedback, the capture); recorded, and at replay such a draw rasterizes nothing (nvn_mtl.m)
NVN(nvnCommandBufferSetRasterizerDiscard, void, NVNcommandBuffer *c, uint32_t en) { REC(c, OP_RAST_DISCARD, p_rast_discard)->on = (en & 0xff) != 0; }
NVN(nvnCommandBufferSetSampleMask, void, NVNcommandBuffer *c, int m) { (void)c; if ((m & 0xffff) != 0xffff) ONCE_LOG("SetSampleMask %#x: ignored by the host for now", m); }
+57 -4
View File
@@ -69,7 +69,8 @@ FITS(win_builder_t, NVNwindowBuilder);
typedef struct { uint32_t magic; void *native; int32_t ntex, interval, next, crop[4]; NVNtexture *tex[4]; uint64_t presents, avail[4], pace, ticket[4]; int32_t nactive; } win_t; // ticket[i]: ticket of the most recent present of image i; nactive as in win_builder_t
FITS(win_t, NVNwindow);
// Command buffer: commands are written into the command memory given by the game (AddCommandMemory), handle = segment start address; when it runs out, the game is called back for more memory
// Command buffer: commands are written into the command memory given by the game (AddCommandMemory), and the list that strings a recording's pieces together into its control memory
// (AddControlMemory), as in NVN; the handle is the address of that list (ctl_e below). When either runs out, the game is called back for more memory
typedef struct {
uint32_t magic, recording;
uint8_t *cur; // Write pointer of the current command memory segment
@@ -77,14 +78,19 @@ typedef struct {
// +0x10 is left to the game: its inlined NVN header code writes byte 1 here after AddCommandMemory and before BeginRecording / CallCommands (an internal flag of real NVN; main+0x4da5c, main+0xb8dec etc.).
// This used to be the low byte of end: rewritten to 01 it cut the segment end by up to 254 bytes, and SMBW's material setup handles (512-byte blocks at minimum) kept overflowing into host segments at the iPhone's addresses
uint8_t *end; // End of the current command memory segment
uint8_t *begin; // First record of this recording (its handle); recording 2 = not written yet
uint8_t *begin; // First record of this recording; recording 2 = not written yet (host-lent segments hang off the recording's guest bytes from here)
PFNNVNCOMMANDBUFFERMEMORYCALLBACKPROC cb; void *cb_data;
NVNdevice *dev;
uint64_t used; // Bytes written since the game last added command memory, across recordings and host segments, including segment-switch JUMPs (returned by GetCommandMemoryUsed)
uint64_t used; // Record bytes written since the game last added command memory, across recordings and host segments (returned by GetCommandMemoryUsed)
int32_t tex_base, samp_base; // Host-table bases of the texture / sampler pool this command buffer last bound (hle_nvn.c dpool_add; 0 = the first pool of its kind)
size_t ctl_size; // Bytes in the last control memory block supplied by the game (the host records no control commands)
int64_t copy_row, copy_image; // SetCopyRowStride / SetCopyImageStride: state of the command buffer, written into each buffer <-> texture copy (p_copy_strides), not recorded
size_t cmd_size; // GetCommandMemorySize: the bytes the game last passed to AddCommandMemory, as in NVN; a host-lent segment leaves it (see there)
uint8_t *ctl_mem; // The control memory block the game last added (aligned to 8), or a host-lent one when the game gave none (hle_nvn.c ctl_put)
uint32_t ctl_size, ctl_used; // Its bytes, and the bytes of control entries written into it (GetControlMemorySize / Used, which also count the entries in ctl_q)
uint64_t ctl_q[2]; // The recording's control entries not written yet (0 = none): the last waits for the next one or the END (CTL_LAST); a piece closed by AddCommandMemory waits
// for the next record, so that the game's control-memory callback never runs inside its own command-memory callback (hle_nvn.c ctl_push)
uint8_t *ctl_list; // The recording's first control entry once written: its handle (NULL before)
uint8_t *chunk; // Start of the recording's piece of records in the current segment not yet in a CTL_CHUNK entry (NULL = none open)
} cmd_t; FITS(cmd_t, NVNcommandBuffer);
// ---------- State objects (defaults follow the NVN / GL defaults) ----------
@@ -105,6 +111,53 @@ typedef struct { uint32_t stride, divisor; } vs_st;
// ---------- Command records: {op, size (including header, aligned to 8)} + payload ----------
typedef struct { uint32_t op, size; } op_hdr;
// A recording's control list (NVN's control memory, hle_nvn.c EndRecording): 8-byte entries, the handle is the first. Command memory holds only the records, as the driver's holds
// only GPU commands: the end of a recording and the link to its next piece when command memory ran out take no command memory, so they take none of what GetCommandMemoryUsed
// reports and games size their command memory by (docs/reference/memory.md, "Model heaps sized by the host's command record sizes"). CallCommands copies the called list's
// pieces into the caller's list, as the driver copies a command set's GPU FIFO entries: the called recording's control memory may be given out again once the call is recorded,
// its command memory not before the caller has run (Donkey Kong Bananza resets the arena of its control memory twice per arena of command memory).
// bits 63-62 kind: CTL_CHUNK records at addr, len bytes; CTL_LINK the list goes on at addr (its control memory ran out). Kinds 0 and 2 are never written.
// bit 61 CTL_LAST: the list ends after this entry (not on a LINK). bits 60-44 len / 8 (CTL_CHUNK: at most CTL_CHUNK_MAX bytes; CTL_ONE = one record, as long as its header says).
// bits 43-0 addr / 8 (every address is 8-aligned, below 2^47)
enum { CTL_CHUNK = 1, CTL_LINK = 3 };
#define CTL_LAST (UINT64_C(1) << 61)
#define CTL_ONE (((UINT64_C(1) << 17) - 1) * 8)
#define CTL_CHUNK_MAX (CTL_ONE - 8)
static inline uint64_t ctl_e(unsigned kind, const void *addr, uint64_t len) { return (uint64_t)kind << 62 | (len >> 3) << 44 | (uint64_t)(uintptr_t)addr >> 3; }
static inline unsigned ctl_kind(uint64_t e) { return (unsigned)(e >> 62); }
static inline const uint8_t *ctl_addr(uint64_t e) { return (const uint8_t *)(uintptr_t)((e & ((UINT64_C(1) << 44) - 1)) << 3); }
static inline uint64_t ctl_len(uint64_t e) { return (e >> 44 & ((UINT64_C(1) << 17) - 1)) << 3; }
static inline size_t ctl_chunk_bytes(uint64_t e) { uint64_t n = ctl_len(e); if (n == CTL_ONE) { op_hdr h; memcpy(&h, ctl_addr(e), sizeof h); n = h.size; } return (size_t)n; }
// Compact records: forms only command memory holds, as small as the driver's command for the same call or close to it where the 8-byte header allows (docs/reference/memory.md,
// "Model heaps sized by the host's command record sizes"). The queue's flatten expands each into the canonical records (hle_nvn.c rec_expand), so replay and capture never see them.
// Header: op = OPC_* in the low 8 bits (canonical ops are below 64) and small arguments in the upper 24; payload below.
enum {
OPC_BASE = 0x80,
OPC_DRAW = OPC_BASE, // prim | first, count (i32) → OP_DRAW, one instance
OPC_DRAW_INST, // prim | first, count, base instance, instances → OP_DRAW
OPC_DRAW_IND, // prim | ind (u64) → OP_DRAW, indirect
OPC_DRAW_IDX, // prim, index type << 8 | count, base vertex, ibuf (u64) → OP_DRAW_IDX, one instance
OPC_DRAW_IDX_INST, // prim, index type << 8 | count, base vertex, base instance, instances, ibuf
OPC_DRAW_IDX_IND, // prim, index type << 8 | ibuf, ind (u64) → OP_DRAW_IDX, indirect
OPC_VIEWPORTS, // first, n << 8 | n × {x, y, w, h} (f32) → OP_VIEWPORTS
OPC_STENCIL, // face, which << 2, value << 4 (20 bits) | none → OP_STENCIL
OPC_HANDLES, // op, stage << 6, first << 9, n << 17 | n × handle (u32) → op (OP_BIND_TEX / _SAMP / _IMG), handles already moved to the bound pools
OPC_BUFS, // op, stage << 6, first << 9, n << 17 | n × {addr (u64), size (u32)} → n records of op (OP_BIND_UBO_SMALL / OP_BIND_SSBO)
OPC_VBUFS, // first, n << 8 | n × {addr (u64), size (u32)} → OP_BIND_VBUF
OPC_VATTR, // n | n × attribute state (u32) → OP_BIND_VATTR, from 0
OPC_VSTREAM, // n | n × stream state (8 bytes) → OP_BIND_VSTREAM, from 0
OPC_UBO, // stage, first << 3, n << 7 | n × (addr >> 8 | size << 40) → n OP_BIND_UBO_SMALL (addresses 256-aligned, sizes below 2^18)
OPC_STATE, // kind, value << 3 (21 bits) | none → OP_BIND_STATE of a 4-byte state
OPC_STATE8, // kind | the 8-byte state → OP_BIND_STATE
OPC_BARRIER, // bits (24) | none → OP_BARRIER
OPC_PRIM_RESTART, // on, all-ones index << 1, index << 2 (22 bits) | none → OP_PRIM_RESTART
OPC_SCISSOR, // none | x, y, w, h (u16) → OP_SCISSOR
OPC_END_
};
#define REC_EXPAND_MAX 4096 // the most canonical bytes one compact record expands to
static inline int rec_compact(uint32_t op) { return (op & 0xff) >= OPC_BASE; }
// A recording's records in order, as one block ending in OP_END (malloc'd; hle_nvn.c): for tests that replay a handle with mtl_exec, and diagnostics
uint8_t *nvn_rec_linear(uint64_t handle, size_t *len);
enum {
OP_END, OP_JUMP, OP_BEGIN, OP_CALL, // OP_BEGIN is no longer recorded (hle_nvn.c BeginRecording)
OP_SIGNAL_EVENT, OP_REPORT_COUNTER, OP_COPY_B2B, OP_UPDATE_UB, // CPU-visible side effects
+33 -19
View File
@@ -176,24 +176,38 @@ static void nq_start(void) { pthread_t t; if(pthread_create(&t,NULL,nq_worker,NU
static nq_node *nq_append(nq_job *j,unsigned kind) { nq_node *n=calloc(1,sizeof *n); if(!n) die("queue continuation allocation failed"); n->kind=kind; if(j->last) j->last->next=n; else j->first=n; j->last=n; return n; }
static void nq_bytes(nq_node *n,const void *bytes,size_t length) { if(n->length+length>n->capacity) { n->capacity=(n->length+length+4095)&~(size_t)4095; n->bytes=realloc(n->bytes,n->capacity); if(!n->bytes) die("queue commands allocation failed"); } memcpy(n->bytes+n->length,bytes,length); n->length+=length; } // NOLINT(bugprone-suspicious-realloc-usage): allocation failure aborts, so the old buffer cannot leak into a continuing process
static void nq_end(nq_job *j) { if(j->last && j->last->kind==NQ_COMMANDS && !j->last->closed) { op_hdr end={OP_END,8}; nq_bytes(j->last,&end,8); j->last->closed=1; } }
static void nq_flatten(nq_job *j,const uint8_t *p,unsigned depth) {
if(depth>64) die("NVN command call nesting exceeds64");
for(;;) {
op_hdr h; memcpy(&h,p,8); if(h.size<8 || h.size&7) die("invalid NVN command size"); const uint8_t *a=p+8;
if(h.op==OP_END) return;
if(h.op==OP_JUMP) { memcpy(&p,a,8); continue; }
if(h.op==OP_CALL) { const uint8_t *called; memcpy(&called,a,8); nq_flatten(j,called,depth+1); p+=h.size; continue; }
if(h.op==OP_WAIT_EVENT || h.op==OP_WAIT_SYNC || h.op==OP_FENCE_SYNC) {
nq_end(j); nq_node *n=nq_append(j,h.op==OP_WAIT_EVENT?NQ_EVENT:h.op==OP_WAIT_SYNC?NQ_SYNC:NQ_FENCE);
if(h.op==OP_WAIT_EVENT) { memcpy(&n->event,a,8); memcpy(&n->mode,a+8,4); memcpy(&n->value,a+12,4); }
else { memcpy(&n->sync_source,a,8); if(h.op==OP_FENCE_SYNC) n->receipt=nq_new(); }
} else {
nq_node *n=j->last; if(!n || n->kind!=NQ_COMMANDS || n->closed) n=nq_append(j,NQ_COMMANDS);
size_t offset=n->length; nq_bytes(n,p,h.size);
if(!cap_rec_fields(h.op,n->bytes+offset+8,h.size,&nq_snapshot_ops,j)) die("queue snapshot: unknown command %u",h.op);
if(h.op==OP_SIGNAL_EVENT) { memcpy(&n->event,a,8); memcpy(&n->mode,a+8,4); memcpy(&n->value,a+12,4); nq_end(j); nq_append(j,NQ_FENCE)->receipt=nq_new(); }
}
p+=h.size;
// One record of a recording, copied into the job (its object pointers snapshotted); waits and fences cut the job
static void nq_record_one(nq_job *j,const uint8_t *p,op_hdr h) {
const uint8_t *a=p+8;
if(h.op==OP_END || h.op==OP_JUMP || h.op==OP_CALL) die("NVN command list: a %s record inside a recording's piece at %p",h.op==OP_END?"END":h.op==OP_JUMP?"JUMP":"CALL",(const void *)p);
if(h.op==OP_WAIT_EVENT || h.op==OP_WAIT_SYNC || h.op==OP_FENCE_SYNC) {
nq_end(j); nq_node *n=nq_append(j,h.op==OP_WAIT_EVENT?NQ_EVENT:h.op==OP_WAIT_SYNC?NQ_SYNC:NQ_FENCE);
if(h.op==OP_WAIT_EVENT) { memcpy(&n->event,a,8); memcpy(&n->mode,a+8,4); memcpy(&n->value,a+12,4); }
else { memcpy(&n->sync_source,a,8); if(h.op==OP_FENCE_SYNC) n->receipt=nq_new(); }
} else {
nq_node *n=j->last; if(!n || n->kind!=NQ_COMMANDS || n->closed) n=nq_append(j,NQ_COMMANDS);
size_t offset=n->length; nq_bytes(n,p,h.size); if(!n->bytes) die("queue commands: a record of %u bytes",h.size);
if(!cap_rec_fields(h.op,n->bytes+offset+8,h.size,&nq_snapshot_ops,j)) die("queue snapshot: unknown command %u",h.op);
if(h.op==OP_SIGNAL_EVENT) { memcpy(&n->event,a,8); memcpy(&n->mode,a+8,4); memcpy(&n->value,a+12,4); nq_end(j); nq_append(j,NQ_FENCE)->receipt=nq_new(); }
}
}
// A compact record (nvn_obj.h OPC_*) goes into the job as the canonical records it stands for
static void nq_record(nq_job *j,const uint8_t *p,op_hdr h) {
if(!rec_compact(h.op)) { nq_record_one(j,p,h); return; }
uint8_t x[REC_EXPAND_MAX] __attribute__((aligned(8))); size_t n=rec_expand(p,x);
for(size_t o=0;o<n;) { op_hdr c; memcpy(&c,x+o,8); nq_record_one(j,x+o,c); o+=c.size; }
}
// A handle is the recording's control list (nvn_obj.h ctl_e): its pieces of records, its links to more control memory. Calls were copied in when they were recorded
static void nq_flatten(nq_job *j,const uint8_t *list) {
for(const uint8_t *e=list;;e+=8) {
uint64_t v; memcpy(&v,e,8); unsigned k=ctl_kind(v);
if(k==CTL_LINK) { e=ctl_addr(v)-8; continue; }
if(k!=CTL_CHUNK) die("NVN command list %p: corrupt control entry %#llx at %p",(const void *)list,(unsigned long long)v,(const void *)e);
const uint8_t *p=ctl_addr(v),*pe=p+ctl_chunk_bytes(v);
while(p<pe) { op_hdr h; memcpy(&h,p,8);
if(h.size<8 || h.size&7 || h.size>(size_t)(pe-p)) die("NVN command list %p: record {op %u, size %u} at %p, %zu bytes into its piece of %zu at %p",(const void *)list,h.op,h.size,(const void *)p,(size_t)(p-ctl_addr(v)),ctl_chunk_bytes(v),(const void *)ctl_addr(v));
nq_record(j,p,h); p+=h.size; }
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); }
@@ -202,7 +216,7 @@ void nvn_queue_submit(queue_t *q,int count,const uint64_t *handles) {
j->objects.klen=16; j->frame=dm_nvn_frame_count();
// No scheduler lock while copying descriptors or resolving shader libraries.
dm_host_mutex_lock(&g_sub_mu); void *pool=objc_autoreleasePoolPush(); dm_host_work++; mtl_prepare(); dm_host_work--; nq_cost cost=nq_cost_begin();
for(int i=0;i<count;i++) nq_flatten(j,(const uint8_t *)(uintptr_t)handles[i],0); nq_end(j);
for(int i=0;i<count;i++) nq_flatten(j,(const uint8_t *)(uintptr_t)handles[i]); nq_end(j);
nq_cost_end(cost); objc_autoreleasePoolPop(pool); pthread_mutex_unlock(&g_sub_mu);
int waits=0; for(nq_node *node=j->first;node;node=node->next) waits|=node->kind==NQ_EVENT || node->kind==NQ_SYNC;
nvn_cap_queue(q->serial,waits);
+2 -2
View File
@@ -85,7 +85,7 @@ static void finalized_upload(int write_after_record) {
CHECK(!g_treg[1].view && !g_treg[2].view && !g_treg[2].alt, "finalization retires every descriptor's cached views");
// Reuse the API object: commands and registered descriptors must use their snapshots.
memset(&tex, 0xa5, sizeof tex);
state_reset(); memset(&R,0,sizeof R); mtl_sub_begin(); mtl_exec((const uint8_t *)handle);
state_reset(); memset(&R,0,sizeof R); mtl_sub_begin(); mtl_exec(nvn_rec_linear(handle, NULL));
CHECK(mtl_wait(mtl_sub_commit(),5000000000ull), "recorded texture readback completed");
CHECK(!mtl_last_commit_error(), "recorded texture readback has no GPU error");
CHECK(!memcmp(mem+131072, pixels, sizeof pixels), "finalized command snapshot uploads CPU-written pixels");
@@ -95,7 +95,7 @@ static void finalized_upload(int write_after_record) {
CHECK(mtl_wait(mtl_sub_commit(),5000000000ull), "registered descriptor upload completed");
CHECK(!g_treg[1].view && !g_treg[2].view && !g_treg[2].alt, "late descriptor views retire at submission end");
// Resolve again: a retired serial may already hold an NvPkg in the ghost cache.
mtl_sub_begin(); mtl_exec((const uint8_t *)handle);
mtl_sub_begin(); mtl_exec(nvn_rec_linear(handle, NULL));
CHECK(mtl_wait(mtl_sub_commit(),5000000000ull), "recorded snapshot can be replayed again");
CHECK(!memcmp(mem+131072, pixels, sizeof pixels), "replayed retired snapshot keeps its CPU content");
mtl_reg_tex(1,NULL,NULL); mtl_reg_tex(2,NULL,NULL); h_nvnCommandBufferFinalize(&cmd);
+8 -5
View File
@@ -71,10 +71,12 @@ void test_set_frame(uint64_t frame) { (void)frame; }
void test_drain(void) { atomic_fetch_add(&drains, 1); }
static NVNqueue queues[2];
static const op_hdr work[] = {{OP_BEGIN, 8}, {OP_END, 8}};
static const op_hdr work[] __attribute__((aligned(8))) = {{OP_BEGIN, 8}};
static uint64_t work_list; // its control list: one piece (nvn_obj.h ctl_e)
static void *submit(void *which) {
second_submit = which != NULL;
NVNcommandHandle handle = (uintptr_t)work;
work_list = ctl_e(CTL_CHUNK, work, sizeof work) | CTL_LAST;
NVNcommandHandle handle = (uintptr_t)&work_list;
h_nvnQueueSubmitCommands(&queues[second_submit], 1, &handle);
dispatch_semaphore_signal(returned);
return NULL;
@@ -127,10 +129,11 @@ int main(void) {
// An unencoded wait must not make suspend wait for a future producer.
// Releasing that event in the background must still respect the closed gate.
_Atomic uint32_t word = 0;
struct { op_hdr wait; volatile uint32_t *word; uint32_t mode, value; op_hdr begin, end; } parked = {
{OP_WAIT_EVENT, 24}, (volatile uint32_t *)&word, 0, 1, {OP_BEGIN, 8}, {OP_END, 8}
struct { op_hdr wait; volatile uint32_t *word; uint32_t mode, value; op_hdr begin; } parked __attribute__((aligned(8))) = {
{OP_WAIT_EVENT, 24}, (volatile uint32_t *)&word, 0, 1, {OP_BEGIN, 8}
};
NVNcommandHandle parked_handle = (uintptr_t)&parked;
static uint64_t parked_list; parked_list = ctl_e(CTL_CHUNK, &parked, sizeof parked) | CTL_LAST;
NVNcommandHandle parked_handle = (uintptr_t)&parked_list;
h_nvnQueueSubmitCommands(&queues[0], 1, &parked_handle);
pthread_create(&background, NULL, suspend_graphics, NULL);
if (!reached(suspended, "suspend returns with an unresolved queue event")) return 1;
+1 -1
View File
@@ -58,7 +58,7 @@ static int run(prog_t *pg, uint8_t *pool, int indexed, int maximum, int count, i
uint32_t vertices = 3;
h_nvnCommandBufferUpdateUniformBuffer(&parent, (uint64_t)(uintptr_t)sentinel, sizeof vertices, 0, sizeof vertices, &vertices);
h_nvnCommandBufferCallCommands(&parent, 1, &draws);
uint64_t handle = h_nvnCommandBufferEndRecording(&parent);
uint64_t handle = (uintptr_t)nvn_rec_linear(h_nvnCommandBufferEndRecording(&parent), NULL); // the recording's records with the call inlined, as the queue submits them
tex_t rt = {.magic = MAGIC('T', 'E', 'X', 0), .serial = nvn_new_serial()};
rt.d = (nvn_texdesc){.target = NVN_TEXTURE_TARGET_2D,
+2 -2
View File
@@ -86,7 +86,7 @@ static void scaled_copy_case(void) {
h_nvnCommandBufferAddCommandMemory(&cmd, (const NVNmemoryPool *)&pool, 0, 65536); h_nvnCommandBufferBeginRecording(&cmd);
NVNcopyRegion sr={0,0,0,320,180,1}, dr={0,0,0,160,90,1};
h_nvnCommandBufferCopyTextureToTexture(&cmd, (const NVNtexture *)&src, NULL, &sr, &dst, NULL, &dr, NVN_COPY_FLAGS_LINEAR_FILTER_BIT);
NVNcommandHandle h=h_nvnCommandBufferEndRecording(&cmd); state_reset(); memset(&R,0,sizeof R); mtl_sub_begin(); mtl_exec((const uint8_t *)h);
NVNcommandHandle h=h_nvnCommandBufferEndRecording(&cmd); state_reset(); memset(&R,0,sizeof R); mtl_sub_begin(); mtl_exec(nvn_rec_linear(h, NULL));
EXPECT("scaled copy committed", 1, mtl_wait(mtl_sub_commit(),5000000000ull)); EXPECT("scaled copy GPU error",0,mtl_last_commit_error());
h_nvnMemoryPoolInvalidateMappedRange((const NVNmemoryPool *)&pool,65536,640*90); uint8_t *map=(uint8_t *)h_nvnMemoryPoolMap((const NVNmemoryPool *)&pool)+65536;
static const uint8_t want[]={255,0,0,255}; int bad=0; for(int i=0;i<160*90;i++)bad+=memcmp(map+i*4,want,4)!=0;
@@ -165,7 +165,7 @@ static void unaligned_upload_case(void) { // a pool made through NVN, so that
NVNcommandBuffer cmd; EXPECT("unaligned case: command buffer init", 1, h_nvnCommandBufferInitialize(&cmd, NULL));
h_nvnCommandBufferAddCommandMemory(&cmd, (const NVNmemoryPool *)&pool, 0, 65536); h_nvnCommandBufferBeginRecording(&cmd);
NVNcopyRegion cr = {0, 0, 0, 6, 6, 1}; h_nvnCommandBufferCopyTextureToTexture(&cmd, &tex[1], NULL, &cr, &tex[0], NULL, &cr, 0);
NVNcommandHandle h = h_nvnCommandBufferEndRecording(&cmd); state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec((const uint8_t *)h);
NVNcommandHandle h = h_nvnCommandBufferEndRecording(&cmd); state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec(nvn_rec_linear(h, NULL));
EXPECT("0: the copy from 1 committed", 1, mtl_wait(mtl_sub_commit(), 5000000000ull));
uint8_t want[24 * 6]; for (int y = 0; y < 6; y++) memcpy(want + y * 24, stored[1] + y * 64, 24);
read_job after_copy = {&tex[0], want, -1}; read_job_tight(&after_copy);
+1 -1
View File
@@ -37,7 +37,7 @@ static void target(recording *r,const tex_t *t,int lv,int slot,const tex_t *othe
}
static void finish(recording *r) {
NVNcommandHandle h=h_nvnCommandBufferEndRecording(&r->cb);state_reset();memset(&R,0,sizeof R);
mtl_sub_begin();mtl_exec((const uint8_t *)h);
mtl_sub_begin();mtl_exec(nvn_rec_linear(h, NULL));
int done=mtl_wait(mtl_sub_commit(),5000000000ull);EXPECT("production GPU done",1,done);if(!done)abort();EXPECT("no error in commit feedback",0,mtl_last_commit_error());
mtl_pool_del(r->mem);free(r->mem);
}
+221 -79
View File
@@ -28,7 +28,13 @@ static uint16_t crc16_a001(const uint8_t *p, size_t n) {
return c;
}
// Command memory callback: hands out a new 256-byte memory segment each time (forces a multi-segment JUMP chain)
// A recording's control list entry (nvn_obj.h ctl_e) at a handle, and whether it is one piece of n record bytes at p, the last entry
static uint64_t ctl_at(NVNcommandHandle h, int i) { uint64_t v; memcpy(&v, (const uint8_t *)(uintptr_t)h + 8 * i, 8); return v; }
// A recording's records as the queue submits them (compact ones expanded); kept until the next call
static uint8_t *lin(NVNcommandHandle h) { static uint8_t *b; free(b); return b = nvn_rec_linear(h, NULL); }
static int one_piece(NVNcommandHandle h, const void *p, size_t n) { uint64_t v = ctl_at(h, 0); return ctl_kind(v) == CTL_CHUNK && (v & CTL_LAST) && ctl_addr(v) == p && ctl_len(v) == n; }
// Command memory callback: hands out a new 256-byte memory segment each time (forces a recording of many pieces); control memory it leaves to the host's own blocks
static uint8_t g_cmdmem[64 * 1024]; static size_t g_cmdoff; static int g_cb_calls; static NVNmemoryPool g_cmdpool;
static void mem_cb(NVNcommandBuffer *c, NVNcommandBufferMemoryEvent ev, size_t minsz, void *data) {
(void)data; g_cb_calls++;
@@ -41,6 +47,14 @@ static void mem_cb(NVNcommandBuffer *c, NVNcommandBufferMemoryEvent ev, size_t m
static int g_nocb_calls;
static void no_mem_cb(NVNcommandBuffer *c, NVNcommandBufferMemoryEvent ev, size_t minsz, void *data) { (void)c; (void)ev; (void)minsz; (void)data; g_nocb_calls++; }
// Control memory callback for the list-overflow test: hands out 32-byte control blocks in turn; command memory from g_cmdpool as mem_cb
static uint8_t g_ctlmem[4096] __attribute__((aligned(8))); static size_t g_ctloff; static int g_ctl_calls;
static void ctl_cb(NVNcommandBuffer *c, NVNcommandBufferMemoryEvent ev, size_t minsz, void *data) {
if (ev == NVN_COMMAND_BUFFER_MEMORY_EVENT_OUT_OF_COMMAND_MEMORY) { mem_cb(c, ev, minsz, data); return; }
g_ctl_calls++; size_t n = minsz > 32 ? minsz : 32;
P(nvnCommandBufferAddControlMemory)(c, g_ctlmem + g_ctloff, n); g_ctloff += n;
}
// Suspend unit test: do the submit on another thread
static _Atomic int g_sstarted, g_sdone; static pthread_mutex_t g_smu = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_scv = PTHREAD_COND_INITIALIZER;
static NVNqueue *g_sq; static NVNcommandHandle g_sh; static NVNT_nvnQueueSubmitCommands g_sub;
@@ -419,15 +433,16 @@ int main(void) {
EXPECT("report converted to ns lies inside submit/wait", 1, counter_ns + 2 >= counter_before && counter_ns <= counter_after);
// 5c. Copy strides are command buffer state (NVN): setting them takes no command memory, Get reads them back, and a copy recorded after them carries them.
// Super Smash Bros. Ultimate records one upload in 256 bytes (main+0x3664960): SetCopyRowStride, SetCopyImageStride, CopyBufferToTexture, END, on a command buffer whose
// out-of-memory handler is null; recorded as two 24-byte records, the copy overflowed and the game's callback jumped to 0
// Super Smash Bros. Ultimate records one upload in 256 bytes of command memory and 256 of control memory (main+0x3664960): SetCopyRowStride, SetCopyImageStride,
// CopyBufferToTexture, on a command buffer whose out-of-memory handler is null; recorded as two 24-byte records, the copy overflowed and the game's callback jumped to 0
{
static uint8_t m[256] __attribute__((aligned(4096))); NVNmemoryPoolBuilder mb; NVNmemoryPool mp; NVNcommandBuffer c3;
static uint8_t m[256] __attribute__((aligned(4096))), ctl[256]; NVNmemoryPoolBuilder mb; NVNmemoryPool mp; NVNcommandBuffer c3;
P(nvnMemoryPoolBuilderSetDefaults)(&mb); P(nvnMemoryPoolBuilderSetStorage)(&mb, m, sizeof m); P(nvnMemoryPoolInitialize)(&mp, &mb);
NVNtextureBuilder tb; NVNtexture tx = {0}; P(nvnTextureBuilderSetDevice)(&tb, &dev); P(nvnTextureBuilderSetDefaults)(&tb);
P(nvnTextureBuilderSetSize2D)(&tb, 8, 8); P(nvnTextureBuilderSetFormat)(&tb, NVN_FORMAT_RGBA8); P(nvnTextureBuilderSetStorage)(&tb, &pool, 0); P(nvnTextureInitialize)(&tx, &tb);
P(nvnCommandBufferInitialize)(&c3, &dev); P(nvnCommandBufferSetMemoryCallback)(&c3, no_mem_cb); P(nvnCommandBufferSetMemoryCallbackData)(&c3, NULL); g_nocb_calls = 0;
EXPECT("copy row stride starts at 0", 0, P(nvnCommandBufferGetCopyRowStride)(&c3));
P(nvnCommandBufferAddControlMemory)(&c3, ctl, sizeof ctl);
P(nvnCommandBufferAddCommandMemory)(&c3, &mp, 0, sizeof m); P(nvnCommandBufferBeginRecording)(&c3);
P(nvnCommandBufferSetCopyRowStride)(&c3, 64); P(nvnCommandBufferSetCopyImageStride)(&c3, 512);
EXPECT("setting the copy strides takes no command memory", 0, P(nvnCommandBufferGetCommandMemoryUsed)(&c3));
@@ -440,6 +455,7 @@ int main(void) {
op_hdr rh; memcpy(&rh, m, sizeof rh); const p_copy_strides *cs = copy_strides(m + 8, rh.size);
EXPECT("the copy carries the strides: 64 per row, 512 per image", 1, rh.op == OP_COPY_B2T && cs && cs->row == 64 && cs->image == 512);
P(nvnCommandBufferSetCopyRowStride)(&c3, 0); P(nvnCommandBufferSetCopyImageStride)(&c3, 0);
P(nvnCommandBufferAddControlMemory)(&c3, ctl, sizeof ctl);
P(nvnCommandBufferAddCommandMemory)(&c3, &mp, 0, sizeof m); P(nvnCommandBufferBeginRecording)(&c3);
P(nvnCommandBufferCopyBufferToTexture)(&c3, 0x10000, &tx, NULL, &rg, 0); P(nvnCommandBufferEndRecording)(&c3);
memcpy(&rh, m, sizeof rh);
@@ -466,7 +482,7 @@ int main(void) {
// Memory added at an offset the host aligns past: the size is the bytes the game passed, not the host's segment
P(nvnCommandBufferAddCommandMemory)(&c4, &mp, 4, sizeof m - 4);
EXPECT("memory added at offset 4: size is the bytes passed", sizeof m - 4, P(nvnCommandBufferGetCommandMemorySize)(&c4));
// Memory added in the middle of a recording (a game's out-of-memory callback): the JUMP to it counts in the old memory, and the size is the new memory's
// Memory added in the middle of a recording (a game's out-of-memory callback): the size is the new memory's
P(nvnCommandBufferBeginRecording)(&c4);
P(nvnCommandBufferDrawElementsBaseVertex)(&c4, NVN_DRAW_PRIMITIVE_TRIANGLES, NVN_INDEX_TYPE_UNSIGNED_SHORT, 36, 0x10000, 5);
P(nvnCommandBufferAddCommandMemory)(&c4, &mp, 0, sizeof m);
@@ -486,14 +502,13 @@ int main(void) {
}
// 5a. Command memory per recording, as GetCommandMemoryUsed reports it (games size prerecorded command blocks by it: Breath of the Wild records one scratch draw per mesh):
// no BEGIN record, a plain indexed draw without the indirect / multi-draw fields, and the handle is the first record; an indirect draw keeps its address
// no BEGIN record and no END in command memory, a plain indexed draw without the indirect / multi-draw fields; the handle is the recording's control list, in the control
// memory the game added (one 8-byte entry for a recording in one piece); an indirect draw keeps its address
{
static uint8_t m[4096] __attribute__((aligned(4096))); NVNmemoryPoolBuilder mb; NVNmemoryPool mp; NVNcommandBuffer c2;
P(nvnMemoryPoolBuilderSetDefaults)(&mb); P(nvnMemoryPoolBuilderSetStorage)(&mb, m, sizeof m); P(nvnMemoryPoolInitialize)(&mp, &mb);
P(nvnCommandBufferInitialize)(&c2, &dev);
// Control memory is unused by the host's command stream: a supplied
// block has its full size available, even after recording commands.
static uint8_t ctl[512];
static uint8_t ctl[512] __attribute__((aligned(8)));
EXPECT("control free before AddControlMemory", 0, P(nvnCommandBufferGetControlMemoryFree)(&c2));
P(nvnCommandBufferAddControlMemory)(&c2, ctl, sizeof ctl);
EXPECT("control block size after grant", sizeof ctl, P(nvnCommandBufferGetControlMemorySize)(&c2));
@@ -501,29 +516,30 @@ int main(void) {
P(nvnCommandBufferAddCommandMemory)(&c2, &mp, 0, sizeof m); P(nvnCommandBufferBeginRecording)(&c2);
P(nvnCommandBufferDrawElementsBaseVertex)(&c2, NVN_DRAW_PRIMITIVE_TRIANGLES, NVN_INDEX_TYPE_UNSIGNED_SHORT, 36, 0x10000, 5);
NVNcommandHandle hd = P(nvnCommandBufferEndRecording)(&c2);
EXPECT("plain indexed draw recording: 0x28 + END", 0x30, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("recording uses no control memory", 0, P(nvnCommandBufferGetControlMemoryUsed)(&c2));
EXPECT("control capacity remains available", sizeof ctl, P(nvnCommandBufferGetControlMemoryFree)(&c2));
EXPECT("plain indexed draw recording: 24 bytes (the driver's 48-72), no END", 24, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("its control list: one entry", 8, P(nvnCommandBufferGetControlMemoryUsed)(&c2));
EXPECT("control free = size - used", sizeof ctl - 8, P(nvnCommandBufferGetControlMemoryFree)(&c2));
op_hdr rh; memcpy(&rh, m, sizeof rh); int compact = rec_compact(rh.op);
uint8_t *L = lin(hd); memcpy(&rh, L, sizeof rh); p_draw_idx dt; const p_draw_idx *d = draw_idx_rec(L + 8, rh.size, &dt);
EXPECT("its handle is its control list, one piece: the compact draw, expanded to OP_DRAW_IDX", 1, (const uint8_t *)hd == ctl && one_piece(hd, m, 24) && compact && rh.op == OP_DRAW_IDX);
P(nvnCommandBufferAddControlMemory)(&c2, ctl, 128);
EXPECT("new control block replaces capacity", 128, P(nvnCommandBufferGetControlMemoryFree)(&c2));
op_hdr rh; memcpy(&rh, m, sizeof rh); p_draw_idx dt; const p_draw_idx *d = draw_idx_rec(m + 8, rh.size, &dt);
EXPECT("its handle is the draw record", 1, (const uint8_t *)hd == m && rh.op == OP_DRAW_IDX);
EXPECT("draw read back: count, base vertex, no indirect address", 1, d->count == 36 && d->base_vertex == 5 && d->ibuf == 0x10000 && !d->ind && !d->mdi_cnt);
P(nvnCommandBufferAddCommandMemory)(&c2, &mp, 0, sizeof m); P(nvnCommandBufferBeginRecording)(&c2); NVNcommandHandle he = P(nvnCommandBufferEndRecording)(&c2);
memcpy(&rh, m, sizeof rh);
EXPECT("empty recording: its END only", 8, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("empty recording's handle is its END", 1, (const uint8_t *)he == m && rh.op == OP_END);
EXPECT("empty recording: no command memory", 0, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("empty recording: one control entry, an empty piece", 1, P(nvnCommandBufferGetControlMemoryUsed)(&c2) == 8 && (const uint8_t *)he == ctl && one_piece(he, NULL, 0));
P(nvnCommandBufferAddCommandMemory)(&c2, &mp, 0, sizeof m); P(nvnCommandBufferBeginRecording)(&c2);
P(nvnCommandBufferDrawElementsIndirect)(&c2, NVN_DRAW_PRIMITIVE_TRIANGLES, NVN_INDEX_TYPE_UNSIGNED_SHORT, 0x10000, 0x20000);
P(nvnCommandBufferEndRecording)(&c2);
memcpy(&rh, m, sizeof rh); d = draw_idx_rec(m + 8, rh.size, &dt);
NVNcommandHandle hi = P(nvnCommandBufferEndRecording)(&c2);
EXPECT("indirect indexed draw: 24 bytes (the driver's 36)", 24, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
L = lin(hi); memcpy(&rh, L, sizeof rh); d = draw_idx_rec(L + 8, rh.size, &dt);
EXPECT("indirect draw keeps its address", 0x20000, d->ind);
// A single texture bind keeps its handle 16 bytes into the command, where a game that patches recorded commands writes a new one (Luigi's Mansion 3: base + GetCommandMemoryUsed + 0x10)
P(nvnCommandBufferAddCommandMemory)(&c2, &mp, 0, sizeof m); P(nvnCommandBufferBeginRecording)(&c2);
size_t at = P(nvnCommandBufferGetCommandMemoryUsed)(&c2);
P(nvnCommandBufferBindTexture)(&c2, NVN_SHADER_STAGE_FRAGMENT, 3, (NVNtextureHandle)(0x1ff00000u | 1234));
P(nvnCommandBufferEndRecording)(&c2);
EXPECT("single texture bind recording, first pools: 0x18 + END", 0x20, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("single texture bind recording, first pools: 0x18", 0x18, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
uint32_t patched = 0x1ff00000u | 1235; memcpy(m + at + 0x10, &patched, 4);
memcpy(&rh, m, sizeof rh); p_bind_handles bt; const p_bind_handles *bh = bind_rec(rh.op, m + 8, &bt);
EXPECT("the bind reads the handle patched at its start + 0x10: slot 3, texture 1235, sampler 511", 1, rh.op == OP_BIND_TEX1 && bh->n == 1 && bh->first == 3 && bh->stage == NVN_SHADER_STAGE_FRAGMENT && bh->h[0] == patched);
@@ -532,7 +548,7 @@ int main(void) {
((cmd_t *)&c2)->tex_base = 7; ((cmd_t *)&c2)->samp_base = 3;
P(nvnCommandBufferBindTexture)(&c2, NVN_SHADER_STAGE_VERTEX, 2, (NVNtextureHandle)(5u << 20 | 1234));
P(nvnCommandBufferEndRecording)(&c2); ((cmd_t *)&c2)->tex_base = ((cmd_t *)&c2)->samp_base = 0;
EXPECT("single texture bind recording, other pools: 0x20 + END", 0x28, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("single texture bind recording, other pools: 0x20", 0x20, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
memcpy(&rh, m, sizeof rh); bh = bind_rec(rh.op, m + 8, &bt);
EXPECT("the bind adds the pool bases: stage, slot 2, texture 1241, sampler 8", 1, bh->stage == NVN_SHADER_STAGE_VERTEX && bh->first == 2 && bh->h[0] == (8u << 20 | 1241));
// State binds carry only the state object's bytes: 16 bytes for a 4-byte state, 24 for an 8-byte one or the multisample state
@@ -540,10 +556,10 @@ int main(void) {
NVNpolygonState ps; P(nvnPolygonStateSetDefaults)(&ps); P(nvnPolygonStateSetCullFace)(&ps, NVN_FACE_BACK); P(nvnCommandBufferBindPolygonState)(&c2, &ps);
NVNdepthStencilState dss; P(nvnDepthStencilStateSetDefaults)(&dss); P(nvnDepthStencilStateSetDepthFunc)(&dss, NVN_DEPTH_FUNC_GREATER); P(nvnCommandBufferBindDepthStencilState)(&c2, &dss);
NVNmultisampleState mss; P(nvnMultisampleStateSetDefaults)(&mss); P(nvnMultisampleStateSetSamples)(&mss, 4); P(nvnCommandBufferBindMultisampleState)(&c2, &mss);
P(nvnCommandBufferEndRecording)(&c2);
EXPECT("polygon, depth-stencil and multisample binds: 16 + 24 + 24 + END", 72, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
{ op_hdr h1, h2, h3; memcpy(&h1, m, 8); memcpy(&h2, m + 16, 8); memcpy(&h3, m + 40, 8);
const p_bind_state *s1 = (const p_bind_state *)(m + 8), *s2 = (const p_bind_state *)(m + 24), *s3 = (const p_bind_state *)(m + 48);
NVNcommandHandle hs3 = P(nvnCommandBufferEndRecording)(&c2);
EXPECT("polygon, depth-stencil and multisample binds: 8 + 16 + 24 (compact; the driver's 20-24, 8 and 80)", 48, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
{ const uint8_t *L3 = lin(hs3); op_hdr h1, h2, h3; memcpy(&h1, L3, 8); memcpy(&h2, L3 + 16, 8); memcpy(&h3, L3 + 40, 8); // expanded: the canonical 16 + 24 + 24
const p_bind_state *s1 = (const p_bind_state *)(L3 + 8), *s2 = (const p_bind_state *)(L3 + 24), *s3 = (const p_bind_state *)(L3 + 48);
poly_st pr; ds_st dr; ms_st mr; memcpy(&pr, s1->bytes, sizeof pr); memcpy(&dr, s2->bytes, sizeof dr); memcpy(&mr, s3->bytes, sizeof mr);
EXPECT("the state records read back: kinds, cull, depth function, samples", 1, h1.op == OP_BIND_STATE && h1.size == 16 && s1->kind == 4 && pr.cull == NVN_FACE_BACK
&& h2.op == OP_BIND_STATE && h2.size == 24 && s2->kind == 5 && dr.df == NVN_DEPTH_FUNC_GREATER && h3.op == OP_BIND_STATE && h3.size == 24 && s3->kind == 3 && mr.samples == 4); }
@@ -559,37 +575,35 @@ int main(void) {
P(nvnCommandBufferBindUniformBuffer)(&c2, NVN_SHADER_STAGE_FRAGMENT, 13, UINT64_C(0x123456789abc0000), 65536);
NVNcommandHandle first = P(nvnCommandBufferEndRecording)(&c2);
size_t first_size = P(nvnCommandBufferGetCommandMemoryUsed)(&c2);
EXPECT("maximum uniform range: 24-byte bind + END", 32, first_size);
EXPECT("maximum uniform range: 24-byte bind", 24, first_size);
op_hdr rh; memcpy(&rh, m, sizeof rh);
EXPECT("bounded uniform record is 24 bytes", 24, rh.size);
p_bind_buf decoded; const p_bind_buf *b = bind_buf_rec(rh.op, m + 8, &decoded);
EXPECT("bounded uniform decode keeps stage, index, address, size", 1,
b->stage == NVN_SHADER_STAGE_FRAGMENT && b->index == 13 && b->addr == UINT64_C(0x123456789abc0000) && b->size == 65536);
op_hdr end; memcpy(&end, m + rh.size, sizeof end);
EXPECT("uniform bind preserves its adjacent END", 1, end.op == OP_END && end.size == 8 && (const uint8_t *)first == m);
EXPECT("uniform bind recording: one piece of 24 bytes", 1, one_piece(first, m, 24));
uint8_t saved[64]; memcpy(saved, m, first_size);
P(nvnCommandBufferAddCommandMemory)(&c2, &mp, (ptrdiff_t)first_size, sizeof m - first_size); P(nvnCommandBufferBeginRecording)(&c2);
NVNbufferRange ranges[] = {{UINT64_C(0xfedcba9876540000), 256}, {UINT64_C(0x1122334455660000), 0}};
P(nvnCommandBufferBindUniformBuffers)(&c2, NVN_SHADER_STAGE_VERTEX, 2, 2, ranges);
P(nvnCommandBufferEndRecording)(&c2);
NVNcommandHandle plural = P(nvnCommandBufferEndRecording)(&c2);
memset(ranges, 0, sizeof ranges);
EXPECT("plural uniform binds: 2 x 24 + END", 56, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("plural uniform binds: one compact record, 8 + 2 x 12", 32, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("independent uniform recording preserves predecessor", 0, memcmp(saved, m, first_size));
size_t pos = first_size;
memcpy(&rh, m + pos, sizeof rh); b = bind_buf_rec(rh.op, m + pos + 8, &decoded);
const uint8_t *L = lin(plural); size_t pos = 0; // expanded: one OP_BIND_UBO_SMALL a binding, as when recorded one by one
memcpy(&rh, L + pos, sizeof rh); b = bind_buf_rec(rh.op, L + pos + 8, &decoded);
EXPECT("plural first uniform keeps copied range and slot", 1,
b->stage == NVN_SHADER_STAGE_VERTEX && b->index == 2 && b->addr == UINT64_C(0xfedcba9876540000) && b->size == 256);
pos += rh.size;
memcpy(&rh, m + pos, sizeof rh); b = bind_buf_rec(rh.op, m + pos + 8, &decoded);
memcpy(&rh, L + pos, sizeof rh); b = bind_buf_rec(rh.op, L + pos + 8, &decoded);
EXPECT("plural second uniform preserves zero range and next slot", 1,
b->stage == NVN_SHADER_STAGE_VERTEX && b->index == 3 && b->addr == UINT64_C(0x1122334455660000) && b->size == 0);
memcpy(&end, m + pos + rh.size, sizeof end);
EXPECT("plural uniform binds preserve their END", 1, end.op == OP_END && end.size == 8);
EXPECT("plural uniform binds: one piece", 1, one_piece(plural, m + first_size, 32));
P(nvnCommandBufferAddCommandMemory)(&c2, &mp, 512, sizeof m - 512); P(nvnCommandBufferBeginRecording)(&c2);
P(nvnCommandBufferBindUniformBuffer)(&c2, NVN_SHADER_STAGE_COMPUTE, 3, UINT64_C(0xffff123456780000), UINT64_C(0x100000001));
P(nvnCommandBufferEndRecording)(&c2);
memcpy(&rh, m + 512, sizeof rh);
EXPECT("wide uniform range keeps full record + END", 40, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("wide uniform range keeps full record", 32, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("wide uniform range keeps full opcode and size", 1, rh.op == OP_BIND_UBO && rh.size == 32);
b = bind_buf_rec(rh.op, m + 520, &decoded);
EXPECT("wide uniform decode preserves all 64 bits", 1,
@@ -604,34 +618,34 @@ int main(void) {
P(nvnCommandBufferInitialize)(&c2, &dev);
P(nvnCommandBufferAddCommandMemory)(&c2, &mp, 0, sizeof m); P(nvnCommandBufferBeginRecording)(&c2);
P(nvnCommandBufferBindVertexBuffer)(&c2, 15, UINT64_C(0xfedcba9876540000), UINT32_MAX);
P(nvnCommandBufferEndRecording)(&c2);
EXPECT("single vertex buffer: 24-byte bind + END", 32, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
op_hdr rh, end; memcpy(&rh, m, sizeof rh); memcpy(&end, m + rh.size, sizeof end);
NVNcommandHandle hv = P(nvnCommandBufferEndRecording)(&c2);
EXPECT("single vertex buffer: 24-byte bind", 24, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
op_hdr rh; memcpy(&rh, m, sizeof rh);
EXPECT("single vertex binding record is 24 bytes", 24, rh.size);
EXPECT("single vertex binding preserves adjacent END", 1, end.op == OP_END && end.size == 8);
EXPECT("single vertex binding recording: one piece", 1, one_piece(hv, m, 24));
p_bind_vbuf tmp; const p_bind_vbuf *b = vbuf_rec(rh.op, m + 8, &tmp);
EXPECT("single vertex decode preserves slot, full address, maximum size", 1,
b->first == 15 && b->n == 1 && b->r[0].address == UINT64_C(0xfedcba9876540000) && b->r[0].size == UINT32_MAX);
NVNbufferRange ranges[] = {{UINT64_C(0x1122334455660000), 0}, {UINT64_C(0x9988776655440000), 256}};
P(nvnCommandBufferAddCommandMemory)(&c2, &mp, 128, sizeof m - 128); P(nvnCommandBufferBeginRecording)(&c2);
P(nvnCommandBufferBindVertexBuffers)(&c2, 3, 1, ranges); P(nvnCommandBufferEndRecording)(&c2);
EXPECT("one-element vertex array: 24-byte bind + END", 32, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("one-element vertex array: 24-byte bind", 24, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
memcpy(&rh, m + 128, sizeof rh); b = vbuf_rec(rh.op, m + 136, &tmp);
EXPECT("one-element vertex array decode preserves zero range", 1,
b->first == 3 && b->n == 1 && b->r[0].address == UINT64_C(0x1122334455660000) && b->r[0].size == 0);
P(nvnCommandBufferAddCommandMemory)(&c2, &mp, 256, sizeof m - 256); P(nvnCommandBufferBeginRecording)(&c2);
P(nvnCommandBufferBindVertexBuffers)(&c2, 4, 2, ranges); P(nvnCommandBufferEndRecording)(&c2);
P(nvnCommandBufferBindVertexBuffers)(&c2, 4, 2, ranges); NVNcommandHandle hv2 = P(nvnCommandBufferEndRecording)(&c2);
memset(ranges, 0, sizeof ranges);
EXPECT("two vertex ranges retain array record + END", 56, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
memcpy(&rh, m + 256, sizeof rh);
EXPECT("two vertex ranges retain array opcode", OP_BIND_VBUF, rh.op);
b = vbuf_rec(rh.op, m + 264, &tmp);
EXPECT("two vertex ranges: one compact record, 8 + 2 x 12 (the driver's 40)", 32, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
const uint8_t *L = lin(hv2); memcpy(&rh, L, sizeof rh);
EXPECT("two vertex ranges expand to the array record", OP_BIND_VBUF, rh.op);
b = vbuf_rec(rh.op, L + 8, &tmp);
EXPECT("vertex array decode preserves both copied ranges", 1,
b->first == 4 && b->n == 2 && b->r[0].address == UINT64_C(0x1122334455660000) && !b->r[0].size &&
b->r[1].address == UINT64_C(0x9988776655440000) && b->r[1].size == 256);
P(nvnCommandBufferAddCommandMemory)(&c2, &mp, 384, sizeof m - 384); P(nvnCommandBufferBeginRecording)(&c2);
P(nvnCommandBufferBindVertexBuffer)(&c2, 7, UINT64_C(0xabcd123456780000), UINT64_C(0x100000001)); P(nvnCommandBufferEndRecording)(&c2);
EXPECT("wide vertex range retains full record + END", 40, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
EXPECT("wide vertex range retains full record", 32, P(nvnCommandBufferGetCommandMemoryUsed)(&c2));
memcpy(&rh, m + 384, sizeof rh);
EXPECT("wide vertex range retains array opcode", OP_BIND_VBUF, rh.op);
b = vbuf_rec(rh.op, m + 392, &tmp);
@@ -641,15 +655,16 @@ int main(void) {
}
// 5b'. Fixed slots sized by GetCommandMemoryUsed, as Tears of the Kingdom gives each model's prerecorded lists (GitHub issue #61): a list measured at S bytes is recorded
// into slot k = base + S × k with AddCommandMemory(max(S, 512)), and slot k + 1 is recorded right after it. The list here is an uniform update of n bytes and a
// uniform buffer bind (the last record before the END in the crash), the next slot's starts with a CALL. Walking slot 0 afterwards must reach its own END through
// its two records; with 24 bytes kept for a JUMP or an END, S = 496 put its END in a host segment and the JUMP at 488 had its target overwritten by that CALL
// uniform buffer bind (the last record before the END in the crash), the next slot's starts with a call. Slot 0 must still be its two records, in one piece inside
// its S bytes, after slot 1 is recorded: when the host linked pieces with JUMPs in command memory, S = 496 put a JUMP at 488 whose target slot 1 overwrote
{
static uint8_t m[8192] __attribute__((aligned(4096))); NVNmemoryPoolBuilder mb; NVNmemoryPool mp; NVNcommandBuffer c3;
P(nvnMemoryPoolBuilderSetDefaults)(&mb); P(nvnMemoryPoolBuilderSetStorage)(&mb, m, sizeof m); P(nvnMemoryPoolInitialize)(&mp, &mb);
P(nvnCommandBufferInitialize)(&c3, &dev);
static uint8_t ub[1024]; NVNcommandHandle other = (NVNcommandHandle)m; // the CALL's target is never followed here
int broken = 0, jumps_fit = 0, first_bad = -1;
for (int n = 0; n <= 1000; n += 8) {
static uint8_t ub[1024]; NVNcommandBuffer co; P(nvnCommandBufferInitialize)(&co, &dev);
P(nvnCommandBufferBeginRecording)(&co); NVNcommandHandle other = P(nvnCommandBufferEndRecording)(&co); // an empty recording to call
int broken = 0, lists = 0, first_bad = -1;
for (int n = 0; n <= 1000; n += 8, lists++) {
P(nvnCommandBufferAddCommandMemory)(&c3, &mp, 0, sizeof m); P(nvnCommandBufferBeginRecording)(&c3); // measure, in ample memory
P(nvnCommandBufferUpdateUniformBuffer)(&c3, 0x10000, 0x1000, 0, (size_t)n, ub); P(nvnCommandBufferBindUniformBuffer)(&c3, NVN_SHADER_STAGE_FRAGMENT, 4, 0x20000, 0x100);
P(nvnCommandBufferEndRecording)(&c3);
@@ -657,44 +672,172 @@ int main(void) {
memset(m, 0, sizeof m);
P(nvnCommandBufferAddCommandMemory)(&c3, &mp, 0, give); P(nvnCommandBufferBeginRecording)(&c3);
P(nvnCommandBufferUpdateUniformBuffer)(&c3, 0x10000, 0x1000, 0, (size_t)n, ub); P(nvnCommandBufferBindUniformBuffer)(&c3, NVN_SHADER_STAGE_FRAGMENT, 4, 0x20000, 0x100);
const uint8_t *h0 = (const uint8_t *)P(nvnCommandBufferEndRecording)(&c3);
NVNcommandHandle h0 = P(nvnCommandBufferEndRecording)(&c3);
P(nvnCommandBufferAddCommandMemory)(&c3, &mp, (ptrdiff_t)S, give); P(nvnCommandBufferBeginRecording)(&c3); // the next slot, right behind
P(nvnCommandBufferCallCommands)(&c3, 1, &other); P(nvnCommandBufferEndRecording)(&c3);
// walk slot 0 as mtl_exec does: JUMP targets must be in the pool or a host segment
const uint8_t *p = h0; int ops[4], k = 0, jumped = 0, ok = 1;
for (int guard = 0; guard < 8; guard++) {
op_hdr h; memcpy(&h, p, sizeof h);
if (h.op == OP_JUMP) { const uint8_t *t; memcpy(&t, p + 8, 8); int in = t >= m && t < m + sizeof m;
for (int i = 0; i < g_nhostseg; i++) in |= t >= g_hostseg[i].mem && t < g_hostseg[i].mem + g_hostseg[i].n;
if (!in) { ok = 0; break; } jumped = 1; p = t; continue; }
uint32_t op = h.op;
P(nvnCommandBufferCallCommands)(&c3, 1, &other);
int call_free = P(nvnCommandBufferGetCommandMemoryUsed)(&c3) == 0; // a call takes no command memory
P(nvnCommandBufferEndRecording)(&c3);
int ok = call_free && one_piece(h0, m, S), k = 0, ops[3] = {0};
size_t ln; uint8_t *L0 = nvn_rec_linear(h0, &ln); // the records as submitted (compact ones expanded), less the END
for (const uint8_t *p = L0; ok && p < L0 + ln - 8; k++) {
op_hdr h; memcpy(&h, p, sizeof h); uint32_t op = h.op;
if (op == OP_BIND_UBO || op == OP_BIND_UBO_SMALL) {
p_bind_buf tmp; const p_bind_buf *b = bind_buf_rec(op, p + 8, &tmp);
ok &= b->stage == NVN_SHADER_STAGE_FRAGMENT && b->index == 4 && b->addr == 0x20000 && b->size == 0x100;
op = OP_BIND_UBO;
}
if (k < 4) ops[k] = (int)op; k++;
if (h.op == OP_END) break;
p += h.size;
if (k < 3) ops[k] = (int)op;
if (!h.size) ok = 0; else p += h.size;
}
ok &= k == 3 && ops[0] == OP_UPDATE_UB && ops[1] == OP_BIND_UBO && ops[2] == OP_END;
free(L0);
ok &= k == 2 && ops[0] == OP_UPDATE_UB && ops[1] == OP_BIND_UBO;
if (!ok) { broken++; if (first_bad < 0) first_bad = (int)S; }
jumps_fit += !jumped && S <= 504; // fits in its 512 bytes with a JUMP's room to spare after its last record: stays in its slot
}
printf("(first broken slot size %d)\n", first_bad);
EXPECT("slotted lists replay whole after the next slot is recorded", 0, broken);
EXPECT("lists of 56..504 bytes stay in their 512 (no host segment)", (504 - 56) / 8 + 1, jumps_fit);
EXPECT("slotted lists stay whole in their slots after the next slot is recorded", 0, broken);
EXPECT("lists checked", 126, lists);
P(nvnCommandBufferFinalize)(&c3); P(nvnMemoryPoolFinalize)(&mp);
}
// 5b'''. Calls and copies (NVN): CallCommands copies the called list's pieces into the caller's list, as the driver copies a command set's GPU FIFO entries, so the called
// recording's control memory may be given out again once the call is recorded (Donkey Kong Bananza resets its control arena twice per command arena: when a call
// pointed at the called list, the caller replayed whatever the next recordings wrote there); CopyCommands copies the records, so its command memory may go too
{
static uint8_t cm[4096] __attribute__((aligned(4096))), ctl_a[256] __attribute__((aligned(8))), ctl_b[256] __attribute__((aligned(8)));
static uint8_t d1[16], d2[16];
NVNmemoryPoolBuilder mb; NVNmemoryPool mp; P(nvnMemoryPoolBuilderSetDefaults)(&mb); P(nvnMemoryPoolBuilderSetStorage)(&mb, cm, sizeof cm); P(nvnMemoryPoolInitialize)(&mp, &mb);
NVNmemoryPoolBuilder db; NVNmemoryPool dp; static uint8_t dpool[4096] __attribute__((aligned(4096)));
P(nvnMemoryPoolBuilderSetDefaults)(&db); P(nvnMemoryPoolBuilderSetStorage)(&db, dpool, sizeof dpool); P(nvnMemoryPoolInitialize)(&dp, &db);
uint8_t *dst = dpool; enum { DSTN = 64 };
NVNcommandBuffer ca, cc; P(nvnCommandBufferInitialize)(&ca, &dev); P(nvnCommandBufferInitialize)(&cc, &dev);
memset(d1, 0x11, sizeof d1); memset(d2, 0x22, sizeof d2);
#define CALLEE() do { P(nvnCommandBufferAddCommandMemory)(&ca, &mp, 0, 1024); P(nvnCommandBufferAddControlMemory)(&ca, ctl_a, sizeof ctl_a); \
P(nvnCommandBufferBeginRecording)(&ca); P(nvnCommandBufferUpdateUniformBuffer)(&ca, (uintptr_t)dst, DSTN, 0, sizeof d1, d1); hc = P(nvnCommandBufferEndRecording)(&ca); } while (0)
NVNcommandHandle hc; CALLEE(); size_t rec_sz = P(nvnCommandBufferGetCommandMemoryUsed)(&ca);
P(nvnCommandBufferAddCommandMemory)(&cc, &mp, 1024, 1024); P(nvnCommandBufferAddControlMemory)(&cc, ctl_b, sizeof ctl_b);
P(nvnCommandBufferBeginRecording)(&cc); P(nvnCommandBufferCallCommands)(&cc, 1, &hc);
EXPECT("a call takes no command memory", 0, P(nvnCommandBufferGetCommandMemoryUsed)(&cc));
P(nvnCommandBufferUpdateUniformBuffer)(&cc, (uintptr_t)dst, DSTN, 16, sizeof d2, d2);
NVNcommandHandle hcall = P(nvnCommandBufferEndRecording)(&cc);
uint64_t e0 = ctl_at(hcall, 0), e1 = ctl_at(hcall, 1);
EXPECT("the caller's list: the called piece, then its own", 1, ctl_kind(e0) == CTL_CHUNK && !(e0 & CTL_LAST) && ctl_addr(e0) == cm && ctl_len(e0) == rec_sz
&& ctl_kind(e1) == CTL_CHUNK && (e1 & CTL_LAST) && ctl_addr(e1) == cm + 1024 && ctl_len(e1) == rec_sz);
memset(ctl_a, 0, sizeof ctl_a); // the called recording's control memory is given out again
memset(dst, 0, DSTN); P(nvnQueueSubmitCommands)(&q, 1, &hcall); P(nvnQueueFinish)(&q);
EXPECT("the call replays after the called list's control memory is reused", 1, !memcmp(dst, d1, 16) && !memcmp(dst + 16, d2, 16));
CALLEE();
P(nvnCommandBufferAddCommandMemory)(&cc, &mp, 2048, 1024); P(nvnCommandBufferAddControlMemory)(&cc, ctl_b, sizeof ctl_b);
P(nvnCommandBufferBeginRecording)(&cc); P(nvnCommandBufferCopyCommands)(&cc, 1, &hc);
EXPECT("a copy takes the copied records' command memory", rec_sz, P(nvnCommandBufferGetCommandMemoryUsed)(&cc));
NVNcommandHandle hcopy = P(nvnCommandBufferEndRecording)(&cc);
EXPECT("the copy is the caller's own piece", 1, one_piece(hcopy, cm + 2048, rec_sz));
memset(cm, 0, 1024); memset(ctl_a, 0, sizeof ctl_a); // both of the source's memories are given out again
memset(dst, 0, DSTN); P(nvnQueueSubmitCommands)(&q, 1, &hcopy); P(nvnQueueFinish)(&q);
EXPECT("the copy replays after the source's command and control memory are reused", 0, memcmp(dst, d1, 16));
#undef CALLEE
// A list that outgrows its control memory goes on in the block the game's callback adds, through a CTL_LINK, and replays whole
NVNcommandBuffer cl; P(nvnCommandBufferInitialize)(&cl, &dev); P(nvnCommandBufferSetMemoryCallback)(&cl, ctl_cb); P(nvnCommandBufferSetMemoryCallbackData)(&cl, NULL);
P(nvnCommandBufferAddCommandMemory)(&ca, &mp, 0, 1024); P(nvnCommandBufferAddControlMemory)(&ca, ctl_a, sizeof ctl_a);
P(nvnCommandBufferBeginRecording)(&ca); P(nvnCommandBufferUpdateUniformBuffer)(&ca, (uintptr_t)dst, DSTN, 0, sizeof d1, d1); hc = P(nvnCommandBufferEndRecording)(&ca);
g_ctloff = 0; g_ctl_calls = 0;
P(nvnCommandBufferAddCommandMemory)(&cl, &mp, 1024, 2048); P(nvnCommandBufferAddControlMemory)(&cl, g_ctlmem + 3072, 16);
P(nvnCommandBufferBeginRecording)(&cl);
for (int k = 0; k < 8; k++) { P(nvnCommandBufferCallCommands)(&cl, 1, &hc); P(nvnCommandBufferUpdateUniformBuffer)(&cl, (uintptr_t)dst, DSTN, 16 + (k & 1) * 16, sizeof d2, d2); }
NVNcommandHandle hl = P(nvnCommandBufferEndRecording)(&cl);
int links = 0, pieces = 0; const uint8_t *e = (const uint8_t *)(uintptr_t)hl;
for (int g = 0; g < 64; g++) { uint64_t v; memcpy(&v, e, 8); if (ctl_kind(v) == CTL_LINK) { links++; e = ctl_addr(v); continue; } pieces++; e += 8; if (v & CTL_LAST) break; }
EXPECT("16 pieces, linked across the callback's blocks", 1, pieces == 16 && links >= 2 && g_ctl_calls >= 2);
size_t ln; uint8_t *lin = nvn_rec_linear(hl, &ln); free(lin);
EXPECT("the linked list holds all 16 records", 16 * rec_sz + 8, ln);
EXPECT("control used: the entries in the last block", 1, P(nvnCommandBufferGetControlMemoryUsed)(&cl) > 0 && P(nvnCommandBufferGetControlMemoryUsed)(&cl) <= 32);
memset(dst, 0, DSTN); P(nvnQueueSubmitCommands)(&q, 1, &hl); P(nvnQueueFinish)(&q);
EXPECT("the linked list replays", 1, !memcmp(dst, d1, 16) && !memcmp(dst + 16, d2, 16) && !memcmp(dst + 32, d2, 16));
P(nvnCommandBufferFinalize)(&ca); P(nvnCommandBufferFinalize)(&cc); P(nvnCommandBufferFinalize)(&cl); P(nvnMemoryPoolFinalize)(&mp); P(nvnMemoryPoolFinalize)(&dp);
}
// 5b''''. Compact records (nvn_obj.h OPC_*): each call recorded both ways expands to exactly the canonical records, in no more command memory
{
static uint8_t m[16384] __attribute__((aligned(4096))); NVNmemoryPoolBuilder mb; NVNmemoryPool mp; NVNcommandBuffer ce;
P(nvnMemoryPoolBuilderSetDefaults)(&mb); P(nvnMemoryPoolBuilderSetStorage)(&mb, m, sizeof m); P(nvnMemoryPoolInitialize)(&mp, &mb);
P(nvnCommandBufferInitialize)(&ce, &dev);
NVNbufferRange r3[3] = {{0x20000, 0x100}, {0x21000, 0}, {0x22000, 0x300}}, rbig[2] = {{0x20000, 0x100}, {0x21000, UINT64_C(0x100000001)}};
NVNtextureHandle th[3] = {0x1ff00001, 0x00100002, 3}; NVNimageHandle ih[3] = {7, 8, 9}; NVNseparateSamplerHandle sh[2] = {{4}, {5}};
float vp[12] = {0, 0, 1280, 720, 10, 20, 30, 40, -1, -2, 3.5f, 4.5f};
NVNvertexAttribState va[17]; for (int i = 0; i < 17; i++) { P(nvnVertexAttribStateSetDefaults)(&va[i]); P(nvnVertexAttribStateSetFormat)(&va[i], NVN_FORMAT_RGBA32F, 4 * i); }
NVNvertexStreamState vs[3]; for (int i = 0; i < 3; i++) { P(nvnVertexStreamStateSetDefaults)(&vs[i]); P(nvnVertexStreamStateSetStride)(&vs[i], 16 + i); }
int bad = 0, smaller = 0, cases = 0; size_t saved = 0;
#define EQ(...) do { size_t u[2]; uint8_t *l[2]; size_t ln[2]; \
for (int k = 0; k < 2; k++) { g_rec_compact = !k; P(nvnCommandBufferAddCommandMemory)(&ce, &mp, 0, sizeof m); P(nvnCommandBufferBeginRecording)(&ce); __VA_ARGS__; \
NVNcommandHandle hh = P(nvnCommandBufferEndRecording)(&ce); u[k] = P(nvnCommandBufferGetCommandMemoryUsed)(&ce); l[k] = nvn_rec_linear(hh, &ln[k]); } \
g_rec_compact = 1; cases++; smaller += u[0] < u[1]; saved += u[1] - u[0]; \
if (ln[0] != ln[1] || memcmp(l[0], l[1], ln[0]) || u[0] > u[1]) { bad++; printf("compact mismatch at line %d: %zu / %zu bytes, linear %zu / %zu\n", __LINE__, u[0], u[1], ln[0], ln[1]); } \
free(l[0]); free(l[1]); } while (0)
#define CB_ &ce
EQ(P(nvnCommandBufferDrawArrays)(CB_, NVN_DRAW_PRIMITIVE_TRIANGLES, 3, 36));
EQ(P(nvnCommandBufferDrawArraysInstanced)(CB_, NVN_DRAW_PRIMITIVE_TRIANGLE_STRIP, 0, 4, 3, 2));
EQ(P(nvnCommandBufferDrawArraysInstanced)(CB_, NVN_DRAW_PRIMITIVE_POINTS, 1, 4, 0, 0));
EQ(P(nvnCommandBufferDrawArraysIndirect)(CB_, NVN_DRAW_PRIMITIVE_LINES, 0x30000));
EQ(h_nvnCommandBufferDrawMeshTasks(CB_, 2, 9));
EQ(h_nvnCommandBufferDrawMeshTasksIndirect(CB_, 0x30040));
EQ(P(nvnCommandBufferDrawElements)(CB_, NVN_DRAW_PRIMITIVE_TRIANGLES, NVN_INDEX_TYPE_UNSIGNED_INT, 99, UINT64_C(0x1234567890)));
EQ(P(nvnCommandBufferDrawElementsBaseVertex)(CB_, NVN_DRAW_PRIMITIVE_TRIANGLES, NVN_INDEX_TYPE_UNSIGNED_BYTE, 6, 0x10000, -7));
EQ(P(nvnCommandBufferDrawElementsInstanced)(CB_, NVN_DRAW_PRIMITIVE_TRIANGLES, NVN_INDEX_TYPE_UNSIGNED_SHORT, 6, 0x10000, 5, 1, 3));
EQ(P(nvnCommandBufferDrawElementsIndirect)(CB_, NVN_DRAW_PRIMITIVE_TRIANGLES, NVN_INDEX_TYPE_UNSIGNED_SHORT, 0x10000, 0x20000));
EQ(P(nvnCommandBufferSetViewport)(CB_, 1, 2, 300, 400));
EQ(P(nvnCommandBufferSetViewports)(CB_, 2, 3, vp));
EQ(P(nvnCommandBufferSetStencilRef)(CB_, NVN_FACE_FRONT_AND_BACK, 0x80));
EQ(P(nvnCommandBufferSetStencilMask)(CB_, NVN_FACE_BACK, 0xff));
EQ(P(nvnCommandBufferSetStencilValueMask)(CB_, NVN_FACE_FRONT, 0));
EQ(P(nvnCommandBufferSetStencilRef)(CB_, NVN_FACE_FRONT, 1 << 20)); // past the compact form: canonical both ways
EQ(P(nvnCommandBufferBindImage)(CB_, NVN_SHADER_STAGE_COMPUTE, 3, 12));
EQ(P(nvnCommandBufferBindImages)(CB_, NVN_SHADER_STAGE_FRAGMENT, 1, 3, ih));
EQ(P(nvnCommandBufferBindTextures)(CB_, NVN_SHADER_STAGE_FRAGMENT, 2, 3, th));
EQ(CB(&ce)->tex_base = 5; CB(&ce)->samp_base = 2; P(nvnCommandBufferBindTextures)(CB_, NVN_SHADER_STAGE_VERTEX, 0, 3, th); CB(&ce)->tex_base = CB(&ce)->samp_base = 0);
EQ(P(nvnCommandBufferBindSeparateSamplers)(CB_, NVN_SHADER_STAGE_FRAGMENT, 0, 2, sh));
EQ(P(nvnCommandBufferBindSeparateTexture)(CB_, NVN_SHADER_STAGE_FRAGMENT, 4, (NVNseparateTextureHandle){77}));
EQ(h_nvnCommandBufferBindTexturesDeferred(CB_, NVN_SHADER_STAGE_FRAGMENT, 0, 2, th));
EQ(P(nvnCommandBufferBindUniformBuffers)(CB_, NVN_SHADER_STAGE_VERTEX, 4, 3, r3));
EQ(P(nvnCommandBufferBindUniformBuffers)(CB_, NVN_SHADER_STAGE_VERTEX, 14, 3, r3)); // past slot 16: one by one both ways
EQ(P(nvnCommandBufferBindUniformBuffers)(CB_, NVN_SHADER_STAGE_FRAGMENT, 0, 2, rbig));
EQ(P(nvnCommandBufferBindStorageBuffer)(CB_, NVN_SHADER_STAGE_COMPUTE, 5, 0x40000, 0x1000));
EQ(P(nvnCommandBufferBindStorageBuffers)(CB_, NVN_SHADER_STAGE_COMPUTE, 1, 3, r3));
EQ(P(nvnCommandBufferBindStorageBuffers)(CB_, NVN_SHADER_STAGE_COMPUTE, 0, 2, rbig));
EQ(P(nvnCommandBufferBindVertexBuffers)(CB_, 1, 3, r3));
EQ(P(nvnCommandBufferBindVertexBuffers)(CB_, 0, 2, rbig));
EQ(P(nvnCommandBufferBindVertexAttribState)(CB_, 17, va));
EQ(P(nvnCommandBufferBindVertexStreamState)(CB_, 3, vs));
EQ(P(nvnCommandBufferBindVertexBuffer)(CB_, 0, 0x20000, 0x1000); P(nvnCommandBufferBindUniformBuffer)(CB_, NVN_SHADER_STAGE_VERTEX, 3, 0x30000, 0x100);
P(nvnCommandBufferBindTexture)(CB_, NVN_SHADER_STAGE_FRAGMENT, 0, 0x1ff00002); P(nvnCommandBufferDrawElementsBaseVertex)(CB_, NVN_DRAW_PRIMITIVE_TRIANGLES, NVN_INDEX_TYPE_UNSIGNED_SHORT, 300, 0x10000, 7));
NVNbufferRange ua[3] = {{0x30000, 0x100}, {0x30100, 0x10000}, {0x7fff00, 0}}, un[2] = {{0x30010, 0x100}, {0x30000, 0x40000}};
EQ(P(nvnCommandBufferBindUniformBuffer)(CB_, NVN_SHADER_STAGE_FRAGMENT, 13, UINT64_C(0xfedcba987600), 0x3ffff));
EQ(P(nvnCommandBufferBindUniformBuffer)(CB_, NVN_SHADER_STAGE_FRAGMENT, 2, 0x30010, 0x100)); // not 256-aligned: the 24-byte form
EQ(P(nvnCommandBufferBindUniformBuffers)(CB_, NVN_SHADER_STAGE_GEOMETRY, 1, 3, ua));
EQ(P(nvnCommandBufferBindUniformBuffers)(CB_, NVN_SHADER_STAGE_VERTEX, 0, 2, un));
NVNcolorState cs; P(nvnColorStateSetDefaults)(&cs); P(nvnColorStateSetBlendEnable)(&cs, 3, 1); P(nvnColorStateSetLogicOp)(&cs, NVN_LOGIC_OP_XOR);
NVNdepthStencilState dss; P(nvnDepthStencilStateSetDefaults)(&dss); P(nvnDepthStencilStateSetDepthFunc)(&dss, NVN_DEPTH_FUNC_GEQUAL); P(nvnDepthStencilStateSetStencilTestEnable)(&dss, 1);
NVNblendState bls; P(nvnBlendStateSetDefaults)(&bls); P(nvnBlendStateSetBlendTarget)(&bls, 2);
NVNchannelMaskState cms; P(nvnChannelMaskStateSetDefaults)(&cms); P(nvnChannelMaskStateSetChannelMask)(&cms, 7, 1, 0, 1, 0);
NVNpolygonState pls; P(nvnPolygonStateSetDefaults)(&pls); P(nvnPolygonStateSetCullFace)(&pls, NVN_FACE_BACK);
NVNmultisampleState mss; P(nvnMultisampleStateSetDefaults)(&mss); P(nvnMultisampleStateSetSamples)(&mss, 4);
EQ(P(nvnCommandBufferBindColorState)(CB_, &cs)); EQ(P(nvnCommandBufferBindDepthStencilState)(CB_, &dss)); EQ(P(nvnCommandBufferBindBlendState)(CB_, &bls));
EQ(P(nvnCommandBufferBindChannelMaskState)(CB_, &cms)); EQ(P(nvnCommandBufferBindPolygonState)(CB_, &pls)); EQ(P(nvnCommandBufferBindMultisampleState)(CB_, &mss));
EQ(P(nvnCommandBufferBarrier)(CB_, 0x1f)); EQ(P(nvnCommandBufferBarrier)(CB_, 1 << 30));
EQ(P(nvnCommandBufferSetPrimitiveRestart)(CB_, 1, -1)); EQ(P(nvnCommandBufferSetPrimitiveRestart)(CB_, 1, 0xffff)); EQ(P(nvnCommandBufferSetPrimitiveRestart)(CB_, 0, 0x7fffffff));
EQ(P(nvnCommandBufferSetScissor)(CB_, 0, 0, 1920, 1080)); EQ(P(nvnCommandBufferSetScissor)(CB_, -4, 0, 70000, 8));
#undef EQ
#undef CB_
printf("(compact records: %d cases, %d smaller, %zu bytes saved)\n", cases, smaller, saved);
EXPECT("compact records expand to the canonical ones, in no more bytes", 0, bad);
EXPECT("compact records are smaller in most cases", 1, smaller >= 35);
P(nvnCommandBufferFinalize)(&ce); P(nvnMemoryPoolFinalize)(&mp);
}
// 5b''. Host segment sizes (hostseg_size), as Super Mario Odyssey grants 512 bytes from an empty pool before recording: such a grant gets a HOSTSEG_SMALL segment; a recording
// that outgrows it with no callback JUMPs into a full one and replays whole through its first handle; a record larger than HOSTSEG_SZ gets a segment that holds it;
// that outgrows it with no callback goes on in a full one, as a second piece of its control list, and replays whole through its handle; a record larger than HOSTSEG_SZ gets a segment that holds it;
// a free small segment is not taken for a full one, and the cap counts every segment's bytes
{
NVNcommandBuffer c4, c5; P(nvnCommandBufferInitialize)(&c4, &dev); P(nvnCommandBufferInitialize)(&c5, &dev);
EXPECT("empty pool, 512 bytes, outside a recording: a small segment", HOSTSEG_SMALL, hostseg_size(CB(&c4), 1, 512));
EXPECT("empty pool, 0 bytes: a full segment", HOSTSEG_SZ, hostseg_size(CB(&c4), 1, 0));
EXPECT("empty pool, more than HOSTSEG_SMALL: a full segment", HOSTSEG_SZ, hostseg_size(CB(&c4), 1, HOSTSEG_SMALL + 1));
EXPECT("a record larger than HOSTSEG_SZ: a segment that holds it", 1, hostseg_size(CB(&c4), 0, HOSTSEG_SZ + 64) >= HOSTSEG_SZ + 64 + 16);
EXPECT("a record larger than HOSTSEG_SZ: a segment that holds it", 1, hostseg_size(CB(&c4), 0, HOSTSEG_SZ + 64) >= HOSTSEG_SZ + 64);
P(nvnCommandBufferAddCommandMemory)(&c4, NULL, 0, 512);
uint8_t *small = CB(&c4)->cur;
EXPECT("the grant lends HOSTSEG_SMALL bytes", HOSTSEG_SMALL, CB(&c4)->end - small);
@@ -706,15 +849,15 @@ int main(void) {
P(nvnCommandBufferUpdateUniformBuffer)(&c4, (uintptr_t)dst, sizeof dst, 0, sizeof d1, d1);
P(nvnCommandBufferUpdateUniformBuffer)(&c4, (uintptr_t)dst, sizeof dst, 64, sizeof d2, d2);
NVNcommandHandle h4 = P(nvnCommandBufferEndRecording)(&c4);
op_hdr h0, h1; memcpy(&h0, small, sizeof h0); memcpy(&h1, small + h0.size, sizeof h1);
EXPECT("the handle is the small segment's start", (uintptr_t)small, h4);
EXPECT("the record that does not fit follows a JUMP", OP_JUMP, h1.op);
op_hdr h0; memcpy(&h0, small, sizeof h0); uint64_t e0 = ctl_at(h4, 0), e1 = ctl_at(h4, 1);
EXPECT("the list's first piece is the first record, in the small segment", 1, ctl_kind(e0) == CTL_CHUNK && !(e0 & CTL_LAST) && ctl_addr(e0) == small && ctl_len(e0) == h0.size);
EXPECT("the record that does not fit is the last piece, elsewhere", 1, ctl_kind(e1) == CTL_CHUNK && (e1 & CTL_LAST) && (ctl_addr(e1) < small || ctl_addr(e1) >= small + HOSTSEG_SMALL));
P(nvnQueueSubmitCommands)(&q, 1, &h4); P(nvnQueueFinish)(&q);
EXPECT("the first record replays", 0, memcmp(dst, d1, sizeof d1));
EXPECT("the record past the JUMP replays", 0, memcmp(dst + 64, d2, sizeof d2));
EXPECT("the record in the second piece replays", 0, memcmp(dst + 64, d2, sizeof d2));
P(nvnCommandBufferBeginRecording)(&c4);
uint8_t *big = cmd_alloc(CB(&c4), HOSTSEG_SZ + 64);
EXPECT("a record larger than HOSTSEG_SZ fits its segment with OP_RESERVE after it", 1, CB(&c4)->end - big >= HOSTSEG_SZ + 64 + OP_RESERVE);
EXPECT("a record larger than HOSTSEG_SZ fits its segment", 1, CB(&c4)->end - big >= HOSTSEG_SZ + 64);
P(nvnCommandBufferEndRecording)(&c4);
pthread_mutex_lock(&g_hostseg_mu); int si = -1; for (int i = 0; i < g_nhostseg; i++) if (g_hostseg[i].mem == small) si = i; if (si >= 0) g_hostseg[si].busy = 0; pthread_mutex_unlock(&g_hostseg_mu);
P(nvnCommandBufferAddCommandMemory)(&c5, NULL, 0, 0);
@@ -769,7 +912,7 @@ int main(void) {
P(nvnWindowBuilderSetTextures)(&wb, 2, missing_first);
EXPECT("WindowInitialize with null first texture", 1, P(nvnWindowInitialize)(&win, &wb));
P(nvnWindowBuilderSetTextures)(&wb, 2, scp); EXPECT("WindowInitialize succeeds", 1, P(nvnWindowInitialize)(&win, &wb));
int idx[4];
int idx[4]; unsigned bi = 0; while (strcmp(nvn_names[bi], "nvnCommandBufferBarrier")) bi++; uint64_t barriers0 = nvn_slot[bi].cnt; // earlier tests bind barriers too
for (int f = 0; f < 4; f++) {
P(nvnWindowAcquireTexture)(&win, &s2, &idx[f]);
for (int b = 0; b < 5; b++) P(nvnCommandBufferBarrier)(&cb, 0);
@@ -777,8 +920,7 @@ int main(void) {
}
EXPECT("swapchain rotates 0,1,0,1", 0x0101, idx[0] << 12 | idx[1] << 8 | idx[2] << 4 | idx[3]);
EXPECT("sync signaled after acquire (0)", 0, P(nvnSyncWait)(&s2, 0));
unsigned bi = 0; while (strcmp(nvn_names[bi], "nvnCommandBufferBarrier")) bi++;
EXPECT("Barrier count = 4 frames × 5", 20, nvn_slot[bi].cnt);
EXPECT("Barrier count = 4 frames × 5", 20, nvn_slot[bi].cnt - barriers0);
// 6b. Readback: pixel (x,y) = {x*16+y, y*16+x, 0x55, 0xAA} (expected values computed directly from the formula)
{
+4 -3
View File
@@ -15,7 +15,7 @@ void svc_thread_dump(void) {}
uint64_t now_ns(void) { return bp_now(); }
static int checks, fails;
#define CHECK(c, label) do { checks++; if (!(c)) { fails++; fprintf(stderr,"FAIL: %s\n",label); } } while (0)
static uint8_t commands[8192]; static size_t used;
static uint8_t commands[8192] __attribute__((aligned(8))); static size_t used;
static void emit(unsigned op, const void *p, size_t n) {
size_t size = (8 + n + 7) & ~7ull; op_hdr h = {op, (uint32_t)size};
memcpy(commands + used, &h, 8); if (n) memcpy(commands + used + 8, p, n); used += size;
@@ -99,8 +99,9 @@ int main(void) { @autoreleasepool {
struct { int32_t first,n; vs_st stream; } stream = {0,1,{.stride=16}}; emit(OP_BIND_VSTREAM,&stream,sizeof stream);
p_bind_vbuf1 vb = {.index=0,.size=sizeof positions,.addr=(uint64_t)vertices}; emit(OP_BIND_VBUF1,&vb,sizeof vb);
p_vp_swizzle sw = {.n=1}; sw.sw[0][1]=flip; emit(OP_VP_SWIZZLE,&sw,sizeof sw);
p_draw draw = {.prim=NVN_DRAW_PRIMITIVE_TRIANGLES,.count=3,.instances=1}; emit(OP_DRAW,&draw,sizeof draw); emit(OP_END,NULL,0);
NVNcommandHandle handle = (NVNcommandHandle)commands;
p_draw draw = {.prim=NVN_DRAW_PRIMITIVE_TRIANGLES,.count=3,.instances=1}; emit(OP_DRAW,&draw,sizeof draw);
static uint64_t list; list = ctl_e(CTL_CHUNK,commands,used) | CTL_LAST; // the records' control list: one piece (nvn_obj.h ctl_e)
NVNcommandHandle handle = (NVNcommandHandle)&list;
P(nvnQueueSubmitCommands)(&queues[queue],1,&handle); P(nvnQueueFinish)(&queues[queue]);
int front = ccw == (front_in_clip[queue][current][winding] ^ flip);
int visible = cull == NVN_FACE_NONE || (cull == NVN_FACE_FRONT && !front) || (cull == NVN_FACE_BACK && front);
+6 -6
View File
@@ -179,7 +179,7 @@ static void packed_copies(int format, int tid) {
NVNsync sync; h_nvnSyncInitialize(&sync, NULL);
h_nvnCommandBufferFenceSync(&cmd, &sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
NVNcommandHandle h = h_nvnCommandBufferEndRecording(&cmd);
state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec((const uint8_t *)h); mtl_sub_commit();
state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec(nvn_rec_linear(h, NULL)); mtl_sub_commit();
int wait = h_nvnSyncWait(&sync, 5000000000ull); EXPECT("packed copies fence wait", 1, wait == 0 || wait == 1);
char n[160]; const char *f = rgba4 ? "RGBA4" : b565 ? "RGB565" : a1 ? "RGB5A1" : "RGB5";
mtl_reg_tex(tid, TX(&copied), NULL); float s[8]; sample2(tid, s);
@@ -236,7 +236,7 @@ static void mirror_completion(void) {
c->poolRelease = dispatch_semaphore_create(0); c->waiterExited = dispatch_semaphore_create(0);
state_reset(); memset(&R, 0, sizeof R); readback_pool_drop(); mtl_sub_begin();
ReadbackDevice *device = [ReadbackDevice new]; device.device = g_dev; device.observedLength = 4096; g_dev = (id)device; // the 128-byte readback's size (mrbuf_get)
mtl_exec((const uint8_t *)handle);
mtl_exec(nvn_rec_linear(handle, NULL));
g_dev = device.device;
[g_commit_blocks addObject:^{
dispatch_semaphore_signal(c->feedbackEntered);
@@ -388,7 +388,7 @@ static void copy_stream(void) { @autoreleasepool {
NVNsync sync; h_nvnSyncInitialize(&sync, NULL);
h_nvnCommandBufferFenceSync(&cmd, &sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
NVNcommandHandle h = h_nvnCommandBufferEndRecording(&cmd);
state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec((const uint8_t *)h); mtl_sub_commit();
state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec(nvn_rec_linear(h, NULL)); mtl_sub_commit();
int wait = h_nvnSyncWait(&sync, 5000000000ull); EXPECT("stream fence wait", 1, wait == 0 || wait == 1);
EXPECT("stream GPU success", 0, mtl_last_commit_error());
EXPECT("9 copies into a texture uploaded from its storage: one re-upload (the CPU write before them)", 1, (int)(g_pkg_reuploads - r0));
@@ -453,7 +453,7 @@ static void copy_stream_3d(void) { @autoreleasepool {
NVNsync sync; h_nvnSyncInitialize(&sync, NULL);
h_nvnCommandBufferFenceSync(&cmd, &sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
NVNcommandHandle h = h_nvnCommandBufferEndRecording(&cmd);
state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec((const uint8_t *)h); mtl_sub_commit();
state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec(nvn_rec_linear(h, NULL)); mtl_sub_commit();
int wait = h_nvnSyncWait(&sync, 5000000000ull); EXPECT("volume fence wait", 1, wait == 0 || wait == 1);
EXPECT("volume GPU success", 0, mtl_last_commit_error());
EXPECT("8 slice copies into a volume uploaded from its storage: no re-upload", 0, (int)(g_pkg_reuploads - r0));
@@ -495,7 +495,7 @@ static void gpu_storage(void) {
NVNsync sync; h_nvnSyncInitialize(&sync, NULL);
h_nvnCommandBufferFenceSync(&cmd, &sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
NVNcommandHandle h = h_nvnCommandBufferEndRecording(&cmd);
state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec((const uint8_t *)h); mtl_sub_commit();
state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec(nvn_rec_linear(h, NULL)); mtl_sub_commit();
int wait = h_nvnSyncWait(&sync, 5000000000ull); EXPECT("GPU storage fence wait", 1, wait == 0 || wait == 1);
EXPECT("GPU success", 0, mtl_last_commit_error());
static const uint8_t expected[] = {51, 102, 153, 255}, expected2[] = {204, 153, 102, 255};
@@ -596,7 +596,7 @@ int main(void) { @autoreleasepool {
NVNsync sync; h_nvnSyncInitialize(&sync, NULL);
h_nvnCommandBufferFenceSync(&cmd, &sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
NVNcommandHandle h = h_nvnCommandBufferEndRecording(&cmd);
state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec((const uint8_t *)h); mtl_sub_commit();
state_reset(); memset(&R, 0, sizeof R); mtl_sub_begin(); mtl_exec(nvn_rec_linear(h, NULL)); mtl_sub_commit();
int wait = h_nvnSyncWait(&sync, 5000000000ull); EXPECT("recorded fence wait", 1, wait == 0 || wait == 1);
EXPECT("GPU success", 0, mtl_last_commit_error());
int bad = 0;
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env python3
"""Bytes of command memory and control memory the game's own NVN driver uses for each command-buffer call: runs the driver's code in an emulator.
NVN's driver, NVN1 on Switch and NVN2 on Switch 2, is linked into each game's sdk module. Its entry points are named in a table of 32-bit offsets into a blob of names
("CommandBufferDrawElements", alphabetical), and its implementations sit in a pointer table in the same order (NVN2's GetProcAddress hands out thunks that dispatch through a
table filled from it). This tool finds both tables, reads the command buffer's layout from the driver's own getters (GetCommandMemoryUsed and the like), and runs each call
between BeginRecording and EndRecording on a command buffer of that layout with ample memory. The bytes are the write pointers' advance. Imports are stubs (memcpy, memmove
and memset copy; anything else returns 0), and fields the driver keeps beyond the layout start at 0, so a call that needs a device or a program object may stop with an error:
its row says so. hle_nvn.c's compact records (nvn_obj.h OPC_*) were sized against this table; docs/reference/memory.md, "Model heaps sized by the host's command record sizes".
Usage: nvn_native_sizes.py <ExeFS/sdk> [--names] (prints call, command bytes, control bytes, error; --names: the entry points and their implementations instead)
Needs unicorn (pip install unicorn) and capstone."""
import argparse, os, re, struct, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import nso # noqa: E402
IB, IND, VB, UB, SB, FRAG = 0x10000, 0x18000, 0x20000, 0x30000, 0x40000, 1
# Calls, as host tests make them: entry point (without the CommandBuffer prefix) and arguments; 'P:<kind>' is a pointer to data the runner places (ptr below)
CASES = [
('empty', []),
('DrawArrays', [('DrawArrays', (4, 0, 36))]),
('DrawElements', [('DrawElements', (4, 1, 36, IB))]),
('DrawElementsBaseVertex', [('DrawElementsBaseVertex', (4, 1, 36, IB, 5))]),
('DrawElementsBaseVertex 0', [('DrawElementsBaseVertex', (4, 1, 36, IB, 0))]),
('DrawArraysInstanced', [('DrawArraysInstanced', (4, 0, 36, 0, 2))]),
('DrawElementsInstanced', [('DrawElementsInstanced', (4, 1, 36, IB, 5, 0, 2))]),
('DrawElementsIndirect', [('DrawElementsIndirect', (4, 1, IB, IND))]),
('BindVertexBuffer', [('BindVertexBuffer', (3, VB, 0x100))]),
('BindVertexBuffers 2', [('BindVertexBuffers', (0, 2, 'P:ranges2'))]),
('BindUniformBuffer', [('BindUniformBuffer', (FRAG, 2, UB, 0x100))]),
('BindUniformBuffers 2', [('BindUniformBuffers', (FRAG, 0, 2, 'P:ranges2'))]),
('BindStorageBuffer', [('BindStorageBuffer', (FRAG, 1, SB, 0x100))]),
('BindTexture', [('BindTexture', (FRAG, 3, 0x1ff00001))]),
('BindTextures 2', [('BindTextures', (FRAG, 0, 2, 'P:handles2'))]),
('BindImage', [('BindImage', (FRAG, 0, 5))]),
('BindBlendState', [('BindBlendState', ('P:BlendState',))]),
('BindColorState', [('BindColorState', ('P:ColorState',))]),
('BindChannelMaskState', [('BindChannelMaskState', ('P:ChannelMaskState',))]),
('BindMultisampleState', [('BindMultisampleState', ('P:MultisampleState',))]),
('BindPolygonState', [('BindPolygonState', ('P:PolygonState',))]),
('BindDepthStencilState', [('BindDepthStencilState', ('P:DepthStencilState',))]),
('BindVertexAttribState 4', [('BindVertexAttribState', (4, 'P:attribs4'))]),
('BindVertexStreamState 2', [('BindVertexStreamState', (2, 'P:streams2'))]),
('UpdateUniformBuffer 64', [('UpdateUniformBuffer', (UB, 0x1000, 0, 64, 'P:data64'))]),
('SetViewports 1', [('SetViewports', (0, 1, 'P:vp1'))]),
('SetScissors 1', [('SetScissors', (0, 1, 'P:sc1'))]),
('Barrier', [('Barrier', (0x10,))]),
('ClearColor', [('ClearColor', (0, 'P:rgba', 0xf))]),
('SetStencilRef', [('SetStencilRef', (3, 0x80))]),
('SetBlendColor', [('SetBlendColor', ('P:rgba',))]),
('SetPrimitiveRestart', [('SetPrimitiveRestart', (1, 0xffff))]),
('mesh: vbuf, ubo, tex, draw', [('BindVertexBuffer', (0, VB, 0x1000)), ('BindUniformBuffer', (0, 3, UB, 0x100)), ('BindTexture', (FRAG, 0, 0x1ff00002)),
('DrawElementsBaseVertex', (4, 1, 300, IB, 7))]),
]
BASE, STUBS, OBJ, CMD, CTL, ARG, STK, RET = 0x80000000, 0x16000000, 0x10000000, 0x11000000, 0x12000000, 0x13000000, 0x14000000, 0x15000000
IDENT = set(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_')
def dyn_tags(d):
mod0 = struct.unpack_from('<I', d, 4)[0]; dyn = mod0 + struct.unpack_from('<i', d, mod0 + 4)[0]; tags = {}
for i in range(4096):
t, v = struct.unpack_from('<qQ', d, dyn + i * 16)
if t == 0: break
tags.setdefault(t, v)
return tags
def relative_relocs(d, tags):
"""{slot: target offset} of the module's relative relocations (RELA type 1027 and RELR)"""
rel = {}
for k in range(tags.get(8, 0) // 24):
off, info, add = struct.unpack_from('<QQq', d, tags[7] + k * 24)
if info & 0xffffffff == 1027: rel[off] = add
where = 0
for k in range(tags.get(35, 0) // 8):
e = struct.unpack_from('<Q', d, tags[36] + k * 8)[0]
if not e & 1:
rel[e] = struct.unpack_from('<Q', d, e)[0]; where = e + 8; continue
for b in range(63):
if e >> (b + 1) & 1: rel[where + b * 8] = struct.unpack_from('<Q', d, where + b * 8)[0]
where += 63 * 8
return rel
def name_table(d):
"""The driver's entry point names, in table order: the table of 32-bit offsets in which the anchor's offset and its successor's differ by the anchor's length + 1"""
word = b'CommandBufferDrawElementsBaseVertex'
anchor = d.find(b'\0' + word + b'\0') + 1
if anchor <= 0: sys.exit('no NVN driver names in this module')
gap = len(word) + 1
def names_at(t, s):
while t >= 4 and struct.unpack_from('<I', d, t)[0]: t -= 4
out = []
while t + 4 <= len(d):
o = struct.unpack_from('<I', d, t)[0]
if out and not o: break
nm = d[s + o:d.find(b'\0', s + o)] if s + o < len(d) else b''
if not re.fullmatch(rb'[A-Za-z0-9_]+', nm): break
out.append(nm.decode()); t += 4
return out
w = struct.unpack_from('<%dI' % (len(d) // 4), d, 0); best = []
for i in range(len(w) - 1):
o = w[i]
if w[i + 1] - o == gap and o <= anchor:
got = names_at(4 * i, anchor - o)
if len(got) > len(best): best = got
return best
def impl_table(d, rel, names, text_end, md):
"""{name: implementation offset}: the pointer table parallel to the names whose getters are leaf functions and whose indexed draws write the index buffer method (0x5f2)"""
idx = {n: i for i, n in enumerate(names)}
def leaf(f):
for i in md.disasm(d[f:f + 48], f):
if i.mnemonic == 'ret': return True
if i.mnemonic in ('bl', 'blr', 'b', 'stp', 'pacibsp'): return False
return False
def draw(f): return any(i.mnemonic == 'mov' and i.op_str.endswith('#0x5f2') for i in md.disasm(d[f:f + 0x400], f))
getters = ['CommandBufferGetCommandMemoryUsed', 'CommandBufferIsRecording', 'CommandBufferGetControlMemoryUsed', 'CommandBufferGetCommandMemorySize']
best, base = 0, None
for b in sorted(rel):
fs = [rel.get(b + 8 * idx[n]) for n in getters]
sc = sum(1 for f in fs if f and f < text_end and leaf(f))
if sc < 3: continue
sc += sum(1 for n in ('CommandBufferDrawElements', 'CommandBufferDrawElementsBaseVertex') if (f := rel.get(b + 8 * idx[n])) and f < text_end and draw(f))
if sc > best: best, base = sc, b
if base is None or best < 5: sys.exit('the implementation table was not found')
return {n: rel.get(base + 8 * i, 0) for i, n in enumerate(names)}
def layout(d, impl, md):
"""The command buffer fields the getters read: write pointers, ends, starts, the recording flag"""
def loads(name):
f = impl[name]; out = []
for i in md.disasm(d[f:f + 32], f):
if i.mnemonic == 'ret': break
m = re.match(r'(ldr|ldrb|ldp) (\w+)(?:, (\w+))?, \[x0(?:, #(0x[0-9a-f]+|\d+))?\]', f'{i.mnemonic} {i.op_str}')
if m:
off = int(m.group(4) or '0', 0)
out.append((m.group(2), off))
if m.group(1) == 'ldp': out.append((m.group(3), off + 8))
m = re.match(r'sub x0, (x\d+), (x\d+)', f'{i.mnemonic} {i.op_str}')
if m: return {r: o for r, o in out}, m.group(1), m.group(2)
return {r: o for r, o in out}, None, None
def diff(name): # (minuend field, subtrahend field) of a getter that returns a - b
regs, a, b = loads(name)
if a not in regs or b not in regs: sys.exit(f'cannot read the layout from {name}')
return regs[a], regs[b]
cur, start = diff('CommandBufferGetCommandMemoryUsed')
end, cur2 = diff('CommandBufferGetCommandMemoryFree')
ccur, cstart = diff('CommandBufferGetControlMemoryUsed')
regs, _, _ = loads('CommandBufferIsRecording')
if cur2 != cur or not regs: sys.exit('unexpected command memory getters')
return dict(cur=cur, start=start, ccur=ccur, cend=ccur + 8, cstart=cstart, rec=next(iter(regs.values()))), sorted({cur + 8, end}) # the fields, the command ends
class Driver:
def __init__(self, path):
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM
m = nso.read(path); d = bytearray(m.image); self.md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
tags = dyn_tags(d); rel = relative_relocs(d, tags)
self.names = name_table(bytes(d)); self.impl = impl_table(bytes(d), rel, self.names, m.text_end, self.md)
self.layout, self.ends = layout(bytes(d), self.impl, self.md)
for off, add in rel.items(): struct.pack_into('<Q', d, off, BASE + add)
symtab, strtab, stubs = tags[6], tags[5], {}
for tab, sz in ((tags.get(23, 0), tags.get(2, 0)), (tags.get(7, 0), tags.get(8, 0))): # imports: JUMP_SLOT, GLOB_DAT, ABS64
for k in range(sz // 24 if tab else 0):
off, info, add = struct.unpack_from('<QQq', d, tab + k * 24)
if info & 0xffffffff not in (1025, 1026, 257): continue
sym = symtab + (info >> 32) * 24
if struct.unpack_from('<H', d, sym + 6)[0]: struct.pack_into('<Q', d, off, BASE + struct.unpack_from('<Q', d, sym + 8)[0] + add); continue
o = struct.unpack_from('<I', d, sym)[0]; name = bytes(d[strtab + o:d.index(b'\0', strtab + o)]).decode('latin1')
struct.pack_into('<Q', d, off, STUBS + 16 * stubs.setdefault(name, len(stubs)) + add)
self.stubname = {i: n for n, i in stubs.items()}
self.img, self.size = bytes(d), (len(d) + m.bss + 0xfffff) & ~0xfffff
def fresh(self):
from unicorn import Uc, UC_ARCH_ARM64, UC_MODE_ARM, UC_HOOK_CODE # pyright: ignore[reportMissingImports] # an optional package, only this tool needs it
from unicorn.arm64_const import UC_ARM64_REG_X0, UC_CPU_ARM64_MAX # pyright: ignore[reportMissingImports]
mu = Uc(UC_ARCH_ARM64, UC_MODE_ARM); mu.ctl_set_cpu_model(UC_CPU_ARM64_MAX) # pointer authentication (pacibsp / retab) as on the console
mu.mem_map(BASE, self.size); mu.mem_write(BASE, self.img)
for a in (0, OBJ, CMD, CTL, ARG, STK, RET, STUBS): mu.mem_map(a, 0x1000000) # page 0 too: a field left at 0 reads zeros
mu.mem_write(RET, b'\x00\x00\x20\xd4'); mu.mem_write(STUBS, b'\xc0\x03\x5f\xd6' * (0x1000000 // 4))
def stub(uc, addr, size, ud):
name = self.stubname.get((addr - STUBS) // 16, ''); x = [uc.reg_read(UC_ARM64_REG_X0 + i) for i in range(3)]
if name in ('memcpy', 'memmove', '__memcpy_chk'): uc.mem_write(x[0], bytes(uc.mem_read(x[1], x[2])))
elif name == 'memset': uc.mem_write(x[0], bytes([x[1] & 0xff]) * x[2])
else: uc.reg_write(UC_ARM64_REG_X0, 0)
mu.hook_add(UC_HOOK_CODE, stub, begin=STUBS, end=STUBS + 0x1000000 - 1)
o, L = bytearray(0x400), self.layout
for k, v in (('cur', CMD), ('start', CMD), ('ccur', CTL), ('cend', CTL + 0x80000), ('cstart', CTL)): struct.pack_into('<Q', o, L[k], v)
for e in self.ends: struct.pack_into('<Q', o, e, CMD + 0x80000)
o[L['rec']] = 1
mu.mem_write(OBJ, bytes(o)); self.mu, self.argp = mu, ARG
def arg(self, data):
a = self.argp; self.mu.mem_write(a, data); self.argp = (a + len(data) + 15) & ~15; return a
def call(self, name, *args, obj=True):
from unicorn import UcError # pyright: ignore[reportMissingImports]
from unicorn.arm64_const import UC_ARM64_REG_X0, UC_ARM64_REG_SP, UC_ARM64_REG_LR, UC_ARM64_REG_PC # pyright: ignore[reportMissingImports]
mu = self.mu
for i, v in enumerate(((OBJ,) if obj else ()) + args): mu.reg_write(UC_ARM64_REG_X0 + i, v & 0xffffffffffffffff)
mu.reg_write(UC_ARM64_REG_SP, STK + 0x800000); mu.reg_write(UC_ARM64_REG_LR, RET)
try: mu.emu_start(BASE + self.impl[name], RET, count=500000)
except UcError as e: return f'{e} at {name}+{mu.reg_read(UC_ARM64_REG_PC) - BASE - self.impl[name]:#x}'
return None if mu.reg_read(UC_ARM64_REG_PC) == RET else f'{name} did not return'
def used(self):
r = lambda k: struct.unpack('<Q', self.mu.mem_read(OBJ + self.layout[k], 8))[0]
return r('cur') - r('start'), r('ccur') - r('cstart')
def ptr(self, kind):
if kind == 'ranges2': return self.arg(struct.pack('<4Q', VB, 0x100, VB + 0x1000, 0x200))
if kind == 'handles2': return self.arg(struct.pack('<2Q', 0x1ff00001, 0x1ff00002))
if kind == 'data64': return self.arg(bytes(range(64)))
if kind == 'vp1': return self.arg(struct.pack('<4f', 0, 0, 1280, 720))
if kind == 'sc1': return self.arg(struct.pack('<4i', 0, 0, 1280, 720))
if kind == 'rgba': return self.arg(struct.pack('<4f', 0.25, 0.5, 0.75, 1))
if kind in ('attribs4', 'streams2'): # NVN's state sizes: an attribute 4 bytes, a stream 8
n, sz, f = (4, 4, 'VertexAttribStateSetDefaults') if kind == 'attribs4' else (2, 8, 'VertexStreamStateSetDefaults')
a = self.arg(bytes(0x20 * n))
for i in range(n): self.call(f, a + sz * i, obj=False)
return a
a = self.arg(bytes(0x80)); self.call(kind + 'SetDefaults', a, obj=False); return a
def main():
ap = argparse.ArgumentParser(description=(__doc__ or '').split('\n')[0]); ap.add_argument('sdk'); ap.add_argument('--names', action='store_true')
a = ap.parse_args()
try: import unicorn # noqa: F401 # pyright: ignore[reportMissingImports]
except ImportError: sys.exit('needs unicorn: pip install unicorn')
drv = Driver(a.sdk)
if a.names:
for n in drv.names: print(f'{n}\t{drv.impl[n]:#x}')
return
print(f'# {len(drv.names)} entry points; command buffer layout {drv.layout}, command memory ends {drv.ends}')
print('call\tcommand bytes\tcontrol bytes\terror')
for name, steps in CASES:
drv.fresh(); err = drv.call('CommandBufferBeginRecording')
for fn, args in steps:
err = err or drv.call('CommandBuffer' + fn, *(drv.ptr(x[2:]) if isinstance(x, str) else x for x in args))
err = err or drv.call('CommandBufferEndRecording')
cmd, ctl = drv.used()
print(f'{name}\t{cmd}\t{ctl}\t{err or ""}')
if __name__ == '__main__':
main()
+1
View File
@@ -563,6 +563,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- `FATAL NVN command memory: the game's pool is empty…`. → [Host-lent command memory segments](../reference/nvn-objects.md#host-lent-command-memory-segments)
- frames stop after about 15 s; a game thread spins in its command-memory callback (a ring allocator at `main+0x9cc120` waiting for fences that have all signalled). → [What `GetCommandMemoryUsed` counts](../reference/nvn-objects.md#what-getcommandmemoryused-counts)
- `CRASH sig=10` in `mtl_exec` after minutes of play, the fault address equal to `x19` and shaped like `0x1000000003`. → [Prerecorded lists in slots of their measured size](../reference/nvn-objects.md#prerecorded-lists-in-slots-of-their-measured-size)
- a model load runs out of its resource heap: `[RED] BufferInitialize: pool has no storage (pool 0x0 …)`, then `CRASH sig=11` in `h_nvnMemoryPoolGetFlags` (Model heaps sized by the host's command record sizes). → [A recording's end and links are in control memory](../reference/nvn-objects.md#a-recordings-end-and-links-are-in-control-memory)
- a jump to pc=0 on a worker thread, with the backtrace `0x0` ← `cmd_alloc_keep` ← `h_nvnCommandBufferCopyBufferToTexture` and `lr` in the game's `main`, just after the instruction that called the game's command memory callback. → [Copy strides are command buffer state](../reference/nvn-objects.md#copy-strides-are-command-buffer-state)
- `CRASH sig=11 addr=0x50` on a game thread, at `pc=main+0x385201c` in Super Smash Bros. Ultimate (`ldr x0, [x8, #0x10]` with `x8 = 0x40`), as a battle starts. Rare: it crashed on 1 of 2 battle starts in one run on a Mac mini and on none of 11 in another. → [`GetCommandMemorySize` read while another thread records](../reference/nvn-objects.md#getcommandmemorysize-read-while-another-thread-records)
- the title showed one stretched 64×64 icon over the 3D scene, a new game a white screen; post-process passes with stale texture handles; `[RED] bind record … overwritten after recording`. → [Recorded commands patched in place by the game (`OP_BIND_TEX1`)](../reference/nvn-objects.md#recorded-commands-patched-in-place-by-the-game-op_bind_tex1)
+16 -2
View File
@@ -406,9 +406,23 @@ The guest address space, heaps, pools, virtual address memory and the allocators
- **Symptom:** a model load exhausts its resource heap: a null `operator new` at the world load, or `BufferInitialize: pool has no storage` followed by a null-pool crash. A display-list heap that runs out shows as `AddCommandMemory` with a null pool outside a recording, then host-lent segments growing until `FATAL NVN command memory` ([Host-lent command memory segments](nvn-objects.md#host-lent-command-memory-segments)).
- **Cause:** games size model allocations by measuring scratch command recordings; oversized host records can exceed the budgets in their resource-size tables. In Breath of the Wild, each model's heap is its table entry + 0x1008, the file goes in 4 KB aligned, and the setup (`main+0x155a2ac`) takes the rest as a frame heap (vtable `main+0x1d4f950`, head `+0xe0`, tail `+0xe8`). Its use is the same in every run; only the file's alignment pad varies (0 to 0xff8), and the entries leave room for any pad, about 0xd00 to spare on most models. Three models were a 4 KB page short, so the loads with a large pad failed. The game sizes the model's prerecorded commands by recording each mesh's draw and each shape's per-pass state into a scratch command buffer and summing `GetCommandMemoryUsed` (`main+0xf9aeb4`, `main+0xf9bb54`), and our records were larger than the driver's (draws carried the indirect and multi-draw fields, every recording began with a BEGIN record). Super Mario Odyssey keeps its display lists in a 62 MB GPU bump heap named "DisplayList" (`main+0x5e8280`: used at `+0x68`, capacity at `+0x6c`, a null block when full), allocated while a kingdom loads; with 40-byte state binds (39% of the display-list bytes) it filled at the load and every later list got a null block.
- **Fix:** plain draws leave unused indirect fields out and recordings start with their first command. Uniform and single vertex-buffer bindings also use compact 24-byte records instead of 32, preserving full GPU addresses and retaining full-width fallback records for ranges above `UINT32_MAX`; multi-vertex ranges retain their array representation. State binds carry only the state object's bytes (16 bytes for color, channel mask and polygon state, 24 for blend, multisample and depth-stencil, instead of 40), and a single texture bind drops its pool bases when both are 0 (24 bytes instead of 32, the handle still 16 bytes in). Replay expands the compact forms into the same canonical binding state. The native inline uniform command takes 20 bytes and the native vertex-buffer command 24, so these small differences can accumulate into an extra 4 KB GPU-pool chunk. Report the bytes actually recorded; do not underreport usage or add a game-specific heap allowance. See [What `GetCommandMemoryUsed` counts](nvn-objects.md#what-getcommandmemoryused-counts).
- **Fix:** plain draws leave unused indirect fields out and recordings start with their first command. Uniform and single vertex-buffer bindings also use compact 24-byte records instead of 32, preserving full GPU addresses and retaining full-width fallback records for ranges above `UINT32_MAX`; multi-vertex ranges retain their array representation. State binds carry only the state object's bytes (16 bytes for color, channel mask and polygon state, 24 for blend, multisample and depth-stencil, instead of 40), and a single texture bind drops its pool bases when both are 0 (24 bytes instead of 32, the handle still 16 bytes in). Replay expands the compact forms into the same canonical binding state. The native inline uniform command takes 20 bytes and the native vertex-buffer command 24, so these small differences can accumulate into an extra 4 KB GPU-pool chunk. Report the bytes actually recorded; do not underreport usage or add a game-specific heap allowance. A recording's end, the links between its pieces and its calls take no command memory, as in NVN: they are entries in control memory ([A recording's end and links are in control memory](nvn-objects.md#a-recordings-end-and-links-are-in-control-memory)), which saves the 8 bytes of END on each scratch recording. On top of that, what games record per mesh and per pass takes compact forms that only command memory holds: `nvn_obj.h` `OPC_*`, with small arguments in the header's upper 24 bits. The queue's flatten expands each into the canonical records (`hle_nvn.c` `rec_expand`), so replay, capture and the replay walkers see no new op. They were sized against the driver's own commands, measured by running the NVN driver linked into a game's `sdk` in an emulator (`dm/tools/nvn_native_sizes.py`). The results, in command bytes, were identical on NVN1 (Fire Emblem: Three Houses, Cuphead, Minecraft Dungeons II) and NVN2 (Ocarina of Time, Donkey Kong Bananza) except where noted:
| Call | Driver | Host before | Host now |
|---|---:|---:|---:|
| DrawElements / with base vertex | 24 / 48-72 | 40 | 24 |
| DrawArrays / instanced | 16 / 24 | 32 | 16 / 24 |
| DrawElementsIndirect | 28-36 | 64 | 24 |
| BindUniformBuffer / two | 20 / 24-40 | 24 / 48 | 16 / 24 |
| BindTextures (two) / BindImage | 28 / 20 | 48 / 40 | 16 |
| SetViewports (one) / SetStencilRef | 36 / 8 | 400 / 32 | 24 / 8 |
| BindVertexAttribState (four) / stream (two) | 24 (NVN1: 68 / 72) | 32 | 24 |
| color / polygon / depth-stencil state | 12 / 20-24 / 8 | 16 / 16 / 24 | 8 / 8 / 16 |
| a mesh: vertex buffer, uniform buffer, texture, draw | 132 | 112 | 88 |
Five calls stay above the driver's, at the floor of an 8-byte header and 8-byte records: the depth-stencil state (16, driver 8), BindTexture (24, driver 16), which keeps its layout because Luigi's Mansion 3 patches its handle 16 bytes in, BindStorageBuffer and SetBlendColor (24, driver 20), and SetScissor (16, driver 12). An empty recording takes no command memory, as on the driver. The driver also uses 56 bytes of control memory for a recording of a few commands and 24 for an empty one; the host uses 8. `t_nvn` records 51 calls both ways and checks that each compact record expands to exactly the canonical records. Donkey Kong Bananza's recorded command bytes per frame fell by a third on the same route (127 → 88 KB at frame 900, 334 → 223 KB at frame 3,000; Mac, no shader libraries for this chain). See [What `GetCommandMemoryUsed` counts](nvn-objects.md#what-getcommandmemoryused-counts).
- **Check:** for Breath of the Wild's whole scene, probe where the setup heap is cut (`main+0x155a520` with `!x21`, the resource heap) and the end of the setup (`main+0x155a5f4` with `!x2`, the frame heap), with `DM_PROBE_HEAP=28,38,40,e0,f8 DM_PROBE_HEAPFRAME=1d4f950 DM_PROBE_HEAPWORDS=1` ([05](../agents/05-debugging.md#probes-without-a-debugger-dm_probe)). A model fits any placement when entry + 0x1008 covers the resource heap's header and object (0x310), the file, the frame heap's block header and its peak use, plus 0xff8 of pad.
- **Found on:** [The Legend of Zelda: Breath of the Wild](../../dm/games/01007EF00011E000/README.md), [Super Mario Bros. Wonder](../../dm/games/010015100B514000/README.md#memory) (buffer bindings; the game note records the failed allocation, measured sizes and validation), [Super Mario Odyssey](../../dm/games/0100000000010000/README.md#services) (state and single texture binds; the note has the heap's measurements).
- **Found on:** [The Legend of Zelda: Breath of the Wild](../../dm/games/01007EF00011E000/README.md), [Super Mario Bros. Wonder](../../dm/games/010015100B514000/README.md#memory) (buffer bindings; the game note records the failed allocation, measured sizes and validation), [Super Mario Odyssey](../../dm/games/0100000000010000/README.md#services) (state and single texture binds; the note has the heap's measurements); reported for the Nintendo Switch 2 Edition of Super Mario Bros. Wonder and for Drag x Drive, the end of each recording in command memory ([PR #1609](https://github.com/seedds/nxnative/pull/1609), not run here).
### Unity's GPU pool block allocation spins at size 0
+16 -5
View File
@@ -249,15 +249,15 @@ A game may tell NVN objects apart by their bytes, without an NVN call. A host re
### Control memory capacity queries
- **Symptom:** `[RED] NVN unimplemented function called: nvnCommandBufferGetControlMemoryFree` (or `…GetControlMemorySize`) once, after the game gives a command buffer control memory.
- **Cause:** `AddControlMemory` was a no-op, and the size and free getters reached the unimplemented stub, which returns 0, so a game that checks the free space sees none left. The host writes its records only to command memory and uses no byte of the game's control memory, so in NVN's terms (size = used + free) the whole block stays free.
- **Fix:** `cmd_t` records the size of the last `AddControlMemory` block and returns it from both `GetControlMemoryFree` and `GetControlMemorySize`; `GetControlMemoryUsed` stays 0. `t_nvn` checks the values before any block, after one, after a recording and after a smaller block replaces it.
- **Cause:** `AddControlMemory` was a no-op, and the size and free getters reached the unimplemented stub, which returns 0, so a game that checks the free space sees none left.
- **Fix:** `cmd_t` records the last `AddControlMemory` block; `GetControlMemorySize` returns its size, `GetControlMemoryUsed` the bytes of control entries the host wrote into it ([A recording's end and links are in control memory](#a-recordings-end-and-links-are-in-control-memory); 0 until then, when the host used none), and `GetControlMemoryFree` the rest. `t_nvn` checks the values before any block, after one, after a recording and after a smaller block replaces it.
- **Found on:** South Park: The Fractured But Whole 1.05, whose port is [PR #662](https://github.com/seedds/nxnative/pull/662) (not yet in the games table). With the getters implemented it reached the title, menu, a save and character customization on the Mac; with them returning 0 it also progressed, but submitted commands at a different rate.
### Host-lent command memory segments
- **Symptom:** `FATAL NVN command memory: the game's pool is empty…`.
- **Cause:** our command records are larger than real NVN commands, so command buffers the game sizes for hardware overflow; when the game's out-of-memory callback declines to add memory, the host lends a segment. Many small command buffers each overflowing once per frame exhausted a fixed pool of 64 × 1 MB.
- **Fix** (`hle_nvn.c`): the pool now grows on demand (256 KB segments, abort only beyond 1 GB; `hostseg_take`). A segment is released only when the game re-grants memory overlapping the guest bytes of the recording that jumped into it (`hostseg_release` in `AddCommandMemory`): the game records setup blocks once and keeps `CallCommands`-ing them for many frames, so recycling segments after a fixed number of frames would overwrite live recordings. An empty-pool grant of at most 4 KB outside a recording gets a 4 KB segment, a record larger than 256 KB gets a segment that holds it, and the cap counts every segment's bytes (`hostseg_size`). Such a grant has no guest range, so its segment is never reclaimed. On hardware a null pool cannot be written to, so a game that grants one has run out of the command memory it measured for itself: the host's records were larger than the driver's ([Model heaps sized by the host's command record sizes](memory.md#model-heaps-sized-by-the-hosts-command-record-sizes)). That is fixed in the record sizes; the host does not try to recycle these segments by guessing which recording a grant replaces.
- **Fix** (`hle_nvn.c`): the pool now grows on demand (256 KB segments, abort only beyond 1 GB; `hostseg_take`). A segment is released only when the game re-grants memory overlapping the guest bytes of the recording that overflowed into it (`hostseg_release` in `AddCommandMemory`): the game records setup blocks once and keeps `CallCommands`-ing them for many frames, so recycling segments after a fixed number of frames would overwrite live recordings. An empty-pool grant of at most 4 KB outside a recording gets a 4 KB segment, a record larger than 256 KB gets a segment that holds it, and the cap counts every segment's bytes (`hostseg_size`). Such a grant has no guest range, so its segment is never reclaimed. On hardware a null pool cannot be written to, so a game that grants one has run out of the command memory it measured for itself: the host's records were larger than the driver's ([Model heaps sized by the host's command record sizes](memory.md#model-heaps-sized-by-the-hosts-command-record-sizes)). That is fixed in the record sizes; the host does not try to recycle these segments by guessing which recording a grant replaces.
- **Found on:** [Super Mario Bros. Wonder](../../dm/games/010015100B514000/README.md) (the many small command buffers: its opening course, per the comment at `HOSTSEG_SZ` in `hle_nvn.c`), [Super Mario Odyssey](../../dm/games/0100000000010000/README.md) (it hands out many 512-byte grants before recording, and with no recording to reclaim them by, 256 KB each reached the cap entering the Wooded Kingdom: the 4 KB segments; 1.4.1 still reached it after 11 minutes of play, about 260,000 4 KB segments, because its display-list heap was full and each re-recording took a new one; fixed by the cause, [Model heaps sized by the host's command record sizes](memory.md#model-heaps-sized-by-the-hosts-command-record-sizes)).
### What `GetCommandMemoryUsed` counts
@@ -267,7 +267,7 @@ Games read this count as a position in their own command memory and size their h
- **Symptom:** frames stop after about 15 s; a game thread spins in its command-memory callback (a ring allocator at `main+0x9cc120` waiting for fences that have all signalled).
- **Cause:**
- NVN counts used bytes from the last `AddCommandMemory`; the host counted from `BeginRecording`. KTGL gives its main command buffer one 16 MB chunk of a ring and, in its callback (`main+0x9ca960`), takes chunk start + `GetCommandMemoryUsed` as the position the GPU has reached, so the position stayed at one frame's size and the ring never freed.
- `GetCommandMemoryUsed` must count everything the recording used, including the parts that went into host segments (plus 16 bytes for the jump). Mario marks a recorded block as empty when the count is 0 and then skips calling it (how that happened: [Inlined SDK code writes into `NVNcommandBuffer` +0x10](#inlined-sdk-code-writes-into-nvncommandbuffer-0x10)).
- `GetCommandMemoryUsed` must count everything the recording used, including the parts that went into host segments. Mario marks a recorded block as empty when the count is 0 and then skips calling it (how that happened: [Inlined SDK code writes into `NVNcommandBuffer` +0x10](#inlined-sdk-code-writes-into-nvncommandbuffer-0x10)).
- Games also size their own heaps and slots from this count: [Model heaps sized by the host's command record sizes](memory.md#model-heaps-sized-by-the-hosts-command-record-sizes) (Breath of the Wild's model heaps) and [Prerecorded lists in slots of their measured size](#prerecorded-lists-in-slots-of-their-measured-size) (next entry).
- **Fix:** the count now resets at `AddCommandMemory` (`hle_nvn.c`).
- **Check:** Super Mario Bros. Wonder and Super Mario Odyssey checked unchanged after the reset.
@@ -277,10 +277,21 @@ Games read this count as a position in their own command memory and size their h
- **Symptom:** `CRASH sig=10` in `mtl_exec` after minutes of play, the fault address equal to `x19` and shaped like `0x1000000003`.
- **Cause:** the fault is the record-header load at the top of `mtl_exec`'s loop, `x19` is the replay pointer, and the address is itself a record header (`{op 3 = OP_CALL, size 16}`): a JUMP's target had been overwritten by the next recording. Tears of the Kingdom gives each model's prerecorded lists fixed slots of the size a recording of that list measured (`GetCommandMemoryUsed`), slot k at base + size × k, and passes `AddCommandMemory` max(size, 512) (`main+0xbb120`); its memory callback is empty. The host kept 24 bytes free after every record for "a JUMP or an END", so a 496-byte list's END went to a host segment and the 16-byte JUMP at 488 reached 8 bytes into the next slot.
- **Fix:** the host now keeps 16 bytes (one JUMP), lets the END take a segment's last bytes, and links only recordings that have records, so a JUMP only stands where a record of 16 bytes or more was to go and never writes past what `GetCommandMemoryUsed` reported (`OP_RESERVE` in `hle_nvn.c`; `t_nvn` "slotted lists").
- **Fix:** first the host kept 16 bytes (one JUMP) instead of 24 and let the END take a segment's last bytes. Now command memory holds nothing but the records: a recording's end and the links between its pieces are entries in control memory, so nothing ever stands past what `GetCommandMemoryUsed` reported ([A recording's end and links are in control memory](#a-recordings-end-and-links-are-in-control-memory); `t_nvn` "slotted lists").
- **Note:** to read such a crash, `x8` holds the jump-table target of the previous record's case, and the registers a callee saved below `sp` give the previous replay pointer (`x19`) and payload (`x26`).
- **Found on:** [The Legend of Zelda: Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md) (1.4.3, GitHub issue #61).
### A recording's end and links are in control memory
- **Symptom:** a model load runs out of its resource heap: `[RED] BufferInitialize: pool has no storage (pool 0x0 …)`, then `CRASH sig=11` in `h_nvnMemoryPoolGetFlags` ([Model heaps sized by the host's command record sizes](memory.md#model-heaps-sized-by-the-hosts-command-record-sizes)).
- **Cause:** in NVN, command memory holds only GPU commands. What strings a recording together is in control memory, which the driver reads on the CPU, at `CallCommands` and at submit: the end of a recording, the link to its next piece of command memory when it ran out, and the pieces of a recording it calls. The handle points there, and the device reports control memory aligned to 8 bytes and at least 256 of it (items 0x14 and 0x16, `hle_nvn.c`). The host wrote all of these as records into command memory instead and counted them in `GetCommandMemoryUsed`: 8 bytes of END per recording, a 16-byte JUMP per new piece and a 16-byte CALL per call, while it reported no control memory used. Engines that size a model's prerecorded commands by measuring scratch recordings, one per mesh and per shape and pass, against a fixed resource budget paid 8 bytes per recording more than the driver's commands.
- **Fix** (`hle_nvn.c`, `nvn_obj.h` `ctl_e`, `nvn_queue.inc` `nq_flatten`): command memory holds only the records. Each recording's control list is 8-byte entries in the game's control memory: a piece of records (address and length), or a link to more control memory, the last one marked. The handle is the first entry. `GetControlMemoryUsed` and `GetControlMemoryFree` count the entries. A non-final entry is written only with 8 bytes left after it, so a list cut off by new control memory (from the game's out-of-control-memory callback or on its own) is always linked on from where it stopped. When the game's callback gives none, the host lends 64 KB blocks that are never reclaimed.
- `CallCommands` copies the called list's pieces into the caller's list, as the driver copies a command set's GPU FIFO entries, so the called recording's control memory may be given out again once the call is recorded. Its command memory must stay, since the pieces still point into it.
- `CopyCommands` copies the records into the caller's command memory, so the source may be recorded over at once. It was recorded as a call before.
- The queue's flatten walks the list. Replay, capture and the capture format are unchanged, since they see the flattened records.
- **Check:** `t_nvn` checks the counts per recording (no END), the handle as a one-piece list, an empty recording (no command memory, one entry), slotted lists, the host-segment piece split, a call that replays after the called list's control memory is overwritten, a copy that replays after both of the source's memories are overwritten, and a list linked across three control blocks from the callback. The out-of-control-memory callback was measured on Cuphead (Unity): it gives one 128 KB block at boot and another each time the callback asks.
- **Found on:** reported for [Super Mario Bros. Wonder](../../dm/games/010015100B514000/README.md)'s Nintendo Switch 2 Edition (`NpcCommonerA` needed `0x5424` bytes of a `0x5000` budget, `PlayerPeachElpWM` `0x400c` of `0x4000`) and for Drag x Drive (`040041601D83A000`, 5 s after boot), in [PR #1609](https://github.com/seedds/nxnative/pull/1609) and [issue #1580](https://github.com/seedds/nxnative/issues/1580). Neither game is on this Mac, so neither was run with this fix. [Donkey Kong Bananza](../../dm/games/040074A01BF12000/README.md) gave the calls their copy: its control memory comes from one arena reset twice per arena of command memory, and while a call pointed at the called list, the caller replayed whatever the next recordings had written there (`FATAL invalid NVN command size` within 100 s in about one run in six).
### Copy strides are command buffer state
- **Symptom:** a jump to pc=0 on a worker thread, with the backtrace `0x0` ← `cmd_alloc_keep` ← `h_nvnCommandBufferCopyBufferToTexture` and `lr` in the game's `main`, just after the instruction that called the game's command memory callback.