From d4aec472f0bfe17b34dfd4a4407de2429ecbacdf Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Wed, 4 Nov 2026 05:40:40 +1100 Subject: [PATCH 01/76] list-journal and api-census (opt-in) list-journal = 1: the hot ID3D12GraphicsCommandList methods and ID3D12Resource::GetGPUVirtualAddress run as x64 code inside the hybrid d3d12.dll (lld links the x64 objects into the ARM64EC image) and append to a per-list journal; the ARM64EC side replays it through the same list_* functions at Close, when full, or before any method that is not journaled. PoE2: x64->native crossings about 10x lower (d3d12 share 57% -> 4%). The x64 code never addresses the DLL's globals: Madeira runs ARM64EC code from a JIT-pool copy of the image, .data included, while x64 code runs at the PE address. State is reached through the object (vtable[-1] holds a struct mad_jr_ctx). api-census = 1: [d3d12-census] lines every 5 s with calls per frame by method and how many state sets repeat what is bound. Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/pe/gen_vtables.py | 6 + madeira-d3d12/src/pe/madeira_d3d12.c | 62 +++- madeira-d3d12/src/pe/madeira_d3d12_stubs.h | 271 +++++++++++++++ madeira-d3d12/src/pe/madeira_list_journal.h | 104 ++++++ .../src/pe/madeira_list_journal.inc.c | 321 ++++++++++++++++++ .../src/pe/madeira_list_journal.x64.S | 109 ++++++ .../src/pe/madeira_list_journal.x64.c | 234 +++++++++++++ 7 files changed, 1096 insertions(+), 11 deletions(-) create mode 100644 madeira-d3d12/src/pe/madeira_list_journal.h create mode 100644 madeira-d3d12/src/pe/madeira_list_journal.inc.c create mode 100644 madeira-d3d12/src/pe/madeira_list_journal.x64.S create mode 100644 madeira-d3d12/src/pe/madeira_list_journal.x64.c diff --git a/madeira-d3d12/src/pe/gen_vtables.py b/madeira-d3d12/src/pe/gen_vtables.py index 400d73e546..ee5ba4a2e9 100644 --- a/madeira-d3d12/src/pe/gen_vtables.py +++ b/madeira-d3d12/src/pe/gen_vtables.py @@ -144,6 +144,12 @@ def emit(header_path, out_path): L.append(" v->%s = stub_%s_%s;" % (name, iface, name)) L.append("}") L.append("") + # Slot names in vtable order, for logs that count calls per slot (api-census). + L.append("static const char *const madeira_slots_%s[%d] __attribute__((unused)) = {" % (iface, len(methods))) + for _, name, _ in methods: + L.append(' "%s",' % name) + L.append("};") + L.append("") L.append("#endif /* MADEIRA_D3D12_STUBS_H */") open(out_path, "w").write("\n".join(L) + "\n") diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index 65df9a089d..fa289ba561 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -39,6 +39,8 @@ #include "madeira_d3d12_stubs.h" #include "madeira_ir_abi.h" #include "madeira_graphics_entry.h" +#include +#include "madeira_list_journal.h" /* list-journal, api-census */ /* madeira-bcd: MAD_BUILD_ID (build-pe.sh passes it from the environment) names the build, * so a log says which runtime ran. */ @@ -1935,11 +1937,25 @@ struct mad_cmd { #define MAD_ARG_DRAWINFO_OFF 544u /* IRRuntimeDrawInfo (24 bytes; first uint16 = index type) at kIRArgumentBufferUniformsBindPoint */ #define MAD_ARG_VBTABLE_OFF 576u /* ml927: IRRuntimeVertexBuffers (31 x {addr, length, stride} = 496 bytes) at kIRVertexBufferBindPoint, object stage */ +/* list-journal with api-census: what a list has bound, to count state sets that + * change nothing (madeira_list_journal.inc.c) */ +struct mad_jr_seen { + const void *pso, *rs[2], *heaps[2]; + UINT64 root[2][16]; + UINT16 root_valid[2]; + UINT topology; UINT8 topology_valid, ib_valid, vb_valid, vp_valid, sc_valid; + D3D12_INDEX_BUFFER_VIEW ib; + D3D12_VERTEX_BUFFER_VIEW vb[4]; + D3D12_VIEWPORT vp; + D3D12_RECT sc; +}; + struct mad_list { ID3D12GraphicsCommandList7Vtbl *vtbl; /* ml1144: full List7 slot table, List1..7 answered; ml1300: List8's slot follows it (g_list_vtbl8) */ LONG refs; const IID *iid; const char *name; + struct mad_journal jr; /* list-journal: records of the x64 methods, replayed at the next flush (MAD_JR_OFFSET) */ D3D12_COMMAND_LIST_TYPE type; struct mad_alloc *alloc; int closed; @@ -1966,6 +1982,7 @@ struct mad_list { * the last latch per parameter (its table and cdata offset + 1) */ struct mad_rootsig *rec_rs[2]; UINT64 rec_tab[2][MAD_ROOT_PARAM_MAX]; struct mad_heap *rec_heap; UINT64 lat_va[2][MAD_ROOT_PARAM_MAX]; unsigned lat_data[2][MAD_ROOT_PARAM_MAX]; + struct mad_jr_seen jr_seen; /* list-journal + api-census */ }; static struct mad_cmd *mad_list_push(struct mad_list *l, enum mad_ck kind) { @@ -2012,6 +2029,7 @@ static ULONG STDMETHODCALLTYPE list_Release(ID3D12GraphicsCommandList *This) { for (unsigned k = 0; k < l->nrings; k++) NSObject_release(l->rings[k]); if (l->nrings) InterlockedExchangeAdd(&g_ring_chunks, -(LONG)l->nrings); /* madeira-bcd metal-gap: live chunks */ free(l->rings); free(l->ring_cpu); free(l->ring_gpu); free(l->cmds); free(l->used); free(l->cdata); + free(l->jr.buf); /* list-journal: empty here (Release goes through a trampoline that flushes) */ free(l); } return (ULONG)r; @@ -2046,6 +2064,7 @@ static HRESULT STDMETHODCALLTYPE list_Reset(ID3D12GraphicsCommandList *This, l->ncdata = 0; l->rec_rs[0] = l->rec_rs[1] = NULL; l->rec_heap = NULL; /* madeira-bcd static-cbv */ memset(l->rec_tab, 0, sizeof l->rec_tab); memset(l->lat_va, 0, sizeof l->lat_va); memset(l->lat_data, 0, sizeof l->lat_data); + memset(&l->jr_seen, 0, sizeof l->jr_seen); /* list-journal + api-census */ mad_list_rings_rewind(l); /* ml1061: only reuses chunks the GPU has finished with */ return S_OK; } @@ -10722,6 +10741,7 @@ static void mad_perf_cb(obj_handle_t cb, double wait_s) { } mad_perf_unlock(); } +static void mad_jr_report(LONG presents, double wall); /* list-journal, api-census */ static void mad_perf_present(void) { LARGE_INTEGER now, fq; double wall; if (g_perf_enabled <= 0) return; @@ -10735,6 +10755,7 @@ static void mad_perf_present(void) { wall, g_perf_presents, g_perf_presents / wall, g_perf_cbs, g_perf_gpu_union * 1000, 100.0 * g_perf_gpu_union / wall, g_perf_gpu_sum * 1000, g_perf_wait_s * 1000, 100.0 * g_perf_wait_s / wall, g_perf_presents ? g_perf_gpu_union * 1000 / g_perf_presents : 0.0, g_perf_presents ? g_perf_wait_s * 1000 / g_perf_presents : 0.0); + mad_jr_report(g_perf_presents, wall); /* api-census */ { /* ml1116: encoder fence traffic per frame (mode 2 should cut waits well below updates) */ static LONG lw, lu, lb; LONG cw = g_fence_waits, cu = g_fence_updates, cb = g_barrier_seen; d3d12_log("[perf] ml1119 caller thread per frame: ExecuteCommandLists %.2f ms, Present %.2f ms (frame %.1f ms)\n", @@ -11508,7 +11529,8 @@ static void mad_list_wait_idle(struct mad_list *l) { -static ID3D12Device10Vtbl g_device_vtbl; +static struct { void *jr_ctx; ID3D12Device10Vtbl v; } g_device_vtbl_jr; /* list-journal / api-census: jr_ctx, just before the slots, is how the x64 trampolines find their state */ +#define g_device_vtbl (g_device_vtbl_jr.v) /* Keep the normal implementation, including submission ordering, behind a * typed compiler-generated x64 entry when an x64 overlay needs to patch it. */ MAD_X64_GRAPHICS_ENTRY void STDMETHODCALLTYPE @@ -11516,19 +11538,26 @@ mad_x64_ExecuteCommandLists(ID3D12CommandQueue *This, UINT count, ID3D12CommandL queue_ExecuteCommandLists(This, count, lists); } -static ID3D12CommandQueueVtbl g_queue_vtbl; -static ID3D12CommandAllocatorVtbl g_alloc_vtbl; +static struct { void *jr_ctx; ID3D12CommandQueueVtbl v; } g_queue_vtbl_jr; /* list-journal / api-census: jr_ctx, just before the slots, is how the x64 trampolines find their state */ +#define g_queue_vtbl (g_queue_vtbl_jr.v) +static struct { void *jr_ctx; ID3D12CommandAllocatorVtbl v; } g_alloc_vtbl_jr; /* list-journal / api-census: jr_ctx, just before the slots, is how the x64 trampolines find their state */ +#define g_alloc_vtbl (g_alloc_vtbl_jr.v) /* ml1300: ID3D12GraphicsCommandList8 is List7 plus OMSetFrontAndBackStencilRef. * The toolchain's d3d12.h stops at List7, so the List8 slot is appended after * the List7 table; g_list_vtbl names that List7 part for every assignment below. * Final Fantasy Tactics - The Ivalice Chronicles creates its command lists as * List8 and treats E_NOINTERFACE as a lost device. */ static struct { - ID3D12GraphicsCommandList7Vtbl v7; - void (STDMETHODCALLTYPE *OMSetFrontAndBackStencilRef)(ID3D12GraphicsCommandList *This, UINT front, UINT back); -} g_list_vtbl8; + void *jr_ctx; /* list-journal / api-census: read by the x64 trampolines (madeira_list_journal.h) */ + struct { + ID3D12GraphicsCommandList7Vtbl v7; + void (STDMETHODCALLTYPE *OMSetFrontAndBackStencilRef)(ID3D12GraphicsCommandList *This, UINT front, UINT back); + } t; +} g_list_vtbl8_jr; +#define g_list_vtbl8 (g_list_vtbl8_jr.t) #define g_list_vtbl (g_list_vtbl8.v7) -static ID3D12FenceVtbl g_fence_vtbl; +static struct { void *jr_ctx; ID3D12FenceVtbl v; } g_fence_vtbl_jr; /* list-journal / api-census: jr_ctx, just before the slots, is how the x64 trampolines find their state */ +#define g_fence_vtbl (g_fence_vtbl_jr.v) static HRESULT STDMETHODCALLTYPE device_QI(ID3D12Device *This, REFIID riid, void **out) { HRESULT hr; @@ -14507,7 +14536,8 @@ mad_x64_GetDesc(ID3D12CommandQueue *This, D3D12_COMMAND_QUEUE_DESC *ret) { } /* ---- resource ------------------------------------------------------------ */ -static ID3D12Resource2Vtbl g_res_vtbl; +static struct { void *jr_ctx; ID3D12Resource2Vtbl v; } g_res_vtbl_jr; /* list-journal / api-census: jr_ctx, just before the slots, is how the x64 trampolines find their state */ +#define g_res_vtbl (g_res_vtbl_jr.v) /* ml1132: every change to the address index is bracketed by these (live_lock * held, so writers are already serialised). The count is odd while the index @@ -15403,9 +15433,12 @@ static HRESULT STDMETHODCALLTYPE device_CreatePlacedResource(ID3D12Device *This, /* ---- root signature, pipeline state, descriptor heap --------------------- */ -static ID3D12RootSignatureVtbl g_rootsig_vtbl; -static ID3D12PipelineStateVtbl g_pso_vtbl; -static ID3D12DescriptorHeapVtbl g_heap_vtbl; +static struct { void *jr_ctx; ID3D12RootSignatureVtbl v; } g_rootsig_vtbl_jr; /* list-journal / api-census: jr_ctx, just before the slots, is how the x64 trampolines find their state */ +#define g_rootsig_vtbl (g_rootsig_vtbl_jr.v) +static struct { void *jr_ctx; ID3D12PipelineStateVtbl v; } g_pso_vtbl_jr; /* list-journal / api-census: jr_ctx, just before the slots, is how the x64 trampolines find their state */ +#define g_pso_vtbl (g_pso_vtbl_jr.v) +static struct { void *jr_ctx; ID3D12DescriptorHeapVtbl v; } g_heap_vtbl_jr; /* list-journal / api-census: jr_ctx, just before the slots, is how the x64 trampolines find their state */ +#define g_heap_vtbl (g_heap_vtbl_jr.v) static HRESULT STDMETHODCALLTYPE rootsig_QI(ID3D12RootSignature *T, REFIID r, void **o) { return mad_qi((struct mad_obj *)T, r, o, 1); } @@ -21218,7 +21251,13 @@ static HRESULT STDMETHODCALLTYPE rootsig_GetDevice(ID3D12RootSignature *This, RE } /* ---- vtable construction ------------------------------------------------- */ +#include "madeira_list_journal.inc.c" /* list-journal, api-census: after the list_* methods it replays */ + static void build_vtables(void) { + /* list-journal / api-census: the tables now hold trampolines another thread may be + * recording through; refilling them would let a call skip its list's flush. The + * configuration they depend on does not change within a process. */ + if (g_jr_installed) return; static LONG done; if (InterlockedCompareExchange(&done, 1, 0) != 0) return; @@ -21578,6 +21617,7 @@ __declspec(dllexport) HRESULT WINAPI MadeiraD3D12CreateDevice(IUnknown *adapter, return E_FAIL; } mad_quiet_log_init(); /* madeira-bcd quiet-log */ + mad_jr_install(); /* list-journal, api-census: over the tables build_vtables just filled */ HRESULT hr = device_QI((ID3D12Device *)d, riid, device); device_Release((ID3D12Device *)d); if (SUCCEEDED(hr)) d3d12_log("[madeira-d3d12] device created: %s\n", MadeiraD3D12GetBuildMarker()); diff --git a/madeira-d3d12/src/pe/madeira_d3d12_stubs.h b/madeira-d3d12/src/pe/madeira_d3d12_stubs.h index cbffd9be27..effa391c89 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12_stubs.h +++ b/madeira-d3d12/src/pe/madeira_d3d12_stubs.h @@ -399,6 +399,88 @@ static void madeira_fill_ID3D12Device10(ID3D12Device10Vtbl *v) { v->CreateReservedResource2 = stub_ID3D12Device10_CreateReservedResource2; } +static const char *const madeira_slots_ID3D12Device10[79] __attribute__((unused)) = { + "QueryInterface", + "AddRef", + "Release", + "GetPrivateData", + "SetPrivateData", + "SetPrivateDataInterface", + "SetName", + "GetNodeCount", + "CreateCommandQueue", + "CreateCommandAllocator", + "CreateGraphicsPipelineState", + "CreateComputePipelineState", + "CreateCommandList", + "CheckFeatureSupport", + "CreateDescriptorHeap", + "GetDescriptorHandleIncrementSize", + "CreateRootSignature", + "CreateConstantBufferView", + "CreateShaderResourceView", + "CreateUnorderedAccessView", + "CreateRenderTargetView", + "CreateDepthStencilView", + "CreateSampler", + "CopyDescriptors", + "CopyDescriptorsSimple", + "GetResourceAllocationInfo", + "GetCustomHeapProperties", + "CreateCommittedResource", + "CreateHeap", + "CreatePlacedResource", + "CreateReservedResource", + "CreateSharedHandle", + "OpenSharedHandle", + "OpenSharedHandleByName", + "MakeResident", + "Evict", + "CreateFence", + "GetDeviceRemovedReason", + "GetCopyableFootprints", + "CreateQueryHeap", + "SetStablePowerState", + "CreateCommandSignature", + "GetResourceTiling", + "GetAdapterLuid", + "CreatePipelineLibrary", + "SetEventOnMultipleFenceCompletion", + "SetResidencyPriority", + "CreatePipelineState", + "OpenExistingHeapFromAddress", + "OpenExistingHeapFromFileMapping", + "EnqueueMakeResident", + "CreateCommandList1", + "CreateProtectedResourceSession", + "CreateCommittedResource1", + "CreateHeap1", + "CreateReservedResource1", + "GetResourceAllocationInfo1", + "CreateLifetimeTracker", + "RemoveDevice", + "EnumerateMetaCommands", + "EnumerateMetaCommandParameters", + "CreateMetaCommand", + "CreateStateObject", + "GetRaytracingAccelerationStructurePrebuildInfo", + "CheckDriverMatchingIdentifier", + "SetBackgroundProcessingMode", + "AddToStateObject", + "CreateProtectedResourceSession1", + "GetResourceAllocationInfo2", + "CreateCommittedResource2", + "CreatePlacedResource1", + "CreateSamplerFeedbackUnorderedAccessView", + "GetCopyableFootprints1", + "CreateShaderCacheSession", + "ShaderCacheControl", + "CreateCommandQueue1", + "CreateCommittedResource3", + "CreatePlacedResource2", + "CreateReservedResource2", +}; + /* ---- ID3D12CommandQueue: 19 slots ---- */ static HRESULT STDMETHODCALLTYPE stub_ID3D12CommandQueue_QueryInterface(ID3D12CommandQueue *This, REFIID riid, void **ppvObject) { madeira_d3d12_note_unimplemented("ID3D12CommandQueue", "QueryInterface"); @@ -489,6 +571,28 @@ static void madeira_fill_ID3D12CommandQueue(ID3D12CommandQueueVtbl *v) { v->GetDesc = stub_ID3D12CommandQueue_GetDesc; } +static const char *const madeira_slots_ID3D12CommandQueue[19] __attribute__((unused)) = { + "QueryInterface", + "AddRef", + "Release", + "GetPrivateData", + "SetPrivateData", + "SetPrivateDataInterface", + "SetName", + "GetDevice", + "UpdateTileMappings", + "CopyTileMappings", + "ExecuteCommandLists", + "SetMarker", + "BeginEvent", + "EndEvent", + "Signal", + "Wait", + "GetTimestampFrequency", + "GetClockCalibration", + "GetDesc", +}; + /* ---- ID3D12CommandAllocator: 9 slots ---- */ static HRESULT STDMETHODCALLTYPE stub_ID3D12CommandAllocator_QueryInterface(ID3D12CommandAllocator *This, REFIID riid, void **ppvObject) { madeira_d3d12_note_unimplemented("ID3D12CommandAllocator", "QueryInterface"); @@ -535,6 +639,18 @@ static void madeira_fill_ID3D12CommandAllocator(ID3D12CommandAllocatorVtbl *v) { v->Reset = stub_ID3D12CommandAllocator_Reset; } +static const char *const madeira_slots_ID3D12CommandAllocator[9] __attribute__((unused)) = { + "QueryInterface", + "AddRef", + "Release", + "GetPrivateData", + "SetPrivateData", + "SetPrivateDataInterface", + "SetName", + "GetDevice", + "Reset", +}; + /* ---- ID3D12GraphicsCommandList7: 81 slots ---- */ static HRESULT STDMETHODCALLTYPE stub_ID3D12GraphicsCommandList7_QueryInterface(ID3D12GraphicsCommandList7 *This, REFIID riid, void **ppvObject) { madeira_d3d12_note_unimplemented("ID3D12GraphicsCommandList7", "QueryInterface"); @@ -871,6 +987,90 @@ static void madeira_fill_ID3D12GraphicsCommandList7(ID3D12GraphicsCommandList7Vt v->Barrier = stub_ID3D12GraphicsCommandList7_Barrier; } +static const char *const madeira_slots_ID3D12GraphicsCommandList7[81] __attribute__((unused)) = { + "QueryInterface", + "AddRef", + "Release", + "GetPrivateData", + "SetPrivateData", + "SetPrivateDataInterface", + "SetName", + "GetDevice", + "GetType", + "Close", + "Reset", + "ClearState", + "DrawInstanced", + "DrawIndexedInstanced", + "Dispatch", + "CopyBufferRegion", + "CopyTextureRegion", + "CopyResource", + "CopyTiles", + "ResolveSubresource", + "IASetPrimitiveTopology", + "RSSetViewports", + "RSSetScissorRects", + "OMSetBlendFactor", + "OMSetStencilRef", + "SetPipelineState", + "ResourceBarrier", + "ExecuteBundle", + "SetDescriptorHeaps", + "SetComputeRootSignature", + "SetGraphicsRootSignature", + "SetComputeRootDescriptorTable", + "SetGraphicsRootDescriptorTable", + "SetComputeRoot32BitConstant", + "SetGraphicsRoot32BitConstant", + "SetComputeRoot32BitConstants", + "SetGraphicsRoot32BitConstants", + "SetComputeRootConstantBufferView", + "SetGraphicsRootConstantBufferView", + "SetComputeRootShaderResourceView", + "SetGraphicsRootShaderResourceView", + "SetComputeRootUnorderedAccessView", + "SetGraphicsRootUnorderedAccessView", + "IASetIndexBuffer", + "IASetVertexBuffers", + "SOSetTargets", + "OMSetRenderTargets", + "ClearDepthStencilView", + "ClearRenderTargetView", + "ClearUnorderedAccessViewUint", + "ClearUnorderedAccessViewFloat", + "DiscardResource", + "BeginQuery", + "EndQuery", + "ResolveQueryData", + "SetPredication", + "SetMarker", + "BeginEvent", + "EndEvent", + "ExecuteIndirect", + "AtomicCopyBufferUINT", + "AtomicCopyBufferUINT64", + "OMSetDepthBounds", + "SetSamplePositions", + "ResolveSubresourceRegion", + "SetViewInstanceMask", + "WriteBufferImmediate", + "SetProtectedResourceSession", + "BeginRenderPass", + "EndRenderPass", + "InitializeMetaCommand", + "ExecuteMetaCommand", + "BuildRaytracingAccelerationStructure", + "EmitRaytracingAccelerationStructurePostbuildInfo", + "CopyRaytracingAccelerationStructure", + "SetPipelineState1", + "DispatchRays", + "RSSetShadingRate", + "RSSetShadingRateImage", + "DispatchMesh", + "Barrier", +}; + /* ---- ID3D12Fence: 11 slots ---- */ static HRESULT STDMETHODCALLTYPE stub_ID3D12Fence_QueryInterface(ID3D12Fence *This, REFIID riid, void **ppvObject) { madeira_d3d12_note_unimplemented("ID3D12Fence", "QueryInterface"); @@ -927,6 +1127,20 @@ static void madeira_fill_ID3D12Fence(ID3D12FenceVtbl *v) { v->Signal = stub_ID3D12Fence_Signal; } +static const char *const madeira_slots_ID3D12Fence[11] __attribute__((unused)) = { + "QueryInterface", + "AddRef", + "Release", + "GetPrivateData", + "SetPrivateData", + "SetPrivateDataInterface", + "SetName", + "GetDevice", + "GetCompletedValue", + "SetEventOnCompletion", + "Signal", +}; + /* ---- ID3D12Resource2: 17 slots ---- */ static HRESULT STDMETHODCALLTYPE stub_ID3D12Resource2_QueryInterface(ID3D12Resource2 *This, REFIID riid, void **ppvObject) { madeira_d3d12_note_unimplemented("ID3D12Resource2", "QueryInterface"); @@ -1012,6 +1226,26 @@ static void madeira_fill_ID3D12Resource2(ID3D12Resource2Vtbl *v) { v->GetDesc1 = stub_ID3D12Resource2_GetDesc1; } +static const char *const madeira_slots_ID3D12Resource2[17] __attribute__((unused)) = { + "QueryInterface", + "AddRef", + "Release", + "GetPrivateData", + "SetPrivateData", + "SetPrivateDataInterface", + "SetName", + "GetDevice", + "Map", + "Unmap", + "GetDesc", + "GetGPUVirtualAddress", + "WriteToSubresource", + "ReadFromSubresource", + "GetHeapProperties", + "GetProtectedResourceSession", + "GetDesc1", +}; + /* ---- ID3D12RootSignature: 8 slots ---- */ static HRESULT STDMETHODCALLTYPE stub_ID3D12RootSignature_QueryInterface(ID3D12RootSignature *This, REFIID riid, void **ppvObject) { madeira_d3d12_note_unimplemented("ID3D12RootSignature", "QueryInterface"); @@ -1053,6 +1287,17 @@ static void madeira_fill_ID3D12RootSignature(ID3D12RootSignatureVtbl *v) { v->GetDevice = stub_ID3D12RootSignature_GetDevice; } +static const char *const madeira_slots_ID3D12RootSignature[8] __attribute__((unused)) = { + "QueryInterface", + "AddRef", + "Release", + "GetPrivateData", + "SetPrivateData", + "SetPrivateDataInterface", + "SetName", + "GetDevice", +}; + /* ---- ID3D12PipelineState: 9 slots ---- */ static HRESULT STDMETHODCALLTYPE stub_ID3D12PipelineState_QueryInterface(ID3D12PipelineState *This, REFIID riid, void **ppvObject) { madeira_d3d12_note_unimplemented("ID3D12PipelineState", "QueryInterface"); @@ -1099,6 +1344,18 @@ static void madeira_fill_ID3D12PipelineState(ID3D12PipelineStateVtbl *v) { v->GetCachedBlob = stub_ID3D12PipelineState_GetCachedBlob; } +static const char *const madeira_slots_ID3D12PipelineState[9] __attribute__((unused)) = { + "QueryInterface", + "AddRef", + "Release", + "GetPrivateData", + "SetPrivateData", + "SetPrivateDataInterface", + "SetName", + "GetDevice", + "GetCachedBlob", +}; + /* ---- ID3D12DescriptorHeap: 11 slots ---- */ static HRESULT STDMETHODCALLTYPE stub_ID3D12DescriptorHeap_QueryInterface(ID3D12DescriptorHeap *This, REFIID riid, void **ppvObject) { madeira_d3d12_note_unimplemented("ID3D12DescriptorHeap", "QueryInterface"); @@ -1155,4 +1412,18 @@ static void madeira_fill_ID3D12DescriptorHeap(ID3D12DescriptorHeapVtbl *v) { v->GetGPUDescriptorHandleForHeapStart = stub_ID3D12DescriptorHeap_GetGPUDescriptorHandleForHeapStart; } +static const char *const madeira_slots_ID3D12DescriptorHeap[11] __attribute__((unused)) = { + "QueryInterface", + "AddRef", + "Release", + "GetPrivateData", + "SetPrivateData", + "SetPrivateDataInterface", + "SetName", + "GetDevice", + "GetDesc", + "GetCPUDescriptorHandleForHeapStart", + "GetGPUDescriptorHandleForHeapStart", +}; + #endif /* MADEIRA_D3D12_STUBS_H */ diff --git a/madeira-d3d12/src/pe/madeira_list_journal.h b/madeira-d3d12/src/pe/madeira_list_journal.h new file mode 100644 index 0000000000..a214223c84 --- /dev/null +++ b/madeira-d3d12/src/pe/madeira_list_journal.h @@ -0,0 +1,104 @@ +/* madeira-d3d12 list-journal: shared between the ARM64EC runtime and its x64 part. + * + * Every ID3D12GraphicsCommandList method an x64 game calls is a crossing from + * emulated x64 code into ARM64EC code. Path of Exile 2 records about ten of them + * per draw, about a million a second, and the crossing costs more than the + * recording itself. With madeira.cfg list-journal = 1 the hot recording methods + * are x64 code inside this DLL (madeira_list_journal.x64.c): they append the + * call and its arguments to a per-list journal, and the ARM64EC runtime replays + * the journal through the same list_* functions as before when the list is + * closed, when the journal is full, or before any method that is not journaled + * (madeira_list_journal.x64.S sends every other slot through a check first). The + * methods see the same calls in the same order; only their timing moves to the + * flush. Methods that read CPU descriptors or other memory the game may change + * right after the call (OMSetRenderTargets, the Clear* methods, ...) are not + * journaled, and static-cbv (which reads descriptor tables while recording) + * turns the journal off. + * + * THE X64 CODE NEVER ADDRESSES THIS DLL'S GLOBALS. Madeira runs a hybrid DLL's + * ARM64EC code from a copy of the whole image in its JIT pool, .data included, + * while x64 code always runs at the PE address (FEX's [pool-rip-fix]): a + * RIP-relative load from x64 code reads the PE's .data, a stale copy the + * ARM64EC code never writes. So each vtable carries a pointer just before its + * first slot (jr_ctx, set by the ARM64EC side and so pointing into the copy it + * uses), and the x64 code reaches its state through the object: [rcx] is the + * vtable, [vtable - 8] the struct mad_jr_ctx. The build checks that the x64 + * objects reference no data symbol. + * + * Also included by the .S file: only preprocessor definitions outside the + * __ASSEMBLER__ guard. */ +#ifndef MADEIRA_LIST_JOURNAL_H +#define MADEIRA_LIST_JOURNAL_H + +/* struct mad_list keeps the journal right after the mad_obj prefix (vtbl, refs, + * iid, name); madeira_d3d12.c asserts both offsets. */ +#define MAD_JR_OFFSET 32 +#define MAD_JR_USED_OFFSET (MAD_JR_OFFSET + 8) +/* struct mad_resource: gpu_address, and GetGPUVirtualAddress's ID3D12Resource slot. */ +#define MAD_RES_GPU_ADDRESS_OFFSET 0x70 +#define MAD_RES_GVA_SLOT 11 + +/* struct mad_jr_ctx: slots per interface (List7's 81 plus List8's one is the most), + * and the byte offsets the trampolines use. */ +#define MAD_JR_SLOTS 96 +#define MAD_JR_CTX_CALLS (8 * MAD_JR_SLOTS) +#define MAD_JR_CTX_FLUSH (MAD_JR_CTX_CALLS + 4 * MAD_JR_SLOTS) +#define MAD_JR_CTX_CENSUS (MAD_JR_CTX_FLUSH + 8) + +#ifndef __ASSEMBLER__ +#include + +/* One per interface whose slots go through trampolines, in ARM64EC .data. */ +struct mad_jr_ctx { + void *target[MAD_JR_SLOTS]; /* the ARM64EC method behind each slot */ + uint32_t calls[MAD_JR_SLOTS]; /* api-census: calls per slot (plain increments, approximate) */ + void (*flush)(void *list); /* list only: replays a list's journal */ + uint8_t census; /* api-census on */ +}; + +struct mad_journal { + uint8_t *buf; /* records, 8-byte aligned; allocated by the first flush */ + uint32_t used, cap; /* bytes */ +}; + +/* One record: a head, then the payload; size covers both, a multiple of 8. */ +struct mad_jr_head { + uint16_t op; + uint16_t size; + uint32_t a; /* the first small argument of the call */ +}; + +enum mad_jr_op { + JR_PSO = 1, JR_ROOTSIG, JR_CROOTSIG, + JR_ROOT_CBV, JR_ROOT_SRV, JR_ROOT_UAV, JR_ROOT_TABLE, + JR_CROOT_CBV, JR_CROOT_SRV, JR_CROOT_UAV, JR_CROOT_TABLE, + JR_ROOT_CONST, JR_ROOT_CONSTS, JR_CROOT_CONST, JR_CROOT_CONSTS, + JR_TOPOLOGY, JR_IB, JR_IB_NULL, JR_VBS, JR_VIEWPORTS, JR_SCISSORS, + JR_STENCIL_REF, JR_BLEND_FACTOR, + JR_DRAW, JR_DRAW_INDEXED, JR_DISPATCH, JR_BARRIERS, JR_HEAPS, + JR_OP_COUNT +}; + +/* Limits above which a call is not journaled (the journal is flushed and the + * ARM64EC method called directly, as without the journal). */ +#define MAD_JR_MAX_CONSTS 64 +#define MAD_JR_MAX_VIEWS 32 +#define MAD_JR_MAX_RECTS 16 +#define MAD_JR_MAX_BARRIERS 32 +#define MAD_JR_MAX_HEAPS 4 +#define MAD_JR_BYTES (64 * 1024) + +/* The x64 methods, by List7 vtable slot (madeira_list_journal.x64.c). */ +struct mad_jr_method { + uint32_t slot; + void *fn; +}; + +/* Defined by the x64 code, read by the ARM64EC side (never the other way). */ +extern const struct mad_jr_method mad_jr_x64_methods[]; +extern void *const mad_jr_list_tramps[MAD_JR_SLOTS]; +extern void *const mad_jr_count_tramps[MAD_JR_SLOTS]; +extern char mad_res_gva_x64[]; +#endif + +#endif /* MADEIRA_LIST_JOURNAL_H */ diff --git a/madeira-d3d12/src/pe/madeira_list_journal.inc.c b/madeira-d3d12/src/pe/madeira_list_journal.inc.c new file mode 100644 index 0000000000..93993d89ce --- /dev/null +++ b/madeira-d3d12/src/pe/madeira_list_journal.inc.c @@ -0,0 +1,321 @@ +/* madeira-d3d12 list-journal, ARM64EC part (see madeira_list_journal.h). + * Included by madeira_d3d12.c after the list_* methods it replays. + * + * madeira.cfg list-journal = 1 (default 0): the hot command-list methods and + * ID3D12Resource::GetGPUVirtualAddress run as x64 code, without a crossing per + * call; the list replays its journal here. + * madeira.cfg api-census = 1 (default 0): every 5 s with the [perf] lines, a + * [d3d12-census] line counts the game's D3D12 calls per frame by method (all + * interfaces the runtime builds), and, with the journal, how many of its state + * sets repeat what is already bound. For finding work the game itself does that + * could be avoided. Both are read once, when the first device is created. */ + +/* The trampolines' state, one per interface; each vtable's jr_ctx points at its + * own (madeira_list_journal.h: the x64 code finds it through the object). */ +static struct mad_jr_ctx g_jr_list_ctx; +static struct mad_jr_ctx g_jr_ctx[8]; /* g_jr_counted, in order */ +static uint8_t g_jr_census; + +static int g_jr_on = -1; +static int g_jr_installed; /* build_vtables leaves the tables alone from then on */ +static LONG64 g_jr_ops[JR_OP_COUNT], g_jr_redundant[JR_OP_COUNT]; +static LONG64 g_jr_flushes, g_jr_records, g_jr_barrier_entries, g_jr_const_words; + +#define MAD_LIST_SLOT_COUNT (sizeof g_list_vtbl8 / sizeof(void *)) +_Static_assert(MAD_LIST_SLOT_COUNT <= MAD_JR_SLOTS, "list slots"); +_Static_assert(offsetof(struct mad_jr_ctx, calls) == MAD_JR_CTX_CALLS, "ctx calls offset (madeira_list_journal.h)"); +_Static_assert(offsetof(struct mad_jr_ctx, flush) == MAD_JR_CTX_FLUSH, "ctx flush offset"); +_Static_assert(offsetof(struct mad_jr_ctx, census) == MAD_JR_CTX_CENSUS, "ctx census offset"); +_Static_assert(offsetof(ID3D12Resource2Vtbl, GetGPUVirtualAddress) / sizeof(void *) == MAD_RES_GVA_SLOT, "GetGPUVirtualAddress slot"); +_Static_assert(offsetof(struct mad_list, jr) == MAD_JR_OFFSET, "journal offset (madeira_list_journal.h)"); +_Static_assert(offsetof(struct mad_list, jr.used) == MAD_JR_USED_OFFSET, "journal fill offset"); +_Static_assert(offsetof(struct mad_resource, gpu_address) == MAD_RES_GPU_ADDRESS_OFFSET, "resource gpu_address offset"); + +/* api-census with the journal: did this state set change anything? Per list, + * since the last Reset. */ +static int mad_jr_repeats(struct mad_list *l, const struct mad_jr_head *h) +{ + struct mad_jr_seen *s = &l->jr_seen; + const UINT64 *v = (const UINT64 *)(h + 1); + int bp, same; + switch (h->op) { + case JR_PSO: + same = s->pso == (const void *)(uintptr_t)v[0]; + s->pso = (const void *)(uintptr_t)v[0]; + return same; + case JR_ROOTSIG: case JR_CROOTSIG: + bp = h->op == JR_CROOTSIG; + same = s->rs[bp] == (const void *)(uintptr_t)v[0]; + if (!same) { s->rs[bp] = (const void *)(uintptr_t)v[0]; s->root_valid[bp] = 0; } + return same; + case JR_ROOT_CBV: case JR_ROOT_SRV: case JR_ROOT_UAV: case JR_ROOT_TABLE: + case JR_CROOT_CBV: case JR_CROOT_SRV: case JR_CROOT_UAV: case JR_CROOT_TABLE: + bp = h->op >= JR_CROOT_CBV; + if (h->a >= 16) return 0; + same = (s->root_valid[bp] >> h->a & 1) && s->root[bp][h->a] == v[0]; + s->root[bp][h->a] = v[0]; s->root_valid[bp] |= (UINT16)(1u << h->a); + return same; + case JR_TOPOLOGY: + same = s->topology_valid && s->topology == h->a; + s->topology = h->a; s->topology_valid = 1; + return same; + case JR_IB: + same = s->ib_valid && !memcmp(&s->ib, h + 1, sizeof s->ib); + memcpy(&s->ib, h + 1, sizeof s->ib); s->ib_valid = 1; + return same; + case JR_VBS: { + const UINT32 *p = (const UINT32 *)(h + 1); + UINT start = h->a, n = p[0], k; + const D3D12_VERTEX_BUFFER_VIEW *views = (const D3D12_VERTEX_BUFFER_VIEW *)(p + 2); + if (!p[1] || !n || start + n > 4) return 0; + same = 1; + for (k = 0; k < n; k++) { + if (!(s->vb_valid >> (start + k) & 1) || memcmp(&s->vb[start + k], &views[k], sizeof views[k])) same = 0; + s->vb[start + k] = views[k]; s->vb_valid |= (UINT8)(1u << (start + k)); + } + return same; + } + case JR_VIEWPORTS: + if (h->a != 1) return 0; + same = s->vp_valid && !memcmp(&s->vp, h + 1, sizeof s->vp); + memcpy(&s->vp, h + 1, sizeof s->vp); s->vp_valid = 1; + return same; + case JR_SCISSORS: + if (h->a != 1) return 0; + same = s->sc_valid && !memcmp(&s->sc, h + 1, sizeof s->sc); + memcpy(&s->sc, h + 1, sizeof s->sc); s->sc_valid = 1; + return same; + case JR_HEAPS: + if (h->a > 2) return 0; + same = !memcmp(s->heaps, h + 1, h->a * sizeof(void *)) && (h->a == 2 || !s->heaps[1]); + memset(s->heaps, 0, sizeof s->heaps); memcpy(s->heaps, h + 1, h->a * sizeof(void *)); + return same; + } + return 0; +} + +/* Replays the journal through the list_* methods, in order, then empties it. + * The first call allocates it. Runs on the thread recording the list. */ +static void mad_jr_flush(void *This) +{ + struct mad_list *l = (struct mad_list *)This; + struct mad_journal *j = &l->jr; + const UINT8 *p, *end; + LONG64 ops[JR_OP_COUNT] = { 0 }, repeats[JR_OP_COUNT] = { 0 }, records = 0, barriers = 0, words = 0; + ID3D12GraphicsCommandList *list = (ID3D12GraphicsCommandList *)This; + if (!j->buf) { + j->buf = malloc(MAD_JR_BYTES); + j->cap = j->buf ? MAD_JR_BYTES : 0; + j->used = 0; + return; + } + p = j->buf; end = j->buf + j->used; + while (p < end) { + const struct mad_jr_head *h = (const struct mad_jr_head *)p; + const UINT64 *v = (const UINT64 *)(h + 1); + const UINT32 *w = (const UINT32 *)(h + 1); + D3D12_GPU_DESCRIPTOR_HANDLE table; + switch (h->op) { + case JR_PSO: list_SetPipelineState(list, (ID3D12PipelineState *)(uintptr_t)v[0]); break; + case JR_ROOTSIG: list_SetGraphicsRootSignature(list, (ID3D12RootSignature *)(uintptr_t)v[0]); break; + case JR_CROOTSIG: list_SetComputeRootSignature(list, (ID3D12RootSignature *)(uintptr_t)v[0]); break; + case JR_ROOT_CBV: list_SetGraphicsRootConstantBufferView(list, h->a, v[0]); break; + case JR_ROOT_SRV: list_SetGraphicsRootShaderResourceView(list, h->a, v[0]); break; + case JR_ROOT_UAV: list_SetGraphicsRootUnorderedAccessView(list, h->a, v[0]); break; + case JR_ROOT_TABLE: table.ptr = v[0]; list_SetGraphicsRootDescriptorTable(list, h->a, table); break; + case JR_CROOT_CBV: list_SetComputeRootConstantBufferView(list, h->a, v[0]); break; + case JR_CROOT_SRV: list_SetComputeRootShaderResourceView(list, h->a, v[0]); break; + case JR_CROOT_UAV: list_SetComputeRootUnorderedAccessView(list, h->a, v[0]); break; + case JR_CROOT_TABLE: table.ptr = v[0]; list_SetComputeRootDescriptorTable(list, h->a, table); break; + case JR_ROOT_CONST: list_SetGraphicsRoot32BitConstant(list, h->a, w[0], w[1]); words++; break; + case JR_CROOT_CONST: list_SetComputeRoot32BitConstant(list, h->a, w[0], w[1]); words++; break; + case JR_ROOT_CONSTS: list_SetGraphicsRoot32BitConstants(list, h->a, w[0], w[0] ? w + 2 : NULL, w[1]); words += w[0]; break; + case JR_CROOT_CONSTS: list_SetComputeRoot32BitConstants(list, h->a, w[0], w[0] ? w + 2 : NULL, w[1]); words += w[0]; break; + case JR_TOPOLOGY: list_IASetPrimitiveTopology(list, (D3D12_PRIMITIVE_TOPOLOGY)h->a); break; + case JR_IB: list_IASetIndexBuffer(list, (const D3D12_INDEX_BUFFER_VIEW *)(h + 1)); break; + case JR_IB_NULL: list_IASetIndexBuffer(list, NULL); break; + case JR_VBS: list_IASetVertexBuffers(list, h->a, w[0], w[1] ? (const D3D12_VERTEX_BUFFER_VIEW *)(w + 2) : NULL); break; + case JR_VIEWPORTS: list_RSSetViewports(list, h->a, h->a ? (const D3D12_VIEWPORT *)(h + 1) : NULL); break; + case JR_SCISSORS: list_RSSetScissorRects(list, h->a, h->a ? (const D3D12_RECT *)(h + 1) : NULL); break; + case JR_STENCIL_REF: list_OMSetStencilRef(list, h->a); break; + case JR_BLEND_FACTOR: list_OMSetBlendFactor(list, h->a ? (const FLOAT *)(h + 1) : NULL); break; + case JR_DRAW: list_DrawInstanced(list, h->a, w[0], w[1], w[2]); break; + case JR_DRAW_INDEXED: list_DrawIndexedInstanced(list, h->a, w[0], w[1], (INT)w[2], w[3]); break; + case JR_DISPATCH: list_Dispatch(list, h->a, w[0], w[1]); break; + case JR_BARRIERS: list_ResourceBarrier(list, h->a, h->a ? (const D3D12_RESOURCE_BARRIER *)(h + 1) : NULL); barriers += h->a; break; + case JR_HEAPS: list_SetDescriptorHeaps(list, h->a, (ID3D12DescriptorHeap *const *)(h + 1)); break; + default: { + static LONG said; + if (!InterlockedExchange(&said, 1)) + d3d12_log("[madeira-d3d12] list-journal: unknown record %u (size %u); the rest of this journal is dropped\n", h->op, h->size); + p = end; + continue; + } + } + if (g_jr_census) { + ops[h->op]++; + if (mad_jr_repeats(l, h)) repeats[h->op]++; + } + records++; + p += h->size; + } + j->used = 0; + if (g_jr_census) { + unsigned k; + for (k = 1; k < JR_OP_COUNT; k++) { + if (ops[k]) InterlockedAdd64(&g_jr_ops[k], ops[k]); + if (repeats[k]) InterlockedAdd64(&g_jr_redundant[k], repeats[k]); + } + InterlockedIncrement64(&g_jr_flushes); + InterlockedAdd64(&g_jr_records, records); + if (barriers) InterlockedAdd64(&g_jr_barrier_entries, barriers); + if (words) InterlockedAdd64(&g_jr_const_words, words); + } +} + +/* api-census: the interfaces whose slots go through counting trampolines. */ +static const struct { + const char *iface; + const char *const *names; + unsigned count; + void *table; +} g_jr_counted[] = { +#define MAD_JR_COUNTED(prefix, name, table) { prefix, madeira_slots_##name, sizeof madeira_slots_##name / sizeof(char *), &table } + MAD_JR_COUNTED("dev", ID3D12Device10, g_device_vtbl), + MAD_JR_COUNTED("queue", ID3D12CommandQueue, g_queue_vtbl), + MAD_JR_COUNTED("alloc", ID3D12CommandAllocator, g_alloc_vtbl), + MAD_JR_COUNTED("fence", ID3D12Fence, g_fence_vtbl), + MAD_JR_COUNTED("res", ID3D12Resource2, g_res_vtbl), + MAD_JR_COUNTED("heap", ID3D12DescriptorHeap, g_heap_vtbl), + MAD_JR_COUNTED("pso", ID3D12PipelineState, g_pso_vtbl), + MAD_JR_COUNTED("rootsig", ID3D12RootSignature, g_rootsig_vtbl), +#undef MAD_JR_COUNTED +}; + +/* After every build_vtables (it refills all slots with the ARM64EC methods). */ +static void mad_jr_install(void) +{ + void **slots = (void **)&g_list_vtbl8; + unsigned i, k; + const struct mad_jr_method *m; + if (g_jr_installed) return; /* the tables kept their trampolines (build_vtables returned early) */ + if (g_jr_on < 0) { + int journal = mad_cfg_int_pe("list-journal", 0) ? 1 : 0; + g_jr_census = mad_cfg_int_pe("api-census", 0) ? 1 : 0; + if (journal && mad_scbv_on() > 0) { + d3d12_log("[madeira-d3d12] list-journal off: static-cbv reads descriptor tables while a list records\n"); + journal = 0; + } + g_jr_on = journal; + if (journal || g_jr_census) + d3d12_log("[madeira-d3d12] list-journal = %d, api-census = %d: %s\n", journal, g_jr_census, + journal ? "hot list methods and GetGPUVirtualAddress run as x64, lists replay at Close" : "calls counted only"); + } + /* Every table gets its jr_ctx first: the x64 GetGPUVirtualAddress reads the + * resource table's even with api-census off. */ + g_jr_list_ctx.flush = mad_jr_flush; + g_jr_list_ctx.census = g_jr_census; + slots[-1] = &g_jr_list_ctx; + for (k = 0; k < sizeof g_jr_counted / sizeof g_jr_counted[0]; k++) { + g_jr_ctx[k].census = g_jr_census; + ((void **)g_jr_counted[k].table)[-1] = &g_jr_ctx[k]; + } + if (g_jr_on || g_jr_census) { + for (i = 0; i < MAD_LIST_SLOT_COUNT; i++) { g_jr_list_ctx.target[i] = slots[i]; slots[i] = mad_jr_list_tramps[i]; } + if (g_jr_on) for (m = mad_jr_x64_methods; m->fn; m++) slots[m->slot] = m->fn; + } + if (g_jr_census) { + for (k = 0; k < sizeof g_jr_counted / sizeof g_jr_counted[0]; k++) { + void **table = (void **)g_jr_counted[k].table; + for (i = 0; i < g_jr_counted[k].count; i++) { + g_jr_ctx[k].target[i] = table[i]; + table[i] = mad_jr_count_tramps[i]; + } + } + } + /* After the census: the x64 GetGPUVirtualAddress counts in the resource ctx itself. */ + if (g_jr_on) g_res_vtbl.GetGPUVirtualAddress = (void *)mad_res_gva_x64; + g_jr_installed = g_jr_on || g_jr_census; +} + +static const char *const g_jr_op_method[JR_OP_COUNT] = { + [JR_PSO] = "SetPipelineState", [JR_ROOTSIG] = "SetGraphicsRootSignature", [JR_CROOTSIG] = "SetComputeRootSignature", + [JR_ROOT_CBV] = "SetGraphicsRootConstantBufferView", [JR_ROOT_SRV] = "SetGraphicsRootShaderResourceView", + [JR_ROOT_UAV] = "SetGraphicsRootUnorderedAccessView", [JR_ROOT_TABLE] = "SetGraphicsRootDescriptorTable", + [JR_CROOT_CBV] = "SetComputeRootConstantBufferView", [JR_CROOT_SRV] = "SetComputeRootShaderResourceView", + [JR_CROOT_UAV] = "SetComputeRootUnorderedAccessView", [JR_CROOT_TABLE] = "SetComputeRootDescriptorTable", + [JR_ROOT_CONST] = "SetGraphicsRoot32BitConstant", [JR_ROOT_CONSTS] = "SetGraphicsRoot32BitConstants", + [JR_CROOT_CONST] = "SetComputeRoot32BitConstant", [JR_CROOT_CONSTS] = "SetComputeRoot32BitConstants", + [JR_TOPOLOGY] = "IASetPrimitiveTopology", [JR_IB] = "IASetIndexBuffer", [JR_IB_NULL] = "IASetIndexBuffer(NULL)", + [JR_VBS] = "IASetVertexBuffers", [JR_VIEWPORTS] = "RSSetViewports", [JR_SCISSORS] = "RSSetScissorRects", + [JR_STENCIL_REF] = "OMSetStencilRef", [JR_BLEND_FACTOR] = "OMSetBlendFactor", [JR_DRAW] = "DrawInstanced", + [JR_DRAW_INDEXED] = "DrawIndexedInstanced", [JR_DISPATCH] = "Dispatch", [JR_BARRIERS] = "ResourceBarrier", + [JR_HEAPS] = "SetDescriptorHeaps", +}; + +struct mad_jr_count { const char *prefix, *name; LONG64 n, repeats; }; +static int mad_jr_count_cmp(const void *a, const void *b) +{ + LONG64 x = ((const struct mad_jr_count *)a)->n, y = ((const struct mad_jr_count *)b)->n; + return x < y ? 1 : x > y ? -1 : 0; +} + +/* Every 5 s from mad_perf_present: the calls of the last window, per frame. */ +static void mad_jr_report(LONG presents, double wall) +{ + struct mad_jr_count c[MAD_JR_SLOTS * 9 + JR_OP_COUNT]; + unsigned n = 0, i, k, shown; + double np = presents > 0 ? (double)presents : 1.0; + char line[960]; int len; + LONG64 ops[JR_OP_COUNT], rep[JR_OP_COUNT], draws, sets = 0, repeated = 0; + if (!g_jr_census) return; + for (k = 1; k < JR_OP_COUNT; k++) { ops[k] = InterlockedExchange64(&g_jr_ops[k], 0); rep[k] = InterlockedExchange64(&g_jr_redundant[k], 0); } + for (i = 0; i < MAD_LIST_SLOT_COUNT; i++) { + LONG64 v = (ULONG)InterlockedExchange((LONG *)&g_jr_list_ctx.calls[i], 0); + if (!v) continue; + c[n].prefix = "list"; c[n].name = i < sizeof madeira_slots_ID3D12GraphicsCommandList7 / sizeof(char *) + ? madeira_slots_ID3D12GraphicsCommandList7[i] : "OMSetFrontAndBackStencilRef"; + c[n].n = v; c[n].repeats = -1; n++; + } + for (k = 1; k < JR_OP_COUNT; k++) { + if (!ops[k]) continue; + c[n].prefix = "list"; c[n].name = g_jr_op_method[k]; c[n].n = ops[k]; c[n].repeats = rep[k]; n++; + if (k <= JR_CROOT_TABLE || k == JR_TOPOLOGY || k == JR_IB || k == JR_VBS || k == JR_VIEWPORTS || k == JR_SCISSORS || k == JR_HEAPS) { + sets += ops[k]; repeated += rep[k]; + } + } + for (k = 0; k < sizeof g_jr_counted / sizeof g_jr_counted[0]; k++) + for (i = 0; i < g_jr_counted[k].count; i++) { + LONG64 v = (ULONG)InterlockedExchange((LONG *)&g_jr_ctx[k].calls[i], 0); + if (!v) continue; + c[n].prefix = g_jr_counted[k].iface; c[n].name = g_jr_counted[k].names[i]; c[n].n = v; c[n].repeats = -1; n++; + } + draws = ops[JR_DRAW] + ops[JR_DRAW_INDEXED]; + { + LONG64 fl = InterlockedExchange64(&g_jr_flushes, 0), rc = InterlockedExchange64(&g_jr_records, 0); + LONG64 be = InterlockedExchange64(&g_jr_barrier_entries, 0), cw = InterlockedExchange64(&g_jr_const_words, 0); + if (g_jr_on > 0) + d3d12_log("[d3d12-census] %.1fs, %ld presents, per frame: draws %.0f, dispatches %.0f, journal %.0f records in %.0f flushes, " + "state sets %.0f of which %.0f (%.0f%%) repeat what is bound (pso %.0f/%.0f, root signature %.0f/%.0f, " + "root arguments %.0f/%.0f, topology %.0f/%.0f, index buffer %.0f/%.0f, vertex buffers %.0f/%.0f, " + "viewport %.0f/%.0f, scissor %.0f/%.0f, heaps %.0f/%.0f), barriers %.0f entries in %.0f calls, root constants %.0f words\n", + wall, (long)presents, draws / np, ops[JR_DISPATCH] / np, rc / np, fl / np, + sets / np, repeated / np, sets ? 100.0 * (double)repeated / (double)sets : 0.0, + rep[JR_PSO] / np, ops[JR_PSO] / np, (rep[JR_ROOTSIG] + rep[JR_CROOTSIG]) / np, (ops[JR_ROOTSIG] + ops[JR_CROOTSIG]) / np, + (rep[JR_ROOT_CBV] + rep[JR_ROOT_SRV] + rep[JR_ROOT_UAV] + rep[JR_ROOT_TABLE] + rep[JR_CROOT_CBV] + rep[JR_CROOT_SRV] + rep[JR_CROOT_UAV] + rep[JR_CROOT_TABLE]) / np, + (ops[JR_ROOT_CBV] + ops[JR_ROOT_SRV] + ops[JR_ROOT_UAV] + ops[JR_ROOT_TABLE] + ops[JR_CROOT_CBV] + ops[JR_CROOT_SRV] + ops[JR_CROOT_UAV] + ops[JR_CROOT_TABLE]) / np, + rep[JR_TOPOLOGY] / np, ops[JR_TOPOLOGY] / np, rep[JR_IB] / np, ops[JR_IB] / np, rep[JR_VBS] / np, ops[JR_VBS] / np, + rep[JR_VIEWPORTS] / np, ops[JR_VIEWPORTS] / np, rep[JR_SCISSORS] / np, ops[JR_SCISSORS] / np, + rep[JR_HEAPS] / np, ops[JR_HEAPS] / np, be / np, ops[JR_BARRIERS] / np, cw / np); + } + qsort(c, n, sizeof c[0], mad_jr_count_cmp); + len = snprintf(line, sizeof line, "[d3d12-census] calls per frame:"); + for (i = 0, shown = 0; i < n && shown < 40; i++, shown++) { + if (len > (int)sizeof line - 80) { + d3d12_log("%s\n", line); + len = snprintf(line, sizeof line, "[d3d12-census] (cont):"); + } + len += snprintf(line + len, sizeof line - len, " %s.%s %.1f", c[i].prefix, c[i].name, c[i].n / np); + } + if (n) d3d12_log("%s\n", line); +} diff --git a/madeira-d3d12/src/pe/madeira_list_journal.x64.S b/madeira-d3d12/src/pe/madeira_list_journal.x64.S new file mode 100644 index 0000000000..76bb9cdaf7 --- /dev/null +++ b/madeira-d3d12/src/pe/madeira_list_journal.x64.S @@ -0,0 +1,109 @@ +/* madeira-d3d12 list-journal, x64 trampolines (see madeira_list_journal.h). + * + * mad_jr_list_tramps[slot]: every list slot that is not journaled points here + * when list-journal or api-census is on. A list whose journal holds records is + * flushed first (one call into ARM64EC, with the argument registers kept), then + * the call goes on to the slot's ARM64EC method as a tail jump, so the stack + * arguments and the return address are the caller's own. + * + * mad_jr_count_tramps[slot]: api-census counting for the other interfaces. + * + * mad_res_gva_x64: ID3D12Resource::GetGPUVirtualAddress without the crossing. + * + * No RIP-relative data access anywhere: the state is struct mad_jr_ctx, found + * through the object (rcx -> vtable -> the pointer just before slot 0). */ +#include "madeira_list_journal.h" + + .text + + .macro LIST_TRAMP i + .balign 16 +mad_jr_list_tramp_\i: + movq (%rcx), %rax + movq -8(%rax), %rax + cmpb $0, MAD_JR_CTX_CENSUS(%rax) + je 1f + incl MAD_JR_CTX_CALLS+4*\i(%rax) +1: cmpl $0, MAD_JR_USED_OFFSET(%rcx) + jne 2f + jmpq *8*\i(%rax) +2: movl $\i, %r10d + jmp mad_jr_flush_and_go + .endm + + .macro COUNT_TRAMP i + .balign 16 +mad_jr_count_tramp_\i: + movq (%rcx), %rax + movq -8(%rax), %rax + incl MAD_JR_CTX_CALLS+4*\i(%rax) + jmpq *8*\i(%rax) + .endm + + .irp i, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95 + LIST_TRAMP \i + .endr + + .irp i, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95 + COUNT_TRAMP \i + .endr + +/* rax = the list's struct mad_jr_ctx, r10d = slot; rcx, rdx, r8, r9 and xmm0-3 + * are the caller's arguments. One stack allocation (described for the + * unwinder): shadow space, xmm0-3, the integer argument registers, ctx, slot. */ + .balign 16 + .def mad_jr_flush_and_go; .scl 3; .type 32; .endef + .seh_proc mad_jr_flush_and_go +mad_jr_flush_and_go: + subq $0x98, %rsp + .seh_stackalloc 0x98 + .seh_endprologue + movdqu %xmm0, 0x20(%rsp) + movdqu %xmm1, 0x30(%rsp) + movdqu %xmm2, 0x40(%rsp) + movdqu %xmm3, 0x50(%rsp) + movq %rcx, 0x60(%rsp) + movq %rdx, 0x68(%rsp) + movq %r8, 0x70(%rsp) + movq %r9, 0x78(%rsp) + movq %rax, 0x80(%rsp) + movq %r10, 0x88(%rsp) + callq *MAD_JR_CTX_FLUSH(%rax) + movdqu 0x20(%rsp), %xmm0 + movdqu 0x30(%rsp), %xmm1 + movdqu 0x40(%rsp), %xmm2 + movdqu 0x50(%rsp), %xmm3 + movq 0x60(%rsp), %rcx + movq 0x68(%rsp), %rdx + movq 0x70(%rsp), %r8 + movq 0x78(%rsp), %r9 + movq 0x80(%rsp), %rax + movq 0x88(%rsp), %r10 + movq (%rax,%r10,8), %rax + addq $0x98, %rsp + rex64 jmpq *%rax + .seh_endproc + + .balign 16 + .globl mad_res_gva_x64 +mad_res_gva_x64: + movq (%rcx), %rax + movq -8(%rax), %rax + cmpb $0, MAD_JR_CTX_CENSUS(%rax) + je 1f + incl MAD_JR_CTX_CALLS+4*MAD_RES_GVA_SLOT(%rax) +1: movq MAD_RES_GPU_ADDRESS_OFFSET(%rcx), %rax + retq + + .section .rdata,"dr" + .balign 8 + .globl mad_jr_list_tramps +mad_jr_list_tramps: + .irp i, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95 + .quad mad_jr_list_tramp_\i + .endr + .globl mad_jr_count_tramps +mad_jr_count_tramps: + .irp i, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95 + .quad mad_jr_count_tramp_\i + .endr diff --git a/madeira-d3d12/src/pe/madeira_list_journal.x64.c b/madeira-d3d12/src/pe/madeira_list_journal.x64.c new file mode 100644 index 0000000000..2ad047800b --- /dev/null +++ b/madeira-d3d12/src/pe/madeira_list_journal.x64.c @@ -0,0 +1,234 @@ +/* madeira-d3d12 list-journal, x64 part (see madeira_list_journal.h). + * + * Built with the x86_64 compiler and linked into the ARM64EC DLL, so an x64 + * game's calls to these methods stay in emulated x64 code instead of crossing + * into ARM64EC. Each method appends one record to the list's journal. When the + * record does not fit, the journal is flushed (one crossing) and the append is + * tried again; a call the journal cannot hold (too many views, constants, ...) + * flushes and goes to the ARM64EC method directly, so the order is kept. + * + * Each method's fast path makes no call, so it needs no stack frame; anything + * else is a tail call to its out-of-line slow_* twin. + * + * No C library calls here: a call from this object would bind to an x64 import + * this DLL does not have. Variable-size copies use rep movsb, which FEX turns + * into its native copy. */ +#include +#include +#include +#include "madeira_list_journal.h" + +#define SLOT(method) ((uint32_t)(offsetof(ID3D12GraphicsCommandList7Vtbl, method) / sizeof(void *))) +#define JOURNAL(list) ((struct mad_journal *)((char *)(list) + MAD_JR_OFFSET)) +/* The list's struct mad_jr_ctx: the pointer just before its vtable's first slot + * (never a RIP-relative global; see madeira_list_journal.h). */ +#define CTX(list) (*(struct mad_jr_ctx *const *)((const char *)*(void *const *)(list) - 8)) +#define ORIGINAL(method, type) ((type)CTX(list)->target[SLOT(method)]) + +typedef ID3D12GraphicsCommandList List; + +static inline void copy_bytes(void *destination, const void *source, size_t count) +{ + __asm__ volatile("rep movsb" : "+D"(destination), "+S"(source), "+c"(count) : : "memory"); +} + +/* A record of `size` bytes (a multiple of 8) at the end of the journal, or NULL + * when it does not fit. Makes no call. */ +static inline struct mad_jr_head *take(List *list, uint32_t size, uint16_t op, uint32_t a) +{ + struct mad_journal *journal = JOURNAL(list); + struct mad_jr_head *head; + if (__builtin_expect(journal->cap - journal->used < size, 0)) return NULL; + head = (struct mad_jr_head *)(journal->buf + journal->used); + journal->used += size; + head->op = op; + head->size = (uint16_t)size; + head->a = a; + return head; +} + +/* Replays what the journal holds (and allocates it the first time); non-zero + * when a record of `size` bytes fits afterwards. */ +static int make_room(List *list, uint32_t size) +{ + struct mad_journal *journal = JOURNAL(list); + if (journal->used || !journal->buf) CTX(list)->flush(list); + return journal->cap - journal->used >= size; +} + +static inline uint32_t round8(uint32_t size) +{ + return (size + 7) & ~7u; +} + +#define SLOW __attribute__((noinline)) + +/* ---- pipeline state and root signatures ---------------------------------- */ + +#define POINTER_METHOD(method, type, op) \ +static void STDMETHODCALLTYPE journal_##method(List *list, type *object); \ +static SLOW void slow_##method(List *list, type *object) \ +{ \ + if (make_room(list, 16)) journal_##method(list, object); \ + else ORIGINAL(method, void (STDMETHODCALLTYPE *)(List *, type *))(list, object); \ +} \ +static void STDMETHODCALLTYPE journal_##method(List *list, type *object) \ +{ \ + struct mad_jr_head *head = take(list, 16, op, 0); \ + if (!head) { slow_##method(list, object); return; } \ + *(uint64_t *)(head + 1) = (uintptr_t)object; \ +} +POINTER_METHOD(SetPipelineState, ID3D12PipelineState, JR_PSO) +POINTER_METHOD(SetGraphicsRootSignature, ID3D12RootSignature, JR_ROOTSIG) +POINTER_METHOD(SetComputeRootSignature, ID3D12RootSignature, JR_CROOTSIG) + +/* ---- root arguments ------------------------------------------------------- */ + +#define ROOT_VALUE_METHOD(method, type, value_of, op) \ +static void STDMETHODCALLTYPE journal_##method(List *list, UINT index, type value); \ +static SLOW void slow_##method(List *list, UINT index, type value) \ +{ \ + if (make_room(list, 16)) journal_##method(list, index, value); \ + else ORIGINAL(method, void (STDMETHODCALLTYPE *)(List *, UINT, type))(list, index, value); \ +} \ +static void STDMETHODCALLTYPE journal_##method(List *list, UINT index, type value) \ +{ \ + struct mad_jr_head *head = take(list, 16, op, index); \ + if (!head) { slow_##method(list, index, value); return; } \ + *(uint64_t *)(head + 1) = value_of; \ +} +ROOT_VALUE_METHOD(SetGraphicsRootConstantBufferView, D3D12_GPU_VIRTUAL_ADDRESS, value, JR_ROOT_CBV) +ROOT_VALUE_METHOD(SetGraphicsRootShaderResourceView, D3D12_GPU_VIRTUAL_ADDRESS, value, JR_ROOT_SRV) +ROOT_VALUE_METHOD(SetGraphicsRootUnorderedAccessView, D3D12_GPU_VIRTUAL_ADDRESS, value, JR_ROOT_UAV) +ROOT_VALUE_METHOD(SetComputeRootConstantBufferView, D3D12_GPU_VIRTUAL_ADDRESS, value, JR_CROOT_CBV) +ROOT_VALUE_METHOD(SetComputeRootShaderResourceView, D3D12_GPU_VIRTUAL_ADDRESS, value, JR_CROOT_SRV) +ROOT_VALUE_METHOD(SetComputeRootUnorderedAccessView, D3D12_GPU_VIRTUAL_ADDRESS, value, JR_CROOT_UAV) +ROOT_VALUE_METHOD(SetGraphicsRootDescriptorTable, D3D12_GPU_DESCRIPTOR_HANDLE, value.ptr, JR_ROOT_TABLE) +ROOT_VALUE_METHOD(SetComputeRootDescriptorTable, D3D12_GPU_DESCRIPTOR_HANDLE, value.ptr, JR_CROOT_TABLE) + +#define ROOT_CONSTANT_METHOD(method, op) \ +static void STDMETHODCALLTYPE journal_##method(List *list, UINT index, UINT data, UINT offset); \ +static SLOW void slow_##method(List *list, UINT index, UINT data, UINT offset) \ +{ \ + if (make_room(list, 16)) journal_##method(list, index, data, offset); \ + else ORIGINAL(method, void (STDMETHODCALLTYPE *)(List *, UINT, UINT, UINT))(list, index, data, offset); \ +} \ +static void STDMETHODCALLTYPE journal_##method(List *list, UINT index, UINT data, UINT offset) \ +{ \ + struct mad_jr_head *head = take(list, 16, op, index); \ + if (!head) { slow_##method(list, index, data, offset); return; } \ + ((uint32_t *)(head + 1))[0] = data; \ + ((uint32_t *)(head + 1))[1] = offset; \ +} +ROOT_CONSTANT_METHOD(SetGraphicsRoot32BitConstant, JR_ROOT_CONST) +ROOT_CONSTANT_METHOD(SetComputeRoot32BitConstant, JR_CROOT_CONST) + +/* Calls with an array argument: `limit_ok` decides whether the journal takes the + * call at all, `size` is its record size. */ +#define ARRAY_METHOD(method, params, args, types, limit_ok, size, op, a, fill) \ +static void STDMETHODCALLTYPE journal_##method params; \ +static SLOW void slow_##method params \ +{ \ + if ((limit_ok) && make_room(list, (size))) { journal_##method args; return; } \ + if (JOURNAL(list)->used) CTX(list)->flush(list); \ + ORIGINAL(method, void (STDMETHODCALLTYPE *) types) args; \ +} \ +static void STDMETHODCALLTYPE journal_##method params \ +{ \ + struct mad_jr_head *head = (limit_ok) ? take(list, (size), op, (a)) : NULL; \ + if (!head) { slow_##method args; return; } \ + fill; \ +} + +ARRAY_METHOD(SetGraphicsRoot32BitConstants, (List *list, UINT index, UINT count, const void *data, UINT offset), + (list, index, count, data, offset), (List *, UINT, UINT, const void *, UINT), + count <= MAD_JR_MAX_CONSTS && (data || !count), round8(16 + count * 4), JR_ROOT_CONSTS, index, + ((uint32_t *)(head + 1))[0] = count; ((uint32_t *)(head + 1))[1] = offset; + copy_bytes((uint32_t *)(head + 1) + 2, data, count * 4)) +ARRAY_METHOD(SetComputeRoot32BitConstants, (List *list, UINT index, UINT count, const void *data, UINT offset), + (list, index, count, data, offset), (List *, UINT, UINT, const void *, UINT), + count <= MAD_JR_MAX_CONSTS && (data || !count), round8(16 + count * 4), JR_CROOT_CONSTS, index, + ((uint32_t *)(head + 1))[0] = count; ((uint32_t *)(head + 1))[1] = offset; + copy_bytes((uint32_t *)(head + 1) + 2, data, count * 4)) + +/* ---- input assembler, rasterizer, output merger ---------------------------- */ + +ARRAY_METHOD(IASetPrimitiveTopology, (List *list, D3D12_PRIMITIVE_TOPOLOGY topology), (list, topology), + (List *, D3D12_PRIMITIVE_TOPOLOGY), 1, 8, JR_TOPOLOGY, (uint32_t)topology, (void)0) +ARRAY_METHOD(IASetIndexBuffer, (List *list, const D3D12_INDEX_BUFFER_VIEW *view), (list, view), + (List *, const D3D12_INDEX_BUFFER_VIEW *), 1, view ? 24 : 8, view ? JR_IB : JR_IB_NULL, 0, + if (view) *(D3D12_INDEX_BUFFER_VIEW *)(head + 1) = *view) +ARRAY_METHOD(IASetVertexBuffers, (List *list, UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW *views), + (list, start, count, views), (List *, UINT, UINT, const D3D12_VERTEX_BUFFER_VIEW *), + count <= MAD_JR_MAX_VIEWS, 16 + (views ? count * 16 : 0), JR_VBS, start, + ((uint32_t *)(head + 1))[0] = count; ((uint32_t *)(head + 1))[1] = views != NULL; + if (views && count) copy_bytes((uint32_t *)(head + 1) + 2, views, count * 16)) +ARRAY_METHOD(RSSetViewports, (List *list, UINT count, const D3D12_VIEWPORT *viewports), (list, count, viewports), + (List *, UINT, const D3D12_VIEWPORT *), count <= MAD_JR_MAX_RECTS && (viewports || !count), + 8 + count * 24, JR_VIEWPORTS, count, if (count) copy_bytes(head + 1, viewports, count * 24)) +ARRAY_METHOD(RSSetScissorRects, (List *list, UINT count, const D3D12_RECT *rects), (list, count, rects), + (List *, UINT, const D3D12_RECT *), count <= MAD_JR_MAX_RECTS && (rects || !count), + 8 + count * 16, JR_SCISSORS, count, if (count) copy_bytes(head + 1, rects, count * 16)) +ARRAY_METHOD(OMSetStencilRef, (List *list, UINT reference), (list, reference), (List *, UINT), + 1, 8, JR_STENCIL_REF, reference, (void)0) +ARRAY_METHOD(OMSetBlendFactor, (List *list, const FLOAT *factor), (list, factor), (List *, const FLOAT *), + 1, 24, JR_BLEND_FACTOR, factor != NULL, if (factor) copy_bytes(head + 1, factor, 16)) +ARRAY_METHOD(SetDescriptorHeaps, (List *list, UINT count, ID3D12DescriptorHeap *const *heaps), (list, count, heaps), + (List *, UINT, ID3D12DescriptorHeap *const *), count <= MAD_JR_MAX_HEAPS && heaps, + 8 + count * 8, JR_HEAPS, count, if (count) copy_bytes(head + 1, heaps, count * 8)) + +/* ---- draws, dispatches, barriers ------------------------------------------ */ + +ARRAY_METHOD(DrawInstanced, (List *list, UINT vertex_count, UINT instance_count, UINT vertex_start, UINT instance_start), + (list, vertex_count, instance_count, vertex_start, instance_start), (List *, UINT, UINT, UINT, UINT), + 1, 24, JR_DRAW, vertex_count, + ((uint32_t *)(head + 1))[0] = instance_count; ((uint32_t *)(head + 1))[1] = vertex_start; + ((uint32_t *)(head + 1))[2] = instance_start) +ARRAY_METHOD(DrawIndexedInstanced, (List *list, UINT index_count, UINT instance_count, UINT index_start, INT base_vertex, UINT instance_start), + (list, index_count, instance_count, index_start, base_vertex, instance_start), (List *, UINT, UINT, UINT, INT, UINT), + 1, 24, JR_DRAW_INDEXED, index_count, + ((uint32_t *)(head + 1))[0] = instance_count; ((uint32_t *)(head + 1))[1] = index_start; + ((uint32_t *)(head + 1))[2] = (uint32_t)base_vertex; ((uint32_t *)(head + 1))[3] = instance_start) +ARRAY_METHOD(Dispatch, (List *list, UINT x, UINT y, UINT z), (list, x, y, z), (List *, UINT, UINT, UINT), + 1, 16, JR_DISPATCH, x, ((uint32_t *)(head + 1))[0] = y; ((uint32_t *)(head + 1))[1] = z) +ARRAY_METHOD(ResourceBarrier, (List *list, UINT count, const D3D12_RESOURCE_BARRIER *barriers), (list, count, barriers), + (List *, UINT, const D3D12_RESOURCE_BARRIER *), count <= MAD_JR_MAX_BARRIERS && (barriers || !count), + 8 + count * 32, JR_BARRIERS, count, if (count) copy_bytes(head + 1, barriers, count * 32)) + +#define METHOD(name) { SLOT(name), (void *)journal_##name } +const struct mad_jr_method mad_jr_x64_methods[] = { + METHOD(SetPipelineState), + METHOD(SetGraphicsRootSignature), + METHOD(SetComputeRootSignature), + METHOD(SetGraphicsRootConstantBufferView), + METHOD(SetGraphicsRootShaderResourceView), + METHOD(SetGraphicsRootUnorderedAccessView), + METHOD(SetComputeRootConstantBufferView), + METHOD(SetComputeRootShaderResourceView), + METHOD(SetComputeRootUnorderedAccessView), + METHOD(SetGraphicsRootDescriptorTable), + METHOD(SetComputeRootDescriptorTable), + METHOD(SetGraphicsRoot32BitConstant), + METHOD(SetComputeRoot32BitConstant), + METHOD(SetGraphicsRoot32BitConstants), + METHOD(SetComputeRoot32BitConstants), + METHOD(IASetPrimitiveTopology), + METHOD(IASetIndexBuffer), + METHOD(IASetVertexBuffers), + METHOD(RSSetViewports), + METHOD(RSSetScissorRects), + METHOD(OMSetStencilRef), + METHOD(OMSetBlendFactor), + METHOD(SetDescriptorHeaps), + METHOD(DrawInstanced), + METHOD(DrawIndexedInstanced), + METHOD(Dispatch), + METHOD(ResourceBarrier), + { 0, NULL } +}; + +_Static_assert(sizeof(D3D12_INDEX_BUFFER_VIEW) == 16, "index buffer view"); +_Static_assert(sizeof(D3D12_VERTEX_BUFFER_VIEW) == 16, "vertex buffer view"); +_Static_assert(sizeof(D3D12_VIEWPORT) == 24, "viewport"); +_Static_assert(sizeof(D3D12_RECT) == 16, "rect"); +_Static_assert(sizeof(D3D12_RESOURCE_BARRIER) == 32, "barrier"); From 049f87fb978322b7b2e8c0199e6d659ff1cb3a83 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Wed, 4 Nov 2026 16:33:42 +1100 Subject: [PATCH 02/76] madeira-duo: hitch recorder ([hitch], [hitch-ecl], [hitch-sum]) Logs every frame over hitch-ms (default 50) and every replay over hitch-ecl-ms (default 33) with where the time went: game/worker thread CPU vs wall, ExecuteCommandLists/Present split, encoding, commits, first-use pipelines, footprint and headroom. 5 s summary of frame-time buckets. Capped at 30 lines per 5 s. Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/pe/madeira_d3d12.c | 171 +++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index fa289ba561..2268e0a121 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -1063,6 +1063,11 @@ static void mad_es_thread_exit(void) { /* DLL_THREAD_DETACH: the thread's stat * screen and the stalls at first draw. QPC ticks, summed over all threads. */ static volatile LONG64 g_pt_gfx, g_pt_cs, g_pt_conv, g_pt_lib, g_pt_rs, g_pt_realize; static volatile LONG g_pn_gfx, g_pn_cs, g_pn_lib, g_pn_rs, g_pn_realize; +/* madeira-duo hitch recorder (mad_hitch_frame, mad_ecl_run): cumulative, never reset, + * QPC ticks. Compute pipelines built at first dispatch; batch commits (mad_queue_flush); + * the game thread's time inside Present. */ +static volatile LONG64 g_hz_cs_realize_t, g_hz_flush_t, g_hz_present_t; +static volatile LONG g_hz_cs_realize_n, g_hz_flush_n; static void mad_pso_time_report(const char *why) { LARGE_INTEGER f; double ms; QueryPerformanceFrequency(&f); @@ -6268,8 +6273,10 @@ static obj_handle_t mad_cpso_realize(struct mad_pso *p) { struct WMTComputePipelineInfo ci; obj_handle_t err = 0; memset(&ci, 0, sizeof ci); if (!p->lz || mad_lzlib_restore(p)) { /* madeira-bcd pso-lazy-libs */ + LONG64 t0 = mad_qpc(); /* madeira-duo hitch recorder */ ci.compute_function = p->vs_fn; p->cps = MTLDevice_newComputePipelineState(p->device_handle, &ci, &err); + InterlockedExchangeAdd64(&g_hz_cs_realize_t, mad_qpc() - t0); InterlockedIncrement(&g_hz_cs_realize_n); } if (err) mad_log_nserror("compute pipeline", err); if (!p->cps) { @@ -10528,6 +10535,54 @@ static void mad_exec_list(struct mad_queue *q, struct mad_list *l, obj_handle_t /* ml1120: the replay itself; runs on the caller (async-submit = 0) or on the * queue's submission worker. */ +/* madeira-duo HITCH RECORDER. The [perf]/[xp] lines average 5 s windows, so a + * single 300 ms frame disappears into them, and the text5 run (4 Nov) could only + * say "ExecuteCommandLists took 100-1276 ms somewhere". This logs every slow + * frame and every slow submission on its own line with where the time went: + * [hitch] a frame (Present to Present on the game's thread) over hitch-ms + * (madeira.cfg, default 50; 0 = off): the game thread's CPU time and + * its time in ExecuteCommandLists / Present, the worker's jobs, the + * Present split, encoding, commits, pipelines compiled, memory; + * [hitch-ecl] one ExecuteCommandLists replay over hitch-ecl-ms (default 33): + * lock wait, pipeline prebuild, encoding, encoder open/end, + * commits, lazy pipelines, the rest (the replay itself), and the + * replaying thread's CPU time (CPU far below wall = it was blocked: + * a lock, a page-in, the GPU); + * [hitch-sum] every 5 s: frames, worst frame, frames over 33/50/100/250 ms. + * The cumulative counters it diffs already exist (the encode split, [xp], + * pso time) or are g_hz_*; per frame it costs three GetThreadTimes-class calls. + * Lines are capped at 30 per 5 s so a stall storm cannot flood the log. */ +static int g_hz_frame_ms = -1, g_hz_ecl_ms; +static LONG g_hz_lines, g_hz_dropped; +static void mad_hz_load(void) { + if (g_hz_frame_ms >= 0) return; + g_hz_ecl_ms = (int)mad_cfg_int_pe("hitch-ecl-ms", 33); /* hitch recorder: log a replay slower than this (0 = off) */ + g_hz_frame_ms = (int)mad_cfg_int_pe("hitch-ms", 50); /* hitch recorder: log a frame slower than this (0 = off) */ + d3d12_log("[madeira-d3d12] hitch recorder: frames over %d ms, replays over %d ms (madeira.cfg hitch-ms / hitch-ecl-ms)\n", + g_hz_frame_ms, g_hz_ecl_ms); +} +static int mad_hz_take(void) { /* one more line in this 5 s window? */ + if (InterlockedIncrement(&g_hz_lines) <= 30) return 1; + InterlockedIncrement(&g_hz_dropped); + return 0; +} +static LONG64 mad_hz_ft(const FILETIME *f) { return (LONG64)(((ULONGLONG)f->dwHighDateTime << 32) | f->dwLowDateTime); } +static LONG64 mad_hz_thread_cpu(HANDLE h) { /* kernel + user, 100 ns units; -1 if unknown */ + FILETIME c, e, k, u; + if (!h || !GetThreadTimes(h, &c, &e, &k, &u)) return -1; + return mad_hz_ft(&k) + mad_hz_ft(&u); +} +static LONG64 mad_hz_process_cpu(void) { + FILETIME c, e, k, u; + if (!GetProcessTimes(GetCurrentProcess(), &c, &e, &k, &u)) return -1; + return mad_hz_ft(&k) + mad_hz_ft(&u); +} +static void mad_hz_memory(char *buf, size_t n) { /* MadeiraCtl op 7: phys_footprint and what iOS still allows */ + struct madeira_ctl_args a; + memset(&a, 0, sizeof a); a.op = 7; MadeiraCtl(&a); + if (a.ret) snprintf(buf, n, "footprint %llu MB, headroom %llu MB", (unsigned long long)(a.ptr >> 20), (unsigned long long)(a.len >> 20)); + else snprintf(buf, n, "footprint unknown"); +} static void mad_ecl_run(ID3D12CommandQueue *This, UINT count, ID3D12CommandList *const *lists) { /* ml1021: hold the queue for the WHOLE replay. A concurrent Present -> * flush_all must not commit the buffer we are still encoding into. */ @@ -10539,16 +10594,26 @@ static void mad_ecl_run(ID3D12CommandQueue *This, UINT count, ID3D12CommandList * by exec_end before a list returns, so nothing in the pool is still in use * when it drains. Same thread pushes and pops. */ obj_handle_t ml1049_pool = NSAutoreleasePool_alloc_init(); + /* madeira-duo hitch recorder: the starting values ([hitch-ecl]) */ + const int hz = (mad_hz_load(), g_hz_ecl_ms > 0); + LONG64 hz_t0 = hz ? mad_qpc() : 0, hz_lock = 0, hz_pre = 0, hz_cpu0 = hz ? mad_hz_thread_cpu(GetCurrentThread()) : -1; + LONG64 hz_enc = g_es_enc_t, hz_open = g_es_open_t, hz_rz = g_pt_realize, hz_cs = g_hz_cs_realize_t, hz_fl = g_hz_flush_t; + LONG hz_rzn = g_pn_realize, hz_csn = g_hz_cs_realize_n, hz_fln = g_hz_flush_n; const int rs = mad_rs_on(); /* madeira-bcd: replay split */ UINT64 rs_t = rs ? mad_tick() : 0; struct mad_eb *eb = mad_es_begin(); /* madeira-bcd encode-batch / draw-dedup: this replay's encode state */ if (ml1021_q) EnterCriticalSection(&ml1021_q->submit_lock); + if (hz) hz_lock = mad_qpc(); if (rs) mad_rs_step(RS_LOCK, &rs_t); struct mad_queue *q = (struct mad_queue *)This; struct mad_rp_carry rp_k; const struct mad_list *rp_want = NULL; /* madeira-bcd rp-carry */ if (g_sd_state < 0) mad_sync_diag_load(); /* madeira-bcd: sync diagnostics, read once */ mad_prebuild_lists(count, lists); /* lazy pipelines this batch binds, built in parallel */ + if (hz) { /* first-use pipeline time is counted from here: prebuild's parallel builds are in "prebuild" */ + hz_pre = mad_qpc(); + hz_rz = g_pt_realize; hz_cs = g_hz_cs_realize_t; hz_rzn = g_pn_realize; hz_csn = g_hz_cs_realize_n; + } if (rs) mad_rs_step(RS_PREBUILD, &rs_t); memset(&rp_k, 0, sizeof rp_k); q->rp_carry = &rp_k; q->rp_next = NULL; q->rp_lists = lists; q->rp_nlists = count; for (UINT i = 0; i < count; i++) { @@ -10609,6 +10674,26 @@ static void mad_ecl_run(ID3D12CommandQueue *This, UINT count, ID3D12CommandList * before the frame's captures can exceed the memory budget */ if (g_capture_on && ml1021_q && g_cap_bytes >= (48ull << 20)) mad_capture_drain(ml1021_q->device, g_capture_frame, 0); if (ml1049_pool) NSObject_release(ml1049_pool); + if (hz) { /* madeira-duo hitch recorder */ + LONG64 t1 = mad_qpc(), qpf = g_xp.qpf ? g_xp.qpf : 1; + double ms = 1000.0 / (double)qpf, tms = 1000.0 / (double)mad_tick_freq(); + if ((t1 - hz_t0) * 1000 > (LONG64)g_hz_ecl_ms * qpf && mad_hz_take()) { + LONG64 cpu1 = hz_cpu0 >= 0 ? mad_hz_thread_cpu(GetCurrentThread()) : -1; + double wall = (t1 - hz_t0) * ms, enc = (g_es_enc_t - hz_enc) * tms, open = (g_es_open_t - hz_open) * tms; + double rz = (g_pt_realize - hz_rz) * ms, cs = (g_hz_cs_realize_t - hz_cs) * ms, fl = (g_hz_flush_t - hz_fl) * ms; + double lock = (hz_lock - hz_t0) * ms, pre = (hz_pre - hz_lock) * ms; + UINT64 cmds = 0; UINT i; char mem[96]; + for (i = 0; i < count; i++) if (lists[i]) cmds += ((struct mad_list *)lists[i])->ncmds; + mad_hz_memory(mem, sizeof mem); + d3d12_log("[hitch-ecl] replay %.1f ms on tid %04lx (%s), thread cpu %.1f ms: lock wait %.1f, prebuild %.1f, encode %.1f, " + "encoders open/end %.1f, commits %ld (%.1f ms), first-use pipelines gfx %ld (%.1f ms) compute %ld (%.1f ms), " + "rest %.1f | %u lists, %llu commands | %s\n", + wall, (unsigned long)GetCurrentThreadId(), q && q->sub_thread ? "worker" : "caller", + cpu1 >= 0 ? (cpu1 - hz_cpu0) / 10000.0 : -1.0, lock, pre, enc, open, + (long)(g_hz_flush_n - hz_fln), fl, (long)(g_pn_realize - hz_rzn), rz, (long)(g_hz_cs_realize_n - hz_csn), cs, + wall - lock - pre - enc - open - fl - rz - cs, count, (unsigned long long)cmds, mem); + } + } } enum { MAD_SUB_ECL = 1, MAD_SUB_SIGNAL, MAD_SUB_WAIT, MAD_SUB_PRESENT }; struct mad_swapchain; @@ -10895,7 +10980,9 @@ static void mad_log_nserror(const char *what, obj_handle_t err) { } /* ml884: commit the queue's open command buffer and track it for fencing. */ static void mad_queue_flush(struct mad_queue *q) { + LONG64 hz_t0; /* madeira-duo hitch recorder: lock wait included */ if (!q) return; + hz_t0 = mad_qpc(); EnterCriticalSection(&q->submit_lock); /* ml1021 */ if (!q->open_cb) { LeaveCriticalSection(&q->submit_lock); return; } if (q->npending == 16) { @@ -10936,6 +11023,7 @@ static void mad_queue_flush(struct mad_queue *q) { d3d12_log("[madeira-d3d12] batch #%llu committed (%llu lists so far)\n", (unsigned long long)q->batches, (unsigned long long)q->executed); LeaveCriticalSection(&q->submit_lock); /* ml1021 */ + InterlockedExchangeAdd64(&g_hz_flush_t, mad_qpc() - hz_t0); InterlockedIncrement(&g_hz_flush_n); } static void mad_device_flush_all(struct mad_device *d) { /* ml1021: the queue registry was read with no lock while creation and @@ -22008,6 +22096,84 @@ static void mad_vt_present(struct mad_device *d, UINT64 presents) { d3d12_log("[vis-trace] readback check so far: %ld mips equal to the GPU's own copy, %ld overwritten by a later readback, " "%ld STALE (an earlier readback), %ld different\n", (long)g_vt_chk[0], (long)g_vt_chk[1], (long)g_vt_chk[2], (long)g_vt_chk[3]); } +/* madeira-duo hitch recorder, the frame half (see mad_hz_load). Called at the end + * of every Present, so a "frame" is Present end to Present end on the game's thread. */ +struct mad_hz_snap { + LONG64 qpc, game_cpu, worker_cpu, proc_cpu, enc, open, rz, cs, create, fl, present; + LONG rzn, csn, createn, fln; + DWORD game_tid; + struct mad_xp xp; +}; +static void mad_hz_snap_take(struct mad_hz_snap *n, HANDLE worker) { + n->qpc = mad_qpc(); + n->game_tid = GetCurrentThreadId(); + n->game_cpu = mad_hz_thread_cpu(GetCurrentThread()); + n->worker_cpu = mad_hz_thread_cpu(worker); + n->proc_cpu = mad_hz_process_cpu(); + n->enc = g_es_enc_t; n->open = g_es_open_t; + n->rz = g_pt_realize; n->rzn = g_pn_realize; n->cs = g_hz_cs_realize_t; n->csn = g_hz_cs_realize_n; + n->create = g_pt_gfx + g_pt_cs; n->createn = g_pn_gfx + g_pn_cs; + n->fl = g_hz_flush_t; n->fln = g_hz_flush_n; n->present = g_hz_present_t; + memcpy(&n->xp, &g_xp, sizeof n->xp); +} +static void mad_hitch_frame(struct mad_swapchain *s, HANDLE worker, UINT64 present_no) { + static struct mad_hz_snap prev; static int have; + static LONG64 win_start, worst; static LONG frames, over[4]; + static const int bucket_ms[4] = { 33, 50, 100, 250 }; + struct mad_hz_snap n; + LONG64 qpf, d; + double ms, tms, frame; + int b; + (void)s; + mad_hz_load(); + if (g_hz_frame_ms <= 0) return; + mad_hz_snap_take(&n, worker); + qpf = n.xp.qpf ? n.xp.qpf : 1; + ms = 1000.0 / (double)qpf; tms = 1000.0 / (double)mad_tick_freq(); + if (!win_start) win_start = n.qpc; + if (have) { + d = n.qpc - prev.qpc; frame = d * ms; + frames++; if (d > worst) worst = d; + for (b = 0; b < 4; b++) if (frame > bucket_ms[b]) over[b]++; + if (frame > g_hz_frame_ms && mad_hz_take()) { + #define HZ(f_) ((double)(n.xp.f_ - prev.xp.f_) * ms) + int same = n.game_tid == prev.game_tid && n.game_cpu >= 0 && prev.game_cpu >= 0; + double gcpu = same ? (n.game_cpu - prev.game_cpu) / 10000.0 : -1.0; + double wcpu = n.worker_cpu >= 0 && prev.worker_cpu >= 0 ? (n.worker_cpu - prev.worker_cpu) / 10000.0 : -1.0; + double pcpu = n.proc_cpu >= 0 && prev.proc_cpu >= 0 ? (n.proc_cpu - prev.proc_cpu) / 10000.0 : -1.0; + double in_ecl = HZ(t_ecl_caller), in_prs = (double)(n.present - prev.present) * ms; + double wbusy = HZ(t_ecl) + HZ(t_prs) + HZ(t_wait) + HZ(t_sig) + HZ(t_pool); + char mem[96]; + mad_hz_memory(mem, sizeof mem); + d3d12_log("[hitch] frame %.1f ms at present #%llu | game thread %04lx: cpu %.1f ms, in ExecuteCommandLists %.1f (%lld calls), " + "in Present %.1f [run-ahead wait %.1f, fps cap %.1f], outside d3d12 %.1f | process cpu %.1f ms | " + "worker busy %.1f ms, cpu %.1f: replay %.1f (%lld), present %.1f (%lld) [flush %.1f, gpu latency wait %.1f (%lld), " + "drawable %.1f, blit+present+commit %.1f], fence wait %.1f (%lld), signal %.1f (%lld), pool drain %.1f | " + "encode %.1f ms, encoders open/end %.1f, commits %ld (%.1f ms) | first-use pipelines gfx %ld (%.1f ms) " + "compute %ld (%.1f ms), created %ld (%.1f ms) | %s\n", + frame, (unsigned long long)present_no, (unsigned long)n.game_tid, gcpu, in_ecl, + (long long)(n.xp.ecl_calls - prev.xp.ecl_calls), in_prs, HZ(t_thr), HZ(t_cap), frame - in_ecl - in_prs, + pcpu, wbusy, wcpu, HZ(t_ecl), (long long)(n.xp.n_ecl - prev.xp.n_ecl), HZ(t_prs), + (long long)(n.xp.pres_done - prev.xp.pres_done), HZ(t_flush), HZ(t_lat), (long long)(n.xp.n_lat - prev.xp.n_lat), + HZ(t_draw), HZ(t_cmt), HZ(t_wait), (long long)(n.xp.n_wait - prev.xp.n_wait), HZ(t_sig), + (long long)(n.xp.n_sig - prev.xp.n_sig), HZ(t_pool), + (n.enc - prev.enc) * tms, (n.open - prev.open) * tms, (long)(n.fln - prev.fln), (n.fl - prev.fl) * ms, + (long)(n.rzn - prev.rzn), (n.rz - prev.rz) * ms, (long)(n.csn - prev.csn), (n.cs - prev.cs) * ms, + (long)(n.createn - prev.createn), (n.create - prev.create) * ms, mem); + #undef HZ + } + } + if ((n.qpc - win_start) >= 5 * qpf) { /* [hitch-sum], and the next window's line budget */ + LONG dropped = InterlockedExchange(&g_hz_dropped, 0); + d3d12_log("[hitch-sum] %.1f s: %ld frames (%.1f fps), worst %.1f ms, over 33 ms %ld, over 50 ms %ld, over 100 ms %ld, " + "over 250 ms %ld, hitch lines over the cap %ld\n", (n.qpc - win_start) * ms / 1000.0, (long)frames, + frames * 1000.0 / ((n.qpc - win_start) * ms), worst * ms, (long)over[0], (long)over[1], (long)over[2], + (long)over[3], (long)dropped); + win_start = n.qpc; worst = 0; frames = 0; memset(over, 0, sizeof over); + InterlockedExchange(&g_hz_lines, 0); + } + prev = n; have = 1; +} static HRESULT STDMETHODCALLTYPE swap_Present(IDXGISwapChain4 *T, UINT sync, UINT flags) { /* ml1119: timed wrapper */ LARGE_INTEGER t0, t1; HRESULT hr; mad_xp_role('P'); InterlockedIncrement64(&g_xp.pres_enq); /* ml1128 */ @@ -22016,6 +22182,11 @@ static HRESULT STDMETHODCALLTYPE swap_Present(IDXGISwapChain4 *T, UINT sync, UIN QueryPerformanceCounter(&t1); InterlockedExchangeAdd64(&g_perf_present_ticks, t1.QuadPart - t0.QuadPart); if (g_xp.fps_cap && !(flags & DXGI_PRESENT_TEST)) mad_fps_cap_pace((struct mad_swapchain *)T, t1.QuadPart); /* madeira-bcd fps-gov */ + if (!(flags & DXGI_PRESENT_TEST)) { /* madeira-duo hitch recorder: fps-cap pacing counts as time in Present */ + struct mad_swapchain *hs = (struct mad_swapchain *)T; + InterlockedExchangeAdd64(&g_hz_present_t, mad_qpc() - t0.QuadPart); + mad_hitch_frame(hs, hs->queue ? hs->queue->sub_thread : NULL, hs->presents); + } return hr; } static HRESULT swap_Present_pool(IDXGISwapChain4 *T, UINT sync, UINT flags) { From 104c5608972b1cf6d19ecdcff2a886d39ef65d53 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Wed, 4 Nov 2026 18:26:21 +1100 Subject: [PATCH 03/76] madeira-duo: pso-warm-compute-only (warm compute pipelines only) PoE2 creates ~10k graphics pipelines and draws with ~2.6k; warming all of them compiled for the whole session on a clamped CPU. Graphics pipelines are already async (pso-async); compute ones block the render thread. Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/pe/madeira_d3d12.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index 2268e0a121..e8efa4beb5 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -3447,12 +3447,17 @@ static int mad_readback_swap_on(void) { * the warm-up turns itself off. */ struct mad_pso_warm_req { UINT64 device, info, vd; }; static void mad_pso_warm(obj_handle_t device, const void *info, const void *vd, UINT kind) { - static int on = -1; + static int on = -1, compute_only; static volatile LONG sent; struct madeira_ctl_args a; struct mad_pso_warm_req r; if (on < 0) { on = mad_cfg_int_pe("pso-warm", 0) > 0; /* pipeline cache warm-up: N background compiles of every lazy pipeline at creation (1-4; 0 = off) */ - if (on) d3d12_log("[madeira-d3d12] pso-warm: lazy pipelines are compiled once in the background when the game creates them (madeira.cfg pso-warm)\n"); } - if (!on || !device || !info) return; + /* madeira-duo: PoE2 creates ~10,000 graphics pipelines and draws with ~2,600 (text6/text8 logs, 4 Nov); + * warming all of them compiled for the whole session on a clamped CPU. Graphics pipelines are + * built off the render thread anyway (pso-async); compute ones block it at first dispatch. */ + compute_only = mad_cfg_int_pe("pso-warm-compute-only", 0) > 0; /* 1: pso-warm compiles compute pipelines only */ + if (on) d3d12_log("[madeira-d3d12] pso-warm: lazy %spipelines are compiled once in the background when the game creates them (madeira.cfg pso-warm%s)\n", + compute_only ? "compute " : "", compute_only ? ", pso-warm-compute-only" : ""); } + if (!on || !device || !info || (compute_only && kind != 2)) return; r.device = device; r.info = (UINT64)(ULONG_PTR)info; r.vd = (UINT64)(ULONG_PTR)vd; memset(&a, 0, sizeof a); a.op = 10; a.len = kind; a.ptr = (UINT64)(ULONG_PTR)&r; MadeiraCtl(&a); /* winemetal copies the descriptors before it returns */ From 3cf7034e0187d406596fea90479f638e08cb196a Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Wed, 4 Nov 2026 22:26:22 +1100 Subject: [PATCH 04/76] madeira-duo: hitch recorder without CPU-time reads; shader cache hit timing GetThreadTimes/GetProcessTimes are Wine server round trips (~100/s from the game thread) and GetThreadTimes returned process time on Madeira. The pso time line now splits out what shader cache hits cost. Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/pe/madeira_d3d12.c | 31 ++++++++++++++-------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index e8efa4beb5..c47e067198 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -1062,6 +1062,7 @@ static void mad_es_thread_exit(void) { /* DLL_THREAD_DETACH: the thread's stat /* madeira-bcd: where pipeline creation time goes -- the "Compiling shaders" * screen and the stalls at first draw. QPC ticks, summed over all threads. */ static volatile LONG64 g_pt_gfx, g_pt_cs, g_pt_conv, g_pt_lib, g_pt_rs, g_pt_realize; +static volatile LONG64 g_pt_conv_hit; static volatile LONG g_pn_conv_hit; /* madeira-duo: shader cache hits within g_pt_conv */ static volatile LONG g_pn_gfx, g_pn_cs, g_pn_lib, g_pn_rs, g_pn_realize; /* madeira-duo hitch recorder (mad_hitch_frame, mad_ecl_run): cumulative, never reset, * QPC ticks. Compute pipelines built at first dispatch; batch commits (mad_queue_flush); @@ -1073,8 +1074,8 @@ static void mad_pso_time_report(const char *why) { QueryPerformanceFrequency(&f); ms = f.QuadPart ? 1000.0 / (double)f.QuadPart : 0.0; d3d12_log("[madeira-d3d12] pso time (%s): %ld graphics pipelines %.0f ms, %ld compute %.0f ms; inside them shader conversion+cache " - "%.0f ms, %ld new Metal libraries %.0f ms; %ld root signatures %.0f ms; %ld lazy pipelines built at first draw %.0f ms\n", - why, g_pn_gfx, (double)g_pt_gfx * ms, g_pn_cs, (double)g_pt_cs * ms, (double)g_pt_conv * ms, g_pn_lib, + "%.0f ms (cache hits %ld, %.0f ms), %ld new Metal libraries %.0f ms; %ld root signatures %.0f ms; %ld lazy pipelines built at first draw %.0f ms\n", + why, g_pn_gfx, (double)g_pt_gfx * ms, g_pn_cs, (double)g_pt_cs * ms, (double)g_pt_conv * ms, (long)g_pn_conv_hit, (double)g_pt_conv_hit * ms, g_pn_lib, (double)g_pt_lib * ms, g_pn_rs, (double)g_pt_rs * ms, g_pn_realize, (double)g_pt_realize * ms); } static LONG g_perf_ecl, g_perf_signals, g_perf_waits, g_perf_polls, g_perf_qwait_sleeps; static LONGLONG g_perf_wait_ticks, g_perf_sig_lat_ticks; static LONG g_perf_sig_lat_n; @@ -10571,17 +10572,12 @@ static int mad_hz_take(void) { /* one more line in this 5 s window? */ InterlockedIncrement(&g_hz_dropped); return 0; } -static LONG64 mad_hz_ft(const FILETIME *f) { return (LONG64)(((ULONGLONG)f->dwHighDateTime << 32) | f->dwLowDateTime); } -static LONG64 mad_hz_thread_cpu(HANDLE h) { /* kernel + user, 100 ns units; -1 if unknown */ - FILETIME c, e, k, u; - if (!h || !GetThreadTimes(h, &c, &e, &k, &u)) return -1; - return mad_hz_ft(&k) + mad_hz_ft(&u); -} -static LONG64 mad_hz_process_cpu(void) { - FILETIME c, e, k, u; - if (!GetProcessTimes(GetCurrentProcess(), &c, &e, &k, &u)) return -1; - return mad_hz_ft(&k) + mad_hz_ft(&u); -} +/* No CPU-time reads: GetThreadTimes / GetProcessTimes are Wine server round trips + * (~100 a second from the game's thread in the 4 Nov res3 log) and GetThreadTimes + * answered with the PROCESS's time on Madeira (cpu above wall). The [xp-t] sampler + * has the per-thread CPU. -1 = not measured. */ +static LONG64 mad_hz_thread_cpu(HANDLE h) { (void)h; return -1; } +static LONG64 mad_hz_process_cpu(void) { return -1; } static void mad_hz_memory(char *buf, size_t n) { /* MadeiraCtl op 7: phys_footprint and what iOS still allows */ struct madeira_ctl_args a; memset(&a, 0, sizeof a); a.op = 7; MadeiraCtl(&a); @@ -17739,10 +17735,15 @@ static void mad_failmemo_add(const UINT64 key[2], const struct madeira_ir_conver } static void mad_ir_convert_cached_impl(struct madeira_ir_convert_args *a); +/* madeira-duo: the res3 log (4 Nov) spent 45.6 s in conversion+cache for 13,806 hits + * and 194 misses; split it, so the pso time line says what a hit costs. */ static void mad_ir_convert_cached(struct madeira_ir_convert_args *a) { /* madeira-bcd: timed */ - LONG64 t0 = mad_qpc(); + LONG64 t0 = mad_qpc(), dt; + LONG hits = g_sc_hit; mad_ir_convert_cached_impl(a); - InterlockedExchangeAdd64(&g_pt_conv, mad_qpc() - t0); + dt = mad_qpc() - t0; + InterlockedExchangeAdd64(&g_pt_conv, dt); + if (g_sc_hit != hits) { InterlockedExchangeAdd64(&g_pt_conv_hit, dt); InterlockedIncrement(&g_pn_conv_hit); } } static void mad_ir_convert_cached_impl(struct madeira_ir_convert_args *a) { UINT64 key[2]; int fresh = 0; From af2edf6ea966a507f03be7f7f2f11419386e0745 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Thu, 5 Nov 2026 00:15:23 +1100 Subject: [PATCH 05/76] gpu-mix: per-frame render/compute/blit pass counts and attachment load/store pixels in [perf] Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/pe/madeira_d3d12.c | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index c47e067198..d0cde10c33 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -702,6 +702,37 @@ static void mad_eco_prio_self(char role) { * call), so the measurement does not cost what it measures. */ static volatile LONG64 g_es_enc_t, g_es_open_t; static volatile LONG g_es_enc_n, g_es_open_n, g_es_use_n; +/* madeira-duo gpu-mix: what the GPU is given per frame, reported with [perf] ml1108. + * Render passes, compute and blit encoders, and the attachment traffic a tile GPU pays + * at pass edges: pixels loaded from memory (load action Load) and stored back (Store), + * summed over attachments. More passes or more load/store pixels per frame in the slow + * windows points at how the work is split; flat counts with rising GPU time point at the + * work itself or the GPU clock. */ +static volatile LONG g_gm_rp, g_gm_rp_small, g_gm_ce, g_gm_be; +static volatile LONG64 g_gm_load_px, g_gm_store_px, g_gm_clear_px, g_gm_rt_px; +static void mad_gm_pass(const struct WMTRenderPassInfo *i) { + LONG64 px = (LONG64)i->render_target_width * i->render_target_height * (i->render_target_array_length ? i->render_target_array_length : 1); + LONG64 ld = 0, st = 0, cl = 0; unsigned k; + InterlockedIncrement(&g_gm_rp); + if (px < 256 * 256) InterlockedIncrement(&g_gm_rp_small); + for (k = 0; k < 8; k++) { + if (!i->colors[k].texture) continue; + if (i->colors[k].load_action == WMTLoadActionLoad) ld += px; else if (i->colors[k].load_action == WMTLoadActionClear) cl += px; + if (i->colors[k].store_action == WMTStoreActionStore || i->colors[k].store_action == WMTStoreActionStoreAndMultisampleResolve) st += px; + } + if (i->depth.texture) { + if (i->depth.load_action == WMTLoadActionLoad) ld += px; else if (i->depth.load_action == WMTLoadActionClear) cl += px; + if (i->depth.store_action == WMTStoreActionStore) st += px; + } + if (i->stencil.texture && i->stencil.texture != i->depth.texture) { + if (i->stencil.load_action == WMTLoadActionLoad) ld += px; else if (i->stencil.load_action == WMTLoadActionClear) cl += px; + if (i->stencil.store_action == WMTStoreActionStore) st += px; + } + if (ld) InterlockedExchangeAdd64(&g_gm_load_px, ld); + if (st) InterlockedExchangeAdd64(&g_gm_store_px, st); + if (cl) InterlockedExchangeAdd64(&g_gm_clear_px, cl); + InterlockedExchangeAdd64(&g_gm_rt_px, px); +} static UINT64 g_es_freq; static inline UINT64 mad_tick(void) { #if defined(__aarch64__) || defined(__arm64ec__) @@ -957,18 +988,21 @@ static void mad_es_bce(obj_handle_t e, const struct wmtcmd_base *c) { static obj_handle_t mad_es_renc(obj_handle_t cb, struct WMTRenderPassInfo *i) { UINT64 t; obj_handle_t r; mad_eb_flush_cur(EBF_ENCODER); + if (i) mad_gm_pass(i); t = mad_tick(); r = (MTLCommandBuffer_renderCommandEncoder)(cb, i); InterlockedExchangeAdd64(&g_es_open_t, (LONG64)(mad_tick() - t)); InterlockedIncrement(&g_es_open_n); return r; } static obj_handle_t mad_es_cenc(obj_handle_t cb, bool concurrent) { UINT64 t; obj_handle_t r; mad_eb_flush_cur(EBF_ENCODER); + InterlockedIncrement(&g_gm_ce); t = mad_tick(); r = (MTLCommandBuffer_computeCommandEncoder)(cb, concurrent); InterlockedExchangeAdd64(&g_es_open_t, (LONG64)(mad_tick() - t)); InterlockedIncrement(&g_es_open_n); return r; } static obj_handle_t mad_es_benc(obj_handle_t cb) { UINT64 t; obj_handle_t r; mad_eb_flush_cur(EBF_ENCODER); + InterlockedIncrement(&g_gm_be); t = mad_tick(); r = (MTLCommandBuffer_blitCommandEncoder)(cb); InterlockedExchangeAdd64(&g_es_open_t, (LONG64)(mad_tick() - t)); InterlockedIncrement(&g_es_open_n); return r; } @@ -10842,6 +10876,16 @@ static void mad_perf_present(void) { g_perf_gpu_sum * 1000, g_perf_wait_s * 1000, 100.0 * g_perf_wait_s / wall, g_perf_presents ? g_perf_gpu_union * 1000 / g_perf_presents : 0.0, g_perf_presents ? g_perf_wait_s * 1000 / g_perf_presents : 0.0); mad_jr_report(g_perf_presents, wall); /* api-census */ + if (g_perf_presents) { /* madeira-duo gpu-mix */ + double n = (double)g_perf_presents; + LONG rp = InterlockedExchange(&g_gm_rp, 0), rs = InterlockedExchange(&g_gm_rp_small, 0); + LONG ce = InterlockedExchange(&g_gm_ce, 0), be = InterlockedExchange(&g_gm_be, 0); + LONG64 lp = InterlockedExchange64(&g_gm_load_px, 0), sp = InterlockedExchange64(&g_gm_store_px, 0); + LONG64 cp = InterlockedExchange64(&g_gm_clear_px, 0), tp = InterlockedExchange64(&g_gm_rt_px, 0); + d3d12_log("[gpu-mix] per frame: %.1f render passes (%.1f under 256x256, avg target %.2f MPix), %.1f compute, %.1f blit encoders; " + "attachment MPix loaded %.2f, stored %.2f, cleared %.2f; cbs %.1f\n", + rp / n, rs / n, rp ? tp / 1e6 / rp : 0.0, ce / n, be / n, lp / 1e6 / n, sp / 1e6 / n, cp / 1e6 / n, g_perf_cbs / n); + } { /* ml1116: encoder fence traffic per frame (mode 2 should cut waits well below updates) */ static LONG lw, lu, lb; LONG cw = g_fence_waits, cu = g_fence_updates, cb = g_barrier_seen; d3d12_log("[perf] ml1119 caller thread per frame: ExecuteCommandLists %.2f ms, Present %.2f ms (frame %.1f ms)\n", From 63a44f9b75573050a6ebca22d2e1b50e1ad7f08e Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Thu, 5 Nov 2026 00:34:08 +1100 Subject: [PATCH 06/76] gpu-work: per-window draws/vertices/dispatches/threadgroups and top render+compute pipelines in [perf] Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/pe/madeira_d3d12.c | 85 +++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 2 deletions(-) diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index d0cde10c33..8834826f5e 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -10346,6 +10346,85 @@ static void mad_ffx_load(void); static void mad_ffx_before(struct mad_exec *e, const struct mad_cmd *c); static void mad_ffx_after(struct mad_exec *e, const struct mad_cmd *c); static obj_handle_t mad_fill_pattern(struct mad_device *d, UINT32 v); +/* madeira-duo gpu-work: the work each pipeline is given, per [perf] window. Draws and + * vertices x instances for render pipelines, dispatches and threadgroups for compute + * ones, counted at replay. With [gpu-mix] flat, the pipelines whose share jumps in the + * slow windows are the work the GPU time goes to. Indirect records count as draws or + * dispatches with no size (the GPU writes it). A small open-addressed table keyed by + * the pipeline; a full table drops new pipelines (counted). */ +#define MAD_GW_N 2048 +struct mad_gw { struct mad_pso *volatile pso; volatile LONG draws; volatile LONG64 work; int compute; char name[84]; }; /* names copied: a pipeline may be freed before the report */ +static struct mad_gw g_gw[MAD_GW_N]; +static volatile LONG g_gw_draws, g_gw_disp, g_gw_ind, g_gw_full; +static volatile LONG64 g_gw_verts, g_gw_tgs; +static void mad_gw_note(struct mad_pso *p, LONG64 work) { + unsigned h, k; + if (!p) return; + h = (unsigned)(((ULONG_PTR)p >> 4) * 2654435761u) & (MAD_GW_N - 1); + for (k = 0; k < 16; k++) { + struct mad_gw *g = &g_gw[(h + k) & (MAD_GW_N - 1)]; + struct mad_pso *cur = g->pso; + if (cur != p) { + if (cur) continue; + cur = InterlockedCompareExchangePointer((void *volatile *)&g->pso, p, NULL); + if (cur && cur != p) continue; + if (!cur) { + g->compute = p->is_compute; + if (p->is_compute) snprintf(g->name, sizeof g->name, "%.48s", p->vs_name); + else snprintf(g->name, sizeof g->name, "%.40s/%.40s", p->vs_name, p->ps_name); + } + } + InterlockedIncrement(&g->draws); + if (work) InterlockedExchangeAdd64(&g->work, work); + return; + } + InterlockedIncrement(&g_gw_full); +} +static void mad_gw_draw(struct mad_exec *e, const struct mad_cmd *c) { + LONG64 v = c->kind == MC_DRAW_INDEXED ? (LONG64)c->u.drawi.icount * (c->u.drawi.inst ? c->u.drawi.inst : 1) + : (LONG64)c->u.draw.vcount * (c->u.draw.icount ? c->u.draw.icount : 1); + InterlockedIncrement(&g_gw_draws); InterlockedExchangeAdd64(&g_gw_verts, v); + mad_gw_note(e->pso, v); +} +static void mad_gw_dispatch(struct mad_exec *e, const struct mad_cmd *c) { + LONG64 t = (LONG64)c->u.dispatch.x * c->u.dispatch.y * c->u.dispatch.z; + InterlockedIncrement(&g_gw_disp); InterlockedExchangeAdd64(&g_gw_tgs, t); + mad_gw_note(e->cpso, t); +} +static void mad_gw_indirect(struct mad_exec *e, const struct mad_cmd *c) { + InterlockedExchangeAdd(&g_gw_ind, (LONG)c->u.ind.count); + mad_gw_note(c->kind == MC_DISPATCH_INDIRECT ? e->cpso : e->pso, 0); +} +/* Called from the [perf] report with the window's frame count: totals, then the top + * pipelines of each kind by work, then the table is emptied for the next window. */ +static void mad_gw_report(double frames) { + struct top { const char *p; LONG draws; LONG64 work; } tg[4], tc[4]; + unsigned i, j, used = 0; + LONG d = InterlockedExchange(&g_gw_draws, 0), di = InterlockedExchange(&g_gw_disp, 0), ind = InterlockedExchange(&g_gw_ind, 0); + LONG full = InterlockedExchange(&g_gw_full, 0); + LONG64 v = InterlockedExchange64(&g_gw_verts, 0), t = InterlockedExchange64(&g_gw_tgs, 0); + char line[1024]; int n; + memset(tg, 0, sizeof tg); memset(tc, 0, sizeof tc); + for (i = 0; i < MAD_GW_N; i++) { + struct mad_gw *g = &g_gw[i]; + struct mad_pso *p = g->pso; LONG dr; LONG64 w; struct top *tt; + if (!p) continue; + used++; + dr = InterlockedExchange(&g->draws, 0); w = InterlockedExchange64(&g->work, 0); + g->pso = NULL; + tt = g->compute ? tc : tg; + for (j = 0; j < 4; j++) if (w > tt[j].work || (!tt[j].p && dr)) break; + if (j < 4) { memmove(&tt[j + 1], &tt[j], (3 - j) * sizeof *tt); tt[j].p = g->name; tt[j].draws = dr; tt[j].work = w; } + } + d3d12_log("[gpu-work] per frame: %.0f draws, %.2f M vertices x instances, %.1f dispatches, %.0f threadgroups, %.1f indirect records; %u pipelines used in the window%s\n", + d / frames, v / 1e6 / frames, di / frames, t / frames, ind / frames, used, full ? " (table full, some not counted)" : ""); + for (j = 0, n = 0; j < 4 && tg[j].p; j++) + n += snprintf(line + n, sizeof line - n, "%s%s %.0f draws %.2f MV", j ? "; " : "", tg[j].p, tg[j].draws / frames, tg[j].work / 1e6 / frames); + if (n) d3d12_log("[gpu-work] top render per frame: %s\n", line); + for (j = 0, n = 0; j < 4 && tc[j].p; j++) + n += snprintf(line + n, sizeof line - n, "%s%s %.1f dispatches %.0f tg", j ? "; " : "", tc[j].p, tc[j].draws / frames, tc[j].work / frames); + if (n) d3d12_log("[gpu-work] top compute per frame: %s\n", line); +} static void mad_exec_list(struct mad_queue *q, struct mad_list *l, obj_handle_t cb) { g_list_seq++; struct mad_exec e; @@ -10456,12 +10535,13 @@ static void mad_exec_list(struct mad_queue *q, struct mad_list *l, obj_handle_t case MC_QUERY_BEGIN: exec_query_begin(&e, c); break; /* ml1088 */ case MC_QUERY_END: exec_query_end(&e, c); break; case MC_QUERY_RESOLVE: exec_query_resolve(&e, c); break; - case MC_DRAW: case MC_DRAW_INDEXED: exec_draw(&e, c); if (g_vt_on > 0) mad_vt_draw(&e, c); break; /* madeira-bcd vis-trace */ + case MC_DRAW: case MC_DRAW_INDEXED: exec_draw(&e, c); mad_gw_draw(&e, c); if (g_vt_on > 0) mad_vt_draw(&e, c); break; /* madeira-bcd vis-trace */ case MC_DRAW_INDIRECT: case MC_DRAW_INDEXED_INDIRECT: case MC_DISPATCH_INDIRECT: { struct mad_cmd t = *c; UINT k; UINT64 toff = 0; int tess = 0; if (!c->u.ind.args || !c->u.ind.args->buffer) { e.skipped++; break; } exec_indirect_probe(&e, c); /* madeira-bcd: diagnostics, every 3 s per pipeline */ + mad_gw_indirect(&e, c); /* madeira-duo gpu-work */ if (c->kind != MC_DISPATCH_INDIRECT && e.pso && e.pso->gs_emu == 2) /* madeira-bcd */ tess = exec_tess_indirect_prep(&e, c, &toff); for (k = 0; k < c->u.ind.count; k++) { @@ -10485,7 +10565,7 @@ static void mad_exec_list(struct mad_queue *q, struct mad_list *l, obj_handle_t if (g_vt_on > 0) InterlockedIncrement(&g_vt_copy_q[q->type & 3]); /* madeira-bcd vis-trace */ break; case MC_BLEND_FACTOR: memcpy(e.blend, c->u.blend.rgba, sizeof e.blend); e.has_blend = 1; break; - case MC_DISPATCH: exec_dispatch(&e, c); if (g_vt_on > 0) { InterlockedIncrement(&g_vt_disp); InterlockedIncrement(&g_vt_disp_q[q->type & 3]); } break; /* madeira-bcd vis-trace */ + case MC_DISPATCH: exec_dispatch(&e, c); mad_gw_dispatch(&e, c); if (g_vt_on > 0) { InterlockedIncrement(&g_vt_disp); InterlockedIncrement(&g_vt_disp_q[q->type & 3]); } break; /* madeira-bcd vis-trace */ case MC_RESOLVE: exec_resolve(&e, c); break; case MC_DISCARD: break; /* madeira-bcd rp-discard: exec_rp_note above */ } @@ -10885,6 +10965,7 @@ static void mad_perf_present(void) { d3d12_log("[gpu-mix] per frame: %.1f render passes (%.1f under 256x256, avg target %.2f MPix), %.1f compute, %.1f blit encoders; " "attachment MPix loaded %.2f, stored %.2f, cleared %.2f; cbs %.1f\n", rp / n, rs / n, rp ? tp / 1e6 / rp : 0.0, ce / n, be / n, lp / 1e6 / n, sp / 1e6 / n, cp / 1e6 / n, g_perf_cbs / n); + mad_gw_report(n); } { /* ml1116: encoder fence traffic per frame (mode 2 should cut waits well below updates) */ static LONG lw, lu, lb; LONG cw = g_fence_waits, cu = g_fence_updates, cb = g_barrier_seen; From 26275eba9f06a91234764198d4502dfbd6ae9cd3 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Thu, 5 Nov 2026 00:58:21 +1100 Subject: [PATCH 07/76] pso-async-threads: configurable background pipeline builders (default 2) Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/pe/madeira_d3d12.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index 8834826f5e..cc7bf1badb 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -6384,8 +6384,15 @@ static int mad_pa_start(void) { LONG s = InterlockedCompareExchange(&state, 1, 0); if (s == 0) { unsigned t, n = 0; + /* madeira-duo pso-async-threads: a build mostly waits on Metal's compiler + * service, which compiles several at once. On a new PoE2 map ~550 + * pipelines miss the archive at ~430 ms each, and with 2 builders enemies + * stayed invisible for seconds (text15: 11k draws skipped). */ + unsigned want = (unsigned)mad_cfg_int_pe("pso-async-threads", 2); + if (want < 1) want = 1; if (want > 8) want = 8; g_pa_sem = CreateSemaphoreA(NULL, 0, MAD_PA_MAX, NULL); - for (t = 0; g_pa_sem && t < 2; t++) { + d3d12_log("[madeira-d3d12] pso-async: %u builder threads (madeira.cfg pso-async-threads)\n", want); + for (t = 0; g_pa_sem && t < want; t++) { HANDLE h = CreateThread(NULL, 256 << 10, mad_pa_worker, NULL, 0, NULL); if (h) { CloseHandle(h); n++; } } From eaa7d1015c89ed0f30be27de5621170cdf5a99b4 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Thu, 5 Nov 2026 02:43:22 +1100 Subject: [PATCH 08/76] Name the pso-async, prebuild and submission worker threads (MADEIRA_THREAD_QOS can class them) Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/pe/madeira_d3d12.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index cc7bf1badb..58e6ad93f7 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -6358,8 +6358,21 @@ static int mad_pso_async_on(void) { } return g_pso_async; } +/* madeira-duo: name our own threads so env.MADEIRA_THREAD_QOS rules can class them + * (an unnamed guest thread runs USER_INTERACTIVE, beside the game's frame threads). */ +static void mad_name_self(const WCHAR *name) { + static HRESULT (WINAPI *set_desc)(HANDLE, const WCHAR *); + static int looked; + if (!looked) { + HMODULE k = GetModuleHandleA("kernelbase.dll"); + if (k) set_desc = (void *)GetProcAddress(k, "SetThreadDescription"); + looked = 1; + } + if (set_desc) set_desc(GetCurrentThread(), name); +} static DWORD WINAPI mad_pa_worker(void *arg) { (void)arg; + mad_name_self(L"MadeiraPSO"); /* madeira-duo: classed by MADEIRA_THREAD_QOS */ for (;;) { struct mad_pso *p = NULL; obj_handle_t pool; LONG n = 0; WaitForSingleObject(g_pa_sem, INFINITE); @@ -6446,6 +6459,7 @@ static void mad_prebuild_run(struct mad_prebuild *w) { } static DWORD WINAPI mad_prebuild_worker(void *arg) { (void)arg; + mad_name_self(L"MadeiraPrebuild"); for (;;) { obj_handle_t pool; WaitForSingleObject(g_pb_go, INFINITE); @@ -11613,6 +11627,7 @@ static void mad_swd_stall(struct mad_queue *q, const char *what, unsigned slices static DWORD WINAPI mad_sub_worker(void *arg) { struct mad_queue *q = arg; mad_xp_role('W'); /* ml1128 */ + mad_name_self(L"MadeiraSubmit"); mad_eco_prio_self(0); /* eco-prio (opt-in) */ for (;;) { struct mad_subjob *j; From 62fe919052f96a349122b3f0f94118be2a047c18 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Thu, 5 Nov 2026 03:55:51 +1100 Subject: [PATCH 09/76] xess-metalfx: MetalFX temporal upscaling behind a builtin libxess.dll madeira_d3d12 records MC_FX_TEMPORAL (MadeiraD3D12TemporalUpscale, madeira_fx.h): the replay runs one MetalFX temporal scale into a private texture and blits it to the game's output, ordered by the device fence. Scalers are cached per formats/sizes and never released. Every object answers IID_MadeiraObject so the exports can reach ours behind a Streamline wrapper. src/libxess: the XeSS 2.0 D3D12 API (all 2.0.2 export names) answered with it. Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/libxess/libxess.c | 491 +++++++++++++++++++++++++++ madeira-d3d12/src/pe/d3d12.def | 2 + madeira-d3d12/src/pe/madeira_d3d12.c | 240 +++++++++++++ madeira-d3d12/src/pe/madeira_fx.h | 37 ++ 4 files changed, 770 insertions(+) create mode 100644 madeira-d3d12/src/libxess/libxess.c create mode 100644 madeira-d3d12/src/pe/madeira_fx.h diff --git a/madeira-d3d12/src/libxess/libxess.c b/madeira-d3d12/src/libxess/libxess.c new file mode 100644 index 0000000000..3fc335bb33 --- /dev/null +++ b/madeira-d3d12/src/libxess/libxess.c @@ -0,0 +1,491 @@ +/* madeira-duo xess-metalfx: Madeira's libxess.dll. + * + * A Wine builtin that answers a game's XeSS 2.x calls with MetalFX temporal + * upscaling. The game's own libxess.dll stays untouched on disk; with + * WINEDLLOVERRIDES libxess=b Wine loads this one instead. The game keeps + * doing what it does for XeSS -- it renders jittered at the input + * resolution, hands over color, depth and motion vectors, and gets the + * upscaled image back in its output texture -- and madeira_d3d12 records a + * MetalFX temporal scale into the command list (MadeiraD3D12TemporalUpscale, + * madeira_fx.h). + * + * The API is XeSS SDK 2.0's (intel/xess, inc/xess/xess.h and xess_d3d12.h): + * the structures below repeat its layouts. Every export of Intel's 2.0.2 + * libxess is present, so a game that links against it loads; what MetalFX + * cannot stand in for (D3D11, Vulkan, debug dumps, Intel driver hooks) answers + * XESS_RESULT_ERROR_UNSUPPORTED. */ +#include +#include +#include +#include +#include +#include +#include +#include "../pe/madeira_fx.h" + +typedef enum { + XESS_RESULT_WARNING_NONEXISTING_FOLDER = 1, + XESS_RESULT_WARNING_OLD_DRIVER = 2, + XESS_RESULT_SUCCESS = 0, + XESS_RESULT_ERROR_UNSUPPORTED_DEVICE = -1, + XESS_RESULT_ERROR_UNSUPPORTED_DRIVER = -2, + XESS_RESULT_ERROR_UNINITIALIZED = -3, + XESS_RESULT_ERROR_INVALID_ARGUMENT = -4, + XESS_RESULT_ERROR_DEVICE_OUT_OF_MEMORY = -5, + XESS_RESULT_ERROR_DEVICE = -6, + XESS_RESULT_ERROR_NOT_IMPLEMENTED = -7, + XESS_RESULT_ERROR_INVALID_CONTEXT = -8, + XESS_RESULT_ERROR_OPERATION_IN_PROGRESS = -9, + XESS_RESULT_ERROR_UNSUPPORTED = -10, + XESS_RESULT_ERROR_CANT_LOAD_LIBRARY = -11, + XESS_RESULT_ERROR_WRONG_CALL_ORDER = -12, + XESS_RESULT_ERROR_UNKNOWN = -1000, +} xess_result_t; + +typedef enum { + XESS_QUALITY_SETTING_ULTRA_PERFORMANCE = 100, + XESS_QUALITY_SETTING_PERFORMANCE = 101, + XESS_QUALITY_SETTING_BALANCED = 102, + XESS_QUALITY_SETTING_QUALITY = 103, + XESS_QUALITY_SETTING_ULTRA_QUALITY = 104, + XESS_QUALITY_SETTING_ULTRA_QUALITY_PLUS = 105, + XESS_QUALITY_SETTING_AA = 106, +} xess_quality_settings_t; + +enum { + XESS_INIT_FLAG_HIGH_RES_MV = 1 << 0, + XESS_INIT_FLAG_INVERTED_DEPTH = 1 << 1, + XESS_INIT_FLAG_EXPOSURE_SCALE_TEXTURE = 1 << 2, + XESS_INIT_FLAG_RESPONSIVE_PIXEL_MASK = 1 << 3, + XESS_INIT_FLAG_USE_NDC_VELOCITY = 1 << 4, + XESS_INIT_FLAG_EXTERNAL_DESCRIPTOR_HEAP = 1 << 5, + XESS_INIT_FLAG_LDR_INPUT_COLOR = 1 << 6, + XESS_INIT_FLAG_JITTERED_MV = 1 << 7, + XESS_INIT_FLAG_ENABLE_AUTOEXPOSURE = 1 << 8, +}; + +typedef enum { + XESS_LOGGING_LEVEL_DEBUG = 0, + XESS_LOGGING_LEVEL_INFO = 1, + XESS_LOGGING_LEVEL_WARNING = 2, + XESS_LOGGING_LEVEL_ERROR = 3, +} xess_logging_level_t; + +typedef void (*xess_app_log_callback_t)(const char *message, xess_logging_level_t level); + +#pragma pack(push, 8) +typedef struct { uint16_t major, minor, patch, reserved; } xess_version_t; +typedef struct { uint32_t x, y; } xess_2d_t; +typedef xess_2d_t xess_coord_t; +typedef struct { + uint32_t requiredDescriptorCount; + uint64_t tempBufferHeapSize; + uint64_t tempTextureHeapSize; +} xess_properties_t; +typedef struct { + xess_2d_t outputResolution; + xess_quality_settings_t qualitySetting; + uint32_t initFlags; + uint32_t creationNodeMask; + uint32_t visibleNodeMask; + ID3D12Heap *pTempBufferHeap; + uint64_t bufferHeapOffset; + ID3D12Heap *pTempTextureHeap; + uint64_t textureHeapOffset; + ID3D12PipelineLibrary *pPipelineLibrary; +} xess_d3d12_init_params_t; +typedef struct { + ID3D12Resource *pColorTexture; + ID3D12Resource *pVelocityTexture; + ID3D12Resource *pDepthTexture; + ID3D12Resource *pExposureScaleTexture; + ID3D12Resource *pResponsivePixelMaskTexture; + ID3D12Resource *pOutputTexture; + float jitterOffsetX; + float jitterOffsetY; + float exposureScale; + uint32_t resetHistory; + uint32_t inputWidth; + uint32_t inputHeight; + xess_coord_t inputColorBase; + xess_coord_t inputMotionVectorBase; + xess_coord_t inputDepthBase; + xess_coord_t inputResponsiveMaskBase; + xess_coord_t reserved0; + xess_coord_t outputColorBase; + ID3D12DescriptorHeap *pDescriptorHeap; + uint32_t descriptorHeapOffset; +} xess_d3d12_execute_params_t; +#pragma pack(pop) + +#define CTX_MAGIC 0x4d465843u /* "CXFM" */ +struct xess_ctx { + uint32_t magic; + ID3D12Device *device; + xess_d3d12_init_params_t init; + int initialized; + int legacy_ratios; + float jitter_scale[2], velocity_scale[2]; + float exposure_multiplier, max_responsive_mask; + xess_app_log_callback_t log_cb; + xess_logging_level_t log_level; + LONG executes, refused; +}; +typedef struct xess_ctx *xess_context_handle_t; + +#define XESS_EXPORT __declspec(dllexport) + +/* ---- logging: the same path as madeira_d3d12's d3d12_log ---- */ +static void xlog(const char *fmt, ...) { + typedef int (__cdecl *dbg_output_fn)(const char *); + static dbg_output_fn dbg_output; + static int looked; + char buf[900]; + size_t len; + va_list ap; + memcpy(buf, "[xess-metalfx] ", 15); + va_start(ap, fmt); + vsnprintf(buf + 15, sizeof buf - 17, fmt, ap); + va_end(ap); + len = strlen(buf); + if (!len || buf[len - 1] != '\n') { buf[len] = '\n'; buf[len + 1] = 0; } + if (!looked) { + HMODULE nt = GetModuleHandleA("ntdll.dll"); + if (nt) dbg_output = (dbg_output_fn)GetProcAddress(nt, "__wine_dbg_output"); + looked = 1; + } + if (dbg_output) dbg_output(buf); +} + +/* ---- madeira_d3d12's exports ---- */ +static PFN_MadeiraD3D12TemporalUpscaleSupported p_supported; +static PFN_MadeiraD3D12TemporalUpscale p_upscale; +static int bridge_ready(void) { + static int state; /* 0 not looked, 1 found, -1 missing */ + if (!state) { + const char *names[] = { "d3d12.dll", "madeira_d3d12.dll" }; + unsigned i; + for (i = 0; i < 2 && !p_upscale; i++) { + HMODULE m = GetModuleHandleA(names[i]); + if (!m) continue; + p_supported = (PFN_MadeiraD3D12TemporalUpscaleSupported)GetProcAddress(m, "MadeiraD3D12TemporalUpscaleSupported"); + p_upscale = (PFN_MadeiraD3D12TemporalUpscale)GetProcAddress(m, "MadeiraD3D12TemporalUpscale"); + } + state = p_supported && p_upscale ? 1 : -1; + xlog("Madeira libxess (XeSS 2.0 API over MetalFX temporal): madeira_d3d12 bridge %s", + state > 0 ? "found" : "MISSING -- XeSS reports an unsupported device"); + } + return state > 0; +} + +static struct xess_ctx *ctx_of(xess_context_handle_t h) { + return h && h->magic == CTX_MAGIC ? h : NULL; +} + +/* Output/input ratio per quality setting: XeSS 1.3+ ratios, or the 1.2 ones + * after xessForceLegacyScaleFactors. MetalFX is created for up to 3x. */ +static float quality_ratio(xess_quality_settings_t q, int legacy) { + switch (q) { + case XESS_QUALITY_SETTING_ULTRA_PERFORMANCE: return 3.0f; + case XESS_QUALITY_SETTING_PERFORMANCE: return legacy ? 2.0f : 2.3f; + case XESS_QUALITY_SETTING_BALANCED: return legacy ? 1.7f : 2.0f; + case XESS_QUALITY_SETTING_QUALITY: return legacy ? 1.5f : 1.7f; + case XESS_QUALITY_SETTING_ULTRA_QUALITY: return legacy ? 1.3f : 1.5f; + case XESS_QUALITY_SETTING_ULTRA_QUALITY_PLUS: return 1.3f; + case XESS_QUALITY_SETTING_AA: return 1.0f; + default: return 0.0f; + } +} +static uint32_t scaled(uint32_t out, float ratio) { + uint32_t v = (uint32_t)((float)out / ratio + 0.5f); + return v ? v : 1; +} + +/* ---- the XeSS API ---- */ +XESS_EXPORT xess_result_t xessGetVersion(xess_version_t *v) { + if (!v) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + v->major = 2; v->minor = 0; v->patch = 2; v->reserved = 0; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessGetIntelXeFXVersion(xess_context_handle_t h, xess_version_t *v) { + if (!ctx_of(h)) return XESS_RESULT_ERROR_INVALID_CONTEXT; + if (!v) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + memset(v, 0, sizeof *v); /* no XeFX: not an Intel GPU */ + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessD3D12CreateContext(ID3D12Device *device, xess_context_handle_t *out) { + struct xess_ctx *c; + if (!device || !out) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + *out = NULL; + if (!bridge_ready() || !p_supported(device)) { + xlog("xessD3D12CreateContext: %s", p_supported ? "this GPU has no MetalFX temporal scaler" : "no madeira_d3d12 bridge"); + return XESS_RESULT_ERROR_UNSUPPORTED_DEVICE; + } + c = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof *c); + if (!c) return XESS_RESULT_ERROR_DEVICE_OUT_OF_MEMORY; + c->magic = CTX_MAGIC; + c->device = device; + device->lpVtbl->AddRef(device); + c->jitter_scale[0] = c->jitter_scale[1] = 1.0f; + c->velocity_scale[0] = c->velocity_scale[1] = 1.0f; + c->exposure_multiplier = 1.0f; + c->max_responsive_mask = 1.0f; + *out = c; + xlog("xessD3D12CreateContext: context %p", (void *)c); + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessD3D12BuildPipelines(xess_context_handle_t h, ID3D12PipelineLibrary *lib, bool blocking, uint32_t flags) { + (void)lib; (void)blocking; (void)flags; + return ctx_of(h) ? XESS_RESULT_SUCCESS : XESS_RESULT_ERROR_INVALID_CONTEXT; +} +XESS_EXPORT xess_result_t xessGetPipelineBuildStatus(xess_context_handle_t h) { + return ctx_of(h) ? XESS_RESULT_SUCCESS : XESS_RESULT_ERROR_INVALID_CONTEXT; +} +XESS_EXPORT xess_result_t xessD3D12Init(xess_context_handle_t h, const xess_d3d12_init_params_t *p) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + if (!p || !p->outputResolution.x || !p->outputResolution.y || !quality_ratio(p->qualitySetting, 0)) + return XESS_RESULT_ERROR_INVALID_ARGUMENT; + c->init = *p; + c->initialized = 1; + xlog("xessD3D12Init: output %ux%u, quality %d, flags %#x%s%s%s%s%s%s", p->outputResolution.x, p->outputResolution.y, + (int)p->qualitySetting, p->initFlags, + (p->initFlags & XESS_INIT_FLAG_HIGH_RES_MV) ? " HIGH_RES_MV(unsupported)" : "", + (p->initFlags & XESS_INIT_FLAG_INVERTED_DEPTH) ? " INVERTED_DEPTH" : "", + (p->initFlags & XESS_INIT_FLAG_EXPOSURE_SCALE_TEXTURE) ? " EXPOSURE_TEXTURE" : "", + (p->initFlags & XESS_INIT_FLAG_USE_NDC_VELOCITY) ? " NDC_VELOCITY" : "", + (p->initFlags & XESS_INIT_FLAG_LDR_INPUT_COLOR) ? " LDR" : "", + (p->initFlags & XESS_INIT_FLAG_ENABLE_AUTOEXPOSURE) ? " AUTOEXPOSURE" : ""); + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessD3D12GetInitParams(xess_context_handle_t h, xess_d3d12_init_params_t *p) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + if (!p) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + if (!c->initialized) return XESS_RESULT_ERROR_UNINITIALIZED; + *p = c->init; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessGetProperties(xess_context_handle_t h, const xess_2d_t *out, xess_properties_t *props) { + (void)out; + if (!ctx_of(h)) return XESS_RESULT_ERROR_INVALID_CONTEXT; + if (!props) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + /* MetalFX keeps its own history; small non-zero sizes so a game that + * creates the heaps it is told about still gets valid ones. */ + props->requiredDescriptorCount = 16; + props->tempBufferHeapSize = 65536; + props->tempTextureHeapSize = 65536; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessGetInputResolution(xess_context_handle_t h, const xess_2d_t *out, xess_quality_settings_t q, xess_2d_t *in) { + struct xess_ctx *c = ctx_of(h); + float r; + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + if (!out || !in || !(r = quality_ratio(q, c->legacy_ratios))) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + in->x = scaled(out->x, r); in->y = scaled(out->y, r); + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessGetOptimalInputResolution(xess_context_handle_t h, const xess_2d_t *out, xess_quality_settings_t q, + xess_2d_t *optimal, xess_2d_t *minimum, xess_2d_t *maximum) { + struct xess_ctx *c = ctx_of(h); + float r; + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + if (!out || !optimal || !(r = quality_ratio(q, c->legacy_ratios))) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + optimal->x = scaled(out->x, r); optimal->y = scaled(out->y, r); + if (minimum) { minimum->x = scaled(out->x, 3.0f); minimum->y = scaled(out->y, 3.0f); } + if (maximum) *maximum = *out; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessGetJitterScale(xess_context_handle_t h, float *x, float *y) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + if (!x || !y) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + *x = c->jitter_scale[0]; *y = c->jitter_scale[1]; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessSetJitterScale(xess_context_handle_t h, float x, float y) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + c->jitter_scale[0] = x; c->jitter_scale[1] = y; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessGetVelocityScale(xess_context_handle_t h, float *x, float *y) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + if (!x || !y) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + *x = c->velocity_scale[0]; *y = c->velocity_scale[1]; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessSetVelocityScale(xess_context_handle_t h, float x, float y) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + c->velocity_scale[0] = x; c->velocity_scale[1] = y; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessSetExposureMultiplier(xess_context_handle_t h, float scale) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + c->exposure_multiplier = scale; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessGetExposureMultiplier(xess_context_handle_t h, float *scale) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + if (!scale) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + *scale = c->exposure_multiplier; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessSetMaxResponsiveMaskValue(xess_context_handle_t h, float value) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + c->max_responsive_mask = value; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessGetMaxResponsiveMaskValue(xess_context_handle_t h, float *value) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + if (!value) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + *value = c->max_responsive_mask; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessSetLoggingCallback(xess_context_handle_t h, xess_logging_level_t level, xess_app_log_callback_t cb) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + c->log_level = level; c->log_cb = cb; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessIsOptimalDriver(xess_context_handle_t h) { + return ctx_of(h) ? XESS_RESULT_SUCCESS : XESS_RESULT_ERROR_INVALID_CONTEXT; +} +XESS_EXPORT xess_result_t xessForceLegacyScaleFactors(xess_context_handle_t h, bool force) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + c->legacy_ratios = force; + return XESS_RESULT_SUCCESS; +} +XESS_EXPORT xess_result_t xessSelectNetworkModel(xess_context_handle_t h, int model) { + (void)model; + return ctx_of(h) ? XESS_RESULT_SUCCESS : XESS_RESULT_ERROR_INVALID_CONTEXT; +} +XESS_EXPORT xess_result_t xessDestroyContext(xess_context_handle_t h) { + struct xess_ctx *c = ctx_of(h); + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + xlog("xessDestroyContext: context %p after %ld executes (%ld refused)", (void *)c, (long)c->executes, (long)c->refused); + c->magic = 0; + if (c->device) c->device->lpVtbl->Release(c->device); + HeapFree(GetProcessHeap(), 0, c); + return XESS_RESULT_SUCCESS; +} + +XESS_EXPORT xess_result_t xessD3D12Execute(xess_context_handle_t h, ID3D12GraphicsCommandList *list, const xess_d3d12_execute_params_t *p) { + struct xess_ctx *c = ctx_of(h); + struct madeira_temporal_upscale_args a; + uint32_t flags; + float mvx, mvy; + HRESULT hr; + LONG n; + if (!c) return XESS_RESULT_ERROR_INVALID_CONTEXT; + if (!c->initialized) return XESS_RESULT_ERROR_UNINITIALIZED; + if (!list || !p || !p->pColorTexture || !p->pVelocityTexture || !p->pOutputTexture) return XESS_RESULT_ERROR_INVALID_ARGUMENT; + flags = c->init.initFlags; + if (!p->pDepthTexture || (flags & XESS_INIT_FLAG_HIGH_RES_MV)) { + /* MetalFX needs depth, and motion vectors at the input size */ + if (InterlockedIncrement(&c->refused) <= 4) + xlog("xessD3D12Execute refused: %s", !p->pDepthTexture ? "no depth texture" : "display-resolution motion vectors are not supported yet"); + return XESS_RESULT_ERROR_UNSUPPORTED; + } + /* XeSS motion vectors are in input pixels (or NDC with USE_NDC_VELOCITY), + * multiplied by the velocity scale; MetalFX wants a factor to input pixels. */ + mvx = c->velocity_scale[0]; mvy = c->velocity_scale[1]; + if (flags & XESS_INIT_FLAG_USE_NDC_VELOCITY) { + mvx *= 0.5f * (float)p->inputWidth; + mvy *= -0.5f * (float)p->inputHeight; + } + memset(&a, 0, sizeof a); + a.size = sizeof a; + a.flags = (p->resetHistory ? MADEIRA_TU_RESET : 0) | + ((flags & XESS_INIT_FLAG_INVERTED_DEPTH) ? MADEIRA_TU_DEPTH_REVERSED : 0) | + ((flags & XESS_INIT_FLAG_ENABLE_AUTOEXPOSURE) ? MADEIRA_TU_AUTO_EXPOSURE : 0); + a.color = p->pColorTexture; + a.depth = p->pDepthTexture; + a.motion = p->pVelocityTexture; + a.exposure = (flags & XESS_INIT_FLAG_EXPOSURE_SCALE_TEXTURE) ? p->pExposureScaleTexture : NULL; + a.output = p->pOutputTexture; + a.input_width = p->inputWidth; + a.input_height = p->inputHeight; + a.jitter_x = p->jitterOffsetX * c->jitter_scale[0]; + a.jitter_y = p->jitterOffsetY * c->jitter_scale[1]; + a.motion_scale_x = mvx; + a.motion_scale_y = mvy; + /* exposureScale is logged, not applied: MetalFX's preExposure is a value + * already multiplied into the color, a different contract. */ + a.pre_exposure = 1.0f; + hr = p_upscale(list, &a); + n = InterlockedIncrement(&c->executes); + if (n <= 4) + xlog("xessD3D12Execute #%ld: input %ux%u (color base %u,%u, output base %u,%u), jitter %.3f %.3f, velocity scale %.3f %.3f, " + "exposure %.3f x %.3f, reset %u, responsive mask %s -> %#lx", + (long)n, p->inputWidth, p->inputHeight, p->inputColorBase.x, p->inputColorBase.y, p->outputColorBase.x, p->outputColorBase.y, + p->jitterOffsetX, p->jitterOffsetY, c->velocity_scale[0], c->velocity_scale[1], p->exposureScale, c->exposure_multiplier, + p->resetHistory, p->pResponsivePixelMaskTexture ? "given (ignored)" : "none", (unsigned long)hr); + else if (FAILED(hr) && InterlockedIncrement(&c->refused) <= 8) + xlog("xessD3D12Execute #%ld failed: %#lx", (long)n, (unsigned long)hr); + return SUCCEEDED(hr) ? XESS_RESULT_SUCCESS : XESS_RESULT_ERROR_INVALID_ARGUMENT; +} + +/* ---- the rest of Intel's 2.0.2 exports: not available here ---- */ +#define UNSUPPORTED(name) XESS_EXPORT xess_result_t name(void) { return XESS_RESULT_ERROR_UNSUPPORTED; } +UNSUPPORTED(xessD3D12GetProfilingData) +UNSUPPORTED(xessD3D12GetResourcesToDump) +UNSUPPORTED(xessGetProfilingData) +UNSUPPORTED(xessStartDump) +UNSUPPORTED(xessGetContextParameterP) +UNSUPPORTED(xessSetContextParameterF) +UNSUPPORTED(xessAILGetDecision) +UNSUPPORTED(xessAILGetVersion) +UNSUPPORTED(xessVKAILGetDecision) +UNSUPPORTED(xessTrinityCreateContext) +UNSUPPORTED(xessTrinityGetRequiredDeviceExtensions) +UNSUPPORTED(xessTrinityGetRequiredDeviceFeatures) +UNSUPPORTED(xessTrinityGetRequiredInstanceExtensions) +UNSUPPORTED(xessVKBuildPipelines) +UNSUPPORTED(xessVKCreateContext) +UNSUPPORTED(xessVKExecute) +UNSUPPORTED(xessVKGetInitParams) +UNSUPPORTED(xessVKGetRequiredDeviceExtensions) +UNSUPPORTED(xessVKGetRequiredDeviceFeatures) +UNSUPPORTED(xessVKGetRequiredInstanceExtensions) +UNSUPPORTED(xessVKGetResourcesToDump) +UNSUPPORTED(xessVKInit) +UNSUPPORTED(INTC_D3D11_XessCreateContext) +UNSUPPORTED(INTC_D3D11_XessDestroyContext) +UNSUPPORTED(INTC_D3D11_XessExecute) +UNSUPPORTED(INTC_D3D11_XessForceLegacyScaleFactors) +UNSUPPORTED(INTC_D3D11_XessGetExposureMultiplier) +UNSUPPORTED(INTC_D3D11_XessGetInitParams) +UNSUPPORTED(INTC_D3D11_XessGetInputResolution) +UNSUPPORTED(INTC_D3D11_XessGetIntelXeFXVersion) +UNSUPPORTED(INTC_D3D11_XessGetJitterScale) +UNSUPPORTED(INTC_D3D11_XessGetOptimalInputResolution) +UNSUPPORTED(INTC_D3D11_XessGetProfilingData) +UNSUPPORTED(INTC_D3D11_XessGetVelocityScale) +UNSUPPORTED(INTC_D3D11_XessGetVersion) +UNSUPPORTED(INTC_D3D11_XessInit) +UNSUPPORTED(INTC_D3D11_XessIsOptimalDriver) +UNSUPPORTED(INTC_D3D11_XessSelectNetworkModel) +UNSUPPORTED(INTC_D3D11_XessSetExposureMultiplier) +UNSUPPORTED(INTC_D3D11_XessSetJitterScale) +UNSUPPORTED(INTC_D3D11_XessSetLoggingCallback) +UNSUPPORTED(INTC_D3D11_XessSetVelocityScale) +UNSUPPORTED(INTC_D3D12_GetApplicationInfo) +UNSUPPORTED(INTC_D3D12_GetGpuCrashDumpBufferInfo) +UNSUPPORTED(INTC_D3D12_GpuCrashDumpOnCommandListCreate) +UNSUPPORTED(INTC_D3D12_GpuCrashDumpOnCommandListDestroy) +UNSUPPORTED(INTC_D3D12_GpuCrashDumpOnDeviceDestroy) +UNSUPPORTED(INTC_D3D12_RegisterDriverCallbacks) + +BOOL WINAPI DllMain(HINSTANCE inst, DWORD reason, void *reserved) { + (void)reserved; + if (reason == DLL_PROCESS_ATTACH) DisableThreadLibraryCalls(inst); + return TRUE; +} diff --git a/madeira-d3d12/src/pe/d3d12.def b/madeira-d3d12/src/pe/d3d12.def index a7190b7d14..a797ee5e5a 100644 --- a/madeira-d3d12/src/pe/d3d12.def +++ b/madeira-d3d12/src/pe/d3d12.def @@ -23,3 +23,5 @@ EXPORTS MadeiraD3D12PresenterAcquire MadeiraD3D12PresenterPresent MadeiraD3D12PresenterDestroy + MadeiraD3D12TemporalUpscaleSupported + MadeiraD3D12TemporalUpscale diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index 58e6ad93f7..76b22ec06f 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -41,6 +41,7 @@ #include "madeira_graphics_entry.h" #include #include "madeira_list_journal.h" /* list-journal, api-census */ +#include "madeira_fx.h" /* madeira-duo xess-metalfx */ /* madeira-bcd: MAD_BUILD_ID (build-pe.sh passes it from the environment) names the build, * so a log says which runtime ran. */ @@ -1536,9 +1537,14 @@ static HRESULT mad_creation_failure(struct mad_device *d, const char *what) { return E_OUTOFMEMORY; } +/* madeira-duo xess-metalfx: every object answers this IID with itself, so an + * export handed a wrapper of one of our objects (Streamline's interposer + * forwards interfaces it does not know) can reach the object behind it. */ +DEFINE_GUID(IID_MadeiraObject, 0x6d616465, 0x6972, 0x6166, 0x78, 0x74, 0x65, 0x6d, 0x70, 0x6f, 0x72, 0x31); static HRESULT mad_qi(struct mad_obj *o, REFIID riid, void **out, int is_device_child) { if (!out) return E_POINTER; *out = NULL; + if (riid && IsEqualGUID(riid, &IID_MadeiraObject)) { InterlockedIncrement(&o->refs); *out = o; return S_OK; } if (IsEqualGUID(riid, &IID_IUnknown) || IsEqualGUID(riid, o->iid) || IsEqualGUID(riid, &IID_ID3D12Object) || (is_device_child && IsEqualGUID(riid, &IID_ID3D12DeviceChild))) { @@ -1933,6 +1939,7 @@ enum mad_ck { MC_CBV_LATCH, /* madeira-bcd static-cbv: a table's constant-buffer descriptors as they were when a draw was recorded */ MC_DISCARD, /* madeira-bcd rp-discard: a DiscardResource (u.discard); the replay only notes it */ MC_WBI, /* write-buffer-immediate: one WriteBufferImmediate value (u.wbi), written by a 4-byte blit copy */ + MC_FX_TEMPORAL, /* madeira-duo xess-metalfx: one MetalFX temporal scale (u.fxt), see MadeiraD3D12TemporalUpscale */ }; struct mad_cmd { enum mad_ck kind; @@ -1968,6 +1975,8 @@ struct mad_cmd { struct { UINT bp, index, data, n; UINT64 va; } latch; /* madeira-bcd static-cbv: bind point (0 graphics, 1 compute), parameter, descriptors in cdata */ struct { struct mad_resource *res; UINT whole; } discard; /* madeira-bcd rp-discard: whole = every subresource, no rectangles */ struct { struct mad_resource *res; UINT64 off; UINT32 value; UINT32 mode; } wbi; /* write-buffer-immediate */ + struct { struct mad_resource *color, *depth, *motion, *exposure, *output; + UINT32 in_w, in_h, flags; float jx, jy, mvx, mvy, pre_exposure; } fxt; /* madeira-duo xess-metalfx: MADEIRA_TU_* flags */ } u; }; @@ -3737,6 +3746,7 @@ static int mad_cmd_names(const struct mad_cmd *c, const struct mad_resource *r) case MC_CLEAR_RT: case MC_CLEAR_DS: return c->u.clear.res == r; case MC_DISCARD: return c->u.discard.res == r; case MC_WBI: return c->u.wbi.res == r; + case MC_FX_TEMPORAL: return c->u.fxt.color == r || c->u.fxt.depth == r || c->u.fxt.motion == r || c->u.fxt.exposure == r || c->u.fxt.output == r; default: return 0; } } @@ -3847,6 +3857,7 @@ static void exec_rp_note(struct mad_exec *e, const struct mad_cmd *c) { if (e->npend && mad_clear_defer_on()) exec_flush_other_views(e, c->u.clear.res, &c->u.clear.v); break; case MC_RESOLVE: break; /* exec_resolve applies every pending clear first */ + case MC_FX_TEMPORAL: break; /* exec_fx_temporal applies every pending clear first */ default: return; } if (e->rp_ndisc) exec_disc_touch(e, c); @@ -10446,6 +10457,165 @@ static void mad_gw_report(double frames) { n += snprintf(line + n, sizeof line - n, "%s%s %.1f dispatches %.0f tg", j ? "; " : "", tc[j].p, tc[j].draws / frames, tc[j].work / frames); if (n) d3d12_log("[gpu-work] top compute per frame: %s\n", line); } +/* madeira-duo xess-metalfx: MetalFX TEMPORAL UPSCALING IN THE REPLAY. + * MadeiraD3D12TemporalUpscale (Madeira's libxess.dll answers a game's XeSS + * calls with it) records MC_FX_TEMPORAL; here it becomes one MetalFX temporal + * scale on the list's command buffer. The scaler writes a private texture of + * our own, made with every usage MetalFX may ask of its output, and a blit + * copies that into the game's output texture, whose usage flags are the + * game's. Ordering: open encoders end first (they update the device fence), + * the scaler waits for that fence and updates it, and the copy waits again. + * Scalers are made once per (formats, sizes, auto exposure) and kept, as + * DXMT's D3D11 path does: an XeSS context comes and goes with resolution + * changes, and a scaler the GPU may still use must not be released. + * madeira.cfg fx-temporal-mv-x / -mv-y / -jitter-x / -jitter-y multiply the + * game's motion vectors and jitter (sign conventions; default 1), + * fx-temporal-max-scale caps the output/input ratio the scaler accepts + * (default 3). */ +struct mad_fxt_entry { + obj_handle_t scaler, out, mv_view; + const struct mad_resource *mv_res; + enum WMTPixelFormat cpf, opf, dpf, mpf; + UINT cw, ch, ow, oh; + int autoexp; +}; +static struct mad_fxt_entry g_fxt[8]; +static unsigned g_nfxt; +static SRWLOCK g_fxt_lock = SRWLOCK_INIT; +static volatile LONG g_fxt_done, g_fxt_skipped; +static float g_fxt_mul[4] = { 1, 1, 1, 1 }, g_fxt_max_scale = 3.0f; +static double mad_cfg_float_pe(const char *key, double dflt) { + char v[64]; + if (!mad_cfg_str_pe(key, v, sizeof v) || !v[0]) return dflt; + return strtod(v, NULL); +} +static enum WMTPixelFormat mad_fxt_mv_pf(enum WMTPixelFormat f) { /* as DXMT's GetCorrectMotionVectorFormat */ + switch (f) { + case WMTPixelFormatRG16Uint: case WMTPixelFormatRG16Float: case WMTPixelFormatRG16Sint: + case WMTPixelFormatRG16Snorm: case WMTPixelFormatRG16Unorm: + return WMTPixelFormatRG16Float; + case WMTPixelFormatRG32Uint: case WMTPixelFormatRG32Float: case WMTPixelFormatRG32Sint: + return WMTPixelFormatRG32Float; + case WMTPixelFormatRGBA16Sint: case WMTPixelFormatRGBA16Snorm: case WMTPixelFormatRGBA16Uint: + case WMTPixelFormatRGBA16Unorm: case WMTPixelFormatRGBA16Float: + return WMTPixelFormatRGBA16Float; + default: + return WMTPixelFormatInvalid; + } +} +static void mad_fxt_skip(struct mad_exec *e, const char *why, const struct mad_cmd *c) { + LONG n = InterlockedIncrement(&g_fxt_skipped); + if (n <= 8 || (n % 1000) == 0) + d3d12_log("[xess-metalfx] temporal scale skipped (%s): color %u depth %u motion %u output %u (%ld skipped so far)\n", why, + c->u.fxt.color ? (unsigned)c->u.fxt.color->tex_pf : 0, c->u.fxt.depth ? (unsigned)c->u.fxt.depth->tex_pf : 0, + c->u.fxt.motion ? (unsigned)c->u.fxt.motion->tex_pf : 0, c->u.fxt.output ? (unsigned)c->u.fxt.output->tex_pf : 0, (long)n); + MAD_SKIP(e); +} +static struct mad_fxt_entry *mad_fxt_get(struct mad_device *d, const struct mad_cmd *c, enum WMTPixelFormat mpf) { + const struct mad_resource *col = c->u.fxt.color, *dep = c->u.fxt.depth, *out = c->u.fxt.output; + int autoexp = (c->u.fxt.flags & MADEIRA_TU_AUTO_EXPOSURE) != 0; + struct mad_fxt_entry *en = NULL; + unsigned k; + AcquireSRWLockExclusive(&g_fxt_lock); + for (k = 0; k < g_nfxt; k++) { + struct mad_fxt_entry *x = &g_fxt[k]; + if (x->cpf == col->tex_pf && x->opf == out->tex_pf && x->dpf == dep->tex_pf && x->mpf == mpf && + x->cw == col->width && x->ch == col->height && x->ow == out->width && x->oh == out->height && x->autoexp == autoexp) { en = x; break; } + } + if (!en && g_nfxt < sizeof g_fxt / sizeof g_fxt[0]) { + struct WMTFXTemporalScalerInfo si; struct WMTTextureInfo ti; + if (!g_nfxt) { + g_fxt_mul[0] = (float)mad_cfg_float_pe("fx-temporal-mv-x", 1.0); + g_fxt_mul[1] = (float)mad_cfg_float_pe("fx-temporal-mv-y", 1.0); + g_fxt_mul[2] = (float)mad_cfg_float_pe("fx-temporal-jitter-x", 1.0); + g_fxt_mul[3] = (float)mad_cfg_float_pe("fx-temporal-jitter-y", 1.0); + g_fxt_max_scale = (float)mad_cfg_float_pe("fx-temporal-max-scale", 3.0); + if (g_fxt_max_scale < 1.0f) g_fxt_max_scale = 1.0f; + } + en = &g_fxt[g_nfxt++]; + memset(en, 0, sizeof *en); + en->cpf = col->tex_pf; en->opf = out->tex_pf; en->dpf = dep->tex_pf; en->mpf = mpf; + en->cw = col->width; en->ch = col->height; en->ow = out->width; en->oh = out->height; en->autoexp = autoexp; + memset(&si, 0, sizeof si); + si.color_format = en->cpf; si.output_format = en->opf; si.depth_format = en->dpf; si.motion_format = mpf; + si.input_width = en->cw; si.input_height = en->ch; si.output_width = en->ow; si.output_height = en->oh; + si.input_content_min_scale = 1.0f; si.input_content_max_scale = g_fxt_max_scale; + si.auto_exposure = autoexp; si.input_content_properties_enabled = true; si.requires_synchronous_initialization = true; + en->scaler = MTLDevice_newTemporalScaler(d->mtl_device, &si); + if (en->scaler) { + memset(&ti, 0, sizeof ti); + ti.pixel_format = en->opf; ti.width = en->ow; ti.height = en->oh; ti.depth = 1; ti.array_length = 1; + ti.type = WMTTextureType2D; ti.mipmap_level_count = 1; ti.sample_count = 1; + ti.usage = (enum WMTTextureUsage)(WMTTextureUsageRenderTarget | WMTTextureUsageShaderRead | WMTTextureUsageShaderWrite); + ti.options = WMTResourceStorageModePrivate; + en->out = MTLDevice_newTexture(d->mtl_device, &ti); + } + d3d12_log("[xess-metalfx] MetalFX temporal scaler #%u: color %ux%u fmt %u, depth fmt %u, motion fmt %u (game %u), output %ux%u fmt %u, " + "max scale %.2f, auto exposure %d -> scaler %s, output texture %s; mv x%.2f y%.2f, jitter x%.2f y%.2f\n", + g_nfxt, en->cw, en->ch, (unsigned)en->cpf, (unsigned)en->dpf, (unsigned)mpf, (unsigned)c->u.fxt.motion->tex_pf, + en->ow, en->oh, (unsigned)en->opf, g_fxt_max_scale, autoexp, en->scaler ? "ok" : "REFUSED", en->out ? "ok" : "FAILED", + g_fxt_mul[0], g_fxt_mul[1], g_fxt_mul[2], g_fxt_mul[3]); + } + ReleaseSRWLockExclusive(&g_fxt_lock); + return en; +} +static void exec_fx_temporal(struct mad_exec *e, const struct mad_cmd *c) { + struct mad_device *d = e->q->device; + struct mad_resource *col = c->u.fxt.color, *dep = c->u.fxt.depth, *mv = c->u.fxt.motion, *ex = c->u.fxt.exposure, *out = c->u.fxt.output; + struct mad_fxt_entry *en; + struct WMTFXTemporalScalerProps p; + struct wmtcmd_blit_copy_from_texture_to_texture k; + enum WMTPixelFormat mpf; + obj_handle_t mtex, fence; + LONG n; + if (!col || !col->texture || !dep || !dep->texture || !mv || !mv->texture || !out || !out->texture || (ex && !ex->texture)) { + mad_fxt_skip(e, "a texture is missing", c); return; + } + if ((mpf = mad_fxt_mv_pf(mv->tex_pf)) == WMTPixelFormatInvalid) { mad_fxt_skip(e, "motion vector format", c); return; } + if (!(en = mad_fxt_get(d, c, mpf))) { mad_fxt_skip(e, "scaler table full", c); return; } + if (!en->scaler || !en->out) { mad_fxt_skip(e, "no scaler", c); return; } + exec_end(e); + while (e->npend) exec_flush_clear(e, 0); /* pending clears of what the scaler reads go first */ + mtex = mv->texture; + if (mpf != mv->tex_pf) { /* a typed view; kept per entry: a command buffer may not retain what it reads */ + if (en->mv_res != mv || !en->mv_view) { + if (en->mv_view) NSObject_release(en->mv_view); /* only when the game changed its motion texture */ + en->mv_view = mad_resolve_view(mv, mpf, 0, 0); en->mv_res = mv; + } + if (!en->mv_view) { mad_fxt_skip(e, "motion vector view", c); return; } + mtex = en->mv_view; + } + memset(&p, 0, sizeof p); + p.input_content_width = c->u.fxt.in_w && c->u.fxt.in_w <= en->cw ? c->u.fxt.in_w : en->cw; + p.input_content_height = c->u.fxt.in_h && c->u.fxt.in_h <= en->ch ? c->u.fxt.in_h : en->ch; + p.reset = (c->u.fxt.flags & MADEIRA_TU_RESET) != 0; + p.depth_reversed = (c->u.fxt.flags & MADEIRA_TU_DEPTH_REVERSED) != 0; + p.motion_vector_scale_x = c->u.fxt.mvx * g_fxt_mul[0]; + p.motion_vector_scale_y = c->u.fxt.mvy * g_fxt_mul[1]; + p.jitter_offset_x = c->u.fxt.jx * g_fxt_mul[2]; + p.jitter_offset_y = c->u.fxt.jy * g_fxt_mul[3]; + p.pre_exposure = c->u.fxt.pre_exposure > 0 ? c->u.fxt.pre_exposure : 1.0f; + fence = e->mode ? mad_enc_fence_obj(d) : 0; + MTLCommandBuffer_encodeTemporalScale(e->cb, en->scaler, col->texture, en->out, dep->texture, mtex, ex ? ex->texture : 0, fence, &p); + g_enc_seq++; + e->fence_needed = 1; /* the copy waits for the scaler */ + if (!exec_begin_blit(e)) { mad_fxt_skip(e, "no blit encoder", c); return; } + exec_note_write(e, out); + memset(&k, 0, sizeof k); + k.type = WMTBlitCommandCopyFromTextureToTexture; + k.src = en->out; + k.src_size.width = en->ow; k.src_size.height = en->oh; k.src_size.depth = 1; + k.dst = out->texture; + MTLBlitCommandEncoder_encodeCommands(e->benc, (const struct wmtcmd_base *)&k); + n = InterlockedIncrement(&g_fxt_done); + if (n <= 6 || (n % 3000) == 0) + d3d12_log("[xess-metalfx] temporal scale #%ld: content %ux%u of %ux%u -> %ux%u, jitter %.3f %.3f, mv scale %.3f %.3f, reset %d, " + "depth reversed %d, exposure %s, pre-exposure %.3f, fence mode %d\n", + (long)n, p.input_content_width, p.input_content_height, en->cw, en->ch, en->ow, en->oh, p.jitter_offset_x, p.jitter_offset_y, + p.motion_vector_scale_x, p.motion_vector_scale_y, (int)p.reset, (int)p.depth_reversed, ex ? "texture" : en->autoexp ? "auto" : "none", + p.pre_exposure, e->mode); +} + static void mad_exec_list(struct mad_queue *q, struct mad_list *l, obj_handle_t cb) { g_list_seq++; struct mad_exec e; @@ -10589,6 +10759,7 @@ static void mad_exec_list(struct mad_queue *q, struct mad_list *l, obj_handle_t case MC_DISPATCH: exec_dispatch(&e, c); mad_gw_dispatch(&e, c); if (g_vt_on > 0) { InterlockedIncrement(&g_vt_disp); InterlockedIncrement(&g_vt_disp_q[q->type & 3]); } break; /* madeira-bcd vis-trace */ case MC_RESOLVE: exec_resolve(&e, c); break; case MC_DISCARD: break; /* madeira-bcd rp-discard: exec_rp_note above */ + case MC_FX_TEMPORAL: exec_fx_temporal(&e, c); break; /* madeira-duo xess-metalfx */ } if (g_ffx_exp > 0 && c->kind == MC_DISPATCH) mad_ffx_after(&e, c); /* cs-split, fi-field-check */ if (rs) { /* madeira-bcd: replay split, summed per list */ @@ -21494,6 +21665,75 @@ static HRESULT STDMETHODCALLTYPE rootsig_GetDevice(ID3D12RootSignature *This, RE /* ---- vtable construction ------------------------------------------------- */ #include "madeira_list_journal.inc.c" /* list-journal, api-census: after the list_* methods it replays */ +/* madeira-duo xess-metalfx: THE EXPORTS (see madeira_fx.h). Madeira's + * libxess.dll calls them with what the game hands XeSS. The list may be a + * wrapper (Streamline's interposer): IID_MadeiraObject reaches ours. */ +static struct mad_list *mad_fxt_list(ID3D12GraphicsCommandList *p) { + void *base = NULL; + if (!p) return NULL; + if (((struct mad_list *)p)->vtbl == &g_list_vtbl) return (struct mad_list *)p; + if (SUCCEEDED(p->lpVtbl->QueryInterface(p, &IID_MadeiraObject, &base)) && base) { + ((IUnknown *)base)->lpVtbl->Release((IUnknown *)base); + if (((struct mad_list *)base)->vtbl == &g_list_vtbl) return (struct mad_list *)base; + } + return NULL; +} +static struct mad_resource *mad_fxt_res(ID3D12Resource *p) { + void *base = NULL; + if (!p) return NULL; + if (((struct mad_resource *)p)->vtbl == &g_res_vtbl) return (struct mad_resource *)p; + if (SUCCEEDED(p->lpVtbl->QueryInterface(p, &IID_MadeiraObject, &base)) && base) { + ((IUnknown *)base)->lpVtbl->Release((IUnknown *)base); + if (((struct mad_resource *)base)->vtbl == &g_res_vtbl) return (struct mad_resource *)base; + } + return NULL; +} +BOOL WINAPI MadeiraD3D12TemporalUpscaleSupported(ID3D12Device *device) { + struct mad_device *d = (struct mad_device *)device; + void *base = NULL; + if (!d) return FALSE; + if (d->vtbl != (void *)&g_device_vtbl) { + if (FAILED(device->lpVtbl->QueryInterface(device, &IID_MadeiraObject, &base)) || !base) return FALSE; + ((IUnknown *)base)->lpVtbl->Release((IUnknown *)base); + d = (struct mad_device *)base; + if (d->vtbl != (void *)&g_device_vtbl) return FALSE; + } + return d->mtl_device && MTLDevice_supportsFXTemporalScaler(d->mtl_device); +} +HRESULT WINAPI MadeiraD3D12TemporalUpscale(ID3D12GraphicsCommandList *list, const struct madeira_temporal_upscale_args *a) { + static LONG said, said_bad; + struct mad_list *l = mad_fxt_list(list); + struct mad_resource *col, *dep, *mv, *ex, *out; + struct mad_cmd *c; + if (!l || !a || a->size < sizeof *a) { + if (InterlockedIncrement(&said_bad) <= 4) + d3d12_log("[xess-metalfx] MadeiraD3D12TemporalUpscale refused: %s\n", !l ? "not one of our command lists" : "bad arguments"); + return E_INVALIDARG; + } + col = mad_fxt_res(a->color); dep = mad_fxt_res(a->depth); mv = mad_fxt_res(a->motion); + ex = mad_fxt_res(a->exposure); out = mad_fxt_res(a->output); + if (!col || !dep || !mv || !out || (a->exposure && !ex)) { + if (InterlockedIncrement(&said_bad) <= 4) + d3d12_log("[xess-metalfx] MadeiraD3D12TemporalUpscale refused: a resource is not ours (color %p depth %p motion %p exposure %p output %p)\n", + (void *)col, (void *)dep, (void *)mv, (void *)ex, (void *)out); + return E_INVALIDARG; + } + if (l->jr.used) mad_jr_flush(l); /* list-journal: what the game recorded before this call goes first */ + if (!(c = mad_list_push(l, MC_FX_TEMPORAL))) return E_FAIL; + c->u.fxt.color = col; c->u.fxt.depth = dep; c->u.fxt.motion = mv; c->u.fxt.exposure = ex; c->u.fxt.output = out; + c->u.fxt.in_w = a->input_width; c->u.fxt.in_h = a->input_height; c->u.fxt.flags = a->flags; + c->u.fxt.jx = a->jitter_x; c->u.fxt.jy = a->jitter_y; c->u.fxt.mvx = a->motion_scale_x; c->u.fxt.mvy = a->motion_scale_y; + c->u.fxt.pre_exposure = a->pre_exposure; + mad_list_note_used(l, col); mad_list_note_used(l, dep); mad_list_note_used(l, mv); mad_list_note_used(l, out); + if (ex) mad_list_note_used(l, ex); + if (InterlockedIncrement(&said) <= 4) + d3d12_log("[xess-metalfx] recorded: color '%s' %ux%u, depth '%s', motion '%s', output '%s' %ux%u, content %ux%u, flags %#x%s\n", + col->name ? col->name : "?", col->width, col->height, dep->name ? dep->name : "?", mv->name ? mv->name : "?", + out->name ? out->name : "?", out->width, out->height, a->input_width, a->input_height, a->flags, + (void *)l != (void *)list ? " (list reached through a wrapper)" : ""); + return S_OK; +} + static void build_vtables(void) { /* list-journal / api-census: the tables now hold trampolines another thread may be * recording through; refilling them would let a call skip its list's flush. The diff --git a/madeira-d3d12/src/pe/madeira_fx.h b/madeira-d3d12/src/pe/madeira_fx.h new file mode 100644 index 0000000000..6e1c10f67b --- /dev/null +++ b/madeira-d3d12/src/pe/madeira_fx.h @@ -0,0 +1,37 @@ +/* madeira-duo xess-metalfx: MetalFX temporal upscaling recorded into a D3D12 + * command list. Shared by madeira_d3d12.dll (the exports) and Madeira's + * libxess.dll, which answers a game's XeSS calls with it. + * + * MadeiraD3D12TemporalUpscale records one MetalFX temporal scale into the list, + * in list order: when the list is replayed, the scaler reads color, depth and + * motion (and the optional 1x1 exposure texture) and writes output, then the + * replay goes on. Units are MetalFX's: jitter in input pixels, motion vectors + * multiplied by motion_scale_* to give input pixels. */ +#ifndef MADEIRA_FX_H +#define MADEIRA_FX_H + +#include + +#define MADEIRA_TU_RESET 0x1u /* drop the history (camera cut, first frame) */ +#define MADEIRA_TU_DEPTH_REVERSED 0x2u /* 1.0 is near */ +#define MADEIRA_TU_AUTO_EXPOSURE 0x4u /* MetalFX computes the exposure itself */ + +struct madeira_temporal_upscale_args { + UINT32 size; /* sizeof(struct madeira_temporal_upscale_args) */ + UINT32 flags; /* MADEIRA_TU_* */ + ID3D12Resource *color; /* jittered input color */ + ID3D12Resource *depth; /* input depth, same size as color */ + ID3D12Resource *motion; /* motion vectors, same size as color */ + ID3D12Resource *exposure; /* optional 1x1 exposure texture, or NULL */ + ID3D12Resource *output; /* the upscaled image */ + UINT32 input_width, input_height; /* the part of color that holds the frame (from 0,0) */ + float jitter_x, jitter_y; + float motion_scale_x, motion_scale_y; + float pre_exposure; /* 0 or 1 = none */ +}; + +typedef BOOL (WINAPI *PFN_MadeiraD3D12TemporalUpscaleSupported)(ID3D12Device *device); +typedef HRESULT (WINAPI *PFN_MadeiraD3D12TemporalUpscale)(ID3D12GraphicsCommandList *list, + const struct madeira_temporal_upscale_args *args); + +#endif From e4a493f1db9fcad506d5921caf98aa10615bb976 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Thu, 5 Nov 2026 15:52:49 +1100 Subject: [PATCH 10/76] [gpu-work]: list up to 12 compute pipelines per window, so small passes (FSR RCAS, NIS) show Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/pe/madeira_d3d12.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index 76b22ec06f..a4944bca67 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -10430,7 +10430,8 @@ static void mad_gw_indirect(struct mad_exec *e, const struct mad_cmd *c) { /* Called from the [perf] report with the window's frame count: totals, then the top * pipelines of each kind by work, then the table is emptied for the next window. */ static void mad_gw_report(double frames) { - struct top { const char *p; LONG draws; LONG64 work; } tg[4], tc[4]; + /* madeira-duo: 12 compute entries, so small passes (FSR's RCAS, NIS) show up too */ + struct top { const char *p; LONG draws; LONG64 work; } tg[4], tc[12]; unsigned i, j, used = 0; LONG d = InterlockedExchange(&g_gw_draws, 0), di = InterlockedExchange(&g_gw_disp, 0), ind = InterlockedExchange(&g_gw_ind, 0); LONG full = InterlockedExchange(&g_gw_full, 0); @@ -10444,16 +10445,17 @@ static void mad_gw_report(double frames) { used++; dr = InterlockedExchange(&g->draws, 0); w = InterlockedExchange64(&g->work, 0); g->pso = NULL; + unsigned nt = g->compute ? 12 : 4; tt = g->compute ? tc : tg; - for (j = 0; j < 4; j++) if (w > tt[j].work || (!tt[j].p && dr)) break; - if (j < 4) { memmove(&tt[j + 1], &tt[j], (3 - j) * sizeof *tt); tt[j].p = g->name; tt[j].draws = dr; tt[j].work = w; } + for (j = 0; j < nt; j++) if (w > tt[j].work || (!tt[j].p && dr)) break; + if (j < nt) { memmove(&tt[j + 1], &tt[j], (nt - 1 - j) * sizeof *tt); tt[j].p = g->name; tt[j].draws = dr; tt[j].work = w; } } d3d12_log("[gpu-work] per frame: %.0f draws, %.2f M vertices x instances, %.1f dispatches, %.0f threadgroups, %.1f indirect records; %u pipelines used in the window%s\n", d / frames, v / 1e6 / frames, di / frames, t / frames, ind / frames, used, full ? " (table full, some not counted)" : ""); for (j = 0, n = 0; j < 4 && tg[j].p; j++) n += snprintf(line + n, sizeof line - n, "%s%s %.0f draws %.2f MV", j ? "; " : "", tg[j].p, tg[j].draws / frames, tg[j].work / 1e6 / frames); if (n) d3d12_log("[gpu-work] top render per frame: %s\n", line); - for (j = 0, n = 0; j < 4 && tc[j].p; j++) + for (j = 0, n = 0; j < 12 && tc[j].p && n < (int)sizeof line - 80; j++) n += snprintf(line + n, sizeof line - n, "%s%s %.1f dispatches %.0f tg", j ? "; " : "", tc[j].p, tc[j].draws / frames, tc[j].work / frames); if (n) d3d12_log("[gpu-work] top compute per frame: %s\n", line); } From 3b9fea415946c2d649fcca52576571d6d227a9b0 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Fri, 6 Nov 2026 01:17:24 +1100 Subject: [PATCH 11/76] rcas-fill: give PoE2's FSR sharpening pass a strength when the game writes none RCASCS reads its strength from root CBV register 10 .x; on the Duo PoE2 writes 0 there at any slider position, so the pass returned its input. With rcas-fill = , the dispatch binds a copy of the buffer with FSR's strength for that sharpness when the game's word is 0. Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/pe/madeira_d3d12.c | 63 ++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index a4944bca67..b3030f8d53 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -5621,6 +5621,66 @@ static void mad_cbv_snapshot(struct mad_exec *e, const struct mad_rootsig *rs, U InterlockedIncrement(&g_sd_snaps); InterlockedExchangeAdd64(&g_sd_snap_bytes, (LONG64)w[k].len); } } +/* madeira-duo (6 Nov 2026): rcas-fill = . PoE2's FSR sharpening + * pass (RCASCS, bytecode FNV df5b6e66dfbf8d11) reads its strength from one word of its + * root CBV, register 10 .x (byte 160), and on the Duo the game writes 0 there whatever + * the slider says (both 100% captures; upload-guard = 2 showed the GPU reads exactly + * those bytes), so the pass returned its input unchanged. The game only runs the pass + * when its slider is above 0. When it does and the word is 0, the dispatch is bound to + * a copy of the buffer's first 256 bytes with FSR's own strength for this sharpness, + * exp2(-(2 - 2 * sharpness)), in that word. The game's buffer is never written; a + * strength the game does give is kept. Unset or 0: off. */ +#define MAD_RCAS_POE2_CS_HASH 0xdf5b6e66dfbf8d11ull +#define MAD_RCAS_STRENGTH_OFFSET 160u +static int g_rcas_fill_read; +static UINT32 g_rcas_fill_bits; +static volatile LONG g_rcas_fills; +static UINT32 mad_rcas_fill_bits(void) { + if (!g_rcas_fill_read) { + char text[32] = ""; + float sharpness = 0.0f; + if (mad_cfg_str_pe("rcas-fill", text, sizeof text)) sharpness = (float)strtod(text, NULL); + if (sharpness > 1.0f) sharpness = 1.0f; + if (sharpness > 0.0f) { + const float strength = exp2f(-(2.0f - 2.0f * sharpness)); + memcpy(&g_rcas_fill_bits, &strength, sizeof g_rcas_fill_bits); + d3d12_log("[rcas-fill] FSR sharpening at %.2f (RCAS strength %.4f) when PoE2 gives none\n", sharpness, strength); + } + g_rcas_fill_read = 1; + } + return g_rcas_fill_bits; +} +static const UINT64 *mad_rcas_fill_root(struct mad_exec *e, const struct mad_rootsig *rs, const UINT64 *root, UINT64 *tmp) { + struct mad_list *l = e->l; + const unsigned per = MAD_ARG_RING_BYTES / MAD_ARG_SLOT_BYTES; + const unsigned slots = (256 + 255 + MAD_ARG_SLOT_BYTES - 1) / MAD_ARG_SLOT_BYTES; + struct mad_resource *resource; + UINT64 offset = 0, ring_offset, gpu, va; + obj_handle_t ring_buffer; + void *cpu; + unsigned char *copy; + UINT32 game_strength; + unsigned i; + for (i = 0; i < rs->nparams && i < MAD_ROOT_PARAM_MAX; i++) + if (rs->params[i].type == MADEIRA_IR_PARAM_CBV && root[i]) break; + if (i >= rs->nparams || i >= MAD_ROOT_PARAM_MAX) return root; + resource = mad_resolve_address(e->q->device, root[i], &offset); + if (!mad_ug_cpu_written(resource) || offset + 256 > resource->size) return root; + memcpy(&game_strength, (const unsigned char *)resource->cpu + offset + MAD_RCAS_STRENGTH_OFFSET, sizeof game_strength); + if (game_strength) return root; + if (slots + 1 > per) return root; + if ((l->ring_used % per) + slots + 1 > per) l->ring_used += per - (l->ring_used % per); /* the copy and the argument slot in one chunk */ + if (!exec_ring_take_z(e, slots, 0, &ring_buffer, &ring_offset, &cpu, &gpu)) return root; + va = (gpu + ring_offset + 255) & ~(UINT64)255; /* D3D12's CBV alignment */ + copy = (unsigned char *)cpu + (va - gpu - ring_offset); + memcpy(copy, (const unsigned char *)resource->cpu + offset, 256); + memcpy(copy + MAD_RCAS_STRENGTH_OFFSET, &g_rcas_fill_bits, sizeof g_rcas_fill_bits); + memcpy(tmp, root, MAD_ROOT_PARAM_MAX * sizeof *tmp); + tmp[i] = va; + if (InterlockedIncrement(&g_rcas_fills) == 1) d3d12_log("[rcas-fill] first fill: RCASCS root CBV p%u had strength 0\n", i); + return tmp; +} + /* Before a draw's or dispatch's argument slot: note (upload-guard), mark * (desc-guard), copy (cbv-snapshot). Returns the root values to encode. */ static const UINT64 *mad_sd_root(struct mad_exec *e, const struct mad_rootsig *rs, const UINT64 *root, UINT64 *tmp, const struct mad_pso *pso) { @@ -5791,10 +5851,13 @@ static int exec_arg_slot_for(struct mad_exec *e, const struct mad_rootsig *rs, c unsigned chunk, slot; UINT64 sd_root[MAD_ROOT_PARAM_MAX]; /* madeira-bcd: sync diagnostics, see mad_sd_root */ UINT64 sc_root[MAD_ROOT_PARAM_MAX]; /* madeira-bcd static-cbv */ + UINT64 rcas_root[MAD_ROOT_PARAM_MAX]; /* madeira-duo rcas-fill */ const unsigned sc_bp = root == e->croot ? 1u : 0u; const int sc_on = (g_scbv_on == 1 || g_scbv_on == 2) && rs && root && (root == e->root || root == e->croot); if (g_sd_state > 0 && rs && root) root = mad_sd_root(e, rs, root, sd_root, pso); if (sc_on) root = mad_scbv_root(e, rs, root, sc_root, sc_bp); + if (pso && pso->cs_hash == MAD_RCAS_POE2_CS_HASH && rs && root && mad_rcas_fill_bits()) /* madeira-duo rcas-fill */ + root = mad_rcas_fill_root(e, rs, root, rcas_root); chunk = l->ring_used / (MAD_ARG_RING_BYTES / MAD_ARG_SLOT_BYTES); slot = l->ring_used % (MAD_ARG_RING_BYTES / MAD_ARG_SLOT_BYTES); if (chunk >= l->nrings && !mad_list_ring_grow(e)) return 0; /* ml1061: pooled, GPU-lifetime aware */ From a175b18bdc847c21e109618ee3251fc5351ecf55 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Sun, 8 Nov 2026 02:24:14 +1100 Subject: [PATCH 12/76] madeira-d3d12: the device build's uncommitted work (prof12-prof18) What madeira_d3d12.dll 69cd8c8c and the app's madeira_ir_unix.mm bc99ccdb carry beyond the local commits: - encoder labels by shader digest ("R ps: vs: WxH", "C cs:") for gpu-pass-timing (encoder-labels = 1) - hp-release: free fully empty runtime texture heaps, keep one spare (default on) - pso-create-build (0/1/2) and pso-seen-record: queue pipeline builds at creation behind draw-time builds - msc-gpu-family, msc-min-os, msc-ignore-debug-info, msc-validation (converter options; non-default values salt the shader cache key) - rp-learn-store / rp-learn-census (retired, default off) - vtx-census = N with VS-output/PS-input varyings census Signed-off-by: Shitiz Garg Co-Authored-By: Claude Opus 5.5 --- madeira-d3d12/src/pe/madeira_d3d12.c | 775 +++++++++++++++++++++- madeira-d3d12/src/unix/madeira_ir_unix.mm | 39 +- 2 files changed, 786 insertions(+), 28 deletions(-) diff --git a/madeira-d3d12/src/pe/madeira_d3d12.c b/madeira-d3d12/src/pe/madeira_d3d12.c index b3030f8d53..22e9c7b4e5 100644 --- a/madeira-d3d12/src/pe/madeira_d3d12.c +++ b/madeira-d3d12/src/pe/madeira_d3d12.c @@ -1243,6 +1243,7 @@ struct mad_resource { UINT samples; struct mad_device *owner; int borrowed; /* texture belongs to a drawable; do not release */ + volatile LONG rpl_state, rpl_wasted; /* madeira-duo rp-learn-store */ obj_handle_t resolve_tmp; /* exec_resolve: render-target stand-in when this is a resolve destination without that usage */ UINT resolve_tmp_w, resolve_tmp_h, resolve_tmp_pf; /* the stand-in's size and pixel format, to replace it when they change */ D3D12_RESOURCE_DESC desc; /* as created; answered by GetDesc */ @@ -1365,10 +1366,14 @@ struct mad_pso { int lazy_cs; /* compute pipeline built at its first dispatch (mad_cpso_realize) */ UINT64 cs_hash; UINT cs_len; /* madeira-bcd: FNV-1a of the CS bytecode, for GPU fault reports */ UINT64 vs_hash; /* madeira-bcd skin-check: FNV-1a of the VS bytecode (0 unless skin-check is on) */ + UINT ps_id, vs_id; /* madeira-duo gpu-pass-timing: the first 4 bytes of each DXBC container digest, to tell PoE2's all-"main" shaders apart in encoder labels */ + UINT vary_out, vary_unused; /* madeira-duo vtx-census: bytes per vertex the VS writes (signature components x 4) and how many of them the PS never reads */ + UINT vary_flags; /* madeira-duo vtx-census: 1 VS min precision, 2 VS native 16-bit, 4 PS min precision, 8 PS native 16-bit, 16 VS has 16-bit outputs */ char *il_tag; int il_int; /* madeira-bcd skin-check-trace: the input layout in short; il_int: an integer element (blend indices) */ LONG first_used; LONG64 born_present; DWORD born_tick; /* madeira-bcd: pso-first-use */ SRWLOCK rlock; /* serialises this pipeline's lazy build (zero = SRWLOCK_INIT) */ - volatile LONG async_q; /* pso-async: handed to the background builders */ + volatile LONG async_q; /* pso-async: handed to the background builders (1; 2 = pso-create-build's low-priority queue) */ + UINT64 seen_key; LONG seen_mark; /* madeira-duo pso-create-build: the pipeline's content key, and drawn once this session */ /* madeira-bcd pso-lazy-libs: lz = the stage libraries were dropped once the * pipeline was created and come back from the shader cache under these keys * at its first draw (mad_lzlib_restore); lz_has_ps never changes after creation */ @@ -2284,6 +2289,8 @@ struct mad_exec { UINT64 vis_prev; /* ml1088: the visibility slot the open encoder was last told to count into, ~0 = disabled */ obj_handle_t enc_vis_buf; /* ml1088: the slot chunk attached to the open encoder (a pass attribute) */ unsigned pass_draws; /* ml1098: draws encoded into the open render pass */ + UINT vc_ps, vc_vs, vc_w, vc_h; UINT64 vc_draws, vc_verts, vc_inst, vc_indirect, vc_idx32; /* madeira-duo vtx-census */ + UINT64 vc_outb, vc_unusedb, vc_v16; /* madeira-duo vtx-census: vertex output bytes (verts x VS output size), the part the PS never reads, verts drawn by a VS with 16-bit types */ /* ml1134: fence-chain = 6 */ int f6_sync_needed; /* a ResourceBarrier (or the list start) since the last sync point */ int f6_list_start; /* the next sync also waits for the device fence (other queue, earlier batch) */ @@ -2710,6 +2717,170 @@ static void f7_store_census(struct mad_exec *e, const struct mad_resource *r, UI done: InterlockedExchangeAdd64(cls, b); } +/* madeira-duo vtx-census (diagnostic, opt-in: madeira.cfg vtx-census = N seconds + * between reports, 0 = off). What each render pass asks the vertex stage for, + * keyed like gpu-pass-timing's labels (the pass's first pipeline digests and + * its size), so the two reports line up: draws, vertices (index count x + * instances), instances and indirect draws per frame. GPU vertex time divided + * by vertices says whether a vertex-heavy pass is the game's geometry or the + * cost of each vertex here. */ +/* madeira-duo vtx-census: what a VS writes per vertex and what the PS reads, from + * the DXIL container's signatures (ISG1/OSG1: Mask = allocated components; an + * output's NeverWrites mask and an input's AlwaysReads mask, as DXC writes them, + * give the components actually written and read). Apple's GPU stores every vertex + * output for the tiler, so written-but-never-read components are pure cost. SFI0 + * says whether the shader uses minimum-precision or native 16-bit types. */ +static const BYTE *mad_dxbc_chunk(const void *bc, SIZE_T len, const char *cc, UINT *clen) { + const BYTE *b = bc; UINT n, i, off; + if (!b || len < 32 || memcmp(b, "DXBC", 4)) return NULL; + memcpy(&n, b + 28, 4); + if (n > 64 || 32 + (SIZE_T)n * 4 > len) return NULL; + for (i = 0; i < n; i++) { + memcpy(&off, b + 32 + i * 4, 4); + if ((SIZE_T)off + 8 > len) return NULL; + if (!memcmp(b + off, cc, 4)) { + UINT sz; memcpy(&sz, b + off + 4, 4); + if ((SIZE_T)off + 8 + sz > len) return NULL; + *clen = sz; return b + off + 8; + } + } + return NULL; +} +struct mad_sig_el { const char *name; UINT index, sv, reg; BYTE mask, rw; UINT minp; }; +static UINT mad_sig_read(const BYTE *c, UINT clen, struct mad_sig_el *el, UINT cap) { + UINT n, off, i, k = 0; + if (!c || clen < 8) return 0; + memcpy(&n, c, 4); memcpy(&off, c + 4, 4); + for (i = 0; i < n && k < cap; i++) { + const BYTE *e = c + off + i * 32; UINT nmo; + if ((SIZE_T)(off + i * 32 + 32) > clen) break; + memcpy(&nmo, e + 4, 4); + el[k].name = nmo < clen ? (const char *)c + nmo : ""; + if (!memchr(el[k].name, 0, clen - (nmo < clen ? nmo : clen))) el[k].name = ""; + memcpy(&el[k].index, e + 8, 4); memcpy(&el[k].sv, e + 12, 4); memcpy(&el[k].reg, e + 20, 4); + el[k].mask = e[24]; el[k].rw = e[25]; memcpy(&el[k].minp, e + 28, 4); + k++; + } + return k; +} +static UINT mad_bits4(UINT m) { m &= 15; return (m & 1) + ((m >> 1) & 1) + ((m >> 2) & 1) + ((m >> 3) & 1); } +static void mad_vary_measure(struct mad_pso *p, const D3D12_GRAPHICS_PIPELINE_STATE_DESC *desc) { + struct mad_sig_el vo[32], pi[32]; + UINT nvo, npi = 0, i, j, cl, out = 0, unused = 0, fl = 0; + const BYTE *c; + UINT64 sf; + if (!desc->VS.pShaderBytecode || desc->GS.pShaderBytecode || desc->HS.pShaderBytecode || desc->DS.pShaderBytecode) return; + c = mad_dxbc_chunk(desc->VS.pShaderBytecode, desc->VS.BytecodeLength, "OSG1", &cl); + nvo = mad_sig_read(c, c ? cl : 0, vo, 32); + if (!nvo) return; + if (desc->PS.pShaderBytecode) { + c = mad_dxbc_chunk(desc->PS.pShaderBytecode, desc->PS.BytecodeLength, "ISG1", &cl); + npi = mad_sig_read(c, c ? cl : 0, pi, 32); + if ((c = mad_dxbc_chunk(desc->PS.pShaderBytecode, desc->PS.BytecodeLength, "SFI0", &cl)) && cl >= 8) { + memcpy(&sf, c, 8); + if (sf & 0x10) fl |= 4; + if (sf & 0x40000) fl |= 8; + } + } + if ((c = mad_dxbc_chunk(desc->VS.pShaderBytecode, desc->VS.BytecodeLength, "SFI0", &cl)) && cl >= 8) { + memcpy(&sf, c, 8); + if (sf & 0x10) fl |= 1; + if (sf & 0x40000) fl |= 2; + } + for (i = 0; i < nvo; i++) { + UINT wr = vo[i].mask & ~vo[i].rw & 15, rd = 0, nw = mad_bits4(wr); + out += nw * 4; + if (vo[i].minp) fl |= 16; + if (vo[i].sv) continue; /* system values (position, clip/cull distances, RT/viewport index) are the rasteriser's */ + for (j = 0; j < npi; j++) + if (pi[j].index == vo[i].index && !_stricmp(pi[j].name, vo[i].name)) rd |= pi[j].rw & pi[j].mask; + unused += mad_bits4(wr & ~rd) * 4; + } + p->vary_out = out; p->vary_unused = unused; p->vary_flags = fl; +} +struct mad_vxc_ent { UINT ps, vs, w, h; UINT64 passes, draws, verts, inst, indirect, idx32, outb, unusedb, v16; }; +#define MAD_VXC_MAX 512 +static struct mad_vxc_ent g_vxc[MAD_VXC_MAX]; +static UINT g_vxc_n; +static SRWLOCK g_vxc_lock = SRWLOCK_INIT; +static int g_vxc_secs = -1; +static ULONGLONG g_vxc_last_tick; static LONG64 g_vxc_last_present; +static int mad_vxc_on(void) { + if (g_vxc_secs < 0) { + long long s = mad_cfg_int_pe("vtx-census", 0); /* madeira-duo diagnostic: seconds between vertex census reports (0 = off) */ + g_vxc_secs = s <= 0 ? 0 : s > 3600 ? 3600 : (int)s; + if (g_vxc_secs) d3d12_log("[madeira-d3d12] vtx-census = %d: per-pass vertex work reported every %d s\n", g_vxc_secs, g_vxc_secs); + } + return g_vxc_secs; +} +static int mad_vxc_cmp(const void *a, const void *b) { + const struct mad_vxc_ent *x = a, *y = b; + return x->verts < y->verts ? 1 : x->verts > y->verts ? -1 : 0; +} +static void mad_vxc_report_locked(void) { + static struct mad_vxc_ent v[MAD_VXC_MAX]; + LONG64 pres = g_presents_now - g_vxc_last_present; + UINT i, n = g_vxc_n; + UINT64 tv = 0, td = 0; + double f = pres > 0 ? 1.0 / (double)pres : 0.0; + if (pres <= 0 || !n) return; + memcpy(v, g_vxc, n * sizeof *v); + qsort(v, n, sizeof *v, mad_vxc_cmp); + { + UINT64 to = 0, tu = 0, t16 = 0; + for (i = 0; i < n; i++) { tv += v[i].verts; td += v[i].draws; to += v[i].outb; tu += v[i].unusedb; t16 += v[i].v16; } + d3d12_log("[vtx-census] window: %lld presents, %u pass kinds; per frame %.0f draws, %.2f M vertices; vertex outputs %.1f MB/f " + "(%.0f B/vertex), %.0f%% of it never read by the pixel shader; %.0f%% of vertices from a VS with 16-bit types\n", + (long long)pres, n, td * f, tv * f / 1e6, to * f / 1048576.0, tv ? (double)to / tv : 0.0, + to ? 100.0 * tu / to : 0.0, tv ? 100.0 * t16 / tv : 0.0); + } + for (i = 0; i < n && i < 25; i++) + d3d12_log("[vtx-census] %2u %8.0f verts/f %6.1f draws/f %8.0f inst/f indirect %.1f/f idx32 %.0f%% passes %.2f/f out %.0f B/v unused %.0f B/v | R ps:%08x vs:%08x %ux%u\n", + i + 1, v[i].verts * f, v[i].draws * f, v[i].inst * f, v[i].indirect * f, + v[i].draws ? 100.0 * v[i].idx32 / v[i].draws : 0.0, v[i].passes * f, + v[i].verts ? (double)v[i].outb / v[i].verts : 0.0, v[i].verts ? (double)v[i].unusedb / v[i].verts : 0.0, + v[i].ps, v[i].vs, v[i].w, v[i].h); + g_vxc_n = 0; + memset(g_vxc, 0, sizeof g_vxc); +} +/* exec_end: one render pass's totals. */ +static void exec_vc_pass(struct mad_exec *e) { + struct mad_vxc_ent *x = NULL; UINT i; + ULONGLONG now; + if (!e->vc_draws) return; + AcquireSRWLockExclusive(&g_vxc_lock); + for (i = 0; i < g_vxc_n; i++) + if (g_vxc[i].ps == e->vc_ps && g_vxc[i].vs == e->vc_vs && g_vxc[i].w == e->vc_w && g_vxc[i].h == e->vc_h) { x = &g_vxc[i]; break; } + if (!x && g_vxc_n < MAD_VXC_MAX) { x = &g_vxc[g_vxc_n++]; x->ps = e->vc_ps; x->vs = e->vc_vs; x->w = e->vc_w; x->h = e->vc_h; } + if (x) { x->passes++; x->draws += e->vc_draws; x->verts += e->vc_verts; x->inst += e->vc_inst; x->indirect += e->vc_indirect; x->idx32 += e->vc_idx32; + x->outb += e->vc_outb; x->unusedb += e->vc_unusedb; x->v16 += e->vc_v16; } + e->vc_outb = e->vc_unusedb = e->vc_v16 = 0; + now = GetTickCount64(); + if (!g_vxc_last_tick) { g_vxc_last_tick = now; g_vxc_last_present = g_presents_now; } + else if (now - g_vxc_last_tick >= (ULONGLONG)g_vxc_secs * 1000) { + mad_vxc_report_locked(); + g_vxc_last_tick = now; g_vxc_last_present = g_presents_now; + } + ReleaseSRWLockExclusive(&g_vxc_lock); + e->vc_draws = 0; +} +/* A draw that is encoded. */ +static void exec_vc_draw(struct mad_exec *e, const struct mad_cmd *c) { + UINT64 nv = 0; + switch (c->kind) { + case MC_DRAW: nv = (UINT64)c->u.draw.vcount * (c->u.draw.icount ? c->u.draw.icount : 1); e->vc_inst += c->u.draw.icount; break; + case MC_DRAW_INDEXED: nv = (UINT64)c->u.drawi.icount * (c->u.drawi.inst ? c->u.drawi.inst : 1); e->vc_inst += c->u.drawi.inst; + if (e->ib_type == WMTIndexTypeUInt32) e->vc_idx32++; + break; + default: e->vc_indirect++; break; + } + e->vc_verts += nv; + if (nv && e->pso) { /* the pipeline this draw runs, not the pass's first */ + e->vc_outb += nv * e->pso->vary_out; e->vc_unusedb += nv * e->pso->vary_unused; + if (e->pso->vary_flags & 3) e->vc_v16 += nv; + } + e->vc_draws++; +} static volatile LONG g_fault_diag; /* madeira-bcd: GPU fault attribution, below */ static void mad_fault_label_render(struct mad_exec *e); static void exec_rp_late_store(struct mad_exec *e); /* madeira-bcd rp-discard, below */ @@ -2724,6 +2895,7 @@ static void exec_end(struct mad_exec *e) { if (e->enc_depth && e->enc_depth->texture) f7_store_census(e, e->enc_depth, e->enc_dp.level); } e->f7_next_rts = 0; + if (e->renc && e->vc_draws) exec_vc_pass(e); /* madeira-duo vtx-census */ if (e->renc && g_fault_diag && e->diag_npso) mad_fault_label_render(e); /* madeira-bcd */ if (e->renc) { if (g_capture_on) { cn = e->enc_nrt; memcpy(crt, e->enc_rt, sizeof crt); memcpy(crtp, e->enc_rtp, sizeof crtp); cdepth = e->enc_depth; cdp = e->enc_dp; cseq = e->renc_seq; cdraws = e->pass_draws; } @@ -3931,6 +4103,8 @@ static const struct mad_list *mad_rp_list_at(const struct mad_queue *q, UINT i) * aspect (0 colour, 1 depth, 2 stencil), so the store is moot; 0 = a draw * while it is bound (a pass loads it), a barrier, copy or partial discard or * clear naming it, the end of the call, or 8192 commands. */ +static int mad_rpc_on(void); /* madeira-duo rp-learn-census, below */ +static int g_rpd_why; /* madeira-duo rp-learn-census: the command kind that decided exec_rp_dead's last 0 (replay threads race; counts only) */ static int exec_rp_dead(const struct mad_exec *e, const struct mad_resource *r, const struct mad_rtvp *v, int aspect) { const struct mad_queue *q = e->q; const struct mad_list *l = e->l; @@ -3939,32 +4113,261 @@ static int exec_rp_dead(const struct mad_exec *e, const struct mad_resource *r, while (l) { for (; j < l->ncmds; j++) { const struct mad_cmd *c = &l->cmds[j]; - if (++n > 8192) return 0; + if (++n > 8192) return 3; /* madeira-duo: undecided at the look-ahead limit (kept, as 0; rp-learn-store watches it) */ switch (c->kind) { case MC_RTS: bound = c->u.rts.depth == r; for (k = 0; k < c->u.rts.n && k < 8; k++) if (c->u.rts.rt[k] == r) bound = 1; break; case MC_DRAW: case MC_DRAW_INDEXED: case MC_DRAW_INDIRECT: case MC_DRAW_INDEXED_INDIRECT: - if (bound) return 0; /* a pass loads it */ + if (bound) { g_rpd_why = c->kind; return 0; } /* a pass loads it */ break; case MC_DISCARD: if (c->u.discard.res == r) return c->u.discard.whole != 0; break; case MC_CLEAR_RT: case MC_CLEAR_DS: if (c->u.clear.res != r) break; - if (c->u.clear.nrect || !mad_rtvp_eq(&c->u.clear.v, v)) return 0; + if (c->u.clear.nrect || !mad_rtvp_eq(&c->u.clear.v, v)) { g_rpd_why = c->kind; return 0; } if (!aspect) return c->kind == MC_CLEAR_RT; return c->kind == MC_CLEAR_DS && (c->u.clear.flags & (aspect == 1 ? D3D12_CLEAR_FLAG_DEPTH : D3D12_CLEAR_FLAG_STENCIL)) != 0; default: - if (mad_cmd_names(c, r)) return 0; + if (mad_cmd_names(c, r)) { + g_rpd_why = c->kind; + if (c->kind == MC_BARRIER) { /* rp-learn-census: 64 + the barrier's state class for r (BC_*), 64 + 4 = a global barrier */ + g_rpd_why = 64 + BC_ALL; + for (k = 0; k < c->u.barrier.n && k < 8; k++) if (c->u.barrier.res[k] == r) { g_rpd_why = 64 + (c->u.barrier.cls[k] < BC_ALL ? c->u.barrier.cls[k] : BC_ALL); break; } + } + return 0; + } break; } } for (l = NULL; !l && ++li < q->rp_nlists; ) l = mad_rp_list_at(q, li); j = 0; bound = 0; /* a list binds its own targets */ } - return 0; + return 2; /* madeira-duo rp-learn-store: no use to the end of the call (kept, as 0) */ +} +/* madeira-duo rp-learn-store (opt-in, default 0). The census (ml1137) shows + * PoE2 storing ~82 MB of attachments a frame, ~48 MB of them with no use in the + * rest of their batch: exec_rp_dead has to keep those, it cannot see the next + * frame. Many are cleared or discarded whole at their next use (a depth buffer + * cleared at the next frame's start), so the store was wasted bandwidth. + * With rp-learn-store = 1 every such store is watched: what the next command + * naming the texture does decides it -- a whole clear or discard (or a pass that + * does not load it) is a wasted store, anything else (a barrier, copy, a pass + * that loads it) a needed one. After rp-learn-store-n wasted stores in a row + * (default 16), with none ever needed, the texture's batch-end stores become + * DontCare. One needed use rules a texture out for the session, and if that use + * meets a store we skipped it is logged as a misprediction (one frame of that + * texture is then undefined). Single-mip, single-layer textures only; never a + * drawable. Needs MadeiraCtl op 24 (the late store, rp-discard's mechanism). + * rp-learn-log = 1 lists every texture as it is learned or ruled out. */ +enum { RPL_PEND = 1, RPL_ELIDED = 2, RPL_NEEDED = 4, RPL_ON = 8, RPL_WATCH = 16 }; +static int g_rpl = -1, g_rpl_n = 16, g_rpl_log; +static volatile LONG g_rpl_learned, g_rpl_ruled_out, g_rpl_mispredict, g_rpl_nwatch; +static volatile LONG64 g_rpl_elided_b, g_rpl_elided_n; +#define MAD_RPL_WATCH_MAX 64 +static struct mad_resource *g_rpl_watch[MAD_RPL_WATCH_MAX]; +static SRWLOCK g_rpl_lock = SRWLOCK_INIT; +static int mad_rpl_on(void) { + if (g_rpl < 0) { + long long n = mad_cfg_int_pe("rp-learn-store-n", 16); /* madeira-duo: rp-learn-store: wasted stores in a row before a texture's batch-end stores are skipped (4-1000) */ + g_rpl_n = n < 4 ? 4 : n > 1000 ? 1000 : (int)n; + g_rpl_log = mad_cfg_int_pe("rp-learn-log", 0) > 0; /* madeira-duo: rp-learn-store: log each texture learned or ruled out */ + g_rpl = mad_cfg_int_pe("rp-learn-store", 0) > 0 && mad_rp_late_ok(); /* madeira-duo: 1 = learn which batch-end attachment stores are always wasted and skip them */ + if (g_rpl) mad_rpc_on(); /* rp-learn-census rides on the late-store path */ + if (g_rpl) d3d12_log("[madeira-d3d12] rp-learn-store = 1: batch-end stores of a texture whose next use was a whole clear or discard %d times " + "in a row (and never a load) are skipped\n", g_rpl_n); + } + return g_rpl; +} +static int mad_rpl_eligible(const struct mad_resource *r) { + return r && r->texture && !r->borrowed && r->desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + r->desc.MipLevels <= 1 && r->desc.DepthOrArraySize <= 1; +} +static void mad_rpl_name(const struct mad_resource *r, char *out, size_t cap) { + snprintf(out, cap, "#%u %s %ux%u fmt %u%s", r->serial, r->name ? r->name : "", r->width, r->height, + (unsigned)r->desc.Format, r->is_depth ? " depth" : ""); +} +static void mad_rpl_watch(struct mad_resource *r, LONG bit) { + AcquireSRWLockExclusive(&g_rpl_lock); + if (r->rpl_state & RPL_WATCH) { /* already watched: a second store before its next use */ + r->rpl_state |= bit; + ReleaseSRWLockExclusive(&g_rpl_lock); + return; + } + r->rpl_state |= bit | RPL_WATCH; + if (g_rpl_nwatch < MAD_RPL_WATCH_MAX) { + g_rpl_watch[g_rpl_nwatch] = r; /* res_Release takes it off before the texture goes (mad_rpl_forget) */ + InterlockedIncrement(&g_rpl_nwatch); + } else r->rpl_state &= ~(RPL_WATCH | RPL_PEND | RPL_ELIDED); /* no room: this store goes unjudged */ + ReleaseSRWLockExclusive(&g_rpl_lock); +} +/* res_Release, at the last reference: a freed texture leaves the watch list. */ +static void mad_rpl_forget(struct mad_resource *r) { + LONG i; + AcquireSRWLockExclusive(&g_rpl_lock); + for (i = 0; i < g_rpl_nwatch; i++) + if (g_rpl_watch[i] == r) { g_rpl_watch[i] = g_rpl_watch[g_rpl_nwatch - 1]; InterlockedDecrement(&g_rpl_nwatch); break; } + r->rpl_state = 0; + ReleaseSRWLockExclusive(&g_rpl_lock); +} +/* The watched texture's next use: wasted = 1 (whole clear / discard / not loaded), 0 = needed. + * Everything that touches r happens under the lock, where it is still on the list. */ +static void mad_rpl_settle(struct mad_resource *r, int wasted) { + LONG st, i, n; + int said = 0; /* 1 misprediction, 2 ruled out, 3 learned */ + char nm[160]; + AcquireSRWLockExclusive(&g_rpl_lock); + for (i = 0; i < g_rpl_nwatch && g_rpl_watch[i] != r; i++) ; + if (i == g_rpl_nwatch) { ReleaseSRWLockExclusive(&g_rpl_lock); return; } + g_rpl_watch[i] = g_rpl_watch[g_rpl_nwatch - 1]; + InterlockedDecrement(&g_rpl_nwatch); + st = r->rpl_state; + r->rpl_state = st & ~(RPL_WATCH | RPL_PEND | RPL_ELIDED); + if (!wasted) { + if (st & RPL_ELIDED) { n = InterlockedIncrement(&g_rpl_mispredict); if (n <= 16) said = 1; } + if (!(st & RPL_NEEDED)) { + n = InterlockedIncrement(&g_rpl_ruled_out); + if (st & RPL_ON) InterlockedDecrement(&g_rpl_learned); + if (!said && g_rpl_log && n <= 200) said = 2; + } + r->rpl_state = (r->rpl_state | RPL_NEEDED) & ~RPL_ON; + } else if (!(st & (RPL_NEEDED | RPL_ON)) && ++r->rpl_wasted >= g_rpl_n) { + r->rpl_state |= RPL_ON; + n = InterlockedIncrement(&g_rpl_learned); + if (g_rpl_log || n <= 8) said = 3; + } + if (said) mad_rpl_name(r, nm, sizeof nm); + ReleaseSRWLockExclusive(&g_rpl_lock); + if (said == 1) d3d12_log("[madeira-d3d12] rp-learn-store: MISPREDICTION %s -- a skipped store was needed (one frame of it undefined); ruled out\n", nm); + else if (said == 2) d3d12_log("[madeira-d3d12] rp-learn-store: ruled out %s\n", nm); + else if (said == 3) d3d12_log("[madeira-d3d12] rp-learn-store: learned %s: its batch-end stores are skipped from now on (%ld learned, %ld ruled out)\n", + nm, (long)g_rpl_learned, (long)g_rpl_ruled_out); +} +/* Replay: does this command settle a watched texture? */ +static void exec_rpl_note(const struct mad_cmd *c) { + struct mad_resource *hit[MAD_RPL_WATCH_MAX]; int wasted[MAD_RPL_WATCH_MAX]; LONG i, n = 0; + switch (c->kind) { /* the commands that never name a texture */ + case MC_DRAW: case MC_DRAW_INDEXED: case MC_DRAW_INDIRECT: case MC_DRAW_INDEXED_INDIRECT: case MC_DISPATCH: case MC_DISPATCH_INDIRECT: + case MC_PSO: case MC_ROOT: case MC_CROOT: case MC_ROOT_CONST: case MC_CROOT_CONST: case MC_RTS: return; + default: break; + } + AcquireSRWLockShared(&g_rpl_lock); + for (i = 0; i < g_rpl_nwatch; i++) { + struct mad_resource *r = g_rpl_watch[i]; + if (!mad_cmd_names(c, r)) continue; + hit[n] = r; + if (c->kind == MC_DISCARD) wasted[n] = c->u.discard.whole != 0; + else if (c->kind == MC_CLEAR_RT) wasted[n] = !c->u.clear.nrect; + else if (c->kind == MC_CLEAR_DS) wasted[n] = !c->u.clear.nrect && (c->u.clear.flags & D3D12_CLEAR_FLAG_DEPTH) && + (!r->has_stencil || (c->u.clear.flags & D3D12_CLEAR_FLAG_STENCIL)); + else wasted[n] = 0; + n++; + } + ReleaseSRWLockShared(&g_rpl_lock); + for (i = 0; i < n; i++) mad_rpl_settle(hit[i], wasted[i]); +} +/* A pass begins on a watched texture: loading it means the store was needed. */ +static void exec_rpl_begin(struct mad_resource *r, int loads) { + if (r && (r->rpl_state & RPL_WATCH)) mad_rpl_settle(r, !loads); +} +/* A texture whose stores the learner wants decided at the pass's end. */ +static int exec_rpl_want(const struct mad_exec *e) { + UINT i; + if (!mad_rpl_on()) return 0; + for (i = 0; i < e->nrt; i++) if (mad_rpl_eligible(e->rt[i]) && !(e->rt[i]->rpl_state & RPL_NEEDED)) return 1; + return mad_rpl_eligible(e->depth) && !(e->depth->rpl_state & RPL_NEEDED); +} +/* exec_rp_late_store: a store exec_rp_dead could not decide (2 = no use to the end of the call). */ +static enum WMTStoreAction exec_rpl_store(struct mad_resource *r, int dead, LONG64 bytes) { + if (dead == 1) return WMTStoreActionDontCare; + if (dead < 2 || !mad_rpl_on() || !mad_rpl_eligible(r) || (r->rpl_state & RPL_NEEDED)) return WMTStoreActionStore; + if (r->rpl_state & RPL_ON) { + mad_rpl_watch(r, RPL_ELIDED); + if (r->rpl_state & RPL_WATCH) { /* only a skip whose fate is watched */ + InterlockedExchangeAdd64(&g_rpl_elided_b, bytes); + if (!(InterlockedIncrement64(&g_rpl_elided_n) % 5000)) + d3d12_log("[madeira-d3d12] rp-learn-store: %lld stores skipped, %lld MB (%ld textures learned, %ld ruled out, %ld mispredictions)\n", + (long long)g_rpl_elided_n, (long long)(g_rpl_elided_b >> 20), (long)g_rpl_learned, (long)g_rpl_ruled_out, (long)g_rpl_mispredict); + return WMTStoreActionDontCare; + } + return WMTStoreActionStore; + } + mad_rpl_watch(r, RPL_PEND); + return WMTStoreActionStore; +} +/* madeira-duo rp-learn-census = N (opt-in, default 0; seconds between reports): + * what exec_rp_dead decides for every batch-end store the late-store path sees, + * so rp-learn-store's reach can be judged: dead (DontCare already), needed (and + * the command that needed it first: a draw with it bound, a copy, a partial + * clear, or a barrier by its state class), end of call / look-ahead limit (the + * stores rp-learn-store watches). Counts color stores and depth only. */ +static int g_rpc_secs = -1; +static volatile LONG64 g_rpc_n[4], g_rpc_b[4], g_rpc_why[72], g_rpc_whyb[72]; +static volatile LONG64 g_rpc_last; +static SRWLOCK g_rpc_lock = SRWLOCK_INIT; +static int mad_rpc_on(void) { + if (g_rpc_secs < 0) { + long long n = mad_cfg_int_pe("rp-learn-census", 0); /* madeira-duo: seconds between rp-learn-census reports (0 = off) */ + g_rpc_secs = n < 0 ? 0 : n > 3600 ? 3600 : (int)n; + if (g_rpc_secs) d3d12_log("[madeira-d3d12] rp-learn-census = %d: batch-end store decisions reported every %d s\n", g_rpc_secs, g_rpc_secs); + } + return g_rpc_secs; +} +static const char *mad_rpc_kind(int k, char *buf, size_t cap) { + static const char *const bc[] = { "barrier read-after-read", "barrier to read (from attachment)", "barrier to read (from copy)", "barrier UAV", "barrier global/other" }; + switch (k) { + case MC_DRAW: case MC_DRAW_INDEXED: case MC_DRAW_INDIRECT: case MC_DRAW_INDEXED_INDIRECT: return "draw with it bound"; + case MC_CLEAR_RT: case MC_CLEAR_DS: return "partial or other-view clear"; + case MC_COPY_T2T: case MC_COPY_T2B: case MC_COPY_B2T: return "copy"; + case MC_RESOLVE: return "resolve"; + case MC_FILL_TEX: return "UAV clear"; + case MC_DISCARD: return "partial discard"; + case MC_FX_TEMPORAL: return "MetalFX temporal"; + default: break; + } + if (k >= 64 && k <= 64 + BC_ALL) return bc[k - 64]; + snprintf(buf, cap, "kind %d", k); + return buf; +} +static void mad_rpc_note(int dead, LONG64 bytes) { + LONG64 now, last; + if (dead < 0 || dead > 3) return; + InterlockedIncrement64(&g_rpc_n[dead]); InterlockedExchangeAdd64(&g_rpc_b[dead], bytes); + if (dead == 0) { + int w = g_rpd_why; + if (w < 0 || w >= 72) w = 71; + InterlockedIncrement64(&g_rpc_why[w]); InterlockedExchangeAdd64(&g_rpc_whyb[w], bytes); + } + now = (LONG64)GetTickCount64(); last = g_rpc_last; + if (!last) { InterlockedCompareExchange64(&g_rpc_last, now, 0); return; } + if (now - last < (LONG64)g_rpc_secs * 1000 || InterlockedCompareExchange64(&g_rpc_last, now, last) != last) return; + if (!TryAcquireSRWLockExclusive(&g_rpc_lock)) return; + { + char line[1024], buf[32]; int len, i, j, top[6], nt = 0; + LONG64 tot = g_rpc_n[0] + g_rpc_n[1] + g_rpc_n[2] + g_rpc_n[3]; + len = snprintf(line, sizeof line, "[madeira-d3d12] rp-learn-census: %lld stores: dead %lld (%lld MB), needed %lld (%lld MB), end of call %lld (%lld MB), " + "look-ahead limit %lld (%lld MB); watched %ld, learned %ld, ruled out %ld | needed first by:", + (long long)tot, (long long)g_rpc_n[1], (long long)(g_rpc_b[1] >> 20), (long long)g_rpc_n[0], (long long)(g_rpc_b[0] >> 20), + (long long)g_rpc_n[2], (long long)(g_rpc_b[2] >> 20), (long long)g_rpc_n[3], (long long)(g_rpc_b[3] >> 20), + (long)g_rpl_nwatch, (long)g_rpl_learned, (long)g_rpl_ruled_out); + for (j = 0; j < 6; j++) { /* the six biggest by bytes */ + int best = -1; + for (i = 0; i < 72; i++) { + int used = 0, t; + for (t = 0; t < nt; t++) if (top[t] == i) used = 1; + if (!used && g_rpc_whyb[i] && (best < 0 || g_rpc_whyb[i] > g_rpc_whyb[best])) best = i; + } + if (best < 0) break; + top[nt++] = best; + if (len < (int)sizeof line) + len += snprintf(line + len, sizeof line - len, " %s %lld (%lld MB);", mad_rpc_kind(best, buf, sizeof buf), + (long long)g_rpc_why[best], (long long)(g_rpc_whyb[best] >> 20)); + } + d3d12_log("%s\n", line); + } + ReleaseSRWLockExclusive(&g_rpc_lock); } /* exec_end, before endEncoding: the store actions the pass left open. */ static void exec_rp_late_store(struct mad_exec *e) { @@ -3975,14 +4378,27 @@ static void exec_rp_late_store(struct mad_exec *e) { memset(&r, 0xff, sizeof r); r.enc = (UINT64)e->renc; memset(r.pad, 0, sizeof r.pad); for (i = 0; i < e->enc_nrt && i < 8; i++) { if (!e->enc_rt[i] || !e->enc_rt[i]->texture) continue; - r.color[i] = exec_rp_dead(e, e->enc_rt[i], &e->enc_rtp[i], 0) ? WMTStoreActionDontCare : WMTStoreActionStore; + { + int dead = exec_rp_dead(e, e->enc_rt[i], &e->enc_rtp[i], 0); + LONG64 nb = mad_tr_bytes(e->enc_rt[i], e->enc_rtp[i].level, e->enc_rtp[i].layers, 0); + if (g_rpc_secs > 0) mad_rpc_note(dead, nb); /* madeira-duo rp-learn-census */ + r.color[i] = exec_rpl_store(e->enc_rt[i], dead, nb); /* madeira-duo rp-learn-store */ + } if (r.color[i] == WMTStoreActionDontCare) moved += mad_tr_bytes(e->enc_rt[i], e->enc_rtp[i].level, e->enc_rtp[i].layers, 0); } if (e->enc_depth && e->enc_depth->texture) { - r.depth = exec_rp_dead(e, e->enc_depth, &e->enc_dp, 1) ? WMTStoreActionDontCare : WMTStoreActionStore; + int dd = exec_rp_dead(e, e->enc_depth, &e->enc_dp, 1), sd; + if (g_rpc_secs > 0) mad_rpc_note(dd, mad_tr_bytes(e->enc_depth, e->enc_dp.level, e->enc_dp.layers, 0)); /* madeira-duo rp-learn-census: depth aspect */ + sd = e->enc_depth->has_stencil ? exec_rp_dead(e, e->enc_depth, &e->enc_dp, 2) : dd; + /* madeira-duo rp-learn-store: depth and stencil are learned together, so both must be undecided */ + if (dd >= 2 && sd >= 2) { + enum WMTStoreAction a2 = exec_rpl_store(e->enc_depth, 2, mad_tr_bytes(e->enc_depth, e->enc_dp.level, e->enc_dp.layers, 0)); + dd = sd = a2 == WMTStoreActionDontCare ? 1 : 0; + } + r.depth = dd == 1 ? WMTStoreActionDontCare : WMTStoreActionStore; if (r.depth == WMTStoreActionDontCare) moved += mad_tr_bytes(e->enc_depth, e->enc_dp.level, e->enc_dp.layers, 0); if (e->enc_depth->has_stencil) { - r.stencil = exec_rp_dead(e, e->enc_depth, &e->enc_dp, 2) ? WMTStoreActionDontCare : WMTStoreActionStore; + r.stencil = sd == 1 ? WMTStoreActionDontCare : WMTStoreActionStore; if (r.stencil == WMTStoreActionDontCare) moved += mad_tr_bytes(e->enc_depth, e->enc_dp.level, e->enc_dp.layers, 1); } } @@ -4752,8 +5168,13 @@ static int exec_begin_render(struct mad_exec *e) { for (i = 0; i < e->nrt; i++) if (e->rt[i]) exec_disc_forget(e, e->rt[i]); /* this pass defines them again */ if (e->depth) exec_disc_forget(e, e->depth); } + if (g_rpl_nwatch) { /* madeira-duo rp-learn-store: a watched texture's next pass loads it or not */ + for (i = 0; i < e->nrt; i++) if (rpi.colors[i].texture) exec_rpl_begin(e->rt[i], rpi.colors[i].load_action == WMTLoadActionLoad); + if (rpi.depth.texture) exec_rpl_begin(e->depth, rpi.depth.load_action == WMTLoadActionLoad || + (rpi.stencil.texture && rpi.stencil.load_action == WMTLoadActionLoad)); + } e->rp_late = 0; /* madeira-bcd rp-discard: a texture the game discards: the store is decided when the pass ends */ - if (mad_rp_discard_on() && !g_capture_on && exec_rp_late_want(e) && mad_rp_late_ok()) { + if (((mad_rp_discard_on() && exec_rp_late_want(e)) || exec_rpl_want(e)) && !g_capture_on && mad_rp_late_ok()) { /* madeira-duo: or rp-learn-store */ for (i = 0; i < e->nrt; i++) if (rpi.colors[i].texture) rpi.colors[i].store_action = WMTStoreActionUnknown; if (rpi.depth.texture) rpi.depth.store_action = WMTStoreActionUnknown; if (rpi.stencil.texture) rpi.stencil.store_action = WMTStoreActionUnknown; @@ -4763,6 +5184,10 @@ static int exec_begin_render(struct mad_exec *e) { rpi.render_target_width = w; rpi.render_target_height = h; rpi.default_raster_sample_count = (e->nrt && e->rt[0] && e->rt[0]->samples) ? e->rt[0]->samples : (e->depth && e->depth->samples) ? e->depth->samples : 1; + if (g_vxc_secs && mad_vxc_on()) { /* madeira-duo vtx-census: keyed as the encoder label */ + e->vc_ps = e->pso ? e->pso->ps_id : 0; e->vc_vs = e->pso ? e->pso->vs_id : 0; e->vc_w = w; e->vc_h = h; + e->vc_draws = e->vc_verts = e->vc_inst = e->vc_indirect = e->vc_idx32 = 0; + } e->enc_vis_buf = 0; if (e->q->device->has_query_heaps) { /* ml1088: every pass carries the slot buffer, so a Begin mid-pass costs nothing */ struct mad_vis_batch *v = mad_vis_get(e); @@ -4779,7 +5204,7 @@ static int exec_begin_render(struct mad_exec *e) { e->renc = MTLCommandBuffer_renderCommandEncoder(e->cb, &rpi); if (e->renc) e->renc_seq = ++g_enc_seq; if (e->renc) mad_tr_pass(&rpi, e->rt, e->rtp, e->nrt, e->depth, &e->dp); /* madeira-bcd gpu-traffic */ e->rp_from = e->cur + 1; /* madeira-bcd rp-discard */ - if (g_enc_labels) mad_label(e->renc, "R#%u %s|%s %ux%u", e->renc_seq, e->pso ? e->pso->vs_name : "-", e->pso ? e->pso->ps_name : "-", w, h); /* ml1142 */ + if (g_enc_labels) mad_label(e->renc, "R#%u ps:%08x vs:%08x %ux%u", e->renc_seq, e->pso ? e->pso->ps_id : 0, e->pso ? e->pso->vs_id : 0, w, h); /* ml1142; madeira-duo: digests, PoE2's entries are all "main" */ e->diag_npso = 0; e->diag_more = 0; /* madeira-bcd: GPU fault attribution */ e->f6_natt = 0; /* ml1134: what this pass writes, for the same-attachment ordering rule */ for (i = 0; i < e->nrt && e->f6_natt < 8; i++) if (e->rt[i]) e->f6_att[e->f6_natt++] = e->rt[i]; @@ -6420,10 +6845,16 @@ static obj_handle_t mad_cpso_realize(struct mad_pso *p) { static int g_pso_async = -1; static struct mad_pso *g_pa_q[MAD_PA_MAX]; static LONG g_pa_head, g_pa_tail; +/* madeira-duo pso-create-build: pipelines queued when the game creates them wait + * here, behind everything a draw is waiting for (g_pa_q is always taken first) */ +#define MAD_PCB_MAX 16384 +static struct mad_pso *g_pcb_q[MAD_PCB_MAX]; +static LONG g_pcb_head, g_pcb_tail; static SRWLOCK g_pa_lock = SRWLOCK_INIT; static HANDLE g_pa_sem; static volatile LONG g_pa_queued, g_pa_built, g_pa_failed, g_pa_inline, g_pa_skips; static ULONG STDMETHODCALLTYPE pso_Release(ID3D12PipelineState *T); +static void mad_pcb_built(struct mad_pso *p); /* madeira-duo pso-create-build */ static int mad_pso_async_on(void) { if (g_pso_async < 0) { int on = mad_pso_lazy_on() && mad_cfg_int_pe("pso-async", 0) > 0; /* madeira.cfg pso-async: 1 = a new render pipeline is built on a background thread and its draws are skipped until it is ready (no frame waits for the compiler); 0 = built at its first draw */ @@ -6448,14 +6879,16 @@ static DWORD WINAPI mad_pa_worker(void *arg) { (void)arg; mad_name_self(L"MadeiraPSO"); /* madeira-duo: classed by MADEIRA_THREAD_QOS */ for (;;) { - struct mad_pso *p = NULL; obj_handle_t pool; LONG n = 0; + struct mad_pso *p = NULL; obj_handle_t pool; LONG n = 0; int low = 0; WaitForSingleObject(g_pa_sem, INFINITE); AcquireSRWLockExclusive(&g_pa_lock); if (g_pa_head != g_pa_tail) { p = g_pa_q[(ULONG)g_pa_head % MAD_PA_MAX]; g_pa_head++; } + else if (g_pcb_head != g_pcb_tail) { p = g_pcb_q[(ULONG)g_pcb_head % MAD_PCB_MAX]; g_pcb_head++; low = 1; } /* pso-create-build */ ReleaseSRWLockExclusive(&g_pa_lock); if (!p) continue; pool = NSAutoreleasePool_alloc_init(); - if (mad_pso_realize(p)) n = InterlockedIncrement(&g_pa_built); + if (low) mad_pcb_built(p); /* pso-create-build: counted on its own */ + else if (mad_pso_realize(p)) n = InterlockedIncrement(&g_pa_built); else InterlockedIncrement(&g_pa_failed); if (n == 1 || (n && !(n % 250))) d3d12_log("[madeira-d3d12] pso-async: %ld pipelines built off the render thread (%ld failed, %ld waiting, %ld built at the draw with the queue full); " @@ -6477,7 +6910,7 @@ static int mad_pa_start(void) { * stayed invisible for seconds (text15: 11k draws skipped). */ unsigned want = (unsigned)mad_cfg_int_pe("pso-async-threads", 2); if (want < 1) want = 1; if (want > 8) want = 8; - g_pa_sem = CreateSemaphoreA(NULL, 0, MAD_PA_MAX, NULL); + g_pa_sem = CreateSemaphoreA(NULL, 0, MAD_PA_MAX + MAD_PCB_MAX, NULL); d3d12_log("[madeira-d3d12] pso-async: %u builder threads (madeira.cfg pso-async-threads)\n", want); for (t = 0; g_pa_sem && t < want; t++) { HANDLE h = CreateThread(NULL, 256 << 10, mad_pa_worker, NULL, 0, NULL); @@ -6492,8 +6925,13 @@ static int mad_pa_start(void) { } /* 1: the pipeline is queued (now or earlier) or built; 0: the caller builds it itself. */ static int mad_pso_async_queue(struct mad_pso *p) { + LONG was; if (p->rps || !p->lazy) return 1; - if (InterlockedCompareExchange(&p->async_q, 1, 0)) return 1; /* queued earlier */ + was = InterlockedCompareExchange(&p->async_q, 1, 0); + /* pso-create-build: waiting in the low-priority queue and now drawn -- queue it + * again at the front; whichever entry a builder reaches first builds it */ + if (was == 2 && InterlockedCompareExchange(&p->async_q, 1, 2) == 2) was = 0; + if (was) return 1; /* queued earlier */ if (!mad_pa_start()) { InterlockedExchange(&p->async_q, 0); return 0; } AcquireSRWLockExclusive(&g_pa_lock); if (g_pa_tail - g_pa_head >= MAD_PA_MAX) { @@ -6511,6 +6949,224 @@ static int mad_pso_async_queue(struct mad_pso *p) { return 1; } +/* madeira-duo PIPELINES BUILT WHEN THE GAME CREATES THEM (madeira.cfg + * pso-create-build, opt-in, default 0). With pso-async a lazy pipeline is built + * once a draw asks for it, and its draws are skipped until then: on a new PoE2 + * map enemies and effects stayed invisible for seconds (prof13: 3,505 draws + * skipped). PoE2 creates its pipelines well before it draws with them (~10,000 + * created, ~2,700 drawn a session), so the build can start at creation instead. + * 1 = pipelines drawn in an earlier session. Every pipeline drawn is + * remembered by a key of its content (shader digests and fixed-function + * state) in %LOCALAPPDATA%\Madeira\pso-seen-.bin; at creation, a + * pipeline on that list is queued for the background builders. + * 2 = every plain render pipeline at creation (Metal memory for all of them). + * Create-time builds wait in a queue of their own, behind everything a draw is + * waiting for, and a queued pipeline that gets drawn is moved to the front. + * Needs pso-async = 1. pso-seen-record = 1 keeps the list with the build off, + * to collect it before trying 1. */ +static int g_pcb_mode = -1, g_seen_record; +static volatile LONG g_pcb_queued, g_pcb_built_n, g_pcb_failed, g_pcb_full, g_pcb_hits, g_pcb_misses; +#define MAD_SEEN_CAP 131072 /* table slots, a power of two; at most half are used */ +static UINT64 *g_seen_tab; +static LONG g_seen_n, g_seen_dirty; +static SRWLOCK g_seen_lock = SRWLOCK_INIT; +static WCHAR g_seen_path[MAX_PATH]; +static HANDLE g_seen_evt; +static int mad_pcb_mode(void) { + if (g_pcb_mode < 0) { + long long m = mad_cfg_int_pe("pso-create-build", 0); /* madeira-duo: 1 = pipelines drawn in an earlier session are built in the background when the game creates them, 2 = every plain render pipeline; 0 = at their first draw (as before) */ + int v = m <= 0 ? 0 : m >= 2 ? 2 : 1; + g_seen_record = v == 1 || mad_cfg_int_pe("pso-seen-record", 0) > 0; /* madeira-duo: 1 = remember the pipelines drawn (pso-create-build = 1 does it anyway) */ + if (v || g_seen_record) + d3d12_log("[madeira-d3d12] pso-create-build = %d%s: %s\n", v, g_seen_record ? ", pso-seen-record" : "", + v == 2 ? "every plain render pipeline is queued for the background builders when the game creates it" + : v == 1 ? "pipelines drawn in earlier sessions are queued for the background builders when the game creates them" + : "pipelines drawn are remembered for pso-create-build = 1"); + MemoryBarrier(); + g_pcb_mode = v; + } + return g_pcb_mode; +} +static UINT64 mad_seen_fnv(UINT64 h, const void *data, SIZE_T n) { + const BYTE *b = data; SIZE_T i; + for (i = 0; i < n; i++) { h ^= b[i]; h *= 1099511628211ull; } + return h; +} +static UINT64 mad_seen_u32(UINT64 h, UINT v) { return mad_seen_fnv(h, &v, sizeof v); } +/* A DXBC/DXIL container carries a 16-byte digest of its contents at offset 4; + * anything else is hashed whole. */ +static UINT64 mad_seen_shader(UINT64 h, const D3D12_SHADER_BYTECODE *bc) { + const BYTE *b = bc->pShaderBytecode; + if (!b || !bc->BytecodeLength) return mad_seen_u32(h, 0); + h = mad_seen_u32(h, (UINT)bc->BytecodeLength); + if (bc->BytecodeLength >= 20 && !memcmp(b, "DXBC", 4)) return mad_seen_fnv(h, b + 4, 16); + return mad_seen_fnv(h, b, bc->BytecodeLength); +} +/* Field by field: the D3D12 structs have padding whose bytes are not the game's. */ +static UINT64 mad_seen_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC *d) { + UINT64 h = 1469598103934665603ull; UINT i; + const D3D12_DEPTH_STENCIL_DESC *ds = &d->DepthStencilState; + h = mad_seen_shader(h, &d->VS); h = mad_seen_shader(h, &d->PS); + h = mad_seen_u32(h, d->BlendState.AlphaToCoverageEnable); h = mad_seen_u32(h, d->BlendState.IndependentBlendEnable); + for (i = 0; i < 8; i++) { + const D3D12_RENDER_TARGET_BLEND_DESC *b = &d->BlendState.RenderTarget[i]; + h = mad_seen_u32(h, b->BlendEnable); h = mad_seen_u32(h, b->LogicOpEnable); + h = mad_seen_u32(h, b->SrcBlend); h = mad_seen_u32(h, b->DestBlend); h = mad_seen_u32(h, b->BlendOp); + h = mad_seen_u32(h, b->SrcBlendAlpha); h = mad_seen_u32(h, b->DestBlendAlpha); h = mad_seen_u32(h, b->BlendOpAlpha); + h = mad_seen_u32(h, b->LogicOp); h = mad_seen_u32(h, b->RenderTargetWriteMask); + } + h = mad_seen_u32(h, d->SampleMask); + h = mad_seen_fnv(h, &d->RasterizerState, sizeof d->RasterizerState); /* 4-byte fields only, no padding */ + h = mad_seen_u32(h, ds->DepthEnable); h = mad_seen_u32(h, ds->DepthWriteMask); h = mad_seen_u32(h, ds->DepthFunc); + h = mad_seen_u32(h, ds->StencilEnable); h = mad_seen_u32(h, ds->StencilReadMask); h = mad_seen_u32(h, ds->StencilWriteMask); + h = mad_seen_fnv(h, &ds->FrontFace, sizeof ds->FrontFace); h = mad_seen_fnv(h, &ds->BackFace, sizeof ds->BackFace); + h = mad_seen_u32(h, d->InputLayout.NumElements); + for (i = 0; d->InputLayout.pInputElementDescs && i < d->InputLayout.NumElements; i++) { + const D3D12_INPUT_ELEMENT_DESC *e = &d->InputLayout.pInputElementDescs[i]; + if (e->SemanticName) h = mad_seen_fnv(h, e->SemanticName, strlen(e->SemanticName)); + h = mad_seen_u32(h, e->SemanticIndex); h = mad_seen_u32(h, e->Format); h = mad_seen_u32(h, e->InputSlot); + h = mad_seen_u32(h, e->AlignedByteOffset); h = mad_seen_u32(h, e->InputSlotClass); h = mad_seen_u32(h, e->InstanceDataStepRate); + } + h = mad_seen_u32(h, d->IBStripCutValue); h = mad_seen_u32(h, d->PrimitiveTopologyType); + h = mad_seen_u32(h, d->NumRenderTargets); + for (i = 0; i < 8; i++) h = mad_seen_u32(h, d->RTVFormats[i]); + h = mad_seen_u32(h, d->DSVFormat); h = mad_seen_u32(h, d->SampleDesc.Count); h = mad_seen_u32(h, d->SampleDesc.Quality); + return h ? h : 1; /* 0 marks an empty slot */ +} +static UINT64 *mad_seen_slot(UINT64 *tab, UINT64 k) { + ULONG i = (ULONG)(k ^ (k >> 29)) & (MAD_SEEN_CAP - 1); + while (tab[i] && tab[i] != k) i = (i + 1) & (MAD_SEEN_CAP - 1); + return &tab[i]; +} +static void mad_seen_save(void) { + struct { UINT magic, version, count, reserved; } hdr = { 0x4e53504du /* "MPSN" */, 1, 0, 0 }; + UINT64 *keys; LONG n = 0, i; WCHAR tmp[MAX_PATH + 8]; HANDLE f; DWORD wr; BOOL ok; + if (!g_seen_path[0] || !(keys = malloc(sizeof *keys * (MAD_SEEN_CAP / 2)))) return; + AcquireSRWLockShared(&g_seen_lock); + for (i = 0; i < MAD_SEEN_CAP && n < MAD_SEEN_CAP / 2; i++) if (g_seen_tab[i]) keys[n++] = g_seen_tab[i]; + InterlockedExchange(&g_seen_dirty, 0); + ReleaseSRWLockShared(&g_seen_lock); + hdr.count = (UINT)n; + _snwprintf(tmp, MAX_PATH + 8, L"%ls.tmp", g_seen_path); + f = CreateFileW(tmp, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (f == INVALID_HANDLE_VALUE) { free(keys); return; } + ok = WriteFile(f, &hdr, sizeof hdr, &wr, NULL) && wr == sizeof hdr && + WriteFile(f, keys, (DWORD)(n * sizeof *keys), &wr, NULL) && wr == (DWORD)(n * sizeof *keys); + CloseHandle(f); + free(keys); + if (!ok || !MoveFileExW(tmp, g_seen_path, MOVEFILE_REPLACE_EXISTING)) DeleteFileW(tmp); +} +static DWORD WINAPI mad_seen_saver(void *arg) { + (void)arg; + mad_name_self(L"MadeiraPSOSeen"); + for (;;) { + WaitForSingleObject(g_seen_evt, 30000); + if (g_seen_dirty) mad_seen_save(); + } + return 0; +} +/* Loads the list once; 0 when there is none to use. */ +static int mad_seen_ready(void) { + static volatile LONG state; /* 0 not loaded, 1 loading, 2 ready, 3 unavailable */ + LONG s = InterlockedCompareExchange(&state, 1, 0); + if (s == 0) { + WCHAR exe[MAX_PATH], base[MAX_PATH]; DWORD n, i; UINT64 h = 1469598103934665603ull; + UINT64 *tab = calloc(MAD_SEEN_CAP, sizeof *tab); + LONG loaded = 0; + n = GetModuleFileNameW(NULL, exe, MAX_PATH); + for (i = 0; i < n && n < MAX_PATH; i++) if (exe[i] >= 'A' && exe[i] <= 'Z') exe[i] += 'a' - 'A'; + if (n && n < MAX_PATH) h = mad_seen_fnv(h, exe, n * sizeof(WCHAR)); + n = GetEnvironmentVariableW(L"LOCALAPPDATA", base, MAX_PATH); + if (tab && n && n < MAX_PATH - 64) { + HANDLE f; DWORD rd; + struct { UINT magic, version, count, reserved; } hdr; + _snwprintf(g_seen_path, MAX_PATH, L"%ls\\Madeira", base); + CreateDirectoryW(g_seen_path, NULL); + _snwprintf(g_seen_path, MAX_PATH, L"%ls\\Madeira\\pso-seen-%016llx.bin", base, (unsigned long long)h); + f = CreateFileW(g_seen_path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (f != INVALID_HANDLE_VALUE) { + if (ReadFile(f, &hdr, sizeof hdr, &rd, NULL) && rd == sizeof hdr && hdr.magic == 0x4e53504du && hdr.version == 1) { + UINT64 k; UINT c; + for (c = 0; c < hdr.count && loaded < MAD_SEEN_CAP / 2; c++) { + if (!ReadFile(f, &k, sizeof k, &rd, NULL) || rd != sizeof k) break; + if (k && !*mad_seen_slot(tab, k)) { *mad_seen_slot(tab, k) = k; loaded++; } + } + } + CloseHandle(f); + } + g_seen_tab = tab; g_seen_n = loaded; + if (g_seen_record && (g_seen_evt = CreateEventA(NULL, FALSE, FALSE, NULL))) { + HANDLE t = CreateThread(NULL, 64 << 10, mad_seen_saver, NULL, 0, NULL); + if (t) CloseHandle(t); + } + d3d12_log("[madeira-d3d12] pso-create-build: %ld pipelines on the list of ones drawn before (%ls)\n", (long)loaded, g_seen_path); + } else free(tab); + MemoryBarrier(); + InterlockedExchange(&state, g_seen_tab ? 2 : 3); + return g_seen_tab != NULL; + } + while (s == 1) { Sleep(0); s = InterlockedCompareExchange(&state, 1, 1); } + return s == 2; +} +static int mad_seen_has(UINT64 k) { + int hit; + if (!mad_seen_ready()) return 0; + AcquireSRWLockShared(&g_seen_lock); + hit = *mad_seen_slot(g_seen_tab, k) == k; + ReleaseSRWLockShared(&g_seen_lock); + return hit; +} +/* A draw used this pipeline: put it on the list (first draw of the session only). */ +static void mad_seen_mark(struct mad_pso *p) { + UINT64 *slot; LONG n = 0; + if (InterlockedExchange(&p->seen_mark, 1) || !mad_seen_ready()) return; + AcquireSRWLockExclusive(&g_seen_lock); + slot = mad_seen_slot(g_seen_tab, p->seen_key); + if (!*slot && g_seen_n < MAD_SEEN_CAP / 2) { *slot = p->seen_key; n = ++g_seen_n; } + ReleaseSRWLockExclusive(&g_seen_lock); + if (n && !(InterlockedIncrement(&g_seen_dirty) % 64) && g_seen_evt) SetEvent(g_seen_evt); +} +static void mad_pcb_built(struct mad_pso *p) { + LONG n = 0; + if (mad_pso_realize(p)) n = InterlockedIncrement(&g_pcb_built_n); + else InterlockedIncrement(&g_pcb_failed); + if (n == 1 || (n && !(n % 500))) + d3d12_log("[madeira-d3d12] pso-create-build: %ld pipelines built ahead of their first draw (%ld failed, %ld queued, %ld not queued with the queue " + "full; on the drawn-before list %ld, not on it %ld)\n", (long)g_pcb_built_n, (long)g_pcb_failed, (long)g_pcb_queued, + (long)g_pcb_full, (long)g_pcb_hits, (long)g_pcb_misses); +} +/* At creation: 1 when the pipeline went to the low-priority queue. */ +static int mad_pcb_on_create(struct mad_pso *p, const D3D12_GRAPHICS_PIPELINE_STATE_DESC *desc) { + int mode = mad_pcb_mode(); + static int said_noasync; + if (g_seen_record) p->seen_key = mad_seen_key(desc); /* drawn ones go on the list (mad_seen_mark) */ + if (!mode) return 0; + if (mode == 1) { + if (!mad_seen_has(p->seen_key)) { InterlockedIncrement(&g_pcb_misses); return 0; } + InterlockedIncrement(&g_pcb_hits); + } + if (!mad_pso_async_on()) { + if (!said_noasync++) d3d12_log("[madeira-d3d12] pso-create-build needs pso-async = 1; pipelines are built at their first draw\n"); + return 0; + } + if (p->rps || !p->lazy || InterlockedCompareExchange(&p->async_q, 2, 0)) return 0; + if (!mad_pa_start()) { InterlockedExchange(&p->async_q, 0); return 0; } + AcquireSRWLockExclusive(&g_pa_lock); + if (g_pcb_tail - g_pcb_head >= MAD_PCB_MAX) { + ReleaseSRWLockExclusive(&g_pa_lock); + InterlockedExchange(&p->async_q, 0); + InterlockedIncrement(&g_pcb_full); + return 0; + } + InterlockedIncrement(&p->refs); /* the worker releases it once the pipeline is built */ + g_pcb_q[(ULONG)g_pcb_tail % MAD_PCB_MAX] = p; g_pcb_tail++; + ReleaseSRWLockExclusive(&g_pa_lock); + ReleaseSemaphore(g_pa_sem, 1, NULL); + if (InterlockedIncrement(&g_pcb_queued) == 1) + d3d12_log("[madeira-d3d12] pso-create-build: first pipeline queued at creation\n"); + return 1; +} + /* PARALLEL FIRST USE. Built at its first draw, a lazy pipeline is compiled on * the submitting thread, one after another, and the first seconds of Ghost of * Tsushima's gameplay need hundreds: ExecuteCommandLists grew from 25 ms to @@ -8732,6 +9388,7 @@ static void exec_draw(struct mad_exec *e, const struct mad_cmd *c) { * (Astra). An engine that zeroes the count of a culled draw would have drawn * one instance of it. Not a skip: there is nothing to draw. */ if ((c->kind == MC_DRAW && !c->u.draw.icount) || (c->kind == MC_DRAW_INDEXED && !c->u.drawi.inst)) { InterlockedIncrement(&g_zero_inst); return; } + if (e->pso && e->pso->seen_key && !e->pso->seen_mark) mad_seen_mark(e->pso); /* madeira-duo pso-create-build */ if (e->pso && !e->pso->rps && e->pso->lazy) { if (!e->pso->tess && mad_pso_async_on() && mad_pso_async_queue(e->pso)) { if (!e->pso->rps) { InterlockedIncrement(&g_pa_skips); MAD_SKIP(e); return; } /* pso-async: still being built */ @@ -8742,6 +9399,7 @@ static void exec_draw(struct mad_exec *e, const struct mad_cmd *c) { MAD_SKIP(e); return; } + if (g_vxc_secs > 0) exec_vc_draw(e, c); /* madeira-duo vtx-census */ if (g_fault_diag) { /* madeira-bcd: GPU fault attribution */ if (mad_fault_skip_pso(e->pso)) { MAD_SKIP(e); return; } mad_fault_note(e, e->pso); @@ -10140,7 +10798,7 @@ static void exec_dispatch(struct mad_exec *e, const struct mad_cmd *c) { e->cenc_pso = e->cpso; e->cenc_seq = g_enc_seq; if (g_fault_diag) mad_label(e->cenc, "C#%u %s fn=%llx:%s", g_enc_seq, e->cpso->vs_name, (unsigned long long)e->cpso->vs_fn, e->cpso->vs_name); - else if (g_enc_labels) mad_label(e->cenc, "C#%u %s", g_enc_seq, e->cpso->vs_name); /* ml1142 */ + else if (g_enc_labels) mad_label(e->cenc, "C#%u %s cs:%08x", g_enc_seq, e->cpso->vs_name, (unsigned)e->cpso->cs_hash); /* ml1142; madeira-duo: + bytecode hash */ if (!e->cenc) { d3d12_log("[madeira-d3d12] no compute encoder\n"); MAD_SKIP(e); return; } exec_fence_compute(e, e->cenc, 0); /* ml1091 */ } @@ -10465,8 +11123,8 @@ static void mad_gw_note(struct mad_pso *p, LONG64 work) { if (cur && cur != p) continue; if (!cur) { g->compute = p->is_compute; - if (p->is_compute) snprintf(g->name, sizeof g->name, "%.48s", p->vs_name); - else snprintf(g->name, sizeof g->name, "%.40s/%.40s", p->vs_name, p->ps_name); + if (p->is_compute) snprintf(g->name, sizeof g->name, "%.40s cs:%08x", p->vs_name, (unsigned)p->cs_hash); + else snprintf(g->name, sizeof g->name, "ps:%08x vs:%08x", p->ps_id, p->vs_id); /* madeira-duo: matches the encoder labels */ } } InterlockedIncrement(&g->draws); @@ -10707,6 +11365,7 @@ static void mad_exec_list(struct mad_queue *q, struct mad_list *l, obj_handle_t if (g_capture_on) mad_capture_log_op(c); /* madeira-bcd */ if (g_ffx_exp > 0 && c->kind == MC_DISPATCH) mad_ffx_before(&e, c); /* fi-setup-zero, fi-field-check */ if ((e.npend | e.rp_ndisc) || c->kind == MC_DISCARD) exec_rp_note(&e, c); /* madeira-bcd clear-defer, rp-discard */ + if (g_rpl_nwatch) exec_rpl_note(c); /* madeira-duo rp-learn-store */ switch (c->kind) { case MC_PSO: if (c->u.pso && c->u.pso->is_compute) e.cpso = c->u.pso; else e.pso = c->u.pso; if (g_sd_state > 0 && g_pso_first && c->u.pso && !c->u.pso->first_used) mad_pso_first(c->u.pso); /* madeira-bcd: pso-first-use */ @@ -12981,14 +13640,38 @@ static void mad_mheap_reclaim(struct mad_device *d, int all) { } } static void mad_hp_reclaim_locked(struct mad_device *d) { - UINT64 done = mad_gpu_completed(d); unsigned i = 0; + UINT64 done = mad_gpu_completed(d); unsigned i = 0, freed = 0, spare = 0; while (i < d->nhret) { if (d->hret[i].serial <= done) { mad_hp_free_locked(&d->theaps[d->hret[i].heap], d->hret[i].off, d->hret[i].size); InterlockedExchangeAdd64(&d->hp_live_bytes, -(LONG64)d->hret[i].size); d->hret[i] = d->hret[--d->nhret]; + freed++; } else i++; } + /* madeira-duo hp-release: a runtime texture heap with nothing left in it goes back + * to the system (one empty heap is kept as a spare). The heaps used to stay at the + * peak of every area load: 8 x 64 MB reserved for 163 MB live in prof12b, all of it + * GPU memory inside the footprint that sets the video budget. Its slot stays (index + * 0 heap, size 0) so live textures' heap indices don't move; mad_hp_alloc skips it + * and reuses it for the next heap. The release waits for the GPU like a D3D12 + * heap's (mhret). madeira.cfg hp-release = 0 keeps every heap. */ + if (freed) { + static int on = -1; + if (on < 0) on = mad_cfg_int_pe("hp-release", 1) ? 1 : 0; + for (i = 0; on && i < d->ntheaps; i++) { + struct mad_texheap *h = &d->theaps[i]; + if (!h->heap || h->nfl != 1 || h->fl[0].off != 0 || h->fl[0].size != h->size) continue; + if (!spare++) continue; + if (!mad_grow((void **)&d->mhret, &d->mhret_cap, d->nmhret + 1, sizeof *d->mhret)) break; + d->mhret[d->nmhret].heap = h->heap; d->mhret[d->nmhret].mem = NULL; + d->mhret[d->nmhret].serial = (UINT64)d->gpu_serial; d->nmhret++; + InterlockedExchangeAdd64(&d->hp_total_bytes, -(LONG64)h->size); + d3d12_log("[madeira-d3d12] hp-release: empty texture heap #%u (%llu MB) released; %lld MB in heaps, %lld MB live\n", + i + 1, (unsigned long long)(h->size >> 20), (long long)(d->hp_total_bytes >> 20), (long long)(d->hp_live_bytes >> 20)); + h->heap = 0; h->size = 0; h->nfl = 0; + } + } } /* Returns the heap index or -1; *off is the placed offset. */ static int mad_hp_alloc(struct mad_device *d, UINT64 size, UINT64 align, UINT64 *off) { @@ -12998,6 +13681,7 @@ static int mad_hp_alloc(struct mad_device *d, UINT64 size, UINT64 align, UINT64 mad_hp_reclaim_locked(d); for (hi = 0; hi < d->ntheaps && found < 0; hi++) { struct mad_texheap *h = &d->theaps[hi]; + if (!h->heap) continue; /* madeira-duo hp-release: a released slot */ for (bi = 0; bi < h->nfl; bi++) { UINT64 a = (h->fl[bi].off + align - 1) & ~(align - 1); if (a + size <= h->fl[bi].off + h->fl[bi].size) { @@ -13014,20 +13698,25 @@ static int mad_hp_alloc(struct mad_device *d, UINT64 size, UINT64 align, UINT64 if (found < 0) { UINT64 hs = size > MAD_HP_HEAP_BYTES ? size : MAD_HP_HEAP_BYTES; obj_handle_t heap = MTLDevice_newPlacementHeap(d->mtl_device, hs, WMTResourceStorageModePrivate); - if (heap && mad_grow((void **)&d->theaps, &d->theaps_cap, d->ntheaps + 1, sizeof *d->theaps)) { - struct mad_texheap *h = &d->theaps[d->ntheaps]; + unsigned slot = d->ntheaps; + for (hi = 0; hi < d->ntheaps; hi++) if (!d->theaps[hi].heap) { slot = hi; break; } /* madeira-duo hp-release: reuse a released slot */ + if (heap && (slot < d->ntheaps || mad_grow((void **)&d->theaps, &d->theaps_cap, d->ntheaps + 1, sizeof *d->theaps))) { + struct mad_texheap *h = &d->theaps[slot]; + struct mad_hblk *keep_fl = h->fl; unsigned keep_cap = slot < d->ntheaps ? h->fl_cap : 0; memset(h, 0, sizeof *h); + if (slot < d->ntheaps) { h->fl = keep_fl; h->fl_cap = keep_cap; } /* the old free list's storage */ h->heap = heap; h->size = hs; mad_hp_free_locked(h, 0, hs); mad_resident(d, heap); /* residency follows the heap, not its textures */ InterlockedExchangeAdd64(&d->hp_total_bytes, (LONG64)hs); - found = (int)d->ntheaps++; + found = (int)slot; + if (slot == d->ntheaps) d->ntheaps++; /* the whole heap is free, so the first block fits by construction */ memmove(&h->fl[0], &h->fl[1], (h->nfl - 1) * sizeof *h->fl); h->nfl--; if (hs > size) mad_hp_free_locked(h, size, hs - size); *off = 0; d3d12_log("[madeira-d3d12] ml1072 texture heap #%u created (%llu MB; %lld MB in heaps, %ld small textures placed so far)\n", - d->ntheaps, (unsigned long long)(hs >> 20), (long long)(d->hp_total_bytes >> 20), d->hp_textures); + slot + 1, (unsigned long long)(hs >> 20), (long long)(d->hp_total_bytes >> 20), d->hp_textures); } else if (heap) NSObject_release(heap); } if (found >= 0) InterlockedExchangeAdd64(&d->hp_live_bytes, (LONG64)size); @@ -15211,6 +15900,7 @@ static ULONG STDMETHODCALLTYPE res_Release(ID3D12Resource *This) { struct mad_resource *r = (struct mad_resource *)This; LONG n = InterlockedDecrement(&r->refs); if (n == 0) { mad_pd_purge(This); /* ml1143 */ + if (r->rpl_state & RPL_WATCH) mad_rpl_forget(r); /* madeira-duo rp-learn-store */ /* The backend owns the storage, so releasing the buffer is the whole * teardown; there is no separate free to order against it. */ mad_untrack(r->owner, r); @@ -17275,6 +17965,20 @@ static void mad_resolve_target(struct mad_device *d) { * PSO as fatal. Every device this runtime targets runs iOS 26+. */ snprintf(g_target.os_version, sizeof g_target.os_version, "18.0"); } + /* madeira-duo msc-gpu-family / msc-min-os (opt-in): convert for a newer GPU + * family or OS than the defaults above, so the converter may use what they + * add. A family the device does not report is refused. Both are part of + * every shader cache key already (the conversion target is). */ + { + long long fam = mad_cfg_int_pe("msc-gpu-family", 0); /* madeira-duo: 0 = the device's newest of Apple7-9 (as before); 1006-1010 = convert for that Apple GPU family, if the device reports it */ + char ver[16]; + if (fam >= 1006 && fam <= 1010 && g_target.os == MADEIRA_IR_OS_IOS) { + if (MTLDevice_supportsFamily(d->mtl_device, (enum WMTGPUFamily)fam)) g_target.family = (uint32_t)fam; + else d3d12_log("[madeira-d3d12] msc-gpu-family = %lld: the device does not report it; kept family %u\n", fam, g_target.family); + } + if (mad_cfg_str_pe("msc-min-os", ver, sizeof ver) && ver[0] >= '1' && ver[0] <= '9') /* madeira-duo: minimum OS the conversion targets, e.g. 26.0 (default 18.0 on iOS) */ + snprintf(g_target.os_version, sizeof g_target.os_version, "%s", ver); + } g_target.resolved = 1; d3d12_log("[madeira-d3d12] conversion target: %s, family %u, min %s " "(device reports mac2=%d apple9=%d apple8=%d apple7=%d)\n", @@ -17412,7 +18116,7 @@ static char g_sc_stamp[96] = "madeira_d3d12 bc1 converter " MAD_SC_CONVERTER_ID; #else static char g_sc_stamp[96] = "madeira_d3d12 bc1 " __DATE__ " " __TIME__; #endif -static char g_sc_rt[96]; +static char g_sc_rt[160]; /* madeira-duo: 96 -> 160, room for the msc-* additions */ /* madeira-bcd shader-cache-native (see mad_scn_init): winemetal's handle for the * build directory (MadeiraCtl op 20); 0 = Wine's file API. */ static UINT32 g_scn; @@ -17445,7 +18149,7 @@ static void mad_sc_key(const struct madeira_ir_convert_args *a, UINT64 key[2]) { struct mad_sc_hash h = { 0xcbf29ce484222325ull, 0x84222325cbf29ce4ull }; const struct madeira_ir_input_layout *lay = (const struct madeira_ir_input_layout *)(uintptr_t)a->layout; mad_sc_feed(&h, g_sc_stamp, strlen(g_sc_stamp) + 1); - mad_sc_feed(&h, g_sc_rt, sizeof g_sc_rt); + mad_sc_feed(&h, g_sc_rt, strlen(g_sc_rt) < 96 ? 96 : sizeof g_sc_rt); /* madeira-duo: the old 96 bytes while it fits, so the default keys stay */ mad_sc_feed_blob(&h, a->dxil, a->dxil_len); mad_sc_feed_str(&h, a->entry_point); mad_sc_feed_blob(&h, a->params, a->num_params * sizeof(struct madeira_ir_root_param)); @@ -17631,6 +18335,16 @@ static int mad_sc_init(void) { size_t l = strlen(g_sc_rt); snprintf(g_sc_rt + l, sizeof g_sc_rt - l, ", dxbc-spaces 1"); } + /* madeira-duo: converter switches read only by madeira_ir_unix.mm; like + * dxbc-spaces, a non-default value gets a cache identity of its own */ + if (mad_cfg_int_pe("msc-ignore-debug-info", 0)) { + size_t l = strlen(g_sc_rt); + snprintf(g_sc_rt + l, sizeof g_sc_rt - l, ", msc-nodebug 1"); + } + if (!mad_cfg_int_pe("msc-validation", 1)) { + size_t l = strlen(g_sc_rt); + snprintf(g_sc_rt + l, sizeof g_sc_rt - l, ", msc-novalidate 1"); + } /* The build directory is the converter's identity alone -- this DLL's * stamp and the app image the converter's unix half is linked into * (MADEIRA_APP_IMAGE_UUID, from the bridge) -- and only other builds' @@ -17643,7 +18357,7 @@ static int mad_sc_init(void) { if (!ul || ul >= sizeof uuid) uuid[0] = 0; mad_sc_feed(&h, g_sc_stamp, strlen(g_sc_stamp) + 1); mad_sc_feed(&h, uuid, strlen(uuid) + 1); - mad_sc_feed(&hr, g_sc_rt, sizeof g_sc_rt); + mad_sc_feed(&hr, g_sc_rt, strlen(g_sc_rt) < 96 ? 96 : sizeof g_sc_rt); /* madeira-duo: as in mad_sc_key */ n = GetEnvironmentVariableW(L"LOCALAPPDATA", base, MAX_PATH); if (!n || n >= MAX_PATH - 112) on = 0; else { @@ -19597,6 +20311,9 @@ static HRESULT device_CreateGraphicsPipelineState_impl(ID3D12Device *This, if (!p) return E_OUTOFMEMORY; p->vtbl = &g_pso_vtbl; p->refs = 1; p->iid = &IID_ID3D12PipelineState; p->name = "PipelineState"; p->born_present = g_presents_now; p->born_tick = GetTickCount(); /* madeira-bcd: pso-first-use */ + if (desc->VS.BytecodeLength >= 8) memcpy(&p->vs_id, (const BYTE *)desc->VS.pShaderBytecode + 4, 4); /* madeira-duo gpu-pass-timing */ + if (desc->PS.pShaderBytecode && desc->PS.BytecodeLength >= 8) memcpy(&p->ps_id, (const BYTE *)desc->PS.pShaderBytecode + 4, 4); + if (g_vxc_secs && mad_vxc_on()) mad_vary_measure(p, desc); /* madeira-duo vtx-census: vertex output bytes */ if (mad_skin_on()) { /* madeira-bcd skin-check: the vertex shader's bytecode, by hash */ p->vs_hash = mad_fnv64(desc->VS.pShaderBytecode, desc->VS.BytecodeLength); mad_skin_layout(p, &desc->InputLayout); /* skin-check-trace: an integer input keeps the bytecode past the shared store */ @@ -20066,7 +20783,11 @@ static HRESULT device_CreateGraphicsPipelineState_impl(ID3D12Device *This, } /* madeira-bcd pso-lazy-libs: built at its first draw, so its libraries can go * until then (pso-warm, above, holds its own references to the functions) */ - if (lz_on && p->lazy && !p->rps && mad_lzlib_can_drop(p, &lzv, &lzp)) mad_lzlib_drop(p, &lzv, &lzp); + { + /* madeira-duo pso-create-build: queued now, so its libraries stay */ + int queued = p->lazy && !p->rps && !p->tess && !p->gs_emu && mad_pcb_on_create(p, desc); + if (!queued && lz_on && p->lazy && !p->rps && mad_lzlib_can_drop(p, &lzv, &lzp)) mad_lzlib_drop(p, &lzv, &lzp); + } hr = pso_QI((ID3D12PipelineState *)p, riid, out); pso_Release((ID3D12PipelineState *)p); return hr; diff --git a/madeira-d3d12/src/unix/madeira_ir_unix.mm b/madeira-d3d12/src/unix/madeira_ir_unix.mm index 5fff64a637..747781779b 100644 --- a/madeira-d3d12/src/unix/madeira_ir_unix.mm +++ b/madeira-d3d12/src/unix/madeira_ir_unix.mm @@ -81,6 +81,8 @@ * hull/domain shader then reports no tessellation numbers and its pipeline * stays a placeholder. */ #define IR_OPT_FUNC_LIST(X) \ + X(IRCompilerIgnoreDebugInformation) \ + X(IRCompilerSetValidationFlags) \ X(IRShaderReflectionCopyHullInfo) \ X(IRShaderReflectionReleaseHullInfo) \ X(IRShaderReflectionCopyDomainInfo) \ @@ -1683,6 +1685,34 @@ static uint32_t mad_ir_compat_flags(void) { return (uint32_t)cached; } +/* madeira-duo: converter settings outside the compatibility flags (opt-in). + * - msc-ignore-debug-info = 1: the converter drops the DXIL's debug information + * (IRCompilerIgnoreDebugInformation); smaller libraries, less to compile. + * - msc-validation = 0: no compile-time validation of the input DXIL + * (IRCompilerSetValidationFlags none); the game's DXIL passed DXC already. + * Either one, set away from its default, joins the DXIL cache key here and the + * PE side's cache identity (madeira_d3d12.c, g_sc_rt). Bits 16+ never reach the + * converter. */ +#define MAD_IR_OPT_NODEBUG (1u << 16) +#define MAD_IR_OPT_NOVALIDATE (1u << 17) +static uint32_t mad_ir_opts(void) { + static int cached = -1; + if (cached < 0) { + int nodebug, novalidate; + pthread_once(&g_ir_once, ir_load_once); /* the optional symbols decide */ + nodebug = madeira_cfg_int("msc-ignore-debug-info", 0) ? 1 : 0; + novalidate = madeira_cfg_int("msc-validation", 1) ? 0 : 1; + if (nodebug && !g_ir.IRCompilerIgnoreDebugInformation) nodebug = 0; + if (novalidate && !g_ir.IRCompilerSetValidationFlags) novalidate = 0; + if (nodebug || novalidate) + fprintf(stderr, "[madeira-ir] madeira-duo converter options: debug information %s, DXIL validation %s " + "(madeira.cfg msc-ignore-debug-info, msc-validation)\n", + nodebug ? "ignored" : "kept", novalidate ? "off" : "on"); + cached = (int)((nodebug ? MAD_IR_OPT_NODEBUG : 0) | (novalidate ? MAD_IR_OPT_NOVALIDATE : 0)); + } + return (uint32_t)cached; +} + extern "C" int madeira_ir_convert_impl(struct madeira_ir_convert_args *a) { pthread_once(&g_ir_once, ir_load_once); if (!a) return MADEIRA_IR_UNSUPPORTED; @@ -1779,7 +1809,7 @@ static uint32_t mad_ir_compat_flags(void) { env.converter_ident = g_ir.ident; env.build_stamp = MAD_SC_BUILD; env.ags_rewrite = (uint32_t)mad_ags_enabled(); - env.compat_flags = mad_ir_compat_flags(); + env.compat_flags = mad_ir_compat_flags() | mad_ir_opts(); /* madeira-duo: the options join the key */ mad_dxc_key(a, &env, &dxc_key, &dxc_check); if (dxc_slot) hit = mad_dxc_slot_take(dxc_key, dxc_check, &hit_len); if (!hit && dxc_disk) { @@ -1926,6 +1956,13 @@ static uint32_t mad_ir_compat_flags(void) { * views every such texture as an array to match. The other flags: * mad_ir_compat_flags. */ g_ir.IRCompilerSetCompatibilityFlags(compiler, (IRCompatibilityFlags)mad_ir_compat_flags()); + { /* madeira-duo: mad_ir_opts */ + uint32_t opts = mad_ir_opts(); + if ((opts & MAD_IR_OPT_NODEBUG) && g_ir.IRCompilerIgnoreDebugInformation) + g_ir.IRCompilerIgnoreDebugInformation(compiler, true); + if ((opts & MAD_IR_OPT_NOVALIDATE) && g_ir.IRCompilerSetValidationFlags) + g_ir.IRCompilerSetValidationFlags(compiler, IRCompilerValidationFlagNone); + } a->ret_len2 = 0; a->ret_vs_output_size = 0; a->ret_gs_max_prims = 0; a->ret_gs_payload = 0; a->ret_gs_passthrough = 0; /* the tessellation reflection too: a conversion that does not fill it must not hand back the caller's bytes */ a->ret_hs_patches_per_tg = a->ret_hs_threads_per_patch = a->ret_hs_input_cps = a->ret_hs_output_cps = 0; From ae49dd73dde4c5ef1c1315c9177d9aa99d74dac6 Mon Sep 17 00:00:00 2001 From: Shitiz Garg Date: Sun, 8 Nov 2026 02:24:32 +1100 Subject: [PATCH 13/76] ntdll iOS: opt-in CPU-time-weighted sampling profiler ([prof], MADEIRA_PROF=1) [cpu-split] counts a sample whenever a thread's run state says RUNNING, which includes threads that are only runnable (a thread yielding in swtch_pri looks as busy as one computing), and it keeps only the top 64 JIT buckets per burst, about a quarter of the samples. That was not enough to find where a game's CPU time goes. With MADEIRA_PROF=1 a sampler thread reads every thread's CPU time each pass (THREAD_EXTENDED_INFO, no suspend) and samples only the threads whose CPU time moved; a sample's weight is the CPU time used since that thread's previous sample, so idle and runnable-but-waiting threads weigh nothing. MADEIRA_PROF_HZ sets the pass rate (default 100, 20-1000). Each record has the host pc, the guest rip for FEX threads, the class (FEX JIT code, ARM64EC image copy, native), the thread slot and whether the thread was running when sampled. Records go to madeira-prof-