Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ jobs:
tests/startup_compute_request_offline_check.py \
tests/compute_container_index_check.py \
tests/startup_shader_cache_rekey_check.py \
tests/startup_shader_cache_revision_check.py \
tests/startup_gfx2hlsl_scalar_m0_check.py \
tests/startup_gfx2hlsl_waitcnt_depctr_check.py \
tests/startup_mesh57_skeleton_check.py \
Expand Down
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5096,6 +5096,9 @@ if(EXISTS "${INTAKE_PYTHON}")
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_rekey_check.py")
add_test(NAME runtime_shader_cache_rekey_cli_check COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_rekey_cli_check.py")
# The launchers' warning when the shader cache and the translator come from different revisions (#2815).
add_test(NAME startup_shader_cache_revision COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_revision_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")
Expand Down
11 changes: 10 additions & 1 deletion docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -1601,7 +1601,16 @@ handle returns `0x80004005`.
The startup shader cache key includes the translator revision. After updating from
an earlier translation revision, run the recording build once to emit
requests, run `python tools/startup/gfx2hlsl.py --pending <cache-directory>`,
then start the build again. The new key keeps the former bytecode and manifest
then start the build again.
The first request of a process also writes the runtime's revisions to `<cache-directory>/revision.txt`
(`graphics`, `compute` and `mesh57` lines). With `-Render -Translate` (`--render --translate`),
`run.ps1` and `run.sh` compare that file with the `gfx2hlsl.py` they start
(`tools/startup/shader_cache_revision.py`) and print one warning naming both revisions when they differ,
or when the cache holds requests but no `revision.txt`: every cached request would be refused as a key
mismatch. The warning comes before the watcher starts, or after the run when the run's own stand-ins
wrote the first `revision.txt`. Rebuild the stand-ins from the same checkout, or start with an empty cache:
`-FreshShaderCache` (`--fresh-shader-cache`) moves a cache that is not empty to `<cache>.old-<date>-<time>` first
([#2815](https://github.com/R0Y00/Xbox2Windows/issues/2815)). The new key keeps the former bytecode and manifest
together under their original name. A 16-dword table load can contain two
independent image descriptors at offsets 0 and 32 from the load address.
For a read-only census of cached shader refusals, use `python -B tools/startup/gfx2hlsl.py --refusals <cache-directory> [--json]` with a translator that supports the flag. Earlier versions treat it as `--pending` and write into the directory. See [Startup translator refusal census](experiments.md#startup-translator-refusal-census).
Expand Down
46 changes: 38 additions & 8 deletions src/startup_stubs/d3d12_draw.inl
Original file line number Diff line number Diff line change
Expand Up @@ -378,10 +378,43 @@ bool append_pso_recipe(const wchar_t* path, const x2w_startup::PsoRecipe& recipe
return ok && done == record.size();
}

// The revisions every request key starts with. tools/startup/gfx2hlsl.py hashes the same bytes, without a
// trailing NUL (pipeline_key, compute_key, mesh57_key); a change of either side makes every cached request a miss.
namespace shader_cache {
constexpr char revision[] = "x2w-startup-shader-29";
constexpr char compute_revision[] = "x2w-startup-shader-29cs"; // tools/startup/gfx2hlsl.py compute_key
constexpr char mesh57_revision[] = "x2w-startup-mesh-57-3";
} // namespace shader_cache

// Once per process, before its first request: <X2W_SHADER_CACHE>\revision.txt names this runtime's revisions, so
// that the launchers (tools/startup/shader_cache_revision.py) can warn before they start a translator of another
// revision. A file that already says the same is left as it is.
void write_cache_revision()
{
static LONG written;
if (InterlockedCompareExchange(&written, 1, 0)) return;
wchar_t dir[MAX_PATH], path[MAX_PATH], temporary[MAX_PATH];
const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH);
if (!n || n >= MAX_PATH) return;
swprintf(path, MAX_PATH, L"%s\\revision.txt", dir);
swprintf(temporary, MAX_PATH, L"%s\\revision.txt.%lu.tmp", dir, GetCurrentProcessId());
const std::string text = std::string("graphics ") + shader_cache::revision + "\ncompute " + shader_cache::compute_revision +
"\nmesh57 " + shader_cache::mesh57_revision + "\n";
std::string old;
if (read_text(path, old) && old == text) return;
HANDLE file = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) return;
DWORD done = 0;
const bool complete = WriteFile(file, text.data(), static_cast<DWORD>(text.size()), &done, nullptr) && done == text.size();
CloseHandle(file);
if (!complete || !MoveFileExW(temporary, path, MOVEFILE_REPLACE_EXISTING)) DeleteFileW(temporary);
}

// Publish each input atomically. The callers write the request's ready marker last.
bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std::size_t bytes)
{
wchar_t path[MAX_PATH], temporary[MAX_PATH], suffix[32];
write_cache_revision();
if (!cache_path(path, L"req_", key, ext)) return false;
if (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return true;
swprintf(suffix, std::size(suffix), L"%s.%lu.tmp", ext, GetCurrentProcessId());
Expand Down Expand Up @@ -508,10 +541,8 @@ void load_translation(Translation& tr, const std::string& rtv_request = {})
Translation* cached_translation(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes,
const std::vector<unsigned char>& root_blob, const std::string& layout = {})
{
// Keep pre-fix desktop bytecode and manifests out of this ABI's cache.
// tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL.
constexpr char revision[] = "x2w-startup-shader-29";
const u64 seed = fnv_bytes(revision, sizeof(revision) - 1);
// Keep pre-fix desktop bytecode and manifests out of this ABI's cache (shader_cache::revision).
const u64 seed = fnv_bytes(shader_cache::revision, sizeof(shader_cache::revision) - 1);
u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed)));
// A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key.
if (!layout.empty()) key = fnv_bytes(layout.data(), layout.size(), key);
Expand Down Expand Up @@ -631,8 +662,7 @@ u64 publish_compute_request(const void* desc)
std::vector<unsigned char> 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-29cs"; // tools/startup/gfx2hlsl.py compute_key
u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1);
u64 key = fnv_bytes(shader_cache::compute_revision, sizeof(shader_cache::compute_revision) - 1);
const std::vector<unsigned char>* 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
Expand Down Expand Up @@ -695,8 +725,8 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector<RootParameter>* bo
return copy_title_bytes(out.data(), pointer, out.size());
};
if (!copy_stage(13, true, mesh) || !copy_stage(5, false, pixel)) return;
constexpr char revision[] = "x2w-startup-mesh-57-3";
const u64 key = fnv_part(root_blob, fnv_part(pixel, fnv_part(mesh, fnv_bytes(revision, sizeof(revision) - 1))));
const u64 key = fnv_part(root_blob, fnv_part(pixel, fnv_part(mesh, fnv_bytes(shader_cache::mesh57_revision,
sizeof(shader_cache::mesh57_revision) - 1))));
static SRWLOCK request_lock = SRWLOCK_INIT;
static std::unordered_set<u64> written;
x2w_startup::ExclusiveNoteLock guard(request_lock);
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_address_srv_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def prepare_draw_cache(directory, consumer, hlsl, modes, binding, *, vertex_hlsl
args = [consumer, vs, ps, root]
subprocess.run(args, env=env, check=True)
subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True)
manifest, = cache.glob("*.txt")
manifest, = (path for path in cache.glob("*.txt") if path.name != "revision.txt")
with manifest.open("a", encoding="ascii") as file:
file.write(f"\n{binding}\n")
source = manifest.with_suffix(".ps.hlsl")
Expand Down
17 changes: 16 additions & 1 deletion tests/startup_compute_request_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@

from startup_stream_check import container, gfx2hlsl

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools" / "startup"))
import shader_cache_revision # noqa: E402

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
Expand Down Expand Up @@ -78,7 +81,8 @@ def prepare(directory):


def names(cache):
return sorted(p.name for p in cache.iterdir())
"""The request files (revision.txt, which the first request writes, is checked on its own)."""
return sorted(p.name for p in cache.iterdir() if p.name != shader_cache_revision.REVISION_FILE)


def check_boundaries(directory, consumer):
Expand Down Expand Up @@ -114,6 +118,8 @@ def check_boundaries(directory, consumer):

def check(directory, consumer, disabled):
cache, env = prepare(directory)
# A revision.txt left by an older build: the first request replaces it.
(cache / shader_cache_revision.REVISION_FILE).write_text("graphics x2w-startup-shader-0\n", encoding="ascii")
if disabled:
env["X2W_D3D12_RENDER"] = "0"
lines = run(directory, consumer, env)
Expand All @@ -137,10 +143,19 @@ def check(directory, consumer, disabled):
assert lines == [f"x2w-draw compute request {key:016x} published {detail}",
f"x2w-draw compute request {key:016x} already present {detail}"], lines

# The stand-in names its revisions next to the request, and they are the ones gfx2hlsl.py at this commit hashes,
# so the launchers' check (tools/startup/shader_cache_revision.py) stays silent for a matching build.
revisions = shader_cache_revision.cache_revisions(cache)
assert revisions == shader_cache_revision.translator_revisions(gfx2hlsl.__file__), revisions
assert shader_cache_revision.warning(cache, gfx2hlsl.__file__) is None, shader_cache_revision.warning(cache, gfx2hlsl.__file__)
revision_file = cache / shader_cache_revision.REVISION_FILE

stamps = {file: (cache / file).stat().st_mtime_ns for file in files}
revision_stamp = revision_file.stat().st_mtime_ns
lines = run(directory, consumer, env)
assert len(lines) == 2 and all("already present" in line for line in lines), lines
assert {file: (cache / file).stat().st_mtime_ns for file in files} == stamps, "a second process rewrote the request"
assert revision_file.stat().st_mtime_ns == revision_stamp, "a second process rewrote an unchanged revision.txt"
assert names(cache) == sorted(files)

# Each pointed-to part is in the key.
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_d16_srv_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def check(directory, consumer, backend):
subprocess.run(args, env=env, check=True)
subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True)

manifest, = cache.glob('*.txt')
manifest, = (path for path in cache.glob('*.txt') if path.name != 'revision.txt')
manifest_text = manifest.read_text(encoding='ascii')
manifest_lines = manifest_text.splitlines()
assert 'udsrc 3 d16unorm16 0' in manifest_lines, manifest_text
Expand Down
3 changes: 2 additions & 1 deletion tests/startup_indirect_draw_indexed.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2098,8 +2098,9 @@ int main(int argc, char** argv) try
return !size || (stream.read(contents.data(), size) && std::memcmp(contents.data(), bytes, size) == 0);
};
for (const auto& file : std::filesystem::directory_iterator(cache)) {
++files;
auto path = file.path();
if (path.filename() == "revision.txt") continue; // the runtime's revisions, written with the first request
++files;
if (path.extension() != ".m57") continue;
++requests;
if (!matches(path, ms, ms_size) ||
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_joined_table_pointer_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def draw(folder, consumer, backend, kind, compiler, prefix, offset):
cmd = [consumer, vs, ps, signature]
subprocess.run(cmd, env=env, check=True)
subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], env=env, check=True)
manifest, = cache.glob('*.txt')
manifest, = (path for path in cache.glob('*.txt') if path.name != 'revision.txt')
text = manifest.read_text(encoding='ascii')
line = f'srv 0 tex2d table 0 {offset}'
assert text.splitlines().count(line) == 1
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_logical_view_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def check(directory, consumer, backend):
subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True)
# Isolate table publication from instruction lowering. Keep the fixture's generated
# screen triangle and replace its constant-colour PS with a single bound buffer read.
manifest, = cache.glob("*.txt")
manifest, = (path for path in cache.glob("*.txt") if path.name != "revision.txt")
with manifest.open("a", encoding="ascii") as file:
file.write("\nsrv 0 buffer table 0 0\n")
shader = manifest.with_suffix(".ps.hlsl")
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_mubuf_descriptor_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def check(directory, consumer, backend):
args = [consumer, vs, ps, root]
subprocess.run(args, env=env, check=True)
subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True)
manifest, = cache.glob('*.txt')
manifest, = (path for path in cache.glob('*.txt') if path.name != 'revision.txt')
text = manifest.read_text(encoding='ascii')
assert 'descword3 0' in text and 'srv 0 buf table 0 0' in text, text
result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True)
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_pixel_uav_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def __init__(self, directory, consumer, words, env, kind='tex2d'):
publish.pop('X2W_TEST_DEBUG_LAYER', None)
subprocess.run([consumer, self.vs, self.ps, self.root], env=publish, check=True)
subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', self.cache], env=publish, check=True)
self.manifest, = self.cache.glob('*.txt')
self.manifest, = (path for path in self.cache.glob('*.txt') if path.name != 'revision.txt')
lines = self.manifest.read_text(encoding='ascii').splitlines()
assert lines[0] == 'x2w-manifest 2' and ('uav 0 %s table 0 0' % kind) in lines and not any(
line.startswith('srv ') for line in lines), lines
Expand Down
25 changes: 24 additions & 1 deletion tests/startup_run_ps1_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
# workers are, records the PIDs and arguments, then waits to be stopped. The early-exit case
# publishes just the watcher's PID and arguments and returns without spawning a child.
WATCH_STUB = """\
# The revisions the launcher compares with the cache: fnv(b'x2w-startup-shader-90'), b'x2w-startup-shader-90cs',
# b'x2w-startup-mesh-57-9' (synthetic, as gfx2hlsl.py spells them).
import json
import os
import subprocess
Expand Down Expand Up @@ -136,8 +138,16 @@ def alive(pid):
return f'"{pid}"' in out.stdout


# A shader cache of an older build (#2815): its revision.txt and one request, against the stub's revisions.
OLDER_CACHE = {"revision.txt": b"graphics x2w-startup-shader-89\ncompute x2w-startup-shader-89cs\n",
"req_0123456789abcdef.a": b""}
REVISION_PHRASES = ("was written by stand-ins of revision graphics x2w-startup-shader-89",
"but the translator", "is revision graphics x2w-startup-shader-90", "Fix: rebuild the stand-ins")


def run_case(shell, script, code, work, translate=False, switches=(), passed=(), fake_user_env=False,
early_exit=False, trace_api_env=None, absolute_build=False, missing_build=False, native=False, manifest="absent"):
early_exit=False, trace_api_env=None, absolute_build=False, missing_build=False,
native=False, manifest="absent", cache_files=None):
"""Run one copy of the script on a stub that exits with `code`; return what is wrong.

`switches` are extra run.ps1 switches and `passed` the debugger arguments they must add.
Expand All @@ -152,6 +162,11 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(),
(startup / "run.ps1").write_bytes(script.encode("utf-8"))
(startup / "debug_launch.py").write_text(STUB.format(code=code, early_exit=early_exit), encoding="utf-8")
(startup / "gfx2hlsl.py").write_text(WATCH_STUB.format(early_exit=early_exit), encoding="utf-8")
shutil.copyfile(RUN_PS1.with_name("shader_cache_revision.py"), startup / "shader_cache_revision.py")
if cache_files is not None: # a shader cache left by an earlier run
(root / "cache").mkdir()
for name, data in cache_files.items():
(root / "cache" / name).write_bytes(data)
build = root / ("build [with spaces]" if absolute_build else "bld")
build.mkdir()
for dll in DLLS: # the stand-ins the script copies next to the executable
Expand Down Expand Up @@ -215,6 +230,13 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(),
if out.returncode != code:
found.append(f"stub debugger exited {code}, run.ps1 exited {out.returncode}")
want_output = STUB_LINES[:HEAD_LINES]
if cache_files is not None:
# One warning with both revisions and the fixes; PowerShell may wrap it, so compare without whitespace.
flat = re.sub(r"\s", "", " ".join(printed))
missing = [phrase for phrase in REVISION_PHRASES if re.sub(r"\s", "", phrase) not in flat]
if missing or flat.count("Fix:rebuildthestand-ins") != 1:
found.append(f"stale shader cache: no single revision warning with {missing} (printed {printed})")
printed = [line for line in printed if line in STUB_LINES] # the case runs with -FakeUser: no other warning
if not fake_user_env and "-FakeUser" not in switches:
want_output = [warning_prefix(shell, env) + FAKE_USER_WARNING, *want_output]
printed = unwrap_first_line(printed, want_output[0])
Expand Down Expand Up @@ -277,6 +299,7 @@ def run_problems(shell, script, work, first_only):
if found and first_only:
return found
found += run_case(shell, script, 7, work, translate=True)
found += run_case(shell, script, 7, work, translate=True, switches=["-FakeUser"], cache_files=OLDER_CACHE)
for code in (0, 7):
found += run_case(shell, script, code, work, translate=True, early_exit=True)
return found
Expand Down
Loading
Loading