diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 3d3ff1750a..a262aad906 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -214,6 +214,7 @@ jobs: tests/startup_translator_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ tests/startup_gfx2hlsl_refusals_check.py \ + tests/startup_compute_request_offline_check.py \ tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ tests/startup_triage_run_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 4ab50f4b80..d29963c260 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -159,6 +159,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_translator_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_smem_offset_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_refusals_check.py +./out/pe-env/bin/python -B tests/startup_compute_request_offline_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sop2_complement_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 36aa44a2b7..ceb64dabe8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2723,6 +2723,13 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_stream_request_warp COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_check.py" "$") + # Device slot 67 compute pipelines publish req_.{desc,sa,sb,data,root,c67}; the control (render mode off) must fail. + add_test(NAME startup_compute_request_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_request_check.py" "$") + add_test(NAME startup_compute_request_disabled_control COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_request_check.py" "$" disabled) + set_tests_properties(startup_compute_request_warp startup_compute_request_disabled_control PROPERTIES TIMEOUT 60) + set_tests_properties(startup_compute_request_disabled_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: no compute request") foreach(backend IN ITEMS warp hardware) add_test(NAME startup_stream_draw_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_draw_check.py" @@ -2857,6 +2864,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: read-only census of every refusal site (--refusals). add_test(NAME startup_gfx2hlsl_refusals COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_refusals_check.py") + # Device slot 67 compute requests offline: key vector, --pending and --refusals (pure Python). + add_test(NAME startup_compute_request_offline COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_request_offline_check.py") # Partial colour exports carry their channel mask to the manifest; compressed exports of whole pairs lower (#1674). add_test(NAME startup_gfx2hlsl_export_mask COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_export_mask_check.py") diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 4dbc686dfd..77e4a2a5af 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -579,6 +579,94 @@ 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. +### Compute pipeline requests + +Device slot 67 creates a pipeline from a console compute program. The stand-in reads 12 64-bit words of the +description: + +| Words | Content | +|---|---| +| 0 | root signature | +| 1-2, 3-4 | two state blocks and their sizes (a size of 0 means the block is absent) | +| 5-6 | program code and its size | +| 7-8 | a second blob and its size | +| 9, 10 | pointers whose targets are not decoded | +| 11 | a value | + +It interprets none of these parts and still creates a placeholder. With `X2W_D3D12_RENDER=1` and +`X2W_SHADER_CACHE` set, it writes a request to the cache directory the graphics requests use: + +| File | Content | +|---|---| +| `req_.desc` | the 12 words with the pointer words 0, 1, 3, 5, 7, 9 and 10 always set to zero, so no process address reaches a file or the key | +| `req_.sa`, `req_.sb` | state blocks A and B (at most 4 KiB each; empty when the size is 0) | +| `req_.data` | the words 7-8 blob (at most 1 MiB; required) | +| `req_.root` | the serialized root signature | +| `req_.c67` | the program code (at most 1 MiB); written last, as the ready marker | + +The `.c67` extension keeps these requests apart from draft #1954, which uses `req_.cs` for desktop DXIL +containers created at device slot 62. + +**Reading the parts.** Each part is checked and then copied once, with a fault-safe copy, before anything is +hashed, scanned or written, so a later write by the title cannot leave a file that does not match its key. +If any declared part cannot be taken, no file is written and the creation counts as failed. The logged reason +names the part and the cause: +- a code or data size of 0 (a program without the words 7-8 blob is refused); +- a size over its limit; +- a part that is not readable to its declared end; +- a description that is not readable; +- a root signature without a recorded blob. + +A cache directory that is set but does not exist makes every creation fail. Publishing is off only when +render mode is off or `X2W_SHADER_CACHE` is unset; such creations are counted nowhere. + +**Key.** The key hashes the revision string followed by `cs`, then each part preceded by its length as a +little-endian u64. The order is: code, words 7-8 blob, root, `.desc`, `.sa`, `.sb` (`compute_key` in +`gfx2hlsl.py`), so moving bytes from one part to the next changes the key. A compute key and a graphics key +can still coincide only through a 64-bit hash collision, or through a graphics program crafted to start with +the compute framing. + +What words 9 and 10 point to is not part of the request, so two descriptions that differ only there share a +key. If those targets are decoded and added later, every key changes and each request is published once more. + +**Pointers inside blobs.** An aligned qword in `.data`, `.sa` or `.sb` that names committed memory of the +process (one `VirtualQuery` per candidate, so no fault is taken) would make its key run-dependent. These +qwords are counted and published, not refused, because hash-like values can name memory by chance. The code +is not scanned. + +**Dedupe.** Each key is written once per cache and never rewritten. Parts left by an interrupted write, which +has no `.c67` yet, are kept, and the next creation completes the request. A key already seen in the process +costs no file access, and the writes take their own lock, not the draw lock. + +**Log and totals.** Each creation logs `x2w-draw compute request published`, `already present` or +`not written`, with the reason when refused, up to 12 lines per run. The render totals line ends with +`compute requests published (already present , failed , pointer-like blob qwords )`. + +**Offline.** `gfx2hlsl.py --pending` and `--watch` take `.c67` as a ready marker. With no compute stage yet, +they record `compute stage not supported` in `.fail`. The request stays in the cache, and a later +`--pending` retries it. `--refusals` reports compute requests in a separate section, so its graphics counts +do not change, and `triage_run.py` puts their `.fail` reasons in a `compute:` class. + +**Local observation** (a local build of this change ported to an older base; one title, local files only, not +in the repository): +- One run published 2,689 requests with 0 failed. It wrote 2,689 files of each of the six kinds, 120.3 MB in + all (98.8 MB of it `.c67`), and counted 729 pointer-like blob qwords. +- A second run with the same cache published 0 (2,689 already present, 0 failed), wrote no files and changed + no modification time. +- An earlier build with the same layout found that in every request the code length equals word 6 and the + blob length equals word 8, and that state block A is 28 bytes and state block B 20 bytes. +- In the first 40 descriptions, words 9 and 10 point at a readable block of at least 4 KiB. + +**Checks.** Run `ctest --preset dev --no-tests=error -R "^startup_compute_request_(warp|disabled_control)$" -V` +after building `startup_stream_consumer`. On WARP: +- The same synthetic description is created twice in each of two processes, with words 9 and 10 pointing + into the consumer and a 20-byte state block B, and the files are written once. +- Each refusal writes no file. These include reads next to a `PAGE_NOACCESS` page and sizes 1 byte over each + limit, while code, data and both state blocks at exactly their limits are published. +- A valid, refused, valid sequence publishes the two valid keys. +- A request whose first four parts already exist is completed without rewriting them. +- The control runs without render mode and must print `FAIL: no compute request`. + `run.ps1` prints the first five lines of `.out` and exits with the debugger's exit code: 2 when the process could not be created, 0 when the debugger finished its report, whatever the process did. Check with `python3 -B tests/startup_run_ps1_check.py` (ctest `startup_run_ps1`): on Windows it @@ -870,7 +958,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_XMEM_GPU_MIRROR=1` | pairs a no-access graphics reservation with the read-write reservation of the same size made just before it, and maps every physical page into both (same section) | | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | -| `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}` and, when needed, RTV variants `req_.rtv`. A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | +| `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index f1790053aa..09a896e65c 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -226,6 +226,137 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* return entry; } +LONG compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words; + +// Device slot 67 (console compute program), 12 64-bit words: 0 (root signature), 1-2 and 3-4 (two state +// blocks and sizes, a size of 0 meaning absent), 5-6 (program code and size), 7-8 (a second blob and size), +// 9 and 10 (pointers whose targets are not decoded) and 11 (a value). The request carries .desc (the 12 +// words with the seven pointer words always zeroed, so no process address reaches a cache file or the key), +// .sa, .sb, .data and .root, then .c67 (the code) last as the ready marker, for an offline compute stage +// (tools/startup/gfx2hlsl.py). Any declared part that cannot be read refuses the whole request before a +// file is written. The pipeline stays +// a placeholder. Like the graphics path, a key is published once per cache whether or not a result exists. +constexpr u64 compute_code_limit = 1u << 20, compute_data_limit = 1u << 20, compute_state_limit = 0x1000; + +// The key frames every part with its length, so moving bytes from one part to the next changes it. +u64 fnv_part(const std::vector& part, u64 key) +{ + const u64 bytes = part.size(); + return fnv_bytes(part.data(), part.size(), fnv_bytes(&bytes, sizeof(bytes), key)); +} + +// A fault-safe copy of title memory: the parts are read once, then hashed, scanned and written from the copy, +// so a title write in between cannot leave a file that does not match its key. +bool copy_title_bytes(void* to, const void* from, std::size_t bytes) noexcept +{ + __try { + std::memcpy(to, from, bytes); + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } + return true; +} + +// 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). +LONG pointer_like_qwords(const std::vector& blob) +{ + LONG found = 0; + for (std::size_t at = 0; at + 8 <= blob.size(); at += 8) { + u64 value; + std::memcpy(&value, blob.data() + at, sizeof(value)); + MEMORY_BASIC_INFORMATION info{}; + if (value >= 0x10000 && value < 0x800000000000ull && + VirtualQuery(reinterpret_cast(value), &info, sizeof(info)) == sizeof(info) && info.State == MEM_COMMIT) + ++found; + } + return found; +} + +SRWLOCK compute_request_lock = SRWLOCK_INIT; +std::unordered_set& compute_keys_seen() { static std::unordered_set s; return s; } + +void publish_compute_request(const void* desc) +{ + wchar_t marker[MAX_PATH]; + if (!render_mode() || !cache_path(marker, L"req_", 0, L".c67")) return; // publishing disabled + static LONG logged; + const char* refusal = nullptr; + u64 words[12]{}; + std::vector root_blob; + if (!desc || !x2w_local::readable(desc, sizeof(words)) || !copy_title_bytes(words, desc, sizeof(words))) + refusal = "description unreadable"; + else { + if (Wrapper* root = as_wrapper(reinterpret_cast(words[0]))) { + 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()) refusal = "no root signature blob"; + } + struct Part { int pointer; u64 limit; bool required; const char *zero, *over, *unreadable; }; + static constexpr Part parts[4] = { + {5, compute_code_limit, true, "code size 0", "code size over 1 MiB", "code unreadable"}, + {7, compute_data_limit, true, "data size 0", "data size over 1 MiB", "data unreadable"}, + {1, compute_state_limit, false, nullptr, "state block A size over 4 KiB", "state block A unreadable"}, + {3, compute_state_limit, false, nullptr, "state block B size over 4 KiB", "state block B unreadable"}, + }; + std::vector copies[4]; // code, data, state A, state B + for (int i = 0; i < 4 && !refusal; ++i) { + const Part& p = parts[i]; + const u64 bytes = words[p.pointer + 1]; + const auto* at = reinterpret_cast(words[p.pointer]); + if (!bytes) refusal = p.required ? p.zero : nullptr; + else if (bytes > p.limit) refusal = p.over; + else { + copies[i].resize(static_cast(bytes)); + if (!x2w_local::readable(at, copies[i].size()) || !copy_title_bytes(copies[i].data(), at, copies[i].size())) + refusal = p.unreadable; + } + } + if (refusal) { + InterlockedIncrement(&compute_requests_failed); + if (first_calls(logged, 12)) log("x2w-draw compute request not written: %s", refusal); + return; + } + const auto& [code, data, state_a, state_b] = copies; + // Pointer words never reach .desc or the key; 9 and 10 are not followed (shortcut: two descriptions that + // differ only in what they point to share a key; publish those targets once they are decoded). + std::vector fields(sizeof(words)); + words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; + std::memcpy(fields.data(), words, sizeof(words)); + constexpr char compute_revision[] = "x2w-startup-shader-8cs"; // tools/startup/gfx2hlsl.py compute_key + u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); + const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; + for (const auto* part : order) key = fnv_part(*part, key); + // A dedicated lock and an in-memory set: a key seen in this process costs no file access, and draws + // under draw_lock are not held up by request writes. + const auto write = [key](const wchar_t* ext, const std::vector& part) { + static const unsigned char none = 0; // a valid buffer for a 0-byte part + return publish_shader_request(key, ext, part.empty() ? &none : part.data(), part.size()); + }; + AcquireSRWLockExclusive(&compute_request_lock); + bool present = compute_keys_seen().count(key) != 0; + bool written = present; + if (!present) { + present = cache_path(marker, L"req_", key, L".c67") && GetFileAttributesW(marker) != INVALID_FILE_ATTRIBUTES; + // Parts left by an interrupted earlier write are kept; the marker comes last, so the request completes here. + written = present || (write(L".desc", fields) && write(L".sa", state_a) && write(L".sb", state_b) && + write(L".data", data) && write(L".root", root_blob) && write(L".c67", code)); + if (written) compute_keys_seen().insert(key); + } + ReleaseSRWLockExclusive(&compute_request_lock); + const LONG pointers = written && !present ? pointer_like_qwords(data) + pointer_like_qwords(state_a) + pointer_like_qwords(state_b) : 0; + if (pointers) InterlockedAdd(&compute_blob_pointer_words, pointers); + InterlockedIncrement(present ? &compute_requests_present : written ? &compute_requests_published : &compute_requests_failed); + if (first_calls(logged, 12)) + log("x2w-draw compute request %016llx %s (code %llu bytes, data %llu bytes, state blocks %llu + %llu bytes, " + "pointer-like blob qwords %ld)", key, present ? "already present" : written ? "published" : "not written", + words[6], words[8], words[2], words[4], pointers); +} + // The INPUT_LAYOUT subobject as the request text tools/startup/gfx2hlsl.py reads: "ia1 ", then one // " " line per element. False when it cannot be read. bool stream_input_layout(const unsigned char* subobject, std::string& text) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 064c0892a6..6257cc2fe2 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3479,7 +3479,8 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE } // Device slots 57 and 67 (Xbox order): (desc*, riid, ppv) with the ID3D12PipelineState IID; pipeline -// descriptions whose layout is not decoded yet. The result is a placeholder PipelineState. +// descriptions whose layout is not decoded yet. The result is a placeholder PipelineState. In render +// mode a slot 67 (compute) description also publishes a translation request (d3d12_draw.inl). template HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, const GUID* iid, void** out) { @@ -3496,6 +3497,7 @@ HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, log("x2w-d3d12 Device::slot%d(pipeline?) desc=[%s] riid=%s -> placeholder", N, bytes, text); } if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE; + if constexpr (N == 67) publish_compute_request(desc); *out = wrap(nullptr, pipeline_kind); note_pipeline(static_cast(*out), N, nullptr, desc, 0x300); return S_OK; @@ -3793,7 +3795,7 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa log("x2w-render totals: resets %ld (failed %ld), closes %ld, clears %ld, target binds %ld (unresolved %ld), executes %ld, draws %ld (skipped %ld), " "translated draws %ld (not drawn %ld), pipelines translated %ld / missing %ld, null bindings %ld (entry %ld, buffer %ld, token %ld, wrapper %ld, dimension %ld), " "textures uploaded %ld (%ld KiB, unreadable %ld), heap-indexed roots deferred %ld (real draws refused: view heap %ld, " - "sampler heap %ld, both heaps %ld, state %ld), pipelines first looked up by ExecuteIndirect %ld", render_resets, + "sampler heap %ld, both heaps %ld, state %ld), pipelines first looked up by ExecuteIndirect %ld, compute requests published %ld (already present %ld, failed %ld, pointer-like blob qwords %ld)", render_resets, render_reset_failures, render_closes, render_clears, render_target_binds, render_target_unresolved, render_executes, render_draws, render_draws_skipped, translated_draws, untranslated_draws, translation_ready, translation_missing, null_total, null_causes[0], null_causes[1], null_causes[2], null_causes[3], null_causes[4], textures_uploaded, @@ -3801,7 +3803,8 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa heap_root_refusals[static_cast(x2w_startup::RealRootDecision::view_heap_missing)], heap_root_refusals[static_cast(x2w_startup::RealRootDecision::sampler_heap_missing)], heap_root_refusals[static_cast(x2w_startup::RealRootDecision::both_heaps_missing)], - heap_root_refusals[static_cast(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups); + heap_root_refusals[static_cast(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups, + compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words); if (render_mode() && frame % 300 == 0) { // Slot-61 calls since the start, by outcome, then by signature kind (zero kinds left out). static const char* const outcomes[] = {"forwarded", "refused graphics-pipeline", "compute-pipeline", diff --git a/tests/startup_compute_request_check.py b/tests/startup_compute_request_check.py new file mode 100644 index 0000000000..4c7af91fc4 --- /dev/null +++ b/tests/startup_compute_request_check.py @@ -0,0 +1,192 @@ +"""Device slot 67 compute requests on WARP: publishing, refusals and boundaries, and the offline handling. + +usage: startup_compute_request_check.py [disabled] + +The consumer creates a WARP device and a root signature, then slot-67 descriptions. The program, data blob and +state blocks are synthetic, and their qwords are not addresses (each is below 0x10000 or at or above 2^47); the +stand-in copies them without interpreting them. Checked: +- req_.c67, .data, .root, .sa, .sb (20 bytes) and .desc (the 12 words with the seven pointer words + zeroed; words 9 and 10 point into the consumer) hold the exact bytes; +- the key is the runtime's length-framed FNV chain, computed here from the literal in d3d12_draw.inl, equals + gfx2hlsl.compute_key, and changes when bytes move from one part to the next; +- the second creation and a second process (other addresses) write nothing; +- each refusal (zero or oversize size, a part unreadable to its end next to a PAGE_NOACCESS page, missing root, + unreadable description) writes no file and logs its reason; code, data and both state blocks at exactly + their limits publish; valid -> refused -> valid publishes exactly the two valid keys; +- parts left by an interrupted earlier write (no .c67) are kept and the next creation completes the request; +- a data qword that names committed memory is counted and still published; +- gfx2hlsl.py --pending records "compute stage not supported" in .fail, and --refusals reports compute + requests in their own section. +"disabled" is the negative control: without X2W_D3D12_RENDER=1 nothing is published, and the check must print +"FAIL: no compute request". +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from startup_stream_check import container, gfx2hlsl + +PROGRAM = struct.pack("<2I", 0x7e020280, 0xbf810000) # v_mov_b32 v1, 0; s_endpgm +DATA = struct.pack("<2Q", 0xfedcba9876543210, 0xffff00001111008c) # synthetic, not addresses +STATE = struct.pack("<3Q", 1, 0x2c, 0xfff0000000000003) # synthetic state block A, 24 bytes +STATE_B = struct.pack("<5I", 0x1234abcd, 0xffff0000, 0, 0, 0) # the consumer's fixed state block B +RUNTIME = Path(__file__).resolve().parents[1] / "src" / "startup_stubs" / "d3d12_draw.inl" +PARTS = (".c67", ".data", ".root", ".desc", ".sa", ".sb") + + +def fnv(data, h=1469598103934665603): + for b in data: + h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff + return h + + +def runtime_key(code, data, root, desc, state_a, state_b): + literal = re.search(rb'constexpr char compute_revision\[\] = "([^"]+)";', RUNTIME.read_bytes()) + graphics = re.search(rb'constexpr char revision\[\] = "([^"]+)";', RUNTIME.read_bytes()) + assert literal and graphics and literal[1] == graphics[1] + b"cs", "the compute revision must follow the graphics one" + key = fnv(literal[1]) + for part in (code, data, root, desc, state_a, state_b): + key = fnv(part, fnv(struct.pack(".{desc,sa,sb,data,root,c67}) is found by + request_keys(compute=True) and pending_keys, but not by the graphics request_keys; gfx2hlsl.py --pending + records "compute stage not supported" in .fail and writes no manifest; --refusals --json reports it in + the compute section only. +""" +import json +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +CODE = struct.pack('<2I', 0x7e020280, 0xbf810000) +DATA = struct.pack('<2Q', 0xfedcba9876543210, 0xffff00001111008c) +ROOT = b'RTS0 synthetic root' +DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) +STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) +STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) +KEY = 0x29c6e5148934abc8 # compute_key of the parts above + + +def framed_key(): + h = 1469598103934665603 + for b in b'x2w-startup-shader-8cs': + h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff + for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): + for b in struct.pack(' creates the root signature +// from that serialized blob instead of using the stream root. +// +// Cases (each pipeline is a placeholder): +// valid the description twice +// order valid, then refused (no root), then valid with another data blob +// code-limit code of exactly 1 MiB (the program, then zeros) code-over: 1 MiB + 1 +// state-limit state block A of exactly 4 KiB state-over: 4 KiB + 1 +// data-limit data blob of exactly 1 MiB data-over: 1 MiB + 1 +// stateb-limit state block B of exactly 4 KiB stateb-over: 4 KiB + 1 +// data-pointer valid, with the first data qword pointing at state block A +// code-zero, data-zero, no-root, code-unreadable, code-past-end, data-unreadable, state-unreadable, +// stateb-unreadable, desc-unreadable +// The unreadable cases point at a PAGE_NOACCESS page; code-past-end ends the code on the last byte before one. +static bool create_slot67(void* device, const char* code_path, const char* data_path, const char* state_path, const char* mode) +{ + std::ifstream code_file(code_path, std::ios::binary), data_file(data_path, std::ios::binary), state_file(state_path, std::ios::binary); + std::vector code{std::istreambuf_iterator(code_file), {}}; + std::vector data{std::istreambuf_iterator(data_file), {}}; + std::vector state{std::istreambuf_iterator(state_file), {}}; + if (code.empty() || data.empty() || state.empty() || !stream_root_signature()) return false; + void* root = stream_root_signature(); + char root_path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_COMPUTE_ROOT", root_path, MAX_PATH); + if (n && n < MAX_PATH) { + std::ifstream file(root_path, std::ios::binary); + const std::vector blob{std::istreambuf_iterator(file), {}}; + using CreateRoot = HRESULT (WINAPI*)(void*, UINT, const void*, SIZE_T, REFIID, void**); + if (blob.empty() || FAILED(reinterpret_cast((*static_cast(device))[16])( + device, 0, blob.data(), blob.size(), __uuidof(ID3D12RootSignature), &root))) return false; + } + // Two pages: the first readable, the second PAGE_NOACCESS. + auto* pages = static_cast(VirtualAlloc(nullptr, 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + DWORD old = 0; + if (!pages || !VirtualProtect(pages + 0x1000, 0x1000, PAGE_NOACCESS, &old)) return false; + unsigned char* guard = pages + 0x1000; + const std::string m(mode); + if (m == "code-limit" || m == "code-over") code.resize((1u << 20) + (m == "code-over")); + if (m == "state-limit" || m == "state-over") state.resize(0x1000 + (m == "state-over")); + std::vector state_b{char(0xcd), char(0xab), 0x34, 0x12, 0, 0, char(0xff), char(0xff), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + if (m == "data-limit" || m == "data-over") data.resize((1u << 20) + (m == "data-over")); + if (m == "stateb-limit" || m == "stateb-over") state_b.resize(0x1000 + (m == "stateb-over")); + if (m == "data-pointer") { // the first qword of the data blob points at state block A + const UINT64 address = reinterpret_cast(state.data()); + if (data.size() < sizeof(address)) return false; + std::memcpy(data.data(), &address, sizeof(address)); + } + alignas(8) unsigned char desc[0x300]{}; + UINT64 words[12] = {reinterpret_cast(root), reinterpret_cast(state.data()), state.size(), + reinterpret_cast(state_b.data()), state_b.size(), + reinterpret_cast(code.data()), code.size(), reinterpret_cast(data.data()), data.size(), + reinterpret_cast(state.data()), reinterpret_cast(desc), 0xb}; + if (m == "code-zero") words[6] = 0; + if (m == "data-zero") words[8] = 0; + if (m == "no-root") words[0] = 0; + if (m == "code-unreadable") words[5] = reinterpret_cast(guard); + if (m == "state-unreadable") words[1] = reinterpret_cast(guard); + if (m == "data-unreadable") words[7] = reinterpret_cast(guard); + if (m == "stateb-unreadable") words[3] = reinterpret_cast(guard); + if (m == "code-past-end") { + std::memcpy(guard - code.size(), code.data(), code.size()); + words[5] = reinterpret_cast(guard - code.size()); + words[6] = code.size() + 1; + } + std::memcpy(desc, words, sizeof(words)); + const void* where = desc; + if (m == "desc-unreadable") where = guard; + using Create = HRESULT (WINAPI*)(void*, const void*, REFIID, void**); + auto create = [&](const void* d) { + void* pipeline = nullptr; + return SUCCEEDED(reinterpret_cast((*static_cast(device))[67])(device, d, __uuidof(ID3D12PipelineState), &pipeline)) && + pipeline; + }; + if (m == "order") { + if (!create(desc)) return false; + UINT64 refused[12]; + std::memcpy(refused, words, sizeof(refused)); + refused[0] = 0; + if (!create(refused)) return false; + std::vector other(data); + other[0] ^= 1; + words[7] = reinterpret_cast(other.data()); + std::memcpy(desc, words, sizeof(words)); + return create(desc); + } + for (int i = 0; i < (m == "valid" ? 2 : 1); ++i) + if (!create(where)) return false; + return true; +} + int main(int argc, char** argv) { - if (argc != 4 && (argc < 6 || argc > 8) && argc != 10) return 2; + if (argc != 4 && (argc < 6 || argc > 9) && argc != 10) return 2; + if (argc == 9 && std::strcmp(argv[4], "slot67") != 0) return 2; const bool draw = argc != 4; StartupBc7Input bc7{}; if (argc == 10) { @@ -165,6 +258,9 @@ int main(int argc, char** argv) const bool hardware = draw && std::strcmp(argv[4], "hardware") == 0; if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, bc7.blocks != nullptr, adapter, device, pso)) return rc; + // slot67 [case]: WARP device and root only, then slot-67 creations. + if ((argc == 8 || argc == 9) && std::strcmp(argv[4], "slot67") == 0) + return create_slot67(device, argv[5], argv[6], argv[7], argc == 9 ? argv[8] : "valid") ? 0 : 10; if (GetEnvironmentVariableW(L"X2W_TEST_TRUNCATED_ONLY", nullptr, 0)) return 0; if (argc == 4) return 0; DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM; diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 1ac521eedb..9681903be3 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -56,6 +56,9 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: "fxc ps: /home/alice/secret/shader.hlsl(1,1): error X3000 at 0x00007ff712345678\n", encoding="utf-8", ) + # A device slot 67 compute request with the same reason is counted in its own class. + (cache_dir / "0000000000000004.fail").write_text("image_load_mip tfe\n", encoding="utf-8") + (cache_dir / "req_0000000000000004.c67").write_bytes(b"\0" * 4) report = triage_run.triage_run(logdir, shader_cache=cache_dir, max_items=16) @@ -73,6 +76,7 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: "| 2 | `slot5` | `0x80004005` |", "| 1 | `persistent_local_storage` | `0x80070005` |", "| 2 | `image_load_mip tfe` |", + "| 1 | `compute: image_load_mip tfe` |", f"| 1 | `{triage_run.OTHER}` |", ] for snippet in expected_snippets: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 18688048c3..2daa7a55a3 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2706,6 +2706,31 @@ def pipeline_key(vs_code, ps_code, root_blob, layout=b''): return fnv(layout, key) if layout else key +def compute_key(cs_code, data, root_blob, desc, state_a=b'', state_b=b''): + """The runtime key of a device slot 67 compute request (req_.c67, .data, .root, .desc, .sa, .sb): the + graphics revision followed by "cs", then each part preceded by its length as a little-endian u64: the code, + the words 7-8 blob, the root signature, the 12 description words with their pointers zeroed and the two + state blocks.""" + key = fnv(b'x2w-startup-shader-8cs') + for part in (cs_code, data, root_blob, desc, state_a, state_b): + key = fnv(part, fnv(struct.pack(' Counter[str]: break if not first_line: first_line = "(empty .fail)" - reasons["(empty .fail)" if first_line == "(empty .fail)" else classify_shader_reason(first_line)] += 1 + reason = "(empty .fail)" if first_line == "(empty .fail)" else classify_shader_reason(first_line) + # A device slot 67 compute request (req_.c67) gets its own class, so graphics counts do not move. + if (cache_dir / ("req_" + fail_path.stem + ".c67")).is_file(): + reason = "compute: " + reason + reasons[reason] += 1 return reasons