From 82484ce45378300a671c11d891f76f5525367e13 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:12:25 +0100 Subject: [PATCH 01/15] startup: separate graphics translation preparation from draw state --- src/startup_stubs/d3d12_draw.inl | 176 +++++++++++++++++++------------ 1 file changed, 111 insertions(+), 65 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index f6e88d4e4f..1ca332cce1 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -158,7 +158,7 @@ const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& reso return nullptr; } -struct Translation { +struct TranslationState { struct Srv { int kind, source, a, b; UINT expected_stride{}; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture, 5 cube; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; struct Ud { int kind, a, b; }; @@ -175,20 +175,32 @@ struct Translation { x2w_startup::TranslatedSamplers samplers; x2w_startup::ExportWriteMasks write_masks; // manifest 'wmask': channels each export leaves unwritten (#1674) x2w_startup::D16ImageSrvs d16_srvs; // manifest 'd16srv': texture views that must match proven D16 formats (#2023) - ID3DBlob* vs = nullptr; - ID3DBlob* ps = nullptr; - ID3D12RootSignature* root = nullptr; + x2w_startup::ComPtr vs; + x2w_startup::ComPtr ps; + x2w_startup::ComPtr root; + std::string fixed_rectangle_ir; + bool fixed_rectangle_on_disk = false; + std::vector pso_recipes; // opt-in X2W_PSO_RECIPE_DIR records for this key +}; + +struct TranslationPreparation : TranslationState { + explicit TranslationPreparation(u64 key) : key(key) {} + + const u64 key; + LONG missing_delta = 0; + LONG recipe_mismatches = 0; +}; + +struct Translation : TranslationState { + explicit Translation(u64 key) : key(key) {} + + const u64 key; // also read by attribution without draw_lock after slot 86 creation std::optional independent_indirect_entry; std::optional indexed_indirect_entry; bool indexed_rect_geometry_attempted = false; - std::string fixed_rectangle_ir; - bool fixed_rectangle_on_disk = false; x2w_startup::ComPtr indexed_rect_geometry; int indirect_base_word = -1; x2w_startup::ComPtr indexed_signature; - std::unordered_map pipelines; // by target formats - std::vector pso_recipes; // opt-in X2W_PSO_RECIPE_DIR records for this key - u64 key = 0; LONG logged_draws = 0, logged_bindings = 0, logged_large = 0; // diagnostics budget per translation }; @@ -344,7 +356,7 @@ bool read_pso_recipe_text(const wchar_t* path, std::string& out, bool& too_large // Called once a translation is ready. A missing directory or file is not an error; the runtime then // follows the unchanged creation path. -void load_pso_recipes(Translation& tr) +void load_pso_recipes(TranslationPreparation& tr) { wchar_t path[MAX_PATH]; if (!pso_recipe_path(path, tr.key)) return; @@ -352,7 +364,7 @@ void load_pso_recipes(Translation& tr) bool too_large = false; if (!read_pso_recipe_text(path, text, too_large)) { if (too_large) { - InterlockedIncrement(&pso_recipe_mismatches); + ++tr.recipe_mismatches; static LONG logged; if (first_calls(logged, 16)) log("x2w-draw pso recipe file for %016llx is above the size limit; ignored", tr.key); } @@ -365,12 +377,8 @@ void load_pso_recipes(Translation& tr) ++rejected; return true; }), parsed.recipes.end()); - if (rejected) InterlockedAdd(&pso_recipe_mismatches, static_cast(rejected)); - if (!parsed.recipes.empty()) { - const std::size_t count = parsed.recipes.size(); - InterlockedAdd(&pso_recipes_loaded, static_cast(std::min(count, LONG_MAX))); - tr.pso_recipes = std::move(parsed.recipes); - } + tr.recipe_mismatches += static_cast(rejected); + tr.pso_recipes = std::move(parsed.recipes); if (rejected || !tr.pso_recipes.empty()) { log("x2w-draw pso recipes %016llx: %zu loaded, %u rejected%s%s", tr.key, tr.pso_recipes.size(), rejected, parsed.error.empty() ? "" : "; first error: ", parsed.error.c_str()); @@ -480,7 +488,8 @@ bool native_shaders_only() return enabled; } -void load_translation(Translation& tr, const std::string& rtv_request = {}, std::string manifest = {}) +void load_translation(TranslationPreparation& tr, ID3D12Device* device, + const std::string& rtv_request = {}, std::string manifest = {}) { tr.state = 2; if (manifest.empty() && native_shaders_only()) { @@ -492,7 +501,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: if (!cache_path(path, L"", tr.key, L".txt")) return; if (!provided && !read_text(path, manifest)) { if (!tr.manifest_retry.pending()) { - InterlockedIncrement(&translation_missing); + ++tr.missing_delta; static LONG missing; if (rtv_request.empty() && first_calls(missing, 12)) log("x2w-draw no translation for pipeline %016llx", tr.key); @@ -604,8 +613,8 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: } if (!provided && (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs)))) return; if (!provided && (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps)))) return; - const HRESULT hr = provided && x2w_local::env_on("X2W_TEST_NATIVE_GRAPHICS_ROOT_FAILURE") ? E_FAIL : - x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.size()), + const HRESULT hr = !device || (provided && x2w_local::env_on("X2W_TEST_NATIVE_GRAPHICS_ROOT_FAILURE")) ? E_FAIL : + x2w_startup::create_translated_root(device, static_cast(tr.uds.size()), static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size()), fixed_manifest); if (FAILED(hr)) { log("x2w-draw root signature for %016llx failed 0x%08lx", tr.key, static_cast(hr)); @@ -613,14 +622,13 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: } tr.state = 1; load_pso_recipes(tr); - if (previously_missing) InterlockedDecrement(&translation_missing); - InterlockedIncrement(&translation_ready); + if (previously_missing) --tr.missing_delta; log("x2w-draw pipeline %016llx translated: %zu entry values, %zu resources, %zu writable views, %zu static samplers, sampler_heap=%u", tr.key, tr.uds.size(), tr.srvs.size(), tr.uavs.size(), tr.samplers.statics.size(), tr.samplers.heap ? 1u : 0u); } #ifdef X2W_NATIVE_SHADERS -static bool try_native_graphics(Translation& tr, bool variant = false) +static bool try_native_graphics(TranslationPreparation& tr, ID3D12Device* device, bool variant = false) { wchar_t sdk[MAX_PATH], path[MAX_PATH]; const auto length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); @@ -643,28 +651,23 @@ static bool try_native_graphics(Translation& tr, bool variant = false) return blob; }; bool vs_hit, ps_hit; - auto vs = stage(pair.vertex.dxil_ir, L"vs_6_6", vs_hit); - auto ps = stage(pair.pixel.dxil_ir, L"ps_6_6", ps_hit); - Translation candidate; - candidate.key = tr.key; + TranslationPreparation candidate(tr.key); + candidate.vs = stage(pair.vertex.dxil_ir, L"vs_6_6", vs_hit); + candidate.ps = stage(pair.pixel.dxil_ir, L"ps_6_6", ps_hit); candidate.manifest_retry = tr.manifest_retry; candidate.native_graphics_attempted = true; if (!pair.input_layout.empty()) { try { candidate.fixed_rectangle_ir = x2w::native_rectangle_geometry(pair.vertex.outputs, pair.pixel.inputs); } catch (const x2w::UnsupportedComputeShader&) {} // Triangle lists and strips still use the original pair. } - candidate.vs = vs.Get(); - candidate.ps = ps.Get(); if (x2w_local::env_on("X2W_TEST_NATIVE_GRAPHICS_MANIFEST_FAILURE")) manifest->append("\nx2w-manifest 999\n"); - load_translation(candidate, request.rtv_request, std::move(*manifest)); - if (candidate.state != 1) { - if (candidate.root) candidate.root->Release(); + load_translation(candidate, device, request.rtv_request, std::move(*manifest)); + if (candidate.state != 1) throw std::runtime_error("native graphics manifest or root signature refused"); - } - candidate.vs = vs.Detach(); - candidate.ps = ps.Detach(); - tr = std::move(candidate); + tr.missing_delta += candidate.missing_delta; + tr.recipe_mismatches += candidate.recipe_mismatches; + static_cast(tr) = std::move(candidate); log("x2w-draw native graphics %016llx ready=%u cache(frontend,vs,ps)=%u,%u,%u", tr.key, tr.state == 1, frontend_hit, vs_hit, ps_hit); return true; @@ -676,6 +679,38 @@ static bool try_native_graphics(Translation& tr, bool variant = false) } #endif +void install_graphics_translation(Translation& entry, TranslationPreparation& prepared) +{ + if (prepared.missing_delta) InterlockedAdd(&translation_missing, prepared.missing_delta); + if (prepared.recipe_mismatches) InterlockedAdd(&pso_recipe_mismatches, prepared.recipe_mismatches); + if (prepared.state == 1) { + InterlockedAdd(&pso_recipes_loaded, static_cast(prepared.pso_recipes.size())); + InterlockedIncrement(&translation_ready); + static_cast(entry) = std::move(prepared); + } else { + entry.state = prepared.state; + entry.manifest_retry = prepared.manifest_retry; +#ifdef X2W_NATIVE_SHADERS + entry.native_graphics_attempted = prepared.native_graphics_attempted; + entry.native_refusal = std::move(prepared.native_refusal); +#endif + } +} + +template +void prepare_graphics_translation(Translation& entry, Prepare&& prepare) +{ + TranslationPreparation prepared(entry.key); + prepared.state = entry.state; + prepared.manifest_retry = entry.manifest_retry; +#ifdef X2W_NATIVE_SHADERS + prepared.native_graphics_attempted = entry.native_graphics_attempted; + prepared.native_refusal = entry.native_refusal; +#endif + prepare(prepared, the_device ? device_of(the_device) : nullptr); + install_graphics_translation(entry, prepared); +} + // draw_lock held. Both pipeline forms use the same request writer and shader cache. Translation* cached_translation(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes, const std::vector& root_blob, const std::string& layout = {}, @@ -703,15 +738,16 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* } auto& entry = translation_by_key()[key]; if (!entry) { - entry = new Translation; - entry->key = key; - // A legacy cache hit still needs source blobs for late RTV specialization. - if (publish_shader_request(key, L".b", b, b_bytes) && - publish_shader_request(key, L".root", root_blob.data(), root_blob.size()) && - (layout.empty() || publish_shader_request(key, L".ia", layout.data(), layout.size())) && - (pixel_entry.empty() || publish_shader_request(key, L".ps57in", pixel_entry.data(), pixel_entry.size()))) - publish_shader_request(key, L".a", a, a_bytes); - load_translation(*entry); + entry = new Translation(key); + prepare_graphics_translation(*entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { + // A legacy cache hit still needs source blobs for late RTV specialization. + if (publish_shader_request(key, L".b", b, b_bytes) && + publish_shader_request(key, L".root", root_blob.data(), root_blob.size()) && + (layout.empty() || publish_shader_request(key, L".ia", layout.data(), layout.size())) && + (pixel_entry.empty() || publish_shader_request(key, L".ps57in", pixel_entry.data(), pixel_entry.size()))) + publish_shader_request(key, L".a", a, a_bytes); + load_translation(prepared, device); + }); } return entry; } @@ -1294,14 +1330,22 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) { if (!base) return nullptr; if (std::none_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant)) { - if (base->manifest_retry.due(GetTickCount64())) - load_translation(*base); + const bool retry = base->manifest_retry.due(GetTickCount64()); + bool needs_native = false; #ifdef X2W_NATIVE_SHADERS - if ((base->manifest_retry.pending() || native_shaders_only()) && !base->native_graphics_attempted) { - base->native_graphics_attempted = true; - try_native_graphics(*base); - } + needs_native = (base->manifest_retry.pending() || native_shaders_only()) && !base->native_graphics_attempted; +#endif + if (retry || needs_native) { + prepare_graphics_translation(*base, [retry](TranslationPreparation& prepared, ID3D12Device* device) { + if (retry) load_translation(prepared, device); +#ifdef X2W_NATIVE_SHADERS + if ((prepared.manifest_retry.pending() || native_shaders_only()) && !prepared.native_graphics_attempted) { + prepared.native_graphics_attempted = true; + try_native_graphics(prepared, device); + } #endif + }); + } return base; } std::string request = "rtv1 " + std::to_string(base->key); @@ -1310,19 +1354,21 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) const u64 key = fnv_bytes(request.data(), request.size()); auto& entry = translation_by_key()[key]; if (!entry) { - entry = new Translation; - entry->key = key; - load_translation(*entry, request); - if (entry->state != 1) { - const bool published = publish_shader_request(key, L".rtv", request.data(), request.size()); + entry = new Translation(key); + prepare_graphics_translation(*entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { + load_translation(prepared, device, request); + if (prepared.state == 1) return; + [[maybe_unused]] const bool published = publish_shader_request(key, L".rtv", request.data(), request.size()); #ifdef X2W_NATIVE_SHADERS - if (published && (entry->manifest_retry.pending() || native_shaders_only()) && - try_native_graphics(*entry, true)) return entry; + if (published && (prepared.manifest_retry.pending() || native_shaders_only()) && + try_native_graphics(prepared, device, true)) return; #endif log("x2w-draw no RTV translation for %016llx (%s)", key, request.c_str()); - } + }); } else if (entry->manifest_retry.due(GetTickCount64())) { - load_translation(*entry, request); + prepare_graphics_translation(*entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { + load_translation(prepared, device, request); + }); } return entry; } @@ -1411,7 +1457,7 @@ bool effective_blend_state(const BoundPipeline& bound, const Translation& tr, UI bool prepare_translated_pso_desc(Translation& tr, bool indexed_rect, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { - desc.pRootSignature = tr.root; + desc.pRootSignature = tr.root.Get(); desc.InputLayout = {tr.fixed_stream.data(), static_cast(tr.fixed_stream.size())}; desc.VS = {tr.vs->GetBufferPointer(), tr.vs->GetBufferSize()}; desc.PS = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()}; @@ -1421,7 +1467,7 @@ bool prepare_translated_pso_desc(Translation& tr, bool indexed_rect, D3D12_GRAPH x2w_startup::ComPtr errors; HRESULT hr = E_NOTIMPL; if (tr.fixed_stream.empty()) - hr = x2w_startup::compile_indexed_rect_geometry(tr.vs, tr.ps, &tr.indexed_rect_geometry, &errors); + hr = x2w_startup::compile_indexed_rect_geometry(tr.vs.Get(), tr.ps.Get(), &tr.indexed_rect_geometry, &errors); else if (tr.fixed_rectangle_on_disk) { wchar_t path[MAX_PATH]; if (cache_path(path, L"", tr.key, L".gs.cso")) @@ -3198,7 +3244,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI tr->indirect_base_word = static_cast(i); } } - entry = found_base && indirect_shader_entry(tr->vs, *tr, indexed) && indirect_shader_entry(tr->ps, *tr, indexed) && + entry = found_base && indirect_shader_entry(tr->vs.Get(), *tr, indexed) && indirect_shader_entry(tr->ps.Get(), *tr, indexed) && std::all_of(tr->srvs.begin(), tr->srvs.end(), [indexed](const Translation::Srv& srv) { return srv.source == 0 || (indexed && srv.kind == 0 && srv.source == 1 && srv.a == 0); }); @@ -3713,7 +3759,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass_dsv_format(*bound, pass) != DXGI_FORMAT_UNKNOWN && bound->stencil_ref != pass.stencil_reference; if (scoped_stencil_ref) list->OMSetStencilRef(bound->stencil_ref); - list->SetGraphicsRootSignature(tr->root); + list->SetGraphicsRootSignature(tr->root.Get()); ID3D12DescriptorHeap* samplers = tr->samplers.heap ? pass.sampler_heap.Get() : nullptr; if (!pass.heap_set || pass.bound_sampler_heap != samplers) { x2w_startup::bind_translated_heaps(list, draw_heap, samplers); From e6586aeb0a2c0cf6bee6f51fbde05f2176680ec4 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:17:24 +0100 Subject: [PATCH 02/15] startup: prepare graphics translations outside the draw lock --- src/startup_stubs/d3d12_draw.inl | 348 +++++++++++++++++++------- src/startup_stubs/d3d12_xs_device.cpp | 6 +- 2 files changed, 256 insertions(+), 98 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 1ca332cce1..e03f91d336 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -195,6 +195,7 @@ struct Translation : TranslationState { explicit Translation(u64 key) : key(key) {} const u64 key; // also read by attribution without draw_lock after slot 86 creation + bool preparing = false; std::optional independent_indirect_entry; std::optional indexed_indirect_entry; bool indexed_rect_geometry_attempted = false; @@ -207,6 +208,7 @@ struct Translation : TranslationState { // Per title pipeline: its translation and the blend state found in its state block (if any). struct BoundPipeline { Translation* translation = nullptr; + bool resolving = false; const std::vector* guest_root = nullptr; bool has_blend = false; D3D12_BLEND_DESC blend{}; @@ -247,13 +249,71 @@ bool find_blend(const std::vector& block, D3D12_BLEND_DESC* out, } SRWLOCK draw_lock = SRWLOCK_INIT; -std::unordered_map& translation_by_pipeline() { static std::unordered_map m; return m; } -std::unordered_map& translation_by_key() { static std::unordered_map m; return m; } +CONDITION_VARIABLE graphics_translation_changed = CONDITION_VARIABLE_INIT; +// Entries have stable addresses and are retained for the lifetime of the graphics cache. +std::unordered_map& translation_by_pipeline() { static std::unordered_map m; return m; } +std::unordered_map& translation_by_key() +{ + // As before, keep successful shader/root objects alive for the whole process. + static auto* entries = new std::unordered_map; + return *entries; +} LONG translated_draws, untranslated_draws, translation_ready, translation_missing, null_bindings; LONG formatted_draws_refused; // draws whose formatted buffer load had no resolved descriptor word 3 (also untranslated) LONG null_by_cause[x2w_local::null_cause_count]; // null_bindings split by cause; the parts add up to it LONG pso_recipes_loaded, pso_recipes_precreated, pso_recipe_mismatches, pso_recipe_fallbacks; +class GraphicsReservation { +public: + explicit GraphicsReservation(bool& pending) : pending_(pending) { pending_ = true; } + ~GraphicsReservation() + { + pending_ = false; + WakeAllConditionVariable(&graphics_translation_changed); + } + GraphicsReservation(const GraphicsReservation&) = delete; + GraphicsReservation& operator=(const GraphicsReservation&) = delete; + +private: + bool& pending_; +}; + +class GraphicsLock { +public: + GraphicsLock() { AcquireSRWLockExclusive(&draw_lock); } + ~GraphicsLock() { ReleaseSRWLockExclusive(&draw_lock); } + GraphicsLock(const GraphicsLock&) = delete; + GraphicsLock& operator=(const GraphicsLock&) = delete; +}; + +// The caller holds draw_lock exclusively and gets it back on every exit. +class GraphicsUnlock { +public: + GraphicsUnlock() { ReleaseSRWLockExclusive(&draw_lock); } + ~GraphicsUnlock() { if (!locked_) AcquireSRWLockExclusive(&draw_lock); } + GraphicsUnlock(const GraphicsUnlock&) = delete; + GraphicsUnlock& operator=(const GraphicsUnlock&) = delete; + + void reacquire() + { + AcquireSRWLockExclusive(&draw_lock); + locked_ = true; + } + void release() + { + locked_ = false; + ReleaseSRWLockExclusive(&draw_lock); + } + +private: + bool locked_ = false; +}; + +void wait_for_graphics_translation() +{ + SleepConditionVariableSRW(&graphics_translation_changed, &draw_lock, INFINITE, 0); +} + void count_null_binding(x2w_local::NullCause cause) { if (cause == x2w_local::NullCause::none) return; @@ -273,8 +333,7 @@ bool cache_path(wchar_t* out, const wchar_t* prefix, u64 key, const wchar_t* ext wchar_t dir[MAX_PATH]; const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); if (!n || n >= MAX_PATH) return false; - swprintf(out, MAX_PATH, L"%s\\%s%016llx%s", dir, prefix, key, extension); - return true; + return swprintf(out, MAX_PATH, L"%s\\%s%016llx%s", dir, prefix, key, extension) > 0; } // X2W_SHADER_CACHE's top-level names, listed at the first cache_lookup (src/startup_stubs/cache_index.h). @@ -309,7 +368,12 @@ bool read_text(const wchar_t* path, std::string& out) if (file == INVALID_HANDLE_VALUE) return false; char buffer[8192]; DWORD got = 0; - while (ReadFile(file, buffer, sizeof(buffer), &got, nullptr) && got) out.append(buffer, got); + try { + while (ReadFile(file, buffer, sizeof(buffer), &got, nullptr) && got) out.append(buffer, got); + } catch (...) { + CloseHandle(file); + throw; + } CloseHandle(file); return true; } @@ -341,7 +405,12 @@ bool read_pso_recipe_text(const wchar_t* path, std::string& out, bool& too_large CloseHandle(file); return false; } - out.resize(static_cast(size.QuadPart)); + try { + out.resize(static_cast(size.QuadPart)); + } catch (...) { + CloseHandle(file); + throw; + } std::size_t done = 0; while (done < out.size()) { DWORD got = 0; @@ -439,10 +508,8 @@ constexpr char mesh57_revision[] = "x2w-startup-mesh-57-3"; // Once per process, before its first request: \revision.txt names this runtime's revisions, so // that the launchers (tools/startup/shader_cache_revision.py) can warn before they start a translator of another // revision. A file that already says the same is left as it is. -void write_cache_revision() +void write_cache_revision_once() { - static LONG written; - if (InterlockedCompareExchange(&written, 1, 0)) return; wchar_t dir[MAX_PATH], path[MAX_PATH], temporary[MAX_PATH]; const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); if (!n || n >= MAX_PATH) return; @@ -463,13 +530,16 @@ void write_cache_revision() // Publish each input atomically. The callers write the request's ready marker last. bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std::size_t bytes) { - wchar_t path[MAX_PATH], temporary[MAX_PATH], suffix[32]; - write_cache_revision(); + static std::once_flag revision; + std::call_once(revision, write_cache_revision_once); + wchar_t path[MAX_PATH], temporary[MAX_PATH], suffix[48]; if (!cache_path(path, L"req_", key, ext)) return false; if (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return true; - swprintf(suffix, std::size(suffix), L"%s.%lu.tmp", ext, GetCurrentProcessId()); + static LONG64 serial; + swprintf(suffix, std::size(suffix), L"%s.%lx.%llx.tmp", ext, GetCurrentProcessId(), + static_cast(InterlockedIncrement64(&serial))); if (!cache_path(temporary, L"req_", key, suffix)) return false; - HANDLE file = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE file = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) return false; DWORD written = 0; const bool complete = WriteFile(file, data, static_cast(bytes), &written, nullptr) && written == bytes; @@ -700,46 +770,75 @@ void install_graphics_translation(Translation& entry, TranslationPreparation& pr template void prepare_graphics_translation(Translation& entry, Prepare&& prepare) { - TranslationPreparation prepared(entry.key); - prepared.state = entry.state; - prepared.manifest_retry = entry.manifest_retry; + GraphicsReservation reservation(entry.preparing); + try { + Wrapper* const wrapper = the_device; + x2w_startup::ComPtr device(wrapper ? device_of(wrapper) : nullptr); + const auto retry = entry.manifest_retry; + const int state = entry.state; #ifdef X2W_NATIVE_SHADERS - prepared.native_graphics_attempted = entry.native_graphics_attempted; - prepared.native_refusal = entry.native_refusal; + const bool native_attempted = entry.native_graphics_attempted; + auto native_refusal = entry.native_refusal; #endif - prepare(prepared, the_device ? device_of(the_device) : nullptr); - install_graphics_translation(entry, prepared); + GraphicsUnlock unlocked; + TranslationPreparation prepared(entry.key); + prepared.state = state; + prepared.manifest_retry = retry; +#ifdef X2W_NATIVE_SHADERS + prepared.native_graphics_attempted = native_attempted; + prepared.native_refusal = std::move(native_refusal); +#endif + prepare(prepared, device.Get()); + if (prepared.state != 1) { + prepared.vs.Reset(); + prepared.ps.Reset(); + prepared.root.Reset(); + } + unlocked.reacquire(); + // The reservation is exclusive through publication. A result prepared on a + // superseded device must not enter the cache. + if (the_device == wrapper) install_graphics_translation(entry, prepared); + else unlocked.release(); + } catch (...) { + // The unlock guard reacquired draw_lock before we clear the reservation. + // A retry leaves its last committed state available. + GraphicsUnlock unlocked; + log("x2w-draw graphics preparation for %016llx interrupted", entry.key); + } + if (!entry.state) entry.state = 2; } // draw_lock held. Both pipeline forms use the same request writer and shader cache. Translation* cached_translation(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes, const std::vector& root_blob, const std::string& layout = {}, - const std::string& slot57_entry = {}) + const std::string& slot57_entry = {}, Translation** binding = nullptr) { - // Keep pre-fix desktop bytecode and manifests out of this ABI's cache (shader_cache::revision). - const u64 seed = fnv_bytes(shader_cache::revision, sizeof(shader_cache::revision) - 1); - u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); - // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. - if (!layout.empty()) key = fnv_bytes(layout.data(), layout.size(), key); + u64 key; std::string pixel_entry = slot57_entry; - if (!pixel_entry.empty()) { - // #3385: with X2W_NATIVE_SHADERS set, the fixed pixel entry used to join every slot 57 key, so a - // translation already cached under the plain key never hit and the Python fallback refused the - // suffixed request (it never read .ps57in). Reuse the cached plain-key translation when one is - // already published: the pipeline already ran with it, and the native path can still try the plain - // request. Only a cold pipeline keeps the entry in its key. In native-shaders-only mode .txt - // manifests are ignored, so a leftover Python manifest must not strip the entry from the request - // the native path receives: the reuse is skipped there and the entry stays in the key. - wchar_t base_path[MAX_PATH]; - const bool base_cached = !native_shaders_only() && cache_path(base_path, L"", key, L".txt") && - GetFileAttributesW(base_path) != INVALID_FILE_ATTRIBUTES; - if (base_cached) pixel_entry.clear(); - else key = fnv_bytes(pixel_entry.data(), pixel_entry.size(), key); - } - auto& entry = translation_by_key()[key]; - if (!entry) { - entry = new Translation(key); - prepare_graphics_translation(*entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { + { + GraphicsUnlock unlocked; + const u64 seed = fnv_bytes(shader_cache::revision, sizeof(shader_cache::revision) - 1); + key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); + // A stream's input layout feeds the vertex fetch, so it is part of the key. + if (!layout.empty()) key = fnv_bytes(layout.data(), layout.size(), key); + if (!pixel_entry.empty()) { + // #3385: retain an already published plain key in legacy mode. Native-only + // ignores the .txt and always keeps the fixed entry in the request. + wchar_t base_path[MAX_PATH]; + const bool base_cached = !native_shaders_only() && cache_path(base_path, L"", key, L".txt") && + GetFileAttributesW(base_path) != INVALID_FILE_ATTRIBUTES; + if (base_cached) pixel_entry.clear(); + else key = fnv_bytes(pixel_entry.data(), pixel_entry.size(), key); + } + } + const auto [found, inserted] = translation_by_key().try_emplace(key, key); + auto& entry = found->second; + if (binding) { + *binding = &entry; + WakeAllConditionVariable(&graphics_translation_changed); + } + if (inserted) { + prepare_graphics_translation(entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { // A legacy cache hit still needs source blobs for late RTV specialization. if (publish_shader_request(key, L".b", b, b_bytes) && publish_shader_request(key, L".root", root_blob.data(), root_blob.size()) && @@ -748,8 +847,12 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* publish_shader_request(key, L".a", a, a_bytes); load_translation(prepared, device); }); + } else { + // The base request only needs the initial publication, not a later attempt + // for ordinary render targets. Variant keys can proceed during that attempt. + while (!entry.state && entry.preparing) wait_for_graphics_translation(); } - return entry; + return &entry; } LONG compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words; @@ -778,6 +881,29 @@ bool copy_title_bytes(void* to, const void* from, std::size_t bytes) noexcept return x2w_local::guarded_memcpy(to, from, bytes, true); } +std::vector snapshot_graphics_stage(const void* data, std::size_t bytes) +{ + if (!bytes || bytes > (1u << 20) || !x2w_local::readable(data, bytes)) return {}; + std::vector stage(bytes); + if (!copy_title_bytes(stage.data(), data, bytes)) stage.clear(); + return stage; +} + +std::vector snapshot_graphics_root(const Wrapper* root) +{ + std::vector blob; + AcquireSRWLockShared(¬e_lock); + try { + const auto found = root_blobs().find(root); + if (found != root_blobs().end()) blob = found->second; + } catch (...) { + ReleaseSRWLockShared(¬e_lock); + throw; + } + ReleaseSRWLockShared(¬e_lock); + return blob; +} + // Aligned qwords of a published blob that name committed memory of this process (one VirtualQuery each, so // no fault is taken): such a value makes the key run-dependent. They are counted and published, not refused // (shortcut: hash-like values can name memory by chance; refuse once a decoder names the pointer fields). @@ -1077,8 +1203,7 @@ Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3 std::memcpy(&shader, stream + at + 8, sizeof(shader)); if (shader.pShaderBytecode || shader.BytecodeLength) { if (type > D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS || shader.BytecodeLength < 32 || - shader.BytecodeLength > (1u << 20) || !x2w_local::readable(shader.pShaderBytecode, shader.BytecodeLength) || - std::memcmp(shader.pShaderBytecode, "DXBC", 4)) return nullptr; + shader.BytecodeLength > (1u << 20)) return nullptr; stages[type - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS] = shader; } } else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND) { @@ -1122,27 +1247,23 @@ Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3 at += size; } if (!root || !stages[0].pShaderBytecode || !stages[1].pShaderBytecode) return nullptr; - std::vector root_blob; - AcquireSRWLockShared(¬e_lock); - const auto found = root_blobs().find(root); - if (found != root_blobs().end()) root_blob = found->second; - ReleaseSRWLockShared(¬e_lock); - if (root_blob.empty()) return nullptr; - AcquireSRWLockExclusive(&draw_lock); - auto* result = cached_translation(stages[0].pShaderBytecode, stages[0].BytecodeLength, - stages[1].pShaderBytecode, stages[1].BytecodeLength, root_blob, layout); - ReleaseSRWLockExclusive(&draw_lock); - return result; + try { + const auto side_a = snapshot_graphics_stage(stages[0].pShaderBytecode, stages[0].BytecodeLength); + const auto side_b = snapshot_graphics_stage(stages[1].pShaderBytecode, stages[1].BytecodeLength); + if (side_a.empty() || side_b.empty() || + std::memcmp(side_a.data(), "DXBC", 4) || std::memcmp(side_b.data(), "DXBC", 4)) return nullptr; + const auto root_blob = snapshot_graphics_root(root); + if (root_blob.empty()) return nullptr; + GraphicsLock lock; + return cached_translation(side_a.data(), side_a.size(), side_b.data(), side_b.size(), root_blob, layout); + } catch (...) { + return nullptr; + } } // draw_lock held. -BoundPipeline* translation_for(Wrapper* pipeline) +void resolve_graphics_binding(Wrapper* pipeline, BoundPipeline* bound) { - auto& by_pipeline = translation_by_pipeline(); - const auto known = by_pipeline.find(pipeline); - if (known != by_pipeline.end()) return known->second; - auto* bound = new BoundPipeline; - Translation*& result = bound->translation; const PipelineInfo* info = pipeline_info(pipeline); const PipelineInfo* own = info; { @@ -1192,7 +1313,7 @@ BoundPipeline* translation_for(Wrapper* pipeline) } } if (info && info->path == 86) { - result = info->stream_translation; + bound->translation = info->stream_translation; if (info->has_stream_depth_stencil) { bound->depth_stencil = info->stream_depth_stencil; bound->has_depth_stencil = true; @@ -1231,34 +1352,45 @@ BoundPipeline* translation_for(Wrapper* pipeline) std::memcpy(words, info->desc.data(), sizeof(words)); Wrapper* root = as_wrapper(reinterpret_cast(words[0])); bound->guest_root = root ? root_info(root) : nullptr; - std::vector root_blob; - if (root) { - AcquireSRWLockShared(¬e_lock); - const auto found = root_blobs().find(root); - if (found != root_blobs().end()) root_blob = found->second; - ReleaseSRWLockShared(¬e_lock); - } - const auto* a = reinterpret_cast(words[5]); - const auto* b = reinterpret_cast(words[9]); - const std::size_t a_bytes = static_cast(words[6]), b_bytes = static_cast(words[10]); - if (!root_blob.empty() && a_bytes && b_bytes && a_bytes <= (1u << 20) && b_bytes <= (1u << 20) && x2w_local::readable(a, a_bytes) && - x2w_local::readable(b, b_bytes)) { + const auto root_blob = root ? snapshot_graphics_root(root) : std::vector{}; + if (!root_blob.empty()) { + const auto a = snapshot_graphics_stage(reinterpret_cast(words[5]), words[6]); + if (a.empty()) return; + const auto b = snapshot_graphics_stage(reinterpret_cast(words[9]), words[10]); + if (b.empty()) return; std::string slot57_entry; #ifdef X2W_NATIVE_SHADERS if (GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0) && - info->state_a.size() >= 0x60 && a_bytes >= 4 && b_bytes >= 4 && - std::memcmp(a, "DXBC", 4) && std::memcmp(b, "DXBC", 4)) { + info->state_a.size() >= 0x60 && a.size() >= 4 && b.size() >= 4 && + std::memcmp(a.data(), "DXBC", 4) && std::memcmp(b.data(), "DXBC", 4)) { // The fixed graphics state has SPI_PS_INPUT_ADDR and SPI_PS_IN_CONTROL // in adjacent dwords. Capture both intact, including control flags. slot57_entry = "PSI1"; slot57_entry.append(reinterpret_cast(info->state_a.data() + 0x58), 8); } #endif - result = cached_translation(a, a_bytes, b, b_bytes, root_blob, {}, slot57_entry); + cached_translation(a.data(), a.size(), b.data(), b.size(), root_blob, {}, slot57_entry, &bound->translation); } } - by_pipeline[pipeline] = bound; - return bound; +} + +// draw_lock held. One owner decodes each wrapper and publishes its binding. +BoundPipeline* translation_for(Wrapper* pipeline) +{ + const auto [found, inserted] = translation_by_pipeline().try_emplace(pipeline); + auto& bound = found->second; + if (inserted) { + GraphicsReservation reservation(bound.resolving); + try { + resolve_graphics_binding(pipeline, &bound); + } catch (...) { + // Publish an unavailable binding and release wrapper waiters. + bound.translation = nullptr; + } + } else { + while (bound.resolving) wait_for_graphics_translation(); + } + return &bound; } // The request translation_for writes on a direct draw, for a pipeline that slot 61 refuses. Only direct draws poll @@ -1266,10 +1398,16 @@ BoundPipeline* translation_for(Wrapper* pipeline) LONG indirect_first_lookups; void request_translation(Wrapper* pipeline) { - AcquireSRWLockExclusive(&draw_lock); - const bool known = translation_by_pipeline().count(pipeline) != 0; - translation_for(pipeline); - ReleaseSRWLockExclusive(&draw_lock); + bool known; + { + GraphicsLock lock; + known = translation_by_pipeline().count(pipeline) != 0; + try { + translation_for(pipeline); + } catch (...) { + return; + } + } if (!known) InterlockedIncrement(&indirect_first_lookups); static LONG lookups; if (first_calls(lookups, 16)) @@ -1292,8 +1430,13 @@ u64 known_pipeline_key(Wrapper* pipeline) AcquireSRWLockShared(&draw_lock); const auto& by_pipeline = translation_by_pipeline(); const auto known = by_pipeline.find(pipeline); - key = known != by_pipeline.end() && known->second && known->second->translation - ? known->second->translation->key : 0; + if (known != by_pipeline.end()) { + // A rehash while waiting cannot invalidate the node's address. + const auto& binding = known->second; + while (binding.resolving && !binding.translation) + SleepConditionVariableSRW(&graphics_translation_changed, &draw_lock, INFINITE, CONDITION_VARIABLE_LOCKMODE_SHARED); + if (binding.translation) key = binding.translation->key; + } ReleaseSRWLockShared(&draw_lock); } if (!key) { @@ -1330,6 +1473,8 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) { if (!base) return nullptr; if (std::none_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant)) { + while (base->preparing) wait_for_graphics_translation(); + if (base->state == 1) return base; const bool retry = base->manifest_retry.due(GetTickCount64()); bool needs_native = false; #ifdef X2W_NATIVE_SHADERS @@ -1352,10 +1497,11 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) for (UINT i = 0; i < pass.target_count; ++i) request += " " + std::to_string(static_cast(pass.target_formats[i])); const u64 key = fnv_bytes(request.data(), request.size()); - auto& entry = translation_by_key()[key]; - if (!entry) { - entry = new Translation(key); - prepare_graphics_translation(*entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { + const auto [found, inserted] = translation_by_key().try_emplace(key, key); + auto& entry = found->second; + while (entry.preparing) wait_for_graphics_translation(); + if (inserted) { + prepare_graphics_translation(entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { load_translation(prepared, device, request); if (prepared.state == 1) return; [[maybe_unused]] const bool published = publish_shader_request(key, L".rtv", request.data(), request.size()); @@ -1365,12 +1511,12 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) #endif log("x2w-draw no RTV translation for %016llx (%s)", key, request.c_str()); }); - } else if (entry->manifest_retry.due(GetTickCount64())) { - prepare_graphics_translation(*entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { + } else if (entry.manifest_retry.due(GetTickCount64())) { + prepare_graphics_translation(entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { load_translation(prepared, device, request); }); } - return entry; + return &entry; } // The depth format a translated draw uses: the pass's own view, else the one the pipeline was created with. @@ -3166,8 +3312,16 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return false; } AcquireSRWLockExclusive(&draw_lock); - BoundPipeline* bound = translation_for(pass.pipeline); - Translation* tr = bound ? translation_for_targets(bound->translation, pass) : nullptr; + BoundPipeline* bound = nullptr; + Translation* tr = nullptr; + try { + bound = translation_for(pass.pipeline); + tr = bound ? translation_for_targets(bound->translation, pass) : nullptr; + } catch (...) { + note_draw_refusal(0, "graphics translation lookup interrupted"); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } if (!tr) note_draw_refusal(0, bound ? "no translation for the bound targets" : "pipeline description not decoded"); if (used_fallback && tr && tr->manifest_retry.pending() && draw_missing_translation(device_of(self->own().list_device), list, pass, count, instances, start, start_instance)) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index cc1f9abc54..34d744ab40 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -8348,7 +8348,11 @@ void x2w_startup::attach_device(ID3D12Device* device, void** wrapped) device->Release(); return; } - the_device = candidate; + { + // Translation publication compares its pinned device under draw_lock. + GraphicsLock lock; + the_device = candidate; + } removal_device = device; } From ab1c7077a767deb5cf847fbef3a462f9a5974380 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:26:03 +0100 Subject: [PATCH 03/15] startup: exercise graphics publication concurrency and precedence --- src/startup_stubs/d3d12_draw.inl | 55 ++- src/startup_stubs/d3d12_xs_device.cpp | 2 + .../startup_graphics_published_load.cmake | 16 + .../startup_graphics_published_load_check.py | 159 ++++++++ tests/startup_indirect_draw_indexed.cpp | 340 +++++++++++++++++- tests/startup_stream_consumer.cpp | 2 +- 6 files changed, 555 insertions(+), 19 deletions(-) create mode 100644 tests/cmake/startup_graphics_published_load.cmake create mode 100644 tests/startup_graphics_published_load_check.py diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index e03f91d336..42960e7e16 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -314,6 +314,50 @@ void wait_for_graphics_translation() SleepConditionVariableSRW(&graphics_translation_changed, &draw_lock, INFINITE, 0); } +HANDLE graphics_fixture_event(const wchar_t* variable, u64 key, DWORD access) +{ + const DWORD saved = GetLastError(); + const HANDLE event = [&]() -> HANDLE { + wchar_t name[MAX_PATH], selected[17]; + const DWORD length = GetEnvironmentVariableW(variable, name, MAX_PATH); + if (!length || length >= MAX_PATH) return nullptr; + const DWORD filter = GetEnvironmentVariableW(L"X2W_TEST_GRAPHICS_KEY", selected, std::size(selected)); + if (filter) { + wchar_t expected[17]; + swprintf(expected, std::size(expected), L"%016llx", key); + if (filter != 16 || std::wcscmp(selected, expected)) return nullptr; + } + return OpenEventW(access, FALSE, name); + }(); + SetLastError(saved); + return event; +} + +void signal_graphics_fixture(const wchar_t* variable, u64 key) +{ + if (HANDLE event = graphics_fixture_event(variable, key, EVENT_MODIFY_STATE)) { + SetEvent(event); + CloseHandle(event); + } +} + +void wait_for_graphics_key(u64 key) +{ + signal_graphics_fixture(L"X2W_TEST_PUBLISHED_GRAPHICS_WAITER", key); + wait_for_graphics_translation(); +} + +bool pause_graphics_fixture(const wchar_t* gate, const wchar_t* entered, u64 key) +{ + HANDLE event = graphics_fixture_event(gate, key, SYNCHRONIZE); + if (!event) return false; + signal_graphics_fixture(entered, key); + const DWORD result = WaitForSingleObject(event, 30000); + CloseHandle(event); + if (result != WAIT_OBJECT_0) throw std::runtime_error("graphics fixture gate timed out"); + return true; +} + void count_null_binding(x2w_local::NullCause cause) { if (cause == x2w_local::NullCause::none) return; @@ -569,6 +613,10 @@ void load_translation(TranslationPreparation& tr, ID3D12Device* device, wchar_t path[MAX_PATH]; const bool provided = !manifest.empty(); if (!cache_path(path, L"", tr.key, L".txt")) return; + if (!provided && pause_graphics_fixture(L"X2W_TEST_PUBLISHED_GRAPHICS_GATE", + L"X2W_TEST_PUBLISHED_GRAPHICS_ENTERED", tr.key) && + x2w_local::env_on("X2W_TEST_PUBLISHED_GRAPHICS_EXCEPTION")) + throw std::runtime_error("published graphics fixture exception"); if (!provided && !read_text(path, manifest)) { if (!tr.manifest_retry.pending()) { ++tr.missing_delta; @@ -704,6 +752,7 @@ static bool try_native_graphics(TranslationPreparation& tr, ID3D12Device* device const auto length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); if (!length || length >= MAX_PATH || !cache_path(path, L"req_", tr.key, variant ? L".rtv" : L".a")) return false; try { + pause_graphics_fixture(L"X2W_TEST_NATIVE_GRAPHICS_GATE", L"X2W_TEST_NATIVE_GRAPHICS_ENTERED", tr.key); const auto request = x2w::read_graphics_request(path); const auto cache = std::filesystem::path(path).parent_path(); bool frontend_hit = false; @@ -850,7 +899,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* } else { // The base request only needs the initial publication, not a later attempt // for ordinary render targets. Variant keys can proceed during that attempt. - while (!entry.state && entry.preparing) wait_for_graphics_translation(); + while (!entry.state && entry.preparing) wait_for_graphics_key(entry.key); } return &entry; } @@ -1473,7 +1522,7 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) { if (!base) return nullptr; if (std::none_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant)) { - while (base->preparing) wait_for_graphics_translation(); + while (base->preparing) wait_for_graphics_key(base->key); if (base->state == 1) return base; const bool retry = base->manifest_retry.due(GetTickCount64()); bool needs_native = false; @@ -1499,7 +1548,7 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) const u64 key = fnv_bytes(request.data(), request.size()); const auto [found, inserted] = translation_by_key().try_emplace(key, key); auto& entry = found->second; - while (entry.preparing) wait_for_graphics_translation(); + while (entry.preparing) wait_for_graphics_key(entry.key); if (inserted) { prepare_graphics_translation(entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { load_translation(prepared, device, request); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 34d744ab40..bc39e802a3 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -110,9 +110,11 @@ #include #include #include +#include #include #include #include +#include #include #include #include diff --git a/tests/cmake/startup_graphics_published_load.cmake b/tests/cmake/startup_graphics_published_load.cmake new file mode 100644 index 0000000000..74aa792580 --- /dev/null +++ b/tests/cmake/startup_graphics_published_load.cmake @@ -0,0 +1,16 @@ +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS unlock concurrent) + add_test(NAME startup_graphics_published_load_${mode}_${backend} + COMMAND startup_indirect_draw_indexed ${backend} graphics-publication-${mode}) + set_tests_properties(startup_graphics_published_load_${mode}_${backend} + PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() + if(TARGET compile_dxil AND TARGET startup_stream_consumer AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME startup_graphics_published_load_precedence_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_graphics_published_load_check.py" + "$" "${DXC_BIN_DIR}" ${backend} "$") + set_tests_properties(startup_graphics_published_load_precedence_${backend} + PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endif() +endforeach() diff --git a/tests/startup_graphics_published_load_check.py b/tests/startup_graphics_published_load_check.py new file mode 100644 index 0000000000..00a63fdc41 --- /dev/null +++ b/tests/startup_graphics_published_load_check.py @@ -0,0 +1,159 @@ +"""Gate the slot 86 loader and check graphics source order and retry behavior.""" +import ctypes +from ctypes import wintypes +from contextlib import ExitStack, contextmanager +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import time +import uuid + +from native_rtv_variant_check import G +from startup_native_graphics_draw_check import patched_pixel, triangle, vop1 + + +kernel = ctypes.WinDLL("kernel32", use_last_error=True) +kernel.CreateEventW.argtypes = [wintypes.LPVOID, wintypes.BOOL, wintypes.BOOL, wintypes.LPCWSTR] +kernel.CreateEventW.restype = wintypes.HANDLE +kernel.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD] +kernel.WaitForSingleObject.restype = wintypes.DWORD +kernel.SetEvent.argtypes = [wintypes.HANDLE] +kernel.SetEvent.restype = wintypes.BOOL +kernel.CloseHandle.argtypes = [wintypes.HANDLE] +kernel.CloseHandle.restype = wintypes.BOOL + + +@contextmanager +def gate(stage, env): + prefix = f"Local\\X2WGraphicsPrecedence.{os.getpid()}.{uuid.uuid4().hex}" + with ExitStack() as stack: + events = [] + for suffix in ("GATE", "ENTERED"): + name = f"{prefix}.{suffix}" + event = kernel.CreateEventW(None, True, False, name) + if not event: + raise ctypes.WinError(ctypes.get_last_error()) + stack.callback(kernel.CloseHandle, event) + env[f"X2W_TEST_{stage}_GRAPHICS_{suffix}"] = name + events.append(event) + yield events + + +def run_draw(args, env, pixels, pause=None, forbid=None): + pixels.unlink(missing_ok=True) + with ExitStack() as stack: + env = env.copy() + # A forbidden phase also signals its entered event, but can exit immediately. + if forbid: + release, unexpected = stack.enter_context(gate(forbid, env)) + kernel.SetEvent(release) + if pause: + release, entered = stack.enter_context(gate(pause, env)) + with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr: + child = subprocess.Popen(args, env=env, stdout=stdout, stderr=stderr) + try: + observed = False + if pause: + deadline = time.monotonic() + 15 + while child.poll() is None and time.monotonic() < deadline: + if kernel.WaitForSingleObject(entered, 100) == 0: + observed = True + assert child.poll() is None and not pixels.exists(), f"draw completed during {pause}" + break + kernel.SetEvent(release) + result = child.wait(timeout=45) + finally: + if pause: + kernel.SetEvent(release) + if child.poll() is None: + child.kill() + child.wait() + stdout.seek(0) + stderr.seek(0) + log = stderr.read().decode(errors="replace") + print(stdout.read().decode(errors="replace").strip()) + if result == 77: + sys.exit(77) + assert result == 0, log[-8000:] + assert not pause or observed, f"{pause} loader never reached its gate\n{log[-8000:]}" + assert not forbid or kernel.WaitForSingleObject(unexpected, 0) == 258, log[-8000:] + errors = [line for line in log.splitlines() if "x2w-d3d12-debug " in line and (" sev=0 " in line or " sev=1 " in line)] + assert not errors, errors + return pixels.read_bytes(), log + + +def check(work, consumer, sdk, adapter, compiler): + cache = work / "cache" + cache.mkdir() + vs, ps, root, pixels = (work / name for name in ("vs", "ps", "root", "pixels")) + vs.write_bytes(triangle()) + ps.write_bytes(patched_pixel(2, [vop1(1, 0, 128), vop1(1, 1, 242)], export=(0xf800180f, 0x01000001))) + args = [consumer, vs, ps, root, adapter, pixels] + env = dict(os.environ, X2W_SHADER_CACHE=str(cache), X2W_NATIVE_SHADERS=sdk, + X2W_NATIVE_SHADERS_ONLY="0", X2W_DRAW_MISSING_SHADER="0", X2W_PIPELINE_COLOUR="0", + X2W_D3D12_DEBUG="1", X2W_D3D12_RENDER="1", X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1") + clear = bytes((0, 0, 255, 255)) + red = bytes((255, 0, 0, 255)) + expected = (red * 4 + clear * 4) * 4 + + image, log = run_draw(args, env, pixels, pause="NATIVE") + assert image == expected and "ready=1 cache(frontend,vs,ps)=" in log and "-> drawn;" in log, log + marker, = cache.glob("req_*.a") + key = marker.stem.removeprefix("req_") + subprocess.run([compiler, "--watch", sdk, cache, cache, "--once"], check=True, timeout=45) + manifest = cache / f"{key}.txt" + legacy = manifest.read_bytes() + + # This gate is reached in slot 86 before it returns the pipeline. A usable + # published translation must bypass native preparation entirely. + image, log = run_draw(args, env, pixels, pause="PUBLISHED", forbid="NATIVE") + assert image == expected and f"pipeline {key} translated:" in log and "native graphics " not in log, log + + delayed = manifest.with_suffix(".txt.pending") + first = pixels.with_suffix(".first") + for flag, message in (("MANIFEST", "unsupported manifest version"), ("ROOT", "failed 0x80004005")): + manifest.rename(delayed) + first.unlink(missing_ok=True) + fault = dict(env, X2W_TEST_PUBLISH_MANIFEST=str(manifest), **{f"X2W_TEST_NATIVE_GRAPHICS_{flag}_FAILURE": "1"}) + image, log = run_draw(args, fault, pixels) + assert message in log and f"native graphics {key} refused:" in log, log + assert first.read_bytes() == clear * 32 and image == expected and log.count("-> drawn;") == 1, log + + # Replacing an already-present but malformed manifest cannot trigger a retry. + delayed.write_bytes(legacy) + manifest.write_bytes(b"x2w-manifest 999\n") + image, log = run_draw(args, dict(env, X2W_TEST_PUBLISH_MANIFEST=str(manifest)), pixels, forbid="NATIVE") + assert image == clear * 32 and first.read_bytes() == image and "-> drawn;" not in log, log + assert log.count("unsupported manifest version") == 1 and manifest.read_bytes() == legacy, log + + native_only = dict(env, X2W_NATIVE_SHADERS_ONLY="1", X2W_TEST_NATIVE_GRAPHICS_ROOT_FAILURE="1") + image, log = run_draw(args, native_only, pixels, pause="NATIVE", forbid="PUBLISHED") + assert image == clear * 32 and f"native graphics {key} refused:" in log and "-> drawn;" not in log, log + + # Raw synthetic inputs give slot 57 a pixel entry. Its published pair still + # plays from the plain key, while native-only keeps the entry in the request. + raw_vs, raw_ps = work / "raw-vs", work / "raw-ps" + raw_vs.write_bytes(struct.pack(" #include #include +#include #include #include #include @@ -217,6 +218,14 @@ float4 translated_pixel() : SV_Target { return translated_texture.Load(int3(0, 0, 0)); } +float translated_float_pixel() : SV_Target { + return translated_texture.Load(int3(0, 0, 0)).r; +} + +float2 translated_float2_pixel() : SV_Target { + return translated_texture.Load(int3(0, 0, 0)).rg; +} + float4 translated_buffer_pixel() : SV_Target { uint value = translated_buffer.Load(ud2); return float4(value & 255, (value >> 8) & 255, (value >> 16) & 255, 255) / 255.0; @@ -307,8 +316,23 @@ ComPtr create_root(ID3D12Device* device, const D3D12_ROOT_S enum class TableSample { texture, buffer, buffer_tail }; +std::uint64_t fixture_hash(const void* data, std::size_t bytes, std::uint64_t key = 1469598103934665603ull) +{ + const auto* p = static_cast(data); + for (std::size_t i = 0; i < bytes; ++i) key = (key ^ p[i]) * 1099511628211ull; + return key; +} + +std::string fixture_key_name(std::uint64_t key) +{ + char name[17]; + std::snprintf(name, sizeof(name), "%016llx", static_cast(key)); + return name; +} + ComPtr translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* root, ID3DBlob* root_blob, - bool needs_start, TableSample sample = TableSample::texture, bool indexed = false, bool rect = false) + bool needs_start, TableSample sample = TableSample::texture, bool indexed = false, + bool rect = false, std::uint64_t* cache_key = nullptr) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. constexpr char revision[] = "x2w-startup-shader-29"; @@ -317,21 +341,15 @@ ComPtr translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r static std::uint32_t indexed_pixel_id = 0xe0000204; auto& vertex_id = vertex_ids[indexed ? 2 : needs_start]; auto& pixel_id = indexed ? indexed_pixel_id : pixel_ids[static_cast(sample)]; - std::uint64_t key = 1469598103934665603ull; - const auto add = [&key](const void* data, std::size_t bytes) { - const auto* p = static_cast(data); - for (std::size_t i = 0; i < bytes; ++i) key = (key ^ p[i]) * 1099511628211ull; - }; - add(revision, sizeof(revision) - 1); - add(&vertex_id, sizeof(vertex_id)); - add(&pixel_id, sizeof(pixel_id)); - add(root_blob->GetBufferPointer(), root_blob->GetBufferSize()); - char stem[32]; - std::snprintf(stem, sizeof(stem), "%016llx", static_cast(key)); + auto key = fixture_hash(revision, sizeof(revision) - 1); + key = fixture_hash(&vertex_id, sizeof(vertex_id), key); + key = fixture_hash(&pixel_id, sizeof(pixel_id), key); + key = fixture_hash(root_blob->GetBufferPointer(), root_blob->GetBufferSize(), key); + if (cache_key) *cache_key = key; char directory[MAX_PATH]; const DWORD size = GetEnvironmentVariableA("X2W_SHADER_CACHE", directory, MAX_PATH); check(size && size < MAX_PATH ? S_OK : E_FAIL, "find fixture cache"); - const std::string prefix = std::string(directory) + "\\" + stem; + const std::string prefix = std::string(directory) + "\\" + fixture_key_name(key); const auto write = [&](const char* suffix, const void* bytes, std::size_t count) { std::ofstream file(prefix + suffix, std::ios::binary | std::ios::trunc); file.write(static_cast(bytes), count); @@ -1844,6 +1862,280 @@ bool check_translated_targets(ID3D12Device* device, ID3D12Device* guest, ID3D12R return true; } +// Reuse the translated-targets setup with independent recordings and readbacks. +// Only DrawInstanced and the submit probe run on the racing threads. +struct GraphicsPublicationDraw { + GraphicsPublicationDraw(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, + IUnknown* pipeline, const TranslatedDrawFixture& binding, DXGI_FORMAT target_format = format) + { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, target_format, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE clear{target_format, {0, 0, 0, 1}}; + target = resource(device, desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &clear); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + check(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap)), "create publication RTV heap"); + const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + guest->CreateRenderTargetView(target.Get(), nullptr, rtv); + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), + "create publication allocator"); + list = begin_guest_list(guest, allocator.Get()); + auto* w = list.Get(); + const D3D12_VIEWPORT viewport{0, 0, width, height, 0, 1}; + const D3D12_RECT scissor{0, 0, width, height}; + ID3D12DescriptorHeap* heaps[]{binding.heap.Get()}; + using Bind = void (WINAPI*)(IUnknown*, IUnknown*); + slot(w, 25)(w, pipeline); + slot(w, 34)(w, root); + slot(w, 32)(w, 1, heaps); + slot(w, 36)(w, 0, binding.gpu); + slot(w, 20)(w, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + slot(w, 21)(w, 1, &viewport); + slot(w, 22)(w, 1, &scissor); + slot(w, 50)(w, 1, &rtv, FALSE, nullptr); + slot(w, 52)( + w, rtv.ptr, clear.Color, 0, nullptr); + } + + void draw() const + { + slot(list.Get(), 12)(list.Get(), 3, 1, 0, 0); + } + + bool verify(ID3D12Device* device, IUnknown* queue, ID3D12CommandQueue* desktop_queue, std::uint32_t expected) const + { + check(slot(list.Get(), 9)(list.Get()), "close publication draw"); + submit_wrapped(queue, list.Get()); + ComPtr fence; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "create publication fence"); + check(desktop_queue->Signal(fence.Get(), 1), "signal publication fence"); + check(mesh_fence_reached(fence.Get(), 10000) ? S_OK : E_FAIL, "reach publication fence"); + + const auto desc = target->GetDesc(); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + const auto readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands copy(device, kept_direct_queue(device), nullptr); + transition(copy.list.Get(), target.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION source{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + D3D12_TEXTURE_COPY_LOCATION destination{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + destination.PlacedFootprint = footprint; + copy.list->CopyTextureRegion(&destination, 0, 0, 0, &source, nullptr); + copy.submit_and_wait(device); + const D3D12_RANGE range{0, static_cast(bytes)}, untouched{0, 0}; + void* memory = nullptr; + check(readback->Map(0, &range, &memory), "map publication readback"); + bool match = true; + const UINT stride = desc.Format == DXGI_FORMAT_R32G32_FLOAT ? 8 : 4; + for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) { + std::uint32_t pixel; + std::memcpy(&pixel, static_cast(memory) + y * footprint.Footprint.RowPitch + x * stride, sizeof(pixel)); + if (pixel != expected) { + std::fprintf(stderr, "publication pixel (%u,%u) format %u: %08x expected %08x\n", + x, y, static_cast(desc.Format), pixel, expected); + match = false; + } + } + readback->Unmap(0, &untouched); + return match; + } + + ComPtr target; + ComPtr rtv_heap; + ComPtr allocator; + ComPtr list; +}; + +struct GraphicsPublicationGate { + using Event = std::unique_ptr; + + GraphicsPublicationGate(std::uint64_t key, bool interrupt) + { + const auto key_name = fixture_key_name(key); + const auto prefix = "Local\\X2WGraphicsPublication." + std::to_string(GetCurrentProcessId()) + "." + key_name; + release.reset(named_event(prefix + ".release", "X2W_TEST_PUBLISHED_GRAPHICS_GATE")); + entered.reset(named_event(prefix + ".entered", "X2W_TEST_PUBLISHED_GRAPHICS_ENTERED")); + waiter.reset(named_event(prefix + ".waiter", "X2W_TEST_PUBLISHED_GRAPHICS_WAITER")); + check(SetEnvironmentVariableA("X2W_TEST_GRAPHICS_KEY", key_name.c_str()) && + SetEnvironmentVariableA("X2W_TEST_PUBLISHED_GRAPHICS_EXCEPTION", interrupt ? "1" : "0") + ? S_OK : E_FAIL, "select publication gate key and outcome"); + } + + ~GraphicsPublicationGate() + { + finish(); + SetEnvironmentVariableA("X2W_TEST_PUBLISHED_GRAPHICS_GATE", nullptr); + SetEnvironmentVariableA("X2W_TEST_PUBLISHED_GRAPHICS_ENTERED", nullptr); + SetEnvironmentVariableA("X2W_TEST_PUBLISHED_GRAPHICS_WAITER", nullptr); + SetEnvironmentVariableA("X2W_TEST_PUBLISHED_GRAPHICS_EXCEPTION", nullptr); + SetEnvironmentVariableA("X2W_TEST_GRAPHICS_KEY", nullptr); + } + + void finish() + { + SetEvent(release.get()); + if (owner.joinable()) owner.join(); + if (peer.joinable()) peer.join(); + if (witness.joinable()) witness.join(); + } + + static HANDLE named_event(const std::string& name, const char* variable) + { + Event event(CreateEventA(nullptr, TRUE, FALSE, name.c_str()), CloseHandle); + check(event && SetEnvironmentVariableA(variable, name.c_str()) ? S_OK : E_FAIL, "create named graphics event"); + return event.release(); + } + + Event release{nullptr, CloseHandle}, entered{nullptr, CloseHandle}, waiter{nullptr, CloseHandle}; + std::thread owner, peer, witness; +}; + +bool race_graphics_draws(ID3D12Device* device, ID3D12Device* guest, std::uint64_t key, + const GraphicsPublicationDraw& first, const GraphicsPublicationDraw& second, bool same_key, + std::uint32_t first_pixel, std::uint32_t second_pixel, bool interrupt = false, + const GraphicsPublicationDraw* other_targets = nullptr) +{ + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr queue; + check(guest->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), + reinterpret_cast(queue.GetAddressOf())), "create publication queue"); + const auto desktop_queue = native_object(device, guest, queue.Get()); + ComPtr allocator; + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), + "create submit probe allocator"); + const auto closed = begin_guest_list(guest, allocator.Get()); + const auto native_probe = native_object(device, guest, closed.Get()); + constexpr std::uint32_t probe_value = 0x618fc52e; + const auto probe_upload = make_buffer(device, sizeof(probe_value), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + const auto probe_readback = make_buffer(device, sizeof(probe_value), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + const D3D12_RANGE no_read{0, 0}, probe_range{0, sizeof(probe_value)}; + void* probe_memory = nullptr; + check(probe_upload->Map(0, &no_read, &probe_memory), "map submit probe source"); + std::memcpy(probe_memory, &probe_value, sizeof(probe_value)); + probe_upload->Unmap(0, &probe_range); + native_probe->CopyBufferRegion(probe_readback.Get(), 0, probe_upload.Get(), 0, sizeof(probe_value)); + check(slot(closed.Get(), 9)(closed.Get()), "close submit probe"); + ComPtr submitted; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&submitted)), "create submit probe fence"); + + constexpr DWORD wait_ms = 10000; + GraphicsPublicationGate gate(key, interrupt); + gate.owner = std::thread([&] { first.draw(); }); + if (WaitForSingleObject(gate.entered.get(), wait_ms) != WAIT_OBJECT_0 || + WaitForSingleObject(gate.owner.native_handle(), 0) != WAIT_TIMEOUT) { + std::fprintf(stderr, "graphics owner did not enter and stop at its load gate\n"); + return false; + } + ResetEvent(gate.entered.get()); + gate.peer = std::thread([&] { second.draw(); }); + if (same_key) { + const HANDLE progress[]{gate.entered.get(), gate.waiter.get(), gate.peer.native_handle()}; + if (WaitForMultipleObjects(static_cast(std::size(progress)), progress, FALSE, wait_ms) != WAIT_OBJECT_0 + 1 || + WaitForSingleObject(gate.peer.native_handle(), 0) != WAIT_TIMEOUT) { + std::fprintf(stderr, "same-key peer prepared twice, completed early, or failed to wait\n"); + return false; + } + } + if (!same_key || other_targets) { + bool witness_ok = false; + gate.witness = std::thread([&] { + submit_wrapped(queue.Get(), closed.Get()); + witness_ok = SUCCEEDED(desktop_queue->Signal(submitted.Get(), 1)) && mesh_fence_reached(submitted.Get(), wait_ms); + if (other_targets) other_targets->draw(); + }); + if (WaitForSingleObject(gate.witness.native_handle(), wait_ms) != WAIT_OBJECT_0 || + (!same_key && WaitForSingleObject(gate.peer.native_handle(), wait_ms) != WAIT_OBJECT_0)) { + std::fprintf(stderr, "independent draw or guest submission stalled behind the graphics load\n"); + gate.finish(); + return false; + } + gate.witness.join(); + if (!witness_ok) return false; + check(probe_readback->Map(0, &probe_range, &probe_memory), "map submit probe readback"); + std::uint32_t observed = 0; + std::memcpy(&observed, probe_memory, sizeof(observed)); + probe_readback->Unmap(0, &no_read); + if (observed != probe_value) { + std::fprintf(stderr, "closed guest list copy did not execute while graphics load was pending\n"); + return false; + } + } + if (WaitForSingleObject(gate.entered.get(), 0) != WAIT_TIMEOUT || + WaitForSingleObject(gate.owner.native_handle(), 0) != WAIT_TIMEOUT) return false; + gate.finish(); + return first.verify(device, queue.Get(), desktop_queue.Get(), first_pixel) && + second.verify(device, queue.Get(), desktop_queue.Get(), second_pixel) && + (!other_targets || other_targets->verify(device, queue.Get(), desktop_queue.Get(), 0x3f800000)); +} + +std::uint64_t publish_graphics_variant(const std::filesystem::path& cache, std::uint64_t base, DXGI_FORMAT target_format) +{ + const std::string line = "rtv1 " + std::to_string(base) + " " + std::to_string(target_format); + const auto key = fixture_hash(line.data(), line.size()); + const auto original = cache / fixture_key_name(base), variant = cache / fixture_key_name(key); + std::filesystem::copy_file(original.string() + ".vs.cso", variant.string() + ".vs.cso"); + const auto pixel = compile(target_format == DXGI_FORMAT_R32_FLOAT ? "translated_float_pixel" : "translated_float2_pixel", "ps_5_1"); + std::ofstream code(variant.string() + ".ps.cso", std::ios::binary); + code.write(static_cast(pixel->GetBufferPointer()), pixel->GetBufferSize()); + check(code.good() ? S_OK : E_FAIL, "publish graphics variant pixel stage"); + code.close(); + std::ifstream source(original.string() + ".txt", std::ios::binary); + std::ofstream manifest(variant.string() + ".txt", std::ios::binary); + manifest << line << '\n' << source.rdbuf(); + check(source && manifest ? S_OK : E_FAIL, "publish graphics variant fixture"); + return key; +} + +bool check_graphics_publication(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, + ID3DBlob* blob, const std::filesystem::path& cache, const std::wstring& log_path, + bool concurrent) +{ + std::uint64_t key, other_key; + const auto first = translated_pipeline(guest, root, blob, false, TableSample::texture, false, false, &key); + const auto peer = translated_pipeline(guest, root, blob, !concurrent, TableSample::texture, false, false, &other_key); + if ((first.Get() == peer.Get()) || (concurrent != (key == other_key))) return false; + const TranslatedDrawFixture red_binding(guest, red), green_binding(guest, green); + const GraphicsPublicationDraw red_draw(device, guest, root, first.Get(), red_binding); + const GraphicsPublicationDraw green_draw(device, guest, root, peer.Get(), green_binding); + if (!race_graphics_draws(device, guest, key, red_draw, green_draw, concurrent, red, green)) return false; + + std::uint64_t variant = 0, sibling = 0, interrupted = 0; + if (concurrent) { + variant = publish_graphics_variant(cache, key, DXGI_FORMAT_R32_FLOAT); + sibling = publish_graphics_variant(cache, key, DXGI_FORMAT_R32G32_FLOAT); + const GraphicsPublicationDraw variant_a(device, guest, root, first.Get(), red_binding, DXGI_FORMAT_R32_FLOAT); + const GraphicsPublicationDraw variant_b(device, guest, root, peer.Get(), red_binding, DXGI_FORMAT_R32_FLOAT); + const GraphicsPublicationDraw sibling_draw(device, guest, root, peer.Get(), red_binding, DXGI_FORMAT_R32G32_FLOAT); + if (!race_graphics_draws(device, guest, variant, variant_a, variant_b, true, 0x3f800000, 0x3f800000, false, &sibling_draw)) + return false; + const auto broken_a = translated_pipeline(guest, root, blob, true, TableSample::texture, false, false, &interrupted); + const auto broken_b = translated_pipeline(guest, root, blob, true); + const GraphicsPublicationDraw no_draw_a(device, guest, root, broken_a.Get(), red_binding); + const GraphicsPublicationDraw no_draw_b(device, guest, root, broken_b.Get(), green_binding); + if (!race_graphics_draws(device, guest, interrupted, no_draw_a, no_draw_b, true, black, black, true)) return false; + } + + std::ifstream input(std::filesystem::path(log_path), std::ios::binary); + const std::string log{std::istreambuf_iterator(input), std::istreambuf_iterator()}; + const auto count = [&](const std::string& query) { + unsigned matches = 0; + for (std::size_t at = 0; (at = log.find(query, at)) != std::string::npos; at += query.size()) ++matches; + return matches; + }; + const auto published = [&](std::uint64_t identity, unsigned draws) { + const auto name = "pipeline " + fixture_key_name(identity); + return count(name + " translated:") == 1 && count(name + " topology 0x4 -> drawn;") == draws; + }; + const bool ok = concurrent + ? published(key, 2) && published(variant, 2) && published(sibling, 1) && + count("graphics preparation for " + fixture_key_name(interrupted) + " interrupted") == 1 && + count("pipeline " + fixture_key_name(interrupted) + " translated:") == 0 + : published(key, 1) && published(other_key, 1); + if (!ok) std::fprintf(stderr, "unexpected number of graphics preparations or translated draws\n"); + return ok; +} + bool check_indirect_other_refusal_census(const std::wstring& log_path) { const std::size_t needed = x2w_d3d12_census_report(nullptr, 0); @@ -2861,6 +3153,15 @@ int main(int argc, char** argv) try const bool refusal_census_control = argc == 3 && std::strcmp(argv[2], "translated-refusal-census-control") == 0; const bool refusal_census = refusal_census_control || (argc == 3 && std::strcmp(argv[2], "translated-refusal-census") == 0); const bool translated_targets = argc == 3 && std::strcmp(argv[2], "translated-targets") == 0; + const bool graphics_concurrent = argc == 3 && std::strcmp(argv[2], "graphics-publication-concurrent") == 0; + const bool graphics_publication = graphics_concurrent || + (argc == 3 && std::strcmp(argv[2], "graphics-publication-unlock") == 0); + if (graphics_publication) { + SetEnvironmentVariableA("X2W_NATIVE_SHADERS", nullptr); + SetEnvironmentVariableA("X2W_NATIVE_SHADERS_ONLY", "0"); + SetEnvironmentVariableA("X2W_DRAW_MISSING_SHADER", "0"); + SetEnvironmentVariableA("X2W_PIPELINE_COLOUR", "0"); + } const bool fallback_enabled = argc == 3 && std::strcmp(argv[2], "missing-shader-fallback") == 0; const bool fallback_fixture = fallback_enabled || (argc == 3 && std::strcmp(argv[2], "missing-shader-fallback-off") == 0); @@ -2888,7 +3189,7 @@ int main(int argc, char** argv) try const bool alias_disabled = argc == 3 && std::strcmp(argv[2], "translated-indexed-alias-off") == 0; const bool alias_index = alias_disabled || (argc == 3 && std::strcmp(argv[2], "translated-indexed-alias") == 0); const bool translated_indexed = alias_index || upload_index || rect || (argc == 3 && std::strcmp(argv[2], "translated-indexed") == 0); - const bool translated = copy_on || copy_off || refusal_census || other_refusal_census || translated_targets || + const bool translated = copy_on || copy_off || refusal_census || other_refusal_census || translated_targets || graphics_publication || fallback_fixture || translated_indexed || (argc == 3 && std::strcmp(argv[2], "translated") == 0); // "count-control" is the negative control: it expects one forwarded call too many. const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; @@ -2933,7 +3234,7 @@ int main(int argc, char** argv) try wchar_t directory[MAX_PATH]; if (!GetTempPathW(MAX_PATH, directory)) return 4; const std::wstring log_path = std::wstring(directory) + L"x2w_indirect_counts_" + std::to_wstring(GetCurrentProcessId()) + L".log"; - if (indexed || lease_arguments || dual_lease || loose_root || refusal_census || other_refusal_census) { + if (indexed || lease_arguments || dual_lease || loose_root || refusal_census || other_refusal_census || graphics_publication) { DeleteFileW(log_path.c_str()); SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); SetEnvironmentVariableA("X2W_PRESENT_SIGNATURE_EVERY", "0"); @@ -3277,6 +3578,15 @@ int main(int argc, char** argv) try const D3D12_ROOT_SIGNATURE_DESC title_desc{1, &table, 0, nullptr, root_flags}; ComPtr root_blob; const auto title_root = create_root(guest.Get(), title_desc, &root_blob); + if (graphics_publication) { + const bool ok = check_graphics_publication(device.Get(), guest.Get(), title_root.Get(), root_blob.Get(), + cache, log_path, graphics_concurrent); + if (ok) { + std::filesystem::remove_all(cache); + DeleteFileW(log_path.c_str()); + } + return ok && (!info || !info->GetNumStoredMessages()) ? 0 : 1; + } if (translated_indexed) { const auto pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), true, TableSample::texture, true, rect); const auto left = writer_pipeline(device.Get(), writer.Get(), "write_left"); diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 4c7a864970..15298e5c26 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -1378,7 +1378,7 @@ int main(int argc, char** argv) if (length && length < MAX_PATH) { const std::string first = std::string(argv[5]) + ".first"; if (const int rc = check_stream_draw(adapter.Get(), device, pso, first.c_str(), nullptr, format)) return rc; - if (!MoveFileW((std::wstring(manifest) + L".pending").c_str(), manifest)) return 61; + if (!MoveFileExW((std::wstring(manifest) + L".pending").c_str(), manifest, MOVEFILE_REPLACE_EXISTING)) return 61; Sleep(1100); } if (GetEnvironmentVariableW(L"X2W_TEST_PLACED_VERTEX", nullptr, 0)) { From 40d6679c7ce479d4318d801e7ea1a0fad0681869 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:27:25 +0100 Subject: [PATCH 04/15] startup: document graphics translation lock scope --- docs/startup-runtime.md | 22 ++++++++++++++-------- src/startup_stubs/manifest_retry.h | 5 ++--- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index ea9c9626db..ed4adf7956 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1073,11 +1073,10 @@ created during the run is translated within seconds and the runtime picks it up instead of on the next run. `compile_dxil --watch` uses the same ready-marker priority, batch size and rescan cadence. The runtime looks for an absent manifest again 1 second after the first miss and doubles the wait with each -further miss up to 32 seconds. A translation published during the run is therefore -used on a draw or Dispatch at most 32 seconds later, and a key that never gets a translation costs one -cache lookup every 32 seconds instead of one per second (each lookup holds `draw_lock`, which every draw -and Dispatch takes). The cache persists: a later run reads every published `.txt` and translates only new -requests. The watcher's first pass retries every earlier failure once, so a translator update reaches +further miss up to 32 seconds. A draw or Dispatch can pick up a newly published translation once that retry +is due. A key that never gets a translation costs at most one cache lookup every 32 seconds once the backoff +reaches its cap. The cache persists across runs, so a later run reads published `.txt` files and +translates only new requests. The watcher's first pass retries every earlier failure once, so a translator update reaches requests that failed in an earlier run; after that, a request whose `.fail` is newer than its ready marker is not retried during the run (the runtime writes each request once and never rewrites it). The one-shot `--pending` scan retries every failure unless `--skip-failed` (`-s`) or @@ -1134,9 +1133,8 @@ launchers' default `X2W_NATIVE_SHADERS_ONLY=1`, `load_compute_translation` retur refusals of a process are logged as `compute pipeline not translated natively: `. A refused key is left to the published translations, so `-Translate` can run beside it for those pipelines. A direct module requires -shader model 6.6 and wave32. The in-process -translation is tried once per key and before a published `.txt`. It covers compute only; graphics -pipelines still need a published translation. +shader model 6.6 and wave32. In-process compute translation is tried once per key and before a published +`.txt`. Published compute translations from `compile_dxil --requests` and `--watch` carry a `native 1` line in the `x2w-manifest 2` manifest. The stand-in requires the current native output revision. An unmarked manifest @@ -1145,6 +1143,14 @@ rebuilds stale native outputs and leaves Python publications in place. The stand absent manifest on subsequent dispatches on the ManifestRetry schedule (1 s, doubling up to 32 s), so a running process can pick up a rebuilt output (by the code path; no test covers the reload). Compute request keys stay at `29cs`, and revision-28 archives are still read. +For graphics, the initiating draw or pipeline creation call prepares a translation synchronously with +`draw_lock` released. That covers request writes, manifest and bytecode reads, eligible native compilation, +and translated root signature creation. Calls that need the same pending key and phase wait with the lock +released. Other keys and guest queue submissions can proceed. The initiating call publishes the result under +the lock before any caller uses it to record. Usable published translations take precedence over native +compilation unless native-only mode is enabled. An absent manifest remains eligible for retry and for the +existing direct-draw fallback. Recording and translated pipeline state object creation still take `draw_lock`. + Check with `ctest --preset dev -R '^startup_compute_dispatch_native_(warp|hardware)$' -V` ([`tests/startup_compute_dispatch_native_check.py`](../tests/startup_compute_dispatch_native_check.py); [route, controls and results](experiments/startup-compute-native-dispatch.md)). diff --git a/src/startup_stubs/manifest_retry.h b/src/startup_stubs/manifest_retry.h index 71d2824e49..89fa68fcf9 100644 --- a/src/startup_stubs/manifest_retry.h +++ b/src/startup_stubs/manifest_retry.h @@ -1,9 +1,8 @@ // When to look again for a shader cache manifest (.txt) that was absent. // // The graphics and compute translation paths look for a missing manifest again on a later draw or Dispatch, because -// the translator (run.ps1 -Translate) can publish it while the title runs. Each look opens a file in the shader cache -// while the caller holds draw_lock, which every draw and Dispatch takes. With a fixed 1 s retry, many keys that -// never get a translation each cost one file open per second, and every other list call waits on that lock. +// the translator (run.ps1 -Translate) can publish it while the title runs. Each look opens a file in the shader +// cache. With a fixed 1 s retry, every key that never gets a translation would cost one file open per second. // // The wait starts at 1 s after the first miss and doubles with each further miss up to 32 s. A translation published // during the run is still found, within 32 s at the latest; a key that is never translated costs one look every 32 s. From 3decc2d1ef19ac4aeff9b0cb4eb2d009feb48c8f Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:39:02 +0100 Subject: [PATCH 05/15] startup: back off abandoned graphics translation attempts --- docs/startup-runtime.md | 31 +++++++++++++++++------------- src/startup_stubs/d3d12_draw.inl | 20 ++++++++++++++----- src/startup_stubs/manifest_retry.h | 5 +++-- 3 files changed, 36 insertions(+), 20 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index ed4adf7956..b5964f2599 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1073,11 +1073,12 @@ created during the run is translated within seconds and the runtime picks it up instead of on the next run. `compile_dxil --watch` uses the same ready-marker priority, batch size and rescan cadence. The runtime looks for an absent manifest again 1 second after the first miss and doubles the wait with each -further miss up to 32 seconds. A draw or Dispatch can pick up a newly published translation once that retry -is due. A key that never gets a translation costs at most one cache lookup every 32 seconds once the backoff -reaches its cap. The cache persists across runs, so a later run reads published `.txt` files and -translates only new requests. The watcher's first pass retries every earlier failure once, so a translator update reaches -requests that failed in an earlier run; after that, a request whose `.fail` is newer than its +further miss up to 32 seconds. A draw or Dispatch can pick up a newly published translation once its retry +is due. A key that never gets a translation costs at most one cache lookup every 32 seconds once the wait +reaches its cap. Compute manifest lookups hold `draw_lock`. The cache persists across runs, so a later +run reads published `.txt` files and translates only new requests. The watcher's first pass retries +every earlier failure once, so a translator update reaches requests that failed in an earlier run. +After that, a request whose `.fail` is newer than its ready marker is not retried during the run (the runtime writes each request once and never rewrites it). The one-shot `--pending` scan retries every failure unless `--skip-failed` (`-s`) or `X2W_SKIP_FAILED=1` is set, which skips requests whose `.fail` is already up to date with their @@ -1106,6 +1107,18 @@ print the same results and write the same failures as one, an unexpected transla `startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it together with a child process. +### Preparing graphics translations in the stand-in + +The initiating draw or pipeline creation call prepares a graphics translation synchronously with +`draw_lock` released. Preparation includes request writes, manifest and bytecode reads, eligible native +compilation, and translated root signature creation. Calls that need the same pending key and phase +wait with the lock released. Other keys and guest queue submissions can proceed. The initiating call +publishes the result under the lock. Usable published translations take precedence over native +compilation unless native-only mode is enabled. When published translations are enabled, the manifest +retry schedule also applies when preparation is interrupted or the device changes. An absent manifest +can use the existing direct-draw fallback. Translated pipeline state object creation and command +recording hold `draw_lock`. + ### Translating compute programs in the stand-in With `X2W_NATIVE_SHADERS=` (`run.ps1 -Render -NativeShaders `), @@ -1143,14 +1156,6 @@ rebuilds stale native outputs and leaves Python publications in place. The stand absent manifest on subsequent dispatches on the ManifestRetry schedule (1 s, doubling up to 32 s), so a running process can pick up a rebuilt output (by the code path; no test covers the reload). Compute request keys stay at `29cs`, and revision-28 archives are still read. -For graphics, the initiating draw or pipeline creation call prepares a translation synchronously with -`draw_lock` released. That covers request writes, manifest and bytecode reads, eligible native compilation, -and translated root signature creation. Calls that need the same pending key and phase wait with the lock -released. Other keys and guest queue submissions can proceed. The initiating call publishes the result under -the lock before any caller uses it to record. Usable published translations take precedence over native -compilation unless native-only mode is enabled. An absent manifest remains eligible for retry and for the -existing direct-draw fallback. Recording and translated pipeline state object creation still take `draw_lock`. - Check with `ctest --preset dev -R '^startup_compute_dispatch_native_(warp|hardware)$' -V` ([`tests/startup_compute_dispatch_native_check.py`](../tests/startup_compute_dispatch_native_check.py); [route, controls and results](experiments/startup-compute-native-dispatch.md)). diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 42960e7e16..ba6000ec6b 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -167,7 +167,7 @@ struct TranslationState { bool native_graphics_attempted = false; std::string native_refusal; // why try_native_graphics last refused this key (X2W_PIPELINE_COLOUR log) #endif - x2w_startup::ManifestRetry manifest_retry; // Only an absent manifest can become ready on a later draw. + x2w_startup::ManifestRetry manifest_retry; // Backoff for absent manifests and abandoned preparations. std::vector srvs; std::vector uavs; // manifest 'uav N tex2d table P O' (#1996 F): u0.. after the SRVs std::vector uds; @@ -822,14 +822,16 @@ void prepare_graphics_translation(Translation& entry, Prepare&& prepare) GraphicsReservation reservation(entry.preparing); try { Wrapper* const wrapper = the_device; - x2w_startup::ComPtr device(wrapper ? device_of(wrapper) : nullptr); const auto retry = entry.manifest_retry; const int state = entry.state; #ifdef X2W_NATIVE_SHADERS const bool native_attempted = entry.native_graphics_attempted; auto native_refusal = entry.native_refusal; #endif + x2w_startup::ComPtr pinned(wrapper ? device_of(wrapper) : nullptr); GraphicsUnlock unlocked; + // Abandoned results and the device reference unwind before the lock guard. + const auto device = std::move(pinned); TranslationPreparation prepared(entry.key); prepared.state = state; prepared.manifest_retry = retry; @@ -846,15 +848,23 @@ void prepare_graphics_translation(Translation& entry, Prepare&& prepare) unlocked.reacquire(); // The reservation is exclusive through publication. A result prepared on a // superseded device must not enter the cache. - if (the_device == wrapper) install_graphics_translation(entry, prepared); - else unlocked.release(); + if (the_device == wrapper) { + install_graphics_translation(entry, prepared); + return; + } + unlocked.release(); } catch (...) { // The unlock guard reacquired draw_lock before we clear the reservation. - // A retry leaves its last committed state available. GraphicsUnlock unlocked; log("x2w-draw graphics preparation for %016llx interrupted", entry.key); } if (!entry.state) entry.state = 2; + if (!native_shaders_only()) { + // Use the last committed retry state, since the discarded candidate may + // already have changed its own schedule or cleared it after reading a manifest. + if (!entry.manifest_retry.pending()) InterlockedIncrement(&translation_missing); + entry.manifest_retry.missed(GetTickCount64()); + } } // draw_lock held. Both pipeline forms use the same request writer and shader cache. diff --git a/src/startup_stubs/manifest_retry.h b/src/startup_stubs/manifest_retry.h index 89fa68fcf9..71d2824e49 100644 --- a/src/startup_stubs/manifest_retry.h +++ b/src/startup_stubs/manifest_retry.h @@ -1,8 +1,9 @@ // When to look again for a shader cache manifest (.txt) that was absent. // // The graphics and compute translation paths look for a missing manifest again on a later draw or Dispatch, because -// the translator (run.ps1 -Translate) can publish it while the title runs. Each look opens a file in the shader -// cache. With a fixed 1 s retry, every key that never gets a translation would cost one file open per second. +// the translator (run.ps1 -Translate) can publish it while the title runs. Each look opens a file in the shader cache +// while the caller holds draw_lock, which every draw and Dispatch takes. With a fixed 1 s retry, many keys that +// never get a translation each cost one file open per second, and every other list call waits on that lock. // // The wait starts at 1 s after the first miss and doubles with each further miss up to 32 s. A translation published // during the run is still found, within 32 s at the latest; a key that is never translated costs one look every 32 s. From cd49b0cd820e69bcf84614569db1347a34d768fd Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:39:06 +0100 Subject: [PATCH 06/15] test: cover retries after abandoned graphics preparation --- tests/startup_indirect_draw_indexed.cpp | 73 ++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 7 deletions(-) diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 2c2d9b9c27..dec01b02d2 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2087,9 +2087,61 @@ std::uint64_t publish_graphics_variant(const std::filesystem::path& cache, std:: return key; } -bool check_graphics_publication(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, - ID3DBlob* blob, const std::filesystem::path& cache, const std::wstring& log_path, - bool concurrent) +bool check_interrupted_graphics_retry(std::uint64_t key, const GraphicsPublicationDraw& draw) +{ + Sleep(1100); // The first interruption must schedule the ordinary one-second retry. + { + GraphicsPublicationGate gate(key, true); + SetEvent(gate.release.get()); + draw.draw(); + if (WaitForSingleObject(gate.entered.get(), 0) != WAIT_OBJECT_0) { + std::fprintf(stderr, "interrupted graphics key never retried\n"); + return false; + } + ResetEvent(gate.entered.get()); + draw.draw(); + if (WaitForSingleObject(gate.entered.get(), 0) != WAIT_TIMEOUT) { + std::fprintf(stderr, "graphics retry interruption did not advance the retry deadline\n"); + return false; + } + } + Sleep(2100); // The second interruption advances the one-second delay to two seconds. + draw.draw(); + return true; +} + +bool check_superseded_graphics_retry(IDXGIAdapter1* adapter, ID3D12Device* guest, std::uint64_t key, + const GraphicsPublicationDraw& draw) +{ + ComPtr replacement; + GraphicsPublicationGate gate(key, false); + gate.owner = std::thread([&] { draw.draw(); }); + if (WaitForSingleObject(gate.entered.get(), 10000) != WAIT_OBJECT_0) { + std::fprintf(stderr, "graphics load did not reach the gate before replacing the guest device\n"); + return false; + } + // Wrap the same adapter so the replacement is safe for the fixture's existing resources. + const std::array parameters{}; + check(D3D12XboxCreateDevice(adapter, parameters.data(), IID_PPV_ARGS(&replacement)), + "replace guest device during graphics preparation"); + if (!replacement || replacement.Get() == guest || + WaitForSingleObject(gate.owner.native_handle(), 0) != WAIT_TIMEOUT) { + std::fprintf(stderr, "guest device replacement did not finish while graphics preparation was paused\n"); + return false; + } + gate.finish(); + + ResetEvent(gate.entered.get()); + Sleep(1100); + draw.draw(); + if (WaitForSingleObject(gate.entered.get(), 0) == WAIT_OBJECT_0) return true; + std::fprintf(stderr, "superseded graphics result was installed or failed to retry\n"); + return false; +} + +bool check_graphics_publication(IDXGIAdapter1* adapter, ID3D12Device* device, ID3D12Device* guest, + ID3D12RootSignature* root, ID3DBlob* blob, const std::filesystem::path& cache, + const std::wstring& log_path, bool concurrent) { std::uint64_t key, other_key; const auto first = translated_pipeline(guest, root, blob, false, TableSample::texture, false, false, &key); @@ -2100,7 +2152,7 @@ bool check_graphics_publication(ID3D12Device* device, ID3D12Device* guest, ID3D1 const GraphicsPublicationDraw green_draw(device, guest, root, peer.Get(), green_binding); if (!race_graphics_draws(device, guest, key, red_draw, green_draw, concurrent, red, green)) return false; - std::uint64_t variant = 0, sibling = 0, interrupted = 0; + std::uint64_t variant = 0, sibling = 0, interrupted = 0, superseded = 0; if (concurrent) { variant = publish_graphics_variant(cache, key, DXGI_FORMAT_R32_FLOAT); sibling = publish_graphics_variant(cache, key, DXGI_FORMAT_R32G32_FLOAT); @@ -2114,6 +2166,12 @@ bool check_graphics_publication(ID3D12Device* device, ID3D12Device* guest, ID3D1 const GraphicsPublicationDraw no_draw_a(device, guest, root, broken_a.Get(), red_binding); const GraphicsPublicationDraw no_draw_b(device, guest, root, broken_b.Get(), green_binding); if (!race_graphics_draws(device, guest, interrupted, no_draw_a, no_draw_b, true, black, black, true)) return false; + const GraphicsPublicationDraw retry_draw(device, guest, root, broken_a.Get(), red_binding); + if (!check_interrupted_graphics_retry(interrupted, retry_draw)) return false; + + superseded = publish_graphics_variant(cache, interrupted, DXGI_FORMAT_R32_FLOAT); + const GraphicsPublicationDraw superseded_draw(device, guest, root, broken_a.Get(), red_binding, DXGI_FORMAT_R32_FLOAT); + if (!check_superseded_graphics_retry(adapter, guest, superseded, superseded_draw)) return false; } std::ifstream input(std::filesystem::path(log_path), std::ios::binary); @@ -2129,8 +2187,9 @@ bool check_graphics_publication(ID3D12Device* device, ID3D12Device* guest, ID3D1 }; const bool ok = concurrent ? published(key, 2) && published(variant, 2) && published(sibling, 1) && - count("graphics preparation for " + fixture_key_name(interrupted) + " interrupted") == 1 && - count("pipeline " + fixture_key_name(interrupted) + " translated:") == 0 + count("graphics preparation for " + fixture_key_name(interrupted) + " interrupted") == 2 && + published(interrupted, 1) && + count("pipeline " + fixture_key_name(superseded) + " topology 0x4 -> drawn;") == 1 : published(key, 1) && published(other_key, 1); if (!ok) std::fprintf(stderr, "unexpected number of graphics preparations or translated draws\n"); return ok; @@ -3579,7 +3638,7 @@ int main(int argc, char** argv) try ComPtr root_blob; const auto title_root = create_root(guest.Get(), title_desc, &root_blob); if (graphics_publication) { - const bool ok = check_graphics_publication(device.Get(), guest.Get(), title_root.Get(), root_blob.Get(), + const bool ok = check_graphics_publication(adapter.Get(), device.Get(), guest.Get(), title_root.Get(), root_blob.Get(), cache, log_path, graphics_concurrent); if (ok) { std::filesystem::remove_all(cache); From e097cffe9121c1ea72e530d5f9bb791bfb6bb8a8 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:00:29 +0100 Subject: [PATCH 07/15] startup: fix graphics command signature and abandonment backoff --- docs/startup-runtime.md | 4 +-- src/startup_stubs/d3d12_draw.inl | 43 +++++++++++++++++++------------- 2 files changed, 27 insertions(+), 20 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index b5964f2599..b332971bc7 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1114,8 +1114,8 @@ The initiating draw or pipeline creation call prepares a graphics translation sy compilation, and translated root signature creation. Calls that need the same pending key and phase wait with the lock released. Other keys and guest queue submissions can proceed. The initiating call publishes the result under the lock. Usable published translations take precedence over native -compilation unless native-only mode is enabled. When published translations are enabled, the manifest -retry schedule also applies when preparation is interrupted or the device changes. An absent manifest +compilation unless native-only mode is enabled. The manifest retry schedule also applies when +preparation is interrupted or the device changes, including in native-only mode. An absent manifest can use the existing direct-draw fallback. Translated pipeline state object creation and command recording hold `draw_lock`. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index ba6000ec6b..d34b2ce8e5 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -343,7 +343,15 @@ void signal_graphics_fixture(const wchar_t* variable, u64 key) void wait_for_graphics_key(u64 key) { - signal_graphics_fixture(L"X2W_TEST_PUBLISHED_GRAPHICS_WAITER", key); + static constexpr wchar_t waiter[] = L"X2W_TEST_PUBLISHED_GRAPHICS_WAITER"; + // Fixtures set the waiter before the first graphics wait and can change its name between races. + static const bool enabled = [] { + const DWORD saved = GetLastError(); + const bool configured = GetEnvironmentVariableW(waiter, nullptr, 0) != 0; + SetLastError(saved); + return configured; + }(); + if (enabled) signal_graphics_fixture(waiter, key); wait_for_graphics_translation(); } @@ -831,7 +839,7 @@ void prepare_graphics_translation(Translation& entry, Prepare&& prepare) x2w_startup::ComPtr pinned(wrapper ? device_of(wrapper) : nullptr); GraphicsUnlock unlocked; // Abandoned results and the device reference unwind before the lock guard. - const auto device = std::move(pinned); + auto device = std::move(pinned); TranslationPreparation prepared(entry.key); prepared.state = state; prepared.manifest_retry = retry; @@ -845,6 +853,7 @@ void prepare_graphics_translation(Translation& entry, Prepare&& prepare) prepared.ps.Reset(); prepared.root.Reset(); } + device.Reset(); unlocked.reacquire(); // The reservation is exclusive through publication. A result prepared on a // superseded device must not enter the cache. @@ -859,12 +868,9 @@ void prepare_graphics_translation(Translation& entry, Prepare&& prepare) log("x2w-draw graphics preparation for %016llx interrupted", entry.key); } if (!entry.state) entry.state = 2; - if (!native_shaders_only()) { - // Use the last committed retry state, since the discarded candidate may - // already have changed its own schedule or cleared it after reading a manifest. - if (!entry.manifest_retry.pending()) InterlockedIncrement(&translation_missing); - entry.manifest_retry.missed(GetTickCount64()); - } + // Use the last committed retry state, since a discarded candidate may have cleared its schedule. + if (!entry.manifest_retry.pending() && !native_shaders_only()) InterlockedIncrement(&translation_missing); + entry.manifest_retry.missed(GetTickCount64()); } // draw_lock held. Both pipeline forms use the same request writer and shader cache. @@ -1537,7 +1543,8 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) const bool retry = base->manifest_retry.due(GetTickCount64()); bool needs_native = false; #ifdef X2W_NATIVE_SHADERS - needs_native = (base->manifest_retry.pending() || native_shaders_only()) && !base->native_graphics_attempted; + needs_native = !base->native_graphics_attempted && + (native_shaders_only() ? !base->manifest_retry.pending() : base->manifest_retry.pending()); #endif if (retry || needs_native) { prepare_graphics_translation(*base, [retry](TranslationPreparation& prepared, ID3D12Device* device) { @@ -1559,10 +1566,12 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) const auto [found, inserted] = translation_by_key().try_emplace(key, key); auto& entry = found->second; while (entry.preparing) wait_for_graphics_key(entry.key); - if (inserted) { + if (inserted || entry.manifest_retry.due(GetTickCount64())) { + // A native-only retry follows an abandonment and must complete the first preparation. + const bool publish_request = inserted || native_shaders_only(); prepare_graphics_translation(entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { load_translation(prepared, device, request); - if (prepared.state == 1) return; + if (!publish_request || prepared.state == 1) return; [[maybe_unused]] const bool published = publish_shader_request(key, L".rtv", request.data(), request.size()); #ifdef X2W_NATIVE_SHADERS if (published && (prepared.manifest_retry.pending() || native_shaders_only()) && @@ -1570,10 +1579,6 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) #endif log("x2w-draw no RTV translation for %016llx (%s)", key, request.c_str()); }); - } else if (entry.manifest_retry.due(GetTickCount64())) { - prepare_graphics_translation(entry, [&](TranslationPreparation& prepared, ID3D12Device* device) { - load_translation(prepared, device, request); - }); } return &entry; } @@ -2721,7 +2726,7 @@ ID3D12Resource* validate_indexed_arguments(Wrapper* self, ID3D12GraphicsCommandL fields[0].Constant = {0, static_cast(translation.indirect_base_word), 1}; fields[1].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED; const D3D12_COMMAND_SIGNATURE_DESC signature{24, 2, fields, 0}; - if (FAILED(device->CreateCommandSignature(&signature, translation.root, IID_PPV_ARGS(&translation.indexed_signature)))) + if (FAILED(device->CreateCommandSignature(&signature, translation.root.Get(), IID_PPV_ARGS(&translation.indexed_signature)))) return nullptr; } const auto argument_desc = draw.argument->GetDesc(); @@ -3382,7 +3387,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return false; } if (!tr) note_draw_refusal(0, bound ? "no translation for the bound targets" : "pipeline description not decoded"); - if (used_fallback && tr && tr->manifest_retry.pending() && + const bool manifest_missing = tr && tr->manifest_retry.pending() && !native_shaders_only(); + if (used_fallback && manifest_missing && draw_missing_translation(device_of(self->own().list_device), list, pass, count, instances, start, start_instance)) { *used_fallback = true; ReleaseSRWLockExclusive(&draw_lock); @@ -3406,7 +3412,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI #endif note_draw_refusal(tr->key, translation_ok ? (!d16_ok ? "d16 texture view not ready" : "formatted buffer not ready") : native ? "native graphics refused" - : tr->manifest_retry.pending() ? "no translation (manifest absent)" + : manifest_missing ? "no translation (manifest absent)" + : tr->manifest_retry.pending() ? "native graphics preparation deferred" : "translation unusable (manifest refused)", translation_ok ? nullptr : native); } From e8ad9ad69de4d19ec5486a08b8f00431e6275887 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:00:35 +0100 Subject: [PATCH 08/15] test: verify graphics retry rejects draws on a superseded list --- tests/startup_indirect_draw_indexed.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index dec01b02d2..ffa9c1b20f 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2133,6 +2133,7 @@ bool check_superseded_graphics_retry(IDXGIAdapter1* adapter, ID3D12Device* guest ResetEvent(gate.entered.get()); Sleep(1100); + // The original list can trigger a retry, but it cannot record a draw for the replacement device. draw.draw(); if (WaitForSingleObject(gate.entered.get(), 0) == WAIT_OBJECT_0) return true; std::fprintf(stderr, "superseded graphics result was installed or failed to retry\n"); @@ -2185,11 +2186,13 @@ bool check_graphics_publication(IDXGIAdapter1* adapter, ID3D12Device* device, ID const auto name = "pipeline " + fixture_key_name(identity); return count(name + " translated:") == 1 && count(name + " topology 0x4 -> drawn;") == draws; }; + const auto superseded_name = "pipeline " + fixture_key_name(superseded); const bool ok = concurrent ? published(key, 2) && published(variant, 2) && published(sibling, 1) && count("graphics preparation for " + fixture_key_name(interrupted) + " interrupted") == 2 && published(interrupted, 1) && - count("pipeline " + fixture_key_name(superseded) + " topology 0x4 -> drawn;") == 1 + count(superseded_name + " translated:") == 2 && + count(superseded_name + " topology 0x4 -> drawn;") == 0 : published(key, 1) && published(other_key, 1); if (!ok) std::fprintf(stderr, "unexpected number of graphics preparations or translated draws\n"); return ok; From f3793797ccb7229a3acf8883c8b9535a5d0d6219 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:11:19 +0100 Subject: [PATCH 09/15] test: cover native-only abandonment backoff --- src/startup_stubs/d3d12_draw.inl | 5 +- .../startup_graphics_published_load.cmake | 6 ++ tests/startup_indirect_draw_indexed.cpp | 58 +++++++++++++++++-- 3 files changed, 62 insertions(+), 7 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index d34b2ce8e5..5e0ef5d3de 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -759,8 +759,11 @@ static bool try_native_graphics(TranslationPreparation& tr, ID3D12Device* device wchar_t sdk[MAX_PATH], path[MAX_PATH]; const auto length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); if (!length || length >= MAX_PATH || !cache_path(path, L"req_", tr.key, variant ? L".rtv" : L".a")) return false; + // Let the enclosing preparation abandon the attempt when the fixture throws. + if (pause_graphics_fixture(L"X2W_TEST_NATIVE_GRAPHICS_GATE", L"X2W_TEST_NATIVE_GRAPHICS_ENTERED", tr.key) && + x2w_local::env_on("X2W_TEST_NATIVE_GRAPHICS_EXCEPTION")) + throw std::runtime_error("native graphics fixture exception"); try { - pause_graphics_fixture(L"X2W_TEST_NATIVE_GRAPHICS_GATE", L"X2W_TEST_NATIVE_GRAPHICS_ENTERED", tr.key); const auto request = x2w::read_graphics_request(path); const auto cache = std::filesystem::path(path).parent_path(); bool frontend_hit = false; diff --git a/tests/cmake/startup_graphics_published_load.cmake b/tests/cmake/startup_graphics_published_load.cmake index 74aa792580..5aac1ab308 100644 --- a/tests/cmake/startup_graphics_published_load.cmake +++ b/tests/cmake/startup_graphics_published_load.cmake @@ -5,6 +5,12 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_graphics_published_load_${mode}_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) endforeach() + if(TARGET x2w_shader_compiler) + add_test(NAME startup_graphics_published_load_native_backoff_${backend} + COMMAND startup_indirect_draw_indexed ${backend} graphics-publication-native-backoff) + set_tests_properties(startup_graphics_published_load_native_backoff_${backend} + PROPERTIES TIMEOUT 150 SKIP_RETURN_CODE 77) + endif() if(TARGET compile_dxil AND TARGET startup_stream_consumer AND EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") add_test(NAME startup_graphics_published_load_precedence_${backend} COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index ffa9c1b20f..b35384b0d0 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2110,6 +2110,46 @@ bool check_interrupted_graphics_retry(std::uint64_t key, const GraphicsPublicati return true; } +bool check_native_graphics_backoff(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, ID3DBlob* blob) +{ + const auto pipeline = translated_pipeline(guest, root, blob, false); + const TranslatedDrawFixture binding(guest, red); + const GraphicsPublicationDraw base(device, guest, root, pipeline.Get(), binding); + const GraphicsPublicationDraw variant(device, guest, root, pipeline.Get(), binding, DXGI_FORMAT_R32_FLOAT); + + const auto prefix = "Local\\X2WGraphicsNativeBackoff." + std::to_string(GetCurrentProcessId()); + using Event = GraphicsPublicationGate::Event; + const Event release(GraphicsPublicationGate::named_event(prefix + ".release", "X2W_TEST_NATIVE_GRAPHICS_GATE"), CloseHandle); + const Event entered(GraphicsPublicationGate::named_event(prefix + ".entered", "X2W_TEST_NATIVE_GRAPHICS_ENTERED"), CloseHandle); + SetEnvironmentVariableA("X2W_TEST_GRAPHICS_KEY", nullptr); + check(SetEnvironmentVariableA("X2W_TEST_NATIVE_GRAPHICS_EXCEPTION", "1") && SetEvent(release.get()) + ? S_OK : E_FAIL, "enable native graphics abandonment"); + + const auto attempt = [&](const GraphicsPublicationDraw& draw, const char* target, DWORD delay, bool expected) { + check(ResetEvent(entered.get()) ? S_OK : E_FAIL, "reset native graphics gate"); + draw.draw(); + if (WaitForSingleObject(entered.get(), 0) == (expected ? WAIT_OBJECT_0 : WAIT_TIMEOUT)) return true; + std::fprintf(stderr, "native-only %s preparation %s (retry delay %lu ms)\n", target, + expected ? "did not run" : "ran before its deadline", delay); + return false; + }; + const auto attempt_both = [&](DWORD delay, bool expected) { + const bool base_ok = attempt(base, "base", delay, expected); + const bool variant_ok = attempt(variant, "RTV variant", delay, expected); + return base_ok && variant_ok; + }; + if (!attempt_both(0, true) || !attempt_both(1000, false)) return false; + // Each entered gate abandons the attempt again. Probe inside and beyond each + // wait, including a second 32 s interval to distinguish the cap from 64 s. + for (DWORD delay : {1000u, 2000u, 4000u, 8000u, 16000u, 32000u, 32000u}) { + Sleep(delay * 3 / 4); + if (!attempt_both(delay, false)) return false; + Sleep(delay / 4 + 100); + if (!attempt_both(delay, true)) return false; + } + return true; +} + bool check_superseded_graphics_retry(IDXGIAdapter1* adapter, ID3D12Device* guest, std::uint64_t key, const GraphicsPublicationDraw& draw) { @@ -2133,7 +2173,9 @@ bool check_superseded_graphics_retry(IDXGIAdapter1* adapter, ID3D12Device* guest ResetEvent(gate.entered.get()); Sleep(1100); - // The original list can trigger a retry, but it cannot record a draw for the replacement device. + // Entering the gate again proves the superseded result did not enter the ready cache and a retry ran. + // The draw heap is already pinned to the original device, which prevents a draw even on a replacement-device + // list. The translated log is written during preparation, before installation. draw.draw(); if (WaitForSingleObject(gate.entered.get(), 0) == WAIT_OBJECT_0) return true; std::fprintf(stderr, "superseded graphics result was installed or failed to retry\n"); @@ -3216,11 +3258,13 @@ int main(int argc, char** argv) try const bool refusal_census = refusal_census_control || (argc == 3 && std::strcmp(argv[2], "translated-refusal-census") == 0); const bool translated_targets = argc == 3 && std::strcmp(argv[2], "translated-targets") == 0; const bool graphics_concurrent = argc == 3 && std::strcmp(argv[2], "graphics-publication-concurrent") == 0; - const bool graphics_publication = graphics_concurrent || + const bool native_graphics_backoff = argc == 3 && std::strcmp(argv[2], "graphics-publication-native-backoff") == 0; + const bool graphics_publication = graphics_concurrent || native_graphics_backoff || (argc == 3 && std::strcmp(argv[2], "graphics-publication-unlock") == 0); if (graphics_publication) { - SetEnvironmentVariableA("X2W_NATIVE_SHADERS", nullptr); - SetEnvironmentVariableA("X2W_NATIVE_SHADERS_ONLY", "0"); + // The native backoff fixture exits at the gate before it needs a DXC directory. + SetEnvironmentVariableA("X2W_NATIVE_SHADERS", native_graphics_backoff ? "." : nullptr); + SetEnvironmentVariableA("X2W_NATIVE_SHADERS_ONLY", native_graphics_backoff ? "1" : "0"); SetEnvironmentVariableA("X2W_DRAW_MISSING_SHADER", "0"); SetEnvironmentVariableA("X2W_PIPELINE_COLOUR", "0"); } @@ -3641,8 +3685,10 @@ int main(int argc, char** argv) try ComPtr root_blob; const auto title_root = create_root(guest.Get(), title_desc, &root_blob); if (graphics_publication) { - const bool ok = check_graphics_publication(adapter.Get(), device.Get(), guest.Get(), title_root.Get(), root_blob.Get(), - cache, log_path, graphics_concurrent); + const bool ok = native_graphics_backoff + ? check_native_graphics_backoff(device.Get(), guest.Get(), title_root.Get(), root_blob.Get()) + : check_graphics_publication(adapter.Get(), device.Get(), guest.Get(), title_root.Get(), root_blob.Get(), + cache, log_path, graphics_concurrent); if (ok) { std::filesystem::remove_all(cache); DeleteFileW(log_path.c_str()); From 538cc3c29bc63ac81ad5c42b6a5443346638ec5e Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:30:06 +0100 Subject: [PATCH 10/15] runtime: capture translated PSO inputs and cache reservations --- src/startup_stubs/d3d12_draw.inl | 264 +++++++++++++++++++++---------- 1 file changed, 179 insertions(+), 85 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 5e0ef5d3de..a9f81a3430 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -195,6 +195,8 @@ struct Translation : TranslationState { explicit Translation(u64 key) : key(key) {} const u64 key; // also read by attribution without draw_lock after slot 86 creation + // A ready payload is installed once and kept for the lifetime of this generation. + const Wrapper* ready_device = nullptr; bool preparing = false; std::optional independent_indirect_entry; std::optional indexed_indirect_entry; @@ -205,6 +207,56 @@ struct Translation : TranslationState { LONG logged_draws = 0, logged_bindings = 0, logged_large = 0; // diagnostics budget per translation }; +struct PsoTargetSignature { + PsoTargetSignature(const Pass& pass, DXGI_FORMAT dsv) : count(pass.target_count), dsv(dsv) + { + std::copy_n(pass.target_formats, count, formats.begin()); + } + + bool operator==(const PsoTargetSignature& other) const + { + return count == other.count && dsv == other.dsv && formats == other.formats; + } + + UINT count; + DXGI_FORMAT dsv; + std::array formats{}; +}; + +struct PsoCacheKey { + const Wrapper* device; + const Translation* generation; + PsoTargetSignature targets; + + bool operator==(const PsoCacheKey& other) const + { + return device == other.device && generation == other.generation && targets == other.targets; + } +}; + +struct PsoCacheHash { + std::size_t operator()(const PsoCacheKey& key) const + { + return static_cast(x2w_startup::pso_targets_key(key.targets.count, key.targets.formats.data(), key.targets.dsv)) ^ + std::hash{}(key.device) ^ (std::hash{}(key.generation) << 1); + } +}; + +struct PsoCacheEntry { + bool preparing = false; + bool complete = false; + // The cache retains successful PSOs for closed lists that can still be submitted. + ID3D12PipelineState* pipeline = nullptr; +}; + +struct PsoTargetCache { + // On a bound pipeline and translation generation the effective blend, depth and + // raster state is fixed for a target signature. Only rectangle geometry can vary. + std::array states; + bool replaying = false; + bool replayed = false; +}; + // Per title pipeline: its translation and the blend state found in its state block (if any). struct BoundPipeline { Translation* translation = nullptr; @@ -220,8 +272,7 @@ struct BoundPipeline { bool has_rasterizer = false; D3D12_RASTERIZER_DESC rasterizer{}; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; - std::unordered_map pipelines; // by target formats - std::unordered_set pso_recipe_targets_tried; // target/dsv signatures already replayed + std::unordered_map pso_targets; }; // Looks for a desktop-layout D3D12_BLEND_DESC inside a state block: two flags, then eight render @@ -809,7 +860,7 @@ static bool try_native_graphics(TranslationPreparation& tr, ID3D12Device* device } #endif -void install_graphics_translation(Translation& entry, TranslationPreparation& prepared) +void install_graphics_translation(Translation& entry, TranslationPreparation& prepared, const Wrapper* device) { if (prepared.missing_delta) InterlockedAdd(&translation_missing, prepared.missing_delta); if (prepared.recipe_mismatches) InterlockedAdd(&pso_recipe_mismatches, prepared.recipe_mismatches); @@ -817,6 +868,7 @@ void install_graphics_translation(Translation& entry, TranslationPreparation& pr InterlockedAdd(&pso_recipes_loaded, static_cast(prepared.pso_recipes.size())); InterlockedIncrement(&translation_ready); static_cast(entry) = std::move(prepared); + entry.ready_device = device; } else { entry.state = prepared.state; entry.manifest_retry = prepared.manifest_retry; @@ -861,7 +913,7 @@ void prepare_graphics_translation(Translation& entry, Prepare&& prepare) // The reservation is exclusive through publication. A result prepared on a // superseded device must not enter the cache. if (the_device == wrapper) { - install_graphics_translation(entry, prepared); + install_graphics_translation(entry, prepared, wrapper); return; } unlocked.release(); @@ -1668,95 +1720,142 @@ bool effective_blend_state(const BoundPipeline& bound, const Translation& tr, UI return x2w_startup::apply_export_write_masks(blend, tr.write_masks, target_count); } -bool prepare_translated_pso_desc(Translation& tr, bool indexed_rect, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) +struct TranslatedPsoInput { + TranslatedPsoInput(ID3D12Device* device, const Translation& tr, const BoundPipeline& bound, const Pass& pass, + DXGI_FORMAT dsv_format, bool use_depth_stencil, const D3D12_BLEND_DESC& blend) + : device(device), translation_key(tr.key), vs(tr.vs), ps(tr.ps), root(tr.root), + fixed_stream(tr.fixed_stream), fixed_rectangle_ir(tr.fixed_rectangle_ir), + fixed_rectangle_on_disk(tr.fixed_rectangle_on_disk), use_depth_stencil(use_depth_stencil), + has_rasterizer(bound.has_rasterizer) + { + semantic_names.reserve(fixed_stream.size()); + for (const auto& element : fixed_stream) semantic_names.emplace_back(element.SemanticName); + for (std::size_t i = 0; i < fixed_stream.size(); ++i) fixed_stream[i].SemanticName = semantic_names[i].c_str(); + state.BlendState = blend; + if (use_depth_stencil) state.DepthStencilState = bound.depth_stencil; + state.SampleMask = ~0u; + state.RasterizerState = has_rasterizer ? bound.rasterizer : x2w_startup::default_pso_rasterizer(); + state.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + state.NumRenderTargets = pass.target_count; + std::copy_n(pass.target_formats, pass.target_count, state.RTVFormats); + state.DSVFormat = dsv_format; + state.SampleDesc.Count = 1; + } + TranslatedPsoInput(const TranslatedPsoInput&) = delete; + TranslatedPsoInput& operator=(const TranslatedPsoInput&) = delete; + + x2w_startup::ComPtr device; + u64 translation_key; + x2w_startup::ComPtr vs, ps; + x2w_startup::ComPtr root; + std::vector fixed_stream; + std::vector semantic_names; + std::string fixed_rectangle_ir; + bool fixed_rectangle_on_disk; + bool use_depth_stencil, has_rasterizer; + D3D12_GRAPHICS_PIPELINE_STATE_DESC state{}; +}; + +x2w_startup::ComPtr prepare_translated_rect_geometry(const TranslatedPsoInput& input) { - desc.pRootSignature = tr.root.Get(); - desc.InputLayout = {tr.fixed_stream.data(), static_cast(tr.fixed_stream.size())}; - desc.VS = {tr.vs->GetBufferPointer(), tr.vs->GetBufferSize()}; - desc.PS = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()}; - if (!indexed_rect) return true; - if (!tr.indexed_rect_geometry_attempted) { - tr.indexed_rect_geometry_attempted = true; - x2w_startup::ComPtr errors; - HRESULT hr = E_NOTIMPL; - if (tr.fixed_stream.empty()) - hr = x2w_startup::compile_indexed_rect_geometry(tr.vs.Get(), tr.ps.Get(), &tr.indexed_rect_geometry, &errors); - else if (tr.fixed_rectangle_on_disk) { - wchar_t path[MAX_PATH]; - if (cache_path(path, L"", tr.key, L".gs.cso")) - hr = D3DReadFileToBlob(path, &tr.indexed_rect_geometry); - } + x2w_startup::ComPtr geometry, errors; + HRESULT hr = E_NOTIMPL; + if (input.fixed_stream.empty()) + hr = x2w_startup::compile_indexed_rect_geometry(input.vs.Get(), input.ps.Get(), &geometry, &errors); + else if (input.fixed_rectangle_on_disk) { + wchar_t path[MAX_PATH]; + if (cache_path(path, L"", input.translation_key, L".gs.cso")) + hr = D3DReadFileToBlob(path, &geometry); + } #ifdef X2W_NATIVE_SHADERS - else if (!tr.fixed_rectangle_ir.empty()) { - wchar_t sdk[MAX_PATH], path[MAX_PATH]; - const auto n = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); - if (n && n < MAX_PATH && cache_path(path, L"", tr.key, L".gs.cso")) { - try { - auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); - const auto result = compiler.compile(tr.fixed_rectangle_ir, L"gs_6_6", - std::filesystem::path(path).parent_path(), x2w::ShaderSourceFormat::dxil_ir); - hr = D3DCreateBlob(result.dxil.size(), &tr.indexed_rect_geometry); - if (SUCCEEDED(hr)) std::memcpy(tr.indexed_rect_geometry->GetBufferPointer(), - result.dxil.data(), result.dxil.size()); - } catch (const std::exception& e) { - log("x2w-draw %016llx native rectangle stage: %s", tr.key, e.what()); - } + else if (!input.fixed_rectangle_ir.empty()) { + wchar_t sdk[MAX_PATH], path[MAX_PATH]; + const auto n = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + if (n && n < MAX_PATH && cache_path(path, L"", input.translation_key, L".gs.cso")) { + try { + auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); + const auto result = compiler.compile(input.fixed_rectangle_ir, L"gs_6_6", + std::filesystem::path(path).parent_path(), x2w::ShaderSourceFormat::dxil_ir); + hr = D3DCreateBlob(result.dxil.size(), &geometry); + if (SUCCEEDED(hr)) std::memcpy(geometry->GetBufferPointer(), result.dxil.data(), result.dxil.size()); + } catch (const std::exception& e) { + log("x2w-draw %016llx native rectangle stage: %s", input.translation_key, e.what()); } } + } #endif - if (FAILED(hr)) - log("x2w-draw %016llx: indexed rectangle geometry unavailable (0x%08lx) %s", tr.key, - static_cast(hr), errors ? static_cast(errors->GetBufferPointer()) : ""); + if (FAILED(hr)) + log("x2w-draw %016llx: indexed rectangle geometry unavailable (0x%08lx) %s", input.translation_key, + static_cast(hr), errors ? static_cast(errors->GetBufferPointer()) : ""); + return geometry; +} + +void prepare_translated_pso_desc(const TranslatedPsoInput& input, ID3DBlob* geometry, + D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) +{ + desc.pRootSignature = input.root.Get(); + desc.InputLayout = {input.fixed_stream.data(), static_cast(input.fixed_stream.size())}; + desc.VS = {input.vs->GetBufferPointer(), input.vs->GetBufferSize()}; + desc.PS = {input.ps->GetBufferPointer(), input.ps->GetBufferSize()}; + if (geometry) desc.GS = {geometry->GetBufferPointer(), geometry->GetBufferSize()}; +} + +ID3DBlob* translated_rect_geometry(Translation& tr, const TranslatedPsoInput& input) +{ + if (!tr.indexed_rect_geometry_attempted) { + tr.indexed_rect_geometry_attempted = true; + tr.indexed_rect_geometry = prepare_translated_rect_geometry(input); } - if (!tr.indexed_rect_geometry) return false; - desc.GS = {tr.indexed_rect_geometry->GetBufferPointer(), tr.indexed_rect_geometry->GetBufferSize()}; - return true; + return tr.indexed_rect_geometry.Get(); } // A recipe can only be used when its draw state and the pass match the recipe's key. Other records // in the same translation file stay on disk for a later pass and are ignored here. -bool replay_pso_recipes(BoundPipeline& bound, Translation& tr, const Pass& pass, DXGI_FORMAT dsv_format, - bool use_depth_stencil, const D3D12_BLEND_DESC& effective_blend) +bool replay_pso_recipes(PsoTargetCache& targets, Translation& tr, const TranslatedPsoInput& input) { unsigned precreated = 0, mismatched = 0, failed = 0; - const D3D12_RASTERIZER_DESC bound_rasterizer = bound.has_rasterizer ? bound.rasterizer : x2w_startup::default_pso_rasterizer(); + const auto& state = input.state; for (const x2w_startup::PsoRecipe& recipe : tr.pso_recipes) { - if (recipe.translation_key != tr.key || !x2w_startup::pso_recipe_targets_match(recipe, pass.target_count, - pass.target_formats, dsv_format)) + if (recipe.translation_key != input.translation_key || + !x2w_startup::pso_recipe_targets_match(recipe, state.NumRenderTargets, state.RTVFormats, state.DSVFormat)) continue; - if (recipe.use_depth_stencil != use_depth_stencil || - (use_depth_stencil && !x2w_startup::same_pso_depth(recipe.depth_stencil, bound.depth_stencil)) || - recipe.has_rasterizer != bound.has_rasterizer || - !x2w_startup::same_pso_rasterizer(recipe.rasterizer, bound_rasterizer) || - !x2w_startup::same_pso_blend(recipe.blend, effective_blend) || recipe.sample_count != 1 || + if (recipe.use_depth_stencil != input.use_depth_stencil || + (input.use_depth_stencil && !x2w_startup::same_pso_depth(recipe.depth_stencil, state.DepthStencilState)) || + recipe.has_rasterizer != input.has_rasterizer || + !x2w_startup::same_pso_rasterizer(recipe.rasterizer, state.RasterizerState) || + !x2w_startup::same_pso_blend(recipe.blend, state.BlendState) || recipe.sample_count != 1 || recipe.sample_mask != ~0u || recipe.topology != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { ++mismatched; continue; } - const u64 key = x2w_startup::pso_state_key(pass.target_count, pass.target_formats, dsv_format, - use_depth_stencil, bound.depth_stencil, bound.has_rasterizer, - bound.rasterizer, recipe.indexed_rect); + const u64 key = x2w_startup::pso_state_key(state.NumRenderTargets, state.RTVFormats, state.DSVFormat, + input.use_depth_stencil, state.DepthStencilState, input.has_rasterizer, + state.RasterizerState, recipe.indexed_rect); if (key != recipe.state_key) { ++mismatched; continue; } - if (bound.pipelines.count(key)) continue; - D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; - if (!prepare_translated_pso_desc(tr, recipe.indexed_rect, desc)) { + auto& entry = targets.states[recipe.indexed_rect]; + if (entry.complete) continue; + x2w_startup::ComPtr geometry(recipe.indexed_rect ? translated_rect_geometry(tr, input) : nullptr); + if (recipe.indexed_rect && !geometry) { ++failed; continue; } + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + prepare_translated_pso_desc(input, geometry.Get(), desc); x2w_startup::apply_pso_recipe(recipe, desc); ID3D12PipelineState* pipeline = nullptr; X2W_ZONE("desktop pipeline creation from recipe"); - const HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); + const HRESULT hr = input.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); check_device("translated CreateGraphicsPipelineState from recipe", 0); if (FAILED(hr) || !pipeline) { if (pipeline) pipeline->Release(); ++failed; continue; } - bound.pipelines[key] = pipeline; + entry.pipeline = pipeline; + entry.complete = true; ++precreated; } if (precreated || mismatched || failed) { @@ -1769,51 +1868,46 @@ bool replay_pso_recipes(BoundPipeline& bound, Translation& tr, const Pass& pass, ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const Pass& pass, bool indexed_rect) { + if (tr.ready_device != the_device) return nullptr; const DXGI_FORMAT dsv_format = pass_dsv_format(bound, pass); // A state decoded from registers needs a depth view to act on; with none bound the pass keeps the desktop default. const bool use_depth_stencil = bound.has_depth_stencil && (!bound.depth_from_registers || dsv_format != DXGI_FORMAT_UNKNOWN); - const u64 key = x2w_startup::pso_state_key(pass.target_count, pass.target_formats, dsv_format, use_depth_stencil, - bound.depth_stencil, bound.has_rasterizer, bound.rasterizer, indexed_rect); - const auto found = bound.pipelines.find(key); - if (found != bound.pipelines.end()) return found->second; + auto& targets = bound.pso_targets[{the_device, &tr, PsoTargetSignature(pass, dsv_format)}]; + auto& entry = targets.states[indexed_rect]; + if (entry.complete) return entry.pipeline; + GraphicsReservation reservation(entry.preparing); D3D12_BLEND_DESC blend{}; if (!effective_blend_state(bound, tr, pass.target_count, blend)) { log("x2w-draw export write masks incompatible with shared logic op for %016llx", tr.key); - bound.pipelines[key] = nullptr; + entry.complete = true; return nullptr; } - const u64 targets_key = x2w_startup::pso_targets_key(pass.target_count, pass.target_formats, dsv_format); - if (!tr.pso_recipes.empty() && bound.pso_recipe_targets_tried.insert(targets_key).second) { - const bool attempted = replay_pso_recipes(bound, tr, pass, dsv_format, use_depth_stencil, blend); - const auto replayed = bound.pipelines.find(key); - if (replayed != bound.pipelines.end()) return replayed->second; + const TranslatedPsoInput input(device_of(the_device), tr, bound, pass, dsv_format, use_depth_stencil, blend); + if (!tr.pso_recipes.empty() && !targets.replayed) { + GraphicsReservation replay(targets.replaying); + const bool attempted = replay_pso_recipes(targets, tr, input); + targets.replayed = true; + if (entry.complete) return entry.pipeline; if (attempted) InterlockedIncrement(&pso_recipe_fallbacks); } - D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; - if (!prepare_translated_pso_desc(tr, indexed_rect, desc)) return nullptr; - // Blend state as found in the pipeline's state block, else opaque. Depth-stencil state and - // DSVFormat come from the stream PSO (or bound DSV), else disabled. Raster state comes from - // the stream RASTERIZER / RASTERIZER1 subobject, else solid fill, no culling, depth clip on. - desc.BlendState = blend; - if (use_depth_stencil) desc.DepthStencilState = bound.depth_stencil; - desc.SampleMask = ~0u; - desc.RasterizerState = bound.has_rasterizer ? bound.rasterizer : x2w_startup::default_pso_rasterizer(); - desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - desc.NumRenderTargets = pass.target_count; - for (UINT i = 0; i < pass.target_count; ++i) desc.RTVFormats[i] = pass.target_formats[i]; - desc.DSVFormat = dsv_format; - desc.SampleDesc.Count = 1; + x2w_startup::ComPtr geometry(indexed_rect ? translated_rect_geometry(tr, input) : nullptr); + if (indexed_rect && !geometry) return nullptr; + auto desc = input.state; + prepare_translated_pso_desc(input, geometry.Get(), desc); ID3D12PipelineState* pipeline = nullptr; X2W_ZONE("desktop pipeline creation"); - const HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); + const HRESULT hr = input.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d)", tr.key, pass.target_count, pass.target_count ? pass.target_formats[0] : 0, static_cast(hr), static_cast(dsv_format), desc.DepthStencilState.DepthEnable ? 1 : 0); check_device("translated CreateGraphicsPipelineState", 0); - bound.pipelines[key] = pipeline; + entry.pipeline = pipeline; + entry.complete = true; if (pipeline) { wchar_t path[MAX_PATH]; if (pso_recipe_path(path, tr.key)) { + const u64 key = x2w_startup::pso_state_key(pass.target_count, pass.target_formats, dsv_format, use_depth_stencil, + bound.depth_stencil, bound.has_rasterizer, bound.rasterizer, indexed_rect); const x2w_startup::PsoRecipe recipe = x2w_startup::make_pso_recipe( tr.key, key, indexed_rect, use_depth_stencil, bound.has_rasterizer, desc); if (!append_pso_recipe(path, recipe)) { From 824fb5cefdf1580ceabeed4e7505f094d35cb882 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:34:06 +0100 Subject: [PATCH 11/15] runtime: prepare translated graphics PSOs off the draw lock --- src/startup_stubs/d3d12_draw.inl | 300 +++++++++++++++++++------- src/startup_stubs/d3d12_xs_device.cpp | 37 ++-- 2 files changed, 243 insertions(+), 94 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index a9f81a3430..460b39767c 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -200,6 +200,7 @@ struct Translation : TranslationState { bool preparing = false; std::optional independent_indirect_entry; std::optional indexed_indirect_entry; + bool indexed_rect_geometry_preparing = false; bool indexed_rect_geometry_attempted = false; x2w_startup::ComPtr indexed_rect_geometry; int indirect_base_word = -1; @@ -224,7 +225,7 @@ struct PsoTargetSignature { }; struct PsoCacheKey { - const Wrapper* device; + Wrapper* device; const Translation* generation; PsoTargetSignature targets; @@ -301,6 +302,7 @@ bool find_blend(const std::vector& block, D3D12_BLEND_DESC* out, SRWLOCK draw_lock = SRWLOCK_INIT; CONDITION_VARIABLE graphics_translation_changed = CONDITION_VARIABLE_INIT; +CONDITION_VARIABLE graphics_pso_changed = CONDITION_VARIABLE_INIT; // Entries have stable addresses and are retained for the lifetime of the graphics cache. std::unordered_map& translation_by_pipeline() { static std::unordered_map m; return m; } std::unordered_map& translation_by_key() @@ -316,17 +318,19 @@ LONG pso_recipes_loaded, pso_recipes_precreated, pso_recipe_mismatches, pso_reci class GraphicsReservation { public: - explicit GraphicsReservation(bool& pending) : pending_(pending) { pending_ = true; } + explicit GraphicsReservation(bool& pending, CONDITION_VARIABLE& changed = graphics_translation_changed) + : pending_(pending), changed_(changed) { pending_ = true; } ~GraphicsReservation() { pending_ = false; - WakeAllConditionVariable(&graphics_translation_changed); + WakeAllConditionVariable(&changed_); } GraphicsReservation(const GraphicsReservation&) = delete; GraphicsReservation& operator=(const GraphicsReservation&) = delete; private: bool& pending_; + CONDITION_VARIABLE& changed_; }; class GraphicsLock { @@ -365,14 +369,15 @@ void wait_for_graphics_translation() SleepConditionVariableSRW(&graphics_translation_changed, &draw_lock, INFINITE, 0); } -HANDLE graphics_fixture_event(const wchar_t* variable, u64 key, DWORD access) +HANDLE graphics_fixture_event(const wchar_t* variable, u64 key, DWORD access, + const wchar_t* selector = L"X2W_TEST_GRAPHICS_KEY") { const DWORD saved = GetLastError(); const HANDLE event = [&]() -> HANDLE { wchar_t name[MAX_PATH], selected[17]; const DWORD length = GetEnvironmentVariableW(variable, name, MAX_PATH); if (!length || length >= MAX_PATH) return nullptr; - const DWORD filter = GetEnvironmentVariableW(L"X2W_TEST_GRAPHICS_KEY", selected, std::size(selected)); + const DWORD filter = GetEnvironmentVariableW(selector, selected, std::size(selected)); if (filter) { wchar_t expected[17]; swprintf(expected, std::size(expected), L"%016llx", key); @@ -384,9 +389,9 @@ HANDLE graphics_fixture_event(const wchar_t* variable, u64 key, DWORD access) return event; } -void signal_graphics_fixture(const wchar_t* variable, u64 key) +void signal_graphics_fixture(const wchar_t* variable, u64 key, const wchar_t* selector = L"X2W_TEST_GRAPHICS_KEY") { - if (HANDLE event = graphics_fixture_event(variable, key, EVENT_MODIFY_STATE)) { + if (HANDLE event = graphics_fixture_event(variable, key, EVENT_MODIFY_STATE, selector)) { SetEvent(event); CloseHandle(event); } @@ -406,11 +411,12 @@ void wait_for_graphics_key(u64 key) wait_for_graphics_translation(); } -bool pause_graphics_fixture(const wchar_t* gate, const wchar_t* entered, u64 key) +bool pause_graphics_fixture(const wchar_t* gate, const wchar_t* entered, u64 key, + const wchar_t* selector = L"X2W_TEST_GRAPHICS_KEY") { - HANDLE event = graphics_fixture_event(gate, key, SYNCHRONIZE); + HANDLE event = graphics_fixture_event(gate, key, SYNCHRONIZE, selector); if (!event) return false; - signal_graphics_fixture(entered, key); + signal_graphics_fixture(entered, key, selector); const DWORD result = WaitForSingleObject(event, 30000); CloseHandle(event); if (result != WAIT_OBJECT_0) throw std::runtime_error("graphics fixture gate timed out"); @@ -568,6 +574,7 @@ bool append_pso_recipe(const wchar_t* path, const x2w_startup::PsoRecipe& recipe HANDLE file = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) return false; + const std::unique_ptr owned_file(file, CloseHandle); LARGE_INTEGER size{}; bool ok = GetFileSizeEx(file, &size) && size.QuadPart >= 0 && static_cast(size.QuadPart) <= x2w_startup::pso_recipe_file_limit; @@ -596,7 +603,6 @@ bool append_pso_recipe(const wchar_t* path, const x2w_startup::PsoRecipe& recipe ok = WriteFile(file, record.data() + done, wanted, &written, nullptr) != 0 && written == wanted; done += written; } - CloseHandle(file); return ok && done == record.size(); } @@ -1740,6 +1746,10 @@ struct TranslatedPsoInput { std::copy_n(pass.target_formats, pass.target_count, state.RTVFormats); state.DSVFormat = dsv_format; state.SampleDesc.Count = 1; + for (std::size_t i = 0; i < recipe_keys.size(); ++i) { + recipe_keys[i] = x2w_startup::pso_state_key(state.NumRenderTargets, state.RTVFormats, state.DSVFormat, + use_depth_stencil, bound.depth_stencil, has_rasterizer, bound.rasterizer, i != 0); + } } TranslatedPsoInput(const TranslatedPsoInput&) = delete; TranslatedPsoInput& operator=(const TranslatedPsoInput&) = delete; @@ -1754,6 +1764,7 @@ struct TranslatedPsoInput { bool fixed_rectangle_on_disk; bool use_depth_stencil, has_rasterizer; D3D12_GRAPHICS_PIPELINE_STATE_DESC state{}; + std::array recipe_keys{}; }; x2w_startup::ComPtr prepare_translated_rect_geometry(const TranslatedPsoInput& input) @@ -1800,22 +1811,69 @@ void prepare_translated_pso_desc(const TranslatedPsoInput& input, ID3DBlob* geom if (geometry) desc.GS = {geometry->GetBufferPointer(), geometry->GetBufferSize()}; } -ID3DBlob* translated_rect_geometry(Translation& tr, const TranslatedPsoInput& input) +x2w_startup::ComPtr translated_rect_geometry(Translation& tr, const TranslatedPsoInput& input) { + // Called by a recipe or a PSO owner with draw_lock released. All callers for + // this generation share one geometry attempt, even across target signatures. + GraphicsLock lock; + while (tr.indexed_rect_geometry_preparing) + SleepConditionVariableSRW(&graphics_pso_changed, &draw_lock, INFINITE, 0); if (!tr.indexed_rect_geometry_attempted) { + GraphicsReservation reservation(tr.indexed_rect_geometry_preparing, graphics_pso_changed); + GraphicsUnlock unlocked; + auto geometry = prepare_translated_rect_geometry(input); + unlocked.reacquire(); + if (the_device != tr.ready_device) { + unlocked.release(); + return {}; + } + tr.indexed_rect_geometry = std::move(geometry); tr.indexed_rect_geometry_attempted = true; - tr.indexed_rect_geometry = prepare_translated_rect_geometry(input); } - return tr.indexed_rect_geometry.Get(); + return tr.indexed_rect_geometry; +} + +// These events are used only by the source-built PSO fixtures. They select a +// target signature so another signature using the same translation can proceed. +constexpr wchar_t pso_fixture_selector[] = L"X2W_TEST_GRAPHICS_PSO_TARGETS"; + +bool pause_translated_pso_fixture(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, bool recipe) +{ + static const bool enabled = [] { + const DWORD saved = GetLastError(); + const bool configured = GetEnvironmentVariableW(L"X2W_TEST_GRAPHICS_PSO_GATE", nullptr, 0) != 0; + SetLastError(saved); + return configured; + }(); + if (!enabled) return false; + const u64 key = x2w_startup::pso_targets_key(desc.NumRenderTargets, desc.RTVFormats, desc.DSVFormat); + return pause_graphics_fixture(L"X2W_TEST_GRAPHICS_PSO_GATE", + recipe ? L"X2W_TEST_GRAPHICS_PSO_REPLAY_ENTERED" : L"X2W_TEST_GRAPHICS_PSO_ENTERED", key, pso_fixture_selector); } +void wait_for_translated_pso(const PsoTargetSignature& targets) +{ + const u64 key = x2w_startup::pso_targets_key(targets.count, targets.formats.data(), targets.dsv); + signal_graphics_fixture(L"X2W_TEST_GRAPHICS_PSO_WAITER", key, pso_fixture_selector); + SleepConditionVariableSRW(&graphics_pso_changed, &draw_lock, INFINITE, 0); +} + +struct PsoReplayResult { + std::array, 2> states; + unsigned precreated = 0, mismatched = 0, failed = 0; + + bool attempted() const { return precreated || mismatched || failed; } +}; + // A recipe can only be used when its draw state and the pass match the recipe's key. Other records // in the same translation file stay on disk for a later pass and are ignored here. -bool replay_pso_recipes(PsoTargetCache& targets, Translation& tr, const TranslatedPsoInput& input) +PsoReplayResult replay_pso_recipes(const std::vector& recipes, + const std::array& complete, Translation& tr, + const TranslatedPsoInput& input) { - unsigned precreated = 0, mismatched = 0, failed = 0; + PsoReplayResult result; const auto& state = input.state; - for (const x2w_startup::PsoRecipe& recipe : tr.pso_recipes) { + for (const x2w_startup::PsoRecipe& recipe : recipes) { if (recipe.translation_key != input.translation_key || !x2w_startup::pso_recipe_targets_match(recipe, state.NumRenderTargets, state.RTVFormats, state.DSVFormat)) continue; @@ -1825,100 +1883,164 @@ bool replay_pso_recipes(PsoTargetCache& targets, Translation& tr, const Translat !x2w_startup::same_pso_rasterizer(recipe.rasterizer, state.RasterizerState) || !x2w_startup::same_pso_blend(recipe.blend, state.BlendState) || recipe.sample_count != 1 || recipe.sample_mask != ~0u || recipe.topology != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { - ++mismatched; + ++result.mismatched; continue; } - const u64 key = x2w_startup::pso_state_key(state.NumRenderTargets, state.RTVFormats, state.DSVFormat, - input.use_depth_stencil, state.DepthStencilState, input.has_rasterizer, - state.RasterizerState, recipe.indexed_rect); - if (key != recipe.state_key) { - ++mismatched; + if (input.recipe_keys[recipe.indexed_rect] != recipe.state_key) { + ++result.mismatched; continue; } - auto& entry = targets.states[recipe.indexed_rect]; - if (entry.complete) continue; - x2w_startup::ComPtr geometry(recipe.indexed_rect ? translated_rect_geometry(tr, input) : nullptr); + auto& pipeline = result.states[recipe.indexed_rect]; + if (complete[recipe.indexed_rect] || pipeline) continue; + auto geometry = recipe.indexed_rect ? translated_rect_geometry(tr, input) : x2w_startup::ComPtr{}; if (recipe.indexed_rect && !geometry) { - ++failed; + ++result.failed; continue; } D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; prepare_translated_pso_desc(input, geometry.Get(), desc); x2w_startup::apply_pso_recipe(recipe, desc); - ID3D12PipelineState* pipeline = nullptr; + pause_translated_pso_fixture(desc, true); X2W_ZONE("desktop pipeline creation from recipe"); const HRESULT hr = input.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); - check_device("translated CreateGraphicsPipelineState from recipe", 0); + check_device("translated CreateGraphicsPipelineState from recipe", 0, input.device.Get()); if (FAILED(hr) || !pipeline) { - if (pipeline) pipeline->Release(); - ++failed; + pipeline.Reset(); + ++result.failed; continue; } - entry.pipeline = pipeline; - entry.complete = true; - ++precreated; + ++result.precreated; } - if (precreated || mismatched || failed) { - log("x2w-draw pso recipes %016llx: precreated %u, mismatched %u, failed %u", tr.key, precreated, mismatched, failed); - InterlockedAdd(&pso_recipes_precreated, static_cast(precreated)); - InterlockedAdd(&pso_recipe_mismatches, static_cast(mismatched)); + if (result.attempted()) { + log("x2w-draw pso recipes %016llx: precreated %u, mismatched %u, failed %u", input.translation_key, + result.precreated, result.mismatched, result.failed); } - return precreated || mismatched || failed; + return result; } -ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const Pass& pass, bool indexed_rect) +x2w_startup::ComPtr create_translated_pso(const TranslatedPsoInput& input, + ID3DBlob* geometry, bool indexed_rect) { - if (tr.ready_device != the_device) return nullptr; - const DXGI_FORMAT dsv_format = pass_dsv_format(bound, pass); - // A state decoded from registers needs a depth view to act on; with none bound the pass keeps the desktop default. - const bool use_depth_stencil = bound.has_depth_stencil && (!bound.depth_from_registers || dsv_format != DXGI_FORMAT_UNKNOWN); - auto& targets = bound.pso_targets[{the_device, &tr, PsoTargetSignature(pass, dsv_format)}]; - auto& entry = targets.states[indexed_rect]; - if (entry.complete) return entry.pipeline; - GraphicsReservation reservation(entry.preparing); - D3D12_BLEND_DESC blend{}; - if (!effective_blend_state(bound, tr, pass.target_count, blend)) { - log("x2w-draw export write masks incompatible with shared logic op for %016llx", tr.key); - entry.complete = true; - return nullptr; - } - const TranslatedPsoInput input(device_of(the_device), tr, bound, pass, dsv_format, use_depth_stencil, blend); - if (!tr.pso_recipes.empty() && !targets.replayed) { - GraphicsReservation replay(targets.replaying); - const bool attempted = replay_pso_recipes(targets, tr, input); - targets.replayed = true; - if (entry.complete) return entry.pipeline; - if (attempted) InterlockedIncrement(&pso_recipe_fallbacks); - } - x2w_startup::ComPtr geometry(indexed_rect ? translated_rect_geometry(tr, input) : nullptr); - if (indexed_rect && !geometry) return nullptr; auto desc = input.state; - prepare_translated_pso_desc(input, geometry.Get(), desc); - ID3D12PipelineState* pipeline = nullptr; - X2W_ZONE("desktop pipeline creation"); - const HRESULT hr = input.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); - log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d)", tr.key, - pass.target_count, pass.target_count ? pass.target_formats[0] : 0, static_cast(hr), - static_cast(dsv_format), desc.DepthStencilState.DepthEnable ? 1 : 0); - check_device("translated CreateGraphicsPipelineState", 0); - entry.pipeline = pipeline; - entry.complete = true; + prepare_translated_pso_desc(input, geometry, desc); + x2w_startup::ComPtr pipeline; + const bool paused = pause_translated_pso_fixture(desc, false); + static LONG fixture_abandonments; + if (paused && x2w_local::env_on("X2W_TEST_GRAPHICS_PSO_ABANDON_ONCE") && first_calls(fixture_abandonments, 1)) + throw std::runtime_error("graphics PSO fixture abandoned the attempt"); + HRESULT hr = E_FAIL; + if (!paused || !x2w_local::env_on("X2W_TEST_GRAPHICS_PSO_FAIL")) { + X2W_ZONE("desktop pipeline creation"); + hr = input.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); + } + log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d)", input.translation_key, + desc.NumRenderTargets, desc.NumRenderTargets ? desc.RTVFormats[0] : 0, static_cast(hr), + static_cast(desc.DSVFormat), desc.DepthStencilState.DepthEnable ? 1 : 0); + check_device("translated CreateGraphicsPipelineState", 0, input.device.Get()); + if (FAILED(hr)) pipeline.Reset(); if (pipeline) { wchar_t path[MAX_PATH]; - if (pso_recipe_path(path, tr.key)) { - const u64 key = x2w_startup::pso_state_key(pass.target_count, pass.target_formats, dsv_format, use_depth_stencil, - bound.depth_stencil, bound.has_rasterizer, bound.rasterizer, indexed_rect); + if (pso_recipe_path(path, input.translation_key)) { const x2w_startup::PsoRecipe recipe = x2w_startup::make_pso_recipe( - tr.key, key, indexed_rect, use_depth_stencil, bound.has_rasterizer, desc); - if (!append_pso_recipe(path, recipe)) { + input.translation_key, input.recipe_keys[indexed_rect], indexed_rect, input.use_depth_stencil, input.has_rasterizer, desc); + bool written = false; + try { + // All local appends use the existing exclusive file open. This mutex + // avoids local writers racing for it while keeping I/O off draw_lock. + static std::mutex appends; + const std::lock_guard lock(appends); + written = append_pso_recipe(path, recipe); + } catch (...) { + // A recipe is diagnostic cache data. Keep the driver's successful PSO. + } + if (!written) { static LONG logged; - if (first_calls(logged, 16)) log("x2w-draw pso recipe for %016llx was not written (directory, size limit or I/O)", tr.key); + if (first_calls(logged, 16)) log("x2w-draw pso recipe for %016llx was not written (directory, size limit or I/O)", input.translation_key); } } } return pipeline; } +// Called with draw_lock held after draw eligibility and heap checks. Only the +// owner of a recording can mutate its Pass. Cache entries outlive this call. +ID3D12PipelineState* pipeline_for(Wrapper* self, ID3D12GraphicsCommandList* list, BoundPipeline& bound, + Translation& tr, const Pass& pass, bool indexed_rect, bool& yielded) +{ + const PsoCacheKey key{self->own().list_device, &tr, PsoTargetSignature(pass, pass_dsv_format(bound, pass))}; + if (tr.ready_device != key.device) return nullptr; + const auto* const guest_pipeline = pass.pipeline; + const UINT topology = pass.topology; + const auto current = [&] { + return the_device == key.device && tr.ready_device == key.device && self->own().list_device == key.device && + recording(self) == list && self->own().pass == &pass && pass.pipeline == guest_pipeline && + pass.topology == topology && pass.targets_bound && key.targets == PsoTargetSignature(pass, pass_dsv_format(bound, pass)); + }; + try { + auto& targets = bound.pso_targets[key]; + auto& entry = targets.states[indexed_rect]; + while (!entry.complete && (entry.preparing || targets.replaying)) { + yielded = true; + wait_for_translated_pso(key.targets); + if (!current()) return nullptr; + } + if (entry.complete) return entry.pipeline; + GraphicsReservation reservation(entry.preparing, graphics_pso_changed); + D3D12_BLEND_DESC blend{}; + if (!effective_blend_state(bound, tr, key.targets.count, blend)) { + log("x2w-draw export write masks incompatible with shared logic op for %016llx", tr.key); + entry.complete = true; + return nullptr; + } + // Register depth state has no effect without a DSV. + const bool use_depth_stencil = bound.has_depth_stencil && (!bound.depth_from_registers || key.targets.dsv != DXGI_FORMAT_UNKNOWN); + const TranslatedPsoInput input(device_of(key.device), tr, bound, pass, key.targets.dsv, use_depth_stencil, blend); + if (!tr.pso_recipes.empty() && !targets.replayed) { + GraphicsReservation replay(targets.replaying, graphics_pso_changed); + const auto recipes = tr.pso_recipes; + const std::array complete{targets.states[0].complete, targets.states[1].complete}; + yielded = true; + GraphicsUnlock unlocked; + auto result = replay_pso_recipes(recipes, complete, tr, input); + unlocked.reacquire(); + if (!current()) { + unlocked.release(); + return nullptr; + } + for (std::size_t i = 0; i < result.states.size(); ++i) { + if (!result.states[i]) continue; + targets.states[i].pipeline = result.states[i].Detach(); + targets.states[i].complete = true; + } + targets.replayed = true; + if (result.attempted()) { + InterlockedAdd(&pso_recipes_precreated, static_cast(result.precreated)); + InterlockedAdd(&pso_recipe_mismatches, static_cast(result.mismatched)); + } + if (entry.complete) return entry.pipeline; + if (result.attempted()) InterlockedIncrement(&pso_recipe_fallbacks); + } + yielded = true; + GraphicsUnlock unlocked; + auto geometry = indexed_rect ? translated_rect_geometry(tr, input) : x2w_startup::ComPtr{}; + if (indexed_rect && !geometry) return nullptr; + auto pipeline = create_translated_pso(input, geometry.Get(), indexed_rect); + geometry.Reset(); + unlocked.reacquire(); + if (!current()) { + unlocked.release(); + return nullptr; + } + entry.pipeline = pipeline.Detach(); + entry.complete = true; + return entry.pipeline; + } catch (...) { + // Reservations clear and wake after the unlock guard restores draw_lock. + log("x2w-draw desktop pipeline preparation for %016llx interrupted", tr.key); + return nullptr; + } +} + // Private shader-visible heap for the translated draws' tables, used as a ring. constexpr UINT draw_heap_size = 1u << 18; ID3D12DescriptorHeap* draw_heap; @@ -3582,7 +3704,23 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } } const bool geometry_rect = indexed_rect || (rect && fixed_stream); - ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass, geometry_rect) : nullptr; + bool pso_yielded = false; + ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) + ? pipeline_for(self, list, *bound, *tr, pass, geometry_rect, pso_yielded) : nullptr; + if (pipeline && pso_yielded) { + // A fixed vertex view is already retained or copied by this recording. + // Recheck the table facts that can have changed while other lists ran. + std::fill(std::begin(d16_unorm16), std::end(d16_unorm16), 0u); + std::fill(std::begin(formatted_buffers), std::end(formatted_buffers), FormattedBufferDescriptor{}); + const bool current_d16 = d16_srvs_ready(*tr, pass, d16_unorm16); + if (!current_d16 || !formatted_buffers_ready(*tr, pass, formatted_buffers)) { + if (indirect) indirect->refusal_code = current_d16 ? indirect_refusal_code::formatted_buffer_not_ready + : indirect_refusal_code::d16_srv_not_ready; + note_draw_refusal(tr->key, current_d16 ? "formatted buffer not ready" : "d16 texture view not ready"); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + } if (indirect && indexed_rect && !pipeline) { indirect->set_refusal("translated indexed rectangle geometry unavailable", indirect_refusal_code::indexed_rect_unavailable); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index bc39e802a3..196ce68408 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -105,6 +105,7 @@ #include #include +#include #include #include #include @@ -448,35 +449,37 @@ bool first_calls(LONG& counter, LONG limit = 3) { return x2w_local::first_calls( // X2W_D3D12_DEBUG=1: the desktop debug layer's messages are drained into the log after forwarded // calls, tagged with the call that preceded them, and a device removal is reported once with its reason. -ID3D12InfoQueue* info_queue; -ID3D12Device* removal_device; +std::atomic info_queue; +std::atomic removal_device; LONG removal_reported, debug_lines; SRWLOCK debug_lock = SRWLOCK_INIT; -void check_device(const char* context, int slot) +void check_device(const char* context, int slot, ID3D12Device* pinned = nullptr) { - if (removal_device && !removal_reported) { - const HRESULT reason = removal_device->GetDeviceRemovedReason(); + auto* device = pinned ? pinned : removal_device.load(); + if (device && !InterlockedCompareExchange(&removal_reported, 0, 0)) { + const HRESULT reason = device->GetDeviceRemovedReason(); if (reason != S_OK && InterlockedExchange(&removal_reported, 1) == 0) log("x2w-d3d12 DEVICE REMOVED, reason 0x%08lx, first noticed after %s %d", static_cast(reason), context, slot); } - if (!info_queue) return; + if (!info_queue.load()) return; AcquireSRWLockExclusive(&debug_lock); - const UINT64 count = info_queue->GetNumStoredMessages(); + auto* queue = info_queue.load(); + const UINT64 count = queue->GetNumStoredMessages(); for (UINT64 i = 0; i < count && debug_lines < 400; ++i) { SIZE_T size = 0; - info_queue->GetMessage(i, nullptr, &size); + queue->GetMessage(i, nullptr, &size); if (!size || size > 8192) continue; alignas(16) char storage[8192]; auto* message = reinterpret_cast(storage); - if (SUCCEEDED(info_queue->GetMessage(i, message, &size))) { + if (SUCCEEDED(queue->GetMessage(i, message, &size))) { ++debug_lines; log("x2w-d3d12-debug [%s %d] sev=%d id=%d %.900s", context, slot, message->Severity, message->ID, message->pDescription); } } - info_queue->ClearStoredMessages(); + queue->ClearStoredMessages(); ReleaseSRWLockExclusive(&debug_lock); } @@ -5591,7 +5594,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) args[1] = reinterpret_cast(&null_rtv); } if (default_view) args[desc_index] = 0; - const LONG removed_before = removal_reported; + const LONG removed_before = InterlockedCompareExchange(&removal_reported, 0, 0); const u64 result = method_of(self->own().real, N)(self->own().real, args[0], args[1], args[2], args[3], 0, 0, 0, 0); // A desktop view creation returns void, so the only failure it reports is a removed device. Only a created view // may keep the resource: on failure the slot is recorded unmaterialized, which releases the slot's previous view @@ -5608,7 +5611,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) if ((N == 20 || N == 21) && args[0] && created) note_view_target(args[D], reinterpret_cast(args[0]), N); check_device("Device view", N); - if (!removed_before && removal_reported && N >= 18 && N <= 21) { + if (!removed_before && InterlockedCompareExchange(&removal_reported, 0, 0) && N >= 18 && N <= 21) { // The view that removed the device: its forwarded description and the resource's shape. char bytes[3 * 40 + 1] = {}; const u64 described = args[desc_index]; @@ -8440,6 +8443,14 @@ HRESULT x2w_d3d12_permissive_create_device(IUnknown* adapter, const void* parame if (FAILED(hr)) return hr; x2w_startup::attach_device(device, out); if (!*out) return E_OUTOFMEMORY; - if (debug) device->QueryInterface(IID_PPV_ARGS(&info_queue)); + if (debug) { + ID3D12InfoQueue* queue = nullptr; + if (SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&queue)))) { + AcquireSRWLockExclusive(&debug_lock); + auto* previous = info_queue.exchange(queue); + ReleaseSRWLockExclusive(&debug_lock); + if (previous) previous->Release(); + } + } return S_OK; } From f2bbcb2b50e9243864e9f559ec44b9c8fa217eaf Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:39:56 +0100 Subject: [PATCH 12/15] test: exercise translated PSO publication on WARP and hardware --- tests/cmake/startup_graphics_pso_load.cmake | 8 + tests/startup_indirect_draw_indexed.cpp | 250 ++++++++++++++++++-- 2 files changed, 237 insertions(+), 21 deletions(-) create mode 100644 tests/cmake/startup_graphics_pso_load.cmake diff --git a/tests/cmake/startup_graphics_pso_load.cmake b/tests/cmake/startup_graphics_pso_load.cmake new file mode 100644 index 0000000000..e2b452b7e0 --- /dev/null +++ b/tests/cmake/startup_graphics_pso_load.cmake @@ -0,0 +1,8 @@ +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS unlock concurrent) + add_test(NAME startup_graphics_pso_load_${mode}_${backend} + COMMAND startup_indirect_draw_indexed ${backend} graphics-pso-${mode}) + set_tests_properties(startup_graphics_pso_load_${mode}_${backend} + PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endforeach() diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index b35384b0d0..1eb02e49f5 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -8,6 +8,7 @@ #include "xmem_section_lease.h" #include "startup_stubs/rect_indirect_args.h" #include "startup_stubs/mesh57_profile.h" +#include "startup_stubs/pso_recipe.h" #include "startup_indirect_mesh_mesh.h" #include "startup_indirect_mesh_amplify.h" #include "startup_indirect_mesh_amplified_mesh.h" @@ -1866,7 +1867,8 @@ bool check_translated_targets(ID3D12Device* device, ID3D12Device* guest, ID3D12R // Only DrawInstanced and the submit probe run on the racing threads. struct GraphicsPublicationDraw { GraphicsPublicationDraw(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, - IUnknown* pipeline, const TranslatedDrawFixture& binding, DXGI_FORMAT target_format = format) + IUnknown* pipeline, const TranslatedDrawFixture& binding, DXGI_FORMAT target_format = format, + DXGI_FORMAT depth_format = DXGI_FORMAT_UNKNOWN) { const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, target_format, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; @@ -1876,6 +1878,22 @@ struct GraphicsPublicationDraw { check(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap)), "create publication RTV heap"); const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); guest->CreateRenderTargetView(target.Get(), nullptr, rtv); + D3D12_CPU_DESCRIPTOR_HANDLE dsv{}, native_dsv{}; + if (depth_format != DXGI_FORMAT_UNKNOWN) { + auto depth_desc = desc; + depth_desc.Format = depth_format; + depth_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + D3D12_CLEAR_VALUE depth_clear{}; + depth_clear.Format = depth_format; + depth_clear.DepthStencil.Depth = 1.0f; + depth = resource(device, depth_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &depth_clear); + const D3D12_DESCRIPTOR_HEAP_DESC dsv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + check(guest->CreateDescriptorHeap(&dsv_desc, IID_PPV_ARGS(&dsv_heap)), "create publication DSV heap"); + dsv.ptr = slot(dsv_heap.Get(), 9)(dsv_heap.Get(), nullptr); + native_dsv = native_object(device, guest, dsv_heap.Get())->GetCPUDescriptorHandleForHeapStart(); + const D3D12_DEPTH_STENCIL_VIEW_DESC view{depth_format, D3D12_DSV_DIMENSION_TEXTURE2D}; + guest->CreateDepthStencilView(depth.Get(), &view, dsv); + } check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "create publication allocator"); list = begin_guest_list(guest, allocator.Get()); @@ -1892,7 +1910,9 @@ struct GraphicsPublicationDraw { slot(w, 21)(w, 1, &viewport); slot(w, 22)(w, 1, &scissor); slot(w, 50)(w, 1, &rtv, FALSE, nullptr); + const D3D12_CPU_DESCRIPTOR_HANDLE*)>(w, 50)(w, 1, &rtv, FALSE, depth ? &dsv : nullptr); + if (depth) native_object(device, guest, w)->ClearDepthStencilView( + native_dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); slot(w, 52)( w, rtv.ptr, clear.Color, 0, nullptr); } @@ -1941,35 +1961,49 @@ struct GraphicsPublicationDraw { return match; } - ComPtr target; - ComPtr rtv_heap; + ComPtr target, depth; + ComPtr rtv_heap, dsv_heap; ComPtr allocator; ComPtr list; }; +enum class GraphicsGate { translation, pso, pso_recipe }; + struct GraphicsPublicationGate { using Event = std::unique_ptr; - GraphicsPublicationGate(std::uint64_t key, bool interrupt) + GraphicsPublicationGate(std::uint64_t key, bool interrupt, GraphicsGate stage = GraphicsGate::translation, + bool abandon_once = false) + : stage(stage), gate_variable(stage == GraphicsGate::translation ? "X2W_TEST_PUBLISHED_GRAPHICS_GATE" : "X2W_TEST_GRAPHICS_PSO_GATE"), + entered_variable(stage == GraphicsGate::translation ? "X2W_TEST_PUBLISHED_GRAPHICS_ENTERED" : + stage == GraphicsGate::pso ? "X2W_TEST_GRAPHICS_PSO_ENTERED" : "X2W_TEST_GRAPHICS_PSO_REPLAY_ENTERED"), + waiter_variable(stage == GraphicsGate::translation ? "X2W_TEST_PUBLISHED_GRAPHICS_WAITER" : "X2W_TEST_GRAPHICS_PSO_WAITER"), + selector(stage == GraphicsGate::translation ? "X2W_TEST_GRAPHICS_KEY" : "X2W_TEST_GRAPHICS_PSO_TARGETS") { const auto key_name = fixture_key_name(key); const auto prefix = "Local\\X2WGraphicsPublication." + std::to_string(GetCurrentProcessId()) + "." + key_name; - release.reset(named_event(prefix + ".release", "X2W_TEST_PUBLISHED_GRAPHICS_GATE")); - entered.reset(named_event(prefix + ".entered", "X2W_TEST_PUBLISHED_GRAPHICS_ENTERED")); - waiter.reset(named_event(prefix + ".waiter", "X2W_TEST_PUBLISHED_GRAPHICS_WAITER")); - check(SetEnvironmentVariableA("X2W_TEST_GRAPHICS_KEY", key_name.c_str()) && - SetEnvironmentVariableA("X2W_TEST_PUBLISHED_GRAPHICS_EXCEPTION", interrupt ? "1" : "0") + release.reset(named_event(prefix + ".release", gate_variable)); + entered.reset(named_event(prefix + ".entered", entered_variable)); + waiter.reset(named_event(prefix + ".waiter", waiter_variable)); + check(SetEnvironmentVariableA(selector, key_name.c_str()) && + SetEnvironmentVariableA(stage == GraphicsGate::translation ? "X2W_TEST_PUBLISHED_GRAPHICS_EXCEPTION" : + "X2W_TEST_GRAPHICS_PSO_FAIL", interrupt ? "1" : "0") ? S_OK : E_FAIL, "select publication gate key and outcome"); + if (abandon_once) + check(SetEnvironmentVariableA("X2W_TEST_GRAPHICS_PSO_ABANDON_ONCE", "1") ? S_OK : E_FAIL, + "abandon the first gated PSO attempt"); } ~GraphicsPublicationGate() { finish(); - SetEnvironmentVariableA("X2W_TEST_PUBLISHED_GRAPHICS_GATE", nullptr); - SetEnvironmentVariableA("X2W_TEST_PUBLISHED_GRAPHICS_ENTERED", nullptr); - SetEnvironmentVariableA("X2W_TEST_PUBLISHED_GRAPHICS_WAITER", nullptr); - SetEnvironmentVariableA("X2W_TEST_PUBLISHED_GRAPHICS_EXCEPTION", nullptr); - SetEnvironmentVariableA("X2W_TEST_GRAPHICS_KEY", nullptr); + SetEnvironmentVariableA(gate_variable, nullptr); + SetEnvironmentVariableA(entered_variable, nullptr); + SetEnvironmentVariableA(waiter_variable, nullptr); + SetEnvironmentVariableA(stage == GraphicsGate::translation ? "X2W_TEST_PUBLISHED_GRAPHICS_EXCEPTION" : + "X2W_TEST_GRAPHICS_PSO_FAIL", nullptr); + if (stage != GraphicsGate::translation) SetEnvironmentVariableA("X2W_TEST_GRAPHICS_PSO_ABANDON_ONCE", nullptr); + SetEnvironmentVariableA(selector, nullptr); } void finish() @@ -1987,6 +2021,11 @@ struct GraphicsPublicationGate { return event.release(); } + GraphicsGate stage; + const char* gate_variable; + const char* entered_variable; + const char* waiter_variable; + const char* selector; Event release{nullptr, CloseHandle}, entered{nullptr, CloseHandle}, waiter{nullptr, CloseHandle}; std::thread owner, peer, witness; }; @@ -1994,7 +2033,9 @@ struct GraphicsPublicationGate { bool race_graphics_draws(ID3D12Device* device, ID3D12Device* guest, std::uint64_t key, const GraphicsPublicationDraw& first, const GraphicsPublicationDraw& second, bool same_key, std::uint32_t first_pixel, std::uint32_t second_pixel, bool interrupt = false, - const GraphicsPublicationDraw* other_targets = nullptr) + const GraphicsPublicationDraw* other_targets = nullptr, + GraphicsGate stage = GraphicsGate::translation, std::uint32_t other_pixel = 0x3f800000, + bool abandon_once = false) { const D3D12_COMMAND_QUEUE_DESC queue_desc{}; ComPtr queue; @@ -2020,7 +2061,7 @@ bool race_graphics_draws(ID3D12Device* device, ID3D12Device* guest, std::uint64_ check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&submitted)), "create submit probe fence"); constexpr DWORD wait_ms = 10000; - GraphicsPublicationGate gate(key, interrupt); + GraphicsPublicationGate gate(key, interrupt, stage, abandon_once); gate.owner = std::thread([&] { first.draw(); }); if (WaitForSingleObject(gate.entered.get(), wait_ms) != WAIT_OBJECT_0 || WaitForSingleObject(gate.owner.native_handle(), 0) != WAIT_TIMEOUT) { @@ -2064,9 +2105,14 @@ bool race_graphics_draws(ID3D12Device* device, ID3D12Device* guest, std::uint64_ if (WaitForSingleObject(gate.entered.get(), 0) != WAIT_TIMEOUT || WaitForSingleObject(gate.owner.native_handle(), 0) != WAIT_TIMEOUT) return false; gate.finish(); + if (stage != GraphicsGate::translation && + WaitForSingleObject(gate.entered.get(), 0) != (abandon_once ? WAIT_OBJECT_0 : WAIT_TIMEOUT)) { + std::fprintf(stderr, "unexpected PSO retry outcome after its gate opened\n"); + return false; + } return first.verify(device, queue.Get(), desktop_queue.Get(), first_pixel) && second.verify(device, queue.Get(), desktop_queue.Get(), second_pixel) && - (!other_targets || other_targets->verify(device, queue.Get(), desktop_queue.Get(), 0x3f800000)); + (!other_targets || other_targets->verify(device, queue.Get(), desktop_queue.Get(), other_pixel)); } std::uint64_t publish_graphics_variant(const std::filesystem::path& cache, std::uint64_t base, DXGI_FORMAT target_format) @@ -2240,6 +2286,151 @@ bool check_graphics_publication(IDXGIAdapter1* adapter, ID3D12Device* device, ID return ok; } +enum class FixturePsoState { baseline, blend, depth, raster }; + +ComPtr translated_stream_pso(ID3D12Device* guest, ID3D12RootSignature* root, ID3DBlob* vs, ID3DBlob* ps, + FixturePsoState state) +{ + struct { + Subobject root; + Subobject vs; + Subobject ps; + Subobject blend; + Subobject depth; + Subobject raster; + } stream; + static_assert(sizeof(stream) == 16 + 24 + 24 + 336 + 56 + 48); + stream.root.value = root; + stream.vs.value = {vs->GetBufferPointer(), vs->GetBufferSize()}; + stream.ps.value = {ps->GetBufferPointer(), ps->GetBufferSize()}; + stream.blend.value = x2w_startup::default_pso_blend(); + if (state == FixturePsoState::blend) { + auto& blend = stream.blend.value.RenderTarget[0]; + blend.BlendEnable = TRUE; + blend.SrcBlend = D3D12_BLEND_ZERO; + blend.DestBlend = D3D12_BLEND_ONE; + } + stream.depth.value = x2w_startup::default_pso_depth(); + stream.depth.value.DepthEnable = TRUE; + stream.depth.value.DepthFunc = state == FixturePsoState::depth ? D3D12_COMPARISON_FUNC_NEVER : D3D12_COMPARISON_FUNC_ALWAYS; + stream.raster.value = x2w_startup::default_pso_rasterizer(); + if (state == FixturePsoState::raster) stream.raster.value.CullMode = D3D12_CULL_MODE_FRONT; + // This root has a descriptor table, so slot 86 selects graphics translation. + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + using Create = HRESULT (WINAPI*)(IUnknown*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); + ComPtr pipeline; + check(slot(guest, 86)(guest, &desc, __uuidof(ID3D12PipelineState), + reinterpret_cast(pipeline.GetAddressOf())), "create translated stream state fixture"); + return pipeline; +} + +void seed_pso_recipes(const std::filesystem::path& cache, std::uint64_t key) +{ + x2w_startup::PsoRecipe hit; + hit.translation_key = key; + hit.target_count = 1; + hit.target_formats[0] = format; + hit.blend = x2w_startup::default_pso_blend(); + hit.depth_stencil = x2w_startup::default_pso_depth(); + hit.rasterizer = x2w_startup::default_pso_rasterizer(); + hit.state_key = x2w_startup::pso_recipe_state_key(hit); + auto mismatch = hit; + mismatch.dsv_format = DXGI_FORMAT_D16_UNORM; + mismatch.blend.RenderTarget[0].RenderTargetWriteMask = 0; + mismatch.state_key = x2w_startup::pso_recipe_state_key(mismatch); + std::ofstream file(cache / ("pso_" + fixture_key_name(key) + ".txt"), std::ios::binary); + file << x2w_startup::serialize_pso_recipe(hit) << x2w_startup::serialize_pso_recipe(mismatch); + check(file.good() ? S_OK : E_FAIL, "seed matching and mismatched graphics PSO recipes"); +} + +bool check_graphics_pso_load(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, ID3DBlob* blob, + const std::filesystem::path& cache, const std::wstring& log_path, bool concurrent) +{ + constexpr auto d16 = DXGI_FORMAT_D16_UNORM; + constexpr auto bgra = DXGI_FORMAT_B8G8R8A8_UNORM; + const auto gate_key = x2w_startup::pso_targets_key(1, &format, DXGI_FORMAT_UNKNOWN); + std::uint64_t base_key = 0; + const auto base = translated_pipeline(guest, root, blob, false, TableSample::texture, false, false, &base_key); + const TranslatedDrawFixture red_binding(guest, red), green_binding(guest, green); + const GraphicsPublicationDraw first(device, guest, root, base.Get(), red_binding); + const GraphicsPublicationDraw depth_target(device, guest, root, base.Get(), green_binding, format, d16); + std::uint64_t recipe_key = 0, stream_key = 0; + if (!concurrent) { + if (!race_graphics_draws(device, guest, gate_key, first, depth_target, false, red, green, false, nullptr, + GraphicsGate::pso)) return false; + } else { + const GraphicsPublicationDraw peer(device, guest, root, base.Get(), green_binding); + if (!race_graphics_draws(device, guest, gate_key, first, peer, true, red, green, false, &depth_target, + GraphicsGate::pso, green)) return false; + + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr queue; + check(guest->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), + reinterpret_cast(queue.GetAddressOf())), "create PSO coverage queue"); + const auto desktop_queue = native_object(device, guest, queue.Get()); + const auto verify = [&](const GraphicsPublicationDraw& draw, std::uint32_t expected) { + draw.draw(); + return draw.verify(device, queue.Get(), desktop_queue.Get(), expected); + }; + const GraphicsPublicationDraw other_rtv(device, guest, root, base.Get(), red_binding, bgra, d16); + if (!verify(other_rtv, 0xffff0000)) return false; + + const auto failing = translated_pipeline(guest, root, blob, false); + const GraphicsPublicationDraw failed_a(device, guest, root, failing.Get(), red_binding); + const GraphicsPublicationDraw failed_b(device, guest, root, failing.Get(), green_binding); + const GraphicsPublicationDraw cached_failure(device, guest, root, failing.Get(), red_binding); + if (!race_graphics_draws(device, guest, gate_key, failed_a, failed_b, true, black, black, true, nullptr, + GraphicsGate::pso) || !verify(cached_failure, black)) return false; + + const auto abandoned = translated_pipeline(guest, root, blob, false); + const GraphicsPublicationDraw abandoned_a(device, guest, root, abandoned.Get(), red_binding); + const GraphicsPublicationDraw abandoned_b(device, guest, root, abandoned.Get(), green_binding); + if (!race_graphics_draws(device, guest, gate_key, abandoned_a, abandoned_b, true, black, green, false, nullptr, + GraphicsGate::pso, 0, true)) return false; + + const auto recipe = translated_pipeline(guest, root, blob, true, TableSample::texture, false, false, &recipe_key); + seed_pso_recipes(cache, recipe_key); + const GraphicsPublicationDraw replay_a(device, guest, root, recipe.Get(), red_binding); + const GraphicsPublicationDraw replay_b(device, guest, root, recipe.Get(), green_binding); + const GraphicsPublicationDraw mismatch(device, guest, root, recipe.Get(), green_binding, format, d16); + if (!race_graphics_draws(device, guest, gate_key, replay_a, replay_b, true, red, green, false, &mismatch, + GraphicsGate::pso_recipe, green)) return false; + + const auto vs = compile("translated_vertex", "vs_5_1"), ps = compile("translated_pixel", "ps_5_1"); + constexpr char revision[] = "x2w-startup-shader-29"; + stream_key = fixture_hash(revision, sizeof(revision) - 1); + for (const auto& code : {vs.Get(), ps.Get(), blob}) + stream_key = fixture_hash(code->GetBufferPointer(), code->GetBufferSize(), stream_key); + for (const char* suffix : {".txt", ".vs.cso", ".ps.cso"}) { + std::filesystem::copy_file(cache / (fixture_key_name(base_key) + suffix), cache / (fixture_key_name(stream_key) + suffix)); + } + for (const auto state : {FixturePsoState::baseline, FixturePsoState::blend, FixturePsoState::depth, FixturePsoState::raster}) { + const auto pso = translated_stream_pso(guest, root, vs.Get(), ps.Get(), state); + const GraphicsPublicationDraw draw(device, guest, root, pso.Get(), red_binding, format, d16); + if (!verify(draw, state == FixturePsoState::baseline ? red : black)) { + std::fprintf(stderr, "translated stream PSO state %u produced unexpected pixels\n", static_cast(state)); + return false; + } + } + } + + std::ifstream input(std::filesystem::path(log_path), std::ios::binary); + const std::string log{std::istreambuf_iterator(input), std::istreambuf_iterator()}; + const auto count = [&](const std::string& query) { + unsigned matches = 0; + for (std::size_t at = 0; (at = log.find(query, at)) != std::string::npos; at += query.size()) ++matches; + return matches; + }; + const auto creates = [&](std::uint64_t key) { return count("desktop pipeline for " + fixture_key_name(key) + ", "); }; + const auto replay_log = "pso recipes " + fixture_key_name(recipe_key) + ": precreated "; + const bool ok = concurrent ? creates(base_key) == 5 && creates(recipe_key) == 1 && creates(stream_key) == 4 && + count(replay_log + "1, mismatched 0, failed 0") == 1 && count(replay_log + "0, mismatched 1, failed 0") == 1 && + count("desktop pipeline preparation for " + fixture_key_name(base_key) + " interrupted") == 1 + : creates(base_key) == 2; + if (!ok) std::fprintf(stderr, "unexpected translated PSO create or recipe replay count\n"); + return ok; +} + bool check_indirect_other_refusal_census(const std::wstring& log_path) { const std::size_t needed = x2w_d3d12_census_report(nullptr, 0); @@ -3261,7 +3452,9 @@ int main(int argc, char** argv) try const bool native_graphics_backoff = argc == 3 && std::strcmp(argv[2], "graphics-publication-native-backoff") == 0; const bool graphics_publication = graphics_concurrent || native_graphics_backoff || (argc == 3 && std::strcmp(argv[2], "graphics-publication-unlock") == 0); - if (graphics_publication) { + const bool pso_concurrent = argc == 3 && std::strcmp(argv[2], "graphics-pso-concurrent") == 0; + const bool pso_load = pso_concurrent || (argc == 3 && std::strcmp(argv[2], "graphics-pso-unlock") == 0); + if (graphics_publication || pso_load) { // The native backoff fixture exits at the gate before it needs a DXC directory. SetEnvironmentVariableA("X2W_NATIVE_SHADERS", native_graphics_backoff ? "." : nullptr); SetEnvironmentVariableA("X2W_NATIVE_SHADERS_ONLY", native_graphics_backoff ? "1" : "0"); @@ -3295,7 +3488,7 @@ int main(int argc, char** argv) try const bool alias_disabled = argc == 3 && std::strcmp(argv[2], "translated-indexed-alias-off") == 0; const bool alias_index = alias_disabled || (argc == 3 && std::strcmp(argv[2], "translated-indexed-alias") == 0); const bool translated_indexed = alias_index || upload_index || rect || (argc == 3 && std::strcmp(argv[2], "translated-indexed") == 0); - const bool translated = copy_on || copy_off || refusal_census || other_refusal_census || translated_targets || graphics_publication || + const bool translated = copy_on || copy_off || refusal_census || other_refusal_census || translated_targets || graphics_publication || pso_load || fallback_fixture || translated_indexed || (argc == 3 && std::strcmp(argv[2], "translated") == 0); // "count-control" is the negative control: it expects one forwarded call too many. const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; @@ -3340,7 +3533,7 @@ int main(int argc, char** argv) try wchar_t directory[MAX_PATH]; if (!GetTempPathW(MAX_PATH, directory)) return 4; const std::wstring log_path = std::wstring(directory) + L"x2w_indirect_counts_" + std::to_wstring(GetCurrentProcessId()) + L".log"; - if (indexed || lease_arguments || dual_lease || loose_root || refusal_census || other_refusal_census || graphics_publication) { + if (indexed || lease_arguments || dual_lease || loose_root || refusal_census || other_refusal_census || graphics_publication || pso_load) { DeleteFileW(log_path.c_str()); SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); SetEnvironmentVariableA("X2W_PRESENT_SIGNATURE_EVERY", "0"); @@ -3684,6 +3877,21 @@ int main(int argc, char** argv) try const D3D12_ROOT_SIGNATURE_DESC title_desc{1, &table, 0, nullptr, root_flags}; ComPtr root_blob; const auto title_root = create_root(guest.Get(), title_desc, &root_blob); + if (pso_load) { + if (pso_concurrent) + check(SetEnvironmentVariableW(L"X2W_PSO_RECIPE_DIR", cache.c_str()) ? S_OK : E_FAIL, + "configure translated PSO recipes"); + else + SetEnvironmentVariableW(L"X2W_PSO_RECIPE_DIR", nullptr); + const bool ok = check_graphics_pso_load(device.Get(), guest.Get(), title_root.Get(), root_blob.Get(), + cache, log_path, pso_concurrent); + if (ok && (!info || !info->GetNumStoredMessages())) { + std::filesystem::remove_all(cache); + DeleteFileW(log_path.c_str()); + return 0; + } + return 1; + } if (graphics_publication) { const bool ok = native_graphics_backoff ? check_native_graphics_backoff(device.Get(), guest.Get(), title_root.Get(), root_blob.Get()) From 0b32e1c72f2fa303eafbdfa0a8bea3b3236a0ab3 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:40:21 +0100 Subject: [PATCH 13/15] docs: describe translated PSO preparation and gated fixtures --- docs/experiments/startup-pso-recipe.md | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/docs/experiments/startup-pso-recipe.md b/docs/experiments/startup-pso-recipe.md index 266c2adefa..72330005c7 100644 --- a/docs/experiments/startup-pso-recipe.md +++ b/docs/experiments/startup-pso-recipe.md @@ -35,6 +35,35 @@ reaches the append path while the file is owned keeps the PSO it already created cache write; a reader denied by that handle also falls back to the unchanged creation path. Neither side can seek to an end offset that another writer selected. +## First use during recording + +A translated draw reserves its PSO after the existing eligibility and descriptor heap checks. The +recording thread retains the device, root signature, shader blobs and input layout for preparation. +It releases the draw lock while it creates the PSO, prepares rectangle geometry, replays recipes and +writes any new recipe record. Appends from threads in the same process take a separate mutex. + +Recordings that need the same PSO wait for its reservation to finish and recheck the cache. A +recipe replay runs once per bound pipeline, device, ready translation and ordered RTV/DSV +signature. The owner publishes successful recipe PSOs and then uses ordinary creation for any +requested state that still needs a PSO. The cache retains a null result after a driver failure. +An interrupted attempt wakes waiters so one can retry. Rectangle geometry keeps its own one-shot +result per ready translation. Cached PSOs stay alive for closed lists that may be submitted later. + +Unrelated recordings and queue submissions can take the draw lock during preparation. The draw +that initiated creation and any draw waiting for the same state still finish synchronously. Each +list has one recording owner, with Close and Reset synchronized by the caller. + +The unlock fixture pauses a cold PSO create and checks that an independent draw and a closed +list submission complete before the gate opens. The concurrent fixture also checks same-state +coalescing, terminal failure, retry after interruption, recipe hits and mismatch fallback. It +compares fenced pixels across different RTV/DSV signatures and distinct blend, depth and raster +states on a shared shader translation. + +```powershell +cmake --build --preset dev --target d3d12_xs_shim startup_indirect_draw_indexed +ctest --preset dev --no-tests=error -j 1 -V -R '^startup_graphics_pso_load_(unlock|concurrent)_(warp|hardware)$' +``` + ## Scope and limits This is state reconstruction, not a D3D12 pipeline library. A replayed record still calls From 98ff231a6316fdec03d15bf39cde76372de56323 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:48:43 +0100 Subject: [PATCH 14/15] runtime: fix device field uses after the atomic change --- src/startup_stubs/d3d12_xs_device.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 196ce68408..2219b472ab 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -5599,7 +5599,8 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) // A desktop view creation returns void, so the only failure it reports is a removed device. Only a created view // may keep the resource: on failure the slot is recorded unmaterialized, which releases the slot's previous view // reference and adds none. - const HRESULT removed = removal_device ? removal_device->GetDeviceRemovedReason() : S_OK; + auto* device = removal_device.load(); + const HRESULT removed = device ? device->GetDeviceRemovedReason() : S_OK; const bool created = SUCCEEDED(removed); record_view(created); if (!created) { From 31be7fb2f8bbd9a18abd7ea0fad5c7d427a8068a Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:07:48 +0100 Subject: [PATCH 15/15] runtime: publish texture uploads when their recordings submit --- src/startup_stubs/d3d12_draw.inl | 87 ++++++++++++++------------- src/startup_stubs/d3d12_xs_device.cpp | 9 +-- 2 files changed, 49 insertions(+), 47 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 460b39767c..3dec635e95 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2073,22 +2073,21 @@ struct TextureUpload { bool gpu_written = false; // a list copy or resolve wrote the texture; its title memory is stale and must not be uploaded }; std::unordered_map& texture_uploads() { static std::unordered_map m; return m; } -u64 address_upload_revision; - -// A texture published in a newly supported console layout is not filled through the shared upload ring. -// The bounded ring can fill while a queue waits on a fence. Each such upload owns -// its upload buffer instead. The buffer and the texture it fills stay referenced by the recording, -// and by every submit of that recording until the queue it went to has completed the submit, as -// for the sampler heaps above. -struct AddressUpload { - x2w_startup::ComPtr buffer, texture; - u64 revision; +u64 texture_upload_revision; + +// Every copy stays pending until its list is submitted, including copies from the upload ring. +// By-address uploads with dedicated backing also hold their resources through each submit. +struct RecordedTextureUpload { + x2w_startup::ComPtr buffer; + ID3D12Resource* texture; + u64 revision = 0; + x2w_startup::ComPtr owned_texture; bool pinned = false; }; -std::unordered_map> recorded_address_uploads; +std::unordered_map> recorded_texture_uploads; struct SubmittedAddressUploads { x2w_startup::ComPtr fence; - std::vector uploads; + std::vector uploads; }; std::vector submitted_address_uploads; @@ -2100,27 +2099,26 @@ bool address_uploads_from_ring() return on; } -void discard_address_uploads(ID3D12CommandList* list) +void discard_texture_uploads(ID3D12CommandList* list) { AcquireSRWLockExclusive(&draw_lock); - const auto recorded = recorded_address_uploads.find(list); - if (recorded != recorded_address_uploads.end()) { + const auto recorded = recorded_texture_uploads.find(list); + if (recorded != recorded_texture_uploads.end()) { for (const auto& upload : recorded->second) { - const auto state = texture_uploads().find(upload.texture.Get()); + const auto state = texture_uploads().find(upload.texture); if (state != texture_uploads().end() && state->second.pending_list == list) { state->second.done = false; state->second.pending_list = nullptr; } } - recorded_address_uploads.erase(recorded); + recorded_texture_uploads.erase(recorded); } ReleaseSRWLockExclusive(&draw_lock); } -// draw_lock held. The lists have already been executed on this queue. Each submit takes its own -// references; they are dropped by a later call, once the fence signalled behind the submit has -// completed. A submit whose fence could not be made or signalled keeps its references. -void retire_address_uploads(ID3D12CommandQueue* queue, const std::vector& lists) +// The lists have been executed on this queue with draw_lock held. Publish their upload revisions in +// submission order. Keep dedicated upload resources until a fence behind their submit completes. +void submit_texture_uploads(ID3D12CommandQueue* queue, const std::vector& lists) { static std::size_t peak, released; const std::size_t before = submitted_address_uploads.size(); @@ -2136,25 +2134,25 @@ void retire_address_uploads(ID3D12CommandQueue* queue, const std::vectorsecond) { - const auto state = texture_uploads().find(upload.texture.Get()); + const auto state = texture_uploads().find(upload.texture); if (state == texture_uploads().end()) continue; // A recording that writes an older revision may be submitted again. When the // last write in a batch differs from the cache, make the next draw restage it. auto& cached = state->second; - cached.done = cached.revision == upload.revision; + cached.done = upload.revision && cached.revision == upload.revision; if (cached.pending_list == list) cached.pending_list = nullptr; } } try { SubmittedAddressUploads batch; for (auto* list : lists) { - const auto it = recorded_address_uploads.find(list); - if (it == recorded_address_uploads.end()) continue; + const auto it = recorded_texture_uploads.find(list); + if (it == recorded_texture_uploads.end()) continue; for (const auto& upload : it->second) - if (!upload.pinned) batch.uploads.push_back(upload); + if (upload.buffer && !upload.pinned) batch.uploads.push_back(upload); } if (batch.uploads.empty()) return; x2w_startup::ComPtr device; @@ -2170,12 +2168,12 @@ void retire_address_uploads(ID3D12CommandQueue* queue, const std::vectorsecond) { - if (upload.pinned) continue; + if (!upload.buffer || upload.pinned) continue; upload.buffer->AddRef(); - upload.texture->AddRef(); + upload.owned_texture->AddRef(); upload.pinned = true; } } @@ -2469,20 +2467,25 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) } constexpr u64 placement = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT; x2w_upload::Page owned; + state.done = false; + state.staged = false; if (dedicated) { u64 bytes = 0; for (UINT i = 0; i < mips; ++i) bytes += (plan.bytes(i) + placement - 1) & ~(placement - 1); bytes *= slices; if (FAILED(x2w_upload::make_page(device_of(the_device), bytes, owned))) return false; - // Store the owning reference before issuing any D3D12 commands that name the buffer. - try { - recorded_address_uploads[list].push_back({owned.resource, texture, ++address_upload_revision}); - } catch (const std::bad_alloc&) { - return false; - } std::memset(owned.cpu, 0, static_cast(bytes)); } - state.staged = false; + // Reserve the record before issuing copies, retaining dedicated backing at the same time. + RecordedTextureUpload* upload; + try { + auto& uploads = recorded_texture_uploads[list]; + uploads.push_back({owned.resource, texture, 0, x2w_startup::ComPtr(dedicated ? texture : nullptr)}); + upload = &uploads.back(); + } catch (const std::bad_alloc&) { + return false; + } + state.revision = ++texture_upload_revision; require_state(self, texture, D3D12_RESOURCE_STATE_COPY_DEST); if (detile_console) { for (UINT slice = 0; slice < slices; ++slice) { @@ -2507,10 +2510,6 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) plan.upload(list, texture, owned.cpu ? owned.resource.Get() : chunk, mips, slices, slice, i, offset); } } - if (dedicated) { - state.pending_list = list; - state.revision = address_upload_revision; - } } else if (tiled_chain) { const x2w_startup::bc64::Chain chain(original->console); for (UINT slice = 0; slice < slices; ++slice) { @@ -2564,6 +2563,8 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) plan.upload(list, texture, chunk, mips, slices, s, i, offset); } } + upload->revision = state.revision; + state.pending_list = list; state.hash = hash; state.generation = generation; state.checked_frame = frame_number; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 2219b472ab..bfe9f07f78 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1064,6 +1064,7 @@ void retire_note_title_release(Wrapper* w); bool retire_hold(Wrapper* list, Wrapper* resource); void retire_drop_recording(Wrapper* list); void release_list_recording(Wrapper* list); +void discard_texture_uploads(ID3D12CommandList* list); void clear_draw_sampler_snapshot(Wrapper* self); void retire_discard_holds(Wrapper* list); void retire_note_submission(ID3D12CommandQueue* queue, const std::vector& lists); @@ -1089,6 +1090,7 @@ ULONG __stdcall release(Wrapper* self) } if (self->own().kind == list_kind && self->own().real) { release_list_recording(self); + discard_texture_uploads(static_cast(self->own().real)); clear_draw_sampler_snapshot(self); discard_mesh_lease_recording(static_cast(self->own().real)); retire_drop_recording(self); @@ -1401,7 +1403,6 @@ void end_open_queries(Wrapper* self, ID3D12GraphicsCommandList* list); void reset_list_dynamic_state(Wrapper* self); void discard_list_gpu_writes(Wrapper* self); void commit_list_gpu_writes(Wrapper* self); -void discard_address_uploads(ID3D12CommandList* list); void use_as_target(Wrapper* self, ID3D12Resource* resource); bool is_container(const void* p); bool shader_dump_dir(wchar_t* out, DWORD size); @@ -1984,7 +1985,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) if (SUCCEEDED(hr)) { reset_list_dynamic_state(self); discard_list_gpu_writes(self); - discard_address_uploads(previous); + discard_texture_uploads(previous); discard_mesh_lease_recording(previous); retire_drop_recording(self); if (draw_dump_frame()) if (auto lost = draw_dumps().discard(previous)) @@ -2023,7 +2024,7 @@ HRESULT __stdcall list_close(Wrapper* self) InterlockedIncrement(&render_closes); if (FAILED(hr)) { discard_list_gpu_writes(self); - discard_address_uploads(list); + discard_texture_uploads(list); discard_mesh_lease_recording(list); retire_drop_recording(self); if (draw_dump_frame()) if (auto lost = draw_dumps().discard(list)) @@ -4992,7 +4993,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) if (id) log("x2w-compute-output-submit list=%p recording=%lld queue=%p", recorded, id, self); } } - retire_address_uploads(queue, native_lists); + submit_texture_uploads(queue, native_lists); note_submits(queue, wrappers); retire_note_submission(queue, wrappers); for (Wrapper* w : wrappers) commit_list_gpu_writes(w);