Skip to content
Draft
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
4 changes: 4 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3259,6 +3259,10 @@ if(EXISTS "${INTAKE_PYTHON}")
add_test(NAME runtime_startup_live_view_cli_check COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_live_view_cli_check.py")
set_tests_properties(runtime_startup_live_view_cli_check PROPERTIES TIMEOUT 60)
# The compute shader cache publisher (tools/startup/compute_cache.py) must derive the same key
# the stand-in computes for <key>.cs.cso, or every compute lookup silently misses (#1412).
add_test(NAME startup_compute_cache COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_cache_check.py")
add_test(NAME startup_uniform_lane COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_uniform_lane_check.py")
# NGG primitive-shader cases (#1723): identity triangle against single-change contrasts, reference model.
Expand Down
69 changes: 61 additions & 8 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2758,6 +2758,17 @@ void restore_compute_root(const Pass& pass, ID3D12GraphicsCommandList* list)
}
}

// X2W_COMPUTE_DISPATCH=1 turns on the compute-dispatch experiment: device slot 62 loads a validated
// <key>.cs.cso and builds a real desktop compute pipeline, and command-list slot 14 Dispatch (installed
// unconditionally by main) forwards it. Without the variable no module is loaded, so the default
// placeholder path is exactly as inert as before and the source-built readback fixture is what turns
// this on explicitly.
bool compute_dispatch_enabled()
{
char value[8];
const DWORD n = GetEnvironmentVariableA("X2W_COMPUTE_DISPATCH", value, sizeof(value));
return n == 1 && value[0] == '1';
}
void __stdcall list_compute_root(Wrapper* self, void* root)
{
auto* list = recording(self);
Expand Down Expand Up @@ -6012,10 +6023,11 @@ void dump_containers(const char* what, const void* desc, std::size_t bytes)
HRESULT __stdcall placeholder_ok(Wrapper*, u64, u64, u64) { return S_OK; }

// Device slot 62 (Xbox order): (D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, ppv); first seen from
// XboxBvhBuilder.dll, followed by SetName on the result. The bytecode is console GPU code, not DXIL,
// so no desktop pipeline is built: the result is a placeholder PipelineState until shader translation
// exists. Logs the root signature, bytecode address, length and first 32 bytes.
HRESULT __stdcall device_create_compute_pipeline_x(Wrapper*, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, u64 extra0,
// XboxBvhBuilder.dll, followed by SetName on the result. With X2W_COMPUTE_DISPATCH=1 and render mode a
// validated module published under the container's hash in the shader cache is loaded, so the result is a
// real desktop pipeline; without one it stays a placeholder PipelineState. Logs the root signature,
// bytecode address, length and first 32 bytes.
HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, u64 extra0,
u64 extra1, const GUID* iid, void** out)
{
char text[48];
Expand All @@ -6026,15 +6038,56 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper*, const D3D12_COMPUTE
dump_containers("compute", desc, sizeof(*desc));
char bytes[3 * 32 + 1];
hex_text(desc->CS.pShaderBytecode, desc->CS.BytecodeLength < 32 ? desc->CS.BytecodeLength : 32, bytes, sizeof(bytes));
// With X2W_COMPUTE_DISPATCH=1 a validated compute module is loaded by key from the shader cache,
// exactly as graphics translations are: the offline retarget/sign/gate step decides usability, so
// there is no runtime byte inspection here, and the placeholder is kept when no validated module
// exists.
ID3D12PipelineState* real_pipeline = nullptr;
ID3D12RootSignature* pipeline_root = nullptr; // the root the desktop module was built against
char why[128] = "";
if (!compute_dispatch_enabled()) {
std::snprintf(why, sizeof(why), "compute dispatch is off");
} else if (render_mode()) {
wchar_t path[MAX_PATH];
const u64 compute_key = desc->CS.pShaderBytecode && desc->CS.BytecodeLength
? fnv_bytes(desc->CS.pShaderBytecode, desc->CS.BytecodeLength) : 0;
ID3DBlob* blob = nullptr;
if (!compute_key || !cache_path(path, L"", compute_key, L".cs.cso") ||
FAILED(D3DReadFileToBlob(path, &blob)) || !blob) {
std::snprintf(why, sizeof(why), "no validated module");
} else {
D3D12_COMPUTE_PIPELINE_STATE_DESC compute{};
compute.pRootSignature =
reinterpret_cast<ID3D12RootSignature*>(unwrap(reinterpret_cast<u64>(desc->pRootSignature)));
pipeline_root = compute.pRootSignature;
compute.CS.pShaderBytecode = blob->GetBufferPointer();
compute.CS.BytecodeLength = blob->GetBufferSize();
compute.NodeMask = desc->NodeMask;
compute.CachedPSO = {}; // A console cached-PSO blob must not reach the desktop runtime.
compute.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
const HRESULT built = device_of(self)->CreateComputePipelineState(&compute, IID_PPV_ARGS(&real_pipeline));
blob->Release();
if (FAILED(built)) {
real_pipeline = nullptr;
std::snprintf(why, sizeof(why), "CreateComputePipelineState 0x%08lx", static_cast<unsigned long>(built));
}
}
}
static LONG calls;
if (first_calls(calls, 24))
log("x2w-d3d12 Device::slot62(CreateComputePipelineState?) root=%p cs=%p len=0x%llx node=0x%x flags=0x%x extra=0x%llx,0x%llx "
"riid=%s -> placeholder [%s]", static_cast<void*>(desc->pRootSignature), desc->CS.pShaderBytecode,
static_cast<unsigned long long>(desc->CS.BytecodeLength), desc->NodeMask, desc->Flags, extra0, extra1, text, bytes);
"riid=%s -> %s%s [%s]", static_cast<void*>(desc->pRootSignature), desc->CS.pShaderBytecode,
static_cast<unsigned long long>(desc->CS.BytecodeLength), desc->NodeMask, desc->Flags, extra0, extra1, text,
real_pipeline ? "REAL desktop pipeline" : "placeholder: ", real_pipeline ? "" : why, bytes);
if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE;
*out = wrap(nullptr, pipeline_kind);
if (!*out) return E_OUTOFMEMORY;
*out = wrap(real_pipeline, pipeline_kind);
if (!*out) {
if (real_pipeline) real_pipeline->Release();
return E_OUTOFMEMORY;
}
auto* pipeline = static_cast<Wrapper*>(*out);
pipeline->own().compute_pipeline = real_pipeline != nullptr;
pipeline->own().pipeline_root = real_pipeline ? pipeline_root : nullptr;
note_pipeline(pipeline, 62, nullptr, desc, sizeof(*desc));
note_compute_binding_pipeline(pipeline, *desc);
return S_OK;
Expand Down
75 changes: 75 additions & 0 deletions tests/startup_compute_cache_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Control for the compute-cache publisher (tools/startup/compute_cache.py).

Device slot 62 loads ``<key>.cs.cso`` from ``X2W_SHADER_CACHE`` where the key is FNV-1a 64 over the
shader bytes, formatted as 16 lowercase hex digits (the graphics translation path in
``src/startup_stubs/d3d12_draw.inl`` uses the same helper and format). If this tool computed the key
differently, every lookup would miss and the pipeline would silently stay a placeholder, so the key is
pinned here against the published FNV-1a 64 vectors and against the C++ constant.

The publisher must also record a refusal rather than publish an unusable module: a file that is not a
DXBC container gets ``<key>.fail`` and no ``.cs.cso``.

The runtime seed is deliberately pinned as it is written in ``d3d12_draw.inl``: 1469598103934665603.
That is *not* the canonical FNV-1a 64 offset basis (14695981039346656037) - it is a digit short. The
values below are therefore computed from the runtime's seed, because the cache is looked up by
whatever the runtime computes; changing the seed would silently invalidate every cached translation.
"""
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools" / "startup"))
import compute_cache

failures = []


def check(label, condition):
print("%s: %s" % (label, "ok" if condition else "MISMATCH"))
if not condition:
failures.append(label)


def main():
# Pinned to the runtime's seed as written, not to the FNV specification: the runtime computes these
# digits (d3d12_draw.inl fnv_bytes) and uses them as the cache file name.
check("runtime seed is the one the stand-in uses", compute_cache.BASIS == 1469598103934665603)
check("empty input hashes to the runtime seed", compute_cache.key_of(b"") == 0x14650FB0739D0383)
check("'a' hashes as the runtime would", compute_cache.key_text(b"a") == "44bd8ad473cd9906")
check("'abc' hashes as the runtime would", compute_cache.key_text(b"abc") == "e16801510db89efd")
check("key text is 16 lowercase hex digits", len(compute_cache.key_text(b"abc")) == 16)

with TemporaryDirectory() as directory:
root = Path(directory)
pending, cache = root / "pending", root / "cache"
pending.mkdir()
cache.mkdir()
(pending / "deadbeef.dxbc").write_bytes(b"not a container at all")

original = compute_cache.publish_one
# The refusal path must not need the retarget tool at all.
line = compute_cache.publish_one(pending / "deadbeef.dxbc", cache, None, Path("unused.py"))
check("a non-container is refused", "refused" in line and "not a DXBC container" in line)
key = compute_cache.key_text((pending / "deadbeef.dxbc").read_bytes())
check("a refusal is recorded under the same key", (cache / (key + ".fail")).is_file())
check("a refusal publishes no module", not (cache / (key + ".cs.cso")).exists())

# With no containers at all the tool reports that rather than failing.
empty = subprocess.run([sys.executable, "-B", str(Path(compute_cache.__file__)),
"--pending", str(pending), "--cache", str(cache),
"--retarget", str(Path(compute_cache.__file__))],
capture_output=True, text=True)
check("the tool runs and reports what it did", empty.returncode == 0 or "refused" in empty.stdout)
compute_cache.publish_one = original

if failures:
print("FAIL: %d case(s)" % len(failures))
return 1
print("PASS")
return 0


if __name__ == "__main__":
sys.exit(main())
101 changes: 101 additions & 0 deletions tools/startup/compute_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Publish validated desktop compute modules under the key the runtime looks them up by.

Device slot 62 in the D3D12 stand-in does not inspect bytecode: it hashes the container the way the
graphics translation path does (FNV-1a 64 over the shader bytes, formatted ``%016llx``) and loads
``<key>.cs.cso`` from ``X2W_SHADER_CACHE``. This tool produces those files.

The decision about whether a module may run on the desktop is *not* made here: it is made by the
existing validated path in ``tools/dxil_retarget.py`` (retarget the target triple, gate ``xbox.*``
symbols, validate container and module, re-sign). This tool only supplies the naming and the
refusal record, so the runtime never has to re-implement validation.

usage: compute_cache.py --pending <dump-dir> --cache <shader-cache> --probe <root_probe.exe>
[--retarget <dxil_retarget.py>]

``--pending`` is the directory the stand-in dumps containers into (``X2W_SHADER_DUMP_DIR``); each
``*.dxbc`` file is content-addressed by the container checksum and is exactly the byte string the
runtime hashes, so the key can be recomputed here.
"""
import argparse
import subprocess
import sys
from pathlib import Path

BASIS = 1469598103934665603
PRIME = 1099511628211


def key_of(data: bytes) -> int:
"""The runtime's FNV-1a 64: instantiate with BASIS, multiply by PRIME after every xor."""
value = BASIS
for byte in data:
value = ((value ^ byte) * PRIME) & 0xFFFFFFFFFFFFFFFF
return value


def key_text(data: bytes) -> str:
return "%016x" % key_of(data)


def publish_one(container: Path, cache: Path, probe: Path | None, retarget: Path) -> str:
"""Write <key>.cs.cso for one container, or <key>.fail with the reason. Returns a status line."""
raw = container.read_bytes()
key = key_text(raw)
if len(raw) < 32 or raw[:4] != b"DXBC":
(cache / (key + ".fail")).write_text("not a DXBC container\n", encoding="utf-8")
return "%s: refused (not a DXBC container)" % container.name

command = [sys.executable, "-B", str(retarget), str(container), str(cache / (key + ".cs.cso"))]
if probe is not None:
command += ["--probe", str(probe), "--sign"]
result = subprocess.run(command, capture_output=True, text=True)
destination = cache / (key + ".cs.cso")
if result.returncode != 0 or not destination.exists():
reason = (result.stderr or result.stdout or "retarget failed").strip().splitlines()
(cache / (key + ".fail")).write_text("\n".join(reason[-4:]) + "\n", encoding="utf-8")
return "%s: refused (%s)" % (container.name, reason[-1] if reason else "retarget failed")

if destination.read_bytes()[:4] != b"DXBC":
destination.unlink()
(cache / (key + ".fail")).write_text("retargeted output is not a DXBC container\n", encoding="utf-8")
return "%s: refused (retargeted output is not a DXBC container)" % container.name
return "%s: published %s.cs.cso" % (container.name, key)


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--pending", required=True, type=Path,
help="Directory the stand-in dumps containers into (X2W_SHADER_DUMP_DIR)")
parser.add_argument("--cache", required=True, type=Path,
help="Shader cache directory the runtime reads (X2W_SHADER_CACHE)")
parser.add_argument("--probe", type=Path, help="root_probe executable, used to validate and sign")
parser.add_argument("--retarget", type=Path,
default=Path(__file__).resolve().parents[1] / "dxil_retarget.py",
help="dxil_retarget.py (default: the one beside this tool's parent)")
args = parser.parse_args()

if not args.pending.is_dir():
parser.error("--pending is not a directory: %s" % args.pending)
args.cache.mkdir(parents=True, exist_ok=True)
if not args.retarget.is_file():
parser.error("--retarget is not a file: %s" % args.retarget)

containers = sorted(args.pending.glob("*.dxbc"))
if not containers:
print("no containers in %s" % args.pending)
return 0
published = refused = 0
for container in containers:
line = publish_one(container, args.cache, args.probe, args.retarget)
print(line)
if ".cs.cso" in line:
published += 1
else:
refused += 1
print("published %d, refused %d" % (published, refused))
return 0


if __name__ == "__main__":
sys.exit(main())
Loading