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
17 changes: 14 additions & 3 deletions dm/gfx/nvn/nvn_mtl.m
Original file line number Diff line number Diff line change
Expand Up @@ -3245,6 +3245,8 @@ static void rb_swap_rows(uint8_t *p, size_t wb, size_t rows, size_t nz, size_t r
// nil elsewhere (or if it is refused: the caller looks the address up as usual). The GPU only reads it, so it is made over the pages the upload has just protected, not through pool_buf,
// which would make them writable again and the texture count as written at once
static uint64_t g_up_src_made; // source buffers made (t_upload_src)
static uint64_t g_up_src_stale; // uploads whose source buffer went with a flushed batch and could not be made again (pkg_upload_)
static int t_up_src_refuse; // tests: refuse the source buffer of the batch that follows a flush (t_upload_src)
static id<MTLBuffer> up_big_src(uint64_t addr, uint64_t len, uint64_t *off) {
// Not once the raw memory table holds the whole pool (big_full): the lookup finds that buffer. Ocarina of Time's first scene made 4,664 of these in one batch, 2.1 GB counted against the working set for pages already wired
pthread_mutex_lock(&g_mu); int k = big_of(addr), in = k >= 0 && !g_big[k].full;
Expand Down Expand Up @@ -3346,8 +3348,16 @@ static void rb_swap_rows(uint8_t *p, size_t wb, size_t rows, size_t nz, size_t r
id<MTLBuffer> stg = up_alloc(total ? total : 16, &stg_off);
// up_alloc may have flushed the batch that held the first source buffer: only then the new batch needs one of its own. Made for every texture, each staged upload from a large pool
// put its storage twice into the residency set (Switch Sports Resort's first court frame: 855 textures, 1.8 GB of source buffers for 908 MB of storage; t_upload_src)
if (upsrc && g_up_seq != src_batch) { uint64_t mo2; id<MTLBuffer> u2 = up_big_src((uint64_t)t->mem, t->L.size, &mo2); if (u2) { upsrc = u2; mb = (__bridge void *)u2; mo = mo2; } }
size_t off = 0; int enc_ok = g_up_ce != nil, nb0 = g_nup_blits;
// The first buffer is then the flushed batch's, whose completion takes it out of the residency set and releases it (up_flush's handler), so this batch's deswizzle must not
// read it. When the new batch's buffer is refused (the pool became resident or had an address given out meanwhile, or Metal made none) the storage is looked up as for any
// other pool; with no buffer there either, the texture is read on the CPU below. Returning nil instead would leave it unmade with its pages already counted as seen
int src_ok = 1;
if (upsrc && g_up_seq != src_batch) {
uint64_t mo2; id<MTLBuffer> u2 = t_up_src_refuse ? nil : up_big_src((uint64_t)t->mem, t->L.size, &mo2);
if (u2) { upsrc = u2; mb = (__bridge void *)u2; mo = mo2; }
else { upsrc = nil; g_up_src_stale++; t_tex_upload_lookup = 1; src_ok = mtl_addr((uint64_t)t->mem, t->L.size, &mb, &mo); t_tex_upload_lookup = 0; }
}
size_t off = 0; int enc_ok = src_ok && g_up_ce != nil, nb0 = g_nup_blits;
for (unsigned l = 0; enc_ok && l < d.mipmapLevelCount; l++) {
uint32_t w = MAX(t->d.width >> l, 1u), h = MAX(t->d.height >> l, 1u), z = t->d.target == 2 ? MAX(t->d.depth >> l, 1u) : 1;
size_t pitch = (size_t)((w + bw - 1) / bw) * bpb, rows = (h + bh - 1) / bh;
Expand All @@ -3367,7 +3377,8 @@ static void rb_swap_rows(uint8_t *p, size_t wb, size_t rows, size_t nz, size_t r
}
g_nup_blits = nb0; // Roll back the copies already recorded for this texture: the already-encoded deswizzle only writes the staging area and is harmless; this texture takes the CPU path below instead
if (!g_cb) up_flush();
RED_ONCE(41, "GPU deswizzle does not support format %#x target %d; falling back to the CPU", t->d.format, t->d.target);
if (src_ok) RED_ONCE(41, "GPU deswizzle does not support format %#x target %d; falling back to the CPU", t->d.format, t->d.target);
else { static int said; if (!said++) MLOG("an upload's source buffer went with a flushed batch and its storage has no buffer now: ser=%llu is read on the CPU", (unsigned long long)t->serial); }
}

// A sparse pool's texture is read through a copy gathered from its page table, unmapped pages as 0 (a mip tail at a 4 KB offset has no host alias; reading the alias stopped the host with SIGBUS)
Expand Down
18 changes: 17 additions & 1 deletion dm/gfx/tests/t_upload_src.m
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Uploads from a large pool (BIG_MIN) read their storage through a zero-copy buffer of the upload batch (up_big_src), which the batch makes resident and retires. One texture
// needs one such buffer: a second is made only when taking its staging flushed the batch that held the first. Before, every staged upload made two, and a scene load of Switch
// Sports Resort (855 textures, 908 MB) added twice its storage to the residency set. Checks the count and every texel, for small textures in one batch and for 64 MB ones whose
// staging splits the batches (UP_BATCH_BYTES)
// staging splits the batches (UP_BATCH_BYTES).
// Then the same split with the second buffer refused (t_up_src_refuse): the first buffer is the flushed batch's, which takes it out of the residency set and releases it when it
// completes, so the new batch must not read it. The upload looks its storage up as for any other pool, or reads it on the CPU, and every texel is still right
#include "../nvn/nvn_mtl.m"
void *front_metal_layer(void) { return NULL; }
module_t *module_of(const void *p) { (void)p; return NULL; }
Expand Down Expand Up @@ -34,7 +36,7 @@
unsigned w = u->t.d.width, h = u->t.d.height;
id<MTLBuffer> rb = [g_dev newBufferWithLength:u->bytes options:MTLResourceStorageModeShared];
id<MTLCommandBuffer> cb = q_cb(); id<MTLBlitCommandEncoder> ce = [cb blitCommandEncoder];
[ce copyFromTexture:tex sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0) sourceSize:MTLSizeMake(w, h, 1) toBuffer:rb destinationOffset:0 destinationBytesPerRow:w * 4 destinationBytesPerImage:u->bytes];

Check failure on line 39 in dm/gfx/tests/t_upload_src.m

View workflow job for this annotation

GitHub Actions / clang-tidy (ratchet)

Nullable pointer is passed to a callee that requires a non-null 6th parameter [clang-analyzer-nullability.NullablePassedToNonnull] (1 in this file, the baseline has 0)
[ce endEncoding]; [cb commit]; [cb waitUntilCompleted];
return cb.status == MTLCommandBufferStatusCompleted && !memcmp(rb.contents, u->ref, u->bytes);
}
Expand Down Expand Up @@ -72,6 +74,20 @@
CHECK("staging splits the batches", batches >= 2);
CHECK("a second source buffer only for a texture whose staging flushed its batch", made == 3 + (batches - 1));

// The batch split again, with the new batch's source buffer refused: the texture whose staging flushed the batch keeps no buffer of the flushed batch
upl again[3];
for (int i = 0; i < 3; i++) make(&again[i], mem, &pool, (size_t)(240 + 72 * i) << 20, 4096, 4096, 200 + i);
uint64_t stale0 = g_up_src_stale;
t_up_src_refuse = 1;
upload_all(again, 3, &made, &batches);
t_up_src_refuse = 0;
uint64_t stale = g_up_src_stale - stale0;
printf("refused: %llu source buffers for 3 textures, %u batches, %llu uploads without the flushed batch's buffer\n", (unsigned long long)made, batches, (unsigned long long)stale);
CHECK("staging splits the batches with the second buffer refused", batches >= 2);
CHECK("a refused second buffer is not made", made == 3);
CHECK("each upload whose batch was flushed gives up the flushed batch's buffer", stale == batches - 1);
for (int i = 0; i < 3; i++) { mtl_tex_release(&again[i].t); free(again[i].ref); }

for (int i = 0; i < 8; i++) { mtl_tex_release(&small[i].t); free(small[i].ref); }
for (int i = 0; i < 3; i++) { mtl_tex_release(&big[i].t); free(big[i].ref); }
mtl_drain(); mtl_alias_drop_pool(&pool); nvn_dirty_remove_range(mem); mtl_pool_del(mem); mtl_drain(); munmap(mem, POOL_SIZE);
Expand Down
1 change: 1 addition & 0 deletions docs/agents/symptoms.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- in an area load GPU allocated jumps by 6-10 GB between two stats windows (Ocarina of Time: 3.3 GB at frame 900, 15.8 GB at frame 1200 on a 16 GB M5, issue #2068; 3.5 to 13.7 GB inside the load on an M5 Pro) while the residency set grows by about 4 GB, and stays there. The memory census's "not counted" line is 8 GB, and the pool buffers made sum to twice the pools' size. → [The pool walk's statistics made chunks of a large pool](../reference/memory.md#the-pool-walks-statistics-made-chunks-of-a-large-pool)
- travelling produces a brief multi-GB footprint spike, then memory returns to its earlier level; periodic memory lines can miss the peak. Upload diagnostics show many swapped-out blocks still alive in one batch. → [Upload staging grows within one rendering submission](../reference/memory.md#upload-staging-grows-within-one-rendering-submission)
- the first frame of a scene that draws hundreds of new packaged textures takes a quarter to half a second, nearly all of it in `submit+present` (`[longframe] … texture uploads 855 first …, 908.5 MB`), and the `residency set up to frame` line of that window counts about twice as many shared buffers from `up_big_src` as packaged textures (2,866 and 1,433). → [Two source buffers for each staged upload from a large pool](../reference/memory.md#two-source-buffers-for-each-staged-upload-from-a-large-pool)
- none attributed in a run. By reading: a packaged texture from a large pool, uploaded where its staging did not fit the open upload batch, could have its deswizzle read through a buffer the previous batch had already taken out of the residency set and released (wrong or stale texels, or a GPU error on the upload command buffer, depending on when that batch completed). → [A staged upload kept the flushed batch's source buffer when the new batch's was refused](../reference/memory.md#a-staged-upload-kept-the-flushed-batchs-source-buffer-when-the-new-batchs-was-refused)
- in a frame that makes many new textures (a scene's first), `res_add` on the submit thread takes tens of milliseconds in all, a few milliseconds at a time, though each is a hash-table insert. → [Residency changes waited for another thread's commit](../reference/memory.md#residency-changes-waited-for-another-threads-commit)
- GPU memory grows with repeated `nvnTextureReadTexels` calls on a long-lived game thread, even after each readback completes. → [GPU readback without an autorelease pool](../reference/memory.md#gpu-readback-without-an-autorelease-pool)
- process footprint and Metal allocation grow during stationary gameplay even after readback fences complete; the deferred-release queue and command allocator sizes remain bounded. → [Completion readbacks survive a guest waiter's pool](../reference/memory.md#completion-readbacks-survive-a-guest-waiters-pool)
Expand Down
8 changes: 8 additions & 0 deletions docs/reference/memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,14 @@ The guest address space, heaps, pools, virtual address memory and the allocators
- **Found on:** Nintendo Switch Sports Resort (`04008E001F098000`, no profile yet), the first frame of the court behind the sport menu (855 textures, 908 MB) on an M2 Max, two 75 s runs each from the same save and pipeline state: the residency commits to frame 2,400 went from 678-692 ms to 520-523 ms, the shared buffers added in that window from 2,852-2,858 (3.0 GB) to 1,429-1,437 (1.6 GB), that frame from 263-270 ms to 243-251 ms and the next load's (340 textures, 188 MB) from 155-157 ms to 134-138 ms. Most of what is left of it is the residency set taking the new textures and their staging (about 0.12 ms and 0.05 ms per MB, measured per commit), memory a first use has to allocate.
- **Check:** `make -C dm/gfx/tests GAME=<id> check_t_upload_src`: eight textures in one batch make eight source buffers (sixteen before), and three 64 MB ones whose staging splits the batches make one more for the texture that flushed its batch (six before); every texel is compared with the CPU reference, under Metal validation.

### A staged upload kept the flushed batch's source buffer when the new batch's was refused

- **Symptom:** none attributed in a run. By reading: a packaged texture from a large pool, uploaded where its staging did not fit the open upload batch, could have its deswizzle read through a buffer the previous batch had already taken out of the residency set and released (wrong or stale texels, or a GPU error on the upload command buffer, depending on when that batch completed).
- **Cause:** `pkg_upload_` reads such a texture through a zero-copy buffer of the upload batch (`up_big_src`), which the batch keeps (`g_up_keep`) and whose completion handler removes from the residency set and releases (`up_flush`). Taking the texture's staging (`up_alloc`) can flush that batch. The upload then asks for a buffer of the new batch ([Two source buffers for each staged upload from a large pool](#two-source-buffers-for-each-staged-upload-from-a-large-pool)), but `up_big_src` can refuse: the pool became resident or had an address given out meanwhile, the raw memory table now holds the whole pool, or Metal made no buffer. On a refusal the upload went on with the first buffer, which belongs to the flushed batch: the new batch's deswizzle was encoded against a buffer that batch retires when it completes.
- **Fix:** a refusal after a batch change drops the first buffer and looks the storage up as for any other pool (`mtl_addr`); with no buffer there either, the texture is read on the CPU, as for a format the GPU deswizzle refuses. It does not return nil: the caller has already counted the texture's pages as seen.
- **Found on:** no game. Found by reading `pkg_upload_` and `up_flush` while carrying the entry above to a local branch; the refusal needs the pool's state to change between the two `up_big_src` calls, which no run was shown to do.
- **Check:** `make -C dm/gfx/tests GAME=<id> check_t_upload_src` repeats its batch split with the second buffer refused through a test switch (`t_up_src_refuse`): no second buffer is made, the upload whose staging flushed the batch gives up the first one (`g_up_src_stale`), and every texel still matches the CPU reference under Metal validation. Without the fix that count check fails on every run; the stale read itself depends on when the flushed batch completes and the test does not make it visible.

### Residency changes waited for another thread's commit

- **Symptom:** in a frame that makes many new textures (a scene's first), `res_add` on the submit thread takes tens of milliseconds in all, a few milliseconds at a time, though each is a hash-table insert.
Expand Down
Loading