diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index cd22a2a6c0..c74995fb50 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -285,6 +285,7 @@ jobs: tests/startup_run_sh_check.py \ tests/startup_flat_param_check.py \ tests/startup_ps_input_scan_check.py \ + tests/startup_packed_position_provenance_check.py \ tests/startup_build_rev_check.py \ tests/startup_gfx2hlsl_bit_alu_check.py \ tests/startup_gfx2hlsl_interp_f16_check.py tests/startup_gfx2hlsl_interp_p2_hi_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 2ef17d51ba..fd65004251 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3661,11 +3661,19 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_ps_input_scan_check.py") add_test(NAME startup_ps_input_scan_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_ps_input_scan_cli_check.py") + # The pixel input masks come from the captured stream description of the exact pipeline (#1629): a decoy + # description, stale or missing masks and contradictory enable/address masks; then the #1634 gradient draw. + add_test(NAME startup_packed_screen_position_provenance COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_packed_position_provenance_check.py") foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_packed_screen_position_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_packed_position_check.py" "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_packed_screen_position_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_packed_screen_position_provenance_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_packed_position_provenance_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_packed_screen_position_provenance_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_flat_param_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_flat_param_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) diff --git a/tests/startup_packed_position_provenance_check.py b/tests/startup_packed_position_provenance_check.py new file mode 100644 index 0000000000..5182ac18ca --- /dev/null +++ b/tests/startup_packed_position_provenance_check.py @@ -0,0 +1,426 @@ +"""Pixel input masks from the captured stream description of the exact pipeline (#1629). + + (no arguments) association controls, pure Python + draw [fxc] + translate the requests below through translate_request, compile the + pixel stage (DXC ps_6_0, and FXC ps_5_1 when given) and draw it with the + #1634 gradient: every pixel must read back its own packed x | (y << 16); + with fxc, also the compiled-result path of a rewritten description + +Two source-built requests share one cache directory. Each has a stream description, req_.psin: + target exports v4; enable 0x8002 (PERSP_CENTER, POS_FIXED_PT) and address 0x8003 (PERSP_SAMPLE allocated + but not enabled). The address mask lays out v0..v1 PERSP_SAMPLE, v2..v3 PERSP_CENTER, v4 the packed + position. Laying out by the enable mask would put the position in v2. + decoy exports v2; enable = address = 0x8002, so its position is v2. +Both draw correctly only when each translation takes the masks of its own description, so no fixed register +and no mask taken from the other description passes. The controls also refuse, by name, a description that +names another pipeline, a stale description whose stage blobs changed, a missing enable or address mask, +contradictory masks (an enabled input not allocated) and a malformed line. + +The masks are part of the request identity (pipeline_key with ps_inputs). In the same cache, pipelines with +the target's exact stage bytes, root signature and input layout but another mask pair are requests of their +own: 0x8003/0x8003 also places the position in v4 and draws the gradient; 0x8002/0x8002 places it in v2, so +the v4 this code reads is not the position and the draw fails at (1,0) as expected. They arrive after the +target's result exists and are translated as new requests, leaving that result untouched. A description +rewritten in place with another pair after its result was published is checked again, refused by name and +its old result withdrawn. The watcher follows the description each translation reads (an RTV variant reads its +source pipeline's): a wrong pair in a base description withdraws the base and its variant, and the corrected +description, newer than their failures, publishes both again without touching the request files. A result +translated with a description records it (.psdep): removing only the base description withdraws the base +and its variant and refuses both by name, while a legacy request that never had a description has no record +and is not checked again. +""" +import os +import re +import struct +import subprocess +import sys +import tempfile +from contextlib import contextmanager +from pathlib import Path + +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, G, compile_hlsl, root_blob + +TARGET = (0x8002, 0x8003) # (enable, address): the packed position in v4 +DECOY = (0x8002, 0x8002) # the packed position in v2 +SAME_V4 = (0x8003, 0x8003) # another valid pair with the packed position in v4 (PERSP_SAMPLE also enabled) + + +def ps_words(reg): + # exp mrt0 vN, vN, vN, vN done vm; s_endpgm (the #1634 fixture's pixel stage) + return struct.pack('.a/.b/.root for VS_WORDS and `ps` under pipeline_key() with `masks`, and the stream + description: `line` when given, else the line naming that key and `masks` (none without masks).""" + key = G.pipeline_key(VS_WORDS, ps, root_blob(), ps_inputs=masks) + name = cache / ('req_%016x' % key) + for ext, blob in (('.b', ps), ('.root', root_blob()), ('.a', VS_WORDS)): + name.with_suffix(ext).write_bytes(blob) + description = line if line is not None else describe(key, masks) if masks else None + if description is not None: + name.with_suffix('.psin').write_bytes(description.encode('ascii')) + return key + + +def describe(key, masks): + return 'psin1 %016x ena=0x%04x addr=0x%04x\n' % (key, *masks) + + +@contextmanager +def fxc_setting(fxc=''): + """X2W_FXC for the translator: by default the manifest-only path (''), where a published manifest is a + finished result without bytecode; with an fxc path, the compile path.""" + previous = os.environ.get('X2W_FXC') + os.environ['X2W_FXC'] = fxc + try: + yield + finally: + if previous is None: + del os.environ['X2W_FXC'] + else: + os.environ['X2W_FXC'] = previous + + +def pending(cache, fxc=''): + """The keys a later --watch pass would translate (failures already written are skipped).""" + with fxc_setting(fxc): + return G.pending_keys(str(cache), True) + + +def watch_pass(cache): + """One translate_pending pass as --watch runs it, on the manifest-only path.""" + with fxc_setting(): + G.translate_pending(str(cache), skip_failed=True, jobs=1) + + +def translated_ps(cache, key, through_pending=False): + """translate_request with the manifest-only path: the pixel HLSL, or the refusal. With through_pending, a + translate_pending pass (as --pending and --watch run it) translates whatever it finds pending instead.""" + with fxc_setting(): + if through_pending: + G.translate_pending(str(cache), skip_failed=True, jobs=1) + fail = cache / ('%016x.fail' % key) + result = 'ok' if (cache / ('%016x.txt' % key)).is_file() else ( + 'unsupported: ' + fail.read_text().strip() if fail.is_file() else 'not translated') + else: + result = G.translate_request(str(cache), key) + if result != 'ok': + return None, result + return (cache / ('%016x.ps.hlsl' % key)).read_text(), result + + +def packed_line(text): + found = re.findall(r'\bv(\d+) = \(uint\(i\.pos\.x\) & 0xffffu\)', text) + return [int(n) for n in found] + + +def build_pair(cache, target=TARGET, decoy=DECOY): + return put_request(cache, ps_words(4), target), put_request(cache, ps_words(2), decoy) + + +def controls(): + failures = [] + + def check(label, ok): + print(('ok ' if ok else 'FAIL ') + label) + if not ok: + failures.append(label) + + def refused(label, cache, key, reason): + text, result = translated_ps(cache, key) + rows = G.request_refusals(str(cache), key) + check(label, text is None and reason in result and any(reason in r for r, _ in rows)) + + # The translator lays out by the address mask and loads by the enable mask. + pipe = G.Pipeline(VS_WORDS, ps_words(4), root_blob(), ps_hw_inputs=TARGET) + check('distinct masks: position after the allocated PERSP_SAMPLE and PERSP_CENTER pairs (v4)', + pipe.packed_position_vgpr == 4 and pipe.persp_center_vgpr == 2) + pipe = G.Pipeline(VS_WORDS, ps_words(4), root_blob(), ps_hw_inputs=(0x0002, 0x8002)) + check('position allocated but not enabled is not modelled', pipe.packed_position_vgpr is None) + for masks in ((0x8003, 0x8002), (0x8100, 0x8000)): + try: + G.Pipeline(VS_WORDS, ps_words(4), root_blob(), ps_hw_inputs=masks) + except G.Unsupported as err: + check('contradictory masks %04x/%04x refused by name' % masks, + 'contradictory pixel input enable/address masks' in str(err)) + else: + check('contradictory masks %04x/%04x refused by name' % masks, False) + + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t, d = build_pair(cache) + text, _ = translated_ps(cache, t) + check('target takes its own description: packed position in v4', text is not None and packed_line(text) == [4]) + text, _ = translated_ps(cache, d) + check('decoy takes its own description: packed position in v2', text is not None and packed_line(text) == [2]) + check('refusal report sees no refusal for either request', + G.request_refusals(str(cache), t) == [] and G.request_refusals(str(cache), d) == []) + # An RTV variant reads its source pipeline's description. + request = 'rtv1 %d 28' % t + variant = G.fnv(request.encode('ascii')) + (cache / ('req_%016x.rtv' % variant)).write_text(request, encoding='ascii') + text, _ = translated_ps(cache, variant) + check('RTV variant takes its source pipeline description: v4', text is not None and packed_line(text) == [4]) + + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t = put_request(cache, ps_words(4)) + text, _ = translated_ps(cache, t) + check('no captured description: no hardware inputs, position not modelled (today)', + text is not None and packed_line(text) == []) + + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t, d = build_pair(cache) + # The decoy's description copied over the target's. + (cache / ('req_%016x.psin' % t)).write_bytes((cache / ('req_%016x.psin' % d)).read_bytes()) + refused('decoy description under the target name refused', cache, t, + 'pixel input description names another pipeline') + # A stale description: the line names the key, but the stored pixel stage changed after capture. + (cache / ('req_%016x.psin' % t)).write_bytes(describe(t, TARGET).encode('ascii')) + (cache / ('req_%016x.b' % t)).write_bytes(ps_words(2)) + refused('stale description (stage blob changed) refused', cache, t, + 'pixel input description names another pipeline') + + for label, line, reason in ( + ('missing address mask', 'psin1 {k} ena=0x8002\n', 'pixel input address mask missing from the stream description'), + ('missing enable mask', 'psin1 {k} addr=0x8003\n', 'pixel input enable mask missing from the stream description'), + ('no masks', 'psin1 {k}\n', 'pixel input enable mask missing from the stream description'), + ('contradictory masks', 'psin1 {k} ena=0x8003 addr=0x8002\n', 'contradictory pixel input enable/address masks'), + ('duplicate mask', 'psin1 {k} ena=0x8002 ena=0x8002\n', 'invalid pixel input description'), + ('malformed line', 'psin1 {k} ena=8002 addr=8003\n', 'invalid pixel input description'), + ('unknown version', 'psin2 {k} ena=0x8002 addr=0x8003\n', 'invalid pixel input description'), + ): + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + masks = tuple(int(m, 16) for m in re.findall(r'(?:ena|addr)=(0x[0-9a-f]+)', line)) + masks = masks if len(masks) == 2 else None + t = G.pipeline_key(VS_WORDS, ps_words(4), root_blob(), ps_inputs=masks) + put_request(cache, ps_words(4), masks, line=line.format(k='%016x' % t)) + refused(label + ' refused by name', cache, t, reason) + + # One cache, pipelines with identical stage bytes, root signature and input layout but different masks. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + bare = G.pipeline_key(VS_WORDS, ps_words(4), root_blob()) + check('without a description the key is unchanged', + bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-17'))))) + keys = [put_request(cache, ps_words(4), masks) for masks in (TARGET, SAME_V4, DECOY)] + check('same stages, root and layout with three mask pairs: three request identities', + len(set(keys)) == 3 and bare not in keys + and all(len(list(cache.glob('req_%016x.*' % key))) == 4 for key in keys)) + texts = [translated_ps(cache, key)[0] for key in keys] + # Under the third pair the position is v2, so the v4 this code reads is not the position. + check('same cache: each pipeline takes its own masks (position v4, v4, not v4), each result under its own key', + None not in texts and [packed_line(text) for text in texts] == [[4], [4], []] + and all((cache / ('%016x.txt' % key)).is_file() for key in keys)) + + # A different mask pair for the same stage bytes after a result exists. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t = put_request(cache, ps_words(4), TARGET) + translated_ps(cache, t, through_pending=True) + published = {ext: (cache / ('%016x%s' % (t, ext))).read_bytes() for ext in ('.txt', '.ps.hlsl')} + w = put_request(cache, ps_words(4), DECOY) + check('another mask pair after the result exists is a pending request of its own', pending(cache) == [w]) + text, _ = translated_ps(cache, w, through_pending=True) + check('it is translated with its own masks (position not v4), the existing result untouched', + text is not None and packed_line(text) == [] + and all((cache / ('%016x%s' % (t, ext))).read_bytes() == data for ext, data in published.items())) + # The target's own description rewritten in place with the other pair, its line still naming the target. + manifest = cache / ('%016x.txt' % t) + stamp = manifest.stat().st_mtime - 100 + os.utime(manifest, (stamp, stamp)) + (cache / ('req_%016x.psin' % t)).write_bytes(describe(t, DECOY).encode('ascii')) + check('a description rewritten after the result is published is checked again', pending(cache) == [t]) + text, result = translated_ps(cache, t, through_pending=True) + check('the rewritten mask pair is refused by name and the old result withdrawn, not reused', + text is None and 'pixel input description names another pipeline' in result and not manifest.is_file()) + check('the refusal is not retried while the request stays the same', pending(cache) == []) + # A description rewritten with the same masks is checked once, then the result counts as done again. + manifest = cache / ('%016x.txt' % w) + stamp = manifest.stat().st_mtime - 100 + os.utime(manifest, (stamp, stamp)) + (cache / ('req_%016x.psin' % w)).write_bytes(describe(w, DECOY).encode('ascii')) + first = pending(cache) + text, _ = translated_ps(cache, w, through_pending=True) + check('a description rewritten unchanged is checked once, then done', + first == [w] and text is not None and packed_line(text) == [] and pending(cache) == []) + + # The watcher follows the description each translation reads: an RTV variant depends on its source's. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t = put_request(cache, ps_words(4), TARGET) + request = 'rtv1 %d 28' % t + v = G.fnv(request.encode('ascii')) + (cache / ('req_%016x.rtv' % v)).write_text(request, encoding='ascii') + for path in cache.glob('req_*'): # captured well before anything below + stamp = path.stat().st_mtime - 1000 + os.utime(path, (stamp, stamp)) + sources = {path: (path.read_bytes(), path.stat().st_mtime_ns) + for path in (cache / ('req_%016x.a' % t), cache / ('req_%016x.rtv' % v))} + watch_pass(cache) + manifests = [cache / ('%016x.txt' % key) for key in (t, v)] + description = cache / ('req_%016x.psin' % t) + check('base and RTV variant published, nothing pending', all(m.is_file() for m in manifests) and pending(cache) == []) + # The base description rewritten with the wrong pair (its line still naming the base), newer than both manifests. + for path in manifests: + if path.is_file(): + stamp = path.stat().st_mtime - 100 + os.utime(path, (stamp, stamp)) + description.write_bytes(describe(t, DECOY).encode('ascii')) + check('a wrong pair in the base description queues the base and its RTV variant', pending(cache) == sorted([t, v])) + watch_pass(cache) + fails = [cache / ('%016x.fail' % key) for key in (t, v)] + check('both refused by name and both published results withdrawn', + not any(m.is_file() for m in manifests) and all(f.is_file() for f in fails) + and 'pixel input description names another pipeline' in fails[0].read_text() + and 'RTV variant source key mismatch' in fails[1].read_text()) + check('the refusals are not retried while the description stays the same', pending(cache) == []) + # The valid description restored, newer than both failures. + for path in fails: + if path.is_file(): + stamp = path.stat().st_mtime - 100 + os.utime(path, (stamp, stamp)) + description.write_bytes(describe(t, TARGET).encode('ascii')) + check('the restored description, newer than the failures, queues both again', pending(cache) == sorted([t, v])) + watch_pass(cache) + texts = [(cache / ('%016x.ps.hlsl' % key)).read_text() if m.is_file() else '' for key, m in zip((t, v), manifests)] + check('both republished from the restored description (position v4), .a and .rtv untouched', + all(m.is_file() for m in manifests) and [packed_line(text) for text in texts] == [[4], [4]] + and all((path.read_bytes(), path.stat().st_mtime_ns) == state for path, state in sources.items()) + and pending(cache) == []) + # Only the base description removed: both results were translated with it, so both are withdrawn. + records = [cache / ('%016x.psdep' % key) for key in (t, v)] + check('both results record the description line they were translated with', + all(r.is_file() and r.read_text() == describe(t, TARGET) for r in records)) + # The failures of the wrong-pair cycle stay: on the manifest-only path a success does not remove them. + description.unlink() + check('a removed description queues the base and its RTV variant', pending(cache) == sorted([t, v])) + watch_pass(cache) + check('both refused by name as missing their description and both published results withdrawn', + not any(m.is_file() for m in manifests) and all(f.is_file() for f in fails) + and all('pixel input description missing for a request translated with one' in f.read_text() + for f in fails)) + check('the refusals are not retried while the description stays missing', pending(cache) == []) + for path in fails: + if path.is_file(): + stamp = path.stat().st_mtime - 100 + os.utime(path, (stamp, stamp)) + description.write_bytes(describe(t, TARGET).encode('ascii')) + check('the description restored again queues both', pending(cache) == sorted([t, v])) + watch_pass(cache) + check('both republished from the restored description', + all(m.is_file() for m in manifests) and pending(cache) == []) + + # A legacy request that never had a description: no dependency record, and its result stays done. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + legacy = put_request(cache, ps_words(4)) + watch_pass(cache) + check('a legacy request publishes without a dependency record and is not checked again', + (cache / ('%016x.txt' % legacy)).is_file() and not (cache / ('%016x.psdep' % legacy)).exists() + and pending(cache) == []) + + # Re-keying a cache keeps both pipelines and their descriptions, each naming its own key. + with tempfile.TemporaryDirectory() as tmp: + old, new = Path(tmp) / 'old', Path(tmp) / 'new' + old.mkdir() + keys = [put_request(old, ps_words(4), masks) for masks in (TARGET, DECOY)] + import io + import shader_cache_rekey + status = shader_cache_rekey.rekey(str(old), str(new), jobs=1, out=io.StringIO()) + check('re-keying keeps both mask pairs as requests with their own descriptions', + status == 0 and all((new / ('req_%016x.psin' % key)).read_bytes() == describe(key, masks).encode('ascii') + for key, masks in zip(keys, (TARGET, DECOY))) + and sorted(p.name for p in new.glob('req_*.psin')) == sorted('req_%016x.psin' % key for key in keys)) + + if failures: + print('%d control(s) failed' % len(failures)) + return 1 + print('controls: masks from the exact pipeline description; decoy, stale, missing and contradictory refused; ' + 'masks in the request identity') + return 0 + + +def draw(dxc, renderer, adapter, fxc=None): + compilers = [('dxc', dxc, '6_0')] + if fxc: + compilers.append(('fxc', fxc, '5_1')) + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + cache = folder / 'cache' + cache.mkdir() + t, d = build_pair(cache) + sources = {} + for label, key in (('target', t), ('decoy', d)): + text, result = translated_ps(cache, key) + assert text is not None, (label, result) + sources[label] = text + # After those results exist, two more pipelines with the target's exact stage bytes, root signature and + # input layout arrive in the same cache: one whose masks also place the position in v4, and one whose + # masks place it in v2 (wrong register for this code). Each is a request of its own and is translated. + same = put_request(cache, ps_words(4), SAME_V4) + wrong = put_request(cache, ps_words(4), DECOY) + assert len({t, d, same, wrong}) == 4 and pending(cache) == sorted([same, wrong]), 'identities' + for label, key in (('same bytes, other masks (v4)', same), ('same bytes, other masks (v2)', wrong)): + text, result = translated_ps(cache, key, through_pending=True) + assert text is not None, (label, result) + sources[label] = text + for kind, compiler, profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs', 'vs_' + profile, folder) + for label, good in (('target', True), ('decoy', True), ('same bytes, other masks (v4)', True), + ('same bytes, other masks (v2)', False)): + ps = compile_hlsl(compiler, kind, sources[label], 'ps', 'ps_' + profile, folder) + run = subprocess.run([renderer, adapter, '--startup-packed-position', vs, ps], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + if good: + assert run.returncode == 0 and 'all 91 packed positions matched' in run.stdout, (label, run.stdout, run.stderr) + else: + assert run.returncode != 0 and 'position mismatch (1,0): expected 00000001 actual 00000000' in run.stderr, (label, run.stderr) + device = [line for line in run.stdout.splitlines() if line.startswith(('backend=', 'adapter=', 'debug_'))] + print(f'{kind} {adapter} {label}: ' + ('91 pixels matched' if good else 'expected mismatch at (1,0)') + + ' [%s]' % '; '.join(device)) + if fxc: + compiled_results(folder / 'compiled', fxc) + return 0 + + +def compiled_results(cache, fxc): + """With bytecode (FXC), an unchanged manifest is not rewritten. A description rewritten unchanged is still + checked once and then done, and one rewritten with another mask pair withdraws the published result.""" + cache.mkdir() + t = put_request(cache, ps_words(4), TARGET) + with fxc_setting(fxc): + G.translate_pending(str(cache), skip_failed=True, jobs=1) + manifest = cache / ('%016x.txt' % t) + assert manifest.is_file() and (cache / ('%016x.ps.cso' % t)).is_file() and pending(cache, fxc) == [], 'compiled' + for masks, done in ((TARGET, True), (DECOY, False)): + stamp = manifest.stat().st_mtime - 100 + os.utime(manifest, (stamp, stamp)) + (cache / ('req_%016x.psin' % t)).write_bytes(describe(t, masks).encode('ascii')) + assert pending(cache, fxc) == [t], ('checked again', masks) + with fxc_setting(fxc): + G.translate_pending(str(cache), skip_failed=True, jobs=1) + assert pending(cache, fxc) == [] and manifest.is_file() == done, ('checked once', masks) + assert 'pixel input description names another pipeline' in (cache / ('%016x.fail' % t)).read_text() + print('fxc compiled result: rewritten description checked once; another mask pair withdraws the result') + + +def main(argv): + if not argv: + return controls() + mode, *args = argv + if mode == 'draw': + status = controls() + return status or draw(*args) + raise SystemExit(__doc__) + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ce212659df..c8c28c7fa9 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7159,10 +7159,17 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( # one is enabled). Without hardware inputs the model assumes the center pair alone: v0, v1. self.persp_center_vgpr = 0 if ps_hw_inputs is not None: + # SPI_PS_INPUT_ADDR allocates the entry VGPRs in bit order; SPI_PS_INPUT_ENA chooses which of the + # allocated inputs are loaded. Every enabled input is also allocated (LLVM AMDGPUAsmPrinter + # getSIProgramInfo: "all enabled inputs are tagged in InputAddr as well"; SIISelLowering + # processPSInputArgs marks an input allocated, then enabled only when it is used). ena, addr = ps_hw_inputs - if ena != addr or not 0 <= ena <= 0xffff: + if not (0 <= ena <= 0xffff and 0 <= addr <= 0xffff): raise Unsupported('unverified pixel input enable/address combination') - self.persp_center_vgpr = (2 if addr & 1 else 0) if addr & 2 else None + if ena & ~addr: + raise Unsupported('contradictory pixel input enable/address masks: an enabled input is not allocated') + # Layout from the address mask; an input allocated but not enabled holds no loaded value. + self.persp_center_vgpr = (2 if addr & 1 else 0) if ena & 2 else None if ena & (1 << 15): # SPI PS inputs 0..6 supply IJ pairs (the pull model supplies three); # line stipple through sample coverage each occupy one VGPR. @@ -7810,10 +7817,16 @@ def fnv(data, h=1469598103934665603): return h -def pipeline_key(vs_code, ps_code, root_blob, layout=b''): - """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout.""" +def pipeline_key(vs_code, ps_code, root_blob, layout=b'', ps_inputs=None): + """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout. + + A pipeline with a stream description (req_.psin) also hashes its pixel input masks: b'psin1' and then + SPI_PS_INPUT_ENA and SPI_PS_INPUT_ADDR as little-endian u32. Two pipelines with the same stages, root + signature and input layout but different masks are then two requests with their own results. Without a + description the key is unchanged.""" key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-17')))) - return fnv(layout, key) if layout else key + key = fnv(layout, key) if layout else key + return key if ps_inputs is None else fnv(b'psin1' + struct.pack('.vs.hlsl, .ps.hlsl and .txt (last), or .fail with the reason. With check, the pair is compiled to .vs.cso and .ps.cso first and a missing fxc is a failure. check=False, or X2W_FXC set to the empty string, publishes the manifest without bytecode.""" name = os.path.join(out_dir, '%016x' % key) try: - pipe = Pipeline(vs_code, ps_code, root_blob, rtv_formats=rtv_formats, vs_fetch=vs_fetch, ps_attr_map=ps_attr_map) + pipe = Pipeline(vs_code, ps_code, root_blob, rtv_formats=rtv_formats, vs_fetch=vs_fetch, ps_attr_map=ps_attr_map, + ps_hw_inputs=ps_hw_inputs) vs, ps, manifest = pipe.hlsl_vs(), pipe.hlsl_ps(), pipe.manifest() if rtv_request: manifest += rtv_request + '\n' @@ -8099,27 +8113,21 @@ def classify_stage(blob): decoded[kind] = ins return kind - name = os.path.join(out_dir, 'req_%016x' % key) - request = '' - formats = () - base = key - if os.path.isfile(name + '.rtv'): - with open(name + '.rtv', encoding='ascii') as file: - request = file.read(256) - if not re.fullmatch(r'rtv1 [0-9]{1,20}(?: [0-9]{1,10}){1,8}', request) or fnv(request.encode('ascii')) != key: - raise Unsupported('invalid RTV variant request') - base, *formats = map(int, request.split()[1:]) - if base > 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): - raise Unsupported('invalid RTV variant values') - name = os.path.join(out_dir, 'req_%016x' % base) + request, base, formats, description = request_source(out_dir, key) + name = os.path.join(out_dir, 'req_%016x' % base) a, b, root = (open(name + ext, 'rb').read() for ext in ('.a', '.b', '.root')) if pair_info is not None and not request: import hashlib pair_info.append((hashlib.sha256(struct.pack('.rtv) names its source pipeline and is translated + from that pipeline's blobs and stream description, req_.psin. This is the one place that names the + description a request depends on: the translation reads its masks from that path, and pending_keys checks + the same path to withdraw a published result or retry a failure after the description changes or, for a + result recorded as translated with it (dependency_record), is removed. The path is returned whether or not the + file exists. An invalid variant line is refused by name.""" + name = os.path.join(out_dir, 'req_%016x' % key) + request = '' + formats = () + base = key + if os.path.isfile(name + '.rtv'): + with open(name + '.rtv', encoding='ascii') as file: + request = file.read(256) + if not re.fullmatch(r'rtv1 [0-9]{1,20}(?: [0-9]{1,10}){1,8}', request) or fnv(request.encode('ascii')) != key: + raise Unsupported('invalid RTV variant request') + base, *formats = map(int, request.split()[1:]) + if base > 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): + raise Unsupported('invalid RTV variant values') + return request, base, formats, os.path.join(out_dir, 'req_%016x.psin' % base) + + +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.""" + _, base, _, description = request_source(out_dir, key) + masks = read_ps_inputs(description, base) + if masks is None: + 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: + raise Unsupported('pixel input description names another pipeline') + return masks + + +def dependency_record(out_dir, key): + """.psdep: written when a graphics request is translated with a stream description, before its manifest. + + It marks a result as known to depend on the description request_source() names, so pending_keys can withdraw + that result when the description is removed. A legacy request that never had a description has no record, and + its inputs are not read again. The record holds the description line the result was translated with.""" + return os.path.join(out_dir, '%016x.psdep' % key) + + +def record_dependency(out_dir, key, base, masks): + path = dependency_record(out_dir, key) + line = 'psin1 %016x ena=0x%04x addr=0x%04x\n' % (base, *masks) + with suppress(FileNotFoundError, UnicodeError), open(path) as existing: + if existing.read() == line: + return + temporary = '%s.%d.tmp' % (path, os.getpid()) + try: + with open(temporary, 'w') as record: + record.write(line) + os.replace(temporary, path) + finally: + with suppress(FileNotFoundError): + os.remove(temporary) + + +def read_ps_inputs(path, key): + """The (enable, address) masks in the stream description at `path` (req_.psin), one ASCII line + 'psin1 ena= addr=' (the key as 16 hex digits, the masks as 0x-prefixed 16-bit values), or + None without the file. The line must name `key`; a malformed line or a missing mask is refused by name.""" + if not os.path.isfile(path): + return None + with open(path, 'rb') as file: + line = file.read(128) + fields = line.decode('ascii', 'replace').split() + if not re.fullmatch(rb'psin1 [0-9a-f]{16}(?: (?:ena|addr)=0x[0-9a-f]{1,4}){0,2}\n?', line): + raise Unsupported('invalid pixel input description') + masks = dict(field.split('=') for field in fields[2:]) + if len(masks) != len(fields) - 2: + raise Unsupported('invalid pixel input description') + if int(fields[1], 16) != key: + raise Unsupported('pixel input description names another pipeline') + for field, label in (('ena', 'enable'), ('addr', 'address')): + if field not in masks: + raise Unsupported('pixel input %s mask missing from the stream description' % label) + return int(masks['ena'], 16), int(masks['addr'], 16) + + def mesh57_key(ms, ps, root): value = fnv(b'x2w-startup-mesh-57-2') for part in (ms, ps, root): @@ -8220,15 +8320,32 @@ def translate_request(out_dir, key): open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason try: - kinds, root, formats, request, fetch, _, attr_map = load_request(out_dir, key, validate_base_key=True) + try: + _, base, _, description = request_source(out_dir, key) + if os.path.isfile(dependency_record(out_dir, key)) and not os.path.isfile(description): + raise Unsupported('pixel input description missing for a request translated with one') + kinds, root, formats, request, fetch, _, attr_map = load_request(out_dir, key, validate_base_key=True) + ps_inputs = request_ps_inputs(out_dir, key) + if ps_inputs is not None: + 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. + with suppress(FileNotFoundError): + os.remove(os.path.join(out_dir, '%016x.txt' % key)) + raise except (Unsupported, OSError, UnicodeError) as reason: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason if set(kinds) != {'vs', 'ps'}: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write('stages %s\n' % sorted(kinds)) return 'stages %s' % sorted(kinds) - return translate_to(out_dir, key, kinds['vs'], kinds['ps'], root, rtv_formats=formats, rtv_request=request, vs_fetch=fetch, - ps_attr_map=attr_map) + result = translate_to(out_dir, key, kinds['vs'], kinds['ps'], root, rtv_formats=formats, rtv_request=request, + vs_fetch=fetch, ps_attr_map=attr_map, ps_hw_inputs=ps_inputs) + if ps_inputs is not None and result == 'ok': + # An unchanged manifest is not rewritten; mark it as checked against this description (pending_keys). + with suppress(FileNotFoundError): + os.utime(os.path.join(out_dir, '%016x.txt' % key)) + return result REFUSALS_CAVEAT = ('Counts after the first refusal are approximate. Skipped instructions leave later state ' @@ -8279,7 +8396,8 @@ def request_refusals(out_dir, key, pair_info=None): """Collect reached refusal sites for one request without publishing a translation.""" refusals = [] try: - kinds, root, formats, _, fetch, decoded, attr_map = load_request(out_dir, key, refusals, pair_info) + kinds, root, formats, request, fetch, decoded, attr_map = load_request(out_dir, key, refusals, pair_info) + ps_inputs = request_ps_inputs(out_dir, key) except Unsupported as reason: refusals.append((str(reason), 'pipeline')) return refusals @@ -8299,7 +8417,7 @@ def request_refusals(out_dir, key, pair_info=None): if set(kinds) != {'vs', 'ps'}: raise Unsupported('stages %s' % sorted(kinds)) pipe = Pipeline(kinds['vs'], kinds['ps'], root, rtv_formats=formats, vs_fetch=fetch, - refusals=refusals, decoded=decoded, ps_attr_map=attr_map) + refusals=refusals, decoded=decoded, ps_attr_map=attr_map, ps_hw_inputs=ps_inputs) op = 'hlsl_vs' pipe.hlsl_vs() op = 'hlsl_ps' @@ -8550,8 +8668,21 @@ def pending_keys(out_dir, skip_failed): stages = ('.cs.cso',) if m.group(2) == 'c67' else ('.ms57.cso', '.ps57.cso') if mesh else ('.vs.cso', '.ps.cso') ready_bytecode = has_complete_mesh57_bytecode if mesh else has_bytecode manifest = result + ('.ms57.txt' if mesh else '.txt') - # A published manifest with bytecode (or manifest-only mode) is done; otherwise resume (#2008). - if os.path.isfile(manifest): + # A published manifest with bytecode (or manifest-only mode) is done; otherwise resume (#2008). The stream + # description the translation reads (request_source: the request's own, or an RTV variant's source + # pipeline's) is a dependency like the request file. Rewritten after the result was published, the result + # is checked again, so one translated with other masks is not kept in silence; rewritten after a refusal, + # the request is retried. + described = None + lost = False + if m.group(2) in ('a', 'rtv'): + with suppress(Unsupported, OSError, UnicodeError): # no description, or a variant line refused later + described = os.path.getmtime(request_source(out_dir, key)[3]) + # A result translated with a description recorded it (dependency_record). With that description gone, + # the result is checked again and withdrawn; a legacy request without a record is not read again. + lost = described is None and os.path.isfile(result + '.psdep') + if os.path.isfile(manifest) and not lost and not ( + described is not None and described > os.path.getmtime(manifest)): if manifest_only or all(ready_bytecode(result + s) for s in stages): continue if mesh and has_complete_mesh57_bytecode(result + '.ms57.cso'): @@ -8559,8 +8690,12 @@ def pending_keys(out_dir, skip_failed): if b'ps none' in published.read().splitlines(): continue fail = os.path.join(out_dir, '%016x.fail' % key) - # A repeated pass retries a failure only once its request is rewritten. - if skip_failed and os.path.exists(fail) and os.path.getmtime(fail) >= os.path.getmtime(os.path.join(out_dir, name)): + # A repeated pass retries a failure only once its request or its stream description is rewritten. A result + # still published without its recorded description is checked even with an older .fail, which a success on + # the manifest-only path leaves in place. + recheck = lost and os.path.isfile(manifest) + if skip_failed and not recheck and os.path.exists(fail) and os.path.getmtime(fail) >= max( + os.path.getmtime(os.path.join(out_dir, name)), described or 0): continue keys.append(key) return keys diff --git a/tools/startup/shader_cache_rekey.py b/tools/startup/shader_cache_rekey.py index 64db2d903a..a1baf93941 100644 --- a/tools/startup/shader_cache_rekey.py +++ b/tools/startup/shader_cache_rekey.py @@ -12,7 +12,9 @@ The old cache is only read. Only request files (req_*) are written; results and .fail files are not, and a file 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. Slot 86 mesh requests are only counted. +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. +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 variant is malformed, does not match its own name or names a base request that is not in the cache, the tool @@ -29,9 +31,9 @@ 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', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67'), +PARTS = {'g': ('.b', '.root', '.ia', '.psin', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67'), 'm57': ('.ps57', '.root', '.m57')} -OPTIONAL = {'.ia'} # a graphics request without an input layout has no .ia +OPTIONAL = {'.ia', '.psin'} # a graphics request may have no input layout (.ia) and no stream description (.psin) class Incomplete(Exception): @@ -61,7 +63,12 @@ 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': - return kind, key, g.pipeline_key(p['.a'], p['.b'], p['.root'], p.get('.ia', b'')), None + # The pixel input masks of a stream description are part of the key; the description names its key. + try: + masks = g.read_ps_inputs(request_name(src, key, '.psin'), key) + except g.Unsupported as reason: + return kind, key, None, str(reason) + 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 return kind, key, g.compute_key(p['.c67'], p['.data'], p['.root'], p['.desc'], p['.sa'], p['.sb']), None @@ -177,6 +184,9 @@ def rekey(src, dst, jobs=None, out=None): done.add(key) # Read again, not checked against the hashing pass: nothing may write the old cache meanwhile. for ext, data in read_parts(src, kind, old).items(): + if ext == '.psin': # the line names the new key + data = ('psin1 %016x ena=0x%04x addr=0x%04x\n' % ( + key, *g.read_ps_inputs(request_name(src, old, '.psin'), old))).encode('ascii') publish(request_name(dst, key, ext), data, stats) current = sum(old == key for old, key in new[kind].items()) print('%s: %d requests, %d already current -> %d keys' % (label, len(new[kind]), current, len(done)), file=out)