Skip to content

Commit d24d7c2

Browse files
Cache Metal 4 compute pipelines for Mario Kart World and Z-A
Backport nxnative 30fb213 for the two iOS game profiles. Keep compute captures out of render-only compaction, bound background capture, and preserve the existing shader chain and legacy renderer.
1 parent 845c721 commit d24d7c2

1 file changed

Lines changed: 57 additions & 7 deletions

File tree

‎dm/gfx/nvn/nvn_mtl.m‎

Lines changed: 57 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6187,10 +6187,11 @@ static int arch_compact_allowed(void) {
61876187
// pipeline found in the files. The flush used to hold a lock against every such compile instead, and one compile that did not return (Super Mario Odyssey's alRenderMaterialUber
61886188
// with the front end at -O2: 33.7 minutes until Metal gave up, GitHub issue #294) held the flush, and the flush every compile and draw that came after it. Now such a compile
61896189
// holds back the file of its own period and nothing else
6190-
@interface ArchEpoch : NSObject { @public id<MTL4Compiler> comp; id<MTL4PipelineDataSetSerializer> ser; dispatch_group_t busy; _Atomic int active, n, vd; int compacting; } @end
6190+
@interface ArchEpoch : NSObject { @public id<MTL4Compiler> comp; id<MTL4PipelineDataSetSerializer> ser; dispatch_group_t busy; _Atomic int active, n, vd, cs; int compacting; } @end
61916191
// n, vd: bases captured, those with a vertex layout
61926192
@implementation ArchEpoch @end
61936193
static ArchEpoch *g_ep; static os_unfair_lock g_ep_lock = OS_UNFAIR_LOCK_INIT; // the current period
6194+
static int g_cps_files;
61946195
static int g_arch_cap; // compiles are captured (an archive folder, a serializer): immutable after pso4_init
61956196
static dispatch_group_t g_arch_pending; // periods handed over and not written yet
61966197
static _Atomic uint64_t g_pb_built, g_pb_archived, g_pb_reused, g_pb_spec, g_pb_legacy, g_pb_base_ns;
@@ -6356,10 +6357,12 @@ static void pso4_init(void) {
63566357
for (NSString *n in names.reverseObjectEnumerator) { // newest first
63576358
NSString *p = [g_arch_dir stringByAppendingPathComponent:n]; NSError *ae = nil;
63586359
id<MTL4Archive> a = arch_file_ok(p) ? [g_dev newArchiveWithURL:[NSURL fileURLWithPath:p] error:&ae] : nil;
6360+
int cf = [n hasPrefix:@"c"];
63596361
int pf = [n hasPrefix:@"p"];
6360-
if (a) { [pf ? archp : arch addObject:a]; if (!pf) [runf addObject:p]; bytes += [[NSFileManager.defaultManager attributesOfItemAtPath:p error:nil] fileSize]; }
6362+
if (cf) ++g_cps_files;
6363+
if (a) { [pf ? archp : arch addObject:a]; if (!pf && !cf) [runf addObject:p]; bytes += [[NSFileManager.defaultManager attributesOfItemAtPath:p error:nil] fileSize]; }
63616364
else MLOG("[RED] pipeline archive file %s not usable (%s): its bases are built again", p.UTF8String, ae ? ae.localizedDescription.UTF8String : "not a pipeline archive");
6362-
g_arch_seq = MAX(g_arch_seq, [n substringFromIndex:pf].intValue + 1);
6365+
g_arch_seq = MAX(g_arch_seq, [n substringFromIndex:pf || cf].intValue + 1);
63636366
}
63646367
if (runf.count > PSO_ARCH_COMPACT && arch_compact_allowed()) { g_compact_enabled = 1; g_compact_files = runf; }
63656368
MLOG("pipeline archive %s: %lu files (%lu of bases without a vertex layout), %.1f MB, opened in %.1f ms", g_arch_dir.UTF8String, (unsigned long)(arch.count + archp.count - (g_arch_bundle != nil)),
@@ -6384,7 +6387,7 @@ static void arch_write(ArchEpoch *ep) {
63846387
g_arch_flush_ok = 0;
63856388
[NSFileManager.defaultManager createDirectoryAtPath:g_arch_dir withIntermediateDirectories:YES attributes:nil error:nil];
63866389
uint64_t t0 = bp_now(); NSError *e = nil;
6387-
NSString *path = [g_arch_dir stringByAppendingPathComponent:[NSString stringWithFormat:vd ? @"%05d.mtl4a" : @"p%05d.mtl4a", g_arch_seq++]], *tmp = [path stringByAppendingString:@".tmp"];
6390+
NSString *path = [g_arch_dir stringByAppendingPathComponent:[NSString stringWithFormat:atomic_load(&ep->cs) ? @"c%05d.mtl4a" : vd ? @"%05d.mtl4a" : @"p%05d.mtl4a", g_arch_seq++]], *tmp = [path stringByAppendingString:@".tmp"];
63886391
if (ep->compacting) [arch_compact_stamp() writeToFile:arch_compact_marker() atomically:YES encoding:NSUTF8StringEncoding error:nil];
63896392
BOOL ok = [ep->ser serializeAsArchiveAndFlushToURL:[NSURL fileURLWithPath:tmp] error:&e];
63906393
if (ep->compacting) unlink(arch_compact_marker().fileSystemRepresentation);
@@ -6393,7 +6396,9 @@ static void arch_write(ArchEpoch *ep) {
63936396
if (!ok) { MLOG("[RED] pipeline archive: writing %s failed%s%s", path.UTF8String, e ? ": " : "", e ? e.localizedDescription.UTF8String : ""); unlink(tmp.fileSystemRepresentation); }
63946397
else {
63956398
g_arch_flush_ok = 1;
6396-
MLOG("pipeline archive: %d new pipeline bases written to %s (%.1f MB, %.0f ms)", n, path.lastPathComponent.UTF8String,
6399+
if (atomic_load(&ep->cs))
6400+
MLOG("compute archive: saved %d compute pipelines", atomic_load(&ep->cs));
6401+
MLOG("pipeline archive: %d new pipelines written to %s (%.1f MB, %.0f ms)", n, path.lastPathComponent.UTF8String,
63976402
[[NSFileManager.defaultManager attributesOfItemAtPath:path error:nil] fileSize] / 1048576.0, (bp_now() - t0) / 1e6);
63986403
}
63996404
if (ep->compacting) arch_compact_finish();
@@ -6424,6 +6429,51 @@ static void arch_note_new(void) { // a base was compiled: flush 10 s later (on
64246429
if (!g_arch_q || atomic_exchange(&g_arch_sched, 1)) return;
64256430
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * (int64_t)NSEC_PER_SEC), g_arch_q, ^{ atomic_store(&g_arch_sched, 0); arch_flush(); });
64266431
}
6432+
// nxnative 30fb21363578: reuse compute pipelines across process launches.
6433+
static id<MTLComputePipelineState> game_compute_pipeline(id<MTLFunction> f, NSError **error) {
6434+
const char *title_id = DM_GAME_ID;
6435+
if (strcasecmp(title_id, "0400C3F00006E000") && strcasecmp(title_id, "0100F43008C44000"))
6436+
return [g_dev newComputePipelineStateWithFunction:f error:error];
6437+
pso4_init();
6438+
MTL4FunctionDescriptor *fd = g_comp4 ? fn4_of(f) : nil;
6439+
if (![fd isKindOfClass:MTL4LibraryFunctionDescriptor.class])
6440+
return [g_dev newComputePipelineStateWithFunction:f error:error];
6441+
6442+
MTL4ComputePipelineDescriptor *d = [MTL4ComputePipelineDescriptor new];
6443+
d.computeFunctionDescriptor = fd;
6444+
id<MTLComputePipelineState> ps = [g_arch_bundle newComputePipelineStateWithDescriptor:d error:nil];
6445+
if (!ps) for (id<MTL4Archive> archive in g_arch4)
6446+
if ((ps = [archive newComputePipelineStateWithDescriptor:d error:nil])) break;
6447+
if (ps) {
6448+
static _Atomic unsigned hits;
6449+
if (atomic_fetch_add(&hits, 1) < 4) MLOG("compute archive: reused %s", f.name.UTF8String);
6450+
return ps;
6451+
}
6452+
6453+
ps = [g_dev newComputePipelineStateWithFunction:f error:error];
6454+
// Capture at utility QoS, with one compiler job at a time. Keep the
6455+
// first launch playable and put a ceiling on app-private cache growth.
6456+
static _Atomic unsigned queued;
6457+
if (ps && g_arch_cap && g_cps_files < 24 && atomic_fetch_add(&queued, 1) < 128) {
6458+
static dispatch_queue_t capture;
6459+
static dispatch_once_t once;
6460+
dispatch_once(&once, ^{
6461+
capture = dispatch_queue_create("dm.nvn.game-compute-archive",
6462+
dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0));
6463+
});
6464+
dispatch_async(capture, ^{ @autoreleasepool {
6465+
ArchEpoch *ep = ep_enter();
6466+
if ([ep->comp newComputePipelineStateWithDescriptor:d compilerTaskOptions:nil error:nil]) {
6467+
atomic_fetch_add(&ep->n, 1);
6468+
atomic_fetch_add(&ep->cs, 1);
6469+
atomic_fetch_add(&g_arch_new, 1);
6470+
arch_note_new();
6471+
}
6472+
ep_leave(ep);
6473+
} });
6474+
}
6475+
return ps;
6476+
}
64276477
static void arch_compact_finish(void) { // after the period that holds the recaptured bases is written (arch_write): the old files go once their bases are in the new one
64286478
if (!g_compact_files || !g_compacted) return;
64296479
if (!g_arch_flush_ok) { MLOG("[RED] pipeline archive: compaction left the old files (the flush failed)"); return; }
@@ -7113,7 +7163,7 @@ static void warm_task(WarmTask *t) {
71137163
g_warm_done++; return;
71147164
}
71157165
if (t->kind == 2) {
7116-
NvShader *cs = warm_shader(t->key, 5); NSError *e = nil; id ps = cs ? [g_dev newComputePipelineStateWithFunction:cs->fn error:&e] : nil;
7166+
NvShader *cs = warm_shader(t->key, 5); NSError *e = nil; id ps = cs ? game_compute_pipeline(cs->fn, &e) : nil;
71177167
if (cs && !ps) MLOG("[RED] background compute pipeline creation failed: %s", e.localizedDescription.UTF8String);
71187168
if (ps) { WarmItem *item = [WarmItem new]; item->kind = 2; item->key = t->key; item->shader = cs; item->object = ps; warm_enqueue(item); g_warm_cps++; }
71197169
g_warm_done++; return;
@@ -10613,7 +10663,7 @@ static void dispatch(const p_dispatch *dp) {
1061310663
const void *k = (__bridge const void *)cs;
1061410664
id<MTLComputePipelineState> ps = hm_get_id(&g_cps, &k);
1061510665
if (!ps) {
10616-
NSError *e = nil; uint64_t bt = bp_now(); ps = [g_dev newComputePipelineStateWithFunction:cs->fn error:&e];
10666+
NSError *e = nil; uint64_t bt = bp_now(); ps = game_compute_pipeline(cs->fn, &e);
1061710667
g_bp_pso_n++; g_bp_pso_ns += bp_now() - bt;
1061810668
if (!ps) { MLOG("[RED] failed to create compute pipeline: %s", e.localizedDescription.UTF8String); return; }
1061910669
pso_record("C\t%s\n", cs->key);

0 commit comments

Comments
 (0)