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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Image atomics on buffer images: the reflection declares a texture_buf…
…fer IMG a buffer, and an unbound one gets a buffer placeholder and an atomic scratch of its own

Main's image-atomic admission (PR #178) takes a bound image only of the shader's declared type (imga_extent). nvn_refl.m declared each IMG from its placeholder table, which has no buffer type, so a texture_buffer IMG came out 2D and every real buffer image failed the admission: "FATAL [RED] image atomics: unsupported or overflowing IMG extent" at the first such dispatch. SHIN MEGAMI TENSEI V (PR #173) stopped there about 60 s into a new game, at Unreal's compute shader 05fe2caae79b6e53 (an atomic on a 448,800-byte buffer image).

- nvn_refl.m: a texture_buffer IMG is declared a buffer (MTLTextureTypeTextureBuffer), as a sampled texture_buffer (TEXD) already was.
- nvn_mtl.m: an unbound buffer image gets a one-texel buffer texture of its own (dummy_img_tbuf; dummy_img's cache is indexed by type and has no slot for it), its row aligned to the format's minimum linear alignment. An unbound IMGA gets a 256-byte atomic scratch (dummy_atom_buf) instead of dummy_buf, the zero buffer unbound buffers read, which the atomics through an unbound slot could write.
- t_imga_tbuf (Metal, API validation layer): the declared type, a bound buffer texture admitted with its extent, the unbound placeholder's type, and the scratch's capacity and that it is not dummy_buf; without the nvn_refl.m line 3 of its 11 checks fail. test_imga_binding_source.py: the unbound IMGA does not take dummy_buf.

Docs: a docs/reference/shaders.md entry, the contract's unbound-IMG paragraph and its verification commands, the symptom index.

Checked on 6062518:
- CI's steps: the host tests, tsan / memory-tsan, the thermal checks, t_perf_order and its tsan build, t_tex, the CPU-only gfx tests, the Python tests (218), the Mac host for Wonder, Hades and Digimon Story Cyber Sleuth, every gfx test compiled, the iOS compile check (133 files) and the unsigned iOS app;
- the gfx run list (52 commands) under Wonder's profile, imga-layout and imga-layout-sanitize, and the contract's commands (t_imga_tbuf among them) under Pokémon Legends: Z-A's profile;
- with SHIN MEGAMI TENSEI V's profile (PR #173 on 6062518 plus this commit): a Mac boot from a new game to the first classroom at 60 fps (frame time p50 16.65 ms), 05fe2caae79b6e53 admitted and no abort;
- reviews: GPT (codex gpt-6-astra) and Opus.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
seedds and claude committed Oct 26, 2026
commit 46b6aa45112b9f568152dce2bf9be42d68f33e8a
21 changes: 18 additions & 3 deletions dm/gfx/nvn/nvn_mtl.m
Original file line number Diff line number Diff line change
Expand Up @@ -5644,7 +5644,7 @@ static void warm_start(void) {
}
// Argument buffer: filled item by item per the B reflection (uniform slot r, separate texture / sampler slot r, storage buffer slot r, driver segments c0 / c2, c1, support_buffer)
// Unbound resources read 0: give all-zero dummy resources (NVN descriptors 0..255 are reserved for the driver; the game binding handle 0 means 'this slot is empty')
static uint64_t g_dummy_img_rid[8][4], g_dummy_tbuf_rid[4];
static uint64_t g_dummy_img_rid[8][4], g_dummy_tbuf_rid[4], g_dummy_img_tbuf_rid[4];
static id<MTLTexture> dummy_tex(int dtt, int dpf) {
static __strong id<MTLTexture> cache[8][4];
MTLTextureType tt = (MTLTextureType)dtt;
Expand All @@ -5668,6 +5668,17 @@ static void warm_start(void) {
d.width = d.height = d.depth = 1; d.storageMode = MTLStorageModePrivate; d.usage = MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite;
t = [g_dev newTextureWithDescriptor:d]; cache[dtt & 7][dpf & 3] = t; g_dummy_img_rid[dtt & 7][dpf & 3] = t.gpuResourceID._impl; res_add(t); return t;
}
// The same for an unbound buffer image (texture_buffer; dummy_img's cache cannot hold it, type 9 falls on 1D's index): one texel on a buffer of its own, not dummy_buf, which reads 0
static id<MTLTexture> dummy_img_tbuf(int dpf) {
static __strong id<MTLTexture> cache[4];
id<MTLTexture> t = cache[dpf & 3]; if (t) return t;
MTLPixelFormat pf = dpf == NVN_DPF_UINT ? MTLPixelFormatRGBA32Uint : dpf == NVN_DPF_SINT ? MTLPixelFormatRGBA32Sint : MTLPixelFormatRGBA32Float;
NSUInteger al = [g_dev minimumLinearTextureAlignmentForPixelFormat:pf], row = (16 + al - 1) / al * al; // one 16-byte texel, its row aligned as for any buffer texture
id<MTLBuffer> b = [g_dev newBufferWithLength:row options:MTLResourceStorageModePrivate]; res_add(b);
MTLTextureDescriptor *d = [MTLTextureDescriptor textureBufferDescriptorWithPixelFormat:pf width:1 resourceOptions:b.resourceOptions usage:MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite];
t = [b newTextureWithDescriptor:d offset:0 bytesPerRow:row];
cache[dpf & 3] = t; g_dummy_img_tbuf_rid[dpf & 3] = t.gpuResourceID._impl; res_add(t); return t;
}
static id<MTLBuffer> dummy_buf(void);
static id<MTLTexture> dummy_tbuf(int dpf) { // Unbound typed buffer: all zeros (pixel class matches the shader's texture_buffer<T>)
static __strong id<MTLTexture> cache[4];
Expand All @@ -5685,6 +5696,9 @@ static void warm_start(void) {
static uint64_t dummy_samp_rid(void) { static uint64_t rid; if (!rid) rid = dummy_samp().gpuResourceID._impl; return rid; }
static id<MTLBuffer> dummy_buf(void) { static id<MTLBuffer> b; if (!b) { b = [g_dev newBufferWithLength:64 << 10 options:MTLResourceStorageModeShared]; res_add(b); } return b; }
static uint64_t dummy_buf_gpu(void) { static uint64_t gpu; if (!gpu) gpu = dummy_buf().gpuAddress; return gpu; }
// The atomics of an unbound image: a scratch of their own. dummy_buf would do for the capacity, but unbound buffers read it as 0, and the IR guard lets the atomics through to the
// dummy image's one texel (its first word)
static id<MTLBuffer> dummy_atom_buf(void) { static id<MTLBuffer> b; if (!b) { b = [g_dev newBufferWithLength:256 options:MTLResourceStorageModePrivate]; res_add(b); } return b; }
// Image atomics on block-linear images retain discard scratch at least as large as the matched IMG extent; linear images require proven direct backing below. SPIRV-Cross indexes
// the IMGA pointer using that image's dimensions (including the array layer), so a full image paired with a 64 KB dummy can run past its end into whatever GPU memory followed:
// Pokémon Legends: Z-A's atomic max into an r32ui 2D array (texture ID 302, fragment shader 2bd5037003980716) wrote into zero-copy pools over the game's heap, which broke pointers in the game's
Expand Down Expand Up @@ -5717,7 +5731,8 @@ static void warm_start(void) {
if (v) { t = v; *rid = r2; } else if (swz_only) t = nil;
}
*real = t != nil;
if (!t) { t = dummy_img(b->dtt, b->dpf); *rid = g_dummy_img_rid[b->dtt & 7][b->dpf & 3]; }
if (!t && b->dtt == (uint8_t)MTLTextureTypeTextureBuffer) { t = dummy_img_tbuf(b->dpf); *rid = g_dummy_img_tbuf_rid[b->dpf & 3]; }
else if (!t) { t = dummy_img(b->dtt, b->dpf); *rid = g_dummy_img_rid[b->dtt & 7][b->dpf & 3]; }
return t;
}
static int imga_extent(id<MTLTexture> t, const nvn_rbind *b, uint64_t *bytes) {
Expand Down Expand Up @@ -5926,7 +5941,7 @@ static int encode_args_(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, i
if (!storage || !gpu || !nvn_imga_capacity(need, storage.length, 0))
MDIE("[RED] image atomics: scratch allocation or capacity failed; refusing short dummy (shader %s stage %d slot %d texture %d need %llu)", sh->key, nvn_stage, reg, tid, (unsigned long long)need);
} else {
storage = dummy_buf(); gpu = storage.gpuAddress;
storage = dummy_atom_buf(); gpu = storage.gpuAddress;
if (atomic_real[reg] || !storage || !gpu || !nvn_imga_capacity(need, storage.length, 0))
MDIE("[RED] image atomics: unmatched unbound IMG/IMGA pair (shader %s stage %d slot %d)", sh->key, nvn_stage, reg);
}
Expand Down
2 changes: 2 additions & 0 deletions dm/gfx/nvn/nvn_refl.m
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ int nvn_refl_from_json(NSDictionary *j, nvn_refl *o, char *err, int errlen) {
if (r->kind == NVN_RB_TEXA) dummy_kind(el, &r->dtt, &r->dpf);
}
else if ([k isEqualToString:@"img"]) { r->kind = NVN_RB_IMG; dummy_kind(b[@"msl_type"], &r->dtt, &r->dpf); // rw: the shader writes it (access::write / read_write; a load-only view of the slot is not)
// a buffer image is declared as one (as TEXD): image atomics admit a bound image only of the declared type (imga_extent), and an unbound one gets a buffer dummy (img_binding)
if ([ty isKindOfClass:[NSString class]] && [ty hasPrefix:@"texture_buffer"]) r->dtt = (uint8_t)MTLTextureTypeTextureBuffer;
r->rw = [ty isKindOfClass:[NSString class]] && ([ty containsString:@"access::write"] || [ty containsString:@"access::read_write"]); }
else if ([k isEqualToString:@"tbuf"]) { r->kind = NVN_RB_TBUF; uint8_t tt; dummy_kind(b[@"msl_type"], &tt, &r->dpf); }
else if ([k isEqualToString:@"sbuf"]) { r->kind = NVN_RB_SBUFP; r->rw = sbuf_rw(b); }
Expand Down
2 changes: 2 additions & 0 deletions dm/gfx/tests/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ t_linear_readback
t_linear_readback.dSYM/
t_copy_alias
t_copy_alias.dSYM/
t_imga_tbuf
t_imga_tbuf.dSYM/
t_pso_pending
t_pso_pending.dSYM/
t_integer_blend
Expand Down
6 changes: 6 additions & 0 deletions dm/gfx/tests/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,12 @@ check_t_copy_alias: t_copy_alias
DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_copy_alias
DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_copy_alias
run: check_t_copy_alias
t_imga_tbuf: t_imga_tbuf.m $(MTL_T_DEP)
clang $(CFLAGS) -fobjc-arc -o $@ t_imga_tbuf.m ../../host/crash.c ../../host/hle_bigstack.c t_host_stubs.c $(filter-out ../nvn/nvn_mtl.m,$(GFX)) $(FW)
.PHONY: check_t_imga_tbuf
check_t_imga_tbuf: t_imga_tbuf
MTL_DEBUG_LAYER=1 ./t_imga_tbuf
run: check_t_imga_tbuf
.PHONY: check_t_linear_readback
check_t_linear_readback: t_linear_readback
MTL_DEBUG_LAYER=1 ./t_linear_readback
Expand Down
52 changes: 52 additions & 0 deletions dm/gfx/tests/t_imga_tbuf.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Image atomics on a buffer image (SHIN MEGAMI TENSEI V's compute shaders; Unreal's cp_i_cb2_4C_r32ui_atomic): the image is declared as a buffer (nvn_refl.m, a texture_buffer
// img binding), so the admission (imga_extent) takes a bound buffer texture, and an unbound one gets a writable buffer dummy (img_binding) whose extent the unbound atomics' own scratch holds
#define nvn_game_fps nvn_game_fps_mtl_default
#include "../nvn/nvn_mtl.m"
#undef nvn_game_fps
#define g_ft g_ft_hle
#include "../nvn/hle_nvn.c"
#undef g_ft
uint64_t g_t0_ns;
void *front_metal_layer(void) { return NULL; }
module_t *module_of(const void *p) { (void)p; return NULL; }
module_t g_mod[MAX_MOD]; int g_nmod;
void svc_thread_dump(void) {}
uint64_t now_ns(void) { return bp_now(); }
static int checks, failed;
#define CHECK(c, label) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s\n", label); } } while (0)

int main(void) { @autoreleasepool {
mtl_init();
nvn_refl r = {0}; char err[256] = "";
NSDictionary *j = @{@"route": @"B", @"bindings": @[
@{@"kind": @"img", @"reg": @2, @"arg_id": @0, @"msl_name": @"cp_i_cb2_4C_r32ui", @"msl_type": @"texture_buffer<uint, access::read_write>"},
@{@"kind": @"img", @"reg": @2, @"arg_id": @1, @"msl_name": @"cp_i_cb2_4C_r32ui_atomic", @"msl_type": @"device atomic_uint*"},
@{@"kind": @"img", @"reg": @3, @"arg_id": @2, @"msl_name": @"cp_i_cb3_4C_r32ui", @"msl_type": @"texture2d<uint, access::read_write>"},
@{@"kind": @"img", @"reg": @3, @"arg_id": @3, @"msl_name": @"cp_i_cb3_4C_r32ui_atomic", @"msl_type": @"device atomic_uint*"}]};
CHECK(!nvn_refl_from_json(j, &r, err, sizeof err), "reflection converts");
CHECK(r.nb == 4 && r.b[0].kind == NVN_RB_IMG && r.b[1].kind == NVN_RB_IMGA && r.b[2].kind == NVN_RB_IMG && r.b[3].kind == NVN_RB_IMGA, "two image + atomics pairs");
CHECK(r.b[0].dtt == (uint8_t)MTLTextureTypeTextureBuffer && r.b[0].dpf == NVN_DPF_UINT && r.b[0].rw, "a buffer image is declared as a writable uint buffer");
CHECK(r.b[2].dtt == (uint8_t)MTLTextureType2D, "a 2D image is still declared as 2D");

// A bound R32Uint buffer texture of 256 texels: admitted against the buffer image, with its whole extent; refused against the 2D one
id<MTLBuffer> mb = [g_dev newBufferWithLength:256 * 4 options:MTLResourceStorageModeShared];
MTLTextureDescriptor *d = [MTLTextureDescriptor textureBufferDescriptorWithPixelFormat:MTLPixelFormatR32Uint width:256 resourceOptions:mb.resourceOptions
usage:MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite];
id<MTLTexture> bt = [mb newTextureWithDescriptor:d offset:0 bytesPerRow:256 * 4];
uint64_t need = 0;
CHECK(bt && imga_extent(bt, &r.b[0], &need) && need == 256 * 4, "a bound buffer texture is admitted with its 1,024 bytes");
CHECK(!imga_extent(bt, &r.b[2], &need), "and refused against a 2D image");

// Unbound: a writable buffer dummy (not dummy_img's 1D one, whose cache index the buffer type falls on), admitted at one texel, which the unbound storage holds
os_unfair_lock_lock(&g_rmu);
uint64_t rid = 0, rid2 = 0; int real = 1, real2 = 1;
id<MTLTexture> t = img_binding(0, &r.b[0], &rid, &real), t2 = img_binding(0, &r.b[2], &rid2, &real2);
id<MTLTexture> one = dummy_img(MTLTextureType1D, NVN_DPF_UINT);
os_unfair_lock_unlock(&g_rmu);
CHECK(t && !real && t.textureType == MTLTextureTypeTextureBuffer && (t.usage & MTLTextureUsageShaderWrite) && rid == t.gpuResourceID._impl, "an unbound buffer image gets a writable buffer dummy");
CHECK(imga_extent(t, &r.b[0], &need) && need == 4 && nvn_imga_capacity(need, dummy_atom_buf().length, 0), "admitted at 4 bytes, which the unbound atomics' scratch holds");
CHECK(dummy_atom_buf() != dummy_buf() && dummy_atom_buf().gpuAddress, "unbound atomics have a scratch of their own, not the buffer unbound buffers read as 0");
CHECK(t2 && !real2 && t2.textureType == MTLTextureType2D && rid2 == t2.gpuResourceID._impl && imga_extent(t2, &r.b[2], &need) && need == 4, "an unbound 2D image still gets a 2D dummy");
CHECK(one && one.textureType == MTLTextureType1D && one != t, "the 1D dummy is unchanged");
printf("t_imga_tbuf: %d checks, %d failed\n", checks, failed); return failed != 0;
} }
5 changes: 5 additions & 0 deletions dm/gfx/tests/test_imga_binding_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ def test_direct_path_checks_actual_backing(self):
self.assertNotIn('atom_scratch', branch)
self.assertNotIn('dummy_buf', branch)

def test_unbound_atomics_do_not_write_the_zero_buffer(self):
branch = SOURCE.split('unmatched unbound IMG/IMGA pair', 1)[0].rsplit('} else {', 1)[1]
self.assertIn('storage = dummy_atom_buf();', branch)
self.assertNotIn('dummy_buf()', branch)

def test_rejection_precedes_argument_publication(self):
body = SOURCE.split('static int encode_args_(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, int metal_vertex) {', 1)[1]
self.assertLess(body.index('refusing short dummy'), body.index('memcpy((uint8_t *)ab.contents'))
Expand Down
1 change: 1 addition & 0 deletions docs/agents/symptoms.md
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- `[RED] shader … reflection conversion failed: 66 bindings, over the limit 64`, then `failed to load`, and the draws with it are dropped (a black map). → [More than 64 bindings in one shader](../reference/shaders.md#more-than-64-bindings-in-one-shader)
- the replay put a texture resource ID where the shader wanted an address; with the old 64 KB dummy buffer, pointers in the game's objects and in the host's program objects got their upper 4 bytes replaced and the game or the replay crashed, or `kIOGPUCommandBufferCallbackErrorPageFault`, after which macOS ignores the process's command buffers (GitHub issue #101). → [Image atomics](../reference/shaders.md#image-atomics)
- Metal shader validation reports invalid image-atomic stores even with an image-sized scratch buffer; without validation, GPU page faults can freeze rendering. → [Bounded MSL 2.3 atomic emulation](../reference/shaders.md#bounded-msl-23-atomic-emulation)
- `FATAL [RED] image atomics: unsupported or overflowing IMG extent` at the first dispatch of a shader whose atomics go to a buffer image (a `texture_buffer` IMG with its `device atomic_uint*` IMGA), with the image bound to a buffer texture (`target 10` in the `image atomics on image slot` line). → [Buffer images declared as buffers for image atomics](../reference/shaders.md#buffer-images-declared-as-buffers-for-image-atomics)
- shaders missing from the map that no game file holds. → [Built-in shaders compiled with the game's own GLSLC](../reference/shaders.md#built-in-shaders-compiled-with-the-games-own-glslc)
- a null read at `main+0x3316dc` in `nnMain`, right after the window setup (the program object's interface pointers at +0xd0 / +0xd8 both null). → [GLSLC GPU code version against the driver's range](../reference/shaders.md#glslc-gpu-code-version-against-the-drivers-range)
- a truncated `.mtl4a` reaches `MTL4ArchiveImpl::loadFromURL`; the bundle reports coverage with `0 of 0 probed bases found`; rebuilt shader libraries reuse an archive of their old binaries; or packing fails with `pso_offline: no base to build` when every eligible pair has function constants. → [Offline pipeline archive reuse and fallback](../reference/shaders.md#offline-pipeline-archive-reuse-and-fallback)
Expand Down
9 changes: 8 additions & 1 deletion docs/image-atomic-binding-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ resource lifetime.
arithmetic and actual IMG dimensions ensure the existing request covers the
matched image; no request is enlarged to conceal a mismatch.
- An unbound IMG may retain the existing dummy pointer only if its actual dummy
extent fits and neither side resolves to a real image.
extent fits and neither side resolves to a real image. The placeholder has the
declared type (a buffer image's is a one-texel buffer texture), and the unbound
IMGA points at an atomic scratch of its own, not at the zero buffer unbound
buffers read.

## Fail-closed limits

Expand Down Expand Up @@ -67,8 +70,12 @@ layout mismatch, or residency caused an earlier GPU fault.
make -C dm/gfx/tests GAME=0100F43008C44000 imga-layout
ASAN_OPTIONS=detect_leaks=0 make -C dm/gfx/tests GAME=0100F43008C44000 imga-layout-sanitize
python3 dm/gfx/tests/test_imga_binding_source.py
make -C dm/gfx/tests GAME=0100F43008C44000 check_t_imga_tbuf
```

`t_imga_tbuf` runs on Metal: a buffer image's declared type, the admission of a
bound buffer texture, and an unbound buffer image's placeholder and scratch.

The portable fixture executes production checked arithmetic/admission helpers:
3 MiB versus 64 KiB capacity, valid packed layouts, overflow, zero dimensions,
short storage, wrong buffer/offset, view rejection, padding and direct arrays.
Expand Down
8 changes: 8 additions & 0 deletions docs/reference/shaders.md
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,14 @@ Cross/helper lowering and the optional Metal checks. Shader acceptance does not
imply admission of every native host layout. None of these tests executes a
shader on a GPU.

### Buffer images declared as buffers for image atomics

- **Symptom:** `FATAL [RED] image atomics: unsupported or overflowing IMG extent` at the first dispatch of a shader whose atomics go to a buffer image (a `texture_buffer` IMG with its `device atomic_uint*` IMGA), with the image bound to a buffer texture (`target 10` in the `image atomics on image slot` line).
- **Cause:** the host's reflection (`nvn_refl.m`) gives each IMG binding the type of its placeholder from its MSL type, and that table has no buffer type, so a `texture_buffer` IMG was declared 2D. The image-atomic admission (`imga_extent`, [contract](../image-atomic-binding-contract.md)) takes a bound image only of the declared type, so every real buffer image failed it. An unbound one got a 2D placeholder, and its atomics went to the shared zero buffer (`dummy_buf`) that unbound buffers read.
- **Fix:** a `texture_buffer` IMG is declared a buffer, as a sampled `texture_buffer` (TEXD) already was. An unbound one gets a one-texel buffer texture of its own (`dummy_img_tbuf`, its row aligned as Metal requires for the format), and an unbound IMGA a scratch of its own (`dummy_atom_buf`), so atomics through an unbound slot no longer write the buffer unbound buffers read as zeros.
- **Check:** `make -C dm/gfx/tests GAME=<id> check_t_imga_tbuf` (on Metal, with the API validation layer: the declared type, a bound buffer texture admitted, the unbound placeholder and scratch); `test_imga_binding_source.py`.
- **Found on:** SHIN MEGAMI TENSEI Ⅴ, whose profile is in [PR #173](https://github.com/seedds/nxnative/pull/173): Unreal's compute shader `05fe2caae79b6e53` (an atomic on a 448,800-byte buffer image) stopped the Mac host about 60 s into a new game once the admission came in (PR #178). With the fix the game runs to its first classroom at 60 fps.

## Shaders compiled at run time

### Built-in shaders compiled with the game's own GLSLC
Expand Down