diff --git a/CMakeLists.txt b/CMakeLists.txt index ba597fee39..34a053c33a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5248,6 +5248,10 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: descriptor offsets inside wide scalar loads (no game data). add_test(NAME startup_translator COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_translator_check.py") + # Startup shader translator: slot 57 pixel entries (.ps57in) translate, and a cached plain-key + # translation is reused instead of the suffixed key (#3385). + add_test(NAME startup_gfx2hlsl_ps57in COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_ps57in_check.py") # Startup shader translator: the SMEM offset 'off' is the literal 0; m0 and other operands keep their handling (#1674). add_test(NAME startup_gfx2hlsl_smem_offset COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_smem_offset_check.py") diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 6efbc1884f..60e9987213 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -686,7 +686,21 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* 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); - if (!slot57_entry.empty()) key = fnv_bytes(slot57_entry.data(), slot57_entry.size(), 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; @@ -695,7 +709,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* 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())) && - (slot57_entry.empty() || publish_shader_request(key, L".ps57in", slot57_entry.data(), slot57_entry.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); } diff --git a/tests/checks/python-linux/startup_gfx2hlsl_ps57in.txt b/tests/checks/python-linux/startup_gfx2hlsl_ps57in.txt new file mode 100644 index 0000000000..7965caeb28 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_ps57in.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_ps57in_check.py diff --git a/tests/startup_gfx2hlsl_ps57in_check.py b/tests/startup_gfx2hlsl_ps57in_check.py new file mode 100644 index 0000000000..2d2f1a03e0 --- /dev/null +++ b/tests/startup_gfx2hlsl_ps57in_check.py @@ -0,0 +1,341 @@ +"""Slot 57 pixel entries (.ps57in) in the startup shader translator (#3385). + +With -NativeShaders (X2W_NATIVE_SHADERS set), the runtime appends a PSI1 suffix plus 8 bytes to the +key of every slot 57 graphics request and writes a .ps57in sidecar (src/startup_stubs/d3d12_draw.inl +cached_translation). The entry bytes are already hashed into the key on main (#3448: read_slot57_entry +and pipeline_key(..., slot57_entry=...)); what main still lacks, and this change adds, is three pieces, +all covered here with source-built fixtures (pure Python, no Windows, no GPU): +- tools/startup/gfx2hlsl.py takes the pixel input masks from the entry: request_ps_inputs() reads the + entry through main's read_slot57_entry, refuses a request with both .psin and .ps57in, validates the + entry's layout (address 2 or 0x8002 with 1 to 7 interpolants, as the native fixed entry builds them in + src/direct_compute_cache.cpp prepare_direct_graphics), and returns the address as both masks. No + .psdep is written for an entry (its bytes are part of the key, so a changed entry is a different + request). Anything wider is refused by name. tools/startup/shader_cache_rekey.py copies the entry + unchanged under its suffixed key. +- src/startup_stubs/d3d12_draw.inl reuses a translation already cached under the plain key: when + .txt is published, the entry leaves the key, so a warmed cache hits at once instead of waiting for + a retranslation under the suffixed key. Only a cold pipeline keeps the entry in its key. In + native-shaders-only mode (X2W_NATIVE_SHADERS_ONLY=1) the reuse is skipped, because .txt manifests are + ignored there and a leftover Python manifest would otherwise strip the entry from the request the native + path receives. The runtime behaviour is Windows-only, so the guard is pinned by source text here, with + mutants that must fail it. +- tools/startup/run.ps1 is untouched by this change: #3449 already made the launcher set + X2W_NATIVE_SHADERS_ONLY=1 unless -Translate is given, so on the default launcher path the reuse above + is skipped and load_translation never reads a .txt manifest; the masks and the reuse only change + -Translate runs. The live launcher path is covered by tests/startup_run_ps1_check.py. + +A slot 57 mesh request (.m57, translate_mesh57) is untouched by the fix and still translates: the +negative control for the mesh path. +""" +import os +import re +import struct +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +sys.path.insert(0, str(ROOT / 'tests')) +os.environ['X2W_FXC'] = '' # manifest only: no FXC/DXC on this host +import gfx2hlsl as G # noqa: E402 +import shader_cache_rekey as R # noqa: E402 +from startup_flat_param_check import VS_WORDS, PS_WORDS, root_blob # noqa: E402 +from startup_mesh57_skeleton_check import MESH, PIXEL, code as mesh_code, root as mesh_root # noqa: E402 + +VS, PS, ROOT_BLOB = VS_WORDS, PS_WORDS, root_blob() +ENTRY = b'PSI1' + struct.pack('..hlsl, or None when the translation never published it.""" + path = Path(directory) / ('%016x.%s.hlsl' % (key, stage)) + return path.read_bytes() if path.is_file() else None + + +# The suffixed key is the plain key hashed with the entry bytes, in runtime order, and nothing else. +key_parts = G.fnv(b'x2w-startup-shader-29') +for part in (VS, PS, ROOT_BLOB, ENTRY): + key_parts = G.fnv(part, key_parts) +expect('suffixed key hashes the entry after the plain key', KEY, key_parts) +expect('suffixed key differs from the plain key', KEY != BASE_KEY, True) +expect('plain key is unchanged by the fix', BASE_KEY, G.pipeline_key(VS, PS, ROOT_BLOB)) + +with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + # A suffixed request translates, applies the entry's masks, and is then complete: the watcher must + # not re-queue it. No .psdep is written for it: there is no .psin to lose. + put_request(d, KEY, entry=ENTRY) + expect('suffixed request translates', translate(d, KEY), 'ok') + expect('suffixed request publishes a manifest', (d / ('%016x.txt' % KEY)).is_file(), True) + expect('suffixed request writes no .fail', fail_text(d, KEY), None) + expect('suffixed request writes no .psdep', (d / ('%016x.psdep' % KEY)).is_file(), False) + expect('suffixed request masks are the entry address twice', + G.request_ps_inputs(str(d), KEY), (0x8002, 0x8002)) + expect('suffixed translation applies the entry masks', + PACKED_LINE in (hlsl_bytes(d, KEY, 'ps') or b'').decode('utf-8'), True) + expect('translated suffixed request is complete', G.pending_keys(str(d), False), []) + + # The plain request still translates, and without the entry its pixel stage has no packed position: + # the masks above really come from the .ps57in, and the two keys are two translations. + put_request(d, BASE_KEY) + expect('plain request still translates', translate(d, BASE_KEY), 'ok') + expect('plain translation has no packed position', + PACKED_LINE in (hlsl_bytes(d, BASE_KEY, 'ps') or b'').decode('utf-8'), False) + expect('plain and suffixed pixel stages differ', + hlsl_bytes(d, BASE_KEY, 'ps') != hlsl_bytes(d, KEY, 'ps'), True) + + # The native fixed entry accepts address 2 as well as 0x8002, with 1 to 7 interpolants: both ends of + # that range translate here. + addr2_entry = b'PSI1' + struct.pack('= 0 else None + + +def guard_problems(text): + """The plain-key reuse guard in cached_translation, and the mutants that must fail it.""" + body = cached_translation_body(text) + if body is None: + return ['cached_translation is missing from d3d12_draw.inl'] + found = [] + if 'std::string pixel_entry = slot57_entry;' not in body: + found.append('cached_translation does not keep the slot 57 entry in a local') + if not re.search(r'const bool base_cached = (!native_shaders_only\(\) && )?cache_path\(base_path, L"", key, L"\.txt"\) &&\s*' + r'GetFileAttributesW\(base_path\) != INVALID_FILE_ATTRIBUTES;', body): + found.append('cached_translation does not check for a published plain-key manifest') + if not re.search(r'const bool base_cached = !native_shaders_only\(\) &&', body): + found.append('cached_translation does not skip the plain-key reuse in native-shaders-only mode') + if 'if (base_cached) pixel_entry.clear();' not in body: + found.append('cached_translation does not drop the entry when the plain key is cached') + if 'else key = fnv_bytes(pixel_entry.data(), pixel_entry.size(), key);' not in body: + found.append('cached_translation does not suffix the key only for a cold pipeline') + if 'publish_shader_request(key, L".ps57in", pixel_entry.data(), pixel_entry.size())' not in body: + found.append('cached_translation does not publish .ps57in under the suffixed key') + if '(pixel_entry.empty() || publish_shader_request(key, L".ps57in"' not in body: + found.append('cached_translation does not gate the .ps57in publish on the kept entry') + return found + + +DRAW = (ROOT / 'src' / 'startup_stubs' / 'd3d12_draw.inl').read_text(encoding='utf-8') +expect('plain-key reuse guard is present', guard_problems(DRAW), []) +for label, mutant in { + 'guard removed': DRAW.replace('if (base_cached) pixel_entry.clear();\n', ''), + 'guard inverted': DRAW.replace('GetFileAttributesW(base_path) != INVALID_FILE_ATTRIBUTES', + 'GetFileAttributesW(base_path) == INVALID_FILE_ATTRIBUTES'), + 'guard checks bytecode, not the manifest': DRAW.replace( + 'cache_path(base_path, L"", key, L".txt")', 'cache_path(base_path, L"", key, L".vs.cso")'), + 'entry never dropped': DRAW.replace('if (base_cached) pixel_entry.clear();', + 'if (base_cached) pixel_entry.size();'), + 'native-shaders-only guard removed': DRAW.replace( + 'const bool base_cached = !native_shaders_only() && cache_path', + 'const bool base_cached = cache_path'), + 'publish gated on the wrong entry': DRAW.replace( + '(pixel_entry.empty() || publish_shader_request(key, L".ps57in"', + '(slot57_entry.empty() || publish_shader_request(key, L".ps57in"'), +}.items(): + expect("mutant '%s' fails the guard" % label, guard_problems(mutant) != [], True) + + +def main(): + for item in failures: + print('FAIL', item) + print('startup gfx2hlsl ps57in: %d failed' % len(failures)) + return 1 if failures else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_shader_cache_key_check.py b/tests/startup_shader_cache_key_check.py index f64ddf3e3f..a2e3e09013 100644 --- a/tests/startup_shader_cache_key_check.py +++ b/tests/startup_shader_cache_key_check.py @@ -59,7 +59,7 @@ def check_slot57_entry(vector, blobs, canonical): assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe", slot57_entry=entry) == 0x06315afc32bae986 entry_key = gfx2hlsl.pipeline_key(*blobs, slot57_entry=entry) assert entry_key == gfx2hlsl.fnv(entry, canonical) != canonical - accepted = check_request(blobs, entry_key, records={".ps57in": entry}) + check_request(blobs, entry_key, records={".ps57in": entry}) print("slot 57 entry: request keyed with its .ps57in accepted and published") check_request(blobs, canonical, BASE_MISMATCH, records={".ps57in": entry}) check_request(blobs, entry_key, BASE_MISMATCH) @@ -77,11 +77,12 @@ def check_slot57_entry(vector, blobs, canonical): check_request(blobs, both, "conflicting stream and slot-57 pixel entry records", records={".psin": description, ".ps57in": entry}) print("slot 57 entry: a request with both .psin and .ps57in refused by name") - # The translation does not read the record's values: another record under its own key gives the same shaders. - changed = check_request(blobs, gfx2hlsl.pipeline_key(*blobs, slot57_entry=other), records={".ps57in": other}) - for stage in (".vs.hlsl", ".ps.hlsl"): - assert accepted[f"{entry_key:016x}{stage}"] == changed[f"{gfx2hlsl.fnv(other, canonical):016x}{stage}"], stage - print("slot 57 entry: two records with the same stages translate to the same HLSL") + # request_ps_inputs reads the record's values: an address the native fixed entry does not accept + # (2 or 0x8002 with 1 to 7 interpolants) is refused by layout even under its own key, so a changed + # record no longer translates to the same shaders. The key still hashes the record as stored. + check_request(blobs, gfx2hlsl.pipeline_key(*blobs, slot57_entry=other), + "invalid slot-57 pixel entry layout", records={".ps57in": other}) + print("slot 57 entry: a record outside the fixed entry's layout is refused by name") for correct in (True, False): base = entry_key if correct else canonical request = f"rtv1 {base} 28" diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ac83e12139..0c8bdee786 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -13327,19 +13327,39 @@ def request_ps_inputs(out_dir, key): """The pixel input masks (SPI_PS_INPUT_ENA, SPI_PS_INPUT_ADDR) of one graphics request, or None. They come from the stream description request_source() names: req_.psin, the separately captured - description of exactly that pipeline (see read_ps_inputs), or for an RTV variant its source pipeline's. The - masks are part of the request's identity: the key must equal pipeline_key() of the stage blobs, root - signature, input layout and these masks, so a description copied from another pipeline, left stale after a - stage change or rewritten with another mask pair is refused, never applied. No file means no captured - description: the translation keeps its model without hardware inputs.""" + description of exactly that pipeline (see read_ps_inputs), or for an RTV variant its source pipeline's; or + from the slot 57 pixel entry req_.ps57in (see read_slot57_entry), whose address is both masks, as the + native fixed entry builds it. The masks are part of the request's identity: the key must equal + pipeline_key() of the stage blobs, root signature, input layout and these masks or that entry, so a + description copied from another pipeline, left stale after a stage change or rewritten with another mask + pair or entry is refused, never applied. No file means no captured description: the translation keeps its + model without hardware inputs. A request has one pixel entry or the other, never both. The entry's layout + is validated here: like the native fixed entry (src/direct_compute_cache.cpp prepare_direct_graphics), + only address 2 or 0x8002 with 1 to 7 interpolants is accepted; anything else is refused by name. The + native path additionally checks the count against the reflected pixel interface's attribute count and the + address against its reflected input address, which the Python reader has no interface for, so that part + stays native-only. + """ _, base, _, description = request_source(out_dir, key) masks = read_ps_inputs(description, base) - if masks is None: + entry = read_slot57_entry(os.path.join(out_dir, 'req_%016x.ps57in' % base)) + if masks is not None and entry: + raise Unsupported('conflicting stream and slot-57 pixel entry records') + if masks is None and not entry: return None name = os.path.join(out_dir, 'req_%016x' % base) a, b, root = (open(name + ext, 'rb').read() for ext in ('.a', '.b', '.root')) layout = open(name + '.ia', 'rb').read() if os.path.isfile(name + '.ia') else b'' - if pipeline_key(a, b, root, layout, masks) != base: + if entry: + address, interpolants = struct.unpack('.psin; pending_keys withdraws it when that + # file is gone. A slot 57 entry has no .psin to lose (its bytes are part of the key, so a changed + # entry is a different request), so no record is written for it. + if ps_inputs is not None and not os.path.isfile(os.path.join(out_dir, 'req_%016x.ps57in' % base)): record_dependency(out_dir, key, base, ps_inputs) # before the manifest is published except Unsupported: # A result published earlier was translated from sources or masks this request no longer confirms. diff --git a/tools/startup/shader_cache_rekey.py b/tools/startup/shader_cache_rekey.py index a1baf93941..c1cb4be86c 100644 --- a/tools/startup/shader_cache_rekey.py +++ b/tools/startup/shader_cache_rekey.py @@ -14,6 +14,7 @@ that already exists in is left as it is. Each file is written to a temporary name and renamed; the ready marker (.a, .c67, .m57) goes last, as the runtime writes it. A stream description (.psin) is written again under the new key with the same masks, since its line names the key and its masks are part of the key. +A slot 57 pixel entry (.ps57in) holds no key and is copied unchanged, since its bytes are part of the key. Slot 86 mesh requests are only counted. All requests are read before anything is written. When a request part is missing or unreadable, or an RTV @@ -31,9 +32,10 @@ REQUEST = re.compile(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57|m86)') # Request files of each kind; the ready marker is last. -PARTS = {'g': ('.b', '.root', '.ia', '.psin', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67'), +PARTS = {'g': ('.b', '.root', '.ia', '.psin', '.ps57in', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67'), 'm57': ('.ps57', '.root', '.m57')} -OPTIONAL = {'.ia', '.psin'} # a graphics request may have no input layout (.ia) and no stream description (.psin) +OPTIONAL = {'.ia', '.psin', '.ps57in'} # a graphics request may have no input layout (.ia) and no stream +# description (.psin) or slot 57 pixel entry (.ps57in); the entry holds no key, so it is copied unchanged class Incomplete(Exception): @@ -63,11 +65,17 @@ def current_key(job): except OSError as error: return kind, key, None, 'unreadable %s: %s' % (os.path.basename(error.filename or ''), error.strerror) if kind == 'g': - # The pixel input masks of a stream description are part of the key; the description names its key. + # The pixel input masks of a stream description, or the bytes of a slot 57 pixel entry, are part of + # the key; the description names its key. A request has one pixel entry or the other, never both. try: masks = g.read_ps_inputs(request_name(src, key, '.psin'), key) + entry = g.read_slot57_entry(request_name(src, key, '.ps57in')) except g.Unsupported as reason: return kind, key, None, str(reason) + if masks is not None and entry: + return kind, key, None, 'conflicting stream and slot-57 pixel entry records' + if entry: + return kind, key, g.pipeline_key(p['.a'], p['.b'], p['.root'], p.get('.ia', b''), slot57_entry=entry), None return kind, key, g.pipeline_key(p['.a'], p['.b'], p['.root'], p.get('.ia', b''), masks), None if kind == 'm57': return kind, key, g.mesh57_key(p['.m57'], p['.ps57'], p['.root']), None