diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index ea9c9626db..b332971bc7 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1073,12 +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 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 -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 @@ -1107,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. 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`. + ### Translating compute programs in the stand-in With `X2W_NATIVE_SHADERS=` (`run.ps1 -Render -NativeShaders `), @@ -1134,9 +1146,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 diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index f6e88d4e4f..5e0ef5d3de 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; }; @@ -167,7 +167,7 @@ struct Translation { 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; @@ -175,26 +175,40 @@ 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 + bool preparing = false; 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 }; // 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{}; @@ -235,13 +249,123 @@ 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); +} + +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) +{ + 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(); +} + +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; @@ -261,8 +385,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). @@ -297,7 +420,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; } @@ -329,7 +457,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; @@ -344,7 +477,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 +485,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 +498,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()); @@ -431,10 +560,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; @@ -455,13 +582,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; @@ -480,7 +610,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()) { @@ -490,9 +621,13 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: 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()) { - 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 +739,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,18 +748,21 @@ 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); 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 { const auto request = x2w::read_graphics_request(path); const auto cache = std::filesystem::path(path).parent_path(); @@ -643,28 +781,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,44 +809,118 @@ 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) +{ + GraphicsReservation reservation(entry.preparing); + try { + Wrapper* const wrapper = the_device; + 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. + auto device = std::move(pinned); + 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(); + } + device.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); + return; + } + unlocked.release(); + } catch (...) { + // The unlock guard reacquired draw_lock before we clear the reservation. + GraphicsUnlock unlocked; + log("x2w-draw graphics preparation for %016llx interrupted", entry.key); + } + if (!entry.state) entry.state = 2; + // 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. 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; - 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); - } - return entry; + { + 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()) && + (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); + }); + } 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_key(entry.key); + } + return &entry; } LONG compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words; @@ -742,6 +949,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). @@ -1041,8 +1271,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) { @@ -1086,27 +1315,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; { @@ -1156,7 +1381,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; @@ -1195,34 +1420,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 @@ -1230,10 +1466,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)) @@ -1256,8 +1498,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) { @@ -1294,37 +1541,49 @@ 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); + 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; #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->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) { + 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); 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; - entry->key = key; - load_translation(*entry, request); - if (entry->state != 1) { - const bool published = publish_shader_request(key, L".rtv", 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_key(entry.key); + 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 (!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 && (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); + }); } - return entry; + return &entry; } // The depth format a translated draw uses: the pass's own view, else the one the pipeline was created with. @@ -1411,7 +1670,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 +1680,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")) @@ -2470,7 +2729,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(); @@ -3120,10 +3379,19 @@ 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() && + 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); @@ -3147,7 +3415,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); } @@ -3198,7 +3467,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 +3982,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); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index cc1f9abc54..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 @@ -8348,7 +8350,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; } diff --git a/tests/cmake/startup_graphics_published_load.cmake b/tests/cmake/startup_graphics_published_load.cmake new file mode 100644 index 0000000000..5aac1ab308 --- /dev/null +++ b/tests/cmake/startup_graphics_published_load.cmake @@ -0,0 +1,22 @@ +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 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 + "${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,384 @@ 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_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_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) +{ + 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); + // 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"); + 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); + 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, superseded = 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; + 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); + 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 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(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; +} + bool check_indirect_other_refusal_census(const std::wstring& log_path) { const std::size_t needed = x2w_d3d12_census_report(nullptr, 0); @@ -2861,6 +3257,17 @@ 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 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) { + // 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"); + } 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 +3295,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 +3340,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 +3684,17 @@ 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 = 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()); + } + 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)) {