From 3dacbe5b5c52f7d2a59aaafeda1849add9b1c923 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Sun, 22 Nov 2026 17:07:00 +1100 Subject: [PATCH 1/6] d3d11: opt-in parking of burst GetData polls on event queries (MADEIRA_D3D11_QUERY_PARK) Games build a GPU fence out of while (GetData(event) == S_FALSE) {}. Path of Exile 2 does it every frame, up to about 130,000 polls a frame. Under emulation every poll is an x64 -> ARM64EC round trip plus a Metal call, and the polling thread keeps a performance core busy for nothing, which on a phone is heat that throttles the threads doing real work. With MADEIRA_D3D11_QUERY_PARK=1, once the polls of one event query come in a burst (pending polls less than 250 us apart, after 2 of them), GetData parks the caller on the queue's shared event until the query's value is signaled, at most 1 ms (Metal's wait timeout is in milliseconds), and then answers. A one-off poll, such as a query read once a frame after it was issued, never waits. It only parks once the chunk holding the signal has been committed, since no wait could see it complete before that, and it does the flush GetData would do anyway (no DONOTFLUSH) first. This is the same idea as D3D9's WaitCPUFenceBounded parking, on the D3D11 event value. A [query-park] line at the first event query says the switch is on. The [gpu-perf] line gains the parked event polls per frame and the time parked per frame. Off by default. Tested on an iPhone with it on in every session since 4 Nov 2026 (Path of Exile 2 on D3D11 and D3D12, Steam): no hangs or missed signals seen. Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- src/d3d11/d3d11_context_imm.cpp | 54 ++++++++++++++++++++++++++++++++- src/d3d11/d3d11_query.hpp | 33 ++++++++++++++++++++ src/dxmt/dxmt_command_queue.cpp | 9 ++++-- src/dxmt/dxmt_command_queue.hpp | 1 + 4 files changed, 93 insertions(+), 4 deletions(-) diff --git a/src/d3d11/d3d11_context_imm.cpp b/src/d3d11/d3d11_context_imm.cpp index 0635a0d28..9825f680f 100644 --- a/src/d3d11/d3d11_context_imm.cpp +++ b/src/d3d11/d3d11_context_imm.cpp @@ -398,6 +398,9 @@ class MTLD3D11ImmediateContext : public ImmediateContextBase { } else { static_cast(pAsync)->Issue(cmd_queue.GetCurrentEventSeqId()); } + /* MADEIRA: the signal (this one, or the earlier one it reuses) may still be + * in the chunk being recorded; GetData only parks once that chunk is out. */ + static_cast(pAsync)->SetIssueChunk(cmd_queue.CurrentSeqId()); break; } case D3D11_QUERY_OCCLUSION: @@ -420,6 +423,52 @@ class MTLD3D11ImmediateContext : public ImmediateContextBase { } } + /* MADEIRA: games build a GPU fence out of `while (GetData(event) == S_FALSE) {}` + * (Path of Exile 2 does it every frame: up to ~130K polls a frame, millions a + * second). Under emulation every poll is an x64 -> ARM64EC round trip plus a + * Metal call, and the polling thread burns a P-core for nothing, which on a + * phone is heat that throttles the threads doing real work. Once the polls + * of one query come in a burst (two pending polls less than 250 us apart), + * this parks the caller on the queue's shared event until the query's value + * is signaled, at most 1 ms (Metal's timeout is in milliseconds), and then + * answers. A one-off poll (a query read once a frame, a frame or more after + * it was issued) never waits. The park only happens once the chunk holding + * the signal has been committed: before that, no wait can see it complete. + * The flush that GetData would do anyway (no DONOTFLUSH) is done first, so + * the signal is on its way before the caller parks. Same idea as D3D9's + * WaitCPUFenceBounded parking (d3d9_query.cpp), on the D3D11 event value. + * Opt-in: env.MADEIRA_D3D11_QUERY_PARK = 1. */ + static bool + QueryParkEnabled() { + static const bool enabled = [] { + const char *value = std::getenv("MADEIRA_D3D11_QUERY_PARK"); + bool on = value && !std::strcmp(value, "1"); + if (on) + ERR("[query-park] D3D11 event-query parking on (env.MADEIRA_D3D11_QUERY_PARK = 1)"); + return on; + }(); + return enabled; + } + + HRESULT + ParkOnEventQuery(MTLD3D11EventQuery *query, UINT &GetDataFlags) { + if ((GetDataFlags & D3D11_ASYNC_GETDATA_DONOTFLUSH) == 0) { + cmd_queue.CurrentFrameStatistics().event_stall++; + Flush(); + GetDataFlags |= D3D11_ASYNC_GETDATA_DONOTFLUSH; /* done: the tail of GetData must not flush again */ + } + auto now = std::chrono::steady_clock::now(); + uint64_t now_ns = std::chrono::duration_cast(now.time_since_epoch()).count(); + if (!query->NotePendingPoll(now_ns) || cmd_queue.CurrentSeqId() <= query->IssueChunk()) + return S_FALSE; + cmd_queue.event.waitUntilSignaledValue(query->SignalSeqId(), 1); + g_perf.polls_parked.fetch_add(1, std::memory_order_relaxed); + g_perf.park_ns.fetch_add( + std::chrono::duration_cast(std::chrono::steady_clock::now() - now).count(), + std::memory_order_relaxed); + return query->CheckEventState(cmd_queue.SignaledEventSeqId()) == EventState::Signaled ? S_OK : S_FALSE; + } + HRESULT STDMETHODCALLTYPE GetData(ID3D11Asynchronous *pAsync, void *pData, UINT DataSize, UINT GetDataFlags) override { @@ -438,7 +487,8 @@ class MTLD3D11ImmediateContext : public ImmediateContextBase { case D3D11_QUERY_EVENT: case D3D11_QUERY_TIMESTAMP: case D3D11_QUERY_TIMESTAMP_DISJOINT: { - switch (static_cast(pAsync)->CheckEventState(cmd_queue.SignaledEventSeqId())) { + auto query = static_cast(pAsync); + switch (query->CheckEventState(cmd_queue.SignaledEventSeqId())) { case EventState::Pending: break; case EventState::Stall: @@ -450,6 +500,8 @@ class MTLD3D11ImmediateContext : public ImmediateContextBase { case EventState::Invalid: return DXGI_ERROR_INVALID_CALL; } + if (hr == S_FALSE && QueryParkEnabled()) + hr = ParkOnEventQuery(query, GetDataFlags); break; } default: diff --git a/src/d3d11/d3d11_query.hpp b/src/d3d11/d3d11_query.hpp index c7ab42cc2..fb24f3e90 100644 --- a/src/d3d11/d3d11_query.hpp +++ b/src/d3d11/d3d11_query.hpp @@ -121,9 +121,24 @@ enum class EventState { constexpr size_t kEventStallThreshold = 64; +/* MADEIRA: burst polling of an event query. Two pending polls less than this + * apart continue a burst; after kEventPollsBeforePark of them the immediate + * context parks the caller on the queue's shared event (see GetData). */ +constexpr uint64_t kEventPollBurstGapNs = 250 * 1000; +constexpr uint32_t kEventPollsBeforePark = 2; + struct MTLD3D11EventQuery : public ID3D11Query { virtual void Issue(uint64_t current_seq_id) = 0; virtual EventState CheckEventState(uint64_t coherent_seq_id) = 0; + /* The event value this query completes at. */ + virtual uint64_t SignalSeqId() = 0; + /* The command chunk that was being recorded when the query was issued: its + * signal reaches the GPU only once that chunk is committed. */ + virtual void SetIssueChunk(uint64_t chunk_seq_id) = 0; + virtual uint64_t IssueChunk() = 0; + /* Records a pending poll at now_ns; true when it continues a burst long + * enough to park on. */ + virtual bool NotePendingPoll(uint64_t now_ns) = 0; }; template @@ -138,6 +153,21 @@ class MTLD3D11EventQueryImpl : public MTLD3DQueryBase { state = QueryState::Issued; should_be_signaled_at = current_seq_id; stall_counter = 0; + issue_chunk = 0; + poll_burst = 0; + last_pending_poll_ns = 0; + } + + uint64_t SignalSeqId() override { return should_be_signaled_at; } + void SetIssueChunk(uint64_t chunk_seq_id) override { issue_chunk = chunk_seq_id; } + uint64_t IssueChunk() override { return issue_chunk; } + bool NotePendingPoll(uint64_t now_ns) override { + if (last_pending_poll_ns && now_ns - last_pending_poll_ns <= kEventPollBurstGapNs) + poll_burst = std::min(poll_burst + 1, kEventPollsBeforePark + 1); + else + poll_burst = 1; + last_pending_poll_ns = now_ns; + return poll_burst > kEventPollsBeforePark; } EventState CheckEventState(uint64_t coherent_seq_id) override { @@ -162,6 +192,9 @@ class MTLD3D11EventQueryImpl : public MTLD3DQueryBase { QueryState state = QueryState::Undefined; uint32_t stall_counter = 0; uint64_t should_be_signaled_at = 0; + uint64_t issue_chunk = 0; + uint32_t poll_burst = 0; + uint64_t last_pending_poll_ns = 0; }; HRESULT CreateOcculusionQuery(MTLD3D11Device *pDevice, diff --git a/src/dxmt/dxmt_command_queue.cpp b/src/dxmt/dxmt_command_queue.cpp index 210ca6ab9..1329045f6 100644 --- a/src/dxmt/dxmt_command_queue.cpp +++ b/src/dxmt/dxmt_command_queue.cpp @@ -243,21 +243,24 @@ CommandQueue::AccountGpuTime(obj_handle_t cmdbuf, uint64_t frame) { const double waits = take(g_perf.map_waits), wait_ms = take(g_perf.map_wait_ns) / 1e6, unsubmitted = take(g_perf.map_waits_unsubmitted); const double pe = take(g_perf.polls_event), po = take(g_perf.polls_other); + const double parked = take(g_perf.polls_parked), park_ms = take(g_perf.park_ns) / 1e6; const double draws = take(g_perf.draws), tess = take(g_perf.draws_tess), gs = take(g_perf.draws_gs); const double dec_ms = take(g_perf.decode_ns) / 1e6, refill_ms = take(g_perf.refill_ns) / 1e6; const double rw_ms = take(g_perf.refill_worker_ns) / 1e6, rq = take(g_perf.refill_queued), ra = take(g_perf.refill_applied), rs = take(g_perf.refill_stale), ro = take(g_perf.refill_overbudget); - char line[800]; + char line[900]; snprintf(line, sizeof(line), "[gpu-perf] ml1254 %.0f frames in %.0f ms (%.1f fps): GPU busy %.0f ms = %.0f%% (%.1f ms/frame), " "%.1f cmdbufs/frame | readback Map waits %.2f/frame, %.1f ms/frame (%.2f/frame on unsubmitted work) | " "not-ready polls/frame: event %.1f, other %.1f | draws/frame %.0f, tess %.0f, GS %.0f | " "game-thread BC decode %.2f ms/frame (%.0f ms per 64 frames), lost-level refill %.2f ms/frame | " - "async refill: worker %.2f ms/frame, queued %.0f applied %.0f stale %.0f over-budget %.0f", + "async refill: worker %.2f ms/frame, queued %.0f applied %.0f stale %.0f over-budget %.0f | " + "parked event polls/frame %.1f, %.2f ms/frame", frames, wall_ms, wall_ms > 0 ? frames * 1000.0 / wall_ms : 0.0, busy_ms, wall_ms > 0 ? busy_ms * 100.0 / wall_ms : 0.0, busy_ms / frames, perf_.cmdbufs / frames, waits / frames, wait_ms / frames, unsubmitted / frames, pe / frames, po / frames, draws / frames, tess / frames, gs / frames, - dec_ms / frames, dec_ms, refill_ms / frames, rw_ms / frames, rq, ra, rs, ro); + dec_ms / frames, dec_ms, refill_ms / frames, rw_ms / frames, rq, ra, rs, ro, parked / frames, + park_ms / frames); ERR(line); perf_.window_frame = frame; perf_.window_start = perf_.last_end; diff --git a/src/dxmt/dxmt_command_queue.hpp b/src/dxmt/dxmt_command_queue.hpp index 3a0a0bf6e..5a739ff2e 100644 --- a/src/dxmt/dxmt_command_queue.hpp +++ b/src/dxmt/dxmt_command_queue.hpp @@ -99,6 +99,7 @@ constexpr uint32_t kCommandChunkCount = 32; struct PerfCounters { std::atomic map_wait_ns{0}, map_waits{0}, map_waits_unsubmitted{0}; std::atomic polls_event{0}, polls_other{0}; + std::atomic polls_parked{0}, park_ns{0}; /* MADEIRA: D3D11 event-query parking */ std::atomic draws{0}, draws_tess{0}, draws_gs{0}; std::atomic decode_ns{0}, refill_ns{0}; /* BC work on the game thread */ std::atomic refill_worker_ns{0}, refill_queued{0}, refill_applied{0}, refill_stale{0}, From fdbf684bd3a4b22519f57046b11ec908e49e8869 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Sun, 8 Nov 2026 02:27:10 +1100 Subject: [PATCH 2/6] winemetal: opt-in per-encoder GPU timing (gpu-pass-timing) There was no way to see which passes cost GPU time on an iPhone that cannot be attached to Instruments. madeira.cfg gpu-pass-timing = P (seconds, 0 = off, the default) times every Metal encoder for one second in every P with an MTLCounterSampleBuffer per command buffer: vertex and fragment start/end samples for render passes, start/end for compute and blit encoders (through pass descriptors, so the dispatch type is kept). Each encoder's label is kept with its samples. Once per window it logs [gpu-pass]: GPU busy per frame, the union of the encoder intervals (what is left are gaps where no encoder ran: fence waits, scheduling), the overlap between encoders, and the passes ranked by GPU time with their vertex and fragment split, keyed by the encoder label. Every gpu-pass-dump-s seconds (default 30) the next three command buffers are listed encoder by encoder with start offsets ([gpu-pass-dump]). Off, nothing is attached and each encoder costs one relaxed load; remote (wmtr) command buffers are never timed. On an iOS 27 iPhone the timestamps came at 1.0 ns per tick with no missing samples. Labels come from the D3D side (encoder-labels in madeira-d3d12). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Shitiz Garg --- src/winemetal/unix/winemetal_unix.c | 415 +++++++++++++++++++++++++++- 1 file changed, 411 insertions(+), 4 deletions(-) diff --git a/src/winemetal/unix/winemetal_unix.c b/src/winemetal/unix/winemetal_unix.c index 8592f8912..9dffe7634 100644 --- a/src/winemetal/unix/winemetal_unix.c +++ b/src/winemetal/unix/winemetal_unix.c @@ -600,6 +600,365 @@ static void madeira_gpu_meter_attach(id cmdbuf) { }]; } +/* madeira-duo gpu-pass-timing: GPU time per Metal encoder, measured on the device. + * madeira.cfg gpu-pass-timing = P (seconds, 0 = off): for one second in every P, + * every render, compute and blit encoder gets Metal timestamp samples at its stage + * boundaries (render: vertex start/end and fragment start/end; compute and blit: + * encoder start/end) in a per-command-buffer MTLCounterSampleBuffer. When the + * buffer completes, the samples become per-encoder GPU intervals, summed per pass + * (keyed by the encoder label with its sequence number dropped, so set + * encoder-labels = 1 for names) and logged as [gpu-pass] once per window: + * GPU busy per frame, the union of the encoder intervals (what's left are gaps + * where no encoder ran: fence waits, scheduling), the overlap between encoders, + * and the passes ranked by GPU time. Every gpu-pass-dump-s seconds (default 30) + * the next three command buffers are also listed encoder by encoder, in order, + * with start offsets, so gaps and overlaps can be seen in place. Off = nothing + * attached, one relaxed load per encoder. Remote (wmtr) command buffers are not + * timed. */ +#define GPT_STATES 12 +#define GPT_SAMPLES 2048 +#define GPT_MAX_ENC (GPT_SAMPLES / 4) +#define GPT_KEYS 512 +struct gpt_enc { + id encoder; /* only compared, never messaged after endEncoding */ + uint16_t base, nsamp; + uint16_t w, h; + uint8_t kind; /* 0 render, 1 compute, 2 blit */ + char label[56]; +}; +struct gpt_cb { + int busy; + id cb; /* the command buffer while it is being encoded; nil once committed */ + id sb; + unsigned n_enc, n_samp; + struct gpt_enc enc[GPT_MAX_ENC]; +}; +struct gpt_key { + char label[56]; uint8_t kind; uint16_t w, h; + unsigned count; + double span_ns, vtx_ns, frag_ns; +}; +static int g_gpt_period = -1, g_gpt_dump_s = 30; +static _Atomic int g_gpt_open; /* states in use; 0 = endEncoding skips the search */ +static os_unfair_lock g_gpt_lock = OS_UNFAIR_LOCK_INIT; +static struct gpt_cb *g_gpt_state[GPT_STATES]; +static id g_gpt_set; +static int g_gpt_ok = -1; /* -1 unchecked, 0 unsupported, 1 ready */ +static double g_gpt_ns_per_tick; /* 0 until two GPU/CPU clock pairs are taken */ +static uint64_t g_gpt_ref_gpu, g_gpt_ref_ns; +static struct gpt_key g_gpt_keys[GPT_KEYS]; +static unsigned g_gpt_nkeys, g_gpt_dump_left; +static uint64_t g_gpt_win_start, g_gpt_last_dump; +static unsigned g_gpt_cbs, g_gpt_encs, g_gpt_lost, g_gpt_nosamp; +static double g_gpt_busy_ns, g_gpt_union_ns, g_gpt_sum_ns; +static _Atomic unsigned g_gpt_presents; + +static uint64_t gpt_now_ns(void) { return clock_gettime_nsec_np(CLOCK_UPTIME_RAW); } + +static int gpt_period(void) { + if (g_gpt_period < 0) { + g_gpt_dump_s = (int)madeira_cfg_int("gpu-pass-dump-s", 30); + g_gpt_period = (int)madeira_cfg_int("gpu-pass-timing", 0); + if (g_gpt_period < 0) g_gpt_period = 0; + } + return g_gpt_period; +} + +/* Whether a command buffer starting to encode now is timed: inside the first + * second of each period. */ +static int gpt_window(void) { + int p = gpt_period(); + if (!p) return 0; + return (gpt_now_ns() / 1000000000ull) % (uint64_t)p == 0; +} + +static int gpt_device_ready(id dev) { + if (g_gpt_ok >= 0) return g_gpt_ok; + g_gpt_ok = 0; + if (![dev respondsToSelector:@selector(supportsCounterSampling:)] || + ![dev supportsCounterSampling:MTLCounterSamplingPointAtStageBoundary]) { + fprintf(stderr, "[gpu-pass] madeira-duo: this GPU can't sample counters at stage boundaries; gpu-pass-timing stays off\n"); + return 0; + } + for (id s in dev.counterSets) + if ([s.name isEqualToString:MTLCommonCounterSetTimestamp]) { g_gpt_set = [s retain]; break; } + if (!g_gpt_set) { + fprintf(stderr, "[gpu-pass] madeira-duo: no timestamp counter set; gpu-pass-timing stays off\n"); + return 0; + } + g_gpt_ok = 1; + fprintf(stderr, "[gpu-pass] madeira-duo: per-encoder GPU timing on, 1 s in every %d s, %d samples per command buffer\n", + g_gpt_period, GPT_SAMPLES); + return 1; +} + +/* GPU timestamp ticks to nanoseconds: pairs of (GPU timestamp, our clock) taken + * at least a second apart. */ +static void gpt_calibrate(id dev) { + MTLTimestamp cpu = 0, gpu = 0; + uint64_t ns; + [dev sampleTimestamps:&cpu gpuTimestamp:&gpu]; + ns = gpt_now_ns(); + if (!g_gpt_ref_ns) { g_gpt_ref_gpu = gpu; g_gpt_ref_ns = ns; return; } + if (ns - g_gpt_ref_ns < 1000000000ull || gpu <= g_gpt_ref_gpu) return; + { + double r = (double)(ns - g_gpt_ref_ns) / (double)(gpu - g_gpt_ref_gpu); + if (!g_gpt_ns_per_tick) + fprintf(stderr, "[gpu-pass] madeira-duo: GPU timestamps run at %.4f ns per tick\n", r); + g_gpt_ns_per_tick = r; + } + g_gpt_ref_gpu = gpu; g_gpt_ref_ns = ns; +} + +/* The timing state of a command buffer being encoded; a new one when the buffer + * starts encoding inside a window (create). Caller holds g_gpt_lock. */ +static struct gpt_cb *gpt_find_locked(id cb, int create) { + struct gpt_cb *freeslot = NULL; + for (unsigned i = 0; i < GPT_STATES; i++) { + struct gpt_cb *g = g_gpt_state[i]; + if (g && g->busy && g->cb == cb) return g; + } + if (!create) return NULL; + for (unsigned i = 0; i < GPT_STATES && !freeslot; i++) { + if (!g_gpt_state[i]) g_gpt_state[i] = calloc(1, sizeof(struct gpt_cb)); + if (g_gpt_state[i] && !g_gpt_state[i]->busy) freeslot = g_gpt_state[i]; + } + if (!freeslot) { g_gpt_lost++; return NULL; } + if (!freeslot->sb) { + MTLCounterSampleBufferDescriptor *d = [[MTLCounterSampleBufferDescriptor alloc] init]; + NSError *err = nil; + d.counterSet = g_gpt_set; + d.storageMode = MTLStorageModeShared; + d.sampleCount = GPT_SAMPLES; + d.label = @"madeira gpu-pass-timing"; + freeslot->sb = [[(id)cb device] newCounterSampleBufferWithDescriptor:d error:&err]; + [d release]; + if (!freeslot->sb) { + fprintf(stderr, "[gpu-pass] madeira-duo: no counter sample buffer (%s); gpu-pass-timing off\n", + err ? err.localizedDescription.UTF8String : "no error given"); + g_gpt_ok = 0; + return NULL; + } + } + freeslot->busy = 1; freeslot->cb = cb; freeslot->n_enc = 0; freeslot->n_samp = 0; + atomic_fetch_add_explicit(&g_gpt_open, 1, memory_order_relaxed); + return freeslot; +} + +/* Reserve samples for an encoder about to be created on cb: returns the state + * and sets *idx, or NULL when this encoder isn't timed. */ +static struct gpt_cb *gpt_begin(id cb, unsigned kind, unsigned nsamp, unsigned w, unsigned h, unsigned *idx) { + struct gpt_cb *g; + if (!gpt_period() || !cb) return NULL; + if (g_gpt_ok == 0) return NULL; + os_unfair_lock_lock(&g_gpt_lock); + g = gpt_find_locked(cb, 0); + if (!g && gpt_window() && gpt_device_ready([(id)cb device])) { + gpt_calibrate([(id)cb device]); + g = gpt_find_locked(cb, 1); + } + if (g && (g->n_enc >= GPT_MAX_ENC || g->n_samp + nsamp > GPT_SAMPLES)) g = NULL; + if (g) { + struct gpt_enc *e = &g->enc[g->n_enc]; + e->encoder = nil; e->base = (uint16_t)g->n_samp; e->nsamp = (uint16_t)nsamp; + e->w = (uint16_t)(w > 65535 ? 65535 : w); e->h = (uint16_t)(h > 65535 ? 65535 : h); + e->kind = (uint8_t)kind; e->label[0] = 0; + *idx = g->n_enc++; g->n_samp += nsamp; + } + os_unfair_lock_unlock(&g_gpt_lock); + return g; +} + +static void gpt_created(struct gpt_cb *g, unsigned idx, id encoder) { + if (!g) return; + os_unfair_lock_lock(&g_gpt_lock); + if (encoder) g->enc[idx].encoder = encoder; + else g->enc[idx].nsamp = 0; /* the encoder wasn't created: nothing to read */ + os_unfair_lock_unlock(&g_gpt_lock); +} + +/* At endEncoding: keep the encoder's label (set right after it was created). */ +static void gpt_end(id encoder) { + if (!atomic_load_explicit(&g_gpt_open, memory_order_relaxed)) return; + os_unfair_lock_lock(&g_gpt_lock); + for (unsigned i = 0; i < GPT_STATES; i++) { + struct gpt_cb *g = g_gpt_state[i]; + if (!g || !g->busy || !g->cb || !g->n_enc) continue; + for (unsigned k = g->n_enc; k-- > 0;) { + if (g->enc[k].encoder != encoder) continue; + NSString *l = [(id)encoder label]; + const char *s = l ? l.UTF8String : NULL; + if (s) { /* drop the "#" so passes of the same kind sum together */ + char *o = g->enc[k].label, *end = o + sizeof g->enc[k].label - 1; + while (*s && o < end) { + if (*s == '#') { s++; while (*s >= '0' && *s <= '9') s++; continue; } + *o++ = *s++; + } + *o = 0; + } + g->enc[k].encoder = nil; + os_unfair_lock_unlock(&g_gpt_lock); + return; + } + } + os_unfair_lock_unlock(&g_gpt_lock); +} + +static int gpt_cmp_iv(const void *a, const void *b) { + const uint64_t *x = a, *y = b; + return x[0] < y[0] ? -1 : x[0] > y[0]; +} +static int gpt_cmp_key(const void *a, const void *b) { + const struct gpt_key *x = a, *y = b; + return x->span_ns < y->span_ns ? 1 : x->span_ns > y->span_ns ? -1 : 0; +} + +static void gpt_report_locked(uint64_t now) { + unsigned presents = atomic_exchange_explicit(&g_gpt_presents, 0, memory_order_relaxed); + double f = presents ? (double)presents : 1.0, total = 0; + unsigned i, shown; + if (!g_gpt_cbs) return; + qsort(g_gpt_keys, g_gpt_nkeys, sizeof g_gpt_keys[0], gpt_cmp_key); + for (i = 0; i < g_gpt_nkeys; i++) total += g_gpt_keys[i].span_ns; + fprintf(stderr, "[gpu-pass] window: %u presents, %u command buffers, %u encoders timed, %u without samples (%u buffers missed); per frame: " + "GPU busy %.2f ms, encoders running %.2f ms (gaps %.2f ms), encoder time summed %.2f ms (overlap %.2f ms)\n", + presents, g_gpt_cbs, g_gpt_encs, g_gpt_nosamp, g_gpt_lost, g_gpt_busy_ns / f / 1e6, g_gpt_union_ns / f / 1e6, + (g_gpt_busy_ns - g_gpt_union_ns) / f / 1e6, g_gpt_sum_ns / f / 1e6, (g_gpt_sum_ns - g_gpt_union_ns) / f / 1e6); + for (i = 0, shown = 0; i < g_gpt_nkeys && shown < 40; i++, shown++) { + struct gpt_key *k = &g_gpt_keys[i]; + fprintf(stderr, "[gpu-pass] %2u %6.2f ms/f %4.1f%% x%-5.1f %c %4ux%-4u vtx %5.2f frag %5.2f | %s\n", i + 1, + k->span_ns / f / 1e6, total > 0 ? 100.0 * k->span_ns / total : 0.0, k->count / f, + k->kind == 0 ? 'R' : k->kind == 1 ? 'C' : 'B', k->w, k->h, k->vtx_ns / f / 1e6, k->frag_ns / f / 1e6, + k->label[0] ? k->label : "(no label: encoder-labels = 1)"); + } + g_gpt_nkeys = 0; g_gpt_cbs = 0; g_gpt_encs = 0; g_gpt_lost = 0; g_gpt_nosamp = 0; + g_gpt_busy_ns = g_gpt_union_ns = g_gpt_sum_ns = 0; + g_gpt_win_start = 0; + (void)now; +} + +static void gpt_complete(struct gpt_cb *g, id buffer) { + NSData *data = nil; + const MTLCounterResultTimestamp *ts; + uint64_t (*iv)[2] = NULL, cb0 = 0; + unsigned n = 0, i, dump = 0; + double npt, union_ns = 0, sum_ns = 0, busy_ns; + if (g->n_samp && g_gpt_ns_per_tick > 0) + data = [g->sb resolveCounterRange:NSMakeRange(0, g->n_samp)]; + if (data.length < g->n_samp * sizeof(MTLCounterResultTimestamp)) data = nil; + busy_ns = (buffer.GPUEndTime - buffer.GPUStartTime) * 1e9; + os_unfair_lock_lock(&g_gpt_lock); + npt = g_gpt_ns_per_tick; + if (data && (iv = malloc(sizeof *iv * g->n_enc))) { + uint64_t now = gpt_now_ns(); + ts = data.bytes; + if (!g_gpt_dump_left && g_gpt_dump_s > 0 && (!g_gpt_last_dump || now - g_gpt_last_dump >= (uint64_t)g_gpt_dump_s * 1000000000ull)) { + g_gpt_last_dump = now; g_gpt_dump_left = 3; /* about one frame's command buffers */ + } + if (g_gpt_dump_left && g->n_enc >= 5) { dump = 1; g_gpt_dump_left--; } + for (i = 0; i < g->n_enc; i++) { + const struct gpt_enc *e = &g->enc[i]; + uint64_t s = ~0ull, t = 0, v = 0, fr = 0; + unsigned k; + if (!e->nsamp) continue; + for (k = 0; k < e->nsamp; k++) { + uint64_t x = ts[e->base + k].timestamp; + if (x == MTLCounterErrorValue || !x) continue; + if (x < s) s = x; + if (x > t) t = x; + } + if (t <= s) { g_gpt_nosamp++; continue; } /* no usable samples (all zero or MTLCounterErrorValue) */ + if (e->kind == 0) { + uint64_t a = ts[e->base].timestamp, b = ts[e->base + 1].timestamp; + uint64_t c = ts[e->base + 2].timestamp, d = ts[e->base + 3].timestamp; + if (a != MTLCounterErrorValue && b != MTLCounterErrorValue && b > a) v = b - a; + if (c != MTLCounterErrorValue && d != MTLCounterErrorValue && d > c) fr = d - c; + } + if (!n || s < cb0) cb0 = s; + iv[n][0] = s; iv[n][1] = t; n++; + sum_ns += (t - s) * npt; + { /* sum per pass */ + struct gpt_key *key = NULL; + unsigned j; + for (j = 0; j < g_gpt_nkeys; j++) + if (g_gpt_keys[j].kind == e->kind && g_gpt_keys[j].w == e->w && g_gpt_keys[j].h == e->h && + !strcmp(g_gpt_keys[j].label, e->label)) { key = &g_gpt_keys[j]; break; } + if (!key && g_gpt_nkeys < GPT_KEYS) { + key = &g_gpt_keys[g_gpt_nkeys++]; + memset(key, 0, sizeof *key); + memcpy(key->label, e->label, sizeof key->label); + key->kind = e->kind; key->w = e->w; key->h = e->h; + } + if (key) { key->count++; key->span_ns += (t - s) * npt; key->vtx_ns += v * npt; key->frag_ns += fr * npt; } + } + } + if (dump) { + fprintf(stderr, "[gpu-pass-dump] command buffer: GPU %.2f ms, %u encoders (start offset us, span us, vtx us, frag us)\n", + busy_ns / 1e3 / 1e3, g->n_enc); + for (i = 0; i < g->n_enc && i < 400; i++) { + const struct gpt_enc *e = &g->enc[i]; + uint64_t a = ~0ull, b = 0; + unsigned k; + if (!e->nsamp) continue; + for (k = 0; k < e->nsamp; k++) { + uint64_t x = ts[e->base + k].timestamp; + if (x == MTLCounterErrorValue || !x) continue; + if (x < a) a = x; + if (x > b) b = x; + } + if (b <= a) { fprintf(stderr, "[gpu-pass-dump] %3u (no samples) %c %ux%u %s\n", i, e->kind == 0 ? 'R' : e->kind == 1 ? 'C' : 'B', e->w, e->h, e->label); continue; } + fprintf(stderr, "[gpu-pass-dump] %3u %8.1f %7.1f", i, (a - cb0) * npt / 1e3, (b - a) * npt / 1e3); + if (e->kind == 0) { + uint64_t p = ts[e->base].timestamp, q = ts[e->base + 1].timestamp, r = ts[e->base + 2].timestamp, s2 = ts[e->base + 3].timestamp; + fprintf(stderr, " %7.1f %7.1f", (p != MTLCounterErrorValue && q > p) ? (q - p) * npt / 1e3 : 0.0, + (r != MTLCounterErrorValue && s2 > r) ? (s2 - r) * npt / 1e3 : 0.0); + } else fprintf(stderr, " - -"); + fprintf(stderr, " %c %ux%u %s\n", e->kind == 0 ? 'R' : e->kind == 1 ? 'C' : 'B', e->w, e->h, e->label); + } + } + qsort(iv, n, sizeof *iv, gpt_cmp_iv); + { + uint64_t cs = 0, ce = 0; + for (i = 0; i < n; i++) { + if (!i || iv[i][0] > ce) { if (i) union_ns += (ce - cs) * npt; cs = iv[i][0]; ce = iv[i][1]; } + else if (iv[i][1] > ce) ce = iv[i][1]; + } + if (n) union_ns += (ce - cs) * npt; + } + free(iv); + g_gpt_cbs++; g_gpt_encs += n; + if (busy_ns > 0) g_gpt_busy_ns += busy_ns; + g_gpt_union_ns += union_ns; g_gpt_sum_ns += sum_ns; + if (!g_gpt_win_start) g_gpt_win_start = now; + } + g->busy = 0; g->cb = nil; + atomic_fetch_sub_explicit(&g_gpt_open, 1, memory_order_relaxed); + /* one report per period, once the window's buffers have come back (or 3 s on, + * should a timed buffer never complete) */ + if (g_gpt_cbs && !gpt_window() && + (!atomic_load_explicit(&g_gpt_open, memory_order_relaxed) || gpt_now_ns() - g_gpt_win_start >= 3000000000ull)) + gpt_report_locked(gpt_now_ns()); + os_unfair_lock_unlock(&g_gpt_lock); +} + +/* At commit: read the samples once the GPU is done with the buffer. */ +static void gpt_commit(id cb) { + struct gpt_cb *g; + if (!atomic_load_explicit(&g_gpt_open, memory_order_relaxed)) return; + os_unfair_lock_lock(&g_gpt_lock); + g = gpt_find_locked(cb, 0); + if (g) g->cb = nil; + os_unfair_lock_unlock(&g_gpt_lock); + if (!g) return; + [cb addCompletedHandler:^(id buffer) { gpt_complete(g, buffer); }]; +} + +/* Presents inside the timed second: the frames the window's numbers divide by. */ +static void gpt_note_present(void) { + if (g_gpt_ok == 1 && gpt_window()) + atomic_fetch_add_explicit(&g_gpt_presents, 1, memory_order_relaxed); +} + static NTSTATUS _MTLCommandBuffer_commit(void *obj) { struct unixcall_generic_obj_noret *params = obj; @@ -625,6 +984,7 @@ _MTLCommandBuffer_commit(void *obj) { } if (atomic_load_explicit(&g_madeira_gpu_meter, memory_order_relaxed)) madeira_gpu_meter_attach((id)params->handle); + gpt_commit((id)params->handle); /* madeira-duo gpu-pass-timing */ [(id)params->handle commit]; return STATUS_SUCCESS; } @@ -1846,7 +2206,19 @@ _MTLCommandBuffer_blitCommandEncoder(void *obj) { wmtr_enc_note(params->ret, params->handle); /* ml820: blit destinations read back per cmdbuf */ return STATUS_SUCCESS; } - params->ret = (obj_handle_t)[(id)params->handle blitCommandEncoder]; + { /* madeira-duo gpu-pass-timing: a timed blit takes its samples through a pass descriptor */ + unsigned gi = 0; + struct gpt_cb *gt = gpt_begin((id)params->handle, 2, 2, 0, 0, &gi); + if (gt) { + MTLBlitPassDescriptor *bd = [MTLBlitPassDescriptor blitPassDescriptor]; + bd.sampleBufferAttachments[0].sampleBuffer = gt->sb; + bd.sampleBufferAttachments[0].startOfEncoderSampleIndex = gt->enc[gi].base; + bd.sampleBufferAttachments[0].endOfEncoderSampleIndex = gt->enc[gi].base + 1; + params->ret = (obj_handle_t)[(id)params->handle blitCommandEncoderWithDescriptor:bd]; + gpt_created(gt, gi, (id)params->ret); + } else + params->ret = (obj_handle_t)[(id)params->handle blitCommandEncoder]; + } if (params->ret && madeira_frame_hooks_on()) ios_frame_pass(1, 0, 0, 0); return STATUS_SUCCESS; } @@ -1864,8 +2236,21 @@ _MTLCommandBuffer_computeCommandEncoder(void *obj) { if (!params->ret) fprintf(stderr, "[wmt-remote] host refused a compute encoder\n"); return STATUS_SUCCESS; } - params->ret = (obj_handle_t)[(id)params->handle - computeCommandEncoderWithDispatchType:params->arg ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial]; + { /* madeira-duo gpu-pass-timing: a timed compute encoder takes its samples through a pass descriptor */ + unsigned gi = 0; + struct gpt_cb *gt = gpt_begin((id)params->handle, 1, 2, 0, 0, &gi); + if (gt) { + MTLComputePassDescriptor *cd = [MTLComputePassDescriptor computePassDescriptor]; + cd.dispatchType = params->arg ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial; + cd.sampleBufferAttachments[0].sampleBuffer = gt->sb; + cd.sampleBufferAttachments[0].startOfEncoderSampleIndex = gt->enc[gi].base; + cd.sampleBufferAttachments[0].endOfEncoderSampleIndex = gt->enc[gi].base + 1; + params->ret = (obj_handle_t)[(id)params->handle computeCommandEncoderWithDescriptor:cd]; + gpt_created(gt, gi, (id)params->ret); + } else + params->ret = (obj_handle_t)[(id)params->handle + computeCommandEncoderWithDispatchType:params->arg ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial]; + } if (params->ret && madeira_frame_hooks_on()) ios_frame_pass(2, 0, 0, 0); return STATUS_SUCCESS; } @@ -1965,7 +2350,26 @@ _MTLCommandBuffer_renderCommandEncoder(void *obj) { descriptor.renderTargetWidth = info->render_target_width; descriptor.visibilityResultBuffer = (id)info->visibility_buffer; - params->ret = (obj_handle_t)[(id)params->handle renderCommandEncoderWithDescriptor:descriptor]; + { /* madeira-duo gpu-pass-timing: vertex and fragment start/end samples for a timed pass */ + unsigned gi = 0, gw = info->render_target_width, gh = info->render_target_height; + struct gpt_cb *gt; + if (!gw && gpt_period()) { + id t = (id)(info->colors[0].texture ? info->colors[0].texture : info->depth.texture); + unsigned lv = info->colors[0].texture ? info->colors[0].level : info->depth.level; + if (t) { gw = (unsigned)(t.width >> lv); gh = (unsigned)(t.height >> lv); if (!gw) gw = 1; if (!gh) gh = 1; } + } + gt = gpt_begin((id)params->handle, 0, 4, gw, gh, &gi); + if (gt) { + MTLRenderPassSampleBufferAttachmentDescriptor *sa = descriptor.sampleBufferAttachments[0]; + sa.sampleBuffer = gt->sb; + sa.startOfVertexSampleIndex = gt->enc[gi].base; + sa.endOfVertexSampleIndex = gt->enc[gi].base + 1; + sa.startOfFragmentSampleIndex = gt->enc[gi].base + 2; + sa.endOfFragmentSampleIndex = gt->enc[gi].base + 3; + } + params->ret = (obj_handle_t)[(id)params->handle renderCommandEncoderWithDescriptor:descriptor]; + gpt_created(gt, gi, (id)params->ret); + } /* Count realized native passes, including clears and the final present. * No new PE ABI or emulated hot-path counters are needed. */ @@ -2001,6 +2405,7 @@ _MTLCommandEncoder_endEncoding(void *obj) { wmtr_call(RM_OP_END_ENCODING, &a, sizeof a, 0, 0, 0); return STATUS_SUCCESS; } + gpt_end((id)params->handle); /* madeira-duo gpu-pass-timing: keep the label */ [(id)params->handle endEncoding]; return STATUS_SUCCESS; } @@ -4013,6 +4418,7 @@ _MTLCommandBuffer_presentDrawable(void *obj) { return STATUS_SUCCESS; } int mode = g_madeira_vsync_mode; + gpt_note_present(); /* madeira-duo gpu-pass-timing */ { /* madeira-bcd fps-gov (tools/patch-winemetal-fps-cap.py): the governor's frame cap, opt-in */ extern unsigned long long ios_fps_cap_dxmt_pace(void); unsigned long long fps_cap_ns = ios_fps_cap_dxmt_pace(); @@ -4070,6 +4476,7 @@ static NTSTATUS _MTLCommandBuffer_presentDrawableAfterMinimumDuration(void *obj) { struct unixcall_generic_obj_obj_double_noret *params = obj; madeira_log_present_cadence("presentDrawableAfterMinDuration", params->arg1); + gpt_note_present(); /* madeira-duo gpu-pass-timing */ madeira_frame_mark_drawable((id)params->arg0); [(id)params->handle presentDrawable:(id)params->arg0 afterMinimumDuration:params->arg1]; From 95db7f41c8d488b868c5f750276b2b51c3cea5d1 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Mon, 9 Nov 2026 18:36:34 +1100 Subject: [PATCH 3/6] winemetal: shader-miss figures for the performance overlay The overlay had no way to show why a stretch hitches or monsters stay invisible: shader conversions, pipeline compiles that missed the pso-archive, and the pso-async backlog only appear in log lines written every few hundred events. madeira_shader_overlay_stats() gives the overlay, once per tick: - shader_misses: madeira-d3d12's count of stages its shader cache did not have, read from the counter block it already publishes with MadeiraCtl op 5 (its overlay fields sit at byte 184, after struct ios_xp_pe and ios_xp_pe_cap); - pipeline_misses: pipelines the pso-archive's saved chunks did not have and that were compiled for the game (inline add, queued add, or a plain create once the archive is full). pso-warm's own background compiles are left out through a thread-local flag; - pso_queue / pso_background: the pso-async queue draws wait on (queued or being built) and the create-time queue behind it, from the same block; - flags: block present, shader cache on, pso-async on, archive in use. The block is the game process's memory, gone once the game exits while Steam stays, so it is read with vm_read_overwrite (as server_ios.c reads guest memory): a stale address gives no figures instead of a fault. Counting costs one relaxed atomic add on a path that is compiling a pipeline anyway; nothing runs per frame. An older madeira-d3d12 (shorter block) gives zeros and no "block present" flag. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Shitiz Garg --- src/winemetal/unix/winemetal_unix.c | 64 +++++++++++++++++++++++++++-- 1 file changed, 61 insertions(+), 3 deletions(-) diff --git a/src/winemetal/unix/winemetal_unix.c b/src/winemetal/unix/winemetal_unix.c index 9dffe7634..2d2218be4 100644 --- a/src/winemetal/unix/winemetal_unix.c +++ b/src/winemetal/unix/winemetal_unix.c @@ -1918,6 +1918,9 @@ static void madeira_arch_load(id device) { cap >> 20, madeira_arch_dir, bad, old); } +static int madeira_arch_in_use(void) { /* madeira-duo overlay-shader: lookups are on */ + return atomic_load_explicit(&madeira_arch_named, memory_order_acquire) == 2; +} static int madeira_arch_full(void) { return atomic_load_explicit(&madeira_arch_bytes, memory_order_relaxed) >= atomic_load_explicit(&madeira_arch_cap, memory_order_relaxed); @@ -1956,6 +1959,53 @@ static void madeira_arch_note_hit(void) { if (n == 1 || (n % 2000) == 0) madeira_arch_say(n == 1 ? "first pipeline from the saved chunks" : "so far"); } +/* madeira-duo overlay-shader: pipelines the saved chunks did not have, compiled for the + * game (inline add, queued add, or a plain create once the archive is full); pso-warm's + * own background compiles are left out (madeira_pso_warm_self). One relaxed add on a + * path that compiles anyway; read by madeira_shader_overlay_stats. */ +static _Atomic unsigned long long madeira_ovl_arch_miss; +static _Thread_local int madeira_pso_warm_self; +static void madeira_ovl_note_miss(void) { + if (!madeira_pso_warm_self) atomic_fetch_add_explicit(&madeira_ovl_arch_miss, 1, memory_order_relaxed); +} + +/* madeira-duo overlay-shader: the performance overlay's shader cells, read once per + * overlay tick. madeira-d3d12 keeps its counts after the fps-gov fields of the counter + * block it publishes with MadeiraCtl op 5 (struct mad_xp in madeira_d3d12.c; byte 184, + * after struct ios_xp_pe and struct ios_xp_pe_cap in server_ios.c). Cumulative counts + * (the overlay takes the rate) and current queue depths: + * shader_misses stages madeira-d3d12's shader cache did not have (converted or refused) + * pipeline_misses pipelines the pso-archive did not have, compiled for the game + * pso_queue pso-async: pipelines a draw is waiting for, queued or being built + * pso_background pso-create-build / cs-create-build: queued at creation, not built yet + * flags: 1 = madeira-d3d12's block is there, 2 = its shader cache is on, 4 = pso-async + * is on, 8 = the pso-archive is in use. Without the block the d3d12 figures are 0. */ +#define MADEIRA_XP_SHADER_AT 184 +struct madeira_xp_shader { int64_t magic, flags, sc_miss, pa_wait, pcb_wait; }; +extern volatile uint64_t ios_xp_pe_block, ios_xp_pe_len; +void madeira_shader_overlay_stats(unsigned long long *shader_misses, unsigned long long *pipeline_misses, + long long *pso_queue, long long *pso_background, int *flags) { + uint64_t block = ios_xp_pe_block, len = ios_xp_pe_len; + int f = madeira_arch_in_use() ? 8 : 0; + *shader_misses = 0; *pso_queue = 0; *pso_background = 0; + *pipeline_misses = atomic_load_explicit(&madeira_ovl_arch_miss, memory_order_relaxed); + /* The block is the game process's memory, which goes when the game exits (Steam can + * stay): read it with vm_read_overwrite, as server_ios.c reads guest memory, so a + * stale address gives no figures instead of a fault. */ + if (block && len >= MADEIRA_XP_SHADER_AT + sizeof(struct madeira_xp_shader)) { + struct madeira_xp_shader x; + vm_size_t got = 0; + if (vm_read_overwrite(mach_task_self(), (vm_address_t)(block + MADEIRA_XP_SHADER_AT), sizeof x, (vm_address_t)&x, + &got) == KERN_SUCCESS && got == sizeof x && x.magic == 0x31304448534d4d4dLL) { + f |= 1 | (int)(x.flags & 3) << 1; + *shader_misses = (unsigned long long)x.sc_miss; + *pso_queue = x.pa_wait > 0 ? x.pa_wait : 0; + *pso_background = x.pcb_wait > 0 ? x.pcb_wait : 0; + } + } + *flags = f; +} + /* madeira_arch_q: an archive of n pipelines becomes the next chunk file and joins * the lookup list. The caller keeps its reference. */ static void madeira_arch_save_archive(id open, unsigned n) { @@ -2177,8 +2227,10 @@ _MTLDevice_newComputePipelineState(void *obj) { if (params->ret_pso) madeira_arch_note_hit(); else err = NULL; } - if (!params->ret_pso && madeira_arch) + if (!params->ret_pso && madeira_arch) { + madeira_ovl_note_miss(); /* madeira-duo overlay-shader */ params->ret_pso = madeira_arch_create(device, descriptor, 1, options, &err); + } if (!params->ret_pso) { err = NULL; params->ret_pso = @@ -2526,8 +2578,10 @@ _MTLDevice_newRenderPipelineState(void *obj) { if (params->ret_pso) madeira_arch_note_hit(); else err = NULL; } - if (!params->ret_pso && madeira_arch) + if (!params->ret_pso && madeira_arch) { + madeira_ovl_note_miss(); /* madeira-duo overlay-shader */ params->ret_pso = madeira_arch_create((id)params->device, descriptor, 0, options, &err); + } if (!params->ret_pso) { err = NULL; params->ret_pso = (obj_handle_t)[(id)params->device newRenderPipelineStateWithDescriptor:descriptor @@ -2645,8 +2699,10 @@ _MTLDevice_newRenderPipelineStateVD(void *obj) { if (params->ret_pso) madeira_arch_note_hit(); else err = NULL; } - if (!params->ret_pso && madeira_arch) + if (!params->ret_pso && madeira_arch) { + madeira_ovl_note_miss(); /* madeira-duo overlay-shader */ params->ret_pso = madeira_arch_create((id)params->device, descriptor, 0, options, &err); + } if (!params->ret_pso) { err = NULL; params->ret_pso = (obj_handle_t)[(id)params->device newRenderPipelineStateWithDescriptor:descriptor @@ -7535,6 +7591,7 @@ static uint32_t madeira_pso_warm_submit(obj_handle_t device, const void *info, c @autoreleasepool { uint64_t t0 = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); obj_handle_t pso = 0; + madeira_pso_warm_self = 1; /* madeira-duo overlay-shader: not a miss the game waits for */ if (kind == 2) { struct unixcall_mtldevice_newcomputepso p; memset(&p, 0, sizeof p); @@ -7554,6 +7611,7 @@ static uint32_t madeira_pso_warm_submit(obj_handle_t device, const void *info, c _MTLDevice_newRenderPipelineState(&p); pso = p.ret_pso; } + madeira_pso_warm_self = 0; madeira_pso_warm_note(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - t0, pso != 0); if (pso) [(id)pso release]; if (f0) [(id)f0 release]; From 694f7686116a25a78adaa1490de4ec902aefa707 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Sun, 15 Nov 2026 00:02:40 +1100 Subject: [PATCH 4/6] winemetal: archive-only pipeline lookup when the caller asks to fail on a miss A render or compute pipeline created with fail_on_binary_archive_miss and no archives of the caller's own now looks only in the pso-archive's saved chunks: a miss returns no pipeline and no error and compiles nothing. madeira-d3d12 uses it (pso-create-block = 2) to take a pipeline from the archive inside the game's create call and leave misses to its background builders. Nothing set the flag without archives before, so other callers are unchanged. Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- src/winemetal/unix/winemetal_unix.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/winemetal/unix/winemetal_unix.c b/src/winemetal/unix/winemetal_unix.c index 2d2218be4..699ab1549 100644 --- a/src/winemetal/unix/winemetal_unix.c +++ b/src/winemetal/unix/winemetal_unix.c @@ -2227,6 +2227,15 @@ _MTLDevice_newComputePipelineState(void *obj) { if (params->ret_pso) madeira_arch_note_hit(); else err = NULL; } + if (!params->ret_pso && info->fail_on_binary_archive_miss && !info->num_binary_archives_for_lookup) { + /* madeira-duo pso-hit-probe: the caller asked for the saved chunks only (madeira-d3d12 + * pso-create-block = 2). A miss returns no pipeline and no error, and compiles nothing; + * the caller builds it later the usual way, which counts the miss then. */ + [madeira_arch release]; + params->ret_error = 0; + [descriptor release]; + return STATUS_SUCCESS; + } if (!params->ret_pso && madeira_arch) { madeira_ovl_note_miss(); /* madeira-duo overlay-shader */ params->ret_pso = madeira_arch_create(device, descriptor, 1, options, &err); @@ -2578,6 +2587,15 @@ _MTLDevice_newRenderPipelineState(void *obj) { if (params->ret_pso) madeira_arch_note_hit(); else err = NULL; } + if (!params->ret_pso && info->fail_on_binary_archive_miss && !info->num_binary_archives_for_lookup) { + /* madeira-duo pso-hit-probe: the caller asked for the saved chunks only (madeira-d3d12 + * pso-create-block = 2). A miss returns no pipeline and no error, and compiles nothing; + * the caller builds it later the usual way, which counts the miss then. */ + [madeira_arch release]; + params->ret_error = 0; + [descriptor release]; + return STATUS_SUCCESS; + } if (!params->ret_pso && madeira_arch) { madeira_ovl_note_miss(); /* madeira-duo overlay-shader */ params->ret_pso = madeira_arch_create((id)params->device, descriptor, 0, options, &err); @@ -2699,6 +2717,15 @@ _MTLDevice_newRenderPipelineStateVD(void *obj) { if (params->ret_pso) madeira_arch_note_hit(); else err = NULL; } + if (!params->ret_pso && info->fail_on_binary_archive_miss && !info->num_binary_archives_for_lookup) { + /* madeira-duo pso-hit-probe: the caller asked for the saved chunks only (madeira-d3d12 + * pso-create-block = 2). A miss returns no pipeline and no error, and compiles nothing; + * the caller builds it later the usual way, which counts the miss then. */ + [madeira_arch release]; + params->ret_error = 0; + [descriptor release]; + return STATUS_SUCCESS; + } if (!params->ret_pso && madeira_arch) { madeira_ovl_note_miss(); /* madeira-duo overlay-shader */ params->ret_pso = madeira_arch_create((id)params->device, descriptor, 0, options, &err); From fe0ba66a76edf4bd5b738fe50965636db6a65dc2 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Sun, 15 Nov 2026 01:50:56 +1100 Subject: [PATCH 5/6] winemetal: pso-warm yields to the game's compiles; archive saves by age pso-warm's background compiles share Metal's compiler with the pipelines the game waits for. A warm-up that missed the saved chunks now waits before compiling until no compile for the game is running and the last ended 500 ms ago; archive hits go straight through. MADEIRA_PSO_WARM_YIELD=0 turns the wait off. The effect of the wait on frame time was not isolated. The [pso-warm] line that suggested hundreds of competing warm compiles a session classed a warm-up by its wall time and counted cache hits that waited for a core as compiles; the next commit fixes that count. In Path of Exile 2 the warm-ups that really compile are about 57 a session. The open archives were saved when full (128) or after 10 s without an add. In a map the adds never pause that long, so a session that ended there lost up to five part-filled archives (50-228 pipelines a session in the logs) and the next visit compiled them again. They are now also saved once their oldest unsaved add is MADEIRA_PSO_ARCHIVE_MAX_AGE seconds old (default 20; the check runs every 5 s). [pso-archive] lines give the inline adds made for the game apart from pso-warm's; [pso-warm] lines how often and how long warm-ups waited. Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 --- src/winemetal/unix/winemetal_unix.c | 99 ++++++++++++++++++++++++++--- 1 file changed, 89 insertions(+), 10 deletions(-) diff --git a/src/winemetal/unix/winemetal_unix.c b/src/winemetal/unix/winemetal_unix.c index 699ab1549..514ddd7b1 100644 --- a/src/winemetal/unix/winemetal_unix.c +++ b/src/winemetal/unix/winemetal_unix.c @@ -1807,8 +1807,11 @@ static struct madeira_arch_slot { os_unfair_lock lock; id open; unsigned n; - uint64_t last; + uint64_t last, first; /* first: the oldest unsaved add (madeira-duo arch-age) */ } madeira_arch_slots[MADEIRA_ARCH_SLOTS]; +static uint64_t madeira_arch_open_first; /* madeira_arch_q only: the queue archive's oldest unsaved add */ +static _Atomic long madeira_arch_fg_inline; +static _Atomic uint64_t madeira_arch_fg_inline_ns; static _Atomic long madeira_arch_inline, madeira_arch_inline_slow; static _Atomic uint64_t madeira_arch_inline_add_ns, madeira_arch_inline_create_ns; @@ -1943,7 +1946,8 @@ static void madeira_arch_say(const char *what) { long added = atomic_load_explicit(&madeira_arch_added, memory_order_relaxed); long in = atomic_load_explicit(&madeira_arch_inline, memory_order_relaxed); fprintf(stderr, "[pso-archive] %s: %ld pipelines found in the saved chunks, %ld not (%ld added, avg %.1f ms " - "an add, %ld failed); inline %ld (avg %.1f ms the add, %.1f ms the create from it, %ld created slowly)\n", + "an add, %ld failed); inline %ld (avg %.1f ms the add, %.1f ms the create from it, %ld created slowly; " + "for the game %ld, avg %.1f ms the add)\n", what, atomic_load_explicit(&madeira_arch_hits, memory_order_relaxed), atomic_load_explicit(&madeira_arch_misses, memory_order_relaxed), added, @@ -1951,7 +1955,12 @@ static void madeira_arch_say(const char *what) { atomic_load_explicit(&madeira_arch_add_failed, memory_order_relaxed), in, in ? (double)atomic_load_explicit(&madeira_arch_inline_add_ns, memory_order_relaxed) / 1e6 / in : 0.0, in ? (double)atomic_load_explicit(&madeira_arch_inline_create_ns, memory_order_relaxed) / 1e6 / in : 0.0, - atomic_load_explicit(&madeira_arch_inline_slow, memory_order_relaxed)); + atomic_load_explicit(&madeira_arch_inline_slow, memory_order_relaxed), + atomic_load_explicit(&madeira_arch_fg_inline, memory_order_relaxed), + atomic_load_explicit(&madeira_arch_fg_inline, memory_order_relaxed) + ? (double)atomic_load_explicit(&madeira_arch_fg_inline_ns, memory_order_relaxed) / 1e6 / + atomic_load_explicit(&madeira_arch_fg_inline, memory_order_relaxed) + : 0.0); } static void madeira_arch_note_hit(void) { @@ -1969,6 +1978,50 @@ static void madeira_ovl_note_miss(void) { if (!madeira_pso_warm_self) atomic_fetch_add_explicit(&madeira_ovl_arch_miss, 1, memory_order_relaxed); } +/* madeira-duo warm-yield: pso-warm's background compiles share Metal's compiler with + * the pipelines the game is waiting for. In Path of Exile 2 (log 2026-11-15 01:17) it + * compiled ~4 compute pipelines a second while new maps loaded and the game's own render + * pipelines got ~1 a second; 815 warm compiles against 383 render ones, most of the + * warmed ones never dispatched. A warm-up that missed the saved chunks now waits, before + * it compiles, until no compile for the game is running and the last one ended 500 ms + * ago. Archive hits still go straight through. MADEIRA_PSO_WARM_YIELD=0: no waiting. */ +static _Atomic int madeira_fg_compiling; +static _Atomic uint64_t madeira_fg_last_ns, madeira_warm_yield_ns; +static _Atomic long madeira_warm_yields; +static void madeira_warm_yield(void) { + static int on = -1; + uint64_t t0, now; + int waited = 0; + if (on < 0) { + const char *e = getenv("MADEIRA_PSO_WARM_YIELD"); + on = !(e && !strcmp(e, "0")); + } + if (!on) return; + t0 = now = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + while (atomic_load_explicit(&madeira_fg_compiling, memory_order_relaxed) > 0 || + now - atomic_load_explicit(&madeira_fg_last_ns, memory_order_relaxed) < 500000000ull) { + { struct timespec ts = { 0, 20000000 }; nanosleep(&ts, NULL); } + waited = 1; + now = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + } + if (waited) { + atomic_fetch_add_explicit(&madeira_warm_yields, 1, memory_order_relaxed); + atomic_fetch_add_explicit(&madeira_warm_yield_ns, now - t0, memory_order_relaxed); + } +} +/* Around a compile after a lookup miss: 1 = a compile for the game (counted), 0 = a + * warm-up (it has waited its turn). */ +static int madeira_compile_begin(void) { + if (madeira_pso_warm_self) { madeira_warm_yield(); return 0; } + atomic_fetch_add_explicit(&madeira_fg_compiling, 1, memory_order_relaxed); + return 1; +} +static void madeira_compile_end(int fg) { + if (fg <= 0) return; + atomic_store_explicit(&madeira_fg_last_ns, clock_gettime_nsec_np(CLOCK_UPTIME_RAW), memory_order_relaxed); + atomic_fetch_sub_explicit(&madeira_fg_compiling, 1, memory_order_relaxed); +} + /* madeira-duo overlay-shader: the performance overlay's shader cells, read once per * overlay tick. madeira-d3d12 keeps its counts after the fps-gov fields of the counter * block it publishes with MadeiraCtl op 5 (struct mad_xp in madeira_d3d12.c; byte 184, @@ -2063,22 +2116,35 @@ static void madeira_arch_save_handed(id open, unsigned n) { }); } -/* madeira_arch_q: save the open archive once 10 s have passed without an add. */ +/* madeira_arch_q: save the open archive once 10 s have passed without an add. + * madeira-duo arch-age: or once its oldest unsaved add is MADEIRA_PSO_ARCHIVE_MAX_AGE + * seconds old (default 20). In a map the adds never stop for 10 s, so a session that + * ended there (killed, or the app closed) lost up to five part-filled archives: 50-228 + * pipelines a session in Path of Exile 2's logs, which the next visit compiled again. */ +static uint64_t madeira_arch_max_age_ns(void) { + static uint64_t v; + if (!v) { + const char *e = getenv("MADEIRA_PSO_ARCHIVE_MAX_AGE"); + long s = e ? atol(e) : 20; + v = (uint64_t)(s >= 2 && s <= 600 ? s : 20) * 1000000000ull; + } + return v; +} static void madeira_arch_arm(void) { if (madeira_arch_timer) return; madeira_arch_timer = 1; - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), madeira_arch_q, ^{ - uint64_t now = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), madeira_arch_q, ^{ + uint64_t now = clock_gettime_nsec_np(CLOCK_UPTIME_RAW), age = madeira_arch_max_age_ns(); int again = 0; madeira_arch_timer = 0; if (madeira_arch_open_n) { - if (now - madeira_arch_last_add >= 9500000000ull) madeira_arch_save(); + if (now - madeira_arch_last_add >= 9500000000ull || now - madeira_arch_open_first >= age) madeira_arch_save(); else again = 1; } for (unsigned i = 0; i < MADEIRA_ARCH_SLOTS; i++) { /* a slot in use is busy, not idle */ struct madeira_arch_slot *s = &madeira_arch_slots[i]; if (!os_unfair_lock_trylock(&s->lock)) { again = 1; continue; } - if (s->n && now - s->last >= 9500000000ull) { + if (s->n && (now - s->last >= 9500000000ull || now - s->first >= age)) { @autoreleasepool { madeira_arch_save_archive(s->open, s->n); } [s->open release]; s->open = nil; @@ -2120,6 +2186,7 @@ static void madeira_arch_add(id descriptor, int kind) { if (ok && !err) { atomic_fetch_add_explicit(&madeira_arch_added, 1, memory_order_relaxed); atomic_fetch_add_explicit(&madeira_arch_add_ns, madeira_arch_last_add - t0, memory_order_relaxed); + if (!madeira_arch_open_n) madeira_arch_open_first = madeira_arch_last_add; /* madeira-duo arch-age */ if (++madeira_arch_open_n >= MADEIRA_ARCH_CHUNK) madeira_arch_save(); } else if (atomic_fetch_add_explicit(&madeira_arch_add_failed, 1, memory_order_relaxed) < 3) { fprintf(stderr, "[pso-archive] an add failed: %s\n", @@ -2171,6 +2238,11 @@ static obj_handle_t madeira_arch_create(id device, id descriptor, int atomic_fetch_add_explicit(&madeira_arch_inline_create_ns, t2 - t1, memory_order_relaxed); if (t2 - t1 > 20000000ull) /* not taken from the archive: compiled again */ atomic_fetch_add_explicit(&madeira_arch_inline_slow, 1, memory_order_relaxed); + if (!madeira_pso_warm_self) { /* madeira-duo: the adds the game waited for, apart from pso-warm's */ + atomic_fetch_add_explicit(&madeira_arch_fg_inline, 1, memory_order_relaxed); + atomic_fetch_add_explicit(&madeira_arch_fg_inline_ns, t1 - t0, memory_order_relaxed); + } + if (!s->n) s->first = t2; /* madeira-duo arch-age */ if (++s->n >= MADEIRA_ARCH_CHUNK) { madeira_arch_save_handed(s->open, s->n); /* the queue takes the reference */ s->open = nil; @@ -2236,6 +2308,7 @@ _MTLDevice_newComputePipelineState(void *obj) { [descriptor release]; return STATUS_SUCCESS; } + int madeira_fg = params->ret_pso ? -1 : madeira_compile_begin(); /* madeira-duo warm-yield */ if (!params->ret_pso && madeira_arch) { madeira_ovl_note_miss(); /* madeira-duo overlay-shader */ params->ret_pso = madeira_arch_create(device, descriptor, 1, options, &err); @@ -2246,6 +2319,7 @@ _MTLDevice_newComputePipelineState(void *obj) { (obj_handle_t)[device newComputePipelineStateWithDescriptor:descriptor options:options reflection:nil error:&err]; if (madeira_arch && params->ret_pso && !err) madeira_arch_add(descriptor, 1); } + madeira_compile_end(madeira_fg); /* madeira-duo warm-yield */ [madeira_arch release]; params->ret_error = (obj_handle_t)err; if (!err && info->binary_archive_for_serialization) { @@ -2596,6 +2670,7 @@ _MTLDevice_newRenderPipelineState(void *obj) { [descriptor release]; return STATUS_SUCCESS; } + int madeira_fg = params->ret_pso ? -1 : madeira_compile_begin(); /* madeira-duo warm-yield */ if (!params->ret_pso && madeira_arch) { madeira_ovl_note_miss(); /* madeira-duo overlay-shader */ params->ret_pso = madeira_arch_create((id)params->device, descriptor, 0, options, &err); @@ -2608,6 +2683,7 @@ _MTLDevice_newRenderPipelineState(void *obj) { error:&err]; if (madeira_arch && params->ret_pso && !err) madeira_arch_add(descriptor, 0); } + madeira_compile_end(madeira_fg); /* madeira-duo warm-yield */ [madeira_arch release]; params->ret_error = (obj_handle_t)err; if (!err && info->binary_archive_for_serialization) { @@ -2726,6 +2802,7 @@ _MTLDevice_newRenderPipelineStateVD(void *obj) { [descriptor release]; return STATUS_SUCCESS; } + int madeira_fg = params->ret_pso ? -1 : madeira_compile_begin(); /* madeira-duo warm-yield */ if (!params->ret_pso && madeira_arch) { madeira_ovl_note_miss(); /* madeira-duo overlay-shader */ params->ret_pso = madeira_arch_create((id)params->device, descriptor, 0, options, &err); @@ -2738,6 +2815,7 @@ _MTLDevice_newRenderPipelineStateVD(void *obj) { error:&err]; if (madeira_arch && params->ret_pso && !err) madeira_arch_add(descriptor, 0); } + madeira_compile_end(madeira_fg); /* madeira-duo warm-yield */ [madeira_arch release]; params->ret_error = (obj_handle_t)err; if (!err && info->binary_archive_for_serialization) { @@ -7568,9 +7646,10 @@ static void madeira_pso_warm_note(uint64_t ns, int ok) { double msh = (double)atomic_load_explicit(&madeira_pso_warm_ns_hits, memory_order_relaxed) / 1e6; atomic_store_explicit(&madeira_pso_warm_said_ns, now, memory_order_relaxed); fprintf(stderr, "[pso-warm] madeira-bcd %ld of %ld pipelines warmed: %ld compiled (avg %.1f ms), " - "%ld already in Metal's cache (avg %.2f ms), %ld failed; %ld waiting\n", + "%ld already in Metal's cache (avg %.2f ms), %ld failed; %ld waiting; %ld waited for the game's compiles (%.1f s)\n", done, sent, compiled, compiled > 0 ? msc / compiled : 0.0, hits, hits ? msh / hits : 0.0, failed, - sent > done ? sent - done : 0); + sent > done ? sent - done : 0, atomic_load_explicit(&madeira_warm_yields, memory_order_relaxed), + (double)atomic_load_explicit(&madeira_warm_yield_ns, memory_order_relaxed) / 1e9); } } From 03d4720d9b1a01520c33f9e926d979d201ae2a47 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Wed, 18 Nov 2026 01:29:21 +1100 Subject: [PATCH 6/6] winemetal: pso-warm counts a warm-up as a hit when the saved chunks had it [pso-warm] classed a warm-up by its wall time: under 3 ms a cache hit, anything longer a compile. The warm-ups run on utility-QoS queues, and while a game saturates the cores a utility thread waits seconds for one, so lookups the saved chunks answered were reported as compiles. Path of Exile 2, 18 Nov 2026: "488 compiled (avg 1045.9 ms)" in a session where the archive's own counters show about 57 pipelines pso-warm really had to add (295 misses, 238 of them for the game). The figure read as hundreds of compute pipelines compiled again every session, which they are not. A warm-up is now a hit when the saved-chunk lookup returned its pipeline (a thread-local set by madeira_arch_note_hit around the warm-up's own create). With no saved chunks in use the 3 ms rule stays. No behaviour change; the [pso-warm] line keeps its wording. Signed-off-by: Shitiz Garg Co-Authored-By: Claude Fable 5.2 --- src/winemetal/unix/winemetal_unix.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/winemetal/unix/winemetal_unix.c b/src/winemetal/unix/winemetal_unix.c index 514ddd7b1..be8f27d85 100644 --- a/src/winemetal/unix/winemetal_unix.c +++ b/src/winemetal/unix/winemetal_unix.c @@ -1963,8 +1963,13 @@ static void madeira_arch_say(const char *what) { : 0.0); } +/* madeira-duo: set by every pipeline the saved chunks answered; pso-warm reads it around + * its own create to tell a hit from a compile (its wall time can't: a utility-QoS warm-up + * waits seconds for a core while a game saturates them, so hits looked like compiles). */ +static _Thread_local int madeira_pso_warm_hit; static void madeira_arch_note_hit(void) { long n = atomic_fetch_add_explicit(&madeira_arch_hits, 1, memory_order_relaxed) + 1; + madeira_pso_warm_hit = 1; if (n == 1 || (n % 2000) == 0) madeira_arch_say(n == 1 ? "first pipeline from the saved chunks" : "so far"); } @@ -7625,14 +7630,15 @@ static int madeira_pso_warm_setup(void) { } /* One finished warm-up: tally it, and report every 500 and whenever the - * backlog empties (at most every 10 s). A build under 3 ms was a cache hit. */ -static void madeira_pso_warm_note(uint64_t ns, int ok) { + * backlog empties (at most every 10 s). hit: the saved chunks had it. With no + * saved chunks in use, a build under 3 ms was a hit in Metal's own cache. */ +static void madeira_pso_warm_note(uint64_t ns, int ok, int hit) { long done = atomic_fetch_add_explicit(&madeira_pso_warm_done, 1, memory_order_relaxed) + 1; long sent = atomic_load_explicit(&madeira_pso_warm_sent, memory_order_relaxed); uint64_t now = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); if (!ok) atomic_fetch_add_explicit(&madeira_pso_warm_failed, 1, memory_order_relaxed); - else if (ns < 3000000) { + else if (hit || (!madeira_arch_in_use() && ns < 3000000)) { atomic_fetch_add_explicit(&madeira_pso_warm_hits, 1, memory_order_relaxed); atomic_fetch_add_explicit(&madeira_pso_warm_ns_hits, ns, memory_order_relaxed); } else @@ -7698,6 +7704,7 @@ static uint32_t madeira_pso_warm_submit(obj_handle_t device, const void *info, c uint64_t t0 = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); obj_handle_t pso = 0; madeira_pso_warm_self = 1; /* madeira-duo overlay-shader: not a miss the game waits for */ + madeira_pso_warm_hit = 0; if (kind == 2) { struct unixcall_mtldevice_newcomputepso p; memset(&p, 0, sizeof p); @@ -7718,7 +7725,7 @@ static uint32_t madeira_pso_warm_submit(obj_handle_t device, const void *info, c pso = p.ret_pso; } madeira_pso_warm_self = 0; - madeira_pso_warm_note(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - t0, pso != 0); + madeira_pso_warm_note(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - t0, pso != 0, madeira_pso_warm_hit); if (pso) [(id)pso release]; if (f0) [(id)f0 release]; if (f1) [(id)f1 release];