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
Residency changes are queued and committed under a lock of their own,…
… so res_add and res_remove no longer wait for another thread's residency commit

Symptom: in a frame that makes many new textures (a scene's first), res_add on the submit thread took tens of milliseconds in all, a few milliseconds at a time, though each is a hash-table insert. Found on Nintendo Switch Sports Resort (04008E001F098000, Switch 2, v65536), the court's first frame (855 textures, 908 MB).

Cause: res_commit held g_res_mu, the lock every res_add and res_remove takes, for the whole [MTLResidencySet commit]. A commit that adds memory takes about 0.04 ms per MB while the GPU is busy, and the upload batches' completion handlers commit their staging's removal on their own threads, so the submit thread, adding the next textures, waited for those commits.

Fix (nvn_mtl.m): res_add and res_remove only queue the change, holding a reference to its allocation, under g_res_mu; res_commit takes the queue and applies and commits it under g_res_commit_mu, which nothing takes inside g_res_mu. A res_commit returns once every change queued before it is committed, also one another thread's commit took (that commit holds g_res_commit_mu until it is done), and a removed allocation stays alive until the commit that takes it out of the set. defer_idle_commit asks res_pending; mtl_res_stats reads the set's counts under g_res_commit_mu; the present snapshot's queue commit, which held g_res_mu to stay apart from the set's commit, holds g_res_commit_mu. Reference: memory.md, a new entry (Residency changes waited for another thread's commit); symptom index regenerated.

Checked: t_res_commit under Metal validation (200 res_add / res_remove while another thread holds a commit for 100 ms take under a millisecond, and a res_commit then waits for that commit and commits its own changes; a change another thread's commit took is in the set when res_commit returns, 50 racing rounds; a removed buffer stays alive until its removal is committed, then goes), also built with -fsanitize=thread (no warnings), the rest of the graphics tests (Apple M2 Max, macOS 27.2), test_docs. In the game, two 75 s runs each from the same state on the work branch (M2 Max), measured with the staged-upload source buffer fix (a separate PR) already in: the submit thread's res_add calls in the court's first frame 42-56 ms in all (the longest 8.8-10.5 ms) → 1.5-1.7 ms (0.08-0.13 ms), the frame 242-263 → 224-232 ms; the last session played to frame 66,000. Not run: regress.py (every game's residency changes take this path), lint_c.py tidy (no clang-tidy here), iOS.
  • Loading branch information
bymaxmarc committed Nov 11, 2026
commit 9e54ea388e723708153ece02034620fbcbb73646
48 changes: 36 additions & 12 deletions dm/gfx/nvn/nvn_mtl.m
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,12 @@ static inline uint64_t tex_slot_h(const uint64_t *tex, const uint64_t *img, unsi
static uint64_t g_pq_done;
static uint64_t g_pq_read;
static id<MTLResidencySet> g_res;
static int g_res_dirty;
// Residency changes wait in g_res_q (under g_res_mu, each holding its allocation) until a commit applies them to g_res and commits it, under g_res_commit_mu alone. A commit
// takes 10-25 ms when it adds hundreds of MB; while it held g_res_mu, as it did, every res_add and res_remove on any thread waited for it: the upload batches' completion
// handlers commit their staging's removal, and the submit thread's res_add of the textures of Switch Sports Resort's court load spent 20-43 ms of that frame waiting
typedef struct { CFTypeRef o; int add; } res_op;
static res_op *g_res_q; static size_t g_res_qn, g_res_qcap; // under g_res_mu
static pthread_mutex_t g_res_commit_mu = PTHREAD_MUTEX_INITIALIZER; // taken before g_res_mu, never inside it
static id<MTLSharedEvent> g_ev;
static _Atomic uint64_t g_fence; // Highest committed fence value (incremented exclusively by the submit thread)
static _Atomic int g_sub_on; // a submission is open: from mtl_sub_begin until its commit has taken its fence and encoded everything (mtl_pool_del reads it)
Expand Down Expand Up @@ -280,6 +285,10 @@ static void ws_report(uint64_t frame, uint64_t frames) {
#define res_add(r) res_add_at((r), __LINE__)
// Both run on guest threads too (pool_res from mtl_addr, uploads), whose implicit autorelease pools never drain; containsObject: / removeObject: on a weak NSHashTable leave the object
// autoreleased in the calling thread's pool (measured in a standalone test: the object outlived its last strong reference until the thread ended), so each has a pool of its own
static void res_q_put(id<MTLAllocation> r, int add) { // Caller holds g_res_mu
if (g_res_qn == g_res_qcap) { g_res_qcap = g_res_qcap ? 2 * g_res_qcap : 256; g_res_q = realloc_or_die(g_res_q, g_res_qcap * sizeof *g_res_q, "the residency changes"); }
g_res_q[g_res_qn++] = (res_op){CFBridgingRetain(r), add};
}
static void res_add_at(id<MTLAllocation> allocation, int line) { @autoreleasepool {
if (!allocation) return;
// An indirectly addressed placed texture needs its heap resident. The heap owner below removes it only after the last texture/view has gone.
Expand All @@ -288,19 +297,18 @@ static void res_add_at(id<MTLAllocation> allocation, int line) { @autoreleasepoo
if (!g_res_objects) g_res_objects = [NSHashTable weakObjectsHashTable];
if ([g_res_objects containsObject:r]) { pthread_mutex_unlock(&g_res_mu); return; } // already resident (a shared texture resolved again): marking the set dirty would cost a commit that changes nothing
{ int k = 0; while (k < RS_SITES - 1 && g_rs_site[k].line && g_rs_site[k].line != line) k++; g_rs_site[k].line = line; g_rs_site[k].n++; g_rs_site[k].bytes += r.allocatedSize; }
[g_res addAllocation:(id<MTLAllocation>)r];
res_q_put(r, 1);
[g_res_objects addObject:r];
g_res_dirty = 1;
pthread_mutex_unlock(&g_res_mu);
} }
static void res_remove(id<MTLAllocation> r) { @autoreleasepool {
if (!r) return;
if ([(id)r conformsToProtocol:@protocol(MTLResource)] && ((id<MTLResource>)r).heap) return;
pthread_mutex_lock(&g_res_mu);
if (![g_res_objects containsObject:r]) { pthread_mutex_unlock(&g_res_mu); return; }
[g_res removeAllocation:(id<MTLAllocation>)r];
res_q_put(r, 0);
[g_res_objects removeObject:r];
g_res_dirty = 1; g_rs_rm++;
g_rs_rm++;
pthread_mutex_unlock(&g_res_mu);
} }
// Recycled texture memory (GitHub issues #1831, #1823). An engine that keeps its render targets in a GPU-only pool and moves or resizes them with its dynamic resolution names new
Expand Down Expand Up @@ -438,11 +446,25 @@ static void res_check(id r, const char *what, int reg) {
MLOG("[RED] missing residency #%d: %s slot %d %s %p (parent chain %d deep) allocated %lu B storage mode %lu%s", nbad, what, reg, is_tex ? "texture" : "buffer", (__bridge void *)a, hops, (unsigned long)a.allocatedSize, (unsigned long)a.storageMode,
t ? [NSString stringWithFormat:@" format %lu %lux%lu type %lu usage %#lx", (unsigned long)t.pixelFormat, (unsigned long)t.width, (unsigned long)t.height, (unsigned long)t.textureType, (unsigned long)t.usage].UTF8String : ""); }
}
static void res_commit(void) {
// Applies and commits every change made before the call. A change another thread's commit took is in the set when this returns too: that commit holds g_res_commit_mu until it is
// done. Each change holds its allocation until it is committed, so a removed one stays alive until it has left the set
static void res_commit(void) { @autoreleasepool {
pthread_mutex_lock(&g_res_commit_mu);
pthread_mutex_lock(&g_res_mu);
if (g_res_dirty) { uint64_t t0 = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); [g_res commit]; g_res_dirty = 0; g_rs_commits++; g_rs_commit_ns += clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - t0; }
res_op *q = g_res_q; size_t n = g_res_qn; g_res_q = NULL; g_res_qn = g_res_qcap = 0;
pthread_mutex_unlock(&g_res_mu);
}
if (n) {
uint64_t t0 = clock_gettime_nsec_np(CLOCK_UPTIME_RAW);
for (size_t i = 0; i < n; i++) { if (q[i].add) [g_res addAllocation:(__bridge id<MTLAllocation>)q[i].o]; else [g_res removeAllocation:(__bridge id<MTLAllocation>)q[i].o]; }
[g_res commit];
uint64_t dt = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - t0;
pthread_mutex_lock(&g_res_mu); g_rs_commits++; g_rs_commit_ns += dt; pthread_mutex_unlock(&g_res_mu);
}
pthread_mutex_unlock(&g_res_commit_mu);
for (size_t i = 0; i < n; i++) CFRelease(q[i].o);
free(q);
} }
static int res_pending(void) { pthread_mutex_lock(&g_res_mu); int n = g_res_qn != 0; pthread_mutex_unlock(&g_res_mu); return n; }
// What the residency set holds: totals by kind and the largest objects. At the first GPU out-of-memory error (the error names none of them), and for DM_CTL "restop" (hle_hid.c). The set holds
// the game's pools (shared buffers over guest memory), textures, heaps and staging alike
static void res_top(const char *why) { @autoreleasepool {
Expand Down Expand Up @@ -475,12 +497,15 @@ static void res_top_once(NSError *err) {
}
// Since the last call: residency commits (count, time), additions by source line (count, MB; the four largest by bytes) and removals
void mtl_res_stats(char *out, size_t n) {
pthread_mutex_lock(&g_res_commit_mu); // the set's counts, which a commit changes
unsigned long set_n = g_res ? (unsigned long)g_res.allocationCount : 0ul; double set_mb = g_res ? g_res.allocatedSize / 1048576.0 : 0;
pthread_mutex_unlock(&g_res_commit_mu);
pthread_mutex_lock(&g_res_mu);
uint64_t tn = 0, tb = 0; for (int k = 0; k < RS_SITES; k++) { tn += g_rs_site[k].n; tb += g_rs_site[k].bytes; }
size_t o = snprintf(out, n, "commits %llu / %.1f ms, added %llu, %.0f MB (", (unsigned long long)g_rs_commits, g_rs_commit_ns / 1e6, (unsigned long long)tn, tb / 1048576.0);
for (int i = 0; i < 4 && o < n; i++) { int best = -1; for (int k = 0; k < RS_SITES; k++) if (g_rs_site[k].n && (best < 0 || g_rs_site[k].bytes > g_rs_site[best].bytes)) best = k;
if (best < 0) break; o += snprintf(out + o, n - o, "%sline %d: %llu, %.0f MB", i ? ", " : "", g_rs_site[best].line, (unsigned long long)g_rs_site[best].n, g_rs_site[best].bytes / 1048576.0); g_rs_site[best].n = 0; }
if (o < n) snprintf(out + o, n - o, "), removed %llu, %lu allocations in the set (%.0f MB)", (unsigned long long)g_rs_rm, g_res ? (unsigned long)g_res.allocationCount : 0ul, g_res ? g_res.allocatedSize / 1048576.0 : 0.0);
if (o < n) snprintf(out + o, n - o, "), removed %llu, %lu allocations in the set (%.0f MB)", (unsigned long long)g_rs_rm, set_n, set_mb);
memset(g_rs_site, 0, sizeof g_rs_site); g_rs_rm = g_rs_commits = g_rs_commit_ns = 0;
pthread_mutex_unlock(&g_res_mu);
}
Expand Down Expand Up @@ -574,8 +599,7 @@ static void defer_kick(void) {
static void defer_idle_commit(void) {
atomic_thread_fence(memory_order_seq_cst);
if (atomic_load(&g_sub_on)) return;
pthread_mutex_lock(&g_res_mu); int dirty = g_res_dirty; pthread_mutex_unlock(&g_res_mu);
if (dirty) defer_kick();
if (res_pending()) defer_kick();
}

// A profile list of shader keys the host asks the next shader build for (bf_want.tsv, dual_want.tsv): each key appended once to the file the environment names. A shader's key is
Expand Down Expand Up @@ -16837,7 +16861,7 @@ static uint64_t snap_take(const tex_t *t) {
r = rec_own_put(b, RO_NOTE, 0); r->a[0] = (uint64_t)(uintptr_t)&g_snap_cmt; r->a[1] = v;
rec_own_push(b);
} else {
pthread_mutex_lock(&g_res_mu); [g_q4 commit:&cb count:1]; [g_q4 signalEvent:g_snap_ev value:v]; pthread_mutex_unlock(&g_res_mu);
pthread_mutex_lock(&g_res_commit_mu); [g_q4 commit:&cb count:1]; [g_q4 signalEvent:g_snap_ev value:v]; pthread_mutex_unlock(&g_res_commit_mu);
atomic_store(&g_snap_cmt, v);
}
g_snap[k].ev = v;
Expand Down
3 changes: 3 additions & 0 deletions dm/gfx/tests/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,9 @@ check_t_border: t_border
t_view_levels: t_view_levels.m $(MTL_T_DEP)
clang $(CFLAGS) -fobjc-arc -o $@ t_view_levels.m $(MTL_T_SRC) $(FW)
check_t_view_levels: RUN_ENV = MTL_DEBUG_LAYER=1
t_res_commit: t_res_commit.m $(MTL_T_DEP)
clang $(CFLAGS) -fobjc-arc -o $@ t_res_commit.m $(MTL_T_SRC) $(FW)
check_t_res_commit: RUN_ENV = MTL_DEBUG_LAYER=1
t_upload_budget: t_upload_budget.m $(MTL_T_DEP)
clang $(CFLAGS) -fobjc-arc -o $@ t_upload_budget.m $(MTL_T_SRC) $(FW)
check_t_upload_budget: t_upload_budget
Expand Down
72 changes: 72 additions & 0 deletions dm/gfx/tests/t_res_commit.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Residency changes and their commit: res_add / res_remove only queue a change, and res_commit applies and commits what is queued under a lock of its own. A commit that adds
// hundreds of MB takes tens of milliseconds; while it held the lock res_add takes, every res_add on any thread waited for it (Switch Sports Resort's court load: the submit
// thread's res_add waited 20-43 ms in one frame for the upload batches' completion handlers). Checks, with real Metal allocations:
// - a res_add or res_remove while another thread's commit is under way returns at once (it waited for the whole commit before);
// - after res_commit returns, what was added before it is in the set, also when another thread's commit took the change;
// - a removed allocation stays alive until the commit that takes it out of the set, then goes.
#include "../nvn/nvn_mtl.m"
void *front_metal_layer(void) { return NULL; }
module_t *module_of(const void *p) { (void)p; return NULL; }
module_t *g_mod; int g_nmod;
void svc_thread_dump(void) {}
uint64_t now_ns(void) { return bp_now(); }
static int checks, failed;
#define CHECK(label, c) do { checks++; if (!(c)) { failed++; fprintf(stderr, "FAIL: %s\n", label); } } while (0)

enum { BIG_BYTES = 48u << 20 };

static id<MTLBuffer> buf(size_t n) { return [g_dev newBufferWithLength:n options:MTLResourceStorageModePrivate]; }

int main(void) { @autoreleasepool {
mtl_init();
CHECK("a residency set", g_res != nil);

// Added, committed, in the set
id<MTLBuffer> a = buf(1u << 20);
res_add(a); res_commit();
CHECK("an allocation added and committed is in the set", [g_res containsAllocation:a]);

// Removed: alive until its commit, gone after it
__weak id<MTLBuffer> weak_r = nil;
@autoreleasepool { id<MTLBuffer> r = buf(1u << 20); weak_r = r; res_add(r); res_commit(); res_remove(r); }
CHECK("a removed allocation stays alive until its removal is committed", weak_r != nil);
@autoreleasepool { res_commit(); }
CHECK("and goes once it is", weak_r == nil);

// A res_add while another thread's commit is under way: a commit alone takes well under a millisecond here, but tens of milliseconds in a game whose GPU is busy (10-25 ms
// each in Switch Sports Resort's court load), so one is stood in for by holding the commit's lock for 100 ms, as a commit holds it
NSMutableArray *small = [NSMutableArray array];
dispatch_semaphore_t held = dispatch_semaphore_create(0), released = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
pthread_mutex_lock(&g_res_commit_mu); dispatch_semaphore_signal(held); usleep(100000); pthread_mutex_unlock(&g_res_commit_mu); dispatch_semaphore_signal(released);
});
dispatch_semaphore_wait(held, DISPATCH_TIME_FOREVER);
uint64_t worst = 0, t_all = bp_now();
for (int i = 0; i < 200; i++) { id<MTLBuffer> s = buf(4096); [small addObject:s]; uint64_t t0 = bp_now(); res_add(s); res_remove(s); res_add(s); uint64_t d = bp_now() - t0; if (d > worst) worst = d; }

Check failure on line 45 in dm/gfx/tests/t_res_commit.m

View workflow job for this annotation

GitHub Actions / clang-tidy (ratchet)

Nullable pointer is passed to a callee that requires a non-null 1st parameter [clang-analyzer-nullability.NullablePassedToNonnull] (1 in this file, the baseline has 0)
uint64_t adds = bp_now() - t_all;
printf("200 res_add / res_remove while a commit holds its lock: %.2f ms in all, the slowest %.3f ms\n", adds / 1e6, worst / 1e6);
CHECK("res_add and res_remove do not wait for a commit under way", adds < 50000000ull);
uint64_t t_c = bp_now(); res_commit(); uint64_t waited = bp_now() - t_c;
CHECK("res_commit waits for the commit under way, then commits its own changes", waited > 20000000ull && dispatch_semaphore_wait(released, DISPATCH_TIME_NOW) == 0);
int all = 1; for (id<MTLBuffer> s in small) all &= [g_res containsAllocation:s];
CHECK("everything added is in the set after the commit", all);

// A change another thread's commit took is in the set when this thread's res_commit returns
for (int round = 0; round < 50; round++) {
id<MTLBuffer> x = buf(BIG_BYTES / 4), y = buf(4096);
res_add(x);
dispatch_semaphore_t go = dispatch_semaphore_create(0), fin = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ dispatch_semaphore_signal(go); res_commit(); dispatch_semaphore_signal(fin); });
dispatch_semaphore_wait(go, DISPATCH_TIME_FOREVER);
res_add(y); res_commit();
int ok = [g_res containsAllocation:x] && [g_res containsAllocation:y];
dispatch_semaphore_wait(fin, DISPATCH_TIME_FOREVER);
if (!ok) { CHECK("a change committed by another thread is in the set when res_commit returns", 0); break; }
res_remove(x); res_remove(y); res_commit();
}
CHECK("racing commits leave nothing queued", !res_pending());
for (id<MTLBuffer> s in small) res_remove(s);
res_remove(a); res_commit();
printf("t_res_commit: %d checks, %d failed\n", checks, failed);
return failed != 0;
} }
1 change: 1 addition & 0 deletions docs/agents/symptoms.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- out of focus, with the picture still and the sound on, GPU allocated climbs by hundreds of MB a second while the residency set stays flat, and swap follows it. → [Retired pool buffers pile up while a game submits nothing](../reference/memory.md#retired-pool-buffers-pile-up-while-a-game-submits-nothing)
- 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)
- 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)
- `footprint` shows `Malloc Large` about the size of `pso_archive/` (the log's `pipeline archive …: N files, … MB`), resident or swapped for the whole run. `MallocStackLogging=1` with `malloc_history <pid> -allBySize` gives `newArchiveWithURL` → `MTL4ArchiveImpl::loadFromURL` → `LoaderGlobalState::loadFile` → `-[NSData initWithContentsOfFile:options:maxLength:error:]` → malloc. → [A pipeline archive on an external drive is read into memory](../reference/memory.md#a-pipeline-archive-on-an-external-drive-is-read-into-memory)
Expand Down
Loading
Loading