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 @@ -3766,6 +3766,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
72 changes: 64 additions & 8 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4024,6 +4024,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 @@ -8215,29 +8226,74 @@ 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.
// 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];
guid_text(iid, text, sizeof(text));
if (!out || !desc || !iid) return E_POINTER;
*out = nullptr;
if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE;
dump_pipeline("compute", 62, desc, sizeof(*desc));
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));
// Validate the cached compute container before handing it to the desktop device.
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.BytecodeLength && x2w_local::readable(desc->CS.pShaderBytecode, desc->CS.BytecodeLength)
? fnv_bytes(desc->CS.pShaderBytecode, desc->CS.BytecodeLength) : 0;
x2w_startup::ComPtr<ID3DBlob> blob;
if (!compute_key || !cache_path(path, L"", compute_key, L".cs.cso") ||
FAILED(D3DReadFileToBlob(path, blob.GetAddressOf())) || !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)));
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;
if (const char* reason = desktop_compute_program_reason(compute.CS)) {
std::snprintf(why, sizeof(why), "cached module rejected: %s", reason);
} else if (!compute.pRootSignature) {
std::snprintf(why, sizeof(why), "root signature has no desktop object");
} else {
const HRESULT built = device_of(self)->CreateComputePipelineState(&compute, IID_PPV_ARGS(&real_pipeline));
if (FAILED(built)) {
real_pipeline = nullptr;
std::snprintf(why, sizeof(why), "CreateComputePipelineState 0x%08lx", static_cast<unsigned long>(built));
} else {
pipeline_root = compute.pRootSignature;
}
}
}
}
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);
if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE;
*out = wrap(nullptr, pipeline_kind);
if (!*out) return E_OUTOFMEMORY;
"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);
*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);
note_compute_builder_pipeline(self, pipeline, _ReturnAddress());
Expand Down
15 changes: 15 additions & 0 deletions tests/cmake/startup_slot62_cache.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_list_dispatch_native)
set(slot62_shader "${CMAKE_CURRENT_BINARY_DIR}/startup_slot62_cache.cso")
add_custom_command(OUTPUT "${slot62_shader}"
COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E main -Fo "${slot62_shader}"
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_slot62_cache.hlsl"
DEPENDS tests/startup_slot62_cache.hlsl VERBATIM)
add_custom_target(startup_slot62_cache_shader DEPENDS "${slot62_shader}")
add_dependencies(startup_list_dispatch_native startup_slot62_cache_shader)
foreach(backend IN ITEMS warp hardware)
add_test(NAME startup_slot62_cache_${backend}
COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_slot62_cache_check.py"
"$<TARGET_FILE:startup_list_dispatch_native>" "${slot62_shader}" ${backend})
set_tests_properties(startup_slot62_cache_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77)
endforeach()
endif()
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())
81 changes: 78 additions & 3 deletions tests/startup_list_dispatch_native.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,73 @@ class Fixture {
native_ = native_object<ID3D12GraphicsCommandList>(device, guest, list_.Get());
}

bool run_cached(bool accepted)
{
D3D12_ROOT_PARAMETER uav{};
uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
const auto signature = guest_root(guest_, {1, &uav}, "create cached compute root");
constexpr char input[] = "slot62 fixture";
D3D12_COMPUTE_PIPELINE_STATE_DESC desc{};
desc.pRootSignature = signature.Get();
desc.CS = {input, sizeof(input) - 1};
using Create = HRESULT(WINAPI*)(IUnknown*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, UINT,
const void*, REFIID, void**);
ComPtr<ID3D12PipelineState> pipeline;
check(slot<Create>(guest_, 62)(guest_, &desc, 0, nullptr, IID_PPV_ARGS(&pipeline)), "create slot 62 PSO");
reset();
if (!accepted) {
std::ifstream log(log_path, std::ios::binary);
bool rejected_before_creation = false;
for (std::string line; std::getline(log, line);) {
if (line.find("cached module rejected: the console compute container is malformed") != std::string::npos)
rejected_before_creation = true;
}
if (!rejected_before_creation) {
std::fprintf(stderr, "expected slot 62 to reject the malformed cache before desktop creation\n");
return false;
}
if (!expect({"invalid cached module", 1, 1, 1, "requires a desktop compute pipeline and root", 0},
[&] { bind(pipeline.Get(), signature.Get()); })) return false;
resolve(1);
check(slot<Close>(list_.Get(), 9)(list_.Get()), "close refused recording");
return execute(0, 1);
}

D3D12_RESOURCE_DESC buffer{};
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffer.Width = sizeof(UINT);
buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1;
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT};
ComPtr<ID3D12Resource> output;
check(device_->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
IID_PPV_ARGS(&output)), "create output UAV");
const auto desktop_pipeline = native_object<ID3D12PipelineState>(device_, guest_, pipeline.Get());
bind(pipeline.Get(), signature.Get());
// The base shim's direct Dispatch accepts SRV-only roots. Exercise the slot 62 PSO on its desktop list.
native_->SetPipelineState(desktop_pipeline.Get());
native_->SetComputeRootUnorderedAccessView(0, output->GetGPUVirtualAddress());
native_->Dispatch(1, 1, 1);
D3D12_RESOURCE_BARRIER barrier{};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Transition = {output.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE};
native_->ResourceBarrier(1, &barrier);
native_->CopyBufferRegion(readback_.Get(), 0, output.Get(), 0, sizeof(UINT));
check(slot<Close>(list_.Get(), 9)(list_.Get()), "close cached PSO recording");
submit();
void* mapped = nullptr;
const D3D12_RANGE read{0, sizeof(UINT)}, untouched{0, 0};
check(readback_->Map(0, &read, &mapped), "map cached PSO readback");
UINT value = 0;
std::memcpy(&value, mapped, sizeof(value));
readback_->Unmap(0, &untouched);
std::printf("slot 62 cached PSO readback: %u (expected 73)\n", value);
return value == 73;
}

bool run()
{
// Recording 1: the fully bound call alone, executed and counted before any refused case runs.
Expand Down Expand Up @@ -306,13 +373,18 @@ class Fixture {
native_->ResolveQueryData(queries_.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, count, readback_.Get(), 0);
}

bool execute(UINT first, UINT count)
void submit()
{
ID3D12CommandList* lists[]{native_.Get()};
queue_->ExecuteCommandLists(1, lists);
check(queue_->Signal(fence_.Get(), ++fence_value_), "signal completion fence");
check(fence_->SetEventOnCompletion(fence_value_, nullptr), "wait for completion");
check(device_->GetDeviceRemovedReason(), "GPU completion");
}

bool execute(UINT first, UINT count)
{
submit();
void* mapped = nullptr;
const D3D12_RANGE read{0, count * sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS)};
check(readback_->Map(0, &read, &mapped), "map query readback");
Expand Down Expand Up @@ -367,7 +439,10 @@ int main(int argc, char** argv) try
const bool warp = argc >= 2 && std::strcmp(argv[1], "warp") == 0;
if (!warp && (argc < 2 || std::strcmp(argv[1], "hardware") != 0)) return 2;
const bool skip_srv = argc == 3 && std::strcmp(argv[2], "skip-srv") == 0;
if (argc > 3 || (argc == 3 && !skip_srv)) return 2;
const bool cached = argc == 3 && std::strcmp(argv[2], "cached") == 0;
const bool rejected = argc == 3 && std::strcmp(argv[2], "rejected-cache") == 0;
if (argc > 3 || (argc == 3 && !skip_srv && !cached && !rejected)) return 2;
if (cached || rejected) SetEnvironmentVariableA("X2W_COMPUTE_DISPATCH", "1");
ComPtr<ID3D12Debug> debug;
const HRESULT debug_hr = D3D12GetDebugInterface(IID_PPV_ARGS(&debug));
if (debug_hr != DXGI_ERROR_SDK_COMPONENT_MISSING) check(debug_hr, "get debug layer");
Expand Down Expand Up @@ -416,7 +491,7 @@ int main(int argc, char** argv) try
bool ok = false;
{
Fixture fixture(device.Get(), guest.Get(), skip_srv);
ok = fixture.run();
ok = cached || rejected ? fixture.run_cached(cached) : fixture.run();
}
if (info) {
for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) {
Expand Down
7 changes: 7 additions & 0 deletions tests/startup_slot62_cache.hlsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
RWByteAddressBuffer output : register(u0);

[numthreads(1, 1, 1)]
void main()
{
output.Store(0, 73);
}
29 changes: 29 additions & 0 deletions tests/startup_slot62_cache_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""Publish a source-built compute shader and a structurally malformed copy."""

import os
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory


def main(consumer, shader, backend):
key = 1469598103934665603
for byte in b"slot62 fixture":
key = ((key ^ byte) * 1099511628211) & 0xFFFFFFFFFFFFFFFF
code = Path(shader).read_bytes()
assert code[:4] == b"DXBC"

with TemporaryDirectory() as directory:
cache = Path(directory) / f"{key:016x}.cs.cso"
env = dict(os.environ, X2W_SHADER_CACHE=directory, X2W_COMPUTE_BUILDER_GATE="0")
for mode, artifact in (("rejected-cache", code + b"\0"), ("cached", code)):
cache.write_bytes(artifact)
result = subprocess.run([consumer, backend, mode], env=env, timeout=30)
if result.returncode:
return result.returncode
return 0


if __name__ == "__main__":
sys.exit(main(*sys.argv[1:]))
Loading
Loading