nvn/textures: cache Metal texture conformance per thread (PR #1467)

Texture resolution repeatedly walks the same Objective-C protocol lists
before checking for a stale sRGB or linear view. Store the class and
conformance result in a small thread-local cache, and use the same
lookup for texture upgrades and GPU ownership checks. The cache holds
class identities without changing the lifetime of the objects checked.

The focused alias and ownership tests pass, as do the iPhone SDK compile
and documentation checks. On an M6, 800,000 comparisons across eight
workers matched the direct query, and the median warm lookup took 3.2 ns
against 74 ns for the direct query. Breath of the Wild 1.9.0 passes the
quick route with pipeline archives off on both hosts.

Co-authored-by: Xipz <[email protected]>
This commit is contained in:
seeddsandXipz committed 2026-11-18 09:26:09 +08:00
1 parent 461a5f9f95
commit efd1bddd82
4 files changed
+34 -3

No files matched your search

+1
View File
@@ -225,6 +225,7 @@ Before publishing, the fixes were integrated with main's pipeline archive and GP
## Found on this game
- [Repeated Metal texture conformance checks](../../../docs/reference/nvn-objects.md#repeated-metal-texture-conformance-checks) (resolved in the host).
- [The split shader tables differ from a game profile's](../../../docs/reference/packing.md#the-split-shader-tables-differ-from-a-game-profiles): the registered 1.9.0 map's duplicate representatives, resolved above.
- [An argument block points into another arena after a nested allocation](../../../docs/reference/rendering.md#an-argument-block-points-into-another-arena-after-a-nested-allocation): two host bugs reproduced by synthetic GPU tests; the [Zora cutscene retest](#zoras-domain-cutscene-gpu-faults-original-device-retest-pending) passed on baseline and fixed hosts, so the connection to the reported game faults remains unconfirmed.
- [Two captures of one shader function crash in Metal's binary cache](../../../docs/reference/rendering.md#two-captures-of-one-shader-function-crash-in-metals-binary-cache): resolved in the host; 1.9.0's prebuild crashed once in a `regress.py` run (M4 Pro, macOS 27.2.1).
+24 -3
View File
@@ -2908,6 +2908,27 @@ void mtl_drain(void) { present_drop_for_suspend(); mtl_present_flush(); snap_dra
// ================= Render replay =================
#include "../../host/front.h"
// Texture lookups run on the submit thread and other game threads. Cache conformance for the few Metal texture and wrapper classes they see.
// Only classes and answers are kept here. The caller's reference to the object must be valid for the check.
static BOOL obj_is_tex(id object) {
if (!object) return NO;
enum { CACHE_SIZE = 8 };
static _Thread_local struct {
struct { __unsafe_unretained Class cls; BOOL is_texture; } entries[CACHE_SIZE];
unsigned next;
} cache;
Class cls = object_getClass(object);
for (unsigned i = 0; i < CACHE_SIZE; i++)
if (cache.entries[i].cls == cls) return cache.entries[i].is_texture;
BOOL is_texture = [object conformsToProtocol:@protocol(MTLTexture)];
unsigned slot = cache.next++ % CACHE_SIZE;
cache.entries[slot].cls = cls;
cache.entries[slot].is_texture = is_texture;
return is_texture;
}
static int g_red_once[175]; // one past the highest key: a new key raises this, and the macro refuses to compile otherwise
#define RED_ONCE(k, ...) do { _Static_assert((k) < sizeof g_red_once / sizeof *g_red_once, "a RED_ONCE key past g_red_once: raise its size"); if (!g_red_once[k]++) MLOG("[RED] " __VA_ARGS__); } while (0)
// NVN vertex streams 0–15 → Metal vertex buffer slots: 0–13 go to 16–29 (30 is the constant fallback buffer), 14 and 15 to 14 and 15. Metal has only the 31 slots 0–30; translated shaders use only buffer(0) (the argument buffer),
@@ -3240,7 +3261,7 @@ static inline void tex_lsize(const tex_t *t, unsigned l, uint32_t *w, uint32_t *
static id<MTLTexture> tex_upgrade(const tex_t *t, id<MTLTexture> asked, MTLTextureUsage add, MTLPixelFormat view_pf) {
id holder = tex_get(t->serial);
// The serial holds an sRGB / linear view (tex_mtl_) of the asked texture, or the asked texture is that view: the parent is upgraded and the view made again on it, so the pair keeps sharing its bytes
id<MTLTexture> view = ![holder isKindOfClass:[NvPkg class]] && [holder conformsToProtocol:@protocol(MTLTexture)] && ((id<MTLTexture>)holder).parentTexture
id<MTLTexture> view = ![holder isKindOfClass:[NvPkg class]] && obj_is_tex(holder) && ((id<MTLTexture>)holder).parentTexture
&& (holder == asked || ((id<MTLTexture>)holder).parentTexture == asked) ? holder : nil;
id<MTLTexture> base = view ? view.parentTexture : asked;
if (base.isSparse) { RED_ONCE(149, "a placement sparse texture needs usage %#lx it was not made with (ser=%llu format %#x): kept as it is, not remade whole", (unsigned long)add, (unsigned long long)t->serial, t->d.format); return base; }
@@ -4641,7 +4662,7 @@ static void gws_drop_pool(const pool_t *p) { // the pool goes: its spans with
// The GPU owns the texture's content: its host texture was made to be rendered into or written by shaders (nvn_ft_poll in hle_nvn.c never re-uploads such a texture from guest memory)
int mtl_tex_gpu_owned(uint64_t serial) {
__unsafe_unretained id o = tex_get(serial);
if (!o || ![o conformsToProtocol:@protocol(MTLTexture)]) return 0;
if (!obj_is_tex(o)) return 0;
return (((id<MTLTexture>)o).usage & (MTLTextureUsageRenderTarget | MTLTextureUsageShaderWrite)) != 0;
}
void mtl_tex_cpu_written(const tex_t *t) {
@@ -5193,7 +5214,7 @@ static id<MTLTexture> tex_mtl_(const tex_t *ct, int *in_storage) {
// An sRGB / linear view whose parent left the sharing table (upgraded, or evicted with its pool; a takeover leaves a held view's parent) no longer shares the storage's bytes: dropped,
// live or finalized (its ghost entry), and made again below on what holds them now. serial_del took only a live entry, so a finalized serial kept resolving to the stale view
// whenever making the new texture failed, and to any thread in between
if (have && [have conformsToProtocol:@protocol(MTLTexture)] && ((id<MTLTexture>)have).parentTexture && own_view_drop_stale(t->serial, have)) {
if (obj_is_tex(have) && ((id<MTLTexture>)have).parentTexture && own_view_drop_stale(t->serial, have)) {
static int nstale; if (nstale++ < 4) MLOG("stale sRGB / linear view dropped ser=%llu format %lu (%d so far)", (unsigned long long)t->serial, (unsigned long)((id<MTLTexture>)have).pixelFormat, nstale);
have = nil;
}
+1
View File
@@ -737,6 +737,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- the submit thread spends a tenth of a millisecond or more a frame in `memcpy` under `pool_walk` in a game that patches its pool tables often (0.13-0.18 ms on an Apple M6; PR #2663 measured about 1 ms of submit and present on an M1 at 30 patches a frame). Ocarina of Time patches 16 to 24 tables a frame of 33,025 entries while Link walks through Kokiri Forest (one per texture type, Pool tables that held only their own texture type), about 5 MB of copies a frame for a few hundred changed entries each; PR #2663 saw about 30 a frame on an older host. → [A patched pool table copied whole](../reference/nvn-objects.md#a-patched-pool-table-copied-whole)
- while a game streams an area in, frames of 100 ms to about 1 s with the GPU at its usual time, no new pipelines and no texture uploads in them: the `[longframe]` lines put the whole frame in `submit+present`, and a long session falls into slow motion for a minute or two at a time. In the `[nvn-mtl] memory up to frame` line, `finalized textures still referenced 512 (small table, N put in total)` stays at 512 and N jumps by millions in one report (651 to 3,669,055 in 300 frames at an area transition; 43 million in one window riding into Hyrule Field), and `deferred-release queue` reaches tens of thousands. After the same game's pause menu, which it streams behind, 50 to 55 fps for about five seconds with `[nvn] pool tables … built whole` at 1.4 to 1.6 a frame (9 ms each) and the pool line's `a new submission over too many retired IDs` counting nearly every build. → [More finalized textures in use than their table held](../reference/nvn-objects.md#more-finalized-textures-in-use-than-their-table-held)
- a pool table keeps naming an sRGB / linear twin's view after the texture it is a view of left the sharing table and, 17 submissions later, the residency set: a texture ID with no residency behind it, which gives GPU address faults in the shaders that sample it (as in issue #1326), and a view that no longer shares its storage's bytes with anything. Seen in `t_pool_notes` only, in no game. → [A view's entry did not hold its parent](../reference/nvn-objects.md#a-views-entry-did-not-hold-its-parent)
- in Breath of the Wild, Metal texture classification accounted for 44 of 130 samples in `tex_mtl_` at about 3,000 checks per frame, an estimated 1.5% of submit-thread CPU. PR #1467 → [Repeated Metal texture conformance checks](../reference/nvn-objects.md#repeated-metal-texture-conformance-checks)
- surfaces that read textures by handle through a texture pool come out black or unlit. PRAGMATA: Cabin's monitor in the Shelter stays black (the console shows a cyan animated face), and every cube map read through the pool samples zero (environment reflections and light). No `[RED]` line. → [Pool tables that held only their own texture type](../reference/nvn-objects.md#pool-tables-that-held-only-their-own-texture-type)
- `[RED] [pool-type] texture ID … (ser=… 1x1 format 0x25 target 1) is Metal type 2, read through a type 5 texture pool table: left out (dummy), no view serves it`, or a 3D texture `read through a type 2 texture pool table`, in the frame after a scene change, with a different ID each run. → [Read marks of a texture type kept when an ID changes type](../reference/nvn-objects.md#read-marks-of-a-texture-type-kept-when-an-id-changes-type)
- the host stops with `[dm] CRASH sig=10` (or 11) on a game thread's store into memory a memory pool covered, while another thread finalizes that pool, or finalizes it and initializes a new one over the same memory. Neither is known from a game yet. → [A memory pool retired while another thread uses its tracking slot](../reference/nvn-objects.md#a-memory-pool-retired-while-another-thread-uses-its-tracking-slot)
+8
View File
@@ -287,6 +287,14 @@ A game may tell NVN objects apart by their bytes, without an NVN call. A host re
- **Check:** `make -C dm/gfx/tests GAME=<id> check_t_pool_notes`: with the note of the twin's first resolution taken, a texture of another description over the storage leaves the twin's parent shared, held and resident and the table's entry unchanged, with no table built; once the twin is finalized the next such texture evicts the parent. The same case fails three checks on the host before the fix. Not checked: a game (none is known to keep a twin live past its parent's object); the check after the entry, which needs a second thread.
- **Found on:** no game: reported from the code and the fixture in [issue #2125](https://github.com/seedds/nxnative/issues/2125).
### Repeated Metal texture conformance checks
- **Symptom:** in Breath of the Wild, Metal texture classification accounted for 44 of 130 samples in `tex_mtl_` at about 3,000 checks per frame, an estimated 1.5% of submit-thread CPU. [PR #1467](https://github.com/seedds/nxnative/pull/1467)
- **Cause:** the stale sRGB / linear view check asked `conformsToProtocol:` on each resolved object before reading its `parentTexture`. The same few classes repeatedly walked their protocol lists.
- **Fix:** `obj_is_tex` caches eight class and conformance pairs per thread. Texture resolution can run on other threads as well as the submit thread. The cache holds class identities and results, and callers still use the serial owner's lifetime rules when they look up and inspect an object. A miss uses the original protocol query.
- **Check:** on an Apple M6, a microbenchmark alternating a Metal texture, its sRGB view and a non-texture object took a median of 74 ns per direct query and 3.2 ns per warm-cache lookup. A separate pass matched the direct query in 800,000 comparisons across eight workers, including nil lookups and class eviction. The Breath of the Wild 1.9.0 quick route passed against `083c5e4f` with pipeline archives disabled on both hosts after the baseline stalled in Metal's archive serializer.
- **Found on:** [The Legend of Zelda: Breath of the Wild](../../dm/games/01007EF00011E000/README.md).
### Pool tables that held only their own texture type
- **Symptom:** surfaces that read textures by handle through a texture pool come out black or unlit. PRAGMATA: Cabin's monitor in the Shelter stays black (the console shows a cyan animated face), and every cube map read through the pool samples zero (environment reflections and light). No `[RED]` line.