From 5607594f5b5983dbda2cf7d660e895399bdb9ead Mon Sep 17 00:00:00 2001 From: lukaslw-lab <291379150+lukaslw-lab@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:35:18 +0100 Subject: [PATCH] startup: translate native compute programs on a worker thread (#3451) The first Dispatch of a compute key translated it in the dispatching thread with draw_lock held, about 100 ms per key, so every other draw and dispatch waited and the title's watchdog ended startup runs. One worker thread of a private pool now translates without draw_lock; Dispatch calls of the key stay untranslated until it has stored the native result (or, refused, the published route). Each queued key holds a module reference until its callback returns, so a FreeLibrary meanwhile unloads the stand-in only after the last one. X2W_TEST_NATIVE_COMPUTE_WAIT=1 lets fixtures that record one Dispatch wait for the result; X2W_TEST_NATIVE_COMPUTE_DELAY_MS slows the worker for startup_compute_native_worker, whose wait control must fail its timing check. Co-Authored-By: Claude Opus 5.5 --- docs/startup-runtime.md | 15 ++ src/startup_stubs/d3d12_compute_dispatch.inl | 133 +++++++++++++++++- .../cmake/startup_compute_native_worker.cmake | 16 +++ tests/startup_compute_native_worker_check.py | 67 +++++++++ tests/startup_compute_request_check.py | 3 +- 5 files changed, 228 insertions(+), 6 deletions(-) create mode 100644 tests/cmake/startup_compute_native_worker.cmake create mode 100644 tests/startup_compute_native_worker_check.py diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 040ae3e4b2..7c4427b389 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1093,6 +1093,21 @@ 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. +The translation runs on one worker thread of a private thread pool, without `draw_lock` +([#3451](https://github.com/R0Y00/Xbox2Windows/issues/3451)): it takes about 100 ms per key and more when +refused, and a title thread that waited for it while holding `draw_lock` held up every other draw and +dispatch. The Dispatch that queues a key, and every Dispatch of that key until the worker has stored +its result, stays untranslated, as a refused one does (`Dispatch(...) refused: no translation`). The worker +then stores the native result, or for a refused key loads the published route. Keys queue behind each other +instead of taking cores from the title. Each queued key holds a reference on the stand-in DLL until its +callback returns, so a `FreeLibrary` meanwhile unloads the DLL only after the last one. Two test switches: +`X2W_TEST_NATIVE_COMPUTE_WAIT=1` makes the Dispatch that queues a key wait (without `draw_lock`) for the +worker's result, for fixtures that record a single Dispatch; `X2W_TEST_NATIVE_COMPUTE_DELAY_MS=` makes +the worker sleep before it translates. `startup_compute_native_worker_` delays the +translation by 4 s and requires the consumer, which records one Dispatch and exits, to finish sooner with +that Dispatch untranslated and its output untouched; `startup_compute_native_worker_wait_control_*` adds +the wait switch and must fail the timing check. + 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 is accepted with a `.cs.hlsl` sidecar, which identifies a Python translation. `compile_dxil --watch` diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 9356b70f3f..229f9a802e 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -55,6 +55,7 @@ struct ComputeTranslation { }; u64 key = 0; int state = 0; // 0 not loaded, 1 ready, 2 unavailable + bool native_in_progress = false; // a Dispatch translates this key in process, outside draw_lock x2w_startup::ManifestRetry manifest_retry; // absent and stale manifests can become ready later std::vector uds, srvs, uavs; UINT heap_srvs = 0; @@ -468,7 +469,9 @@ const char* load_compute_translation(ComputeTranslation& tr) // it in this process with the C++ compiler (src/gfx1013_compute_native.cpp), before a published .txt is read // and with no offline translator running. The dispatch path below binds root constants and supported table views. // The constant sampler words the compiler resolved become static samplers. -// A refusal is logged and leaves the key to the published translations. draw_lock held. Returns whether tr is ready. +// A refusal is logged and leaves the key to the published translations. Runs on the worker below, without draw_lock: +// it reads only tr, the frozen requests and the pack (both locked or read-only) and the device, and DXC has its own +// lock. Returns whether tr is ready. bool translate_compute_natively(ComputeTranslation& tr) { #ifdef X2W_NATIVE_SHADERS @@ -583,8 +586,14 @@ bool translate_compute_natively(ComputeTranslation& tr) // Never released: a static destructor would release DXC after its module may have detached. static x2w::ShaderDxilCompiler* const compiler = new x2w::ShaderDxilCompiler(x2w::ShaderDxilCompiler::runtime_worker(sdk)); - const auto shader = compiler->compile(program.dxil_ir, L"cs_6_6", std::filesystem::path(path).parent_path() / L"native", - x2w::ShaderSourceFormat::dxil_ir); + // Callers run without draw_lock, so two keys can be translated at once; the shared DXC instance is not. + static SRWLOCK compile_lock = SRWLOCK_INIT; + AcquireSRWLockExclusive(&compile_lock); + const auto shader = [&] { + struct Unlock { ~Unlock() { ReleaseSRWLockExclusive(&compile_lock); } } unlock; + return compiler->compile(program.dxil_ir, L"cs_6_6", std::filesystem::path(path).parent_path() / L"native", + x2w::ShaderSourceFormat::dxil_ir); + }(); if (const char* failure = create_compute_pipeline(tr, shader.dxil.data(), shader.dxil.size())) throw std::runtime_error(failure); log("x2w-draw compute pipeline %016llx translated natively: %zu entry values, %zu inputs, %zu outputs (frontend %s)", tr.key, @@ -600,6 +609,101 @@ bool translate_compute_natively(ComputeTranslation& tr) #endif } +// A thread-pool work item: translates one key in process without draw_lock, so no title thread waits for it, then +// stores the result in the key's entry under draw_lock. A refused key takes the published route, as it would have +// at once before. Until then the key's entry has native_in_progress set and its Dispatch calls stay untranslated. +// Each queued item holds a reference on this module, released when its callback returns, so a FreeLibrary while +// items are queued or running unloads the module only after the last one (no wait in DllMain, no unmapped code). +HMODULE this_module() +{ + HMODULE module = nullptr; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(&this_module), &module); + return module; +} +void CALLBACK translate_compute_natively_work(PTP_CALLBACK_INSTANCE instance, void* context) +{ + const u64 key = reinterpret_cast(context); + // X2W_TEST_NATIVE_COMPUTE_DELAY_MS=: a slow translation, for the fixture that checks no Dispatch waits for it. + static const DWORD delay_ms = [] { + char value[16]{}; + const DWORD length = GetEnvironmentVariableA("X2W_TEST_NATIVE_COMPUTE_DELAY_MS", value, sizeof(value)); + return length && length < sizeof(value) ? static_cast(std::strtoul(value, nullptr, 10)) : DWORD{0}; + }(); + if (delay_ms) Sleep(delay_ms); + ComputeTranslation candidate; + candidate.key = key; + const bool ready = translate_compute_natively(candidate); + AcquireSRWLockExclusive(&draw_lock); + auto found = compute_translations().find(key); + if (found != compute_translations().end()) { + ComputeTranslation& tr = found->second; + tr.native_in_progress = false; + if (ready) { + tr.uds = std::move(candidate.uds); + tr.srvs = std::move(candidate.srvs); + tr.uavs = std::move(candidate.uavs); + tr.samplers = std::move(candidate.samplers); + tr.root = std::move(candidate.root); + tr.pipeline = std::move(candidate.pipeline); + tr.state = candidate.state; + } else if (!tr.state) { + tr.unmodelled = load_compute_translation(tr); + if (tr.unmodelled) log("x2w-draw compute pipeline %016llx not translated: %s", key, tr.unmodelled); + } + } + ReleaseSRWLockExclusive(&draw_lock); + if (instance) FreeLibraryWhenCallbackReturns(instance, this_module()); +} + +// Whether X2W_NATIVE_SHADERS names a compiler directory (read once). +bool native_compute_enabled() +{ +#ifdef X2W_NATIVE_SHADERS + static const bool enabled = [] { + wchar_t sdk[MAX_PATH]; + const DWORD length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + return length && length < MAX_PATH; + }(); + return enabled; +#else + return false; +#endif +} + +// One worker thread: translations queue behind each other instead of taking cores from the title. +bool submit_native_compute(u64 key) +{ + static TP_CALLBACK_ENVIRON environment; + static const bool ready = [] { + PTP_POOL pool = CreateThreadpool(nullptr); + if (!pool) return false; + SetThreadpoolThreadMaximum(pool, 1); + if (!SetThreadpoolThreadMinimum(pool, 1)) return false; + InitializeThreadpoolEnvironment(&environment); + SetThreadpoolCallbackPool(&environment, pool); + return true; // the pool lives as long as the process + }(); + if (!ready) return false; + // The item's module reference, handed back by translate_compute_natively_work. + HMODULE module = nullptr; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast(&submit_native_compute), + &module)) + return false; + PTP_WORK work = CreateThreadpoolWork( + [](PTP_CALLBACK_INSTANCE instance, void* context, PTP_WORK self) { + translate_compute_natively_work(instance, context); + CloseThreadpoolWork(self); + }, + reinterpret_cast(key), &environment); + if (!work) { + FreeLibrary(module); + return false; + } + SubmitThreadpoolWork(work); + return true; +} + // Resolve a compute root SRV (`srv buf root `) from the guest address recorded by slot 43 for // to the end of its backing upload allocation or aliased placed buffer (up to the 16 MiB compute raw buffer limit). IndirectBufferView compute_root_srv_buffer(Wrapper* self, const Pass& pass, int param, std::uint32_t (&words)[8], @@ -808,8 +912,27 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& else if (!ensure_draw_heap(self->own().list_device)) reason = "no descriptor heap on this device"; else { if (!tr->state || tr->manifest_retry.due(GetTickCount64())) { - // The in-process translation is tried once per key, before a published one. - if (tr->state || !translate_compute_natively(*tr)) { + // The in-process translation is tried once per key, before a published one, on a worker thread: it takes + // about 100 ms per key (more when refused), and a title thread waiting for it while holding draw_lock + // stalled every other draw and dispatch until the title's watchdog ended it (#3451). Until the worker has + // stored its result, Dispatch calls of the key stay untranslated, as a refused translation leaves them. + // The worker stores the native result, or for a refused key loads the published route. + bool skip = false; + if (!tr->state && tr->native_in_progress) { + skip = true; + } else if (!tr->state && native_compute_enabled() && submit_native_compute(key)) { + tr->native_in_progress = true; + skip = true; + // X2W_TEST_NATIVE_COMPUTE_WAIT=1: this Dispatch waits, without draw_lock, until the worker stored the + // key's result, so a fixture that records one Dispatch sees it translated. Not for title runs. + static const bool wait = x2w_local::env_on("X2W_TEST_NATIVE_COMPUTE_WAIT"); + while (wait && tr->native_in_progress) { + ReleaseSRWLockExclusive(&draw_lock); + Sleep(1); + AcquireSRWLockExclusive(&draw_lock); + } + } + if (!skip) { tr->unmodelled = load_compute_translation(*tr); if (tr->unmodelled) log("x2w-draw compute pipeline %016llx not translated: %s", key, tr->unmodelled); } diff --git a/tests/cmake/startup_compute_native_worker.cmake b/tests/cmake/startup_compute_native_worker.cmake new file mode 100644 index 0000000000..dda4ba2756 --- /dev/null +++ b/tests/cmake/startup_compute_native_worker.cmake @@ -0,0 +1,16 @@ +# #3451: a Dispatch does not wait for the in-process compute translation (X2W_NATIVE_SHADERS). The control makes the +# Dispatch wait for the worker, as before, and must fail the timing check. +if(TARGET x2w_shader_compiler AND TARGET startup_stream_consumer AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_native_worker_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_native_worker_check.py" + "$" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(startup_compute_native_worker_${adapter} PROPERTIES TIMEOUT 120) + add_test(NAME startup_compute_native_worker_wait_control_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_native_worker_check.py" + "$" "${DXC_BIN_DIR}" ${adapter} --control) + set_tests_properties(startup_compute_native_worker_wait_control_${adapter} PROPERTIES TIMEOUT 120 + PASS_REGULAR_EXPRESSION "FAIL: \\(a\\) the Dispatch returned before the slow translation.*native_worker_check: [1-9]") + endforeach() +endif() diff --git a/tests/startup_compute_native_worker_check.py b/tests/startup_compute_native_worker_check.py new file mode 100644 index 0000000000..08948dfb10 --- /dev/null +++ b/tests/startup_compute_native_worker_check.py @@ -0,0 +1,67 @@ +"""A Dispatch does not wait for the in-process compute translation (#3451). + +usage: startup_compute_native_worker_check.py [--control] + +The program and table are those of step 1 of startup_compute_dispatch_native_check.py (dispatch-records32, which +the C++ compiler translates). X2W_TEST_NATIVE_COMPUTE_DELAY_MS makes the worker sleep 4 s before it translates. + (a) the consumer process, which records one Dispatch and exits, finishes before that delay has passed; + (b) that Dispatch is refused with "no translation" and every output word keeps the sentinel, and no native + translation is logged before the process ends. +--control adds X2W_TEST_NATIVE_COMPUTE_WAIT=1, which makes the Dispatch wait for the worker as a title thread did +before #3451; (a) must then fail. +""" +import os +from pathlib import Path +import sys +import tempfile +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_compute_dispatch_native_check import LOAD_X8, LOADS_X4 + +DELAY_MS = 4000 + + +def main(consumer, dxc_dir, adapter, control): + failures = 0 + + def check(ok, what): + nonlocal failures + print(f'{"ok" if ok else "FAIL"}: {what}') + failures += not ok + + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + _, env = prepare_case(directory, adapter) + env.update(X2W_NATIVE_SHADERS=dxc_dir, X2W_TEST_NATIVE_COMPUTE_DELAY_MS=str(DELAY_MS)) + env.pop('X2W_TEST_NATIVE_COMPUTE_WAIT', None) + if control: + env['X2W_TEST_NATIVE_COMPUTE_WAIT'] = '1' + case_a = (directory / 'program').read_bytes() + assert case_a.count(LOAD_X8) == 1 + (directory / 'program').write_bytes(case_a.replace(LOAD_X8, LOADS_X4)) + started = time.monotonic() + got, result = dispatch(directory, consumer, env, 'dispatch-records32') + elapsed_ms = (time.monotonic() - started) * 1000 + print(f'consumer finished after {elapsed_ms:.0f} ms (translation delay {DELAY_MS} ms)') + check(elapsed_ms < DELAY_MS, '(a) the Dispatch returned before the slow translation') + check(got == [C.SENTINEL] * C.WORDS and len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1 + and not lines(result, 'translated natively'), + '(b) the Dispatch stayed untranslated and left every word untouched') + if failures: + print(result.stderr[-3000:]) + print(f'startup_compute_native_worker_check: {failures} failed') + return 1 if failures else 0 + + +if __name__ == '__main__': + arguments = sys.argv[1:] + control = '--control' in arguments + if control: + arguments.remove('--control') + if len(arguments) != 3 or arguments[2] not in ('warp', 'hardware'): + sys.exit(__doc__) + sys.exit(main(*arguments, control)) diff --git a/tests/startup_compute_request_check.py b/tests/startup_compute_request_check.py index 951d6415a5..f6c1cf4857 100644 --- a/tests/startup_compute_request_check.py +++ b/tests/startup_compute_request_check.py @@ -75,8 +75,9 @@ def prepare(directory): (directory / "vertex").write_bytes(container(1)) (directory / "pixel").write_bytes(container(0)) # The truncated stream that prepares the device publishes nothing, so the cache holds only compute files. + # X2W_TEST_NATIVE_COMPUTE_WAIT: these fixtures record one Dispatch, so it waits for the native worker (#3451). env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_RENDER="1", X2W_SHADER_CACHE=str(cache), - X2W_TEST_TRUNCATED_ONLY="1") + X2W_TEST_TRUNCATED_ONLY="1", X2W_TEST_NATIVE_COMPUTE_WAIT="1") return cache, env